const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/LeadSiteHome-BoWLNAjR.js","assets/useLeadSiteSearchSuggestions-CtPaB7TH.js","assets/CityPagesModule-Bf4w-LyO.js","assets/imageOptimization-Csrlnz8M.js","assets/LeadSiteLuxuryHome-DNyeLG1D.js","assets/LeadSiteLandRanchHome-CUnQZCCF.js","assets/LeadSiteSearch-BC4GLYwg.js","assets/LeadSiteListingCardImage-DjjGe2rj.js","assets/LeadSiteMap-BMzBsRlH.js","assets/LeadSiteLuxurySearch-oRPNnVRs.js","assets/LeadSiteListingDetail-BLDbi8JV.js","assets/ListingVideoTour-BZ3H5tTO.js","assets/useListingVideos-CEgymU26.js","assets/LeadSiteLuxuryListingDetail-BEn4rDLg.js","assets/LeadSiteCityPage-CrRJTLTr.js","assets/LeadSiteSubdivisionPage-CWx-Vqf5.js","assets/PublicLiveEvent-yJZMKAeL.js","assets/useLiveEngagement-C9eZ45FU.js","assets/LiveEventConsole-hi3fnHhB.js","assets/PostcardManager-C1MUr47Y.js","assets/usePostcardZones-D9UaZZ9L.js","assets/DirectMail-Ciitkq-p.js","assets/jspdf.es.min-BmYlwThl.js","assets/LeadSiteEditor-Dj-Ka6UO.js","assets/ImageUrlField-BRMRHZAD.js","assets/LeadSiteEditor-BzY4kI8E.css","assets/AdminLeadSiteThemes-CjzGSBzV.js","assets/MLSListingDetail-7aNeO_ix.js","assets/EmailCampaignComposer-BZjaAL-C.js","assets/EditorModeSelector-L6cvm-FL.js","assets/SharedCampaignTemplates-BnUhfhpv.js","assets/TemplateEditorDialog-CKAT2kn2.js","assets/AgentTemplates-99xNXNxJ.js","assets/TheLocalMoveHome-BsyL0gcX.js","assets/tlm-hero-bg-BbD3acLf.js","assets/TheLocalMoveGetStarted-h6OdbIq9.js"])))=>i.map(i=>d[i]); var q5t=Object.defineProperty;var c7e=s=>{throw TypeError(s)};var V5t=(s,t,n)=>t in s?q5t(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n;var Ta=(s,t,n)=>V5t(s,typeof t!="symbol"?t+"":t,n),q_e=(s,t,n)=>t.has(s)||c7e("Cannot "+n);var Zs=(s,t,n)=>(q_e(s,t,"read from private field"),n?n.call(s):t.get(s)),Ri=(s,t,n)=>t.has(s)?c7e("Cannot add the same private member more than once"):t instanceof WeakSet?t.add(s):t.set(s,n),$a=(s,t,n,r)=>(q_e(s,t,"write to private field"),r?r.call(s,n):t.set(s,n),n),Ho=(s,t,n)=>(q_e(s,t,"access private method"),n);var uV=(s,t,n,r)=>({set _(a){$a(s,t,a,n)},get _(){return Zs(s,t,r)}});function H5t(s,t){for(var n=0;nr[a]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const a of document.querySelectorAll('link[rel="modulepreload"]'))r(a);new MutationObserver(a=>{for(const i of a)if(i.type==="childList")for(const l of i.addedNodes)l.tagName==="LINK"&&l.rel==="modulepreload"&&r(l)}).observe(document,{childList:!0,subtree:!0});function n(a){const i={};return a.integrity&&(i.integrity=a.integrity),a.referrerPolicy&&(i.referrerPolicy=a.referrerPolicy),a.crossOrigin==="use-credentials"?i.credentials="include":a.crossOrigin==="anonymous"?i.credentials="omit":i.credentials="same-origin",i}function r(a){if(a.ep)return;a.ep=!0;const i=n(a);fetch(a.href,i)}})();const G5t="modulepreload",W5t=function(s){return"/"+s},d7e={},xi=function(t,n,r){let a=Promise.resolve();if(n&&n.length>0){document.getElementsByTagName("link");const l=document.querySelector("meta[property=csp-nonce]"),o=(l==null?void 0:l.nonce)||(l==null?void 0:l.getAttribute("nonce"));a=Promise.allSettled(n.map(c=>{if(c=W5t(c),c in d7e)return;d7e[c]=!0;const d=c.endsWith(".css"),u=d?'[rel="stylesheet"]':"";if(document.querySelector(`link[href="${c}"]${u}`))return;const h=document.createElement("link");if(h.rel=d?"stylesheet":G5t,d||(h.as="script"),h.crossOrigin="",h.href=c,o&&h.setAttribute("nonce",o),document.head.appendChild(h),d)return new Promise((p,f)=>{h.addEventListener("load",p),h.addEventListener("error",()=>f(new Error(`Unable to preload CSS for ${c}`)))})}))}function i(l){const o=new Event("vite:preloadError",{cancelable:!0});if(o.payload=l,window.dispatchEvent(o),!o.defaultPrevented)throw l}return a.then(l=>{for(const o of l||[])o.status==="rejected"&&i(o.reason);return t().catch(i)})};var kh=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function _l(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}function K5t(s){if(s.__esModule)return s;var t=s.default;if(typeof t=="function"){var n=function r(){return this instanceof r?Reflect.construct(t,arguments,this.constructor):t.apply(this,arguments)};n.prototype=t.prototype}else n={};return Object.defineProperty(n,"__esModule",{value:!0}),Object.keys(s).forEach(function(r){var a=Object.getOwnPropertyDescriptor(s,r);Object.defineProperty(n,r,a.get?a:{enumerable:!0,get:function(){return s[r]}})}),n}var ptt={exports:{}},Yge={},ftt={exports:{}},fl={};/** * @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 N$=Symbol.for("react.element"),Y5t=Symbol.for("react.portal"),Z5t=Symbol.for("react.fragment"),Q5t=Symbol.for("react.strict_mode"),X5t=Symbol.for("react.profiler"),J5t=Symbol.for("react.provider"),eTt=Symbol.for("react.context"),tTt=Symbol.for("react.forward_ref"),sTt=Symbol.for("react.suspense"),nTt=Symbol.for("react.memo"),rTt=Symbol.for("react.lazy"),u7e=Symbol.iterator;function aTt(s){return s===null||typeof s!="object"?null:(s=u7e&&s[u7e]||s["@@iterator"],typeof s=="function"?s:null)}var xtt={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},gtt=Object.assign,ytt={};function vD(s,t,n){this.props=s,this.context=t,this.refs=ytt,this.updater=n||xtt}vD.prototype.isReactComponent={};vD.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")};vD.prototype.forceUpdate=function(s){this.updater.enqueueForceUpdate(this,s,"forceUpdate")};function vtt(){}vtt.prototype=vD.prototype;function VTe(s,t,n){this.props=s,this.context=t,this.refs=ytt,this.updater=n||xtt}var HTe=VTe.prototype=new vtt;HTe.constructor=VTe;gtt(HTe,vD.prototype);HTe.isPureReactComponent=!0;var h7e=Array.isArray,btt=Object.prototype.hasOwnProperty,GTe={current:null},_tt={key:!0,ref:!0,__self:!0,__source:!0};function wtt(s,t,n){var r,a={},i=null,l=null;if(t!=null)for(r in t.ref!==void 0&&(l=t.ref),t.key!==void 0&&(i=""+t.key),t)btt.call(t,r)&&!_tt.hasOwnProperty(r)&&(a[r]=t[r]);var o=arguments.length-2;if(o===1)a.children=n;else if(1>>1,ve=he[le];if(0>>1;lea(Ie,me))Cea(Me,Ie)?(he[le]=Me,he[Ce]=me,le=Ce):(he[le]=Ie,he[Te]=me,le=Te);else if(Cea(Me,me))he[le]=Me,he[Ce]=me,le=Ce;else break e}}return ce}function a(he,ce){var me=he.sortIndex-ce.sortIndex;return me!==0?me:he.id-ce.id}if(typeof performance=="object"&&typeof performance.now=="function"){var i=performance;s.unstable_now=function(){return i.now()}}else{var l=Date,o=l.now();s.unstable_now=function(){return l.now()-o}}var c=[],d=[],u=1,h=null,p=3,f=!1,y=!1,_=!1,v=typeof setTimeout=="function"?setTimeout:null,j=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;typeof navigator<"u"&&navigator.scheduling!==void 0&&navigator.scheduling.isInputPending!==void 0&&navigator.scheduling.isInputPending.bind(navigator.scheduling);function S(he){for(var ce=n(d);ce!==null;){if(ce.callback===null)r(d);else if(ce.startTime<=he)r(d),ce.sortIndex=ce.expirationTime,t(c,ce);else break;ce=n(d)}}function A(he){if(_=!1,S(he),!y)if(n(c)!==null)y=!0,se(E);else{var ce=n(d);ce!==null&&oe(A,ce.startTime-he)}}function E(he,ce){y=!1,_&&(_=!1,j(I),I=-1),f=!0;var me=p;try{for(S(ce),h=n(c);h!==null&&(!(h.expirationTime>ce)||he&&!H());){var le=h.callback;if(typeof le=="function"){h.callback=null,p=h.priorityLevel;var ve=le(h.expirationTime<=ce);ce=s.unstable_now(),typeof ve=="function"?h.callback=ve:h===n(c)&&r(c),S(ce)}else r(c);h=n(c)}if(h!==null)var ge=!0;else{var Te=n(d);Te!==null&&oe(A,Te.startTime-ce),ge=!1}return ge}finally{h=null,p=me,f=!1}}var O=!1,D=null,I=-1,F=5,z=-1;function H(){return!(s.unstable_now()-zhe||125le?(he.sortIndex=me,t(d,he),n(c)===null&&he===n(d)&&(_?(j(I),I=-1):_=!0,oe(A,me-le))):(he.sortIndex=ve,t(c,he),y||f||(y=!0,se(E))),he},s.unstable_shouldYield=H,s.unstable_wrapCallback=function(he){var ce=p;return function(){var me=p;p=ce;try{return he.apply(this,arguments)}finally{p=me}}}})(Ctt);Stt.exports=Ctt;var _7=Stt.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 xTt=N,xy=_7;function Gr(s){for(var t="https://reactjs.org/docs/error-decoder.html?invariant="+s,n=1;n"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),wke=Object.prototype.hasOwnProperty,gTt=/^[: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]*$/,p7e={},f7e={};function yTt(s){return wke.call(f7e,s)?!0:wke.call(p7e,s)?!1:gTt.test(s)?f7e[s]=!0:(p7e[s]=!0,!1)}function vTt(s,t,n,r){if(n!==null&&n.type===0)return!1;switch(typeof t){case"function":case"symbol":return!0;case"boolean":return r?!1:n!==null?!n.acceptsBooleans:(s=s.toLowerCase().slice(0,5),s!=="data-"&&s!=="aria-");default:return!1}}function bTt(s,t,n,r){if(t===null||typeof t>"u"||vTt(s,t,n,r))return!0;if(r)return!1;if(n!==null)switch(n.type){case 3:return!t;case 4:return t===!1;case 5:return isNaN(t);case 6:return isNaN(t)||1>t}return!1}function ag(s,t,n,r,a,i,l){this.acceptsBooleans=t===2||t===3||t===4,this.attributeName=r,this.attributeNamespace=a,this.mustUseProperty=n,this.propertyName=s,this.type=t,this.sanitizeURL=i,this.removeEmptyString=l}var bf={};"children dangerouslySetInnerHTML defaultValue defaultChecked innerHTML suppressContentEditableWarning suppressHydrationWarning style".split(" ").forEach(function(s){bf[s]=new ag(s,0,!1,s,null,!1,!1)});[["acceptCharset","accept-charset"],["className","class"],["htmlFor","for"],["httpEquiv","http-equiv"]].forEach(function(s){var t=s[0];bf[t]=new ag(t,1,!1,s[1],null,!1,!1)});["contentEditable","draggable","spellCheck","value"].forEach(function(s){bf[s]=new ag(s,2,!1,s.toLowerCase(),null,!1,!1)});["autoReverse","externalResourcesRequired","focusable","preserveAlpha"].forEach(function(s){bf[s]=new ag(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){bf[s]=new ag(s,3,!1,s.toLowerCase(),null,!1,!1)});["checked","multiple","muted","selected"].forEach(function(s){bf[s]=new ag(s,3,!0,s,null,!1,!1)});["capture","download"].forEach(function(s){bf[s]=new ag(s,4,!1,s,null,!1,!1)});["cols","rows","size","span"].forEach(function(s){bf[s]=new ag(s,6,!1,s,null,!1,!1)});["rowSpan","start"].forEach(function(s){bf[s]=new ag(s,5,!1,s.toLowerCase(),null,!1,!1)});var YTe=/[\-:]([a-z])/g;function ZTe(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(YTe,ZTe);bf[t]=new ag(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(YTe,ZTe);bf[t]=new ag(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(YTe,ZTe);bf[t]=new ag(t,1,!1,s,"http://www.w3.org/XML/1998/namespace",!1,!1)});["tabIndex","crossOrigin"].forEach(function(s){bf[s]=new ag(s,1,!1,s.toLowerCase(),null,!1,!1)});bf.xlinkHref=new ag("xlinkHref",1,!1,"xlink:href","http://www.w3.org/1999/xlink",!0,!1);["src","href","action","formAction"].forEach(function(s){bf[s]=new ag(s,1,!1,s.toLowerCase(),null,!0,!0)});function QTe(s,t,n,r){var a=bf.hasOwnProperty(t)?bf[t]:null;(a!==null?a.type!==0:r||!(2o||a[l]!==i[o]){var c=` `+a[l].replace(" at new "," at ");return s.displayName&&c.includes("")&&(c=c.replace("",s.displayName)),c}while(1<=l&&0<=o);break}}}finally{G_e=!1,Error.prepareStackTrace=n}return(s=s?s.displayName||s.name:"")?WF(s):""}function _Tt(s){switch(s.tag){case 5:return WF(s.type);case 16:return WF("Lazy");case 13:return WF("Suspense");case 19:return WF("SuspenseList");case 0:case 2:case 15:return s=W_e(s.type,!1),s;case 11:return s=W_e(s.type.render,!1),s;case 1:return s=W_e(s.type,!0),s;default:return""}}function Ske(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 cP:return"Fragment";case lP:return"Portal";case jke:return"Profiler";case XTe:return"StrictMode";case Nke:return"Suspense";case kke:return"SuspenseList"}if(typeof s=="object")switch(s.$$typeof){case Att:return(s.displayName||"Context")+".Consumer";case Ett:return(s._context.displayName||"Context")+".Provider";case JTe:var t=s.render;return s=s.displayName,s||(s=t.displayName||t.name||"",s=s!==""?"ForwardRef("+s+")":"ForwardRef"),s;case eEe:return t=s.displayName||null,t!==null?t:Ske(s.type)||"Memo";case $k:t=s._payload,s=s._init;try{return Ske(s(t))}catch{}}return null}function wTt(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 Ske(t);case 8:return t===XTe?"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 g4(s){switch(typeof s){case"boolean":case"number":case"string":case"undefined":return s;case"object":return s;default:return""}}function Itt(s){var t=s.type;return(s=s.nodeName)&&s.toLowerCase()==="input"&&(t==="checkbox"||t==="radio")}function jTt(s){var t=Itt(s)?"checked":"value",n=Object.getOwnPropertyDescriptor(s.constructor.prototype,t),r=""+s[t];if(!s.hasOwnProperty(t)&&typeof n<"u"&&typeof n.get=="function"&&typeof n.set=="function"){var a=n.get,i=n.set;return Object.defineProperty(s,t,{configurable:!0,get:function(){return a.call(this)},set:function(l){r=""+l,i.call(this,l)}}),Object.defineProperty(s,t,{enumerable:n.enumerable}),{getValue:function(){return r},setValue:function(l){r=""+l},stopTracking:function(){s._valueTracker=null,delete s[t]}}}}function pV(s){s._valueTracker||(s._valueTracker=jTt(s))}function Ptt(s){if(!s)return!1;var t=s._valueTracker;if(!t)return!0;var n=t.getValue(),r="";return s&&(r=Itt(s)?s.checked?"true":"false":s.value),s=r,s!==n?(t.setValue(s),!0):!1}function ipe(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 Cke(s,t){var n=t.checked;return Ru({},t,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:n??s._wrapperState.initialChecked})}function g7e(s,t){var n=t.defaultValue==null?"":t.defaultValue,r=t.checked!=null?t.checked:t.defaultChecked;n=g4(t.value!=null?t.value:n),s._wrapperState={initialChecked:r,initialValue:n,controlled:t.type==="checkbox"||t.type==="radio"?t.checked!=null:t.value!=null}}function Ltt(s,t){t=t.checked,t!=null&&QTe(s,"checked",t,!1)}function Tke(s,t){Ltt(s,t);var n=g4(t.value),r=t.type;if(n!=null)r==="number"?(n===0&&s.value===""||s.value!=n)&&(s.value=""+n):s.value!==""+n&&(s.value=""+n);else if(r==="submit"||r==="reset"){s.removeAttribute("value");return}t.hasOwnProperty("value")?Eke(s,t.type,n):t.hasOwnProperty("defaultValue")&&Eke(s,t.type,g4(t.defaultValue)),t.checked==null&&t.defaultChecked!=null&&(s.defaultChecked=!!t.defaultChecked)}function y7e(s,t,n){if(t.hasOwnProperty("value")||t.hasOwnProperty("defaultValue")){var r=t.type;if(!(r!=="submit"&&r!=="reset"||t.value!==void 0&&t.value!==null))return;t=""+s._wrapperState.initialValue,n||t===s.value||(s.value=t),s.defaultValue=t}n=s.name,n!==""&&(s.name=""),s.defaultChecked=!!s._wrapperState.initialChecked,n!==""&&(s.name=n)}function Eke(s,t,n){(t!=="number"||ipe(s.ownerDocument)!==s)&&(n==null?s.defaultValue=""+s._wrapperState.initialValue:s.defaultValue!==""+n&&(s.defaultValue=""+n))}var KF=Array.isArray;function zP(s,t,n,r){if(s=s.options,t){t={};for(var a=0;a"+t.valueOf().toString()+"",t=fV.firstChild;s.firstChild;)s.removeChild(s.firstChild);for(;t.firstChild;)s.appendChild(t.firstChild)}});function Cz(s,t){if(t){var n=s.firstChild;if(n&&n===s.lastChild&&n.nodeType===3){n.nodeValue=t;return}}s.textContent=t}var w7={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},NTt=["Webkit","ms","Moz","O"];Object.keys(w7).forEach(function(s){NTt.forEach(function(t){t=t+s.charAt(0).toUpperCase()+s.substring(1),w7[t]=w7[s]})});function Ftt(s,t,n){return t==null||typeof t=="boolean"||t===""?"":n||typeof t!="number"||t===0||w7.hasOwnProperty(s)&&w7[s]?(""+t).trim():t+"px"}function ztt(s,t){s=s.style;for(var n in t)if(t.hasOwnProperty(n)){var r=n.indexOf("--")===0,a=Ftt(n,t[n],r);n==="float"&&(n="cssFloat"),r?s.setProperty(n,a):s[n]=a}}var kTt=Ru({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 Ike(s,t){if(t){if(kTt[s]&&(t.children!=null||t.dangerouslySetInnerHTML!=null))throw Error(Gr(137,s));if(t.dangerouslySetInnerHTML!=null){if(t.children!=null)throw Error(Gr(60));if(typeof t.dangerouslySetInnerHTML!="object"||!("__html"in t.dangerouslySetInnerHTML))throw Error(Gr(61))}if(t.style!=null&&typeof t.style!="object")throw Error(Gr(62))}}function Pke(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 Lke=null;function tEe(s){return s=s.target||s.srcElement||window,s.correspondingUseElement&&(s=s.correspondingUseElement),s.nodeType===3?s.parentNode:s}var Dke=null,BP=null,$P=null;function _7e(s){if(s=C$(s)){if(typeof Dke!="function")throw Error(Gr(280));var t=s.stateNode;t&&(t=e0e(t),Dke(s.stateNode,s.type,t))}}function Btt(s){BP?$P?$P.push(s):$P=[s]:BP=s}function $tt(){if(BP){var s=BP,t=$P;if($P=BP=null,_7e(s),t)for(s=0;s>>=0,s===0?32:31-(RTt(s)/OTt|0)|0}var xV=64,gV=4194304;function YF(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 dpe(s,t){var n=s.pendingLanes;if(n===0)return 0;var r=0,a=s.suspendedLanes,i=s.pingedLanes,l=n&268435455;if(l!==0){var o=l&~a;o!==0?r=YF(o):(i&=l,i!==0&&(r=YF(i)))}else l=n&~a,l!==0?r=YF(l):i!==0&&(r=YF(i));if(r===0)return 0;if(t!==0&&t!==r&&!(t&a)&&(a=r&-r,i=t&-t,a>=i||a===16&&(i&4194240)!==0))return t;if(r&4&&(r|=n&16),t=s.entangledLanes,t!==0)for(s=s.entanglements,t&=r;0n;n++)t.push(s);return t}function k$(s,t,n){s.pendingLanes|=t,t!==536870912&&(s.suspendedLanes=0,s.pingedLanes=0),s=s.eventTimes,t=31-ob(t),s[t]=n}function $Tt(s,t){var n=s.pendingLanes&~t;s.pendingLanes=t,s.suspendedLanes=0,s.pingedLanes=0,s.expiredLanes&=t,s.mutableReadLanes&=t,s.entangledLanes&=t,t=s.entanglements;var r=s.eventTimes;for(s=s.expirationTimes;0=N7),A7e=" ",M7e=!1;function ost(s,t){switch(s){case"keyup":return fEt.indexOf(t.keyCode)!==-1;case"keydown":return t.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function lst(s){return s=s.detail,typeof s=="object"&&"data"in s?s.data:null}var dP=!1;function gEt(s,t){switch(s){case"compositionend":return lst(t);case"keypress":return t.which!==32?null:(M7e=!0,A7e);case"textInput":return s=t.data,s===A7e&&M7e?null:s;default:return null}}function yEt(s,t){if(dP)return s==="compositionend"||!cEe&&ost(s,t)?(s=ast(),tW=iEe=_S=null,dP=!1,s):null;switch(s){case"paste":return null;case"keypress":if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1=t)return{node:n,offset:t-s};s=r}e:{for(;n;){if(n.nextSibling){n=n.nextSibling;break e}n=n.parentNode}n=void 0}n=D7e(n)}}function hst(s,t){return s&&t?s===t?!0:s&&s.nodeType===3?!1:t&&t.nodeType===3?hst(s,t.parentNode):"contains"in s?s.contains(t):s.compareDocumentPosition?!!(s.compareDocumentPosition(t)&16):!1:!1}function mst(){for(var s=window,t=ipe();t instanceof s.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href=="string"}catch{n=!1}if(n)s=t.contentWindow;else break;t=ipe(s.document)}return t}function dEe(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 CEt(s){var t=mst(),n=s.focusedElem,r=s.selectionRange;if(t!==n&&n&&n.ownerDocument&&hst(n.ownerDocument.documentElement,n)){if(r!==null&&dEe(n)){if(t=r.start,s=r.end,s===void 0&&(s=t),"selectionStart"in n)n.selectionStart=t,n.selectionEnd=Math.min(s,n.value.length);else if(s=(t=n.ownerDocument||document)&&t.defaultView||window,s.getSelection){s=s.getSelection();var a=n.textContent.length,i=Math.min(r.start,a);r=r.end===void 0?i:Math.min(r.end,a),!s.extend&&i>r&&(a=r,r=i,i=a),a=R7e(n,i);var l=R7e(n,r);a&&l&&(s.rangeCount!==1||s.anchorNode!==a.node||s.anchorOffset!==a.offset||s.focusNode!==l.node||s.focusOffset!==l.offset)&&(t=t.createRange(),t.setStart(a.node,a.offset),s.removeAllRanges(),i>r?(s.addRange(t),s.extend(l.node,l.offset)):(t.setEnd(l.node,l.offset),s.addRange(t)))}}for(t=[],s=n;s=s.parentNode;)s.nodeType===1&&t.push({element:s,left:s.scrollLeft,top:s.scrollTop});for(typeof n.focus=="function"&&n.focus(),n=0;n=document.documentMode,uP=null,$ke=null,S7=null,Uke=!1;function O7e(s,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Uke||uP==null||uP!==ipe(r)||(r=uP,"selectionStart"in r&&dEe(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),S7&&Pz(S7,r)||(S7=r,r=mpe($ke,"onSelect"),0pP||(s.current=Kke[pP],Kke[pP]=null,pP--)}function gd(s,t){pP++,Kke[pP]=s.current,s.current=t}var y4={},sx=D4(y4),Fg=D4(!1),tM=y4;function n8(s,t){var n=s.type.contextTypes;if(!n)return y4;var r=s.stateNode;if(r&&r.__reactInternalMemoizedUnmaskedChildContext===t)return r.__reactInternalMemoizedMaskedChildContext;var a={},i;for(i in n)a[i]=t[i];return r&&(s=s.stateNode,s.__reactInternalMemoizedUnmaskedChildContext=t,s.__reactInternalMemoizedMaskedChildContext=a),a}function zg(s){return s=s.childContextTypes,s!=null}function fpe(){Fd(Fg),Fd(sx)}function V7e(s,t,n){if(sx.current!==y4)throw Error(Gr(168));gd(sx,t),gd(Fg,n)}function wst(s,t,n){var r=s.stateNode;if(t=t.childContextTypes,typeof r.getChildContext!="function")return n;r=r.getChildContext();for(var a in r)if(!(a in t))throw Error(Gr(108,wTt(s)||"Unknown",a));return Ru({},n,r)}function xpe(s){return s=(s=s.stateNode)&&s.__reactInternalMemoizedMergedChildContext||y4,tM=sx.current,gd(sx,s),gd(Fg,Fg.current),!0}function H7e(s,t,n){var r=s.stateNode;if(!r)throw Error(Gr(169));n?(s=wst(s,t,tM),r.__reactInternalMemoizedMergedChildContext=s,Fd(Fg),Fd(sx),gd(sx,s)):Fd(Fg),gd(Fg,n)}var j2=null,t0e=!1,owe=!1;function jst(s){j2===null?j2=[s]:j2.push(s)}function zEt(s){t0e=!0,jst(s)}function R4(){if(!owe&&j2!==null){owe=!0;var s=0,t=Tc;try{var n=j2;for(Tc=1;s>=l,a-=l,M2=1<<32-ob(t)+a|n<I?(F=D,D=null):F=D.sibling;var z=p(j,D,S[I],A);if(z===null){D===null&&(D=F);break}s&&D&&z.alternate===null&&t(j,D),w=i(z,w,I),O===null?E=z:O.sibling=z,O=z,D=F}if(I===S.length)return n(j,D),au&&p3(j,I),E;if(D===null){for(;II?(F=D,D=null):F=D.sibling;var H=p(j,D,z.value,A);if(H===null){D===null&&(D=F);break}s&&D&&H.alternate===null&&t(j,D),w=i(H,w,I),O===null?E=H:O.sibling=H,O=H,D=F}if(z.done)return n(j,D),au&&p3(j,I),E;if(D===null){for(;!z.done;I++,z=S.next())z=h(j,z.value,A),z!==null&&(w=i(z,w,I),O===null?E=z:O.sibling=z,O=z);return au&&p3(j,I),E}for(D=r(j,D);!z.done;I++,z=S.next())z=f(D,j,I,z.value,A),z!==null&&(s&&z.alternate!==null&&D.delete(z.key===null?I:z.key),w=i(z,w,I),O===null?E=z:O.sibling=z,O=z);return s&&D.forEach(function(Z){return t(j,Z)}),au&&p3(j,I),E}function v(j,w,S,A){if(typeof S=="object"&&S!==null&&S.type===cP&&S.key===null&&(S=S.props.children),typeof S=="object"&&S!==null){switch(S.$$typeof){case mV:e:{for(var E=S.key,O=w;O!==null;){if(O.key===E){if(E=S.type,E===cP){if(O.tag===7){n(j,O.sibling),w=a(O,S.props.children),w.return=j,j=w;break e}}else if(O.elementType===E||typeof E=="object"&&E!==null&&E.$$typeof===$k&&K7e(E)===O.type){n(j,O.sibling),w=a(O,S.props),w.ref=$O(j,O,S),w.return=j,j=w;break e}n(j,O);break}else t(j,O);O=O.sibling}S.type===cP?(w=mA(S.props.children,j.mode,A,S.key),w.return=j,j=w):(A=cW(S.type,S.key,S.props,null,j.mode,A),A.ref=$O(j,w,S),A.return=j,j=A)}return l(j);case lP:e:{for(O=S.key;w!==null;){if(w.key===O)if(w.tag===4&&w.stateNode.containerInfo===S.containerInfo&&w.stateNode.implementation===S.implementation){n(j,w.sibling),w=a(w,S.children||[]),w.return=j,j=w;break e}else{n(j,w);break}else t(j,w);w=w.sibling}w=fwe(S,j.mode,A),w.return=j,j=w}return l(j);case $k:return O=S._init,v(j,w,O(S._payload),A)}if(KF(S))return y(j,w,S,A);if(RO(S))return _(j,w,S,A);NV(j,S)}return typeof S=="string"&&S!==""||typeof S=="number"?(S=""+S,w!==null&&w.tag===6?(n(j,w.sibling),w=a(w,S),w.return=j,j=w):(n(j,w),w=pwe(S,j.mode,A),w.return=j,j=w),l(j)):n(j,w)}return v}var a8=Cst(!0),Tst=Cst(!1),vpe=D4(null),bpe=null,gP=null,pEe=null;function fEe(){pEe=gP=bpe=null}function xEe(s){var t=vpe.current;Fd(vpe),s._currentValue=t}function Qke(s,t,n){for(;s!==null;){var r=s.alternate;if((s.childLanes&t)!==t?(s.childLanes|=t,r!==null&&(r.childLanes|=t)):r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t),s===n)break;s=s.return}}function qP(s,t){bpe=s,pEe=gP=null,s=s.dependencies,s!==null&&s.firstContext!==null&&(s.lanes&t&&(Pg=!0),s.firstContext=null)}function Uv(s){var t=s._currentValue;if(pEe!==s)if(s={context:s,memoizedValue:t,next:null},gP===null){if(bpe===null)throw Error(Gr(308));gP=s,bpe.dependencies={lanes:0,firstContext:s}}else gP=gP.next=s;return t}var FE=null;function gEe(s){FE===null?FE=[s]:FE.push(s)}function Est(s,t,n,r){var a=t.interleaved;return a===null?(n.next=n,gEe(t)):(n.next=a.next,a.next=n),t.interleaved=n,rN(s,r)}function rN(s,t){s.lanes|=t;var n=s.alternate;for(n!==null&&(n.lanes|=t),n=s,s=s.return;s!==null;)s.childLanes|=t,n=s.alternate,n!==null&&(n.childLanes|=t),n=s,s=s.return;return n.tag===3?n.stateNode:null}var Uk=!1;function yEe(s){s.updateQueue={baseState:s.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function Ast(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 $2(s,t){return{eventTime:s,lane:t,tag:0,payload:null,callback:null,next:null}}function RS(s,t,n){var r=s.updateQueue;if(r===null)return null;if(r=r.shared,$l&2){var a=r.pending;return a===null?t.next=t:(t.next=a.next,a.next=t),r.pending=t,rN(s,n)}return a=r.interleaved,a===null?(t.next=t,gEe(r)):(t.next=a.next,a.next=t),r.interleaved=t,rN(s,n)}function nW(s,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,(n&4194240)!==0)){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,nEe(s,n)}}function Y7e(s,t){var n=s.updateQueue,r=s.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var a=null,i=null;if(n=n.firstBaseUpdate,n!==null){do{var l={eventTime:n.eventTime,lane:n.lane,tag:n.tag,payload:n.payload,callback:n.callback,next:null};i===null?a=i=l:i=i.next=l,n=n.next}while(n!==null);i===null?a=i=t:i=i.next=t}else a=i=t;n={baseState:r.baseState,firstBaseUpdate:a,lastBaseUpdate:i,shared:r.shared,effects:r.effects},s.updateQueue=n;return}s=n.lastBaseUpdate,s===null?n.firstBaseUpdate=t:s.next=t,n.lastBaseUpdate=t}function _pe(s,t,n,r){var a=s.updateQueue;Uk=!1;var i=a.firstBaseUpdate,l=a.lastBaseUpdate,o=a.shared.pending;if(o!==null){a.shared.pending=null;var c=o,d=c.next;c.next=null,l===null?i=d:l.next=d,l=c;var u=s.alternate;u!==null&&(u=u.updateQueue,o=u.lastBaseUpdate,o!==l&&(o===null?u.firstBaseUpdate=d:o.next=d,u.lastBaseUpdate=c))}if(i!==null){var h=a.baseState;l=0,u=d=c=null,o=i;do{var p=o.lane,f=o.eventTime;if((r&p)===p){u!==null&&(u=u.next={eventTime:f,lane:0,tag:o.tag,payload:o.payload,callback:o.callback,next:null});e:{var y=s,_=o;switch(p=t,f=n,_.tag){case 1:if(y=_.payload,typeof y=="function"){h=y.call(f,h,p);break e}h=y;break e;case 3:y.flags=y.flags&-65537|128;case 0:if(y=_.payload,p=typeof y=="function"?y.call(f,h,p):y,p==null)break e;h=Ru({},h,p);break e;case 2:Uk=!0}}o.callback!==null&&o.lane!==0&&(s.flags|=64,p=a.effects,p===null?a.effects=[o]:p.push(o))}else f={eventTime:f,lane:p,tag:o.tag,payload:o.payload,callback:o.callback,next:null},u===null?(d=u=f,c=h):u=u.next=f,l|=p;if(o=o.next,o===null){if(o=a.shared.pending,o===null)break;p=o,o=p.next,p.next=null,a.lastBaseUpdate=p,a.shared.pending=null}}while(!0);if(u===null&&(c=h),a.baseState=c,a.firstBaseUpdate=d,a.lastBaseUpdate=u,t=a.shared.interleaved,t!==null){a=t;do l|=a.lane,a=a.next;while(a!==t)}else i===null&&(a.shared.lanes=0);rM|=l,s.lanes=l,s.memoizedState=h}}function Z7e(s,t,n){if(s=t.effects,t.effects=null,s!==null)for(t=0;tn?n:4,s(!0);var r=cwe.transition;cwe.transition={};try{s(!1),t()}finally{Tc=n,cwe.transition=r}}function Wst(){return qv().memoizedState}function qEt(s,t,n){var r=FS(s);if(n={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null},Kst(s))Yst(t,n);else if(n=Est(s,t,n,r),n!==null){var a=Jx();lb(n,s,r,a),Zst(n,t,r)}}function VEt(s,t,n){var r=FS(s),a={lane:r,action:n,hasEagerState:!1,eagerState:null,next:null};if(Kst(s))Yst(t,a);else{var i=s.alternate;if(s.lanes===0&&(i===null||i.lanes===0)&&(i=t.lastRenderedReducer,i!==null))try{var l=t.lastRenderedState,o=i(l,n);if(a.hasEagerState=!0,a.eagerState=o,wb(o,l)){var c=t.interleaved;c===null?(a.next=a,gEe(t)):(a.next=c.next,c.next=a),t.interleaved=a;return}}catch{}finally{}n=Est(s,t,a,r),n!==null&&(a=Jx(),lb(n,s,r,a),Zst(n,t,r))}}function Kst(s){var t=s.alternate;return s===Mu||t!==null&&t===Mu}function Yst(s,t){C7=jpe=!0;var n=s.pending;n===null?t.next=t:(t.next=n.next,n.next=t),s.pending=t}function Zst(s,t,n){if(n&4194240){var r=t.lanes;r&=s.pendingLanes,n|=r,t.lanes=n,nEe(s,n)}}var Npe={readContext:Uv,useCallback:$f,useContext:$f,useEffect:$f,useImperativeHandle:$f,useInsertionEffect:$f,useLayoutEffect:$f,useMemo:$f,useReducer:$f,useRef:$f,useState:$f,useDebugValue:$f,useDeferredValue:$f,useTransition:$f,useMutableSource:$f,useSyncExternalStore:$f,useId:$f,unstable_isNewReconciler:!1},HEt={readContext:Uv,useCallback:function(s,t){return L_().memoizedState=[s,t===void 0?null:t],s},useContext:Uv,useEffect:X7e,useImperativeHandle:function(s,t,n){return n=n!=null?n.concat([s]):null,aW(4194308,4,Ust.bind(null,t,s),n)},useLayoutEffect:function(s,t){return aW(4194308,4,s,t)},useInsertionEffect:function(s,t){return aW(4,2,s,t)},useMemo:function(s,t){var n=L_();return t=t===void 0?null:t,s=s(),n.memoizedState=[s,t],s},useReducer:function(s,t,n){var r=L_();return t=n!==void 0?n(t):t,r.memoizedState=r.baseState=t,s={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:s,lastRenderedState:t},r.queue=s,s=s.dispatch=qEt.bind(null,Mu,s),[r.memoizedState,s]},useRef:function(s){var t=L_();return s={current:s},t.memoizedState=s},useState:Q7e,useDebugValue:SEe,useDeferredValue:function(s){return L_().memoizedState=s},useTransition:function(){var s=Q7e(!1),t=s[0];return s=UEt.bind(null,s[1]),L_().memoizedState=s,[t,s]},useMutableSource:function(){},useSyncExternalStore:function(s,t,n){var r=Mu,a=L_();if(au){if(n===void 0)throw Error(Gr(407));n=n()}else{if(n=t(),Np===null)throw Error(Gr(349));nM&30||Lst(r,t,n)}a.memoizedState=n;var i={value:n,getSnapshot:t};return a.queue=i,X7e(Rst.bind(null,r,i,s),[s]),r.flags|=2048,$z(9,Dst.bind(null,r,i,n,t),void 0,null),n},useId:function(){var s=L_(),t=Np.identifierPrefix;if(au){var n=I2,r=M2;n=(r&~(1<<32-ob(r)-1)).toString(32)+n,t=":"+t+"R"+n,n=zz++,0<\/script>",s=s.removeChild(s.firstChild)):typeof r.is=="string"?s=l.createElement(n,{is:r.is}):(s=l.createElement(n),n==="select"&&(l=s,r.multiple?l.multiple=!0:r.size&&(l.size=r.size))):s=l.createElementNS(s,n),s[W_]=t,s[Rz]=r,int(s,t,!1,!1),t.stateNode=s;e:{switch(l=Pke(n,r),n){case"dialog":Md("cancel",s),Md("close",s),a=r;break;case"iframe":case"object":case"embed":Md("load",s),a=r;break;case"video":case"audio":for(a=0;al8&&(t.flags|=128,r=!0,UO(i,!1),t.lanes=4194304)}else{if(!r)if(s=wpe(l),s!==null){if(t.flags|=128,r=!0,n=s.updateQueue,n!==null&&(t.updateQueue=n,t.flags|=4),UO(i,!0),i.tail===null&&i.tailMode==="hidden"&&!l.alternate&&!au)return Uf(t),null}else 2*wh()-i.renderingStartTime>l8&&n!==1073741824&&(t.flags|=128,r=!0,UO(i,!1),t.lanes=4194304);i.isBackwards?(l.sibling=t.child,t.child=l):(n=i.last,n!==null?n.sibling=l:t.child=l,i.last=l)}return i.tail!==null?(t=i.tail,i.rendering=t,i.tail=t.sibling,i.renderingStartTime=wh(),t.sibling=null,n=ku.current,gd(ku,r?n&1|2:n&1),t):(Uf(t),null);case 22:case 23:return IEe(),r=t.memoizedState!==null,s!==null&&s.memoizedState!==null!==r&&(t.flags|=8192),r&&t.mode&1?z0&1073741824&&(Uf(t),t.subtreeFlags&6&&(t.flags|=8192)):Uf(t),null;case 24:return null;case 25:return null}throw Error(Gr(156,t.tag))}function JEt(s,t){switch(hEe(t),t.tag){case 1:return zg(t.type)&&fpe(),s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 3:return i8(),Fd(Fg),Fd(sx),_Ee(),s=t.flags,s&65536&&!(s&128)?(t.flags=s&-65537|128,t):null;case 5:return bEe(t),null;case 13:if(Fd(ku),s=t.memoizedState,s!==null&&s.dehydrated!==null){if(t.alternate===null)throw Error(Gr(340));r8()}return s=t.flags,s&65536?(t.flags=s&-65537|128,t):null;case 19:return Fd(ku),null;case 4:return i8(),null;case 10:return xEe(t.type._context),null;case 22:case 23:return IEe(),null;case 24:return null;default:return null}}var SV=!1,Wf=!1,eAt=typeof WeakSet=="function"?WeakSet:Set,Ja=null;function yP(s,t){var n=s.ref;if(n!==null)if(typeof n=="function")try{n(null)}catch(r){Ju(s,t,r)}else n.current=null}function iSe(s,t,n){try{n()}catch(r){Ju(s,t,r)}}var c9e=!1;function tAt(s,t){if(qke=upe,s=mst(),dEe(s)){if("selectionStart"in s)var n={start:s.selectionStart,end:s.selectionEnd};else e:{n=(n=s.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,i=r.focusNode;r=r.focusOffset;try{n.nodeType,i.nodeType}catch{n=null;break e}var l=0,o=-1,c=-1,d=0,u=0,h=s,p=null;t:for(;;){for(var f;h!==n||a!==0&&h.nodeType!==3||(o=l+a),h!==i||r!==0&&h.nodeType!==3||(c=l+r),h.nodeType===3&&(l+=h.nodeValue.length),(f=h.firstChild)!==null;)p=h,h=f;for(;;){if(h===s)break t;if(p===n&&++d===a&&(o=l),p===i&&++u===r&&(c=l),(f=h.nextSibling)!==null)break;h=p,p=h.parentNode}h=f}n=o===-1||c===-1?null:{start:o,end:c}}else n=null}n=n||{start:0,end:0}}else n=null;for(Vke={focusedElem:s,selectionRange:n},upe=!1,Ja=t;Ja!==null;)if(t=Ja,s=t.child,(t.subtreeFlags&1028)!==0&&s!==null)s.return=t,Ja=s;else for(;Ja!==null;){t=Ja;try{var y=t.alternate;if(t.flags&1024)switch(t.tag){case 0:case 11:case 15:break;case 1:if(y!==null){var _=y.memoizedProps,v=y.memoizedState,j=t.stateNode,w=j.getSnapshotBeforeUpdate(t.elementType===t.type?_:U1(t.type,_),v);j.__reactInternalSnapshotBeforeUpdate=w}break;case 3:var S=t.stateNode.containerInfo;S.nodeType===1?S.textContent="":S.nodeType===9&&S.documentElement&&S.removeChild(S.documentElement);break;case 5:case 6:case 4:case 17:break;default:throw Error(Gr(163))}}catch(A){Ju(t,t.return,A)}if(s=t.sibling,s!==null){s.return=t.return,Ja=s;break}Ja=t.return}return y=c9e,c9e=!1,y}function T7(s,t,n){var r=t.updateQueue;if(r=r!==null?r.lastEffect:null,r!==null){var a=r=r.next;do{if((a.tag&s)===s){var i=a.destroy;a.destroy=void 0,i!==void 0&&iSe(t,n,i)}a=a.next}while(a!==r)}}function r0e(s,t){if(t=t.updateQueue,t=t!==null?t.lastEffect:null,t!==null){var n=t=t.next;do{if((n.tag&s)===s){var r=n.create;n.destroy=r()}n=n.next}while(n!==t)}}function oSe(s){var t=s.ref;if(t!==null){var n=s.stateNode;switch(s.tag){case 5:s=n;break;default:s=n}typeof t=="function"?t(s):t.current=s}}function cnt(s){var t=s.alternate;t!==null&&(s.alternate=null,cnt(t)),s.child=null,s.deletions=null,s.sibling=null,s.tag===5&&(t=s.stateNode,t!==null&&(delete t[W_],delete t[Rz],delete t[Wke],delete t[OEt],delete t[FEt])),s.stateNode=null,s.return=null,s.dependencies=null,s.memoizedProps=null,s.memoizedState=null,s.pendingProps=null,s.stateNode=null,s.updateQueue=null}function dnt(s){return s.tag===5||s.tag===3||s.tag===4}function d9e(s){e:for(;;){for(;s.sibling===null;){if(s.return===null||dnt(s.return))return null;s=s.return}for(s.sibling.return=s.return,s=s.sibling;s.tag!==5&&s.tag!==6&&s.tag!==18;){if(s.flags&2||s.child===null||s.tag===4)continue e;s.child.return=s,s=s.child}if(!(s.flags&2))return s.stateNode}}function lSe(s,t,n){var r=s.tag;if(r===5||r===6)s=s.stateNode,t?n.nodeType===8?n.parentNode.insertBefore(s,t):n.insertBefore(s,t):(n.nodeType===8?(t=n.parentNode,t.insertBefore(s,n)):(t=n,t.appendChild(s)),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=ppe));else if(r!==4&&(s=s.child,s!==null))for(lSe(s,t,n),s=s.sibling;s!==null;)lSe(s,t,n),s=s.sibling}function cSe(s,t,n){var r=s.tag;if(r===5||r===6)s=s.stateNode,t?n.insertBefore(s,t):n.appendChild(s);else if(r!==4&&(s=s.child,s!==null))for(cSe(s,t,n),s=s.sibling;s!==null;)cSe(s,t,n),s=s.sibling}var Qp=null,H1=!1;function fk(s,t,n){for(n=n.child;n!==null;)unt(s,t,n),n=n.sibling}function unt(s,t,n){if(iw&&typeof iw.onCommitFiberUnmount=="function")try{iw.onCommitFiberUnmount(Zge,n)}catch{}switch(n.tag){case 5:Wf||yP(n,t);case 6:var r=Qp,a=H1;Qp=null,fk(s,t,n),Qp=r,H1=a,Qp!==null&&(H1?(s=Qp,n=n.stateNode,s.nodeType===8?s.parentNode.removeChild(n):s.removeChild(n)):Qp.removeChild(n.stateNode));break;case 18:Qp!==null&&(H1?(s=Qp,n=n.stateNode,s.nodeType===8?iwe(s.parentNode,n):s.nodeType===1&&iwe(s,n),Mz(s)):iwe(Qp,n.stateNode));break;case 4:r=Qp,a=H1,Qp=n.stateNode.containerInfo,H1=!0,fk(s,t,n),Qp=r,H1=a;break;case 0:case 11:case 14:case 15:if(!Wf&&(r=n.updateQueue,r!==null&&(r=r.lastEffect,r!==null))){a=r=r.next;do{var i=a,l=i.destroy;i=i.tag,l!==void 0&&(i&2||i&4)&&iSe(n,t,l),a=a.next}while(a!==r)}fk(s,t,n);break;case 1:if(!Wf&&(yP(n,t),r=n.stateNode,typeof r.componentWillUnmount=="function"))try{r.props=n.memoizedProps,r.state=n.memoizedState,r.componentWillUnmount()}catch(o){Ju(n,t,o)}fk(s,t,n);break;case 21:fk(s,t,n);break;case 22:n.mode&1?(Wf=(r=Wf)||n.memoizedState!==null,fk(s,t,n),Wf=r):fk(s,t,n);break;default:fk(s,t,n)}}function u9e(s){var t=s.updateQueue;if(t!==null){s.updateQueue=null;var n=s.stateNode;n===null&&(n=s.stateNode=new eAt),t.forEach(function(r){var a=dAt.bind(null,s,r);n.has(r)||(n.add(r),r.then(a,a))})}}function P1(s,t){var n=t.deletions;if(n!==null)for(var r=0;ra&&(a=l),r&=~i}if(r=a,r=wh()-r,r=(120>r?120:480>r?480:1080>r?1080:1920>r?1920:3e3>r?3e3:4320>r?4320:1960*nAt(r/1960))-r,10s?16:s,wS===null)var r=!1;else{if(s=wS,wS=null,Cpe=0,$l&6)throw Error(Gr(331));var a=$l;for($l|=4,Ja=s.current;Ja!==null;){var i=Ja,l=i.child;if(Ja.flags&16){var o=i.deletions;if(o!==null){for(var c=0;cwh()-AEe?hA(s,0):EEe|=n),Bg(s,t)}function vnt(s,t){t===0&&(s.mode&1?(t=gV,gV<<=1,!(gV&130023424)&&(gV=4194304)):t=1);var n=Jx();s=rN(s,t),s!==null&&(k$(s,t,n),Bg(s,n))}function cAt(s){var t=s.memoizedState,n=0;t!==null&&(n=t.retryLane),vnt(s,n)}function dAt(s,t){var n=0;switch(s.tag){case 13:var r=s.stateNode,a=s.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=s.stateNode;break;default:throw Error(Gr(314))}r!==null&&r.delete(t),vnt(s,n)}var bnt;bnt=function(s,t,n){if(s!==null)if(s.memoizedProps!==t.pendingProps||Fg.current)Pg=!0;else{if(!(s.lanes&n)&&!(t.flags&128))return Pg=!1,QEt(s,t,n);Pg=!!(s.flags&131072)}else Pg=!1,au&&t.flags&1048576&&Nst(t,ype,t.index);switch(t.lanes=0,t.tag){case 2:var r=t.type;iW(s,t),s=t.pendingProps;var a=n8(t,sx.current);qP(t,n),a=jEe(null,t,r,s,a,n);var i=NEe();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,zg(r)?(i=!0,xpe(t)):i=!1,t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,yEe(t),a.updater=n0e,t.stateNode=a,a._reactInternals=t,Jke(t,r,s,n),t=sSe(null,t,r,!0,i,n)):(t.tag=0,au&&i&&uEe(t),Bx(null,t,a,n),t=t.child),t;case 16:r=t.elementType;e:{switch(iW(s,t),s=t.pendingProps,a=r._init,r=a(r._payload),t.type=r,a=t.tag=hAt(r),s=U1(r,s),a){case 0:t=tSe(null,t,r,s,n);break e;case 1:t=i9e(null,t,r,s,n);break e;case 11:t=r9e(null,t,r,s,n);break e;case 14:t=a9e(null,t,r,U1(r.type,s),n);break e}throw Error(Gr(306,r,""))}return t;case 0:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:U1(r,a),tSe(s,t,r,a,n);case 1:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:U1(r,a),i9e(s,t,r,a,n);case 3:e:{if(nnt(t),s===null)throw Error(Gr(387));r=t.pendingProps,i=t.memoizedState,a=i.element,Ast(s,t),_pe(t,r,null,n);var l=t.memoizedState;if(r=l.element,i.isDehydrated)if(i={element:r,isDehydrated:!1,cache:l.cache,pendingSuspenseBoundaries:l.pendingSuspenseBoundaries,transitions:l.transitions},t.updateQueue.baseState=i,t.memoizedState=i,t.flags&256){a=o8(Error(Gr(423)),t),t=o9e(s,t,r,n,a);break e}else if(r!==a){a=o8(Error(Gr(424)),t),t=o9e(s,t,r,n,a);break e}else for(Q0=DS(t.stateNode.containerInfo.firstChild),X0=t,au=!0,Q1=null,n=Tst(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling;else{if(r8(),r===a){t=aN(s,t,n);break e}Bx(s,t,r,n)}t=t.child}return t;case 5:return Mst(t),s===null&&Zke(t),r=t.type,a=t.pendingProps,i=s!==null?s.memoizedProps:null,l=a.children,Hke(r,a)?l=null:i!==null&&Hke(r,i)&&(t.flags|=32),snt(s,t),Bx(s,t,l,n),t.child;case 6:return s===null&&Zke(t),null;case 13:return rnt(s,t,n);case 4:return vEe(t,t.stateNode.containerInfo),r=t.pendingProps,s===null?t.child=a8(t,null,r,n):Bx(s,t,r,n),t.child;case 11:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:U1(r,a),r9e(s,t,r,a,n);case 7:return Bx(s,t,t.pendingProps,n),t.child;case 8:return Bx(s,t,t.pendingProps.children,n),t.child;case 12:return Bx(s,t,t.pendingProps.children,n),t.child;case 10:e:{if(r=t.type._context,a=t.pendingProps,i=t.memoizedProps,l=a.value,gd(vpe,r._currentValue),r._currentValue=l,i!==null)if(wb(i.value,l)){if(i.children===a.children&&!Fg.current){t=aN(s,t,n);break e}}else for(i=t.child,i!==null&&(i.return=t);i!==null;){var o=i.dependencies;if(o!==null){l=i.child;for(var c=o.firstContext;c!==null;){if(c.context===r){if(i.tag===1){c=$2(-1,n&-n),c.tag=2;var d=i.updateQueue;if(d!==null){d=d.shared;var u=d.pending;u===null?c.next=c:(c.next=u.next,u.next=c),d.pending=c}}i.lanes|=n,c=i.alternate,c!==null&&(c.lanes|=n),Qke(i.return,n,t),o.lanes|=n;break}c=c.next}}else if(i.tag===10)l=i.type===t.type?null:i.child;else if(i.tag===18){if(l=i.return,l===null)throw Error(Gr(341));l.lanes|=n,o=l.alternate,o!==null&&(o.lanes|=n),Qke(l,n,t),l=i.sibling}else l=i.child;if(l!==null)l.return=i;else for(l=i;l!==null;){if(l===t){l=null;break}if(i=l.sibling,i!==null){i.return=l.return,l=i;break}l=l.return}i=l}Bx(s,t,a.children,n),t=t.child}return t;case 9:return a=t.type,r=t.pendingProps.children,qP(t,n),a=Uv(a),r=r(a),t.flags|=1,Bx(s,t,r,n),t.child;case 14:return r=t.type,a=U1(r,t.pendingProps),a=U1(r.type,a),a9e(s,t,r,a,n);case 15:return ent(s,t,t.type,t.pendingProps,n);case 17:return r=t.type,a=t.pendingProps,a=t.elementType===r?a:U1(r,a),iW(s,t),t.tag=1,zg(r)?(s=!0,xpe(t)):s=!1,qP(t,n),Qst(t,r,a),Jke(t,r,a,n),sSe(null,t,r,!0,s,n);case 19:return ant(s,t,n);case 22:return tnt(s,t,n)}throw Error(Gr(156,t.tag))};function _nt(s,t){return Ktt(s,t)}function uAt(s,t,n,r){this.tag=s,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Cv(s,t,n,r){return new uAt(s,t,n,r)}function LEe(s){return s=s.prototype,!(!s||!s.isReactComponent)}function hAt(s){if(typeof s=="function")return LEe(s)?1:0;if(s!=null){if(s=s.$$typeof,s===JTe)return 11;if(s===eEe)return 14}return 2}function zS(s,t){var n=s.alternate;return n===null?(n=Cv(s.tag,t,s.key,s.mode),n.elementType=s.elementType,n.type=s.type,n.stateNode=s.stateNode,n.alternate=s,s.alternate=n):(n.pendingProps=t,n.type=s.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=s.flags&14680064,n.childLanes=s.childLanes,n.lanes=s.lanes,n.child=s.child,n.memoizedProps=s.memoizedProps,n.memoizedState=s.memoizedState,n.updateQueue=s.updateQueue,t=s.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=s.sibling,n.index=s.index,n.ref=s.ref,n}function cW(s,t,n,r,a,i){var l=2;if(r=s,typeof s=="function")LEe(s)&&(l=1);else if(typeof s=="string")l=5;else e:switch(s){case cP:return mA(n.children,a,i,t);case XTe:l=8,a|=8;break;case jke:return s=Cv(12,n,t,a|2),s.elementType=jke,s.lanes=i,s;case Nke:return s=Cv(13,n,t,a),s.elementType=Nke,s.lanes=i,s;case kke:return s=Cv(19,n,t,a),s.elementType=kke,s.lanes=i,s;case Mtt:return i0e(n,a,i,t);default:if(typeof s=="object"&&s!==null)switch(s.$$typeof){case Ett:l=10;break e;case Att:l=9;break e;case JTe:l=11;break e;case eEe:l=14;break e;case $k:l=16,r=null;break e}throw Error(Gr(130,s==null?s:typeof s,""))}return t=Cv(l,n,t,a),t.elementType=s,t.type=r,t.lanes=i,t}function mA(s,t,n,r){return s=Cv(7,s,r,t),s.lanes=n,s}function i0e(s,t,n,r){return s=Cv(22,s,r,t),s.elementType=Mtt,s.lanes=n,s.stateNode={isHidden:!1},s}function pwe(s,t,n){return s=Cv(6,s,null,t),s.lanes=n,s}function fwe(s,t,n){return t=Cv(4,s.children!==null?s.children:[],s.key,t),t.lanes=n,t.stateNode={containerInfo:s.containerInfo,pendingChildren:null,implementation:s.implementation},t}function mAt(s,t,n,r,a){this.tag=t,this.containerInfo=s,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Y_e(0),this.expirationTimes=Y_e(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Y_e(0),this.identifierPrefix=r,this.onRecoverableError=a,this.mutableSourceEagerHydrationData=null}function DEe(s,t,n,r,a,i,l,o,c){return s=new mAt(s,t,n,o,c),t===1?(t=1,i===!0&&(t|=8)):t=0,i=Cv(3,null,null,t),s.current=i,i.stateNode=s,i.memoizedState={element:r,isDehydrated:n,cache:null,transitions:null,pendingSuspenseBoundaries:null},yEe(i),s}function pAt(s,t,n){var r=3"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(knt)}catch(s){console.error(s)}}knt(),ktt.exports=_y;var qx=ktt.exports;const zEe=_l(qx);var Snt,v9e=qx;Snt=v9e.createRoot,v9e.hydrateRoot;const vAt=1,bAt=1e6;let xwe=0;function _At(){return xwe=(xwe+1)%Number.MAX_SAFE_INTEGER,xwe.toString()}const gwe=new Map,b9e=s=>{if(gwe.has(s))return;const t=setTimeout(()=>{gwe.delete(s),M7({type:"REMOVE_TOAST",toastId:s})},bAt);gwe.set(s,t)},wAt=(s,t)=>{switch(t.type){case"ADD_TOAST":return{...s,toasts:[t.toast,...s.toasts].slice(0,vAt)};case"UPDATE_TOAST":return{...s,toasts:s.toasts.map(n=>n.id===t.toast.id?{...n,...t.toast}:n)};case"DISMISS_TOAST":{const{toastId:n}=t;return n?b9e(n):s.toasts.forEach(r=>{b9e(r.id)}),{...s,toasts:s.toasts.map(r=>r.id===n||n===void 0?{...r,open:!1}:r)}}case"REMOVE_TOAST":return t.toastId===void 0?{...s,toasts:[]}:{...s,toasts:s.toasts.filter(n=>n.id!==t.toastId)}}},dW=[];let uW={toasts:[]};function M7(s){uW=wAt(uW,s),dW.forEach(t=>{t(uW)})}function Br({...s}){const t=_At(),n=a=>M7({type:"UPDATE_TOAST",toast:{...a,id:t}}),r=()=>M7({type:"DISMISS_TOAST",toastId:t});return M7({type:"ADD_TOAST",toast:{...s,id:t,open:!0,onOpenChange:a=>{a||r()}}}),{id:t,dismiss:r,update:n}}function Fa(){const[s,t]=N.useState(uW);return N.useEffect(()=>(dW.push(t),()=>{const n=dW.indexOf(t);n>-1&&dW.splice(n,1)}),[s]),{...s,toast:Br,dismiss:n=>M7({type:"DISMISS_TOAST",toastId:n})}}function xr(s,t,{checkForDefaultPrevented:n=!0}={}){return function(a){if(s==null||s(a),n===!1||!a.defaultPrevented)return t==null?void 0:t(a)}}function _9e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function iN(...s){return t=>{let n=!1;const r=s.map(a=>{const i=_9e(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{children:l,...o}=i,c=N.useMemo(()=>o,Object.values(o));return e.jsx(n.Provider,{value:c,children:l})};r.displayName=s+"Provider";function a(i){const l=N.useContext(n);if(l)return l;if(t!==void 0)return t;throw new Error(`\`${i}\` must be used within \`${s}\``)}return[r,a]}function uu(s,t=[]){let n=[];function r(i,l){const o=N.createContext(l),c=n.length;n=[...n,l];const d=h=>{var j;const{scope:p,children:f,...y}=h,_=((j=p==null?void 0:p[s])==null?void 0:j[c])||o,v=N.useMemo(()=>y,Object.values(y));return e.jsx(_.Provider,{value:v,children:f})};d.displayName=i+"Provider";function u(h,p){var _;const f=((_=p==null?void 0:p[s])==null?void 0:_[c])||o,y=N.useContext(f);if(y)return y;if(l!==void 0)return l;throw new Error(`\`${h}\` must be used within \`${i}\``)}return[d,u]}const a=()=>{const i=n.map(l=>N.createContext(l));return function(o){const c=(o==null?void 0:o[s])||i;return N.useMemo(()=>({[`__scope${s}`]:{...o,[s]:c}}),[o,c])}};return a.scopeName=s,[r,NAt(a,...t)]}function NAt(...s){const t=s[0];if(s.length===1)return t;const n=()=>{const r=s.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(i){const l=r.reduce((o,{useScope:c,scopeName:d})=>{const h=c(i)[`__scope${d}`];return{...o,...h}},{});return N.useMemo(()=>({[`__scope${t.scopeName}`]:l}),[l])}};return n.scopeName=t.scopeName,n}function v4(s){const t=kAt(s),n=N.forwardRef((r,a)=>{const{children:i,...l}=r,o=N.Children.toArray(i),c=o.find(SAt);if(c){const d=c.props.children,u=o.map(h=>h===c?N.Children.count(d)>1?N.Children.only(null):N.isValidElement(d)?d.props.children:null:h);return e.jsx(t,{...l,ref:a,children:N.isValidElement(d)?N.cloneElement(d,void 0,u):null})}return e.jsx(t,{...l,ref:a,children:i})});return n.displayName=`${s}.Slot`,n}var BEe=v4("Slot");function kAt(s){const t=N.forwardRef((n,r)=>{const{children:a,...i}=n;if(N.isValidElement(a)){const l=TAt(a),o=CAt(i,a.props);return a.type!==N.Fragment&&(o.ref=r?iN(r,l):l),N.cloneElement(a,o)}return N.Children.count(a)>1?N.Children.only(null):null});return t.displayName=`${s}.SlotClone`,t}var Cnt=Symbol("radix.slottable");function Tnt(s){const t=({children:n})=>e.jsx(e.Fragment,{children:n});return t.displayName=`${s}.Slottable`,t.__radixId=Cnt,t}function SAt(s){return N.isValidElement(s)&&typeof s.type=="function"&&"__radixId"in s.type&&s.type.__radixId===Cnt}function CAt(s,t){const n={...t};for(const r in t){const a=s[r],i=t[r];/^on[A-Z]/.test(r)?a&&i?n[r]=(...o)=>{const c=i(...o);return a(...o),c}:a&&(n[r]=a):r==="style"?n[r]={...a,...i}:r==="className"&&(n[r]=[a,i].filter(Boolean).join(" "))}return{...s,...n}}function TAt(s){var r,a;let t=(r=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?s.props.ref:s.props.ref||s.ref)}function wD(s){const t=s+"CollectionProvider",[n,r]=uu(t),[a,i]=n(t,{collectionRef:{current:null},itemMap:new Map}),l=_=>{const{scope:v,children:j}=_,w=Ct.useRef(null),S=Ct.useRef(new Map).current;return e.jsx(a,{scope:v,itemMap:S,collectionRef:w,children:j})};l.displayName=t;const o=s+"CollectionSlot",c=v4(o),d=Ct.forwardRef((_,v)=>{const{scope:j,children:w}=_,S=i(o,j),A=ji(v,S.collectionRef);return e.jsx(c,{ref:A,children:w})});d.displayName=o;const u=s+"CollectionItemSlot",h="data-radix-collection-item",p=v4(u),f=Ct.forwardRef((_,v)=>{const{scope:j,children:w,...S}=_,A=Ct.useRef(null),E=ji(v,A),O=i(u,j);return Ct.useEffect(()=>(O.itemMap.set(A,{ref:A,...S}),()=>void O.itemMap.delete(A))),e.jsx(p,{[h]:"",ref:E,children:w})});f.displayName=u;function y(_){const v=i(s+"CollectionConsumer",_);return Ct.useCallback(()=>{const w=v.collectionRef.current;if(!w)return[];const S=Array.from(w.querySelectorAll(`[${h}]`));return Array.from(v.itemMap.values()).sort((O,D)=>S.indexOf(O.ref.current)-S.indexOf(D.ref.current))},[v.collectionRef,v.itemMap])}return[{Provider:l,Slot:d,ItemSlot:f},y,r]}var EAt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],Yr=EAt.reduce((s,t)=>{const n=v4(`Primitive.${t}`),r=N.forwardRef((a,i)=>{const{asChild:l,...o}=a,c=l?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),e.jsx(c,{...o,ref:i})});return r.displayName=`Primitive.${t}`,{...s,[t]:r}},{});function $Ee(s,t){s&&qx.flushSync(()=>s.dispatchEvent(t))}function rh(s){const t=N.useRef(s);return N.useEffect(()=>{t.current=s}),N.useMemo(()=>(...n)=>{var r;return(r=t.current)==null?void 0:r.call(t,...n)},[])}function AAt(s,t=globalThis==null?void 0:globalThis.document){const n=rh(s);N.useEffect(()=>{const r=a=>{a.key==="Escape"&&n(a)};return t.addEventListener("keydown",r,{capture:!0}),()=>t.removeEventListener("keydown",r,{capture:!0})},[n,t])}var MAt="DismissableLayer",pSe="dismissableLayer.update",IAt="dismissableLayer.pointerDownOutside",PAt="dismissableLayer.focusOutside",w9e,Ent=N.createContext({layers:new Set,layersWithOutsidePointerEventsDisabled:new Set,branches:new Set}),O4=N.forwardRef((s,t)=>{const{disableOutsidePointerEvents:n=!1,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,onDismiss:o,...c}=s,d=N.useContext(Ent),[u,h]=N.useState(null),p=(u==null?void 0:u.ownerDocument)??(globalThis==null?void 0:globalThis.document),[,f]=N.useState({}),y=ji(t,D=>h(D)),_=Array.from(d.layers),[v]=[...d.layersWithOutsidePointerEventsDisabled].slice(-1),j=_.indexOf(v),w=u?_.indexOf(u):-1,S=d.layersWithOutsidePointerEventsDisabled.size>0,A=w>=j,E=DAt(D=>{const I=D.target,F=[...d.branches].some(z=>z.contains(I));!A||F||(a==null||a(D),l==null||l(D),D.defaultPrevented||o==null||o())},p),O=RAt(D=>{const I=D.target;[...d.branches].some(z=>z.contains(I))||(i==null||i(D),l==null||l(D),D.defaultPrevented||o==null||o())},p);return AAt(D=>{w===d.layers.size-1&&(r==null||r(D),!D.defaultPrevented&&o&&(D.preventDefault(),o()))},p),N.useEffect(()=>{if(u)return n&&(d.layersWithOutsidePointerEventsDisabled.size===0&&(w9e=p.body.style.pointerEvents,p.body.style.pointerEvents="none"),d.layersWithOutsidePointerEventsDisabled.add(u)),d.layers.add(u),j9e(),()=>{n&&d.layersWithOutsidePointerEventsDisabled.size===1&&(p.body.style.pointerEvents=w9e)}},[u,p,n,d]),N.useEffect(()=>()=>{u&&(d.layers.delete(u),d.layersWithOutsidePointerEventsDisabled.delete(u),j9e())},[u,d]),N.useEffect(()=>{const D=()=>f({});return document.addEventListener(pSe,D),()=>document.removeEventListener(pSe,D)},[]),e.jsx(Yr.div,{...c,ref:y,style:{pointerEvents:S?A?"auto":"none":void 0,...s.style},onFocusCapture:xr(s.onFocusCapture,O.onFocusCapture),onBlurCapture:xr(s.onBlurCapture,O.onBlurCapture),onPointerDownCapture:xr(s.onPointerDownCapture,E.onPointerDownCapture)})});O4.displayName=MAt;var LAt="DismissableLayerBranch",Ant=N.forwardRef((s,t)=>{const n=N.useContext(Ent),r=N.useRef(null),a=ji(t,r);return N.useEffect(()=>{const i=r.current;if(i)return n.branches.add(i),()=>{n.branches.delete(i)}},[n.branches]),e.jsx(Yr.div,{...s,ref:a})});Ant.displayName=LAt;function DAt(s,t=globalThis==null?void 0:globalThis.document){const n=rh(s),r=N.useRef(!1),a=N.useRef(()=>{});return N.useEffect(()=>{const i=o=>{if(o.target&&!r.current){let c=function(){Mnt(IAt,n,d,{discrete:!0})};const d={originalEvent:o};o.pointerType==="touch"?(t.removeEventListener("click",a.current),a.current=c,t.addEventListener("click",a.current,{once:!0})):c()}else t.removeEventListener("click",a.current);r.current=!1},l=window.setTimeout(()=>{t.addEventListener("pointerdown",i)},0);return()=>{window.clearTimeout(l),t.removeEventListener("pointerdown",i),t.removeEventListener("click",a.current)}},[t,n]),{onPointerDownCapture:()=>r.current=!0}}function RAt(s,t=globalThis==null?void 0:globalThis.document){const n=rh(s),r=N.useRef(!1);return N.useEffect(()=>{const a=i=>{i.target&&!r.current&&Mnt(PAt,n,{originalEvent:i},{discrete:!1})};return t.addEventListener("focusin",a),()=>t.removeEventListener("focusin",a)},[t,n]),{onFocusCapture:()=>r.current=!0,onBlurCapture:()=>r.current=!1}}function j9e(){const s=new CustomEvent(pSe);document.dispatchEvent(s)}function Mnt(s,t,n,{discrete:r}){const a=n.originalEvent.target,i=new CustomEvent(s,{bubbles:!1,cancelable:!0,detail:n});t&&a.addEventListener(s,t,{once:!0}),r?$Ee(a,i):a.dispatchEvent(i)}var OAt=O4,FAt=Ant,lh=globalThis!=null&&globalThis.document?N.useLayoutEffect:()=>{},zAt="Portal",jD=N.forwardRef((s,t)=>{var o;const{container:n,...r}=s,[a,i]=N.useState(!1);lh(()=>i(!0),[]);const l=n||a&&((o=globalThis==null?void 0:globalThis.document)==null?void 0:o.body);return l?zEe.createPortal(e.jsx(Yr.div,{...r,ref:t}),l):null});jD.displayName=zAt;function BAt(s,t){return N.useReducer((n,r)=>t[n][r]??n,s)}var Lh=s=>{const{present:t,children:n}=s,r=$At(t),a=typeof n=="function"?n({present:r.isPresent}):N.Children.only(n),i=ji(r.ref,UAt(a));return typeof n=="function"||r.isPresent?N.cloneElement(a,{ref:i}):null};Lh.displayName="Presence";function $At(s){const[t,n]=N.useState(),r=N.useRef(null),a=N.useRef(s),i=N.useRef("none"),l=s?"mounted":"unmounted",[o,c]=BAt(l,{mounted:{UNMOUNT:"unmounted",ANIMATION_OUT:"unmountSuspended"},unmountSuspended:{MOUNT:"mounted",ANIMATION_END:"unmounted"},unmounted:{MOUNT:"mounted"}});return N.useEffect(()=>{const d=EV(r.current);i.current=o==="mounted"?d:"none"},[o]),lh(()=>{const d=r.current,u=a.current;if(u!==s){const p=i.current,f=EV(d);s?c("MOUNT"):f==="none"||(d==null?void 0:d.display)==="none"?c("UNMOUNT"):c(u&&p!==f?"ANIMATION_OUT":"UNMOUNT"),a.current=s}},[s,c]),lh(()=>{if(t){let d;const u=t.ownerDocument.defaultView??window,h=f=>{const _=EV(r.current).includes(f.animationName);if(f.target===t&&_&&(c("ANIMATION_END"),!a.current)){const v=t.style.animationFillMode;t.style.animationFillMode="forwards",d=u.setTimeout(()=>{t.style.animationFillMode==="forwards"&&(t.style.animationFillMode=v)})}},p=f=>{f.target===t&&(i.current=EV(r.current))};return t.addEventListener("animationstart",p),t.addEventListener("animationcancel",h),t.addEventListener("animationend",h),()=>{u.clearTimeout(d),t.removeEventListener("animationstart",p),t.removeEventListener("animationcancel",h),t.removeEventListener("animationend",h)}}else c("ANIMATION_END")},[t,c]),{isPresent:["mounted","unmountSuspended"].includes(o),ref:N.useCallback(d=>{r.current=d?getComputedStyle(d):null,n(d)},[])}}function EV(s){return(s==null?void 0:s.animationName)||"none"}function UAt(s){var r,a;let t=(r=Object.getOwnPropertyDescriptor(s.props,"ref"))==null?void 0:r.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?s.ref:(t=(a=Object.getOwnPropertyDescriptor(s,"ref"))==null?void 0:a.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?s.props.ref:s.props.ref||s.ref)}var qAt=KTe[" useInsertionEffect ".trim().toString()]||lh;function cm({prop:s,defaultProp:t,onChange:n=()=>{},caller:r}){const[a,i,l]=VAt({defaultProp:t,onChange:n}),o=s!==void 0,c=o?s:a;{const u=N.useRef(s!==void 0);N.useEffect(()=>{const h=u.current;h!==o&&console.warn(`${r} is changing from ${h?"controlled":"uncontrolled"} to ${o?"controlled":"uncontrolled"}. Components should not switch from controlled to uncontrolled (or vice versa). Decide between using a controlled or uncontrolled value for the lifetime of the component.`),u.current=o},[o,r])}const d=N.useCallback(u=>{var h;if(o){const p=HAt(u)?u(s):u;p!==s&&((h=l.current)==null||h.call(l,p))}else i(u)},[o,s,i,l]);return[c,d]}function VAt({defaultProp:s,onChange:t}){const[n,r]=N.useState(s),a=N.useRef(n),i=N.useRef(t);return qAt(()=>{i.current=t},[t]),N.useEffect(()=>{var l;a.current!==n&&((l=i.current)==null||l.call(i,n),a.current=n)},[n,a]),[n,r,i]}function HAt(s){return typeof s=="function"}var Int=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"}),GAt="VisuallyHidden",u0e=N.forwardRef((s,t)=>e.jsx(Yr.span,{...s,ref:t,style:{...Int,...s.style}}));u0e.displayName=GAt;var WAt=u0e,UEe="ToastProvider",[qEe,KAt,YAt]=wD("Toast"),[Pnt,Ipn]=uu("Toast",[YAt]),[ZAt,h0e]=Pnt(UEe),Lnt=s=>{const{__scopeToast:t,label:n="Notification",duration:r=5e3,swipeDirection:a="right",swipeThreshold:i=50,children:l}=s,[o,c]=N.useState(null),[d,u]=N.useState(0),h=N.useRef(!1),p=N.useRef(!1);return n.trim()||console.error(`Invalid prop \`label\` supplied to \`${UEe}\`. Expected non-empty \`string\`.`),e.jsx(qEe.Provider,{scope:t,children:e.jsx(ZAt,{scope:t,label:n,duration:r,swipeDirection:a,swipeThreshold:i,toastCount:d,viewport:o,onViewportChange:c,onToastAdd:N.useCallback(()=>u(f=>f+1),[]),onToastRemove:N.useCallback(()=>u(f=>f-1),[]),isFocusedToastEscapeKeyDownRef:h,isClosePausedRef:p,children:l})})};Lnt.displayName=UEe;var Dnt="ToastViewport",QAt=["F8"],fSe="toast.viewportPause",xSe="toast.viewportResume",Rnt=N.forwardRef((s,t)=>{const{__scopeToast:n,hotkey:r=QAt,label:a="Notifications ({hotkey})",...i}=s,l=h0e(Dnt,n),o=KAt(n),c=N.useRef(null),d=N.useRef(null),u=N.useRef(null),h=N.useRef(null),p=ji(t,h,l.onViewportChange),f=r.join("+").replace(/Key/g,"").replace(/Digit/g,""),y=l.toastCount>0;N.useEffect(()=>{const v=j=>{var S;r.length!==0&&r.every(A=>j[A]||j.code===A)&&((S=h.current)==null||S.focus())};return document.addEventListener("keydown",v),()=>document.removeEventListener("keydown",v)},[r]),N.useEffect(()=>{const v=c.current,j=h.current;if(y&&v&&j){const w=()=>{if(!l.isClosePausedRef.current){const O=new CustomEvent(fSe);j.dispatchEvent(O),l.isClosePausedRef.current=!0}},S=()=>{if(l.isClosePausedRef.current){const O=new CustomEvent(xSe);j.dispatchEvent(O),l.isClosePausedRef.current=!1}},A=O=>{!v.contains(O.relatedTarget)&&S()},E=()=>{v.contains(document.activeElement)||S()};return v.addEventListener("focusin",w),v.addEventListener("focusout",A),v.addEventListener("pointermove",w),v.addEventListener("pointerleave",E),window.addEventListener("blur",w),window.addEventListener("focus",S),()=>{v.removeEventListener("focusin",w),v.removeEventListener("focusout",A),v.removeEventListener("pointermove",w),v.removeEventListener("pointerleave",E),window.removeEventListener("blur",w),window.removeEventListener("focus",S)}}},[y,l.isClosePausedRef]);const _=N.useCallback(({tabbingDirection:v})=>{const w=o().map(S=>{const A=S.ref.current,E=[A,...dMt(A)];return v==="forwards"?E:E.reverse()});return(v==="forwards"?w.reverse():w).flat()},[o]);return N.useEffect(()=>{const v=h.current;if(v){const j=w=>{var E,O,D;const S=w.altKey||w.ctrlKey||w.metaKey;if(w.key==="Tab"&&!S){const I=document.activeElement,F=w.shiftKey;if(w.target===v&&F){(E=d.current)==null||E.focus();return}const Z=_({tabbingDirection:F?"backwards":"forwards"}),Y=Z.findIndex(W=>W===I);ywe(Z.slice(Y+1))?w.preventDefault():F?(O=d.current)==null||O.focus():(D=u.current)==null||D.focus()}};return v.addEventListener("keydown",j),()=>v.removeEventListener("keydown",j)}},[o,_]),e.jsxs(FAt,{ref:c,role:"region","aria-label":a.replace("{hotkey}",f),tabIndex:-1,style:{pointerEvents:y?void 0:"none"},children:[y&&e.jsx(gSe,{ref:d,onFocusFromOutsideViewport:()=>{const v=_({tabbingDirection:"forwards"});ywe(v)}}),e.jsx(qEe.Slot,{scope:n,children:e.jsx(Yr.ol,{tabIndex:-1,...i,ref:p})}),y&&e.jsx(gSe,{ref:u,onFocusFromOutsideViewport:()=>{const v=_({tabbingDirection:"backwards"});ywe(v)}})]})});Rnt.displayName=Dnt;var Ont="ToastFocusProxy",gSe=N.forwardRef((s,t)=>{const{__scopeToast:n,onFocusFromOutsideViewport:r,...a}=s,i=h0e(Ont,n);return e.jsx(u0e,{"aria-hidden":!0,tabIndex:0,...a,ref:t,style:{position:"fixed"},onFocus:l=>{var d;const o=l.relatedTarget;!((d=i.viewport)!=null&&d.contains(o))&&r()}})});gSe.displayName=Ont;var E$="Toast",XAt="toast.swipeStart",JAt="toast.swipeMove",eMt="toast.swipeCancel",tMt="toast.swipeEnd",Fnt=N.forwardRef((s,t)=>{const{forceMount:n,open:r,defaultOpen:a,onOpenChange:i,...l}=s,[o,c]=cm({prop:r,defaultProp:a??!0,onChange:i,caller:E$});return e.jsx(Lh,{present:n||o,children:e.jsx(rMt,{open:o,...l,ref:t,onClose:()=>c(!1),onPause:rh(s.onPause),onResume:rh(s.onResume),onSwipeStart:xr(s.onSwipeStart,d=>{d.currentTarget.setAttribute("data-swipe","start")}),onSwipeMove:xr(s.onSwipeMove,d=>{const{x:u,y:h}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","move"),d.currentTarget.style.setProperty("--radix-toast-swipe-move-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-move-y",`${h}px`)}),onSwipeCancel:xr(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:xr(s.onSwipeEnd,d=>{const{x:u,y:h}=d.detail.delta;d.currentTarget.setAttribute("data-swipe","end"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-x"),d.currentTarget.style.removeProperty("--radix-toast-swipe-move-y"),d.currentTarget.style.setProperty("--radix-toast-swipe-end-x",`${u}px`),d.currentTarget.style.setProperty("--radix-toast-swipe-end-y",`${h}px`),c(!1)})})})});Fnt.displayName=E$;var[sMt,nMt]=Pnt(E$,{onClose(){}}),rMt=N.forwardRef((s,t)=>{const{__scopeToast:n,type:r="foreground",duration:a,open:i,onClose:l,onEscapeKeyDown:o,onPause:c,onResume:d,onSwipeStart:u,onSwipeMove:h,onSwipeCancel:p,onSwipeEnd:f,...y}=s,_=h0e(E$,n),[v,j]=N.useState(null),w=ji(t,W=>j(W)),S=N.useRef(null),A=N.useRef(null),E=a||_.duration,O=N.useRef(0),D=N.useRef(E),I=N.useRef(0),{onToastAdd:F,onToastRemove:z}=_,H=rh(()=>{var ee;(v==null?void 0:v.contains(document.activeElement))&&((ee=_.viewport)==null||ee.focus()),l()}),Z=N.useCallback(W=>{!W||W===1/0||(window.clearTimeout(I.current),O.current=new Date().getTime(),I.current=window.setTimeout(H,W))},[H]);N.useEffect(()=>{const W=_.viewport;if(W){const ee=()=>{Z(D.current),d==null||d()},se=()=>{const oe=new Date().getTime()-O.current;D.current=D.current-oe,window.clearTimeout(I.current),c==null||c()};return W.addEventListener(fSe,se),W.addEventListener(xSe,ee),()=>{W.removeEventListener(fSe,se),W.removeEventListener(xSe,ee)}}},[_.viewport,E,c,d,Z]),N.useEffect(()=>{i&&!_.isClosePausedRef.current&&Z(E)},[i,E,_.isClosePausedRef,Z]),N.useEffect(()=>(F(),()=>z()),[F,z]);const Y=N.useMemo(()=>v?Hnt(v):null,[v]);return _.viewport?e.jsxs(e.Fragment,{children:[Y&&e.jsx(aMt,{__scopeToast:n,role:"status","aria-live":r==="foreground"?"assertive":"polite","aria-atomic":!0,children:Y}),e.jsx(sMt,{scope:n,onClose:H,children:qx.createPortal(e.jsx(qEe.ItemSlot,{scope:n,children:e.jsx(OAt,{asChild:!0,onEscapeKeyDown:xr(o,()=>{_.isFocusedToastEscapeKeyDownRef.current||H(),_.isFocusedToastEscapeKeyDownRef.current=!1}),children:e.jsx(Yr.li,{role:"status","aria-live":"off","aria-atomic":!0,tabIndex:0,"data-state":i?"open":"closed","data-swipe-direction":_.swipeDirection,...y,ref:w,style:{userSelect:"none",touchAction:"none",...s.style},onKeyDown:xr(s.onKeyDown,W=>{W.key==="Escape"&&(o==null||o(W.nativeEvent),W.nativeEvent.defaultPrevented||(_.isFocusedToastEscapeKeyDownRef.current=!0,H()))}),onPointerDown:xr(s.onPointerDown,W=>{W.button===0&&(S.current={x:W.clientX,y:W.clientY})}),onPointerMove:xr(s.onPointerMove,W=>{if(!S.current)return;const ee=W.clientX-S.current.x,se=W.clientY-S.current.y,oe=!!A.current,he=["left","right"].includes(_.swipeDirection),ce=["left","up"].includes(_.swipeDirection)?Math.min:Math.max,me=he?ce(0,ee):0,le=he?0:ce(0,se),ve=W.pointerType==="touch"?10:2,ge={x:me,y:le},Te={originalEvent:W,delta:ge};oe?(A.current=ge,AV(JAt,h,Te,{discrete:!1})):N9e(ge,_.swipeDirection,ve)?(A.current=ge,AV(XAt,u,Te,{discrete:!1}),W.target.setPointerCapture(W.pointerId)):(Math.abs(ee)>ve||Math.abs(se)>ve)&&(S.current=null)}),onPointerUp:xr(s.onPointerUp,W=>{const ee=A.current,se=W.target;if(se.hasPointerCapture(W.pointerId)&&se.releasePointerCapture(W.pointerId),A.current=null,S.current=null,ee){const oe=W.currentTarget,he={originalEvent:W,delta:ee};N9e(ee,_.swipeDirection,_.swipeThreshold)?AV(tMt,f,he,{discrete:!0}):AV(eMt,p,he,{discrete:!0}),oe.addEventListener("click",ce=>ce.preventDefault(),{once:!0})}})})})}),_.viewport)})]}):null}),aMt=s=>{const{__scopeToast:t,children:n,...r}=s,a=h0e(E$,t),[i,l]=N.useState(!1),[o,c]=N.useState(!1);return lMt(()=>l(!0)),N.useEffect(()=>{const d=window.setTimeout(()=>c(!0),1e3);return()=>window.clearTimeout(d)},[]),o?null:e.jsx(jD,{asChild:!0,children:e.jsx(u0e,{...r,children:i&&e.jsxs(e.Fragment,{children:[a.label," ",n]})})})},iMt="ToastTitle",znt=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Yr.div,{...r,ref:t})});znt.displayName=iMt;var oMt="ToastDescription",Bnt=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s;return e.jsx(Yr.div,{...r,ref:t})});Bnt.displayName=oMt;var $nt="ToastAction",Unt=N.forwardRef((s,t)=>{const{altText:n,...r}=s;return n.trim()?e.jsx(Vnt,{altText:n,asChild:!0,children:e.jsx(VEe,{...r,ref:t})}):(console.error(`Invalid prop \`altText\` supplied to \`${$nt}\`. Expected non-empty \`string\`.`),null)});Unt.displayName=$nt;var qnt="ToastClose",VEe=N.forwardRef((s,t)=>{const{__scopeToast:n,...r}=s,a=nMt(qnt,n);return e.jsx(Vnt,{asChild:!0,children:e.jsx(Yr.button,{type:"button",...r,ref:t,onClick:xr(s.onClick,a.onClose)})})});VEe.displayName=qnt;var Vnt=N.forwardRef((s,t)=>{const{__scopeToast:n,altText:r,...a}=s;return e.jsx(Yr.div,{"data-radix-toast-announce-exclude":"","data-radix-toast-announce-alt":r||void 0,...a,ref:t})});function Hnt(s){const t=[];return Array.from(s.childNodes).forEach(r=>{if(r.nodeType===r.TEXT_NODE&&r.textContent&&t.push(r.textContent),cMt(r)){const a=r.ariaHidden||r.hidden||r.style.display==="none",i=r.dataset.radixToastAnnounceExclude==="";if(!a)if(i){const l=r.dataset.radixToastAnnounceAlt;l&&t.push(l)}else t.push(...Hnt(r))}}),t}function AV(s,t,n,{discrete:r}){const a=n.originalEvent.currentTarget,i=new CustomEvent(s,{bubbles:!0,cancelable:!0,detail:n});t&&a.addEventListener(s,t,{once:!0}),r?$Ee(a,i):a.dispatchEvent(i)}var N9e=(s,t,n=0)=>{const r=Math.abs(s.x),a=Math.abs(s.y),i=r>a;return t==="left"||t==="right"?i&&r>n:!i&&a>n};function lMt(s=()=>{}){const t=rh(s);lh(()=>{let n=0,r=0;return n=window.requestAnimationFrame(()=>r=window.requestAnimationFrame(t)),()=>{window.cancelAnimationFrame(n),window.cancelAnimationFrame(r)}},[t])}function cMt(s){return s.nodeType===s.ELEMENT_NODE}function dMt(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function ywe(s){const t=document.activeElement;return s.some(n=>n===t?!0:(n.focus(),document.activeElement!==t))}var uMt=Lnt,Gnt=Rnt,Wnt=Fnt,Knt=znt,Ynt=Bnt,Znt=Unt,Qnt=VEe;function Xnt(s){var t,n,r="";if(typeof s=="string"||typeof s=="number")r+=s;else if(typeof s=="object")if(Array.isArray(s)){var a=s.length;for(t=0;ttypeof s=="boolean"?`${s}`:s===0?"0":s,S9e=So,OM=(s,t)=>n=>{var r;if((t==null?void 0:t.variants)==null)return S9e(s,n==null?void 0:n.class,n==null?void 0:n.className);const{variants:a,defaultVariants:i}=t,l=Object.keys(a).map(d=>{const u=n==null?void 0:n[d],h=i==null?void 0:i[d];if(u===null)return null;const p=k9e(u)||k9e(h);return a[d][p]}),o=n&&Object.entries(n).reduce((d,u)=>{let[h,p]=u;return p===void 0||(d[h]=p),d},{}),c=t==null||(r=t.compoundVariants)===null||r===void 0?void 0:r.reduce((d,u)=>{let{class:h,className:p,...f}=u;return Object.entries(f).every(y=>{let[_,v]=y;return Array.isArray(v)?v.includes({...i,...o}[_]):{...i,...o}[_]===v})?[...d,h,p]:d},[]);return S9e(s,l,c,n==null?void 0:n.class,n==null?void 0:n.className)};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hMt=s=>s.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),Jnt=(...s)=>s.filter((t,n,r)=>!!t&&t.trim()!==""&&r.indexOf(t)===n).join(" ").trim();/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */var mMt={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 ert=N.forwardRef(({color:s="currentColor",size:t=24,strokeWidth:n=2,absoluteStrokeWidth:r,className:a="",children:i,iconNode:l,...o},c)=>N.createElement("svg",{ref:c,...mMt,width:t,height:t,stroke:s,strokeWidth:r?Number(n)*24/Number(t):n,className:Jnt("lucide",a),...o},[...l.map(([d,u])=>N.createElement(d,u)),...Array.isArray(i)?i:[i]]));/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const re=(s,t)=>{const n=N.forwardRef(({className:r,...a},i)=>N.createElement(ert,{ref:i,iconNode:t,className:Jnt(`lucide-${hMt(s)}`,r),...a}));return n.displayName=`${s}`,n};/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hW=re("AArrowDown",[["path",{d:"M3.5 13h6",key:"p1my2r"}],["path",{d:"m2 16 4.5-9 4.5 9",key:"ndf0b3"}],["path",{d:"M18 7v9",key:"pknjwm"}],["path",{d:"m14 12 4 4 4-4",key:"buelq4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mW=re("AArrowUp",[["path",{d:"M3.5 13h6",key:"p1my2r"}],["path",{d:"m2 16 4.5-9 4.5 9",key:"ndf0b3"}],["path",{d:"M18 16V7",key:"ty0viw"}],["path",{d:"m14 11 4-4 4 4",key:"1pu57t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pW=re("ALargeSmall",[["path",{d:"M21 14h-5",key:"1vh23k"}],["path",{d:"M16 16v-3.5a2.5 2.5 0 0 1 5 0V16",key:"1wh10o"}],["path",{d:"M4.5 13h6",key:"dfilno"}],["path",{d:"m3 16 4.5-9 4.5 9",key:"2dxa0e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fW=re("Accessibility",[["circle",{cx:"16",cy:"4",r:"1",key:"1grugj"}],["path",{d:"m18 19 1-7-6 1",key:"r0i19z"}],["path",{d:"m5 8 3-3 5.5 3-2.36 3.5",key:"9ptxx2"}],["path",{d:"M4.24 14.5a5 5 0 0 0 6.88 6",key:"10kmtu"}],["path",{d:"M13.76 17.5a5 5 0 0 0-6.88-6",key:"2qq6rc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const em=re("Activity",[["path",{d:"M22 12h-2.48a2 2 0 0 0-1.93 1.46l-2.35 8.36a.25.25 0 0 1-.48 0L9.24 2.18a.25.25 0 0 0-.48 0l-2.35 8.36A2 2 0 0 1 4.49 12H2",key:"169zse"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xW=re("AirVent",[["path",{d:"M6 12H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"larmp2"}],["path",{d:"M6 8h12",key:"6g4wlu"}],["path",{d:"M18.3 17.7a2.5 2.5 0 0 1-3.16 3.83 2.53 2.53 0 0 1-1.14-2V12",key:"1bo8pg"}],["path",{d:"M6.6 15.6A2 2 0 1 0 10 17v-5",key:"t9h90c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gW=re("Airplay",[["path",{d:"M5 17H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-1",key:"ns4c3b"}],["path",{d:"m12 15 5 6H7Z",key:"14qnn2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const x3=re("AlarmClockCheck",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"m9 13 2 2 4-4",key:"6343dt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g3=re("AlarmClockMinus",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"M9 13h6",key:"1uhe8q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yW=re("AlarmClockOff",[["path",{d:"M6.87 6.87a8 8 0 1 0 11.26 11.26",key:"3on8tj"}],["path",{d:"M19.9 14.25a8 8 0 0 0-9.15-9.15",key:"15ghsc"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.26 18.67 4 21",key:"yzmioq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M4 4 2 6",key:"1ycko6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const y3=re("AlarmClockPlus",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vW=re("AlarmClock",[["circle",{cx:"12",cy:"13",r:"8",key:"3y4lt7"}],["path",{d:"M12 9v4l2 2",key:"1c63tq"}],["path",{d:"M5 3 2 6",key:"18tl5t"}],["path",{d:"m22 6-3-3",key:"1opdir"}],["path",{d:"M6.38 18.7 4 21",key:"17xu3x"}],["path",{d:"M17.64 18.67 20 21",key:"kv2oe2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bW=re("AlarmSmoke",[["path",{d:"M11 21c0-2.5 2-2.5 2-5",key:"1sicvv"}],["path",{d:"M16 21c0-2.5 2-2.5 2-5",key:"1o3eny"}],["path",{d:"m19 8-.8 3a1.25 1.25 0 0 1-1.2 1H7a1.25 1.25 0 0 1-1.2-1L5 8",key:"1bvca4"}],["path",{d:"M21 3a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V4a1 1 0 0 1 1-1z",key:"x3qr1j"}],["path",{d:"M6 21c0-2.5 2-2.5 2-5",key:"i3w1gp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _W=re("Album",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["polyline",{points:"11 3 11 11 14 8 17 11 17 3",key:"1wcwz3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wW=re("AlignCenterHorizontal",[["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M10 16v4a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-4",key:"11f1s0"}],["path",{d:"M10 8V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v4",key:"t14dx9"}],["path",{d:"M20 16v1a2 2 0 0 1-2 2h-2a2 2 0 0 1-2-2v-1",key:"1w07xs"}],["path",{d:"M14 8V7c0-1.1.9-2 2-2h2a2 2 0 0 1 2 2v1",key:"1apec2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jW=re("AlignCenterVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M8 10H4a2 2 0 0 1-2-2V6c0-1.1.9-2 2-2h4",key:"14d6g8"}],["path",{d:"M16 10h4a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2h-4",key:"1e2lrw"}],["path",{d:"M8 20H7a2 2 0 0 1-2-2v-2c0-1.1.9-2 2-2h1",key:"1fkdwx"}],["path",{d:"M16 14h1a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2h-1",key:"1euafb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pA=re("AlignCenter",[["path",{d:"M17 12H7",key:"16if0g"}],["path",{d:"M19 18H5",key:"18s9l3"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NW=re("AlignEndHorizontal",[["rect",{width:"6",height:"16",x:"4",y:"2",rx:"2",key:"z5wdxg"}],["rect",{width:"6",height:"9",x:"14",y:"9",rx:"2",key:"um7a8w"}],["path",{d:"M22 22H2",key:"19qnx5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kW=re("AlignEndVertical",[["rect",{width:"16",height:"6",x:"2",y:"4",rx:"2",key:"10wcwx"}],["rect",{width:"9",height:"6",x:"9",y:"14",rx:"2",key:"4p5bwg"}],["path",{d:"M22 22V2",key:"12ipfv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SW=re("AlignHorizontalDistributeCenter",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M17 22v-5",key:"4b6g73"}],["path",{d:"M17 7V2",key:"hnrr36"}],["path",{d:"M7 22v-3",key:"1r4jpn"}],["path",{d:"M7 5V2",key:"liy1u9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CW=re("AlignHorizontalDistributeEnd",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M10 2v20",key:"uyc634"}],["path",{d:"M20 2v20",key:"1tx262"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TW=re("AlignHorizontalDistributeStart",[["rect",{width:"6",height:"14",x:"4",y:"5",rx:"2",key:"1wwnby"}],["rect",{width:"6",height:"10",x:"14",y:"7",rx:"2",key:"1fe6j6"}],["path",{d:"M4 2v20",key:"gtpd5x"}],["path",{d:"M14 2v20",key:"tg6bpw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EW=re("AlignHorizontalJustifyCenter",[["rect",{width:"6",height:"14",x:"2",y:"5",rx:"2",key:"dy24zr"}],["rect",{width:"6",height:"10",x:"16",y:"7",rx:"2",key:"13zkjt"}],["path",{d:"M12 2v20",key:"t6zp3m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AW=re("AlignHorizontalJustifyEnd",[["rect",{width:"6",height:"14",x:"2",y:"5",rx:"2",key:"dy24zr"}],["rect",{width:"6",height:"10",x:"12",y:"7",rx:"2",key:"1ht384"}],["path",{d:"M22 2v20",key:"40qfg1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MW=re("AlignHorizontalJustifyStart",[["rect",{width:"6",height:"14",x:"6",y:"5",rx:"2",key:"hsirpf"}],["rect",{width:"6",height:"10",x:"16",y:"7",rx:"2",key:"13zkjt"}],["path",{d:"M2 2v20",key:"1ivd8o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IW=re("AlignHorizontalSpaceAround",[["rect",{width:"6",height:"10",x:"9",y:"7",rx:"2",key:"yn7j0q"}],["path",{d:"M4 22V2",key:"tsjzd3"}],["path",{d:"M20 22V2",key:"1bnhr8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PW=re("AlignHorizontalSpaceBetween",[["rect",{width:"6",height:"14",x:"3",y:"5",rx:"2",key:"j77dae"}],["rect",{width:"6",height:"10",x:"15",y:"7",rx:"2",key:"bq30hj"}],["path",{d:"M3 2v20",key:"1d2pfg"}],["path",{d:"M21 2v20",key:"p059bm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LW=re("AlignJustify",[["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 18h18",key:"1h113x"}],["path",{d:"M3 6h18",key:"d0wm0j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fA=re("AlignLeft",[["path",{d:"M15 12H3",key:"6jk70r"}],["path",{d:"M17 18H3",key:"1amg6g"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xA=re("AlignRight",[["path",{d:"M21 12H9",key:"dn1m92"}],["path",{d:"M21 18H7",key:"1ygte8"}],["path",{d:"M21 6H3",key:"1jwq7v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DW=re("AlignStartHorizontal",[["rect",{width:"6",height:"16",x:"4",y:"6",rx:"2",key:"1n4dg1"}],["rect",{width:"6",height:"9",x:"14",y:"6",rx:"2",key:"17khns"}],["path",{d:"M22 2H2",key:"fhrpnj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RW=re("AlignStartVertical",[["rect",{width:"9",height:"6",x:"6",y:"14",rx:"2",key:"lpm2y7"}],["rect",{width:"16",height:"6",x:"6",y:"4",rx:"2",key:"rdj6ps"}],["path",{d:"M2 2v20",key:"1ivd8o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OW=re("AlignVerticalDistributeCenter",[["path",{d:"M22 17h-3",key:"1lwga1"}],["path",{d:"M22 7h-5",key:"o2endc"}],["path",{d:"M5 17H2",key:"1gx9xc"}],["path",{d:"M7 7H2",key:"6bq26l"}],["rect",{x:"5",y:"14",width:"14",height:"6",rx:"2",key:"1qrzuf"}],["rect",{x:"7",y:"4",width:"10",height:"6",rx:"2",key:"we8e9z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FW=re("AlignVerticalDistributeEnd",[["rect",{width:"14",height:"6",x:"5",y:"14",rx:"2",key:"jmoj9s"}],["rect",{width:"10",height:"6",x:"7",y:"4",rx:"2",key:"aza5on"}],["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zW=re("AlignVerticalDistributeStart",[["rect",{width:"14",height:"6",x:"5",y:"14",rx:"2",key:"jmoj9s"}],["rect",{width:"10",height:"6",x:"7",y:"4",rx:"2",key:"aza5on"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M2 4h20",key:"mda7wb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BW=re("AlignVerticalJustifyCenter",[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $W=re("AlignVerticalJustifyEnd",[["rect",{width:"14",height:"6",x:"5",y:"12",rx:"2",key:"4l4tp2"}],["rect",{width:"10",height:"6",x:"7",y:"2",rx:"2",key:"ypihtt"}],["path",{d:"M2 22h20",key:"272qi7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UW=re("AlignVerticalJustifyStart",[["rect",{width:"14",height:"6",x:"5",y:"16",rx:"2",key:"1i8z2d"}],["rect",{width:"10",height:"6",x:"7",y:"6",rx:"2",key:"13squh"}],["path",{d:"M2 2h20",key:"1ennik"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qW=re("AlignVerticalSpaceAround",[["rect",{width:"10",height:"6",x:"7",y:"9",rx:"2",key:"b1zbii"}],["path",{d:"M22 20H2",key:"1p1f7z"}],["path",{d:"M22 4H2",key:"1b7qnq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VW=re("AlignVerticalSpaceBetween",[["rect",{width:"14",height:"6",x:"5",y:"15",rx:"2",key:"1w91an"}],["rect",{width:"10",height:"6",x:"7",y:"3",rx:"2",key:"17wqzy"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M2 3h20",key:"91anmk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HW=re("Ambulance",[["path",{d:"M10 10H6",key:"1bsnug"}],["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.28a1 1 0 0 0-.684-.948l-1.923-.641a1 1 0 0 1-.578-.502l-1.539-3.076A1 1 0 0 0 16.382 8H14",key:"lrkjwd"}],["path",{d:"M8 8v4",key:"1fwk8c"}],["path",{d:"M9 18h6",key:"x1upvd"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GW=re("Ampersand",[["path",{d:"M17.5 12c0 4.4-3.6 8-8 8A4.5 4.5 0 0 1 5 15.5c0-6 8-4 8-8.5a3 3 0 1 0-6 0c0 3 2.5 8.5 12 13",key:"1o9ehi"}],["path",{d:"M16 12h3",key:"4uvgyw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WW=re("Ampersands",[["path",{d:"M10 17c-5-3-7-7-7-9a2 2 0 0 1 4 0c0 2.5-5 2.5-5 6 0 1.7 1.3 3 3 3 2.8 0 5-2.2 5-5",key:"12lh1k"}],["path",{d:"M22 17c-5-3-7-7-7-9a2 2 0 0 1 4 0c0 2.5-5 2.5-5 6 0 1.7 1.3 3 3 3 2.8 0 5-2.2 5-5",key:"173c68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KW=re("Amphora",[["path",{d:"M10 2v5.632c0 .424-.272.795-.653.982A6 6 0 0 0 6 14c.006 4 3 7 5 8",key:"1h8rid"}],["path",{d:"M10 5H8a2 2 0 0 0 0 4h.68",key:"3ezsi6"}],["path",{d:"M14 2v5.632c0 .424.272.795.652.982A6 6 0 0 1 18 14c0 4-3 7-5 8",key:"yt6q09"}],["path",{d:"M14 5h2a2 2 0 0 1 0 4h-.68",key:"8f95yk"}],["path",{d:"M18 22H6",key:"mg6kv4"}],["path",{d:"M9 2h6",key:"1jrp98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YW=re("Anchor",[["path",{d:"M12 22V8",key:"qkxhtm"}],["path",{d:"M5 12H2a10 10 0 0 0 20 0h-3",key:"1hv3nh"}],["circle",{cx:"12",cy:"5",r:"3",key:"rqqgnr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZW=re("Angry",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 16s-1.5-2-4-2-4 2-4 2",key:"epbg0q"}],["path",{d:"M7.5 8 10 9",key:"olxxln"}],["path",{d:"m14 9 2.5-1",key:"1j6cij"}],["path",{d:"M9 10h.01",key:"qbtxuw"}],["path",{d:"M15 10h.01",key:"1qmjsl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QW=re("Annoyed",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 15h8",key:"45n4r"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M14 9h2",key:"116p9w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XW=re("Antenna",[["path",{d:"M2 12 7 2",key:"117k30"}],["path",{d:"m7 12 5-10",key:"1tvx22"}],["path",{d:"m12 12 5-10",key:"ev1o1a"}],["path",{d:"m17 12 5-10",key:"1e4ti3"}],["path",{d:"M4.5 7h15",key:"vlsxkz"}],["path",{d:"M12 16v6",key:"c8a4gj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JW=re("Anvil",[["path",{d:"M7 10H6a4 4 0 0 1-4-4 1 1 0 0 1 1-1h4",key:"1hjpb6"}],["path",{d:"M7 5a1 1 0 0 1 1-1h13a1 1 0 0 1 1 1 7 7 0 0 1-7 7H8a1 1 0 0 1-1-1z",key:"1qn45f"}],["path",{d:"M9 12v5",key:"3anwtq"}],["path",{d:"M15 12v5",key:"5xh3zn"}],["path",{d:"M5 20a3 3 0 0 1 3-3h8a3 3 0 0 1 3 3 1 1 0 0 1-1 1H6a1 1 0 0 1-1-1",key:"1fi4x8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eK=re("Aperture",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m14.31 8 5.74 9.94",key:"1y6ab4"}],["path",{d:"M9.69 8h11.48",key:"1wxppr"}],["path",{d:"m7.38 12 5.74-9.94",key:"1grp0k"}],["path",{d:"M9.69 16 3.95 6.06",key:"libnyf"}],["path",{d:"M14.31 16H2.83",key:"x5fava"}],["path",{d:"m16.62 12-5.74 9.94",key:"1vwawt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tK=re("AppWindowMac",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M14 8h.01",key:"1primd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sK=re("AppWindow",[["rect",{x:"2",y:"4",width:"20",height:"16",rx:"2",key:"izxlao"}],["path",{d:"M10 4v4",key:"pp8u80"}],["path",{d:"M2 8h20",key:"d11cs7"}],["path",{d:"M6 4v4",key:"1svtjw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nK=re("Apple",[["path",{d:"M12 20.94c1.5 0 2.75 1.06 4 1.06 3 0 6-8 6-12.22A4.91 4.91 0 0 0 17 5c-2.22 0-4 1.44-5 2-1-.56-2.78-2-5-2a4.9 4.9 0 0 0-5 4.78C2 14 5 22 8 22c1.25 0 2.5-1.06 4-1.06Z",key:"3s7exb"}],["path",{d:"M10 2c1 .5 2 2 2 5",key:"fcco2y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HP=re("ArchiveRestore",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h2",key:"tvwodi"}],["path",{d:"M20 8v11a2 2 0 0 1-2 2h-2",key:"1gkqxj"}],["path",{d:"m9 15 3-3 3 3",key:"1pd0qc"}],["path",{d:"M12 12v9",key:"192myk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rK=re("ArchiveX",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"m9.5 17 5-5",key:"nakeu6"}],["path",{d:"m9.5 12 5 5",key:"1hccrj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tm=re("Archive",[["rect",{width:"20",height:"5",x:"2",y:"3",rx:"1",key:"1wp1u1"}],["path",{d:"M4 8v11a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8",key:"1s80jp"}],["path",{d:"M10 12h4",key:"a56b0p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aK=re("Armchair",[["path",{d:"M19 9V6a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v3",key:"irtipd"}],["path",{d:"M3 16a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-9a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"1qyhux"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iK=re("ArrowBigDownDash",[["path",{d:"M15 5H9",key:"1tp3ed"}],["path",{d:"M15 9v3h4l-7 7-7-7h4V9z",key:"ncdc4b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oK=re("ArrowBigDown",[["path",{d:"M15 6v6h4l-7 7-7-7h4V6h6z",key:"1thax2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lK=re("ArrowBigLeftDash",[["path",{d:"M19 15V9",key:"1hci5f"}],["path",{d:"M15 15h-3v4l-7-7 7-7v4h3v6z",key:"16tjna"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cK=re("ArrowBigLeft",[["path",{d:"M18 15h-6v4l-7-7 7-7v4h6v6z",key:"lbrdak"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dK=re("ArrowBigRightDash",[["path",{d:"M5 9v6",key:"158jrl"}],["path",{d:"M9 9h3V5l7 7-7 7v-4H9V9z",key:"1sg2xn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uK=re("ArrowBigRight",[["path",{d:"M6 9h6V5l7 7-7 7v-4H6V9z",key:"7fvt9c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hK=re("ArrowBigUpDash",[["path",{d:"M9 19h6",key:"456am0"}],["path",{d:"M9 15v-3H5l7-7 7 7h-4v3H9z",key:"1r2uve"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mK=re("ArrowBigUp",[["path",{d:"M9 18v-6H5l7-7 7 7h-4v6H9z",key:"1x06kx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pK=re("ArrowDown01",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fK=re("ArrowDown10",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v3=re("ArrowDownAZ",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xK=re("ArrowDownFromLine",[["path",{d:"M19 3H5",key:"1236rx"}],["path",{d:"M12 21V7",key:"gj6g52"}],["path",{d:"m6 15 6 6 6-6",key:"h15q88"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gK=re("ArrowDownLeft",[["path",{d:"M17 7 7 17",key:"15tmo1"}],["path",{d:"M17 17H7V7",key:"1org7z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yK=re("ArrowDownNarrowWide",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h4",key:"6d7r33"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h10",key:"1438ji"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I7=re("ArrowDownRight",[["path",{d:"m7 7 10 10",key:"1fmybs"}],["path",{d:"M17 7v10H7",key:"6fjiku"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vK=re("ArrowDownToDot",[["path",{d:"M12 2v14",key:"jyx4ut"}],["path",{d:"m19 9-7 7-7-7",key:"1oe3oy"}],["circle",{cx:"12",cy:"21",r:"1",key:"o0uj5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bK=re("ArrowDownToLine",[["path",{d:"M12 17V3",key:"1cwfxf"}],["path",{d:"m6 11 6 6 6-6",key:"12ii2o"}],["path",{d:"M19 21H5",key:"150jfl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _K=re("ArrowDownUp",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"m21 8-4-4-4 4",key:"1c9v7m"}],["path",{d:"M17 4v16",key:"7dpous"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const b3=re("ArrowDownWideNarrow",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 20V4",key:"1yoxec"}],["path",{d:"M11 4h10",key:"1w87gc"}],["path",{d:"M11 8h7",key:"djye34"}],["path",{d:"M11 12h4",key:"q8tih4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _3=re("ArrowDownZA",[["path",{d:"m3 16 4 4 4-4",key:"1co6wj"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sm=re("ArrowDown",[["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"m19 12-7 7-7-7",key:"1idqje"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wK=re("ArrowLeftFromLine",[["path",{d:"m9 6-6 6 6 6",key:"7v63n9"}],["path",{d:"M3 12h14",key:"13k4hi"}],["path",{d:"M21 19V5",key:"b4bplr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jK=re("ArrowLeftRight",[["path",{d:"M8 3 4 7l4 4",key:"9rb6wj"}],["path",{d:"M4 7h16",key:"6tx8e3"}],["path",{d:"m16 21 4-4-4-4",key:"siv7j2"}],["path",{d:"M20 17H4",key:"h6l3hr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NK=re("ArrowLeftToLine",[["path",{d:"M3 19V5",key:"rwsyhb"}],["path",{d:"m13 6-6 6 6 6",key:"1yhaz7"}],["path",{d:"M7 12h14",key:"uoisry"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qr=re("ArrowLeft",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kK=re("ArrowRightFromLine",[["path",{d:"M3 5v14",key:"1nt18q"}],["path",{d:"M21 12H7",key:"13ipq5"}],["path",{d:"m15 18 6-6-6-6",key:"6tx3qv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lw=re("ArrowRightLeft",[["path",{d:"m16 3 4 4-4 4",key:"1x1c3m"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"m8 21-4-4 4-4",key:"h9nckh"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SK=re("ArrowRightToLine",[["path",{d:"M17 12H3",key:"8awo09"}],["path",{d:"m11 18 6-6-6-6",key:"8c2y43"}],["path",{d:"M21 5v14",key:"nzette"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oa=re("ArrowRight",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"m12 5 7 7-7 7",key:"xquz4c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CK=re("ArrowUp01",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["rect",{x:"15",y:"4",width:"4",height:"6",ry:"2",key:"1bwicg"}],["path",{d:"M17 20v-6h-2",key:"1qp1so"}],["path",{d:"M15 20h4",key:"1j968p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TK=re("ArrowUp10",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M17 10V4h-2",key:"zcsr5x"}],["path",{d:"M15 10h4",key:"id2lce"}],["rect",{x:"15",y:"14",width:"4",height:"6",ry:"2",key:"33xykx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w3=re("ArrowUpAZ",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M20 8h-5",key:"1vsyxs"}],["path",{d:"M15 10V6.5a2.5 2.5 0 0 1 5 0V10",key:"ag13bf"}],["path",{d:"M15 14h5l-5 6h5",key:"ur5jdg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ah=re("ArrowUpDown",[["path",{d:"m21 16-4 4-4-4",key:"f6ql7i"}],["path",{d:"M17 20V4",key:"1ejh1v"}],["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EK=re("ArrowUpFromDot",[["path",{d:"m5 9 7-7 7 7",key:"1hw5ic"}],["path",{d:"M12 16V2",key:"ywoabb"}],["circle",{cx:"12",cy:"21",r:"1",key:"o0uj5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AK=re("ArrowUpFromLine",[["path",{d:"m18 9-6-6-6 6",key:"kcunyi"}],["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MK=re("ArrowUpLeft",[["path",{d:"M7 17V7h10",key:"11bw93"}],["path",{d:"M17 17 7 7",key:"2786uv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const j3=re("ArrowUpNarrowWide",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M11 12h4",key:"q8tih4"}],["path",{d:"M11 16h7",key:"uosisv"}],["path",{d:"M11 20h10",key:"jvxblo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GP=re("ArrowUpRight",[["path",{d:"M7 7h10v10",key:"1tivn9"}],["path",{d:"M7 17 17 7",key:"1vkiza"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IK=re("ArrowUpToLine",[["path",{d:"M5 3h14",key:"7usisc"}],["path",{d:"m18 13-6-6-6 6",key:"1kf1n9"}],["path",{d:"M12 7v14",key:"1akyts"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PK=re("ArrowUpWideNarrow",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M11 12h10",key:"1438ji"}],["path",{d:"M11 16h7",key:"uosisv"}],["path",{d:"M11 20h4",key:"1krc32"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const N3=re("ArrowUpZA",[["path",{d:"m3 8 4-4 4 4",key:"11wl7u"}],["path",{d:"M7 4v16",key:"1glfcx"}],["path",{d:"M15 4h5l-5 6h5",key:"8asdl1"}],["path",{d:"M15 20v-3.5a2.5 2.5 0 0 1 5 0V20",key:"r6l5cz"}],["path",{d:"M20 18h-5",key:"18j1r2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iu=re("ArrowUp",[["path",{d:"m5 12 7-7 7 7",key:"hav0vg"}],["path",{d:"M12 19V5",key:"x0mq9r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LK=re("ArrowsUpFromLine",[["path",{d:"m4 6 3-3 3 3",key:"9aidw8"}],["path",{d:"M7 17V3",key:"19qxw1"}],["path",{d:"m14 6 3-3 3 3",key:"6iy689"}],["path",{d:"M17 17V3",key:"o0fmgi"}],["path",{d:"M4 21h16",key:"1h09gz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DK=re("Asterisk",[["path",{d:"M12 6v12",key:"1vza4d"}],["path",{d:"M17.196 9 6.804 15",key:"1ah31z"}],["path",{d:"m6.804 9 10.392 6",key:"1b6pxd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RK=re("AtSign",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M16 8v5a3 3 0 0 0 6 0v-1a10 10 0 1 0-4 8",key:"7n84p3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OK=re("Atom",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M20.2 20.2c2.04-2.03.02-7.36-4.5-11.9-4.54-4.52-9.87-6.54-11.9-4.5-2.04 2.03-.02 7.36 4.5 11.9 4.54 4.52 9.87 6.54 11.9 4.5Z",key:"1l2ple"}],["path",{d:"M15.7 15.7c4.52-4.54 6.54-9.87 4.5-11.9-2.03-2.04-7.36-.02-11.9 4.5-4.52 4.54-6.54 9.87-4.5 11.9 2.03 2.04 7.36.02 11.9-4.5Z",key:"1wam0m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FK=re("AudioLines",[["path",{d:"M2 10v3",key:"1fnikh"}],["path",{d:"M6 6v11",key:"11sgs0"}],["path",{d:"M10 3v18",key:"yhl04a"}],["path",{d:"M14 8v7",key:"3a1oy3"}],["path",{d:"M18 5v13",key:"123xd1"}],["path",{d:"M22 10v3",key:"154ddg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zK=re("AudioWaveform",[["path",{d:"M2 13a2 2 0 0 0 2-2V7a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0V4a2 2 0 0 1 4 0v13a2 2 0 0 0 4 0v-4a2 2 0 0 1 2-2",key:"57tc96"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fc=re("Award",[["path",{d:"m15.477 12.89 1.515 8.526a.5.5 0 0 1-.81.47l-3.58-2.687a1 1 0 0 0-1.197 0l-3.586 2.686a.5.5 0 0 1-.81-.469l1.514-8.526",key:"1yiouv"}],["circle",{cx:"12",cy:"8",r:"6",key:"1vp47v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BK=re("Axe",[["path",{d:"m14 12-8.5 8.5a2.12 2.12 0 1 1-3-3L11 9",key:"csbz4o"}],["path",{d:"M15 13 9 7l4-4 6 6h3a8 8 0 0 1-7 7z",key:"113wfo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k3=re("Axis3d",[["path",{d:"M4 4v16h16",key:"1s015l"}],["path",{d:"m4 20 7-7",key:"17qe9y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $K=re("Baby",[["path",{d:"M9 12h.01",key:"157uk2"}],["path",{d:"M15 12h.01",key:"1k8ypt"}],["path",{d:"M10 16c.5.3 1.2.5 2 .5s1.5-.2 2-.5",key:"1u7htd"}],["path",{d:"M19 6.3a9 9 0 0 1 1.8 3.9 2 2 0 0 1 0 3.6 9 9 0 0 1-17.6 0 2 2 0 0 1 0-3.6A9 9 0 0 1 12 3c2 0 3.5 1.1 3.5 2.5s-.9 2.5-2 2.5c-.8 0-1.5-.4-1.5-1",key:"5yv0yz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UK=re("Backpack",[["path",{d:"M4 10a4 4 0 0 1 4-4h8a4 4 0 0 1 4 4v10a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2z",key:"1ol0lm"}],["path",{d:"M8 10h8",key:"c7uz4u"}],["path",{d:"M8 18h8",key:"1no2b1"}],["path",{d:"M8 22v-6a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v6",key:"1fr6do"}],["path",{d:"M9 6V4a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v2",key:"donm21"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qK=re("BadgeAlert",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VK=re("BadgeCent",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M15.4 10a4 4 0 1 0 0 4",key:"2eqtx8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S3=re("BadgeCheck",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HK=re("BadgeDollarSign",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GK=re("BadgeEuro",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M7 12h5",key:"gblrwe"}],["path",{d:"M15 9.4a4 4 0 1 0 0 5.2",key:"1makmb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WK=re("BadgeHelp",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["line",{x1:"12",x2:"12.01",y1:"17",y2:"17",key:"io3f8k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KK=re("BadgeIndianRupee",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M8 8h8",key:"1bis0t"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m13 17-5-1h1a4 4 0 0 0 0-8",key:"nu2bwa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YK=re("BadgeInfo",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"12",x2:"12",y1:"16",y2:"12",key:"1y1yb1"}],["line",{x1:"12",x2:"12.01",y1:"8",y2:"8",key:"110wyk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZK=re("BadgeJapaneseYen",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m9 8 3 3v7",key:"17yadx"}],["path",{d:"m12 11 3-3",key:"p4cfq1"}],["path",{d:"M9 12h6",key:"1c52cq"}],["path",{d:"M9 16h6",key:"8wimt3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QK=re("BadgeMinus",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XK=re("BadgePercent",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JK=re("BadgePlus",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"12",x2:"12",y1:"8",y2:"16",key:"10p56q"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eY=re("BadgePoundSterling",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M8 12h4",key:"qz6y1c"}],["path",{d:"M10 16V9.5a2.5 2.5 0 0 1 5 0",key:"3mlbjk"}],["path",{d:"M8 16h7",key:"sbedsn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tY=re("BadgeRussianRuble",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M9 16h5",key:"1syiyw"}],["path",{d:"M9 12h5a2 2 0 1 0 0-4h-3v9",key:"1ge9c1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sY=re("BadgeSwissFranc",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["path",{d:"M11 17V8h4",key:"1bfq6y"}],["path",{d:"M11 12h3",key:"2eqnfz"}],["path",{d:"M9 16h4",key:"1skf3a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nY=re("BadgeX",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}],["line",{x1:"15",x2:"9",y1:"9",y2:"15",key:"f7djnv"}],["line",{x1:"9",x2:"15",y1:"9",y2:"15",key:"1shsy8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rY=re("Badge",[["path",{d:"M3.85 8.62a4 4 0 0 1 4.78-4.77 4 4 0 0 1 6.74 0 4 4 0 0 1 4.78 4.78 4 4 0 0 1 0 6.74 4 4 0 0 1-4.77 4.78 4 4 0 0 1-6.75 0 4 4 0 0 1-4.78-4.77 4 4 0 0 1 0-6.76Z",key:"3c2336"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aY=re("BaggageClaim",[["path",{d:"M22 18H6a2 2 0 0 1-2-2V7a2 2 0 0 0-2-2",key:"4irg2o"}],["path",{d:"M17 14V4a2 2 0 0 0-2-2h-1a2 2 0 0 0-2 2v10",key:"14fcyx"}],["rect",{width:"13",height:"8",x:"8",y:"6",rx:"1",key:"o6oiis"}],["circle",{cx:"18",cy:"20",r:"2",key:"t9985n"}],["circle",{cx:"9",cy:"20",r:"2",key:"e5v82j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WP=re("Ban",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.9 4.9 14.2 14.2",key:"1m5liu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iY=re("Banana",[["path",{d:"M4 13c3.5-2 8-2 10 2a5.5 5.5 0 0 1 8 5",key:"1cscit"}],["path",{d:"M5.15 17.89c5.52-1.52 8.65-6.89 7-12C11.55 4 11.5 2 13 2c3.22 0 5 5.5 5 8 0 6.5-4.2 12-10.49 12C5.11 22 2 22 2 20c0-1.5 1.14-1.55 3.15-2.11Z",key:"1y1nbv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oY=re("Bandage",[["path",{d:"M10 10.01h.01",key:"1e9xi7"}],["path",{d:"M10 14.01h.01",key:"ac23bv"}],["path",{d:"M14 10.01h.01",key:"2wfrvf"}],["path",{d:"M14 14.01h.01",key:"8tw8yn"}],["path",{d:"M18 6v11.5",key:"dkbidh"}],["path",{d:"M6 6v12",key:"vkc79e"}],["rect",{x:"2",y:"6",width:"20",height:"12",rx:"2",key:"1wpnh2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lY=re("Banknote",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M6 12h.01M18 12h.01",key:"113zkx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cY=re("Barcode",[["path",{d:"M3 5v14",key:"1nt18q"}],["path",{d:"M8 5v14",key:"1ybrkv"}],["path",{d:"M12 5v14",key:"s699le"}],["path",{d:"M17 5v14",key:"ycjyhj"}],["path",{d:"M21 5v14",key:"nzette"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dY=re("Baseline",[["path",{d:"M4 20h16",key:"14thso"}],["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kp=re("Bath",[["path",{d:"M10 4 8 6",key:"1rru8s"}],["path",{d:"M17 19v2",key:"ts1sot"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M7 19v2",key:"12npes"}],["path",{d:"M9 5 7.621 3.621A2.121 2.121 0 0 0 4 5v12a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-5",key:"14ym8i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uY=re("BatteryCharging",[["path",{d:"M15 7h1a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-2",key:"1sdynx"}],["path",{d:"M6 7H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h1",key:"1gkd3k"}],["path",{d:"m11 7-3 5h4l-3 5",key:"b4a64w"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hY=re("BatteryFull",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}],["line",{x1:"10",x2:"10",y1:"11",y2:"13",key:"haxvl5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"13",key:"c6fn6x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mY=re("BatteryLow",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pY=re("BatteryMedium",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}],["line",{x1:"6",x2:"6",y1:"11",y2:"13",key:"1wd6dw"}],["line",{x1:"10",x2:"10",y1:"11",y2:"13",key:"haxvl5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fY=re("BatteryWarning",[["path",{d:"M10 17h.01",key:"nbq80n"}],["path",{d:"M10 7v6",key:"nne03l"}],["path",{d:"M14 7h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2h-2",key:"1x5o8m"}],["path",{d:"M22 11v2",key:"1wo06k"}],["path",{d:"M6 7H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"1mdjgh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xY=re("Battery",[["rect",{width:"16",height:"10",x:"2",y:"7",rx:"2",ry:"2",key:"1w10f2"}],["line",{x1:"22",x2:"22",y1:"11",y2:"13",key:"4dh1rd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P7=re("Beaker",[["path",{d:"M4.5 3h15",key:"c7n0jr"}],["path",{d:"M6 3v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V3",key:"m1uhx7"}],["path",{d:"M6 14h12",key:"4cwo0f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gY=re("BeanOff",[["path",{d:"M9 9c-.64.64-1.521.954-2.402 1.165A6 6 0 0 0 8 22a13.96 13.96 0 0 0 9.9-4.1",key:"bq3udt"}],["path",{d:"M10.75 5.093A6 6 0 0 1 22 8c0 2.411-.61 4.68-1.683 6.66",key:"17ccse"}],["path",{d:"M5.341 10.62a4 4 0 0 0 6.487 1.208M10.62 5.341a4.015 4.015 0 0 1 2.039 2.04",key:"18zqgq"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yY=re("Bean",[["path",{d:"M10.165 6.598C9.954 7.478 9.64 8.36 9 9c-.64.64-1.521.954-2.402 1.165A6 6 0 0 0 8 22c7.732 0 14-6.268 14-14a6 6 0 0 0-11.835-1.402Z",key:"1tvzk7"}],["path",{d:"M5.341 10.62a4 4 0 1 0 5.279-5.28",key:"2cyri2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U2=re("BedDouble",[["path",{d:"M2 20v-8a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v8",key:"1k78r4"}],["path",{d:"M4 10V6a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4",key:"fb3tl2"}],["path",{d:"M12 4v6",key:"1dcgq2"}],["path",{d:"M2 18h20",key:"ajqnye"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vY=re("BedSingle",[["path",{d:"M3 20v-8a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v8",key:"1wm6mi"}],["path",{d:"M5 10V6a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v4",key:"4k93s5"}],["path",{d:"M3 18h18",key:"1h113x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J0=re("Bed",[["path",{d:"M2 4v16",key:"vw9hq8"}],["path",{d:"M2 8h18a2 2 0 0 1 2 2v10",key:"1dgv2r"}],["path",{d:"M2 17h20",key:"18nfp3"}],["path",{d:"M6 8v9",key:"1yriud"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bY=re("Beef",[["circle",{cx:"12.5",cy:"8.5",r:"2.5",key:"9738u8"}],["path",{d:"M12.5 2a6.5 6.5 0 0 0-6.22 4.6c-1.1 3.13-.78 3.9-3.18 6.08A3 3 0 0 0 5 18c4 0 8.4-1.8 11.4-4.3A6.5 6.5 0 0 0 12.5 2Z",key:"o0f6za"}],["path",{d:"m18.5 6 2.19 4.5a6.48 6.48 0 0 1 .31 2 6.49 6.49 0 0 1-2.6 5.2C15.4 20.2 11 22 7 22a3 3 0 0 1-2.68-1.66L2.4 16.5",key:"k7p6i0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _Y=re("BeerOff",[["path",{d:"M13 13v5",key:"igwfh0"}],["path",{d:"M17 11.47V8",key:"16yw0g"}],["path",{d:"M17 11h1a3 3 0 0 1 2.745 4.211",key:"1xbt65"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 8v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2v-3",key:"c55o3e"}],["path",{d:"M7.536 7.535C6.766 7.649 6.154 8 5.5 8a2.5 2.5 0 0 1-1.768-4.268",key:"1ydug7"}],["path",{d:"M8.727 3.204C9.306 2.767 9.885 2 11 2c1.56 0 2 1.5 3 1.5s1.72-.5 2.5-.5a1 1 0 1 1 0 5c-.78 0-1.5-.5-2.5-.5a3.149 3.149 0 0 0-.842.12",key:"q81o7q"}],["path",{d:"M9 14.6V18",key:"20ek98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wY=re("Beer",[["path",{d:"M17 11h1a3 3 0 0 1 0 6h-1",key:"1yp76v"}],["path",{d:"M9 12v6",key:"1u1cab"}],["path",{d:"M13 12v6",key:"1sugkk"}],["path",{d:"M14 7.5c-1 0-1.44.5-3 .5s-2-.5-3-.5-1.72.5-2.5.5a2.5 2.5 0 0 1 0-5c.78 0 1.57.5 2.5.5S9.44 2 11 2s2 1.5 3 1.5 1.72-.5 2.5-.5a2.5 2.5 0 0 1 0 5c-.78 0-1.5-.5-2.5-.5Z",key:"1510fo"}],["path",{d:"M5 8v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V8",key:"19jb7n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jY=re("BellDot",[["path",{d:"M19.4 14.9C20.2 16.4 21 17 21 17H3s3-2 3-9c0-3.3 2.7-6 6-6 .7 0 1.3.1 1.9.3",key:"xcehk"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["circle",{cx:"18",cy:"8",r:"3",key:"1g0gzu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NY=re("BellElectric",[["path",{d:"M18.8 4A6.3 8.7 0 0 1 20 9",key:"xve1fh"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["circle",{cx:"9",cy:"9",r:"7",key:"p2h5vp"}],["rect",{width:"10",height:"6",x:"4",y:"16",rx:"2",key:"17f3te"}],["path",{d:"M14 19c3 0 4.6-1.6 4.6-1.6",key:"n7odp6"}],["circle",{cx:"20",cy:"16",r:"2",key:"1v9bxh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kY=re("BellMinus",[["path",{d:"M18.4 12c.8 3.8 2.6 5 2.6 5H3s3-2 3-9c0-3.3 2.7-6 6-6 1.8 0 3.4.8 4.5 2",key:"eck70s"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M15 8h6",key:"8ybuxh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cw=re("BellOff",[["path",{d:"M8.7 3A6 6 0 0 1 18 8a21.3 21.3 0 0 0 .6 5",key:"o7mx20"}],["path",{d:"M17 17H3s3-2 3-9a4.67 4.67 0 0 1 .3-1.7",key:"16f1lm"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SY=re("BellPlus",[["path",{d:"M19.3 14.8C20.1 16.4 21 17 21 17H3s3-2 3-9c0-3.3 2.7-6 6-6 1 0 1.9.2 2.8.7",key:"guizqy"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M15 8h6",key:"8ybuxh"}],["path",{d:"M18 5v6",key:"g5ayrv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BS=re("BellRing",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}],["path",{d:"M4 2C2.8 3.7 2 5.7 2 8",key:"tap9e0"}],["path",{d:"M22 8c0-2.3-.8-4.3-2-6",key:"5bb3ad"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nm=re("Bell",[["path",{d:"M6 8a6 6 0 0 1 12 0c0 7 3 9 3 9H3s3-2 3-9",key:"1qo2s2"}],["path",{d:"M10.3 21a1.94 1.94 0 0 0 3.4 0",key:"qgo35s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C3=re("BetweenHorizontalEnd",[["rect",{width:"13",height:"7",x:"3",y:"3",rx:"1",key:"11xb64"}],["path",{d:"m22 15-3-3 3-3",key:"26chmm"}],["rect",{width:"13",height:"7",x:"3",y:"14",rx:"1",key:"k6ky7n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T3=re("BetweenHorizontalStart",[["rect",{width:"13",height:"7",x:"8",y:"3",rx:"1",key:"pkso9a"}],["path",{d:"m2 9 3 3-3 3",key:"1agib5"}],["rect",{width:"13",height:"7",x:"8",y:"14",rx:"1",key:"1q5fc1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CY=re("BetweenVerticalEnd",[["rect",{width:"7",height:"13",x:"3",y:"3",rx:"1",key:"1fdu0f"}],["path",{d:"m9 22 3-3 3 3",key:"17z65a"}],["rect",{width:"7",height:"13",x:"14",y:"3",rx:"1",key:"1squn4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TY=re("BetweenVerticalStart",[["rect",{width:"7",height:"13",x:"3",y:"8",rx:"1",key:"1fjrkv"}],["path",{d:"m15 2-3 3-3-3",key:"1uh6eb"}],["rect",{width:"7",height:"13",x:"14",y:"8",rx:"1",key:"w3fjg8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EY=re("BicepsFlexed",[["path",{d:"M12.409 13.017A5 5 0 0 1 22 15c0 3.866-4 7-9 7-4.077 0-8.153-.82-10.371-2.462-.426-.316-.631-.832-.62-1.362C2.118 12.723 2.627 2 10 2a3 3 0 0 1 3 3 2 2 0 0 1-2 2c-1.105 0-1.64-.444-2-1",key:"1pmlyh"}],["path",{d:"M15 14a5 5 0 0 0-7.584 2",key:"5rb254"}],["path",{d:"M9.964 6.825C8.019 7.977 9.5 13 8 15",key:"kbvsx9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AY=re("Bike",[["circle",{cx:"18.5",cy:"17.5",r:"3.5",key:"15x4ox"}],["circle",{cx:"5.5",cy:"17.5",r:"3.5",key:"1noe27"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["path",{d:"M12 17.5V14l-3-3 4-3 2 3h2",key:"1npguv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MY=re("Binary",[["rect",{x:"14",y:"14",width:"4",height:"6",rx:"2",key:"p02svl"}],["rect",{x:"6",y:"4",width:"4",height:"6",rx:"2",key:"xm4xkj"}],["path",{d:"M6 20h4",key:"1i6q5t"}],["path",{d:"M14 10h4",key:"ru81e7"}],["path",{d:"M6 14h2v6",key:"16z9wg"}],["path",{d:"M14 4h2v6",key:"1idq9u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IY=re("Binoculars",[["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M19 7V4a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3",key:"3apit1"}],["path",{d:"M20 21a2 2 0 0 0 2-2v-3.851c0-1.39-2-2.962-2-4.829V8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v11a2 2 0 0 0 2 2z",key:"rhpgnw"}],["path",{d:"M 22 16 L 2 16",key:"14lkq7"}],["path",{d:"M4 21a2 2 0 0 1-2-2v-3.851c0-1.39 2-2.962 2-4.829V8a1 1 0 0 1 1-1h4a1 1 0 0 1 1 1v11a2 2 0 0 1-2 2z",key:"104b3k"}],["path",{d:"M9 7V4a1 1 0 0 0-1-1H6a1 1 0 0 0-1 1v3",key:"14fczp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PY=re("Biohazard",[["circle",{cx:"12",cy:"11.9",r:"2",key:"e8h31w"}],["path",{d:"M6.7 3.4c-.9 2.5 0 5.2 2.2 6.7C6.5 9 3.7 9.6 2 11.6",key:"17bolr"}],["path",{d:"m8.9 10.1 1.4.8",key:"15ezny"}],["path",{d:"M17.3 3.4c.9 2.5 0 5.2-2.2 6.7 2.4-1.2 5.2-.6 6.9 1.5",key:"wtwa5u"}],["path",{d:"m15.1 10.1-1.4.8",key:"1r0b28"}],["path",{d:"M16.7 20.8c-2.6-.4-4.6-2.6-4.7-5.3-.2 2.6-2.1 4.8-4.7 5.2",key:"m7qszh"}],["path",{d:"M12 13.9v1.6",key:"zfyyim"}],["path",{d:"M13.5 5.4c-1-.2-2-.2-3 0",key:"1bi9q0"}],["path",{d:"M17 16.4c.7-.7 1.2-1.6 1.5-2.5",key:"1rhjqw"}],["path",{d:"M5.5 13.9c.3.9.8 1.8 1.5 2.5",key:"8gsud3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LY=re("Bird",[["path",{d:"M16 7h.01",key:"1kdx03"}],["path",{d:"M3.4 18H12a8 8 0 0 0 8-8V7a4 4 0 0 0-7.28-2.3L2 20",key:"oj1oa8"}],["path",{d:"m20 7 2 .5-2 .5",key:"12nv4d"}],["path",{d:"M10 18v3",key:"1yea0a"}],["path",{d:"M14 17.75V21",key:"1pymcb"}],["path",{d:"M7 18a6 6 0 0 0 3.84-10.61",key:"1npnn0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DY=re("Bitcoin",[["path",{d:"M11.767 19.089c4.924.868 6.14-6.025 1.216-6.894m-1.216 6.894L5.86 18.047m5.908 1.042-.347 1.97m1.563-8.864c4.924.869 6.14-6.025 1.215-6.893m-1.215 6.893-3.94-.694m5.155-6.2L8.29 4.26m5.908 1.042.348-1.97M7.48 20.364l3.126-17.727",key:"yr8idg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RY=re("Blend",[["circle",{cx:"9",cy:"9",r:"7",key:"p2h5vp"}],["circle",{cx:"15",cy:"15",r:"7",key:"19ennj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OY=re("Blinds",[["path",{d:"M3 3h18",key:"o7r712"}],["path",{d:"M20 7H8",key:"gd2fo2"}],["path",{d:"M20 11H8",key:"1ynp89"}],["path",{d:"M10 19h10",key:"19hjk5"}],["path",{d:"M8 15h12",key:"1yqzne"}],["path",{d:"M4 3v14",key:"fggqzn"}],["circle",{cx:"4",cy:"19",r:"2",key:"p3m9r0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FY=re("Blocks",[["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["path",{d:"M10 21V8a1 1 0 0 0-1-1H4a1 1 0 0 0-1 1v12a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-5a1 1 0 0 0-1-1H3",key:"1fpvtg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zY=re("BluetoothConnected",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}],["line",{x1:"18",x2:"21",y1:"12",y2:"12",key:"1rsjjs"}],["line",{x1:"3",x2:"6",y1:"12",y2:"12",key:"11yl8c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BY=re("BluetoothOff",[["path",{d:"m17 17-5 5V12l-5 5",key:"v5aci6"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M14.5 9.5 17 7l-5-5v4.5",key:"1kddfz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $Y=re("BluetoothSearching",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}],["path",{d:"M20.83 14.83a4 4 0 0 0 0-5.66",key:"k8tn1j"}],["path",{d:"M18 12h.01",key:"yjnet6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UY=re("Bluetooth",[["path",{d:"m7 7 10 10-5 5V2l5 5L7 17",key:"1q5490"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $S=re("Bold",[["path",{d:"M6 12h9a4 4 0 0 1 0 8H7a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1h7a4 4 0 0 1 0 8",key:"mg9rjx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qY=re("Bolt",[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VY=re("Bomb",[["circle",{cx:"11",cy:"13",r:"9",key:"hd149"}],["path",{d:"M14.35 4.65 16.3 2.7a2.41 2.41 0 0 1 3.4 0l1.6 1.6a2.4 2.4 0 0 1 0 3.4l-1.95 1.95",key:"jp4j1b"}],["path",{d:"m22 2-1.5 1.5",key:"ay92ug"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HY=re("Bone",[["path",{d:"M17 10c.7-.7 1.69 0 2.5 0a2.5 2.5 0 1 0 0-5 .5.5 0 0 1-.5-.5 2.5 2.5 0 1 0-5 0c0 .81.7 1.8 0 2.5l-7 7c-.7.7-1.69 0-2.5 0a2.5 2.5 0 0 0 0 5c.28 0 .5.22.5.5a2.5 2.5 0 1 0 5 0c0-.81-.7-1.8 0-2.5Z",key:"w610uw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GY=re("BookA",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m8 13 4-7 4 7",key:"4rari8"}],["path",{d:"M9.1 11h5.7",key:"1gkovt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WY=re("BookAudio",[["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8v3",key:"gejaml"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 8v3",key:"1qzp49"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KY=re("BookCheck",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 9.5 2 2 4-4",key:"1dth82"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YY=re("BookCopy",[["path",{d:"M2 16V4a2 2 0 0 1 2-2h11",key:"spzkk5"}],["path",{d:"M22 18H11a2 2 0 1 0 0 4h10.5a.5.5 0 0 0 .5-.5v-15a.5.5 0 0 0-.5-.5H11a2 2 0 0 0-2 2v12",key:"1wz07i"}],["path",{d:"M5 14H4a2 2 0 1 0 0 4h1",key:"16gqf9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E3=re("BookDashed",[["path",{d:"M12 17h2",key:"13u4lk"}],["path",{d:"M12 22h2",key:"kn7ki6"}],["path",{d:"M12 2h2",key:"cvn524"}],["path",{d:"M18 22h1a1 1 0 0 0 1-1",key:"w6gbqz"}],["path",{d:"M18 2h1a1 1 0 0 1 1 1v1",key:"1vpra5"}],["path",{d:"M20 15v2h-2",key:"fph276"}],["path",{d:"M20 8v3",key:"deu0bs"}],["path",{d:"M4 11V9",key:"v3xsx8"}],["path",{d:"M4 19.5V15",key:"6gr39e"}],["path",{d:"M4 5v-.5A2.5 2.5 0 0 1 6.5 2H8",key:"wywhs9"}],["path",{d:"M8 22H6.5a1 1 0 0 1 0-5H8",key:"1cu73q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZY=re("BookDown",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 10 3 3 3-3",key:"zt5b4y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QY=re("BookHeadphones",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 12v-2a4 4 0 0 1 8 0v2",key:"1vsqkj"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XY=re("BookHeart",[["path",{d:"M16 8.2A2.22 2.22 0 0 0 13.8 6c-.8 0-1.4.3-1.8.9-.4-.6-1-.9-1.8-.9A2.22 2.22 0 0 0 8 8.2c0 .6.3 1.2.7 1.6A226.652 226.652 0 0 0 12 13a404 404 0 0 0 3.3-3.1 2.413 2.413 0 0 0 .7-1.7",key:"1t75a8"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JY=re("BookImage",[["path",{d:"m20 13.7-2.1-2.1a2 2 0 0 0-2.8 0L9.7 17",key:"q6ojf0"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["circle",{cx:"10",cy:"8",r:"2",key:"2qkj4p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eZ=re("BookKey",[["path",{d:"m19 3 1 1",key:"ze14oc"}],["path",{d:"m20 2-4.5 4.5",key:"1sppr8"}],["path",{d:"M20 8v13a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"1ocbpn"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H14",key:"1gfsgw"}],["circle",{cx:"14",cy:"8",r:"2",key:"u49eql"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tZ=re("BookLock",[["path",{d:"M18 6V4a2 2 0 1 0-4 0v2",key:"1aquzs"}],["path",{d:"M20 15v6a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"1rkj32"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H10",key:"18wgow"}],["rect",{x:"12",y:"6",width:"8",height:"5",rx:"1",key:"73l30o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sZ=re("BookMarked",[["path",{d:"M10 2v8l3-3 3 3V2",key:"sqw3rj"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nZ=re("BookMinus",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rZ=re("BookOpenCheck",[["path",{d:"M12 21V7",key:"gj6g52"}],["path",{d:"m16 12 2 2 4-4",key:"mdajum"}],["path",{d:"M22 6V4a1 1 0 0 0-1-1h-5a4 4 0 0 0-4 4 4 4 0 0 0-4-4H3a1 1 0 0 0-1 1v13a1 1 0 0 0 1 1h6a3 3 0 0 1 3 3 3 3 0 0 1 3-3h6a1 1 0 0 0 1-1v-1.3",key:"8arnkb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aZ=re("BookOpenText",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M16 12h2",key:"7q9ll5"}],["path",{d:"M16 8h2",key:"msurwy"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}],["path",{d:"M6 12h2",key:"32wvfc"}],["path",{d:"M6 8h2",key:"30oboj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rm=re("BookOpen",[["path",{d:"M12 7v14",key:"1akyts"}],["path",{d:"M3 18a1 1 0 0 1-1-1V4a1 1 0 0 1 1-1h5a4 4 0 0 1 4 4 4 4 0 0 1 4-4h5a1 1 0 0 1 1 1v13a1 1 0 0 1-1 1h-6a3 3 0 0 0-3 3 3 3 0 0 0-3-3z",key:"ruj8y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iZ=re("BookPlus",[["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oZ=re("BookText",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"M8 11h8",key:"vwpz6n"}],["path",{d:"M8 7h6",key:"1f0q6e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lZ=re("BookType",[["path",{d:"M10 13h4",key:"ytezjc"}],["path",{d:"M12 6v7",key:"1f6ttz"}],["path",{d:"M16 8V6H8v2",key:"x8j6u4"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cZ=re("BookUp2",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M18 2h1a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"161d7n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2",key:"1lorq7"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dZ=re("BookUp",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uZ=re("BookUser",[["path",{d:"M15 13a3 3 0 1 0-6 0",key:"10j68g"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hZ=re("BookX",[["path",{d:"m14.5 7-5 5",key:"dy991v"}],["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}],["path",{d:"m9.5 7 5 5",key:"s45iea"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mZ=re("Book",[["path",{d:"M4 19.5v-15A2.5 2.5 0 0 1 6.5 2H19a1 1 0 0 1 1 1v18a1 1 0 0 1-1 1H6.5a1 1 0 0 1 0-5H20",key:"k3hazp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pZ=re("BookmarkCheck",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fZ=re("BookmarkMinus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L7=re("BookmarkPlus",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}],["line",{x1:"12",x2:"12",y1:"7",y2:"13",key:"1cppfj"}],["line",{x1:"15",x2:"9",y1:"10",y2:"10",key:"1gty7f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xZ=re("BookmarkX",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2Z",key:"169p4p"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pv=re("Bookmark",[["path",{d:"m19 21-7-4-7 4V5a2 2 0 0 1 2-2h10a2 2 0 0 1 2 2v16z",key:"1fy3hk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gZ=re("BoomBox",[["path",{d:"M4 9V5a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v4",key:"vvzvr1"}],["path",{d:"M8 8v1",key:"xcqmfk"}],["path",{d:"M12 8v1",key:"1rj8u4"}],["path",{d:"M16 8v1",key:"1q12zr"}],["rect",{width:"20",height:"12",x:"2",y:"9",rx:"2",key:"igpb89"}],["circle",{cx:"8",cy:"15",r:"2",key:"fa4a8s"}],["circle",{cx:"16",cy:"15",r:"2",key:"14c3ya"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yZ=re("BotMessageSquare",[["path",{d:"M12 6V2H8",key:"1155em"}],["path",{d:"m8 18-4 4V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2Z",key:"w2lp3e"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M9 11v2",key:"1ueba0"}],["path",{d:"M15 11v2",key:"i11awn"}],["path",{d:"M20 12h2",key:"1q8mjw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vZ=re("BotOff",[["path",{d:"M13.67 8H18a2 2 0 0 1 2 2v4.33",key:"7az073"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}],["path",{d:"M8 8H6a2 2 0 0 0-2 2v8a2 2 0 0 0 2 2h12a2 2 0 0 0 1.414-.586",key:"s09a7a"}],["path",{d:"M9 13v2",key:"rq6x2g"}],["path",{d:"M9.67 4H12v2.33",key:"110xot"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const US=re("Bot",[["path",{d:"M12 8V4H8",key:"hb8ula"}],["rect",{width:"16",height:"12",x:"4",y:"8",rx:"2",key:"enze0r"}],["path",{d:"M2 14h2",key:"vft8re"}],["path",{d:"M20 14h2",key:"4cs60a"}],["path",{d:"M15 13v2",key:"1xurst"}],["path",{d:"M9 13v2",key:"rq6x2g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D7=re("Box",[["path",{d:"M21 8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16Z",key:"hh9hay"}],["path",{d:"m3.3 7 8.7 5 8.7-5",key:"g66t2b"}],["path",{d:"M12 22V12",key:"d0xqtd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bZ=re("Boxes",[["path",{d:"M2.97 12.92A2 2 0 0 0 2 14.63v3.24a2 2 0 0 0 .97 1.71l3 1.8a2 2 0 0 0 2.06 0L12 19v-5.5l-5-3-4.03 2.42Z",key:"lc1i9w"}],["path",{d:"m7 16.5-4.74-2.85",key:"1o9zyk"}],["path",{d:"m7 16.5 5-3",key:"va8pkn"}],["path",{d:"M7 16.5v5.17",key:"jnp8gn"}],["path",{d:"M12 13.5V19l3.97 2.38a2 2 0 0 0 2.06 0l3-1.8a2 2 0 0 0 .97-1.71v-3.24a2 2 0 0 0-.97-1.71L17 10.5l-5 3Z",key:"8zsnat"}],["path",{d:"m17 16.5-5-3",key:"8arw3v"}],["path",{d:"m17 16.5 4.74-2.85",key:"8rfmw"}],["path",{d:"M17 16.5v5.17",key:"k6z78m"}],["path",{d:"M7.97 4.42A2 2 0 0 0 7 6.13v4.37l5 3 5-3V6.13a2 2 0 0 0-.97-1.71l-3-1.8a2 2 0 0 0-2.06 0l-3 1.8Z",key:"1xygjf"}],["path",{d:"M12 8 7.26 5.15",key:"1vbdud"}],["path",{d:"m12 8 4.74-2.85",key:"3rx089"}],["path",{d:"M12 13.5V8",key:"1io7kd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A3=re("Braces",[["path",{d:"M8 3H7a2 2 0 0 0-2 2v5a2 2 0 0 1-2 2 2 2 0 0 1 2 2v5c0 1.1.9 2 2 2h1",key:"ezmyqa"}],["path",{d:"M16 21h1a2 2 0 0 0 2-2v-5c0-1.1.9-2 2-2a2 2 0 0 1-2-2V5a2 2 0 0 0-2-2h-1",key:"e1hn23"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _Z=re("Brackets",[["path",{d:"M16 3h3v18h-3",key:"1yor1f"}],["path",{d:"M8 21H5V3h3",key:"1qrfwo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wZ=re("BrainCircuit",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M9 13a4.5 4.5 0 0 0 3-4",key:"10igwf"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M12 13h4",key:"1ku699"}],["path",{d:"M12 18h6a2 2 0 0 1 2 2v1",key:"105ag5"}],["path",{d:"M12 8h8",key:"1lhi5i"}],["path",{d:"M16 8V5a2 2 0 0 1 2-2",key:"u6izg6"}],["circle",{cx:"16",cy:"13",r:".5",key:"ry7gng"}],["circle",{cx:"18",cy:"3",r:".5",key:"1aiba7"}],["circle",{cx:"20",cy:"21",r:".5",key:"yhc1fs"}],["circle",{cx:"20",cy:"8",r:".5",key:"1e43v0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jZ=re("BrainCog",[["path",{d:"M12 5a3 3 0 1 0-5.997.142 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588 4 4 0 0 0 7.636 2.106 3.2 3.2 0 0 0 .164-.546c.028-.13.306-.13.335 0a3.2 3.2 0 0 0 .163.546 4 4 0 0 0 7.636-2.106 4 4 0 0 0 .556-6.588 4 4 0 0 0-2.526-5.77A3 3 0 1 0 12 5",key:"1kgmhc"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m15.7 10.4-.9.4",key:"ayzo6p"}],["path",{d:"m9.2 13.2-.9.4",key:"1uzb3g"}],["path",{d:"m13.6 15.7-.4-.9",key:"11ifqf"}],["path",{d:"m10.8 9.2-.4-.9",key:"1pmk2v"}],["path",{d:"m15.7 13.5-.9-.4",key:"7ng02m"}],["path",{d:"m9.2 10.9-.9-.4",key:"1x66zd"}],["path",{d:"m10.5 15.7.4-.9",key:"3js94g"}],["path",{d:"m13.1 9.2.4-.9",key:"18n7mc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R7=re("Brain",[["path",{d:"M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z",key:"l5xja"}],["path",{d:"M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z",key:"ep3f8r"}],["path",{d:"M15 13a4.5 4.5 0 0 1-3-4 4.5 4.5 0 0 1-3 4",key:"1p4c4q"}],["path",{d:"M17.599 6.5a3 3 0 0 0 .399-1.375",key:"tmeiqw"}],["path",{d:"M6.003 5.125A3 3 0 0 0 6.401 6.5",key:"105sqy"}],["path",{d:"M3.477 10.896a4 4 0 0 1 .585-.396",key:"ql3yin"}],["path",{d:"M19.938 10.5a4 4 0 0 1 .585.396",key:"1qfode"}],["path",{d:"M6 18a4 4 0 0 1-1.967-.516",key:"2e4loj"}],["path",{d:"M19.967 17.484A4 4 0 0 1 18 18",key:"159ez6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NZ=re("BrickWall",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 9v6",key:"199k2o"}],["path",{d:"M16 15v6",key:"8rj2es"}],["path",{d:"M16 3v6",key:"1j6rpj"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M8 15v6",key:"1stoo3"}],["path",{d:"M8 3v6",key:"vlvjmk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kZ=re("BriefcaseBusiness",[["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2",key:"1ksdt3"}],["path",{d:"M22 13a18.15 18.15 0 0 1-20 0",key:"12hx5q"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SZ=re("BriefcaseConveyorBelt",[["path",{d:"M10 20v2",key:"1n8e1g"}],["path",{d:"M14 20v2",key:"1lq872"}],["path",{d:"M18 20v2",key:"10uadw"}],["path",{d:"M21 20H3",key:"kdqkdp"}],["path",{d:"M6 20v2",key:"a9bc87"}],["path",{d:"M8 16V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v12",key:"17n9tx"}],["rect",{x:"4",y:"6",width:"16",height:"10",rx:"2",key:"1097i5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CZ=re("BriefcaseMedical",[["path",{d:"M12 11v4",key:"a6ujw6"}],["path",{d:"M14 13h-4",key:"1pl8zg"}],["path",{d:"M16 6V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v2",key:"1ksdt3"}],["path",{d:"M18 6v14",key:"1mu4gy"}],["path",{d:"M6 6v14",key:"1s15cj"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zm=re("Briefcase",[["path",{d:"M16 20V4a2 2 0 0 0-2-2h-4a2 2 0 0 0-2 2v16",key:"jecpp"}],["rect",{width:"20",height:"14",x:"2",y:"6",rx:"2",key:"i6l2r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TZ=re("BringToFront",[["rect",{x:"8",y:"8",width:"8",height:"8",rx:"2",key:"yj20xf"}],["path",{d:"M4 10a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2",key:"1ltk23"}],["path",{d:"M14 20a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2",key:"1q24h9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EZ=re("Brush",[["path",{d:"m9.06 11.9 8.07-8.06a2.85 2.85 0 1 1 4.03 4.03l-8.06 8.08",key:"1styjt"}],["path",{d:"M7.07 14.94c-1.66 0-3 1.35-3 3.02 0 1.33-2.5 1.52-2 2.02 1.08 1.1 2.49 2.02 4 2.02 2.2 0 4-1.8 4-4.04a3.01 3.01 0 0 0-3-3.02z",key:"z0l1mu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AZ=re("BugOff",[["path",{d:"M15 7.13V6a3 3 0 0 0-5.14-2.1L8 2",key:"vl8zik"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M22 13h-4v-2a4 4 0 0 0-4-4h-1.3",key:"1ou0bd"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M7.7 7.7A4 4 0 0 0 6 11v3a6 6 0 0 0 11.13 3.13",key:"1njkjs"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MZ=re("BugPlay",[["path",{d:"M12.765 21.522a.5.5 0 0 1-.765-.424v-8.196a.5.5 0 0 1 .765-.424l5.878 3.674a1 1 0 0 1 0 1.696z",key:"17shqo"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M18 11a4 4 0 0 0-4-4h-4a4 4 0 0 0-4 4v3a6.1 6.1 0 0 0 2 4.5",key:"1tjixy"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IZ=re("Bug",[["path",{d:"m8 2 1.88 1.88",key:"fmnt4t"}],["path",{d:"M14.12 3.88 16 2",key:"qol33r"}],["path",{d:"M9 7.13v-1a3.003 3.003 0 1 1 6 0v1",key:"d7y7pr"}],["path",{d:"M12 20c-3.3 0-6-2.7-6-6v-3a4 4 0 0 1 4-4h4a4 4 0 0 1 4 4v3c0 3.3-2.7 6-6 6",key:"xs1cw7"}],["path",{d:"M12 20v-9",key:"1qisl0"}],["path",{d:"M6.53 9C4.6 8.8 3 7.1 3 5",key:"32zzws"}],["path",{d:"M6 13H2",key:"82j7cp"}],["path",{d:"M3 21c0-2.1 1.7-3.9 3.8-4",key:"4p0ekp"}],["path",{d:"M20.97 5c0 2.1-1.6 3.8-3.5 4",key:"18gb23"}],["path",{d:"M22 13h-4",key:"1jl80f"}],["path",{d:"M17.2 17c2.1.1 3.8 1.9 3.8 4",key:"k3fwyw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ua=re("Building2",[["path",{d:"M6 22V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v18Z",key:"1b4qmf"}],["path",{d:"M6 12H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h2",key:"i71pzd"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-2",key:"10jefs"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"M10 10h4",key:"tcdvrf"}],["path",{d:"M10 14h4",key:"kelpxr"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gA=re("Building",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["path",{d:"M9 22v-4h6v4",key:"r93iot"}],["path",{d:"M8 6h.01",key:"1dz90k"}],["path",{d:"M16 6h.01",key:"1x0f13"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M8 14h.01",key:"6423bh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PZ=re("BusFront",[["path",{d:"M4 6 2 7",key:"1mqr15"}],["path",{d:"M10 6h4",key:"1itunk"}],["path",{d:"m22 7-2-1",key:"1umjhc"}],["rect",{width:"16",height:"16",x:"4",y:"3",rx:"2",key:"1wxw4b"}],["path",{d:"M4 11h16",key:"mpoxn0"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M16 15h.01",key:"rnfrdf"}],["path",{d:"M6 19v2",key:"1loha6"}],["path",{d:"M18 21v-2",key:"sqyl04"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LZ=re("Bus",[["path",{d:"M8 6v6",key:"18i7km"}],["path",{d:"M15 6v6",key:"1sg6z9"}],["path",{d:"M2 12h19.6",key:"de5uta"}],["path",{d:"M18 18h3s.5-1.7.8-2.8c.1-.4.2-.8.2-1.2 0-.4-.1-.8-.2-1.2l-1.4-5C20.1 6.8 19.1 6 18 6H4a2 2 0 0 0-2 2v10h3",key:"1wwztk"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}],["path",{d:"M9 18h5",key:"lrx6i"}],["circle",{cx:"16",cy:"18",r:"2",key:"1v4tcr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DZ=re("CableCar",[["path",{d:"M10 3h.01",key:"lbucoy"}],["path",{d:"M14 2h.01",key:"1k8aa1"}],["path",{d:"m2 9 20-5",key:"1kz0j5"}],["path",{d:"M12 12V6.5",key:"1vbrij"}],["rect",{width:"16",height:"10",x:"4",y:"12",rx:"3",key:"if91er"}],["path",{d:"M9 12v5",key:"3anwtq"}],["path",{d:"M15 12v5",key:"5xh3zn"}],["path",{d:"M4 17h16",key:"g4d7ey"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RZ=re("Cable",[["path",{d:"M17 21v-2a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h2a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1",key:"10bnsj"}],["path",{d:"M19 15V6.5a1 1 0 0 0-7 0v11a1 1 0 0 1-7 0V9",key:"1eqmu1"}],["path",{d:"M21 21v-2h-4",key:"14zm7j"}],["path",{d:"M3 5h4V3",key:"z442eg"}],["path",{d:"M7 5a1 1 0 0 1 1 1v1a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V6a1 1 0 0 1 1-1V3",key:"ebdjd7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OZ=re("CakeSlice",[["circle",{cx:"9",cy:"7",r:"2",key:"1305pl"}],["path",{d:"M7.2 7.9 3 11v9c0 .6.4 1 1 1h16c.6 0 1-.4 1-1v-9c0-2-3-6-7-8l-3.6 2.6",key:"xle13f"}],["path",{d:"M16 13H3",key:"1wpj08"}],["path",{d:"M16 17H3",key:"3lvfcd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ah=re("Cake",[["path",{d:"M20 21v-8a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v8",key:"1w3rig"}],["path",{d:"M4 16s.5-1 2-1 2.5 2 4 2 2.5-2 4-2 2.5 2 4 2 2-1 2-1",key:"n2jgmb"}],["path",{d:"M2 21h20",key:"1nyx9w"}],["path",{d:"M7 8v3",key:"1qtyvj"}],["path",{d:"M12 8v3",key:"hwp4zt"}],["path",{d:"M17 8v3",key:"1i6e5u"}],["path",{d:"M7 4h.01",key:"1bh4kh"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M17 4h.01",key:"1upcoc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dw=re("Calculator",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["line",{x1:"8",x2:"16",y1:"6",y2:"6",key:"x4nwl0"}],["line",{x1:"16",x2:"16",y1:"14",y2:"18",key:"wjye3r"}],["path",{d:"M16 10h.01",key:"1m94wz"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FZ=re("Calendar1",[["path",{d:"M11 14h1v4",key:"fy54vd"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zZ=re("CalendarArrowDown",[["path",{d:"m14 18 4 4 4-4",key:"1waygx"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M18 14v8",key:"irew45"}],["path",{d:"M21 11.354V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7.343",key:"bse4f3"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BZ=re("CalendarArrowUp",[["path",{d:"m14 18 4-4 4 4",key:"ftkppy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M18 22v-8",key:"su0gjh"}],["path",{d:"M21 11.343V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h9",key:"1exg90"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $Z=re("CalendarCheck2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 14V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"bce9hv"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m16 20 2 2 4-4",key:"13tcca"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O7=re("CalendarCheck",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m9 16 2 2 4-4",key:"19s6y9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xf=re("CalendarClock",[["path",{d:"M21 7.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h3.5",key:"1osxxc"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M3 10h5",key:"r794hk"}],["path",{d:"M17.5 17.5 16 16.3V14",key:"akvzfd"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UZ=re("CalendarCog",[["path",{d:"m15.2 16.9-.9-.4",key:"1r0w5f"}],["path",{d:"m15.2 19.1-.9.4",key:"j188fs"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"m16.9 15.2-.4-.9",key:"699xu"}],["path",{d:"m16.9 20.8-.4.9",key:"dfjc4z"}],["path",{d:"m19.5 14.3-.4.9",key:"1eb35c"}],["path",{d:"m19.5 21.7-.4-.9",key:"1tonu5"}],["path",{d:"M21 10.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"11kmuh"}],["path",{d:"m21.7 16.5-.9.4",key:"1knoei"}],["path",{d:"m21.7 19.5-.9-.4",key:"q4dx6b"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cl=re("CalendarDays",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qZ=re("CalendarFold",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 17V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h11Z",key:"kg77oy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M15 22v-4a2 2 0 0 1 2-2h4",key:"1gnbqr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uw=re("CalendarHeart",[["path",{d:"M3 10h18V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7",key:"136lmk"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21.29 14.7a2.43 2.43 0 0 0-2.65-.52c-.3.12-.57.3-.8.53l-.34.34-.35-.34a2.43 2.43 0 0 0-2.65-.53c-.3.12-.56.3-.79.53-.95.94-1 2.53.2 3.74L17.5 22l3.6-3.55c1.2-1.21 1.14-2.8.19-3.74Z",key:"1t7hil"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VZ=re("CalendarMinus2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M10 16h4",key:"17e571"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HZ=re("CalendarMinus",[["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 15V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8.5",key:"1scpom"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F7=re("CalendarOff",[["path",{d:"M4.2 4.2A2 2 0 0 0 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 1.82-1.18",key:"16swn3"}],["path",{d:"M21 15.5V6a2 2 0 0 0-2-2H9.5",key:"yhw86o"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h7",key:"1wap6i"}],["path",{d:"M21 10h-5.5",key:"quycpq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GZ=re("CalendarPlus2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M10 16h4",key:"17e571"}],["path",{d:"M12 14v4",key:"1thi36"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lg=re("CalendarPlus",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 13V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"3spt84"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M19 16v6",key:"tddt3s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WZ=re("CalendarRange",[["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M17 14h-6",key:"bkmgh3"}],["path",{d:"M13 18H7",key:"bb0bb7"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 18h.01",key:"1bdyru"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KZ=re("CalendarSearch",[["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 11.75V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h7.25",key:"1jrsq6"}],["path",{d:"m22 22-1.875-1.875",key:"13zax7"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 2v4",key:"1cmpym"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YZ=re("CalendarSync",[["path",{d:"M11 10v4h4",key:"172dkj"}],["path",{d:"m11 14 1.535-1.605a5 5 0 0 1 8 1.5",key:"vu0qm5"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"m21 18-1.535 1.605a5 5 0 0 1-8-1.5",key:"1qgeyt"}],["path",{d:"M21 22v-4h-4",key:"hrummi"}],["path",{d:"M21 8.5V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h4.3",key:"mctw84"}],["path",{d:"M3 10h4",key:"1el30a"}],["path",{d:"M8 2v4",key:"1cmpym"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZZ=re("CalendarX2",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M21 13V6a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h8",key:"3spt84"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m17 22 5-5",key:"1k6ppv"}],["path",{d:"m17 17 5 5",key:"p7ous7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z7=re("CalendarX",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"m14 14-4 4",key:"rymu2i"}],["path",{d:"m10 14 4 4",key:"3sz06r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yr=re("Calendar",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QZ=re("CameraOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16",key:"qmtpty"}],["path",{d:"M9.5 4h5L17 7h3a2 2 0 0 1 2 2v7.5",key:"1ufyfc"}],["path",{d:"M14.121 15.121A3 3 0 1 1 9.88 10.88",key:"11zox6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jf=re("Camera",[["path",{d:"M14.5 4h-5L7 7H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3l-2.5-3z",key:"1tc9qg"}],["circle",{cx:"12",cy:"13",r:"3",key:"1vg3eu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XZ=re("CandyCane",[["path",{d:"M5.7 21a2 2 0 0 1-3.5-2l8.6-14a6 6 0 0 1 10.4 6 2 2 0 1 1-3.464-2 2 2 0 1 0-3.464-2Z",key:"isaq8g"}],["path",{d:"M17.75 7 15 2.1",key:"12x7e8"}],["path",{d:"M10.9 4.8 13 9",key:"100a87"}],["path",{d:"m7.9 9.7 2 4.4",key:"ntfhaj"}],["path",{d:"M4.9 14.7 7 18.9",key:"1x43jy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JZ=re("CandyOff",[["path",{d:"m8.5 8.5-1 1a4.95 4.95 0 0 0 7 7l1-1",key:"1ff4ui"}],["path",{d:"M11.843 6.187A4.947 4.947 0 0 1 16.5 7.5a4.947 4.947 0 0 1 1.313 4.657",key:"1sbrv4"}],["path",{d:"M14 16.5V14",key:"1maf8j"}],["path",{d:"M14 6.5v1.843",key:"1a6u6t"}],["path",{d:"M10 10v7.5",key:"80pj65"}],["path",{d:"m16 7 1-5 1.367.683A3 3 0 0 0 19.708 3H21v1.292a3 3 0 0 0 .317 1.341L22 7l-5 1",key:"11a9mt"}],["path",{d:"m8 17-1 5-1.367-.683A3 3 0 0 0 4.292 21H3v-1.292a3 3 0 0 0-.317-1.341L2 17l5-1",key:"3mjmon"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eQ=re("Candy",[["path",{d:"m9.5 7.5-2 2a4.95 4.95 0 1 0 7 7l2-2a4.95 4.95 0 1 0-7-7Z",key:"ue6khb"}],["path",{d:"M14 6.5v10",key:"5xnk7c"}],["path",{d:"M10 7.5v10",key:"1uew51"}],["path",{d:"m16 7 1-5 1.37.68A3 3 0 0 0 19.7 3H21v1.3c0 .46.1.92.32 1.33L22 7l-5 1",key:"b9cp6k"}],["path",{d:"m8 17-1 5-1.37-.68A3 3 0 0 0 4.3 21H3v-1.3a3 3 0 0 0-.32-1.33L2 17l5-1",key:"5lney8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tQ=re("Cannabis",[["path",{d:"M12 22v-4",key:"1utk9m"}],["path",{d:"M7 12c-1.5 0-4.5 1.5-5 3 3.5 1.5 6 1 6 1-1.5 1.5-2 3.5-2 5 2.5 0 4.5-1.5 6-3 1.5 1.5 3.5 3 6 3 0-1.5-.5-3.5-2-5 0 0 2.5.5 6-1-.5-1.5-3.5-3-5-3 1.5-1 4-4 4-6-2.5 0-5.5 1.5-7 3 0-2.5-.5-5-2-7-1.5 2-2 4.5-2 7-1.5-1.5-4.5-3-7-3 0 2 2.5 5 4 6",key:"1mezod"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sQ=re("CaptionsOff",[["path",{d:"M10.5 5H19a2 2 0 0 1 2 2v8.5",key:"jqtk4d"}],["path",{d:"M17 11h-.5",key:"1961ue"}],["path",{d:"M19 19H5a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2",key:"1keqsi"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M7 11h4",key:"1o1z6v"}],["path",{d:"M7 15h2.5",key:"1ina1g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M3=re("Captions",[["rect",{width:"18",height:"14",x:"3",y:"5",rx:"2",ry:"2",key:"12ruh7"}],["path",{d:"M7 15h4M15 15h2M7 11h2M13 11h4",key:"1ueiar"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nQ=re("CarFront",[["path",{d:"m21 8-2 2-1.5-3.7A2 2 0 0 0 15.646 5H8.4a2 2 0 0 0-1.903 1.257L5 10 3 8",key:"1imjwt"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 14h.01",key:"7oqj8z"}],["rect",{width:"18",height:"8",x:"3",y:"10",rx:"2",key:"a7itu8"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rQ=re("CarTaxiFront",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"m21 8-2 2-1.5-3.7A2 2 0 0 0 15.646 5H8.4a2 2 0 0 0-1.903 1.257L5 10 3 8",key:"1imjwt"}],["path",{d:"M7 14h.01",key:"1qa3f1"}],["path",{d:"M17 14h.01",key:"7oqj8z"}],["rect",{width:"18",height:"8",x:"3",y:"10",rx:"2",key:"a7itu8"}],["path",{d:"M5 18v2",key:"ppbyun"}],["path",{d:"M19 18v2",key:"gy7782"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aQ=re("Car",[["path",{d:"M19 17h2c.6 0 1-.4 1-1v-3c0-.9-.7-1.7-1.5-1.9C18.7 10.6 16 10 16 10s-1.3-1.4-2.2-2.3c-.5-.4-1.1-.7-1.8-.7H5c-.6 0-1.1.4-1.4.9l-1.4 2.9A3.7 3.7 0 0 0 2 12v4c0 .6.4 1 1 1h2",key:"5owen"}],["circle",{cx:"7",cy:"17",r:"2",key:"u2ysq9"}],["path",{d:"M9 17h6",key:"r8uit2"}],["circle",{cx:"17",cy:"17",r:"2",key:"axvx0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iQ=re("Caravan",[["path",{d:"M18 19V9a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v8a2 2 0 0 0 2 2h2",key:"19jm3t"}],["path",{d:"M2 9h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H2",key:"13hakp"}],["path",{d:"M22 17v1a1 1 0 0 1-1 1H10v-9a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v9",key:"1crci8"}],["circle",{cx:"8",cy:"19",r:"2",key:"t8fc5s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oQ=re("Carrot",[["path",{d:"M2.27 21.7s9.87-3.5 12.73-6.36a4.5 4.5 0 0 0-6.36-6.37C5.77 11.84 2.27 21.7 2.27 21.7zM8.64 14l-2.05-2.04M15.34 15l-2.46-2.46",key:"rfqxbe"}],["path",{d:"M22 9s-1.33-2-3.5-2C16.86 7 15 9 15 9s1.33 2 3.5 2S22 9 22 9z",key:"6b25w4"}],["path",{d:"M15 2s-2 1.33-2 3.5S15 9 15 9s2-1.84 2-3.5C17 3.33 15 2 15 2z",key:"fn65lo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lQ=re("CaseLower",[["circle",{cx:"7",cy:"12",r:"3",key:"12clwm"}],["path",{d:"M10 9v6",key:"17i7lo"}],["circle",{cx:"17",cy:"12",r:"3",key:"gl7c2s"}],["path",{d:"M14 7v8",key:"dl84cr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cQ=re("CaseSensitive",[["path",{d:"m3 15 4-8 4 8",key:"1vwr6u"}],["path",{d:"M4 13h6",key:"1r9ots"}],["circle",{cx:"18",cy:"12",r:"3",key:"1kchzo"}],["path",{d:"M21 9v6",key:"anns31"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dQ=re("CaseUpper",[["path",{d:"m3 15 4-8 4 8",key:"1vwr6u"}],["path",{d:"M4 13h6",key:"1r9ots"}],["path",{d:"M15 11h4.5a2 2 0 0 1 0 4H15V7h4a2 2 0 0 1 0 4",key:"1sqfas"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uQ=re("CassetteTape",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["circle",{cx:"8",cy:"10",r:"2",key:"1xl4ub"}],["path",{d:"M8 12h8",key:"1wcyev"}],["circle",{cx:"16",cy:"10",r:"2",key:"r14t7q"}],["path",{d:"m6 20 .7-2.9A1.4 1.4 0 0 1 8.1 16h7.8a1.4 1.4 0 0 1 1.4 1l.7 3",key:"l01ucn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hQ=re("Cast",[["path",{d:"M2 8V6a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v12a2 2 0 0 1-2 2h-6",key:"3zrzxg"}],["path",{d:"M2 12a9 9 0 0 1 8 8",key:"g6cvee"}],["path",{d:"M2 16a5 5 0 0 1 4 4",key:"1y1dii"}],["line",{x1:"2",x2:"2.01",y1:"20",y2:"20",key:"xu2jvo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mQ=re("Castle",[["path",{d:"M22 20v-9H2v9a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2Z",key:"109fe4"}],["path",{d:"M18 11V4H6v7",key:"mon5oj"}],["path",{d:"M15 22v-4a3 3 0 0 0-3-3a3 3 0 0 0-3 3v4",key:"1k4jtn"}],["path",{d:"M22 11V9",key:"3zbp94"}],["path",{d:"M2 11V9",key:"1x5rnq"}],["path",{d:"M6 4V2",key:"1rsq15"}],["path",{d:"M18 4V2",key:"1jsdo1"}],["path",{d:"M10 4V2",key:"75d9ly"}],["path",{d:"M14 4V2",key:"8nj3z6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pQ=re("Cat",[["path",{d:"M12 5c.67 0 1.35.09 2 .26 1.78-2 5.03-2.84 6.42-2.26 1.4.58-.42 7-.42 7 .57 1.07 1 2.24 1 3.44C21 17.9 16.97 21 12 21s-9-3-9-7.56c0-1.25.5-2.4 1-3.44 0 0-1.89-6.42-.5-7 1.39-.58 4.72.23 6.5 2.23A9.04 9.04 0 0 1 12 5Z",key:"x6xyqk"}],["path",{d:"M8 14v.5",key:"1nzgdb"}],["path",{d:"M16 14v.5",key:"1lajdz"}],["path",{d:"M11.25 16.25h1.5L12 17l-.75-.75Z",key:"12kq1m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fQ=re("Cctv",[["path",{d:"M16.75 12h3.632a1 1 0 0 1 .894 1.447l-2.034 4.069a1 1 0 0 1-1.708.134l-2.124-2.97",key:"ir91b5"}],["path",{d:"M17.106 9.053a1 1 0 0 1 .447 1.341l-3.106 6.211a1 1 0 0 1-1.342.447L3.61 12.3a2.92 2.92 0 0 1-1.3-3.91L3.69 5.6a2.92 2.92 0 0 1 3.92-1.3z",key:"jlp8i1"}],["path",{d:"M2 19h3.76a2 2 0 0 0 1.8-1.1L9 15",key:"19bib8"}],["path",{d:"M2 21v-4",key:"l40lih"}],["path",{d:"M7 9h.01",key:"19b3jx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I3=re("ChartArea",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z",key:"q0gr47"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P3=re("ChartBarBig",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"7",y:"13",width:"9",height:"4",rx:"1",key:"1iip1u"}],["rect",{x:"7",y:"5",width:"12",height:"4",rx:"1",key:"1anskk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xQ=re("ChartBarDecreasing",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11h8",key:"1feolt"}],["path",{d:"M7 16h3",key:"ur6vzw"}],["path",{d:"M7 6h12",key:"sz5b0d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gQ=re("ChartBarIncreasing",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11h8",key:"1feolt"}],["path",{d:"M7 16h12",key:"wsnu98"}],["path",{d:"M7 6h3",key:"w9rmul"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yQ=re("ChartBarStacked",[["path",{d:"M11 13v4",key:"vyy2rb"}],["path",{d:"M15 5v4",key:"1gx88a"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"7",y:"13",width:"9",height:"4",rx:"1",key:"1iip1u"}],["rect",{x:"7",y:"5",width:"12",height:"4",rx:"1",key:"1anskk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L3=re("ChartBar",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16h8",key:"srdodz"}],["path",{d:"M7 11h12",key:"127s9w"}],["path",{d:"M7 6h3",key:"w9rmul"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D3=re("ChartCandlestick",[["path",{d:"M9 5v4",key:"14uxtq"}],["rect",{width:"4",height:"6",x:"7",y:"9",rx:"1",key:"f4fvz0"}],["path",{d:"M9 15v2",key:"r5rk32"}],["path",{d:"M17 3v2",key:"1l2re6"}],["rect",{width:"4",height:"8",x:"15",y:"5",rx:"1",key:"z38je5"}],["path",{d:"M17 13v3",key:"5l0wba"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R3=re("ChartColumnBig",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vQ=re("ChartColumnDecreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17v-3",key:"1sqioe"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17V5",key:"1wzmnc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O3=re("ChartColumnIncreasing",[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17V5",key:"sfb6ij"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bQ=re("ChartColumnStacked",[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _o=re("ChartColumn",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _Q=re("ChartGantt",[["path",{d:"M10 6h8",key:"zvc2xc"}],["path",{d:"M12 16h6",key:"yi5mkt"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 11h7",key:"wz2hg0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F3=re("ChartLine",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wQ=re("ChartNetwork",[["path",{d:"m13.11 7.664 1.78 2.672",key:"go2gg9"}],["path",{d:"m14.162 12.788-3.324 1.424",key:"11x848"}],["path",{d:"m20 4-6.06 1.515",key:"1wxxh7"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["circle",{cx:"12",cy:"6",r:"2",key:"1jj5th"}],["circle",{cx:"16",cy:"12",r:"2",key:"4ma0v8"}],["circle",{cx:"9",cy:"15",r:"2",key:"lf2ghp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jQ=re("ChartNoAxesColumnDecreasing",[["path",{d:"M12 20V10",key:"g8npz5"}],["path",{d:"M18 20v-4",key:"8uic4z"}],["path",{d:"M6 20V4",key:"1w1bmo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z3=re("ChartNoAxesColumnIncreasing",[["line",{x1:"12",x2:"12",y1:"20",y2:"10",key:"1vz5eb"}],["line",{x1:"18",x2:"18",y1:"20",y2:"4",key:"cun8e5"}],["line",{x1:"6",x2:"6",y1:"20",y2:"16",key:"hq0ia6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B3=re("ChartNoAxesColumn",[["line",{x1:"18",x2:"18",y1:"20",y2:"10",key:"1xfpm4"}],["line",{x1:"12",x2:"12",y1:"20",y2:"4",key:"be30l9"}],["line",{x1:"6",x2:"6",y1:"20",y2:"14",key:"1r4le6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NQ=re("ChartNoAxesCombined",[["path",{d:"M12 16v5",key:"zza2cw"}],["path",{d:"M16 14v7",key:"1g90b9"}],["path",{d:"M20 10v11",key:"1iqoj0"}],["path",{d:"m22 3-8.646 8.646a.5.5 0 0 1-.708 0L9.354 8.354a.5.5 0 0 0-.707 0L2 15",key:"1fw8x9"}],["path",{d:"M4 18v3",key:"1yp0dc"}],["path",{d:"M8 14v7",key:"n3cwzv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $3=re("ChartNoAxesGantt",[["path",{d:"M8 6h10",key:"9lnwnk"}],["path",{d:"M6 12h9",key:"1g9pqf"}],["path",{d:"M11 18h7",key:"c8dzvl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U3=re("ChartPie",[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",key:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q3=re("ChartScatter",[["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["circle",{cx:"18.5",cy:"5.5",r:".5",fill:"currentColor",key:"lysivs"}],["circle",{cx:"11.5",cy:"11.5",r:".5",fill:"currentColor",key:"byv1b8"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["circle",{cx:"17.5",cy:"14.5",r:".5",fill:"currentColor",key:"1gjh6j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kQ=re("ChartSpline",[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 16c.5-2 1.5-7 4-7 2 0 2 3 4 3 2.5 0 4.5-5 5-7",key:"lw07rv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B7=re("CheckCheck",[["path",{d:"M18 6 7 17l-5-5",key:"116fxf"}],["path",{d:"m22 10-7.5 7.5L13 16",key:"ke71qq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lr=re("Check",[["path",{d:"M20 6 9 17l-5-5",key:"1gmf2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SQ=re("ChefHat",[["path",{d:"M17 21a1 1 0 0 0 1-1v-5.35c0-.457.316-.844.727-1.041a4 4 0 0 0-2.134-7.589 5 5 0 0 0-9.186 0 4 4 0 0 0-2.134 7.588c.411.198.727.585.727 1.041V20a1 1 0 0 0 1 1Z",key:"1qvrer"}],["path",{d:"M6 17h12",key:"1jwigz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CQ=re("Cherry",[["path",{d:"M2 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"cvxqlc"}],["path",{d:"M12 17a5 5 0 0 0 10 0c0-2.76-2.5-5-5-3-2.5-2-5 .24-5 3Z",key:"1ostrc"}],["path",{d:"M7 14c3.22-2.91 4.29-8.75 5-12 1.66 2.38 4.94 9 5 12",key:"hqx58h"}],["path",{d:"M22 9c-4.29 0-7.14-2.33-10-7 5.71 0 10 4.67 10 7Z",key:"eykp1o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ao=re("ChevronDown",[["path",{d:"m6 9 6 6 6-6",key:"qrunsl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TQ=re("ChevronFirst",[["path",{d:"m17 18-6-6 6-6",key:"1yerx2"}],["path",{d:"M7 6v12",key:"1p53r6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EQ=re("ChevronLast",[["path",{d:"m7 18 6-6-6-6",key:"lwmzdw"}],["path",{d:"M17 6v12",key:"1o0aio"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ml=re("ChevronLeft",[["path",{d:"m15 18-6-6 6-6",key:"1wnfg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ga=re("ChevronRight",[["path",{d:"m9 18 6-6-6-6",key:"mthhwq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ex=re("ChevronUp",[["path",{d:"m18 15-6-6-6 6",key:"153udz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AQ=re("ChevronsDownUp",[["path",{d:"m7 20 5-5 5 5",key:"13a0gw"}],["path",{d:"m7 4 5 5 5-5",key:"1kwcof"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MQ=re("ChevronsDown",[["path",{d:"m7 6 5 5 5-5",key:"1lc07p"}],["path",{d:"m7 13 5 5 5-5",key:"1d48rs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IQ=re("ChevronsLeftRightEllipsis",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PQ=re("ChevronsLeftRight",[["path",{d:"m9 7-5 5 5 5",key:"j5w590"}],["path",{d:"m15 7 5 5-5 5",key:"1bl6da"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LQ=re("ChevronsLeft",[["path",{d:"m11 17-5-5 5-5",key:"13zhaf"}],["path",{d:"m18 17-5-5 5-5",key:"h8a8et"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DQ=re("ChevronsRightLeft",[["path",{d:"m20 17-5-5 5-5",key:"30x0n2"}],["path",{d:"m4 17 5-5-5-5",key:"16spf4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RQ=re("ChevronsRight",[["path",{d:"m6 17 5-5-5-5",key:"xnjwq"}],["path",{d:"m13 17 5-5-5-5",key:"17xmmf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $g=re("ChevronsUpDown",[["path",{d:"m7 15 5 5 5-5",key:"1hf1tw"}],["path",{d:"m7 9 5-5 5 5",key:"sgt6xg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OQ=re("ChevronsUp",[["path",{d:"m17 11-5-5-5 5",key:"e8nh98"}],["path",{d:"m17 18-5-5-5 5",key:"2avn1x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yA=re("Chrome",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["line",{x1:"21.17",x2:"12",y1:"8",y2:"8",key:"a0cw5f"}],["line",{x1:"3.95",x2:"8.54",y1:"6.06",y2:"14",key:"1kftof"}],["line",{x1:"10.88",x2:"15.46",y1:"21.94",y2:"14",key:"1ymyh8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FQ=re("Church",[["path",{d:"M10 9h4",key:"u4k05v"}],["path",{d:"M12 7v5",key:"ma6bk"}],["path",{d:"M14 22v-4a2 2 0 0 0-4 0v4",key:"1pdhuj"}],["path",{d:"M18 22V5.618a1 1 0 0 0-.553-.894l-4.553-2.277a2 2 0 0 0-1.788 0L6.553 4.724A1 1 0 0 0 6 5.618V22",key:"1rkokr"}],["path",{d:"m18 7 3.447 1.724a1 1 0 0 1 .553.894V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.618a1 1 0 0 1 .553-.894L6 7",key:"1w6esw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zQ=re("CigaretteOff",[["path",{d:"M12 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h13",key:"1gdiyg"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M21 12a1 1 0 0 1 1 1v2a1 1 0 0 1-.5.866",key:"166zjj"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BQ=re("Cigarette",[["path",{d:"M17 12H3a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h14",key:"1mb5g1"}],["path",{d:"M18 8c0-2.5-2-2.5-2-5",key:"1il607"}],["path",{d:"M21 16a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"1yl5r7"}],["path",{d:"M22 8c0-2.5-2-2.5-2-5",key:"1gah44"}],["path",{d:"M7 12v4",key:"jqww69"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bi=re("CircleAlert",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"12",x2:"12",y1:"8",y2:"12",key:"1pkeuh"}],["line",{x1:"12",x2:"12.01",y1:"16",y2:"16",key:"4dfq90"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V3=re("CircleArrowDown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H3=re("CircleArrowLeft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"m12 8-4 4 4 4",key:"15vm53"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G3=re("CircleArrowOutDownLeft",[["path",{d:"M2 12a10 10 0 1 1 10 10",key:"1yn6ov"}],["path",{d:"m2 22 10-10",key:"28ilpk"}],["path",{d:"M8 22H2v-6",key:"sulq54"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W3=re("CircleArrowOutDownRight",[["path",{d:"M12 22a10 10 0 1 1 10-10",key:"130bv5"}],["path",{d:"M22 22 12 12",key:"131aw7"}],["path",{d:"M22 16v6h-6",key:"1gvm70"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K3=re("CircleArrowOutUpLeft",[["path",{d:"M2 8V2h6",key:"hiwtdz"}],["path",{d:"m2 2 10 10",key:"1oh8rs"}],["path",{d:"M12 2A10 10 0 1 1 2 12",key:"rrk4fa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y3=re("CircleArrowOutUpRight",[["path",{d:"M22 12A10 10 0 1 1 12 2",key:"1fm58d"}],["path",{d:"M22 2 12 12",key:"yg2myt"}],["path",{d:"M16 2h6v6",key:"zan5cs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z3=re("CircleArrowRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q3=re("CircleArrowUp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pi=re("CircleCheckBig",[["path",{d:"M21.801 10A10 10 0 1 1 17 3.335",key:"yps3ct"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vr=re("CircleCheck",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X3=re("CircleChevronDown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m16 10-4 4-4-4",key:"894hmk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J3=re("CircleChevronLeft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m14 16-4-4 4-4",key:"ojs7w8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e5=re("CircleChevronRight",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m10 8 4 4-4 4",key:"1wy4r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t5=re("CircleChevronUp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m8 14 4-4 4 4",key:"fy2ptz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $Q=re("CircleDashed",[["path",{d:"M10.1 2.182a10 10 0 0 1 3.8 0",key:"5ilxe3"}],["path",{d:"M13.9 21.818a10 10 0 0 1-3.8 0",key:"11zvb9"}],["path",{d:"M17.609 3.721a10 10 0 0 1 2.69 2.7",key:"1iw5b2"}],["path",{d:"M2.182 13.9a10 10 0 0 1 0-3.8",key:"c0bmvh"}],["path",{d:"M20.279 17.609a10 10 0 0 1-2.7 2.69",key:"1ruxm7"}],["path",{d:"M21.818 10.1a10 10 0 0 1 0 3.8",key:"qkgqxc"}],["path",{d:"M3.721 6.391a10 10 0 0 1 2.7-2.69",key:"1mcia2"}],["path",{d:"M6.391 20.279a10 10 0 0 1-2.69-2.7",key:"1fvljs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const s5=re("CircleDivide",[["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}],["line",{x1:"12",x2:"12",y1:"16",y2:"16",key:"aqc6ln"}],["line",{x1:"12",x2:"12",y1:"8",y2:"8",key:"1mkcni"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UQ=re("CircleDollarSign",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 18V6",key:"zqpxq5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qQ=re("CircleDotDashed",[["path",{d:"M10.1 2.18a9.93 9.93 0 0 1 3.8 0",key:"1qdqn0"}],["path",{d:"M17.6 3.71a9.95 9.95 0 0 1 2.69 2.7",key:"1bq7p6"}],["path",{d:"M21.82 10.1a9.93 9.93 0 0 1 0 3.8",key:"1rlaqf"}],["path",{d:"M20.29 17.6a9.95 9.95 0 0 1-2.7 2.69",key:"1xk03u"}],["path",{d:"M13.9 21.82a9.94 9.94 0 0 1-3.8 0",key:"l7re25"}],["path",{d:"M6.4 20.29a9.95 9.95 0 0 1-2.69-2.7",key:"1v18p6"}],["path",{d:"M2.18 13.9a9.93 9.93 0 0 1 0-3.8",key:"xdo6bj"}],["path",{d:"M3.71 6.4a9.95 9.95 0 0 1 2.7-2.69",key:"1jjmaz"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VQ=re("CircleDot",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HQ=re("CircleEllipsis",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7 12h.01",key:"eqddd0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GQ=re("CircleEqual",[["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M7 14h10",key:"1mhdw3"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WQ=re("CircleFadingArrowUp",[["path",{d:"M12 2a10 10 0 0 1 7.38 16.75",key:"175t95"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}],["path",{d:"M2.5 8.875a10 10 0 0 0-.5 3",key:"1vce0s"}],["path",{d:"M2.83 16a10 10 0 0 0 2.43 3.4",key:"o3fkw4"}],["path",{d:"M4.636 5.235a10 10 0 0 1 .891-.857",key:"1szpfk"}],["path",{d:"M8.644 21.42a10 10 0 0 0 7.631-.38",key:"9yhvd4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KQ=re("CircleFadingPlus",[["path",{d:"M12 2a10 10 0 0 1 7.38 16.75",key:"175t95"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"M2.5 8.875a10 10 0 0 0-.5 3",key:"1vce0s"}],["path",{d:"M2.83 16a10 10 0 0 0 2.43 3.4",key:"o3fkw4"}],["path",{d:"M4.636 5.235a10 10 0 0 1 .891-.857",key:"1szpfk"}],["path",{d:"M8.644 21.42a10 10 0 0 0 7.631-.38",key:"9yhvd4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n5=re("CircleGauge",[["path",{d:"M15.6 2.7a10 10 0 1 0 5.7 5.7",key:"1e0p6d"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M13.4 10.6 19 5",key:"1kr7tw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q_=re("CircleHelp",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r5=re("CircleMinus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YQ=re("CircleOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.35 2.69A10 10 0 0 1 21.3 15.65",key:"1pfsoa"}],["path",{d:"M19.08 19.08A10 10 0 1 1 4.92 4.92",key:"1ablyi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a5=re("CircleParkingOff",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m5 5 14 14",key:"11anup"}],["path",{d:"M13 13a3 3 0 1 0 0-6H9v2",key:"uoagbd"}],["path",{d:"M9 17v-2.34",key:"a9qo08"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const i5=re("CircleParking",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9 17V7h4a3 3 0 0 1 0 6H9",key:"1dfk2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const o5=re("CirclePause",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"10",x2:"10",y1:"15",y2:"9",key:"c1nkhi"}],["line",{x1:"14",x2:"14",y1:"15",y2:"9",key:"h65svq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const l5=re("CirclePercent",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jh=re("CirclePlay",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polygon",{points:"10 8 16 12 10 16 10 8",key:"1cimsy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const c5=re("CirclePlus",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const d5=re("CirclePower",[["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M7.998 9.003a5 5 0 1 0 8-.005",key:"1pek45"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const u5=re("CircleSlash2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZQ=re("CircleSlash",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const h5=re("CircleStop",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["rect",{x:"9",y:"9",width:"6",height:"6",rx:"1",key:"1ssd4o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const m5=re("CircleUserRound",[["path",{d:"M18 20a6 6 0 0 0-12 0",key:"1qehca"}],["circle",{cx:"12",cy:"10",r:"4",key:"1h16sb"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const p5=re("CircleUser",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 20.662V19a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v1.662",key:"154egf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uc=re("CircleX",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const am=re("Circle",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QQ=re("CircuitBoard",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M11 9h4a2 2 0 0 0 2-2V3",key:"1ve2rv"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"M7 21v-4a2 2 0 0 1 2-2h4",key:"1fwkro"}],["circle",{cx:"15",cy:"15",r:"2",key:"3i40o0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XQ=re("Citrus",[["path",{d:"M21.66 17.67a1.08 1.08 0 0 1-.04 1.6A12 12 0 0 1 4.73 2.38a1.1 1.1 0 0 1 1.61-.04z",key:"4ite01"}],["path",{d:"M19.65 15.66A8 8 0 0 1 8.35 4.34",key:"1gxipu"}],["path",{d:"m14 10-5.5 5.5",key:"92pfem"}],["path",{d:"M14 17.85V10H6.15",key:"xqmtsk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JQ=re("Clapperboard",[["path",{d:"M20.2 6 3 11l-.9-2.4c-.3-1.1.3-2.2 1.3-2.5l13.5-4c1.1-.3 2.2.3 2.5 1.3Z",key:"1tn4o7"}],["path",{d:"m6.2 5.3 3.1 3.9",key:"iuk76l"}],["path",{d:"m12.4 3.4 3.1 4",key:"6hsd6n"}],["path",{d:"M3 11h18v8a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2Z",key:"ltgou9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KP=re("ClipboardCheck",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m9 14 2 2 4-4",key:"df797q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eX=re("ClipboardCopy",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-2",key:"4jdomd"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v4",key:"3hqy98"}],["path",{d:"M21 14H11",key:"1bme5i"}],["path",{d:"m15 10-4 4 4 4",key:"5dvupr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cb=re("ClipboardList",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M12 11h4",key:"1jrz19"}],["path",{d:"M12 16h4",key:"n85exb"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tX=re("ClipboardMinus",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M9 14h6",key:"159ibu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sX=re("ClipboardPaste",[["path",{d:"M15 2H9a1 1 0 0 0-1 1v2c0 .6.4 1 1 1h6c.6 0 1-.4 1-1V3c0-.6-.4-1-1-1Z",key:"1pp7kr"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2M16 4h2a2 2 0 0 1 2 2v2M11 14h10",key:"2ik1ml"}],["path",{d:"m17 10 4 4-4 4",key:"vp2hj1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const f5=re("ClipboardPenLine",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",key:"1oijnt"}],["path",{d:"M8 4H6a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-.5",key:"1but9f"}],["path",{d:"M16 4h2a2 2 0 0 1 1.73 1",key:"1p8n7l"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const x5=re("ClipboardPen",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",key:"1oijnt"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-5.5",key:"cereej"}],["path",{d:"M4 13.5V6a2 2 0 0 1 2-2h2",key:"5ua5vh"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nX=re("ClipboardPlus",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M9 14h6",key:"159ibu"}],["path",{d:"M12 17v-6",key:"1y8rbf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rX=re("ClipboardType",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"M9 12v-1h6v1",key:"iehl6m"}],["path",{d:"M11 17h2",key:"12w5me"}],["path",{d:"M12 11v6",key:"1bwqyc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aX=re("ClipboardX",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}],["path",{d:"m15 11-6 6",key:"1toa9n"}],["path",{d:"m9 11 6 6",key:"wlibny"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iX=re("Clipboard",[["rect",{width:"8",height:"4",x:"8",y:"2",rx:"1",ry:"1",key:"tgr4d6"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2h2",key:"116196"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oX=re("Clock1",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 14.5 8",key:"12zbmj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lX=re("Clock10",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 8 10",key:"atfzqc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cX=re("Clock11",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 9.5 8",key:"l5bg6f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dX=re("Clock12",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12",key:"1fub01"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uX=re("Clock2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 10",key:"1g230d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $7=re("Clock3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16.5 12",key:"1aq6pp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hX=re("Clock4",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mX=re("Clock5",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 14.5 16",key:"1pcbox"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pX=re("Clock6",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 12 16.5",key:"hb2qv6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fX=re("Clock7",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 9.5 16",key:"ka3394"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xX=re("Clock8",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 8 14",key:"tmc9b4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gX=re("Clock9",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 7.5 12",key:"1k60p0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yX=re("ClockAlert",[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["path",{d:"M16 21.16a10 10 0 1 1 5-13.516",key:"cxo92l"}],["path",{d:"M20 11.5v6",key:"2ei3xq"}],["path",{d:"M20 21.5h.01",key:"1r2dzp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vX=re("ClockArrowDown",[["path",{d:"M12.338 21.994A10 10 0 1 1 21.925 13.227",key:"1i7shu"}],["path",{d:"M12 6v6l2 1",key:"19cm8n"}],["path",{d:"m14 18 4 4 4-4",key:"1waygx"}],["path",{d:"M18 14v8",key:"irew45"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bX=re("ClockArrowUp",[["path",{d:"M13.228 21.925A10 10 0 1 1 21.994 12.338",key:"1fzlyi"}],["path",{d:"M12 6v6l1.562.781",key:"1ujuk9"}],["path",{d:"m14 18 4-4 4 4",key:"ftkppy"}],["path",{d:"M18 22v-8",key:"su0gjh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pr=re("Clock",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["polyline",{points:"12 6 12 12 16 14",key:"68esgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _X=re("CloudAlert",[["path",{d:"M12 12v4",key:"tww15h"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M17 18h.5a1 1 0 0 0 0-9h-1.79A7 7 0 1 0 7 17.708",key:"xsb5ju"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wX=re("CloudCog",[["circle",{cx:"12",cy:"17",r:"3",key:"1spfwm"}],["path",{d:"M4.2 15.1A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.2",key:"zaobp"}],["path",{d:"m15.7 18.4-.9-.3",key:"4qxpbn"}],["path",{d:"m9.2 15.9-.9-.3",key:"17q7o2"}],["path",{d:"m10.6 20.7.3-.9",key:"1pf4s2"}],["path",{d:"m13.1 14.2.3-.9",key:"1mnuqm"}],["path",{d:"m13.6 20.7-.4-1",key:"1jpd1m"}],["path",{d:"m10.8 14.3-.4-1",key:"17ugyy"}],["path",{d:"m8.3 18.6 1-.4",key:"s42vdx"}],["path",{d:"m14.7 15.8 1-.4",key:"2wizun"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g5=re("CloudDownload",[["path",{d:"M12 13v8l-4-4",key:"1f5nwf"}],["path",{d:"m12 21 4-4",key:"1lfcce"}],["path",{d:"M4.393 15.269A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.436 8.284",key:"ui1hmy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jX=re("CloudDrizzle",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M8 19v1",key:"1dk2by"}],["path",{d:"M8 14v1",key:"84yxot"}],["path",{d:"M16 19v1",key:"v220m7"}],["path",{d:"M16 14v1",key:"g12gj6"}],["path",{d:"M12 21v1",key:"q8vafk"}],["path",{d:"M12 16v1",key:"1mx6rx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NX=re("CloudFog",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 17H7",key:"pygtm1"}],["path",{d:"M17 21H9",key:"1u2q02"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kX=re("CloudHail",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 14v2",key:"a1is7l"}],["path",{d:"M8 14v2",key:"1e9m6t"}],["path",{d:"M16 20h.01",key:"xwek51"}],["path",{d:"M8 20h.01",key:"1vjney"}],["path",{d:"M12 16v2",key:"z66u1j"}],["path",{d:"M12 22h.01",key:"1urd7a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SX=re("CloudLightning",[["path",{d:"M6 16.326A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 .5 8.973",key:"1cez44"}],["path",{d:"m13 12-3 5h4l-3 5",key:"1t22er"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CX=re("CloudMoonRain",[["path",{d:"M10.188 8.5A6 6 0 0 1 16 4a1 1 0 0 0 6 6 6 6 0 0 1-3 5.197",key:"erj67n"}],["path",{d:"M11 20v2",key:"174qtz"}],["path",{d:"M3 20a5 5 0 1 1 8.9-4H13a3 3 0 0 1 2 5.24",key:"1qmrp3"}],["path",{d:"M7 19v2",key:"12npes"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TX=re("CloudMoon",[["path",{d:"M10.188 8.5A6 6 0 0 1 16 4a1 1 0 0 0 6 6 6 6 0 0 1-3 5.197",key:"erj67n"}],["path",{d:"M13 16a3 3 0 1 1 0 6H7a5 5 0 1 1 4.9-6Z",key:"p44pc9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EX=re("CloudOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.782 5.782A7 7 0 0 0 9 19h8.5a4.5 4.5 0 0 0 1.307-.193",key:"yfwify"}],["path",{d:"M21.532 16.5A4.5 4.5 0 0 0 17.5 10h-1.79A7.008 7.008 0 0 0 10 5.07",key:"jlfiyv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AX=re("CloudRainWind",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m9.2 22 3-7",key:"sb5f6j"}],["path",{d:"m9 13-3 7",key:"500co5"}],["path",{d:"m17 13-3 7",key:"8t2fiy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MX=re("CloudRain",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M16 14v6",key:"1j4efv"}],["path",{d:"M8 14v6",key:"17c4r9"}],["path",{d:"M12 16v6",key:"c8a4gj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IX=re("CloudSnow",[["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M8 19h.01",key:"puxtts"}],["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M12 21h.01",key:"h35vbk"}],["path",{d:"M16 15h.01",key:"rnfrdf"}],["path",{d:"M16 19h.01",key:"1vcnzz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PX=re("CloudSunRain",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M3 20a5 5 0 1 1 8.9-4H13a3 3 0 0 1 2 5.24",key:"1qmrp3"}],["path",{d:"M11 20v2",key:"174qtz"}],["path",{d:"M7 19v2",key:"12npes"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LX=re("CloudSun",[["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}],["path",{d:"M15.947 12.65a4 4 0 0 0-5.925-4.128",key:"dpwdj0"}],["path",{d:"M13 22H7a5 5 0 1 1 4.9-6H13a3 3 0 0 1 0 6Z",key:"s09mg5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const y5=re("CloudUpload",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M4 14.899A7 7 0 1 1 15.71 8h1.79a4.5 4.5 0 0 1 2.5 8.242",key:"1pljnt"}],["path",{d:"m8 17 4-4 4 4",key:"1quai1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DX=re("Cloud",[["path",{d:"M17.5 19H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"p7xjir"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RX=re("Cloudy",[["path",{d:"M17.5 21H9a7 7 0 1 1 6.71-9h1.79a4.5 4.5 0 1 1 0 9Z",key:"gqqjvc"}],["path",{d:"M22 10a3 3 0 0 0-3-3h-2.207a5.502 5.502 0 0 0-10.702.5",key:"1p2s76"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P2=re("Clover",[["path",{d:"M16.17 7.83 2 22",key:"t58vo8"}],["path",{d:"M4.02 12a2.827 2.827 0 1 1 3.81-4.17A2.827 2.827 0 1 1 12 4.02a2.827 2.827 0 1 1 4.17 3.81A2.827 2.827 0 1 1 19.98 12a2.827 2.827 0 1 1-3.81 4.17A2.827 2.827 0 1 1 12 19.98a2.827 2.827 0 1 1-4.17-3.81A1 1 0 1 1 4 12",key:"17k36q"}],["path",{d:"m7.83 7.83 8.34 8.34",key:"1d7sxk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OX=re("Club",[["path",{d:"M17.28 9.05a5.5 5.5 0 1 0-10.56 0A5.5 5.5 0 1 0 12 17.66a5.5 5.5 0 1 0 5.28-8.6Z",key:"27yuqz"}],["path",{d:"M12 17.66L12 22",key:"ogfahf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const N2=re("CodeXml",[["path",{d:"m18 16 4-4-4-4",key:"1inbqp"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}],["path",{d:"m14.5 4-5 16",key:"e7oirm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vA=re("Code",[["polyline",{points:"16 18 22 12 16 6",key:"z7tu5w"}],["polyline",{points:"8 6 2 12 8 18",key:"1eg1df"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FX=re("Codepen",[["polygon",{points:"12 2 22 8.5 22 15.5 12 22 2 15.5 2 8.5 12 2",key:"srzb37"}],["line",{x1:"12",x2:"12",y1:"22",y2:"15.5",key:"1t73f2"}],["polyline",{points:"22 8.5 12 15.5 2 8.5",key:"ajlxae"}],["polyline",{points:"2 15.5 12 8.5 22 15.5",key:"susrui"}],["line",{x1:"12",x2:"12",y1:"2",y2:"8.5",key:"2cldga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zX=re("Codesandbox",[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}],["polyline",{points:"7.5 4.21 12 6.81 16.5 4.21",key:"fabo96"}],["polyline",{points:"7.5 19.79 7.5 14.6 3 12",key:"z377f1"}],["polyline",{points:"21 12 16.5 14.6 16.5 19.79",key:"9nrev1"}],["polyline",{points:"3.27 6.96 12 12.01 20.73 6.96",key:"1180pa"}],["line",{x1:"12",x2:"12",y1:"22.08",y2:"12",key:"3z3uq6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ey=re("Coffee",[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M16 8a1 1 0 0 1 1 1v8a4 4 0 0 1-4 4H7a4 4 0 0 1-4-4V9a1 1 0 0 1 1-1h14a4 4 0 1 1 0 8h-1",key:"pwadti"}],["path",{d:"M6 2v2",key:"colzsn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BX=re("Cog",[["path",{d:"M12 20a8 8 0 1 0 0-16 8 8 0 0 0 0 16Z",key:"sobvz5"}],["path",{d:"M12 14a2 2 0 1 0 0-4 2 2 0 0 0 0 4Z",key:"11i496"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 22v-2",key:"1osdcq"}],["path",{d:"m17 20.66-1-1.73",key:"eq3orb"}],["path",{d:"M11 10.27 7 3.34",key:"16pf9h"}],["path",{d:"m20.66 17-1.73-1",key:"sg0v6f"}],["path",{d:"m3.34 7 1.73 1",key:"1ulond"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"m20.66 7-1.73 1",key:"1ow05n"}],["path",{d:"m3.34 17 1.73-1",key:"nuk764"}],["path",{d:"m17 3.34-1 1.73",key:"2wel8s"}],["path",{d:"m11 13.73-4 6.93",key:"794ttg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U7=re("Coins",[["circle",{cx:"8",cy:"8",r:"6",key:"3yglwk"}],["path",{d:"M18.09 10.37A6 6 0 1 1 10.34 18",key:"t5s6rm"}],["path",{d:"M7 6h1v4",key:"1obek4"}],["path",{d:"m16.71 13.88.7.71-2.82 2.82",key:"1rbuyh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v5=re("Columns2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 3v18",key:"108xh3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const b5=re("Columns3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $X=re("Columns4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7.5 3v18",key:"w0wo6v"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M16.5 3v18",key:"10tjh1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UX=re("Combine",[["path",{d:"M10 18H5a3 3 0 0 1-3-3v-1",key:"ru65g8"}],["path",{d:"M14 2a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"e30een"}],["path",{d:"M20 2a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"2ahx8o"}],["path",{d:"m7 21 3-3-3-3",key:"127cv2"}],["rect",{x:"14",y:"14",width:"8",height:"8",rx:"2",key:"1b0bso"}],["rect",{x:"2",y:"2",width:"8",height:"8",rx:"2",key:"1x09vl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qX=re("Command",[["path",{d:"M15 6v12a3 3 0 1 0 3-3H6a3 3 0 1 0 3 3V6a3 3 0 1 0-3 3h12a3 3 0 1 0-3-3",key:"11bfej"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YP=re("Compass",[["path",{d:"m16.24 7.76-1.804 5.411a2 2 0 0 1-1.265 1.265L7.76 16.24l1.804-5.411a2 2 0 0 1 1.265-1.265z",key:"9ktpf1"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VX=re("Component",[["path",{d:"M15.536 11.293a1 1 0 0 0 0 1.414l2.376 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1uwlt4"}],["path",{d:"M2.297 11.293a1 1 0 0 0 0 1.414l2.377 2.377a1 1 0 0 0 1.414 0l2.377-2.377a1 1 0 0 0 0-1.414L6.088 8.916a1 1 0 0 0-1.414 0z",key:"10291m"}],["path",{d:"M8.916 17.912a1 1 0 0 0 0 1.415l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.415l-2.377-2.376a1 1 0 0 0-1.414 0z",key:"1tqoq1"}],["path",{d:"M8.916 4.674a1 1 0 0 0 0 1.414l2.377 2.376a1 1 0 0 0 1.414 0l2.377-2.376a1 1 0 0 0 0-1.414l-2.377-2.377a1 1 0 0 0-1.414 0z",key:"1x6lto"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HX=re("Computer",[["rect",{width:"14",height:"8",x:"5",y:"2",rx:"2",key:"wc9tft"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h2",key:"rwmk9e"}],["path",{d:"M12 18h6",key:"aqd8w3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GX=re("ConciergeBell",[["path",{d:"M3 20a1 1 0 0 1-1-1v-1a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1a1 1 0 0 1-1 1Z",key:"1pvr1r"}],["path",{d:"M20 16a8 8 0 1 0-16 0",key:"1pa543"}],["path",{d:"M12 4v4",key:"1bq03y"}],["path",{d:"M10 4h4",key:"1xpv9s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WX=re("Cone",[["path",{d:"m20.9 18.55-8-15.98a1 1 0 0 0-1.8 0l-8 15.98",key:"53pte7"}],["ellipse",{cx:"12",cy:"19",rx:"9",ry:"3",key:"1ji25f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KX=re("Construction",[["rect",{x:"2",y:"6",width:"20",height:"8",rx:"1",key:"1estib"}],["path",{d:"M17 14v7",key:"7m2elx"}],["path",{d:"M7 14v7",key:"1cm7wv"}],["path",{d:"M17 3v3",key:"1v4jwn"}],["path",{d:"M7 3v3",key:"7o6guu"}],["path",{d:"M10 14 2.3 6.3",key:"1023jk"}],["path",{d:"m14 6 7.7 7.7",key:"1s8pl2"}],["path",{d:"m8 6 8 8",key:"hl96qh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _5=re("ContactRound",[["path",{d:"M16 2v2",key:"scm5qe"}],["path",{d:"M17.915 22a6 6 0 0 0-12 0",key:"suqz9p"}],["path",{d:"M8 2v2",key:"pbkmx"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bA=re("Contact",[["path",{d:"M16 2v2",key:"scm5qe"}],["path",{d:"M7 22v-2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2",key:"1waht3"}],["path",{d:"M8 2v2",key:"pbkmx"}],["circle",{cx:"12",cy:"11",r:"3",key:"itu57m"}],["rect",{x:"3",y:"4",width:"18",height:"18",rx:"2",key:"12vinp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YX=re("Container",[["path",{d:"M22 7.7c0-.6-.4-1.2-.8-1.5l-6.3-3.9a1.72 1.72 0 0 0-1.7 0l-10.3 6c-.5.2-.9.8-.9 1.4v6.6c0 .5.4 1.2.8 1.5l6.3 3.9a1.72 1.72 0 0 0 1.7 0l10.3-6c.5-.3.9-1 .9-1.5Z",key:"1t2lqe"}],["path",{d:"M10 21.9V14L2.1 9.1",key:"o7czzq"}],["path",{d:"m10 14 11.9-6.9",key:"zm5e20"}],["path",{d:"M14 19.8v-8.1",key:"159ecu"}],["path",{d:"M18 17.5V9.4",key:"11uown"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZX=re("Contrast",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 18a6 6 0 0 0 0-12v12z",key:"j4l70d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QX=re("Cookie",[["path",{d:"M12 2a10 10 0 1 0 10 10 4 4 0 0 1-5-5 4 4 0 0 1-5-5",key:"laymnq"}],["path",{d:"M8.5 8.5v.01",key:"ue8clq"}],["path",{d:"M16 15.5v.01",key:"14dtrp"}],["path",{d:"M12 12v.01",key:"u5ubse"}],["path",{d:"M11 17v.01",key:"1hyl5a"}],["path",{d:"M7 14v.01",key:"uct60s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XX=re("CookingPot",[["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M20 12v8a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-8",key:"u0tga0"}],["path",{d:"m4 8 16-4",key:"16g0ng"}],["path",{d:"m8.86 6.78-.45-1.81a2 2 0 0 1 1.45-2.43l1.94-.48a2 2 0 0 1 2.43 1.46l.45 1.8",key:"12cejc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JX=re("CopyCheck",[["path",{d:"m12 15 2 2 4-4",key:"2c609p"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eJ=re("CopyMinus",[["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tJ=re("CopyPlus",[["line",{x1:"15",x2:"15",y1:"12",y2:"18",key:"1p7wdc"}],["line",{x1:"12",x2:"18",y1:"15",y2:"15",key:"1nscbv"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sJ=re("CopySlash",[["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nJ=re("CopyX",[["line",{x1:"12",x2:"18",y1:"12",y2:"18",key:"1rg63v"}],["line",{x1:"12",x2:"18",y1:"18",y2:"12",key:"ebkxgr"}],["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zr=re("Copy",[["rect",{width:"14",height:"14",x:"8",y:"8",rx:"2",ry:"2",key:"17jyea"}],["path",{d:"M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2",key:"zix9uf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rJ=re("Copyleft",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M9.17 14.83a4 4 0 1 0 0-5.66",key:"1sveal"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aJ=re("Copyright",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M14.83 14.83a4 4 0 1 1 0-5.66",key:"1i56pz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iJ=re("CornerDownLeft",[["polyline",{points:"9 10 4 15 9 20",key:"r3jprv"}],["path",{d:"M20 4v7a4 4 0 0 1-4 4H4",key:"6o5b7l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oJ=re("CornerDownRight",[["polyline",{points:"15 10 20 15 15 20",key:"1q7qjw"}],["path",{d:"M4 4v7a4 4 0 0 0 4 4h12",key:"z08zvw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lJ=re("CornerLeftDown",[["polyline",{points:"14 15 9 20 4 15",key:"nkc4i"}],["path",{d:"M20 4h-7a4 4 0 0 0-4 4v12",key:"nbpdq2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cJ=re("CornerLeftUp",[["polyline",{points:"14 9 9 4 4 9",key:"m9oyvo"}],["path",{d:"M20 20h-7a4 4 0 0 1-4-4V4",key:"1blwi3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dJ=re("CornerRightDown",[["polyline",{points:"10 15 15 20 20 15",key:"axus6l"}],["path",{d:"M4 4h7a4 4 0 0 1 4 4v12",key:"wcbgct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uJ=re("CornerRightUp",[["polyline",{points:"10 9 15 4 20 9",key:"1lr6px"}],["path",{d:"M4 20h7a4 4 0 0 0 4-4V4",key:"1plgdj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hJ=re("CornerUpLeft",[["polyline",{points:"9 14 4 9 9 4",key:"881910"}],["path",{d:"M20 20v-7a4 4 0 0 0-4-4H4",key:"1nkjon"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mJ=re("CornerUpRight",[["polyline",{points:"15 14 20 9 15 4",key:"1tbx3s"}],["path",{d:"M4 20v-7a4 4 0 0 1 4-4h12",key:"1lu4f8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pJ=re("Cpu",[["rect",{width:"16",height:"16",x:"4",y:"4",rx:"2",key:"14l7u7"}],["rect",{width:"6",height:"6",x:"9",y:"9",rx:"1",key:"5aljv4"}],["path",{d:"M15 2v2",key:"13l42r"}],["path",{d:"M15 20v2",key:"15mkzm"}],["path",{d:"M2 15h2",key:"1gxd5l"}],["path",{d:"M2 9h2",key:"1bbxkp"}],["path",{d:"M20 15h2",key:"19e6y8"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M9 2v2",key:"165o2o"}],["path",{d:"M9 20v2",key:"i2bqo8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fJ=re("CreativeCommons",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M10 9.3a2.8 2.8 0 0 0-3.5 1 3.1 3.1 0 0 0 0 3.4 2.7 2.7 0 0 0 3.5 1",key:"1ss3eq"}],["path",{d:"M17 9.3a2.8 2.8 0 0 0-3.5 1 3.1 3.1 0 0 0 0 3.4 2.7 2.7 0 0 0 3.5 1",key:"1od56t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uf=re("CreditCard",[["rect",{width:"20",height:"14",x:"2",y:"5",rx:"2",key:"ynyp8z"}],["line",{x1:"2",x2:"22",y1:"10",y2:"10",key:"1b3vmo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xJ=re("Croissant",[["path",{d:"m4.6 13.11 5.79-3.21c1.89-1.05 4.79 1.78 3.71 3.71l-3.22 5.81C8.8 23.16.79 15.23 4.6 13.11Z",key:"1ozxlb"}],["path",{d:"m10.5 9.5-1-2.29C9.2 6.48 8.8 6 8 6H4.5C2.79 6 2 6.5 2 8.5a7.71 7.71 0 0 0 2 4.83",key:"ffuyb5"}],["path",{d:"M8 6c0-1.55.24-4-2-4-2 0-2.5 2.17-2.5 4",key:"osnpzi"}],["path",{d:"m14.5 13.5 2.29 1c.73.3 1.21.7 1.21 1.5v3.5c0 1.71-.5 2.5-2.5 2.5a7.71 7.71 0 0 1-4.83-2",key:"1vubaw"}],["path",{d:"M18 16c1.55 0 4-.24 4 2 0 2-2.17 2.5-4 2.5",key:"wxr772"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gJ=re("Crop",[["path",{d:"M6 2v14a2 2 0 0 0 2 2h14",key:"ron5a4"}],["path",{d:"M18 22V8a2 2 0 0 0-2-2H2",key:"7s9ehn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yJ=re("Cross",[["path",{d:"M4 9a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h4a1 1 0 0 1 1 1v4a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-4a1 1 0 0 1 1-1h4a2 2 0 0 0 2-2v-2a2 2 0 0 0-2-2h-4a1 1 0 0 1-1-1V4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4a1 1 0 0 1-1 1z",key:"1xbrqy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vJ=re("Crosshair",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"22",x2:"18",y1:"12",y2:"12",key:"l9bcsi"}],["line",{x1:"6",x2:"2",y1:"12",y2:"12",key:"13hhkx"}],["line",{x1:"12",x2:"12",y1:"6",y2:"2",key:"10w3f3"}],["line",{x1:"12",x2:"12",y1:"22",y2:"18",key:"15g9kq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hf=re("Crown",[["path",{d:"M11.562 3.266a.5.5 0 0 1 .876 0L15.39 8.87a1 1 0 0 0 1.516.294L21.183 5.5a.5.5 0 0 1 .798.519l-2.834 10.246a1 1 0 0 1-.956.734H5.81a1 1 0 0 1-.957-.734L2.02 6.02a.5.5 0 0 1 .798-.519l4.276 3.664a1 1 0 0 0 1.516-.294z",key:"1vdc57"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bJ=re("Cuboid",[["path",{d:"m21.12 6.4-6.05-4.06a2 2 0 0 0-2.17-.05L2.95 8.41a2 2 0 0 0-.95 1.7v5.82a2 2 0 0 0 .88 1.66l6.05 4.07a2 2 0 0 0 2.17.05l9.95-6.12a2 2 0 0 0 .95-1.7V8.06a2 2 0 0 0-.88-1.66Z",key:"1u2ovd"}],["path",{d:"M10 22v-8L2.25 9.15",key:"11pn4q"}],["path",{d:"m10 14 11.77-6.87",key:"1kt1wh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _J=re("CupSoda",[["path",{d:"m6 8 1.75 12.28a2 2 0 0 0 2 1.72h4.54a2 2 0 0 0 2-1.72L18 8",key:"8166m8"}],["path",{d:"M5 8h14",key:"pcz4l3"}],["path",{d:"M7 15a6.47 6.47 0 0 1 5 0 6.47 6.47 0 0 0 5 0",key:"yjz344"}],["path",{d:"m12 8 1-6h2",key:"3ybfa4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wJ=re("Currency",[["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}],["line",{x1:"3",x2:"6",y1:"3",y2:"6",key:"1jkytn"}],["line",{x1:"21",x2:"18",y1:"3",y2:"6",key:"14zfjt"}],["line",{x1:"3",x2:"6",y1:"21",y2:"18",key:"iusuec"}],["line",{x1:"21",x2:"18",y1:"21",y2:"18",key:"yj2dd7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jJ=re("Cylinder",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5v14a9 3 0 0 0 18 0V5",key:"aqi0yr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NJ=re("Dam",[["path",{d:"M11 11.31c1.17.56 1.54 1.69 3.5 1.69 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"157kva"}],["path",{d:"M11.75 18c.35.5 1.45 1 2.75 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"d7q6m6"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M7 3a1 1 0 0 0-1 1v16a1 1 0 0 0 1 1h4a1 1 0 0 0 1-1L10 4a1 1 0 0 0-1-1z",key:"pr6s65"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kJ=re("DatabaseBackup",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 12a9 3 0 0 0 5 2.69",key:"1ui2ym"}],["path",{d:"M21 9.3V5",key:"6k6cib"}],["path",{d:"M3 5v14a9 3 0 0 0 6.47 2.88",key:"i62tjy"}],["path",{d:"M12 12v4h4",key:"1bxaet"}],["path",{d:"M13 20a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L12 16",key:"1f4ei9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SJ=re("DatabaseZap",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 15 21.84",key:"14ibmq"}],["path",{d:"M21 5V8",key:"1marbg"}],["path",{d:"M21 12L18 17H22L19 22",key:"zafso"}],["path",{d:"M3 12A9 3 0 0 0 14.59 14.87",key:"1y4wr8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q7=re("Database",[["ellipse",{cx:"12",cy:"5",rx:"9",ry:"3",key:"msslwz"}],["path",{d:"M3 5V19A9 3 0 0 0 21 19V5",key:"1wlel7"}],["path",{d:"M3 12A9 3 0 0 0 21 12",key:"mv7ke4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CJ=re("Delete",[["path",{d:"M10 5a2 2 0 0 0-1.344.519l-6.328 5.74a1 1 0 0 0 0 1.481l6.328 5.741A2 2 0 0 0 10 19h10a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2z",key:"1yo7s0"}],["path",{d:"m12 9 6 6",key:"anjzzh"}],["path",{d:"m18 9-6 6",key:"1fp51s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TJ=re("Dessert",[["circle",{cx:"12",cy:"4",r:"2",key:"muu5ef"}],["path",{d:"M10.2 3.2C5.5 4 2 8.1 2 13a2 2 0 0 0 4 0v-1a2 2 0 0 1 4 0v4a2 2 0 0 0 4 0v-4a2 2 0 0 1 4 0v1a2 2 0 0 0 4 0c0-4.9-3.5-9-8.2-9.8",key:"lfo06j"}],["path",{d:"M3.2 14.8a9 9 0 0 0 17.6 0",key:"12xarc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EJ=re("Diameter",[["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["circle",{cx:"5",cy:"5",r:"2",key:"1gwv83"}],["path",{d:"M6.48 3.66a10 10 0 0 1 13.86 13.86",key:"xr8kdq"}],["path",{d:"m6.41 6.41 11.18 11.18",key:"uhpjw7"}],["path",{d:"M3.66 6.48a10 10 0 0 0 13.86 13.86",key:"cldpwv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AJ=re("DiamondMinus",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0z",key:"1ey20j"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w5=re("DiamondPercent",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0Z",key:"1tpxz2"}],["path",{d:"M9.2 9.2h.01",key:"1b7bvt"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"M14.7 14.8h.01",key:"17nsh4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MJ=re("DiamondPlus",[["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41L13.7 2.71a2.41 2.41 0 0 0-3.41 0z",key:"1ey20j"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IJ=re("Diamond",[["path",{d:"M2.7 10.3a2.41 2.41 0 0 0 0 3.41l7.59 7.59a2.41 2.41 0 0 0 3.41 0l7.59-7.59a2.41 2.41 0 0 0 0-3.41l-7.59-7.59a2.41 2.41 0 0 0-3.41 0Z",key:"1f1r0c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PJ=re("Dice1",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LJ=re("Dice2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M9 15h.01",key:"fzyn71"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DJ=re("Dice3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RJ=re("Dice4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 16h.01",key:"18s6g9"}],["path",{d:"M16 16h.01",key:"1f9h7w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OJ=re("Dice5",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 16h.01",key:"18s6g9"}],["path",{d:"M16 16h.01",key:"1f9h7w"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FJ=re("Dice6",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M16 8h.01",key:"cr5u4v"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M16 16h.01",key:"1f9h7w"}],["path",{d:"M8 8h.01",key:"1e4136"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M8 16h.01",key:"18s6g9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zJ=re("Dices",[["rect",{width:"12",height:"12",x:"2",y:"10",rx:"2",ry:"2",key:"6agr2n"}],["path",{d:"m17.92 14 3.5-3.5a2.24 2.24 0 0 0 0-3l-5-4.92a2.24 2.24 0 0 0-3 0L10 6",key:"1o487t"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 14h.01",key:"ssrbsk"}],["path",{d:"M15 6h.01",key:"cblpky"}],["path",{d:"M18 9h.01",key:"2061c0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BJ=re("Diff",[["path",{d:"M12 3v14",key:"7cf3v8"}],["path",{d:"M5 10h14",key:"elsbfy"}],["path",{d:"M5 21h14",key:"11awu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $J=re("Disc2",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UJ=re("Disc3",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M6 12c0-1.7.7-3.2 1.8-4.2",key:"oqkarx"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M18 12c0 1.7-.7 3.2-1.8 4.2",key:"1eah9h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qJ=re("DiscAlbum",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"12",r:"5",key:"nd82uf"}],["path",{d:"M12 12h.01",key:"1mp3jc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VJ=re("Disc",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HJ=re("Divide",[["circle",{cx:"12",cy:"6",r:"1",key:"1bh7o1"}],["line",{x1:"5",x2:"19",y1:"12",y2:"12",key:"13b5wn"}],["circle",{cx:"12",cy:"18",r:"1",key:"lqb9t5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GJ=re("DnaOff",[["path",{d:"M15 2c-1.35 1.5-2.092 3-2.5 4.5L14 8",key:"1bivrr"}],["path",{d:"m17 6-2.891-2.891",key:"xu6p2f"}],["path",{d:"M2 15c3.333-3 6.667-3 10-3",key:"nxix30"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"m20 9 .891.891",key:"3xwk7g"}],["path",{d:"M22 9c-1.5 1.35-3 2.092-4.5 2.5l-1-1",key:"18cutr"}],["path",{d:"M3.109 14.109 4 15",key:"q76aoh"}],["path",{d:"m6.5 12.5 1 1",key:"cs35ky"}],["path",{d:"m7 18 2.891 2.891",key:"1sisit"}],["path",{d:"M9 22c1.35-1.5 2.092-3 2.5-4.5L10 16",key:"rlvei3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WJ=re("Dna",[["path",{d:"m10 16 1.5 1.5",key:"11lckj"}],["path",{d:"m14 8-1.5-1.5",key:"1ohn8i"}],["path",{d:"M15 2c-1.798 1.998-2.518 3.995-2.807 5.993",key:"80uv8i"}],["path",{d:"m16.5 10.5 1 1",key:"696xn5"}],["path",{d:"m17 6-2.891-2.891",key:"xu6p2f"}],["path",{d:"M2 15c6.667-6 13.333 0 20-6",key:"1pyr53"}],["path",{d:"m20 9 .891.891",key:"3xwk7g"}],["path",{d:"M3.109 14.109 4 15",key:"q76aoh"}],["path",{d:"m6.5 12.5 1 1",key:"cs35ky"}],["path",{d:"m7 18 2.891 2.891",key:"1sisit"}],["path",{d:"M9 22c1.798-1.998 2.518-3.995 2.807-5.993",key:"q3hbxp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KJ=re("Dock",[["path",{d:"M2 8h20",key:"d11cs7"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 16h12",key:"u522kt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YJ=re("Dog",[["path",{d:"M11.25 16.25h1.5L12 17z",key:"w7jh35"}],["path",{d:"M16 14v.5",key:"1lajdz"}],["path",{d:"M4.42 11.247A13.152 13.152 0 0 0 4 14.556C4 18.728 7.582 21 12 21s8-2.272 8-6.444a11.702 11.702 0 0 0-.493-3.309",key:"u7s9ue"}],["path",{d:"M8 14v.5",key:"1nzgdb"}],["path",{d:"M8.5 8.5c-.384 1.05-1.083 2.028-2.344 2.5-1.931.722-3.576-.297-3.656-1-.113-.994 1.177-6.53 4-7 1.923-.321 3.651.845 3.651 2.235A7.497 7.497 0 0 1 14 5.277c0-1.39 1.844-2.598 3.767-2.277 2.823.47 4.113 6.006 4 7-.08.703-1.725 1.722-3.656 1-1.261-.472-1.855-1.45-2.239-2.5",key:"v8hric"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yl=re("DollarSign",[["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"M17 5H9.5a3.5 3.5 0 0 0 0 7h5a3.5 3.5 0 0 1 0 7H6",key:"1b0p4s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZJ=re("Donut",[["path",{d:"M20.5 10a2.5 2.5 0 0 1-2.4-3H18a2.95 2.95 0 0 1-2.6-4.4 10 10 0 1 0 6.3 7.1c-.3.2-.8.3-1.2.3",key:"19sr3x"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QJ=re("DoorClosed",[["path",{d:"M18 20V6a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v14",key:"36qu9e"}],["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"M14 12v.01",key:"xfcn54"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hw=re("DoorOpen",[["path",{d:"M13 4h3a2 2 0 0 1 2 2v14",key:"hrm0s9"}],["path",{d:"M2 20h3",key:"1gaodv"}],["path",{d:"M13 20h9",key:"s90cdi"}],["path",{d:"M10 12v.01",key:"vx6srw"}],["path",{d:"M13 4.562v16.157a1 1 0 0 1-1.242.97L5 20V5.562a2 2 0 0 1 1.515-1.94l4-1A2 2 0 0 1 13 4.561Z",key:"199qr4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XJ=re("Dot",[["circle",{cx:"12.1",cy:"12.1",r:"1",key:"18d7e5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ia=re("Download",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"7 10 12 15 17 10",key:"2ggqvy"}],["line",{x1:"12",x2:"12",y1:"15",y2:"3",key:"1vk2je"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JJ=re("DraftingCompass",[["path",{d:"m12.99 6.74 1.93 3.44",key:"iwagvd"}],["path",{d:"M19.136 12a10 10 0 0 1-14.271 0",key:"ppmlo4"}],["path",{d:"m21 21-2.16-3.84",key:"vylbct"}],["path",{d:"m3 21 8.02-14.26",key:"1ssaw4"}],["circle",{cx:"12",cy:"5",r:"2",key:"f1ur92"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eee=re("Drama",[["path",{d:"M10 11h.01",key:"d2at3l"}],["path",{d:"M14 6h.01",key:"k028ub"}],["path",{d:"M18 6h.01",key:"1v4wsw"}],["path",{d:"M6.5 13.1h.01",key:"1748ia"}],["path",{d:"M22 5c0 9-4 12-6 12s-6-3-6-12c0-2 2-3 6-3s6 1 6 3",key:"172yzv"}],["path",{d:"M17.4 9.9c-.8.8-2 .8-2.8 0",key:"1obv0w"}],["path",{d:"M10.1 7.1C9 7.2 7.7 7.7 6 8.6c-3.5 2-4.7 3.9-3.7 5.6 4.5 7.8 9.5 8.4 11.2 7.4.9-.5 1.9-2.1 1.9-4.7",key:"rqjl8i"}],["path",{d:"M9.1 16.5c.3-1.1 1.4-1.7 2.4-1.4",key:"1mr6wy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tee=re("Dribbble",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M19.13 5.09C15.22 9.14 10 10.44 2.25 10.94",key:"hpej1"}],["path",{d:"M21.75 12.84c-6.62-1.41-12.14 1-16.38 6.32",key:"1tr44o"}],["path",{d:"M8.56 2.75c4.37 6 6 9.42 8 17.72",key:"kbh691"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const see=re("Drill",[["path",{d:"M10 18a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1H5a3 3 0 0 1-3-3 1 1 0 0 1 1-1z",key:"ioqxb1"}],["path",{d:"M13 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9a1 1 0 0 1 1 1v6a1 1 0 0 1-1 1l-.81 3.242a1 1 0 0 1-.97.758H8",key:"1rs59n"}],["path",{d:"M14 4h3a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-3",key:"105ega"}],["path",{d:"M18 6h4",key:"66u95g"}],["path",{d:"m5 10-2 8",key:"xt2lic"}],["path",{d:"m7 18 2-8",key:"1bzku2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nee=re("Droplet",[["path",{d:"M12 22a7 7 0 0 0 7-7c0-2-1-3.9-3-5.5s-3.5-4-4-6.5c-.5 2.5-2 4.9-4 6.5C6 11.1 5 13 5 15a7 7 0 0 0 7 7z",key:"c7niix"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const db=re("Droplets",[["path",{d:"M7 16.3c2.2 0 4-1.83 4-4.05 0-1.16-.57-2.26-1.71-3.19S7.29 6.75 7 5.3c-.29 1.45-1.14 2.84-2.29 3.76S3 11.1 3 12.25c0 2.22 1.8 4.05 4 4.05z",key:"1ptgy4"}],["path",{d:"M12.56 6.6A10.97 10.97 0 0 0 14 3.02c.5 2.5 2 4.9 4 6.5s3 3.5 3 5.5a6.98 6.98 0 0 1-11.91 4.97",key:"1sl1rz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ree=re("Drum",[["path",{d:"m2 2 8 8",key:"1v6059"}],["path",{d:"m22 2-8 8",key:"173r8a"}],["ellipse",{cx:"12",cy:"9",rx:"10",ry:"5",key:"liohsx"}],["path",{d:"M7 13.4v7.9",key:"1yi6u9"}],["path",{d:"M12 14v8",key:"1tn2tj"}],["path",{d:"M17 13.4v7.9",key:"eqz2v3"}],["path",{d:"M2 9v8a10 5 0 0 0 20 0V9",key:"1750ul"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aee=re("Drumstick",[["path",{d:"M15.4 15.63a7.875 6 135 1 1 6.23-6.23 4.5 3.43 135 0 0-6.23 6.23",key:"1dtqwm"}],["path",{d:"m8.29 12.71-2.6 2.6a2.5 2.5 0 1 0-1.65 4.65A2.5 2.5 0 1 0 8.7 18.3l2.59-2.59",key:"1oq1fw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iee=re("Dumbbell",[["path",{d:"M14.4 14.4 9.6 9.6",key:"ic80wn"}],["path",{d:"M18.657 21.485a2 2 0 1 1-2.829-2.828l-1.767 1.768a2 2 0 1 1-2.829-2.829l6.364-6.364a2 2 0 1 1 2.829 2.829l-1.768 1.767a2 2 0 1 1 2.828 2.829z",key:"nnl7wr"}],["path",{d:"m21.5 21.5-1.4-1.4",key:"1f1ice"}],["path",{d:"M3.9 3.9 2.5 2.5",key:"1evmna"}],["path",{d:"M6.404 12.768a2 2 0 1 1-2.829-2.829l1.768-1.767a2 2 0 1 1-2.828-2.829l2.828-2.828a2 2 0 1 1 2.829 2.828l1.767-1.768a2 2 0 1 1 2.829 2.829z",key:"yhosts"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oee=re("EarOff",[["path",{d:"M6 18.5a3.5 3.5 0 1 0 7 0c0-1.57.92-2.52 2.04-3.46",key:"1qngmn"}],["path",{d:"M6 8.5c0-.75.13-1.47.36-2.14",key:"b06bma"}],["path",{d:"M8.8 3.15A6.5 6.5 0 0 1 19 8.5c0 1.63-.44 2.81-1.09 3.76",key:"g10hsz"}],["path",{d:"M12.5 6A2.5 2.5 0 0 1 15 8.5M10 13a2 2 0 0 0 1.82-1.18",key:"ygzou7"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lee=re("Ear",[["path",{d:"M6 8.5a6.5 6.5 0 1 1 13 0c0 6-6 6-6 10a3.5 3.5 0 1 1-7 0",key:"1dfaln"}],["path",{d:"M15 8.5a2.5 2.5 0 0 0-5 0v1a2 2 0 1 1 0 4",key:"1qnva7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cee=re("EarthLock",[["path",{d:"M7 3.34V5a3 3 0 0 0 3 3",key:"w732o8"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2 2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"f02343"}],["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M12 2a10 10 0 1 0 9.54 13",key:"zjsr6q"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const j5=re("Earth",[["path",{d:"M21.54 15H17a2 2 0 0 0-2 2v4.54",key:"1djwo0"}],["path",{d:"M7 3.34V5a3 3 0 0 0 3 3a2 2 0 0 1 2 2c0 1.1.9 2 2 2a2 2 0 0 0 2-2c0-1.1.9-2 2-2h3.17",key:"1tzkfa"}],["path",{d:"M11 21.95V18a2 2 0 0 0-2-2a2 2 0 0 1-2-2v-1a2 2 0 0 0-2-2H2.05",key:"14pb5j"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dee=re("Eclipse",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a7 7 0 1 0 10 10",key:"1yuj32"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uee=re("EggFried",[["circle",{cx:"11.5",cy:"12.5",r:"3.5",key:"1cl1mi"}],["path",{d:"M3 8c0-3.5 2.5-6 6.5-6 5 0 4.83 3 7.5 5s5 2 5 6c0 4.5-2.5 6.5-7 6.5-2.5 0-2.5 2.5-6 2.5s-7-2-7-5.5c0-3 1.5-3 1.5-5C3.5 10 3 9 3 8Z",key:"165ef9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hee=re("EggOff",[["path",{d:"M6.399 6.399C5.362 8.157 4.65 10.189 4.5 12c-.37 4.43 1.27 9.95 7.5 10 3.256-.026 5.259-1.547 6.375-3.625",key:"6et380"}],["path",{d:"M19.532 13.875A14.07 14.07 0 0 0 19.5 12c-.36-4.34-3.95-9.96-7.5-10-1.04.012-2.082.502-3.046 1.297",key:"gcdc3f"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZP=re("Egg",[["path",{d:"M12 22c6.23-.05 7.87-5.57 7.5-10-.36-4.34-3.95-9.96-7.5-10-3.55.04-7.14 5.66-7.5 10-.37 4.43 1.27 9.95 7.5 10z",key:"1c39pg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ag=re("EllipsisVertical",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kf=re("Ellipsis",[["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mee=re("EqualApproximately",[["path",{d:"M5 15a6.5 6.5 0 0 1 7 0 6.5 6.5 0 0 0 7 0",key:"yrdkhy"}],["path",{d:"M5 9a6.5 6.5 0 0 1 7 0 6.5 6.5 0 0 0 7 0",key:"gzkvyz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pee=re("EqualNot",[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}],["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fee=re("Equal",[["line",{x1:"5",x2:"19",y1:"9",y2:"9",key:"1nwqeh"}],["line",{x1:"5",x2:"19",y1:"15",y2:"15",key:"g8yjpy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xee=re("Eraser",[["path",{d:"m7 21-4.3-4.3c-1-1-1-2.5 0-3.4l9.6-9.6c1-1 2.5-1 3.4 0l5.6 5.6c1 1 1 2.5 0 3.4L13 21",key:"182aya"}],["path",{d:"M22 21H7",key:"t4ddhn"}],["path",{d:"m5 11 9 9",key:"1mo9qw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gee=re("EthernetPort",[["path",{d:"m15 20 3-3h2a2 2 0 0 0 2-2V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2h2l3 3z",key:"rbahqx"}],["path",{d:"M6 8v1",key:"1636ez"}],["path",{d:"M10 8v1",key:"1talb4"}],["path",{d:"M14 8v1",key:"1rsfgr"}],["path",{d:"M18 8v1",key:"gnkwox"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yee=re("Euro",[["path",{d:"M4 10h12",key:"1y6xl8"}],["path",{d:"M4 14h9",key:"1loblj"}],["path",{d:"M19 6a7.7 7.7 0 0 0-5.2-2A7.9 7.9 0 0 0 6 12c0 4.4 3.5 8 7.8 8 2 0 3.8-.8 5.2-2",key:"1j6lzo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vee=re("Expand",[["path",{d:"m21 21-6-6m6 6v-4.8m0 4.8h-4.8",key:"1c15vz"}],["path",{d:"M3 16.2V21m0 0h4.8M3 21l6-6",key:"1fsnz2"}],["path",{d:"M21 7.8V3m0 0h-4.8M21 3l-6 6",key:"hawz9i"}],["path",{d:"M3 7.8V3m0 0h4.8M3 3l6 6",key:"u9ee12"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tr=re("ExternalLink",[["path",{d:"M15 3h6v6",key:"1q9fwt"}],["path",{d:"M10 14 21 3",key:"gplh6r"}],["path",{d:"M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6",key:"a6xqqp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bee=re("EyeClosed",[["path",{d:"m15 18-.722-3.25",key:"1j64jw"}],["path",{d:"M2 8a10.645 10.645 0 0 0 20 0",key:"1e7gxb"}],["path",{d:"m20 15-1.726-2.05",key:"1cnuld"}],["path",{d:"m4 15 1.726-2.05",key:"1dsqqd"}],["path",{d:"m9 18 .722-3.25",key:"ypw2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mf=re("EyeOff",[["path",{d:"M10.733 5.076a10.744 10.744 0 0 1 11.205 6.575 1 1 0 0 1 0 .696 10.747 10.747 0 0 1-1.444 2.49",key:"ct8e1f"}],["path",{d:"M14.084 14.158a3 3 0 0 1-4.242-4.242",key:"151rxh"}],["path",{d:"M17.479 17.499a10.75 10.75 0 0 1-15.417-5.151 1 1 0 0 1 0-.696 10.75 10.75 0 0 1 4.446-5.143",key:"13bj9a"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sr=re("Eye",[["path",{d:"M2.062 12.348a1 1 0 0 1 0-.696 10.75 10.75 0 0 1 19.876 0 1 1 0 0 1 0 .696 10.75 10.75 0 0 1-19.876 0",key:"1nclc0"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mh=re("Facebook",[["path",{d:"M18 2h-3a5 5 0 0 0-5 5v3H7v4h3v8h4v-8h3l1-4h-4V7a1 1 0 0 1 1-1h3z",key:"1jg4f8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ee=re("Factory",[["path",{d:"M2 20a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V8l-7 5V8l-7 5V4a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"159hny"}],["path",{d:"M17 18h1",key:"uldtlt"}],["path",{d:"M12 18h1",key:"s9uhes"}],["path",{d:"M7 18h1",key:"1neino"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wee=re("Fan",[["path",{d:"M10.827 16.379a6.082 6.082 0 0 1-8.618-7.002l5.412 1.45a6.082 6.082 0 0 1 7.002-8.618l-1.45 5.412a6.082 6.082 0 0 1 8.618 7.002l-5.412-1.45a6.082 6.082 0 0 1-7.002 8.618l1.45-5.412Z",key:"484a7f"}],["path",{d:"M12 12v.01",key:"u5ubse"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jee=re("FastForward",[["polygon",{points:"13 19 22 12 13 5 13 19",key:"587y9g"}],["polygon",{points:"2 19 11 12 2 5 2 19",key:"3pweh0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nee=re("Feather",[["path",{d:"M12.67 19a2 2 0 0 0 1.416-.588l6.154-6.172a6 6 0 0 0-8.49-8.49L5.586 9.914A2 2 0 0 0 5 11.328V18a1 1 0 0 0 1 1z",key:"18jl4k"}],["path",{d:"M16 8 2 22",key:"vp34q"}],["path",{d:"M17.5 15H9",key:"1oz8nu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kee=re("Fence",[["path",{d:"M4 3 2 5v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"1n2rgs"}],["path",{d:"M6 8h4",key:"utf9t1"}],["path",{d:"M6 18h4",key:"12yh4b"}],["path",{d:"m12 3-2 2v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"3ha7mj"}],["path",{d:"M14 8h4",key:"1r8wg2"}],["path",{d:"M14 18h4",key:"1t3kbu"}],["path",{d:"m20 3-2 2v15c0 .6.4 1 1 1h2c.6 0 1-.4 1-1V5Z",key:"dfd4e2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const See=re("FerrisWheel",[["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m6.8 15-3.5 2",key:"hjy98k"}],["path",{d:"m20.7 7-3.5 2",key:"f08gto"}],["path",{d:"M6.8 9 3.3 7",key:"1aevh4"}],["path",{d:"m20.7 17-3.5-2",key:"1liqo3"}],["path",{d:"m9 22 3-8 3 8",key:"wees03"}],["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M18 18.7a9 9 0 1 0-12 0",key:"dhzg4g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cee=re("Figma",[["path",{d:"M5 5.5A3.5 3.5 0 0 1 8.5 2H12v7H8.5A3.5 3.5 0 0 1 5 5.5z",key:"1340ok"}],["path",{d:"M12 2h3.5a3.5 3.5 0 1 1 0 7H12V2z",key:"1hz3m3"}],["path",{d:"M12 12.5a3.5 3.5 0 1 1 7 0 3.5 3.5 0 1 1-7 0z",key:"1oz8n2"}],["path",{d:"M5 19.5A3.5 3.5 0 0 1 8.5 16H12v3.5a3.5 3.5 0 1 1-7 0z",key:"1ff65i"}],["path",{d:"M5 12.5A3.5 3.5 0 0 1 8.5 9H12v7H8.5A3.5 3.5 0 0 1 5 12.5z",key:"pdip6e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tee=re("FileArchive",[["path",{d:"M10 12v-1",key:"v7bkov"}],["path",{d:"M10 18v-2",key:"1cjy8d"}],["path",{d:"M10 7V6",key:"dljcrl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 .274 1.01",key:"gkbcor"}],["circle",{cx:"10",cy:"20",r:"2",key:"1xzdoj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eee=re("FileAudio2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2",key:"17k7jt"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"3",cy:"17",r:"1",key:"vo6nti"}],["path",{d:"M2 17v-3a4 4 0 0 1 8 0v3",key:"1ggdre"}],["circle",{cx:"9",cy:"17",r:"1",key:"bc1fq4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aee=re("FileAudio",[["path",{d:"M17.5 22h.5a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"rslqgf"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 19a2 2 0 1 1 4 0v1a2 2 0 1 1-4 0v-4a6 6 0 0 1 12 0v4a2 2 0 1 1-4 0v-1a2 2 0 1 1 4 0",key:"9f7x3i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const N5=re("FileAxis3d",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 18 4-4",key:"12zab0"}],["path",{d:"M8 10v8h8",key:"tlaukw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mee=re("FileBadge2",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m14 12.5 1 5.5-3-1-3 1 1-5.5",key:"14xlky"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iee=re("FileBadge",[["path",{d:"M12 22h6a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"12ixgl"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M5 17a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",key:"u0c8gj"}],["path",{d:"M7 16.5 8 22l-3-1-3 1 1-5.5",key:"5gm2nr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pee=re("FileBox",[["path",{d:"M14.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"16lz6z"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 13.1a2 2 0 0 0-1 1.76v3.24a2 2 0 0 0 .97 1.78L6 21.7a2 2 0 0 0 2.03.01L11 19.9a2 2 0 0 0 1-1.76V14.9a2 2 0 0 0-.97-1.78L8 11.3a2 2 0 0 0-2.03-.01Z",key:"99pj1s"}],["path",{d:"M7 17v5",key:"1yj1jh"}],["path",{d:"M11.7 14.2 7 17l-4.7-2.8",key:"1yk8tc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k5=re("FileChartColumnIncreasing",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 18v-2",key:"qcmpov"}],["path",{d:"M12 18v-4",key:"q1q25u"}],["path",{d:"M16 18v-6",key:"15y0np"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S5=re("FileChartColumn",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 18v-1",key:"zg0ygc"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"M16 18v-3",key:"j5jt4h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C5=re("FileChartLine",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m16 13-3.5 3.5-2-2L8 17",key:"zz7yod"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T5=re("FileChartPie",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3.5",key:"13ddob"}],["path",{d:"M4.017 11.512a6 6 0 1 0 8.466 8.475",key:"s6vs5t"}],["path",{d:"M9 16a1 1 0 0 1-1-1v-4c0-.552.45-1.008.995-.917a6 6 0 0 1 4.922 4.922c.091.544-.365.995-.917.995z",key:"1dl6s6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lee=re("FileCheck2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3 15 2 2 4-4",key:"1lhrkk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V7=re("FileCheck",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m9 15 2 2 4-4",key:"1grp1n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dee=re("FileClock",[["path",{d:"M16 22h2a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"37hlfg"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"8",cy:"16",r:"6",key:"10v15b"}],["path",{d:"M9.5 17.5 8 16.25V14",key:"1o80t2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ree=re("FileCode2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m5 12-3 3 3 3",key:"oke12k"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oee=re("FileCode",[["path",{d:"M10 12.5 8 15l2 2.5",key:"1tg20x"}],["path",{d:"m14 12.5 2 2.5-2 2.5",key:"yinavb"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E5=re("FileCog",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m3.2 12.9-.9-.4",key:"1i3dj5"}],["path",{d:"m3.2 15.1-.9.4",key:"1fvgj0"}],["path",{d:"M4.677 21.5a2 2 0 0 0 1.313.5H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2.5",key:"1yo3oz"}],["path",{d:"m4.9 11.2-.4-.9",key:"otmhb9"}],["path",{d:"m4.9 16.8-.4.9",key:"1b8z07"}],["path",{d:"m7.5 10.3-.4.9",key:"11k65u"}],["path",{d:"m7.5 17.7-.4-.9",key:"431x55"}],["path",{d:"m9.7 12.5-.9.4",key:"87sjan"}],["path",{d:"m9.7 15.5-.9-.4",key:"khqm91"}],["circle",{cx:"6",cy:"14",r:"3",key:"a1xfv6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fee=re("FileDiff",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"M9 17h6",key:"r8uit2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zee=re("FileDigit",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"4",height:"6",x:"2",y:"12",rx:"2",key:"jm304g"}],["path",{d:"M10 12h2v6",key:"12zw74"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _A=re("FileDown",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 18v-6",key:"17g6i2"}],["path",{d:"m9 15 3 3 3-3",key:"1npd3o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bee=re("FileHeart",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v2",key:"17k7jt"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10.29 10.7a2.43 2.43 0 0 0-2.66-.52c-.29.12-.56.3-.78.53l-.35.34-.35-.34a2.43 2.43 0 0 0-2.65-.53c-.3.12-.56.3-.79.53-.95.94-1 2.53.2 3.74L6.5 18l3.6-3.55c1.2-1.21 1.14-2.8.19-3.74Z",key:"1c1fso"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q2=re("FileImage",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"10",cy:"12",r:"2",key:"737tya"}],["path",{d:"m20 17-1.296-1.296a2.41 2.41 0 0 0-3.408 0L9 22",key:"wt3hpn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ee=re("FileInput",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 15h10",key:"jfw4w8"}],["path",{d:"m9 18 3-3-3-3",key:"112psh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uee=re("FileJson2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"fq0c9t"}],["path",{d:"M8 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"4gibmv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qee=re("FileJson",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 12a1 1 0 0 0-1 1v1a1 1 0 0 1-1 1 1 1 0 0 1 1 1v1a1 1 0 0 0 1 1",key:"1oajmo"}],["path",{d:"M14 18a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1 1 1 0 0 1-1-1v-1a1 1 0 0 0-1-1",key:"mpwhp6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vee=re("FileKey2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v6",key:"rc0qvx"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"4",cy:"16",r:"2",key:"1ehqvc"}],["path",{d:"m10 10-4.5 4.5",key:"7fwrp6"}],["path",{d:"m9 11 1 1",key:"wa6s5q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hee=re("FileKey",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["circle",{cx:"10",cy:"16",r:"2",key:"4ckbqe"}],["path",{d:"m16 10-4.5 4.5",key:"7p3ebg"}],["path",{d:"m15 11 1 1",key:"1bsyx3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gee=re("FileLock2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v1",key:"jmtmu2"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"8",height:"5",x:"2",y:"13",rx:"1",key:"10y5wo"}],["path",{d:"M8 13v-2a2 2 0 1 0-4 0v2",key:"1pdxzg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wee=re("FileLock",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["rect",{width:"8",height:"6",x:"8",y:"12",rx:"1",key:"3yr8at"}],["path",{d:"M10 12v-2a2 2 0 1 1 4 0v2",key:"j4i8d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kee=re("FileMinus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yee=re("FileMinus",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 15h6",key:"cctwl0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zee=re("FileMusic",[["path",{d:"M10.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v8.4",key:"1d3kfm"}],["path",{d:"M8 18v-7.7L16 9v7",key:"1oie6o"}],["circle",{cx:"14",cy:"16",r:"2",key:"1bzzi3"}],["circle",{cx:"6",cy:"18",r:"2",key:"1fncim"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qee=re("FileOutput",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 7V4a2 2 0 0 1 2-2 2 2 0 0 0-2 2",key:"1vk7w2"}],["path",{d:"M4.063 20.999a2 2 0 0 0 2 1L18 22a2 2 0 0 0 2-2V7l-5-5H6",key:"1jink5"}],["path",{d:"m5 11-3 3",key:"1dgrs4"}],["path",{d:"m5 17-3-3h10",key:"1mvvaf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A5=re("FilePenLine",[["path",{d:"m18 5-2.414-2.414A2 2 0 0 0 14.172 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2",key:"142zxg"}],["path",{d:"M21.378 12.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"2t3380"}],["path",{d:"M8 18h1",key:"13wk12"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M5=re("FilePen",[["path",{d:"M12.5 22H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v9.5",key:"1couwa"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M13.378 15.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1y4qbx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xee=re("FilePlus2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M3 15h6",key:"4e2qda"}],["path",{d:"M6 12v6",key:"1u72j0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jee=re("FilePlus",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 15h6",key:"cctwl0"}],["path",{d:"M12 18v-6",key:"17g6i2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ete=re("FileQuestion",[["path",{d:"M12 17h.01",key:"p32p05"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tte=re("FileScan",[["path",{d:"M20 10V7l-5-5H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h4",key:"1rdf37"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M16 14a2 2 0 0 0-2 2",key:"ceaadl"}],["path",{d:"M20 14a2 2 0 0 1 2 2",key:"1ny6zw"}],["path",{d:"M20 22a2 2 0 0 0 2-2",key:"1l9q4k"}],["path",{d:"M16 22a2 2 0 0 1-2-2",key:"1wqh5n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ste=re("FileSearch2",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["circle",{cx:"11.5",cy:"14.5",r:"2.5",key:"1bq0ko"}],["path",{d:"M13.3 16.3 15 18",key:"2quom7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nte=re("FileSearch",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4.268 21a2 2 0 0 0 1.727 1H18a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v3",key:"ms7g94"}],["path",{d:"m9 18-1.5-1.5",key:"1j6qii"}],["circle",{cx:"5",cy:"14",r:"3",key:"ufru5t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rte=re("FileSliders",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M10 11v2",key:"1s651w"}],["path",{d:"M8 17h8",key:"wh5c61"}],["path",{d:"M14 16v2",key:"12fp5e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mw=re("FileSpreadsheet",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 13h2",key:"yr2amv"}],["path",{d:"M14 13h2",key:"un5t4a"}],["path",{d:"M8 17h2",key:"2yhykz"}],["path",{d:"M14 17h2",key:"10kma7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H7=re("FileStack",[["path",{d:"M21 7h-3a2 2 0 0 1-2-2V2",key:"9rb54x"}],["path",{d:"M21 6v6.5c0 .8-.7 1.5-1.5 1.5h-7c-.8 0-1.5-.7-1.5-1.5v-9c0-.8.7-1.5 1.5-1.5H17Z",key:"1059l0"}],["path",{d:"M7 8v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H15",key:"16874u"}],["path",{d:"M3 12v8.8c0 .3.2.6.4.8.2.2.5.4.8.4H11",key:"k2ox98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ate=re("FileSymlink",[["path",{d:"m10 18 3-3-3-3",key:"18f6ys"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 11V4a2 2 0 0 1 2-2h9l5 5v13a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h7",key:"50q2rw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ite=re("FileTerminal",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 16 2-2-2-2",key:"10vzyd"}],["path",{d:"M12 18h4",key:"1wd2n7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const br=re("FileText",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M10 9H8",key:"b1mrlr"}],["path",{d:"M16 13H8",key:"t4e002"}],["path",{d:"M16 17H8",key:"z1uh3a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ote=re("FileType2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M2 13v-1h6v1",key:"1dh9dg"}],["path",{d:"M5 12v6",key:"150t9c"}],["path",{d:"M4 18h2",key:"1xrofg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lte=re("FileType",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M9 13v-1h6v1",key:"1bb014"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M11 18h2",key:"12mj7e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cte=re("FileUp",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"m15 15-3-3-3 3",key:"15xj92"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dte=re("FileUser",[["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M15 18a3 3 0 1 0-6 0",key:"16awa0"}],["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7z",key:"1mlx9k"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ute=re("FileVideo2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["rect",{width:"8",height:"6",x:"2",y:"12",rx:"1",key:"1a6c1e"}],["path",{d:"m10 15.5 4 2.5v-6l-4 2.5",key:"t7cp39"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G7=re("FileVideo",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m10 11 5 3-5 3v-6Z",key:"7ntvm4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hte=re("FileVolume2",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M11.5 13.5a2.5 2.5 0 0 1 0 3",key:"1fccat"}],["path",{d:"M15 12a5 5 0 0 1 0 6",key:"ps46cm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mte=re("FileVolume",[["path",{d:"M11 11a5 5 0 0 1 0 6",key:"193qb2"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"M4 6.765V4a2 2 0 0 1 2-2h9l5 5v13a2 2 0 0 1-2 2H6a2 2 0 0 1-.93-.23",key:"ifyjnl"}],["path",{d:"M7 10.51a.5.5 0 0 0-.826-.38l-1.893 1.628A1 1 0 0 1 3.63 12H2.5a.5.5 0 0 0-.5.5v3a.5.5 0 0 0 .5.5h1.129a1 1 0 0 1 .652.242l1.893 1.63a.5.5 0 0 0 .826-.38z",key:"mk8rxu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pte=re("FileWarning",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fte=re("FileX2",[["path",{d:"M4 22h14a2 2 0 0 0 2-2V7l-5-5H6a2 2 0 0 0-2 2v4",key:"1pf5j1"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m8 12.5-5 5",key:"b853mi"}],["path",{d:"m3 12.5 5 5",key:"1qls4r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xte=re("FileX",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}],["path",{d:"m14.5 12.5-5 5",key:"b62r18"}],["path",{d:"m9.5 12.5 5 5",key:"1rk7el"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QP=re("File",[["path",{d:"M15 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7Z",key:"1rqfz7"}],["path",{d:"M14 2v4a2 2 0 0 0 2 2h4",key:"tnqrlb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gte=re("Files",[["path",{d:"M20 7h-3a2 2 0 0 1-2-2V2",key:"x099mo"}],["path",{d:"M9 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h7l4 4v10a2 2 0 0 1-2 2Z",key:"18t6ie"}],["path",{d:"M3 7.6v12.8A1.6 1.6 0 0 0 4.6 22h9.8",key:"1nja0z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sh=re("Film",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M3 7.5h4",key:"zfgn84"}],["path",{d:"M3 12h18",key:"1i2n21"}],["path",{d:"M3 16.5h4",key:"1230mu"}],["path",{d:"M17 3v18",key:"in4fa5"}],["path",{d:"M17 7.5h4",key:"myr1c1"}],["path",{d:"M17 16.5h4",key:"go4c1d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yte=re("FilterX",[["path",{d:"M13.013 3H2l8 9.46V19l4 2v-8.54l.9-1.055",key:"1fi1da"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lv=re("Filter",[["polygon",{points:"22 3 2 3 10 12.46 10 19 14 21 14 12.46 22 3",key:"1yg77f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vte=re("Fingerprint",[["path",{d:"M12 10a2 2 0 0 0-2 2c0 1.02-.1 2.51-.26 4",key:"1nerag"}],["path",{d:"M14 13.12c0 2.38 0 6.38-1 8.88",key:"o46ks0"}],["path",{d:"M17.29 21.02c.12-.6.43-2.3.5-3.02",key:"ptglia"}],["path",{d:"M2 12a10 10 0 0 1 18-6",key:"ydlgp0"}],["path",{d:"M2 16h.01",key:"1gqxmh"}],["path",{d:"M21.8 16c.2-2 .131-5.354 0-6",key:"drycrb"}],["path",{d:"M5 19.5C5.5 18 6 15 6 12a6 6 0 0 1 .34-2",key:"1tidbn"}],["path",{d:"M8.65 22c.21-.66.45-1.32.57-2",key:"13wd9y"}],["path",{d:"M9 6.8a6 6 0 0 1 9 5.2v2",key:"1fr1j5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bte=re("FireExtinguisher",[["path",{d:"M15 6.5V3a1 1 0 0 0-1-1h-2a1 1 0 0 0-1 1v3.5",key:"sqyvz"}],["path",{d:"M9 18h8",key:"i7pszb"}],["path",{d:"M18 3h-3",key:"7idoqj"}],["path",{d:"M11 3a6 6 0 0 0-6 6v11",key:"1v5je3"}],["path",{d:"M5 13h4",key:"svpcxo"}],["path",{d:"M17 10a4 4 0 0 0-8 0v10a2 2 0 0 0 2 2h4a2 2 0 0 0 2-2Z",key:"vsjego"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _te=re("FishOff",[["path",{d:"M18 12.47v.03m0-.5v.47m-.475 5.056A6.744 6.744 0 0 1 15 18c-3.56 0-7.56-2.53-8.5-6 .348-1.28 1.114-2.433 2.121-3.38m3.444-2.088A8.802 8.802 0 0 1 15 6c3.56 0 6.06 2.54 7 6-.309 1.14-.786 2.177-1.413 3.058",key:"1j1hse"}],["path",{d:"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33m7.48-4.372A9.77 9.77 0 0 1 16 6.07m0 11.86a9.77 9.77 0 0 1-1.728-3.618",key:"1q46z8"}],["path",{d:"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98M8.53 3h5.27a2 2 0 0 1 1.98 1.67l.23 1.4M2 2l20 20",key:"1407gh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wte=re("FishSymbol",[["path",{d:"M2 16s9-15 20-4C11 23 2 8 2 8",key:"h4oh4o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jte=re("Fish",[["path",{d:"M6.5 12c.94-3.46 4.94-6 8.5-6 3.56 0 6.06 2.54 7 6-.94 3.47-3.44 6-7 6s-7.56-2.53-8.5-6Z",key:"15baut"}],["path",{d:"M18 12v.5",key:"18hhni"}],["path",{d:"M16 17.93a9.77 9.77 0 0 1 0-11.86",key:"16dt7o"}],["path",{d:"M7 10.67C7 8 5.58 5.97 2.73 5.5c-1 1.5-1 5 .23 6.5-1.24 1.5-1.24 5-.23 6.5C5.58 18.03 7 16 7 13.33",key:"l9di03"}],["path",{d:"M10.46 7.26C10.2 5.88 9.17 4.24 8 3h5.8a2 2 0 0 1 1.98 1.67l.23 1.4",key:"1kjonw"}],["path",{d:"m16.01 17.93-.23 1.4A2 2 0 0 1 13.8 21H9.5a5.96 5.96 0 0 0 1.49-3.98",key:"1zlm23"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nte=re("FlagOff",[["path",{d:"M8 2c3 0 5 2 8 2s4-1 4-1v11",key:"9rwyz9"}],["path",{d:"M4 22V4",key:"1plyxx"}],["path",{d:"M4 15s1-1 4-1 5 2 8 2",key:"1myooe"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kte=re("FlagTriangleLeft",[["path",{d:"M17 22V2L7 7l10 5",key:"1rmf0r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ste=re("FlagTriangleRight",[["path",{d:"M7 22V2l10 5-10 5",key:"17n18y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V2=re("Flag",[["path",{d:"M4 15s1-1 4-1 5 2 8 2 4-1 4-1V3s-1 1-4 1-5-2-8-2-4 1-4 1z",key:"i9b6wo"}],["line",{x1:"4",x2:"4",y1:"22",y2:"15",key:"1cm3nv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cte=re("FlameKindling",[["path",{d:"M12 2c1 3 2.5 3.5 3.5 4.5A5 5 0 0 1 17 10a5 5 0 1 1-10 0c0-.3 0-.6.1-.9a2 2 0 1 0 3.3-2C8 4.5 11 2 12 2Z",key:"1ir223"}],["path",{d:"m5 22 14-4",key:"1brv4h"}],["path",{d:"m5 18 14 4",key:"lgyyje"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hc=re("Flame",[["path",{d:"M8.5 14.5A2.5 2.5 0 0 0 11 12c0-1.38-.5-2-1-3-1.072-2.143-.224-4.054 2-6 .5 2.5 2 4.9 4 6.5 2 1.6 3 3.5 3 5.5a7 7 0 1 1-14 0c0-1.153.433-2.294 1-3a2.5 2.5 0 0 0 2.5 2.5z",key:"96xj49"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tte=re("FlashlightOff",[["path",{d:"M16 16v4a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4",key:"1r120k"}],["path",{d:"M7 2h11v4c0 2-2 2-2 4v1",key:"dz1920"}],["line",{x1:"11",x2:"18",y1:"6",y2:"6",key:"bi1vpe"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ete=re("Flashlight",[["path",{d:"M18 6c0 2-2 2-2 4v10a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2V10c0-2-2-2-2-4V2h12z",key:"1orkel"}],["line",{x1:"6",x2:"18",y1:"6",y2:"6",key:"1z11jq"}],["line",{x1:"12",x2:"12",y1:"12",y2:"12",key:"1f4yc1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ate=re("FlaskConicalOff",[["path",{d:"M10 10 4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-1.272-2.542",key:"59ek9y"}],["path",{d:"M10 2v2.343",key:"15t272"}],["path",{d:"M14 2v6.343",key:"sxr80q"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h9",key:"t5njau"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qS=re("FlaskConical",[["path",{d:"M10 2v7.527a2 2 0 0 1-.211.896L4.72 20.55a1 1 0 0 0 .9 1.45h12.76a1 1 0 0 0 .9-1.45l-5.069-10.127A2 2 0 0 1 14 9.527V2",key:"pzvekw"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mte=re("FlaskRound",[["path",{d:"M10 2v7.31",key:"5d1hyh"}],["path",{d:"M14 9.3V1.99",key:"14k4l0"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14 9.3a6.5 6.5 0 1 1-4 0",key:"1r8fvy"}],["path",{d:"M5.52 16h12.96",key:"46hh1i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ite=re("FlipHorizontal2",[["path",{d:"m3 7 5 5-5 5V7",key:"couhi7"}],["path",{d:"m21 7-5 5 5 5V7",key:"6ouia7"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W7=re("FlipHorizontal",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h3",key:"1i73f7"}],["path",{d:"M16 3h3a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-3",key:"saxlbk"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 2v2",key:"tus03m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pte=re("FlipVertical2",[["path",{d:"m17 3-5 5-5-5h10",key:"1ftt6x"}],["path",{d:"m17 21-5-5-5 5h10",key:"1m0wmu"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lte=re("FlipVertical",[["path",{d:"M21 8V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v3",key:"14bfxa"}],["path",{d:"M21 16v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-3",key:"14rx03"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rb=re("Flower2",[["path",{d:"M12 5a3 3 0 1 1 3 3m-3-3a3 3 0 1 0-3 3m3-3v1M9 8a3 3 0 1 0 3 3M9 8h1m5 0a3 3 0 1 1-3 3m3-3h-1m-2 3v-1",key:"3pnvol"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["path",{d:"M12 10v12",key:"6ubwww"}],["path",{d:"M12 22c4.2 0 7-1.667 7-5-4.2 0-7 1.667-7 5Z",key:"9hd38g"}],["path",{d:"M12 22c-4.2 0-7-1.667-7-5 4.2 0 7 1.667 7 5Z",key:"ufn41s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dte=re("Flower",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 16.5A4.5 4.5 0 1 1 7.5 12 4.5 4.5 0 1 1 12 7.5a4.5 4.5 0 1 1 4.5 4.5 4.5 4.5 0 1 1-4.5 4.5",key:"14wa3c"}],["path",{d:"M12 7.5V9",key:"1oy5b0"}],["path",{d:"M7.5 12H9",key:"eltsq1"}],["path",{d:"M16.5 12H15",key:"vk5kw4"}],["path",{d:"M12 16.5V15",key:"k7eayi"}],["path",{d:"m8 8 1.88 1.88",key:"nxy4qf"}],["path",{d:"M14.12 9.88 16 8",key:"1lst6k"}],["path",{d:"m8 16 1.88-1.88",key:"h2eex1"}],["path",{d:"M14.12 14.12 16 16",key:"uqkrx3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rte=re("Focus",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ote=re("FoldHorizontal",[["path",{d:"M2 12h6",key:"1wqiqv"}],["path",{d:"M22 12h-6",key:"1eg9hc"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m19 9-3 3 3 3",key:"12ol22"}],["path",{d:"m5 15 3-3-3-3",key:"1kdhjc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fte=re("FoldVertical",[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3-3-3 3",key:"e37ymu"}],["path",{d:"m15 5-3 3-3-3",key:"19d6lf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zte=re("FolderArchive",[["circle",{cx:"15",cy:"19",r:"2",key:"u2pros"}],["path",{d:"M20.9 19.8A2 2 0 0 0 22 18V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2h5.1",key:"1jj40k"}],["path",{d:"M15 11v-1",key:"cntcp"}],["path",{d:"M15 17v-2",key:"1279jj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bte=re("FolderCheck",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9 13 2 2 4-4",key:"6343dt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $te=re("FolderClock",[["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}],["path",{d:"M7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2",key:"1urifu"}],["path",{d:"M16 14v2l1 1",key:"xth2jh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ute=re("FolderClosed",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M2 10h20",key:"1ir3d8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qte=re("FolderCode",[["path",{d:"M10 10.5 8 13l2 2.5",key:"m4t9c1"}],["path",{d:"m14 10.5 2 2.5-2 2.5",key:"14w2eb"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2z",key:"1u1bxd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I5=re("FolderCog",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"M10.3 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v3.3",key:"1k8050"}],["path",{d:"m21.7 19.4-.9-.3",key:"1qgwi9"}],["path",{d:"m15.2 16.9-.9-.3",key:"1t7mvx"}],["path",{d:"m16.6 21.7.3-.9",key:"1j67ps"}],["path",{d:"m19.1 15.2.3-.9",key:"18r7jp"}],["path",{d:"m19.6 21.7-.4-1",key:"z2vh2"}],["path",{d:"m16.8 15.3-.4-1",key:"1ei7r6"}],["path",{d:"m14.3 19.6 1-.4",key:"11sv9r"}],["path",{d:"m20.7 16.8 1-.4",key:"19m87a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vte=re("FolderDot",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"1",key:"49l61u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hte=re("FolderDown",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m15 13-3 3-3-3",key:"6j2sf0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gte=re("FolderGit2",[["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v5",key:"1w6njk"}],["circle",{cx:"13",cy:"12",r:"2",key:"1j92g6"}],["path",{d:"M18 19c-2.8 0-5-2.2-5-5v8",key:"pkpw2h"}],["circle",{cx:"20",cy:"19",r:"2",key:"1obnsp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wte=re("FolderGit",[["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M14 13h3",key:"1dgedf"}],["path",{d:"M7 13h3",key:"1pygq7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kte=re("FolderHeart",[["path",{d:"M11 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v1.5",key:"6hud8k"}],["path",{d:"M13.9 17.45c-1.2-1.2-1.14-2.8-.2-3.73a2.43 2.43 0 0 1 3.44 0l.36.34.34-.34a2.43 2.43 0 0 1 3.45-.01c.95.95 1 2.53-.2 3.74L17.5 21Z",key:"wpff58"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yte=re("FolderInput",[["path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-1",key:"fm4g5t"}],["path",{d:"M2 13h10",key:"pgb2dq"}],["path",{d:"m9 16 3-3-3-3",key:"6m91ic"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zte=re("FolderKanban",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["path",{d:"M8 10v4",key:"tgpxqk"}],["path",{d:"M12 10v2",key:"hh53o1"}],["path",{d:"M16 10v6",key:"1d6xys"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qte=re("FolderKey",[["circle",{cx:"16",cy:"20",r:"2",key:"1vifvg"}],["path",{d:"M10 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v2",key:"3hgo9p"}],["path",{d:"m22 14-4.5 4.5",key:"1ef6z8"}],["path",{d:"m21 15 1 1",key:"1ejcpy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xte=re("FolderLock",[["rect",{width:"8",height:"5",x:"14",y:"17",rx:"1",key:"19aais"}],["path",{d:"M10 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v2.5",key:"1w6v7t"}],["path",{d:"M20 17v-2a2 2 0 1 0-4 0v2",key:"pwaxnr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jte=re("FolderMinus",[["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ese=re("FolderOpenDot",[["path",{d:"m6 14 1.45-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.55 6a2 2 0 0 1-1.94 1.5H4a2 2 0 0 1-2-2V5c0-1.1.9-2 2-2h3.93a2 2 0 0 1 1.66.9l.82 1.2a2 2 0 0 0 1.66.9H18a2 2 0 0 1 2 2v2",key:"1nmvlm"}],["circle",{cx:"14",cy:"15",r:"1",key:"1gm4qj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pf=re("FolderOpen",[["path",{d:"m6 14 1.5-2.9A2 2 0 0 1 9.24 10H20a2 2 0 0 1 1.94 2.5l-1.54 6a2 2 0 0 1-1.95 1.5H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H18a2 2 0 0 1 2 2v2",key:"usdka0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tse=re("FolderOutput",[["path",{d:"M2 7.5V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-1.5",key:"1yk7aj"}],["path",{d:"M2 13h10",key:"pgb2dq"}],["path",{d:"m5 10-3 3 3 3",key:"1r8ie0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const P5=re("FolderPen",[["path",{d:"M2 11.5V5a2 2 0 0 1 2-2h3.9c.7 0 1.3.3 1.7.9l.8 1.2c.4.6 1 .9 1.7.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-9.5",key:"a8xqs0"}],["path",{d:"M11.378 13.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1saktj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sse=re("FolderPlus",[["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"M9 13h6",key:"1uhe8q"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nse=re("FolderRoot",[["path",{d:"M4 20h16a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.93a2 2 0 0 1-1.66-.9l-.82-1.2A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13c0 1.1.9 2 2 2Z",key:"1fr9dc"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}],["path",{d:"M12 15v5",key:"11xva1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rse=re("FolderSearch2",[["circle",{cx:"11.5",cy:"12.5",r:"2.5",key:"1ea5ju"}],["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M13.3 14.3 15 16",key:"1y4v1n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ase=re("FolderSearch",[["path",{d:"M10.7 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v4.1",key:"1bw5m7"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ise=re("FolderSymlink",[["path",{d:"M2 9V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h7",key:"x1c07l"}],["path",{d:"m8 16 3-3-3-3",key:"rlqrt1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ose=re("FolderSync",[["path",{d:"M9 20H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h3.9a2 2 0 0 1 1.69.9l.81 1.2a2 2 0 0 0 1.67.9H20a2 2 0 0 1 2 2v.5",key:"1dkoa9"}],["path",{d:"M12 10v4h4",key:"1czhmt"}],["path",{d:"m12 14 1.535-1.605a5 5 0 0 1 8 1.5",key:"lvuxfi"}],["path",{d:"M22 22v-4h-4",key:"1ewp4q"}],["path",{d:"m22 18-1.535 1.605a5 5 0 0 1-8-1.5",key:"14ync0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lse=re("FolderTree",[["path",{d:"M20 10a1 1 0 0 0 1-1V6a1 1 0 0 0-1-1h-2.5a1 1 0 0 1-.8-.4l-.9-1.2A1 1 0 0 0 15 3h-2a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"hod4my"}],["path",{d:"M20 21a1 1 0 0 0 1-1v-3a1 1 0 0 0-1-1h-2.9a1 1 0 0 1-.88-.55l-.42-.85a1 1 0 0 0-.92-.6H13a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1Z",key:"w4yl2u"}],["path",{d:"M3 5a2 2 0 0 0 2 2h3",key:"f2jnh7"}],["path",{d:"M3 3v13a2 2 0 0 0 2 2h3",key:"k8epm1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cse=re("FolderUp",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"M12 10v6",key:"1bos4e"}],["path",{d:"m9 13 3-3 3 3",key:"1pxg3c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dse=re("FolderX",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}],["path",{d:"m9.5 10.5 5 5",key:"ra9qjz"}],["path",{d:"m14.5 10.5-5 5",key:"l2rkpq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const use=re("Folder",[["path",{d:"M20 20a2 2 0 0 0 2-2V8a2 2 0 0 0-2-2h-7.9a2 2 0 0 1-1.69-.9L9.6 3.9A2 2 0 0 0 7.93 3H4a2 2 0 0 0-2 2v13a2 2 0 0 0 2 2Z",key:"1kt360"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hse=re("Folders",[["path",{d:"M20 17a2 2 0 0 0 2-2V9a2 2 0 0 0-2-2h-3.9a2 2 0 0 1-1.69-.9l-.81-1.2a2 2 0 0 0-1.67-.9H8a2 2 0 0 0-2 2v9a2 2 0 0 0 2 2Z",key:"4u7rpt"}],["path",{d:"M2 8v11a2 2 0 0 0 2 2h14",key:"1eicx1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mse=re("Footprints",[["path",{d:"M4 16v-2.38C4 11.5 2.97 10.5 3 8c.03-2.72 1.49-6 4.5-6C9.37 2 10 3.8 10 5.5c0 3.11-2 5.66-2 8.68V16a2 2 0 1 1-4 0Z",key:"1dudjm"}],["path",{d:"M20 20v-2.38c0-2.12 1.03-3.12 1-5.62-.03-2.72-1.49-6-4.5-6C14.63 6 14 7.8 14 9.5c0 3.11 2 5.66 2 8.68V20a2 2 0 1 0 4 0Z",key:"l2t8xc"}],["path",{d:"M16 17h4",key:"1dejxt"}],["path",{d:"M4 13h4",key:"1bwh8b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pse=re("Forklift",[["path",{d:"M12 12H5a2 2 0 0 0-2 2v5",key:"7zsz91"}],["circle",{cx:"13",cy:"19",r:"2",key:"wjnkru"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M8 19h3m5-17v17h6M6 12V7c0-1.1.9-2 2-2h3l5 5",key:"13bk1p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fse=re("Forward",[["polyline",{points:"15 17 20 12 15 7",key:"1w3sku"}],["path",{d:"M4 18v-2a4 4 0 0 1 4-4h12",key:"jmiej9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xse=re("Frame",[["line",{x1:"22",x2:"2",y1:"6",y2:"6",key:"15w7dq"}],["line",{x1:"22",x2:"2",y1:"18",y2:"18",key:"1ip48p"}],["line",{x1:"6",x2:"6",y1:"2",y2:"22",key:"a2lnyx"}],["line",{x1:"18",x2:"18",y1:"2",y2:"22",key:"8vb6jd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gse=re("Framer",[["path",{d:"M5 16V9h14V2H5l14 14h-7m-7 0 7 7v-7m-7 0h7",key:"1a2nng"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yse=re("Frown",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M16 16s-1.5-2-4-2-4 2-4 2",key:"epbg0q"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vse=re("Fuel",[["line",{x1:"3",x2:"15",y1:"22",y2:"22",key:"xegly4"}],["line",{x1:"4",x2:"14",y1:"9",y2:"9",key:"xcnuvu"}],["path",{d:"M14 22V4a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v18",key:"16j0yd"}],["path",{d:"M14 13h2a2 2 0 0 1 2 2v2a2 2 0 0 0 2 2a2 2 0 0 0 2-2V9.83a2 2 0 0 0-.59-1.42L18 5",key:"7cu91f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bse=re("Fullscreen",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{width:"10",height:"8",x:"7",y:"8",rx:"1",key:"vys8me"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _se=re("GalleryHorizontalEnd",[["path",{d:"M2 7v10",key:"a2pl2d"}],["path",{d:"M6 5v14",key:"1kq3d7"}],["rect",{width:"12",height:"18",x:"10",y:"3",rx:"2",key:"13i7bc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wse=re("GalleryHorizontal",[["path",{d:"M2 3v18",key:"pzttux"}],["rect",{width:"12",height:"18",x:"6",y:"3",rx:"2",key:"btr8bg"}],["path",{d:"M22 3v18",key:"6jf3v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jse=re("GalleryThumbnails",[["rect",{width:"18",height:"14",x:"3",y:"3",rx:"2",key:"74y24f"}],["path",{d:"M4 21h1",key:"16zlid"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M19 21h1",key:"edywat"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nse=re("GalleryVerticalEnd",[["path",{d:"M7 2h10",key:"nczekb"}],["path",{d:"M5 6h14",key:"u2x4p"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kse=re("GalleryVertical",[["path",{d:"M3 2h18",key:"15qxfx"}],["rect",{width:"18",height:"12",x:"3",y:"6",rx:"2",key:"1439r6"}],["path",{d:"M3 22h18",key:"8prr45"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sse=re("Gamepad2",[["line",{x1:"6",x2:"10",y1:"11",y2:"11",key:"1gktln"}],["line",{x1:"8",x2:"8",y1:"9",y2:"13",key:"qnk9ow"}],["line",{x1:"15",x2:"15.01",y1:"12",y2:"12",key:"krot7o"}],["line",{x1:"18",x2:"18.01",y1:"10",y2:"10",key:"1lcuu1"}],["path",{d:"M17.32 5H6.68a4 4 0 0 0-3.978 3.59c-.006.052-.01.101-.017.152C2.604 9.416 2 14.456 2 16a3 3 0 0 0 3 3c1 0 1.5-.5 2-1l1.414-1.414A2 2 0 0 1 9.828 16h4.344a2 2 0 0 1 1.414.586L17 18c.5.5 1 1 2 1a3 3 0 0 0 3-3c0-1.545-.604-6.584-.685-7.258-.007-.05-.011-.1-.017-.151A4 4 0 0 0 17.32 5z",key:"mfqc10"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cse=re("Gamepad",[["line",{x1:"6",x2:"10",y1:"12",y2:"12",key:"161bw2"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"15",x2:"15.01",y1:"13",y2:"13",key:"dqpgro"}],["line",{x1:"18",x2:"18.01",y1:"11",y2:"11",key:"meh2c"}],["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tse=re("Gauge",[["path",{d:"m12 14 4-4",key:"9kzdfg"}],["path",{d:"M3.34 19a10 10 0 1 1 17.32 0",key:"19p75a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ese=re("Gavel",[["path",{d:"m14.5 12.5-8 8a2.119 2.119 0 1 1-3-3l8-8",key:"15492f"}],["path",{d:"m16 16 6-6",key:"vzrcl6"}],["path",{d:"m8 8 6-6",key:"18bi4p"}],["path",{d:"m9 7 8 8",key:"5jnvq1"}],["path",{d:"m21 11-8-8",key:"z4y7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ase=re("Gem",[["path",{d:"M6 3h12l4 6-10 13L2 9Z",key:"1pcd5k"}],["path",{d:"M11 3 8 9l4 13 4-13-3-6",key:"1fcu3u"}],["path",{d:"M2 9h20",key:"16fsjt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wA=re("Ghost",[["path",{d:"M9 10h.01",key:"qbtxuw"}],["path",{d:"M15 10h.01",key:"1qmjsl"}],["path",{d:"M12 2a8 8 0 0 0-8 8v12l3-3 2.5 2.5L12 19l2.5 2.5L17 19l3 3V10a8 8 0 0 0-8-8z",key:"uwwb07"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oi=re("Gift",[["rect",{x:"3",y:"8",width:"18",height:"4",rx:"1",key:"bkv52"}],["path",{d:"M12 8v13",key:"1c76mn"}],["path",{d:"M19 12v7a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-7",key:"6wjy6b"}],["path",{d:"M7.5 8a2.5 2.5 0 0 1 0-5A4.8 8 0 0 1 12 8a4.8 8 0 0 1 4.5-5 2.5 2.5 0 0 1 0 5",key:"1ihvrl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mse=re("GitBranchPlus",[["path",{d:"M6 3v12",key:"qpgusn"}],["path",{d:"M18 9a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"1d02ji"}],["path",{d:"M6 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6z",key:"chk6ph"}],["path",{d:"M15 6a9 9 0 0 0-9 9",key:"or332x"}],["path",{d:"M18 15v6",key:"9wciyi"}],["path",{d:"M21 18h-6",key:"139f0c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ise=re("GitBranch",[["line",{x1:"6",x2:"6",y1:"3",y2:"15",key:"17qcm7"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M18 9a9 9 0 0 1-9 9",key:"n2h4wq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const L5=re("GitCommitHorizontal",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["line",{x1:"3",x2:"9",y1:"12",y2:"12",key:"1dyftd"}],["line",{x1:"15",x2:"21",y1:"12",y2:"12",key:"oup4p8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pse=re("GitCommitVertical",[["path",{d:"M12 3v6",key:"1holv5"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M12 15v6",key:"a9ows0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lse=re("GitCompareArrows",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"M12 18H7a2 2 0 0 1-2-2V9",key:"16sdep"}],["path",{d:"m9 15 3 3-3 3",key:"1m3kbl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dse=re("GitCompare",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["path",{d:"M11 18H8a2 2 0 0 1-2-2V9",key:"19pyzm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rse=re("GitFork",[["circle",{cx:"12",cy:"18",r:"3",key:"1mpf1b"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}],["path",{d:"M18 9v2c0 .6-.4 1-1 1H7c-.6 0-1-.4-1-1V9",key:"1uq4wg"}],["path",{d:"M12 12v3",key:"158kv8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ose=re("GitGraph",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v6",key:"158jrl"}],["circle",{cx:"5",cy:"18",r:"3",key:"104gr9"}],["path",{d:"M12 3v18",key:"108xh3"}],["circle",{cx:"19",cy:"6",r:"3",key:"108a5v"}],["path",{d:"M16 15.7A9 9 0 0 0 19 9",key:"1e3vqb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fse=re("GitMerge",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 21V9a9 9 0 0 0 9 9",key:"7kw0sc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zse=re("GitPullRequestArrow",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v12",key:"ih889a"}],["circle",{cx:"19",cy:"18",r:"3",key:"1qljk2"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v7",key:"1yj91y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bse=re("GitPullRequestClosed",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 9v12",key:"1sc30k"}],["path",{d:"m21 3-6 6",key:"16nqsk"}],["path",{d:"m21 9-6-6",key:"9j17rh"}],["path",{d:"M18 11.5V15",key:"65xf6f"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $se=re("GitPullRequestCreateArrow",[["circle",{cx:"5",cy:"6",r:"3",key:"1qnov2"}],["path",{d:"M5 9v12",key:"ih889a"}],["path",{d:"m15 9-3-3 3-3",key:"1lwv8l"}],["path",{d:"M12 6h5a2 2 0 0 1 2 2v3",key:"1rbwk6"}],["path",{d:"M19 15v6",key:"10aioa"}],["path",{d:"M22 18h-6",key:"1d5gi5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Use=re("GitPullRequestCreate",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M6 9v12",key:"1sc30k"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v3",key:"1jb6z3"}],["path",{d:"M18 15v6",key:"9wciyi"}],["path",{d:"M21 18h-6",key:"139f0c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qse=re("GitPullRequestDraft",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M18 6V5",key:"1oao2s"}],["path",{d:"M18 11v-1",key:"11c8tz"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vse=re("GitPullRequest",[["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M13 6h3a2 2 0 0 1 2 2v7",key:"1yeb86"}],["line",{x1:"6",x2:"6",y1:"9",y2:"21",key:"rroup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hse=re("Github",[["path",{d:"M15 22v-4a4.8 4.8 0 0 0-1-3.5c3 0 6-2 6-5.5.08-1.25-.27-2.48-1-3.5.28-1.15.28-2.35 0-3.5 0 0-1 0-3 1.5-2.64-.5-5.36-.5-8 0C6 2 5 2 5 2c-.3 1.15-.3 2.35 0 3.5A5.403 5.403 0 0 0 4 9c0 3.5 3 5.5 6 5.5-.39.49-.68 1.05-.85 1.65-.17.6-.22 1.23-.15 1.85v4",key:"tonef"}],["path",{d:"M9 18c-4.51 2-5-2-7-2",key:"9comsn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gse=re("Gitlab",[["path",{d:"m22 13.29-3.33-10a.42.42 0 0 0-.14-.18.38.38 0 0 0-.22-.11.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18l-2.26 6.67H8.32L6.1 3.26a.42.42 0 0 0-.1-.18.38.38 0 0 0-.26-.08.39.39 0 0 0-.23.07.42.42 0 0 0-.14.18L2 13.29a.74.74 0 0 0 .27.83L12 21l9.69-6.88a.71.71 0 0 0 .31-.83Z",key:"148pdi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wse=re("GlassWater",[["path",{d:"M5.116 4.104A1 1 0 0 1 6.11 3h11.78a1 1 0 0 1 .994 1.105L17.19 20.21A2 2 0 0 1 15.2 22H8.8a2 2 0 0 1-2-1.79z",key:"p55z4y"}],["path",{d:"M6 12a5 5 0 0 1 6 0 5 5 0 0 0 6 0",key:"mjntcy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kse=re("Glasses",[["circle",{cx:"6",cy:"15",r:"4",key:"vux9w4"}],["circle",{cx:"18",cy:"15",r:"4",key:"18o8ve"}],["path",{d:"M14 15a2 2 0 0 0-2-2 2 2 0 0 0-2 2",key:"1ag4bs"}],["path",{d:"M2.5 13 5 7c.7-1.3 1.4-2 3-2",key:"1hm1gs"}],["path",{d:"M21.5 13 19 7c-.7-1.3-1.5-2-3-2",key:"1r31ai"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yse=re("GlobeLock",[["path",{d:"M15.686 15A14.5 14.5 0 0 1 12 22a14.5 14.5 0 0 1 0-20 10 10 0 1 0 9.542 13",key:"qkt0x6"}],["path",{d:"M2 12h8.5",key:"ovaggd"}],["path",{d:"M20 6V4a2 2 0 1 0-4 0v2",key:"1of5e8"}],["rect",{width:"8",height:"5",x:"14",y:"6",rx:"1",key:"1fmf51"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lc=re("Globe",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 2a14.5 14.5 0 0 0 0 20 14.5 14.5 0 0 0 0-20",key:"13o1zl"}],["path",{d:"M2 12h20",key:"9i4pu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zse=re("Goal",[["path",{d:"M12 13V2l8 4-8 4",key:"5wlwwj"}],["path",{d:"M20.561 10.222a9 9 0 1 1-12.55-5.29",key:"1c0wjv"}],["path",{d:"M8.002 9.997a5 5 0 1 0 8.9 2.02",key:"gb1g7m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qse=re("Grab",[["path",{d:"M18 11.5V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1.4",key:"edstyy"}],["path",{d:"M14 10V8a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"19wdwo"}],["path",{d:"M10 9.9V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v5",key:"1lugqo"}],["path",{d:"M6 14a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1hbeus"}],["path",{d:"M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-4a8 8 0 0 1-8-8 2 2 0 1 1 4 0",key:"1etffm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yd=re("GraduationCap",[["path",{d:"M21.42 10.922a1 1 0 0 0-.019-1.838L12.83 5.18a2 2 0 0 0-1.66 0L2.6 9.08a1 1 0 0 0 0 1.832l8.57 3.908a2 2 0 0 0 1.66 0z",key:"j76jl0"}],["path",{d:"M22 10v6",key:"1lu8f3"}],["path",{d:"M6 12.5V16a6 3 0 0 0 12 0v-3.5",key:"1r8lef"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xse=re("Grape",[["path",{d:"M22 5V2l-5.89 5.89",key:"1eenpo"}],["circle",{cx:"16.6",cy:"15.89",r:"3",key:"xjtalx"}],["circle",{cx:"8.11",cy:"7.4",r:"3",key:"u2fv6i"}],["circle",{cx:"12.35",cy:"11.65",r:"3",key:"i6i8g7"}],["circle",{cx:"13.91",cy:"5.85",r:"3",key:"6ye0dv"}],["circle",{cx:"18.15",cy:"10.09",r:"3",key:"snx9no"}],["circle",{cx:"6.56",cy:"13.2",r:"3",key:"17x4xg"}],["circle",{cx:"10.8",cy:"17.44",r:"3",key:"1hogw9"}],["circle",{cx:"5",cy:"19",r:"3",key:"1sn6vo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jse=re("Grid2x2Check",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const D5=re("Grid2x2Plus",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"M16 19h6",key:"xwg31i"}],["path",{d:"M19 22v-6",key:"qhmiwi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ene=re("Grid2x2X",[["path",{d:"M12 3v17a1 1 0 0 1-1 1H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6a1 1 0 0 1-1 1H3",key:"11za1p"}],["path",{d:"m16 16 5 5",key:"8tpb07"}],["path",{d:"m16 21 5-5",key:"193jll"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const R5=re("Grid2x2",[["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 12h18",key:"1i2n21"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mv=re("Grid3x3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tne=re("GripHorizontal",[["circle",{cx:"12",cy:"9",r:"1",key:"124mty"}],["circle",{cx:"19",cy:"9",r:"1",key:"1ruzo2"}],["circle",{cx:"5",cy:"9",r:"1",key:"1a8b28"}],["circle",{cx:"12",cy:"15",r:"1",key:"1e56xg"}],["circle",{cx:"19",cy:"15",r:"1",key:"1a92ep"}],["circle",{cx:"5",cy:"15",r:"1",key:"5r1jwy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pu=re("GripVertical",[["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}],["circle",{cx:"9",cy:"5",r:"1",key:"hp0tcf"}],["circle",{cx:"9",cy:"19",r:"1",key:"fkjjf6"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"15",cy:"5",r:"1",key:"19l28e"}],["circle",{cx:"15",cy:"19",r:"1",key:"f4zoj3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sne=re("Grip",[["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["circle",{cx:"19",cy:"5",r:"1",key:"w8mnmm"}],["circle",{cx:"5",cy:"5",r:"1",key:"lttvr7"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["circle",{cx:"19",cy:"12",r:"1",key:"1wjl8i"}],["circle",{cx:"5",cy:"12",r:"1",key:"1pcz8c"}],["circle",{cx:"12",cy:"19",r:"1",key:"lyex9k"}],["circle",{cx:"19",cy:"19",r:"1",key:"shf9b7"}],["circle",{cx:"5",cy:"19",r:"1",key:"bfqh0e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nne=re("Group",[["path",{d:"M3 7V5c0-1.1.9-2 2-2h2",key:"adw53z"}],["path",{d:"M17 3h2c1.1 0 2 .9 2 2v2",key:"an4l38"}],["path",{d:"M21 17v2c0 1.1-.9 2-2 2h-2",key:"144t0e"}],["path",{d:"M7 21H5c-1.1 0-2-.9-2-2v-2",key:"rtnfgi"}],["rect",{width:"7",height:"5",x:"7",y:"7",rx:"1",key:"1eyiv7"}],["rect",{width:"7",height:"5",x:"10",y:"12",rx:"1",key:"1qlmkx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rne=re("Guitar",[["path",{d:"m11.9 12.1 4.514-4.514",key:"109xqo"}],["path",{d:"M20.1 2.3a1 1 0 0 0-1.4 0l-1.114 1.114A2 2 0 0 0 17 4.828v1.344a2 2 0 0 1-.586 1.414A2 2 0 0 1 17.828 7h1.344a2 2 0 0 0 1.414-.586L21.7 5.3a1 1 0 0 0 0-1.4z",key:"txyc8t"}],["path",{d:"m6 16 2 2",key:"16qmzd"}],["path",{d:"M8.2 9.9C8.7 8.8 9.8 8 11 8c2.8 0 5 2.2 5 5 0 1.2-.8 2.3-1.9 2.8l-.9.4A2 2 0 0 0 12 18a4 4 0 0 1-4 4c-3.3 0-6-2.7-6-6a4 4 0 0 1 4-4 2 2 0 0 0 1.8-1.2z",key:"1u8q3z"}],["circle",{cx:"11.5",cy:"12.5",r:".5",fill:"currentColor",key:"16onso"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ane=re("Ham",[["path",{d:"M13.144 21.144A7.274 10.445 45 1 0 2.856 10.856",key:"1k1t7q"}],["path",{d:"M13.144 21.144A7.274 4.365 45 0 0 2.856 10.856a7.274 4.365 45 0 0 10.288 10.288",key:"153t1g"}],["path",{d:"M16.565 10.435 18.6 8.4a2.501 2.501 0 1 0 1.65-4.65 2.5 2.5 0 1 0-4.66 1.66l-2.024 2.025",key:"gzrt0n"}],["path",{d:"m8.5 16.5-1-1",key:"otr954"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K7=re("Hammer",[["path",{d:"m15 12-8.373 8.373a1 1 0 1 1-3-3L12 9",key:"eefl8a"}],["path",{d:"m18 15 4-4",key:"16gjal"}],["path",{d:"m21.5 11.5-1.914-1.914A2 2 0 0 1 19 8.172V7l-2.26-2.26a6 6 0 0 0-4.202-1.756L9 2.96l.92.82A6.18 6.18 0 0 1 12 8.4V10l2 2h1.172a2 2 0 0 1 1.414.586L18.5 14.5",key:"b7pghm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ine=re("HandCoins",[["path",{d:"M11 15h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 17",key:"geh8rc"}],["path",{d:"m7 21 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"1fto5m"}],["path",{d:"m2 16 6 6",key:"1pfhp9"}],["circle",{cx:"16",cy:"9",r:"2.9",key:"1n0dlu"}],["circle",{cx:"6",cy:"5",r:"3",key:"151irh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jA=re("HandHeart",[["path",{d:"M11 14h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 16",key:"1ifwr1"}],["path",{d:"m7 20 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"17abbs"}],["path",{d:"m2 15 6 6",key:"10dquu"}],["path",{d:"M19.5 8.5c.7-.7 1.5-1.6 1.5-2.7A2.73 2.73 0 0 0 16 4a2.78 2.78 0 0 0-5 1.8c0 1.2.8 2 1.5 2.8L16 12Z",key:"1h3036"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X1=re("HandHelping",[["path",{d:"M11 12h2a2 2 0 1 0 0-4h-3c-.6 0-1.1.2-1.4.6L3 14",key:"1j4xps"}],["path",{d:"m7 18 1.6-1.4c.3-.4.8-.6 1.4-.6h4c1.1 0 2.1-.4 2.8-1.2l4.6-4.4a2 2 0 0 0-2.75-2.91l-4.2 3.9",key:"uospg8"}],["path",{d:"m2 13 6 6",key:"16e5sb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const one=re("HandMetal",[["path",{d:"M18 12.5V10a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1.4",key:"wc6myp"}],["path",{d:"M14 11V9a2 2 0 1 0-4 0v2",key:"94qvcw"}],["path",{d:"M10 10.5V5a2 2 0 1 0-4 0v9",key:"m1ah89"}],["path",{d:"m7 15-1.76-1.76a2 2 0 0 0-2.83 2.82l3.6 3.6C7.5 21.14 9.2 22 12 22h2a8 8 0 0 0 8-8V7a2 2 0 1 0-4 0v5",key:"t1skq1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lne=re("HandPlatter",[["path",{d:"M12 3V2",key:"ar7q03"}],["path",{d:"m15.4 17.4 3.2-2.8a2 2 0 1 1 2.8 2.9l-3.6 3.3c-.7.8-1.7 1.2-2.8 1.2h-4c-1.1 0-2.1-.4-2.8-1.2l-1.302-1.464A1 1 0 0 0 6.151 19H5",key:"n2g93r"}],["path",{d:"M2 14h12a2 2 0 0 1 0 4h-2",key:"1o2jem"}],["path",{d:"M4 10h16",key:"img6z1"}],["path",{d:"M5 10a7 7 0 0 1 14 0",key:"1ega1o"}],["path",{d:"M5 14v6a1 1 0 0 1-1 1H2",key:"1hescx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y7=re("Hand",[["path",{d:"M18 11V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1fvzgz"}],["path",{d:"M14 10V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v2",key:"1kc0my"}],["path",{d:"M10 10.5V6a2 2 0 0 0-2-2a2 2 0 0 0-2 2v8",key:"10h0bg"}],["path",{d:"M18 8a2 2 0 1 1 4 0v6a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"1s1gnw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pw=re("Handshake",[["path",{d:"m11 17 2 2a1 1 0 1 0 3-3",key:"efffak"}],["path",{d:"m14 14 2.5 2.5a1 1 0 1 0 3-3l-3.88-3.88a3 3 0 0 0-4.24 0l-.88.88a1 1 0 1 1-3-3l2.81-2.81a5.79 5.79 0 0 1 7.06-.87l.47.28a2 2 0 0 0 1.42.25L21 4",key:"9pr0kb"}],["path",{d:"m21 3 1 11h-2",key:"1tisrp"}],["path",{d:"M3 3 2 14l6.5 6.5a1 1 0 1 0 3-3",key:"1uvwmv"}],["path",{d:"M3 4h8",key:"1ep09j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cne=re("HardDriveDownload",[["path",{d:"M12 2v8",key:"1q4o3n"}],["path",{d:"m16 6-4 4-4-4",key:"6wukr"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 18h.01",key:"h775k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dne=re("HardDriveUpload",[["path",{d:"m16 6-4-4-4 4",key:"13yo43"}],["path",{d:"M12 2v8",key:"1q4o3n"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M10 18h.01",key:"h775k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z7=re("HardDrive",[["line",{x1:"22",x2:"2",y1:"12",y2:"12",key:"1y58io"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}],["line",{x1:"6",x2:"6.01",y1:"16",y2:"16",key:"sgf278"}],["line",{x1:"10",x2:"10.01",y1:"16",y2:"16",key:"1l4acy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const une=re("HardHat",[["path",{d:"M10 10V5a1 1 0 0 1 1-1h2a1 1 0 0 1 1 1v5",key:"1p9q5i"}],["path",{d:"M14 6a6 6 0 0 1 6 6v3",key:"1hnv84"}],["path",{d:"M4 15v-3a6 6 0 0 1 6-6",key:"9ciidu"}],["rect",{x:"2",y:"15",width:"20",height:"4",rx:"1",key:"g3x8cw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VS=re("Hash",[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hne=re("Haze",[["path",{d:"m5.2 6.2 1.4 1.4",key:"17imol"}],["path",{d:"M2 13h2",key:"13gyu8"}],["path",{d:"M20 13h2",key:"16rner"}],["path",{d:"m17.4 7.6 1.4-1.4",key:"t4xlah"}],["path",{d:"M22 17H2",key:"1gtaj3"}],["path",{d:"M22 21H2",key:"1gy6en"}],["path",{d:"M16 13a4 4 0 0 0-8 0",key:"1dyczq"}],["path",{d:"M12 5V2.5",key:"1vytko"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mne=re("HdmiPort",[["path",{d:"M22 9a1 1 0 0 0-1-1H3a1 1 0 0 0-1 1v4a1 1 0 0 0 1 1h1l2 2h12l2-2h1a1 1 0 0 0 1-1Z",key:"2128wb"}],["path",{d:"M7.5 12h9",key:"1t0ckc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XP=re("Heading1",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"m17 12 3-2v8",key:"1hhhft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JP=re("Heading2",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M21 18h-4c0-4 4-3 4-6 0-1.5-2-2.5-4-1",key:"9jr5yi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q7=re("Heading3",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17.5 10.5c1.7-1 3.5 0 3.5 1.5a2 2 0 0 1-2 2",key:"68ncm8"}],["path",{d:"M17 17.5c2 1.5 4 .3 4-1.5a2 2 0 0 0-2-2",key:"1ejuhz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pne=re("Heading4",[["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17 10v3a1 1 0 0 0 1 1h3",key:"tj5zdr"}],["path",{d:"M21 10v8",key:"1kdml4"}],["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fne=re("Heading5",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["path",{d:"M17 13v-3h4",key:"1nvgqp"}],["path",{d:"M17 17.7c.4.2.8.3 1.3.3 1.5 0 2.7-1.1 2.7-2.5S19.8 13 18.3 13H17",key:"2nebdn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xne=re("Heading6",[["path",{d:"M4 12h8",key:"17cfdx"}],["path",{d:"M4 18V6",key:"1rz3zl"}],["path",{d:"M12 18V6",key:"zqpxq5"}],["circle",{cx:"19",cy:"16",r:"2",key:"15mx69"}],["path",{d:"M20 10c-2 2-3 3.5-3 6",key:"f35dl0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gne=re("Heading",[["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M6 20V4",key:"1w1bmo"}],["path",{d:"M18 20V4",key:"o2hl4u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yne=re("HeadphoneOff",[["path",{d:"M21 14h-1.343",key:"1jdnxi"}],["path",{d:"M9.128 3.47A9 9 0 0 1 21 12v3.343",key:"6kipu2"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.414 20.414A2 2 0 0 1 19 21h-1a2 2 0 0 1-2-2v-3",key:"9x50f4"}],["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 2.636-6.364",key:"1bkxnm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vne=re("Headphones",[["path",{d:"M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3",key:"1xhozi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bne=re("Headset",[["path",{d:"M3 11h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-5Zm0 0a9 9 0 1 1 18 0m0 0v5a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3Z",key:"12oyoe"}],["path",{d:"M21 16v2a4 4 0 0 1-4 4h-5",key:"1x7m43"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ne=re("HeartCrack",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"m12 13-1-1 2-2-3-3 2-2",key:"xjdxli"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NA=re("HeartHandshake",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M12 5 9.04 7.96a2.17 2.17 0 0 0 0 3.08c.82.82 2.13.85 3 .07l2.07-1.9a2.82 2.82 0 0 1 3.79 0l2.96 2.66",key:"4oyue0"}],["path",{d:"m18 15-2-2",key:"60u0ii"}],["path",{d:"m15 18-2-2",key:"6p76be"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wne=re("HeartOff",[["line",{x1:"2",y1:"2",x2:"22",y2:"22",key:"1w4vcy"}],["path",{d:"M16.5 16.5 12 21l-7-7c-1.5-1.45-3-3.2-3-5.5a5.5 5.5 0 0 1 2.14-4.35",key:"3mpagl"}],["path",{d:"M8.76 3.1c1.15.22 2.13.78 3.24 1.9 1.5-1.5 2.74-2 4.5-2A5.5 5.5 0 0 1 22 8.5c0 2.12-1.3 3.78-2.67 5.17",key:"1gh3v3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jne=re("HeartPulse",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}],["path",{d:"M3.22 12H9.5l.5-1 2 4.5 2-7 1.5 3.5h5.27",key:"1uw2ng"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gi=re("Heart",[["path",{d:"M19 14c1.49-1.46 3-3.21 3-5.5A5.5 5.5 0 0 0 16.5 3c-1.76 0-3 .5-4.5 2-1.5-1.5-2.74-2-4.5-2A5.5 5.5 0 0 0 2 8.5c0 2.3 1.5 4.05 3 5.5l7 7Z",key:"c3ymky"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nne=re("Heater",[["path",{d:"M11 8c2-3-2-3 0-6",key:"1ldv5m"}],["path",{d:"M15.5 8c2-3-2-3 0-6",key:"1otqoz"}],["path",{d:"M6 10h.01",key:"1lbq93"}],["path",{d:"M6 14h.01",key:"zudwn7"}],["path",{d:"M10 16v-4",key:"1c25yv"}],["path",{d:"M14 16v-4",key:"1dkbt8"}],["path",{d:"M18 16v-4",key:"1yg9me"}],["path",{d:"M20 6a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h3",key:"1ubg90"}],["path",{d:"M5 20v2",key:"1abpe8"}],["path",{d:"M19 20v2",key:"kqn6ft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kne=re("Hexagon",[["path",{d:"M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z",key:"yt0hxn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sne=re("Highlighter",[["path",{d:"m9 11-6 6v3h9l3-3",key:"1a3l36"}],["path",{d:"m22 12-4.6 4.6a2 2 0 0 1-2.8 0l-5.2-5.2a2 2 0 0 1 0-2.8L14 4",key:"14a9rk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kA=re("History",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M12 7v5l4 2",key:"1fdv2h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cne=re("HopOff",[["path",{d:"M10.82 16.12c1.69.6 3.91.79 5.18.85.28.01.53-.09.7-.27",key:"qyzcap"}],["path",{d:"M11.14 20.57c.52.24 2.44 1.12 4.08 1.37.46.06.86-.25.9-.71.12-1.52-.3-3.43-.5-4.28",key:"y078lb"}],["path",{d:"M16.13 21.05c1.65.63 3.68.84 4.87.91a.9.9 0 0 0 .7-.26",key:"1utre3"}],["path",{d:"M17.99 5.52a20.83 20.83 0 0 1 3.15 4.5.8.8 0 0 1-.68 1.13c-1.17.1-2.5.02-3.9-.25",key:"17o9hm"}],["path",{d:"M20.57 11.14c.24.52 1.12 2.44 1.37 4.08.04.3-.08.59-.31.75",key:"1d1n4p"}],["path",{d:"M4.93 4.93a10 10 0 0 0-.67 13.4c.35.43.96.4 1.17-.12.69-1.71 1.07-5.07 1.07-6.71 1.34.45 3.1.9 4.88.62a.85.85 0 0 0 .48-.24",key:"9uv3tt"}],["path",{d:"M5.52 17.99c1.05.95 2.91 2.42 4.5 3.15a.8.8 0 0 0 1.13-.68c.2-2.34-.33-5.3-1.57-8.28",key:"1292wz"}],["path",{d:"M8.35 2.68a10 10 0 0 1 9.98 1.58c.43.35.4.96-.12 1.17-1.5.6-4.3.98-6.07 1.05",key:"7ozu9p"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tne=re("Hop",[["path",{d:"M10.82 16.12c1.69.6 3.91.79 5.18.85.55.03 1-.42.97-.97-.06-1.27-.26-3.5-.85-5.18",key:"18lxf1"}],["path",{d:"M11.5 6.5c1.64 0 5-.38 6.71-1.07.52-.2.55-.82.12-1.17A10 10 0 0 0 4.26 18.33c.35.43.96.4 1.17-.12.69-1.71 1.07-5.07 1.07-6.71 1.34.45 3.1.9 4.88.62a.88.88 0 0 0 .73-.74c.3-2.14-.15-3.5-.61-4.88",key:"vtfxrw"}],["path",{d:"M15.62 16.95c.2.85.62 2.76.5 4.28a.77.77 0 0 1-.9.7 16.64 16.64 0 0 1-4.08-1.36",key:"13hl71"}],["path",{d:"M16.13 21.05c1.65.63 3.68.84 4.87.91a.9.9 0 0 0 .96-.96 17.68 17.68 0 0 0-.9-4.87",key:"1sl8oj"}],["path",{d:"M16.94 15.62c.86.2 2.77.62 4.29.5a.77.77 0 0 0 .7-.9 16.64 16.64 0 0 0-1.36-4.08",key:"19c6kt"}],["path",{d:"M17.99 5.52a20.82 20.82 0 0 1 3.15 4.5.8.8 0 0 1-.68 1.13c-2.33.2-5.3-.32-8.27-1.57",key:"85ghs3"}],["path",{d:"M4.93 4.93 3 3a.7.7 0 0 1 0-1",key:"x087yj"}],["path",{d:"M9.58 12.18c1.24 2.98 1.77 5.95 1.57 8.28a.8.8 0 0 1-1.13.68 20.82 20.82 0 0 1-4.5-3.15",key:"11xdqo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ene=re("Hospital",[["path",{d:"M12 6v4",key:"16clxf"}],["path",{d:"M14 14h-4",key:"esezmu"}],["path",{d:"M14 18h-4",key:"16mqa2"}],["path",{d:"M14 8h-4",key:"z8ypaz"}],["path",{d:"M18 12h2a2 2 0 0 1 2 2v6a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-9a2 2 0 0 1 2-2h2",key:"b1k337"}],["path",{d:"M18 22V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v18",key:"16g51d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ane=re("Hotel",[["path",{d:"M10 22v-6.57",key:"1wmca3"}],["path",{d:"M12 11h.01",key:"z322tv"}],["path",{d:"M12 7h.01",key:"1ivr5q"}],["path",{d:"M14 15.43V22",key:"1q2vjd"}],["path",{d:"M15 16a5 5 0 0 0-6 0",key:"o9wqvi"}],["path",{d:"M16 11h.01",key:"xkw8gn"}],["path",{d:"M16 7h.01",key:"1kdx03"}],["path",{d:"M8 11h.01",key:"1dfujw"}],["path",{d:"M8 7h.01",key:"1vti4s"}],["rect",{x:"4",y:"2",width:"16",height:"20",rx:"2",key:"1uxh74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mne=re("Hourglass",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M5 2h14",key:"pdyrp9"}],["path",{d:"M17 22v-4.172a2 2 0 0 0-.586-1.414L12 12l-4.414 4.414A2 2 0 0 0 7 17.828V22",key:"1d314k"}],["path",{d:"M7 2v4.172a2 2 0 0 0 .586 1.414L12 12l4.414-4.414A2 2 0 0 0 17 6.172V2",key:"1vvvr6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ine=re("HousePlug",[["path",{d:"M10 12V8.964",key:"1vll13"}],["path",{d:"M14 12V8.964",key:"1x3qvg"}],["path",{d:"M15 12a1 1 0 0 1 1 1v2a2 2 0 0 1-2 2h-4a2 2 0 0 1-2-2v-2a1 1 0 0 1 1-1z",key:"ppykja"}],["path",{d:"M8.5 21H5a2 2 0 0 1-2-2v-9a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2h-5a2 2 0 0 1-2-2v-2",key:"1gvg2z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pne=re("HousePlus",[["path",{d:"M13.22 2.416a2 2 0 0 0-2.511.057l-7 5.999A2 2 0 0 0 3 10v9a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7.354",key:"5phn05"}],["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M15 6h6",key:"1jlkvy"}],["path",{d:"M18 3v6",key:"x1uolp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Or=re("House",[["path",{d:"M15 21v-8a1 1 0 0 0-1-1h-4a1 1 0 0 0-1 1v8",key:"5wwlr5"}],["path",{d:"M3 10a2 2 0 0 1 .709-1.528l7-5.999a2 2 0 0 1 2.582 0l7 5.999A2 2 0 0 1 21 10v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z",key:"1d0kgt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const O5=re("IceCreamBowl",[["path",{d:"M12 17c5 0 8-2.69 8-6H4c0 3.31 3 6 8 6m-4 4h8m-4-3v3M5.14 11a3.5 3.5 0 1 1 6.71 0",key:"1uxfcu"}],["path",{d:"M12.14 11a3.5 3.5 0 1 1 6.71 0",key:"4k3m1s"}],["path",{d:"M15.5 6.5a3.5 3.5 0 1 0-7 0",key:"zmuahr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const F5=re("IceCreamCone",[["path",{d:"m7 11 4.08 10.35a1 1 0 0 0 1.84 0L17 11",key:"1v6356"}],["path",{d:"M17 7A5 5 0 0 0 7 7",key:"151p3v"}],["path",{d:"M17 7a2 2 0 0 1 0 4H7a2 2 0 0 1 0-4",key:"1sdaij"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lne=re("IdCard",[["path",{d:"M16 10h2",key:"8sgtl7"}],["path",{d:"M16 14h2",key:"epxaof"}],["path",{d:"M6.17 15a3 3 0 0 1 5.66 0",key:"n6f512"}],["circle",{cx:"9",cy:"11",r:"2",key:"yxgjnd"}],["rect",{x:"2",y:"5",width:"20",height:"14",rx:"2",key:"qneu4z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dne=re("ImageDown",[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19 3 3v-5.5",key:"9ldu5r"}],["path",{d:"m17 22 3-3",key:"1nkfve"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rne=re("ImageMinus",[["path",{d:"M21 9v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7",key:"m87ecr"}],["line",{x1:"16",x2:"22",y1:"5",y2:"5",key:"ez7e4s"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const One=re("ImageOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M10.41 10.41a2 2 0 1 1-2.83-2.83",key:"1bzlo9"}],["line",{x1:"13.5",x2:"6",y1:"13.5",y2:"21",key:"1q0aeu"}],["line",{x1:"18",x2:"21",y1:"12",y2:"15",key:"5mozeu"}],["path",{d:"M3.59 3.59A1.99 1.99 0 0 0 3 5v14a2 2 0 0 0 2 2h14c.55 0 1.052-.22 1.41-.59",key:"mmje98"}],["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fne=re("ImagePlay",[["path",{d:"m11 16-5 5",key:"j5f7ct"}],["path",{d:"M11 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v6.5",key:"7s81lt"}],["path",{d:"M15.765 22a.5.5 0 0 1-.765-.424V13.38a.5.5 0 0 1 .765-.424l5.878 3.674a1 1 0 0 1 0 1.696z",key:"1omb6s"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ty=re("ImagePlus",[["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}],["path",{d:"M21 11.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7.5",key:"1ue2ih"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zne=re("ImageUp",[["path",{d:"M10.3 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10l-3.1-3.1a2 2 0 0 0-2.814.014L6 21",key:"9csbqa"}],["path",{d:"m14 19.5 3-3 3 3",key:"9vmjn0"}],["path",{d:"M17 22v-5.5",key:"1aa6fl"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bne=re("ImageUpscale",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M17 21h2a2 2 0 0 0 2-2",key:"130fy9"}],["path",{d:"M21 12v3",key:"1wzk3p"}],["path",{d:"m21 3-5 5",key:"1g5oa7"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2",key:"kk3yz1"}],["path",{d:"m5 21 4.144-4.144a1.21 1.21 0 0 1 1.712 0L13 19",key:"fyekpt"}],["path",{d:"M9 3h3",key:"d52fa"}],["rect",{x:"3",y:"11",width:"10",height:"10",rx:"1",key:"1wpmix"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xo=re("Image",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["circle",{cx:"9",cy:"9",r:"2",key:"af1f0g"}],["path",{d:"m21 15-3.086-3.086a2 2 0 0 0-2.828 0L6 21",key:"1xmnt7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ne=re("Images",[["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"m22 13-1.296-1.296a2.41 2.41 0 0 0-3.408 0L11 18",key:"nf6bnh"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["rect",{width:"16",height:"16",x:"6",y:"2",rx:"2",key:"12espp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Une=re("Import",[["path",{d:"M12 3v12",key:"1x0j5s"}],["path",{d:"m8 11 4 4 4-4",key:"1dohi6"}],["path",{d:"M8 5H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-4",key:"1ywtjm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H2=re("Inbox",[["polyline",{points:"22 12 16 12 14 15 10 15 8 12 2 12",key:"o97t9d"}],["path",{d:"M5.45 5.11 2 12v6a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-6l-3.45-6.89A2 2 0 0 0 16.76 4H7.24a2 2 0 0 0-1.79 1.11z",key:"oot6mr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const z5=re("IndentDecrease",[["path",{d:"M21 12H11",key:"wd7e0v"}],["path",{d:"M21 18H11",key:"4wu86t"}],["path",{d:"M21 6H11",key:"6dy1d6"}],["path",{d:"m7 8-4 4 4 4",key:"o5hrat"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const B5=re("IndentIncrease",[["path",{d:"M21 12H11",key:"wd7e0v"}],["path",{d:"M21 18H11",key:"4wu86t"}],["path",{d:"M21 6H11",key:"6dy1d6"}],["path",{d:"m3 8 4 4-4 4",key:"1a3j6y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qne=re("IndianRupee",[["path",{d:"M6 3h12",key:"ggurg9"}],["path",{d:"M6 8h12",key:"6g4wlu"}],["path",{d:"m6 13 8.5 8",key:"u1kupk"}],["path",{d:"M6 13h3",key:"wdp6ag"}],["path",{d:"M9 13c6.667 0 6.667-10 0-10",key:"1nkvk2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vne=re("Infinity",[["path",{d:"M12 12c-2-2.67-4-4-6-4a4 4 0 1 0 0 8c2 0 4-1.33 6-4Zm0 0c2 2.67 4 4 6 4a4 4 0 0 0 0-8c-2 0-4 1.33-6 4Z",key:"1z0uae"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fw=re("Info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hne=re("InspectionPanel",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7h.01",key:"7u93v4"}],["path",{d:"M17 7h.01",key:"14a9sn"}],["path",{d:"M7 17h.01",key:"19xn7k"}],["path",{d:"M17 17h.01",key:"1sd3ek"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ou=re("Instagram",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"5",ry:"5",key:"2e1cvw"}],["path",{d:"M16 11.37A4 4 0 1 1 12.63 8 4 4 0 0 1 16 11.37z",key:"9exkf1"}],["line",{x1:"17.5",x2:"17.51",y1:"6.5",y2:"6.5",key:"r4j83e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HS=re("Italic",[["line",{x1:"19",x2:"10",y1:"4",y2:"4",key:"15jd3p"}],["line",{x1:"14",x2:"5",y1:"20",y2:"20",key:"bu0au3"}],["line",{x1:"15",x2:"9",y1:"4",y2:"20",key:"uljnxc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gne=re("IterationCcw",[["path",{d:"M20 10c0-4.4-3.6-8-8-8s-8 3.6-8 8 3.6 8 8 8h8",key:"4znkd0"}],["polyline",{points:"16 14 20 18 16 22",key:"11njsm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wne=re("IterationCw",[["path",{d:"M4 10c0-4.4 3.6-8 8-8s8 3.6 8 8-3.6 8-8 8H4",key:"tuf4su"}],["polyline",{points:"8 22 4 18 8 14",key:"evkj9s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kne=re("JapaneseYen",[["path",{d:"M12 9.5V21m0-11.5L6 3m6 6.5L18 3",key:"2ej80x"}],["path",{d:"M6 15h12",key:"1hwgt5"}],["path",{d:"M6 11h12",key:"wf4gp6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yne=re("Joystick",[["path",{d:"M21 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-2Z",key:"jg2n2t"}],["path",{d:"M6 15v-2",key:"gd6mvg"}],["path",{d:"M12 15V9",key:"8c7uyn"}],["circle",{cx:"12",cy:"6",r:"3",key:"1gm2ql"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G2=re("Kanban",[["path",{d:"M6 5v11",key:"mdvv1e"}],["path",{d:"M12 5v6",key:"14ar3b"}],["path",{d:"M18 5v14",key:"7ji314"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const SA=re("KeyRound",[["path",{d:"M2.586 17.414A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814a6.5 6.5 0 1 0-4-4z",key:"1s6t7t"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zne=re("KeySquare",[["path",{d:"M12.4 2.7a2.5 2.5 0 0 1 3.4 0l5.5 5.5a2.5 2.5 0 0 1 0 3.4l-3.7 3.7a2.5 2.5 0 0 1-3.4 0L8.7 9.8a2.5 2.5 0 0 1 0-3.4z",key:"165ttr"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"m9.4 10.6-6.814 6.814A2 2 0 0 0 2 18.828V21a1 1 0 0 0 1 1h3a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h1a1 1 0 0 0 1-1v-1a1 1 0 0 1 1-1h.172a2 2 0 0 0 1.414-.586l.814-.814",key:"1ubxi2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ug=re("Key",[["path",{d:"m15.5 7.5 2.3 2.3a1 1 0 0 0 1.4 0l2.1-2.1a1 1 0 0 0 0-1.4L19 4",key:"g0fldk"}],["path",{d:"m21 2-9.6 9.6",key:"1j0ho8"}],["circle",{cx:"7.5",cy:"15.5",r:"5.5",key:"yqb3hr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qne=re("KeyboardMusic",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M6 8h4",key:"utf9t1"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"M6 12v4",key:"dy92yo"}],["path",{d:"M10 12v4",key:"1fxnav"}],["path",{d:"M14 12v4",key:"1hft58"}],["path",{d:"M18 12v4",key:"tjjnbz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xne=re("KeyboardOff",[["path",{d:"M 20 4 A2 2 0 0 1 22 6",key:"1g1fkt"}],["path",{d:"M 22 6 L 22 16.41",key:"1qjg3w"}],["path",{d:"M 7 16 L 16 16",key:"n0yqwb"}],["path",{d:"M 9.69 4 L 20 4",key:"kbpcgx"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20 20H4a2 2 0 0 1-2-2V6a2 2 0 0 1 2-2",key:"s23sx2"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M8 12h.01",key:"czm47f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jne=re("Keyboard",[["path",{d:"M10 8h.01",key:"1r9ogq"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M14 8h.01",key:"1primd"}],["path",{d:"M16 12h.01",key:"1l6xoz"}],["path",{d:"M18 8h.01",key:"emo2bl"}],["path",{d:"M6 8h.01",key:"x9i8wu"}],["path",{d:"M7 16h10",key:"wp8him"}],["path",{d:"M8 12h.01",key:"czm47f"}],["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ere=re("LampCeiling",[["path",{d:"M12 2v5",key:"nd4vlx"}],["path",{d:"M6 7h12l4 9H2l4-9Z",key:"123d64"}],["path",{d:"M9.17 16a3 3 0 1 0 5.66 0",key:"1061mw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tre=re("LampDesk",[["path",{d:"m14 5-3 3 2 7 8-8-7-2Z",key:"1b0msb"}],["path",{d:"m14 5-3 3-3-3 3-3 3 3Z",key:"1uemms"}],["path",{d:"M9.5 6.5 4 12l3 6",key:"1bx08v"}],["path",{d:"M3 22v-2c0-1.1.9-2 2-2h4a2 2 0 0 1 2 2v2H3Z",key:"wap775"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sre=re("LampFloor",[["path",{d:"M9 2h6l3 7H6l3-7Z",key:"wcx6mj"}],["path",{d:"M12 9v13",key:"3n1su1"}],["path",{d:"M9 22h6",key:"1rlq3v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nre=re("LampWallDown",[["path",{d:"M11 13h6l3 7H8l3-7Z",key:"9n3qlo"}],["path",{d:"M14 13V8a2 2 0 0 0-2-2H8",key:"1hu4hb"}],["path",{d:"M4 9h2a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H4v6Z",key:"s053bc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rre=re("LampWallUp",[["path",{d:"M11 4h6l3 7H8l3-7Z",key:"11x1ee"}],["path",{d:"M14 11v5a2 2 0 0 1-2 2H8",key:"eutp5o"}],["path",{d:"M4 15h2a2 2 0 0 1 2 2v2a2 2 0 0 1-2 2H4v-6Z",key:"1iuthr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const are=re("Lamp",[["path",{d:"M8 2h8l4 10H4L8 2Z",key:"9dma5w"}],["path",{d:"M12 12v6",key:"3ahymv"}],["path",{d:"M8 22v-2c0-1.1.9-2 2-2h4a2 2 0 0 1 2 2v2H8Z",key:"mwf4oh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ire=re("LandPlot",[["path",{d:"m12 8 6-3-6-3v10",key:"mvpnpy"}],["path",{d:"m8 11.99-5.5 3.14a1 1 0 0 0 0 1.74l8.5 4.86a2 2 0 0 0 2 0l8.5-4.86a1 1 0 0 0 0-1.74L16 12",key:"ek95tt"}],["path",{d:"m6.49 12.85 11.02 6.3",key:"1kt42w"}],["path",{d:"M17.51 12.85 6.5 19.15",key:"v55bdg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ore=re("Landmark",[["line",{x1:"3",x2:"21",y1:"22",y2:"22",key:"j8o0r"}],["line",{x1:"6",x2:"6",y1:"18",y2:"11",key:"10tf0k"}],["line",{x1:"10",x2:"10",y1:"18",y2:"11",key:"54lgf6"}],["line",{x1:"14",x2:"14",y1:"18",y2:"11",key:"380y"}],["line",{x1:"18",x2:"18",y1:"18",y2:"11",key:"1kevvc"}],["polygon",{points:"12 2 20 7 4 7",key:"jkujk7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lre=re("Languages",[["path",{d:"m5 8 6 6",key:"1wu5hv"}],["path",{d:"m4 14 6-6 2-3",key:"1k1g8d"}],["path",{d:"M2 5h12",key:"or177f"}],["path",{d:"M7 2h1",key:"1t2jsx"}],["path",{d:"m22 22-5-10-5 10",key:"don7ne"}],["path",{d:"M14 18h6",key:"1m8k6r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cre=re("LaptopMinimalCheck",[["path",{d:"M2 20h20",key:"owomy5"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}],["rect",{x:"3",y:"4",width:"18",height:"12",rx:"2",key:"8ur36m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $5=re("LaptopMinimal",[["rect",{width:"18",height:"12",x:"3",y:"4",rx:"2",ry:"2",key:"1qhy41"}],["line",{x1:"2",x2:"22",y1:"20",y2:"20",key:"ni3hll"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dre=re("Laptop",[["path",{d:"M20 16V7a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v9m16 0H4m16 0 1.28 2.55a1 1 0 0 1-.9 1.45H3.62a1 1 0 0 1-.9-1.45L4 16",key:"tarvll"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ure=re("LassoSelect",[["path",{d:"M7 22a5 5 0 0 1-2-4",key:"umushi"}],["path",{d:"M7 16.93c.96.43 1.96.74 2.99.91",key:"ybbtv3"}],["path",{d:"M3.34 14A6.8 6.8 0 0 1 2 10c0-4.42 4.48-8 10-8s10 3.58 10 8a7.19 7.19 0 0 1-.33 2",key:"gt5e1w"}],["path",{d:"M5 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",key:"bq3ynw"}],["path",{d:"M14.33 22h-.09a.35.35 0 0 1-.24-.32v-10a.34.34 0 0 1 .33-.34c.08 0 .15.03.21.08l7.34 6a.33.33 0 0 1-.21.59h-4.49l-2.57 3.85a.35.35 0 0 1-.28.14z",key:"72q637"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hre=re("Lasso",[["path",{d:"M7 22a5 5 0 0 1-2-4",key:"umushi"}],["path",{d:"M3.3 14A6.8 6.8 0 0 1 2 10c0-4.4 4.5-8 10-8s10 3.6 10 8-4.5 8-10 8a12 12 0 0 1-5-1",key:"146dds"}],["path",{d:"M5 18a2 2 0 1 0 0-4 2 2 0 0 0 0 4z",key:"bq3ynw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mre=re("Laugh",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M18 13a6 6 0 0 1-6 5 6 6 0 0 1-6-5h12Z",key:"b2q4dd"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pre=re("Layers2",[["path",{d:"m16.02 12 5.48 3.13a1 1 0 0 1 0 1.74L13 21.74a2 2 0 0 1-2 0l-8.5-4.87a1 1 0 0 1 0-1.74L7.98 12",key:"1cuww1"}],["path",{d:"M13 13.74a2 2 0 0 1-2 0L2.5 8.87a1 1 0 0 1 0-1.74L11 2.26a2 2 0 0 1 2 0l8.5 4.87a1 1 0 0 1 0 1.74Z",key:"pdlvxu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fre=re("Layers3",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m6.08 9.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59",key:"1e5n1m"}],["path",{d:"m6.08 14.5-3.5 1.6a1 1 0 0 0 0 1.81l8.6 3.91a2 2 0 0 0 1.65 0l8.58-3.9a1 1 0 0 0 0-1.83l-3.5-1.59",key:"1iwflc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X7=re("Layers",[["path",{d:"m12.83 2.18a2 2 0 0 0-1.66 0L2.6 6.08a1 1 0 0 0 0 1.83l8.58 3.91a2 2 0 0 0 1.66 0l8.58-3.9a1 1 0 0 0 0-1.83Z",key:"8b97xw"}],["path",{d:"m22 17.65-9.17 4.16a2 2 0 0 1-1.66 0L2 17.65",key:"dd6zsq"}],["path",{d:"m22 12.65-9.17 4.16a2 2 0 0 1-1.66 0L2 12.65",key:"ep9fru"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GS=re("LayoutDashboard",[["rect",{width:"7",height:"9",x:"3",y:"3",rx:"1",key:"10lvy0"}],["rect",{width:"7",height:"5",x:"14",y:"3",rx:"1",key:"16une8"}],["rect",{width:"7",height:"9",x:"14",y:"12",rx:"1",key:"1hutg5"}],["rect",{width:"7",height:"5",x:"3",y:"16",rx:"1",key:"ldoo1y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ff=re("LayoutGrid",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xre=re("LayoutList",[["rect",{width:"7",height:"7",x:"3",y:"3",rx:"1",key:"1g98yp"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["path",{d:"M14 4h7",key:"3xa0d5"}],["path",{d:"M14 9h7",key:"1icrd9"}],["path",{d:"M14 15h7",key:"1mj8o2"}],["path",{d:"M14 20h7",key:"11slyb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gre=re("LayoutPanelLeft",[["rect",{width:"7",height:"18",x:"3",y:"3",rx:"1",key:"2obqm"}],["rect",{width:"7",height:"7",x:"14",y:"3",rx:"1",key:"6d4xhi"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yre=re("LayoutPanelTop",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"7",height:"7",x:"3",y:"14",rx:"1",key:"1bb6yr"}],["rect",{width:"7",height:"7",x:"14",y:"14",rx:"1",key:"nxv5o0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WS=re("LayoutTemplate",[["rect",{width:"18",height:"7",x:"3",y:"3",rx:"1",key:"f1a2em"}],["rect",{width:"9",height:"7",x:"3",y:"14",rx:"1",key:"jqznyg"}],["rect",{width:"5",height:"7",x:"16",y:"14",rx:"1",key:"q5h2i8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vre=re("Leaf",[["path",{d:"M11 20A7 7 0 0 1 9.8 6.1C15.5 5 17 4.48 19 2c1 2 2 4.18 2 8 0 5.5-4.78 10-10 10Z",key:"nnexq3"}],["path",{d:"M2 21c0-3 1.85-5.36 5.08-6C9.5 14.52 12 13 13 12",key:"mt58a7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bre=re("LeafyGreen",[["path",{d:"M2 22c1.25-.987 2.27-1.975 3.9-2.2a5.56 5.56 0 0 1 3.8 1.5 4 4 0 0 0 6.187-2.353 3.5 3.5 0 0 0 3.69-5.116A3.5 3.5 0 0 0 20.95 8 3.5 3.5 0 1 0 16 3.05a3.5 3.5 0 0 0-5.831 1.373 3.5 3.5 0 0 0-5.116 3.69 4 4 0 0 0-2.348 6.155C3.499 15.42 4.409 16.712 4.2 18.1 3.926 19.743 3.014 20.732 2 22",key:"1134nt"}],["path",{d:"M2 22 17 7",key:"1q7jp2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _re=re("Lectern",[["path",{d:"M16 12h3a2 2 0 0 0 1.902-1.38l1.056-3.333A1 1 0 0 0 21 6H3a1 1 0 0 0-.958 1.287l1.056 3.334A2 2 0 0 0 5 12h3",key:"13jjxg"}],["path",{d:"M18 6V3a1 1 0 0 0-1-1h-3",key:"1550fe"}],["rect",{width:"8",height:"12",x:"8",y:"10",rx:"1",key:"qmu8b6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wre=re("LetterText",[["path",{d:"M15 12h6",key:"upa0zy"}],["path",{d:"M15 6h6",key:"1jlkvy"}],["path",{d:"m3 13 3.553-7.724a.5.5 0 0 1 .894 0L11 13",key:"blevx4"}],["path",{d:"M3 18h18",key:"1h113x"}],["path",{d:"M4 11h6",key:"olkgv1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jre=re("LibraryBig",[["rect",{width:"8",height:"18",x:"3",y:"3",rx:"1",key:"oynpb5"}],["path",{d:"M7 3v18",key:"bbkbws"}],["path",{d:"M20.4 18.9c.2.5-.1 1.1-.6 1.3l-1.9.7c-.5.2-1.1-.1-1.3-.6L11.1 5.1c-.2-.5.1-1.1.6-1.3l1.9-.7c.5-.2 1.1.1 1.3.6Z",key:"1qboyk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qg=re("Library",[["path",{d:"m16 6 4 14",key:"ji33uf"}],["path",{d:"M12 6v14",key:"1n7gus"}],["path",{d:"M8 8v12",key:"1gg7y9"}],["path",{d:"M4 4v16",key:"6qkkli"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eL=re("LifeBuoy",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"m4.93 4.93 4.24 4.24",key:"1ymg45"}],["path",{d:"m14.83 9.17 4.24-4.24",key:"1cb5xl"}],["path",{d:"m14.83 14.83 4.24 4.24",key:"q42g0n"}],["path",{d:"m9.17 14.83-4.24 4.24",key:"bqpfvv"}],["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nre=re("Ligature",[["path",{d:"M8 20V8c0-2.2 1.8-4 4-4 1.5 0 2.8.8 3.5 2",key:"1rtphz"}],["path",{d:"M6 12h4",key:"a4o3ry"}],["path",{d:"M14 12h2v8",key:"c1fccl"}],["path",{d:"M6 20h4",key:"1i6q5t"}],["path",{d:"M14 20h4",key:"lzx1xo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kre=re("LightbulbOff",[["path",{d:"M16.8 11.2c.8-.9 1.2-2 1.2-3.2a6 6 0 0 0-9.3-5",key:"1fkcox"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M6.3 6.3a4.67 4.67 0 0 0 1.2 5.2c.7.7 1.3 1.5 1.5 2.5",key:"10m8kw"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W2=re("Lightbulb",[["path",{d:"M15 14c.2-1 .7-1.7 1.5-2.5 1-.9 1.5-2.2 1.5-3.5A6 6 0 0 0 6 8c0 1 .2 2.2 1.5 3.5.7.7 1.3 1.5 1.5 2.5",key:"1gvzjb"}],["path",{d:"M9 18h6",key:"x1upvd"}],["path",{d:"M10 22h4",key:"ceow96"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sre=re("Link2Off",[["path",{d:"M9 17H7A5 5 0 0 1 7 7",key:"10o201"}],["path",{d:"M15 7h2a5 5 0 0 1 4 8",key:"1d3206"}],["line",{x1:"8",x2:"12",y1:"12",y2:"12",key:"rvw6j4"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tl=re("Link2",[["path",{d:"M9 17H7A5 5 0 0 1 7 7h2",key:"8i5ue5"}],["path",{d:"M15 7h2a5 5 0 1 1 0 10h-2",key:"1b9ql8"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yo=re("Link",[["path",{d:"M10 13a5 5 0 0 0 7.54.54l3-3a5 5 0 0 0-7.07-7.07l-1.72 1.71",key:"1cjeqo"}],["path",{d:"M14 11a5 5 0 0 0-7.54-.54l-3 3a5 5 0 0 0 7.07 7.07l1.71-1.71",key:"19qd67"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xf=re("Linkedin",[["path",{d:"M16 8a6 6 0 0 1 6 6v7h-4v-7a2 2 0 0 0-2-2 2 2 0 0 0-2 2v7h-4v-7a6 6 0 0 1 6-6z",key:"c2jq9f"}],["rect",{width:"4",height:"12",x:"2",y:"9",key:"mk3on5"}],["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cre=re("ListCheck",[["path",{d:"M11 18H3",key:"n3j2dh"}],["path",{d:"m15 18 2 2 4-4",key:"1szwhi"}],["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lu=re("ListChecks",[["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"m3 7 2 2 4-4",key:"1obspn"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tre=re("ListCollapse",[["path",{d:"m3 10 2.5-2.5L3 5",key:"i6eama"}],["path",{d:"m3 19 2.5-2.5L3 14",key:"w2gmor"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ere=re("ListEnd",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M10 18H3",key:"13769t"}],["path",{d:"M21 6v10a2 2 0 0 1-2 2h-5",key:"ilrcs8"}],["path",{d:"m16 16-2 2 2 2",key:"kkc6pm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J7=re("ListFilter",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M10 18h4",key:"1ulq68"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Are=re("ListMinus",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mre=re("ListMusic",[["path",{d:"M21 15V6",key:"h1cx4g"}],["path",{d:"M18.5 18a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5Z",key:"8saifv"}],["path",{d:"M12 12H3",key:"18klou"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M12 18H3",key:"11ftsu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ub=re("ListOrdered",[["path",{d:"M10 12h11",key:"6m4ad9"}],["path",{d:"M10 18h11",key:"11hvi2"}],["path",{d:"M10 6h11",key:"c7qv1k"}],["path",{d:"M4 10h2",key:"16xx2s"}],["path",{d:"M4 6h1v4",key:"cnovpq"}],["path",{d:"M6 18H4c0-1 2-2 2-3s-1-1.5-2-1",key:"m9a95d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ire=re("ListPlus",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M18 9v6",key:"1twb98"}],["path",{d:"M21 12h-6",key:"bt1uis"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pre=re("ListRestart",[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M7 12H3",key:"13ou7f"}],["path",{d:"M7 18H3",key:"1sijw9"}],["path",{d:"M12 18a5 5 0 0 0 9-3 4.5 4.5 0 0 0-4.5-4.5c-1.33 0-2.54.54-3.41 1.41L11 14",key:"qth677"}],["path",{d:"M11 10v4h4",key:"172dkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lre=re("ListStart",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M10 6H3",key:"lf8lx7"}],["path",{d:"M21 18V8a2 2 0 0 0-2-2h-5",key:"1hghli"}],["path",{d:"m16 8-2-2 2-2",key:"160uvd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dre=re("ListTodo",[["rect",{x:"3",y:"5",width:"6",height:"6",rx:"1",key:"1defrl"}],["path",{d:"m3 17 2 2 4-4",key:"1jhpwq"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rre=re("ListTree",[["path",{d:"M21 12h-8",key:"1bmf0i"}],["path",{d:"M21 6H8",key:"1pqkrb"}],["path",{d:"M21 18h-8",key:"1tm79t"}],["path",{d:"M3 6v4c0 1.1.9 2 2 2h3",key:"1ywdgy"}],["path",{d:"M3 10v6c0 1.1.9 2 2 2h3",key:"2wc746"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ore=re("ListVideo",[["path",{d:"M12 12H3",key:"18klou"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M12 18H3",key:"11ftsu"}],["path",{d:"m16 12 5 3-5 3v-6Z",key:"zpskkp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fre=re("ListX",[["path",{d:"M11 12H3",key:"51ecnj"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"m19 10-4 4",key:"1tz659"}],["path",{d:"m15 10 4 4",key:"1n7nei"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sp=re("List",[["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M3 18h.01",key:"1tta3j"}],["path",{d:"M3 6h.01",key:"1rqtza"}],["path",{d:"M8 12h13",key:"1za7za"}],["path",{d:"M8 18h13",key:"1lx6n3"}],["path",{d:"M8 6h13",key:"ik3vkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rs=re("LoaderCircle",[["path",{d:"M21 12a9 9 0 1 1-6.219-8.56",key:"13zald"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zre=re("LoaderPinwheel",[["path",{d:"M22 12a1 1 0 0 1-10 0 1 1 0 0 0-10 0",key:"1lzz15"}],["path",{d:"M7 20.7a1 1 0 1 1 5-8.7 1 1 0 1 0 5-8.6",key:"1gnrpi"}],["path",{d:"M7 3.3a1 1 0 1 1 5 8.6 1 1 0 1 0 5 8.6",key:"u9yy5q"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bre=re("Loader",[["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m16.2 7.8 2.9-2.9",key:"r700ao"}],["path",{d:"M18 12h4",key:"wj9ykh"}],["path",{d:"m16.2 16.2 2.9 2.9",key:"1bxg5t"}],["path",{d:"M12 18v4",key:"jadmvz"}],["path",{d:"m4.9 19.1 2.9-2.9",key:"bwix9q"}],["path",{d:"M2 12h4",key:"j09sii"}],["path",{d:"m4.9 4.9 2.9 2.9",key:"giyufr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $re=re("LocateFixed",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["circle",{cx:"12",cy:"12",r:"7",key:"fim9np"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ure=re("LocateOff",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["path",{d:"M7.11 7.11C5.83 8.39 5 10.1 5 12c0 3.87 3.13 7 7 7 1.9 0 3.61-.83 4.89-2.11",key:"1oh7ia"}],["path",{d:"M18.71 13.96c.19-.63.29-1.29.29-1.96 0-3.87-3.13-7-7-7-.67 0-1.33.1-1.96.29",key:"3qdecy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tL=re("Locate",[["line",{x1:"2",x2:"5",y1:"12",y2:"12",key:"bvdh0s"}],["line",{x1:"19",x2:"22",y1:"12",y2:"12",key:"1tbv5k"}],["line",{x1:"12",x2:"12",y1:"2",y2:"5",key:"11lu5j"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}],["circle",{cx:"12",cy:"12",r:"7",key:"fim9np"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const U5=re("LockKeyholeOpen",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{width:"18",height:"12",x:"3",y:"10",rx:"2",key:"l0tzu3"}],["path",{d:"M7 10V7a5 5 0 0 1 9.33-2.5",key:"car5b7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qre=re("LockKeyhole",[["circle",{cx:"12",cy:"16",r:"1",key:"1au0dj"}],["rect",{x:"3",y:"10",width:"18",height:"12",rx:"2",key:"6s8ecr"}],["path",{d:"M7 10V7a5 5 0 0 1 10 0v3",key:"1pqi11"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q5=re("LockOpen",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 9.9-1",key:"1mm8w8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gc=re("Lock",[["rect",{width:"18",height:"11",x:"3",y:"11",rx:"2",ry:"2",key:"1w4ew1"}],["path",{d:"M7 11V7a5 5 0 0 1 10 0v4",key:"fwvmzm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CA=re("LogIn",[["path",{d:"M15 3h4a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2h-4",key:"u53s6r"}],["polyline",{points:"10 17 15 12 10 7",key:"1ail0h"}],["line",{x1:"15",x2:"3",y1:"12",y2:"12",key:"v6grx8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TA=re("LogOut",[["path",{d:"M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4",key:"1uf3rs"}],["polyline",{points:"16 17 21 12 16 7",key:"1gabdz"}],["line",{x1:"21",x2:"9",y1:"12",y2:"12",key:"1uyos4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vre=re("Logs",[["path",{d:"M13 12h8",key:"h98zly"}],["path",{d:"M13 18h8",key:"oe0vm4"}],["path",{d:"M13 6h8",key:"15sg57"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M3 18h1",key:"1eiwyy"}],["path",{d:"M3 6h1",key:"rgxa97"}],["path",{d:"M8 12h1",key:"1con00"}],["path",{d:"M8 18h1",key:"13wk12"}],["path",{d:"M8 6h1",key:"tn6mkg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hre=re("Lollipop",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}],["path",{d:"M11 11a2 2 0 0 0 4 0 4 4 0 0 0-8 0 6 6 0 0 0 12 0",key:"107gwy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gre=re("Luggage",[["path",{d:"M6 20a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2",key:"1m57jg"}],["path",{d:"M8 18V4a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v14",key:"1l99gc"}],["path",{d:"M10 20h4",key:"ni2waw"}],["circle",{cx:"16",cy:"20",r:"2",key:"1vifvg"}],["circle",{cx:"8",cy:"20",r:"2",key:"ckkr5m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wre=re("Magnet",[["path",{d:"m6 15-4-4 6.75-6.77a7.79 7.79 0 0 1 11 11L13 22l-4-4 6.39-6.36a2.14 2.14 0 0 0-3-3L6 15",key:"1i3lhw"}],["path",{d:"m5 8 4 4",key:"j6kj7e"}],["path",{d:"m12 15 4 4",key:"lnac28"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sL=re("MailCheck",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kre=re("MailMinus",[["path",{d:"M22 15V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"fuxbkv"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M16 19h6",key:"xwg31i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nL=re("MailOpen",[["path",{d:"M21.2 8.4c.5.38.8.97.8 1.6v10a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V10a2 2 0 0 1 .8-1.6l8-6a2 2 0 0 1 2.4 0l8 6Z",key:"1jhwl8"}],["path",{d:"m22 10-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 10",key:"1qfld7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e9=re("MailPlus",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h8",key:"12jkf8"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M16 19h6",key:"xwg31i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yre=re("MailQuestion",[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M18 15.28c.2-.4.5-.8.9-1a2.1 2.1 0 0 1 2.6.4c.3.4.5.8.5 1.3 0 1.3-2 2-2 2",key:"7z9rxb"}],["path",{d:"M20 22v.01",key:"12bgn6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zre=re("MailSearch",[["path",{d:"M22 12.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h7.5",key:"w80f2v"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M18 21a3 3 0 1 0 0-6 3 3 0 0 0 0 6Z",key:"8lzu5m"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m22 22-1.5-1.5",key:"1x83k4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qre=re("MailWarning",[["path",{d:"M22 10.5V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h12.5",key:"e61zoh"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"M20 14v4",key:"1hm744"}],["path",{d:"M20 22v.01",key:"12bgn6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rL=re("MailX",[["path",{d:"M22 13V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v12c0 1.1.9 2 2 2h9",key:"1j9vog"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}],["path",{d:"m17 17 4 4",key:"1b3523"}],["path",{d:"m21 17-4 4",key:"uinynz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gs=re("Mail",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7",key:"1ocrg3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xre=re("Mailbox",[["path",{d:"M22 17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V9.5C2 7 4 5 6.5 5H18c2.2 0 4 1.8 4 4v8Z",key:"1lbycx"}],["polyline",{points:"15,9 18,9 18,11",key:"1pm9c0"}],["path",{d:"M6.5 5C9 5 11 7 11 9.5V17a2 2 0 0 1-2 2",key:"15i455"}],["line",{x1:"6",x2:"7",y1:"10",y2:"10",key:"1e2scm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jre=re("Mails",[["rect",{width:"16",height:"13",x:"6",y:"4",rx:"2",key:"1drq3f"}],["path",{d:"m22 7-7.1 3.78c-.57.3-1.23.3-1.8 0L6 7",key:"xn252p"}],["path",{d:"M2 8v11c0 1.1.9 2 2 2h14",key:"n13cji"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eae=re("MapPinCheckInside",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tae=re("MapPinCheck",[["path",{d:"M19.43 12.935c.357-.967.57-1.955.57-2.935a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32.197 32.197 0 0 0 .813-.728",key:"1dq61d"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"m16 18 2 2 4-4",key:"1mkfmb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sae=re("MapPinHouse",[["path",{d:"M15 22a1 1 0 0 1-1-1v-4a1 1 0 0 1 .445-.832l3-2a1 1 0 0 1 1.11 0l3 2A1 1 0 0 1 22 17v4a1 1 0 0 1-1 1z",key:"1p1rcz"}],["path",{d:"M18 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 .601.2",key:"mcbcs9"}],["path",{d:"M18 22v-3",key:"1t1ugv"}],["circle",{cx:"10",cy:"10",r:"3",key:"1ns7v1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nae=re("MapPinMinusInside",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rae=re("MapPinMinus",[["path",{d:"M18.977 14C19.6 12.701 20 11.343 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32 32 0 0 0 .824-.738",key:"11uxia"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M16 18h6",key:"987eiv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aae=re("MapPinOff",[["path",{d:"M12.75 7.09a3 3 0 0 1 2.16 2.16",key:"1d4wjd"}],["path",{d:"M17.072 17.072c-1.634 2.17-3.527 3.912-4.471 4.727a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 1.432-4.568",key:"12yil7"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M8.475 2.818A8 8 0 0 1 20 10c0 1.183-.31 2.377-.81 3.533",key:"lhrkcz"}],["path",{d:"M9.13 9.13a3 3 0 0 0 3.74 3.74",key:"13wojd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iae=re("MapPinPlusInside",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oae=re("MapPinPlus",[["path",{d:"M19.914 11.105A7.298 7.298 0 0 0 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 32 32 0 0 0 .824-.738",key:"fcdtly"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M16 18h6",key:"987eiv"}],["path",{d:"M19 15v6",key:"10aioa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lae=re("MapPinXInside",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cae=re("MapPinX",[["path",{d:"M19.752 11.901A7.78 7.78 0 0 0 20 10a8 8 0 0 0-16 0c0 4.993 5.539 10.193 7.399 11.799a1 1 0 0 0 1.202 0 19 19 0 0 0 .09-.077",key:"y0ewhp"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"m21.5 15.5-5 5",key:"11iqnx"}],["path",{d:"m21.5 20.5-5-5",key:"1bylgx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ka=re("MapPin",[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dae=re("MapPinned",[["path",{d:"M18 8c0 3.613-3.869 7.429-5.393 8.795a1 1 0 0 1-1.214 0C9.87 15.429 6 11.613 6 8a6 6 0 0 1 12 0",key:"11u0oz"}],["circle",{cx:"12",cy:"8",r:"2",key:"1822b1"}],["path",{d:"M8.714 14h-3.71a1 1 0 0 0-.948.683l-2.004 6A1 1 0 0 0 3 22h18a1 1 0 0 0 .948-1.316l-2-6a1 1 0 0 0-.949-.684h-3.712",key:"q8zwxj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const EA=re("Map",[["path",{d:"M14.106 5.553a2 2 0 0 0 1.788 0l3.659-1.83A1 1 0 0 1 21 4.619v12.764a1 1 0 0 1-.553.894l-4.553 2.277a2 2 0 0 1-1.788 0l-4.212-2.106a2 2 0 0 0-1.788 0l-3.659 1.83A1 1 0 0 1 3 19.381V6.618a1 1 0 0 1 .553-.894l4.553-2.277a2 2 0 0 1 1.788 0z",key:"169xi5"}],["path",{d:"M15 5.764v15",key:"1pn4in"}],["path",{d:"M9 3.236v15",key:"1uimfh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uae=re("Martini",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M12 11v11",key:"ur9y6a"}],["path",{d:"m19 3-7 8-7-8Z",key:"1sgpiw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t9=re("Maximize2",[["polyline",{points:"15 3 21 3 21 9",key:"mznyad"}],["polyline",{points:"9 21 3 21 3 15",key:"1avn1i"}],["line",{x1:"21",x2:"14",y1:"3",y2:"10",key:"ota7mn"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AA=re("Maximize",[["path",{d:"M8 3H5a2 2 0 0 0-2 2v3",key:"1dcmit"}],["path",{d:"M21 8V5a2 2 0 0 0-2-2h-3",key:"1e4gt3"}],["path",{d:"M3 16v3a2 2 0 0 0 2 2h3",key:"wsl5sc"}],["path",{d:"M16 21h3a2 2 0 0 0 2-2v-3",key:"18trek"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K2=re("Medal",[["path",{d:"M7.21 15 2.66 7.14a2 2 0 0 1 .13-2.2L4.4 2.8A2 2 0 0 1 6 2h12a2 2 0 0 1 1.6.8l1.6 2.14a2 2 0 0 1 .14 2.2L16.79 15",key:"143lza"}],["path",{d:"M11 12 5.12 2.2",key:"qhuxz6"}],["path",{d:"m13 12 5.88-9.8",key:"hbye0f"}],["path",{d:"M8 7h8",key:"i86dvs"}],["circle",{cx:"12",cy:"17",r:"5",key:"qbz8iq"}],["path",{d:"M12 18v-2h-.5",key:"fawc4q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hae=re("MegaphoneOff",[["path",{d:"M9.26 9.26 3 11v3l14.14 3.14",key:"3429n"}],["path",{d:"M21 15.34V6l-7.31 2.03",key:"4o1dh8"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zd=re("Megaphone",[["path",{d:"m3 11 18-5v12L3 14v-3z",key:"n962bs"}],["path",{d:"M11.6 16.8a3 3 0 1 1-5.8-1.6",key:"1yl0tm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mae=re("Meh",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["line",{x1:"8",x2:"16",y1:"15",y2:"15",key:"1xb1d9"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pae=re("MemoryStick",[["path",{d:"M6 19v-3",key:"1nvgqn"}],["path",{d:"M10 19v-3",key:"iu8nkm"}],["path",{d:"M14 19v-3",key:"kcehxu"}],["path",{d:"M18 19v-3",key:"1vh91z"}],["path",{d:"M8 11V9",key:"63erz4"}],["path",{d:"M16 11V9",key:"fru6f3"}],["path",{d:"M12 11V9",key:"ha00sb"}],["path",{d:"M2 15h20",key:"16ne18"}],["path",{d:"M2 7a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v1.1a2 2 0 0 0 0 3.837V17a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-5.1a2 2 0 0 0 0-3.837Z",key:"lhddv3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KS=re("Menu",[["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}],["line",{x1:"4",x2:"20",y1:"6",y2:"6",key:"1owob3"}],["line",{x1:"4",x2:"20",y1:"18",y2:"18",key:"yk5zj1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fae=re("Merge",[["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M12 2v10.3a4 4 0 0 1-1.172 2.872L4 22",key:"1hyw0i"}],["path",{d:"m20 22-5-5",key:"1m27yz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xae=re("MessageCircleCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22z",key:"k85zhp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gae=re("MessageCircleDashed",[["path",{d:"M13.5 3.1c-.5 0-1-.1-1.5-.1s-1 .1-1.5.1",key:"16ll65"}],["path",{d:"M19.3 6.8a10.45 10.45 0 0 0-2.1-2.1",key:"1nq77a"}],["path",{d:"M20.9 13.5c.1-.5.1-1 .1-1.5s-.1-1-.1-1.5",key:"1sf7wn"}],["path",{d:"M17.2 19.3a10.45 10.45 0 0 0 2.1-2.1",key:"x1hs5g"}],["path",{d:"M10.5 20.9c.5.1 1 .1 1.5.1s1-.1 1.5-.1",key:"19m18z"}],["path",{d:"M3.5 17.5 2 22l4.5-1.5",key:"1f36qi"}],["path",{d:"M3.1 10.5c0 .5-.1 1-.1 1.5s.1 1 .1 1.5",key:"1vz3ju"}],["path",{d:"M6.8 4.7a10.45 10.45 0 0 0-2.1 2.1",key:"19f9do"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aL=re("MessageCircleHeart",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M15.8 9.2a2.5 2.5 0 0 0-3.5 0l-.3.4-.35-.3a2.42 2.42 0 1 0-3.2 3.6l3.6 3.5 3.6-3.5c1.2-1.2 1.1-2.7.2-3.7",key:"43lnbm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yae=re("MessageCircleMore",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vae=re("MessageCircleOff",[["path",{d:"M20.5 14.9A9 9 0 0 0 9.1 3.5",key:"1iebmn"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5.6 5.6C3 8.3 2.2 12.5 4 16l-2 6 6-2c3.4 1.8 7.6 1.1 10.3-1.7",key:"1ov8ce"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bae=re("MessageCirclePlus",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const s9=re("MessageCircleQuestion",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M9.09 9a3 3 0 0 1 5.83 1c0 2-3 3-3 3",key:"1u773s"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ae=re("MessageCircleReply",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}],["path",{d:"M7 12h7a2 2 0 0 1 2 2v1",key:"1gheu4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wae=re("MessageCircleWarning",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jae=re("MessageCircleX",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zl=re("MessageCircle",[["path",{d:"M7.9 20A9 9 0 1 0 4 16.1L2 22Z",key:"vv11sd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nae=re("MessageSquareCode",[["path",{d:"M10 7.5 8 10l2 2.5",key:"xb17xw"}],["path",{d:"m14 7.5 2 2.5-2 2.5",key:"5rap1v"}],["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kae=re("MessageSquareDashed",[["path",{d:"M10 17H7l-4 4v-7",key:"1r71xu"}],["path",{d:"M14 17h1",key:"nufu4t"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 14v1a2 2 0 0 1-2 2",key:"29akq3"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M9 3h1",key:"1yesri"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sae=re("MessageSquareDiff",[["path",{d:"m5 19-2 2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2",key:"1xuzuj"}],["path",{d:"M9 10h6",key:"9gxzsh"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 17h6",key:"r8uit2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cae=re("MessageSquareDot",[["path",{d:"M11.7 3H5a2 2 0 0 0-2 2v16l4-4h12a2 2 0 0 0 2-2v-2.7",key:"uodpkb"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iL=re("MessageSquareHeart",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M14.8 7.5a1.84 1.84 0 0 0-2.6 0l-.2.3-.3-.3a1.84 1.84 0 1 0-2.4 2.8L12 13l2.7-2.7c.9-.9.8-2.1.1-2.8",key:"1blaws"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tae=re("MessageSquareLock",[["path",{d:"M19 15v-2a2 2 0 1 0-4 0v2",key:"h3d1vz"}],["path",{d:"M9 17H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v3.5",key:"xsnnhn"}],["rect",{x:"13",y:"15",width:"8",height:"5",rx:"1",key:"1ccwuk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n9=re("MessageSquareMore",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M8 10h.01",key:"19clt8"}],["path",{d:"M12 10h.01",key:"1nrarc"}],["path",{d:"M16 10h.01",key:"1m94wz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eae=re("MessageSquareOff",[["path",{d:"M21 15V5a2 2 0 0 0-2-2H9",key:"43el77"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M3.6 3.6c-.4.3-.6.8-.6 1.4v16l4-4h10",key:"pwpm4a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X_=re("MessageSquarePlus",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v6",key:"lw1j43"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xw=re("MessageSquareQuote",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M8 12a2 2 0 0 0 2-2V8H8",key:"1jfesj"}],["path",{d:"M14 12a2 2 0 0 0 2-2V8h-2",key:"1dq9mh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aae=re("MessageSquareReply",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"m10 7-3 3 3 3",key:"1eugdv"}],["path",{d:"M17 13v-1a2 2 0 0 0-2-2H7",key:"ernfh3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mae=re("MessageSquareShare",[["path",{d:"M21 12v3a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h7",key:"tqtdkg"}],["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"m16 8 5-5",key:"15mbrl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iae=re("MessageSquareText",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M13 8H7",key:"14i4kc"}],["path",{d:"M17 12H7",key:"16if0g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pae=re("MessageSquareWarning",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"M12 7v2",key:"stiyo7"}],["path",{d:"M12 13h.01",key:"y0uutt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lae=re("MessageSquareX",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}],["path",{d:"m14.5 7.5-5 5",key:"3lb6iw"}],["path",{d:"m9.5 7.5 5 5",key:"ko136h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ai=re("MessageSquare",[["path",{d:"M21 15a2 2 0 0 1-2 2H7l-4 4V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2z",key:"1lielz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oL=re("MessagesSquare",[["path",{d:"M14 9a2 2 0 0 1-2 2H6l-4 4V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2z",key:"p1xzt8"}],["path",{d:"M18 9h2a2 2 0 0 1 2 2v11l-4-4h-6a2 2 0 0 1-2-2v-1",key:"1cx29u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dae=re("MicOff",[["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}],["path",{d:"M18.89 13.23A7.12 7.12 0 0 0 19 12v-2",key:"80xlxr"}],["path",{d:"M5 10v2a7 7 0 0 0 12 5",key:"p2k8kg"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V5=re("MicVocal",[["path",{d:"m11 7.601-5.994 8.19a1 1 0 0 0 .1 1.298l.817.818a1 1 0 0 0 1.314.087L15.09 12",key:"80a601"}],["path",{d:"M16.5 21.174C15.5 20.5 14.372 20 13 20c-2.058 0-3.928 2.356-6 2-2.072-.356-2.775-3.369-1.5-4.5",key:"j0ngtp"}],["circle",{cx:"16",cy:"7",r:"5",key:"d08jfb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dv=re("Mic",[["path",{d:"M12 2a3 3 0 0 0-3 3v7a3 3 0 0 0 6 0V5a3 3 0 0 0-3-3Z",key:"131961"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["line",{x1:"12",x2:"12",y1:"19",y2:"22",key:"x3vr5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rae=re("Microchip",[["path",{d:"M18 12h2",key:"quuxs7"}],["path",{d:"M18 16h2",key:"zsn3lv"}],["path",{d:"M18 20h2",key:"9x5y9y"}],["path",{d:"M18 4h2",key:"1luxfb"}],["path",{d:"M18 8h2",key:"nxqzg"}],["path",{d:"M4 12h2",key:"1ltxp0"}],["path",{d:"M4 16h2",key:"8a5zha"}],["path",{d:"M4 20h2",key:"27dk57"}],["path",{d:"M4 4h2",key:"10groj"}],["path",{d:"M4 8h2",key:"18vq6w"}],["path",{d:"M8 2a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2h-1.5c-.276 0-.494.227-.562.495a2 2 0 0 1-3.876 0C9.994 2.227 9.776 2 9.5 2z",key:"1681fp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oae=re("Microscope",[["path",{d:"M6 18h8",key:"1borvv"}],["path",{d:"M3 22h18",key:"8prr45"}],["path",{d:"M14 22a7 7 0 1 0 0-14h-1",key:"1jwaiy"}],["path",{d:"M9 14h2",key:"197e7h"}],["path",{d:"M9 12a2 2 0 0 1-2-2V6h6v4a2 2 0 0 1-2 2Z",key:"1bmzmy"}],["path",{d:"M12 6V3a1 1 0 0 0-1-1H9a1 1 0 0 0-1 1v3",key:"1drr47"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fae=re("Microwave",[["rect",{width:"20",height:"15",x:"2",y:"4",rx:"2",key:"2no95f"}],["rect",{width:"8",height:"7",x:"6",y:"8",rx:"1",key:"zh9wx"}],["path",{d:"M18 8v7",key:"o5zi4n"}],["path",{d:"M6 19v2",key:"1loha6"}],["path",{d:"M18 19v2",key:"1dawf0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zae=re("Milestone",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M4 6a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h13a2 2 0 0 0 1.152-.365l3.424-2.317a1 1 0 0 0 0-1.635l-3.424-2.318A2 2 0 0 0 17 6z",key:"1btarq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bae=re("MilkOff",[["path",{d:"M8 2h8",key:"1ssgc1"}],["path",{d:"M9 2v1.343M15 2v2.789a4 4 0 0 0 .672 2.219l.656.984a4 4 0 0 1 .672 2.22v1.131M7.8 7.8l-.128.192A4 4 0 0 0 7 10.212V20a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-3",key:"y0ejgx"}],["path",{d:"M7 15a6.47 6.47 0 0 1 5 0 6.472 6.472 0 0 0 3.435.435",key:"iaxqsy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ae=re("Milk",[["path",{d:"M8 2h8",key:"1ssgc1"}],["path",{d:"M9 2v2.789a4 4 0 0 1-.672 2.219l-.656.984A4 4 0 0 0 7 10.212V20a2 2 0 0 0 2 2h6a2 2 0 0 0 2-2v-9.789a4 4 0 0 0-.672-2.219l-.656-.984A4 4 0 0 1 15 4.788V2",key:"qtp12x"}],["path",{d:"M7 15a6.472 6.472 0 0 1 5 0 6.47 6.47 0 0 0 5 0",key:"ygeh44"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uae=re("Minimize2",[["polyline",{points:"4 14 10 14 10 20",key:"11kfnr"}],["polyline",{points:"20 10 14 10 14 4",key:"rlmsce"}],["line",{x1:"14",x2:"21",y1:"10",y2:"3",key:"o5lafz"}],["line",{x1:"3",x2:"10",y1:"21",y2:"14",key:"1atl0r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qae=re("Minimize",[["path",{d:"M8 3v3a2 2 0 0 1-2 2H3",key:"hohbtr"}],["path",{d:"M21 8h-3a2 2 0 0 1-2-2V3",key:"5jw1f3"}],["path",{d:"M3 16h3a2 2 0 0 1 2 2v3",key:"198tvr"}],["path",{d:"M16 21v-3a2 2 0 0 1 2-2h3",key:"ph8mxp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hb=re("Minus",[["path",{d:"M5 12h14",key:"1ays0h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vae=re("MonitorCheck",[["path",{d:"m9 10 2 2 4-4",key:"1gnqz4"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hae=re("MonitorCog",[["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m15.2 4.9-.9-.4",key:"12wd2u"}],["path",{d:"m15.2 7.1-.9.4",key:"1r2vl7"}],["path",{d:"m16.9 3.2-.4-.9",key:"3zbo91"}],["path",{d:"m16.9 8.8-.4.9",key:"1qr2dn"}],["path",{d:"m19.5 2.3-.4.9",key:"1rjrkq"}],["path",{d:"m19.5 9.7-.4-.9",key:"heryx5"}],["path",{d:"m21.7 4.5-.9.4",key:"17fqt1"}],["path",{d:"m21.7 7.5-.9-.4",key:"14zyni"}],["path",{d:"M22 13v2a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h7",key:"1tnzv8"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["circle",{cx:"18",cy:"6",r:"3",key:"1h7g24"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gae=re("MonitorDot",[["circle",{cx:"19",cy:"6",r:"3",key:"108a5v"}],["path",{d:"M22 12v3a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h9",key:"1fet9y"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wae=re("MonitorDown",[["path",{d:"M12 13V7",key:"h0r20n"}],["path",{d:"m15 10-3 3-3-3",key:"lzhmyn"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kae=re("MonitorOff",[["path",{d:"M17 17H4a2 2 0 0 1-2-2V5c0-1.5 1-2 1-2",key:"k0q8oc"}],["path",{d:"M22 15V5a2 2 0 0 0-2-2H9",key:"cp1ac0"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yae=re("MonitorPause",[["path",{d:"M10 13V7",key:"1u13u9"}],["path",{d:"M14 13V7",key:"1vj9om"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lL=re("MonitorPlay",[["path",{d:"M10 7.75a.75.75 0 0 1 1.142-.638l3.664 2.249a.75.75 0 0 1 0 1.278l-3.664 2.25a.75.75 0 0 1-1.142-.64z",key:"1pctta"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zae=re("MonitorSmartphone",[["path",{d:"M18 8V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v7a2 2 0 0 0 2 2h8",key:"10dyio"}],["path",{d:"M10 19v-3.96 3.15",key:"1irgej"}],["path",{d:"M7 19h5",key:"qswx4l"}],["rect",{width:"6",height:"10",x:"16",y:"12",rx:"2",key:"1egngj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qae=re("MonitorSpeaker",[["path",{d:"M5.5 20H8",key:"1k40s5"}],["path",{d:"M17 9h.01",key:"1j24nn"}],["rect",{width:"10",height:"16",x:"12",y:"4",rx:"2",key:"ixliua"}],["path",{d:"M8 6H4a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2h4",key:"1mp6e1"}],["circle",{cx:"17",cy:"15",r:"1",key:"tqvash"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xae=re("MonitorStop",[["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["rect",{x:"2",y:"3",width:"20",height:"14",rx:"2",key:"x3v2xh"}],["rect",{x:"9",y:"7",width:"6",height:"6",rx:"1",key:"5m2oou"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MA=re("MonitorUp",[["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}],["path",{d:"M12 13V7",key:"h0r20n"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jae=re("MonitorX",[["path",{d:"m14.5 12.5-5-5",key:"1jahn5"}],["path",{d:"m9.5 12.5 5-5",key:"1k2t7b"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"M8 21h8",key:"1ev6f3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mb=re("Monitor",[["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}],["line",{x1:"8",x2:"16",y1:"21",y2:"21",key:"1svkeh"}],["line",{x1:"12",x2:"12",y1:"17",y2:"21",key:"vw1qmm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eie=re("MoonStar",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9",key:"4ay0iu"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tie=re("Moon",[["path",{d:"M12 3a6 6 0 0 0 9 9 9 9 0 1 1-9-9Z",key:"a7tn18"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sie=re("MountainSnow",[["path",{d:"m8 3 4 8 5-5 5 15H2L8 3z",key:"otkl63"}],["path",{d:"M4.14 15.08c2.62-1.57 5.24-1.43 7.86.42 2.74 1.94 5.49 2 8.23.19",key:"1pvmmp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nie=re("Mountain",[["path",{d:"m8 3 4 8 5-5 5 15H2L8 3z",key:"otkl63"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rie=re("MouseOff",[["path",{d:"M12 6v.343",key:"1gyhex"}],["path",{d:"M18.218 18.218A7 7 0 0 1 5 15V9a7 7 0 0 1 .782-3.218",key:"ukzz01"}],["path",{d:"M19 13.343V9A7 7 0 0 0 8.56 2.902",key:"104jy9"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aie=re("MousePointer2",[["path",{d:"M4.037 4.688a.495.495 0 0 1 .651-.651l16 6.5a.5.5 0 0 1-.063.947l-6.124 1.58a2 2 0 0 0-1.438 1.435l-1.579 6.126a.5.5 0 0 1-.947.063z",key:"edeuup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iie=re("MousePointerBan",[["path",{d:"M2.034 2.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.944L8.204 7.545a1 1 0 0 0-.66.66l-1.066 3.443a.5.5 0 0 1-.944.033z",key:"11pp1i"}],["circle",{cx:"16",cy:"16",r:"6",key:"qoo3c4"}],["path",{d:"m11.8 11.8 8.4 8.4",key:"oogvdj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oc=re("MousePointerClick",[["path",{d:"M14 4.1 12 6",key:"ita8i4"}],["path",{d:"m5.1 8-2.9-.8",key:"1go3kf"}],["path",{d:"m6 12-1.9 2",key:"mnht97"}],["path",{d:"M7.2 2.2 8 5.1",key:"1cfko1"}],["path",{d:"M9.037 9.69a.498.498 0 0 1 .653-.653l11 4.5a.5.5 0 0 1-.074.949l-4.349 1.041a1 1 0 0 0-.74.739l-1.04 4.35a.5.5 0 0 1-.95.074z",key:"s0h3yz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lm=re("MousePointer",[["path",{d:"M12.586 12.586 19 19",key:"ea5xo7"}],["path",{d:"M3.688 3.037a.497.497 0 0 0-.651.651l6.5 15.999a.501.501 0 0 0 .947-.062l1.569-6.083a2 2 0 0 1 1.448-1.479l6.124-1.579a.5.5 0 0 0 .063-.947z",key:"277e5u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oie=re("Mouse",[["rect",{x:"5",y:"2",width:"14",height:"20",rx:"7",key:"11ol66"}],["path",{d:"M12 6v4",key:"16clxf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const H5=re("Move3d",[["path",{d:"M5 3v16h16",key:"1mqmf9"}],["path",{d:"m5 19 6-6",key:"jh6hbb"}],["path",{d:"m2 6 3-3 3 3",key:"tkyvxa"}],["path",{d:"m18 16 3 3-3 3",key:"1d4glt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lie=re("MoveDiagonal2",[["path",{d:"M19 13v6h-6",key:"1hxl6d"}],["path",{d:"M5 11V5h6",key:"12e2xe"}],["path",{d:"m5 5 14 14",key:"11anup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cie=re("MoveDiagonal",[["path",{d:"M11 19H5v-6",key:"8awifj"}],["path",{d:"M13 5h6v6",key:"7voy1q"}],["path",{d:"M19 5 5 19",key:"wwaj1z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const die=re("MoveDownLeft",[["path",{d:"M11 19H5V13",key:"1akmht"}],["path",{d:"M19 5L5 19",key:"72u4yj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uie=re("MoveDownRight",[["path",{d:"M19 13V19H13",key:"10vkzq"}],["path",{d:"M5 5L19 19",key:"5zm2fv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hie=re("MoveDown",[["path",{d:"M8 18L12 22L16 18",key:"cskvfv"}],["path",{d:"M12 2V22",key:"r89rzk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mie=re("MoveHorizontal",[["path",{d:"m18 8 4 4-4 4",key:"1ak13k"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m6 8-4 4 4 4",key:"15zrgr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pie=re("MoveLeft",[["path",{d:"M6 8L2 12L6 16",key:"kyvwex"}],["path",{d:"M2 12H22",key:"1m8cig"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fie=re("MoveRight",[["path",{d:"M18 8L22 12L18 16",key:"1r0oui"}],["path",{d:"M2 12H22",key:"1m8cig"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xie=re("MoveUpLeft",[["path",{d:"M5 11V5H11",key:"3q78g9"}],["path",{d:"M5 5L19 19",key:"5zm2fv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gie=re("MoveUpRight",[["path",{d:"M13 5H19V11",key:"1n1gyv"}],["path",{d:"M19 5L5 19",key:"72u4yj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yie=re("MoveUp",[["path",{d:"M8 6L12 2L16 6",key:"1yvkyx"}],["path",{d:"M12 2V22",key:"r89rzk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vie=re("MoveVertical",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m8 18 4 4 4-4",key:"bh5tu3"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bie=re("Move",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m19 9 3 3-3 3",key:"1mg7y2"}],["path",{d:"M2 12h20",key:"9i4pu4"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}],["path",{d:"m9 5 3-3 3 3",key:"l8vdw6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ie=re("Music2",[["circle",{cx:"8",cy:"18",r:"4",key:"1fc0mg"}],["path",{d:"M12 18V2l7 4",key:"g04rme"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wie=re("Music3",[["circle",{cx:"12",cy:"18",r:"4",key:"m3r9ws"}],["path",{d:"M16 18V2",key:"40x2m5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jie=re("Music4",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["path",{d:"m9 9 12-2",key:"1e64n2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cL=re("Music",[["path",{d:"M9 18V5l12-2v13",key:"1jmyc2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["circle",{cx:"18",cy:"16",r:"3",key:"1hluhg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nie=re("Navigation2Off",[["path",{d:"M9.31 9.31 5 21l7-4 7 4-1.17-3.17",key:"qoq2o2"}],["path",{d:"M14.53 8.88 12 2l-1.17 3.17",key:"k3sjzy"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kie=re("Navigation2",[["polygon",{points:"12 2 19 21 12 17 5 21 12 2",key:"x8c0qg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sie=re("NavigationOff",[["path",{d:"M8.43 8.43 3 11l8 2 2 8 2.57-5.43",key:"1vdtb7"}],["path",{d:"M17.39 11.73 22 2l-9.73 4.61",key:"tya3r6"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r9=re("Navigation",[["polygon",{points:"3 11 22 2 13 21 11 13 3 11",key:"1ltx0t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cie=re("Network",[["rect",{x:"16",y:"16",width:"6",height:"6",rx:"1",key:"4q2zg0"}],["rect",{x:"2",y:"16",width:"6",height:"6",rx:"1",key:"8cvhb9"}],["rect",{x:"9",y:"2",width:"6",height:"6",rx:"1",key:"1egb70"}],["path",{d:"M5 16v-3a1 1 0 0 1 1-1h12a1 1 0 0 1 1 1v3",key:"1jsf9p"}],["path",{d:"M12 12V8",key:"2874zd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sy=re("Newspaper",[["path",{d:"M4 22h16a2 2 0 0 0 2-2V4a2 2 0 0 0-2-2H8a2 2 0 0 0-2 2v16a2 2 0 0 1-2 2Zm0 0a2 2 0 0 1-2-2v-9c0-1.1.9-2 2-2h2",key:"7pis2x"}],["path",{d:"M18 14h-8",key:"sponae"}],["path",{d:"M15 18h-5",key:"95g1m2"}],["path",{d:"M10 6h8v4h-8V6Z",key:"smlsk5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tie=re("Nfc",[["path",{d:"M6 8.32a7.43 7.43 0 0 1 0 7.36",key:"9iaqei"}],["path",{d:"M9.46 6.21a11.76 11.76 0 0 1 0 11.58",key:"1yha7l"}],["path",{d:"M12.91 4.1a15.91 15.91 0 0 1 .01 15.8",key:"4iu2gk"}],["path",{d:"M16.37 2a20.16 20.16 0 0 1 0 20",key:"sap9u2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eie=re("NotebookPen",[["path",{d:"M13.4 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-7.4",key:"re6nr2"}],["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["path",{d:"M21.378 5.626a1 1 0 1 0-3.004-3.004l-5.01 5.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"pqwjuv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aie=re("NotebookTabs",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M15 2v20",key:"dcj49h"}],["path",{d:"M15 7h5",key:"1xj5lc"}],["path",{d:"M15 12h5",key:"w5shd9"}],["path",{d:"M15 17h5",key:"1qaofu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mie=re("NotebookText",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M9.5 8h5",key:"11mslq"}],["path",{d:"M9.5 12H16",key:"ktog6x"}],["path",{d:"M9.5 16H14",key:"p1seyn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iie=re("Notebook",[["path",{d:"M2 6h4",key:"aawbzj"}],["path",{d:"M2 10h4",key:"l0bgd4"}],["path",{d:"M2 14h4",key:"1gsvsf"}],["path",{d:"M2 18h4",key:"1bu2t1"}],["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M16 2v20",key:"rotuqe"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pie=re("NotepadTextDashed",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"M16 2v4",key:"4m81vk"}],["path",{d:"M16 4h2a2 2 0 0 1 2 2v2",key:"j91f56"}],["path",{d:"M20 12v2",key:"w8o0tu"}],["path",{d:"M20 18v2a2 2 0 0 1-2 2h-1",key:"1c9ggx"}],["path",{d:"M13 22h-2",key:"191ugt"}],["path",{d:"M7 22H6a2 2 0 0 1-2-2v-2",key:"1rt9px"}],["path",{d:"M4 14v-2",key:"1v0sqh"}],["path",{d:"M4 8V6a2 2 0 0 1 2-2h2",key:"1mwabg"}],["path",{d:"M8 10h6",key:"3oa6kw"}],["path",{d:"M8 14h8",key:"1fgep2"}],["path",{d:"M8 18h5",key:"17enja"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lie=re("NotepadText",[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"16",height:"18",x:"4",y:"4",rx:"2",key:"1u9h20"}],["path",{d:"M8 10h6",key:"3oa6kw"}],["path",{d:"M8 14h8",key:"1fgep2"}],["path",{d:"M8 18h5",key:"17enja"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Die=re("NutOff",[["path",{d:"M12 4V2",key:"1k5q1u"}],["path",{d:"M5 10v4a7.004 7.004 0 0 0 5.277 6.787c.412.104.802.292 1.102.592L12 22l.621-.621c.3-.3.69-.488 1.102-.592a7.01 7.01 0 0 0 4.125-2.939",key:"1xcvy9"}],["path",{d:"M19 10v3.343",key:"163tfc"}],["path",{d:"M12 12c-1.349-.573-1.905-1.005-2.5-2-.546.902-1.048 1.353-2.5 2-1.018-.644-1.46-1.08-2-2-1.028.71-1.69.918-3 1 1.081-1.048 1.757-2.03 2-3 .194-.776.84-1.551 1.79-2.21m11.654 5.997c.887-.457 1.28-.891 1.556-1.787 1.032.916 1.683 1.157 3 1-1.297-1.036-1.758-2.03-2-3-.5-2-4-4-8-4-.74 0-1.461.068-2.15.192",key:"17914v"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rie=re("Nut",[["path",{d:"M12 4V2",key:"1k5q1u"}],["path",{d:"M5 10v4a7.004 7.004 0 0 0 5.277 6.787c.412.104.802.292 1.102.592L12 22l.621-.621c.3-.3.69-.488 1.102-.592A7.003 7.003 0 0 0 19 14v-4",key:"1tgyif"}],["path",{d:"M12 4C8 4 4.5 6 4 8c-.243.97-.919 1.952-2 3 1.31-.082 1.972-.29 3-1 .54.92.982 1.356 2 2 1.452-.647 1.954-1.098 2.5-2 .595.995 1.151 1.427 2.5 2 1.31-.621 1.862-1.058 2.5-2 .629.977 1.162 1.423 2.5 2 1.209-.548 1.68-.967 2-2 1.032.916 1.683 1.157 3 1-1.297-1.036-1.758-2.03-2-3-.5-2-4-4-8-4Z",key:"tnsqj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const V_=re("OctagonAlert",[["path",{d:"M12 16h.01",key:"1drbdi"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M15.312 2a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586l-4.688-4.688A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2z",key:"1fd625"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oie=re("OctagonMinus",[["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const G5=re("OctagonPause",[["path",{d:"M10 15V9",key:"1lckn7"}],["path",{d:"M14 15V9",key:"1muqhk"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const W5=re("OctagonX",[["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fie=re("Octagon",[["path",{d:"M2.586 16.726A2 2 0 0 1 2 15.312V8.688a2 2 0 0 1 .586-1.414l4.688-4.688A2 2 0 0 1 8.688 2h6.624a2 2 0 0 1 1.414.586l4.688 4.688A2 2 0 0 1 22 8.688v6.624a2 2 0 0 1-.586 1.414l-4.688 4.688a2 2 0 0 1-1.414.586H8.688a2 2 0 0 1-1.414-.586z",key:"2d38gg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zie=re("Omega",[["path",{d:"M3 20h4.5a.5.5 0 0 0 .5-.5v-.282a.52.52 0 0 0-.247-.437 8 8 0 1 1 8.494-.001.52.52 0 0 0-.247.438v.282a.5.5 0 0 0 .5.5H21",key:"1x94xo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bie=re("Option",[["path",{d:"M3 3h6l6 18h6",key:"ph9rgk"}],["path",{d:"M14 3h7",key:"16f0ms"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ie=re("Orbit",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M10.4 21.9a10 10 0 0 0 9.941-15.416",key:"eohfx2"}],["path",{d:"M13.5 2.1a10 10 0 0 0-9.841 15.416",key:"19pvbm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uie=re("Origami",[["path",{d:"M12 12V4a1 1 0 0 1 1-1h6.297a1 1 0 0 1 .651 1.759l-4.696 4.025",key:"1bx4vc"}],["path",{d:"m12 21-7.414-7.414A2 2 0 0 1 4 12.172V6.415a1.002 1.002 0 0 1 1.707-.707L20 20.009",key:"1h3km6"}],["path",{d:"m12.214 3.381 8.414 14.966a1 1 0 0 1-.167 1.199l-1.168 1.163a1 1 0 0 1-.706.291H6.351a1 1 0 0 1-.625-.219L3.25 18.8a1 1 0 0 1 .631-1.781l4.165.027",key:"1hj4wg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qie=re("Package2",[["path",{d:"M3 9h18v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V9Z",key:"1ront0"}],["path",{d:"m3 9 2.45-4.9A2 2 0 0 1 7.24 3h9.52a2 2 0 0 1 1.8 1.1L21 9",key:"19h2x1"}],["path",{d:"M12 3v6",key:"1holv5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vie=re("PackageCheck",[["path",{d:"m16 16 2 2 4-4",key:"gfu2re"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hie=re("PackageMinus",[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gie=re("PackageOpen",[["path",{d:"M12 22v-9",key:"x3hkom"}],["path",{d:"M15.17 2.21a1.67 1.67 0 0 1 1.63 0L21 4.57a1.93 1.93 0 0 1 0 3.36L8.82 14.79a1.655 1.655 0 0 1-1.64 0L3 12.43a1.93 1.93 0 0 1 0-3.36z",key:"2ntwy6"}],["path",{d:"M20 13v3.87a2.06 2.06 0 0 1-1.11 1.83l-6 3.08a1.93 1.93 0 0 1-1.78 0l-6-3.08A2.06 2.06 0 0 1 4 16.87V13",key:"1pmm1c"}],["path",{d:"M21 12.43a1.93 1.93 0 0 0 0-3.36L8.83 2.2a1.64 1.64 0 0 0-1.63 0L3 4.57a1.93 1.93 0 0 0 0 3.36l12.18 6.86a1.636 1.636 0 0 0 1.63 0z",key:"12ttoo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const a9=re("PackagePlus",[["path",{d:"M16 16h6",key:"100bgy"}],["path",{d:"M19 13v6",key:"85cyf1"}],["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wie=re("PackageSearch",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["circle",{cx:"18.5",cy:"15.5",r:"2.5",key:"b5zd12"}],["path",{d:"M20.27 17.27 22 19",key:"1l4muz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kie=re("PackageX",[["path",{d:"M21 10V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l2-1.14",key:"e7tb2h"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}],["polyline",{points:"3.29 7 12 12 20.71 7",key:"ousv84"}],["line",{x1:"12",x2:"12",y1:"22",y2:"12",key:"a4e8g8"}],["path",{d:"m17 13 5 5m-5 0 5-5",key:"im3w4b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ec=re("Package",[["path",{d:"M11 21.73a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73z",key:"1a0edw"}],["path",{d:"M12 22V12",key:"d0xqtd"}],["path",{d:"m3.3 7 7.703 4.734a2 2 0 0 0 1.994 0L20.7 7",key:"yx3hmr"}],["path",{d:"m7.5 4.27 9 5.15",key:"1c824w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yie=re("PaintBucket",[["path",{d:"m19 11-8-8-8.6 8.6a2 2 0 0 0 0 2.8l5.2 5.2c.8.8 2 .8 2.8 0L19 11Z",key:"irua1i"}],["path",{d:"m5 2 5 5",key:"1lls2c"}],["path",{d:"M2 13h15",key:"1hkzvu"}],["path",{d:"M22 20a2 2 0 1 1-4 0c0-1.6 1.7-2.4 2-4 .3 1.6 2 2.4 2 4Z",key:"xk76lq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zie=re("PaintRoller",[["rect",{width:"16",height:"6",x:"2",y:"2",rx:"2",key:"jcyz7m"}],["path",{d:"M10 16v-2a2 2 0 0 1 2-2h8a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2",key:"1b9h7c"}],["rect",{width:"4",height:"6",x:"8",y:"16",rx:"1",key:"d6e7yl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const K5=re("PaintbrushVertical",[["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M14 2v4",key:"qmzblu"}],["path",{d:"M17 2a1 1 0 0 1 1 1v9H6V3a1 1 0 0 1 1-1z",key:"ycvu00"}],["path",{d:"M6 12a1 1 0 0 0-1 1v1a2 2 0 0 0 2 2h2a1 1 0 0 1 1 1v2.9a2 2 0 1 0 4 0V17a1 1 0 0 1 1-1h2a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1",key:"iw4wnp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qie=re("Paintbrush",[["path",{d:"m14.622 17.897-10.68-2.913",key:"vj2p1u"}],["path",{d:"M18.376 2.622a1 1 0 1 1 3.002 3.002L17.36 9.643a.5.5 0 0 0 0 .707l.944.944a2.41 2.41 0 0 1 0 3.408l-.944.944a.5.5 0 0 1-.707 0L8.354 7.348a.5.5 0 0 1 0-.707l.944-.944a2.41 2.41 0 0 1 3.408 0l.944.944a.5.5 0 0 0 .707 0z",key:"18tc5c"}],["path",{d:"M9 8c-1.804 2.71-3.97 3.46-6.583 3.948a.507.507 0 0 0-.302.819l7.32 8.883a1 1 0 0 0 1.185.204C12.735 20.405 16 16.792 16 15",key:"ytzfxy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pl=re("Palette",[["circle",{cx:"13.5",cy:"6.5",r:".5",fill:"currentColor",key:"1okk4w"}],["circle",{cx:"17.5",cy:"10.5",r:".5",fill:"currentColor",key:"f64h9f"}],["circle",{cx:"8.5",cy:"7.5",r:".5",fill:"currentColor",key:"fotxhn"}],["circle",{cx:"6.5",cy:"12.5",r:".5",fill:"currentColor",key:"qy21gx"}],["path",{d:"M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10c.926 0 1.648-.746 1.648-1.688 0-.437-.18-.835-.437-1.125-.29-.289-.438-.652-.438-1.125a1.64 1.64 0 0 1 1.668-1.668h1.996c3.051 0 5.555-2.503 5.555-5.554C21.965 6.012 17.461 2 12 2z",key:"12rzf8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xie=re("PanelBottomClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"m15 8-3 3-3-3",key:"1oxy1z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y5=re("PanelBottomDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M14 15h1",key:"171nev"}],["path",{d:"M19 15h2",key:"1vnucp"}],["path",{d:"M3 15h2",key:"8bym0q"}],["path",{d:"M9 15h1",key:"1tg3ks"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jie=re("PanelBottomOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"m9 10 3-3 3 3",key:"11gsxs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eoe=re("PanelBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z5=re("PanelLeftClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m16 15-3-3 3-3",key:"14y99z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Q5=re("PanelLeftDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 14v1",key:"askpd8"}],["path",{d:"M9 19v2",key:"16tejx"}],["path",{d:"M9 3v2",key:"1noubl"}],["path",{d:"M9 9v1",key:"19ebxg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const X5=re("PanelLeftOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"m14 9 3 3-3 3",key:"8010ee"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J5=re("PanelLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const toe=re("PanelRightClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m8 9 3 3-3 3",key:"12hl5m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eT=re("PanelRightDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 14v1",key:"ilsfch"}],["path",{d:"M15 19v2",key:"1fst2f"}],["path",{d:"M15 3v2",key:"z204g4"}],["path",{d:"M15 9v1",key:"z2a8b1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const soe=re("PanelRightOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}],["path",{d:"m10 15-3-3 3-3",key:"1pgupc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const noe=re("PanelRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const roe=re("PanelTopClose",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"m9 16 3-3 3 3",key:"1idcnm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tT=re("PanelTopDashed",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M14 9h1",key:"l0svgy"}],["path",{d:"M19 9h2",key:"te2zfg"}],["path",{d:"M3 9h2",key:"1h4ldw"}],["path",{d:"M9 9h1",key:"15jzuz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aoe=re("PanelTopOpen",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"m15 14-3 3-3-3",key:"g215vf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ioe=re("PanelTop",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ooe=re("PanelsLeftBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M9 15h12",key:"5ijen5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const loe=re("PanelsRightBottom",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 15h12",key:"1wkqb3"}],["path",{d:"M15 3v18",key:"14nvp0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k2=re("PanelsTopLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M9 21V9",key:"1oto5p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YS=re("Paperclip",[["path",{d:"m21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48",key:"1u3ebp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const coe=re("Parentheses",[["path",{d:"M8 21s-4-3-4-9 4-9 4-9",key:"uto9ud"}],["path",{d:"M16 3s4 3 4 9-4 9-4 9",key:"4w2vsq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const doe=re("ParkingMeter",[["path",{d:"M11 15h2",key:"199qp6"}],["path",{d:"M12 12v3",key:"158kv8"}],["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M15.282 19a1 1 0 0 0 .948-.68l2.37-6.988a7 7 0 1 0-13.2 0l2.37 6.988a1 1 0 0 0 .948.68z",key:"1jofit"}],["path",{d:"M9 9a3 3 0 1 1 6 0",key:"jdoeu8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ih=re("PartyPopper",[["path",{d:"M5.8 11.3 2 22l10.7-3.79",key:"gwxi1d"}],["path",{d:"M4 3h.01",key:"1vcuye"}],["path",{d:"M22 8h.01",key:"1mrtc2"}],["path",{d:"M15 2h.01",key:"1cjtqr"}],["path",{d:"M22 20h.01",key:"1mrys2"}],["path",{d:"m22 2-2.24.75a2.9 2.9 0 0 0-1.96 3.12c.1.86-.57 1.63-1.45 1.63h-.38c-.86 0-1.6.6-1.76 1.44L14 10",key:"hbicv8"}],["path",{d:"m22 13-.82-.33c-.86-.34-1.82.2-1.98 1.11c-.11.7-.72 1.22-1.43 1.22H17",key:"1i94pl"}],["path",{d:"m11 2 .33.82c.34.86-.2 1.82-1.11 1.98C9.52 4.9 9 5.52 9 6.23V7",key:"1cofks"}],["path",{d:"M11 13c1.93 1.93 2.83 4.17 2 5-.83.83-3.07-.07-5-2-1.93-1.93-2.83-4.17-2-5 .83-.83 3.07.07 5 2Z",key:"4kbmks"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gf=re("Pause",[["rect",{x:"14",y:"4",width:"4",height:"16",rx:"1",key:"zuxfzm"}],["rect",{x:"6",y:"4",width:"4",height:"16",rx:"1",key:"1okwgv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uoe=re("PawPrint",[["circle",{cx:"11",cy:"4",r:"2",key:"vol9p0"}],["circle",{cx:"18",cy:"8",r:"2",key:"17gozi"}],["circle",{cx:"20",cy:"16",r:"2",key:"1v9bxh"}],["path",{d:"M9 10a5 5 0 0 1 5 5v3.5a3.5 3.5 0 0 1-6.84 1.045Q6.52 17.48 4.46 16.84A3.5 3.5 0 0 1 5.5 10Z",key:"1ydw1z"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hoe=re("PcCase",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",key:"1uq1d7"}],["path",{d:"M15 14h.01",key:"1kp3bh"}],["path",{d:"M9 6h6",key:"dgm16u"}],["path",{d:"M9 10h6",key:"9gxzsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const J1=re("PenLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const moe=re("PenOff",[["path",{d:"m10 10-6.157 6.162a2 2 0 0 0-.5.833l-1.322 4.36a.5.5 0 0 0 .622.624l4.358-1.323a2 2 0 0 0 .83-.5L14 13.982",key:"bjo8r8"}],["path",{d:"m12.829 7.172 4.359-4.346a1 1 0 1 1 3.986 3.986l-4.353 4.353",key:"16h5ne"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZS=re("PenTool",[["path",{d:"M15.707 21.293a1 1 0 0 1-1.414 0l-1.586-1.586a1 1 0 0 1 0-1.414l5.586-5.586a1 1 0 0 1 1.414 0l1.586 1.586a1 1 0 0 1 0 1.414z",key:"nt11vn"}],["path",{d:"m18 13-1.375-6.874a1 1 0 0 0-.746-.776L3.235 2.028a1 1 0 0 0-1.207 1.207L5.35 15.879a1 1 0 0 0 .776.746L13 18",key:"15qc1e"}],["path",{d:"m2.3 2.3 7.286 7.286",key:"1wuzzi"}],["circle",{cx:"11",cy:"11",r:"2",key:"xmgehs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _v=re("Pen",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const i9=re("PencilLine",[["path",{d:"M12 20h9",key:"t2du7b"}],["path",{d:"M16.376 3.622a1 1 0 0 1 3.002 3.002L7.368 18.635a2 2 0 0 1-.855.506l-2.872.838a.5.5 0 0 1-.62-.62l.838-2.872a2 2 0 0 1 .506-.854z",key:"1ykcvy"}],["path",{d:"m15 5 3 3",key:"1w25hb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const poe=re("PencilOff",[["path",{d:"m10 10-6.157 6.162a2 2 0 0 0-.5.833l-1.322 4.36a.5.5 0 0 0 .622.624l4.358-1.323a2 2 0 0 0 .83-.5L14 13.982",key:"bjo8r8"}],["path",{d:"m12.829 7.172 4.359-4.346a1 1 0 1 1 3.986 3.986l-4.353 4.353",key:"16h5ne"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const foe=re("PencilRuler",[["path",{d:"M13 7 8.7 2.7a2.41 2.41 0 0 0-3.4 0L2.7 5.3a2.41 2.41 0 0 0 0 3.4L7 13",key:"orapub"}],["path",{d:"m8 6 2-2",key:"115y1s"}],["path",{d:"m18 16 2-2",key:"ee94s4"}],["path",{d:"m17 11 4.3 4.3c.94.94.94 2.46 0 3.4l-2.6 2.6c-.94.94-2.46.94-3.4 0L11 17",key:"cfq27r"}],["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ya=re("Pencil",[["path",{d:"M21.174 6.812a1 1 0 0 0-3.986-3.987L3.842 16.174a2 2 0 0 0-.5.83l-1.321 4.352a.5.5 0 0 0 .623.622l4.353-1.32a2 2 0 0 0 .83-.497z",key:"1a8usu"}],["path",{d:"m15 5 4 4",key:"1mk7zo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xoe=re("Pentagon",[["path",{d:"M10.83 2.38a2 2 0 0 1 2.34 0l8 5.74a2 2 0 0 1 .73 2.25l-3.04 9.26a2 2 0 0 1-1.9 1.37H7.04a2 2 0 0 1-1.9-1.37L2.1 10.37a2 2 0 0 1 .73-2.25z",key:"2hea0t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QS=re("Percent",[["line",{x1:"19",x2:"5",y1:"5",y2:"19",key:"1x9vlm"}],["circle",{cx:"6.5",cy:"6.5",r:"2.5",key:"4mh3h7"}],["circle",{cx:"17.5",cy:"17.5",r:"2.5",key:"1mdrzq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const goe=re("PersonStanding",[["circle",{cx:"12",cy:"5",r:"1",key:"gxeob9"}],["path",{d:"m9 20 3-6 3 6",key:"se2kox"}],["path",{d:"m6 8 6 2 6-2",key:"4o3us4"}],["path",{d:"M12 10v4",key:"1kjpxc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yoe=re("PhilippinePeso",[["path",{d:"M20 11H4",key:"6ut86h"}],["path",{d:"M20 7H4",key:"zbl0bi"}],["path",{d:"M7 21V4a1 1 0 0 1 1-1h4a1 1 0 0 1 0 12H7",key:"1ana5r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const voe=re("PhoneCall",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}],["path",{d:"M14.05 2a9 9 0 0 1 8 7.94",key:"vmijpz"}],["path",{d:"M14.05 6A5 5 0 0 1 18 10",key:"13nbpp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const boe=re("PhoneForwarded",[["polyline",{points:"18 2 22 6 18 10",key:"6vjanh"}],["line",{x1:"14",x2:"22",y1:"6",y2:"6",key:"1jsywh"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _oe=re("PhoneIncoming",[["polyline",{points:"16 2 16 8 22 8",key:"1ygljm"}],["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const woe=re("PhoneMissed",[["line",{x1:"22",x2:"16",y1:"2",y2:"8",key:"1xzwqn"}],["line",{x1:"16",x2:"22",y1:"2",y2:"8",key:"13zxdn"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const joe=re("PhoneOff",[["path",{d:"M10.68 13.31a16 16 0 0 0 3.41 2.6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7 2 2 0 0 1 1.72 2v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.42 19.42 0 0 1-3.33-2.67m-2.67-3.34a19.79 19.79 0 0 1-3.07-8.63A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91",key:"z86iuo"}],["line",{x1:"22",x2:"2",y1:"2",y2:"22",key:"11kh81"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Noe=re("PhoneOutgoing",[["polyline",{points:"22 8 22 2 16 2",key:"1g204g"}],["line",{x1:"16",x2:"22",y1:"8",y2:"2",key:"1ggias"}],["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cr=re("Phone",[["path",{d:"M22 16.92v3a2 2 0 0 1-2.18 2 19.79 19.79 0 0 1-8.63-3.07 19.5 19.5 0 0 1-6-6 19.79 19.79 0 0 1-3.07-8.67A2 2 0 0 1 4.11 2h3a2 2 0 0 1 2 1.72 12.84 12.84 0 0 0 .7 2.81 2 2 0 0 1-.45 2.11L8.09 9.91a16 16 0 0 0 6 6l1.27-1.27a2 2 0 0 1 2.11-.45 12.84 12.84 0 0 0 2.81.7A2 2 0 0 1 22 16.92z",key:"foiqr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const koe=re("Pi",[["line",{x1:"9",x2:"9",y1:"4",y2:"20",key:"ovs5a5"}],["path",{d:"M4 7c0-1.7 1.3-3 3-3h13",key:"10pag4"}],["path",{d:"M18 20c-1.7 0-3-1.3-3-3V4",key:"1gaosr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Soe=re("Piano",[["path",{d:"M18.5 8c-1.4 0-2.6-.8-3.2-2A6.87 6.87 0 0 0 2 9v11a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-8.5C22 9.6 20.4 8 18.5 8",key:"lag0yf"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M6 14v4",key:"9ng0ue"}],["path",{d:"M10 14v4",key:"1v8uk5"}],["path",{d:"M14 14v4",key:"1tqops"}],["path",{d:"M18 14v4",key:"18uqwm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Coe=re("Pickaxe",[["path",{d:"M14.531 12.469 6.619 20.38a1 1 0 1 1-3-3l7.912-7.912",key:"we99rg"}],["path",{d:"M15.686 4.314A12.5 12.5 0 0 0 5.461 2.958 1 1 0 0 0 5.58 4.71a22 22 0 0 1 6.318 3.393",key:"1w6hck"}],["path",{d:"M17.7 3.7a1 1 0 0 0-1.4 0l-4.6 4.6a1 1 0 0 0 0 1.4l2.6 2.6a1 1 0 0 0 1.4 0l4.6-4.6a1 1 0 0 0 0-1.4z",key:"15hgfx"}],["path",{d:"M19.686 8.314a12.501 12.501 0 0 1 1.356 10.225 1 1 0 0 1-1.751-.119 22 22 0 0 0-3.393-6.319",key:"452b4h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Toe=re("PictureInPicture2",[["path",{d:"M21 9V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10c0 1.1.9 2 2 2h4",key:"daa4of"}],["rect",{width:"10",height:"7",x:"12",y:"13",rx:"2",key:"1nb8gs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eoe=re("PictureInPicture",[["path",{d:"M8 4.5v5H3m-1-6 6 6m13 0v-3c0-1.16-.84-2-2-2h-7m-9 9v2c0 1.05.95 2 2 2h3",key:"bcd8fb"}],["rect",{width:"10",height:"7",x:"12",y:"13.5",ry:"2",key:"136fx3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aoe=re("PiggyBank",[["path",{d:"M19 5c-1.5 0-2.8 1.4-3 2-3.5-1.5-11-.3-11 5 0 1.8 0 3 2 4.5V20h4v-2h3v2h4v-4c1-.5 1.7-1 2-2h2v-4h-2c0-1-.5-1.5-1-2V5z",key:"1ivx2i"}],["path",{d:"M2 9v1c0 1.1.9 2 2 2h1",key:"nm575m"}],["path",{d:"M16 11h.01",key:"xkw8gn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Moe=re("PilcrowLeft",[["path",{d:"M14 3v11",key:"mlfb7b"}],["path",{d:"M14 9h-3a3 3 0 0 1 0-6h9",key:"1ulc19"}],["path",{d:"M18 3v11",key:"1phi0r"}],["path",{d:"M22 18H2l4-4",key:"yt65j9"}],["path",{d:"m6 22-4-4",key:"6jgyf5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ioe=re("PilcrowRight",[["path",{d:"M10 3v11",key:"o3l5kj"}],["path",{d:"M10 9H7a1 1 0 0 1 0-6h8",key:"1wb1nc"}],["path",{d:"M14 3v11",key:"mlfb7b"}],["path",{d:"m18 14 4 4H2",key:"4r8io1"}],["path",{d:"m22 18-4 4",key:"1hjjrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Poe=re("Pilcrow",[["path",{d:"M13 4v16",key:"8vvj80"}],["path",{d:"M17 4v16",key:"7dpous"}],["path",{d:"M19 4H9.5a4.5 4.5 0 0 0 0 9H13",key:"sh4n9v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Loe=re("PillBottle",[["path",{d:"M18 11h-4a1 1 0 0 0-1 1v5a1 1 0 0 0 1 1h4",key:"17ldeb"}],["path",{d:"M6 7v13a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2V7",key:"nc37y6"}],["rect",{width:"16",height:"5",x:"4",y:"2",rx:"1",key:"3jeezo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Doe=re("Pill",[["path",{d:"m10.5 20.5 10-10a4.95 4.95 0 1 0-7-7l-10 10a4.95 4.95 0 1 0 7 7Z",key:"wa1lgi"}],["path",{d:"m8.5 8.5 7 7",key:"rvfmvr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const o9=re("PinOff",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M15 9.34V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H7.89",key:"znwnzq"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v1.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h11",key:"c9qhm2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XS=re("Pin",[["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M9 10.76a2 2 0 0 1-1.11 1.79l-1.78.9A2 2 0 0 0 5 15.24V16a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-.76a2 2 0 0 0-1.11-1.79l-1.78-.9A2 2 0 0 1 15 10.76V7a1 1 0 0 1 1-1 2 2 0 0 0 0-4H8a2 2 0 0 0 0 4 1 1 0 0 1 1 1z",key:"1nkz8b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Roe=re("Pipette",[["path",{d:"m2 22 1-1h3l9-9",key:"1sre89"}],["path",{d:"M3 21v-3l9-9",key:"hpe2y6"}],["path",{d:"m15 6 3.4-3.4a2.1 2.1 0 1 1 3 3L18 9l.4.4a2.1 2.1 0 1 1-3 3l-3.8-3.8a2.1 2.1 0 1 1 3-3l.4.4Z",key:"196du1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ooe=re("Pizza",[["path",{d:"m12 14-1 1",key:"11onhr"}],["path",{d:"m13.75 18.25-1.25 1.42",key:"1yisr3"}],["path",{d:"M17.775 5.654a15.68 15.68 0 0 0-12.121 12.12",key:"1qtqk6"}],["path",{d:"M18.8 9.3a1 1 0 0 0 2.1 7.7",key:"fbbbr2"}],["path",{d:"M21.964 20.732a1 1 0 0 1-1.232 1.232l-18-5a1 1 0 0 1-.695-1.232A19.68 19.68 0 0 1 15.732 2.037a1 1 0 0 1 1.232.695z",key:"1hyfdd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Foe=re("PlaneLanding",[["path",{d:"M2 22h20",key:"272qi7"}],["path",{d:"M3.77 10.77 2 9l2-4.5 1.1.55c.55.28.9.84.9 1.45s.35 1.17.9 1.45L8 8.5l3-6 1.05.53a2 2 0 0 1 1.09 1.52l.72 5.4a2 2 0 0 0 1.09 1.52l4.4 2.2c.42.22.78.55 1.01.96l.6 1.03c.49.88-.06 1.98-1.06 2.1l-1.18.15c-.47.06-.95-.02-1.37-.24L4.29 11.15a2 2 0 0 1-.52-.38Z",key:"1ma21e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zoe=re("PlaneTakeoff",[["path",{d:"M2 22h20",key:"272qi7"}],["path",{d:"M6.36 17.4 4 17l-2-4 1.1-.55a2 2 0 0 1 1.8 0l.17.1a2 2 0 0 0 1.8 0L8 12 5 6l.9-.45a2 2 0 0 1 2.09.2l4.02 3a2 2 0 0 0 2.1.2l4.19-2.06a2.41 2.41 0 0 1 1.73-.17L21 7a1.4 1.4 0 0 1 .87 1.99l-.38.76c-.23.46-.6.84-1.07 1.08L7.58 17.2a2 2 0 0 1-1.22.18Z",key:"fkigj9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const l9=re("Plane",[["path",{d:"M17.8 19.2 16 11l3.5-3.5C21 6 21.5 4 21 3c-1-.5-3 0-4.5 1.5L13 8 4.8 6.2c-.5-.1-.9.1-1.1.5l-.3.5c-.2.5-.1 1 .3 1.3L9 12l-2 3H4l-1 1 3 2 2 3 1-1v-3l3-2 3.5 5.3c.3.4.8.5 1.3.3l.5-.2c.4-.3.6-.7.5-1.2z",key:"1v9wt8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const El=re("Play",[["polygon",{points:"6 3 20 12 6 21 6 3",key:"1oa8hb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Boe=re("Plug2",[["path",{d:"M9 2v6",key:"17ngun"}],["path",{d:"M15 2v6",key:"s7yy2p"}],["path",{d:"M12 17v5",key:"bb1du9"}],["path",{d:"M5 8h14",key:"pcz4l3"}],["path",{d:"M6 11V8h12v3a6 6 0 1 1-12 0Z",key:"wtfw2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sT=re("PlugZap",[["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m18 3-4 4h6l-4 4",key:"16psg9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Y2=re("Plug",[["path",{d:"M12 22v-5",key:"1ega77"}],["path",{d:"M9 8V2",key:"14iosj"}],["path",{d:"M15 8V2",key:"18g5xt"}],["path",{d:"M18 8v5a4 4 0 0 1-4 4h-4a4 4 0 0 1-4-4V8Z",key:"osxo6l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Is=re("Plus",[["path",{d:"M5 12h14",key:"1ays0h"}],["path",{d:"M12 5v14",key:"s699le"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $oe=re("PocketKnife",[["path",{d:"M3 2v1c0 1 2 1 2 2S3 6 3 7s2 1 2 2-2 1-2 2 2 1 2 2",key:"19w3oe"}],["path",{d:"M18 6h.01",key:"1v4wsw"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"M20.83 8.83a4 4 0 0 0-5.66-5.66l-12 12a4 4 0 1 0 5.66 5.66Z",key:"6fykxj"}],["path",{d:"M18 11.66V22a4 4 0 0 0 4-4V6",key:"1utzek"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uoe=re("Pocket",[["path",{d:"M4 3h16a2 2 0 0 1 2 2v6a10 10 0 0 1-10 10A10 10 0 0 1 2 11V5a2 2 0 0 1 2-2z",key:"1mz881"}],["polyline",{points:"8 10 12 14 16 10",key:"w4mbv5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qoe=re("Podcast",[["path",{d:"M16.85 18.58a9 9 0 1 0-9.7 0",key:"d71mpg"}],["path",{d:"M8 14a5 5 0 1 1 8 0",key:"fc81rn"}],["circle",{cx:"12",cy:"11",r:"1",key:"1gvufo"}],["path",{d:"M13 17a1 1 0 1 0-2 0l.5 4.5a.5.5 0 1 0 1 0Z",key:"za5kbj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Voe=re("PointerOff",[["path",{d:"M10 4.5V4a2 2 0 0 0-2.41-1.957",key:"jsi14n"}],["path",{d:"M13.9 8.4a2 2 0 0 0-1.26-1.295",key:"hirc7f"}],["path",{d:"M21.7 16.2A8 8 0 0 0 22 14v-3a2 2 0 1 0-4 0v-1a2 2 0 0 0-3.63-1.158",key:"1jxb2e"}],["path",{d:"m7 15-1.8-1.8a2 2 0 0 0-2.79 2.86L6 19.7a7.74 7.74 0 0 0 6 2.3h2a8 8 0 0 0 5.657-2.343",key:"10r7hm"}],["path",{d:"M6 6v8",key:"tv5xkp"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hoe=re("Pointer",[["path",{d:"M22 14a8 8 0 0 1-8 8",key:"56vcr3"}],["path",{d:"M18 11v-1a2 2 0 0 0-2-2a2 2 0 0 0-2 2",key:"1agjmk"}],["path",{d:"M14 10V9a2 2 0 0 0-2-2a2 2 0 0 0-2 2v1",key:"wdbh2u"}],["path",{d:"M10 9.5V4a2 2 0 0 0-2-2a2 2 0 0 0-2 2v10",key:"1ibuk9"}],["path",{d:"M18 11a2 2 0 1 1 4 0v3a8 8 0 0 1-8 8h-2c-2.8 0-4.5-.86-5.99-2.34l-3.6-3.6a2 2 0 0 1 2.83-2.82L7 15",key:"g6ys72"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Goe=re("Popcorn",[["path",{d:"M18 8a2 2 0 0 0 0-4 2 2 0 0 0-4 0 2 2 0 0 0-4 0 2 2 0 0 0-4 0 2 2 0 0 0 0 4",key:"10td1f"}],["path",{d:"M10 22 9 8",key:"yjptiv"}],["path",{d:"m14 22 1-14",key:"8jwc8b"}],["path",{d:"M20 8c.5 0 .9.4.8 1l-2.6 12c-.1.5-.7 1-1.2 1H7c-.6 0-1.1-.4-1.2-1L3.2 9c-.1-.6.3-1 .8-1Z",key:"1qo33t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Woe=re("Popsicle",[["path",{d:"M18.6 14.4c.8-.8.8-2 0-2.8l-8.1-8.1a4.95 4.95 0 1 0-7.1 7.1l8.1 8.1c.9.7 2.1.7 2.9-.1Z",key:"1o68ps"}],["path",{d:"m22 22-5.5-5.5",key:"17o70y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Koe=re("PoundSterling",[["path",{d:"M18 7c0-5.333-8-5.333-8 0",key:"1prm2n"}],["path",{d:"M10 7v14",key:"18tmcs"}],["path",{d:"M6 21h12",key:"4dkmi1"}],["path",{d:"M6 13h10",key:"ybwr4a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yoe=re("PowerOff",[["path",{d:"M18.36 6.64A9 9 0 0 1 20.77 15",key:"dxknvb"}],["path",{d:"M6.16 6.16a9 9 0 1 0 12.68 12.68",key:"1x7qb5"}],["path",{d:"M12 2v4",key:"3427ic"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const c9=re("Power",[["path",{d:"M12 2v10",key:"mnfbl"}],["path",{d:"M18.4 6.6a9 9 0 1 1-12.77.04",key:"obofu9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ny=re("Presentation",[["path",{d:"M2 3h20",key:"91anmk"}],["path",{d:"M21 3v11a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V3",key:"2k9sn8"}],["path",{d:"m7 21 5-5 5 5",key:"bip4we"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zoe=re("PrinterCheck",[["path",{d:"M13.5 22H7a1 1 0 0 1-1-1v-6a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v.5",key:"qeb09x"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}],["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v2",key:"1md90i"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const d9=re("Printer",[["path",{d:"M6 18H4a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2h-2",key:"143wyd"}],["path",{d:"M6 9V3a1 1 0 0 1 1-1h10a1 1 0 0 1 1 1v6",key:"1itne7"}],["rect",{x:"6",y:"14",width:"12",height:"8",rx:"1",key:"1ue0tg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qoe=re("Projector",[["path",{d:"M5 7 3 5",key:"1yys58"}],["path",{d:"M9 6V3",key:"1ptz9u"}],["path",{d:"m13 7 2-2",key:"1w3vmq"}],["circle",{cx:"9",cy:"13",r:"3",key:"1mma13"}],["path",{d:"M11.83 12H20a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h2.17",key:"2frwzc"}],["path",{d:"M16 16h2",key:"dnq2od"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xoe=re("Proportions",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M12 9v11",key:"1fnkrn"}],["path",{d:"M2 9h13a2 2 0 0 1 2 2v9",key:"11z3ex"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Joe=re("Puzzle",[["path",{d:"M15.39 4.39a1 1 0 0 0 1.68-.474 2.5 2.5 0 1 1 3.014 3.015 1 1 0 0 0-.474 1.68l1.683 1.682a2.414 2.414 0 0 1 0 3.414L19.61 15.39a1 1 0 0 1-1.68-.474 2.5 2.5 0 1 0-3.014 3.015 1 1 0 0 1 .474 1.68l-1.683 1.682a2.414 2.414 0 0 1-3.414 0L8.61 19.61a1 1 0 0 0-1.68.474 2.5 2.5 0 1 1-3.014-3.015 1 1 0 0 0 .474-1.68l-1.683-1.682a2.414 2.414 0 0 1 0-3.414L4.39 8.61a1 1 0 0 1 1.68.474 2.5 2.5 0 1 0 3.014-3.015 1 1 0 0 1-.474-1.68l1.683-1.682a2.414 2.414 0 0 1 3.414 0z",key:"w46dr5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ele=re("Pyramid",[["path",{d:"M2.5 16.88a1 1 0 0 1-.32-1.43l9-13.02a1 1 0 0 1 1.64 0l9 13.01a1 1 0 0 1-.32 1.44l-8.51 4.86a2 2 0 0 1-1.98 0Z",key:"aenxs0"}],["path",{d:"M12 2v20",key:"t6zp3m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ry=re("QrCode",[["rect",{width:"5",height:"5",x:"3",y:"3",rx:"1",key:"1tu5fj"}],["rect",{width:"5",height:"5",x:"16",y:"3",rx:"1",key:"1v8r4q"}],["rect",{width:"5",height:"5",x:"3",y:"16",rx:"1",key:"1x03jg"}],["path",{d:"M21 16h-3a2 2 0 0 0-2 2v3",key:"177gqh"}],["path",{d:"M21 21v.01",key:"ents32"}],["path",{d:"M12 7v3a2 2 0 0 1-2 2H7",key:"8crl2c"}],["path",{d:"M3 12h.01",key:"nlz23k"}],["path",{d:"M12 3h.01",key:"n36tog"}],["path",{d:"M12 16v.01",key:"133mhm"}],["path",{d:"M16 12h1",key:"1slzba"}],["path",{d:"M21 12v.01",key:"1lwtk9"}],["path",{d:"M12 21v-1",key:"1880an"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gw=re("Quote",[["path",{d:"M16 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"rib7q0"}],["path",{d:"M5 3a2 2 0 0 0-2 2v6a2 2 0 0 0 2 2 1 1 0 0 1 1 1v1a2 2 0 0 1-2 2 1 1 0 0 0-1 1v2a1 1 0 0 0 1 1 6 6 0 0 0 6-6V5a2 2 0 0 0-2-2z",key:"1ymkrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tle=re("Rabbit",[["path",{d:"M13 16a3 3 0 0 1 2.24 5",key:"1epib5"}],["path",{d:"M18 12h.01",key:"yjnet6"}],["path",{d:"M18 21h-8a4 4 0 0 1-4-4 7 7 0 0 1 7-7h.2L9.6 6.4a1 1 0 1 1 2.8-2.8L15.8 7h.2c3.3 0 6 2.7 6 6v1a2 2 0 0 1-2 2h-1a3 3 0 0 0-3 3",key:"ue9ozu"}],["path",{d:"M20 8.54V4a2 2 0 1 0-4 0v3",key:"49iql8"}],["path",{d:"M7.612 12.524a3 3 0 1 0-1.6 4.3",key:"1e33i0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IA=re("Radar",[["path",{d:"M19.07 4.93A10 10 0 0 0 6.99 3.34",key:"z3du51"}],["path",{d:"M4 6h.01",key:"oypzma"}],["path",{d:"M2.29 9.62A10 10 0 1 0 21.31 8.35",key:"qzzz0"}],["path",{d:"M16.24 7.76A6 6 0 1 0 8.23 16.67",key:"1yjesh"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M17.99 11.66A6 6 0 0 1 15.77 16.67",key:"1u2y91"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"m13.41 10.59 5.66-5.66",key:"mhq4k0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sle=re("Radiation",[["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M7.5 4.2c-.3-.5-.9-.7-1.3-.4C3.9 5.5 2.3 8.1 2 11c-.1.5.4 1 1 1h5c0-1.5.8-2.8 2-3.4-1.1-1.9-2-3.5-2.5-4.4z",key:"wy49g3"}],["path",{d:"M21 12c.6 0 1-.4 1-1-.3-2.9-1.8-5.5-4.1-7.1-.4-.3-1.1-.2-1.3.3-.6.9-1.5 2.5-2.6 4.3 1.2.7 2 2 2 3.5h5z",key:"vklnvr"}],["path",{d:"M7.5 19.8c-.3.5-.1 1.1.4 1.3 2.6 1.2 5.6 1.2 8.2 0 .5-.2.7-.8.4-1.3-.5-.9-1.4-2.5-2.5-4.3-1.2.7-2.8.7-4 0-1.1 1.8-2 3.4-2.5 4.3z",key:"wkdf1o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nle=re("Radical",[["path",{d:"M3 12h3.28a1 1 0 0 1 .948.684l2.298 7.934a.5.5 0 0 0 .96-.044L13.82 4.771A1 1 0 0 1 14.792 4H21",key:"1mqj8i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rle=re("RadioReceiver",[["path",{d:"M5 16v2",key:"g5qcv5"}],["path",{d:"M19 16v2",key:"1gbaio"}],["rect",{width:"20",height:"8",x:"2",y:"8",rx:"2",key:"vjsjur"}],["path",{d:"M18 12h.01",key:"yjnet6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ale=re("RadioTower",[["path",{d:"M4.9 16.1C1 12.2 1 5.8 4.9 1.9",key:"s0qx1y"}],["path",{d:"M7.8 4.7a6.14 6.14 0 0 0-.8 7.5",key:"1idnkw"}],["circle",{cx:"12",cy:"9",r:"2",key:"1092wv"}],["path",{d:"M16.2 4.8c2 2 2.26 5.11.8 7.47",key:"ojru2q"}],["path",{d:"M19.1 1.9a9.96 9.96 0 0 1 0 14.1",key:"rhi7fg"}],["path",{d:"M9.5 18h5",key:"mfy3pd"}],["path",{d:"m8 22 4-11 4 11",key:"25yftu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yf=re("Radio",[["path",{d:"M4.9 19.1C1 15.2 1 8.8 4.9 4.9",key:"1vaf9d"}],["path",{d:"M7.8 16.2c-2.3-2.3-2.3-6.1 0-8.5",key:"u1ii0m"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}],["path",{d:"M16.2 7.8c2.3 2.3 2.3 6.1 0 8.5",key:"1j5fej"}],["path",{d:"M19.1 4.9C23 8.8 23 15.1 19.1 19",key:"10b0cb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ile=re("Radius",[["path",{d:"M20.34 17.52a10 10 0 1 0-2.82 2.82",key:"fydyku"}],["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["path",{d:"m13.41 13.41 4.18 4.18",key:"1gqbwc"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ole=re("RailSymbol",[["path",{d:"M5 15h14",key:"m0yey3"}],["path",{d:"M5 9h14",key:"7tsvo6"}],["path",{d:"m14 20-5-5 6-6-5-5",key:"1jo42i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lle=re("Rainbow",[["path",{d:"M22 17a10 10 0 0 0-20 0",key:"ozegv"}],["path",{d:"M6 17a6 6 0 0 1 12 0",key:"5giftw"}],["path",{d:"M10 17a2 2 0 0 1 4 0",key:"gnsikk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cle=re("Rat",[["path",{d:"M17 5c0-1.7-1.3-3-3-3s-3 1.3-3 3c0 .8.3 1.5.8 2H11c-3.9 0-7 3.1-7 7c0 2.2 1.8 4 4 4",key:"1wq71c"}],["path",{d:"M16.8 3.9c.3-.3.6-.5 1-.7 1.5-.6 3.3.1 3.9 1.6.6 1.5-.1 3.3-1.6 3.9l1.6 2.8c.2.3.2.7.2 1-.2.8-.9 1.2-1.7 1.1 0 0-1.6-.3-2.7-.6H17c-1.7 0-3 1.3-3 3",key:"1crdmb"}],["path",{d:"M13.2 18a3 3 0 0 0-2.2-5",key:"1ol3lk"}],["path",{d:"M13 22H4a2 2 0 0 1 0-4h12",key:"bt3f23"}],["path",{d:"M16 9h.01",key:"1bdo4e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dle=re("Ratio",[["rect",{width:"12",height:"20",x:"6",y:"2",rx:"2",key:"1oxtiu"}],["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ule=re("ReceiptCent",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M12 6.5v11",key:"ecfhkf"}],["path",{d:"M15 9.4a4 4 0 1 0 0 5.2",key:"1makmb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hle=re("ReceiptEuro",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 12h5",key:"1g6qi8"}],["path",{d:"M16 9.5a4 4 0 1 0 0 5.2",key:"b2px4r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mle=re("ReceiptIndianRupee",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 7h8",key:"i86dvs"}],["path",{d:"M12 17.5 8 15h1a4 4 0 0 0 0-8",key:"grpkl4"}],["path",{d:"M8 11h8",key:"vwpz6n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ple=re("ReceiptJapaneseYen",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"m12 10 3-3",key:"1mc12w"}],["path",{d:"m9 7 3 3v7.5",key:"39i0xv"}],["path",{d:"M9 11h6",key:"1fldmi"}],["path",{d:"M9 15h6",key:"cctwl0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fle=re("ReceiptPoundSterling",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 13h5",key:"1k9z8w"}],["path",{d:"M10 17V9.5a2.5 2.5 0 0 1 5 0",key:"1dzgp0"}],["path",{d:"M8 17h7",key:"8mjdqu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xle=re("ReceiptRussianRuble",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M8 15h5",key:"vxg57a"}],["path",{d:"M8 11h5a2 2 0 1 0 0-4h-3v10",key:"1usi5u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gle=re("ReceiptSwissFranc",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M10 17V7h5",key:"k7jq18"}],["path",{d:"M10 11h4",key:"1i0mka"}],["path",{d:"M8 15h5",key:"vxg57a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yle=re("ReceiptText",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M14 8H8",key:"1l3xfs"}],["path",{d:"M16 12H8",key:"1fr5h0"}],["path",{d:"M13 16H8",key:"wsln4y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vle=re("Receipt",[["path",{d:"M4 2v20l2-1 2 1 2-1 2 1 2-1 2 1 2-1 2 1V2l-2 1-2-1-2 1-2-1-2 1-2-1-2 1Z",key:"q3az6g"}],["path",{d:"M16 8h-6a2 2 0 1 0 0 4h4a2 2 0 1 1 0 4H8",key:"1h4pet"}],["path",{d:"M12 17.5v-11",key:"1jc1ny"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nT=re("RectangleEllipsis",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M17 12h.01",key:"1m0b6t"}],["path",{d:"M7 12h.01",key:"eqddd0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ble=re("RectangleHorizontal",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"2",key:"9lu3g6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _le=re("RectangleVertical",[["rect",{width:"12",height:"20",x:"6",y:"2",rx:"2",key:"1oxtiu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wle=re("Recycle",[["path",{d:"M7 19H4.815a1.83 1.83 0 0 1-1.57-.881 1.785 1.785 0 0 1-.004-1.784L7.196 9.5",key:"x6z5xu"}],["path",{d:"M11 19h8.203a1.83 1.83 0 0 0 1.556-.89 1.784 1.784 0 0 0 0-1.775l-1.226-2.12",key:"1x4zh5"}],["path",{d:"m14 16-3 3 3 3",key:"f6jyew"}],["path",{d:"M8.293 13.596 7.196 9.5 3.1 10.598",key:"wf1obh"}],["path",{d:"m9.344 5.811 1.093-1.892A1.83 1.83 0 0 1 11.985 3a1.784 1.784 0 0 1 1.546.888l3.943 6.843",key:"9tzpgr"}],["path",{d:"m13.378 9.633 4.096 1.098 1.097-4.096",key:"1oe83g"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jle=re("Redo2",[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nle=re("RedoDot",[["circle",{cx:"12",cy:"17",r:"1",key:"1ixnty"}],["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JS=re("Redo",[["path",{d:"M21 7v6h-6",key:"3ptur4"}],["path",{d:"M3 17a9 9 0 0 1 9-9 9 9 0 0 1 6 2.3l3 2.7",key:"1kgawr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kle=re("RefreshCcwDot",[["path",{d:"M3 2v6h6",key:"18ldww"}],["path",{d:"M21 12A9 9 0 0 0 6 5.3L3 8",key:"1pbrqz"}],["path",{d:"M21 22v-6h-6",key:"usdfbe"}],["path",{d:"M3 12a9 9 0 0 0 15 6.7l3-2.7",key:"1hosoe"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dL=re("RefreshCcw",[["path",{d:"M21 12a9 9 0 0 0-9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"14sxne"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}],["path",{d:"M3 12a9 9 0 0 0 9 9 9.75 9.75 0 0 0 6.74-2.74L21 16",key:"1hlbsb"}],["path",{d:"M16 16h5v5",key:"ccwih5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sle=re("RefreshCwOff",[["path",{d:"M21 8L18.74 5.74A9.75 9.75 0 0 0 12 3C11 3 10.03 3.16 9.13 3.47",key:"1krf6h"}],["path",{d:"M8 16H3v5",key:"1cv678"}],["path",{d:"M3 12C3 9.51 4 7.26 5.64 5.64",key:"ruvoct"}],["path",{d:"m3 16 2.26 2.26A9.75 9.75 0 0 0 12 21c2.49 0 4.74-1 6.36-2.64",key:"19q130"}],["path",{d:"M21 12c0 1-.16 1.97-.47 2.87",key:"4w8emr"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M22 22 2 2",key:"1r8tn9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ei=re("RefreshCw",[["path",{d:"M3 12a9 9 0 0 1 9-9 9.75 9.75 0 0 1 6.74 2.74L21 8",key:"v9h5vc"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}],["path",{d:"M21 12a9 9 0 0 1-9 9 9.75 9.75 0 0 1-6.74-2.74L3 16",key:"3uifl3"}],["path",{d:"M8 16H3v5",key:"1cv678"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cle=re("Refrigerator",[["path",{d:"M5 6a4 4 0 0 1 4-4h6a4 4 0 0 1 4 4v14a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V6Z",key:"fpq118"}],["path",{d:"M5 10h14",key:"elsbfy"}],["path",{d:"M15 7v6",key:"1nx30x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tle=re("Regex",[["path",{d:"M17 3v10",key:"15fgeh"}],["path",{d:"m12.67 5.5 8.66 5",key:"1gpheq"}],["path",{d:"m12.67 10.5 8.66-5",key:"1dkfa6"}],["path",{d:"M9 17a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2a2 2 0 0 0 2 2h2a2 2 0 0 0 2-2v-2z",key:"swwfx4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ele=re("RemoveFormatting",[["path",{d:"M4 7V4h16v3",key:"9msm58"}],["path",{d:"M5 20h6",key:"1h6pxn"}],["path",{d:"M13 4 8 20",key:"kqq6aj"}],["path",{d:"m15 15 5 5",key:"me55sn"}],["path",{d:"m20 15-5 5",key:"11p7ol"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ale=re("Repeat1",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}],["path",{d:"M11 10h1v4",key:"70cz1p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mle=re("Repeat2",[["path",{d:"m2 9 3-3 3 3",key:"1ltn5i"}],["path",{d:"M13 18H7a2 2 0 0 1-2-2V6",key:"1r6tfw"}],["path",{d:"m22 15-3 3-3-3",key:"4rnwn2"}],["path",{d:"M11 6h6a2 2 0 0 1 2 2v10",key:"2f72bc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const u9=re("Repeat",[["path",{d:"m17 2 4 4-4 4",key:"nntrym"}],["path",{d:"M3 11v-1a4 4 0 0 1 4-4h14",key:"84bu3i"}],["path",{d:"m7 22-4-4 4-4",key:"1wqhfi"}],["path",{d:"M21 13v1a4 4 0 0 1-4 4H3",key:"1rx37r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ile=re("ReplaceAll",[["path",{d:"M14 14a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"1yyzbs"}],["path",{d:"M14 4a2 2 0 0 1 2-2",key:"1w2hp7"}],["path",{d:"M16 10a2 2 0 0 1-2-2",key:"shjach"}],["path",{d:"M20 14a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2",key:"zfj4xr"}],["path",{d:"M20 2a2 2 0 0 1 2 2",key:"188mtx"}],["path",{d:"M22 8a2 2 0 0 1-2 2",key:"ddf4tu"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a 3 3 0 0 1 3-3h1",key:"1ageje"}],["rect",{x:"2",y:"14",width:"8",height:"8",rx:"2",key:"4rksxw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ple=re("Replace",[["path",{d:"M14 4a2 2 0 0 1 2-2",key:"1w2hp7"}],["path",{d:"M16 10a2 2 0 0 1-2-2",key:"shjach"}],["path",{d:"M20 2a2 2 0 0 1 2 2",key:"188mtx"}],["path",{d:"M22 8a2 2 0 0 1-2 2",key:"ddf4tu"}],["path",{d:"m3 7 3 3 3-3",key:"x25e72"}],["path",{d:"M6 10V5a3 3 0 0 1 3-3h1",key:"3y3t5z"}],["rect",{x:"2",y:"14",width:"8",height:"8",rx:"2",key:"4rksxw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lle=re("ReplyAll",[["polyline",{points:"7 17 2 12 7 7",key:"t83bqg"}],["polyline",{points:"12 17 7 12 12 7",key:"1g4ajm"}],["path",{d:"M22 18v-2a4 4 0 0 0-4-4H7",key:"1fcyog"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const h9=re("Reply",[["polyline",{points:"9 17 4 12 9 7",key:"hvgpf2"}],["path",{d:"M20 18v-2a4 4 0 0 0-4-4H4",key:"5vmcpk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dle=re("Rewind",[["polygon",{points:"11 19 2 12 11 5 11 19",key:"14yba5"}],["polygon",{points:"22 19 13 12 22 5 22 19",key:"1pi1cj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rle=re("Ribbon",[["path",{d:"M12 11.22C11 9.997 10 9 10 8a2 2 0 0 1 4 0c0 1-.998 2.002-2.01 3.22",key:"1rnhq3"}],["path",{d:"m12 18 2.57-3.5",key:"116vt7"}],["path",{d:"M6.243 9.016a7 7 0 0 1 11.507-.009",key:"10dq0b"}],["path",{d:"M9.35 14.53 12 11.22",key:"tdsyp2"}],["path",{d:"M9.35 14.53C7.728 12.246 6 10.221 6 7a6 5 0 0 1 12 0c-.005 3.22-1.778 5.235-3.43 7.5l3.557 4.527a1 1 0 0 1-.203 1.43l-1.894 1.36a1 1 0 0 1-1.384-.215L12 18l-2.679 3.593a1 1 0 0 1-1.39.213l-1.865-1.353a1 1 0 0 1-.203-1.422z",key:"nmifey"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tx=re("Rocket",[["path",{d:"M4.5 16.5c-1.5 1.26-2 5-2 5s3.74-.5 5-2c.71-.84.7-2.13-.09-2.91a2.18 2.18 0 0 0-2.91-.09z",key:"m3kijz"}],["path",{d:"m12 15-3-3a22 22 0 0 1 2-3.95A12.88 12.88 0 0 1 22 2c0 2.72-.78 7.5-6 11a22.35 22.35 0 0 1-4 2z",key:"1fmvmk"}],["path",{d:"M9 12H4s.55-3.03 2-4c1.62-1.08 5 0 5 0",key:"1f8sc4"}],["path",{d:"M12 15v5s3.03-.55 4-2c1.08-1.62 0-5 0-5",key:"qeys4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ole=re("RockingChair",[["polyline",{points:"3.5 2 6.5 12.5 18 12.5",key:"y3iy52"}],["line",{x1:"9.5",x2:"5.5",y1:"12.5",y2:"20",key:"19vg5i"}],["line",{x1:"15",x2:"18.5",y1:"12.5",y2:"20",key:"1inpmv"}],["path",{d:"M2.75 18a13 13 0 0 0 18.5 0",key:"1nquas"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fle=re("RollerCoaster",[["path",{d:"M6 19V5",key:"1r845m"}],["path",{d:"M10 19V6.8",key:"9j2tfs"}],["path",{d:"M14 19v-7.8",key:"10s8qv"}],["path",{d:"M18 5v4",key:"1tajlv"}],["path",{d:"M18 19v-6",key:"ielfq3"}],["path",{d:"M22 19V9",key:"158nzp"}],["path",{d:"M2 19V9a4 4 0 0 1 4-4c2 0 4 1.33 6 4s4 4 6 4a4 4 0 1 0-3-6.65",key:"1930oh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rT=re("Rotate3d",[["path",{d:"M16.466 7.5C15.643 4.237 13.952 2 12 2 9.239 2 7 6.477 7 12s2.239 10 5 10c.342 0 .677-.069 1-.2",key:"10n0gc"}],["path",{d:"m15.194 13.707 3.814 1.86-1.86 3.814",key:"16shm9"}],["path",{d:"M19 15.57c-1.804.885-4.274 1.43-7 1.43-5.523 0-10-2.239-10-5s4.477-5 10-5c4.838 0 8.873 1.718 9.8 4",key:"1lxi77"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zle=re("RotateCcwSquare",[["path",{d:"M20 9V7a2 2 0 0 0-2-2h-6",key:"19z8uc"}],["path",{d:"m15 2-3 3 3 3",key:"177bxs"}],["path",{d:"M20 13v5a2 2 0 0 1-2 2H6a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h2",key:"d36hnl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bm=re("RotateCcw",[["path",{d:"M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8",key:"1357e3"}],["path",{d:"M3 3v5h5",key:"1xhq8a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ble=re("RotateCwSquare",[["path",{d:"M12 5H6a2 2 0 0 0-2 2v3",key:"l96uqu"}],["path",{d:"m9 8 3-3-3-3",key:"1gzgc3"}],["path",{d:"M4 14v4a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V7a2 2 0 0 0-2-2h-2",key:"1w2k5h"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PA=re("RotateCw",[["path",{d:"M21 12a9 9 0 1 1-9-9c2.52 0 4.93 1 6.74 2.74L21 8",key:"1p45f6"}],["path",{d:"M21 3v5h-5",key:"1q7to0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $le=re("RouteOff",[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5c.4 0 .9-.1 1.3-.2",key:"1effex"}],["path",{d:"M5.2 5.2A3.5 3.53 0 0 0 6.5 12H12",key:"k9y2ds"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M21 15.3a3.5 3.5 0 0 0-3.3-3.3",key:"11nlu2"}],["path",{d:"M15 5h-4.3",key:"6537je"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const m9=re("Route",[["circle",{cx:"6",cy:"19",r:"3",key:"1kj8tv"}],["path",{d:"M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15",key:"1d8sl"}],["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ule=re("Router",[["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",key:"w68u3i"}],["path",{d:"M6.01 18H6",key:"19vcac"}],["path",{d:"M10.01 18H10",key:"uamcmx"}],["path",{d:"M15 10v4",key:"qjz1xs"}],["path",{d:"M17.84 7.17a4 4 0 0 0-5.66 0",key:"1rif40"}],["path",{d:"M20.66 4.34a8 8 0 0 0-11.31 0",key:"6a5xfq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aT=re("Rows2",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 12h18",key:"1i2n21"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iT=re("Rows3",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qle=re("Rows4",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 7.5H3",key:"1hm9pq"}],["path",{d:"M21 12H3",key:"2avoz0"}],["path",{d:"M21 16.5H3",key:"n7jzkj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vle=re("Rss",[["path",{d:"M4 11a9 9 0 0 1 9 9",key:"pv89mb"}],["path",{d:"M4 4a16 16 0 0 1 16 16",key:"k0647b"}],["circle",{cx:"5",cy:"19",r:"1",key:"bfqh0e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Z2=re("Ruler",[["path",{d:"M21.3 15.3a2.4 2.4 0 0 1 0 3.4l-2.6 2.6a2.4 2.4 0 0 1-3.4 0L2.7 8.7a2.41 2.41 0 0 1 0-3.4l2.6-2.6a2.41 2.41 0 0 1 3.4 0Z",key:"icamh8"}],["path",{d:"m14.5 12.5 2-2",key:"inckbg"}],["path",{d:"m11.5 9.5 2-2",key:"fmmyf7"}],["path",{d:"m8.5 6.5 2-2",key:"vc6u1g"}],["path",{d:"m17.5 15.5 2-2",key:"wo5hmg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hle=re("RussianRuble",[["path",{d:"M6 11h8a4 4 0 0 0 0-8H9v18",key:"18ai8t"}],["path",{d:"M6 15h8",key:"1y8f6l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gle=re("Sailboat",[["path",{d:"M22 18H2a4 4 0 0 0 4 4h12a4 4 0 0 0 4-4Z",key:"1404fh"}],["path",{d:"M21 14 10 2 3 14h18Z",key:"1nzg7v"}],["path",{d:"M10 2v16",key:"1labyt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wle=re("Salad",[["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 21a9 9 0 0 0 9-9H3a9 9 0 0 0 9 9Z",key:"4rw317"}],["path",{d:"M11.38 12a2.4 2.4 0 0 1-.4-4.77 2.4 2.4 0 0 1 3.2-2.77 2.4 2.4 0 0 1 3.47-.63 2.4 2.4 0 0 1 3.37 3.37 2.4 2.4 0 0 1-1.1 3.7 2.51 2.51 0 0 1 .03 1.1",key:"10xrj0"}],["path",{d:"m13 12 4-4",key:"1hckqy"}],["path",{d:"M10.9 7.25A3.99 3.99 0 0 0 4 10c0 .73.2 1.41.54 2",key:"1p4srx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kle=re("Sandwich",[["path",{d:"m2.37 11.223 8.372-6.777a2 2 0 0 1 2.516 0l8.371 6.777",key:"f1wd0e"}],["path",{d:"M21 15a1 1 0 0 1 1 1v2a1 1 0 0 1-1 1h-5.25",key:"1pfu07"}],["path",{d:"M3 15a1 1 0 0 0-1 1v2a1 1 0 0 0 1 1h9",key:"1oq9qw"}],["path",{d:"m6.67 15 6.13 4.6a2 2 0 0 0 2.8-.4l3.15-4.2",key:"1fnwu5"}],["rect",{width:"20",height:"4",x:"2",y:"11",rx:"1",key:"itshg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yle=re("SatelliteDish",[["path",{d:"M4 10a7.31 7.31 0 0 0 10 10Z",key:"1fzpp3"}],["path",{d:"m9 15 3-3",key:"88sc13"}],["path",{d:"M17 13a6 6 0 0 0-6-6",key:"15cc6u"}],["path",{d:"M21 13A10 10 0 0 0 11 3",key:"11nf8s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zle=re("Satellite",[["path",{d:"M13 7 9 3 5 7l4 4",key:"vyckw6"}],["path",{d:"m17 11 4 4-4 4-4-4",key:"rchckc"}],["path",{d:"m8 12 4 4 6-6-4-4Z",key:"1sshf7"}],["path",{d:"m16 8 3-3",key:"x428zp"}],["path",{d:"M9 21a6 6 0 0 0-6-6",key:"1iajcf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qle=re("SaveAll",[["path",{d:"M10 2v3a1 1 0 0 0 1 1h5",key:"1xspal"}],["path",{d:"M18 18v-6a1 1 0 0 0-1-1h-6a1 1 0 0 0-1 1v6",key:"1ra60u"}],["path",{d:"M18 22H4a2 2 0 0 1-2-2V6",key:"pblm9e"}],["path",{d:"M8 18a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h9.172a2 2 0 0 1 1.414.586l2.828 2.828A2 2 0 0 1 22 6.828V16a2 2 0 0 1-2.01 2z",key:"1yve0x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xle=re("SaveOff",[["path",{d:"M13 13H8a1 1 0 0 0-1 1v7",key:"h8g396"}],["path",{d:"M14 8h1",key:"1lfen6"}],["path",{d:"M17 21v-4",key:"1yknxs"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M20.41 20.41A2 2 0 0 1 19 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 .59-1.41",key:"1t4vdl"}],["path",{d:"M29.5 11.5s5 5 4 5",key:"zzn4i6"}],["path",{d:"M9 3h6.2a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V15",key:"24cby9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jo=re("Save",[["path",{d:"M15.2 3a2 2 0 0 1 1.4.6l3.8 3.8a2 2 0 0 1 .6 1.4V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2z",key:"1c8476"}],["path",{d:"M17 21v-7a1 1 0 0 0-1-1H8a1 1 0 0 0-1 1v7",key:"1ydtos"}],["path",{d:"M7 3v4a1 1 0 0 0 1 1h7",key:"t51u73"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oT=re("Scale3d",[["path",{d:"M5 7v11a1 1 0 0 0 1 1h11",key:"13dt1j"}],["path",{d:"M5.293 18.707 11 13",key:"ezgbsx"}],["circle",{cx:"19",cy:"19",r:"2",key:"17f5cg"}],["circle",{cx:"5",cy:"5",r:"2",key:"1gwv83"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const p9=re("Scale",[["path",{d:"m16 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"7g6ntu"}],["path",{d:"m2 16 3-8 3 8c-.87.65-1.92 1-3 1s-2.13-.35-3-1Z",key:"ijws7r"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M12 3v18",key:"108xh3"}],["path",{d:"M3 7h2c2 0 5-1 7-2 2 1 5 2 7 2h2",key:"3gwbw2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jle=re("Scaling",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M14 15H9v-5",key:"pi4jk9"}],["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M21 3 9 15",key:"15kdhq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ece=re("ScanBarcode",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 7v10",key:"23sfjj"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M17 7v10",key:"578dap"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tce=re("ScanEye",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sce=re("ScanFace",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 9h.01",key:"x1ddxp"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nce=re("ScanLine",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 12h10",key:"b7w52i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rce=re("ScanQrCode",[["path",{d:"M17 12v4a1 1 0 0 1-1 1h-4",key:"uk4fdo"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M17 8V7",key:"q2g9wo"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M7 17h.01",key:"19xn7k"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["rect",{x:"7",y:"7",width:"5",height:"5",rx:"1",key:"m9kyts"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ace=re("ScanSearch",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m16 16-1.9-1.9",key:"1dq9hf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ice=re("ScanText",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}],["path",{d:"M7 8h8",key:"1jbsf9"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h6",key:"1vyc9m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oce=re("Scan",[["path",{d:"M3 7V5a2 2 0 0 1 2-2h2",key:"aa7l1z"}],["path",{d:"M17 3h2a2 2 0 0 1 2 2v2",key:"4qcy5o"}],["path",{d:"M21 17v2a2 2 0 0 1-2 2h-2",key:"6vwrx8"}],["path",{d:"M7 21H5a2 2 0 0 1-2-2v-2",key:"ioqczr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lce=re("School",[["path",{d:"M14 22v-4a2 2 0 1 0-4 0v4",key:"hhkicm"}],["path",{d:"m18 10 3.447 1.724a1 1 0 0 1 .553.894V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2v-7.382a1 1 0 0 1 .553-.894L6 10",key:"1xqip1"}],["path",{d:"M18 5v17",key:"1sw6gf"}],["path",{d:"m4 6 7.106-3.553a2 2 0 0 1 1.788 0L20 6",key:"9d2mlk"}],["path",{d:"M6 5v17",key:"1xfsm0"}],["circle",{cx:"12",cy:"9",r:"2",key:"1092wv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cce=re("ScissorsLineDashed",[["path",{d:"M5.42 9.42 8 12",key:"12pkuq"}],["circle",{cx:"4",cy:"8",r:"2",key:"107mxr"}],["path",{d:"m14 6-8.58 8.58",key:"gvzu5l"}],["circle",{cx:"4",cy:"16",r:"2",key:"1ehqvc"}],["path",{d:"M10.8 14.8 14 18",key:"ax7m9r"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dce=re("Scissors",[["circle",{cx:"6",cy:"6",r:"3",key:"1lh9wr"}],["path",{d:"M8.12 8.12 12 12",key:"1alkpv"}],["path",{d:"M20 4 8.12 15.88",key:"xgtan2"}],["circle",{cx:"6",cy:"18",r:"3",key:"fqmcym"}],["path",{d:"M14.8 14.8 20 20",key:"ptml3r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uce=re("ScreenShareOff",[["path",{d:"M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3",key:"i8wdob"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m22 3-5 5",key:"12jva0"}],["path",{d:"m17 3 5 5",key:"k36vhe"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hce=re("ScreenShare",[["path",{d:"M13 3H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-3",key:"i8wdob"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}],["path",{d:"m17 8 5-5",key:"fqif7o"}],["path",{d:"M17 3h5v5",key:"1o3tu8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const f9=re("ScrollText",[["path",{d:"M15 12h-5",key:"r7krc0"}],["path",{d:"M15 8h-5",key:"1khuty"}],["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mce=re("Scroll",[["path",{d:"M19 17V5a2 2 0 0 0-2-2H4",key:"zz82l3"}],["path",{d:"M8 21h12a2 2 0 0 0 2-2v-1a1 1 0 0 0-1-1H11a1 1 0 0 0-1 1v1a2 2 0 1 1-4 0V5a2 2 0 1 0-4 0v2a1 1 0 0 0 1 1h3",key:"1ph1d7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pce=re("SearchCheck",[["path",{d:"m8 11 2 2 4-4",key:"1sed1v"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fce=re("SearchCode",[["path",{d:"m13 13.5 2-2.5-2-2.5",key:"1rvxrh"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}],["path",{d:"M9 8.5 7 11l2 2.5",key:"6ffwbx"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xce=re("SearchSlash",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const x9=re("SearchX",[["path",{d:"m13.5 8.5-5 5",key:"1cs55j"}],["path",{d:"m8.5 8.5 5 5",key:"a8mexj"}],["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gr=re("Search",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["path",{d:"m21 21-4.3-4.3",key:"1qie3q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gce=re("Section",[["path",{d:"M16 5a4 3 0 0 0-8 0c0 4 8 3 8 7a4 3 0 0 1-8 0",key:"vqan6v"}],["path",{d:"M8 19a4 3 0 0 0 8 0c0-4-8-3-8-7a4 3 0 0 1 8 0",key:"wdjd8o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lT=re("SendHorizontal",[["path",{d:"M3.714 3.048a.498.498 0 0 0-.683.627l2.843 7.627a2 2 0 0 1 0 1.396l-2.842 7.627a.498.498 0 0 0 .682.627l18-8.5a.5.5 0 0 0 0-.904z",key:"117uat"}],["path",{d:"M6 12h16",key:"s4cdu5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yce=re("SendToBack",[["rect",{x:"14",y:"14",width:"8",height:"8",rx:"2",key:"1b0bso"}],["rect",{x:"2",y:"2",width:"8",height:"8",rx:"2",key:"1x09vl"}],["path",{d:"M7 14v1a2 2 0 0 0 2 2h1",key:"pao6x6"}],["path",{d:"M14 7h1a2 2 0 0 1 2 2v1",key:"19tdru"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lr=re("Send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vce=re("SeparatorHorizontal",[["line",{x1:"3",x2:"21",y1:"12",y2:"12",key:"10d38w"}],["polyline",{points:"8 8 12 4 16 8",key:"zo8t4w"}],["polyline",{points:"16 16 12 20 8 16",key:"1oyrid"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bce=re("SeparatorVertical",[["line",{x1:"12",x2:"12",y1:"3",y2:"21",key:"1efggb"}],["polyline",{points:"8 8 4 12 8 16",key:"bnfmv4"}],["polyline",{points:"16 16 20 12 16 8",key:"u90052"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ce=re("ServerCog",[["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"M4.5 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-.5",key:"tn8das"}],["path",{d:"M4.5 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-.5",key:"1g2pve"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m15.7 13.4-.9-.3",key:"1jwmzr"}],["path",{d:"m9.2 10.9-.9-.3",key:"qapnim"}],["path",{d:"m10.6 15.7.3-.9",key:"quwk0k"}],["path",{d:"m13.6 15.7-.4-1",key:"cb9xp7"}],["path",{d:"m10.8 9.3-.4-1",key:"1uaiz5"}],["path",{d:"m8.3 13.6 1-.4",key:"s6srou"}],["path",{d:"m14.7 10.8 1-.4",key:"4d31cq"}],["path",{d:"m13.4 8.3-.3.9",key:"1bm987"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wce=re("ServerCrash",[["path",{d:"M6 10H4a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-2",key:"4b9dqc"}],["path",{d:"M6 14H4a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-4a2 2 0 0 0-2-2h-2",key:"22nnkd"}],["path",{d:"M6 6h.01",key:"1utrut"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m13 6-4 6h6l-4 6",key:"14hqih"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jce=re("ServerOff",[["path",{d:"M7 2h13a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-5",key:"bt2siv"}],["path",{d:"M10 10 2.5 2.5C2 2 2 2.5 2 5v3a2 2 0 0 0 2 2h6z",key:"1hjrv1"}],["path",{d:"M22 17v-1a2 2 0 0 0-2-2h-1",key:"1iynyr"}],["path",{d:"M4 14a2 2 0 0 0-2 2v4a2 2 0 0 0 2 2h16.5l1-.5.5.5-8-8H4z",key:"161ggg"}],["path",{d:"M6 18h.01",key:"uhywen"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nce=re("Server",[["rect",{width:"20",height:"8",x:"2",y:"2",rx:"2",ry:"2",key:"ngkwjq"}],["rect",{width:"20",height:"8",x:"2",y:"14",rx:"2",ry:"2",key:"iecqi9"}],["line",{x1:"6",x2:"6.01",y1:"6",y2:"6",key:"16zg32"}],["line",{x1:"6",x2:"6.01",y1:"18",y2:"18",key:"nzw8ys"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const g9=re("Settings2",[["path",{d:"M20 7h-9",key:"3s1dr2"}],["path",{d:"M14 17H5",key:"gfn3mx"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["circle",{cx:"7",cy:"7",r:"3",key:"dfmy0x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ko=re("Settings",[["path",{d:"M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z",key:"1qme2f"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kce=re("Shapes",[["path",{d:"M8.3 10a.7.7 0 0 1-.626-1.079L11.4 3a.7.7 0 0 1 1.198-.043L16.3 8.9a.7.7 0 0 1-.572 1.1Z",key:"1bo67w"}],["rect",{x:"3",y:"14",width:"7",height:"7",rx:"1",key:"1bkyp8"}],["circle",{cx:"17.5",cy:"17.5",r:"3.5",key:"w3z12y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vl=re("Share2",[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const y9=re("Share",[["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["polyline",{points:"16 6 12 2 8 6",key:"m901s6"}],["line",{x1:"12",x2:"12",y1:"2",y2:"15",key:"1p0rca"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sce=re("Sheet",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["line",{x1:"3",x2:"21",y1:"9",y2:"9",key:"1vqk6q"}],["line",{x1:"3",x2:"21",y1:"15",y2:"15",key:"o2sbyz"}],["line",{x1:"9",x2:"9",y1:"9",y2:"21",key:"1ib60c"}],["line",{x1:"15",x2:"15",y1:"9",y2:"21",key:"1n26ft"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cce=re("Shell",[["path",{d:"M14 11a2 2 0 1 1-4 0 4 4 0 0 1 8 0 6 6 0 0 1-12 0 8 8 0 0 1 16 0 10 10 0 1 1-20 0 11.93 11.93 0 0 1 2.42-7.22 2 2 0 1 1 3.16 2.44",key:"1cn552"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uL=re("ShieldAlert",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 8v4",key:"1got3b"}],["path",{d:"M12 16h.01",key:"1drbdi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tce=re("ShieldBan",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m4.243 5.21 14.39 12.472",key:"1c9a7c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eg=re("ShieldCheck",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ece=re("ShieldEllipsis",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M8 12h.01",key:"czm47f"}],["path",{d:"M12 12h.01",key:"1mp3jc"}],["path",{d:"M16 12h.01",key:"1l6xoz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ace=re("ShieldHalf",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M12 22V2",key:"zs6s6o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mce=re("ShieldMinus",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9 12h6",key:"1c52cq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LA=re("ShieldOff",[["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M5 5a1 1 0 0 0-1 1v7c0 5 3.5 7.5 7.67 8.94a1 1 0 0 0 .67.01c2.35-.82 4.48-1.97 5.9-3.71",key:"1jlk70"}],["path",{d:"M9.309 3.652A12.252 12.252 0 0 0 11.24 2.28a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1v7a9.784 9.784 0 0 1-.08 1.264",key:"18rp1v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ice=re("ShieldPlus",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9 12h6",key:"1c52cq"}],["path",{d:"M12 9v6",key:"199k2o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pce=re("ShieldQuestion",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"M9.1 9a3 3 0 0 1 5.82 1c0 2-3 3-3 3",key:"mhlwft"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cT=re("ShieldX",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}],["path",{d:"m14.5 9.5-5 5",key:"17q4r4"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ih=re("Shield",[["path",{d:"M20 13c0 5-3.5 7.5-7.66 8.95a1 1 0 0 1-.67-.01C7.5 20.5 4 18 4 13V6a1 1 0 0 1 1-1c2 0 4.5-1.2 6.24-2.72a1.17 1.17 0 0 1 1.52 0C14.51 3.81 17 5 19 5a1 1 0 0 1 1 1z",key:"oel41y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lce=re("ShipWheel",[["circle",{cx:"12",cy:"12",r:"8",key:"46899m"}],["path",{d:"M12 2v7.5",key:"1e5rl5"}],["path",{d:"m19 5-5.23 5.23",key:"1ezxxf"}],["path",{d:"M22 12h-7.5",key:"le1719"}],["path",{d:"m19 19-5.23-5.23",key:"p3fmgn"}],["path",{d:"M12 14.5V22",key:"dgcmos"}],["path",{d:"M10.23 13.77 5 19",key:"qwopd4"}],["path",{d:"M9.5 12H2",key:"r7bup8"}],["path",{d:"M10.23 10.23 5 5",key:"k2y7lj"}],["circle",{cx:"12",cy:"12",r:"2.5",key:"ix0uyj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dce=re("Ship",[["path",{d:"M12 10.189V14",key:"1p8cqu"}],["path",{d:"M12 2v3",key:"qbqxhf"}],["path",{d:"M19 13V7a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2v6",key:"qpkstq"}],["path",{d:"M19.38 20A11.6 11.6 0 0 0 21 14l-8.188-3.639a2 2 0 0 0-1.624 0L3 14a11.6 11.6 0 0 0 2.81 7.76",key:"7tigtc"}],["path",{d:"M2 21c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1s1.2 1 2.5 1c2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"1924j5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rce=re("Shirt",[["path",{d:"M20.38 3.46 16 2a4 4 0 0 1-8 0L3.62 3.46a2 2 0 0 0-1.34 2.23l.58 3.47a1 1 0 0 0 .99.84H6v10c0 1.1.9 2 2 2h8a2 2 0 0 0 2-2V10h2.15a1 1 0 0 0 .99-.84l.58-3.47a2 2 0 0 0-1.34-2.23z",key:"1wgbhj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yw=re("ShoppingBag",[["path",{d:"M6 2 3 6v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V6l-3-4Z",key:"hou9p0"}],["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M16 10a4 4 0 0 1-8 0",key:"1ltviw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oce=re("ShoppingBasket",[["path",{d:"m15 11-1 9",key:"5wnq3a"}],["path",{d:"m19 11-4-7",key:"cnml18"}],["path",{d:"M2 11h20",key:"3eubbj"}],["path",{d:"m3.5 11 1.6 7.4a2 2 0 0 0 2 1.6h9.8a2 2 0 0 0 2-1.6l1.7-7.4",key:"yiazzp"}],["path",{d:"M4.5 15.5h15",key:"13mye1"}],["path",{d:"m5 11 4-7",key:"116ra9"}],["path",{d:"m9 11 1 9",key:"1ojof7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dg=re("ShoppingCart",[["circle",{cx:"8",cy:"21",r:"1",key:"jimo8o"}],["circle",{cx:"19",cy:"21",r:"1",key:"13723u"}],["path",{d:"M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12",key:"9zh506"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fce=re("Shovel",[["path",{d:"M2 22v-5l5-5 5 5-5 5z",key:"1fh25c"}],["path",{d:"M9.5 14.5 16 8",key:"1smz5x"}],["path",{d:"m17 2 5 5-.5.5a3.53 3.53 0 0 1-5 0s0 0 0 0a3.53 3.53 0 0 1 0-5L17 2",key:"1q8uv5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zce=re("ShowerHead",[["path",{d:"m4 4 2.5 2.5",key:"uv2vmf"}],["path",{d:"M13.5 6.5a4.95 4.95 0 0 0-7 7",key:"frdkwv"}],["path",{d:"M15 5 5 15",key:"1ag8rq"}],["path",{d:"M14 17v.01",key:"eokfpp"}],["path",{d:"M10 16v.01",key:"14uyyl"}],["path",{d:"M13 13v.01",key:"1v1k97"}],["path",{d:"M16 10v.01",key:"5169yg"}],["path",{d:"M11 20v.01",key:"cj92p8"}],["path",{d:"M17 14v.01",key:"11cswd"}],["path",{d:"M20 11v.01",key:"19e0od"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bce=re("Shrink",[["path",{d:"m15 15 6 6m-6-6v4.8m0-4.8h4.8",key:"17vawe"}],["path",{d:"M9 19.8V15m0 0H4.2M9 15l-6 6",key:"chjx8e"}],["path",{d:"M15 4.2V9m0 0h4.8M15 9l6-6",key:"lav6yq"}],["path",{d:"M9 4.2V9m0 0H4.2M9 9 3 3",key:"1pxi2q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ce=re("Shrub",[["path",{d:"M12 22v-7l-2-2",key:"eqv9mc"}],["path",{d:"M17 8v.8A6 6 0 0 1 13.8 20H10A6.5 6.5 0 0 1 7 8a5 5 0 0 1 10 0Z",key:"ubcgy"}],["path",{d:"m14 14-2 2",key:"847xa2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DA=re("Shuffle",[["path",{d:"m18 14 4 4-4 4",key:"10pe0f"}],["path",{d:"m18 2 4 4-4 4",key:"pucp1d"}],["path",{d:"M2 18h1.973a4 4 0 0 0 3.3-1.7l5.454-8.6a4 4 0 0 1 3.3-1.7H22",key:"1ailkh"}],["path",{d:"M2 6h1.972a4 4 0 0 1 3.6 2.2",key:"km57vx"}],["path",{d:"M22 18h-6.041a4 4 0 0 1-3.3-1.8l-.359-.45",key:"os18l9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uce=re("Sigma",[["path",{d:"M18 7V5a1 1 0 0 0-1-1H6.5a.5.5 0 0 0-.4.8l4.5 6a2 2 0 0 1 0 2.4l-4.5 6a.5.5 0 0 0 .4.8H17a1 1 0 0 0 1-1v-2",key:"wuwx1p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qce=re("SignalHigh",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M17 20V8",key:"1tkaf5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vce=re("SignalLow",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hce=re("SignalMedium",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gce=re("SignalZero",[["path",{d:"M2 20h.01",key:"4haj6o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wce=re("Signal",[["path",{d:"M2 20h.01",key:"4haj6o"}],["path",{d:"M7 20v-4",key:"j294jx"}],["path",{d:"M12 20v-8",key:"i3yub9"}],["path",{d:"M17 20V8",key:"1tkaf5"}],["path",{d:"M22 4v16",key:"sih9yq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kce=re("Signature",[["path",{d:"m21 17-2.156-1.868A.5.5 0 0 0 18 15.5v.5a1 1 0 0 1-1 1h-2a1 1 0 0 1-1-1c0-2.545-3.991-3.97-8.5-4a1 1 0 0 0 0 5c4.153 0 4.745-11.295 5.708-13.5a2.5 2.5 0 1 1 3.31 3.284",key:"y32ogt"}],["path",{d:"M3 21h18",key:"itz85i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yce=re("SignpostBig",[["path",{d:"M10 9H4L2 7l2-2h6",key:"1hq7x2"}],["path",{d:"M14 5h6l2 2-2 2h-6",key:"bv62ej"}],["path",{d:"M10 22V4a2 2 0 1 1 4 0v18",key:"eqpcf2"}],["path",{d:"M8 22h8",key:"rmew8v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zce=re("Signpost",[["path",{d:"M12 13v8",key:"1l5pq0"}],["path",{d:"M12 3v3",key:"1n5kay"}],["path",{d:"M18 6a2 2 0 0 1 1.387.56l2.307 2.22a1 1 0 0 1 0 1.44l-2.307 2.22A2 2 0 0 1 18 13H6a2 2 0 0 1-1.387-.56l-2.306-2.22a1 1 0 0 1 0-1.44l2.306-2.22A2 2 0 0 1 6 6z",key:"gqqp9m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qce=re("Siren",[["path",{d:"M7 18v-6a5 5 0 1 1 10 0v6",key:"pcx96s"}],["path",{d:"M5 21a1 1 0 0 0 1 1h12a1 1 0 0 0 1-1v-1a2 2 0 0 0-2-2H7a2 2 0 0 0-2 2z",key:"1b4s83"}],["path",{d:"M21 12h1",key:"jtio3y"}],["path",{d:"M18.5 4.5 18 5",key:"g5sp9y"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"m4.929 4.929.707.707",key:"1i51kw"}],["path",{d:"M12 12v6",key:"3ahymv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xce=re("SkipBack",[["polygon",{points:"19 20 9 12 19 4 19 20",key:"o2sva"}],["line",{x1:"5",x2:"5",y1:"19",y2:"5",key:"1ocqjk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jce=re("SkipForward",[["polygon",{points:"5 4 15 12 5 20 5 4",key:"16p6eg"}],["line",{x1:"19",x2:"19",y1:"5",y2:"19",key:"futhcm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ede=re("Skull",[["path",{d:"m12.5 17-.5-1-.5 1h1z",key:"3me087"}],["path",{d:"M15 22a1 1 0 0 0 1-1v-1a2 2 0 0 0 1.56-3.25 8 8 0 1 0-11.12 0A2 2 0 0 0 8 20v1a1 1 0 0 0 1 1z",key:"1o5pge"}],["circle",{cx:"15",cy:"12",r:"1",key:"1tmaij"}],["circle",{cx:"9",cy:"12",r:"1",key:"1vctgf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tde=re("Slack",[["rect",{width:"3",height:"8",x:"13",y:"2",rx:"1.5",key:"diqz80"}],["path",{d:"M19 8.5V10h1.5A1.5 1.5 0 1 0 19 8.5",key:"183iwg"}],["rect",{width:"3",height:"8",x:"8",y:"14",rx:"1.5",key:"hqg7r1"}],["path",{d:"M5 15.5V14H3.5A1.5 1.5 0 1 0 5 15.5",key:"76g71w"}],["rect",{width:"8",height:"3",x:"14",y:"13",rx:"1.5",key:"1kmz0a"}],["path",{d:"M15.5 19H14v1.5a1.5 1.5 0 1 0 1.5-1.5",key:"jc4sz0"}],["rect",{width:"8",height:"3",x:"2",y:"8",rx:"1.5",key:"1omvl4"}],["path",{d:"M8.5 5H10V3.5A1.5 1.5 0 1 0 8.5 5",key:"16f3cl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sde=re("Slash",[["path",{d:"M22 2 2 22",key:"y4kqgn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nde=re("Slice",[["path",{d:"M11 16.586V19a1 1 0 0 1-1 1H2L18.37 3.63a1 1 0 1 1 3 3l-9.663 9.663a1 1 0 0 1-1.414 0L8 14",key:"1sllp5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const e4=re("SlidersHorizontal",[["line",{x1:"21",x2:"14",y1:"4",y2:"4",key:"obuewd"}],["line",{x1:"10",x2:"3",y1:"4",y2:"4",key:"1q6298"}],["line",{x1:"21",x2:"12",y1:"12",y2:"12",key:"1iu8h1"}],["line",{x1:"8",x2:"3",y1:"12",y2:"12",key:"ntss68"}],["line",{x1:"21",x2:"16",y1:"20",y2:"20",key:"14d8ph"}],["line",{x1:"12",x2:"3",y1:"20",y2:"20",key:"m0wm8r"}],["line",{x1:"14",x2:"14",y1:"2",y2:"6",key:"14e1ph"}],["line",{x1:"8",x2:"8",y1:"10",y2:"14",key:"1i6ji0"}],["line",{x1:"16",x2:"16",y1:"18",y2:"22",key:"1lctlv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dT=re("SlidersVertical",[["line",{x1:"4",x2:"4",y1:"21",y2:"14",key:"1p332r"}],["line",{x1:"4",x2:"4",y1:"10",y2:"3",key:"gb41h5"}],["line",{x1:"12",x2:"12",y1:"21",y2:"12",key:"hf2csr"}],["line",{x1:"12",x2:"12",y1:"8",y2:"3",key:"1kfi7u"}],["line",{x1:"20",x2:"20",y1:"21",y2:"16",key:"1lhrwl"}],["line",{x1:"20",x2:"20",y1:"12",y2:"3",key:"16vvfq"}],["line",{x1:"2",x2:"6",y1:"14",y2:"14",key:"1uebub"}],["line",{x1:"10",x2:"14",y1:"8",y2:"8",key:"1yglbp"}],["line",{x1:"18",x2:"22",y1:"16",y2:"16",key:"1jxqpz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rde=re("SmartphoneCharging",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12.667 8 10 12h4l-2.667 4",key:"h9lk2d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ade=re("SmartphoneNfc",[["rect",{width:"7",height:"12",x:"2",y:"6",rx:"1",key:"5nje8w"}],["path",{d:"M13 8.32a7.43 7.43 0 0 1 0 7.36",key:"1g306n"}],["path",{d:"M16.46 6.21a11.76 11.76 0 0 1 0 11.58",key:"uqvjvo"}],["path",{d:"M19.91 4.1a15.91 15.91 0 0 1 .01 15.8",key:"ujntz3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tg=re("Smartphone",[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ide=re("SmilePlus",[["path",{d:"M22 11v1a10 10 0 1 1-9-10",key:"ew0xw9"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}],["path",{d:"M16 5h6",key:"1vod17"}],["path",{d:"M19 2v6",key:"4bpg5p"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ode=re("Smile",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M8 14s1.5 2 4 2 4-2 4-2",key:"1y1vjs"}],["line",{x1:"9",x2:"9.01",y1:"9",y2:"9",key:"yxxnd0"}],["line",{x1:"15",x2:"15.01",y1:"9",y2:"9",key:"1p4y9e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lde=re("Snail",[["path",{d:"M2 13a6 6 0 1 0 12 0 4 4 0 1 0-8 0 2 2 0 0 0 4 0",key:"hneq2s"}],["circle",{cx:"10",cy:"13",r:"8",key:"194lz3"}],["path",{d:"M2 21h12c4.4 0 8-3.6 8-8V7a2 2 0 1 0-4 0v6",key:"ixqyt7"}],["path",{d:"M18 3 19.1 5.2",key:"9tjm43"}],["path",{d:"M22 3 20.9 5.2",key:"j3odrs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tv=re("Snowflake",[["line",{x1:"2",x2:"22",y1:"12",y2:"12",key:"1dnqot"}],["line",{x1:"12",x2:"12",y1:"2",y2:"22",key:"7eqyqh"}],["path",{d:"m20 16-4-4 4-4",key:"rquw4f"}],["path",{d:"m4 8 4 4-4 4",key:"12s3z9"}],["path",{d:"m16 4-4 4-4-4",key:"1tumq1"}],["path",{d:"m8 20 4-4 4 4",key:"9p200w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cde=re("Sofa",[["path",{d:"M20 9V6a2 2 0 0 0-2-2H6a2 2 0 0 0-2 2v3",key:"1dgpiv"}],["path",{d:"M2 16a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-5a2 2 0 0 0-4 0v1.5a.5.5 0 0 1-.5.5h-11a.5.5 0 0 1-.5-.5V11a2 2 0 0 0-4 0z",key:"xacw8m"}],["path",{d:"M4 18v2",key:"jwo5n2"}],["path",{d:"M20 18v2",key:"1ar1qi"}],["path",{d:"M12 4v9",key:"oqhhn3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dde=re("Soup",[["path",{d:"M12 21a9 9 0 0 0 9-9H3a9 9 0 0 0 9 9Z",key:"4rw317"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["path",{d:"M19.5 12 22 6",key:"shfsr5"}],["path",{d:"M16.25 3c.27.1.8.53.75 1.36-.06.83-.93 1.2-1 2.02-.05.78.34 1.24.73 1.62",key:"rpc6vp"}],["path",{d:"M11.25 3c.27.1.8.53.74 1.36-.05.83-.93 1.2-.98 2.02-.06.78.33 1.24.72 1.62",key:"1lf63m"}],["path",{d:"M6.25 3c.27.1.8.53.75 1.36-.06.83-.93 1.2-1 2.02-.05.78.34 1.24.74 1.62",key:"97tijn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ude=re("Space",[["path",{d:"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1",key:"lt2kga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hde=re("Spade",[["path",{d:"M5 9c-1.5 1.5-3 3.2-3 5.5A5.5 5.5 0 0 0 7.5 20c1.8 0 3-.5 4.5-2 1.5 1.5 2.7 2 4.5 2a5.5 5.5 0 0 0 5.5-5.5c0-2.3-1.5-4-3-5.5l-7-7-7 7Z",key:"40bo9n"}],["path",{d:"M12 18v4",key:"jadmvz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const t4=re("Sparkle",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const un=re("Sparkles",[["path",{d:"M9.937 15.5A2 2 0 0 0 8.5 14.063l-6.135-1.582a.5.5 0 0 1 0-.962L8.5 9.936A2 2 0 0 0 9.937 8.5l1.582-6.135a.5.5 0 0 1 .963 0L14.063 8.5A2 2 0 0 0 15.5 9.937l6.135 1.581a.5.5 0 0 1 0 .964L15.5 14.063a2 2 0 0 0-1.437 1.437l-1.582 6.135a.5.5 0 0 1-.963 0z",key:"4pj2yx"}],["path",{d:"M20 3v4",key:"1olli1"}],["path",{d:"M22 5h-4",key:"1gvqau"}],["path",{d:"M4 17v2",key:"vumght"}],["path",{d:"M5 18H3",key:"zchphs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mde=re("Speaker",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",key:"1nb95v"}],["path",{d:"M12 6h.01",key:"1vi96p"}],["circle",{cx:"12",cy:"14",r:"4",key:"1jruaj"}],["path",{d:"M12 14h.01",key:"1etili"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pde=re("Speech",[["path",{d:"M8.8 20v-4.1l1.9.2a2.3 2.3 0 0 0 2.164-2.1V8.3A5.37 5.37 0 0 0 2 8.25c0 2.8.656 3.054 1 4.55a5.77 5.77 0 0 1 .029 2.758L2 20",key:"11atix"}],["path",{d:"M19.8 17.8a7.5 7.5 0 0 0 .003-10.603",key:"yol142"}],["path",{d:"M17 15a3.5 3.5 0 0 0-.025-4.975",key:"ssbmkc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fde=re("SpellCheck2",[["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M4 21c1.1 0 1.1-1 2.3-1s1.1 1 2.3 1c1.1 0 1.1-1 2.3-1 1.1 0 1.1 1 2.3 1 1.1 0 1.1-1 2.3-1 1.1 0 1.1 1 2.3 1 1.1 0 1.1-1 2.3-1",key:"8mdmtu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xde=re("SpellCheck",[["path",{d:"m6 16 6-12 6 12",key:"1b4byz"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m16 20 2 2 4-4",key:"13tcca"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gde=re("Spline",[["circle",{cx:"19",cy:"5",r:"2",key:"mhkx31"}],["circle",{cx:"5",cy:"19",r:"2",key:"v8kfzx"}],["path",{d:"M5 17A12 12 0 0 1 17 5",key:"1okkup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yde=re("Split",[["path",{d:"M16 3h5v5",key:"1806ms"}],["path",{d:"M8 3H3v5",key:"15dfkv"}],["path",{d:"M12 22v-8.3a4 4 0 0 0-1.172-2.872L3 3",key:"1qrqzj"}],["path",{d:"m15 9 6-6",key:"ko1vev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vde=re("SprayCan",[["path",{d:"M3 3h.01",key:"159qn6"}],["path",{d:"M7 5h.01",key:"1hq22a"}],["path",{d:"M11 7h.01",key:"1osv80"}],["path",{d:"M3 7h.01",key:"1xzrh3"}],["path",{d:"M7 9h.01",key:"19b3jx"}],["path",{d:"M3 11h.01",key:"1eifu7"}],["rect",{width:"4",height:"4",x:"15",y:"5",key:"mri9e4"}],["path",{d:"m19 9 2 2v10c0 .6-.4 1-1 1h-6c-.6 0-1-.4-1-1V11l2-2",key:"aib6hk"}],["path",{d:"m13 14 8-2",key:"1d7bmk"}],["path",{d:"m13 19 8-2",key:"1y2vml"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RA=re("Sprout",[["path",{d:"M7 20h10",key:"e6iznv"}],["path",{d:"M10 20c5.5-2.5.8-6.4 3-10",key:"161w41"}],["path",{d:"M9.5 9.4c1.1.8 1.8 2.2 2.3 3.7-2 .4-3.5.4-4.8-.3-1.2-.6-2.3-1.9-3-4.2 2.8-.5 4.4 0 5.5.8z",key:"9gtqwd"}],["path",{d:"M14.1 6a7 7 0 0 0-1.1 4c1.9-.1 3.3-.6 4.3-1.4 1-1 1.6-2.3 1.7-4.6-2.7.1-4 1-4.9 2z",key:"bkxnd2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uT=re("SquareActivity",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M17 12h-2l-2 5-2-10-2 5H7",key:"15hlnc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hT=re("SquareArrowDownLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 8-8 8",key:"166keh"}],["path",{d:"M16 16H8V8",key:"1w2ppm"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mT=re("SquareArrowDownRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m8 8 8 8",key:"1imecy"}],["path",{d:"M16 8v8H8",key:"1lbpgo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pT=re("SquareArrowDown",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8 12 4 4 4-4",key:"k98ssh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fT=re("SquareArrowLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m12 8-4 4 4 4",key:"15vm53"}],["path",{d:"M16 12H8",key:"1fr5h0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xT=re("SquareArrowOutDownLeft",[["path",{d:"M13 21h6a2 2 0 0 0 2-2V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v6",key:"14qz4y"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M9 21H3v-6",key:"wtvkvv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gT=re("SquareArrowOutDownRight",[["path",{d:"M21 11V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"14rsvq"}],["path",{d:"m21 21-9-9",key:"1et2py"}],["path",{d:"M21 15v6h-6",key:"1jko0i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yT=re("SquareArrowOutUpLeft",[["path",{d:"M13 3h6a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-6",key:"14mv1t"}],["path",{d:"m3 3 9 9",key:"rks13r"}],["path",{d:"M3 9V3h6",key:"ira0h2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vT=re("SquareArrowOutUpRight",[["path",{d:"M21 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h6",key:"y09zxi"}],["path",{d:"m21 3-9 9",key:"mpx6sq"}],["path",{d:"M15 3h6v6",key:"1q9fwt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bT=re("SquareArrowRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"m12 16 4-4-4-4",key:"1i9zcv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _T=re("SquareArrowUpLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 16V8h8",key:"19xb1h"}],["path",{d:"M16 16 8 8",key:"1qdy8n"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wT=re("SquareArrowUpRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 8h8v8",key:"b65dnt"}],["path",{d:"m8 16 8-8",key:"13b9ih"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jT=re("SquareArrowUp",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 12-4-4-4 4",key:"177agl"}],["path",{d:"M12 16V8",key:"1sbj14"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const NT=re("SquareAsterisk",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 8v8",key:"napkw2"}],["path",{d:"m8.5 14 7-4",key:"12hpby"}],["path",{d:"m8.5 10 7 4",key:"wwy2dy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kT=re("SquareBottomDashedScissors",[["path",{d:"M4 22a2 2 0 0 1-2-2V4a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2",key:"1vzg26"}],["path",{d:"M10 22H8",key:"euku7a"}],["path",{d:"M16 22h-2",key:"18d249"}],["circle",{cx:"8",cy:"8",r:"2",key:"14cg06"}],["path",{d:"M9.414 9.414 12 12",key:"qz4lzr"}],["path",{d:"M14.8 14.8 18 18",key:"11flf1"}],["circle",{cx:"8",cy:"16",r:"2",key:"1acxsx"}],["path",{d:"m18 6-8.586 8.586",key:"11kzk1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A_=re("SquareChartGantt",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 8h7",key:"kbo1nt"}],["path",{d:"M8 12h6",key:"ikassy"}],["path",{d:"M11 16h5",key:"oq65wt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S2=re("SquareCheckBig",[["path",{d:"M21 10.5V19a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h12.5",key:"1uzm8b"}],["path",{d:"m9 11 3 3L22 4",key:"1pflzl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ST=re("SquareCheck",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const CT=re("SquareChevronDown",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m16 10-4 4-4-4",key:"894hmk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const TT=re("SquareChevronLeft",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m14 16-4-4 4-4",key:"ojs7w8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ET=re("SquareChevronRight",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m10 8 4 4-4 4",key:"1wy4r4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const AT=re("SquareChevronUp",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m8 14 4-4 4 4",key:"fy2ptz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const MT=re("SquareCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bde=re("SquareDashedBottomCode",[["path",{d:"M10 9.5 8 12l2 2.5",key:"3mjy60"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"m14 9.5 2 2.5-2 2.5",key:"1bir2l"}],["path",{d:"M5 21a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2",key:"as5y1o"}],["path",{d:"M9 21h1",key:"15o7lz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _de=re("SquareDashedBottom",[["path",{d:"M5 21a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2",key:"as5y1o"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 21h1",key:"v9vybs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const IT=re("SquareDashedKanban",[["path",{d:"M8 7v7",key:"1x2jlm"}],["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M16 7v9",key:"1hp2iy"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M21 14v1",key:"169vum"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M3 9v1",key:"1r0deq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const PT=re("SquareDashedMousePointer",[["path",{d:"M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z",key:"xwnzip"}],["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h2",key:"1qve2z"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v2",key:"p14lih"}],["path",{d:"M3 14v1",key:"vnatye"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const LT=re("SquareDashed",[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const DT=re("SquareDivide",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["line",{x1:"8",x2:"16",y1:"12",y2:"12",key:"1jonct"}],["line",{x1:"12",x2:"12",y1:"16",y2:"16",key:"aqc6ln"}],["line",{x1:"12",x2:"12",y1:"8",y2:"8",key:"1mkcni"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const RT=re("SquareDot",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OT=re("SquareEqual",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M7 14h10",key:"1mhdw3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const FT=re("SquareFunction",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"M9 17c2 0 2.8-1 2.8-2.8V10c0-2 1-3.3 3.2-3",key:"m1af9g"}],["path",{d:"M9 11.2h5.7",key:"3zgcl2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zT=re("SquareKanban",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 7v7",key:"1x2jlm"}],["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M16 7v9",key:"1hp2iy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const BT=re("SquareLibrary",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7v10",key:"d5nglc"}],["path",{d:"M11 7v10",key:"pptsnr"}],["path",{d:"m15 7 2 10",key:"1m7qm5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $T=re("SquareM",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 16V8l4 4 4-4v8",key:"141u4e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const UT=re("SquareMenu",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 8h10",key:"1jw688"}],["path",{d:"M7 12h10",key:"b7w52i"}],["path",{d:"M7 16h10",key:"wp8him"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qT=re("SquareMinus",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const VT=re("SquareMousePointer",[["path",{d:"M12.034 12.681a.498.498 0 0 1 .647-.647l9 3.5a.5.5 0 0 1-.033.943l-3.444 1.068a1 1 0 0 0-.66.66l-1.067 3.443a.5.5 0 0 1-.943.033z",key:"xwnzip"}],["path",{d:"M21 11V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h6",key:"14rsvq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const HT=re("SquareParkingOff",[["path",{d:"M3.6 3.6A2 2 0 0 1 5 3h14a2 2 0 0 1 2 2v14a2 2 0 0 1-.59 1.41",key:"9l1ft6"}],["path",{d:"M3 8.7V19a2 2 0 0 0 2 2h10.3",key:"17knke"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M13 13a3 3 0 1 0 0-6H9v2",key:"uoagbd"}],["path",{d:"M9 17v-2.3",key:"1jxgo2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const GT=re("SquareParking",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M9 17V7h4a3 3 0 0 1 0 6H9",key:"1dfk2c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wu=re("SquarePen",[["path",{d:"M12 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7",key:"1m0v6g"}],["path",{d:"M18.375 2.625a1 1 0 0 1 3 3l-9.013 9.014a2 2 0 0 1-.853.505l-2.873.84a.5.5 0 0 1-.62-.62l.84-2.873a2 2 0 0 1 .506-.852z",key:"ohrbg2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const WT=re("SquarePercent",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const KT=re("SquarePi",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M7 7h10",key:"udp07y"}],["path",{d:"M10 7v10",key:"i1d9ee"}],["path",{d:"M16 17a2 2 0 0 1-2-2V7",key:"ftwdc7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const YT=re("SquarePilcrow",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M12 12H9.5a2.5 2.5 0 0 1 0-5H17",key:"1l9586"}],["path",{d:"M12 7v10",key:"jspqdw"}],["path",{d:"M16 7v10",key:"lavkr4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ZT=re("SquarePlay",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"m9 8 6 4-6 4Z",key:"f1r3lt"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const QT=re("SquarePlus",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M8 12h8",key:"1wcyev"}],["path",{d:"M12 8v8",key:"napkw2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const XT=re("SquarePower",[["path",{d:"M12 7v4",key:"xawao1"}],["path",{d:"M7.998 9.003a5 5 0 1 0 8-.005",key:"1pek45"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wde=re("SquareRadical",[["path",{d:"M7 12h2l2 5 2-10h4",key:"1fxv6h"}],["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const JT=re("SquareScissors",[["rect",{width:"20",height:"20",x:"2",y:"2",rx:"2",key:"1btzen"}],["circle",{cx:"8",cy:"8",r:"2",key:"14cg06"}],["path",{d:"M9.414 9.414 12 12",key:"qz4lzr"}],["path",{d:"M14.8 14.8 18 18",key:"11flf1"}],["circle",{cx:"8",cy:"16",r:"2",key:"1acxsx"}],["path",{d:"m18 6-8.586 8.586",key:"11kzk1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eE=re("SquareSigma",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M16 8.9V7H8l4 5-4 5h8v-1.9",key:"9nih0i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tE=re("SquareSlash",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["line",{x1:"9",x2:"15",y1:"15",y2:"9",key:"1dfufj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sE=re("SquareSplitHorizontal",[["path",{d:"M8 19H5c-1 0-2-1-2-2V7c0-1 1-2 2-2h3",key:"lubmu8"}],["path",{d:"M16 5h3c1 0 2 1 2 2v10c0 1-1 2-2 2h-3",key:"1ag34g"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nE=re("SquareSplitVertical",[["path",{d:"M5 8V5c0-1 1-2 2-2h10c1 0 2 1 2 2v3",key:"1pi83i"}],["path",{d:"M19 16v3c0 1-1 2-2 2H7c-1 0-2-1-2-2v-3",key:"ido5k7"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jde=re("SquareSquare",[["rect",{x:"3",y:"3",width:"18",height:"18",rx:"2",key:"h1oib"}],["rect",{x:"8",y:"8",width:"8",height:"8",rx:"1",key:"z9xiuo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nde=re("SquareStack",[["path",{d:"M4 10c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h4c1.1 0 2 .9 2 2",key:"4i38lg"}],["path",{d:"M10 16c-1.1 0-2-.9-2-2v-4c0-1.1.9-2 2-2h4c1.1 0 2 .9 2 2",key:"mlte4a"}],["rect",{width:"8",height:"8",x:"14",y:"14",rx:"2",key:"1fa9i4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rE=re("SquareTerminal",[["path",{d:"m7 11 2-2-2-2",key:"1lz0vl"}],["path",{d:"M11 13h4",key:"1p7l4v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aE=re("SquareUserRound",[["path",{d:"M18 21a6 6 0 0 0-12 0",key:"kaz2du"}],["circle",{cx:"12",cy:"11",r:"4",key:"1gt34v"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iE=re("SquareUser",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 21v-2a2 2 0 0 1 2-2h6a2 2 0 0 1 2 2v2",key:"1m6ac2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oE=re("SquareX",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"m9 9 6 6",key:"z0biqf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ay=re("Square",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kde=re("Squircle",[["path",{d:"M12 3c7.2 0 9 1.8 9 9s-1.8 9-9 9-9-1.8-9-9 1.8-9 9-9",key:"garfkc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sde=re("Squirrel",[["path",{d:"M15.236 22a3 3 0 0 0-2.2-5",key:"21bitc"}],["path",{d:"M16 20a3 3 0 0 1 3-3h1a2 2 0 0 0 2-2v-2a4 4 0 0 0-4-4V4",key:"oh0fg0"}],["path",{d:"M18 13h.01",key:"9veqaj"}],["path",{d:"M18 6a4 4 0 0 0-4 4 7 7 0 0 0-7 7c0-5 4-5 4-10.5a4.5 4.5 0 1 0-9 0 2.5 2.5 0 0 0 5 0C7 10 3 11 3 17c0 2.8 2.2 5 5 5h10",key:"980v8a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cde=re("Stamp",[["path",{d:"M5 22h14",key:"ehvnwv"}],["path",{d:"M19.27 13.73A2.5 2.5 0 0 0 17.5 13h-11A2.5 2.5 0 0 0 4 15.5V17a1 1 0 0 0 1 1h14a1 1 0 0 0 1-1v-1.5c0-.66-.26-1.3-.73-1.77Z",key:"1sy9ra"}],["path",{d:"M14 13V8.5C14 7 15 7 15 5a3 3 0 0 0-3-3c-1.66 0-3 1-3 3s1 2 1 3.5V13",key:"cnxgux"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tde=re("StarHalf",[["path",{d:"M12 18.338a2.1 2.1 0 0 0-.987.244L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.12 2.12 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.12 2.12 0 0 0 1.597-1.16l2.309-4.679A.53.53 0 0 1 12 2",key:"2ksp49"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ede=re("StarOff",[["path",{d:"M8.34 8.34 2 9.27l5 4.87L5.82 21 12 17.77 18.18 21l-.59-3.43",key:"16m0ql"}],["path",{d:"M18.42 12.76 22 9.27l-6.91-1L12 2l-1.44 2.91",key:"1vt8nq"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oa=re("Star",[["path",{d:"M11.525 2.295a.53.53 0 0 1 .95 0l2.31 4.679a2.123 2.123 0 0 0 1.595 1.16l5.166.756a.53.53 0 0 1 .294.904l-3.736 3.638a2.123 2.123 0 0 0-.611 1.878l.882 5.14a.53.53 0 0 1-.771.56l-4.618-2.428a2.122 2.122 0 0 0-1.973 0L6.396 21.01a.53.53 0 0 1-.77-.56l.881-5.139a2.122 2.122 0 0 0-.611-1.879L2.16 9.795a.53.53 0 0 1 .294-.906l5.165-.755a2.122 2.122 0 0 0 1.597-1.16z",key:"r04s7s"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ade=re("StepBack",[["line",{x1:"18",x2:"18",y1:"20",y2:"4",key:"cun8e5"}],["polygon",{points:"14,20 4,12 14,4",key:"ypakod"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mde=re("StepForward",[["line",{x1:"6",x2:"6",y1:"4",y2:"20",key:"fy8qot"}],["polygon",{points:"10,4 20,12 10,20",key:"1mc1pf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ide=re("Stethoscope",[["path",{d:"M11 2v2",key:"1539x4"}],["path",{d:"M5 2v2",key:"1yf1q8"}],["path",{d:"M5 3H4a2 2 0 0 0-2 2v4a6 6 0 0 0 12 0V5a2 2 0 0 0-2-2h-1",key:"rb5t3r"}],["path",{d:"M8 15a6 6 0 0 0 12 0v-3",key:"x18d4x"}],["circle",{cx:"20",cy:"10",r:"2",key:"ts1r5v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pde=re("Sticker",[["path",{d:"M15.5 3H5a2 2 0 0 0-2 2v14c0 1.1.9 2 2 2h14a2 2 0 0 0 2-2V8.5L15.5 3Z",key:"1wis1t"}],["path",{d:"M14 3v4a2 2 0 0 0 2 2h4",key:"36rjfy"}],["path",{d:"M8 13h.01",key:"1sbv64"}],["path",{d:"M16 13h.01",key:"wip0gl"}],["path",{d:"M10 16s.8 1 2 1c1.3 0 2-1 2-1",key:"1vvgv3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const v9=re("StickyNote",[["path",{d:"M16 3H5a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2V8Z",key:"qazsjp"}],["path",{d:"M15 3v4a2 2 0 0 0 2 2h4",key:"40519r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const b9=re("Store",[["path",{d:"m2 7 4.41-4.41A2 2 0 0 1 7.83 2h8.34a2 2 0 0 1 1.42.59L22 7",key:"ztvudi"}],["path",{d:"M4 12v8a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2v-8",key:"1b2hhj"}],["path",{d:"M15 22v-4a2 2 0 0 0-2-2h-2a2 2 0 0 0-2 2v4",key:"2ebpfo"}],["path",{d:"M2 7h20",key:"1fcdvo"}],["path",{d:"M22 7v3a2 2 0 0 1-2 2a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 16 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 12 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 8 12a2.7 2.7 0 0 1-1.59-.63.7.7 0 0 0-.82 0A2.7 2.7 0 0 1 4 12a2 2 0 0 1-2-2V7",key:"6c3vgh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lde=re("StretchHorizontal",[["rect",{width:"20",height:"6",x:"2",y:"4",rx:"2",key:"qdearl"}],["rect",{width:"20",height:"6",x:"2",y:"14",rx:"2",key:"1xrn6j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dde=re("StretchVertical",[["rect",{width:"6",height:"20",x:"4",y:"2",rx:"2",key:"19qu7m"}],["rect",{width:"6",height:"20",x:"14",y:"2",rx:"2",key:"24v0nk"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _9=re("Strikethrough",[["path",{d:"M16 4H9a3 3 0 0 0-2.83 4",key:"43sutm"}],["path",{d:"M14 12a4 4 0 0 1 0 8H6",key:"nlfj13"}],["line",{x1:"4",x2:"20",y1:"12",y2:"12",key:"1e0a9i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rde=re("Subscript",[["path",{d:"m4 5 8 8",key:"1eunvl"}],["path",{d:"m12 5-8 8",key:"1ah0jp"}],["path",{d:"M20 19h-4c0-1.5.44-2 1.5-2.5S20 15.33 20 14c0-.47-.17-.93-.48-1.29a2.11 2.11 0 0 0-2.62-.44c-.42.24-.74.62-.9 1.07",key:"e8ta8j"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ode=re("SunDim",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 4h.01",key:"1ujb9j"}],["path",{d:"M20 12h.01",key:"1ykeid"}],["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M4 12h.01",key:"158zrr"}],["path",{d:"M17.657 6.343h.01",key:"31pqzk"}],["path",{d:"M17.657 17.657h.01",key:"jehnf4"}],["path",{d:"M6.343 17.657h.01",key:"gdk6ow"}],["path",{d:"M6.343 6.343h.01",key:"1uurf0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fde=re("SunMedium",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 3v1",key:"1asbbs"}],["path",{d:"M12 20v1",key:"1wcdkc"}],["path",{d:"M3 12h1",key:"lp3yf2"}],["path",{d:"M20 12h1",key:"1vloll"}],["path",{d:"m18.364 5.636-.707.707",key:"1hakh0"}],["path",{d:"m6.343 17.657-.707.707",key:"18m9nf"}],["path",{d:"m5.636 5.636.707.707",key:"1xv1c5"}],["path",{d:"m17.657 17.657.707.707",key:"vl76zb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zde=re("SunMoon",[["path",{d:"M12 8a2.83 2.83 0 0 0 4 4 4 4 0 1 1-4-4",key:"1fu5g2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.9 4.9 1.4 1.4",key:"b9915j"}],["path",{d:"m17.7 17.7 1.4 1.4",key:"qc3ed3"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.3 17.7-1.4 1.4",key:"5gca6"}],["path",{d:"m19.1 4.9-1.4 1.4",key:"wpu9u6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bde=re("SunSnow",[["path",{d:"M10 9a3 3 0 1 0 0 6",key:"6zmtdl"}],["path",{d:"M2 12h1",key:"1uaihz"}],["path",{d:"M14 21V3",key:"1llu3z"}],["path",{d:"M10 4V3",key:"pkzwkn"}],["path",{d:"M10 21v-1",key:"1u8rkd"}],["path",{d:"m3.64 18.36.7-.7",key:"105rm9"}],["path",{d:"m4.34 6.34-.7-.7",key:"d3unjp"}],["path",{d:"M14 12h8",key:"4f43i9"}],["path",{d:"m17 4-3 3",key:"15jcng"}],["path",{d:"m14 17 3 3",key:"6tlq38"}],["path",{d:"m21 15-3-3 3-3",key:"1nlnje"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pb=re("Sun",[["circle",{cx:"12",cy:"12",r:"4",key:"4exip2"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m4.93 4.93 1.41 1.41",key:"149t6j"}],["path",{d:"m17.66 17.66 1.41 1.41",key:"ptbguv"}],["path",{d:"M2 12h2",key:"1t8f8n"}],["path",{d:"M20 12h2",key:"1q8mjw"}],["path",{d:"m6.34 17.66-1.41 1.41",key:"1m8zz5"}],["path",{d:"m19.07 4.93-1.41 1.41",key:"1shlcs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $de=re("Sunrise",[["path",{d:"M12 2v8",key:"1q4o3n"}],["path",{d:"m4.93 10.93 1.41 1.41",key:"2a7f42"}],["path",{d:"M2 18h2",key:"j10viu"}],["path",{d:"M20 18h2",key:"wocana"}],["path",{d:"m19.07 10.93-1.41 1.41",key:"15zs5n"}],["path",{d:"M22 22H2",key:"19qnx5"}],["path",{d:"m8 6 4-4 4 4",key:"ybng9g"}],["path",{d:"M16 18a4 4 0 0 0-8 0",key:"1lzouq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ude=re("Sunset",[["path",{d:"M12 10V2",key:"16sf7g"}],["path",{d:"m4.93 10.93 1.41 1.41",key:"2a7f42"}],["path",{d:"M2 18h2",key:"j10viu"}],["path",{d:"M20 18h2",key:"wocana"}],["path",{d:"m19.07 10.93-1.41 1.41",key:"15zs5n"}],["path",{d:"M22 22H2",key:"19qnx5"}],["path",{d:"m16 6-4 4-4-4",key:"6wukr"}],["path",{d:"M16 18a4 4 0 0 0-8 0",key:"1lzouq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qde=re("Superscript",[["path",{d:"m4 19 8-8",key:"hr47gm"}],["path",{d:"m12 19-8-8",key:"1dhhmo"}],["path",{d:"M20 12h-4c0-1.5.442-2 1.5-2.5S20 8.334 20 7.002c0-.472-.17-.93-.484-1.29a2.105 2.105 0 0 0-2.617-.436c-.42.239-.738.614-.899 1.06",key:"1dfcux"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vde=re("SwatchBook",[["path",{d:"M11 17a4 4 0 0 1-8 0V5a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2Z",key:"1ldrpk"}],["path",{d:"M16.7 13H19a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2H7",key:"11i5po"}],["path",{d:"M 7 17h.01",key:"1euzgo"}],["path",{d:"m11 8 2.3-2.3a2.4 2.4 0 0 1 3.404.004L18.6 7.6a2.4 2.4 0 0 1 .026 3.434L9.9 19.8",key:"o2gii7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hde=re("SwissFranc",[["path",{d:"M10 21V3h8",key:"br2l0g"}],["path",{d:"M6 16h9",key:"2py0wn"}],["path",{d:"M10 9.5h7",key:"13dmhz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gde=re("SwitchCamera",[["path",{d:"M11 19H4a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2h5",key:"mtk2lu"}],["path",{d:"M13 5h7a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2h-5",key:"120jsl"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}],["path",{d:"m18 22-3-3 3-3",key:"kgdoj7"}],["path",{d:"m6 2 3 3-3 3",key:"1fnbkv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wde=re("Sword",[["polyline",{points:"14.5 17.5 3 6 3 3 6 3 17.5 14.5",key:"1hfsw2"}],["line",{x1:"13",x2:"19",y1:"19",y2:"13",key:"1vrmhu"}],["line",{x1:"16",x2:"20",y1:"16",y2:"20",key:"1bron3"}],["line",{x1:"19",x2:"21",y1:"21",y2:"19",key:"13pww6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kde=re("Swords",[["polyline",{points:"14.5 17.5 3 6 3 3 6 3 17.5 14.5",key:"1hfsw2"}],["line",{x1:"13",x2:"19",y1:"19",y2:"13",key:"1vrmhu"}],["line",{x1:"16",x2:"20",y1:"16",y2:"20",key:"1bron3"}],["line",{x1:"19",x2:"21",y1:"21",y2:"19",key:"13pww6"}],["polyline",{points:"14.5 6.5 18 3 21 3 21 6 17.5 9.5",key:"hbey2j"}],["line",{x1:"5",x2:"9",y1:"14",y2:"18",key:"1hf58s"}],["line",{x1:"7",x2:"4",y1:"17",y2:"20",key:"pidxm4"}],["line",{x1:"3",x2:"5",y1:"19",y2:"21",key:"1pehsh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yde=re("Syringe",[["path",{d:"m18 2 4 4",key:"22kx64"}],["path",{d:"m17 7 3-3",key:"1w1zoj"}],["path",{d:"M19 9 8.7 19.3c-1 1-2.5 1-3.4 0l-.6-.6c-1-1-1-2.5 0-3.4L15 5",key:"1exhtz"}],["path",{d:"m9 11 4 4",key:"rovt3i"}],["path",{d:"m5 19-3 3",key:"59f2uf"}],["path",{d:"m14 4 6 6",key:"yqp9t2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hL=re("Table2",[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zde=re("TableCellsMerge",[["path",{d:"M12 21v-6",key:"lihzve"}],["path",{d:"M12 9V3",key:"da5inc"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qde=re("TableCellsSplit",[["path",{d:"M12 15V9",key:"8c7uyn"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M3 9h18",key:"1pudct"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xde=re("TableColumnsSplit",[["path",{d:"M14 14v2",key:"w2a1xv"}],["path",{d:"M14 20v2",key:"1lq872"}],["path",{d:"M14 2v2",key:"6buw04"}],["path",{d:"M14 8v2",key:"i67w9a"}],["path",{d:"M2 15h8",key:"82wtch"}],["path",{d:"M2 3h6a2 2 0 0 1 2 2v14a2 2 0 0 1-2 2H2",key:"up0l64"}],["path",{d:"M2 9h8",key:"yelfik"}],["path",{d:"M22 15h-4",key:"1es58f"}],["path",{d:"M22 3h-2a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h2",key:"pdjoqf"}],["path",{d:"M22 9h-4",key:"1luja7"}],["path",{d:"M5 3v18",key:"14hmio"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jde=re("TableOfContents",[["path",{d:"M16 12H3",key:"1a2rj7"}],["path",{d:"M16 18H3",key:"12xzn7"}],["path",{d:"M16 6H3",key:"1wxfjs"}],["path",{d:"M21 12h.01",key:"msek7k"}],["path",{d:"M21 18h.01",key:"1e8rq1"}],["path",{d:"M21 6h.01",key:"1koanj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eue=re("TableProperties",[["path",{d:"M15 3v18",key:"14nvp0"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M21 9H3",key:"1338ky"}],["path",{d:"M21 15H3",key:"9uk58r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tue=re("TableRowsSplit",[["path",{d:"M14 10h2",key:"1lstlu"}],["path",{d:"M15 22v-8",key:"1fwwgm"}],["path",{d:"M15 2v4",key:"1044rn"}],["path",{d:"M2 10h2",key:"1r8dkt"}],["path",{d:"M20 10h2",key:"1ug425"}],["path",{d:"M3 19h18",key:"awlh7x"}],["path",{d:"M3 22v-6a2 2 135 0 1 2-2h14a2 2 45 0 1 2 2v6",key:"ibqhof"}],["path",{d:"M3 2v2a2 2 45 0 0 2 2h14a2 2 135 0 0 2-2V2",key:"1uenja"}],["path",{d:"M8 10h2",key:"66od0"}],["path",{d:"M9 22v-8",key:"fmnu31"}],["path",{d:"M9 2v4",key:"j1yeou"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mL=re("Table",[["path",{d:"M12 3v18",key:"108xh3"}],["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sue=re("TabletSmartphone",[["rect",{width:"10",height:"14",x:"3",y:"8",rx:"2",key:"1vrsiq"}],["path",{d:"M5 4a2 2 0 0 1 2-2h12a2 2 0 0 1 2 2v16a2 2 0 0 1-2 2h-2.4",key:"1j4zmg"}],["path",{d:"M8 18h.01",key:"lrp35t"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pL=re("Tablet",[["rect",{width:"16",height:"20",x:"4",y:"2",rx:"2",ry:"2",key:"76otgf"}],["line",{x1:"12",x2:"12.01",y1:"18",y2:"18",key:"1dp563"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nue=re("Tablets",[["circle",{cx:"7",cy:"7",r:"5",key:"x29byf"}],["circle",{cx:"17",cy:"17",r:"5",key:"1op1d2"}],["path",{d:"M12 17h10",key:"ls21zv"}],["path",{d:"m3.46 10.54 7.08-7.08",key:"1rehiu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oh=re("Tag",[["path",{d:"M12.586 2.586A2 2 0 0 0 11.172 2H4a2 2 0 0 0-2 2v7.172a2 2 0 0 0 .586 1.414l8.704 8.704a2.426 2.426 0 0 0 3.42 0l6.58-6.58a2.426 2.426 0 0 0 0-3.42z",key:"vktsd0"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const w9=re("Tags",[["path",{d:"m15 5 6.3 6.3a2.4 2.4 0 0 1 0 3.4L17 19",key:"1cbfv1"}],["path",{d:"M9.586 5.586A2 2 0 0 0 8.172 5H3a1 1 0 0 0-1 1v5.172a2 2 0 0 0 .586 1.414L8.29 18.29a2.426 2.426 0 0 0 3.42 0l3.58-3.58a2.426 2.426 0 0 0 0-3.42z",key:"135mg7"}],["circle",{cx:"6.5",cy:"9.5",r:".5",fill:"currentColor",key:"5pm5xn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rue=re("Tally1",[["path",{d:"M4 4v16",key:"6qkkli"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const aue=re("Tally2",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const iue=re("Tally3",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const oue=re("Tally4",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}],["path",{d:"M19 4v16",key:"8ij5ei"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lue=re("Tally5",[["path",{d:"M4 4v16",key:"6qkkli"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"M14 4v16",key:"12vmem"}],["path",{d:"M19 4v16",key:"8ij5ei"}],["path",{d:"M22 6 2 18",key:"h9moai"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cue=re("Tangent",[["circle",{cx:"17",cy:"4",r:"2",key:"y5j2s2"}],["path",{d:"M15.59 5.41 5.41 15.59",key:"l0vprr"}],["circle",{cx:"4",cy:"17",r:"2",key:"9p4efm"}],["path",{d:"M12 22s-4-9-1.5-11.5S22 12 22 12",key:"1twk4o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ac=re("Target",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const due=re("Telescope",[["path",{d:"m10.065 12.493-6.18 1.318a.934.934 0 0 1-1.108-.702l-.537-2.15a1.07 1.07 0 0 1 .691-1.265l13.504-4.44",key:"k4qptu"}],["path",{d:"m13.56 11.747 4.332-.924",key:"19l80z"}],["path",{d:"m16 21-3.105-6.21",key:"7oh9d"}],["path",{d:"M16.485 5.94a2 2 0 0 1 1.455-2.425l1.09-.272a1 1 0 0 1 1.212.727l1.515 6.06a1 1 0 0 1-.727 1.213l-1.09.272a2 2 0 0 1-2.425-1.455z",key:"m7xp4m"}],["path",{d:"m6.158 8.633 1.114 4.456",key:"74o979"}],["path",{d:"m8 21 3.105-6.21",key:"1fvxut"}],["circle",{cx:"12",cy:"13",r:"2",key:"1c1ljs"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uue=re("TentTree",[["circle",{cx:"4",cy:"4",r:"2",key:"bt5ra8"}],["path",{d:"m14 5 3-3 3 3",key:"1sorif"}],["path",{d:"m14 10 3-3 3 3",key:"1jyi9h"}],["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M17 14H7l-5 8h20Z",key:"13ar7p"}],["path",{d:"M8 14v8",key:"1ghmqk"}],["path",{d:"m9 14 5 8",key:"13pgi6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hue=re("Tent",[["path",{d:"M3.5 21 14 3",key:"1szst5"}],["path",{d:"M20.5 21 10 3",key:"1310c3"}],["path",{d:"M15.5 21 12 15l-3.5 6",key:"1ddtfw"}],["path",{d:"M2 21h20",key:"1nyx9w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mue=re("Terminal",[["polyline",{points:"4 17 10 11 4 5",key:"akl6gq"}],["line",{x1:"12",x2:"20",y1:"19",y2:"19",key:"q2wloq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lE=re("TestTubeDiagonal",[["path",{d:"M21 7 6.82 21.18a2.83 2.83 0 0 1-3.99-.01a2.83 2.83 0 0 1 0-4L17 3",key:"1ub6xw"}],["path",{d:"m16 2 6 6",key:"1gw87d"}],["path",{d:"M12 16H4",key:"1cjfip"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pue=re("TestTube",[["path",{d:"M14.5 2v17.5c0 1.4-1.1 2.5-2.5 2.5c-1.4 0-2.5-1.1-2.5-2.5V2",key:"125lnx"}],["path",{d:"M8.5 2h7",key:"csnxdl"}],["path",{d:"M14.5 16h-5",key:"1ox875"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fue=re("TestTubes",[["path",{d:"M9 2v17.5A2.5 2.5 0 0 1 6.5 22A2.5 2.5 0 0 1 4 19.5V2",key:"1hjrqt"}],["path",{d:"M20 2v17.5a2.5 2.5 0 0 1-2.5 2.5a2.5 2.5 0 0 1-2.5-2.5V2",key:"16lc8n"}],["path",{d:"M3 2h7",key:"7s29d5"}],["path",{d:"M14 2h7",key:"7sicin"}],["path",{d:"M9 16H4",key:"1bfye3"}],["path",{d:"M20 16h-5",key:"ddnjpe"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xue=re("TextCursorInput",[["path",{d:"M5 4h1a3 3 0 0 1 3 3 3 3 0 0 1 3-3h1",key:"18xjzo"}],["path",{d:"M13 20h-1a3 3 0 0 1-3-3 3 3 0 0 1-3 3H5",key:"fj48gi"}],["path",{d:"M5 16H4a2 2 0 0 1-2-2v-4a2 2 0 0 1 2-2h1",key:"1n9rhb"}],["path",{d:"M13 8h7a2 2 0 0 1 2 2v4a2 2 0 0 1-2 2h-7",key:"13ksps"}],["path",{d:"M9 7v10",key:"1vc8ob"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gue=re("TextCursor",[["path",{d:"M17 22h-1a4 4 0 0 1-4-4V6a4 4 0 0 1 4-4h1",key:"uvaxm9"}],["path",{d:"M7 22h1a4 4 0 0 0 4-4v-1",key:"11xy8d"}],["path",{d:"M7 2h1a4 4 0 0 1 4 4v1",key:"1uw06m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yue=re("TextQuote",[["path",{d:"M17 6H3",key:"16j9eg"}],["path",{d:"M21 12H8",key:"scolzb"}],["path",{d:"M21 18H8",key:"1wfozv"}],["path",{d:"M3 12v6",key:"fv4c87"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vue=re("TextSearch",[["path",{d:"M21 6H3",key:"1jwq7v"}],["path",{d:"M10 12H3",key:"1ulcyk"}],["path",{d:"M10 18H3",key:"13769t"}],["circle",{cx:"17",cy:"15",r:"3",key:"1upz2a"}],["path",{d:"m21 19-1.9-1.9",key:"dwi7p8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cE=re("TextSelect",[["path",{d:"M5 3a2 2 0 0 0-2 2",key:"y57alp"}],["path",{d:"M19 3a2 2 0 0 1 2 2",key:"18rm91"}],["path",{d:"M21 19a2 2 0 0 1-2 2",key:"1j7049"}],["path",{d:"M5 21a2 2 0 0 1-2-2",key:"sbafld"}],["path",{d:"M9 3h1",key:"1yesri"}],["path",{d:"M9 21h1",key:"15o7lz"}],["path",{d:"M14 3h1",key:"1ec4yj"}],["path",{d:"M14 21h1",key:"v9vybs"}],["path",{d:"M3 9v1",key:"1r0deq"}],["path",{d:"M21 9v1",key:"mxsmne"}],["path",{d:"M3 14v1",key:"vnatye"}],["path",{d:"M21 14v1",key:"169vum"}],["line",{x1:"7",x2:"15",y1:"8",y2:"8",key:"1758g8"}],["line",{x1:"7",x2:"17",y1:"12",y2:"12",key:"197423"}],["line",{x1:"7",x2:"13",y1:"16",y2:"16",key:"37cgm6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bue=re("Text",[["path",{d:"M17 6.1H3",key:"wptmhv"}],["path",{d:"M21 12.1H3",key:"1j38uz"}],["path",{d:"M15.1 18H3",key:"1nb16a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _ue=re("Theater",[["path",{d:"M2 10s3-3 3-8",key:"3xiif0"}],["path",{d:"M22 10s-3-3-3-8",key:"ioaa5q"}],["path",{d:"M10 2c0 4.4-3.6 8-8 8",key:"16fkpi"}],["path",{d:"M14 2c0 4.4 3.6 8 8 8",key:"b9eulq"}],["path",{d:"M2 10s2 2 2 5",key:"1au1lb"}],["path",{d:"M22 10s-2 2-2 5",key:"qi2y5e"}],["path",{d:"M8 15h8",key:"45n4r"}],["path",{d:"M2 22v-1a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v1",key:"1vsc2m"}],["path",{d:"M14 22v-1a2 2 0 0 1 2-2h4a2 2 0 0 1 2 2v1",key:"hrha4u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wue=re("ThermometerSnowflake",[["path",{d:"M2 12h10",key:"19562f"}],["path",{d:"M9 4v16",key:"81ygyz"}],["path",{d:"m3 9 3 3-3 3",key:"1sas0l"}],["path",{d:"M12 6 9 9 6 6",key:"pfrgxu"}],["path",{d:"m6 18 3-3 1.5 1.5",key:"1e277p"}],["path",{d:"M20 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"iof6y5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jue=re("ThermometerSun",[["path",{d:"M12 9a4 4 0 0 0-2 7.5",key:"1jvsq6"}],["path",{d:"M12 3v2",key:"1w22ol"}],["path",{d:"m6.6 18.4-1.4 1.4",key:"w2yidj"}],["path",{d:"M20 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"iof6y5"}],["path",{d:"M4 13H2",key:"118le4"}],["path",{d:"M6.34 7.34 4.93 5.93",key:"1brd51"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const j9=re("Thermometer",[["path",{d:"M14 4v10.54a4 4 0 1 1-4 0V4a2 2 0 0 1 4 0Z",key:"17jzev"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const N9=re("ThumbsDown",[["path",{d:"M17 14V2",key:"8ymqnk"}],["path",{d:"M9 18.12 10 14H4.17a2 2 0 0 1-1.92-2.56l2.33-8A2 2 0 0 1 6.5 2H20a2 2 0 0 1 2 2v8a2 2 0 0 1-2 2h-2.76a2 2 0 0 0-1.79 1.11L12 22a3.13 3.13 0 0 1-3-3.88Z",key:"m61m77"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $m=re("ThumbsUp",[["path",{d:"M7 10v12",key:"1qc93n"}],["path",{d:"M15 5.88 14 10h5.83a2 2 0 0 1 1.92 2.56l-2.33 8A2 2 0 0 1 17.5 22H4a2 2 0 0 1-2-2v-8a2 2 0 0 1 2-2h2.76a2 2 0 0 0 1.79-1.11L12 2a3.13 3.13 0 0 1 3 3.88Z",key:"emmmcr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nue=re("TicketCheck",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const kue=re("TicketMinus",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M9 12h6",key:"1c52cq"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Sue=re("TicketPercent",[["path",{d:"M2 9a3 3 0 1 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 1 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"1l48ns"}],["path",{d:"M9 9h.01",key:"1q5me6"}],["path",{d:"m15 9-6 6",key:"1uzhvr"}],["path",{d:"M15 15h.01",key:"lqbp3k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Cue=re("TicketPlus",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M9 12h6",key:"1c52cq"}],["path",{d:"M12 9v6",key:"199k2o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Tue=re("TicketSlash",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"m9.5 14.5 5-5",key:"qviqfa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Eue=re("TicketX",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"m9.5 14.5 5-5",key:"qviqfa"}],["path",{d:"m9.5 9.5 5 5",key:"18nt4w"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const k9=re("Ticket",[["path",{d:"M2 9a3 3 0 0 1 0 6v2a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2v-2a3 3 0 0 1 0-6V7a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2Z",key:"qn84l0"}],["path",{d:"M13 5v2",key:"dyzc3o"}],["path",{d:"M13 17v2",key:"1ont0d"}],["path",{d:"M13 11v2",key:"1wjjxi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Aue=re("TicketsPlane",[["path",{d:"M10.5 17h1.227a2 2 0 0 0 1.345-.52L18 12",key:"16muxl"}],["path",{d:"m12 13.5 3.75.5",key:"1i9qhk"}],["path",{d:"m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8",key:"12lg5p"}],["path",{d:"M6 10V8",key:"1y41hn"}],["path",{d:"M6 14v1",key:"cao2tf"}],["path",{d:"M6 19v2",key:"1loha6"}],["rect",{x:"2",y:"8",width:"20",height:"13",rx:"2",key:"p3bz5l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mue=re("Tickets",[["path",{d:"m4.5 8 10.58-5.06a1 1 0 0 1 1.342.488L18.5 8",key:"12lg5p"}],["path",{d:"M6 10V8",key:"1y41hn"}],["path",{d:"M6 14v1",key:"cao2tf"}],["path",{d:"M6 19v2",key:"1loha6"}],["rect",{x:"2",y:"8",width:"20",height:"13",rx:"2",key:"p3bz5l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Iue=re("TimerOff",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"M4.6 11a8 8 0 0 0 1.7 8.7 8 8 0 0 0 8.7 1.7",key:"10he05"}],["path",{d:"M7.4 7.4a8 8 0 0 1 10.3 1 8 8 0 0 1 .9 10.2",key:"15f7sh"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M12 12v-2",key:"fwoke6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Pue=re("TimerReset",[["path",{d:"M10 2h4",key:"n1abiw"}],["path",{d:"M12 14v-4",key:"1evpnu"}],["path",{d:"M4 13a8 8 0 0 1 8-7 8 8 0 1 1-5.3 14L4 17.6",key:"1ts96g"}],["path",{d:"M9 17H4v5",key:"8t5av"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lue=re("Timer",[["line",{x1:"10",x2:"14",y1:"2",y2:"2",key:"14vaq8"}],["line",{x1:"12",x2:"15",y1:"14",y2:"11",key:"17fdiu"}],["circle",{cx:"12",cy:"14",r:"8",key:"1e1u0o"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Due=re("ToggleLeft",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"8",cy:"12",r:"2",key:"1nvbw3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rue=re("ToggleRight",[["rect",{width:"20",height:"12",x:"2",y:"6",rx:"6",ry:"6",key:"f2vt7d"}],["circle",{cx:"16",cy:"12",r:"2",key:"4ma0v8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Oue=re("Toilet",[["path",{d:"M7 12h13a1 1 0 0 1 1 1 5 5 0 0 1-5 5h-.598a.5.5 0 0 0-.424.765l1.544 2.47a.5.5 0 0 1-.424.765H5.402a.5.5 0 0 1-.424-.765L7 18",key:"kc4kqr"}],["path",{d:"M8 18a5 5 0 0 1-5-5V4a2 2 0 0 1 2-2h8a2 2 0 0 1 2 2v8",key:"1tqs57"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fue=re("Tornado",[["path",{d:"M21 4H3",key:"1hwok0"}],["path",{d:"M18 8H6",key:"41n648"}],["path",{d:"M19 12H9",key:"1g4lpz"}],["path",{d:"M16 16h-6",key:"1j5d54"}],["path",{d:"M11 20H9",key:"39obr8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zue=re("Torus",[["ellipse",{cx:"12",cy:"11",rx:"3",ry:"2",key:"1b2qxu"}],["ellipse",{cx:"12",cy:"12.5",rx:"10",ry:"8.5",key:"h8emeu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bue=re("TouchpadOff",[["path",{d:"M4 4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h16",key:"lnt0bk"}],["path",{d:"M2 14h12",key:"d8icqz"}],["path",{d:"M22 14h-2",key:"jrx26d"}],["path",{d:"M12 20v-6",key:"1rm09r"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M22 16V6a2 2 0 0 0-2-2H10",key:"11y8e4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $ue=re("Touchpad",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M2 14h20",key:"myj16y"}],["path",{d:"M12 20v-6",key:"1rm09r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uue=re("TowerControl",[["path",{d:"M18.2 12.27 20 6H4l1.8 6.27a1 1 0 0 0 .95.73h10.5a1 1 0 0 0 .96-.73Z",key:"1pledb"}],["path",{d:"M8 13v9",key:"hmv0ci"}],["path",{d:"M16 22v-9",key:"ylnf1u"}],["path",{d:"m9 6 1 7",key:"dpdgam"}],["path",{d:"m15 6-1 7",key:"ls7zgu"}],["path",{d:"M12 6V2",key:"1pj48d"}],["path",{d:"M13 2h-2",key:"mj6ths"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const que=re("ToyBrick",[["rect",{width:"18",height:"12",x:"3",y:"8",rx:"1",key:"158fvp"}],["path",{d:"M10 8V5c0-.6-.4-1-1-1H6a1 1 0 0 0-1 1v3",key:"s0042v"}],["path",{d:"M19 8V5c0-.6-.4-1-1-1h-3a1 1 0 0 0-1 1v3",key:"9wmeh2"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vue=re("Tractor",[["path",{d:"m10 11 11 .9a1 1 0 0 1 .8 1.1l-.665 4.158a1 1 0 0 1-.988.842H20",key:"she1j9"}],["path",{d:"M16 18h-5",key:"bq60fd"}],["path",{d:"M18 5a1 1 0 0 0-1 1v5.573",key:"1kv8ia"}],["path",{d:"M3 4h8.129a1 1 0 0 1 .99.863L13 11.246",key:"1q1ert"}],["path",{d:"M4 11V4",key:"9ft8pt"}],["path",{d:"M7 15h.01",key:"k5ht0j"}],["path",{d:"M8 10.1V4",key:"1jgyzo"}],["circle",{cx:"18",cy:"18",r:"2",key:"1emm8v"}],["circle",{cx:"7",cy:"15",r:"5",key:"ddtuc"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hue=re("TrafficCone",[["path",{d:"M9.3 6.2a4.55 4.55 0 0 0 5.4 0",key:"flyxqv"}],["path",{d:"M7.9 10.7c.9.8 2.4 1.3 4.1 1.3s3.2-.5 4.1-1.3",key:"1nlxxg"}],["path",{d:"M13.9 3.5a1.93 1.93 0 0 0-3.8-.1l-3 10c-.1.2-.1.4-.1.6 0 1.7 2.2 3 5 3s5-1.3 5-3c0-.2 0-.4-.1-.5Z",key:"vz7x1l"}],["path",{d:"m7.5 12.2-4.7 2.7c-.5.3-.8.7-.8 1.1s.3.8.8 1.1l7.6 4.5c.9.5 2.1.5 3 0l7.6-4.5c.7-.3 1-.7 1-1.1s-.3-.8-.8-1.1l-4.7-2.8",key:"1xfzlw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Gue=re("TrainFrontTunnel",[["path",{d:"M2 22V12a10 10 0 1 1 20 0v10",key:"o0fyp0"}],["path",{d:"M15 6.8v1.4a3 2.8 0 1 1-6 0V6.8",key:"m8q3n9"}],["path",{d:"M10 15h.01",key:"44in9x"}],["path",{d:"M14 15h.01",key:"5mohn5"}],["path",{d:"M10 19a4 4 0 0 1-4-4v-3a6 6 0 1 1 12 0v3a4 4 0 0 1-4 4Z",key:"hckbmu"}],["path",{d:"m9 19-2 3",key:"iij7hm"}],["path",{d:"m15 19 2 3",key:"npx8sa"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wue=re("TrainFront",[["path",{d:"M8 3.1V7a4 4 0 0 0 8 0V3.1",key:"1v71zp"}],["path",{d:"m9 15-1-1",key:"1yrq24"}],["path",{d:"m15 15 1-1",key:"1t0d6s"}],["path",{d:"M9 19c-2.8 0-5-2.2-5-5v-4a8 8 0 0 1 16 0v4c0 2.8-2.2 5-5 5Z",key:"1p0hjs"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m16 19 2 3",key:"xo31yx"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Kue=re("TrainTrack",[["path",{d:"M2 17 17 2",key:"18b09t"}],["path",{d:"m2 14 8 8",key:"1gv9hu"}],["path",{d:"m5 11 8 8",key:"189pqp"}],["path",{d:"m8 8 8 8",key:"1imecy"}],["path",{d:"m11 5 8 8",key:"ummqn6"}],["path",{d:"m14 2 8 8",key:"1vk7dn"}],["path",{d:"M7 22 22 7",key:"15mb1i"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dE=re("TramFront",[["rect",{width:"16",height:"16",x:"4",y:"3",rx:"2",key:"1wxw4b"}],["path",{d:"M4 11h16",key:"mpoxn0"}],["path",{d:"M12 3v8",key:"1h2ygw"}],["path",{d:"m8 19-2 3",key:"13i0xs"}],["path",{d:"m18 22-2-3",key:"1p0ohu"}],["path",{d:"M8 15h.01",key:"a7atzg"}],["path",{d:"M16 15h.01",key:"rnfrdf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _n=re("Trash2",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}],["line",{x1:"10",x2:"10",y1:"11",y2:"17",key:"1uufr5"}],["line",{x1:"14",x2:"14",y1:"11",y2:"17",key:"xtxkd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yue=re("Trash",[["path",{d:"M3 6h18",key:"d0wm0j"}],["path",{d:"M19 6v14c0 1-1 2-2 2H7c-1 0-2-1-2-2V6",key:"4alrt4"}],["path",{d:"M8 6V4c0-1 1-2 2-2h4c1 0 2 1 2 2v2",key:"v07s0e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zue=re("TreeDeciduous",[["path",{d:"M8 19a4 4 0 0 1-2.24-7.32A3.5 3.5 0 0 1 9 6.03V6a3 3 0 1 1 6 0v.04a3.5 3.5 0 0 1 3.24 5.65A4 4 0 0 1 16 19Z",key:"oadzkq"}],["path",{d:"M12 19v3",key:"npa21l"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uE=re("TreePalm",[["path",{d:"M13 8c0-2.76-2.46-5-5.5-5S2 5.24 2 8h2l1-1 1 1h4",key:"foxbe7"}],["path",{d:"M13 7.14A5.82 5.82 0 0 1 16.5 6c3.04 0 5.5 2.24 5.5 5h-3l-1-1-1 1h-3",key:"18arnh"}],["path",{d:"M5.89 9.71c-2.15 2.15-2.3 5.47-.35 7.43l4.24-4.25.7-.7.71-.71 2.12-2.12c-1.95-1.96-5.27-1.8-7.42.35",key:"ywahnh"}],["path",{d:"M11 15.5c.5 2.5-.17 4.5-1 6.5h4c2-5.5-.5-12-1-14",key:"ft0feo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const s4=re("TreePine",[["path",{d:"m17 14 3 3.3a1 1 0 0 1-.7 1.7H4.7a1 1 0 0 1-.7-1.7L7 14h-.3a1 1 0 0 1-.7-1.7L9 9h-.2A1 1 0 0 1 8 7.3L12 3l4 4.3a1 1 0 0 1-.8 1.7H15l3 3.3a1 1 0 0 1-.7 1.7H17Z",key:"cpyugq"}],["path",{d:"M12 22v-3",key:"kmzjlo"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Que=re("Trees",[["path",{d:"M10 10v.2A3 3 0 0 1 8.9 16H5a3 3 0 0 1-1-5.8V10a3 3 0 0 1 6 0Z",key:"1l6gj6"}],["path",{d:"M7 16v6",key:"1a82de"}],["path",{d:"M13 19v3",key:"13sx9i"}],["path",{d:"M12 19h8.3a1 1 0 0 0 .7-1.7L18 14h.3a1 1 0 0 0 .7-1.7L16 9h.2a1 1 0 0 0 .8-1.7L13 3l-1.4 1.5",key:"1sj9kv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xue=re("Trello",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",ry:"2",key:"1m3agn"}],["rect",{width:"3",height:"9",x:"7",y:"7",key:"14n3xi"}],["rect",{width:"3",height:"5",x:"14",y:"7",key:"s4azjd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fb=re("TrendingDown",[["polyline",{points:"22 17 13.5 8.5 8.5 13.5 2 7",key:"1r2t7k"}],["polyline",{points:"16 17 22 17 22 11",key:"11uiuu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jue=re("TrendingUpDown",[["path",{d:"M14.828 14.828 21 21",key:"ar5fw7"}],["path",{d:"M21 16v5h-5",key:"1ck2sf"}],["path",{d:"m21 3-9 9-4-4-6 6",key:"1h02xo"}],["path",{d:"M21 8V3h-5",key:"1qoq8a"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const go=re("TrendingUp",[["polyline",{points:"22 7 13.5 15.5 8.5 10.5 2 17",key:"126l90"}],["polyline",{points:"16 7 22 7 22 13",key:"kwv8wd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ic=re("TriangleAlert",[["path",{d:"m21.73 18-8-14a2 2 0 0 0-3.48 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3",key:"wmoenq"}],["path",{d:"M12 9v4",key:"juzpu7"}],["path",{d:"M12 17h.01",key:"p32p05"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ehe=re("TriangleRight",[["path",{d:"M22 18a2 2 0 0 1-2 2H3c-1.1 0-1.3-.6-.4-1.3L20.4 4.3c.9-.7 1.6-.4 1.6.7Z",key:"183wce"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const the=re("Triangle",[["path",{d:"M13.73 4a2 2 0 0 0-3.46 0l-8 14A2 2 0 0 0 4 21h16a2 2 0 0 0 1.73-3Z",key:"14u9p9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xo=re("Trophy",[["path",{d:"M6 9H4.5a2.5 2.5 0 0 1 0-5H6",key:"17hqa7"}],["path",{d:"M18 9h1.5a2.5 2.5 0 0 0 0-5H18",key:"lmptdp"}],["path",{d:"M4 22h16",key:"57wxv0"}],["path",{d:"M10 14.66V17c0 .55-.47.98-.97 1.21C7.85 18.75 7 20.24 7 22",key:"1nw9bq"}],["path",{d:"M14 14.66V17c0 .55.47.98.97 1.21C16.15 18.75 17 20.24 17 22",key:"1np0yb"}],["path",{d:"M18 2H6v7a6 6 0 0 0 12 0V2Z",key:"u46fv3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const S9=re("Truck",[["path",{d:"M14 18V6a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v11a1 1 0 0 0 1 1h2",key:"wrbu53"}],["path",{d:"M15 18H9",key:"1lyqi6"}],["path",{d:"M19 18h2a1 1 0 0 0 1-1v-3.65a1 1 0 0 0-.22-.624l-3.48-4.35A1 1 0 0 0 17.52 8H14",key:"lysw3i"}],["circle",{cx:"17",cy:"18",r:"2",key:"332jqn"}],["circle",{cx:"7",cy:"18",r:"2",key:"19iecd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const she=re("Turtle",[["path",{d:"m12 10 2 4v3a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-3a8 8 0 1 0-16 0v3a1 1 0 0 0 1 1h2a1 1 0 0 0 1-1v-3l2-4h4Z",key:"1lbbv7"}],["path",{d:"M4.82 7.9 8 10",key:"m9wose"}],["path",{d:"M15.18 7.9 12 10",key:"p8dp2u"}],["path",{d:"M16.93 10H20a2 2 0 0 1 0 4H2",key:"12nsm7"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nhe=re("TvMinimalPlay",[["path",{d:"M10 7.75a.75.75 0 0 1 1.142-.638l3.664 2.249a.75.75 0 0 1 0 1.278l-3.664 2.25a.75.75 0 0 1-1.142-.64z",key:"1pctta"}],["path",{d:"M7 21h10",key:"1b0cd5"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hE=re("TvMinimal",[["path",{d:"M7 21h10",key:"1b0cd5"}],["rect",{width:"20",height:"14",x:"2",y:"3",rx:"2",key:"48i651"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rhe=re("Tv",[["rect",{width:"20",height:"15",x:"2",y:"7",rx:"2",ry:"2",key:"10ag99"}],["polyline",{points:"17 2 12 7 7 2",key:"11pgbg"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ahe=re("Twitch",[["path",{d:"M21 2H3v16h5v4l4-4h5l4-4V2zm-10 9V7m5 4V7",key:"c0yzno"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ihe=re("Twitter",[["path",{d:"M22 4s-.7 2.1-2 3.4c1.6 10-9.4 17.3-18 11.6 2.2.1 4.4-.6 6-2C3 15.5.5 9.6 3 5c2.2 2.6 5.6 4.1 9 4-.9-4.2 4-6.6 7-3.8 1.1 0 3-1.2 3-1.2z",key:"pff0z6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ohe=re("TypeOutline",[["path",{d:"M14 16.5a.5.5 0 0 0 .5.5h.5a2 2 0 0 1 0 4H9a2 2 0 0 1 0-4h.5a.5.5 0 0 0 .5-.5v-9a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5V8a2 2 0 0 1-4 0V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2v3a2 2 0 0 1-4 0v-.5a.5.5 0 0 0-.5-.5h-3a.5.5 0 0 0-.5.5Z",key:"1reda3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lhe=re("Type",[["polyline",{points:"4 7 4 4 20 4 20 7",key:"1nosan"}],["line",{x1:"9",x2:"15",y1:"20",y2:"20",key:"swin9y"}],["line",{x1:"12",x2:"12",y1:"4",y2:"20",key:"1tx1rr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const che=re("UmbrellaOff",[["path",{d:"M12 2v1",key:"11qlp1"}],["path",{d:"M15.5 21a1.85 1.85 0 0 1-3.5-1v-8H2a10 10 0 0 1 3.428-6.575",key:"eki10q"}],["path",{d:"M17.5 12H22A10 10 0 0 0 9.004 3.455",key:"n2ayka"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dhe=re("Umbrella",[["path",{d:"M22 12a10.06 10.06 1 0 0-20 0Z",key:"1teyop"}],["path",{d:"M12 12v8a2 2 0 0 0 4 0",key:"ulpmoc"}],["path",{d:"M12 2v1",key:"11qlp1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fL=re("Underline",[["path",{d:"M6 4v6a6 6 0 0 0 12 0V4",key:"9kb039"}],["line",{x1:"4",x2:"20",y1:"20",y2:"20",key:"nun2al"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const uhe=re("Undo2",[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const hhe=re("UndoDot",[["path",{d:"M21 17a9 9 0 0 0-15-6.7L3 13",key:"8mp6z9"}],["path",{d:"M3 7v6h6",key:"1v2h90"}],["circle",{cx:"12",cy:"17",r:"1",key:"1ixnty"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const n4=re("Undo",[["path",{d:"M3 7v6h6",key:"1v2h90"}],["path",{d:"M21 17a9 9 0 0 0-9-9 9 9 0 0 0-6 2.3L3 13",key:"1r6uu6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mhe=re("UnfoldHorizontal",[["path",{d:"M16 12h6",key:"15xry1"}],["path",{d:"M8 12H2",key:"1jqql6"}],["path",{d:"M12 2v2",key:"tus03m"}],["path",{d:"M12 8v2",key:"1woqiv"}],["path",{d:"M12 14v2",key:"8jcxud"}],["path",{d:"M12 20v2",key:"1lh1kg"}],["path",{d:"m19 15 3-3-3-3",key:"wjy7rq"}],["path",{d:"m5 9-3 3 3 3",key:"j64kie"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const phe=re("UnfoldVertical",[["path",{d:"M12 22v-6",key:"6o8u61"}],["path",{d:"M12 8V2",key:"1wkif3"}],["path",{d:"M4 12H2",key:"rhcxmi"}],["path",{d:"M10 12H8",key:"s88cx1"}],["path",{d:"M16 12h-2",key:"10asgb"}],["path",{d:"M22 12h-2",key:"14jgyd"}],["path",{d:"m15 19-3 3-3-3",key:"11eu04"}],["path",{d:"m15 5-3-3-3 3",key:"itvq4r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fhe=re("Ungroup",[["rect",{width:"8",height:"6",x:"5",y:"4",rx:"1",key:"nzclkv"}],["rect",{width:"8",height:"6",x:"11",y:"14",rx:"1",key:"4tytwb"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const mE=re("University",[["circle",{cx:"12",cy:"10",r:"1",key:"1gnqs8"}],["path",{d:"M22 20V8h-4l-6-4-6 4H2v12a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2",key:"1qj5sn"}],["path",{d:"M6 17v.01",key:"roodi6"}],["path",{d:"M6 13v.01",key:"67c122"}],["path",{d:"M18 17v.01",key:"12ktxm"}],["path",{d:"M18 13v.01",key:"tn1rt1"}],["path",{d:"M14 22v-5a2 2 0 0 0-2-2a2 2 0 0 0-2 2v5",key:"11g7fi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xhe=re("Unlink2",[["path",{d:"M15 7h2a5 5 0 0 1 0 10h-2m-6 0H7A5 5 0 0 1 7 7h2",key:"1re2ne"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const OA=re("Unlink",[["path",{d:"m18.84 12.25 1.72-1.71h-.02a5.004 5.004 0 0 0-.12-7.07 5.006 5.006 0 0 0-6.95 0l-1.72 1.71",key:"yqzxt4"}],["path",{d:"m5.17 11.75-1.71 1.71a5.004 5.004 0 0 0 .12 7.07 5.006 5.006 0 0 0 6.95 0l1.71-1.71",key:"4qinb0"}],["line",{x1:"8",x2:"8",y1:"2",y2:"5",key:"1041cp"}],["line",{x1:"2",x2:"5",y1:"8",y2:"8",key:"14m1p5"}],["line",{x1:"16",x2:"16",y1:"19",y2:"22",key:"rzdirn"}],["line",{x1:"19",x2:"22",y1:"16",y2:"16",key:"ox905f"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ghe=re("Unplug",[["path",{d:"m19 5 3-3",key:"yk6iyv"}],["path",{d:"m2 22 3-3",key:"19mgm9"}],["path",{d:"M6.3 20.3a2.4 2.4 0 0 0 3.4 0L12 18l-6-6-2.3 2.3a2.4 2.4 0 0 0 0 3.4Z",key:"goz73y"}],["path",{d:"M7.5 13.5 10 11",key:"7xgeeb"}],["path",{d:"M10.5 16.5 13 14",key:"10btkg"}],["path",{d:"m12 6 6 6 2.3-2.3a2.4 2.4 0 0 0 0-3.4l-2.6-2.6a2.4 2.4 0 0 0-3.4 0Z",key:"1snsnr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _a=re("Upload",[["path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4",key:"ih7n3h"}],["polyline",{points:"17 8 12 3 7 8",key:"t8dd8p"}],["line",{x1:"12",x2:"12",y1:"3",y2:"15",key:"widbto"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yhe=re("Usb",[["circle",{cx:"10",cy:"7",r:"1",key:"dypaad"}],["circle",{cx:"4",cy:"20",r:"1",key:"22iqad"}],["path",{d:"M4.7 19.3 19 5",key:"1enqfc"}],["path",{d:"m21 3-3 1 2 2Z",key:"d3ov82"}],["path",{d:"M9.26 7.68 5 12l2 5",key:"1esawj"}],["path",{d:"m10 14 5 2 3.5-3.5",key:"v8oal5"}],["path",{d:"m18 12 1-1 1 1-1 1Z",key:"1bh22v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xb=re("UserCheck",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["polyline",{points:"16 11 18 13 22 9",key:"1pwet4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const C9=re("UserCog",[["circle",{cx:"18",cy:"15",r:"3",key:"gjjjvw"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M10 15H6a4 4 0 0 0-4 4v2",key:"1nfge6"}],["path",{d:"m21.7 16.4-.9-.3",key:"12j9ji"}],["path",{d:"m15.2 13.9-.9-.3",key:"1fdjdi"}],["path",{d:"m16.6 18.7.3-.9",key:"heedtr"}],["path",{d:"m19.1 12.2.3-.9",key:"1af3ki"}],["path",{d:"m19.6 18.7-.4-1",key:"1x9vze"}],["path",{d:"m16.8 12.3-.4-1",key:"vqeiwj"}],["path",{d:"m14.3 16.6 1-.4",key:"1qlj63"}],["path",{d:"m20.7 13.8 1-.4",key:"1v5t8k"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const T9=re("UserMinus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vhe=re("UserPen",[["path",{d:"M11.5 15H7a4 4 0 0 0-4 4v2",key:"15lzij"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fo=re("UserPlus",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"19",x2:"19",y1:"8",y2:"14",key:"1bvyxn"}],["line",{x1:"22",x2:"16",y1:"11",y2:"11",key:"1shjgl"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pE=re("UserRoundCheck",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"m16 19 2 2 4-4",key:"1b14m6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fE=re("UserRoundCog",[["path",{d:"M2 21a8 8 0 0 1 10.434-7.62",key:"1yezr2"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m19.5 14.3-.4.9",key:"1eb35c"}],["path",{d:"m16.9 20.8-.4.9",key:"dfjc4z"}],["path",{d:"m21.7 19.5-.9-.4",key:"q4dx6b"}],["path",{d:"m15.2 16.9-.9-.4",key:"1r0w5f"}],["path",{d:"m21.7 16.5-.9.4",key:"1knoei"}],["path",{d:"m15.2 19.1-.9.4",key:"j188fs"}],["path",{d:"m19.5 21.7-.4-.9",key:"1tonu5"}],["path",{d:"m16.9 15.2-.4-.9",key:"699xu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xE=re("UserRoundMinus",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 19h-6",key:"vcuq98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bhe=re("UserRoundPen",[["path",{d:"M2 21a8 8 0 0 1 10.821-7.487",key:"1c8h7z"}],["path",{d:"M21.378 16.626a1 1 0 0 0-3.004-3.004l-4.01 4.012a2 2 0 0 0-.506.854l-.837 2.87a.5.5 0 0 0 .62.62l2.87-.837a2 2 0 0 0 .854-.506z",key:"1817ys"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gE=re("UserRoundPlus",[["path",{d:"M2 21a8 8 0 0 1 13.292-6",key:"bjp14o"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M19 16v6",key:"tddt3s"}],["path",{d:"M22 19h-6",key:"vcuq98"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _he=re("UserRoundSearch",[["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M2 21a8 8 0 0 1 10.434-7.62",key:"1yezr2"}],["circle",{cx:"18",cy:"18",r:"3",key:"1xkwt0"}],["path",{d:"m22 22-1.9-1.9",key:"1e5ubv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yE=re("UserRoundX",[["path",{d:"M2 21a8 8 0 0 1 11.873-7",key:"74fkxq"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"m17 17 5 5",key:"p7ous7"}],["path",{d:"m22 17-5 5",key:"gqnmv0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const vE=re("UserRound",[["circle",{cx:"12",cy:"8",r:"5",key:"1hypcn"}],["path",{d:"M20 21a8 8 0 0 0-16 0",key:"rfgkzh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const whe=re("UserSearch",[["circle",{cx:"10",cy:"7",r:"4",key:"e45bow"}],["path",{d:"M10.3 15H7a4 4 0 0 0-4 4v2",key:"3bnktk"}],["circle",{cx:"17",cy:"17",r:"3",key:"18b49y"}],["path",{d:"m21 21-1.9-1.9",key:"1g2n9r"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const jhe=re("UserX",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["line",{x1:"17",x2:"22",y1:"8",y2:"13",key:"3nzzx3"}],["line",{x1:"22",x2:"17",y1:"8",y2:"13",key:"1swrse"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Wi=re("User",[["path",{d:"M19 21v-2a4 4 0 0 0-4-4H9a4 4 0 0 0-4 4v2",key:"975kel"}],["circle",{cx:"12",cy:"7",r:"4",key:"17ys0d"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const q0=re("UsersRound",[["path",{d:"M18 21a8 8 0 0 0-16 0",key:"3ypg7q"}],["circle",{cx:"10",cy:"8",r:"5",key:"o932ke"}],["path",{d:"M22 20c0-3.37-2-6.5-4-8a5 5 0 0 0-.45-8.3",key:"10s06x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const An=re("Users",[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["path",{d:"M16 3.13a4 4 0 0 1 0 7.75",key:"1da9ce"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const bE=re("UtensilsCrossed",[["path",{d:"m16 2-2.3 2.3a3 3 0 0 0 0 4.2l1.8 1.8a3 3 0 0 0 4.2 0L22 8",key:"n7qcjb"}],["path",{d:"M15 15 3.3 3.3a4.2 4.2 0 0 0 0 6l7.3 7.3c.7.7 2 .7 2.8 0L15 15Zm0 0 7 7",key:"d0u48b"}],["path",{d:"m2.1 21.8 6.4-6.3",key:"yn04lh"}],["path",{d:"m19 5-7 7",key:"194lzd"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const _E=re("Utensils",[["path",{d:"M3 2v7c0 1.1.9 2 2 2h4a2 2 0 0 0 2-2V2",key:"cjf0a3"}],["path",{d:"M7 2v20",key:"1473qp"}],["path",{d:"M21 15V2a5 5 0 0 0-5 5v6c0 1.1.9 2 2 2h3Zm0 0v7",key:"j28e5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Nhe=re("UtilityPole",[["path",{d:"M12 2v20",key:"t6zp3m"}],["path",{d:"M2 5h20",key:"1fs1ex"}],["path",{d:"M3 3v2",key:"9imdir"}],["path",{d:"M7 3v2",key:"n0os7"}],["path",{d:"M17 3v2",key:"1l2re6"}],["path",{d:"M21 3v2",key:"1duuac"}],["path",{d:"m19 5-7 7-7-7",key:"133zxf"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const xL=re("Variable",[["path",{d:"M8 21s-4-3-4-9 4-9 4-9",key:"uto9ud"}],["path",{d:"M16 3s4 3 4 9-4 9-4 9",key:"4w2vsq"}],["line",{x1:"15",x2:"9",y1:"9",y2:"15",key:"f7djnv"}],["line",{x1:"9",x2:"15",y1:"9",y2:"15",key:"1shsy8"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const khe=re("Vault",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["path",{d:"m7.9 7.9 2.7 2.7",key:"hpeyl3"}],["circle",{cx:"16.5",cy:"7.5",r:".5",fill:"currentColor",key:"w0ekpg"}],["path",{d:"m13.4 10.6 2.7-2.7",key:"264c1n"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["path",{d:"m7.9 16.1 2.7-2.7",key:"p81g5e"}],["circle",{cx:"16.5",cy:"16.5",r:".5",fill:"currentColor",key:"fubopw"}],["path",{d:"m13.4 13.4 2.7 2.7",key:"abhel3"}],["circle",{cx:"12",cy:"12",r:"2",key:"1c9p78"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const She=re("Vegan",[["path",{d:"M16 8q6 0 6-6-6 0-6 6",key:"qsyyc4"}],["path",{d:"M17.41 3.59a10 10 0 1 0 3 3",key:"41m9h7"}],["path",{d:"M2 2a26.6 26.6 0 0 1 10 20c.9-6.82 1.5-9.5 4-14",key:"qiv7li"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Che=re("VenetianMask",[["path",{d:"M18 11c-1.5 0-2.5.5-3 2",key:"1fod00"}],["path",{d:"M4 6a2 2 0 0 0-2 2v4a5 5 0 0 0 5 5 8 8 0 0 1 5 2 8 8 0 0 1 5-2 5 5 0 0 0 5-5V8a2 2 0 0 0-2-2h-3a8 8 0 0 0-5 2 8 8 0 0 0-5-2z",key:"d70hit"}],["path",{d:"M6 11c1.5 0 2.5.5 3 2",key:"136fht"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const The=re("VibrateOff",[["path",{d:"m2 8 2 2-2 2 2 2-2 2",key:"sv1b1"}],["path",{d:"m22 8-2 2 2 2-2 2 2 2",key:"101i4y"}],["path",{d:"M8 8v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2",key:"1hbad5"}],["path",{d:"M16 10.34V6c0-.55-.45-1-1-1h-4.34",key:"1x5tf0"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ehe=re("Vibrate",[["path",{d:"m2 8 2 2-2 2 2 2-2 2",key:"sv1b1"}],["path",{d:"m22 8-2 2 2 2-2 2 2 2",key:"101i4y"}],["rect",{width:"8",height:"14",x:"8",y:"5",rx:"1",key:"1oyrl4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ahe=re("VideoOff",[["path",{d:"M10.66 6H14a2 2 0 0 1 2 2v2.5l5.248-3.062A.5.5 0 0 1 22 7.87v8.196",key:"w8jjjt"}],["path",{d:"M16 16a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h2",key:"1xawa7"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const fr=re("Video",[["path",{d:"m16 13 5.223 3.482a.5.5 0 0 0 .777-.416V7.87a.5.5 0 0 0-.752-.432L16 10.5",key:"ftymec"}],["rect",{x:"2",y:"6",width:"14",height:"12",rx:"2",key:"158x01"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Mhe=re("Videotape",[["rect",{width:"20",height:"16",x:"2",y:"4",rx:"2",key:"18n3k1"}],["path",{d:"M2 8h20",key:"d11cs7"}],["circle",{cx:"8",cy:"14",r:"2",key:"1k2qr5"}],["path",{d:"M8 12h8",key:"1wcyev"}],["circle",{cx:"16",cy:"14",r:"2",key:"14k7lr"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ihe=re("View",[["path",{d:"M21 17v2a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-2",key:"mrq65r"}],["path",{d:"M21 7V5a2 2 0 0 0-2-2H5a2 2 0 0 0-2 2v2",key:"be3xqs"}],["circle",{cx:"12",cy:"12",r:"1",key:"41hilf"}],["path",{d:"M18.944 12.33a1 1 0 0 0 0-.66 7.5 7.5 0 0 0-13.888 0 1 1 0 0 0 0 .66 7.5 7.5 0 0 0 13.888 0",key:"11ak4c"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Phe=re("Voicemail",[["circle",{cx:"6",cy:"12",r:"4",key:"1ehtga"}],["circle",{cx:"18",cy:"12",r:"4",key:"4vafl8"}],["line",{x1:"6",x2:"18",y1:"16",y2:"16",key:"pmt8us"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Lhe=re("Volleyball",[["path",{d:"M11.1 7.1a16.55 16.55 0 0 1 10.9 4",key:"2880wi"}],["path",{d:"M12 12a12.6 12.6 0 0 1-8.7 5",key:"113sja"}],["path",{d:"M16.8 13.6a16.55 16.55 0 0 1-9 7.5",key:"1qmsgl"}],["path",{d:"M20.7 17a12.8 12.8 0 0 0-8.7-5 13.3 13.3 0 0 1 0-10",key:"1bmeqp"}],["path",{d:"M6.3 3.8a16.55 16.55 0 0 0 1.9 11.5",key:"iekzv9"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Dhe=re("Volume1",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const E9=re("Volume2",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["path",{d:"M16 9a5 5 0 0 1 0 6",key:"1q6k2b"}],["path",{d:"M19.364 18.364a9 9 0 0 0 0-12.728",key:"ijwkga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Rhe=re("VolumeOff",[["path",{d:"M16 9a5 5 0 0 1 .95 2.293",key:"1fgyg8"}],["path",{d:"M19.364 5.636a9 9 0 0 1 1.889 9.96",key:"l3zxae"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"m7 7-.587.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298V11",key:"1gbwow"}],["path",{d:"M9.828 4.172A.686.686 0 0 1 11 4.657v.686",key:"s2je0y"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const A9=re("VolumeX",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}],["line",{x1:"22",x2:"16",y1:"9",y2:"15",key:"1ewh16"}],["line",{x1:"16",x2:"22",y1:"9",y2:"15",key:"5ykzw1"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ohe=re("Volume",[["path",{d:"M11 4.702a.705.705 0 0 0-1.203-.498L6.413 7.587A1.4 1.4 0 0 1 5.416 8H3a1 1 0 0 0-1 1v6a1 1 0 0 0 1 1h2.416a1.4 1.4 0 0 1 .997.413l3.383 3.384A.705.705 0 0 0 11 19.298z",key:"uqj9uw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Fhe=re("Vote",[["path",{d:"m9 12 2 2 4-4",key:"dzmm74"}],["path",{d:"M5 7c0-1.1.9-2 2-2h10a2 2 0 0 1 2 2v12H5V7Z",key:"1ezoue"}],["path",{d:"M22 19H2",key:"nuriw5"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const zhe=re("WalletCards",[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9a2 2 0 0 1 2-2h14a2 2 0 0 1 2 2",key:"4125el"}],["path",{d:"M3 11h3c.8 0 1.6.3 2.1.9l1.1.9c1.6 1.6 4.1 1.6 5.7 0l1.1-.9c.5-.5 1.3-.9 2.1-.9H21",key:"1dpki6"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const wE=re("WalletMinimal",[["path",{d:"M17 14h.01",key:"7oqj8z"}],["path",{d:"M7 7h12a2 2 0 0 1 2 2v10a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h14",key:"u1rqew"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gL=re("Wallet",[["path",{d:"M19 7V4a1 1 0 0 0-1-1H5a2 2 0 0 0 0 4h15a1 1 0 0 1 1 1v4h-3a2 2 0 0 0 0 4h3a1 1 0 0 0 1-1v-2a1 1 0 0 0-1-1",key:"18etb6"}],["path",{d:"M3 5v14a2 2 0 0 0 2 2h15a1 1 0 0 0 1-1v-4",key:"xoc0q4"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Bhe=re("Wallpaper",[["circle",{cx:"8",cy:"9",r:"2",key:"gjzl9d"}],["path",{d:"m9 17 6.1-6.1a2 2 0 0 1 2.81.01L22 15V5a2 2 0 0 0-2-2H4a2 2 0 0 0-2 2v10a2 2 0 0 0 2 2h16a2 2 0 0 0 2-2",key:"69xh40"}],["path",{d:"M8 21h8",key:"1ev6f3"}],["path",{d:"M12 17v4",key:"1riwvh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Im=re("WandSparkles",[["path",{d:"m21.64 3.64-1.28-1.28a1.21 1.21 0 0 0-1.72 0L2.36 18.64a1.21 1.21 0 0 0 0 1.72l1.28 1.28a1.2 1.2 0 0 0 1.72 0L21.64 5.36a1.2 1.2 0 0 0 0-1.72",key:"ul74o6"}],["path",{d:"m14 7 3 3",key:"1r5n42"}],["path",{d:"M5 6v4",key:"ilb8ba"}],["path",{d:"M19 14v4",key:"blhpug"}],["path",{d:"M10 2v2",key:"7u0qdc"}],["path",{d:"M7 8H3",key:"zfb6yr"}],["path",{d:"M21 16h-4",key:"1cnmox"}],["path",{d:"M11 3H9",key:"1obp7u"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $he=re("Wand",[["path",{d:"M15 4V2",key:"z1p9b7"}],["path",{d:"M15 16v-2",key:"px0unx"}],["path",{d:"M8 9h2",key:"1g203m"}],["path",{d:"M20 9h2",key:"19tzq7"}],["path",{d:"M17.8 11.8 19 13",key:"yihg8r"}],["path",{d:"M15 9h.01",key:"x1ddxp"}],["path",{d:"M17.8 6.2 19 5",key:"fd4us0"}],["path",{d:"m3 21 9-9",key:"1jfql5"}],["path",{d:"M12.2 6.2 11 5",key:"i3da3b"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Uhe=re("Warehouse",[["path",{d:"M22 8.35V20a2 2 0 0 1-2 2H4a2 2 0 0 1-2-2V8.35A2 2 0 0 1 3.26 6.5l8-3.2a2 2 0 0 1 1.48 0l8 3.2A2 2 0 0 1 22 8.35Z",key:"gksnxg"}],["path",{d:"M6 18h12",key:"9pbo8z"}],["path",{d:"M6 14h12",key:"4cwo0f"}],["rect",{width:"12",height:"12",x:"6",y:"10",key:"apd30q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const qhe=re("WashingMachine",[["path",{d:"M3 6h3",key:"155dbl"}],["path",{d:"M17 6h.01",key:"e2y6kg"}],["rect",{width:"18",height:"20",x:"3",y:"2",rx:"2",key:"od3kk9"}],["circle",{cx:"12",cy:"13",r:"5",key:"nlbqau"}],["path",{d:"M12 18a2.5 2.5 0 0 0 0-5 2.5 2.5 0 0 1 0-5",key:"17lach"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Vhe=re("Watch",[["circle",{cx:"12",cy:"12",r:"6",key:"1vlfrh"}],["polyline",{points:"12 10 12 12 13 13",key:"19dquz"}],["path",{d:"m16.13 7.66-.81-4.05a2 2 0 0 0-2-1.61h-2.68a2 2 0 0 0-2 1.61l-.78 4.05",key:"18k57s"}],["path",{d:"m7.88 16.36.8 4a2 2 0 0 0 2 1.61h2.72a2 2 0 0 0 2-1.61l.81-4.05",key:"16ny36"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Hhe=re("Waves",[["path",{d:"M2 6c.6.5 1.2 1 2.5 1C7 7 7 5 9.5 5c2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"knzxuh"}],["path",{d:"M2 12c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"2jd2cc"}],["path",{d:"M2 18c.6.5 1.2 1 2.5 1 2.5 0 2.5-2 5-2 2.6 0 2.4 2 5 2 2.5 0 2.5-2 5-2 1.3 0 1.9.5 2.5 1",key:"rd2r6e"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Ghe=re("Waypoints",[["circle",{cx:"12",cy:"4.5",r:"2.5",key:"r5ysbb"}],["path",{d:"m10.2 6.3-3.9 3.9",key:"1nzqf6"}],["circle",{cx:"4.5",cy:"12",r:"2.5",key:"jydg6v"}],["path",{d:"M7 12h10",key:"b7w52i"}],["circle",{cx:"19.5",cy:"12",r:"2.5",key:"1piiel"}],["path",{d:"m13.8 17.7 3.9-3.9",key:"1wyg1y"}],["circle",{cx:"12",cy:"19.5",r:"2.5",key:"13o1pw"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Whe=re("Webcam",[["circle",{cx:"12",cy:"10",r:"8",key:"1gshiw"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}],["path",{d:"M7 22h10",key:"10w4w3"}],["path",{d:"M12 22v-4",key:"1utk9m"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Khe=re("WebhookOff",[["path",{d:"M17 17h-5c-1.09-.02-1.94.92-2.5 1.9A3 3 0 1 1 2.57 15",key:"1tvl6x"}],["path",{d:"M9 3.4a4 4 0 0 1 6.52.66",key:"q04jfq"}],["path",{d:"m6 17 3.1-5.8a2.5 2.5 0 0 0 .057-2.05",key:"azowf0"}],["path",{d:"M20.3 20.3a4 4 0 0 1-2.3.7",key:"5joiws"}],["path",{d:"M18.6 13a4 4 0 0 1 3.357 3.414",key:"cangb8"}],["path",{d:"m12 6 .6 1",key:"tpjl1n"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Yhe=re("Webhook",[["path",{d:"M18 16.98h-5.99c-1.1 0-1.95.94-2.48 1.9A4 4 0 0 1 2 17c.01-.7.2-1.4.57-2",key:"q3hayz"}],["path",{d:"m6 17 3.13-5.78c.53-.97.1-2.18-.5-3.1a4 4 0 1 1 6.89-4.06",key:"1go1hn"}],["path",{d:"m12 6 3.13 5.73C15.66 12.7 16.9 13 18 13a4 4 0 0 1 0 8",key:"qlwsc0"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Zhe=re("Weight",[["circle",{cx:"12",cy:"5",r:"3",key:"rqqgnr"}],["path",{d:"M6.5 8a2 2 0 0 0-1.905 1.46L2.1 18.5A2 2 0 0 0 4 21h16a2 2 0 0 0 1.925-2.54L19.4 9.5A2 2 0 0 0 17.48 8Z",key:"56o5sh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Qhe=re("WheatOff",[["path",{d:"m2 22 10-10",key:"28ilpk"}],["path",{d:"m16 8-1.17 1.17",key:"1qqm82"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"m8 8-.53.53a3.5 3.5 0 0 0 0 4.94L9 15l1.53-1.53c.55-.55.88-1.25.98-1.97",key:"4wz8re"}],["path",{d:"M10.91 5.26c.15-.26.34-.51.56-.73L13 3l1.53 1.53a3.5 3.5 0 0 1 .28 4.62",key:"rves66"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"m16 16-.53.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.49 3.49 0 0 1 1.97-.98",key:"ak46r"}],["path",{d:"M18.74 13.09c.26-.15.51-.34.73-.56L21 11l-1.53-1.53a3.5 3.5 0 0 0-4.62-.28",key:"1tw520"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Xhe=re("Wheat",[["path",{d:"M2 22 16 8",key:"60hf96"}],["path",{d:"M3.47 12.53 5 11l1.53 1.53a3.5 3.5 0 0 1 0 4.94L5 19l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1rdhi6"}],["path",{d:"M7.47 8.53 9 7l1.53 1.53a3.5 3.5 0 0 1 0 4.94L9 15l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"1sdzmb"}],["path",{d:"M11.47 4.53 13 3l1.53 1.53a3.5 3.5 0 0 1 0 4.94L13 11l-1.53-1.53a3.5 3.5 0 0 1 0-4.94Z",key:"eoatbi"}],["path",{d:"M20 2h2v2a4 4 0 0 1-4 4h-2V6a4 4 0 0 1 4-4Z",key:"19rau1"}],["path",{d:"M11.47 17.47 13 19l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L5 19l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"tc8ph9"}],["path",{d:"M15.47 13.47 17 15l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L9 15l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"2m8kc5"}],["path",{d:"M19.47 9.47 21 11l-1.53 1.53a3.5 3.5 0 0 1-4.94 0L13 11l1.53-1.53a3.5 3.5 0 0 1 4.94 0Z",key:"vex3ng"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const Jhe=re("WholeWord",[["circle",{cx:"7",cy:"12",r:"3",key:"12clwm"}],["path",{d:"M10 9v6",key:"17i7lo"}],["circle",{cx:"17",cy:"12",r:"3",key:"gl7c2s"}],["path",{d:"M14 7v8",key:"dl84cr"}],["path",{d:"M22 17v1c0 .5-.5 1-1 1H3c-.5 0-1-.5-1-1v-1",key:"lt2kga"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const eme=re("WifiHigh",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const tme=re("WifiLow",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const sme=re("WifiOff",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}],["path",{d:"M5 12.859a10 10 0 0 1 5.17-2.69",key:"1dl1wf"}],["path",{d:"M19 12.859a10 10 0 0 0-2.007-1.523",key:"4k23kn"}],["path",{d:"M2 8.82a15 15 0 0 1 4.177-2.643",key:"1grhjp"}],["path",{d:"M22 8.82a15 15 0 0 0-11.288-3.764",key:"z3jwby"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const nme=re("WifiZero",[["path",{d:"M12 20h.01",key:"zekei9"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const rme=re("Wifi",[["path",{d:"M12 20h.01",key:"zekei9"}],["path",{d:"M2 8.82a15 15 0 0 1 20 0",key:"dnpr2z"}],["path",{d:"M5 12.859a10 10 0 0 1 14 0",key:"1x1e6c"}],["path",{d:"M8.5 16.429a5 5 0 0 1 7 0",key:"1bycff"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ame=re("WindArrowDown",[["path",{d:"M10 2v8",key:"d4bbey"}],["path",{d:"M12.8 21.6A2 2 0 1 0 14 18H2",key:"19kp1d"}],["path",{d:"M17.5 10a2.5 2.5 0 1 1 2 4H2",key:"19kpjc"}],["path",{d:"m6 6 4 4 4-4",key:"k13n16"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ime=re("Wind",[["path",{d:"M12.8 19.6A2 2 0 1 0 14 16H2",key:"148xed"}],["path",{d:"M17.5 8a2.5 2.5 0 1 1 2 4H2",key:"1u4tom"}],["path",{d:"M9.8 4.4A2 2 0 1 1 11 8H2",key:"75valh"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ome=re("WineOff",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M7 10h3m7 0h-1.343",key:"v48bem"}],["path",{d:"M12 15v7",key:"t2xh3l"}],["path",{d:"M7.307 7.307A12.33 12.33 0 0 0 7 10a5 5 0 0 0 7.391 4.391M8.638 2.981C8.75 2.668 8.872 2.34 9 2h6c1.5 4 2 6 2 8 0 .407-.05.809-.145 1.198",key:"1ymjlu"}],["line",{x1:"2",x2:"22",y1:"2",y2:"22",key:"a6p6uj"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const M9=re("Wine",[["path",{d:"M8 22h8",key:"rmew8v"}],["path",{d:"M7 10h10",key:"1101jm"}],["path",{d:"M12 15v7",key:"t2xh3l"}],["path",{d:"M12 15a5 5 0 0 0 5-5c0-2-.5-4-2-8H9c-1.5 4-2 6-2 8a5 5 0 0 0 5 5Z",key:"10ffi3"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const I9=re("Workflow",[["rect",{width:"8",height:"8",x:"3",y:"3",rx:"2",key:"by2w9f"}],["path",{d:"M7 11v4a2 2 0 0 0 2 2h4",key:"xkn7yn"}],["rect",{width:"8",height:"8",x:"13",y:"13",rx:"2",key:"1cgmvn"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const lme=re("Worm",[["path",{d:"m19 12-1.5 3",key:"9bcu4o"}],["path",{d:"M19.63 18.81 22 20",key:"121v98"}],["path",{d:"M6.47 8.23a1.68 1.68 0 0 1 2.44 1.93l-.64 2.08a6.76 6.76 0 0 0 10.16 7.67l.42-.27a1 1 0 1 0-2.73-4.21l-.42.27a1.76 1.76 0 0 1-2.63-1.99l.64-2.08A6.66 6.66 0 0 0 3.94 3.9l-.7.4a1 1 0 1 0 2.55 4.34z",key:"1tij6q"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const cme=re("WrapText",[["line",{x1:"3",x2:"21",y1:"6",y2:"6",key:"4m8b97"}],["path",{d:"M3 12h15a3 3 0 1 1 0 6h-4",key:"1cl7v7"}],["polyline",{points:"16 16 14 18 16 20",key:"1jznyi"}],["line",{x1:"3",x2:"10",y1:"18",y2:"18",key:"1h33wv"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const gb=re("Wrench",[["path",{d:"M14.7 6.3a1 1 0 0 0 0 1.4l1.6 1.6a1 1 0 0 0 1.4 0l3.77-3.77a6 6 0 0 1-7.94 7.94l-6.91 6.91a2.12 2.12 0 0 1-3-3l6.91-6.91a6 6 0 0 1 7.94-7.94l-3.76 3.76z",key:"cbrjhi"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const $n=re("X",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const dme=re("Youtube",[["path",{d:"M2.5 17a24.12 24.12 0 0 1 0-10 2 2 0 0 1 1.4-1.4 49.56 49.56 0 0 1 16.2 0A2 2 0 0 1 21.5 7a24.12 24.12 0 0 1 0 10 2 2 0 0 1-1.4 1.4 49.55 49.55 0 0 1-16.2 0A2 2 0 0 1 2.5 17",key:"1q2vi4"}],["path",{d:"m10 15 5-3-5-3z",key:"1jp15x"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const ume=re("ZapOff",[["path",{d:"M10.513 4.856 13.12 2.17a.5.5 0 0 1 .86.46l-1.377 4.317",key:"193nxd"}],["path",{d:"M15.656 10H20a1 1 0 0 1 .78 1.63l-1.72 1.773",key:"27a7lr"}],["path",{d:"M16.273 16.273 10.88 21.83a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14H4a1 1 0 0 1-.78-1.63l4.507-4.643",key:"1e0qe9"}],["path",{d:"m2 2 20 20",key:"1ooewy"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const im=re("Zap",[["path",{d:"M4 14a1 1 0 0 1-.78-1.63l9.9-10.2a.5.5 0 0 1 .86.46l-1.92 6.02A1 1 0 0 0 13 10h7a1 1 0 0 1 .78 1.63l-9.9 10.2a.5.5 0 0 1-.86-.46l1.92-6.02A1 1 0 0 0 11 14z",key:"1xq2db"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const r4=re("ZoomIn",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"11",x2:"11",y1:"8",y2:"14",key:"1vmskp"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const yL=re("ZoomOut",[["circle",{cx:"11",cy:"11",r:"8",key:"4ej97u"}],["line",{x1:"21",x2:"16.65",y1:"21",y2:"16.65",key:"13gj7c"}],["line",{x1:"8",x2:"14",y1:"11",y2:"11",key:"durymu"}]]);/** * @license lucide-react v0.462.0 - ISC * * This source code is licensed under the ISC license. * See the LICENSE file in the root directory of this source tree. */const pMt=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:hW,AArrowUp:mW,ALargeSmall:pW,Accessibility:fW,Activity:em,AirVent:xW,Airplay:gW,AlarmClock:vW,AlarmClockCheck:x3,AlarmClockMinus:g3,AlarmClockOff:yW,AlarmClockPlus:y3,AlarmSmoke:bW,Album:_W,AlignCenter:pA,AlignCenterHorizontal:wW,AlignCenterVertical:jW,AlignEndHorizontal:NW,AlignEndVertical:kW,AlignHorizontalDistributeCenter:SW,AlignHorizontalDistributeEnd:CW,AlignHorizontalDistributeStart:TW,AlignHorizontalJustifyCenter:EW,AlignHorizontalJustifyEnd:AW,AlignHorizontalJustifyStart:MW,AlignHorizontalSpaceAround:IW,AlignHorizontalSpaceBetween:PW,AlignJustify:LW,AlignLeft:fA,AlignRight:xA,AlignStartHorizontal:DW,AlignStartVertical:RW,AlignVerticalDistributeCenter:OW,AlignVerticalDistributeEnd:FW,AlignVerticalDistributeStart:zW,AlignVerticalJustifyCenter:BW,AlignVerticalJustifyEnd:$W,AlignVerticalJustifyStart:UW,AlignVerticalSpaceAround:qW,AlignVerticalSpaceBetween:VW,Ambulance:HW,Ampersand:GW,Ampersands:WW,Amphora:KW,Anchor:YW,Angry:ZW,Annoyed:QW,Antenna:XW,Anvil:JW,Aperture:eK,AppWindow:sK,AppWindowMac:tK,Apple:nK,Archive:tm,ArchiveRestore:HP,ArchiveX:rK,Armchair:aK,ArrowBigDown:oK,ArrowBigDownDash:iK,ArrowBigLeft:cK,ArrowBigLeftDash:lK,ArrowBigRight:uK,ArrowBigRightDash:dK,ArrowBigUp:mK,ArrowBigUpDash:hK,ArrowDown:sm,ArrowDown01:pK,ArrowDown10:fK,ArrowDownAZ:v3,ArrowDownFromLine:xK,ArrowDownLeft:gK,ArrowDownNarrowWide:yK,ArrowDownRight:I7,ArrowDownToDot:vK,ArrowDownToLine:bK,ArrowDownUp:_K,ArrowDownWideNarrow:b3,ArrowDownZA:_3,ArrowLeft:qr,ArrowLeftFromLine:wK,ArrowLeftRight:jK,ArrowLeftToLine:NK,ArrowRight:Oa,ArrowRightFromLine:kK,ArrowRightLeft:lw,ArrowRightToLine:SK,ArrowUp:Iu,ArrowUp01:CK,ArrowUp10:TK,ArrowUpAZ:w3,ArrowUpDown:ah,ArrowUpFromDot:EK,ArrowUpFromLine:AK,ArrowUpLeft:MK,ArrowUpNarrowWide:j3,ArrowUpRight:GP,ArrowUpToLine:IK,ArrowUpWideNarrow:PK,ArrowUpZA:N3,ArrowsUpFromLine:LK,Asterisk:DK,AtSign:RK,Atom:OK,AudioLines:FK,AudioWaveform:zK,Award:fc,Axe:BK,Axis3d:k3,Baby:$K,Backpack:UK,Badge:rY,BadgeAlert:qK,BadgeCent:VK,BadgeCheck:S3,BadgeDollarSign:HK,BadgeEuro:GK,BadgeHelp:WK,BadgeIndianRupee:KK,BadgeInfo:YK,BadgeJapaneseYen:ZK,BadgeMinus:QK,BadgePercent:XK,BadgePlus:JK,BadgePoundSterling:eY,BadgeRussianRuble:tY,BadgeSwissFranc:sY,BadgeX:nY,BaggageClaim:aY,Ban:WP,Banana:iY,Bandage:oY,Banknote:lY,Barcode:cY,Baseline:dY,Bath:kp,Battery:xY,BatteryCharging:uY,BatteryFull:hY,BatteryLow:mY,BatteryMedium:pY,BatteryWarning:fY,Beaker:P7,Bean:yY,BeanOff:gY,Bed:J0,BedDouble:U2,BedSingle:vY,Beef:bY,Beer:wY,BeerOff:_Y,Bell:nm,BellDot:jY,BellElectric:NY,BellMinus:kY,BellOff:cw,BellPlus:SY,BellRing:BS,BetweenHorizontalEnd:C3,BetweenHorizontalStart:T3,BetweenVerticalEnd:CY,BetweenVerticalStart:TY,BicepsFlexed:EY,Bike:AY,Binary:MY,Binoculars:IY,Biohazard:PY,Bird:LY,Bitcoin:DY,Blend:RY,Blinds:OY,Blocks:FY,Bluetooth:UY,BluetoothConnected:zY,BluetoothOff:BY,BluetoothSearching:$Y,Bold:$S,Bolt:qY,Bomb:VY,Bone:HY,Book:mZ,BookA:GY,BookAudio:WY,BookCheck:KY,BookCopy:YY,BookDashed:E3,BookDown:ZY,BookHeadphones:QY,BookHeart:XY,BookImage:JY,BookKey:eZ,BookLock:tZ,BookMarked:sZ,BookMinus:nZ,BookOpen:rm,BookOpenCheck:rZ,BookOpenText:aZ,BookPlus:iZ,BookText:oZ,BookType:lZ,BookUp:dZ,BookUp2:cZ,BookUser:uZ,BookX:hZ,Bookmark:Pv,BookmarkCheck:pZ,BookmarkMinus:fZ,BookmarkPlus:L7,BookmarkX:xZ,BoomBox:gZ,Bot:US,BotMessageSquare:yZ,BotOff:vZ,Box:D7,Boxes:bZ,Braces:A3,Brackets:_Z,Brain:R7,BrainCircuit:wZ,BrainCog:jZ,BrickWall:NZ,Briefcase:zm,BriefcaseBusiness:kZ,BriefcaseConveyorBelt:SZ,BriefcaseMedical:CZ,BringToFront:TZ,Brush:EZ,Bug:IZ,BugOff:AZ,BugPlay:MZ,Building:gA,Building2:Ua,Bus:LZ,BusFront:PZ,Cable:RZ,CableCar:DZ,Cake:Ah,CakeSlice:OZ,Calculator:dw,Calendar:yr,Calendar1:FZ,CalendarArrowDown:zZ,CalendarArrowUp:BZ,CalendarCheck:O7,CalendarCheck2:$Z,CalendarClock:Xf,CalendarCog:UZ,CalendarDays:Cl,CalendarFold:qZ,CalendarHeart:uw,CalendarMinus:HZ,CalendarMinus2:VZ,CalendarOff:F7,CalendarPlus:Lg,CalendarPlus2:GZ,CalendarRange:WZ,CalendarSearch:KZ,CalendarSync:YZ,CalendarX:z7,CalendarX2:ZZ,Camera:Jf,CameraOff:QZ,Candy:eQ,CandyCane:XZ,CandyOff:JZ,Cannabis:tQ,Captions:M3,CaptionsOff:sQ,Car:aQ,CarFront:nQ,CarTaxiFront:rQ,Caravan:iQ,Carrot:oQ,CaseLower:lQ,CaseSensitive:cQ,CaseUpper:dQ,CassetteTape:uQ,Cast:hQ,Castle:mQ,Cat:pQ,Cctv:fQ,ChartArea:I3,ChartBar:L3,ChartBarBig:P3,ChartBarDecreasing:xQ,ChartBarIncreasing:gQ,ChartBarStacked:yQ,ChartCandlestick:D3,ChartColumn:_o,ChartColumnBig:R3,ChartColumnDecreasing:vQ,ChartColumnIncreasing:O3,ChartColumnStacked:bQ,ChartGantt:_Q,ChartLine:F3,ChartNetwork:wQ,ChartNoAxesColumn:B3,ChartNoAxesColumnDecreasing:jQ,ChartNoAxesColumnIncreasing:z3,ChartNoAxesCombined:NQ,ChartNoAxesGantt:$3,ChartPie:U3,ChartScatter:q3,ChartSpline:kQ,Check:Lr,CheckCheck:B7,ChefHat:SQ,Cherry:CQ,ChevronDown:ao,ChevronFirst:TQ,ChevronLast:EQ,ChevronLeft:ml,ChevronRight:ga,ChevronUp:ex,ChevronsDown:MQ,ChevronsDownUp:AQ,ChevronsLeft:LQ,ChevronsLeftRight:PQ,ChevronsLeftRightEllipsis:IQ,ChevronsRight:RQ,ChevronsRightLeft:DQ,ChevronsUp:OQ,ChevronsUpDown:$g,Chrome:yA,Church:FQ,Cigarette:BQ,CigaretteOff:zQ,Circle:am,CircleAlert:Bi,CircleArrowDown:V3,CircleArrowLeft:H3,CircleArrowOutDownLeft:G3,CircleArrowOutDownRight:W3,CircleArrowOutUpLeft:K3,CircleArrowOutUpRight:Y3,CircleArrowRight:Z3,CircleArrowUp:Q3,CircleCheck:vr,CircleCheckBig:Pi,CircleChevronDown:X3,CircleChevronLeft:J3,CircleChevronRight:e5,CircleChevronUp:t5,CircleDashed:$Q,CircleDivide:s5,CircleDollarSign:UQ,CircleDot:VQ,CircleDotDashed:qQ,CircleEllipsis:HQ,CircleEqual:GQ,CircleFadingArrowUp:WQ,CircleFadingPlus:KQ,CircleGauge:n5,CircleHelp:q_,CircleMinus:r5,CircleOff:YQ,CircleParking:i5,CircleParkingOff:a5,CirclePause:o5,CirclePercent:l5,CirclePlay:jh,CirclePlus:c5,CirclePower:d5,CircleSlash:ZQ,CircleSlash2:u5,CircleStop:h5,CircleUser:p5,CircleUserRound:m5,CircleX:Uc,CircuitBoard:QQ,Citrus:XQ,Clapperboard:JQ,Clipboard:iX,ClipboardCheck:KP,ClipboardCopy:eX,ClipboardList:cb,ClipboardMinus:tX,ClipboardPaste:sX,ClipboardPen:x5,ClipboardPenLine:f5,ClipboardPlus:nX,ClipboardType:rX,ClipboardX:aX,Clock:pr,Clock1:oX,Clock10:lX,Clock11:cX,Clock12:dX,Clock2:uX,Clock3:$7,Clock4:hX,Clock5:mX,Clock6:pX,Clock7:fX,Clock8:xX,Clock9:gX,ClockAlert:yX,ClockArrowDown:vX,ClockArrowUp:bX,Cloud:DX,CloudAlert:_X,CloudCog:wX,CloudDownload:g5,CloudDrizzle:jX,CloudFog:NX,CloudHail:kX,CloudLightning:SX,CloudMoon:TX,CloudMoonRain:CX,CloudOff:EX,CloudRain:MX,CloudRainWind:AX,CloudSnow:IX,CloudSun:LX,CloudSunRain:PX,CloudUpload:y5,Cloudy:RX,Clover:P2,Club:OX,Code:vA,CodeXml:N2,Codepen:FX,Codesandbox:zX,Coffee:ey,Cog:BX,Coins:U7,Columns2:v5,Columns3:b5,Columns4:$X,Combine:UX,Command:qX,Compass:YP,Component:VX,Computer:HX,ConciergeBell:GX,Cone:WX,Construction:KX,Contact:bA,ContactRound:_5,Container:YX,Contrast:ZX,Cookie:QX,CookingPot:XX,Copy:Zr,CopyCheck:JX,CopyMinus:eJ,CopyPlus:tJ,CopySlash:sJ,CopyX:nJ,Copyleft:rJ,Copyright:aJ,CornerDownLeft:iJ,CornerDownRight:oJ,CornerLeftDown:lJ,CornerLeftUp:cJ,CornerRightDown:dJ,CornerRightUp:uJ,CornerUpLeft:hJ,CornerUpRight:mJ,Cpu:pJ,CreativeCommons:fJ,CreditCard:uf,Croissant:xJ,Crop:gJ,Cross:yJ,Crosshair:vJ,Crown:hf,Cuboid:bJ,CupSoda:_J,Currency:wJ,Cylinder:jJ,Dam:NJ,Database:q7,DatabaseBackup:kJ,DatabaseZap:SJ,Delete:CJ,Dessert:TJ,Diameter:EJ,Diamond:IJ,DiamondMinus:AJ,DiamondPercent:w5,DiamondPlus:MJ,Dice1:PJ,Dice2:LJ,Dice3:DJ,Dice4:RJ,Dice5:OJ,Dice6:FJ,Dices:zJ,Diff:BJ,Disc:VJ,Disc2:$J,Disc3:UJ,DiscAlbum:qJ,Divide:HJ,Dna:WJ,DnaOff:GJ,Dock:KJ,Dog:YJ,DollarSign:Yl,Donut:ZJ,DoorClosed:QJ,DoorOpen:hw,Dot:XJ,Download:Ia,DraftingCompass:JJ,Drama:eee,Dribbble:tee,Drill:see,Droplet:nee,Droplets:db,Drum:ree,Drumstick:aee,Dumbbell:iee,Ear:lee,EarOff:oee,Earth:j5,EarthLock:cee,Eclipse:dee,Egg:ZP,EggFried:uee,EggOff:hee,Ellipsis:Kf,EllipsisVertical:Ag,Equal:fee,EqualApproximately:mee,EqualNot:pee,Eraser:xee,EthernetPort:gee,Euro:yee,Expand:vee,ExternalLink:tr,Eye:Sr,EyeClosed:bee,EyeOff:mf,Facebook:Mh,Factory:_ee,Fan:wee,FastForward:jee,Feather:Nee,Fence:kee,FerrisWheel:See,Figma:Cee,File:QP,FileArchive:Tee,FileAudio:Aee,FileAudio2:Eee,FileAxis3d:N5,FileBadge:Iee,FileBadge2:Mee,FileBox:Pee,FileChartColumn:S5,FileChartColumnIncreasing:k5,FileChartLine:C5,FileChartPie:T5,FileCheck:V7,FileCheck2:Lee,FileClock:Dee,FileCode:Oee,FileCode2:Ree,FileCog:E5,FileDiff:Fee,FileDigit:zee,FileDown:_A,FileHeart:Bee,FileImage:q2,FileInput:$ee,FileJson:qee,FileJson2:Uee,FileKey:Hee,FileKey2:Vee,FileLock:Wee,FileLock2:Gee,FileMinus:Yee,FileMinus2:Kee,FileMusic:Zee,FileOutput:Qee,FilePen:M5,FilePenLine:A5,FilePlus:Jee,FilePlus2:Xee,FileQuestion:ete,FileScan:tte,FileSearch:nte,FileSearch2:ste,FileSliders:rte,FileSpreadsheet:mw,FileStack:H7,FileSymlink:ate,FileTerminal:ite,FileText:br,FileType:lte,FileType2:ote,FileUp:cte,FileUser:dte,FileVideo:G7,FileVideo2:ute,FileVolume:mte,FileVolume2:hte,FileWarning:pte,FileX:xte,FileX2:fte,Files:gte,Film:Sh,Filter:Lv,FilterX:yte,Fingerprint:vte,FireExtinguisher:bte,Fish:jte,FishOff:_te,FishSymbol:wte,Flag:V2,FlagOff:Nte,FlagTriangleLeft:kte,FlagTriangleRight:Ste,Flame:Hc,FlameKindling:Cte,Flashlight:Ete,FlashlightOff:Tte,FlaskConical:qS,FlaskConicalOff:Ate,FlaskRound:Mte,FlipHorizontal:W7,FlipHorizontal2:Ite,FlipVertical:Lte,FlipVertical2:Pte,Flower:Dte,Flower2:rb,Focus:Rte,FoldHorizontal:Ote,FoldVertical:Fte,Folder:use,FolderArchive:zte,FolderCheck:Bte,FolderClock:$te,FolderClosed:Ute,FolderCode:qte,FolderCog:I5,FolderDot:Vte,FolderDown:Hte,FolderGit:Wte,FolderGit2:Gte,FolderHeart:Kte,FolderInput:Yte,FolderKanban:Zte,FolderKey:Qte,FolderLock:Xte,FolderMinus:Jte,FolderOpen:pf,FolderOpenDot:ese,FolderOutput:tse,FolderPen:P5,FolderPlus:sse,FolderRoot:nse,FolderSearch:ase,FolderSearch2:rse,FolderSymlink:ise,FolderSync:ose,FolderTree:lse,FolderUp:cse,FolderX:dse,Folders:hse,Footprints:mse,Forklift:pse,Forward:fse,Frame:xse,Framer:gse,Frown:yse,Fuel:vse,Fullscreen:bse,GalleryHorizontal:wse,GalleryHorizontalEnd:_se,GalleryThumbnails:jse,GalleryVertical:kse,GalleryVerticalEnd:Nse,Gamepad:Cse,Gamepad2:Sse,Gauge:Tse,Gavel:Ese,Gem:Ase,Ghost:wA,Gift:Oi,GitBranch:Ise,GitBranchPlus:Mse,GitCommitHorizontal:L5,GitCommitVertical:Pse,GitCompare:Dse,GitCompareArrows:Lse,GitFork:Rse,GitGraph:Ose,GitMerge:Fse,GitPullRequest:Vse,GitPullRequestArrow:zse,GitPullRequestClosed:Bse,GitPullRequestCreate:Use,GitPullRequestCreateArrow:$se,GitPullRequestDraft:qse,Github:Hse,Gitlab:Gse,GlassWater:Wse,Glasses:Kse,Globe:lc,GlobeLock:Yse,Goal:Zse,Grab:Qse,GraduationCap:yd,Grape:Xse,Grid2x2:R5,Grid2x2Check:Jse,Grid2x2Plus:D5,Grid2x2X:ene,Grid3x3:mv,Grip:sne,GripHorizontal:tne,GripVertical:Pu,Group:nne,Guitar:rne,Ham:ane,Hammer:K7,Hand:Y7,HandCoins:ine,HandHeart:jA,HandHelping:X1,HandMetal:one,HandPlatter:lne,Handshake:pw,HardDrive:Z7,HardDriveDownload:cne,HardDriveUpload:dne,HardHat:une,Hash:VS,Haze:hne,HdmiPort:mne,Heading:gne,Heading1:XP,Heading2:JP,Heading3:Q7,Heading4:pne,Heading5:fne,Heading6:xne,HeadphoneOff:yne,Headphones:vne,Headset:bne,Heart:gi,HeartCrack:_ne,HeartHandshake:NA,HeartOff:wne,HeartPulse:jne,Heater:Nne,Hexagon:kne,Highlighter:Sne,History:kA,Hop:Tne,HopOff:Cne,Hospital:Ene,Hotel:Ane,Hourglass:Mne,House:Or,HousePlug:Ine,HousePlus:Pne,IceCreamBowl:O5,IceCreamCone:F5,IdCard:Lne,Image:Xo,ImageDown:Dne,ImageMinus:Rne,ImageOff:One,ImagePlay:Fne,ImagePlus:ty,ImageUp:zne,ImageUpscale:Bne,Images:$ne,Import:Une,Inbox:H2,IndentDecrease:z5,IndentIncrease:B5,IndianRupee:qne,Infinity:Vne,Info:fw,InspectionPanel:Hne,Instagram:ou,Italic:HS,IterationCcw:Gne,IterationCw:Wne,JapaneseYen:Kne,Joystick:Yne,Kanban:G2,Key:Ug,KeyRound:SA,KeySquare:Zne,Keyboard:Jne,KeyboardMusic:Qne,KeyboardOff:Xne,Lamp:are,LampCeiling:ere,LampDesk:tre,LampFloor:sre,LampWallDown:nre,LampWallUp:rre,LandPlot:ire,Landmark:ore,Languages:lre,Laptop:dre,LaptopMinimal:$5,LaptopMinimalCheck:cre,Lasso:hre,LassoSelect:ure,Laugh:mre,Layers:X7,Layers2:pre,Layers3:fre,LayoutDashboard:GS,LayoutGrid:ff,LayoutList:xre,LayoutPanelLeft:gre,LayoutPanelTop:yre,LayoutTemplate:WS,Leaf:vre,LeafyGreen:bre,Lectern:_re,LetterText:wre,Library:qg,LibraryBig:jre,LifeBuoy:eL,Ligature:Nre,Lightbulb:W2,LightbulbOff:kre,Link:Yo,Link2:Tl,Link2Off:Sre,Linkedin:xf,List:Sp,ListCheck:Cre,ListChecks:lu,ListCollapse:Tre,ListEnd:Ere,ListFilter:J7,ListMinus:Are,ListMusic:Mre,ListOrdered:ub,ListPlus:Ire,ListRestart:Pre,ListStart:Lre,ListTodo:Dre,ListTree:Rre,ListVideo:Ore,ListX:Fre,Loader:Bre,LoaderCircle:rs,LoaderPinwheel:zre,Locate:tL,LocateFixed:$re,LocateOff:Ure,Lock:Gc,LockKeyhole:qre,LockKeyholeOpen:U5,LockOpen:q5,LogIn:CA,LogOut:TA,Logs:Vre,Lollipop:Hre,Luggage:Gre,Magnet:Wre,Mail:Gs,MailCheck:sL,MailMinus:Kre,MailOpen:nL,MailPlus:e9,MailQuestion:Yre,MailSearch:Zre,MailWarning:Qre,MailX:rL,Mailbox:Xre,Mails:Jre,Map:EA,MapPin:ka,MapPinCheck:tae,MapPinCheckInside:eae,MapPinHouse:sae,MapPinMinus:rae,MapPinMinusInside:nae,MapPinOff:aae,MapPinPlus:oae,MapPinPlusInside:iae,MapPinX:cae,MapPinXInside:lae,MapPinned:dae,Martini:uae,Maximize:AA,Maximize2:t9,Medal:K2,Megaphone:zd,MegaphoneOff:hae,Meh:mae,MemoryStick:pae,Menu:KS,Merge:fae,MessageCircle:Zl,MessageCircleCode:xae,MessageCircleDashed:gae,MessageCircleHeart:aL,MessageCircleMore:yae,MessageCircleOff:vae,MessageCirclePlus:bae,MessageCircleQuestion:s9,MessageCircleReply:_ae,MessageCircleWarning:wae,MessageCircleX:jae,MessageSquare:Ai,MessageSquareCode:Nae,MessageSquareDashed:kae,MessageSquareDiff:Sae,MessageSquareDot:Cae,MessageSquareHeart:iL,MessageSquareLock:Tae,MessageSquareMore:n9,MessageSquareOff:Eae,MessageSquarePlus:X_,MessageSquareQuote:xw,MessageSquareReply:Aae,MessageSquareShare:Mae,MessageSquareText:Iae,MessageSquareWarning:Pae,MessageSquareX:Lae,MessagesSquare:oL,Mic:Dv,MicOff:Dae,MicVocal:V5,Microchip:Rae,Microscope:Oae,Microwave:Fae,Milestone:zae,Milk:$ae,MilkOff:Bae,Minimize:qae,Minimize2:Uae,Minus:hb,Monitor:mb,MonitorCheck:Vae,MonitorCog:Hae,MonitorDot:Gae,MonitorDown:Wae,MonitorOff:Kae,MonitorPause:Yae,MonitorPlay:lL,MonitorSmartphone:Zae,MonitorSpeaker:Qae,MonitorStop:Xae,MonitorUp:MA,MonitorX:Jae,Moon:tie,MoonStar:eie,Mountain:nie,MountainSnow:sie,Mouse:oie,MouseOff:rie,MousePointer:Lm,MousePointer2:aie,MousePointerBan:iie,MousePointerClick:oc,Move:bie,Move3d:H5,MoveDiagonal:cie,MoveDiagonal2:lie,MoveDown:hie,MoveDownLeft:die,MoveDownRight:uie,MoveHorizontal:mie,MoveLeft:pie,MoveRight:fie,MoveUp:yie,MoveUpLeft:xie,MoveUpRight:gie,MoveVertical:vie,Music:cL,Music2:_ie,Music3:wie,Music4:jie,Navigation:r9,Navigation2:kie,Navigation2Off:Nie,NavigationOff:Sie,Network:Cie,Newspaper:sy,Nfc:Tie,Notebook:Iie,NotebookPen:Eie,NotebookTabs:Aie,NotebookText:Mie,NotepadText:Lie,NotepadTextDashed:Pie,Nut:Rie,NutOff:Die,Octagon:Fie,OctagonAlert:V_,OctagonMinus:Oie,OctagonPause:G5,OctagonX:W5,Omega:zie,Option:Bie,Orbit:$ie,Origami:Uie,Package:Ec,Package2:qie,PackageCheck:Vie,PackageMinus:Hie,PackageOpen:Gie,PackagePlus:a9,PackageSearch:Wie,PackageX:Kie,PaintBucket:Yie,PaintRoller:Zie,Paintbrush:Qie,PaintbrushVertical:K5,Palette:pl,PanelBottom:eoe,PanelBottomClose:Xie,PanelBottomDashed:Y5,PanelBottomOpen:Jie,PanelLeft:J5,PanelLeftClose:Z5,PanelLeftDashed:Q5,PanelLeftOpen:X5,PanelRight:noe,PanelRightClose:toe,PanelRightDashed:eT,PanelRightOpen:soe,PanelTop:ioe,PanelTopClose:roe,PanelTopDashed:tT,PanelTopOpen:aoe,PanelsLeftBottom:ooe,PanelsRightBottom:loe,PanelsTopLeft:k2,Paperclip:YS,Parentheses:coe,ParkingMeter:doe,PartyPopper:ih,Pause:gf,PawPrint:uoe,PcCase:hoe,Pen:_v,PenLine:J1,PenOff:moe,PenTool:ZS,Pencil:ya,PencilLine:i9,PencilOff:poe,PencilRuler:foe,Pentagon:xoe,Percent:QS,PersonStanding:goe,PhilippinePeso:yoe,Phone:Cr,PhoneCall:voe,PhoneForwarded:boe,PhoneIncoming:_oe,PhoneMissed:woe,PhoneOff:joe,PhoneOutgoing:Noe,Pi:koe,Piano:Soe,Pickaxe:Coe,PictureInPicture:Eoe,PictureInPicture2:Toe,PiggyBank:Aoe,Pilcrow:Poe,PilcrowLeft:Moe,PilcrowRight:Ioe,Pill:Doe,PillBottle:Loe,Pin:XS,PinOff:o9,Pipette:Roe,Pizza:Ooe,Plane:l9,PlaneLanding:Foe,PlaneTakeoff:zoe,Play:El,Plug:Y2,Plug2:Boe,PlugZap:sT,Plus:Is,Pocket:Uoe,PocketKnife:$oe,Podcast:qoe,Pointer:Hoe,PointerOff:Voe,Popcorn:Goe,Popsicle:Woe,PoundSterling:Koe,Power:c9,PowerOff:Yoe,Presentation:ny,Printer:d9,PrinterCheck:Zoe,Projector:Qoe,Proportions:Xoe,Puzzle:Joe,Pyramid:ele,QrCode:ry,Quote:gw,Rabbit:tle,Radar:IA,Radiation:sle,Radical:nle,Radio:yf,RadioReceiver:rle,RadioTower:ale,Radius:ile,RailSymbol:ole,Rainbow:lle,Rat:cle,Ratio:dle,Receipt:vle,ReceiptCent:ule,ReceiptEuro:hle,ReceiptIndianRupee:mle,ReceiptJapaneseYen:ple,ReceiptPoundSterling:fle,ReceiptRussianRuble:xle,ReceiptSwissFranc:gle,ReceiptText:yle,RectangleEllipsis:nT,RectangleHorizontal:ble,RectangleVertical:_le,Recycle:wle,Redo:JS,Redo2:jle,RedoDot:Nle,RefreshCcw:dL,RefreshCcwDot:kle,RefreshCw:Ei,RefreshCwOff:Sle,Refrigerator:Cle,Regex:Tle,RemoveFormatting:Ele,Repeat:u9,Repeat1:Ale,Repeat2:Mle,Replace:Ple,ReplaceAll:Ile,Reply:h9,ReplyAll:Lle,Rewind:Dle,Ribbon:Rle,Rocket:tx,RockingChair:Ole,RollerCoaster:Fle,Rotate3d:rT,RotateCcw:Bm,RotateCcwSquare:zle,RotateCw:PA,RotateCwSquare:Ble,Route:m9,RouteOff:$le,Router:Ule,Rows2:aT,Rows3:iT,Rows4:qle,Rss:Vle,Ruler:Z2,RussianRuble:Hle,Sailboat:Gle,Salad:Wle,Sandwich:Kle,Satellite:Zle,SatelliteDish:Yle,Save:Jo,SaveAll:Qle,SaveOff:Xle,Scale:p9,Scale3d:oT,Scaling:Jle,Scan:oce,ScanBarcode:ece,ScanEye:tce,ScanFace:sce,ScanLine:nce,ScanQrCode:rce,ScanSearch:ace,ScanText:ice,School:lce,Scissors:dce,ScissorsLineDashed:cce,ScreenShare:hce,ScreenShareOff:uce,Scroll:mce,ScrollText:f9,Search:gr,SearchCheck:pce,SearchCode:fce,SearchSlash:xce,SearchX:x9,Section:gce,Send:lr,SendHorizontal:lT,SendToBack:yce,SeparatorHorizontal:vce,SeparatorVertical:bce,Server:Nce,ServerCog:_ce,ServerCrash:wce,ServerOff:jce,Settings:Ko,Settings2:g9,Shapes:kce,Share:y9,Share2:Vl,Sheet:Sce,Shell:Cce,Shield:Ih,ShieldAlert:uL,ShieldBan:Tce,ShieldCheck:eg,ShieldEllipsis:Ece,ShieldHalf:Ace,ShieldMinus:Mce,ShieldOff:LA,ShieldPlus:Ice,ShieldQuestion:Pce,ShieldX:cT,Ship:Dce,ShipWheel:Lce,Shirt:Rce,ShoppingBag:yw,ShoppingBasket:Oce,ShoppingCart:Dg,Shovel:Fce,ShowerHead:zce,Shrink:Bce,Shrub:$ce,Shuffle:DA,Sigma:Uce,Signal:Wce,SignalHigh:qce,SignalLow:Vce,SignalMedium:Hce,SignalZero:Gce,Signature:Kce,Signpost:Zce,SignpostBig:Yce,Siren:Qce,SkipBack:Xce,SkipForward:Jce,Skull:ede,Slack:tde,Slash:sde,Slice:nde,SlidersHorizontal:e4,SlidersVertical:dT,Smartphone:tg,SmartphoneCharging:rde,SmartphoneNfc:ade,Smile:ode,SmilePlus:ide,Snail:lde,Snowflake:Tv,Sofa:cde,Soup:dde,Space:ude,Spade:hde,Sparkle:t4,Sparkles:un,Speaker:mde,Speech:pde,SpellCheck:xde,SpellCheck2:fde,Spline:gde,Split:yde,SprayCan:vde,Sprout:RA,Square:ay,SquareActivity:uT,SquareArrowDown:pT,SquareArrowDownLeft:hT,SquareArrowDownRight:mT,SquareArrowLeft:fT,SquareArrowOutDownLeft:xT,SquareArrowOutDownRight:gT,SquareArrowOutUpLeft:yT,SquareArrowOutUpRight:vT,SquareArrowRight:bT,SquareArrowUp:jT,SquareArrowUpLeft:_T,SquareArrowUpRight:wT,SquareAsterisk:NT,SquareBottomDashedScissors:kT,SquareChartGantt:A_,SquareCheck:ST,SquareCheckBig:S2,SquareChevronDown:CT,SquareChevronLeft:TT,SquareChevronRight:ET,SquareChevronUp:AT,SquareCode:MT,SquareDashed:LT,SquareDashedBottom:_de,SquareDashedBottomCode:bde,SquareDashedKanban:IT,SquareDashedMousePointer:PT,SquareDivide:DT,SquareDot:RT,SquareEqual:OT,SquareFunction:FT,SquareKanban:zT,SquareLibrary:BT,SquareM:$T,SquareMenu:UT,SquareMinus:qT,SquareMousePointer:VT,SquareParking:GT,SquareParkingOff:HT,SquarePen:wu,SquarePercent:WT,SquarePi:KT,SquarePilcrow:YT,SquarePlay:ZT,SquarePlus:QT,SquarePower:XT,SquareRadical:wde,SquareScissors:JT,SquareSigma:eE,SquareSlash:tE,SquareSplitHorizontal:sE,SquareSplitVertical:nE,SquareSquare:jde,SquareStack:Nde,SquareTerminal:rE,SquareUser:iE,SquareUserRound:aE,SquareX:oE,Squircle:kde,Squirrel:Sde,Stamp:Cde,Star:oa,StarHalf:Tde,StarOff:Ede,StepBack:Ade,StepForward:Mde,Stethoscope:Ide,Sticker:Pde,StickyNote:v9,Store:b9,StretchHorizontal:Lde,StretchVertical:Dde,Strikethrough:_9,Subscript:Rde,Sun:pb,SunDim:Ode,SunMedium:Fde,SunMoon:zde,SunSnow:Bde,Sunrise:$de,Sunset:Ude,Superscript:qde,SwatchBook:Vde,SwissFranc:Hde,SwitchCamera:Gde,Sword:Wde,Swords:Kde,Syringe:Yde,Table:mL,Table2:hL,TableCellsMerge:Zde,TableCellsSplit:Qde,TableColumnsSplit:Xde,TableOfContents:Jde,TableProperties:eue,TableRowsSplit:tue,Tablet:pL,TabletSmartphone:sue,Tablets:nue,Tag:oh,Tags:w9,Tally1:rue,Tally2:aue,Tally3:iue,Tally4:oue,Tally5:lue,Tangent:cue,Target:Ac,Telescope:due,Tent:hue,TentTree:uue,Terminal:mue,TestTube:pue,TestTubeDiagonal:lE,TestTubes:fue,Text:bue,TextCursor:gue,TextCursorInput:xue,TextQuote:yue,TextSearch:vue,TextSelect:cE,Theater:_ue,Thermometer:j9,ThermometerSnowflake:wue,ThermometerSun:jue,ThumbsDown:N9,ThumbsUp:$m,Ticket:k9,TicketCheck:Nue,TicketMinus:kue,TicketPercent:Sue,TicketPlus:Cue,TicketSlash:Tue,TicketX:Eue,Tickets:Mue,TicketsPlane:Aue,Timer:Lue,TimerOff:Iue,TimerReset:Pue,ToggleLeft:Due,ToggleRight:Rue,Toilet:Oue,Tornado:Fue,Torus:zue,Touchpad:$ue,TouchpadOff:Bue,TowerControl:Uue,ToyBrick:que,Tractor:Vue,TrafficCone:Hue,TrainFront:Wue,TrainFrontTunnel:Gue,TrainTrack:Kue,TramFront:dE,Trash:Yue,Trash2:_n,TreeDeciduous:Zue,TreePalm:uE,TreePine:s4,Trees:Que,Trello:Xue,TrendingDown:fb,TrendingUp:go,TrendingUpDown:Jue,Triangle:the,TriangleAlert:ic,TriangleRight:ehe,Trophy:xo,Truck:S9,Turtle:she,Tv:rhe,TvMinimal:hE,TvMinimalPlay:nhe,Twitch:ahe,Twitter:ihe,Type:lhe,TypeOutline:ohe,Umbrella:dhe,UmbrellaOff:che,Underline:fL,Undo:n4,Undo2:uhe,UndoDot:hhe,UnfoldHorizontal:mhe,UnfoldVertical:phe,Ungroup:fhe,University:mE,Unlink:OA,Unlink2:xhe,Unplug:ghe,Upload:_a,Usb:yhe,User:Wi,UserCheck:xb,UserCog:C9,UserMinus:T9,UserPen:vhe,UserPlus:Fo,UserRound:vE,UserRoundCheck:pE,UserRoundCog:fE,UserRoundMinus:xE,UserRoundPen:bhe,UserRoundPlus:gE,UserRoundSearch:_he,UserRoundX:yE,UserSearch:whe,UserX:jhe,Users:An,UsersRound:q0,Utensils:_E,UtensilsCrossed:bE,UtilityPole:Nhe,Variable:xL,Vault:khe,Vegan:She,VenetianMask:Che,Vibrate:Ehe,VibrateOff:The,Video:fr,VideoOff:Ahe,Videotape:Mhe,View:Ihe,Voicemail:Phe,Volleyball:Lhe,Volume:Ohe,Volume1:Dhe,Volume2:E9,VolumeOff:Rhe,VolumeX:A9,Vote:Fhe,Wallet:gL,WalletCards:zhe,WalletMinimal:wE,Wallpaper:Bhe,Wand:$he,WandSparkles:Im,Warehouse:Uhe,WashingMachine:qhe,Watch:Vhe,Waves:Hhe,Waypoints:Ghe,Webcam:Whe,Webhook:Yhe,WebhookOff:Khe,Weight:Zhe,Wheat:Xhe,WheatOff:Qhe,WholeWord:Jhe,Wifi:rme,WifiHigh:eme,WifiLow:tme,WifiOff:sme,WifiZero:nme,Wind:ime,WindArrowDown:ame,Wine:M9,WineOff:ome,Workflow:I9,Worm:lme,WrapText:cme,Wrench:gb,X:$n,Youtube:dme,Zap:im,ZapOff:ume,ZoomIn:r4,ZoomOut:yL},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 m0e=Object.freeze(Object.defineProperty({__proto__:null,AArrowDown:hW,AArrowDownIcon:hW,AArrowUp:mW,AArrowUpIcon:mW,ALargeSmall:pW,ALargeSmallIcon:pW,Accessibility:fW,AccessibilityIcon:fW,Activity:em,ActivityIcon:em,ActivitySquare:uT,ActivitySquareIcon:uT,AirVent:xW,AirVentIcon:xW,Airplay:gW,AirplayIcon:gW,AlarmCheck:x3,AlarmCheckIcon:x3,AlarmClock:vW,AlarmClockCheck:x3,AlarmClockCheckIcon:x3,AlarmClockIcon:vW,AlarmClockMinus:g3,AlarmClockMinusIcon:g3,AlarmClockOff:yW,AlarmClockOffIcon:yW,AlarmClockPlus:y3,AlarmClockPlusIcon:y3,AlarmMinus:g3,AlarmMinusIcon:g3,AlarmPlus:y3,AlarmPlusIcon:y3,AlarmSmoke:bW,AlarmSmokeIcon:bW,Album:_W,AlbumIcon:_W,AlertCircle:Bi,AlertCircleIcon:Bi,AlertOctagon:V_,AlertOctagonIcon:V_,AlertTriangle:ic,AlertTriangleIcon:ic,AlignCenter:pA,AlignCenterHorizontal:wW,AlignCenterHorizontalIcon:wW,AlignCenterIcon:pA,AlignCenterVertical:jW,AlignCenterVerticalIcon:jW,AlignEndHorizontal:NW,AlignEndHorizontalIcon:NW,AlignEndVertical:kW,AlignEndVerticalIcon:kW,AlignHorizontalDistributeCenter:SW,AlignHorizontalDistributeCenterIcon:SW,AlignHorizontalDistributeEnd:CW,AlignHorizontalDistributeEndIcon:CW,AlignHorizontalDistributeStart:TW,AlignHorizontalDistributeStartIcon:TW,AlignHorizontalJustifyCenter:EW,AlignHorizontalJustifyCenterIcon:EW,AlignHorizontalJustifyEnd:AW,AlignHorizontalJustifyEndIcon:AW,AlignHorizontalJustifyStart:MW,AlignHorizontalJustifyStartIcon:MW,AlignHorizontalSpaceAround:IW,AlignHorizontalSpaceAroundIcon:IW,AlignHorizontalSpaceBetween:PW,AlignHorizontalSpaceBetweenIcon:PW,AlignJustify:LW,AlignJustifyIcon:LW,AlignLeft:fA,AlignLeftIcon:fA,AlignRight:xA,AlignRightIcon:xA,AlignStartHorizontal:DW,AlignStartHorizontalIcon:DW,AlignStartVertical:RW,AlignStartVerticalIcon:RW,AlignVerticalDistributeCenter:OW,AlignVerticalDistributeCenterIcon:OW,AlignVerticalDistributeEnd:FW,AlignVerticalDistributeEndIcon:FW,AlignVerticalDistributeStart:zW,AlignVerticalDistributeStartIcon:zW,AlignVerticalJustifyCenter:BW,AlignVerticalJustifyCenterIcon:BW,AlignVerticalJustifyEnd:$W,AlignVerticalJustifyEndIcon:$W,AlignVerticalJustifyStart:UW,AlignVerticalJustifyStartIcon:UW,AlignVerticalSpaceAround:qW,AlignVerticalSpaceAroundIcon:qW,AlignVerticalSpaceBetween:VW,AlignVerticalSpaceBetweenIcon:VW,Ambulance:HW,AmbulanceIcon:HW,Ampersand:GW,AmpersandIcon:GW,Ampersands:WW,AmpersandsIcon:WW,Amphora:KW,AmphoraIcon:KW,Anchor:YW,AnchorIcon:YW,Angry:ZW,AngryIcon:ZW,Annoyed:QW,AnnoyedIcon:QW,Antenna:XW,AntennaIcon:XW,Anvil:JW,AnvilIcon:JW,Aperture:eK,ApertureIcon:eK,AppWindow:sK,AppWindowIcon:sK,AppWindowMac:tK,AppWindowMacIcon:tK,Apple:nK,AppleIcon:nK,Archive:tm,ArchiveIcon:tm,ArchiveRestore:HP,ArchiveRestoreIcon:HP,ArchiveX:rK,ArchiveXIcon:rK,AreaChart:I3,AreaChartIcon:I3,Armchair:aK,ArmchairIcon:aK,ArrowBigDown:oK,ArrowBigDownDash:iK,ArrowBigDownDashIcon:iK,ArrowBigDownIcon:oK,ArrowBigLeft:cK,ArrowBigLeftDash:lK,ArrowBigLeftDashIcon:lK,ArrowBigLeftIcon:cK,ArrowBigRight:uK,ArrowBigRightDash:dK,ArrowBigRightDashIcon:dK,ArrowBigRightIcon:uK,ArrowBigUp:mK,ArrowBigUpDash:hK,ArrowBigUpDashIcon:hK,ArrowBigUpIcon:mK,ArrowDown:sm,ArrowDown01:pK,ArrowDown01Icon:pK,ArrowDown10:fK,ArrowDown10Icon:fK,ArrowDownAZ:v3,ArrowDownAZIcon:v3,ArrowDownAz:v3,ArrowDownAzIcon:v3,ArrowDownCircle:V3,ArrowDownCircleIcon:V3,ArrowDownFromLine:xK,ArrowDownFromLineIcon:xK,ArrowDownIcon:sm,ArrowDownLeft:gK,ArrowDownLeftFromCircle:G3,ArrowDownLeftFromCircleIcon:G3,ArrowDownLeftFromSquare:xT,ArrowDownLeftFromSquareIcon:xT,ArrowDownLeftIcon:gK,ArrowDownLeftSquare:hT,ArrowDownLeftSquareIcon:hT,ArrowDownNarrowWide:yK,ArrowDownNarrowWideIcon:yK,ArrowDownRight:I7,ArrowDownRightFromCircle:W3,ArrowDownRightFromCircleIcon:W3,ArrowDownRightFromSquare:gT,ArrowDownRightFromSquareIcon:gT,ArrowDownRightIcon:I7,ArrowDownRightSquare:mT,ArrowDownRightSquareIcon:mT,ArrowDownSquare:pT,ArrowDownSquareIcon:pT,ArrowDownToDot:vK,ArrowDownToDotIcon:vK,ArrowDownToLine:bK,ArrowDownToLineIcon:bK,ArrowDownUp:_K,ArrowDownUpIcon:_K,ArrowDownWideNarrow:b3,ArrowDownWideNarrowIcon:b3,ArrowDownZA:_3,ArrowDownZAIcon:_3,ArrowDownZa:_3,ArrowDownZaIcon:_3,ArrowLeft:qr,ArrowLeftCircle:H3,ArrowLeftCircleIcon:H3,ArrowLeftFromLine:wK,ArrowLeftFromLineIcon:wK,ArrowLeftIcon:qr,ArrowLeftRight:jK,ArrowLeftRightIcon:jK,ArrowLeftSquare:fT,ArrowLeftSquareIcon:fT,ArrowLeftToLine:NK,ArrowLeftToLineIcon:NK,ArrowRight:Oa,ArrowRightCircle:Z3,ArrowRightCircleIcon:Z3,ArrowRightFromLine:kK,ArrowRightFromLineIcon:kK,ArrowRightIcon:Oa,ArrowRightLeft:lw,ArrowRightLeftIcon:lw,ArrowRightSquare:bT,ArrowRightSquareIcon:bT,ArrowRightToLine:SK,ArrowRightToLineIcon:SK,ArrowUp:Iu,ArrowUp01:CK,ArrowUp01Icon:CK,ArrowUp10:TK,ArrowUp10Icon:TK,ArrowUpAZ:w3,ArrowUpAZIcon:w3,ArrowUpAz:w3,ArrowUpAzIcon:w3,ArrowUpCircle:Q3,ArrowUpCircleIcon:Q3,ArrowUpDown:ah,ArrowUpDownIcon:ah,ArrowUpFromDot:EK,ArrowUpFromDotIcon:EK,ArrowUpFromLine:AK,ArrowUpFromLineIcon:AK,ArrowUpIcon:Iu,ArrowUpLeft:MK,ArrowUpLeftFromCircle:K3,ArrowUpLeftFromCircleIcon:K3,ArrowUpLeftFromSquare:yT,ArrowUpLeftFromSquareIcon:yT,ArrowUpLeftIcon:MK,ArrowUpLeftSquare:_T,ArrowUpLeftSquareIcon:_T,ArrowUpNarrowWide:j3,ArrowUpNarrowWideIcon:j3,ArrowUpRight:GP,ArrowUpRightFromCircle:Y3,ArrowUpRightFromCircleIcon:Y3,ArrowUpRightFromSquare:vT,ArrowUpRightFromSquareIcon:vT,ArrowUpRightIcon:GP,ArrowUpRightSquare:wT,ArrowUpRightSquareIcon:wT,ArrowUpSquare:jT,ArrowUpSquareIcon:jT,ArrowUpToLine:IK,ArrowUpToLineIcon:IK,ArrowUpWideNarrow:PK,ArrowUpWideNarrowIcon:PK,ArrowUpZA:N3,ArrowUpZAIcon:N3,ArrowUpZa:N3,ArrowUpZaIcon:N3,ArrowsUpFromLine:LK,ArrowsUpFromLineIcon:LK,Asterisk:DK,AsteriskIcon:DK,AsteriskSquare:NT,AsteriskSquareIcon:NT,AtSign:RK,AtSignIcon:RK,Atom:OK,AtomIcon:OK,AudioLines:FK,AudioLinesIcon:FK,AudioWaveform:zK,AudioWaveformIcon:zK,Award:fc,AwardIcon:fc,Axe:BK,AxeIcon:BK,Axis3D:k3,Axis3DIcon:k3,Axis3d:k3,Axis3dIcon:k3,Baby:$K,BabyIcon:$K,Backpack:UK,BackpackIcon:UK,Badge:rY,BadgeAlert:qK,BadgeAlertIcon:qK,BadgeCent:VK,BadgeCentIcon:VK,BadgeCheck:S3,BadgeCheckIcon:S3,BadgeDollarSign:HK,BadgeDollarSignIcon:HK,BadgeEuro:GK,BadgeEuroIcon:GK,BadgeHelp:WK,BadgeHelpIcon:WK,BadgeIcon:rY,BadgeIndianRupee:KK,BadgeIndianRupeeIcon:KK,BadgeInfo:YK,BadgeInfoIcon:YK,BadgeJapaneseYen:ZK,BadgeJapaneseYenIcon:ZK,BadgeMinus:QK,BadgeMinusIcon:QK,BadgePercent:XK,BadgePercentIcon:XK,BadgePlus:JK,BadgePlusIcon:JK,BadgePoundSterling:eY,BadgePoundSterlingIcon:eY,BadgeRussianRuble:tY,BadgeRussianRubleIcon:tY,BadgeSwissFranc:sY,BadgeSwissFrancIcon:sY,BadgeX:nY,BadgeXIcon:nY,BaggageClaim:aY,BaggageClaimIcon:aY,Ban:WP,BanIcon:WP,Banana:iY,BananaIcon:iY,Bandage:oY,BandageIcon:oY,Banknote:lY,BanknoteIcon:lY,BarChart:z3,BarChart2:B3,BarChart2Icon:B3,BarChart3:_o,BarChart3Icon:_o,BarChart4:O3,BarChart4Icon:O3,BarChartBig:R3,BarChartBigIcon:R3,BarChartHorizontal:L3,BarChartHorizontalBig:P3,BarChartHorizontalBigIcon:P3,BarChartHorizontalIcon:L3,BarChartIcon:z3,Barcode:cY,BarcodeIcon:cY,Baseline:dY,BaselineIcon:dY,Bath:kp,BathIcon:kp,Battery:xY,BatteryCharging:uY,BatteryChargingIcon:uY,BatteryFull:hY,BatteryFullIcon:hY,BatteryIcon:xY,BatteryLow:mY,BatteryLowIcon:mY,BatteryMedium:pY,BatteryMediumIcon:pY,BatteryWarning:fY,BatteryWarningIcon:fY,Beaker:P7,BeakerIcon:P7,Bean:yY,BeanIcon:yY,BeanOff:gY,BeanOffIcon:gY,Bed:J0,BedDouble:U2,BedDoubleIcon:U2,BedIcon:J0,BedSingle:vY,BedSingleIcon:vY,Beef:bY,BeefIcon:bY,Beer:wY,BeerIcon:wY,BeerOff:_Y,BeerOffIcon:_Y,Bell:nm,BellDot:jY,BellDotIcon:jY,BellElectric:NY,BellElectricIcon:NY,BellIcon:nm,BellMinus:kY,BellMinusIcon:kY,BellOff:cw,BellOffIcon:cw,BellPlus:SY,BellPlusIcon:SY,BellRing:BS,BellRingIcon:BS,BetweenHorizonalEnd:C3,BetweenHorizonalEndIcon:C3,BetweenHorizonalStart:T3,BetweenHorizonalStartIcon:T3,BetweenHorizontalEnd:C3,BetweenHorizontalEndIcon:C3,BetweenHorizontalStart:T3,BetweenHorizontalStartIcon:T3,BetweenVerticalEnd:CY,BetweenVerticalEndIcon:CY,BetweenVerticalStart:TY,BetweenVerticalStartIcon:TY,BicepsFlexed:EY,BicepsFlexedIcon:EY,Bike:AY,BikeIcon:AY,Binary:MY,BinaryIcon:MY,Binoculars:IY,BinocularsIcon:IY,Biohazard:PY,BiohazardIcon:PY,Bird:LY,BirdIcon:LY,Bitcoin:DY,BitcoinIcon:DY,Blend:RY,BlendIcon:RY,Blinds:OY,BlindsIcon:OY,Blocks:FY,BlocksIcon:FY,Bluetooth:UY,BluetoothConnected:zY,BluetoothConnectedIcon:zY,BluetoothIcon:UY,BluetoothOff:BY,BluetoothOffIcon:BY,BluetoothSearching:$Y,BluetoothSearchingIcon:$Y,Bold:$S,BoldIcon:$S,Bolt:qY,BoltIcon:qY,Bomb:VY,BombIcon:VY,Bone:HY,BoneIcon:HY,Book:mZ,BookA:GY,BookAIcon:GY,BookAudio:WY,BookAudioIcon:WY,BookCheck:KY,BookCheckIcon:KY,BookCopy:YY,BookCopyIcon:YY,BookDashed:E3,BookDashedIcon:E3,BookDown:ZY,BookDownIcon:ZY,BookHeadphones:QY,BookHeadphonesIcon:QY,BookHeart:XY,BookHeartIcon:XY,BookIcon:mZ,BookImage:JY,BookImageIcon:JY,BookKey:eZ,BookKeyIcon:eZ,BookLock:tZ,BookLockIcon:tZ,BookMarked:sZ,BookMarkedIcon:sZ,BookMinus:nZ,BookMinusIcon:nZ,BookOpen:rm,BookOpenCheck:rZ,BookOpenCheckIcon:rZ,BookOpenIcon:rm,BookOpenText:aZ,BookOpenTextIcon:aZ,BookPlus:iZ,BookPlusIcon:iZ,BookTemplate:E3,BookTemplateIcon:E3,BookText:oZ,BookTextIcon:oZ,BookType:lZ,BookTypeIcon:lZ,BookUp:dZ,BookUp2:cZ,BookUp2Icon:cZ,BookUpIcon:dZ,BookUser:uZ,BookUserIcon:uZ,BookX:hZ,BookXIcon:hZ,Bookmark:Pv,BookmarkCheck:pZ,BookmarkCheckIcon:pZ,BookmarkIcon:Pv,BookmarkMinus:fZ,BookmarkMinusIcon:fZ,BookmarkPlus:L7,BookmarkPlusIcon:L7,BookmarkX:xZ,BookmarkXIcon:xZ,BoomBox:gZ,BoomBoxIcon:gZ,Bot:US,BotIcon:US,BotMessageSquare:yZ,BotMessageSquareIcon:yZ,BotOff:vZ,BotOffIcon:vZ,Box:D7,BoxIcon:D7,BoxSelect:LT,BoxSelectIcon:LT,Boxes:bZ,BoxesIcon:bZ,Braces:A3,BracesIcon:A3,Brackets:_Z,BracketsIcon:_Z,Brain:R7,BrainCircuit:wZ,BrainCircuitIcon:wZ,BrainCog:jZ,BrainCogIcon:jZ,BrainIcon:R7,BrickWall:NZ,BrickWallIcon:NZ,Briefcase:zm,BriefcaseBusiness:kZ,BriefcaseBusinessIcon:kZ,BriefcaseConveyorBelt:SZ,BriefcaseConveyorBeltIcon:SZ,BriefcaseIcon:zm,BriefcaseMedical:CZ,BriefcaseMedicalIcon:CZ,BringToFront:TZ,BringToFrontIcon:TZ,Brush:EZ,BrushIcon:EZ,Bug:IZ,BugIcon:IZ,BugOff:AZ,BugOffIcon:AZ,BugPlay:MZ,BugPlayIcon:MZ,Building:gA,Building2:Ua,Building2Icon:Ua,BuildingIcon:gA,Bus:LZ,BusFront:PZ,BusFrontIcon:PZ,BusIcon:LZ,Cable:RZ,CableCar:DZ,CableCarIcon:DZ,CableIcon:RZ,Cake:Ah,CakeIcon:Ah,CakeSlice:OZ,CakeSliceIcon:OZ,Calculator:dw,CalculatorIcon:dw,Calendar:yr,Calendar1:FZ,Calendar1Icon:FZ,CalendarArrowDown:zZ,CalendarArrowDownIcon:zZ,CalendarArrowUp:BZ,CalendarArrowUpIcon:BZ,CalendarCheck:O7,CalendarCheck2:$Z,CalendarCheck2Icon:$Z,CalendarCheckIcon:O7,CalendarClock:Xf,CalendarClockIcon:Xf,CalendarCog:UZ,CalendarCogIcon:UZ,CalendarDays:Cl,CalendarDaysIcon:Cl,CalendarFold:qZ,CalendarFoldIcon:qZ,CalendarHeart:uw,CalendarHeartIcon:uw,CalendarIcon:yr,CalendarMinus:HZ,CalendarMinus2:VZ,CalendarMinus2Icon:VZ,CalendarMinusIcon:HZ,CalendarOff:F7,CalendarOffIcon:F7,CalendarPlus:Lg,CalendarPlus2:GZ,CalendarPlus2Icon:GZ,CalendarPlusIcon:Lg,CalendarRange:WZ,CalendarRangeIcon:WZ,CalendarSearch:KZ,CalendarSearchIcon:KZ,CalendarSync:YZ,CalendarSyncIcon:YZ,CalendarX:z7,CalendarX2:ZZ,CalendarX2Icon:ZZ,CalendarXIcon:z7,Camera:Jf,CameraIcon:Jf,CameraOff:QZ,CameraOffIcon:QZ,CandlestickChart:D3,CandlestickChartIcon:D3,Candy:eQ,CandyCane:XZ,CandyCaneIcon:XZ,CandyIcon:eQ,CandyOff:JZ,CandyOffIcon:JZ,Cannabis:tQ,CannabisIcon:tQ,Captions:M3,CaptionsIcon:M3,CaptionsOff:sQ,CaptionsOffIcon:sQ,Car:aQ,CarFront:nQ,CarFrontIcon:nQ,CarIcon:aQ,CarTaxiFront:rQ,CarTaxiFrontIcon:rQ,Caravan:iQ,CaravanIcon:iQ,Carrot:oQ,CarrotIcon:oQ,CaseLower:lQ,CaseLowerIcon:lQ,CaseSensitive:cQ,CaseSensitiveIcon:cQ,CaseUpper:dQ,CaseUpperIcon:dQ,CassetteTape:uQ,CassetteTapeIcon:uQ,Cast:hQ,CastIcon:hQ,Castle:mQ,CastleIcon:mQ,Cat:pQ,CatIcon:pQ,Cctv:fQ,CctvIcon:fQ,ChartArea:I3,ChartAreaIcon:I3,ChartBar:L3,ChartBarBig:P3,ChartBarBigIcon:P3,ChartBarDecreasing:xQ,ChartBarDecreasingIcon:xQ,ChartBarIcon:L3,ChartBarIncreasing:gQ,ChartBarIncreasingIcon:gQ,ChartBarStacked:yQ,ChartBarStackedIcon:yQ,ChartCandlestick:D3,ChartCandlestickIcon:D3,ChartColumn:_o,ChartColumnBig:R3,ChartColumnBigIcon:R3,ChartColumnDecreasing:vQ,ChartColumnDecreasingIcon:vQ,ChartColumnIcon:_o,ChartColumnIncreasing:O3,ChartColumnIncreasingIcon:O3,ChartColumnStacked:bQ,ChartColumnStackedIcon:bQ,ChartGantt:_Q,ChartGanttIcon:_Q,ChartLine:F3,ChartLineIcon:F3,ChartNetwork:wQ,ChartNetworkIcon:wQ,ChartNoAxesColumn:B3,ChartNoAxesColumnDecreasing:jQ,ChartNoAxesColumnDecreasingIcon:jQ,ChartNoAxesColumnIcon:B3,ChartNoAxesColumnIncreasing:z3,ChartNoAxesColumnIncreasingIcon:z3,ChartNoAxesCombined:NQ,ChartNoAxesCombinedIcon:NQ,ChartNoAxesGantt:$3,ChartNoAxesGanttIcon:$3,ChartPie:U3,ChartPieIcon:U3,ChartScatter:q3,ChartScatterIcon:q3,ChartSpline:kQ,ChartSplineIcon:kQ,Check:Lr,CheckCheck:B7,CheckCheckIcon:B7,CheckCircle:Pi,CheckCircle2:vr,CheckCircle2Icon:vr,CheckCircleIcon:Pi,CheckIcon:Lr,CheckSquare:S2,CheckSquare2:ST,CheckSquare2Icon:ST,CheckSquareIcon:S2,ChefHat:SQ,ChefHatIcon:SQ,Cherry:CQ,CherryIcon:CQ,ChevronDown:ao,ChevronDownCircle:X3,ChevronDownCircleIcon:X3,ChevronDownIcon:ao,ChevronDownSquare:CT,ChevronDownSquareIcon:CT,ChevronFirst:TQ,ChevronFirstIcon:TQ,ChevronLast:EQ,ChevronLastIcon:EQ,ChevronLeft:ml,ChevronLeftCircle:J3,ChevronLeftCircleIcon:J3,ChevronLeftIcon:ml,ChevronLeftSquare:TT,ChevronLeftSquareIcon:TT,ChevronRight:ga,ChevronRightCircle:e5,ChevronRightCircleIcon:e5,ChevronRightIcon:ga,ChevronRightSquare:ET,ChevronRightSquareIcon:ET,ChevronUp:ex,ChevronUpCircle:t5,ChevronUpCircleIcon:t5,ChevronUpIcon:ex,ChevronUpSquare:AT,ChevronUpSquareIcon:AT,ChevronsDown:MQ,ChevronsDownIcon:MQ,ChevronsDownUp:AQ,ChevronsDownUpIcon:AQ,ChevronsLeft:LQ,ChevronsLeftIcon:LQ,ChevronsLeftRight:PQ,ChevronsLeftRightEllipsis:IQ,ChevronsLeftRightEllipsisIcon:IQ,ChevronsLeftRightIcon:PQ,ChevronsRight:RQ,ChevronsRightIcon:RQ,ChevronsRightLeft:DQ,ChevronsRightLeftIcon:DQ,ChevronsUp:OQ,ChevronsUpDown:$g,ChevronsUpDownIcon:$g,ChevronsUpIcon:OQ,Chrome:yA,ChromeIcon:yA,Church:FQ,ChurchIcon:FQ,Cigarette:BQ,CigaretteIcon:BQ,CigaretteOff:zQ,CigaretteOffIcon:zQ,Circle:am,CircleAlert:Bi,CircleAlertIcon:Bi,CircleArrowDown:V3,CircleArrowDownIcon:V3,CircleArrowLeft:H3,CircleArrowLeftIcon:H3,CircleArrowOutDownLeft:G3,CircleArrowOutDownLeftIcon:G3,CircleArrowOutDownRight:W3,CircleArrowOutDownRightIcon:W3,CircleArrowOutUpLeft:K3,CircleArrowOutUpLeftIcon:K3,CircleArrowOutUpRight:Y3,CircleArrowOutUpRightIcon:Y3,CircleArrowRight:Z3,CircleArrowRightIcon:Z3,CircleArrowUp:Q3,CircleArrowUpIcon:Q3,CircleCheck:vr,CircleCheckBig:Pi,CircleCheckBigIcon:Pi,CircleCheckIcon:vr,CircleChevronDown:X3,CircleChevronDownIcon:X3,CircleChevronLeft:J3,CircleChevronLeftIcon:J3,CircleChevronRight:e5,CircleChevronRightIcon:e5,CircleChevronUp:t5,CircleChevronUpIcon:t5,CircleDashed:$Q,CircleDashedIcon:$Q,CircleDivide:s5,CircleDivideIcon:s5,CircleDollarSign:UQ,CircleDollarSignIcon:UQ,CircleDot:VQ,CircleDotDashed:qQ,CircleDotDashedIcon:qQ,CircleDotIcon:VQ,CircleEllipsis:HQ,CircleEllipsisIcon:HQ,CircleEqual:GQ,CircleEqualIcon:GQ,CircleFadingArrowUp:WQ,CircleFadingArrowUpIcon:WQ,CircleFadingPlus:KQ,CircleFadingPlusIcon:KQ,CircleGauge:n5,CircleGaugeIcon:n5,CircleHelp:q_,CircleHelpIcon:q_,CircleIcon:am,CircleMinus:r5,CircleMinusIcon:r5,CircleOff:YQ,CircleOffIcon:YQ,CircleParking:i5,CircleParkingIcon:i5,CircleParkingOff:a5,CircleParkingOffIcon:a5,CirclePause:o5,CirclePauseIcon:o5,CirclePercent:l5,CirclePercentIcon:l5,CirclePlay:jh,CirclePlayIcon:jh,CirclePlus:c5,CirclePlusIcon:c5,CirclePower:d5,CirclePowerIcon:d5,CircleSlash:ZQ,CircleSlash2:u5,CircleSlash2Icon:u5,CircleSlashIcon:ZQ,CircleSlashed:u5,CircleSlashedIcon:u5,CircleStop:h5,CircleStopIcon:h5,CircleUser:p5,CircleUserIcon:p5,CircleUserRound:m5,CircleUserRoundIcon:m5,CircleX:Uc,CircleXIcon:Uc,CircuitBoard:QQ,CircuitBoardIcon:QQ,Citrus:XQ,CitrusIcon:XQ,Clapperboard:JQ,ClapperboardIcon:JQ,Clipboard:iX,ClipboardCheck:KP,ClipboardCheckIcon:KP,ClipboardCopy:eX,ClipboardCopyIcon:eX,ClipboardEdit:x5,ClipboardEditIcon:x5,ClipboardIcon:iX,ClipboardList:cb,ClipboardListIcon:cb,ClipboardMinus:tX,ClipboardMinusIcon:tX,ClipboardPaste:sX,ClipboardPasteIcon:sX,ClipboardPen:x5,ClipboardPenIcon:x5,ClipboardPenLine:f5,ClipboardPenLineIcon:f5,ClipboardPlus:nX,ClipboardPlusIcon:nX,ClipboardSignature:f5,ClipboardSignatureIcon:f5,ClipboardType:rX,ClipboardTypeIcon:rX,ClipboardX:aX,ClipboardXIcon:aX,Clock:pr,Clock1:oX,Clock10:lX,Clock10Icon:lX,Clock11:cX,Clock11Icon:cX,Clock12:dX,Clock12Icon:dX,Clock1Icon:oX,Clock2:uX,Clock2Icon:uX,Clock3:$7,Clock3Icon:$7,Clock4:hX,Clock4Icon:hX,Clock5:mX,Clock5Icon:mX,Clock6:pX,Clock6Icon:pX,Clock7:fX,Clock7Icon:fX,Clock8:xX,Clock8Icon:xX,Clock9:gX,Clock9Icon:gX,ClockAlert:yX,ClockAlertIcon:yX,ClockArrowDown:vX,ClockArrowDownIcon:vX,ClockArrowUp:bX,ClockArrowUpIcon:bX,ClockIcon:pr,Cloud:DX,CloudAlert:_X,CloudAlertIcon:_X,CloudCog:wX,CloudCogIcon:wX,CloudDownload:g5,CloudDownloadIcon:g5,CloudDrizzle:jX,CloudDrizzleIcon:jX,CloudFog:NX,CloudFogIcon:NX,CloudHail:kX,CloudHailIcon:kX,CloudIcon:DX,CloudLightning:SX,CloudLightningIcon:SX,CloudMoon:TX,CloudMoonIcon:TX,CloudMoonRain:CX,CloudMoonRainIcon:CX,CloudOff:EX,CloudOffIcon:EX,CloudRain:MX,CloudRainIcon:MX,CloudRainWind:AX,CloudRainWindIcon:AX,CloudSnow:IX,CloudSnowIcon:IX,CloudSun:LX,CloudSunIcon:LX,CloudSunRain:PX,CloudSunRainIcon:PX,CloudUpload:y5,CloudUploadIcon:y5,Cloudy:RX,CloudyIcon:RX,Clover:P2,CloverIcon:P2,Club:OX,ClubIcon:OX,Code:vA,Code2:N2,Code2Icon:N2,CodeIcon:vA,CodeSquare:MT,CodeSquareIcon:MT,CodeXml:N2,CodeXmlIcon:N2,Codepen:FX,CodepenIcon:FX,Codesandbox:zX,CodesandboxIcon:zX,Coffee:ey,CoffeeIcon:ey,Cog:BX,CogIcon:BX,Coins:U7,CoinsIcon:U7,Columns:v5,Columns2:v5,Columns2Icon:v5,Columns3:b5,Columns3Icon:b5,Columns4:$X,Columns4Icon:$X,ColumnsIcon:v5,Combine:UX,CombineIcon:UX,Command:qX,CommandIcon:qX,Compass:YP,CompassIcon:YP,Component:VX,ComponentIcon:VX,Computer:HX,ComputerIcon:HX,ConciergeBell:GX,ConciergeBellIcon:GX,Cone:WX,ConeIcon:WX,Construction:KX,ConstructionIcon:KX,Contact:bA,Contact2:_5,Contact2Icon:_5,ContactIcon:bA,ContactRound:_5,ContactRoundIcon:_5,Container:YX,ContainerIcon:YX,Contrast:ZX,ContrastIcon:ZX,Cookie:QX,CookieIcon:QX,CookingPot:XX,CookingPotIcon:XX,Copy:Zr,CopyCheck:JX,CopyCheckIcon:JX,CopyIcon:Zr,CopyMinus:eJ,CopyMinusIcon:eJ,CopyPlus:tJ,CopyPlusIcon:tJ,CopySlash:sJ,CopySlashIcon:sJ,CopyX:nJ,CopyXIcon:nJ,Copyleft:rJ,CopyleftIcon:rJ,Copyright:aJ,CopyrightIcon:aJ,CornerDownLeft:iJ,CornerDownLeftIcon:iJ,CornerDownRight:oJ,CornerDownRightIcon:oJ,CornerLeftDown:lJ,CornerLeftDownIcon:lJ,CornerLeftUp:cJ,CornerLeftUpIcon:cJ,CornerRightDown:dJ,CornerRightDownIcon:dJ,CornerRightUp:uJ,CornerRightUpIcon:uJ,CornerUpLeft:hJ,CornerUpLeftIcon:hJ,CornerUpRight:mJ,CornerUpRightIcon:mJ,Cpu:pJ,CpuIcon:pJ,CreativeCommons:fJ,CreativeCommonsIcon:fJ,CreditCard:uf,CreditCardIcon:uf,Croissant:xJ,CroissantIcon:xJ,Crop:gJ,CropIcon:gJ,Cross:yJ,CrossIcon:yJ,Crosshair:vJ,CrosshairIcon:vJ,Crown:hf,CrownIcon:hf,Cuboid:bJ,CuboidIcon:bJ,CupSoda:_J,CupSodaIcon:_J,CurlyBraces:A3,CurlyBracesIcon:A3,Currency:wJ,CurrencyIcon:wJ,Cylinder:jJ,CylinderIcon:jJ,Dam:NJ,DamIcon:NJ,Database:q7,DatabaseBackup:kJ,DatabaseBackupIcon:kJ,DatabaseIcon:q7,DatabaseZap:SJ,DatabaseZapIcon:SJ,Delete:CJ,DeleteIcon:CJ,Dessert:TJ,DessertIcon:TJ,Diameter:EJ,DiameterIcon:EJ,Diamond:IJ,DiamondIcon:IJ,DiamondMinus:AJ,DiamondMinusIcon:AJ,DiamondPercent:w5,DiamondPercentIcon:w5,DiamondPlus:MJ,DiamondPlusIcon:MJ,Dice1:PJ,Dice1Icon:PJ,Dice2:LJ,Dice2Icon:LJ,Dice3:DJ,Dice3Icon:DJ,Dice4:RJ,Dice4Icon:RJ,Dice5:OJ,Dice5Icon:OJ,Dice6:FJ,Dice6Icon:FJ,Dices:zJ,DicesIcon:zJ,Diff:BJ,DiffIcon:BJ,Disc:VJ,Disc2:$J,Disc2Icon:$J,Disc3:UJ,Disc3Icon:UJ,DiscAlbum:qJ,DiscAlbumIcon:qJ,DiscIcon:VJ,Divide:HJ,DivideCircle:s5,DivideCircleIcon:s5,DivideIcon:HJ,DivideSquare:DT,DivideSquareIcon:DT,Dna:WJ,DnaIcon:WJ,DnaOff:GJ,DnaOffIcon:GJ,Dock:KJ,DockIcon:KJ,Dog:YJ,DogIcon:YJ,DollarSign:Yl,DollarSignIcon:Yl,Donut:ZJ,DonutIcon:ZJ,DoorClosed:QJ,DoorClosedIcon:QJ,DoorOpen:hw,DoorOpenIcon:hw,Dot:XJ,DotIcon:XJ,DotSquare:RT,DotSquareIcon:RT,Download:Ia,DownloadCloud:g5,DownloadCloudIcon:g5,DownloadIcon:Ia,DraftingCompass:JJ,DraftingCompassIcon:JJ,Drama:eee,DramaIcon:eee,Dribbble:tee,DribbbleIcon:tee,Drill:see,DrillIcon:see,Droplet:nee,DropletIcon:nee,Droplets:db,DropletsIcon:db,Drum:ree,DrumIcon:ree,Drumstick:aee,DrumstickIcon:aee,Dumbbell:iee,DumbbellIcon:iee,Ear:lee,EarIcon:lee,EarOff:oee,EarOffIcon:oee,Earth:j5,EarthIcon:j5,EarthLock:cee,EarthLockIcon:cee,Eclipse:dee,EclipseIcon:dee,Edit:wu,Edit2:_v,Edit2Icon:_v,Edit3:J1,Edit3Icon:J1,EditIcon:wu,Egg:ZP,EggFried:uee,EggFriedIcon:uee,EggIcon:ZP,EggOff:hee,EggOffIcon:hee,Ellipsis:Kf,EllipsisIcon:Kf,EllipsisVertical:Ag,EllipsisVerticalIcon:Ag,Equal:fee,EqualApproximately:mee,EqualApproximatelyIcon:mee,EqualIcon:fee,EqualNot:pee,EqualNotIcon:pee,EqualSquare:OT,EqualSquareIcon:OT,Eraser:xee,EraserIcon:xee,EthernetPort:gee,EthernetPortIcon:gee,Euro:yee,EuroIcon:yee,Expand:vee,ExpandIcon:vee,ExternalLink:tr,ExternalLinkIcon:tr,Eye:Sr,EyeClosed:bee,EyeClosedIcon:bee,EyeIcon:Sr,EyeOff:mf,EyeOffIcon:mf,Facebook:Mh,FacebookIcon:Mh,Factory:_ee,FactoryIcon:_ee,Fan:wee,FanIcon:wee,FastForward:jee,FastForwardIcon:jee,Feather:Nee,FeatherIcon:Nee,Fence:kee,FenceIcon:kee,FerrisWheel:See,FerrisWheelIcon:See,Figma:Cee,FigmaIcon:Cee,File:QP,FileArchive:Tee,FileArchiveIcon:Tee,FileAudio:Aee,FileAudio2:Eee,FileAudio2Icon:Eee,FileAudioIcon:Aee,FileAxis3D:N5,FileAxis3DIcon:N5,FileAxis3d:N5,FileAxis3dIcon:N5,FileBadge:Iee,FileBadge2:Mee,FileBadge2Icon:Mee,FileBadgeIcon:Iee,FileBarChart:k5,FileBarChart2:S5,FileBarChart2Icon:S5,FileBarChartIcon:k5,FileBox:Pee,FileBoxIcon:Pee,FileChartColumn:S5,FileChartColumnIcon:S5,FileChartColumnIncreasing:k5,FileChartColumnIncreasingIcon:k5,FileChartLine:C5,FileChartLineIcon:C5,FileChartPie:T5,FileChartPieIcon:T5,FileCheck:V7,FileCheck2:Lee,FileCheck2Icon:Lee,FileCheckIcon:V7,FileClock:Dee,FileClockIcon:Dee,FileCode:Oee,FileCode2:Ree,FileCode2Icon:Ree,FileCodeIcon:Oee,FileCog:E5,FileCog2:E5,FileCog2Icon:E5,FileCogIcon:E5,FileDiff:Fee,FileDiffIcon:Fee,FileDigit:zee,FileDigitIcon:zee,FileDown:_A,FileDownIcon:_A,FileEdit:M5,FileEditIcon:M5,FileHeart:Bee,FileHeartIcon:Bee,FileIcon:QP,FileImage:q2,FileImageIcon:q2,FileInput:$ee,FileInputIcon:$ee,FileJson:qee,FileJson2:Uee,FileJson2Icon:Uee,FileJsonIcon:qee,FileKey:Hee,FileKey2:Vee,FileKey2Icon:Vee,FileKeyIcon:Hee,FileLineChart:C5,FileLineChartIcon:C5,FileLock:Wee,FileLock2:Gee,FileLock2Icon:Gee,FileLockIcon:Wee,FileMinus:Yee,FileMinus2:Kee,FileMinus2Icon:Kee,FileMinusIcon:Yee,FileMusic:Zee,FileMusicIcon:Zee,FileOutput:Qee,FileOutputIcon:Qee,FilePen:M5,FilePenIcon:M5,FilePenLine:A5,FilePenLineIcon:A5,FilePieChart:T5,FilePieChartIcon:T5,FilePlus:Jee,FilePlus2:Xee,FilePlus2Icon:Xee,FilePlusIcon:Jee,FileQuestion:ete,FileQuestionIcon:ete,FileScan:tte,FileScanIcon:tte,FileSearch:nte,FileSearch2:ste,FileSearch2Icon:ste,FileSearchIcon:nte,FileSignature:A5,FileSignatureIcon:A5,FileSliders:rte,FileSlidersIcon:rte,FileSpreadsheet:mw,FileSpreadsheetIcon:mw,FileStack:H7,FileStackIcon:H7,FileSymlink:ate,FileSymlinkIcon:ate,FileTerminal:ite,FileTerminalIcon:ite,FileText:br,FileTextIcon:br,FileType:lte,FileType2:ote,FileType2Icon:ote,FileTypeIcon:lte,FileUp:cte,FileUpIcon:cte,FileUser:dte,FileUserIcon:dte,FileVideo:G7,FileVideo2:ute,FileVideo2Icon:ute,FileVideoIcon:G7,FileVolume:mte,FileVolume2:hte,FileVolume2Icon:hte,FileVolumeIcon:mte,FileWarning:pte,FileWarningIcon:pte,FileX:xte,FileX2:fte,FileX2Icon:fte,FileXIcon:xte,Files:gte,FilesIcon:gte,Film:Sh,FilmIcon:Sh,Filter:Lv,FilterIcon:Lv,FilterX:yte,FilterXIcon:yte,Fingerprint:vte,FingerprintIcon:vte,FireExtinguisher:bte,FireExtinguisherIcon:bte,Fish:jte,FishIcon:jte,FishOff:_te,FishOffIcon:_te,FishSymbol:wte,FishSymbolIcon:wte,Flag:V2,FlagIcon:V2,FlagOff:Nte,FlagOffIcon:Nte,FlagTriangleLeft:kte,FlagTriangleLeftIcon:kte,FlagTriangleRight:Ste,FlagTriangleRightIcon:Ste,Flame:Hc,FlameIcon:Hc,FlameKindling:Cte,FlameKindlingIcon:Cte,Flashlight:Ete,FlashlightIcon:Ete,FlashlightOff:Tte,FlashlightOffIcon:Tte,FlaskConical:qS,FlaskConicalIcon:qS,FlaskConicalOff:Ate,FlaskConicalOffIcon:Ate,FlaskRound:Mte,FlaskRoundIcon:Mte,FlipHorizontal:W7,FlipHorizontal2:Ite,FlipHorizontal2Icon:Ite,FlipHorizontalIcon:W7,FlipVertical:Lte,FlipVertical2:Pte,FlipVertical2Icon:Pte,FlipVerticalIcon:Lte,Flower:Dte,Flower2:rb,Flower2Icon:rb,FlowerIcon:Dte,Focus:Rte,FocusIcon:Rte,FoldHorizontal:Ote,FoldHorizontalIcon:Ote,FoldVertical:Fte,FoldVerticalIcon:Fte,Folder:use,FolderArchive:zte,FolderArchiveIcon:zte,FolderCheck:Bte,FolderCheckIcon:Bte,FolderClock:$te,FolderClockIcon:$te,FolderClosed:Ute,FolderClosedIcon:Ute,FolderCode:qte,FolderCodeIcon:qte,FolderCog:I5,FolderCog2:I5,FolderCog2Icon:I5,FolderCogIcon:I5,FolderDot:Vte,FolderDotIcon:Vte,FolderDown:Hte,FolderDownIcon:Hte,FolderEdit:P5,FolderEditIcon:P5,FolderGit:Wte,FolderGit2:Gte,FolderGit2Icon:Gte,FolderGitIcon:Wte,FolderHeart:Kte,FolderHeartIcon:Kte,FolderIcon:use,FolderInput:Yte,FolderInputIcon:Yte,FolderKanban:Zte,FolderKanbanIcon:Zte,FolderKey:Qte,FolderKeyIcon:Qte,FolderLock:Xte,FolderLockIcon:Xte,FolderMinus:Jte,FolderMinusIcon:Jte,FolderOpen:pf,FolderOpenDot:ese,FolderOpenDotIcon:ese,FolderOpenIcon:pf,FolderOutput:tse,FolderOutputIcon:tse,FolderPen:P5,FolderPenIcon:P5,FolderPlus:sse,FolderPlusIcon:sse,FolderRoot:nse,FolderRootIcon:nse,FolderSearch:ase,FolderSearch2:rse,FolderSearch2Icon:rse,FolderSearchIcon:ase,FolderSymlink:ise,FolderSymlinkIcon:ise,FolderSync:ose,FolderSyncIcon:ose,FolderTree:lse,FolderTreeIcon:lse,FolderUp:cse,FolderUpIcon:cse,FolderX:dse,FolderXIcon:dse,Folders:hse,FoldersIcon:hse,Footprints:mse,FootprintsIcon:mse,ForkKnife:_E,ForkKnifeCrossed:bE,ForkKnifeCrossedIcon:bE,ForkKnifeIcon:_E,Forklift:pse,ForkliftIcon:pse,FormInput:nT,FormInputIcon:nT,Forward:fse,ForwardIcon:fse,Frame:xse,FrameIcon:xse,Framer:gse,FramerIcon:gse,Frown:yse,FrownIcon:yse,Fuel:vse,FuelIcon:vse,Fullscreen:bse,FullscreenIcon:bse,FunctionSquare:FT,FunctionSquareIcon:FT,GalleryHorizontal:wse,GalleryHorizontalEnd:_se,GalleryHorizontalEndIcon:_se,GalleryHorizontalIcon:wse,GalleryThumbnails:jse,GalleryThumbnailsIcon:jse,GalleryVertical:kse,GalleryVerticalEnd:Nse,GalleryVerticalEndIcon:Nse,GalleryVerticalIcon:kse,Gamepad:Cse,Gamepad2:Sse,Gamepad2Icon:Sse,GamepadIcon:Cse,GanttChart:$3,GanttChartIcon:$3,GanttChartSquare:A_,GanttChartSquareIcon:A_,Gauge:Tse,GaugeCircle:n5,GaugeCircleIcon:n5,GaugeIcon:Tse,Gavel:Ese,GavelIcon:Ese,Gem:Ase,GemIcon:Ase,Ghost:wA,GhostIcon:wA,Gift:Oi,GiftIcon:Oi,GitBranch:Ise,GitBranchIcon:Ise,GitBranchPlus:Mse,GitBranchPlusIcon:Mse,GitCommit:L5,GitCommitHorizontal:L5,GitCommitHorizontalIcon:L5,GitCommitIcon:L5,GitCommitVertical:Pse,GitCommitVerticalIcon:Pse,GitCompare:Dse,GitCompareArrows:Lse,GitCompareArrowsIcon:Lse,GitCompareIcon:Dse,GitFork:Rse,GitForkIcon:Rse,GitGraph:Ose,GitGraphIcon:Ose,GitMerge:Fse,GitMergeIcon:Fse,GitPullRequest:Vse,GitPullRequestArrow:zse,GitPullRequestArrowIcon:zse,GitPullRequestClosed:Bse,GitPullRequestClosedIcon:Bse,GitPullRequestCreate:Use,GitPullRequestCreateArrow:$se,GitPullRequestCreateArrowIcon:$se,GitPullRequestCreateIcon:Use,GitPullRequestDraft:qse,GitPullRequestDraftIcon:qse,GitPullRequestIcon:Vse,Github:Hse,GithubIcon:Hse,Gitlab:Gse,GitlabIcon:Gse,GlassWater:Wse,GlassWaterIcon:Wse,Glasses:Kse,GlassesIcon:Kse,Globe:lc,Globe2:j5,Globe2Icon:j5,GlobeIcon:lc,GlobeLock:Yse,GlobeLockIcon:Yse,Goal:Zse,GoalIcon:Zse,Grab:Qse,GrabIcon:Qse,GraduationCap:yd,GraduationCapIcon:yd,Grape:Xse,GrapeIcon:Xse,Grid:mv,Grid2X2:R5,Grid2X2Icon:R5,Grid2X2Plus:D5,Grid2X2PlusIcon:D5,Grid2x2:R5,Grid2x2Check:Jse,Grid2x2CheckIcon:Jse,Grid2x2Icon:R5,Grid2x2Plus:D5,Grid2x2PlusIcon:D5,Grid2x2X:ene,Grid2x2XIcon:ene,Grid3X3:mv,Grid3X3Icon:mv,Grid3x3:mv,Grid3x3Icon:mv,GridIcon:mv,Grip:sne,GripHorizontal:tne,GripHorizontalIcon:tne,GripIcon:sne,GripVertical:Pu,GripVerticalIcon:Pu,Group:nne,GroupIcon:nne,Guitar:rne,GuitarIcon:rne,Ham:ane,HamIcon:ane,Hammer:K7,HammerIcon:K7,Hand:Y7,HandCoins:ine,HandCoinsIcon:ine,HandHeart:jA,HandHeartIcon:jA,HandHelping:X1,HandHelpingIcon:X1,HandIcon:Y7,HandMetal:one,HandMetalIcon:one,HandPlatter:lne,HandPlatterIcon:lne,Handshake:pw,HandshakeIcon:pw,HardDrive:Z7,HardDriveDownload:cne,HardDriveDownloadIcon:cne,HardDriveIcon:Z7,HardDriveUpload:dne,HardDriveUploadIcon:dne,HardHat:une,HardHatIcon:une,Hash:VS,HashIcon:VS,Haze:hne,HazeIcon:hne,HdmiPort:mne,HdmiPortIcon:mne,Heading:gne,Heading1:XP,Heading1Icon:XP,Heading2:JP,Heading2Icon:JP,Heading3:Q7,Heading3Icon:Q7,Heading4:pne,Heading4Icon:pne,Heading5:fne,Heading5Icon:fne,Heading6:xne,Heading6Icon:xne,HeadingIcon:gne,HeadphoneOff:yne,HeadphoneOffIcon:yne,Headphones:vne,HeadphonesIcon:vne,Headset:bne,HeadsetIcon:bne,Heart:gi,HeartCrack:_ne,HeartCrackIcon:_ne,HeartHandshake:NA,HeartHandshakeIcon:NA,HeartIcon:gi,HeartOff:wne,HeartOffIcon:wne,HeartPulse:jne,HeartPulseIcon:jne,Heater:Nne,HeaterIcon:Nne,HelpCircle:q_,HelpCircleIcon:q_,HelpingHand:X1,HelpingHandIcon:X1,Hexagon:kne,HexagonIcon:kne,Highlighter:Sne,HighlighterIcon:Sne,History:kA,HistoryIcon:kA,Home:Or,HomeIcon:Or,Hop:Tne,HopIcon:Tne,HopOff:Cne,HopOffIcon:Cne,Hospital:Ene,HospitalIcon:Ene,Hotel:Ane,HotelIcon:Ane,Hourglass:Mne,HourglassIcon:Mne,House:Or,HouseIcon:Or,HousePlug:Ine,HousePlugIcon:Ine,HousePlus:Pne,HousePlusIcon:Pne,IceCream:F5,IceCream2:O5,IceCream2Icon:O5,IceCreamBowl:O5,IceCreamBowlIcon:O5,IceCreamCone:F5,IceCreamConeIcon:F5,IceCreamIcon:F5,Icon:ert,IdCard:Lne,IdCardIcon:Lne,Image:Xo,ImageDown:Dne,ImageDownIcon:Dne,ImageIcon:Xo,ImageMinus:Rne,ImageMinusIcon:Rne,ImageOff:One,ImageOffIcon:One,ImagePlay:Fne,ImagePlayIcon:Fne,ImagePlus:ty,ImagePlusIcon:ty,ImageUp:zne,ImageUpIcon:zne,ImageUpscale:Bne,ImageUpscaleIcon:Bne,Images:$ne,ImagesIcon:$ne,Import:Une,ImportIcon:Une,Inbox:H2,InboxIcon:H2,Indent:B5,IndentDecrease:z5,IndentDecreaseIcon:z5,IndentIcon:B5,IndentIncrease:B5,IndentIncreaseIcon:B5,IndianRupee:qne,IndianRupeeIcon:qne,Infinity:Vne,InfinityIcon:Vne,Info:fw,InfoIcon:fw,Inspect:VT,InspectIcon:VT,InspectionPanel:Hne,InspectionPanelIcon:Hne,Instagram:ou,InstagramIcon:ou,Italic:HS,ItalicIcon:HS,IterationCcw:Gne,IterationCcwIcon:Gne,IterationCw:Wne,IterationCwIcon:Wne,JapaneseYen:Kne,JapaneseYenIcon:Kne,Joystick:Yne,JoystickIcon:Yne,Kanban:G2,KanbanIcon:G2,KanbanSquare:zT,KanbanSquareDashed:IT,KanbanSquareDashedIcon:IT,KanbanSquareIcon:zT,Key:Ug,KeyIcon:Ug,KeyRound:SA,KeyRoundIcon:SA,KeySquare:Zne,KeySquareIcon:Zne,Keyboard:Jne,KeyboardIcon:Jne,KeyboardMusic:Qne,KeyboardMusicIcon:Qne,KeyboardOff:Xne,KeyboardOffIcon:Xne,Lamp:are,LampCeiling:ere,LampCeilingIcon:ere,LampDesk:tre,LampDeskIcon:tre,LampFloor:sre,LampFloorIcon:sre,LampIcon:are,LampWallDown:nre,LampWallDownIcon:nre,LampWallUp:rre,LampWallUpIcon:rre,LandPlot:ire,LandPlotIcon:ire,Landmark:ore,LandmarkIcon:ore,Languages:lre,LanguagesIcon:lre,Laptop:dre,Laptop2:$5,Laptop2Icon:$5,LaptopIcon:dre,LaptopMinimal:$5,LaptopMinimalCheck:cre,LaptopMinimalCheckIcon:cre,LaptopMinimalIcon:$5,Lasso:hre,LassoIcon:hre,LassoSelect:ure,LassoSelectIcon:ure,Laugh:mre,LaughIcon:mre,Layers:X7,Layers2:pre,Layers2Icon:pre,Layers3:fre,Layers3Icon:fre,LayersIcon:X7,Layout:k2,LayoutDashboard:GS,LayoutDashboardIcon:GS,LayoutGrid:ff,LayoutGridIcon:ff,LayoutIcon:k2,LayoutList:xre,LayoutListIcon:xre,LayoutPanelLeft:gre,LayoutPanelLeftIcon:gre,LayoutPanelTop:yre,LayoutPanelTopIcon:yre,LayoutTemplate:WS,LayoutTemplateIcon:WS,Leaf:vre,LeafIcon:vre,LeafyGreen:bre,LeafyGreenIcon:bre,Lectern:_re,LecternIcon:_re,LetterText:wre,LetterTextIcon:wre,Library:qg,LibraryBig:jre,LibraryBigIcon:jre,LibraryIcon:qg,LibrarySquare:BT,LibrarySquareIcon:BT,LifeBuoy:eL,LifeBuoyIcon:eL,Ligature:Nre,LigatureIcon:Nre,Lightbulb:W2,LightbulbIcon:W2,LightbulbOff:kre,LightbulbOffIcon:kre,LineChart:F3,LineChartIcon:F3,Link:Yo,Link2:Tl,Link2Icon:Tl,Link2Off:Sre,Link2OffIcon:Sre,LinkIcon:Yo,Linkedin:xf,LinkedinIcon:xf,List:Sp,ListCheck:Cre,ListCheckIcon:Cre,ListChecks:lu,ListChecksIcon:lu,ListCollapse:Tre,ListCollapseIcon:Tre,ListEnd:Ere,ListEndIcon:Ere,ListFilter:J7,ListFilterIcon:J7,ListIcon:Sp,ListMinus:Are,ListMinusIcon:Are,ListMusic:Mre,ListMusicIcon:Mre,ListOrdered:ub,ListOrderedIcon:ub,ListPlus:Ire,ListPlusIcon:Ire,ListRestart:Pre,ListRestartIcon:Pre,ListStart:Lre,ListStartIcon:Lre,ListTodo:Dre,ListTodoIcon:Dre,ListTree:Rre,ListTreeIcon:Rre,ListVideo:Ore,ListVideoIcon:Ore,ListX:Fre,ListXIcon:Fre,Loader:Bre,Loader2:rs,Loader2Icon:rs,LoaderCircle:rs,LoaderCircleIcon:rs,LoaderIcon:Bre,LoaderPinwheel:zre,LoaderPinwheelIcon:zre,Locate:tL,LocateFixed:$re,LocateFixedIcon:$re,LocateIcon:tL,LocateOff:Ure,LocateOffIcon:Ure,Lock:Gc,LockIcon:Gc,LockKeyhole:qre,LockKeyholeIcon:qre,LockKeyholeOpen:U5,LockKeyholeOpenIcon:U5,LockOpen:q5,LockOpenIcon:q5,LogIn:CA,LogInIcon:CA,LogOut:TA,LogOutIcon:TA,Logs:Vre,LogsIcon:Vre,Lollipop:Hre,LollipopIcon:Hre,LucideAArrowDown:hW,LucideAArrowUp:mW,LucideALargeSmall:pW,LucideAccessibility:fW,LucideActivity:em,LucideActivitySquare:uT,LucideAirVent:xW,LucideAirplay:gW,LucideAlarmCheck:x3,LucideAlarmClock:vW,LucideAlarmClockCheck:x3,LucideAlarmClockMinus:g3,LucideAlarmClockOff:yW,LucideAlarmClockPlus:y3,LucideAlarmMinus:g3,LucideAlarmPlus:y3,LucideAlarmSmoke:bW,LucideAlbum:_W,LucideAlertCircle:Bi,LucideAlertOctagon:V_,LucideAlertTriangle:ic,LucideAlignCenter:pA,LucideAlignCenterHorizontal:wW,LucideAlignCenterVertical:jW,LucideAlignEndHorizontal:NW,LucideAlignEndVertical:kW,LucideAlignHorizontalDistributeCenter:SW,LucideAlignHorizontalDistributeEnd:CW,LucideAlignHorizontalDistributeStart:TW,LucideAlignHorizontalJustifyCenter:EW,LucideAlignHorizontalJustifyEnd:AW,LucideAlignHorizontalJustifyStart:MW,LucideAlignHorizontalSpaceAround:IW,LucideAlignHorizontalSpaceBetween:PW,LucideAlignJustify:LW,LucideAlignLeft:fA,LucideAlignRight:xA,LucideAlignStartHorizontal:DW,LucideAlignStartVertical:RW,LucideAlignVerticalDistributeCenter:OW,LucideAlignVerticalDistributeEnd:FW,LucideAlignVerticalDistributeStart:zW,LucideAlignVerticalJustifyCenter:BW,LucideAlignVerticalJustifyEnd:$W,LucideAlignVerticalJustifyStart:UW,LucideAlignVerticalSpaceAround:qW,LucideAlignVerticalSpaceBetween:VW,LucideAmbulance:HW,LucideAmpersand:GW,LucideAmpersands:WW,LucideAmphora:KW,LucideAnchor:YW,LucideAngry:ZW,LucideAnnoyed:QW,LucideAntenna:XW,LucideAnvil:JW,LucideAperture:eK,LucideAppWindow:sK,LucideAppWindowMac:tK,LucideApple:nK,LucideArchive:tm,LucideArchiveRestore:HP,LucideArchiveX:rK,LucideAreaChart:I3,LucideArmchair:aK,LucideArrowBigDown:oK,LucideArrowBigDownDash:iK,LucideArrowBigLeft:cK,LucideArrowBigLeftDash:lK,LucideArrowBigRight:uK,LucideArrowBigRightDash:dK,LucideArrowBigUp:mK,LucideArrowBigUpDash:hK,LucideArrowDown:sm,LucideArrowDown01:pK,LucideArrowDown10:fK,LucideArrowDownAZ:v3,LucideArrowDownAz:v3,LucideArrowDownCircle:V3,LucideArrowDownFromLine:xK,LucideArrowDownLeft:gK,LucideArrowDownLeftFromCircle:G3,LucideArrowDownLeftFromSquare:xT,LucideArrowDownLeftSquare:hT,LucideArrowDownNarrowWide:yK,LucideArrowDownRight:I7,LucideArrowDownRightFromCircle:W3,LucideArrowDownRightFromSquare:gT,LucideArrowDownRightSquare:mT,LucideArrowDownSquare:pT,LucideArrowDownToDot:vK,LucideArrowDownToLine:bK,LucideArrowDownUp:_K,LucideArrowDownWideNarrow:b3,LucideArrowDownZA:_3,LucideArrowDownZa:_3,LucideArrowLeft:qr,LucideArrowLeftCircle:H3,LucideArrowLeftFromLine:wK,LucideArrowLeftRight:jK,LucideArrowLeftSquare:fT,LucideArrowLeftToLine:NK,LucideArrowRight:Oa,LucideArrowRightCircle:Z3,LucideArrowRightFromLine:kK,LucideArrowRightLeft:lw,LucideArrowRightSquare:bT,LucideArrowRightToLine:SK,LucideArrowUp:Iu,LucideArrowUp01:CK,LucideArrowUp10:TK,LucideArrowUpAZ:w3,LucideArrowUpAz:w3,LucideArrowUpCircle:Q3,LucideArrowUpDown:ah,LucideArrowUpFromDot:EK,LucideArrowUpFromLine:AK,LucideArrowUpLeft:MK,LucideArrowUpLeftFromCircle:K3,LucideArrowUpLeftFromSquare:yT,LucideArrowUpLeftSquare:_T,LucideArrowUpNarrowWide:j3,LucideArrowUpRight:GP,LucideArrowUpRightFromCircle:Y3,LucideArrowUpRightFromSquare:vT,LucideArrowUpRightSquare:wT,LucideArrowUpSquare:jT,LucideArrowUpToLine:IK,LucideArrowUpWideNarrow:PK,LucideArrowUpZA:N3,LucideArrowUpZa:N3,LucideArrowsUpFromLine:LK,LucideAsterisk:DK,LucideAsteriskSquare:NT,LucideAtSign:RK,LucideAtom:OK,LucideAudioLines:FK,LucideAudioWaveform:zK,LucideAward:fc,LucideAxe:BK,LucideAxis3D:k3,LucideAxis3d:k3,LucideBaby:$K,LucideBackpack:UK,LucideBadge:rY,LucideBadgeAlert:qK,LucideBadgeCent:VK,LucideBadgeCheck:S3,LucideBadgeDollarSign:HK,LucideBadgeEuro:GK,LucideBadgeHelp:WK,LucideBadgeIndianRupee:KK,LucideBadgeInfo:YK,LucideBadgeJapaneseYen:ZK,LucideBadgeMinus:QK,LucideBadgePercent:XK,LucideBadgePlus:JK,LucideBadgePoundSterling:eY,LucideBadgeRussianRuble:tY,LucideBadgeSwissFranc:sY,LucideBadgeX:nY,LucideBaggageClaim:aY,LucideBan:WP,LucideBanana:iY,LucideBandage:oY,LucideBanknote:lY,LucideBarChart:z3,LucideBarChart2:B3,LucideBarChart3:_o,LucideBarChart4:O3,LucideBarChartBig:R3,LucideBarChartHorizontal:L3,LucideBarChartHorizontalBig:P3,LucideBarcode:cY,LucideBaseline:dY,LucideBath:kp,LucideBattery:xY,LucideBatteryCharging:uY,LucideBatteryFull:hY,LucideBatteryLow:mY,LucideBatteryMedium:pY,LucideBatteryWarning:fY,LucideBeaker:P7,LucideBean:yY,LucideBeanOff:gY,LucideBed:J0,LucideBedDouble:U2,LucideBedSingle:vY,LucideBeef:bY,LucideBeer:wY,LucideBeerOff:_Y,LucideBell:nm,LucideBellDot:jY,LucideBellElectric:NY,LucideBellMinus:kY,LucideBellOff:cw,LucideBellPlus:SY,LucideBellRing:BS,LucideBetweenHorizonalEnd:C3,LucideBetweenHorizonalStart:T3,LucideBetweenHorizontalEnd:C3,LucideBetweenHorizontalStart:T3,LucideBetweenVerticalEnd:CY,LucideBetweenVerticalStart:TY,LucideBicepsFlexed:EY,LucideBike:AY,LucideBinary:MY,LucideBinoculars:IY,LucideBiohazard:PY,LucideBird:LY,LucideBitcoin:DY,LucideBlend:RY,LucideBlinds:OY,LucideBlocks:FY,LucideBluetooth:UY,LucideBluetoothConnected:zY,LucideBluetoothOff:BY,LucideBluetoothSearching:$Y,LucideBold:$S,LucideBolt:qY,LucideBomb:VY,LucideBone:HY,LucideBook:mZ,LucideBookA:GY,LucideBookAudio:WY,LucideBookCheck:KY,LucideBookCopy:YY,LucideBookDashed:E3,LucideBookDown:ZY,LucideBookHeadphones:QY,LucideBookHeart:XY,LucideBookImage:JY,LucideBookKey:eZ,LucideBookLock:tZ,LucideBookMarked:sZ,LucideBookMinus:nZ,LucideBookOpen:rm,LucideBookOpenCheck:rZ,LucideBookOpenText:aZ,LucideBookPlus:iZ,LucideBookTemplate:E3,LucideBookText:oZ,LucideBookType:lZ,LucideBookUp:dZ,LucideBookUp2:cZ,LucideBookUser:uZ,LucideBookX:hZ,LucideBookmark:Pv,LucideBookmarkCheck:pZ,LucideBookmarkMinus:fZ,LucideBookmarkPlus:L7,LucideBookmarkX:xZ,LucideBoomBox:gZ,LucideBot:US,LucideBotMessageSquare:yZ,LucideBotOff:vZ,LucideBox:D7,LucideBoxSelect:LT,LucideBoxes:bZ,LucideBraces:A3,LucideBrackets:_Z,LucideBrain:R7,LucideBrainCircuit:wZ,LucideBrainCog:jZ,LucideBrickWall:NZ,LucideBriefcase:zm,LucideBriefcaseBusiness:kZ,LucideBriefcaseConveyorBelt:SZ,LucideBriefcaseMedical:CZ,LucideBringToFront:TZ,LucideBrush:EZ,LucideBug:IZ,LucideBugOff:AZ,LucideBugPlay:MZ,LucideBuilding:gA,LucideBuilding2:Ua,LucideBus:LZ,LucideBusFront:PZ,LucideCable:RZ,LucideCableCar:DZ,LucideCake:Ah,LucideCakeSlice:OZ,LucideCalculator:dw,LucideCalendar:yr,LucideCalendar1:FZ,LucideCalendarArrowDown:zZ,LucideCalendarArrowUp:BZ,LucideCalendarCheck:O7,LucideCalendarCheck2:$Z,LucideCalendarClock:Xf,LucideCalendarCog:UZ,LucideCalendarDays:Cl,LucideCalendarFold:qZ,LucideCalendarHeart:uw,LucideCalendarMinus:HZ,LucideCalendarMinus2:VZ,LucideCalendarOff:F7,LucideCalendarPlus:Lg,LucideCalendarPlus2:GZ,LucideCalendarRange:WZ,LucideCalendarSearch:KZ,LucideCalendarSync:YZ,LucideCalendarX:z7,LucideCalendarX2:ZZ,LucideCamera:Jf,LucideCameraOff:QZ,LucideCandlestickChart:D3,LucideCandy:eQ,LucideCandyCane:XZ,LucideCandyOff:JZ,LucideCannabis:tQ,LucideCaptions:M3,LucideCaptionsOff:sQ,LucideCar:aQ,LucideCarFront:nQ,LucideCarTaxiFront:rQ,LucideCaravan:iQ,LucideCarrot:oQ,LucideCaseLower:lQ,LucideCaseSensitive:cQ,LucideCaseUpper:dQ,LucideCassetteTape:uQ,LucideCast:hQ,LucideCastle:mQ,LucideCat:pQ,LucideCctv:fQ,LucideChartArea:I3,LucideChartBar:L3,LucideChartBarBig:P3,LucideChartBarDecreasing:xQ,LucideChartBarIncreasing:gQ,LucideChartBarStacked:yQ,LucideChartCandlestick:D3,LucideChartColumn:_o,LucideChartColumnBig:R3,LucideChartColumnDecreasing:vQ,LucideChartColumnIncreasing:O3,LucideChartColumnStacked:bQ,LucideChartGantt:_Q,LucideChartLine:F3,LucideChartNetwork:wQ,LucideChartNoAxesColumn:B3,LucideChartNoAxesColumnDecreasing:jQ,LucideChartNoAxesColumnIncreasing:z3,LucideChartNoAxesCombined:NQ,LucideChartNoAxesGantt:$3,LucideChartPie:U3,LucideChartScatter:q3,LucideChartSpline:kQ,LucideCheck:Lr,LucideCheckCheck:B7,LucideCheckCircle:Pi,LucideCheckCircle2:vr,LucideCheckSquare:S2,LucideCheckSquare2:ST,LucideChefHat:SQ,LucideCherry:CQ,LucideChevronDown:ao,LucideChevronDownCircle:X3,LucideChevronDownSquare:CT,LucideChevronFirst:TQ,LucideChevronLast:EQ,LucideChevronLeft:ml,LucideChevronLeftCircle:J3,LucideChevronLeftSquare:TT,LucideChevronRight:ga,LucideChevronRightCircle:e5,LucideChevronRightSquare:ET,LucideChevronUp:ex,LucideChevronUpCircle:t5,LucideChevronUpSquare:AT,LucideChevronsDown:MQ,LucideChevronsDownUp:AQ,LucideChevronsLeft:LQ,LucideChevronsLeftRight:PQ,LucideChevronsLeftRightEllipsis:IQ,LucideChevronsRight:RQ,LucideChevronsRightLeft:DQ,LucideChevronsUp:OQ,LucideChevronsUpDown:$g,LucideChrome:yA,LucideChurch:FQ,LucideCigarette:BQ,LucideCigaretteOff:zQ,LucideCircle:am,LucideCircleAlert:Bi,LucideCircleArrowDown:V3,LucideCircleArrowLeft:H3,LucideCircleArrowOutDownLeft:G3,LucideCircleArrowOutDownRight:W3,LucideCircleArrowOutUpLeft:K3,LucideCircleArrowOutUpRight:Y3,LucideCircleArrowRight:Z3,LucideCircleArrowUp:Q3,LucideCircleCheck:vr,LucideCircleCheckBig:Pi,LucideCircleChevronDown:X3,LucideCircleChevronLeft:J3,LucideCircleChevronRight:e5,LucideCircleChevronUp:t5,LucideCircleDashed:$Q,LucideCircleDivide:s5,LucideCircleDollarSign:UQ,LucideCircleDot:VQ,LucideCircleDotDashed:qQ,LucideCircleEllipsis:HQ,LucideCircleEqual:GQ,LucideCircleFadingArrowUp:WQ,LucideCircleFadingPlus:KQ,LucideCircleGauge:n5,LucideCircleHelp:q_,LucideCircleMinus:r5,LucideCircleOff:YQ,LucideCircleParking:i5,LucideCircleParkingOff:a5,LucideCirclePause:o5,LucideCirclePercent:l5,LucideCirclePlay:jh,LucideCirclePlus:c5,LucideCirclePower:d5,LucideCircleSlash:ZQ,LucideCircleSlash2:u5,LucideCircleSlashed:u5,LucideCircleStop:h5,LucideCircleUser:p5,LucideCircleUserRound:m5,LucideCircleX:Uc,LucideCircuitBoard:QQ,LucideCitrus:XQ,LucideClapperboard:JQ,LucideClipboard:iX,LucideClipboardCheck:KP,LucideClipboardCopy:eX,LucideClipboardEdit:x5,LucideClipboardList:cb,LucideClipboardMinus:tX,LucideClipboardPaste:sX,LucideClipboardPen:x5,LucideClipboardPenLine:f5,LucideClipboardPlus:nX,LucideClipboardSignature:f5,LucideClipboardType:rX,LucideClipboardX:aX,LucideClock:pr,LucideClock1:oX,LucideClock10:lX,LucideClock11:cX,LucideClock12:dX,LucideClock2:uX,LucideClock3:$7,LucideClock4:hX,LucideClock5:mX,LucideClock6:pX,LucideClock7:fX,LucideClock8:xX,LucideClock9:gX,LucideClockAlert:yX,LucideClockArrowDown:vX,LucideClockArrowUp:bX,LucideCloud:DX,LucideCloudAlert:_X,LucideCloudCog:wX,LucideCloudDownload:g5,LucideCloudDrizzle:jX,LucideCloudFog:NX,LucideCloudHail:kX,LucideCloudLightning:SX,LucideCloudMoon:TX,LucideCloudMoonRain:CX,LucideCloudOff:EX,LucideCloudRain:MX,LucideCloudRainWind:AX,LucideCloudSnow:IX,LucideCloudSun:LX,LucideCloudSunRain:PX,LucideCloudUpload:y5,LucideCloudy:RX,LucideClover:P2,LucideClub:OX,LucideCode:vA,LucideCode2:N2,LucideCodeSquare:MT,LucideCodeXml:N2,LucideCodepen:FX,LucideCodesandbox:zX,LucideCoffee:ey,LucideCog:BX,LucideCoins:U7,LucideColumns:v5,LucideColumns2:v5,LucideColumns3:b5,LucideColumns4:$X,LucideCombine:UX,LucideCommand:qX,LucideCompass:YP,LucideComponent:VX,LucideComputer:HX,LucideConciergeBell:GX,LucideCone:WX,LucideConstruction:KX,LucideContact:bA,LucideContact2:_5,LucideContactRound:_5,LucideContainer:YX,LucideContrast:ZX,LucideCookie:QX,LucideCookingPot:XX,LucideCopy:Zr,LucideCopyCheck:JX,LucideCopyMinus:eJ,LucideCopyPlus:tJ,LucideCopySlash:sJ,LucideCopyX:nJ,LucideCopyleft:rJ,LucideCopyright:aJ,LucideCornerDownLeft:iJ,LucideCornerDownRight:oJ,LucideCornerLeftDown:lJ,LucideCornerLeftUp:cJ,LucideCornerRightDown:dJ,LucideCornerRightUp:uJ,LucideCornerUpLeft:hJ,LucideCornerUpRight:mJ,LucideCpu:pJ,LucideCreativeCommons:fJ,LucideCreditCard:uf,LucideCroissant:xJ,LucideCrop:gJ,LucideCross:yJ,LucideCrosshair:vJ,LucideCrown:hf,LucideCuboid:bJ,LucideCupSoda:_J,LucideCurlyBraces:A3,LucideCurrency:wJ,LucideCylinder:jJ,LucideDam:NJ,LucideDatabase:q7,LucideDatabaseBackup:kJ,LucideDatabaseZap:SJ,LucideDelete:CJ,LucideDessert:TJ,LucideDiameter:EJ,LucideDiamond:IJ,LucideDiamondMinus:AJ,LucideDiamondPercent:w5,LucideDiamondPlus:MJ,LucideDice1:PJ,LucideDice2:LJ,LucideDice3:DJ,LucideDice4:RJ,LucideDice5:OJ,LucideDice6:FJ,LucideDices:zJ,LucideDiff:BJ,LucideDisc:VJ,LucideDisc2:$J,LucideDisc3:UJ,LucideDiscAlbum:qJ,LucideDivide:HJ,LucideDivideCircle:s5,LucideDivideSquare:DT,LucideDna:WJ,LucideDnaOff:GJ,LucideDock:KJ,LucideDog:YJ,LucideDollarSign:Yl,LucideDonut:ZJ,LucideDoorClosed:QJ,LucideDoorOpen:hw,LucideDot:XJ,LucideDotSquare:RT,LucideDownload:Ia,LucideDownloadCloud:g5,LucideDraftingCompass:JJ,LucideDrama:eee,LucideDribbble:tee,LucideDrill:see,LucideDroplet:nee,LucideDroplets:db,LucideDrum:ree,LucideDrumstick:aee,LucideDumbbell:iee,LucideEar:lee,LucideEarOff:oee,LucideEarth:j5,LucideEarthLock:cee,LucideEclipse:dee,LucideEdit:wu,LucideEdit2:_v,LucideEdit3:J1,LucideEgg:ZP,LucideEggFried:uee,LucideEggOff:hee,LucideEllipsis:Kf,LucideEllipsisVertical:Ag,LucideEqual:fee,LucideEqualApproximately:mee,LucideEqualNot:pee,LucideEqualSquare:OT,LucideEraser:xee,LucideEthernetPort:gee,LucideEuro:yee,LucideExpand:vee,LucideExternalLink:tr,LucideEye:Sr,LucideEyeClosed:bee,LucideEyeOff:mf,LucideFacebook:Mh,LucideFactory:_ee,LucideFan:wee,LucideFastForward:jee,LucideFeather:Nee,LucideFence:kee,LucideFerrisWheel:See,LucideFigma:Cee,LucideFile:QP,LucideFileArchive:Tee,LucideFileAudio:Aee,LucideFileAudio2:Eee,LucideFileAxis3D:N5,LucideFileAxis3d:N5,LucideFileBadge:Iee,LucideFileBadge2:Mee,LucideFileBarChart:k5,LucideFileBarChart2:S5,LucideFileBox:Pee,LucideFileChartColumn:S5,LucideFileChartColumnIncreasing:k5,LucideFileChartLine:C5,LucideFileChartPie:T5,LucideFileCheck:V7,LucideFileCheck2:Lee,LucideFileClock:Dee,LucideFileCode:Oee,LucideFileCode2:Ree,LucideFileCog:E5,LucideFileCog2:E5,LucideFileDiff:Fee,LucideFileDigit:zee,LucideFileDown:_A,LucideFileEdit:M5,LucideFileHeart:Bee,LucideFileImage:q2,LucideFileInput:$ee,LucideFileJson:qee,LucideFileJson2:Uee,LucideFileKey:Hee,LucideFileKey2:Vee,LucideFileLineChart:C5,LucideFileLock:Wee,LucideFileLock2:Gee,LucideFileMinus:Yee,LucideFileMinus2:Kee,LucideFileMusic:Zee,LucideFileOutput:Qee,LucideFilePen:M5,LucideFilePenLine:A5,LucideFilePieChart:T5,LucideFilePlus:Jee,LucideFilePlus2:Xee,LucideFileQuestion:ete,LucideFileScan:tte,LucideFileSearch:nte,LucideFileSearch2:ste,LucideFileSignature:A5,LucideFileSliders:rte,LucideFileSpreadsheet:mw,LucideFileStack:H7,LucideFileSymlink:ate,LucideFileTerminal:ite,LucideFileText:br,LucideFileType:lte,LucideFileType2:ote,LucideFileUp:cte,LucideFileUser:dte,LucideFileVideo:G7,LucideFileVideo2:ute,LucideFileVolume:mte,LucideFileVolume2:hte,LucideFileWarning:pte,LucideFileX:xte,LucideFileX2:fte,LucideFiles:gte,LucideFilm:Sh,LucideFilter:Lv,LucideFilterX:yte,LucideFingerprint:vte,LucideFireExtinguisher:bte,LucideFish:jte,LucideFishOff:_te,LucideFishSymbol:wte,LucideFlag:V2,LucideFlagOff:Nte,LucideFlagTriangleLeft:kte,LucideFlagTriangleRight:Ste,LucideFlame:Hc,LucideFlameKindling:Cte,LucideFlashlight:Ete,LucideFlashlightOff:Tte,LucideFlaskConical:qS,LucideFlaskConicalOff:Ate,LucideFlaskRound:Mte,LucideFlipHorizontal:W7,LucideFlipHorizontal2:Ite,LucideFlipVertical:Lte,LucideFlipVertical2:Pte,LucideFlower:Dte,LucideFlower2:rb,LucideFocus:Rte,LucideFoldHorizontal:Ote,LucideFoldVertical:Fte,LucideFolder:use,LucideFolderArchive:zte,LucideFolderCheck:Bte,LucideFolderClock:$te,LucideFolderClosed:Ute,LucideFolderCode:qte,LucideFolderCog:I5,LucideFolderCog2:I5,LucideFolderDot:Vte,LucideFolderDown:Hte,LucideFolderEdit:P5,LucideFolderGit:Wte,LucideFolderGit2:Gte,LucideFolderHeart:Kte,LucideFolderInput:Yte,LucideFolderKanban:Zte,LucideFolderKey:Qte,LucideFolderLock:Xte,LucideFolderMinus:Jte,LucideFolderOpen:pf,LucideFolderOpenDot:ese,LucideFolderOutput:tse,LucideFolderPen:P5,LucideFolderPlus:sse,LucideFolderRoot:nse,LucideFolderSearch:ase,LucideFolderSearch2:rse,LucideFolderSymlink:ise,LucideFolderSync:ose,LucideFolderTree:lse,LucideFolderUp:cse,LucideFolderX:dse,LucideFolders:hse,LucideFootprints:mse,LucideForkKnife:_E,LucideForkKnifeCrossed:bE,LucideForklift:pse,LucideFormInput:nT,LucideForward:fse,LucideFrame:xse,LucideFramer:gse,LucideFrown:yse,LucideFuel:vse,LucideFullscreen:bse,LucideFunctionSquare:FT,LucideGalleryHorizontal:wse,LucideGalleryHorizontalEnd:_se,LucideGalleryThumbnails:jse,LucideGalleryVertical:kse,LucideGalleryVerticalEnd:Nse,LucideGamepad:Cse,LucideGamepad2:Sse,LucideGanttChart:$3,LucideGanttChartSquare:A_,LucideGauge:Tse,LucideGaugeCircle:n5,LucideGavel:Ese,LucideGem:Ase,LucideGhost:wA,LucideGift:Oi,LucideGitBranch:Ise,LucideGitBranchPlus:Mse,LucideGitCommit:L5,LucideGitCommitHorizontal:L5,LucideGitCommitVertical:Pse,LucideGitCompare:Dse,LucideGitCompareArrows:Lse,LucideGitFork:Rse,LucideGitGraph:Ose,LucideGitMerge:Fse,LucideGitPullRequest:Vse,LucideGitPullRequestArrow:zse,LucideGitPullRequestClosed:Bse,LucideGitPullRequestCreate:Use,LucideGitPullRequestCreateArrow:$se,LucideGitPullRequestDraft:qse,LucideGithub:Hse,LucideGitlab:Gse,LucideGlassWater:Wse,LucideGlasses:Kse,LucideGlobe:lc,LucideGlobe2:j5,LucideGlobeLock:Yse,LucideGoal:Zse,LucideGrab:Qse,LucideGraduationCap:yd,LucideGrape:Xse,LucideGrid:mv,LucideGrid2X2:R5,LucideGrid2X2Plus:D5,LucideGrid2x2:R5,LucideGrid2x2Check:Jse,LucideGrid2x2Plus:D5,LucideGrid2x2X:ene,LucideGrid3X3:mv,LucideGrid3x3:mv,LucideGrip:sne,LucideGripHorizontal:tne,LucideGripVertical:Pu,LucideGroup:nne,LucideGuitar:rne,LucideHam:ane,LucideHammer:K7,LucideHand:Y7,LucideHandCoins:ine,LucideHandHeart:jA,LucideHandHelping:X1,LucideHandMetal:one,LucideHandPlatter:lne,LucideHandshake:pw,LucideHardDrive:Z7,LucideHardDriveDownload:cne,LucideHardDriveUpload:dne,LucideHardHat:une,LucideHash:VS,LucideHaze:hne,LucideHdmiPort:mne,LucideHeading:gne,LucideHeading1:XP,LucideHeading2:JP,LucideHeading3:Q7,LucideHeading4:pne,LucideHeading5:fne,LucideHeading6:xne,LucideHeadphoneOff:yne,LucideHeadphones:vne,LucideHeadset:bne,LucideHeart:gi,LucideHeartCrack:_ne,LucideHeartHandshake:NA,LucideHeartOff:wne,LucideHeartPulse:jne,LucideHeater:Nne,LucideHelpCircle:q_,LucideHelpingHand:X1,LucideHexagon:kne,LucideHighlighter:Sne,LucideHistory:kA,LucideHome:Or,LucideHop:Tne,LucideHopOff:Cne,LucideHospital:Ene,LucideHotel:Ane,LucideHourglass:Mne,LucideHouse:Or,LucideHousePlug:Ine,LucideHousePlus:Pne,LucideIceCream:F5,LucideIceCream2:O5,LucideIceCreamBowl:O5,LucideIceCreamCone:F5,LucideIdCard:Lne,LucideImage:Xo,LucideImageDown:Dne,LucideImageMinus:Rne,LucideImageOff:One,LucideImagePlay:Fne,LucideImagePlus:ty,LucideImageUp:zne,LucideImageUpscale:Bne,LucideImages:$ne,LucideImport:Une,LucideInbox:H2,LucideIndent:B5,LucideIndentDecrease:z5,LucideIndentIncrease:B5,LucideIndianRupee:qne,LucideInfinity:Vne,LucideInfo:fw,LucideInspect:VT,LucideInspectionPanel:Hne,LucideInstagram:ou,LucideItalic:HS,LucideIterationCcw:Gne,LucideIterationCw:Wne,LucideJapaneseYen:Kne,LucideJoystick:Yne,LucideKanban:G2,LucideKanbanSquare:zT,LucideKanbanSquareDashed:IT,LucideKey:Ug,LucideKeyRound:SA,LucideKeySquare:Zne,LucideKeyboard:Jne,LucideKeyboardMusic:Qne,LucideKeyboardOff:Xne,LucideLamp:are,LucideLampCeiling:ere,LucideLampDesk:tre,LucideLampFloor:sre,LucideLampWallDown:nre,LucideLampWallUp:rre,LucideLandPlot:ire,LucideLandmark:ore,LucideLanguages:lre,LucideLaptop:dre,LucideLaptop2:$5,LucideLaptopMinimal:$5,LucideLaptopMinimalCheck:cre,LucideLasso:hre,LucideLassoSelect:ure,LucideLaugh:mre,LucideLayers:X7,LucideLayers2:pre,LucideLayers3:fre,LucideLayout:k2,LucideLayoutDashboard:GS,LucideLayoutGrid:ff,LucideLayoutList:xre,LucideLayoutPanelLeft:gre,LucideLayoutPanelTop:yre,LucideLayoutTemplate:WS,LucideLeaf:vre,LucideLeafyGreen:bre,LucideLectern:_re,LucideLetterText:wre,LucideLibrary:qg,LucideLibraryBig:jre,LucideLibrarySquare:BT,LucideLifeBuoy:eL,LucideLigature:Nre,LucideLightbulb:W2,LucideLightbulbOff:kre,LucideLineChart:F3,LucideLink:Yo,LucideLink2:Tl,LucideLink2Off:Sre,LucideLinkedin:xf,LucideList:Sp,LucideListCheck:Cre,LucideListChecks:lu,LucideListCollapse:Tre,LucideListEnd:Ere,LucideListFilter:J7,LucideListMinus:Are,LucideListMusic:Mre,LucideListOrdered:ub,LucideListPlus:Ire,LucideListRestart:Pre,LucideListStart:Lre,LucideListTodo:Dre,LucideListTree:Rre,LucideListVideo:Ore,LucideListX:Fre,LucideLoader:Bre,LucideLoader2:rs,LucideLoaderCircle:rs,LucideLoaderPinwheel:zre,LucideLocate:tL,LucideLocateFixed:$re,LucideLocateOff:Ure,LucideLock:Gc,LucideLockKeyhole:qre,LucideLockKeyholeOpen:U5,LucideLockOpen:q5,LucideLogIn:CA,LucideLogOut:TA,LucideLogs:Vre,LucideLollipop:Hre,LucideLuggage:Gre,LucideMSquare:$T,LucideMagnet:Wre,LucideMail:Gs,LucideMailCheck:sL,LucideMailMinus:Kre,LucideMailOpen:nL,LucideMailPlus:e9,LucideMailQuestion:Yre,LucideMailSearch:Zre,LucideMailWarning:Qre,LucideMailX:rL,LucideMailbox:Xre,LucideMails:Jre,LucideMap:EA,LucideMapPin:ka,LucideMapPinCheck:tae,LucideMapPinCheckInside:eae,LucideMapPinHouse:sae,LucideMapPinMinus:rae,LucideMapPinMinusInside:nae,LucideMapPinOff:aae,LucideMapPinPlus:oae,LucideMapPinPlusInside:iae,LucideMapPinX:cae,LucideMapPinXInside:lae,LucideMapPinned:dae,LucideMartini:uae,LucideMaximize:AA,LucideMaximize2:t9,LucideMedal:K2,LucideMegaphone:zd,LucideMegaphoneOff:hae,LucideMeh:mae,LucideMemoryStick:pae,LucideMenu:KS,LucideMenuSquare:UT,LucideMerge:fae,LucideMessageCircle:Zl,LucideMessageCircleCode:xae,LucideMessageCircleDashed:gae,LucideMessageCircleHeart:aL,LucideMessageCircleMore:yae,LucideMessageCircleOff:vae,LucideMessageCirclePlus:bae,LucideMessageCircleQuestion:s9,LucideMessageCircleReply:_ae,LucideMessageCircleWarning:wae,LucideMessageCircleX:jae,LucideMessageSquare:Ai,LucideMessageSquareCode:Nae,LucideMessageSquareDashed:kae,LucideMessageSquareDiff:Sae,LucideMessageSquareDot:Cae,LucideMessageSquareHeart:iL,LucideMessageSquareLock:Tae,LucideMessageSquareMore:n9,LucideMessageSquareOff:Eae,LucideMessageSquarePlus:X_,LucideMessageSquareQuote:xw,LucideMessageSquareReply:Aae,LucideMessageSquareShare:Mae,LucideMessageSquareText:Iae,LucideMessageSquareWarning:Pae,LucideMessageSquareX:Lae,LucideMessagesSquare:oL,LucideMic:Dv,LucideMic2:V5,LucideMicOff:Dae,LucideMicVocal:V5,LucideMicrochip:Rae,LucideMicroscope:Oae,LucideMicrowave:Fae,LucideMilestone:zae,LucideMilk:$ae,LucideMilkOff:Bae,LucideMinimize:qae,LucideMinimize2:Uae,LucideMinus:hb,LucideMinusCircle:r5,LucideMinusSquare:qT,LucideMonitor:mb,LucideMonitorCheck:Vae,LucideMonitorCog:Hae,LucideMonitorDot:Gae,LucideMonitorDown:Wae,LucideMonitorOff:Kae,LucideMonitorPause:Yae,LucideMonitorPlay:lL,LucideMonitorSmartphone:Zae,LucideMonitorSpeaker:Qae,LucideMonitorStop:Xae,LucideMonitorUp:MA,LucideMonitorX:Jae,LucideMoon:tie,LucideMoonStar:eie,LucideMoreHorizontal:Kf,LucideMoreVertical:Ag,LucideMountain:nie,LucideMountainSnow:sie,LucideMouse:oie,LucideMouseOff:rie,LucideMousePointer:Lm,LucideMousePointer2:aie,LucideMousePointerBan:iie,LucideMousePointerClick:oc,LucideMousePointerSquareDashed:PT,LucideMove:bie,LucideMove3D:H5,LucideMove3d:H5,LucideMoveDiagonal:cie,LucideMoveDiagonal2:lie,LucideMoveDown:hie,LucideMoveDownLeft:die,LucideMoveDownRight:uie,LucideMoveHorizontal:mie,LucideMoveLeft:pie,LucideMoveRight:fie,LucideMoveUp:yie,LucideMoveUpLeft:xie,LucideMoveUpRight:gie,LucideMoveVertical:vie,LucideMusic:cL,LucideMusic2:_ie,LucideMusic3:wie,LucideMusic4:jie,LucideNavigation:r9,LucideNavigation2:kie,LucideNavigation2Off:Nie,LucideNavigationOff:Sie,LucideNetwork:Cie,LucideNewspaper:sy,LucideNfc:Tie,LucideNotebook:Iie,LucideNotebookPen:Eie,LucideNotebookTabs:Aie,LucideNotebookText:Mie,LucideNotepadText:Lie,LucideNotepadTextDashed:Pie,LucideNut:Rie,LucideNutOff:Die,LucideOctagon:Fie,LucideOctagonAlert:V_,LucideOctagonMinus:Oie,LucideOctagonPause:G5,LucideOctagonX:W5,LucideOmega:zie,LucideOption:Bie,LucideOrbit:$ie,LucideOrigami:Uie,LucideOutdent:z5,LucidePackage:Ec,LucidePackage2:qie,LucidePackageCheck:Vie,LucidePackageMinus:Hie,LucidePackageOpen:Gie,LucidePackagePlus:a9,LucidePackageSearch:Wie,LucidePackageX:Kie,LucidePaintBucket:Yie,LucidePaintRoller:Zie,LucidePaintbrush:Qie,LucidePaintbrush2:K5,LucidePaintbrushVertical:K5,LucidePalette:pl,LucidePalmtree:uE,LucidePanelBottom:eoe,LucidePanelBottomClose:Xie,LucidePanelBottomDashed:Y5,LucidePanelBottomInactive:Y5,LucidePanelBottomOpen:Jie,LucidePanelLeft:J5,LucidePanelLeftClose:Z5,LucidePanelLeftDashed:Q5,LucidePanelLeftInactive:Q5,LucidePanelLeftOpen:X5,LucidePanelRight:noe,LucidePanelRightClose:toe,LucidePanelRightDashed:eT,LucidePanelRightInactive:eT,LucidePanelRightOpen:soe,LucidePanelTop:ioe,LucidePanelTopClose:roe,LucidePanelTopDashed:tT,LucidePanelTopInactive:tT,LucidePanelTopOpen:aoe,LucidePanelsLeftBottom:ooe,LucidePanelsLeftRight:b5,LucidePanelsRightBottom:loe,LucidePanelsTopBottom:iT,LucidePanelsTopLeft:k2,LucidePaperclip:YS,LucideParentheses:coe,LucideParkingCircle:i5,LucideParkingCircleOff:a5,LucideParkingMeter:doe,LucideParkingSquare:GT,LucideParkingSquareOff:HT,LucidePartyPopper:ih,LucidePause:gf,LucidePauseCircle:o5,LucidePauseOctagon:G5,LucidePawPrint:uoe,LucidePcCase:hoe,LucidePen:_v,LucidePenBox:wu,LucidePenLine:J1,LucidePenOff:moe,LucidePenSquare:wu,LucidePenTool:ZS,LucidePencil:ya,LucidePencilLine:i9,LucidePencilOff:poe,LucidePencilRuler:foe,LucidePentagon:xoe,LucidePercent:QS,LucidePercentCircle:l5,LucidePercentDiamond:w5,LucidePercentSquare:WT,LucidePersonStanding:goe,LucidePhilippinePeso:yoe,LucidePhone:Cr,LucidePhoneCall:voe,LucidePhoneForwarded:boe,LucidePhoneIncoming:_oe,LucidePhoneMissed:woe,LucidePhoneOff:joe,LucidePhoneOutgoing:Noe,LucidePi:koe,LucidePiSquare:KT,LucidePiano:Soe,LucidePickaxe:Coe,LucidePictureInPicture:Eoe,LucidePictureInPicture2:Toe,LucidePieChart:U3,LucidePiggyBank:Aoe,LucidePilcrow:Poe,LucidePilcrowLeft:Moe,LucidePilcrowRight:Ioe,LucidePilcrowSquare:YT,LucidePill:Doe,LucidePillBottle:Loe,LucidePin:XS,LucidePinOff:o9,LucidePipette:Roe,LucidePizza:Ooe,LucidePlane:l9,LucidePlaneLanding:Foe,LucidePlaneTakeoff:zoe,LucidePlay:El,LucidePlayCircle:jh,LucidePlaySquare:ZT,LucidePlug:Y2,LucidePlug2:Boe,LucidePlugZap:sT,LucidePlugZap2:sT,LucidePlus:Is,LucidePlusCircle:c5,LucidePlusSquare:QT,LucidePocket:Uoe,LucidePocketKnife:$oe,LucidePodcast:qoe,LucidePointer:Hoe,LucidePointerOff:Voe,LucidePopcorn:Goe,LucidePopsicle:Woe,LucidePoundSterling:Koe,LucidePower:c9,LucidePowerCircle:d5,LucidePowerOff:Yoe,LucidePowerSquare:XT,LucidePresentation:ny,LucidePrinter:d9,LucidePrinterCheck:Zoe,LucideProjector:Qoe,LucideProportions:Xoe,LucidePuzzle:Joe,LucidePyramid:ele,LucideQrCode:ry,LucideQuote:gw,LucideRabbit:tle,LucideRadar:IA,LucideRadiation:sle,LucideRadical:nle,LucideRadio:yf,LucideRadioReceiver:rle,LucideRadioTower:ale,LucideRadius:ile,LucideRailSymbol:ole,LucideRainbow:lle,LucideRat:cle,LucideRatio:dle,LucideReceipt:vle,LucideReceiptCent:ule,LucideReceiptEuro:hle,LucideReceiptIndianRupee:mle,LucideReceiptJapaneseYen:ple,LucideReceiptPoundSterling:fle,LucideReceiptRussianRuble:xle,LucideReceiptSwissFranc:gle,LucideReceiptText:yle,LucideRectangleEllipsis:nT,LucideRectangleHorizontal:ble,LucideRectangleVertical:_le,LucideRecycle:wle,LucideRedo:JS,LucideRedo2:jle,LucideRedoDot:Nle,LucideRefreshCcw:dL,LucideRefreshCcwDot:kle,LucideRefreshCw:Ei,LucideRefreshCwOff:Sle,LucideRefrigerator:Cle,LucideRegex:Tle,LucideRemoveFormatting:Ele,LucideRepeat:u9,LucideRepeat1:Ale,LucideRepeat2:Mle,LucideReplace:Ple,LucideReplaceAll:Ile,LucideReply:h9,LucideReplyAll:Lle,LucideRewind:Dle,LucideRibbon:Rle,LucideRocket:tx,LucideRockingChair:Ole,LucideRollerCoaster:Fle,LucideRotate3D:rT,LucideRotate3d:rT,LucideRotateCcw:Bm,LucideRotateCcwSquare:zle,LucideRotateCw:PA,LucideRotateCwSquare:Ble,LucideRoute:m9,LucideRouteOff:$le,LucideRouter:Ule,LucideRows:aT,LucideRows2:aT,LucideRows3:iT,LucideRows4:qle,LucideRss:Vle,LucideRuler:Z2,LucideRussianRuble:Hle,LucideSailboat:Gle,LucideSalad:Wle,LucideSandwich:Kle,LucideSatellite:Zle,LucideSatelliteDish:Yle,LucideSave:Jo,LucideSaveAll:Qle,LucideSaveOff:Xle,LucideScale:p9,LucideScale3D:oT,LucideScale3d:oT,LucideScaling:Jle,LucideScan:oce,LucideScanBarcode:ece,LucideScanEye:tce,LucideScanFace:sce,LucideScanLine:nce,LucideScanQrCode:rce,LucideScanSearch:ace,LucideScanText:ice,LucideScatterChart:q3,LucideSchool:lce,LucideSchool2:mE,LucideScissors:dce,LucideScissorsLineDashed:cce,LucideScissorsSquare:JT,LucideScissorsSquareDashedBottom:kT,LucideScreenShare:hce,LucideScreenShareOff:uce,LucideScroll:mce,LucideScrollText:f9,LucideSearch:gr,LucideSearchCheck:pce,LucideSearchCode:fce,LucideSearchSlash:xce,LucideSearchX:x9,LucideSection:gce,LucideSend:lr,LucideSendHorizonal:lT,LucideSendHorizontal:lT,LucideSendToBack:yce,LucideSeparatorHorizontal:vce,LucideSeparatorVertical:bce,LucideServer:Nce,LucideServerCog:_ce,LucideServerCrash:wce,LucideServerOff:jce,LucideSettings:Ko,LucideSettings2:g9,LucideShapes:kce,LucideShare:y9,LucideShare2:Vl,LucideSheet:Sce,LucideShell:Cce,LucideShield:Ih,LucideShieldAlert:uL,LucideShieldBan:Tce,LucideShieldCheck:eg,LucideShieldClose:cT,LucideShieldEllipsis:Ece,LucideShieldHalf:Ace,LucideShieldMinus:Mce,LucideShieldOff:LA,LucideShieldPlus:Ice,LucideShieldQuestion:Pce,LucideShieldX:cT,LucideShip:Dce,LucideShipWheel:Lce,LucideShirt:Rce,LucideShoppingBag:yw,LucideShoppingBasket:Oce,LucideShoppingCart:Dg,LucideShovel:Fce,LucideShowerHead:zce,LucideShrink:Bce,LucideShrub:$ce,LucideShuffle:DA,LucideSidebar:J5,LucideSidebarClose:Z5,LucideSidebarOpen:X5,LucideSigma:Uce,LucideSigmaSquare:eE,LucideSignal:Wce,LucideSignalHigh:qce,LucideSignalLow:Vce,LucideSignalMedium:Hce,LucideSignalZero:Gce,LucideSignature:Kce,LucideSignpost:Zce,LucideSignpostBig:Yce,LucideSiren:Qce,LucideSkipBack:Xce,LucideSkipForward:Jce,LucideSkull:ede,LucideSlack:tde,LucideSlash:sde,LucideSlashSquare:tE,LucideSlice:nde,LucideSliders:dT,LucideSlidersHorizontal:e4,LucideSlidersVertical:dT,LucideSmartphone:tg,LucideSmartphoneCharging:rde,LucideSmartphoneNfc:ade,LucideSmile:ode,LucideSmilePlus:ide,LucideSnail:lde,LucideSnowflake:Tv,LucideSofa:cde,LucideSortAsc:j3,LucideSortDesc:b3,LucideSoup:dde,LucideSpace:ude,LucideSpade:hde,LucideSparkle:t4,LucideSparkles:un,LucideSpeaker:mde,LucideSpeech:pde,LucideSpellCheck:xde,LucideSpellCheck2:fde,LucideSpline:gde,LucideSplit:yde,LucideSplitSquareHorizontal:sE,LucideSplitSquareVertical:nE,LucideSprayCan:vde,LucideSprout:RA,LucideSquare:ay,LucideSquareActivity:uT,LucideSquareArrowDown:pT,LucideSquareArrowDownLeft:hT,LucideSquareArrowDownRight:mT,LucideSquareArrowLeft:fT,LucideSquareArrowOutDownLeft:xT,LucideSquareArrowOutDownRight:gT,LucideSquareArrowOutUpLeft:yT,LucideSquareArrowOutUpRight:vT,LucideSquareArrowRight:bT,LucideSquareArrowUp:jT,LucideSquareArrowUpLeft:_T,LucideSquareArrowUpRight:wT,LucideSquareAsterisk:NT,LucideSquareBottomDashedScissors:kT,LucideSquareChartGantt:A_,LucideSquareCheck:ST,LucideSquareCheckBig:S2,LucideSquareChevronDown:CT,LucideSquareChevronLeft:TT,LucideSquareChevronRight:ET,LucideSquareChevronUp:AT,LucideSquareCode:MT,LucideSquareDashed:LT,LucideSquareDashedBottom:_de,LucideSquareDashedBottomCode:bde,LucideSquareDashedKanban:IT,LucideSquareDashedMousePointer:PT,LucideSquareDivide:DT,LucideSquareDot:RT,LucideSquareEqual:OT,LucideSquareFunction:FT,LucideSquareGanttChart:A_,LucideSquareKanban:zT,LucideSquareLibrary:BT,LucideSquareM:$T,LucideSquareMenu:UT,LucideSquareMinus:qT,LucideSquareMousePointer:VT,LucideSquareParking:GT,LucideSquareParkingOff:HT,LucideSquarePen:wu,LucideSquarePercent:WT,LucideSquarePi:KT,LucideSquarePilcrow:YT,LucideSquarePlay:ZT,LucideSquarePlus:QT,LucideSquarePower:XT,LucideSquareRadical:wde,LucideSquareScissors:JT,LucideSquareSigma:eE,LucideSquareSlash:tE,LucideSquareSplitHorizontal:sE,LucideSquareSplitVertical:nE,LucideSquareSquare:jde,LucideSquareStack:Nde,LucideSquareTerminal:rE,LucideSquareUser:iE,LucideSquareUserRound:aE,LucideSquareX:oE,LucideSquircle:kde,LucideSquirrel:Sde,LucideStamp:Cde,LucideStar:oa,LucideStarHalf:Tde,LucideStarOff:Ede,LucideStars:un,LucideStepBack:Ade,LucideStepForward:Mde,LucideStethoscope:Ide,LucideSticker:Pde,LucideStickyNote:v9,LucideStopCircle:h5,LucideStore:b9,LucideStretchHorizontal:Lde,LucideStretchVertical:Dde,LucideStrikethrough:_9,LucideSubscript:Rde,LucideSubtitles:M3,LucideSun:pb,LucideSunDim:Ode,LucideSunMedium:Fde,LucideSunMoon:zde,LucideSunSnow:Bde,LucideSunrise:$de,LucideSunset:Ude,LucideSuperscript:qde,LucideSwatchBook:Vde,LucideSwissFranc:Hde,LucideSwitchCamera:Gde,LucideSword:Wde,LucideSwords:Kde,LucideSyringe:Yde,LucideTable:mL,LucideTable2:hL,LucideTableCellsMerge:Zde,LucideTableCellsSplit:Qde,LucideTableColumnsSplit:Xde,LucideTableOfContents:Jde,LucideTableProperties:eue,LucideTableRowsSplit:tue,LucideTablet:pL,LucideTabletSmartphone:sue,LucideTablets:nue,LucideTag:oh,LucideTags:w9,LucideTally1:rue,LucideTally2:aue,LucideTally3:iue,LucideTally4:oue,LucideTally5:lue,LucideTangent:cue,LucideTarget:Ac,LucideTelescope:due,LucideTent:hue,LucideTentTree:uue,LucideTerminal:mue,LucideTerminalSquare:rE,LucideTestTube:pue,LucideTestTube2:lE,LucideTestTubeDiagonal:lE,LucideTestTubes:fue,LucideText:bue,LucideTextCursor:gue,LucideTextCursorInput:xue,LucideTextQuote:yue,LucideTextSearch:vue,LucideTextSelect:cE,LucideTextSelection:cE,LucideTheater:_ue,LucideThermometer:j9,LucideThermometerSnowflake:wue,LucideThermometerSun:jue,LucideThumbsDown:N9,LucideThumbsUp:$m,LucideTicket:k9,LucideTicketCheck:Nue,LucideTicketMinus:kue,LucideTicketPercent:Sue,LucideTicketPlus:Cue,LucideTicketSlash:Tue,LucideTicketX:Eue,LucideTickets:Mue,LucideTicketsPlane:Aue,LucideTimer:Lue,LucideTimerOff:Iue,LucideTimerReset:Pue,LucideToggleLeft:Due,LucideToggleRight:Rue,LucideToilet:Oue,LucideTornado:Fue,LucideTorus:zue,LucideTouchpad:$ue,LucideTouchpadOff:Bue,LucideTowerControl:Uue,LucideToyBrick:que,LucideTractor:Vue,LucideTrafficCone:Hue,LucideTrain:dE,LucideTrainFront:Wue,LucideTrainFrontTunnel:Gue,LucideTrainTrack:Kue,LucideTramFront:dE,LucideTrash:Yue,LucideTrash2:_n,LucideTreeDeciduous:Zue,LucideTreePalm:uE,LucideTreePine:s4,LucideTrees:Que,LucideTrello:Xue,LucideTrendingDown:fb,LucideTrendingUp:go,LucideTrendingUpDown:Jue,LucideTriangle:the,LucideTriangleAlert:ic,LucideTriangleRight:ehe,LucideTrophy:xo,LucideTruck:S9,LucideTurtle:she,LucideTv:rhe,LucideTv2:hE,LucideTvMinimal:hE,LucideTvMinimalPlay:nhe,LucideTwitch:ahe,LucideTwitter:ihe,LucideType:lhe,LucideTypeOutline:ohe,LucideUmbrella:dhe,LucideUmbrellaOff:che,LucideUnderline:fL,LucideUndo:n4,LucideUndo2:uhe,LucideUndoDot:hhe,LucideUnfoldHorizontal:mhe,LucideUnfoldVertical:phe,LucideUngroup:fhe,LucideUniversity:mE,LucideUnlink:OA,LucideUnlink2:xhe,LucideUnlock:q5,LucideUnlockKeyhole:U5,LucideUnplug:ghe,LucideUpload:_a,LucideUploadCloud:y5,LucideUsb:yhe,LucideUser:Wi,LucideUser2:vE,LucideUserCheck:xb,LucideUserCheck2:pE,LucideUserCircle:p5,LucideUserCircle2:m5,LucideUserCog:C9,LucideUserCog2:fE,LucideUserMinus:T9,LucideUserMinus2:xE,LucideUserPen:vhe,LucideUserPlus:Fo,LucideUserPlus2:gE,LucideUserRound:vE,LucideUserRoundCheck:pE,LucideUserRoundCog:fE,LucideUserRoundMinus:xE,LucideUserRoundPen:bhe,LucideUserRoundPlus:gE,LucideUserRoundSearch:_he,LucideUserRoundX:yE,LucideUserSearch:whe,LucideUserSquare:iE,LucideUserSquare2:aE,LucideUserX:jhe,LucideUserX2:yE,LucideUsers:An,LucideUsers2:q0,LucideUsersRound:q0,LucideUtensils:_E,LucideUtensilsCrossed:bE,LucideUtilityPole:Nhe,LucideVariable:xL,LucideVault:khe,LucideVegan:She,LucideVenetianMask:Che,LucideVerified:S3,LucideVibrate:Ehe,LucideVibrateOff:The,LucideVideo:fr,LucideVideoOff:Ahe,LucideVideotape:Mhe,LucideView:Ihe,LucideVoicemail:Phe,LucideVolleyball:Lhe,LucideVolume:Ohe,LucideVolume1:Dhe,LucideVolume2:E9,LucideVolumeOff:Rhe,LucideVolumeX:A9,LucideVote:Fhe,LucideWallet:gL,LucideWallet2:wE,LucideWalletCards:zhe,LucideWalletMinimal:wE,LucideWallpaper:Bhe,LucideWand:$he,LucideWand2:Im,LucideWandSparkles:Im,LucideWarehouse:Uhe,LucideWashingMachine:qhe,LucideWatch:Vhe,LucideWaves:Hhe,LucideWaypoints:Ghe,LucideWebcam:Whe,LucideWebhook:Yhe,LucideWebhookOff:Khe,LucideWeight:Zhe,LucideWheat:Xhe,LucideWheatOff:Qhe,LucideWholeWord:Jhe,LucideWifi:rme,LucideWifiHigh:eme,LucideWifiLow:tme,LucideWifiOff:sme,LucideWifiZero:nme,LucideWind:ime,LucideWindArrowDown:ame,LucideWine:M9,LucideWineOff:ome,LucideWorkflow:I9,LucideWorm:lme,LucideWrapText:cme,LucideWrench:gb,LucideX:$n,LucideXCircle:Uc,LucideXOctagon:W5,LucideXSquare:oE,LucideYoutube:dme,LucideZap:im,LucideZapOff:ume,LucideZoomIn:r4,LucideZoomOut:yL,Luggage:Gre,LuggageIcon:Gre,MSquare:$T,MSquareIcon:$T,Magnet:Wre,MagnetIcon:Wre,Mail:Gs,MailCheck:sL,MailCheckIcon:sL,MailIcon:Gs,MailMinus:Kre,MailMinusIcon:Kre,MailOpen:nL,MailOpenIcon:nL,MailPlus:e9,MailPlusIcon:e9,MailQuestion:Yre,MailQuestionIcon:Yre,MailSearch:Zre,MailSearchIcon:Zre,MailWarning:Qre,MailWarningIcon:Qre,MailX:rL,MailXIcon:rL,Mailbox:Xre,MailboxIcon:Xre,Mails:Jre,MailsIcon:Jre,Map:EA,MapIcon:EA,MapPin:ka,MapPinCheck:tae,MapPinCheckIcon:tae,MapPinCheckInside:eae,MapPinCheckInsideIcon:eae,MapPinHouse:sae,MapPinHouseIcon:sae,MapPinIcon:ka,MapPinMinus:rae,MapPinMinusIcon:rae,MapPinMinusInside:nae,MapPinMinusInsideIcon:nae,MapPinOff:aae,MapPinOffIcon:aae,MapPinPlus:oae,MapPinPlusIcon:oae,MapPinPlusInside:iae,MapPinPlusInsideIcon:iae,MapPinX:cae,MapPinXIcon:cae,MapPinXInside:lae,MapPinXInsideIcon:lae,MapPinned:dae,MapPinnedIcon:dae,Martini:uae,MartiniIcon:uae,Maximize:AA,Maximize2:t9,Maximize2Icon:t9,MaximizeIcon:AA,Medal:K2,MedalIcon:K2,Megaphone:zd,MegaphoneIcon:zd,MegaphoneOff:hae,MegaphoneOffIcon:hae,Meh:mae,MehIcon:mae,MemoryStick:pae,MemoryStickIcon:pae,Menu:KS,MenuIcon:KS,MenuSquare:UT,MenuSquareIcon:UT,Merge:fae,MergeIcon:fae,MessageCircle:Zl,MessageCircleCode:xae,MessageCircleCodeIcon:xae,MessageCircleDashed:gae,MessageCircleDashedIcon:gae,MessageCircleHeart:aL,MessageCircleHeartIcon:aL,MessageCircleIcon:Zl,MessageCircleMore:yae,MessageCircleMoreIcon:yae,MessageCircleOff:vae,MessageCircleOffIcon:vae,MessageCirclePlus:bae,MessageCirclePlusIcon:bae,MessageCircleQuestion:s9,MessageCircleQuestionIcon:s9,MessageCircleReply:_ae,MessageCircleReplyIcon:_ae,MessageCircleWarning:wae,MessageCircleWarningIcon:wae,MessageCircleX:jae,MessageCircleXIcon:jae,MessageSquare:Ai,MessageSquareCode:Nae,MessageSquareCodeIcon:Nae,MessageSquareDashed:kae,MessageSquareDashedIcon:kae,MessageSquareDiff:Sae,MessageSquareDiffIcon:Sae,MessageSquareDot:Cae,MessageSquareDotIcon:Cae,MessageSquareHeart:iL,MessageSquareHeartIcon:iL,MessageSquareIcon:Ai,MessageSquareLock:Tae,MessageSquareLockIcon:Tae,MessageSquareMore:n9,MessageSquareMoreIcon:n9,MessageSquareOff:Eae,MessageSquareOffIcon:Eae,MessageSquarePlus:X_,MessageSquarePlusIcon:X_,MessageSquareQuote:xw,MessageSquareQuoteIcon:xw,MessageSquareReply:Aae,MessageSquareReplyIcon:Aae,MessageSquareShare:Mae,MessageSquareShareIcon:Mae,MessageSquareText:Iae,MessageSquareTextIcon:Iae,MessageSquareWarning:Pae,MessageSquareWarningIcon:Pae,MessageSquareX:Lae,MessageSquareXIcon:Lae,MessagesSquare:oL,MessagesSquareIcon:oL,Mic:Dv,Mic2:V5,Mic2Icon:V5,MicIcon:Dv,MicOff:Dae,MicOffIcon:Dae,MicVocal:V5,MicVocalIcon:V5,Microchip:Rae,MicrochipIcon:Rae,Microscope:Oae,MicroscopeIcon:Oae,Microwave:Fae,MicrowaveIcon:Fae,Milestone:zae,MilestoneIcon:zae,Milk:$ae,MilkIcon:$ae,MilkOff:Bae,MilkOffIcon:Bae,Minimize:qae,Minimize2:Uae,Minimize2Icon:Uae,MinimizeIcon:qae,Minus:hb,MinusCircle:r5,MinusCircleIcon:r5,MinusIcon:hb,MinusSquare:qT,MinusSquareIcon:qT,Monitor:mb,MonitorCheck:Vae,MonitorCheckIcon:Vae,MonitorCog:Hae,MonitorCogIcon:Hae,MonitorDot:Gae,MonitorDotIcon:Gae,MonitorDown:Wae,MonitorDownIcon:Wae,MonitorIcon:mb,MonitorOff:Kae,MonitorOffIcon:Kae,MonitorPause:Yae,MonitorPauseIcon:Yae,MonitorPlay:lL,MonitorPlayIcon:lL,MonitorSmartphone:Zae,MonitorSmartphoneIcon:Zae,MonitorSpeaker:Qae,MonitorSpeakerIcon:Qae,MonitorStop:Xae,MonitorStopIcon:Xae,MonitorUp:MA,MonitorUpIcon:MA,MonitorX:Jae,MonitorXIcon:Jae,Moon:tie,MoonIcon:tie,MoonStar:eie,MoonStarIcon:eie,MoreHorizontal:Kf,MoreHorizontalIcon:Kf,MoreVertical:Ag,MoreVerticalIcon:Ag,Mountain:nie,MountainIcon:nie,MountainSnow:sie,MountainSnowIcon:sie,Mouse:oie,MouseIcon:oie,MouseOff:rie,MouseOffIcon:rie,MousePointer:Lm,MousePointer2:aie,MousePointer2Icon:aie,MousePointerBan:iie,MousePointerBanIcon:iie,MousePointerClick:oc,MousePointerClickIcon:oc,MousePointerIcon:Lm,MousePointerSquareDashed:PT,MousePointerSquareDashedIcon:PT,Move:bie,Move3D:H5,Move3DIcon:H5,Move3d:H5,Move3dIcon:H5,MoveDiagonal:cie,MoveDiagonal2:lie,MoveDiagonal2Icon:lie,MoveDiagonalIcon:cie,MoveDown:hie,MoveDownIcon:hie,MoveDownLeft:die,MoveDownLeftIcon:die,MoveDownRight:uie,MoveDownRightIcon:uie,MoveHorizontal:mie,MoveHorizontalIcon:mie,MoveIcon:bie,MoveLeft:pie,MoveLeftIcon:pie,MoveRight:fie,MoveRightIcon:fie,MoveUp:yie,MoveUpIcon:yie,MoveUpLeft:xie,MoveUpLeftIcon:xie,MoveUpRight:gie,MoveUpRightIcon:gie,MoveVertical:vie,MoveVerticalIcon:vie,Music:cL,Music2:_ie,Music2Icon:_ie,Music3:wie,Music3Icon:wie,Music4:jie,Music4Icon:jie,MusicIcon:cL,Navigation:r9,Navigation2:kie,Navigation2Icon:kie,Navigation2Off:Nie,Navigation2OffIcon:Nie,NavigationIcon:r9,NavigationOff:Sie,NavigationOffIcon:Sie,Network:Cie,NetworkIcon:Cie,Newspaper:sy,NewspaperIcon:sy,Nfc:Tie,NfcIcon:Tie,Notebook:Iie,NotebookIcon:Iie,NotebookPen:Eie,NotebookPenIcon:Eie,NotebookTabs:Aie,NotebookTabsIcon:Aie,NotebookText:Mie,NotebookTextIcon:Mie,NotepadText:Lie,NotepadTextDashed:Pie,NotepadTextDashedIcon:Pie,NotepadTextIcon:Lie,Nut:Rie,NutIcon:Rie,NutOff:Die,NutOffIcon:Die,Octagon:Fie,OctagonAlert:V_,OctagonAlertIcon:V_,OctagonIcon:Fie,OctagonMinus:Oie,OctagonMinusIcon:Oie,OctagonPause:G5,OctagonPauseIcon:G5,OctagonX:W5,OctagonXIcon:W5,Omega:zie,OmegaIcon:zie,Option:Bie,OptionIcon:Bie,Orbit:$ie,OrbitIcon:$ie,Origami:Uie,OrigamiIcon:Uie,Outdent:z5,OutdentIcon:z5,Package:Ec,Package2:qie,Package2Icon:qie,PackageCheck:Vie,PackageCheckIcon:Vie,PackageIcon:Ec,PackageMinus:Hie,PackageMinusIcon:Hie,PackageOpen:Gie,PackageOpenIcon:Gie,PackagePlus:a9,PackagePlusIcon:a9,PackageSearch:Wie,PackageSearchIcon:Wie,PackageX:Kie,PackageXIcon:Kie,PaintBucket:Yie,PaintBucketIcon:Yie,PaintRoller:Zie,PaintRollerIcon:Zie,Paintbrush:Qie,Paintbrush2:K5,Paintbrush2Icon:K5,PaintbrushIcon:Qie,PaintbrushVertical:K5,PaintbrushVerticalIcon:K5,Palette:pl,PaletteIcon:pl,Palmtree:uE,PalmtreeIcon:uE,PanelBottom:eoe,PanelBottomClose:Xie,PanelBottomCloseIcon:Xie,PanelBottomDashed:Y5,PanelBottomDashedIcon:Y5,PanelBottomIcon:eoe,PanelBottomInactive:Y5,PanelBottomInactiveIcon:Y5,PanelBottomOpen:Jie,PanelBottomOpenIcon:Jie,PanelLeft:J5,PanelLeftClose:Z5,PanelLeftCloseIcon:Z5,PanelLeftDashed:Q5,PanelLeftDashedIcon:Q5,PanelLeftIcon:J5,PanelLeftInactive:Q5,PanelLeftInactiveIcon:Q5,PanelLeftOpen:X5,PanelLeftOpenIcon:X5,PanelRight:noe,PanelRightClose:toe,PanelRightCloseIcon:toe,PanelRightDashed:eT,PanelRightDashedIcon:eT,PanelRightIcon:noe,PanelRightInactive:eT,PanelRightInactiveIcon:eT,PanelRightOpen:soe,PanelRightOpenIcon:soe,PanelTop:ioe,PanelTopClose:roe,PanelTopCloseIcon:roe,PanelTopDashed:tT,PanelTopDashedIcon:tT,PanelTopIcon:ioe,PanelTopInactive:tT,PanelTopInactiveIcon:tT,PanelTopOpen:aoe,PanelTopOpenIcon:aoe,PanelsLeftBottom:ooe,PanelsLeftBottomIcon:ooe,PanelsLeftRight:b5,PanelsLeftRightIcon:b5,PanelsRightBottom:loe,PanelsRightBottomIcon:loe,PanelsTopBottom:iT,PanelsTopBottomIcon:iT,PanelsTopLeft:k2,PanelsTopLeftIcon:k2,Paperclip:YS,PaperclipIcon:YS,Parentheses:coe,ParenthesesIcon:coe,ParkingCircle:i5,ParkingCircleIcon:i5,ParkingCircleOff:a5,ParkingCircleOffIcon:a5,ParkingMeter:doe,ParkingMeterIcon:doe,ParkingSquare:GT,ParkingSquareIcon:GT,ParkingSquareOff:HT,ParkingSquareOffIcon:HT,PartyPopper:ih,PartyPopperIcon:ih,Pause:gf,PauseCircle:o5,PauseCircleIcon:o5,PauseIcon:gf,PauseOctagon:G5,PauseOctagonIcon:G5,PawPrint:uoe,PawPrintIcon:uoe,PcCase:hoe,PcCaseIcon:hoe,Pen:_v,PenBox:wu,PenBoxIcon:wu,PenIcon:_v,PenLine:J1,PenLineIcon:J1,PenOff:moe,PenOffIcon:moe,PenSquare:wu,PenSquareIcon:wu,PenTool:ZS,PenToolIcon:ZS,Pencil:ya,PencilIcon:ya,PencilLine:i9,PencilLineIcon:i9,PencilOff:poe,PencilOffIcon:poe,PencilRuler:foe,PencilRulerIcon:foe,Pentagon:xoe,PentagonIcon:xoe,Percent:QS,PercentCircle:l5,PercentCircleIcon:l5,PercentDiamond:w5,PercentDiamondIcon:w5,PercentIcon:QS,PercentSquare:WT,PercentSquareIcon:WT,PersonStanding:goe,PersonStandingIcon:goe,PhilippinePeso:yoe,PhilippinePesoIcon:yoe,Phone:Cr,PhoneCall:voe,PhoneCallIcon:voe,PhoneForwarded:boe,PhoneForwardedIcon:boe,PhoneIcon:Cr,PhoneIncoming:_oe,PhoneIncomingIcon:_oe,PhoneMissed:woe,PhoneMissedIcon:woe,PhoneOff:joe,PhoneOffIcon:joe,PhoneOutgoing:Noe,PhoneOutgoingIcon:Noe,Pi:koe,PiIcon:koe,PiSquare:KT,PiSquareIcon:KT,Piano:Soe,PianoIcon:Soe,Pickaxe:Coe,PickaxeIcon:Coe,PictureInPicture:Eoe,PictureInPicture2:Toe,PictureInPicture2Icon:Toe,PictureInPictureIcon:Eoe,PieChart:U3,PieChartIcon:U3,PiggyBank:Aoe,PiggyBankIcon:Aoe,Pilcrow:Poe,PilcrowIcon:Poe,PilcrowLeft:Moe,PilcrowLeftIcon:Moe,PilcrowRight:Ioe,PilcrowRightIcon:Ioe,PilcrowSquare:YT,PilcrowSquareIcon:YT,Pill:Doe,PillBottle:Loe,PillBottleIcon:Loe,PillIcon:Doe,Pin:XS,PinIcon:XS,PinOff:o9,PinOffIcon:o9,Pipette:Roe,PipetteIcon:Roe,Pizza:Ooe,PizzaIcon:Ooe,Plane:l9,PlaneIcon:l9,PlaneLanding:Foe,PlaneLandingIcon:Foe,PlaneTakeoff:zoe,PlaneTakeoffIcon:zoe,Play:El,PlayCircle:jh,PlayCircleIcon:jh,PlayIcon:El,PlaySquare:ZT,PlaySquareIcon:ZT,Plug:Y2,Plug2:Boe,Plug2Icon:Boe,PlugIcon:Y2,PlugZap:sT,PlugZap2:sT,PlugZap2Icon:sT,PlugZapIcon:sT,Plus:Is,PlusCircle:c5,PlusCircleIcon:c5,PlusIcon:Is,PlusSquare:QT,PlusSquareIcon:QT,Pocket:Uoe,PocketIcon:Uoe,PocketKnife:$oe,PocketKnifeIcon:$oe,Podcast:qoe,PodcastIcon:qoe,Pointer:Hoe,PointerIcon:Hoe,PointerOff:Voe,PointerOffIcon:Voe,Popcorn:Goe,PopcornIcon:Goe,Popsicle:Woe,PopsicleIcon:Woe,PoundSterling:Koe,PoundSterlingIcon:Koe,Power:c9,PowerCircle:d5,PowerCircleIcon:d5,PowerIcon:c9,PowerOff:Yoe,PowerOffIcon:Yoe,PowerSquare:XT,PowerSquareIcon:XT,Presentation:ny,PresentationIcon:ny,Printer:d9,PrinterCheck:Zoe,PrinterCheckIcon:Zoe,PrinterIcon:d9,Projector:Qoe,ProjectorIcon:Qoe,Proportions:Xoe,ProportionsIcon:Xoe,Puzzle:Joe,PuzzleIcon:Joe,Pyramid:ele,PyramidIcon:ele,QrCode:ry,QrCodeIcon:ry,Quote:gw,QuoteIcon:gw,Rabbit:tle,RabbitIcon:tle,Radar:IA,RadarIcon:IA,Radiation:sle,RadiationIcon:sle,Radical:nle,RadicalIcon:nle,Radio:yf,RadioIcon:yf,RadioReceiver:rle,RadioReceiverIcon:rle,RadioTower:ale,RadioTowerIcon:ale,Radius:ile,RadiusIcon:ile,RailSymbol:ole,RailSymbolIcon:ole,Rainbow:lle,RainbowIcon:lle,Rat:cle,RatIcon:cle,Ratio:dle,RatioIcon:dle,Receipt:vle,ReceiptCent:ule,ReceiptCentIcon:ule,ReceiptEuro:hle,ReceiptEuroIcon:hle,ReceiptIcon:vle,ReceiptIndianRupee:mle,ReceiptIndianRupeeIcon:mle,ReceiptJapaneseYen:ple,ReceiptJapaneseYenIcon:ple,ReceiptPoundSterling:fle,ReceiptPoundSterlingIcon:fle,ReceiptRussianRuble:xle,ReceiptRussianRubleIcon:xle,ReceiptSwissFranc:gle,ReceiptSwissFrancIcon:gle,ReceiptText:yle,ReceiptTextIcon:yle,RectangleEllipsis:nT,RectangleEllipsisIcon:nT,RectangleHorizontal:ble,RectangleHorizontalIcon:ble,RectangleVertical:_le,RectangleVerticalIcon:_le,Recycle:wle,RecycleIcon:wle,Redo:JS,Redo2:jle,Redo2Icon:jle,RedoDot:Nle,RedoDotIcon:Nle,RedoIcon:JS,RefreshCcw:dL,RefreshCcwDot:kle,RefreshCcwDotIcon:kle,RefreshCcwIcon:dL,RefreshCw:Ei,RefreshCwIcon:Ei,RefreshCwOff:Sle,RefreshCwOffIcon:Sle,Refrigerator:Cle,RefrigeratorIcon:Cle,Regex:Tle,RegexIcon:Tle,RemoveFormatting:Ele,RemoveFormattingIcon:Ele,Repeat:u9,Repeat1:Ale,Repeat1Icon:Ale,Repeat2:Mle,Repeat2Icon:Mle,RepeatIcon:u9,Replace:Ple,ReplaceAll:Ile,ReplaceAllIcon:Ile,ReplaceIcon:Ple,Reply:h9,ReplyAll:Lle,ReplyAllIcon:Lle,ReplyIcon:h9,Rewind:Dle,RewindIcon:Dle,Ribbon:Rle,RibbonIcon:Rle,Rocket:tx,RocketIcon:tx,RockingChair:Ole,RockingChairIcon:Ole,RollerCoaster:Fle,RollerCoasterIcon:Fle,Rotate3D:rT,Rotate3DIcon:rT,Rotate3d:rT,Rotate3dIcon:rT,RotateCcw:Bm,RotateCcwIcon:Bm,RotateCcwSquare:zle,RotateCcwSquareIcon:zle,RotateCw:PA,RotateCwIcon:PA,RotateCwSquare:Ble,RotateCwSquareIcon:Ble,Route:m9,RouteIcon:m9,RouteOff:$le,RouteOffIcon:$le,Router:Ule,RouterIcon:Ule,Rows:aT,Rows2:aT,Rows2Icon:aT,Rows3:iT,Rows3Icon:iT,Rows4:qle,Rows4Icon:qle,RowsIcon:aT,Rss:Vle,RssIcon:Vle,Ruler:Z2,RulerIcon:Z2,RussianRuble:Hle,RussianRubleIcon:Hle,Sailboat:Gle,SailboatIcon:Gle,Salad:Wle,SaladIcon:Wle,Sandwich:Kle,SandwichIcon:Kle,Satellite:Zle,SatelliteDish:Yle,SatelliteDishIcon:Yle,SatelliteIcon:Zle,Save:Jo,SaveAll:Qle,SaveAllIcon:Qle,SaveIcon:Jo,SaveOff:Xle,SaveOffIcon:Xle,Scale:p9,Scale3D:oT,Scale3DIcon:oT,Scale3d:oT,Scale3dIcon:oT,ScaleIcon:p9,Scaling:Jle,ScalingIcon:Jle,Scan:oce,ScanBarcode:ece,ScanBarcodeIcon:ece,ScanEye:tce,ScanEyeIcon:tce,ScanFace:sce,ScanFaceIcon:sce,ScanIcon:oce,ScanLine:nce,ScanLineIcon:nce,ScanQrCode:rce,ScanQrCodeIcon:rce,ScanSearch:ace,ScanSearchIcon:ace,ScanText:ice,ScanTextIcon:ice,ScatterChart:q3,ScatterChartIcon:q3,School:lce,School2:mE,School2Icon:mE,SchoolIcon:lce,Scissors:dce,ScissorsIcon:dce,ScissorsLineDashed:cce,ScissorsLineDashedIcon:cce,ScissorsSquare:JT,ScissorsSquareDashedBottom:kT,ScissorsSquareDashedBottomIcon:kT,ScissorsSquareIcon:JT,ScreenShare:hce,ScreenShareIcon:hce,ScreenShareOff:uce,ScreenShareOffIcon:uce,Scroll:mce,ScrollIcon:mce,ScrollText:f9,ScrollTextIcon:f9,Search:gr,SearchCheck:pce,SearchCheckIcon:pce,SearchCode:fce,SearchCodeIcon:fce,SearchIcon:gr,SearchSlash:xce,SearchSlashIcon:xce,SearchX:x9,SearchXIcon:x9,Section:gce,SectionIcon:gce,Send:lr,SendHorizonal:lT,SendHorizonalIcon:lT,SendHorizontal:lT,SendHorizontalIcon:lT,SendIcon:lr,SendToBack:yce,SendToBackIcon:yce,SeparatorHorizontal:vce,SeparatorHorizontalIcon:vce,SeparatorVertical:bce,SeparatorVerticalIcon:bce,Server:Nce,ServerCog:_ce,ServerCogIcon:_ce,ServerCrash:wce,ServerCrashIcon:wce,ServerIcon:Nce,ServerOff:jce,ServerOffIcon:jce,Settings:Ko,Settings2:g9,Settings2Icon:g9,SettingsIcon:Ko,Shapes:kce,ShapesIcon:kce,Share:y9,Share2:Vl,Share2Icon:Vl,ShareIcon:y9,Sheet:Sce,SheetIcon:Sce,Shell:Cce,ShellIcon:Cce,Shield:Ih,ShieldAlert:uL,ShieldAlertIcon:uL,ShieldBan:Tce,ShieldBanIcon:Tce,ShieldCheck:eg,ShieldCheckIcon:eg,ShieldClose:cT,ShieldCloseIcon:cT,ShieldEllipsis:Ece,ShieldEllipsisIcon:Ece,ShieldHalf:Ace,ShieldHalfIcon:Ace,ShieldIcon:Ih,ShieldMinus:Mce,ShieldMinusIcon:Mce,ShieldOff:LA,ShieldOffIcon:LA,ShieldPlus:Ice,ShieldPlusIcon:Ice,ShieldQuestion:Pce,ShieldQuestionIcon:Pce,ShieldX:cT,ShieldXIcon:cT,Ship:Dce,ShipIcon:Dce,ShipWheel:Lce,ShipWheelIcon:Lce,Shirt:Rce,ShirtIcon:Rce,ShoppingBag:yw,ShoppingBagIcon:yw,ShoppingBasket:Oce,ShoppingBasketIcon:Oce,ShoppingCart:Dg,ShoppingCartIcon:Dg,Shovel:Fce,ShovelIcon:Fce,ShowerHead:zce,ShowerHeadIcon:zce,Shrink:Bce,ShrinkIcon:Bce,Shrub:$ce,ShrubIcon:$ce,Shuffle:DA,ShuffleIcon:DA,Sidebar:J5,SidebarClose:Z5,SidebarCloseIcon:Z5,SidebarIcon:J5,SidebarOpen:X5,SidebarOpenIcon:X5,Sigma:Uce,SigmaIcon:Uce,SigmaSquare:eE,SigmaSquareIcon:eE,Signal:Wce,SignalHigh:qce,SignalHighIcon:qce,SignalIcon:Wce,SignalLow:Vce,SignalLowIcon:Vce,SignalMedium:Hce,SignalMediumIcon:Hce,SignalZero:Gce,SignalZeroIcon:Gce,Signature:Kce,SignatureIcon:Kce,Signpost:Zce,SignpostBig:Yce,SignpostBigIcon:Yce,SignpostIcon:Zce,Siren:Qce,SirenIcon:Qce,SkipBack:Xce,SkipBackIcon:Xce,SkipForward:Jce,SkipForwardIcon:Jce,Skull:ede,SkullIcon:ede,Slack:tde,SlackIcon:tde,Slash:sde,SlashIcon:sde,SlashSquare:tE,SlashSquareIcon:tE,Slice:nde,SliceIcon:nde,Sliders:dT,SlidersHorizontal:e4,SlidersHorizontalIcon:e4,SlidersIcon:dT,SlidersVertical:dT,SlidersVerticalIcon:dT,Smartphone:tg,SmartphoneCharging:rde,SmartphoneChargingIcon:rde,SmartphoneIcon:tg,SmartphoneNfc:ade,SmartphoneNfcIcon:ade,Smile:ode,SmileIcon:ode,SmilePlus:ide,SmilePlusIcon:ide,Snail:lde,SnailIcon:lde,Snowflake:Tv,SnowflakeIcon:Tv,Sofa:cde,SofaIcon:cde,SortAsc:j3,SortAscIcon:j3,SortDesc:b3,SortDescIcon:b3,Soup:dde,SoupIcon:dde,Space:ude,SpaceIcon:ude,Spade:hde,SpadeIcon:hde,Sparkle:t4,SparkleIcon:t4,Sparkles:un,SparklesIcon:un,Speaker:mde,SpeakerIcon:mde,Speech:pde,SpeechIcon:pde,SpellCheck:xde,SpellCheck2:fde,SpellCheck2Icon:fde,SpellCheckIcon:xde,Spline:gde,SplineIcon:gde,Split:yde,SplitIcon:yde,SplitSquareHorizontal:sE,SplitSquareHorizontalIcon:sE,SplitSquareVertical:nE,SplitSquareVerticalIcon:nE,SprayCan:vde,SprayCanIcon:vde,Sprout:RA,SproutIcon:RA,Square:ay,SquareActivity:uT,SquareActivityIcon:uT,SquareArrowDown:pT,SquareArrowDownIcon:pT,SquareArrowDownLeft:hT,SquareArrowDownLeftIcon:hT,SquareArrowDownRight:mT,SquareArrowDownRightIcon:mT,SquareArrowLeft:fT,SquareArrowLeftIcon:fT,SquareArrowOutDownLeft:xT,SquareArrowOutDownLeftIcon:xT,SquareArrowOutDownRight:gT,SquareArrowOutDownRightIcon:gT,SquareArrowOutUpLeft:yT,SquareArrowOutUpLeftIcon:yT,SquareArrowOutUpRight:vT,SquareArrowOutUpRightIcon:vT,SquareArrowRight:bT,SquareArrowRightIcon:bT,SquareArrowUp:jT,SquareArrowUpIcon:jT,SquareArrowUpLeft:_T,SquareArrowUpLeftIcon:_T,SquareArrowUpRight:wT,SquareArrowUpRightIcon:wT,SquareAsterisk:NT,SquareAsteriskIcon:NT,SquareBottomDashedScissors:kT,SquareBottomDashedScissorsIcon:kT,SquareChartGantt:A_,SquareChartGanttIcon:A_,SquareCheck:ST,SquareCheckBig:S2,SquareCheckBigIcon:S2,SquareCheckIcon:ST,SquareChevronDown:CT,SquareChevronDownIcon:CT,SquareChevronLeft:TT,SquareChevronLeftIcon:TT,SquareChevronRight:ET,SquareChevronRightIcon:ET,SquareChevronUp:AT,SquareChevronUpIcon:AT,SquareCode:MT,SquareCodeIcon:MT,SquareDashed:LT,SquareDashedBottom:_de,SquareDashedBottomCode:bde,SquareDashedBottomCodeIcon:bde,SquareDashedBottomIcon:_de,SquareDashedIcon:LT,SquareDashedKanban:IT,SquareDashedKanbanIcon:IT,SquareDashedMousePointer:PT,SquareDashedMousePointerIcon:PT,SquareDivide:DT,SquareDivideIcon:DT,SquareDot:RT,SquareDotIcon:RT,SquareEqual:OT,SquareEqualIcon:OT,SquareFunction:FT,SquareFunctionIcon:FT,SquareGanttChart:A_,SquareGanttChartIcon:A_,SquareIcon:ay,SquareKanban:zT,SquareKanbanIcon:zT,SquareLibrary:BT,SquareLibraryIcon:BT,SquareM:$T,SquareMIcon:$T,SquareMenu:UT,SquareMenuIcon:UT,SquareMinus:qT,SquareMinusIcon:qT,SquareMousePointer:VT,SquareMousePointerIcon:VT,SquareParking:GT,SquareParkingIcon:GT,SquareParkingOff:HT,SquareParkingOffIcon:HT,SquarePen:wu,SquarePenIcon:wu,SquarePercent:WT,SquarePercentIcon:WT,SquarePi:KT,SquarePiIcon:KT,SquarePilcrow:YT,SquarePilcrowIcon:YT,SquarePlay:ZT,SquarePlayIcon:ZT,SquarePlus:QT,SquarePlusIcon:QT,SquarePower:XT,SquarePowerIcon:XT,SquareRadical:wde,SquareRadicalIcon:wde,SquareScissors:JT,SquareScissorsIcon:JT,SquareSigma:eE,SquareSigmaIcon:eE,SquareSlash:tE,SquareSlashIcon:tE,SquareSplitHorizontal:sE,SquareSplitHorizontalIcon:sE,SquareSplitVertical:nE,SquareSplitVerticalIcon:nE,SquareSquare:jde,SquareSquareIcon:jde,SquareStack:Nde,SquareStackIcon:Nde,SquareTerminal:rE,SquareTerminalIcon:rE,SquareUser:iE,SquareUserIcon:iE,SquareUserRound:aE,SquareUserRoundIcon:aE,SquareX:oE,SquareXIcon:oE,Squircle:kde,SquircleIcon:kde,Squirrel:Sde,SquirrelIcon:Sde,Stamp:Cde,StampIcon:Cde,Star:oa,StarHalf:Tde,StarHalfIcon:Tde,StarIcon:oa,StarOff:Ede,StarOffIcon:Ede,Stars:un,StarsIcon:un,StepBack:Ade,StepBackIcon:Ade,StepForward:Mde,StepForwardIcon:Mde,Stethoscope:Ide,StethoscopeIcon:Ide,Sticker:Pde,StickerIcon:Pde,StickyNote:v9,StickyNoteIcon:v9,StopCircle:h5,StopCircleIcon:h5,Store:b9,StoreIcon:b9,StretchHorizontal:Lde,StretchHorizontalIcon:Lde,StretchVertical:Dde,StretchVerticalIcon:Dde,Strikethrough:_9,StrikethroughIcon:_9,Subscript:Rde,SubscriptIcon:Rde,Subtitles:M3,SubtitlesIcon:M3,Sun:pb,SunDim:Ode,SunDimIcon:Ode,SunIcon:pb,SunMedium:Fde,SunMediumIcon:Fde,SunMoon:zde,SunMoonIcon:zde,SunSnow:Bde,SunSnowIcon:Bde,Sunrise:$de,SunriseIcon:$de,Sunset:Ude,SunsetIcon:Ude,Superscript:qde,SuperscriptIcon:qde,SwatchBook:Vde,SwatchBookIcon:Vde,SwissFranc:Hde,SwissFrancIcon:Hde,SwitchCamera:Gde,SwitchCameraIcon:Gde,Sword:Wde,SwordIcon:Wde,Swords:Kde,SwordsIcon:Kde,Syringe:Yde,SyringeIcon:Yde,Table:mL,Table2:hL,Table2Icon:hL,TableCellsMerge:Zde,TableCellsMergeIcon:Zde,TableCellsSplit:Qde,TableCellsSplitIcon:Qde,TableColumnsSplit:Xde,TableColumnsSplitIcon:Xde,TableIcon:mL,TableOfContents:Jde,TableOfContentsIcon:Jde,TableProperties:eue,TablePropertiesIcon:eue,TableRowsSplit:tue,TableRowsSplitIcon:tue,Tablet:pL,TabletIcon:pL,TabletSmartphone:sue,TabletSmartphoneIcon:sue,Tablets:nue,TabletsIcon:nue,Tag:oh,TagIcon:oh,Tags:w9,TagsIcon:w9,Tally1:rue,Tally1Icon:rue,Tally2:aue,Tally2Icon:aue,Tally3:iue,Tally3Icon:iue,Tally4:oue,Tally4Icon:oue,Tally5:lue,Tally5Icon:lue,Tangent:cue,TangentIcon:cue,Target:Ac,TargetIcon:Ac,Telescope:due,TelescopeIcon:due,Tent:hue,TentIcon:hue,TentTree:uue,TentTreeIcon:uue,Terminal:mue,TerminalIcon:mue,TerminalSquare:rE,TerminalSquareIcon:rE,TestTube:pue,TestTube2:lE,TestTube2Icon:lE,TestTubeDiagonal:lE,TestTubeDiagonalIcon:lE,TestTubeIcon:pue,TestTubes:fue,TestTubesIcon:fue,Text:bue,TextCursor:gue,TextCursorIcon:gue,TextCursorInput:xue,TextCursorInputIcon:xue,TextIcon:bue,TextQuote:yue,TextQuoteIcon:yue,TextSearch:vue,TextSearchIcon:vue,TextSelect:cE,TextSelectIcon:cE,TextSelection:cE,TextSelectionIcon:cE,Theater:_ue,TheaterIcon:_ue,Thermometer:j9,ThermometerIcon:j9,ThermometerSnowflake:wue,ThermometerSnowflakeIcon:wue,ThermometerSun:jue,ThermometerSunIcon:jue,ThumbsDown:N9,ThumbsDownIcon:N9,ThumbsUp:$m,ThumbsUpIcon:$m,Ticket:k9,TicketCheck:Nue,TicketCheckIcon:Nue,TicketIcon:k9,TicketMinus:kue,TicketMinusIcon:kue,TicketPercent:Sue,TicketPercentIcon:Sue,TicketPlus:Cue,TicketPlusIcon:Cue,TicketSlash:Tue,TicketSlashIcon:Tue,TicketX:Eue,TicketXIcon:Eue,Tickets:Mue,TicketsIcon:Mue,TicketsPlane:Aue,TicketsPlaneIcon:Aue,Timer:Lue,TimerIcon:Lue,TimerOff:Iue,TimerOffIcon:Iue,TimerReset:Pue,TimerResetIcon:Pue,ToggleLeft:Due,ToggleLeftIcon:Due,ToggleRight:Rue,ToggleRightIcon:Rue,Toilet:Oue,ToiletIcon:Oue,Tornado:Fue,TornadoIcon:Fue,Torus:zue,TorusIcon:zue,Touchpad:$ue,TouchpadIcon:$ue,TouchpadOff:Bue,TouchpadOffIcon:Bue,TowerControl:Uue,TowerControlIcon:Uue,ToyBrick:que,ToyBrickIcon:que,Tractor:Vue,TractorIcon:Vue,TrafficCone:Hue,TrafficConeIcon:Hue,Train:dE,TrainFront:Wue,TrainFrontIcon:Wue,TrainFrontTunnel:Gue,TrainFrontTunnelIcon:Gue,TrainIcon:dE,TrainTrack:Kue,TrainTrackIcon:Kue,TramFront:dE,TramFrontIcon:dE,Trash:Yue,Trash2:_n,Trash2Icon:_n,TrashIcon:Yue,TreeDeciduous:Zue,TreeDeciduousIcon:Zue,TreePalm:uE,TreePalmIcon:uE,TreePine:s4,TreePineIcon:s4,Trees:Que,TreesIcon:Que,Trello:Xue,TrelloIcon:Xue,TrendingDown:fb,TrendingDownIcon:fb,TrendingUp:go,TrendingUpDown:Jue,TrendingUpDownIcon:Jue,TrendingUpIcon:go,Triangle:the,TriangleAlert:ic,TriangleAlertIcon:ic,TriangleIcon:the,TriangleRight:ehe,TriangleRightIcon:ehe,Trophy:xo,TrophyIcon:xo,Truck:S9,TruckIcon:S9,Turtle:she,TurtleIcon:she,Tv:rhe,Tv2:hE,Tv2Icon:hE,TvIcon:rhe,TvMinimal:hE,TvMinimalIcon:hE,TvMinimalPlay:nhe,TvMinimalPlayIcon:nhe,Twitch:ahe,TwitchIcon:ahe,Twitter:ihe,TwitterIcon:ihe,Type:lhe,TypeIcon:lhe,TypeOutline:ohe,TypeOutlineIcon:ohe,Umbrella:dhe,UmbrellaIcon:dhe,UmbrellaOff:che,UmbrellaOffIcon:che,Underline:fL,UnderlineIcon:fL,Undo:n4,Undo2:uhe,Undo2Icon:uhe,UndoDot:hhe,UndoDotIcon:hhe,UndoIcon:n4,UnfoldHorizontal:mhe,UnfoldHorizontalIcon:mhe,UnfoldVertical:phe,UnfoldVerticalIcon:phe,Ungroup:fhe,UngroupIcon:fhe,University:mE,UniversityIcon:mE,Unlink:OA,Unlink2:xhe,Unlink2Icon:xhe,UnlinkIcon:OA,Unlock:q5,UnlockIcon:q5,UnlockKeyhole:U5,UnlockKeyholeIcon:U5,Unplug:ghe,UnplugIcon:ghe,Upload:_a,UploadCloud:y5,UploadCloudIcon:y5,UploadIcon:_a,Usb:yhe,UsbIcon:yhe,User:Wi,User2:vE,User2Icon:vE,UserCheck:xb,UserCheck2:pE,UserCheck2Icon:pE,UserCheckIcon:xb,UserCircle:p5,UserCircle2:m5,UserCircle2Icon:m5,UserCircleIcon:p5,UserCog:C9,UserCog2:fE,UserCog2Icon:fE,UserCogIcon:C9,UserIcon:Wi,UserMinus:T9,UserMinus2:xE,UserMinus2Icon:xE,UserMinusIcon:T9,UserPen:vhe,UserPenIcon:vhe,UserPlus:Fo,UserPlus2:gE,UserPlus2Icon:gE,UserPlusIcon:Fo,UserRound:vE,UserRoundCheck:pE,UserRoundCheckIcon:pE,UserRoundCog:fE,UserRoundCogIcon:fE,UserRoundIcon:vE,UserRoundMinus:xE,UserRoundMinusIcon:xE,UserRoundPen:bhe,UserRoundPenIcon:bhe,UserRoundPlus:gE,UserRoundPlusIcon:gE,UserRoundSearch:_he,UserRoundSearchIcon:_he,UserRoundX:yE,UserRoundXIcon:yE,UserSearch:whe,UserSearchIcon:whe,UserSquare:iE,UserSquare2:aE,UserSquare2Icon:aE,UserSquareIcon:iE,UserX:jhe,UserX2:yE,UserX2Icon:yE,UserXIcon:jhe,Users:An,Users2:q0,Users2Icon:q0,UsersIcon:An,UsersRound:q0,UsersRoundIcon:q0,Utensils:_E,UtensilsCrossed:bE,UtensilsCrossedIcon:bE,UtensilsIcon:_E,UtilityPole:Nhe,UtilityPoleIcon:Nhe,Variable:xL,VariableIcon:xL,Vault:khe,VaultIcon:khe,Vegan:She,VeganIcon:She,VenetianMask:Che,VenetianMaskIcon:Che,Verified:S3,VerifiedIcon:S3,Vibrate:Ehe,VibrateIcon:Ehe,VibrateOff:The,VibrateOffIcon:The,Video:fr,VideoIcon:fr,VideoOff:Ahe,VideoOffIcon:Ahe,Videotape:Mhe,VideotapeIcon:Mhe,View:Ihe,ViewIcon:Ihe,Voicemail:Phe,VoicemailIcon:Phe,Volleyball:Lhe,VolleyballIcon:Lhe,Volume:Ohe,Volume1:Dhe,Volume1Icon:Dhe,Volume2:E9,Volume2Icon:E9,VolumeIcon:Ohe,VolumeOff:Rhe,VolumeOffIcon:Rhe,VolumeX:A9,VolumeXIcon:A9,Vote:Fhe,VoteIcon:Fhe,Wallet:gL,Wallet2:wE,Wallet2Icon:wE,WalletCards:zhe,WalletCardsIcon:zhe,WalletIcon:gL,WalletMinimal:wE,WalletMinimalIcon:wE,Wallpaper:Bhe,WallpaperIcon:Bhe,Wand:$he,Wand2:Im,Wand2Icon:Im,WandIcon:$he,WandSparkles:Im,WandSparklesIcon:Im,Warehouse:Uhe,WarehouseIcon:Uhe,WashingMachine:qhe,WashingMachineIcon:qhe,Watch:Vhe,WatchIcon:Vhe,Waves:Hhe,WavesIcon:Hhe,Waypoints:Ghe,WaypointsIcon:Ghe,Webcam:Whe,WebcamIcon:Whe,Webhook:Yhe,WebhookIcon:Yhe,WebhookOff:Khe,WebhookOffIcon:Khe,Weight:Zhe,WeightIcon:Zhe,Wheat:Xhe,WheatIcon:Xhe,WheatOff:Qhe,WheatOffIcon:Qhe,WholeWord:Jhe,WholeWordIcon:Jhe,Wifi:rme,WifiHigh:eme,WifiHighIcon:eme,WifiIcon:rme,WifiLow:tme,WifiLowIcon:tme,WifiOff:sme,WifiOffIcon:sme,WifiZero:nme,WifiZeroIcon:nme,Wind:ime,WindArrowDown:ame,WindArrowDownIcon:ame,WindIcon:ime,Wine:M9,WineIcon:M9,WineOff:ome,WineOffIcon:ome,Workflow:I9,WorkflowIcon:I9,Worm:lme,WormIcon:lme,WrapText:cme,WrapTextIcon:cme,Wrench:gb,WrenchIcon:gb,X:$n,XCircle:Uc,XCircleIcon:Uc,XIcon:$n,XOctagon:W5,XOctagonIcon:W5,XSquare:oE,XSquareIcon:oE,Youtube:dme,YoutubeIcon:dme,Zap:im,ZapIcon:im,ZapOff:ume,ZapOffIcon:ume,ZoomIn:r4,ZoomInIcon:r4,ZoomOut:yL,ZoomOutIcon:yL,createLucideIcon:re,icons:pMt},Symbol.toStringTag,{value:"Module"})),HEe="-",fMt=s=>{const t=gMt(s),{conflictingClassGroups:n,conflictingClassGroupModifiers:r}=s;return{getClassGroupId:l=>{const o=l.split(HEe);return o[0]===""&&o.length!==1&&o.shift(),trt(o,t)||xMt(l)},getConflictingClassGroupIds:(l,o)=>{const c=n[l]||[];return o&&r[l]?[...c,...r[l]]:c}}},trt=(s,t)=>{var l;if(s.length===0)return t.classGroupId;const n=s[0],r=t.nextPart.get(n),a=r?trt(s.slice(1),r):void 0;if(a)return a;if(t.validators.length===0)return;const i=s.join(HEe);return(l=t.validators.find(({validator:o})=>o(i)))==null?void 0:l.classGroupId},C9e=/^\[(.+)\]$/,xMt=s=>{if(C9e.test(s)){const t=C9e.exec(s)[1],n=t==null?void 0:t.substring(0,t.indexOf(":"));if(n)return"arbitrary.."+n}},gMt=s=>{const{theme:t,prefix:n}=s,r={nextPart:new Map,validators:[]};return vMt(Object.entries(s.classGroups),n).forEach(([i,l])=>{ySe(l,r,i,t)}),r},ySe=(s,t,n,r)=>{s.forEach(a=>{if(typeof a=="string"){const i=a===""?t:T9e(t,a);i.classGroupId=n;return}if(typeof a=="function"){if(yMt(a)){ySe(a(r),t,n,r);return}t.validators.push({validator:a,classGroupId:n});return}Object.entries(a).forEach(([i,l])=>{ySe(l,T9e(t,i),n,r)})})},T9e=(s,t)=>{let n=s;return t.split(HEe).forEach(r=>{n.nextPart.has(r)||n.nextPart.set(r,{nextPart:new Map,validators:[]}),n=n.nextPart.get(r)}),n},yMt=s=>s.isThemeGetter,vMt=(s,t)=>t?s.map(([n,r])=>{const a=r.map(i=>typeof i=="string"?t+i:typeof i=="object"?Object.fromEntries(Object.entries(i).map(([l,o])=>[t+l,o])):i);return[n,a]}):s,bMt=s=>{if(s<1)return{get:()=>{},set:()=>{}};let t=0,n=new Map,r=new Map;const a=(i,l)=>{n.set(i,l),t++,t>s&&(t=0,r=n,n=new Map)};return{get(i){let l=n.get(i);if(l!==void 0)return l;if((l=r.get(i))!==void 0)return a(i,l),l},set(i,l){n.has(i)?n.set(i,l):a(i,l)}}},srt="!",_Mt=s=>{const{separator:t,experimentalParseClassName:n}=s,r=t.length===1,a=t[0],i=t.length,l=o=>{const c=[];let d=0,u=0,h;for(let v=0;vu?h-u:void 0;return{modifiers:c,hasImportantModifier:f,baseClassName:y,maybePostfixModifierPosition:_}};return n?o=>n({className:o,parseClassName:l}):l},wMt=s=>{if(s.length<=1)return s;const t=[];let n=[];return s.forEach(r=>{r[0]==="["?(t.push(...n.sort(),r),n=[]):n.push(r)}),t.push(...n.sort()),t},jMt=s=>({cache:bMt(s.cacheSize),parseClassName:_Mt(s),...fMt(s)}),NMt=/\s+/,kMt=(s,t)=>{const{parseClassName:n,getClassGroupId:r,getConflictingClassGroupIds:a}=t,i=[],l=s.trim().split(NMt);let o="";for(let c=l.length-1;c>=0;c-=1){const d=l[c],{modifiers:u,hasImportantModifier:h,baseClassName:p,maybePostfixModifierPosition:f}=n(d);let y=!!f,_=r(y?p.substring(0,f):p);if(!_){if(!y){o=d+(o.length>0?" "+o:o);continue}if(_=r(p),!_){o=d+(o.length>0?" "+o:o);continue}y=!1}const v=wMt(u).join(":"),j=h?v+srt:v,w=j+_;if(i.includes(w))continue;i.push(w);const S=a(_,y);for(let A=0;A0?" "+o:o)}return o};function SMt(){let s=0,t,n,r="";for(;s{if(typeof s=="string")return s;let t,n="";for(let r=0;rh(u),s());return n=jMt(d),r=n.cache.get,a=n.cache.set,i=o,o(c)}function o(c){const d=r(c);if(d)return d;const u=kMt(c,n);return a(c,u),u}return function(){return i(SMt.apply(null,arguments))}}const Ed=s=>{const t=n=>n[s]||[];return t.isThemeGetter=!0,t},rrt=/^\[(?:([a-z-]+):)?(.+)\]$/i,TMt=/^\d+\/\d+$/,EMt=new Set(["px","full","screen"]),AMt=/^(\d+(\.\d+)?)?(xs|sm|md|lg|xl)$/,MMt=/\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$/,IMt=/^(rgba?|hsla?|hwb|(ok)?(lab|lch))\(.+\)$/,PMt=/^(inset_)?-?((\d+)?\.?(\d+)[a-z]+|0)_-?((\d+)?\.?(\d+)[a-z]+|0)/,LMt=/^(url|image|image-set|cross-fade|element|(repeating-)?(linear|radial|conic)-gradient)\(.+\)$/,Jj=s=>vL(s)||EMt.has(s)||TMt.test(s),xk=s=>ND(s,"length",UMt),vL=s=>!!s&&!Number.isNaN(Number(s)),vwe=s=>ND(s,"number",vL),VO=s=>!!s&&Number.isInteger(Number(s)),DMt=s=>s.endsWith("%")&&vL(s.slice(0,-1)),Bo=s=>rrt.test(s),gk=s=>AMt.test(s),RMt=new Set(["length","size","percentage"]),OMt=s=>ND(s,RMt,art),FMt=s=>ND(s,"position",art),zMt=new Set(["image","url"]),BMt=s=>ND(s,zMt,VMt),$Mt=s=>ND(s,"",qMt),HO=()=>!0,ND=(s,t,n)=>{const r=rrt.exec(s);return r?r[1]?typeof t=="string"?r[1]===t:t.has(r[1]):n(r[2]):!1},UMt=s=>MMt.test(s)&&!IMt.test(s),art=()=>!1,qMt=s=>PMt.test(s),VMt=s=>LMt.test(s),HMt=()=>{const s=Ed("colors"),t=Ed("spacing"),n=Ed("blur"),r=Ed("brightness"),a=Ed("borderColor"),i=Ed("borderRadius"),l=Ed("borderSpacing"),o=Ed("borderWidth"),c=Ed("contrast"),d=Ed("grayscale"),u=Ed("hueRotate"),h=Ed("invert"),p=Ed("gap"),f=Ed("gradientColorStops"),y=Ed("gradientColorStopPositions"),_=Ed("inset"),v=Ed("margin"),j=Ed("opacity"),w=Ed("padding"),S=Ed("saturate"),A=Ed("scale"),E=Ed("sepia"),O=Ed("skew"),D=Ed("space"),I=Ed("translate"),F=()=>["auto","contain","none"],z=()=>["auto","hidden","clip","visible","scroll"],H=()=>["auto",Bo,t],Z=()=>[Bo,t],Y=()=>["",Jj,xk],W=()=>["auto",vL,Bo],ee=()=>["bottom","center","left","left-bottom","left-top","right","right-bottom","right-top","top"],se=()=>["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"],he=()=>["start","end","center","between","around","evenly","stretch"],ce=()=>["","0",Bo],me=()=>["auto","avoid","all","avoid-page","page","left","right","column"],le=()=>[vL,Bo];return{cacheSize:500,separator:":",theme:{colors:[HO],spacing:[Jj,xk],blur:["none","",gk,Bo],brightness:le(),borderColor:[s],borderRadius:["none","","full",gk,Bo],borderSpacing:Z(),borderWidth:Y(),contrast:le(),grayscale:ce(),hueRotate:le(),invert:ce(),gap:Z(),gradientColorStops:[s],gradientColorStopPositions:[DMt,xk],inset:H(),margin:H(),opacity:le(),padding:Z(),saturate:le(),scale:le(),sepia:ce(),skew:le(),space:Z(),translate:Z()},classGroups:{aspect:[{aspect:["auto","square","video",Bo]}],container:["container"],columns:[{columns:[gk]}],"break-after":[{"break-after":me()}],"break-before":[{"break-before":me()}],"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:[...ee(),Bo]}],overflow:[{overflow:z()}],"overflow-x":[{"overflow-x":z()}],"overflow-y":[{"overflow-y":z()}],overscroll:[{overscroll:F()}],"overscroll-x":[{"overscroll-x":F()}],"overscroll-y":[{"overscroll-y":F()}],position:["static","fixed","absolute","relative","sticky"],inset:[{inset:[_]}],"inset-x":[{"inset-x":[_]}],"inset-y":[{"inset-y":[_]}],start:[{start:[_]}],end:[{end:[_]}],top:[{top:[_]}],right:[{right:[_]}],bottom:[{bottom:[_]}],left:[{left:[_]}],visibility:["visible","invisible","collapse"],z:[{z:["auto",VO,Bo]}],basis:[{basis:H()}],"flex-direction":[{flex:["row","row-reverse","col","col-reverse"]}],"flex-wrap":[{flex:["wrap","wrap-reverse","nowrap"]}],flex:[{flex:["1","auto","initial","none",Bo]}],grow:[{grow:ce()}],shrink:[{shrink:ce()}],order:[{order:["first","last","none",VO,Bo]}],"grid-cols":[{"grid-cols":[HO]}],"col-start-end":[{col:["auto",{span:["full",VO,Bo]},Bo]}],"col-start":[{"col-start":W()}],"col-end":[{"col-end":W()}],"grid-rows":[{"grid-rows":[HO]}],"row-start-end":[{row:["auto",{span:[VO,Bo]},Bo]}],"row-start":[{"row-start":W()}],"row-end":[{"row-end":W()}],"grid-flow":[{"grid-flow":["row","col","dense","row-dense","col-dense"]}],"auto-cols":[{"auto-cols":["auto","min","max","fr",Bo]}],"auto-rows":[{"auto-rows":["auto","min","max","fr",Bo]}],gap:[{gap:[p]}],"gap-x":[{"gap-x":[p]}],"gap-y":[{"gap-y":[p]}],"justify-content":[{justify:["normal",...he()]}],"justify-items":[{"justify-items":["start","end","center","stretch"]}],"justify-self":[{"justify-self":["auto","start","end","center","stretch"]}],"align-content":[{content:["normal",...he(),"baseline"]}],"align-items":[{items:["start","end","center","baseline","stretch"]}],"align-self":[{self:["auto","start","end","center","stretch","baseline"]}],"place-content":[{"place-content":[...he(),"baseline"]}],"place-items":[{"place-items":["start","end","center","baseline","stretch"]}],"place-self":[{"place-self":["auto","start","end","center","stretch"]}],p:[{p:[w]}],px:[{px:[w]}],py:[{py:[w]}],ps:[{ps:[w]}],pe:[{pe:[w]}],pt:[{pt:[w]}],pr:[{pr:[w]}],pb:[{pb:[w]}],pl:[{pl:[w]}],m:[{m:[v]}],mx:[{mx:[v]}],my:[{my:[v]}],ms:[{ms:[v]}],me:[{me:[v]}],mt:[{mt:[v]}],mr:[{mr:[v]}],mb:[{mb:[v]}],ml:[{ml:[v]}],"space-x":[{"space-x":[D]}],"space-x-reverse":["space-x-reverse"],"space-y":[{"space-y":[D]}],"space-y-reverse":["space-y-reverse"],w:[{w:["auto","min","max","fit","svw","lvw","dvw",Bo,t]}],"min-w":[{"min-w":[Bo,t,"min","max","fit"]}],"max-w":[{"max-w":[Bo,t,"none","full","min","max","fit","prose",{screen:[gk]},gk]}],h:[{h:[Bo,t,"auto","min","max","fit","svh","lvh","dvh"]}],"min-h":[{"min-h":[Bo,t,"min","max","fit","svh","lvh","dvh"]}],"max-h":[{"max-h":[Bo,t,"min","max","fit","svh","lvh","dvh"]}],size:[{size:[Bo,t,"auto","min","max","fit"]}],"font-size":[{text:["base",gk,xk]}],"font-smoothing":["antialiased","subpixel-antialiased"],"font-style":["italic","not-italic"],"font-weight":[{font:["thin","extralight","light","normal","medium","semibold","bold","extrabold","black",vwe]}],"font-family":[{font:[HO]}],"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",Bo]}],"line-clamp":[{"line-clamp":["none",vL,vwe]}],leading:[{leading:["none","tight","snug","normal","relaxed","loose",Jj,Bo]}],"list-image":[{"list-image":["none",Bo]}],"list-style-type":[{list:["none","disc","decimal",Bo]}],"list-style-position":[{list:["inside","outside"]}],"placeholder-color":[{placeholder:[s]}],"placeholder-opacity":[{"placeholder-opacity":[j]}],"text-alignment":[{text:["left","center","right","justify","start","end"]}],"text-color":[{text:[s]}],"text-opacity":[{"text-opacity":[j]}],"text-decoration":["underline","overline","line-through","no-underline"],"text-decoration-style":[{decoration:[...se(),"wavy"]}],"text-decoration-thickness":[{decoration:["auto","from-font",Jj,xk]}],"underline-offset":[{"underline-offset":["auto",Jj,Bo]}],"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:Z()}],"vertical-align":[{align:["baseline","top","middle","bottom","text-top","text-bottom","sub","super",Bo]}],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",Bo]}],"bg-attachment":[{bg:["fixed","local","scroll"]}],"bg-clip":[{"bg-clip":["border","padding","content","text"]}],"bg-opacity":[{"bg-opacity":[j]}],"bg-origin":[{"bg-origin":["border","padding","content"]}],"bg-position":[{bg:[...ee(),FMt]}],"bg-repeat":[{bg:["no-repeat",{repeat:["","x","y","round","space"]}]}],"bg-size":[{bg:["auto","cover","contain",OMt]}],"bg-image":[{bg:["none",{"gradient-to":["t","tr","r","br","b","bl","l","tl"]},BMt]}],"bg-color":[{bg:[s]}],"gradient-from-pos":[{from:[y]}],"gradient-via-pos":[{via:[y]}],"gradient-to-pos":[{to:[y]}],"gradient-from":[{from:[f]}],"gradient-via":[{via:[f]}],"gradient-to":[{to:[f]}],rounded:[{rounded:[i]}],"rounded-s":[{"rounded-s":[i]}],"rounded-e":[{"rounded-e":[i]}],"rounded-t":[{"rounded-t":[i]}],"rounded-r":[{"rounded-r":[i]}],"rounded-b":[{"rounded-b":[i]}],"rounded-l":[{"rounded-l":[i]}],"rounded-ss":[{"rounded-ss":[i]}],"rounded-se":[{"rounded-se":[i]}],"rounded-ee":[{"rounded-ee":[i]}],"rounded-es":[{"rounded-es":[i]}],"rounded-tl":[{"rounded-tl":[i]}],"rounded-tr":[{"rounded-tr":[i]}],"rounded-br":[{"rounded-br":[i]}],"rounded-bl":[{"rounded-bl":[i]}],"border-w":[{border:[o]}],"border-w-x":[{"border-x":[o]}],"border-w-y":[{"border-y":[o]}],"border-w-s":[{"border-s":[o]}],"border-w-e":[{"border-e":[o]}],"border-w-t":[{"border-t":[o]}],"border-w-r":[{"border-r":[o]}],"border-w-b":[{"border-b":[o]}],"border-w-l":[{"border-l":[o]}],"border-opacity":[{"border-opacity":[j]}],"border-style":[{border:[...se(),"hidden"]}],"divide-x":[{"divide-x":[o]}],"divide-x-reverse":["divide-x-reverse"],"divide-y":[{"divide-y":[o]}],"divide-y-reverse":["divide-y-reverse"],"divide-opacity":[{"divide-opacity":[j]}],"divide-style":[{divide:se()}],"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:["",...se()]}],"outline-offset":[{"outline-offset":[Jj,Bo]}],"outline-w":[{outline:[Jj,xk]}],"outline-color":[{outline:[s]}],"ring-w":[{ring:Y()}],"ring-w-inset":["ring-inset"],"ring-color":[{ring:[s]}],"ring-opacity":[{"ring-opacity":[j]}],"ring-offset-w":[{"ring-offset":[Jj,xk]}],"ring-offset-color":[{"ring-offset":[s]}],shadow:[{shadow:["","inner","none",gk,$Mt]}],"shadow-color":[{shadow:[HO]}],opacity:[{opacity:[j]}],"mix-blend":[{"mix-blend":[...oe(),"plus-lighter","plus-darker"]}],"bg-blend":[{"bg-blend":oe()}],filter:[{filter:["","none"]}],blur:[{blur:[n]}],brightness:[{brightness:[r]}],contrast:[{contrast:[c]}],"drop-shadow":[{"drop-shadow":["","none",gk,Bo]}],grayscale:[{grayscale:[d]}],"hue-rotate":[{"hue-rotate":[u]}],invert:[{invert:[h]}],saturate:[{saturate:[S]}],sepia:[{sepia:[E]}],"backdrop-filter":[{"backdrop-filter":["","none"]}],"backdrop-blur":[{"backdrop-blur":[n]}],"backdrop-brightness":[{"backdrop-brightness":[r]}],"backdrop-contrast":[{"backdrop-contrast":[c]}],"backdrop-grayscale":[{"backdrop-grayscale":[d]}],"backdrop-hue-rotate":[{"backdrop-hue-rotate":[u]}],"backdrop-invert":[{"backdrop-invert":[h]}],"backdrop-opacity":[{"backdrop-opacity":[j]}],"backdrop-saturate":[{"backdrop-saturate":[S]}],"backdrop-sepia":[{"backdrop-sepia":[E]}],"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",Bo]}],duration:[{duration:le()}],ease:[{ease:["linear","in","out","in-out",Bo]}],delay:[{delay:le()}],animate:[{animate:["none","spin","ping","pulse","bounce",Bo]}],transform:[{transform:["","gpu","none"]}],scale:[{scale:[A]}],"scale-x":[{"scale-x":[A]}],"scale-y":[{"scale-y":[A]}],rotate:[{rotate:[VO,Bo]}],"translate-x":[{"translate-x":[I]}],"translate-y":[{"translate-y":[I]}],"skew-x":[{"skew-x":[O]}],"skew-y":[{"skew-y":[O]}],"transform-origin":[{origin:["center","top","top-right","right","bottom-right","bottom","bottom-left","left","top-left",Bo]}],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",Bo]}],"caret-color":[{caret:[s]}],"pointer-events":[{"pointer-events":["none","auto"]}],resize:[{resize:["none","y","x",""]}],"scroll-behavior":[{scroll:["auto","smooth"]}],"scroll-m":[{"scroll-m":Z()}],"scroll-mx":[{"scroll-mx":Z()}],"scroll-my":[{"scroll-my":Z()}],"scroll-ms":[{"scroll-ms":Z()}],"scroll-me":[{"scroll-me":Z()}],"scroll-mt":[{"scroll-mt":Z()}],"scroll-mr":[{"scroll-mr":Z()}],"scroll-mb":[{"scroll-mb":Z()}],"scroll-ml":[{"scroll-ml":Z()}],"scroll-p":[{"scroll-p":Z()}],"scroll-px":[{"scroll-px":Z()}],"scroll-py":[{"scroll-py":Z()}],"scroll-ps":[{"scroll-ps":Z()}],"scroll-pe":[{"scroll-pe":Z()}],"scroll-pt":[{"scroll-pt":Z()}],"scroll-pr":[{"scroll-pr":Z()}],"scroll-pb":[{"scroll-pb":Z()}],"scroll-pl":[{"scroll-pl":Z()}],"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",Bo]}],fill:[{fill:[s,"none"]}],"stroke-w":[{stroke:[Jj,xk,vwe]}],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"]}}},GMt=CMt(HMt);function Mt(...s){return GMt(So(s))}function jc(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 E9e(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric"}).format(t)}function qz(s){return s?s.replace(/<[^>]*>/g,""):""}const WMt=uMt,irt=N.forwardRef(({className:s,...t},n)=>e.jsx(Gnt,{ref:n,className:Mt("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}));irt.displayName=Gnt.displayName;const KMt=OM("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"}}),ort=N.forwardRef(({className:s,variant:t,...n},r)=>e.jsx(Wnt,{ref:r,className:Mt(KMt({variant:t}),s),...n}));ort.displayName=Wnt.displayName;const YMt=N.forwardRef(({className:s,...t},n)=>e.jsx(Znt,{ref:n,className:Mt("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}));YMt.displayName=Znt.displayName;const lrt=N.forwardRef(({className:s,...t},n)=>e.jsx(Qnt,{ref:n,className:Mt("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($n,{className:"h-4 w-4"})}));lrt.displayName=Qnt.displayName;const crt=N.forwardRef(({className:s,...t},n)=>e.jsx(Knt,{ref:n,className:Mt("text-sm font-semibold",s),...t}));crt.displayName=Knt.displayName;const drt=N.forwardRef(({className:s,...t},n)=>e.jsx(Ynt,{ref:n,className:Mt("text-sm opacity-90",s),...t}));drt.displayName=Ynt.displayName;function ZMt(){const{toasts:s}=Fa();return e.jsxs(WMt,{children:[s.map(function({id:t,title:n,description:r,action:a,...i}){return e.jsxs(ort,{...i,children:[e.jsxs("div",{className:"grid gap-1",children:[n&&e.jsx(crt,{children:n}),r&&e.jsx(drt,{children:r})]}),a,e.jsx(lrt,{})]},t)}),e.jsx(irt,{})]})}var A9e=["light","dark"],QMt="(prefers-color-scheme: dark)",XMt=N.createContext(void 0),JMt={setTheme:s=>{},themes:[]},e6t=()=>{var s;return(s=N.useContext(XMt))!=null?s:JMt};N.memo(({forcedTheme:s,storageKey:t,attribute:n,enableSystem:r,enableColorScheme:a,defaultTheme:i,value:l,attrs:o,nonce:c})=>{let d=i==="system",u=n==="class"?`var d=document.documentElement,c=d.classList;${`c.remove(${o.map(y=>`'${y}'`).join(",")})`};`:`var d=document.documentElement,n='${n}',s='setAttribute';`,h=a?A9e.includes(i)&&i?`if(e==='light'||e==='dark'||!e)d.style.colorScheme=e||'${i}'`:"if(e==='light'||e==='dark')d.style.colorScheme=e":"",p=(y,_=!1,v=!0)=>{let j=l?l[y]:y,w=_?y+"|| ''":`'${j}'`,S="";return a&&v&&!_&&A9e.includes(y)&&(S+=`d.style.colorScheme = '${y}';`),n==="class"?_||j?S+=`c.add(${w})`:S+="null":j&&(S+=`d[s](n,${w})`),S},f=s?`!function(){${u}${p(s)}}()`:r?`!function(){try{${u}var e=localStorage.getItem('${t}');if('system'===e||(!e&&${d})){var t='${QMt}',m=window.matchMedia(t);if(m.media!==t||m.matches){${p("dark")}}else{${p("light")}}}else if(e){${l?`var x=${JSON.stringify(l)};`:""}${p(l?"x[e]":"e",!0)}}${d?"":"else{"+p(i,!1,!1)+"}"}${h}}catch(e){}}()`:`!function(){try{${u}var e=localStorage.getItem('${t}');if(e){${l?`var x=${JSON.stringify(l)};`:""}${p(l?"x[e]":"e",!0)}}else{${p(i,!1,!1)};}${h}}catch(t){}}();`;return N.createElement("script",{nonce:c,dangerouslySetInnerHTML:{__html:f}})});var t6t=s=>{switch(s){case"success":return r6t;case"info":return i6t;case"warning":return a6t;case"error":return o6t;default:return null}},s6t=Array(12).fill(0),n6t=({visible:s,className:t})=>Ct.createElement("div",{className:["sonner-loading-wrapper",t].filter(Boolean).join(" "),"data-visible":s},Ct.createElement("div",{className:"sonner-spinner"},s6t.map((n,r)=>Ct.createElement("div",{className:"sonner-loading-bar",key:`spinner-bar-${r}`})))),r6t=Ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ct.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"})),a6t=Ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 24 24",fill:"currentColor",height:"20",width:"20"},Ct.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"})),i6t=Ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ct.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"})),o6t=Ct.createElement("svg",{xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 20 20",fill:"currentColor",height:"20",width:"20"},Ct.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"})),l6t=Ct.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"},Ct.createElement("line",{x1:"18",y1:"6",x2:"6",y2:"18"}),Ct.createElement("line",{x1:"6",y1:"6",x2:"18",y2:"18"})),c6t=()=>{let[s,t]=Ct.useState(document.hidden);return Ct.useEffect(()=>{let n=()=>{t(document.hidden)};return document.addEventListener("visibilitychange",n),()=>window.removeEventListener("visibilitychange",n)},[]),s},vSe=1,d6t=class{constructor(){this.subscribe=t=>(this.subscribers.push(t),()=>{let n=this.subscribers.indexOf(t);this.subscribers.splice(n,1)}),this.publish=t=>{this.subscribers.forEach(n=>n(t))},this.addToast=t=>{this.publish(t),this.toasts=[...this.toasts,t]},this.create=t=>{var n;let{message:r,...a}=t,i=typeof(t==null?void 0:t.id)=="number"||((n=t.id)==null?void 0:n.length)>0?t.id:vSe++,l=this.toasts.find(c=>c.id===i),o=t.dismissible===void 0?!0:t.dismissible;return this.dismissedToasts.has(i)&&this.dismissedToasts.delete(i),l?this.toasts=this.toasts.map(c=>c.id===i?(this.publish({...c,...t,id:i,title:r}),{...c,...t,id:i,dismissible:o,title:r}):c):this.addToast({title:r,...a,dismissible:o,id:i}),i},this.dismiss=t=>(this.dismissedToasts.add(t),t||this.toasts.forEach(n=>{this.subscribers.forEach(r=>r({id:n.id,dismiss:!0}))}),this.subscribers.forEach(n=>n({id:t,dismiss:!0})),t),this.message=(t,n)=>this.create({...n,message:t}),this.error=(t,n)=>this.create({...n,message:t,type:"error"}),this.success=(t,n)=>this.create({...n,type:"success",message:t}),this.info=(t,n)=>this.create({...n,type:"info",message:t}),this.warning=(t,n)=>this.create({...n,type:"warning",message:t}),this.loading=(t,n)=>this.create({...n,type:"loading",message:t}),this.promise=(t,n)=>{if(!n)return;let r;n.loading!==void 0&&(r=this.create({...n,promise:t,type:"loading",message:n.loading,description:typeof n.description!="function"?n.description:void 0}));let a=t instanceof Promise?t:t(),i=r!==void 0,l,o=a.then(async d=>{if(l=["resolve",d],Ct.isValidElement(d))i=!1,this.create({id:r,type:"default",message:d});else if(h6t(d)&&!d.ok){i=!1;let u=typeof n.error=="function"?await n.error(`HTTP error! status: ${d.status}`):n.error,h=typeof n.description=="function"?await n.description(`HTTP error! status: ${d.status}`):n.description;this.create({id:r,type:"error",message:u,description:h})}else if(n.success!==void 0){i=!1;let u=typeof n.success=="function"?await n.success(d):n.success,h=typeof n.description=="function"?await n.description(d):n.description;this.create({id:r,type:"success",message:u,description:h})}}).catch(async d=>{if(l=["reject",d],n.error!==void 0){i=!1;let u=typeof n.error=="function"?await n.error(d):n.error,h=typeof n.description=="function"?await n.description(d):n.description;this.create({id:r,type:"error",message:u,description:h})}}).finally(()=>{var d;i&&(this.dismiss(r),r=void 0),(d=n.finally)==null||d.call(n)}),c=()=>new Promise((d,u)=>o.then(()=>l[0]==="reject"?u(l[1]):d(l[1])).catch(u));return typeof r!="string"&&typeof r!="number"?{unwrap:c}:Object.assign(r,{unwrap:c})},this.custom=(t,n)=>{let r=(n==null?void 0:n.id)||vSe++;return this.create({jsx:t(r),id:r,...n}),r},this.getActiveToasts=()=>this.toasts.filter(t=>!this.dismissedToasts.has(t.id)),this.subscribers=[],this.toasts=[],this.dismissedToasts=new Set}},Tg=new d6t,u6t=(s,t)=>{let n=(t==null?void 0:t.id)||vSe++;return Tg.addToast({title:s,...t,id:n}),n},h6t=s=>s&&typeof s=="object"&&"ok"in s&&typeof s.ok=="boolean"&&"status"in s&&typeof s.status=="number",m6t=u6t,p6t=()=>Tg.toasts,f6t=()=>Tg.getActiveToasts(),ae=Object.assign(m6t,{success:Tg.success,info:Tg.info,warning:Tg.warning,error:Tg.error,custom:Tg.custom,message:Tg.message,promise:Tg.promise,dismiss:Tg.dismiss,loading:Tg.loading},{getHistory:p6t,getToasts:f6t});function x6t(s,{insertAt:t}={}){if(typeof document>"u")return;let n=document.head||document.getElementsByTagName("head")[0],r=document.createElement("style");r.type="text/css",t==="top"&&n.firstChild?n.insertBefore(r,n.firstChild):n.appendChild(r),r.styleSheet?r.styleSheet.cssText=s:r.appendChild(document.createTextNode(s))}x6t(`: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 MV(s){return s.label!==void 0}var g6t=3,y6t="32px",v6t="16px",M9e=4e3,b6t=356,_6t=14,w6t=20,j6t=200;function L1(...s){return s.filter(Boolean).join(" ")}function N6t(s){let[t,n]=s.split("-"),r=[];return t&&r.push(t),n&&r.push(n),r}var k6t=s=>{var t,n,r,a,i,l,o,c,d,u,h;let{invert:p,toast:f,unstyled:y,interacting:_,setHeights:v,visibleToasts:j,heights:w,index:S,toasts:A,expanded:E,removeToast:O,defaultRichColors:D,closeButton:I,style:F,cancelButtonStyle:z,actionButtonStyle:H,className:Z="",descriptionClassName:Y="",duration:W,position:ee,gap:se,loadingIcon:oe,expandByDefault:he,classNames:ce,icons:me,closeButtonAriaLabel:le="Close toast",pauseWhenPageIsHidden:ve}=s,[ge,Te]=Ct.useState(null),[Ie,Ce]=Ct.useState(null),[Me,Pe]=Ct.useState(!1),[Re,Ae]=Ct.useState(!1),[Be,we]=Ct.useState(!1),[Je,ke]=Ct.useState(!1),[it,je]=Ct.useState(!1),[He,$e]=Ct.useState(0),[Ke,Ge]=Ct.useState(0),rt=Ct.useRef(f.duration||W||M9e),tt=Ct.useRef(null),at=Ct.useRef(null),Ye=S===0,ut=S+1<=j,_t=f.type,bt=f.dismissible!==!1,$t=f.className||"",Yt=f.descriptionClassName||"",Ds=Ct.useMemo(()=>w.findIndex(xn=>xn.toastId===f.id)||0,[w,f.id]),Ls=Ct.useMemo(()=>{var xn;return(xn=f.closeButton)!=null?xn:I},[f.closeButton,I]),xs=Ct.useMemo(()=>f.duration||W||M9e,[f.duration,W]),Lt=Ct.useRef(0),Jt=Ct.useRef(0),gt=Ct.useRef(0),zt=Ct.useRef(null),[As,Xt]=ee.split("-"),Qs=Ct.useMemo(()=>w.reduce((xn,Pn,Qn)=>Qn>=Ds?xn:xn+Pn.height,0),[w,Ds]),ks=c6t(),$s=f.invert||p,an=_t==="loading";Jt.current=Ct.useMemo(()=>Ds*se+Qs,[Ds,Qs]),Ct.useEffect(()=>{rt.current=xs},[xs]),Ct.useEffect(()=>{Pe(!0)},[]),Ct.useEffect(()=>{let xn=at.current;if(xn){let Pn=xn.getBoundingClientRect().height;return Ge(Pn),v(Qn=>[{toastId:f.id,height:Pn,position:f.position},...Qn]),()=>v(Qn=>Qn.filter(sa=>sa.toastId!==f.id))}},[v,f.id]),Ct.useLayoutEffect(()=>{if(!Me)return;let xn=at.current,Pn=xn.style.height;xn.style.height="auto";let Qn=xn.getBoundingClientRect().height;xn.style.height=Pn,Ge(Qn),v(sa=>sa.find(na=>na.toastId===f.id)?sa.map(na=>na.toastId===f.id?{...na,height:Qn}:na):[{toastId:f.id,height:Qn,position:f.position},...sa])},[Me,f.title,f.description,v,f.id]);let tn=Ct.useCallback(()=>{Ae(!0),$e(Jt.current),v(xn=>xn.filter(Pn=>Pn.toastId!==f.id)),setTimeout(()=>{O(f)},j6t)},[f,O,v,Jt]);Ct.useEffect(()=>{if(f.promise&&_t==="loading"||f.duration===1/0||f.type==="loading")return;let xn;return E||_||ve&&ks?(()=>{if(gt.current{var Pn;(Pn=f.onAutoClose)==null||Pn.call(f,f),tn()},rt.current)),()=>clearTimeout(xn)},[E,_,f,_t,ve,ks,tn]),Ct.useEffect(()=>{f.delete&&tn()},[tn,f.delete]);function er(){var xn,Pn,Qn;return me!=null&&me.loading?Ct.createElement("div",{className:L1(ce==null?void 0:ce.loader,(xn=f==null?void 0:f.classNames)==null?void 0:xn.loader,"sonner-loader"),"data-visible":_t==="loading"},me.loading):oe?Ct.createElement("div",{className:L1(ce==null?void 0:ce.loader,(Pn=f==null?void 0:f.classNames)==null?void 0:Pn.loader,"sonner-loader"),"data-visible":_t==="loading"},oe):Ct.createElement(n6t,{className:L1(ce==null?void 0:ce.loader,(Qn=f==null?void 0:f.classNames)==null?void 0:Qn.loader),visible:_t==="loading"})}return Ct.createElement("li",{tabIndex:0,ref:at,className:L1(Z,$t,ce==null?void 0:ce.toast,(t=f==null?void 0:f.classNames)==null?void 0:t.toast,ce==null?void 0:ce.default,ce==null?void 0:ce[_t],(n=f==null?void 0:f.classNames)==null?void 0:n[_t]),"data-sonner-toast":"","data-rich-colors":(r=f.richColors)!=null?r:D,"data-styled":!(f.jsx||f.unstyled||y),"data-mounted":Me,"data-promise":!!f.promise,"data-swiped":it,"data-removed":Re,"data-visible":ut,"data-y-position":As,"data-x-position":Xt,"data-index":S,"data-front":Ye,"data-swiping":Be,"data-dismissible":bt,"data-type":_t,"data-invert":$s,"data-swipe-out":Je,"data-swipe-direction":Ie,"data-expanded":!!(E||he&&Me),style:{"--index":S,"--toasts-before":S,"--z-index":A.length-S,"--offset":`${Re?He:Jt.current}px`,"--initial-height":he?"auto":`${Ke}px`,...F,...f.style},onDragEnd:()=>{we(!1),Te(null),zt.current=null},onPointerDown:xn=>{an||!bt||(tt.current=new Date,$e(Jt.current),xn.target.setPointerCapture(xn.pointerId),xn.target.tagName!=="BUTTON"&&(we(!0),zt.current={x:xn.clientX,y:xn.clientY}))},onPointerUp:()=>{var xn,Pn,Qn,sa;if(Je||!bt)return;zt.current=null;let na=Number(((xn=at.current)==null?void 0:xn.style.getPropertyValue("--swipe-amount-x").replace("px",""))||0),Es=Number(((Pn=at.current)==null?void 0:Pn.style.getPropertyValue("--swipe-amount-y").replace("px",""))||0),mi=new Date().getTime()-((Qn=tt.current)==null?void 0:Qn.getTime()),Ar=ge==="x"?na:Es,Hn=Math.abs(Ar)/mi;if(Math.abs(Ar)>=w6t||Hn>.11){$e(Jt.current),(sa=f.onDismiss)==null||sa.call(f,f),Ce(ge==="x"?na>0?"right":"left":Es>0?"down":"up"),tn(),ke(!0),je(!1);return}we(!1),Te(null)},onPointerMove:xn=>{var Pn,Qn,sa,na;if(!zt.current||!bt||((Pn=window.getSelection())==null?void 0:Pn.toString().length)>0)return;let Es=xn.clientY-zt.current.y,mi=xn.clientX-zt.current.x,Ar=(Qn=s.swipeDirections)!=null?Qn:N6t(ee);!ge&&(Math.abs(mi)>1||Math.abs(Es)>1)&&Te(Math.abs(mi)>Math.abs(Es)?"x":"y");let Hn={x:0,y:0};ge==="y"?(Ar.includes("top")||Ar.includes("bottom"))&&(Ar.includes("top")&&Es<0||Ar.includes("bottom")&&Es>0)&&(Hn.y=Es):ge==="x"&&(Ar.includes("left")||Ar.includes("right"))&&(Ar.includes("left")&&mi<0||Ar.includes("right")&&mi>0)&&(Hn.x=mi),(Math.abs(Hn.x)>0||Math.abs(Hn.y)>0)&&je(!0),(sa=at.current)==null||sa.style.setProperty("--swipe-amount-x",`${Hn.x}px`),(na=at.current)==null||na.style.setProperty("--swipe-amount-y",`${Hn.y}px`)}},Ls&&!f.jsx?Ct.createElement("button",{"aria-label":le,"data-disabled":an,"data-close-button":!0,onClick:an||!bt?()=>{}:()=>{var xn;tn(),(xn=f.onDismiss)==null||xn.call(f,f)},className:L1(ce==null?void 0:ce.closeButton,(a=f==null?void 0:f.classNames)==null?void 0:a.closeButton)},(i=me==null?void 0:me.close)!=null?i:l6t):null,f.jsx||N.isValidElement(f.title)?f.jsx?f.jsx:typeof f.title=="function"?f.title():f.title:Ct.createElement(Ct.Fragment,null,_t||f.icon||f.promise?Ct.createElement("div",{"data-icon":"",className:L1(ce==null?void 0:ce.icon,(l=f==null?void 0:f.classNames)==null?void 0:l.icon)},f.promise||f.type==="loading"&&!f.icon?f.icon||er():null,f.type!=="loading"?f.icon||(me==null?void 0:me[_t])||t6t(_t):null):null,Ct.createElement("div",{"data-content":"",className:L1(ce==null?void 0:ce.content,(o=f==null?void 0:f.classNames)==null?void 0:o.content)},Ct.createElement("div",{"data-title":"",className:L1(ce==null?void 0:ce.title,(c=f==null?void 0:f.classNames)==null?void 0:c.title)},typeof f.title=="function"?f.title():f.title),f.description?Ct.createElement("div",{"data-description":"",className:L1(Y,Yt,ce==null?void 0:ce.description,(d=f==null?void 0:f.classNames)==null?void 0:d.description)},typeof f.description=="function"?f.description():f.description):null),N.isValidElement(f.cancel)?f.cancel:f.cancel&&MV(f.cancel)?Ct.createElement("button",{"data-button":!0,"data-cancel":!0,style:f.cancelButtonStyle||z,onClick:xn=>{var Pn,Qn;MV(f.cancel)&&bt&&((Qn=(Pn=f.cancel).onClick)==null||Qn.call(Pn,xn),tn())},className:L1(ce==null?void 0:ce.cancelButton,(u=f==null?void 0:f.classNames)==null?void 0:u.cancelButton)},f.cancel.label):null,N.isValidElement(f.action)?f.action:f.action&&MV(f.action)?Ct.createElement("button",{"data-button":!0,"data-action":!0,style:f.actionButtonStyle||H,onClick:xn=>{var Pn,Qn;MV(f.action)&&((Qn=(Pn=f.action).onClick)==null||Qn.call(Pn,xn),!xn.defaultPrevented&&tn())},className:L1(ce==null?void 0:ce.actionButton,(h=f==null?void 0:f.classNames)==null?void 0:h.actionButton)},f.action.label):null))};function I9e(){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 S6t(s,t){let n={};return[s,t].forEach((r,a)=>{let i=a===1,l=i?"--mobile-offset":"--offset",o=i?v6t:y6t;function c(d){["top","right","bottom","left"].forEach(u=>{n[`${l}-${u}`]=typeof d=="number"?`${d}px`:d})}typeof r=="number"||typeof r=="string"?c(r):typeof r=="object"?["top","right","bottom","left"].forEach(d=>{r[d]===void 0?n[`${l}-${d}`]=o:n[`${l}-${d}`]=typeof r[d]=="number"?`${r[d]}px`:r[d]}):c(o)}),n}var C6t=N.forwardRef(function(s,t){let{invert:n,position:r="bottom-right",hotkey:a=["altKey","KeyT"],expand:i,closeButton:l,className:o,offset:c,mobileOffset:d,theme:u="light",richColors:h,duration:p,style:f,visibleToasts:y=g6t,toastOptions:_,dir:v=I9e(),gap:j=_6t,loadingIcon:w,icons:S,containerAriaLabel:A="Notifications",pauseWhenPageIsHidden:E}=s,[O,D]=Ct.useState([]),I=Ct.useMemo(()=>Array.from(new Set([r].concat(O.filter(ve=>ve.position).map(ve=>ve.position)))),[O,r]),[F,z]=Ct.useState([]),[H,Z]=Ct.useState(!1),[Y,W]=Ct.useState(!1),[ee,se]=Ct.useState(u!=="system"?u:typeof window<"u"&&window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?"dark":"light"),oe=Ct.useRef(null),he=a.join("+").replace(/Key/g,"").replace(/Digit/g,""),ce=Ct.useRef(null),me=Ct.useRef(!1),le=Ct.useCallback(ve=>{D(ge=>{var Te;return(Te=ge.find(Ie=>Ie.id===ve.id))!=null&&Te.delete||Tg.dismiss(ve.id),ge.filter(({id:Ie})=>Ie!==ve.id)})},[]);return Ct.useEffect(()=>Tg.subscribe(ve=>{if(ve.dismiss){D(ge=>ge.map(Te=>Te.id===ve.id?{...Te,delete:!0}:Te));return}setTimeout(()=>{zEe.flushSync(()=>{D(ge=>{let Te=ge.findIndex(Ie=>Ie.id===ve.id);return Te!==-1?[...ge.slice(0,Te),{...ge[Te],...ve},...ge.slice(Te+1)]:[ve,...ge]})})})}),[]),Ct.useEffect(()=>{if(u!=="system"){se(u);return}if(u==="system"&&(window.matchMedia&&window.matchMedia("(prefers-color-scheme: dark)").matches?se("dark"):se("light")),typeof window>"u")return;let ve=window.matchMedia("(prefers-color-scheme: dark)");try{ve.addEventListener("change",({matches:ge})=>{se(ge?"dark":"light")})}catch{ve.addListener(({matches:Te})=>{try{se(Te?"dark":"light")}catch(Ie){console.error(Ie)}})}},[u]),Ct.useEffect(()=>{O.length<=1&&Z(!1)},[O]),Ct.useEffect(()=>{let ve=ge=>{var Te,Ie;a.every(Ce=>ge[Ce]||ge.code===Ce)&&(Z(!0),(Te=oe.current)==null||Te.focus()),ge.code==="Escape"&&(document.activeElement===oe.current||(Ie=oe.current)!=null&&Ie.contains(document.activeElement))&&Z(!1)};return document.addEventListener("keydown",ve),()=>document.removeEventListener("keydown",ve)},[a]),Ct.useEffect(()=>{if(oe.current)return()=>{ce.current&&(ce.current.focus({preventScroll:!0}),ce.current=null,me.current=!1)}},[oe.current]),Ct.createElement("section",{ref:t,"aria-label":`${A} ${he}`,tabIndex:-1,"aria-live":"polite","aria-relevant":"additions text","aria-atomic":"false",suppressHydrationWarning:!0},I.map((ve,ge)=>{var Te;let[Ie,Ce]=ve.split("-");return O.length?Ct.createElement("ol",{key:ve,dir:v==="auto"?I9e():v,tabIndex:-1,ref:oe,className:o,"data-sonner-toaster":!0,"data-theme":ee,"data-y-position":Ie,"data-lifted":H&&O.length>1&&!i,"data-x-position":Ce,style:{"--front-toast-height":`${((Te=F[0])==null?void 0:Te.height)||0}px`,"--width":`${b6t}px`,"--gap":`${j}px`,...f,...S6t(c,d)},onBlur:Me=>{me.current&&!Me.currentTarget.contains(Me.relatedTarget)&&(me.current=!1,ce.current&&(ce.current.focus({preventScroll:!0}),ce.current=null))},onFocus:Me=>{Me.target instanceof HTMLElement&&Me.target.dataset.dismissible==="false"||me.current||(me.current=!0,ce.current=Me.relatedTarget)},onMouseEnter:()=>Z(!0),onMouseMove:()=>Z(!0),onMouseLeave:()=>{Y||Z(!1)},onDragEnd:()=>Z(!1),onPointerDown:Me=>{Me.target instanceof HTMLElement&&Me.target.dataset.dismissible==="false"||W(!0)},onPointerUp:()=>W(!1)},O.filter(Me=>!Me.position&&ge===0||Me.position===ve).map((Me,Pe)=>{var Re,Ae;return Ct.createElement(k6t,{key:Me.id,icons:S,index:Pe,toast:Me,defaultRichColors:h,duration:(Re=_==null?void 0:_.duration)!=null?Re:p,className:_==null?void 0:_.className,descriptionClassName:_==null?void 0:_.descriptionClassName,invert:n,visibleToasts:y,closeButton:(Ae=_==null?void 0:_.closeButton)!=null?Ae:l,interacting:Y,position:ve,style:_==null?void 0:_.style,unstyled:_==null?void 0:_.unstyled,classNames:_==null?void 0:_.classNames,cancelButtonStyle:_==null?void 0:_.cancelButtonStyle,actionButtonStyle:_==null?void 0:_.actionButtonStyle,removeToast:le,toasts:O.filter(Be=>Be.position==Me.position),heights:F.filter(Be=>Be.position==Me.position),setHeights:z,expandByDefault:i,gap:j,loadingIcon:w,expanded:H,pauseWhenPageIsHidden:E,swipeDirections:s.swipeDirections})})):null}))});const T6t=({...s})=>{const{theme:t="system"}=e6t();return e.jsx(C6t,{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 E6t=KTe[" useId ".trim().toString()]||(()=>{}),A6t=0;function om(s){const[t,n]=N.useState(E6t());return lh(()=>{s||n(r=>r??String(A6t++))},[s]),s||(t?`radix-${t}`:"")}const M6t=["top","right","bottom","left"],b4=Math.min,V0=Math.max,Ape=Math.round,IV=Math.floor,_4=s=>({x:s,y:s}),I6t={left:"right",right:"left",bottom:"top",top:"bottom"},P6t={start:"end",end:"start"};function bSe(s,t,n){return V0(s,b4(t,n))}function oN(s,t){return typeof s=="function"?s(t):s}function lN(s){return s.split("-")[0]}function kD(s){return s.split("-")[1]}function GEe(s){return s==="x"?"y":"x"}function WEe(s){return s==="y"?"height":"width"}function w4(s){return["top","bottom"].includes(lN(s))?"y":"x"}function KEe(s){return GEe(w4(s))}function L6t(s,t,n){n===void 0&&(n=!1);const r=kD(s),a=KEe(s),i=WEe(a);let l=a==="x"?r===(n?"end":"start")?"right":"left":r==="start"?"bottom":"top";return t.reference[i]>t.floating[i]&&(l=Mpe(l)),[l,Mpe(l)]}function D6t(s){const t=Mpe(s);return[_Se(s),t,_Se(t)]}function _Se(s){return s.replace(/start|end/g,t=>P6t[t])}function R6t(s,t,n){const r=["left","right"],a=["right","left"],i=["top","bottom"],l=["bottom","top"];switch(s){case"top":case"bottom":return n?t?a:r:t?r:a;case"left":case"right":return t?i:l;default:return[]}}function O6t(s,t,n,r){const a=kD(s);let i=R6t(lN(s),n==="start",r);return a&&(i=i.map(l=>l+"-"+a),t&&(i=i.concat(i.map(_Se)))),i}function Mpe(s){return s.replace(/left|right|bottom|top/g,t=>I6t[t])}function F6t(s){return{top:0,right:0,bottom:0,left:0,...s}}function urt(s){return typeof s!="number"?F6t(s):{top:s,right:s,bottom:s,left:s}}function Ipe(s){const{x:t,y:n,width:r,height:a}=s;return{width:r,height:a,top:n,left:t,right:t+r,bottom:n+a,x:t,y:n}}function P9e(s,t,n){let{reference:r,floating:a}=s;const i=w4(t),l=KEe(t),o=WEe(l),c=lN(t),d=i==="y",u=r.x+r.width/2-a.width/2,h=r.y+r.height/2-a.height/2,p=r[o]/2-a[o]/2;let f;switch(c){case"top":f={x:u,y:r.y-a.height};break;case"bottom":f={x:u,y:r.y+r.height};break;case"right":f={x:r.x+r.width,y:h};break;case"left":f={x:r.x-a.width,y:h};break;default:f={x:r.x,y:r.y}}switch(kD(t)){case"start":f[l]-=p*(n&&d?-1:1);break;case"end":f[l]+=p*(n&&d?-1:1);break}return f}const z6t=async(s,t,n)=>{const{placement:r="bottom",strategy:a="absolute",middleware:i=[],platform:l}=n,o=i.filter(Boolean),c=await(l.isRTL==null?void 0:l.isRTL(t));let d=await l.getElementRects({reference:s,floating:t,strategy:a}),{x:u,y:h}=P9e(d,r,c),p=r,f={},y=0;for(let _=0;_({name:"arrow",options:s,async fn(t){const{x:n,y:r,placement:a,rects:i,platform:l,elements:o,middlewareData:c}=t,{element:d,padding:u=0}=oN(s,t)||{};if(d==null)return{};const h=urt(u),p={x:n,y:r},f=KEe(a),y=WEe(f),_=await l.getDimensions(d),v=f==="y",j=v?"top":"left",w=v?"bottom":"right",S=v?"clientHeight":"clientWidth",A=i.reference[y]+i.reference[f]-p[f]-i.floating[y],E=p[f]-i.reference[f],O=await(l.getOffsetParent==null?void 0:l.getOffsetParent(d));let D=O?O[S]:0;(!D||!await(l.isElement==null?void 0:l.isElement(O)))&&(D=o.floating[S]||i.floating[y]);const I=A/2-E/2,F=D/2-_[y]/2-1,z=b4(h[j],F),H=b4(h[w],F),Z=z,Y=D-_[y]-H,W=D/2-_[y]/2+I,ee=bSe(Z,W,Y),se=!c.arrow&&kD(a)!=null&&W!==ee&&i.reference[y]/2-(WW<=0)){var H,Z;const W=(((H=i.flip)==null?void 0:H.index)||0)+1,ee=D[W];if(ee)return{data:{index:W,overflows:z},reset:{placement:ee}};let se=(Z=z.filter(oe=>oe.overflows[0]<=0).sort((oe,he)=>oe.overflows[1]-he.overflows[1])[0])==null?void 0:Z.placement;if(!se)switch(f){case"bestFit":{var Y;const oe=(Y=z.filter(he=>{if(O){const ce=w4(he.placement);return ce===w||ce==="y"}return!0}).map(he=>[he.placement,he.overflows.filter(ce=>ce>0).reduce((ce,me)=>ce+me,0)]).sort((he,ce)=>he[1]-ce[1])[0])==null?void 0:Y[0];oe&&(se=oe);break}case"initialPlacement":se=o;break}if(a!==se)return{reset:{placement:se}}}return{}}}};function L9e(s,t){return{top:s.top-t.height,right:s.right-t.width,bottom:s.bottom-t.height,left:s.left-t.width}}function D9e(s){return M6t.some(t=>s[t]>=0)}const U6t=function(s){return s===void 0&&(s={}),{name:"hide",options:s,async fn(t){const{rects:n}=t,{strategy:r="referenceHidden",...a}=oN(s,t);switch(r){case"referenceHidden":{const i=await Vz(t,{...a,elementContext:"reference"}),l=L9e(i,n.reference);return{data:{referenceHiddenOffsets:l,referenceHidden:D9e(l)}}}case"escaped":{const i=await Vz(t,{...a,altBoundary:!0}),l=L9e(i,n.floating);return{data:{escapedOffsets:l,escaped:D9e(l)}}}default:return{}}}}};async function q6t(s,t){const{placement:n,platform:r,elements:a}=s,i=await(r.isRTL==null?void 0:r.isRTL(a.floating)),l=lN(n),o=kD(n),c=w4(n)==="y",d=["left","top"].includes(l)?-1:1,u=i&&c?-1:1,h=oN(t,s);let{mainAxis:p,crossAxis:f,alignmentAxis:y}=typeof h=="number"?{mainAxis:h,crossAxis:0,alignmentAxis:null}:{mainAxis:h.mainAxis||0,crossAxis:h.crossAxis||0,alignmentAxis:h.alignmentAxis};return o&&typeof y=="number"&&(f=o==="end"?y*-1:y),c?{x:f*u,y:p*d}:{x:p*d,y:f*u}}const V6t=function(s){return s===void 0&&(s=0),{name:"offset",options:s,async fn(t){var n,r;const{x:a,y:i,placement:l,middlewareData:o}=t,c=await q6t(t,s);return l===((n=o.offset)==null?void 0:n.placement)&&(r=o.arrow)!=null&&r.alignmentOffset?{}:{x:a+c.x,y:i+c.y,data:{...c,placement:l}}}}},H6t=function(s){return s===void 0&&(s={}),{name:"shift",options:s,async fn(t){const{x:n,y:r,placement:a}=t,{mainAxis:i=!0,crossAxis:l=!1,limiter:o={fn:v=>{let{x:j,y:w}=v;return{x:j,y:w}}},...c}=oN(s,t),d={x:n,y:r},u=await Vz(t,c),h=w4(lN(a)),p=GEe(h);let f=d[p],y=d[h];if(i){const v=p==="y"?"top":"left",j=p==="y"?"bottom":"right",w=f+u[v],S=f-u[j];f=bSe(w,f,S)}if(l){const v=h==="y"?"top":"left",j=h==="y"?"bottom":"right",w=y+u[v],S=y-u[j];y=bSe(w,y,S)}const _=o.fn({...t,[p]:f,[h]:y});return{..._,data:{x:_.x-n,y:_.y-r,enabled:{[p]:i,[h]:l}}}}}},G6t=function(s){return s===void 0&&(s={}),{options:s,fn(t){const{x:n,y:r,placement:a,rects:i,middlewareData:l}=t,{offset:o=0,mainAxis:c=!0,crossAxis:d=!0}=oN(s,t),u={x:n,y:r},h=w4(a),p=GEe(h);let f=u[p],y=u[h];const _=oN(o,t),v=typeof _=="number"?{mainAxis:_,crossAxis:0}:{mainAxis:0,crossAxis:0,..._};if(c){const S=p==="y"?"height":"width",A=i.reference[p]-i.floating[S]+v.mainAxis,E=i.reference[p]+i.reference[S]-v.mainAxis;fE&&(f=E)}if(d){var j,w;const S=p==="y"?"width":"height",A=["top","left"].includes(lN(a)),E=i.reference[h]-i.floating[S]+(A&&((j=l.offset)==null?void 0:j[h])||0)+(A?0:v.crossAxis),O=i.reference[h]+i.reference[S]+(A?0:((w=l.offset)==null?void 0:w[h])||0)-(A?v.crossAxis:0);yO&&(y=O)}return{[p]:f,[h]:y}}}},W6t=function(s){return s===void 0&&(s={}),{name:"size",options:s,async fn(t){var n,r;const{placement:a,rects:i,platform:l,elements:o}=t,{apply:c=()=>{},...d}=oN(s,t),u=await Vz(t,d),h=lN(a),p=kD(a),f=w4(a)==="y",{width:y,height:_}=i.floating;let v,j;h==="top"||h==="bottom"?(v=h,j=p===(await(l.isRTL==null?void 0:l.isRTL(o.floating))?"start":"end")?"left":"right"):(j=h,v=p==="end"?"top":"bottom");const w=_-u.top-u.bottom,S=y-u.left-u.right,A=b4(_-u[v],w),E=b4(y-u[j],S),O=!t.middlewareData.shift;let D=A,I=E;if((n=t.middlewareData.shift)!=null&&n.enabled.x&&(I=S),(r=t.middlewareData.shift)!=null&&r.enabled.y&&(D=w),O&&!p){const z=V0(u.left,0),H=V0(u.right,0),Z=V0(u.top,0),Y=V0(u.bottom,0);f?I=y-2*(z!==0||H!==0?z+H:V0(u.left,u.right)):D=_-2*(Z!==0||Y!==0?Z+Y:V0(u.top,u.bottom))}await c({...t,availableWidth:I,availableHeight:D});const F=await l.getDimensions(o.floating);return y!==F.width||_!==F.height?{reset:{rects:!0}}:{}}}};function p0e(){return typeof window<"u"}function SD(s){return hrt(s)?(s.nodeName||"").toLowerCase():"#document"}function iy(s){var t;return(s==null||(t=s.ownerDocument)==null?void 0:t.defaultView)||window}function Uw(s){var t;return(t=(hrt(s)?s.ownerDocument:s.document)||window.document)==null?void 0:t.documentElement}function hrt(s){return p0e()?s instanceof Node||s instanceof iy(s).Node:!1}function jb(s){return p0e()?s instanceof Element||s instanceof iy(s).Element:!1}function Cw(s){return p0e()?s instanceof HTMLElement||s instanceof iy(s).HTMLElement:!1}function R9e(s){return!p0e()||typeof ShadowRoot>"u"?!1:s instanceof ShadowRoot||s instanceof iy(s).ShadowRoot}function A$(s){const{overflow:t,overflowX:n,overflowY:r,display:a}=Nb(s);return/auto|scroll|overlay|hidden|clip/.test(t+r+n)&&!["inline","contents"].includes(a)}function K6t(s){return["table","td","th"].includes(SD(s))}function f0e(s){return[":popover-open",":modal"].some(t=>{try{return s.matches(t)}catch{return!1}})}function YEe(s){const t=ZEe(),n=jb(s)?Nb(s):s;return n.transform!=="none"||n.perspective!=="none"||(n.containerType?n.containerType!=="normal":!1)||!t&&(n.backdropFilter?n.backdropFilter!=="none":!1)||!t&&(n.filter?n.filter!=="none":!1)||["transform","perspective","filter"].some(r=>(n.willChange||"").includes(r))||["paint","layout","strict","content"].some(r=>(n.contain||"").includes(r))}function Y6t(s){let t=j4(s);for(;Cw(t)&&!c8(t);){if(YEe(t))return t;if(f0e(t))return null;t=j4(t)}return null}function ZEe(){return typeof CSS>"u"||!CSS.supports?!1:CSS.supports("-webkit-backdrop-filter","none")}function c8(s){return["html","body","#document"].includes(SD(s))}function Nb(s){return iy(s).getComputedStyle(s)}function x0e(s){return jb(s)?{scrollLeft:s.scrollLeft,scrollTop:s.scrollTop}:{scrollLeft:s.scrollX,scrollTop:s.scrollY}}function j4(s){if(SD(s)==="html")return s;const t=s.assignedSlot||s.parentNode||R9e(s)&&s.host||Uw(s);return R9e(t)?t.host:t}function mrt(s){const t=j4(s);return c8(t)?s.ownerDocument?s.ownerDocument.body:s.body:Cw(t)&&A$(t)?t:mrt(t)}function Hz(s,t,n){var r;t===void 0&&(t=[]),n===void 0&&(n=!0);const a=mrt(s),i=a===((r=s.ownerDocument)==null?void 0:r.body),l=iy(a);if(i){const o=wSe(l);return t.concat(l,l.visualViewport||[],A$(a)?a:[],o&&n?Hz(o):[])}return t.concat(a,Hz(a,[],n))}function wSe(s){return s.parent&&Object.getPrototypeOf(s.parent)?s.frameElement:null}function prt(s){const t=Nb(s);let n=parseFloat(t.width)||0,r=parseFloat(t.height)||0;const a=Cw(s),i=a?s.offsetWidth:n,l=a?s.offsetHeight:r,o=Ape(n)!==i||Ape(r)!==l;return o&&(n=i,r=l),{width:n,height:r,$:o}}function QEe(s){return jb(s)?s:s.contextElement}function bL(s){const t=QEe(s);if(!Cw(t))return _4(1);const n=t.getBoundingClientRect(),{width:r,height:a,$:i}=prt(t);let l=(i?Ape(n.width):n.width)/r,o=(i?Ape(n.height):n.height)/a;return(!l||!Number.isFinite(l))&&(l=1),(!o||!Number.isFinite(o))&&(o=1),{x:l,y:o}}const Z6t=_4(0);function frt(s){const t=iy(s);return!ZEe()||!t.visualViewport?Z6t:{x:t.visualViewport.offsetLeft,y:t.visualViewport.offsetTop}}function Q6t(s,t,n){return t===void 0&&(t=!1),!n||t&&n!==iy(s)?!1:t}function iM(s,t,n,r){t===void 0&&(t=!1),n===void 0&&(n=!1);const a=s.getBoundingClientRect(),i=QEe(s);let l=_4(1);t&&(r?jb(r)&&(l=bL(r)):l=bL(s));const o=Q6t(i,n,r)?frt(i):_4(0);let c=(a.left+o.x)/l.x,d=(a.top+o.y)/l.y,u=a.width/l.x,h=a.height/l.y;if(i){const p=iy(i),f=r&&jb(r)?iy(r):r;let y=p,_=wSe(y);for(;_&&r&&f!==y;){const v=bL(_),j=_.getBoundingClientRect(),w=Nb(_),S=j.left+(_.clientLeft+parseFloat(w.paddingLeft))*v.x,A=j.top+(_.clientTop+parseFloat(w.paddingTop))*v.y;c*=v.x,d*=v.y,u*=v.x,h*=v.y,c+=S,d+=A,y=iy(_),_=wSe(y)}}return Ipe({width:u,height:h,x:c,y:d})}function X6t(s){let{elements:t,rect:n,offsetParent:r,strategy:a}=s;const i=a==="fixed",l=Uw(r),o=t?f0e(t.floating):!1;if(r===l||o&&i)return n;let c={scrollLeft:0,scrollTop:0},d=_4(1);const u=_4(0),h=Cw(r);if((h||!h&&!i)&&((SD(r)!=="body"||A$(l))&&(c=x0e(r)),Cw(r))){const p=iM(r);d=bL(r),u.x=p.x+r.clientLeft,u.y=p.y+r.clientTop}return{width:n.width*d.x,height:n.height*d.y,x:n.x*d.x-c.scrollLeft*d.x+u.x,y:n.y*d.y-c.scrollTop*d.y+u.y}}function J6t(s){return Array.from(s.getClientRects())}function jSe(s,t){const n=x0e(s).scrollLeft;return t?t.left+n:iM(Uw(s)).left+n}function eIt(s){const t=Uw(s),n=x0e(s),r=s.ownerDocument.body,a=V0(t.scrollWidth,t.clientWidth,r.scrollWidth,r.clientWidth),i=V0(t.scrollHeight,t.clientHeight,r.scrollHeight,r.clientHeight);let l=-n.scrollLeft+jSe(s);const o=-n.scrollTop;return Nb(r).direction==="rtl"&&(l+=V0(t.clientWidth,r.clientWidth)-a),{width:a,height:i,x:l,y:o}}function tIt(s,t){const n=iy(s),r=Uw(s),a=n.visualViewport;let i=r.clientWidth,l=r.clientHeight,o=0,c=0;if(a){i=a.width,l=a.height;const d=ZEe();(!d||d&&t==="fixed")&&(o=a.offsetLeft,c=a.offsetTop)}return{width:i,height:l,x:o,y:c}}function sIt(s,t){const n=iM(s,!0,t==="fixed"),r=n.top+s.clientTop,a=n.left+s.clientLeft,i=Cw(s)?bL(s):_4(1),l=s.clientWidth*i.x,o=s.clientHeight*i.y,c=a*i.x,d=r*i.y;return{width:l,height:o,x:c,y:d}}function O9e(s,t,n){let r;if(t==="viewport")r=tIt(s,n);else if(t==="document")r=eIt(Uw(s));else if(jb(t))r=sIt(t,n);else{const a=frt(s);r={...t,x:t.x-a.x,y:t.y-a.y}}return Ipe(r)}function xrt(s,t){const n=j4(s);return n===t||!jb(n)||c8(n)?!1:Nb(n).position==="fixed"||xrt(n,t)}function nIt(s,t){const n=t.get(s);if(n)return n;let r=Hz(s,[],!1).filter(o=>jb(o)&&SD(o)!=="body"),a=null;const i=Nb(s).position==="fixed";let l=i?j4(s):s;for(;jb(l)&&!c8(l);){const o=Nb(l),c=YEe(l);!c&&o.position==="fixed"&&(a=null),(i?!c&&!a:!c&&o.position==="static"&&!!a&&["absolute","fixed"].includes(a.position)||A$(l)&&!c&&xrt(s,l))?r=r.filter(u=>u!==l):a=o,l=j4(l)}return t.set(s,r),r}function rIt(s){let{element:t,boundary:n,rootBoundary:r,strategy:a}=s;const l=[...n==="clippingAncestors"?f0e(t)?[]:nIt(t,this._c):[].concat(n),r],o=l[0],c=l.reduce((d,u)=>{const h=O9e(t,u,a);return d.top=V0(h.top,d.top),d.right=b4(h.right,d.right),d.bottom=b4(h.bottom,d.bottom),d.left=V0(h.left,d.left),d},O9e(t,o,a));return{width:c.right-c.left,height:c.bottom-c.top,x:c.left,y:c.top}}function aIt(s){const{width:t,height:n}=prt(s);return{width:t,height:n}}function iIt(s,t,n){const r=Cw(t),a=Uw(t),i=n==="fixed",l=iM(s,!0,i,t);let o={scrollLeft:0,scrollTop:0};const c=_4(0);if(r||!r&&!i)if((SD(t)!=="body"||A$(a))&&(o=x0e(t)),r){const f=iM(t,!0,i,t);c.x=f.x+t.clientLeft,c.y=f.y+t.clientTop}else a&&(c.x=jSe(a));let d=0,u=0;if(a&&!r&&!i){const f=a.getBoundingClientRect();u=f.top+o.scrollTop,d=f.left+o.scrollLeft-jSe(a,f)}const h=l.left+o.scrollLeft-c.x-d,p=l.top+o.scrollTop-c.y-u;return{x:h,y:p,width:l.width,height:l.height}}function bwe(s){return Nb(s).position==="static"}function F9e(s,t){if(!Cw(s)||Nb(s).position==="fixed")return null;if(t)return t(s);let n=s.offsetParent;return Uw(s)===n&&(n=n.ownerDocument.body),n}function grt(s,t){const n=iy(s);if(f0e(s))return n;if(!Cw(s)){let a=j4(s);for(;a&&!c8(a);){if(jb(a)&&!bwe(a))return a;a=j4(a)}return n}let r=F9e(s,t);for(;r&&K6t(r)&&bwe(r);)r=F9e(r,t);return r&&c8(r)&&bwe(r)&&!YEe(r)?n:r||Y6t(s)||n}const oIt=async function(s){const t=this.getOffsetParent||grt,n=this.getDimensions,r=await n(s.floating);return{reference:iIt(s.reference,await t(s.floating),s.strategy),floating:{x:0,y:0,width:r.width,height:r.height}}};function lIt(s){return Nb(s).direction==="rtl"}const cIt={convertOffsetParentRelativeRectToViewportRelativeRect:X6t,getDocumentElement:Uw,getClippingRect:rIt,getOffsetParent:grt,getElementRects:oIt,getClientRects:J6t,getDimensions:aIt,getScale:bL,isElement:jb,isRTL:lIt};function dIt(s,t){let n=null,r;const a=Uw(s);function i(){var o;clearTimeout(r),(o=n)==null||o.disconnect(),n=null}function l(o,c){o===void 0&&(o=!1),c===void 0&&(c=1),i();const{left:d,top:u,width:h,height:p}=s.getBoundingClientRect();if(o||t(),!h||!p)return;const f=IV(u),y=IV(a.clientWidth-(d+h)),_=IV(a.clientHeight-(u+p)),v=IV(d),w={rootMargin:-f+"px "+-y+"px "+-_+"px "+-v+"px",threshold:V0(0,b4(1,c))||1};let S=!0;function A(E){const O=E[0].intersectionRatio;if(O!==c){if(!S)return l();O?l(!1,O):r=setTimeout(()=>{l(!1,1e-7)},1e3)}S=!1}try{n=new IntersectionObserver(A,{...w,root:a.ownerDocument})}catch{n=new IntersectionObserver(A,w)}n.observe(s)}return l(!0),i}function uIt(s,t,n,r){r===void 0&&(r={});const{ancestorScroll:a=!0,ancestorResize:i=!0,elementResize:l=typeof ResizeObserver=="function",layoutShift:o=typeof IntersectionObserver=="function",animationFrame:c=!1}=r,d=QEe(s),u=a||i?[...d?Hz(d):[],...Hz(t)]:[];u.forEach(j=>{a&&j.addEventListener("scroll",n,{passive:!0}),i&&j.addEventListener("resize",n)});const h=d&&o?dIt(d,n):null;let p=-1,f=null;l&&(f=new ResizeObserver(j=>{let[w]=j;w&&w.target===d&&f&&(f.unobserve(t),cancelAnimationFrame(p),p=requestAnimationFrame(()=>{var S;(S=f)==null||S.observe(t)})),n()}),d&&!c&&f.observe(d),f.observe(t));let y,_=c?iM(s):null;c&&v();function v(){const j=iM(s);_&&(j.x!==_.x||j.y!==_.y||j.width!==_.width||j.height!==_.height)&&n(),_=j,y=requestAnimationFrame(v)}return n(),()=>{var j;u.forEach(w=>{a&&w.removeEventListener("scroll",n),i&&w.removeEventListener("resize",n)}),h==null||h(),(j=f)==null||j.disconnect(),f=null,c&&cancelAnimationFrame(y)}}const hIt=V6t,mIt=H6t,pIt=$6t,fIt=W6t,xIt=U6t,z9e=B6t,gIt=G6t,yIt=(s,t,n)=>{const r=new Map,a={platform:cIt,...n},i={...a.platform,_c:r};return z6t(s,t,{...a,platform:i})};var hme=typeof document<"u"?N.useLayoutEffect:N.useEffect;function Ppe(s,t){if(s===t)return!0;if(typeof s!=typeof t)return!1;if(typeof s=="function"&&s.toString()===t.toString())return!0;let n,r,a;if(s&&t&&typeof s=="object"){if(Array.isArray(s)){if(n=s.length,n!==t.length)return!1;for(r=n;r--!==0;)if(!Ppe(s[r],t[r]))return!1;return!0}if(a=Object.keys(s),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!{}.hasOwnProperty.call(t,a[r]))return!1;for(r=n;r--!==0;){const i=a[r];if(!(i==="_owner"&&s.$$typeof)&&!Ppe(s[i],t[i]))return!1}return!0}return s!==s&&t!==t}function yrt(s){return typeof window>"u"?1:(s.ownerDocument.defaultView||window).devicePixelRatio||1}function B9e(s,t){const n=yrt(s);return Math.round(t*n)/n}function _we(s){const t=N.useRef(s);return hme(()=>{t.current=s}),t}function vIt(s){s===void 0&&(s={});const{placement:t="bottom",strategy:n="absolute",middleware:r=[],platform:a,elements:{reference:i,floating:l}={},transform:o=!0,whileElementsMounted:c,open:d}=s,[u,h]=N.useState({x:0,y:0,strategy:n,placement:t,middlewareData:{},isPositioned:!1}),[p,f]=N.useState(r);Ppe(p,r)||f(r);const[y,_]=N.useState(null),[v,j]=N.useState(null),w=N.useCallback(he=>{he!==O.current&&(O.current=he,_(he))},[]),S=N.useCallback(he=>{he!==D.current&&(D.current=he,j(he))},[]),A=i||y,E=l||v,O=N.useRef(null),D=N.useRef(null),I=N.useRef(u),F=c!=null,z=_we(c),H=_we(a),Z=_we(d),Y=N.useCallback(()=>{if(!O.current||!D.current)return;const he={placement:t,strategy:n,middleware:p};H.current&&(he.platform=H.current),yIt(O.current,D.current,he).then(ce=>{const me={...ce,isPositioned:Z.current!==!1};W.current&&!Ppe(I.current,me)&&(I.current=me,qx.flushSync(()=>{h(me)}))})},[p,t,n,H,Z]);hme(()=>{d===!1&&I.current.isPositioned&&(I.current.isPositioned=!1,h(he=>({...he,isPositioned:!1})))},[d]);const W=N.useRef(!1);hme(()=>(W.current=!0,()=>{W.current=!1}),[]),hme(()=>{if(A&&(O.current=A),E&&(D.current=E),A&&E){if(z.current)return z.current(A,E,Y);Y()}},[A,E,Y,z,F]);const ee=N.useMemo(()=>({reference:O,floating:D,setReference:w,setFloating:S}),[w,S]),se=N.useMemo(()=>({reference:A,floating:E}),[A,E]),oe=N.useMemo(()=>{const he={position:n,left:0,top:0};if(!se.floating)return he;const ce=B9e(se.floating,u.x),me=B9e(se.floating,u.y);return o?{...he,transform:"translate("+ce+"px, "+me+"px)",...yrt(se.floating)>=1.5&&{willChange:"transform"}}:{position:n,left:ce,top:me}},[n,o,se.floating,u.x,u.y]);return N.useMemo(()=>({...u,update:Y,refs:ee,elements:se,floatingStyles:oe}),[u,Y,ee,se,oe])}const bIt=s=>{function t(n){return{}.hasOwnProperty.call(n,"current")}return{name:"arrow",options:s,fn(n){const{element:r,padding:a}=typeof s=="function"?s(n):s;return r&&t(r)?r.current!=null?z9e({element:r.current,padding:a}).fn(n):{}:r?z9e({element:r,padding:a}).fn(n):{}}}},_It=(s,t)=>({...hIt(s),options:[s,t]}),wIt=(s,t)=>({...mIt(s),options:[s,t]}),jIt=(s,t)=>({...gIt(s),options:[s,t]}),NIt=(s,t)=>({...pIt(s),options:[s,t]}),kIt=(s,t)=>({...fIt(s),options:[s,t]}),SIt=(s,t)=>({...xIt(s),options:[s,t]}),CIt=(s,t)=>({...bIt(s),options:[s,t]});var TIt="Arrow",vrt=N.forwardRef((s,t)=>{const{children:n,width:r=10,height:a=5,...i}=s;return e.jsx(Yr.svg,{...i,ref:t,width:r,height:a,viewBox:"0 0 30 10",preserveAspectRatio:"none",children:s.asChild?n:e.jsx("polygon",{points:"0,0 30,0 15,10"})})});vrt.displayName=TIt;var EIt=vrt;function M$(s){const[t,n]=N.useState(void 0);return lh(()=>{if(s){n({width:s.offsetWidth,height:s.offsetHeight});const r=new ResizeObserver(a=>{if(!Array.isArray(a)||!a.length)return;const i=a[0];let l,o;if("borderBoxSize"in i){const c=i.borderBoxSize,d=Array.isArray(c)?c[0]:c;l=d.inlineSize,o=d.blockSize}else l=s.offsetWidth,o=s.offsetHeight;n({width:l,height:o})});return r.observe(s,{box:"border-box"}),()=>r.unobserve(s)}else n(void 0)},[s]),t}var XEe="Popper",[brt,qw]=uu(XEe),[AIt,_rt]=brt(XEe),wrt=s=>{const{__scopePopper:t,children:n}=s,[r,a]=N.useState(null);return e.jsx(AIt,{scope:t,anchor:r,onAnchorChange:a,children:n})};wrt.displayName=XEe;var jrt="PopperAnchor",Nrt=N.forwardRef((s,t)=>{const{__scopePopper:n,virtualRef:r,...a}=s,i=_rt(jrt,n),l=N.useRef(null),o=ji(t,l);return N.useEffect(()=>{i.onAnchorChange((r==null?void 0:r.current)||l.current)}),r?null:e.jsx(Yr.div,{...a,ref:o})});Nrt.displayName=jrt;var JEe="PopperContent",[MIt,IIt]=brt(JEe),krt=N.forwardRef((s,t)=>{var Me,Pe,Re,Ae,Be,we;const{__scopePopper:n,side:r="bottom",sideOffset:a=0,align:i="center",alignOffset:l=0,arrowPadding:o=0,avoidCollisions:c=!0,collisionBoundary:d=[],collisionPadding:u=0,sticky:h="partial",hideWhenDetached:p=!1,updatePositionStrategy:f="optimized",onPlaced:y,..._}=s,v=_rt(JEe,n),[j,w]=N.useState(null),S=ji(t,Je=>w(Je)),[A,E]=N.useState(null),O=M$(A),D=(O==null?void 0:O.width)??0,I=(O==null?void 0:O.height)??0,F=r+(i!=="center"?"-"+i:""),z=typeof u=="number"?u:{top:0,right:0,bottom:0,left:0,...u},H=Array.isArray(d)?d:[d],Z=H.length>0,Y={padding:z,boundary:H.filter(LIt),altBoundary:Z},{refs:W,floatingStyles:ee,placement:se,isPositioned:oe,middlewareData:he}=vIt({strategy:"fixed",placement:F,whileElementsMounted:(...Je)=>uIt(...Je,{animationFrame:f==="always"}),elements:{reference:v.anchor},middleware:[_It({mainAxis:a+I,alignmentAxis:l}),c&&wIt({mainAxis:!0,crossAxis:!1,limiter:h==="partial"?jIt():void 0,...Y}),c&&NIt({...Y}),kIt({...Y,apply:({elements:Je,rects:ke,availableWidth:it,availableHeight:je})=>{const{width:He,height:$e}=ke.reference,Ke=Je.floating.style;Ke.setProperty("--radix-popper-available-width",`${it}px`),Ke.setProperty("--radix-popper-available-height",`${je}px`),Ke.setProperty("--radix-popper-anchor-width",`${He}px`),Ke.setProperty("--radix-popper-anchor-height",`${$e}px`)}}),A&&CIt({element:A,padding:o}),DIt({arrowWidth:D,arrowHeight:I}),p&&SIt({strategy:"referenceHidden",...Y})]}),[ce,me]=Trt(se),le=rh(y);lh(()=>{oe&&(le==null||le())},[oe,le]);const ve=(Me=he.arrow)==null?void 0:Me.x,ge=(Pe=he.arrow)==null?void 0:Pe.y,Te=((Re=he.arrow)==null?void 0:Re.centerOffset)!==0,[Ie,Ce]=N.useState();return lh(()=>{j&&Ce(window.getComputedStyle(j).zIndex)},[j]),e.jsx("div",{ref:W.setFloating,"data-radix-popper-content-wrapper":"",style:{...ee,transform:oe?ee.transform:"translate(0, -200%)",minWidth:"max-content",zIndex:Ie,"--radix-popper-transform-origin":[(Ae=he.transformOrigin)==null?void 0:Ae.x,(Be=he.transformOrigin)==null?void 0:Be.y].join(" "),...((we=he.hide)==null?void 0:we.referenceHidden)&&{visibility:"hidden",pointerEvents:"none"}},dir:s.dir,children:e.jsx(MIt,{scope:n,placedSide:ce,onArrowChange:E,arrowX:ve,arrowY:ge,shouldHideArrow:Te,children:e.jsx(Yr.div,{"data-side":ce,"data-align":me,..._,ref:S,style:{..._.style,animation:oe?void 0:"none"}})})})});krt.displayName=JEe;var Srt="PopperArrow",PIt={top:"bottom",right:"left",bottom:"top",left:"right"},Crt=N.forwardRef(function(t,n){const{__scopePopper:r,...a}=t,i=IIt(Srt,r),l=PIt[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(EIt,{...a,ref:n,style:{...a.style,display:"block"}})})});Crt.displayName=Srt;function LIt(s){return s!==null}var DIt=s=>({name:"transformOrigin",options:s,fn(t){var v,j,w;const{placement:n,rects:r,middlewareData:a}=t,l=((v=a.arrow)==null?void 0:v.centerOffset)!==0,o=l?0:s.arrowWidth,c=l?0:s.arrowHeight,[d,u]=Trt(n),h={start:"0%",center:"50%",end:"100%"}[u],p=(((j=a.arrow)==null?void 0:j.x)??0)+o/2,f=(((w=a.arrow)==null?void 0:w.y)??0)+c/2;let y="",_="";return d==="bottom"?(y=l?h:`${p}px`,_=`${-c}px`):d==="top"?(y=l?h:`${p}px`,_=`${r.floating.height+c}px`):d==="right"?(y=`${-c}px`,_=l?h:`${f}px`):d==="left"&&(y=`${r.floating.width+c}px`,_=l?h:`${f}px`),{data:{x:y,y:_}}}});function Trt(s){const[t,n="center"]=s.split("-");return[t,n]}var I$=wrt,CD=Nrt,P$=krt,L$=Crt,[g0e,Lpn]=uu("Tooltip",[qw]),y0e=qw(),Ert="TooltipProvider",RIt=700,NSe="tooltip.open",[OIt,eAe]=g0e(Ert),Art=s=>{const{__scopeTooltip:t,delayDuration:n=RIt,skipDelayDuration:r=300,disableHoverableContent:a=!1,children:i}=s,l=N.useRef(!0),o=N.useRef(!1),c=N.useRef(0);return N.useEffect(()=>{const d=c.current;return()=>window.clearTimeout(d)},[]),e.jsx(OIt,{scope:t,isOpenDelayedRef:l,delayDuration:n,onOpen:N.useCallback(()=>{window.clearTimeout(c.current),l.current=!1},[]),onClose:N.useCallback(()=>{window.clearTimeout(c.current),c.current=window.setTimeout(()=>l.current=!0,r)},[r]),isPointerInTransitRef:o,onPointerInTransitChange:N.useCallback(d=>{o.current=d},[]),disableHoverableContent:a,children:i})};Art.displayName=Ert;var Gz="Tooltip",[FIt,v0e]=g0e(Gz),Mrt=s=>{const{__scopeTooltip:t,children:n,open:r,defaultOpen:a,onOpenChange:i,disableHoverableContent:l,delayDuration:o}=s,c=eAe(Gz,s.__scopeTooltip),d=y0e(t),[u,h]=N.useState(null),p=om(),f=N.useRef(0),y=l??c.disableHoverableContent,_=o??c.delayDuration,v=N.useRef(!1),[j,w]=cm({prop:r,defaultProp:a??!1,onChange:D=>{D?(c.onOpen(),document.dispatchEvent(new CustomEvent(NSe))):c.onClose(),i==null||i(D)},caller:Gz}),S=N.useMemo(()=>j?v.current?"delayed-open":"instant-open":"closed",[j]),A=N.useCallback(()=>{window.clearTimeout(f.current),f.current=0,v.current=!1,w(!0)},[w]),E=N.useCallback(()=>{window.clearTimeout(f.current),f.current=0,w(!1)},[w]),O=N.useCallback(()=>{window.clearTimeout(f.current),f.current=window.setTimeout(()=>{v.current=!0,w(!0),f.current=0},_)},[_,w]);return N.useEffect(()=>()=>{f.current&&(window.clearTimeout(f.current),f.current=0)},[]),e.jsx(I$,{...d,children:e.jsx(FIt,{scope:t,contentId:p,open:j,stateAttribute:S,trigger:u,onTriggerChange:h,onTriggerEnter:N.useCallback(()=>{c.isOpenDelayedRef.current?O():A()},[c.isOpenDelayedRef,O,A]),onTriggerLeave:N.useCallback(()=>{y?E():(window.clearTimeout(f.current),f.current=0)},[E,y]),onOpen:A,onClose:E,disableHoverableContent:y,children:n})})};Mrt.displayName=Gz;var kSe="TooltipTrigger",Irt=N.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=v0e(kSe,n),i=eAe(kSe,n),l=y0e(n),o=N.useRef(null),c=ji(t,o,a.onTriggerChange),d=N.useRef(!1),u=N.useRef(!1),h=N.useCallback(()=>d.current=!1,[]);return N.useEffect(()=>()=>document.removeEventListener("pointerup",h),[h]),e.jsx(CD,{asChild:!0,...l,children:e.jsx(Yr.button,{"aria-describedby":a.open?a.contentId:void 0,"data-state":a.stateAttribute,...r,ref:c,onPointerMove:xr(s.onPointerMove,p=>{p.pointerType!=="touch"&&!u.current&&!i.isPointerInTransitRef.current&&(a.onTriggerEnter(),u.current=!0)}),onPointerLeave:xr(s.onPointerLeave,()=>{a.onTriggerLeave(),u.current=!1}),onPointerDown:xr(s.onPointerDown,()=>{a.open&&a.onClose(),d.current=!0,document.addEventListener("pointerup",h,{once:!0})}),onFocus:xr(s.onFocus,()=>{d.current||a.onOpen()}),onBlur:xr(s.onBlur,a.onClose),onClick:xr(s.onClick,a.onClose)})})});Irt.displayName=kSe;var zIt="TooltipPortal",[Dpn,BIt]=g0e(zIt,{forceMount:void 0}),d8="TooltipContent",Prt=N.forwardRef((s,t)=>{const n=BIt(d8,s.__scopeTooltip),{forceMount:r=n.forceMount,side:a="top",...i}=s,l=v0e(d8,s.__scopeTooltip);return e.jsx(Lh,{present:r||l.open,children:l.disableHoverableContent?e.jsx(Lrt,{side:a,...i,ref:t}):e.jsx($It,{side:a,...i,ref:t})})}),$It=N.forwardRef((s,t)=>{const n=v0e(d8,s.__scopeTooltip),r=eAe(d8,s.__scopeTooltip),a=N.useRef(null),i=ji(t,a),[l,o]=N.useState(null),{trigger:c,onClose:d}=n,u=a.current,{onPointerInTransitChange:h}=r,p=N.useCallback(()=>{o(null),h(!1)},[h]),f=N.useCallback((y,_)=>{const v=y.currentTarget,j={x:y.clientX,y:y.clientY},w=GIt(j,v.getBoundingClientRect()),S=WIt(j,w),A=KIt(_.getBoundingClientRect()),E=ZIt([...S,...A]);o(E),h(!0)},[h]);return N.useEffect(()=>()=>p(),[p]),N.useEffect(()=>{if(c&&u){const y=v=>f(v,u),_=v=>f(v,c);return c.addEventListener("pointerleave",y),u.addEventListener("pointerleave",_),()=>{c.removeEventListener("pointerleave",y),u.removeEventListener("pointerleave",_)}}},[c,u,f,p]),N.useEffect(()=>{if(l){const y=_=>{const v=_.target,j={x:_.clientX,y:_.clientY},w=(c==null?void 0:c.contains(v))||(u==null?void 0:u.contains(v)),S=!YIt(j,l);w?p():S&&(p(),d())};return document.addEventListener("pointermove",y),()=>document.removeEventListener("pointermove",y)}},[c,u,l,d,p]),e.jsx(Lrt,{...s,ref:i})}),[UIt,qIt]=g0e(Gz,{isInside:!1}),VIt=Tnt("TooltipContent"),Lrt=N.forwardRef((s,t)=>{const{__scopeTooltip:n,children:r,"aria-label":a,onEscapeKeyDown:i,onPointerDownOutside:l,...o}=s,c=v0e(d8,n),d=y0e(n),{onClose:u}=c;return N.useEffect(()=>(document.addEventListener(NSe,u),()=>document.removeEventListener(NSe,u)),[u]),N.useEffect(()=>{if(c.trigger){const h=p=>{const f=p.target;f!=null&&f.contains(c.trigger)&&u()};return window.addEventListener("scroll",h,{capture:!0}),()=>window.removeEventListener("scroll",h,{capture:!0})}},[c.trigger,u]),e.jsx(O4,{asChild:!0,disableOutsidePointerEvents:!1,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:h=>h.preventDefault(),onDismiss:u,children:e.jsxs(P$,{"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(VIt,{children:r}),e.jsx(UIt,{scope:n,isInside:!0,children:e.jsx(WAt,{id:c.contentId,role:"tooltip",children:a||r})})]})})});Prt.displayName=d8;var Drt="TooltipArrow",HIt=N.forwardRef((s,t)=>{const{__scopeTooltip:n,...r}=s,a=y0e(n);return qIt(Drt,n).isInside?null:e.jsx(L$,{...a,...r,ref:t})});HIt.displayName=Drt;function GIt(s,t){const n=Math.abs(t.top-s.y),r=Math.abs(t.bottom-s.y),a=Math.abs(t.right-s.x),i=Math.abs(t.left-s.x);switch(Math.min(n,r,a,i)){case i:return"left";case a:return"right";case n:return"top";case r:return"bottom";default:throw new Error("unreachable")}}function WIt(s,t,n=5){const r=[];switch(t){case"top":r.push({x:s.x-n,y:s.y+n},{x:s.x+n,y:s.y+n});break;case"bottom":r.push({x:s.x-n,y:s.y-n},{x:s.x+n,y:s.y-n});break;case"left":r.push({x:s.x+n,y:s.y-n},{x:s.x+n,y:s.y+n});break;case"right":r.push({x:s.x-n,y:s.y-n},{x:s.x-n,y:s.y+n});break}return r}function KIt(s){const{top:t,right:n,bottom:r,left:a}=s;return[{x:a,y:t},{x:n,y:t},{x:n,y:r},{x:a,y:r}]}function YIt(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=p>r&&n<(h-d)*(r-u)/(p-u)+d&&(a=!a)}return a}function ZIt(s){const t=s.slice();return t.sort((n,r)=>n.xr.x?1:n.yr.y?1:0),QIt(t)}function QIt(s){if(s.length<=1)return s.slice();const t=[];for(let r=0;r=2;){const i=t[t.length-1],l=t[t.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))t.pop();else break}t.push(a)}t.pop();const n=[];for(let r=s.length-1;r>=0;r--){const a=s[r];for(;n.length>=2;){const i=n[n.length-1],l=n[n.length-2];if((i.x-l.x)*(a.y-l.y)>=(i.y-l.y)*(a.x-l.x))n.pop();else break}n.push(a)}return n.pop(),t.length===1&&n.length===1&&t[0].x===n[0].x&&t[0].y===n[0].y?t:t.concat(n)}var XIt=Art,JIt=Mrt,ePt=Irt,Rrt=Prt;const Vw=XIt,Bc=JIt,$c=ePt,Nc=N.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(Rrt,{ref:r,sideOffset:t,className:Mt("z-50 overflow-hidden rounded-md border bg-popover px-3 py-1.5 text-sm text-popover-foreground shadow-md animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n}));Nc.displayName=Rrt.displayName;var TD=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(){}},oM=typeof window>"u"||"Deno"in globalThis;function $x(){}function tPt(s,t){return typeof s=="function"?s(t):s}function SSe(s){return typeof s=="number"&&s>=0&&s!==1/0}function Ort(s,t){return Math.max(s+(t||0)-Date.now(),0)}function a4(s,t){return typeof s=="function"?s(t):s}function xv(s,t){return typeof s=="function"?s(t):s}function $9e(s,t){const{type:n="all",exact:r,fetchStatus:a,predicate:i,queryKey:l,stale:o}=s;if(l){if(r){if(t.queryHash!==tAe(l,t.options))return!1}else if(!Wz(t.queryKey,l))return!1}if(n!=="all"){const c=t.isActive();if(n==="active"&&!c||n==="inactive"&&c)return!1}return!(typeof o=="boolean"&&t.isStale()!==o||a&&a!==t.state.fetchStatus||i&&!i(t))}function U9e(s,t){const{exact:n,status:r,predicate:a,mutationKey:i}=s;if(i){if(!t.options.mutationKey)return!1;if(n){if(lM(t.options.mutationKey)!==lM(i))return!1}else if(!Wz(t.options.mutationKey,i))return!1}return!(r&&t.state.status!==r||a&&!a(t))}function tAe(s,t){return((t==null?void 0:t.queryKeyHashFn)||lM)(s)}function lM(s){return JSON.stringify(s,(t,n)=>CSe(n)?Object.keys(n).sort().reduce((r,a)=>(r[a]=n[a],r),{}):n)}function Wz(s,t){return s===t?!0:typeof s!=typeof t?!1:s&&t&&typeof s=="object"&&typeof t=="object"?Object.keys(t).every(n=>Wz(s[n],t[n])):!1}function Frt(s,t){if(s===t)return s;const n=q9e(s)&&q9e(t);if(n||CSe(s)&&CSe(t)){const r=n?s:Object.keys(s),a=r.length,i=n?t:Object.keys(t),l=i.length,o=n?[]:{},c=new Set(r);let d=0;for(let u=0;u{setTimeout(t,s)})}function TSe(s,t,n){return typeof n.structuralSharing=="function"?n.structuralSharing(s,t):n.structuralSharing!==!1?Frt(s,t):t}function nPt(s,t,n=0){const r=[...s,t];return n&&r.length>n?r.slice(1):r}function rPt(s,t,n=0){const r=[t,...s];return n&&r.length>n?r.slice(0,-1):r}var sAe=Symbol();function zrt(s,t){return!s.queryFn&&(t!=null&&t.initialPromise)?()=>t.initialPromise:!s.queryFn||s.queryFn===sAe?()=>Promise.reject(new Error(`Missing queryFn: '${s.queryHash}'`)):s.queryFn}function Brt(s,t){return typeof s=="function"?s(...t):!!s}var sA,uS,VL,ntt,aPt=(ntt=class extends TD{constructor(){super();Ri(this,sA);Ri(this,uS);Ri(this,VL);$a(this,VL,t=>{if(!oM&&window.addEventListener){const n=()=>t();return window.addEventListener("visibilitychange",n,!1),()=>{window.removeEventListener("visibilitychange",n)}}})}onSubscribe(){Zs(this,uS)||this.setEventListener(Zs(this,VL))}onUnsubscribe(){var t;this.hasListeners()||((t=Zs(this,uS))==null||t.call(this),$a(this,uS,void 0))}setEventListener(t){var n;$a(this,VL,t),(n=Zs(this,uS))==null||n.call(this),$a(this,uS,t(r=>{typeof r=="boolean"?this.setFocused(r):this.onFocus()}))}setFocused(t){Zs(this,sA)!==t&&($a(this,sA,t),this.onFocus())}onFocus(){const t=this.isFocused();this.listeners.forEach(n=>{n(t)})}isFocused(){var t;return typeof Zs(this,sA)=="boolean"?Zs(this,sA):((t=globalThis.document)==null?void 0:t.visibilityState)!=="hidden"}},sA=new WeakMap,uS=new WeakMap,VL=new WeakMap,ntt),nAe=new aPt,HL,hS,GL,rtt,iPt=(rtt=class extends TD{constructor(){super();Ri(this,HL,!0);Ri(this,hS);Ri(this,GL);$a(this,GL,t=>{if(!oM&&window.addEventListener){const n=()=>t(!0),r=()=>t(!1);return window.addEventListener("online",n,!1),window.addEventListener("offline",r,!1),()=>{window.removeEventListener("online",n),window.removeEventListener("offline",r)}}})}onSubscribe(){Zs(this,hS)||this.setEventListener(Zs(this,GL))}onUnsubscribe(){var t;this.hasListeners()||((t=Zs(this,hS))==null||t.call(this),$a(this,hS,void 0))}setEventListener(t){var n;$a(this,GL,t),(n=Zs(this,hS))==null||n.call(this),$a(this,hS,t(this.setOnline.bind(this)))}setOnline(t){Zs(this,HL)!==t&&($a(this,HL,t),this.listeners.forEach(r=>{r(t)}))}isOnline(){return Zs(this,HL)}},HL=new WeakMap,hS=new WeakMap,GL=new WeakMap,rtt),Dpe=new iPt;function ESe(){let s,t;const n=new Promise((a,i)=>{s=a,t=i});n.status="pending",n.catch(()=>{});function r(a){Object.assign(n,a),delete n.resolve,delete n.reject}return n.resolve=a=>{r({status:"fulfilled",value:a}),s(a)},n.reject=a=>{r({status:"rejected",reason:a}),t(a)},n}function oPt(s){return Math.min(1e3*2**s,3e4)}function $rt(s){return(s??"online")==="online"?Dpe.isOnline():!0}var Urt=class extends Error{constructor(s){super("CancelledError"),this.revert=s==null?void 0:s.revert,this.silent=s==null?void 0:s.silent}};function wwe(s){return s instanceof Urt}function qrt(s){let t=!1,n=0,r=!1,a;const i=ESe(),l=_=>{var v;r||(p(new Urt(_)),(v=s.abort)==null||v.call(s))},o=()=>{t=!0},c=()=>{t=!1},d=()=>nAe.isFocused()&&(s.networkMode==="always"||Dpe.isOnline())&&s.canRun(),u=()=>$rt(s.networkMode)&&s.canRun(),h=_=>{var v;r||(r=!0,(v=s.onSuccess)==null||v.call(s,_),a==null||a(),i.resolve(_))},p=_=>{var v;r||(r=!0,(v=s.onError)==null||v.call(s,_),a==null||a(),i.reject(_))},f=()=>new Promise(_=>{var v;a=j=>{(r||d())&&_(j)},(v=s.onPause)==null||v.call(s)}).then(()=>{var _;a=void 0,r||(_=s.onContinue)==null||_.call(s)}),y=()=>{if(r)return;let _;const v=n===0?s.initialPromise:void 0;try{_=v??s.fn()}catch(j){_=Promise.reject(j)}Promise.resolve(_).then(h).catch(j=>{var O;if(r)return;const w=s.retry??(oM?0:3),S=s.retryDelay??oPt,A=typeof S=="function"?S(n,j):S,E=w===!0||typeof w=="number"&&nd()?void 0:f()).then(()=>{t?p(j):y()})})};return{promise:i,cancel:l,continue:()=>(a==null||a(),i),cancelRetry:o,continueRetry:c,canStart:u,start:()=>(u()?y():f().then(y),i)}}var lPt=s=>setTimeout(s,0);function cPt(){let s=[],t=0,n=o=>{o()},r=o=>{o()},a=lPt;const i=o=>{t?s.push(o):a(()=>{n(o)})},l=()=>{const o=s;s=[],o.length&&a(()=>{r(()=>{o.forEach(c=>{n(c)})})})};return{batch:o=>{let c;t++;try{c=o()}finally{t--,t||l()}return c},batchCalls:o=>(...c)=>{i(()=>{o(...c)})},schedule:i,setNotifyFunction:o=>{n=o},setBatchNotifyFunction:o=>{r=o},setScheduler:o=>{a=o}}}var Pm=cPt(),nA,att,Vrt=(att=class{constructor(){Ri(this,nA)}destroy(){this.clearGcTimeout()}scheduleGc(){this.clearGcTimeout(),SSe(this.gcTime)&&$a(this,nA,setTimeout(()=>{this.optionalRemove()},this.gcTime))}updateGcTime(s){this.gcTime=Math.max(this.gcTime||0,s??(oM?1/0:5*60*1e3))}clearGcTimeout(){Zs(this,nA)&&(clearTimeout(Zs(this,nA)),$a(this,nA,void 0))}},nA=new WeakMap,att),WL,rA,fv,aA,qf,b$,iA,q1,h2,itt,dPt=(itt=class extends Vrt{constructor(t){super();Ri(this,q1);Ri(this,WL);Ri(this,rA);Ri(this,fv);Ri(this,aA);Ri(this,qf);Ri(this,b$);Ri(this,iA);$a(this,iA,!1),$a(this,b$,t.defaultOptions),this.setOptions(t.options),this.observers=[],$a(this,aA,t.client),$a(this,fv,Zs(this,aA).getQueryCache()),this.queryKey=t.queryKey,this.queryHash=t.queryHash,$a(this,WL,uPt(this.options)),this.state=t.state??Zs(this,WL),this.scheduleGc()}get meta(){return this.options.meta}get promise(){var t;return(t=Zs(this,qf))==null?void 0:t.promise}setOptions(t){this.options={...Zs(this,b$),...t},this.updateGcTime(this.options.gcTime)}optionalRemove(){!this.observers.length&&this.state.fetchStatus==="idle"&&Zs(this,fv).remove(this)}setData(t,n){const r=TSe(this.state.data,t,this.options);return Ho(this,q1,h2).call(this,{data:r,type:"success",dataUpdatedAt:n==null?void 0:n.updatedAt,manual:n==null?void 0:n.manual}),r}setState(t,n){Ho(this,q1,h2).call(this,{type:"setState",state:t,setStateOptions:n})}cancel(t){var r,a;const n=(r=Zs(this,qf))==null?void 0:r.promise;return(a=Zs(this,qf))==null||a.cancel(t),n?n.then($x).catch($x):Promise.resolve()}destroy(){super.destroy(),this.cancel({silent:!0})}reset(){this.destroy(),this.setState(Zs(this,WL))}isActive(){return this.observers.some(t=>xv(t.options.enabled,this)!==!1)}isDisabled(){return this.getObserversCount()>0?!this.isActive():this.options.queryFn===sAe||this.state.dataUpdateCount+this.state.errorUpdateCount===0}isStatic(){return this.getObserversCount()>0?this.observers.some(t=>a4(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:!Ort(this.state.dataUpdatedAt,t)}onFocus(){var n;const t=this.observers.find(r=>r.shouldFetchOnWindowFocus());t==null||t.refetch({cancelRefetch:!1}),(n=Zs(this,qf))==null||n.continue()}onOnline(){var n;const t=this.observers.find(r=>r.shouldFetchOnReconnect());t==null||t.refetch({cancelRefetch:!1}),(n=Zs(this,qf))==null||n.continue()}addObserver(t){this.observers.includes(t)||(this.observers.push(t),this.clearGcTimeout(),Zs(this,fv).notify({type:"observerAdded",query:this,observer:t}))}removeObserver(t){this.observers.includes(t)&&(this.observers=this.observers.filter(n=>n!==t),this.observers.length||(Zs(this,qf)&&(Zs(this,iA)?Zs(this,qf).cancel({revert:!0}):Zs(this,qf).cancelRetry()),this.scheduleGc()),Zs(this,fv).notify({type:"observerRemoved",query:this,observer:t}))}getObserversCount(){return this.observers.length}invalidate(){this.state.isInvalidated||Ho(this,q1,h2).call(this,{type:"invalidate"})}fetch(t,n){var d,u,h;if(this.state.fetchStatus!=="idle"){if(this.state.data!==void 0&&(n!=null&&n.cancelRefetch))this.cancel({silent:!0});else if(Zs(this,qf))return Zs(this,qf).continueRetry(),Zs(this,qf).promise}if(t&&this.setOptions(t),!this.options.queryFn){const p=this.observers.find(f=>f.options.queryFn);p&&this.setOptions(p.options)}const r=new AbortController,a=p=>{Object.defineProperty(p,"signal",{enumerable:!0,get:()=>($a(this,iA,!0),r.signal)})},i=()=>{const p=zrt(this.options,n),y=(()=>{const _={client:Zs(this,aA),queryKey:this.queryKey,meta:this.meta};return a(_),_})();return $a(this,iA,!1),this.options.persister?this.options.persister(p,y,this):p(y)},o=(()=>{const p={fetchOptions:n,options:this.options,queryKey:this.queryKey,client:Zs(this,aA),state:this.state,fetchFn:i};return a(p),p})();(d=this.options.behavior)==null||d.onFetch(o,this),$a(this,rA,this.state),(this.state.fetchStatus==="idle"||this.state.fetchMeta!==((u=o.fetchOptions)==null?void 0:u.meta))&&Ho(this,q1,h2).call(this,{type:"fetch",meta:(h=o.fetchOptions)==null?void 0:h.meta});const c=p=>{var f,y,_,v;wwe(p)&&p.silent||Ho(this,q1,h2).call(this,{type:"error",error:p}),wwe(p)||((y=(f=Zs(this,fv).config).onError)==null||y.call(f,p,this),(v=(_=Zs(this,fv).config).onSettled)==null||v.call(_,this.state.data,p,this)),this.scheduleGc()};return $a(this,qf,qrt({initialPromise:n==null?void 0:n.initialPromise,fn:o.fetchFn,abort:r.abort.bind(r),onSuccess:p=>{var f,y,_,v;if(p===void 0){c(new Error(`${this.queryHash} data is undefined`));return}try{this.setData(p)}catch(j){c(j);return}(y=(f=Zs(this,fv).config).onSuccess)==null||y.call(f,p,this),(v=(_=Zs(this,fv).config).onSettled)==null||v.call(_,p,this.state.error,this),this.scheduleGc()},onError:c,onFail:(p,f)=>{Ho(this,q1,h2).call(this,{type:"failed",failureCount:p,error:f})},onPause:()=>{Ho(this,q1,h2).call(this,{type:"pause"})},onContinue:()=>{Ho(this,q1,h2).call(this,{type:"continue"})},retry:o.options.retry,retryDelay:o.options.retryDelay,networkMode:o.options.networkMode,canRun:()=>!0})),Zs(this,qf).start()}},WL=new WeakMap,rA=new WeakMap,fv=new WeakMap,aA=new WeakMap,qf=new WeakMap,b$=new WeakMap,iA=new WeakMap,q1=new WeakSet,h2=function(t){const n=r=>{switch(t.type){case"failed":return{...r,fetchFailureCount:t.failureCount,fetchFailureReason:t.error};case"pause":return{...r,fetchStatus:"paused"};case"continue":return{...r,fetchStatus:"fetching"};case"fetch":return{...r,...Hrt(r.data,this.options),fetchMeta:t.meta??null};case"success":return $a(this,rA,void 0),{...r,data:t.data,dataUpdateCount:r.dataUpdateCount+1,dataUpdatedAt:t.dataUpdatedAt??Date.now(),error:null,isInvalidated:!1,status:"success",...!t.manual&&{fetchStatus:"idle",fetchFailureCount:0,fetchFailureReason:null}};case"error":const a=t.error;return wwe(a)&&a.revert&&Zs(this,rA)?{...Zs(this,rA),fetchStatus:"idle"}:{...r,error:a,errorUpdateCount:r.errorUpdateCount+1,errorUpdatedAt:Date.now(),fetchFailureCount:r.fetchFailureCount+1,fetchFailureReason:a,fetchStatus:"idle",status:"error"};case"invalidate":return{...r,isInvalidated:!0};case"setState":return{...r,...t.state}}};this.state=n(this.state),Pm.batch(()=>{this.observers.forEach(r=>{r.onQueryUpdate()}),Zs(this,fv).notify({query:this,type:"updated",action:t})})},itt);function Hrt(s,t){return{fetchFailureCount:0,fetchFailureReason:null,fetchStatus:$rt(t.networkMode)?"fetching":"paused",...s===void 0&&{error:null,status:"pending"}}}function uPt(s){const t=typeof s.initialData=="function"?s.initialData():s.initialData,n=t!==void 0,r=n?typeof s.initialDataUpdatedAt=="function"?s.initialDataUpdatedAt():s.initialDataUpdatedAt:0;return{data:t,dataUpdateCount:0,dataUpdatedAt:n?r??Date.now():0,error:null,errorUpdateCount:0,errorUpdatedAt:0,fetchFailureCount:0,fetchFailureReason:null,fetchMeta:null,isInvalidated:!1,status:n?"success":"pending",fetchStatus:"idle"}}var B_,ott,hPt=(ott=class extends TD{constructor(t={}){super();Ri(this,B_);this.config=t,$a(this,B_,new Map)}build(t,n,r){const a=n.queryKey,i=n.queryHash??tAe(a,n);let l=this.get(i);return l||(l=new dPt({client:t,queryKey:a,queryHash:i,options:t.defaultQueryOptions(n),state:r,defaultOptions:t.getQueryDefaults(a)}),this.add(l)),l}add(t){Zs(this,B_).has(t.queryHash)||(Zs(this,B_).set(t.queryHash,t),this.notify({type:"added",query:t}))}remove(t){const n=Zs(this,B_).get(t.queryHash);n&&(t.destroy(),n===t&&Zs(this,B_).delete(t.queryHash),this.notify({type:"removed",query:t}))}clear(){Pm.batch(()=>{this.getAll().forEach(t=>{this.remove(t)})})}get(t){return Zs(this,B_).get(t)}getAll(){return[...Zs(this,B_).values()]}find(t){const n={exact:!0,...t};return this.getAll().find(r=>$9e(n,r))}findAll(t={}){const n=this.getAll();return Object.keys(t).length>0?n.filter(r=>$9e(t,r)):n}notify(t){Pm.batch(()=>{this.listeners.forEach(n=>{n(t)})})}onFocus(){Pm.batch(()=>{this.getAll().forEach(t=>{t.onFocus()})})}onOnline(){Pm.batch(()=>{this.getAll().forEach(t=>{t.onOnline()})})}},B_=new WeakMap,ott),$_,Fx,oA,U_,Mk,ltt,mPt=(ltt=class extends Vrt{constructor(t){super();Ri(this,U_);Ri(this,$_);Ri(this,Fx);Ri(this,oA);this.mutationId=t.mutationId,$a(this,Fx,t.mutationCache),$a(this,$_,[]),this.state=t.state||Grt(),this.setOptions(t.options),this.scheduleGc()}setOptions(t){this.options=t,this.updateGcTime(this.options.gcTime)}get meta(){return this.options.meta}addObserver(t){Zs(this,$_).includes(t)||(Zs(this,$_).push(t),this.clearGcTimeout(),Zs(this,Fx).notify({type:"observerAdded",mutation:this,observer:t}))}removeObserver(t){$a(this,$_,Zs(this,$_).filter(n=>n!==t)),this.scheduleGc(),Zs(this,Fx).notify({type:"observerRemoved",mutation:this,observer:t})}optionalRemove(){Zs(this,$_).length||(this.state.status==="pending"?this.scheduleGc():Zs(this,Fx).remove(this))}continue(){var t;return((t=Zs(this,oA))==null?void 0:t.continue())??this.execute(this.state.variables)}async execute(t){var i,l,o,c,d,u,h,p,f,y,_,v,j,w,S,A,E,O,D,I;const n=()=>{Ho(this,U_,Mk).call(this,{type:"continue"})};$a(this,oA,qrt({fn:()=>this.options.mutationFn?this.options.mutationFn(t):Promise.reject(new Error("No mutationFn found")),onFail:(F,z)=>{Ho(this,U_,Mk).call(this,{type:"failed",failureCount:F,error:z})},onPause:()=>{Ho(this,U_,Mk).call(this,{type:"pause"})},onContinue:n,retry:this.options.retry??0,retryDelay:this.options.retryDelay,networkMode:this.options.networkMode,canRun:()=>Zs(this,Fx).canRun(this)}));const r=this.state.status==="pending",a=!Zs(this,oA).canStart();try{if(r)n();else{Ho(this,U_,Mk).call(this,{type:"pending",variables:t,isPaused:a}),await((l=(i=Zs(this,Fx).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&&Ho(this,U_,Mk).call(this,{type:"pending",context:z,variables:t,isPaused:a})}const F=await Zs(this,oA).start();return await((u=(d=Zs(this,Fx).config).onSuccess)==null?void 0:u.call(d,F,t,this.state.context,this)),await((p=(h=this.options).onSuccess)==null?void 0:p.call(h,F,t,this.state.context)),await((y=(f=Zs(this,Fx).config).onSettled)==null?void 0:y.call(f,F,null,this.state.variables,this.state.context,this)),await((v=(_=this.options).onSettled)==null?void 0:v.call(_,F,null,t,this.state.context)),Ho(this,U_,Mk).call(this,{type:"success",data:F}),F}catch(F){try{throw await((w=(j=Zs(this,Fx).config).onError)==null?void 0:w.call(j,F,t,this.state.context,this)),await((A=(S=this.options).onError)==null?void 0:A.call(S,F,t,this.state.context)),await((O=(E=Zs(this,Fx).config).onSettled)==null?void 0:O.call(E,void 0,F,this.state.variables,this.state.context,this)),await((I=(D=this.options).onSettled)==null?void 0:I.call(D,void 0,F,t,this.state.context)),F}finally{Ho(this,U_,Mk).call(this,{type:"error",error:F})}}finally{Zs(this,Fx).runNext(this)}}},$_=new WeakMap,Fx=new WeakMap,oA=new WeakMap,U_=new WeakSet,Mk=function(t){const n=r=>{switch(t.type){case"failed":return{...r,failureCount:t.failureCount,failureReason:t.error};case"pause":return{...r,isPaused:!0};case"continue":return{...r,isPaused:!1};case"pending":return{...r,context:t.context,data:void 0,failureCount:0,failureReason:null,error:null,isPaused:t.isPaused,status:"pending",variables:t.variables,submittedAt:Date.now()};case"success":return{...r,data:t.data,failureCount:0,failureReason:null,error:null,status:"success",isPaused:!1};case"error":return{...r,data:void 0,error:t.error,failureCount:r.failureCount+1,failureReason:t.error,isPaused:!1,status:"error"}}};this.state=n(this.state),Pm.batch(()=>{Zs(this,$_).forEach(r=>{r.onMutationUpdate(t)}),Zs(this,Fx).notify({mutation:this,type:"updated",action:t})})},ltt);function Grt(){return{context:void 0,data:void 0,error:null,failureCount:0,failureReason:null,isPaused:!1,status:"idle",variables:void 0,submittedAt:0}}var C2,V1,_$,ctt,pPt=(ctt=class extends TD{constructor(t={}){super();Ri(this,C2);Ri(this,V1);Ri(this,_$);this.config=t,$a(this,C2,new Set),$a(this,V1,new Map),$a(this,_$,0)}build(t,n,r){const a=new mPt({mutationCache:this,mutationId:++uV(this,_$)._,options:t.defaultMutationOptions(n),state:r});return this.add(a),a}add(t){Zs(this,C2).add(t);const n=PV(t);if(typeof n=="string"){const r=Zs(this,V1).get(n);r?r.push(t):Zs(this,V1).set(n,[t])}this.notify({type:"added",mutation:t})}remove(t){if(Zs(this,C2).delete(t)){const n=PV(t);if(typeof n=="string"){const r=Zs(this,V1).get(n);if(r)if(r.length>1){const a=r.indexOf(t);a!==-1&&r.splice(a,1)}else r[0]===t&&Zs(this,V1).delete(n)}}this.notify({type:"removed",mutation:t})}canRun(t){const n=PV(t);if(typeof n=="string"){const r=Zs(this,V1).get(n),a=r==null?void 0:r.find(i=>i.state.status==="pending");return!a||a===t}else return!0}runNext(t){var r;const n=PV(t);if(typeof n=="string"){const a=(r=Zs(this,V1).get(n))==null?void 0:r.find(i=>i!==t&&i.state.isPaused);return(a==null?void 0:a.continue())??Promise.resolve()}else return Promise.resolve()}clear(){Pm.batch(()=>{Zs(this,C2).forEach(t=>{this.notify({type:"removed",mutation:t})}),Zs(this,C2).clear(),Zs(this,V1).clear()})}getAll(){return Array.from(Zs(this,C2))}find(t){const n={exact:!0,...t};return this.getAll().find(r=>U9e(n,r))}findAll(t={}){return this.getAll().filter(n=>U9e(t,n))}notify(t){Pm.batch(()=>{this.listeners.forEach(n=>{n(t)})})}resumePausedMutations(){const t=this.getAll().filter(n=>n.state.isPaused);return Pm.batch(()=>Promise.all(t.map(n=>n.continue().catch($x))))}},C2=new WeakMap,V1=new WeakMap,_$=new WeakMap,ctt);function PV(s){var t;return(t=s.options.scope)==null?void 0:t.id}function Rpe(s){return{onFetch:(t,n)=>{var u,h,p,f,y;const r=t.options,a=(p=(h=(u=t.fetchOptions)==null?void 0:u.meta)==null?void 0:h.fetchMore)==null?void 0:p.direction,i=((f=t.state.data)==null?void 0:f.pages)||[],l=((y=t.state.data)==null?void 0:y.pageParams)||[];let o={pages:[],pageParams:[]},c=0;const d=async()=>{let _=!1;const v=S=>{Object.defineProperty(S,"signal",{enumerable:!0,get:()=>(t.signal.aborted?_=!0:t.signal.addEventListener("abort",()=>{_=!0}),t.signal)})},j=zrt(t.options,t.fetchOptions),w=async(S,A,E)=>{if(_)return Promise.reject();if(A==null&&S.pages.length)return Promise.resolve(S);const D=(()=>{const H={client:t.client,queryKey:t.queryKey,pageParam:A,direction:E?"backward":"forward",meta:t.options.meta};return v(H),H})(),I=await j(D),{maxPages:F}=t.options,z=E?rPt:nPt;return{pages:z(S.pages,I,F),pageParams:z(S.pageParams,A,F)}};if(a&&i.length){const S=a==="backward",A=S?Wrt:ASe,E={pages:i,pageParams:l},O=A(r,E);o=await w(E,O,S)}else{const S=s??i.length;do{const A=c===0?l[0]??r.initialPageParam:ASe(r,o);if(c>0&&A==null)break;o=await w(o,A),c++}while(c{var _,v;return(v=(_=t.options).persister)==null?void 0:v.call(_,d,{client:t.client,queryKey:t.queryKey,meta:t.options.meta,signal:t.signal},n)}:t.fetchFn=d}}}function ASe(s,{pages:t,pageParams:n}){const r=t.length-1;return t.length>0?s.getNextPageParam(t[r],t,n[r],n):void 0}function Wrt(s,{pages:t,pageParams:n}){var r;return t.length>0?(r=s.getPreviousPageParam)==null?void 0:r.call(s,t[0],t,n[0],n):void 0}function fPt(s,t){return t?ASe(s,t)!=null:!1}function xPt(s,t){return!t||!s.getPreviousPageParam?!1:Wrt(s,t)!=null}var Xu,mS,pS,KL,YL,fS,ZL,QL,dtt,gPt=(dtt=class{constructor(s={}){Ri(this,Xu);Ri(this,mS);Ri(this,pS);Ri(this,KL);Ri(this,YL);Ri(this,fS);Ri(this,ZL);Ri(this,QL);$a(this,Xu,s.queryCache||new hPt),$a(this,mS,s.mutationCache||new pPt),$a(this,pS,s.defaultOptions||{}),$a(this,KL,new Map),$a(this,YL,new Map),$a(this,fS,0)}mount(){uV(this,fS)._++,Zs(this,fS)===1&&($a(this,ZL,nAe.subscribe(async s=>{s&&(await this.resumePausedMutations(),Zs(this,Xu).onFocus())})),$a(this,QL,Dpe.subscribe(async s=>{s&&(await this.resumePausedMutations(),Zs(this,Xu).onOnline())})))}unmount(){var s,t;uV(this,fS)._--,Zs(this,fS)===0&&((s=Zs(this,ZL))==null||s.call(this),$a(this,ZL,void 0),(t=Zs(this,QL))==null||t.call(this),$a(this,QL,void 0))}isFetching(s){return Zs(this,Xu).findAll({...s,fetchStatus:"fetching"}).length}isMutating(s){return Zs(this,mS).findAll({...s,status:"pending"}).length}getQueryData(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=Zs(this,Xu).get(t.queryHash))==null?void 0:n.state.data}ensureQueryData(s){const t=this.defaultQueryOptions(s),n=Zs(this,Xu).build(this,t),r=n.state.data;return r===void 0?this.fetchQuery(s):(s.revalidateIfStale&&n.isStaleByTime(a4(t.staleTime,n))&&this.prefetchQuery(t),Promise.resolve(r))}getQueriesData(s){return Zs(this,Xu).findAll(s).map(({queryKey:t,state:n})=>{const r=n.data;return[t,r]})}setQueryData(s,t,n){const r=this.defaultQueryOptions({queryKey:s}),a=Zs(this,Xu).get(r.queryHash),i=a==null?void 0:a.state.data,l=tPt(t,i);if(l!==void 0)return Zs(this,Xu).build(this,r).setData(l,{...n,manual:!0})}setQueriesData(s,t,n){return Pm.batch(()=>Zs(this,Xu).findAll(s).map(({queryKey:r})=>[r,this.setQueryData(r,t,n)]))}getQueryState(s){var n;const t=this.defaultQueryOptions({queryKey:s});return(n=Zs(this,Xu).get(t.queryHash))==null?void 0:n.state}removeQueries(s){const t=Zs(this,Xu);Pm.batch(()=>{t.findAll(s).forEach(n=>{t.remove(n)})})}resetQueries(s,t){const n=Zs(this,Xu);return Pm.batch(()=>(n.findAll(s).forEach(r=>{r.reset()}),this.refetchQueries({type:"active",...s},t)))}cancelQueries(s,t={}){const n={revert:!0,...t},r=Pm.batch(()=>Zs(this,Xu).findAll(s).map(a=>a.cancel(n)));return Promise.all(r).then($x).catch($x)}invalidateQueries(s,t={}){return Pm.batch(()=>(Zs(this,Xu).findAll(s).forEach(n=>{n.invalidate()}),(s==null?void 0:s.refetchType)==="none"?Promise.resolve():this.refetchQueries({...s,type:(s==null?void 0:s.refetchType)??(s==null?void 0:s.type)??"active"},t)))}refetchQueries(s,t={}){const n={...t,cancelRefetch:t.cancelRefetch??!0},r=Pm.batch(()=>Zs(this,Xu).findAll(s).filter(a=>!a.isDisabled()&&!a.isStatic()).map(a=>{let i=a.fetch(void 0,n);return n.throwOnError||(i=i.catch($x)),a.state.fetchStatus==="paused"?Promise.resolve():i}));return Promise.all(r).then($x)}fetchQuery(s){const t=this.defaultQueryOptions(s);t.retry===void 0&&(t.retry=!1);const n=Zs(this,Xu).build(this,t);return n.isStaleByTime(a4(t.staleTime,n))?n.fetch(t):Promise.resolve(n.state.data)}prefetchQuery(s){return this.fetchQuery(s).then($x).catch($x)}fetchInfiniteQuery(s){return s.behavior=Rpe(s.pages),this.fetchQuery(s)}prefetchInfiniteQuery(s){return this.fetchInfiniteQuery(s).then($x).catch($x)}ensureInfiniteQueryData(s){return s.behavior=Rpe(s.pages),this.ensureQueryData(s)}resumePausedMutations(){return Dpe.isOnline()?Zs(this,mS).resumePausedMutations():Promise.resolve()}getQueryCache(){return Zs(this,Xu)}getMutationCache(){return Zs(this,mS)}getDefaultOptions(){return Zs(this,pS)}setDefaultOptions(s){$a(this,pS,s)}setQueryDefaults(s,t){Zs(this,KL).set(lM(s),{queryKey:s,defaultOptions:t})}getQueryDefaults(s){const t=[...Zs(this,KL).values()],n={};return t.forEach(r=>{Wz(s,r.queryKey)&&Object.assign(n,r.defaultOptions)}),n}setMutationDefaults(s,t){Zs(this,YL).set(lM(s),{mutationKey:s,defaultOptions:t})}getMutationDefaults(s){const t=[...Zs(this,YL).values()],n={};return t.forEach(r=>{Wz(s,r.mutationKey)&&Object.assign(n,r.defaultOptions)}),n}defaultQueryOptions(s){if(s._defaulted)return s;const t={...Zs(this,pS).queries,...this.getQueryDefaults(s.queryKey),...s,_defaulted:!0};return t.queryHash||(t.queryHash=tAe(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===sAe&&(t.enabled=!1),t}defaultMutationOptions(s){return s!=null&&s._defaulted?s:{...Zs(this,pS).mutations,...(s==null?void 0:s.mutationKey)&&this.getMutationDefaults(s.mutationKey),...s,_defaulted:!0}}clear(){Zs(this,Xu).clear(),Zs(this,mS).clear()}},Xu=new WeakMap,mS=new WeakMap,pS=new WeakMap,KL=new WeakMap,YL=new WeakMap,fS=new WeakMap,ZL=new WeakMap,QL=new WeakMap,dtt),kg,kl,w$,zx,lA,XL,xS,gS,j$,JL,e8,cA,dA,yS,t8,xc,QF,MSe,ISe,PSe,LSe,DSe,RSe,OSe,Yrt,utt,Krt=(utt=class extends TD{constructor(t,n){super();Ri(this,xc);Ri(this,kg);Ri(this,kl);Ri(this,w$);Ri(this,zx);Ri(this,lA);Ri(this,XL);Ri(this,xS);Ri(this,gS);Ri(this,j$);Ri(this,JL);Ri(this,e8);Ri(this,cA);Ri(this,dA);Ri(this,yS);Ri(this,t8,new Set);this.options=n,$a(this,kg,t),$a(this,gS,null),$a(this,xS,ESe()),this.options.experimental_prefetchInRender||Zs(this,xS).reject(new Error("experimental_prefetchInRender feature flag is not enabled")),this.bindMethods(),this.setOptions(n)}bindMethods(){this.refetch=this.refetch.bind(this)}onSubscribe(){this.listeners.size===1&&(Zs(this,kl).addObserver(this),H9e(Zs(this,kl),this.options)?Ho(this,xc,QF).call(this):this.updateResult(),Ho(this,xc,LSe).call(this))}onUnsubscribe(){this.hasListeners()||this.destroy()}shouldFetchOnReconnect(){return FSe(Zs(this,kl),this.options,this.options.refetchOnReconnect)}shouldFetchOnWindowFocus(){return FSe(Zs(this,kl),this.options,this.options.refetchOnWindowFocus)}destroy(){this.listeners=new Set,Ho(this,xc,DSe).call(this),Ho(this,xc,RSe).call(this),Zs(this,kl).removeObserver(this)}setOptions(t){const n=this.options,r=Zs(this,kl);if(this.options=Zs(this,kg).defaultQueryOptions(t),this.options.enabled!==void 0&&typeof this.options.enabled!="boolean"&&typeof this.options.enabled!="function"&&typeof xv(this.options.enabled,Zs(this,kl))!="boolean")throw new Error("Expected enabled to be a boolean or a callback that returns a boolean");Ho(this,xc,OSe).call(this),Zs(this,kl).setOptions(this.options),n._defaulted&&!Lpe(this.options,n)&&Zs(this,kg).getQueryCache().notify({type:"observerOptionsUpdated",query:Zs(this,kl),observer:this});const a=this.hasListeners();a&&G9e(Zs(this,kl),r,this.options,n)&&Ho(this,xc,QF).call(this),this.updateResult(),a&&(Zs(this,kl)!==r||xv(this.options.enabled,Zs(this,kl))!==xv(n.enabled,Zs(this,kl))||a4(this.options.staleTime,Zs(this,kl))!==a4(n.staleTime,Zs(this,kl)))&&Ho(this,xc,MSe).call(this);const i=Ho(this,xc,ISe).call(this);a&&(Zs(this,kl)!==r||xv(this.options.enabled,Zs(this,kl))!==xv(n.enabled,Zs(this,kl))||i!==Zs(this,yS))&&Ho(this,xc,PSe).call(this,i)}getOptimisticResult(t){const n=Zs(this,kg).getQueryCache().build(Zs(this,kg),t),r=this.createResult(n,t);return vPt(this,r)&&($a(this,zx,r),$a(this,XL,this.options),$a(this,lA,Zs(this,kl).state)),r}getCurrentResult(){return Zs(this,zx)}trackResult(t,n){return new Proxy(t,{get:(r,a)=>(this.trackProp(a),n==null||n(a),Reflect.get(r,a))})}trackProp(t){Zs(this,t8).add(t)}getCurrentQuery(){return Zs(this,kl)}refetch({...t}={}){return this.fetch({...t})}fetchOptimistic(t){const n=Zs(this,kg).defaultQueryOptions(t),r=Zs(this,kg).getQueryCache().build(Zs(this,kg),n);return r.fetch().then(()=>this.createResult(r,n))}fetch(t){return Ho(this,xc,QF).call(this,{...t,cancelRefetch:t.cancelRefetch??!0}).then(()=>(this.updateResult(),Zs(this,zx)))}createResult(t,n){var F;const r=Zs(this,kl),a=this.options,i=Zs(this,zx),l=Zs(this,lA),o=Zs(this,XL),d=t!==r?t.state:Zs(this,w$),{state:u}=t;let h={...u},p=!1,f;if(n._optimisticResults){const z=this.hasListeners(),H=!z&&H9e(t,n),Z=z&&G9e(t,r,n,a);(H||Z)&&(h={...h,...Hrt(u.data,t.options)}),n._optimisticResults==="isRestoring"&&(h.fetchStatus="idle")}let{error:y,errorUpdatedAt:_,status:v}=h;f=h.data;let j=!1;if(n.placeholderData!==void 0&&f===void 0&&v==="pending"){let z;i!=null&&i.isPlaceholderData&&n.placeholderData===(o==null?void 0:o.placeholderData)?(z=i.data,j=!0):z=typeof n.placeholderData=="function"?n.placeholderData((F=Zs(this,e8))==null?void 0:F.state.data,Zs(this,e8)):n.placeholderData,z!==void 0&&(v="success",f=TSe(i==null?void 0:i.data,z,n),p=!0)}if(n.select&&f!==void 0&&!j)if(i&&f===(l==null?void 0:l.data)&&n.select===Zs(this,j$))f=Zs(this,JL);else try{$a(this,j$,n.select),f=n.select(f),f=TSe(i==null?void 0:i.data,f,n),$a(this,JL,f),$a(this,gS,null)}catch(z){$a(this,gS,z)}Zs(this,gS)&&(y=Zs(this,gS),f=Zs(this,JL),_=Date.now(),v="error");const w=h.fetchStatus==="fetching",S=v==="pending",A=v==="error",E=S&&w,O=f!==void 0,I={status:v,fetchStatus:h.fetchStatus,isPending:S,isSuccess:v==="success",isError:A,isInitialLoading:E,isLoading:E,data:f,dataUpdatedAt:h.dataUpdatedAt,error:y,errorUpdatedAt:_,failureCount:h.fetchFailureCount,failureReason:h.fetchFailureReason,errorUpdateCount:h.errorUpdateCount,isFetched:h.dataUpdateCount>0||h.errorUpdateCount>0,isFetchedAfterMount:h.dataUpdateCount>d.dataUpdateCount||h.errorUpdateCount>d.errorUpdateCount,isFetching:w,isRefetching:w&&!S,isLoadingError:A&&!O,isPaused:h.fetchStatus==="paused",isPlaceholderData:p,isRefetchError:A&&O,isStale:rAe(t,n),refetch:this.refetch,promise:Zs(this,xS),isEnabled:xv(n.enabled,t)!==!1};if(this.options.experimental_prefetchInRender){const z=Y=>{I.status==="error"?Y.reject(I.error):I.data!==void 0&&Y.resolve(I.data)},H=()=>{const Y=$a(this,xS,I.promise=ESe());z(Y)},Z=Zs(this,xS);switch(Z.status){case"pending":t.queryHash===r.queryHash&&z(Z);break;case"fulfilled":(I.status==="error"||I.data!==Z.value)&&H();break;case"rejected":(I.status!=="error"||I.error!==Z.reason)&&H();break}}return I}updateResult(){const t=Zs(this,zx),n=this.createResult(Zs(this,kl),this.options);if($a(this,lA,Zs(this,kl).state),$a(this,XL,this.options),Zs(this,lA).data!==void 0&&$a(this,e8,Zs(this,kl)),Lpe(n,t))return;$a(this,zx,n);const r=()=>{if(!t)return!0;const{notifyOnChangeProps:a}=this.options,i=typeof a=="function"?a():a;if(i==="all"||!i&&!Zs(this,t8).size)return!0;const l=new Set(i??Zs(this,t8));return this.options.throwOnError&&l.add("error"),Object.keys(Zs(this,zx)).some(o=>{const c=o;return Zs(this,zx)[c]!==t[c]&&l.has(c)})};Ho(this,xc,Yrt).call(this,{listeners:r()})}onQueryUpdate(){this.updateResult(),this.hasListeners()&&Ho(this,xc,LSe).call(this)}},kg=new WeakMap,kl=new WeakMap,w$=new WeakMap,zx=new WeakMap,lA=new WeakMap,XL=new WeakMap,xS=new WeakMap,gS=new WeakMap,j$=new WeakMap,JL=new WeakMap,e8=new WeakMap,cA=new WeakMap,dA=new WeakMap,yS=new WeakMap,t8=new WeakMap,xc=new WeakSet,QF=function(t){Ho(this,xc,OSe).call(this);let n=Zs(this,kl).fetch(this.options,t);return t!=null&&t.throwOnError||(n=n.catch($x)),n},MSe=function(){Ho(this,xc,DSe).call(this);const t=a4(this.options.staleTime,Zs(this,kl));if(oM||Zs(this,zx).isStale||!SSe(t))return;const r=Ort(Zs(this,zx).dataUpdatedAt,t)+1;$a(this,cA,setTimeout(()=>{Zs(this,zx).isStale||this.updateResult()},r))},ISe=function(){return(typeof this.options.refetchInterval=="function"?this.options.refetchInterval(Zs(this,kl)):this.options.refetchInterval)??!1},PSe=function(t){Ho(this,xc,RSe).call(this),$a(this,yS,t),!(oM||xv(this.options.enabled,Zs(this,kl))===!1||!SSe(Zs(this,yS))||Zs(this,yS)===0)&&$a(this,dA,setInterval(()=>{(this.options.refetchIntervalInBackground||nAe.isFocused())&&Ho(this,xc,QF).call(this)},Zs(this,yS)))},LSe=function(){Ho(this,xc,MSe).call(this),Ho(this,xc,PSe).call(this,Ho(this,xc,ISe).call(this))},DSe=function(){Zs(this,cA)&&(clearTimeout(Zs(this,cA)),$a(this,cA,void 0))},RSe=function(){Zs(this,dA)&&(clearInterval(Zs(this,dA)),$a(this,dA,void 0))},OSe=function(){const t=Zs(this,kg).getQueryCache().build(Zs(this,kg),this.options);if(t===Zs(this,kl))return;const n=Zs(this,kl);$a(this,kl,t),$a(this,w$,t.state),this.hasListeners()&&(n==null||n.removeObserver(this),t.addObserver(this))},Yrt=function(t){Pm.batch(()=>{t.listeners&&this.listeners.forEach(n=>{n(Zs(this,zx))}),Zs(this,kg).getQueryCache().notify({query:Zs(this,kl),type:"observerResultsUpdated"})})},utt);function yPt(s,t){return xv(t.enabled,s)!==!1&&s.state.data===void 0&&!(s.state.status==="error"&&t.retryOnMount===!1)}function H9e(s,t){return yPt(s,t)||s.state.data!==void 0&&FSe(s,t,t.refetchOnMount)}function FSe(s,t,n){if(xv(t.enabled,s)!==!1&&a4(t.staleTime,s)!=="static"){const r=typeof n=="function"?n(s):n;return r==="always"||r!==!1&&rAe(s,t)}return!1}function G9e(s,t,n,r){return(s!==t||xv(r.enabled,s)===!1)&&(!n.suspense||s.state.status!=="error")&&rAe(s,n)}function rAe(s,t){return xv(t.enabled,s)!==!1&&s.isStaleByTime(a4(t.staleTime,s))}function vPt(s,t){return!Lpe(s.getCurrentResult(),t)}var bPt=class extends Krt{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:Rpe()})}getOptimisticResult(s){return s.behavior=Rpe(),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 y,_;const{state:n}=s,r=super.createResult(s,t),{isFetching:a,isRefetching:i,isError:l,isRefetchError:o}=r,c=(_=(y=n.fetchMeta)==null?void 0:y.fetchMore)==null?void 0:_.direction,d=l&&c==="forward",u=a&&c==="forward",h=l&&c==="backward",p=a&&c==="backward";return{...r,fetchNextPage:this.fetchNextPage,fetchPreviousPage:this.fetchPreviousPage,hasNextPage:fPt(t,n.data),hasPreviousPage:xPt(t,n.data),isFetchNextPageError:d,isFetchingNextPage:u,isFetchPreviousPageError:h,isFetchingPreviousPage:p,isRefetchError:o&&!d&&!h,isRefetching:i&&!u&&!p}}},vS,bS,Sg,T2,tN,mme,zSe,htt,_Pt=(htt=class extends TD{constructor(n,r){super();Ri(this,tN);Ri(this,vS);Ri(this,bS);Ri(this,Sg);Ri(this,T2);$a(this,vS,n),this.setOptions(r),this.bindMethods(),Ho(this,tN,mme).call(this)}bindMethods(){this.mutate=this.mutate.bind(this),this.reset=this.reset.bind(this)}setOptions(n){var a;const r=this.options;this.options=Zs(this,vS).defaultMutationOptions(n),Lpe(this.options,r)||Zs(this,vS).getMutationCache().notify({type:"observerOptionsUpdated",mutation:Zs(this,Sg),observer:this}),r!=null&&r.mutationKey&&this.options.mutationKey&&lM(r.mutationKey)!==lM(this.options.mutationKey)?this.reset():((a=Zs(this,Sg))==null?void 0:a.state.status)==="pending"&&Zs(this,Sg).setOptions(this.options)}onUnsubscribe(){var n;this.hasListeners()||(n=Zs(this,Sg))==null||n.removeObserver(this)}onMutationUpdate(n){Ho(this,tN,mme).call(this),Ho(this,tN,zSe).call(this,n)}getCurrentResult(){return Zs(this,bS)}reset(){var n;(n=Zs(this,Sg))==null||n.removeObserver(this),$a(this,Sg,void 0),Ho(this,tN,mme).call(this),Ho(this,tN,zSe).call(this)}mutate(n,r){var a;return $a(this,T2,r),(a=Zs(this,Sg))==null||a.removeObserver(this),$a(this,Sg,Zs(this,vS).getMutationCache().build(Zs(this,vS),this.options)),Zs(this,Sg).addObserver(this),Zs(this,Sg).execute(n)}},vS=new WeakMap,bS=new WeakMap,Sg=new WeakMap,T2=new WeakMap,tN=new WeakSet,mme=function(){var r;const n=((r=Zs(this,Sg))==null?void 0:r.state)??Grt();$a(this,bS,{...n,isPending:n.status==="pending",isSuccess:n.status==="success",isError:n.status==="error",isIdle:n.status==="idle",mutate:this.mutate,reset:this.reset})},zSe=function(n){Pm.batch(()=>{var r,a,i,l,o,c,d,u;if(Zs(this,T2)&&this.hasListeners()){const h=Zs(this,bS).variables,p=Zs(this,bS).context;(n==null?void 0:n.type)==="success"?((a=(r=Zs(this,T2)).onSuccess)==null||a.call(r,n.data,h,p),(l=(i=Zs(this,T2)).onSettled)==null||l.call(i,n.data,null,h,p)):(n==null?void 0:n.type)==="error"&&((c=(o=Zs(this,T2)).onError)==null||c.call(o,n.error,h,p),(u=(d=Zs(this,T2)).onSettled)==null||u.call(d,void 0,n.error,h,p))}this.listeners.forEach(h=>{h(Zs(this,bS))})})},htt),Zrt=N.createContext(void 0),Kt=s=>{const t=N.useContext(Zrt);if(!t)throw new Error("No QueryClient set, use QueryClientProvider to set one");return t},wPt=({client:s,children:t})=>(N.useEffect(()=>(s.mount(),()=>{s.unmount()}),[s]),e.jsx(Zrt.Provider,{value:s,children:t})),Qrt=N.createContext(!1),jPt=()=>N.useContext(Qrt);Qrt.Provider;function NPt(){let s=!1;return{clearReset:()=>{s=!1},reset:()=>{s=!0},isReset:()=>s}}var kPt=N.createContext(NPt()),SPt=()=>N.useContext(kPt),CPt=(s,t)=>{(s.suspense||s.throwOnError||s.experimental_prefetchInRender)&&(t.isReset()||(s.retryOnMount=!1))},TPt=s=>{N.useEffect(()=>{s.clearReset()},[s])},EPt=({result:s,errorResetBoundary:t,throwOnError:n,query:r,suspense:a})=>s.isError&&!t.isReset()&&!s.isFetching&&r&&(a&&s.data===void 0||Brt(n,[s.error,r])),APt=s=>{if(s.suspense){const t=r=>r==="static"?r:Math.max(r??1e3,1e3),n=s.staleTime;s.staleTime=typeof n=="function"?(...r)=>t(n(...r)):t(n),typeof s.gcTime=="number"&&(s.gcTime=Math.max(s.gcTime,1e3))}},MPt=(s,t)=>s.isLoading&&s.isFetching&&!t,IPt=(s,t)=>(s==null?void 0:s.suspense)&&t.isPending,W9e=(s,t,n)=>t.fetchOptimistic(s).catch(()=>{n.clearReset()});function Xrt(s,t,n){var h,p,f,y,_;const r=jPt(),a=SPt(),i=Kt(),l=i.defaultQueryOptions(s);(p=(h=i.getDefaultOptions().queries)==null?void 0:h._experimental_beforeQuery)==null||p.call(h,l),l._optimisticResults=r?"isRestoring":"optimistic",APt(l),CPt(l,a),TPt(a);const o=!i.getQueryCache().get(l.queryHash),[c]=N.useState(()=>new t(i,l)),d=c.getOptimisticResult(l),u=!r&&s.subscribed!==!1;if(N.useSyncExternalStore(N.useCallback(v=>{const j=u?c.subscribe(Pm.batchCalls(v)):$x;return c.updateResult(),j},[c,u]),()=>c.getCurrentResult(),()=>c.getCurrentResult()),N.useEffect(()=>{c.setOptions(l)},[l,c]),IPt(l,d))throw W9e(l,c,a);if(EPt({result:d,errorResetBoundary:a,throwOnError:l.throwOnError,query:i.getQueryCache().get(l.queryHash),suspense:l.suspense}))throw d.error;if((y=(f=i.getDefaultOptions().queries)==null?void 0:f._experimental_afterQuery)==null||y.call(f,l,d),l.experimental_prefetchInRender&&!oM&&MPt(d,r)){const v=o?W9e(l,c,a):(_=i.getQueryCache().get(l.queryHash))==null?void 0:_.promise;v==null||v.catch($x).finally(()=>{c.updateResult()})}return l.notifyOnChangeProps?d:c.trackResult(d)}function dt(s,t){return Xrt(s,Krt)}function yt(s,t){const n=Kt(),[r]=N.useState(()=>new _Pt(n,s));N.useEffect(()=>{r.setOptions(s)},[r,s]);const a=N.useSyncExternalStore(N.useCallback(l=>r.subscribe(Pm.batchCalls(l)),[r]),()=>r.getCurrentResult(),()=>r.getCurrentResult()),i=N.useCallback((l,o)=>{r.mutate(l,o).catch($x)},[r]);if(a.error&&Brt(r.options.throwOnError,[a.error]))throw a.error;return{...a,mutate:i,mutateAsync:a.mutate}}function PPt(s,t){return Xrt(s,bPt)}/** * @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 Kz(){return Kz=Object.assign?Object.assign.bind():function(s){for(var t=1;t"u")throw new Error(t)}function Jrt(s,t){if(!s){typeof console<"u"&&console.warn(t);try{throw new Error(t)}catch{}}}function DPt(){return Math.random().toString(36).substr(2,8)}function Y9e(s,t){return{usr:s.state,key:s.key,idx:t}}function BSe(s,t,n,r){return n===void 0&&(n=null),Kz({pathname:typeof s=="string"?s:s.pathname,search:"",hash:""},typeof t=="string"?ED(t):t,{state:n,key:t&&t.key||r||DPt()})}function Ope(s){let{pathname:t="/",search:n="",hash:r=""}=s;return n&&n!=="?"&&(t+=n.charAt(0)==="?"?n:"?"+n),r&&r!=="#"&&(t+=r.charAt(0)==="#"?r:"#"+r),t}function ED(s){let t={};if(s){let n=s.indexOf("#");n>=0&&(t.hash=s.substr(n),s=s.substr(0,n));let r=s.indexOf("?");r>=0&&(t.search=s.substr(r),s=s.substr(0,r)),s&&(t.pathname=s)}return t}function RPt(s,t,n,r){r===void 0&&(r={});let{window:a=document.defaultView,v5Compat:i=!1}=r,l=a.history,o=jS.Pop,c=null,d=u();d==null&&(d=0,l.replaceState(Kz({},l.state,{idx:d}),""));function u(){return(l.state||{idx:null}).idx}function h(){o=jS.Pop;let v=u(),j=v==null?null:v-d;d=v,c&&c({action:o,location:_.location,delta:j})}function p(v,j){o=jS.Push;let w=BSe(_.location,v,j);d=u()+1;let S=Y9e(w,d),A=_.createHref(w);try{l.pushState(S,"",A)}catch(E){if(E instanceof DOMException&&E.name==="DataCloneError")throw E;a.location.assign(A)}i&&c&&c({action:o,location:_.location,delta:1})}function f(v,j){o=jS.Replace;let w=BSe(_.location,v,j);d=u();let S=Y9e(w,d),A=_.createHref(w);l.replaceState(S,"",A),i&&c&&c({action:o,location:_.location,delta:0})}function y(v){let j=a.location.origin!=="null"?a.location.origin:a.location.href,w=typeof v=="string"?v:Ope(v);return w=w.replace(/ $/,"%20"),Lu(j,"No window.location.(origin|href) available to create URL for href: "+w),new URL(w,j)}let _={get action(){return o},get location(){return s(a,l)},listen(v){if(c)throw new Error("A history only accepts one active listener");return a.addEventListener(K9e,h),c=v,()=>{a.removeEventListener(K9e,h),c=null}},createHref(v){return t(a,v)},createURL:y,encodeLocation(v){let j=y(v);return{pathname:j.pathname,search:j.search,hash:j.hash}},push:p,replace:f,go(v){return l.go(v)}};return _}var Z9e;(function(s){s.data="data",s.deferred="deferred",s.redirect="redirect",s.error="error"})(Z9e||(Z9e={}));function OPt(s,t,n){return n===void 0&&(n="/"),FPt(s,t,n,!1)}function FPt(s,t,n,r){let a=typeof t=="string"?ED(t):t,i=u8(a.pathname||"/",n);if(i==null)return null;let l=eat(s);zPt(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("/")&&(Lu(c.relativePath.startsWith(r),'Absolute route path "'+c.relativePath+'" nested under path '+('"'+r+'" is not valid. An absolute child route path ')+"must start with the combined path of all its parent routes."),c.relativePath=c.relativePath.slice(r.length));let d=i4([r,c.relativePath]),u=n.concat(c);i.children&&i.children.length>0&&(Lu(i.index!==!0,"Index routes must not have child routes. Please remove "+('all child routes from route path "'+d+'".')),eat(i.children,t,u,d)),!(i.path==null&&!i.index)&&t.push({path:d,score:GPt(d,i.index),routesMeta:u})};return s.forEach((i,l)=>{var o;if(i.path===""||!((o=i.path)!=null&&o.includes("?")))a(i,l);else for(let c of tat(i.path))a(i,l,c)}),t}function tat(s){let t=s.split("/");if(t.length===0)return[];let[n,...r]=t,a=n.endsWith("?"),i=n.replace(/\?$/,"");if(r.length===0)return a?[i,""]:[i];let l=tat(r.join("/")),o=[];return o.push(...l.map(c=>c===""?i:[i,c].join("/"))),a&&o.push(...l),o.map(c=>s.startsWith("/")&&c===""?"/":c)}function zPt(s){s.sort((t,n)=>t.score!==n.score?n.score-t.score:WPt(t.routesMeta.map(r=>r.childrenIndex),n.routesMeta.map(r=>r.childrenIndex)))}const BPt=/^:[\w-]+$/,$Pt=3,UPt=2,qPt=1,VPt=10,HPt=-2,Q9e=s=>s==="*";function GPt(s,t){let n=s.split("/"),r=n.length;return n.some(Q9e)&&(r+=HPt),t&&(r+=UPt),n.filter(a=>!Q9e(a)).reduce((a,i)=>a+(BPt.test(i)?$Pt:i===""?qPt:VPt),r)}function WPt(s,t){return s.length===t.length&&s.slice(0,-1).every((r,a)=>r===t[a])?s[s.length-1]-t[t.length-1]:0}function KPt(s,t,n){let{routesMeta:r}=s,a={},i="/",l=[];for(let o=0;o{let{paramName:p,isOptional:f}=u;if(p==="*"){let _=o[h]||"";l=i.slice(0,i.length-_.length).replace(/(.)\/+$/,"$1")}const y=o[h];return f&&!y?d[p]=void 0:d[p]=(y||"").replace(/%2F/g,"/"),d},{}),pathname:i,pathnameBase:l,pattern:s}}function YPt(s,t,n){t===void 0&&(t=!1),n===void 0&&(n=!0),Jrt(s==="*"||!s.endsWith("*")||s.endsWith("/*"),'Route path "'+s+'" will be treated as if it were '+('"'+s.replace(/\*$/,"/*")+'" because the `*` character must ')+"always follow a `/` in the pattern. To get rid of this warning, "+('please change the route path to "'+s.replace(/\*$/,"/*")+'".'));let r=[],a="^"+s.replace(/\/*\*?$/,"").replace(/^\/*/,"/").replace(/[\\.*+^${}|()[\]]/g,"\\$&").replace(/\/:([\w-]+)(\?)?/g,(l,o,c)=>(r.push({paramName:o,isOptional:c!=null}),c?"/?([^\\/]+)?":"/([^\\/]+)"));return s.endsWith("*")?(r.push({paramName:"*"}),a+=s==="*"||s==="/*"?"(.*)$":"(?:\\/(.+)|\\/*)$"):n?a+="\\/*$":s!==""&&s!=="/"&&(a+="(?:(?=\\/|$))"),[new RegExp(a,t?void 0:"i"),r]}function ZPt(s){try{return s.split("/").map(t=>decodeURIComponent(t).replace(/\//g,"%2F")).join("/")}catch(t){return Jrt(!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 u8(s,t){if(t==="/")return s;if(!s.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith("/")?t.length-1:t.length,r=s.charAt(n);return r&&r!=="/"?null:s.slice(n)||"/"}function QPt(s,t){t===void 0&&(t="/");let{pathname:n,search:r="",hash:a=""}=typeof s=="string"?ED(s):s;return{pathname:n?n.startsWith("/")?n:XPt(n,t):t,search:tLt(r),hash:sLt(a)}}function XPt(s,t){let n=t.replace(/\/+$/,"").split("/");return s.split("/").forEach(a=>{a===".."?n.length>1&&n.pop():a!=="."&&n.push(a)}),n.length>1?n.join("/"):"/"}function jwe(s,t,n,r){return"Cannot include a '"+s+"' character in a manually specified "+("`to."+t+"` field ["+JSON.stringify(r)+"]. Please separate it out to the ")+("`to."+n+"` field. Alternatively you may provide the full path as ")+'a string in and the router will parse it for you.'}function JPt(s){return s.filter((t,n)=>n===0||t.route.path&&t.route.path.length>0)}function aAe(s,t){let n=JPt(s);return t?n.map((r,a)=>a===n.length-1?r.pathname:r.pathnameBase):n.map(r=>r.pathnameBase)}function iAe(s,t,n,r){r===void 0&&(r=!1);let a;typeof s=="string"?a=ED(s):(a=Kz({},s),Lu(!a.pathname||!a.pathname.includes("?"),jwe("?","pathname","search",a)),Lu(!a.pathname||!a.pathname.includes("#"),jwe("#","pathname","hash",a)),Lu(!a.search||!a.search.includes("#"),jwe("#","search","hash",a)));let i=s===""||a.pathname==="",l=i?"/":a.pathname,o;if(l==null)o=n;else{let h=t.length-1;if(!r&&l.startsWith("..")){let p=l.split("/");for(;p[0]==="..";)p.shift(),h-=1;a.pathname=p.join("/")}o=h>=0?t[h]:"/"}let c=QPt(a,o),d=l&&l!=="/"&&l.endsWith("/"),u=(i||l===".")&&n.endsWith("/");return!c.pathname.endsWith("/")&&(d||u)&&(c.pathname+="/"),c}const i4=s=>s.join("/").replace(/\/\/+/g,"/"),eLt=s=>s.replace(/\/+$/,"").replace(/^\/*/,"/"),tLt=s=>!s||s==="?"?"":s.startsWith("?")?s:"?"+s,sLt=s=>!s||s==="#"?"":s.startsWith("#")?s:"#"+s;function nLt(s){return s!=null&&typeof s.status=="number"&&typeof s.statusText=="string"&&typeof s.internal=="boolean"&&"data"in s}const sat=["post","put","patch","delete"];new Set(sat);const rLt=["get",...sat];new Set(rLt);/** * 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 Yz(){return Yz=Object.assign?Object.assign.bind():function(s){for(var t=1;t{o.current=!0}),N.useCallback(function(d,u){if(u===void 0&&(u={}),!o.current)return;if(typeof d=="number"){r.go(d);return}let h=iAe(d,JSON.parse(l),i,u.relative==="path");s==null&&t!=="/"&&(h.pathname=h.pathname==="/"?t:i4([t,h.pathname])),(u.replace?r.replace:r.push)(h,u.state,u)},[t,r,l,i,s])}const oLt=N.createContext(null);function lLt(s){let t=N.useContext(Hw).outlet;return t&&N.createElement(oLt.Provider,{value:s},t)}function bi(){let{matches:s}=N.useContext(Hw),t=s[s.length-1];return t?t.params:{}}function w0e(s,t){let{relative:n}=t===void 0?{}:t,{future:r}=N.useContext(yN),{matches:a}=N.useContext(Hw),{pathname:i}=Xl(),l=JSON.stringify(aAe(a,r.v7_relativeSplatPath));return N.useMemo(()=>iAe(s,JSON.parse(l),i,n==="path"),[s,l,i,n])}function cLt(s,t){return dLt(s,t)}function dLt(s,t,n,r){AD()||Lu(!1);let{navigator:a}=N.useContext(yN),{matches:i}=N.useContext(Hw),l=i[i.length-1],o=l?l.params:{};l&&l.pathname;let c=l?l.pathnameBase:"/";l&&l.route;let d=Xl(),u;if(t){var h;let v=typeof t=="string"?ED(t):t;c==="/"||(h=v.pathname)!=null&&h.startsWith(c)||Lu(!1),u=v}else u=d;let p=u.pathname||"/",f=p;if(c!=="/"){let v=c.replace(/^\//,"").split("/");f="/"+p.replace(/^\//,"").split("/").slice(v.length).join("/")}let y=OPt(s,{pathname:f}),_=fLt(y&&y.map(v=>Object.assign({},v,{params:Object.assign({},o,v.params),pathname:i4([c,a.encodeLocation?a.encodeLocation(v.pathname).pathname:v.pathname]),pathnameBase:v.pathnameBase==="/"?c:i4([c,a.encodeLocation?a.encodeLocation(v.pathnameBase).pathname:v.pathnameBase])})),i,n,r);return t&&_?N.createElement(_0e.Provider,{value:{location:Yz({pathname:"/",search:"",hash:"",state:null,key:"default"},u),navigationType:jS.Pop}},_):_}function uLt(){let s=vLt(),t=nLt(s)?s.status+" "+s.statusText:s instanceof Error?s.message:JSON.stringify(s),n=s instanceof Error?s.stack:null,a={padding:"0.5rem",backgroundColor:"rgba(200,200,200, 0.5)"};return N.createElement(N.Fragment,null,N.createElement("h2",null,"Unexpected Application Error!"),N.createElement("h3",{style:{fontStyle:"italic"}},t),n?N.createElement("pre",{style:a},n):null,null)}const hLt=N.createElement(uLt,null);class mLt extends N.Component{constructor(t){super(t),this.state={location:t.location,revalidation:t.revalidation,error:t.error}}static getDerivedStateFromError(t){return{error:t}}static getDerivedStateFromProps(t,n){return n.location!==t.location||n.revalidation!=="idle"&&t.revalidation==="idle"?{error:t.error,location:t.location,revalidation:t.revalidation}:{error:t.error!==void 0?t.error:n.error,location:n.location,revalidation:t.revalidation||n.revalidation}}componentDidCatch(t,n){console.error("React Router caught the following error during render",t,n)}render(){return this.state.error!==void 0?N.createElement(Hw.Provider,{value:this.props.routeContext},N.createElement(rat.Provider,{value:this.state.error,children:this.props.component})):this.props.children}}function pLt(s){let{routeContext:t,match:n,children:r}=s,a=N.useContext(b0e);return a&&a.static&&a.staticContext&&(n.route.errorElement||n.route.ErrorBoundary)&&(a.staticContext._deepestRenderedBoundaryId=n.route.id),N.createElement(Hw.Provider,{value:t},r)}function fLt(s,t,n,r){var a;if(t===void 0&&(t=[]),n===void 0&&(n=null),r===void 0&&(r=null),s==null){var i;if(!n)return null;if(n.errors)s=n.matches;else if((i=r)!=null&&i.v7_partialHydration&&t.length===0&&!n.initialized&&n.matches.length>0)s=n.matches;else return null}let l=s,o=(a=n)==null?void 0:a.errors;if(o!=null){let u=l.findIndex(h=>h.route.id&&(o==null?void 0:o[h.route.id])!==void 0);u>=0||Lu(!1),l=l.slice(0,Math.min(l.length,u+1))}let c=!1,d=-1;if(n&&r&&r.v7_partialHydration)for(let u=0;u=0?l=l.slice(0,d+1):l=[l[0]];break}}}return l.reduceRight((u,h,p)=>{let f,y=!1,_=null,v=null;n&&(f=o&&h.route.id?o[h.route.id]:void 0,_=h.route.errorElement||hLt,c&&(d<0&&p===0?(y=!0,v=null):d===p&&(y=!0,v=h.route.hydrateFallbackElement||null)));let j=t.concat(l.slice(0,p+1)),w=()=>{let S;return f?S=_:y?S=v:h.route.Component?S=N.createElement(h.route.Component,null):h.route.element?S=h.route.element:S=u,N.createElement(pLt,{match:h,routeContext:{outlet:u,matches:j,isDataRoute:n!=null},children:S})};return n&&(h.route.ErrorBoundary||h.route.errorElement||p===0)?N.createElement(mLt,{location:n.location,revalidation:n.revalidation,component:_,error:f,children:w(),routeContext:{outlet:null,matches:j,isDataRoute:!0}}):w()},null)}var iat=function(s){return s.UseBlocker="useBlocker",s.UseRevalidator="useRevalidator",s.UseNavigateStable="useNavigate",s}(iat||{}),zpe=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}(zpe||{});function xLt(s){let t=N.useContext(b0e);return t||Lu(!1),t}function gLt(s){let t=N.useContext(nat);return t||Lu(!1),t}function yLt(s){let t=N.useContext(Hw);return t||Lu(!1),t}function oat(s){let t=yLt(),n=t.matches[t.matches.length-1];return n.route.id||Lu(!1),n.route.id}function vLt(){var s;let t=N.useContext(rat),n=gLt(zpe.UseRouteError),r=oat(zpe.UseRouteError);return t!==void 0?t:(s=n.errors)==null?void 0:s[r]}function bLt(){let{router:s}=xLt(iat.UseNavigateStable),t=oat(zpe.UseNavigateStable),n=N.useRef(!1);return aat(()=>{n.current=!0}),N.useCallback(function(a,i){i===void 0&&(i={}),n.current&&(typeof a=="number"?s.navigate(a):s.navigate(a,Yz({fromRouteId:t},i)))},[s,t])}function _Lt(s,t){s==null||s.v7_startTransition,s==null||s.v7_relativeSplatPath}function o4(s){let{to:t,replace:n,state:r,relative:a}=s;AD()||Lu(!1);let{future:i,static:l}=N.useContext(yN),{matches:o}=N.useContext(Hw),{pathname:c}=Xl(),d=Ln(),u=iAe(t,aAe(o,i.v7_relativeSplatPath),c,a==="path"),h=JSON.stringify(u);return N.useEffect(()=>d(JSON.parse(h),{replace:n,state:r,relative:a}),[d,h,a,n,r]),null}function lat(s){return lLt(s.context)}function as(s){Lu(!1)}function wLt(s){let{basename:t="/",children:n=null,location:r,navigationType:a=jS.Pop,navigator:i,static:l=!1,future:o}=s;AD()&&Lu(!1);let c=t.replace(/^\/*/,"/"),d=N.useMemo(()=>({basename:c,navigator:i,static:l,future:Yz({v7_relativeSplatPath:!1},o)}),[c,o,i,l]);typeof r=="string"&&(r=ED(r));let{pathname:u="/",search:h="",hash:p="",state:f=null,key:y="default"}=r,_=N.useMemo(()=>{let v=u8(u,c);return v==null?null:{location:{pathname:v,search:h,hash:p,state:f,key:y},navigationType:a}},[c,u,h,p,f,y,a]);return _==null?null:N.createElement(yN.Provider,{value:d},N.createElement(_0e.Provider,{children:n,value:_}))}function Bpe(s){let{children:t,location:n}=s;return cLt($Se(t),n)}new Promise(()=>{});function $Se(s,t){t===void 0&&(t=[]);let n=[];return N.Children.forEach(s,(r,a)=>{if(!N.isValidElement(r))return;let i=[...t,a];if(r.type===N.Fragment){n.push.apply(n,$Se(r.props.children,i));return}r.type!==as&&Lu(!1),!r.props.index||!r.props.children||Lu(!1);let l={id:r.props.id||i.join("-"),caseSensitive:r.props.caseSensitive,element:r.props.element,Component:r.props.Component,index:r.props.index,path:r.props.path,loader:r.props.loader,action:r.props.action,errorElement:r.props.errorElement,ErrorBoundary:r.props.ErrorBoundary,hasErrorBoundary:r.props.ErrorBoundary!=null||r.props.errorElement!=null,shouldRevalidate:r.props.shouldRevalidate,handle:r.props.handle,lazy:r.props.lazy};r.props.children&&(l.children=$Se(r.props.children,i)),n.push(l)}),n}/** * React Router DOM v6.30.1 * * Copyright (c) Remix Software Inc. * * This source code is licensed under the MIT license found in the * LICENSE.md file in the root directory of this source tree. * * @license MIT */function $pe(){return $pe=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&(n[a]=s[a]);return n}function jLt(s){return!!(s.metaKey||s.altKey||s.ctrlKey||s.shiftKey)}function NLt(s,t){return s.button===0&&(!t||t==="_self")&&!jLt(s)}function USe(s){return s===void 0&&(s=""),new URLSearchParams(typeof s=="string"||Array.isArray(s)||s instanceof URLSearchParams?s:Object.keys(s).reduce((t,n)=>{let r=s[n];return t.concat(Array.isArray(r)?r.map(a=>[n,a]):[[n,r]])},[]))}function kLt(s,t){let n=USe(s);return t&&t.forEach((r,a)=>{n.has(a)||t.getAll(a).forEach(i=>{n.append(a,i)})}),n}const SLt=["onClick","relative","reloadDocument","replace","state","target","to","preventScrollReset","viewTransition"],CLt=["aria-current","caseSensitive","className","end","style","to","viewTransition","children"],TLt="6";try{window.__reactRouterVersion=TLt}catch{}const ELt=N.createContext({isTransitioning:!1}),ALt="startTransition",X9e=KTe[ALt];function MLt(s){let{basename:t,children:n,future:r,window:a}=s,i=N.useRef();i.current==null&&(i.current=LPt({window:a,v5Compat:!0}));let l=i.current,[o,c]=N.useState({action:l.action,location:l.location}),{v7_startTransition:d}=r||{},u=N.useCallback(h=>{d&&X9e?X9e(()=>c(h)):c(h)},[c,d]);return N.useLayoutEffect(()=>l.listen(u),[l,u]),N.useEffect(()=>_Lt(r),[r]),N.createElement(wLt,{basename:t,children:n,location:o.location,navigationType:o.action,navigator:l,future:r})}const ILt=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u",PLt=/^(?:[a-z][a-z0-9+.-]*:|\/\/)/i,In=N.forwardRef(function(t,n){let{onClick:r,relative:a,reloadDocument:i,replace:l,state:o,target:c,to:d,preventScrollReset:u,viewTransition:h}=t,p=cat(t,SLt),{basename:f}=N.useContext(yN),y,_=!1;if(typeof d=="string"&&PLt.test(d)&&(y=d,ILt))try{let S=new URL(window.location.href),A=d.startsWith("//")?new URL(S.protocol+d):new URL(d),E=u8(A.pathname,f);A.origin===S.origin&&E!=null?d=E+A.search+A.hash:_=!0}catch{}let v=aLt(d,{relative:a}),j=DLt(d,{replace:l,state:o,target:c,preventScrollReset:u,relative:a,viewTransition:h});function w(S){r&&r(S),S.defaultPrevented||j(S)}return N.createElement("a",$pe({},p,{href:y||v,onClick:_||i?r:w,ref:n,target:c}))}),GO=N.forwardRef(function(t,n){let{"aria-current":r="page",caseSensitive:a=!1,className:i="",end:l=!1,style:o,to:c,viewTransition:d,children:u}=t,h=cat(t,CLt),p=w0e(c,{relative:h.relative}),f=Xl(),y=N.useContext(nat),{navigator:_,basename:v}=N.useContext(yN),j=y!=null&&RLt(p)&&d===!0,w=_.encodeLocation?_.encodeLocation(p).pathname:p.pathname,S=f.pathname,A=y&&y.navigation&&y.navigation.location?y.navigation.location.pathname:null;a||(S=S.toLowerCase(),A=A?A.toLowerCase():null,w=w.toLowerCase()),A&&v&&(A=u8(A,v)||A);const E=w!=="/"&&w.endsWith("/")?w.length-1:w.length;let O=S===w||!l&&S.startsWith(w)&&S.charAt(E)==="/",D=A!=null&&(A===w||!l&&A.startsWith(w)&&A.charAt(w.length)==="/"),I={isActive:O,isPending:D,isTransitioning:j},F=O?r:void 0,z;typeof i=="function"?z=i(I):z=[i,O?"active":null,D?"pending":null,j?"transitioning":null].filter(Boolean).join(" ");let H=typeof o=="function"?o(I):o;return N.createElement(In,$pe({},h,{"aria-current":F,className:z,ref:n,style:H,to:c,viewTransition:d}),typeof u=="function"?u(I):u)});var qSe;(function(s){s.UseScrollRestoration="useScrollRestoration",s.UseSubmit="useSubmit",s.UseSubmitFetcher="useSubmitFetcher",s.UseFetcher="useFetcher",s.useViewTransitionState="useViewTransitionState"})(qSe||(qSe={}));var J9e;(function(s){s.UseFetcher="useFetcher",s.UseFetchers="useFetchers",s.UseScrollRestoration="useScrollRestoration"})(J9e||(J9e={}));function LLt(s){let t=N.useContext(b0e);return t||Lu(!1),t}function DLt(s,t){let{target:n,replace:r,state:a,preventScrollReset:i,relative:l,viewTransition:o}=t===void 0?{}:t,c=Ln(),d=Xl(),u=w0e(s,{relative:l});return N.useCallback(h=>{if(NLt(h,n)){h.preventDefault();let p=r!==void 0?r:Ope(d)===Ope(u);c(s,{replace:p,state:a,preventScrollReset:i,relative:l,viewTransition:o})}},[d,c,u,r,a,n,s,i,l,o])}function xl(s){let t=N.useRef(USe(s)),n=N.useRef(!1),r=Xl(),a=N.useMemo(()=>kLt(r.search,n.current?null:t.current),[r.search]),i=Ln(),l=N.useCallback((o,c)=>{const d=USe(typeof o=="function"?o(a):o);n.current=!0,i("?"+d,c)},[i,a]);return[a,l]}function RLt(s,t){t===void 0&&(t={});let n=N.useContext(ELt);n==null&&Lu(!1);let{basename:r}=LLt(qSe.useViewTransitionState),a=w0e(s,{relative:t.relative});if(!n.isTransitioning)return!1;let i=u8(n.currentLocation.pathname,r)||n.currentLocation.pathname,l=u8(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Fpe(a.pathname,l)!=null||Fpe(a.pathname,i)!=null}var OLt=typeof Element<"u",FLt=typeof Map=="function",zLt=typeof Set=="function",BLt=typeof ArrayBuffer=="function"&&!!ArrayBuffer.isView;function pme(s,t){if(s===t)return!0;if(s&&t&&typeof s=="object"&&typeof t=="object"){if(s.constructor!==t.constructor)return!1;var n,r,a;if(Array.isArray(s)){if(n=s.length,n!=t.length)return!1;for(r=n;r--!==0;)if(!pme(s[r],t[r]))return!1;return!0}var i;if(FLt&&s instanceof Map&&t instanceof Map){if(s.size!==t.size)return!1;for(i=s.entries();!(r=i.next()).done;)if(!t.has(r.value[0]))return!1;for(i=s.entries();!(r=i.next()).done;)if(!pme(r.value[1],t.get(r.value[0])))return!1;return!0}if(zLt&&s instanceof Set&&t instanceof Set){if(s.size!==t.size)return!1;for(i=s.entries();!(r=i.next()).done;)if(!t.has(r.value[0]))return!1;return!0}if(BLt&&ArrayBuffer.isView(s)&&ArrayBuffer.isView(t)){if(n=s.length,n!=t.length)return!1;for(r=n;r--!==0;)if(s[r]!==t[r])return!1;return!0}if(s.constructor===RegExp)return s.source===t.source&&s.flags===t.flags;if(s.valueOf!==Object.prototype.valueOf&&typeof s.valueOf=="function"&&typeof t.valueOf=="function")return s.valueOf()===t.valueOf();if(s.toString!==Object.prototype.toString&&typeof s.toString=="function"&&typeof t.toString=="function")return s.toString()===t.toString();if(a=Object.keys(s),n=a.length,n!==Object.keys(t).length)return!1;for(r=n;r--!==0;)if(!Object.prototype.hasOwnProperty.call(t,a[r]))return!1;if(OLt&&s instanceof Element)return!1;for(r=n;r--!==0;)if(!((a[r]==="_owner"||a[r]==="__v"||a[r]==="__o")&&s.$$typeof)&&!pme(s[a[r]],t[a[r]]))return!1;return!0}return s!==s&&t!==t}var $Lt=function(t,n){try{return pme(t,n)}catch(r){if((r.message||"").match(/stack|recursion/i))return console.warn("react-fast-compare cannot handle circular refs"),!1;throw r}};const ULt=_l($Lt);var qLt=function(s,t,n,r,a,i,l,o){if(!s){var c;if(t===void 0)c=new Error("Minified exception occurred; use the non-minified dev environment for the full error message and additional helpful warnings.");else{var d=[n,r,a,i,l,o],u=0;c=new Error(t.replace(/%s/g,function(){return d[u++]})),c.name="Invariant Violation"}throw c.framesToPop=1,c}},VLt=qLt;const eze=_l(VLt);var HLt=function(t,n,r,a){var i=r?r.call(a,t,n):void 0;if(i!==void 0)return!!i;if(t===n)return!0;if(typeof t!="object"||!t||typeof n!="object"||!n)return!1;var l=Object.keys(t),o=Object.keys(n);if(l.length!==o.length)return!1;for(var c=Object.prototype.hasOwnProperty.bind(n),d=0;d(s.BASE="base",s.BODY="body",s.HEAD="head",s.HTML="html",s.LINK="link",s.META="meta",s.NOSCRIPT="noscript",s.SCRIPT="script",s.STYLE="style",s.TITLE="title",s.FRAGMENT="Symbol(react.fragment)",s))(dat||{}),Nwe={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"]}},tze=Object.values(dat),oAe={accesskey:"accessKey",charset:"charSet",class:"className",contenteditable:"contentEditable",contextmenu:"contextMenu","http-equiv":"httpEquiv",itemprop:"itemProp",tabindex:"tabIndex"},WLt=Object.entries(oAe).reduce((s,[t,n])=>(s[n]=t,s),{}),ab="data-rh",_L={DEFAULT_TITLE:"defaultTitle",DEFER:"defer",ENCODE_SPECIAL_CHARACTERS:"encodeSpecialCharacters",ON_CHANGE_CLIENT_STATE:"onChangeClientState",TITLE_TEMPLATE:"titleTemplate",PRIORITIZE_SEO_TAGS:"prioritizeSeoTags"},wL=(s,t)=>{for(let n=s.length-1;n>=0;n-=1){const r=s[n];if(Object.prototype.hasOwnProperty.call(r,t))return r[t]}return null},KLt=s=>{let t=wL(s,"title");const n=wL(s,_L.TITLE_TEMPLATE);if(Array.isArray(t)&&(t=t.join("")),n&&t)return n.replace(/%s/g,()=>t);const r=wL(s,_L.DEFAULT_TITLE);return t||r||void 0},YLt=s=>wL(s,_L.ON_CHANGE_CLIENT_STATE)||(()=>{}),kwe=(s,t)=>t.filter(n=>typeof n[s]<"u").map(n=>n[s]).reduce((n,r)=>({...n,...r}),{}),ZLt=(s,t)=>t.filter(n=>typeof n.base<"u").map(n=>n.base).reverse().reduce((n,r)=>{if(!n.length){const a=Object.keys(r);for(let i=0;iconsole&&typeof console.warn=="function"&&console.warn(s),WO=(s,t,n)=>{const r={};return n.filter(a=>Array.isArray(a[s])?!0:(typeof a[s]<"u"&&QLt(`Helmet: ${s} should be of type "Array". Instead found type "${typeof a[s]}"`),!1)).map(a=>a[s]).reverse().reduce((a,i)=>{const l={};i.filter(c=>{let d;const u=Object.keys(c);for(let p=0;pa.push(c));const o=Object.keys(l);for(let c=0;c{if(Array.isArray(s)&&s.length){for(let n=0;n({baseTag:ZLt(["href"],s),bodyAttributes:kwe("bodyAttributes",s),defer:wL(s,_L.DEFER),encode:wL(s,_L.ENCODE_SPECIAL_CHARACTERS),htmlAttributes:kwe("htmlAttributes",s),linkTags:WO("link",["rel","href"],s),metaTags:WO("meta",["name","charset","http-equiv","property","itemprop"],s),noscriptTags:WO("noscript",["innerHTML"],s),onChangeClientState:YLt(s),scriptTags:WO("script",["src","innerHTML"],s),styleTags:WO("style",["cssText"],s),title:KLt(s),titleAttributes:kwe("titleAttributes",s),prioritizeSeoTags:XLt(s,_L.PRIORITIZE_SEO_TAGS)}),uat=s=>Array.isArray(s)?s.join(""):s,e8t=(s,t)=>{const n=Object.keys(s);for(let r=0;rArray.isArray(s)?s.reduce((n,r)=>(e8t(r,t)?n.priority.push(r):n.default.push(r),n),{priority:[],default:[]}):{default:s,priority:[]},sze=(s,t)=>({...s,[t]:void 0}),t8t=["noscript","script","style"],VSe=(s,t=!0)=>t===!1?String(s):String(s).replace(/&/g,"&").replace(//g,">").replace(/"/g,""").replace(/'/g,"'"),hat=s=>Object.keys(s).reduce((t,n)=>{const r=typeof s[n]<"u"?`${n}="${s[n]}"`:`${n}`;return t?`${t} ${r}`:r},""),s8t=(s,t,n,r)=>{const a=hat(n),i=uat(t);return a?`<${s} ${ab}="true" ${a}>${VSe(i,r)}`:`<${s} ${ab}="true">${VSe(i,r)}`},n8t=(s,t,n=!0)=>t.reduce((r,a)=>{const i=a,l=Object.keys(i).filter(d=>!(d==="innerHTML"||d==="cssText")).reduce((d,u)=>{const h=typeof i[u]>"u"?u:`${u}="${VSe(i[u],n)}"`;return d?`${d} ${h}`:h},""),o=i.innerHTML||i.cssText||"",c=t8t.indexOf(s)===-1;return`${r}<${s} ${ab}="true" ${l}${c?"/>":`>${o}`}`},""),mat=(s,t={})=>Object.keys(s).reduce((n,r)=>{const a=oAe[r];return n[a||r]=s[r],n},t),r8t=(s,t,n)=>{const r={key:t,[ab]:!0},a=mat(n,r);return[Ct.createElement("title",a,t)]},fme=(s,t)=>t.map((n,r)=>{const a={key:r,[ab]:!0};return Object.keys(n).forEach(i=>{const o=oAe[i]||i;if(o==="innerHTML"||o==="cssText"){const c=n.innerHTML||n.cssText;a.dangerouslySetInnerHTML={__html:c}}else a[o]=n[i]}),Ct.createElement(s,a)}),pv=(s,t,n=!0)=>{switch(s){case"title":return{toComponent:()=>r8t(s,t.title,t.titleAttributes),toString:()=>s8t(s,t.title,t.titleAttributes,n)};case"bodyAttributes":case"htmlAttributes":return{toComponent:()=>mat(t),toString:()=>hat(t)};default:return{toComponent:()=>fme(s,t),toString:()=>n8t(s,t,n)}}},a8t=({metaTags:s,linkTags:t,scriptTags:n,encode:r})=>{const a=Swe(s,Nwe.meta),i=Swe(t,Nwe.link),l=Swe(n,Nwe.script);return{priorityMethods:{toComponent:()=>[...fme("meta",a.priority),...fme("link",i.priority),...fme("script",l.priority)],toString:()=>`${pv("meta",a.priority,r)} ${pv("link",i.priority,r)} ${pv("script",l.priority,r)}`},metaTags:a.default,linkTags:i.default,scriptTags:l.default}},i8t=s=>{const{baseTag:t,bodyAttributes:n,encode:r=!0,htmlAttributes:a,noscriptTags:i,styleTags:l,title:o="",titleAttributes:c,prioritizeSeoTags:d}=s;let{linkTags:u,metaTags:h,scriptTags:p}=s,f={toComponent:()=>{},toString:()=>""};return d&&({priorityMethods:f,linkTags:u,metaTags:h,scriptTags:p}=a8t(s)),{priority:f,base:pv("base",t,r),bodyAttributes:pv("bodyAttributes",n,r),htmlAttributes:pv("htmlAttributes",a,r),link:pv("link",u,r),meta:pv("meta",h,r),noscript:pv("noscript",i,r),script:pv("script",p,r),style:pv("style",l,r),title:pv("title",{title:o,titleAttributes:c},r)}},HSe=i8t,LV=[],pat=!!(typeof window<"u"&&window.document&&window.document.createElement),GSe=class{constructor(s,t){Ta(this,"instances",[]);Ta(this,"canUseDOM",pat);Ta(this,"context");Ta(this,"value",{setHelmet:s=>{this.context.helmet=s},helmetInstances:{get:()=>this.canUseDOM?LV:this.instances,add:s=>{(this.canUseDOM?LV:this.instances).push(s)},remove:s=>{const t=(this.canUseDOM?LV:this.instances).indexOf(s);(this.canUseDOM?LV:this.instances).splice(t,1)}}});this.context=s,this.canUseDOM=t||!1,t||(s.helmet=HSe({baseTag:[],bodyAttributes:{},encodeSpecialCharacters:!0,htmlAttributes:{},linkTags:[],metaTags:[],noscriptTags:[],scriptTags:[],styleTags:[],title:"",titleAttributes:{}}))}},o8t={},fat=Ct.createContext(o8t),uA,xat=(uA=class extends N.Component{constructor(n){super(n);Ta(this,"helmetData");this.helmetData=new GSe(this.props.context||{},uA.canUseDOM)}render(){return Ct.createElement(fat.Provider,{value:this.helmetData.value},this.props.children)}},Ta(uA,"canUseDOM",pat),uA),iI=(s,t)=>{const n=document.head||document.querySelector("head"),r=n.querySelectorAll(`${s}[${ab}]`),a=[].slice.call(r),i=[];let l;return t&&t.length&&t.forEach(o=>{const c=document.createElement(s);for(const d in o)if(Object.prototype.hasOwnProperty.call(o,d))if(d==="innerHTML")c.innerHTML=o.innerHTML;else if(d==="cssText")c.styleSheet?c.styleSheet.cssText=o.cssText:c.appendChild(document.createTextNode(o.cssText));else{const u=d,h=typeof o[u]>"u"?"":o[u];c.setAttribute(d,h)}c.setAttribute(ab,"true"),a.some((d,u)=>(l=u,c.isEqualNode(d)))?a.splice(l,1):i.push(c)}),a.forEach(o=>{var c;return(c=o.parentNode)==null?void 0:c.removeChild(o)}),i.forEach(o=>n.appendChild(o)),{oldTags:a,newTags:i}},WSe=(s,t)=>{const n=document.getElementsByTagName(s)[0];if(!n)return;const r=n.getAttribute(ab),a=r?r.split(","):[],i=[...a],l=Object.keys(t);for(const o of l){const c=t[o]||"";n.getAttribute(o)!==c&&n.setAttribute(o,c),a.indexOf(o)===-1&&a.push(o);const d=i.indexOf(o);d!==-1&&i.splice(d,1)}for(let o=i.length-1;o>=0;o-=1)n.removeAttribute(i[o]);a.length===i.length?n.removeAttribute(ab):n.getAttribute(ab)!==l.join(",")&&n.setAttribute(ab,l.join(","))},l8t=(s,t)=>{typeof s<"u"&&document.title!==s&&(document.title=uat(s)),WSe("title",t)},nze=(s,t)=>{const{baseTag:n,bodyAttributes:r,htmlAttributes:a,linkTags:i,metaTags:l,noscriptTags:o,onChangeClientState:c,scriptTags:d,styleTags:u,title:h,titleAttributes:p}=s;WSe("body",r),WSe("html",a),l8t(h,p);const f={baseTag:iI("base",n),linkTags:iI("link",i),metaTags:iI("meta",l),noscriptTags:iI("noscript",o),scriptTags:iI("script",d),styleTags:iI("style",u)},y={},_={};Object.keys(f).forEach(v=>{const{newTags:j,oldTags:w}=f[v];j.length&&(y[v]=j),w.length&&(_[v]=f[v].oldTags)}),t&&t(),c(s,y,_)},KO=null,c8t=s=>{KO&&cancelAnimationFrame(KO),s.defer?KO=requestAnimationFrame(()=>{nze(s,()=>{KO=null})}):(nze(s),KO=null)},d8t=c8t,rze=class extends N.Component{constructor(){super(...arguments);Ta(this,"rendered",!1)}shouldComponentUpdate(t){return!GLt(t,this.props)}componentDidUpdate(){this.emitChange()}componentWillUnmount(){const{helmetInstances:t}=this.props.context;t.remove(this),this.emitChange()}emitChange(){const{helmetInstances:t,setHelmet:n}=this.props.context;let r=null;const a=JLt(t.get().map(i=>{const l={...i.props};return delete l.context,l}));xat.canUseDOM?d8t(a):HSe&&(r=HSe(a)),n(r)}init(){if(this.rendered)return;this.rendered=!0;const{helmetInstances:t}=this.props.context;t.add(this),this.emitChange()}render(){return this.init(),null}},_ke,Zo=(_ke=class extends N.Component{shouldComponentUpdate(s){return!ULt(sze(this.props,"helmetData"),sze(s,"helmetData"))}mapNestedChildrenToProps(s,t){if(!t)return null;switch(s.type){case"script":case"noscript":return{innerHTML:t};case"style":return{cssText:t};default:throw new Error(`<${s.type} /> elements are self-closing and can not contain children. Refer to our API for more information.`)}}flattenArrayTypeChildren(s,t,n,r){return{...t,[s.type]:[...t[s.type]||[],{...n,...this.mapNestedChildrenToProps(s,r)}]}}mapObjectTypeChildren(s,t,n,r){switch(s.type){case"title":return{...t,[s.type]:r,titleAttributes:{...n}};case"body":return{...t,bodyAttributes:{...n}};case"html":return{...t,htmlAttributes:{...n}};default:return{...t,[s.type]:{...n}}}}mapArrayTypeChildrenToProps(s,t){let n={...t};return Object.keys(s).forEach(r=>{n={...n,[r]:s[r]}}),n}warnOnInvalidChildren(s,t){return eze(tze.some(n=>s.type===n),typeof s.type=="function"?"You may be attempting to nest components within each other, which is not allowed. Refer to our API for more information.":`Only elements types ${tze.join(", ")} are allowed. Helmet does not support rendering <${s.type}> elements. Refer to our API for more information.`),eze(!t||typeof t=="string"||Array.isArray(t)&&!t.some(n=>typeof n!="string"),`Helmet expects a string as a child of <${s.type}>. Did you forget to wrap your children in braces? ( <${s.type}>{\`\`} ) Refer to our API for more information.`),!0}mapChildrenToProps(s,t){let n={};return Ct.Children.forEach(s,r=>{if(!r||!r.props)return;const{children:a,...i}=r.props,l=Object.keys(i).reduce((c,d)=>(c[WLt[d]||d]=i[d],c),{});let{type:o}=r;switch(typeof o=="symbol"?o=o.toString():this.warnOnInvalidChildren(r,a),o){case"Symbol(react.fragment)":t=this.mapChildrenToProps(a,t);break;case"link":case"meta":case"noscript":case"script":case"style":n=this.flattenArrayTypeChildren(r,n,l,a);break;default:t=this.mapObjectTypeChildren(r,t,l,a);break}}),this.mapArrayTypeChildrenToProps(n,t)}render(){const{children:s,...t}=this.props;let n={...t},{helmetData:r}=t;if(s&&(n=this.mapChildrenToProps(s,n)),r&&!(r instanceof GSe)){const a=r;r=new GSe(a.context,!0),delete n.helmetData}return r?Ct.createElement(rze,{...n,context:r.value}):Ct.createElement(fat.Consumer,null,a=>Ct.createElement(rze,{...n,context:a}))}},Ta(_ke,"defaultProps",{defer:!0,encodeSpecialCharacters:!0,prioritizeSeoTags:!1}),_ke);const u8t=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>xi(async()=>{const{default:r}=await Promise.resolve().then(()=>MD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)};class lAe extends Error{constructor(t,n="FunctionsError",r){super(t),this.name=n,this.context=r}}class h8t extends lAe{constructor(t){super("Failed to send a request to the Edge Function","FunctionsFetchError",t)}}class m8t extends lAe{constructor(t){super("Relay Error invoking the Edge Function","FunctionsRelayError",t)}}class p8t extends lAe{constructor(t){super("Edge Function returned a non-2xx status code","FunctionsHttpError",t)}}var KSe;(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"})(KSe||(KSe={}));var f8t=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class x8t{constructor(t,{headers:n={},customFetch:r,region:a=KSe.Any}={}){this.url=t,this.headers=n,this.region=a,this.fetch=u8t(r)}setAuth(t){this.headers.Authorization=`Bearer ${t}`}invoke(t,n={}){var r;return f8t(this,void 0,void 0,function*(){try{const{headers:a,method:i,body:l}=n;let o={},{region:c}=n;c||(c=this.region),c&&c!=="any"&&(o["x-region"]=c);let d;l&&(a&&!Object.prototype.hasOwnProperty.call(a,"Content-Type")||!a)&&(typeof Blob<"u"&&l instanceof Blob||l instanceof ArrayBuffer?(o["Content-Type"]="application/octet-stream",d=l):typeof l=="string"?(o["Content-Type"]="text/plain",d=l):typeof FormData<"u"&&l instanceof FormData?d=l:(o["Content-Type"]="application/json",d=JSON.stringify(l)));const u=yield this.fetch(`${this.url}/${t}`,{method:i||"POST",headers:Object.assign(Object.assign(Object.assign({},o),this.headers),a),body:d}).catch(y=>{throw new h8t(y)}),h=u.headers.get("x-relay-error");if(h&&h==="true")throw new m8t(u);if(!u.ok)throw new p8t(u);let p=((r=u.headers.get("Content-Type"))!==null&&r!==void 0?r:"text/plain").split(";")[0].trim(),f;return p==="application/json"?f=yield u.json():p==="application/octet-stream"?f=yield u.blob():p==="text/event-stream"?f=u:p==="multipart/form-data"?f=yield u.formData():f=yield u.text(),{data:f,error:null}}catch(a){return{data:null,error:a}}})}}var Mg={},cAe={},j0e={},D$={},N0e={},k0e={},g8t=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")},h8=g8t();const y8t=h8.fetch,gat=h8.fetch.bind(h8),yat=h8.Headers,v8t=h8.Request,b8t=h8.Response,MD=Object.freeze(Object.defineProperty({__proto__:null,Headers:yat,Request:v8t,Response:b8t,default:gat,fetch:y8t},Symbol.toStringTag,{value:"Module"})),_8t=K5t(MD);var S0e={};Object.defineProperty(S0e,"__esModule",{value:!0});let w8t=class extends Error{constructor(t){super(t.message),this.name="PostgrestError",this.details=t.details,this.hint=t.hint,this.code=t.code}};S0e.default=w8t;var vat=kh&&kh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(k0e,"__esModule",{value:!0});const j8t=vat(_8t),N8t=vat(S0e);let k8t=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=j8t.default:this.fetch=fetch}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(t,n){return this.headers=Object.assign({},this.headers),this.headers[t]=n,this}then(t,n){this.schema===void 0||(["GET","HEAD"].includes(this.method)?this.headers["Accept-Profile"]=this.schema:this.headers["Content-Profile"]=this.schema),this.method!=="GET"&&this.method!=="HEAD"&&(this.headers["Content-Type"]="application/json");const r=this.fetch;let a=r(this.url.toString(),{method:this.method,headers:this.headers,body:JSON.stringify(this.body),signal:this.signal}).then(async i=>{var l,o,c;let d=null,u=null,h=null,p=i.status,f=i.statusText;if(i.ok){if(this.method!=="HEAD"){const j=await i.text();j===""||(this.headers.Accept==="text/csv"||this.headers.Accept&&this.headers.Accept.includes("application/vnd.pgrst.plan+text")?u=j:u=JSON.parse(j))}const _=(l=this.headers.Prefer)===null||l===void 0?void 0:l.match(/count=(exact|planned|estimated)/),v=(o=i.headers.get("content-range"))===null||o===void 0?void 0:o.split("/");_&&v&&v.length>1&&(h=parseInt(v[1])),this.isMaybeSingle&&this.method==="GET"&&Array.isArray(u)&&(u.length>1?(d={code:"PGRST116",details:`Results contain ${u.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:"JSON object requested, multiple (or no) rows returned"},u=null,h=null,p=406,f="Not Acceptable"):u.length===1?u=u[0]:u=null)}else{const _=await i.text();try{d=JSON.parse(_),Array.isArray(d)&&i.status===404&&(u=[],d=null,p=200,f="OK")}catch{i.status===404&&_===""?(p=204,f="No Content"):d={message:_}}if(d&&this.isMaybeSingle&&(!((c=d==null?void 0:d.details)===null||c===void 0)&&c.includes("0 rows"))&&(d=null,p=200,f="OK"),d&&this.shouldThrowOnError)throw new N8t.default(d)}return{error:d,data:u,count:h,status:p,statusText:f}});return this.shouldThrowOnError||(a=a.catch(i=>{var l,o,c;return{error:{message:`${(l=i==null?void 0:i.name)!==null&&l!==void 0?l:"FetchError"}: ${i==null?void 0:i.message}`,details:`${(o=i==null?void 0:i.stack)!==null&&o!==void 0?o:""}`,hint:"",code:`${(c=i==null?void 0:i.code)!==null&&c!==void 0?c:""}`},data:null,count:null,status:0,statusText:""}})),a.then(t,n)}returns(){return this}overrideTypes(){return this}};k0e.default=k8t;var S8t=kh&&kh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(N0e,"__esModule",{value:!0});const C8t=S8t(k0e);let T8t=class extends C8t.default{select(t){let n=!1;const r=(t??"*").split("").map(a=>/\s/.test(a)&&!n?"":(a==='"'&&(n=!n),a)).join("");return this.url.searchParams.set("select",r),this.headers.Prefer&&(this.headers.Prefer+=","),this.headers.Prefer+="return=representation",this}order(t,{ascending:n=!0,nullsFirst:r,foreignTable:a,referencedTable:i=a}={}){const l=i?`${i}.order`:"order",o=this.url.searchParams.get(l);return this.url.searchParams.set(l,`${o?`${o},`:""}${t}.${n?"asc":"desc"}${r===void 0?"":r?".nullsfirst":".nullslast"}`),this}limit(t,{foreignTable:n,referencedTable:r=n}={}){const a=typeof r>"u"?"limit":`${r}.limit`;return this.url.searchParams.set(a,`${t}`),this}range(t,n,{foreignTable:r,referencedTable:a=r}={}){const i=typeof a>"u"?"offset":`${a}.offset`,l=typeof a>"u"?"limit":`${a}.limit`;return this.url.searchParams.set(i,`${t}`),this.url.searchParams.set(l,`${n-t+1}`),this}abortSignal(t){return this.signal=t,this}single(){return this.headers.Accept="application/vnd.pgrst.object+json",this}maybeSingle(){return this.method==="GET"?this.headers.Accept="application/json":this.headers.Accept="application/vnd.pgrst.object+json",this.isMaybeSingle=!0,this}csv(){return this.headers.Accept="text/csv",this}geojson(){return this.headers.Accept="application/geo+json",this}explain({analyze:t=!1,verbose:n=!1,settings:r=!1,buffers:a=!1,wal:i=!1,format:l="text"}={}){var o;const c=[t?"analyze":null,n?"verbose":null,r?"settings":null,a?"buffers":null,i?"wal":null].filter(Boolean).join("|"),d=(o=this.headers.Accept)!==null&&o!==void 0?o:"application/json";return this.headers.Accept=`application/vnd.pgrst.plan+${l}; for="${d}"; options=${c};`,l==="json"?this:this}rollback(){var t;return((t=this.headers.Prefer)!==null&&t!==void 0?t:"").trim().length>0?this.headers.Prefer+=",tx=rollback":this.headers.Prefer="tx=rollback",this}returns(){return this}};N0e.default=T8t;var E8t=kh&&kh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(D$,"__esModule",{value:!0});const A8t=E8t(N0e);let M8t=class extends A8t.default{eq(t,n){return this.url.searchParams.append(t,`eq.${n}`),this}neq(t,n){return this.url.searchParams.append(t,`neq.${n}`),this}gt(t,n){return this.url.searchParams.append(t,`gt.${n}`),this}gte(t,n){return this.url.searchParams.append(t,`gte.${n}`),this}lt(t,n){return this.url.searchParams.append(t,`lt.${n}`),this}lte(t,n){return this.url.searchParams.append(t,`lte.${n}`),this}like(t,n){return this.url.searchParams.append(t,`like.${n}`),this}likeAllOf(t,n){return this.url.searchParams.append(t,`like(all).{${n.join(",")}}`),this}likeAnyOf(t,n){return this.url.searchParams.append(t,`like(any).{${n.join(",")}}`),this}ilike(t,n){return this.url.searchParams.append(t,`ilike.${n}`),this}ilikeAllOf(t,n){return this.url.searchParams.append(t,`ilike(all).{${n.join(",")}}`),this}ilikeAnyOf(t,n){return this.url.searchParams.append(t,`ilike(any).{${n.join(",")}}`),this}is(t,n){return this.url.searchParams.append(t,`is.${n}`),this}in(t,n){const r=Array.from(new Set(n)).map(a=>typeof a=="string"&&new RegExp("[,()]").test(a)?`"${a}"`:`${a}`).join(",");return this.url.searchParams.append(t,`in.(${r})`),this}contains(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cs.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cs.{${n.join(",")}}`):this.url.searchParams.append(t,`cs.${JSON.stringify(n)}`),this}containedBy(t,n){return typeof n=="string"?this.url.searchParams.append(t,`cd.${n}`):Array.isArray(n)?this.url.searchParams.append(t,`cd.{${n.join(",")}}`):this.url.searchParams.append(t,`cd.${JSON.stringify(n)}`),this}rangeGt(t,n){return this.url.searchParams.append(t,`sr.${n}`),this}rangeGte(t,n){return this.url.searchParams.append(t,`nxl.${n}`),this}rangeLt(t,n){return this.url.searchParams.append(t,`sl.${n}`),this}rangeLte(t,n){return this.url.searchParams.append(t,`nxr.${n}`),this}rangeAdjacent(t,n){return this.url.searchParams.append(t,`adj.${n}`),this}overlaps(t,n){return typeof n=="string"?this.url.searchParams.append(t,`ov.${n}`):this.url.searchParams.append(t,`ov.{${n.join(",")}}`),this}textSearch(t,n,{config:r,type:a}={}){let i="";a==="plain"?i="pl":a==="phrase"?i="ph":a==="websearch"&&(i="w");const l=r===void 0?"":`(${r})`;return this.url.searchParams.append(t,`${i}fts${l}.${n}`),this}match(t){return Object.entries(t).forEach(([n,r])=>{this.url.searchParams.append(n,`eq.${r}`)}),this}not(t,n,r){return this.url.searchParams.append(t,`not.${n}.${r}`),this}or(t,{foreignTable:n,referencedTable:r=n}={}){const a=r?`${r}.or`:"or";return this.url.searchParams.append(a,`(${t})`),this}filter(t,n,r){return this.url.searchParams.append(t,`${n}.${r}`),this}};D$.default=M8t;var I8t=kh&&kh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(j0e,"__esModule",{value:!0});const YO=I8t(D$);let P8t=class{constructor(t,{headers:n={},schema:r,fetch:a}){this.url=t,this.headers=n,this.schema=r,this.fetch=a}select(t,{head:n=!1,count:r}={}){const a=n?"HEAD":"GET";let i=!1;const l=(t??"*").split("").map(o=>/\s/.test(o)&&!i?"":(o==='"'&&(i=!i),o)).join("");return this.url.searchParams.set("select",l),r&&(this.headers.Prefer=`count=${r}`),new YO.default({method:a,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}insert(t,{count:n,defaultToNull:r=!0}={}){const a="POST",i=[];if(this.headers.Prefer&&i.push(this.headers.Prefer),n&&i.push(`count=${n}`),r||i.push("missing=default"),this.headers.Prefer=i.join(","),Array.isArray(t)){const l=t.reduce((o,c)=>o.concat(Object.keys(c)),[]);if(l.length>0){const o=[...new Set(l)].map(c=>`"${c}"`);this.url.searchParams.set("columns",o.join(","))}}return new YO.default({method:a,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}upsert(t,{onConflict:n,ignoreDuplicates:r=!1,count:a,defaultToNull:i=!0}={}){const l="POST",o=[`resolution=${r?"ignore":"merge"}-duplicates`];if(n!==void 0&&this.url.searchParams.set("on_conflict",n),this.headers.Prefer&&o.push(this.headers.Prefer),a&&o.push(`count=${a}`),i||o.push("missing=default"),this.headers.Prefer=o.join(","),Array.isArray(t)){const c=t.reduce((d,u)=>d.concat(Object.keys(u)),[]);if(c.length>0){const d=[...new Set(c)].map(u=>`"${u}"`);this.url.searchParams.set("columns",d.join(","))}}return new YO.default({method:l,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}update(t,{count:n}={}){const r="PATCH",a=[];return this.headers.Prefer&&a.push(this.headers.Prefer),n&&a.push(`count=${n}`),this.headers.Prefer=a.join(","),new YO.default({method:r,url:this.url,headers:this.headers,schema:this.schema,body:t,fetch:this.fetch,allowEmpty:!1})}delete({count:t}={}){const n="DELETE",r=[];return t&&r.push(`count=${t}`),this.headers.Prefer&&r.unshift(this.headers.Prefer),this.headers.Prefer=r.join(","),new YO.default({method:n,url:this.url,headers:this.headers,schema:this.schema,fetch:this.fetch,allowEmpty:!1})}};j0e.default=P8t;var C0e={},T0e={};Object.defineProperty(T0e,"__esModule",{value:!0});T0e.version=void 0;T0e.version="0.0.0-automated";Object.defineProperty(C0e,"__esModule",{value:!0});C0e.DEFAULT_HEADERS=void 0;const L8t=T0e;C0e.DEFAULT_HEADERS={"X-Client-Info":`postgrest-js/${L8t.version}`};var bat=kh&&kh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(cAe,"__esModule",{value:!0});const D8t=bat(j0e),R8t=bat(D$),O8t=C0e;let F8t=class _at{constructor(t,{headers:n={},schema:r,fetch:a}={}){this.url=t,this.headers=Object.assign(Object.assign({},O8t.DEFAULT_HEADERS),n),this.schemaName=r,this.fetch=a}from(t){const n=new URL(`${this.url}/${t}`);return new D8t.default(n,{headers:Object.assign({},this.headers),schema:this.schemaName,fetch:this.fetch})}schema(t){return new _at(this.url,{headers:this.headers,schema:t,fetch:this.fetch})}rpc(t,n={},{head:r=!1,get:a=!1,count:i}={}){let l;const o=new URL(`${this.url}/rpc/${t}`);let c;r||a?(l=r?"HEAD":"GET",Object.entries(n).filter(([u,h])=>h!==void 0).map(([u,h])=>[u,Array.isArray(h)?`{${h.join(",")}}`:`${h}`]).forEach(([u,h])=>{o.searchParams.append(u,h)})):(l="POST",c=n);const d=Object.assign({},this.headers);return i&&(d.Prefer=`count=${i}`),new R8t.default({method:l,url:o,headers:d,schema:this.schemaName,body:c,fetch:this.fetch,allowEmpty:!1})}};cAe.default=F8t;var ID=kh&&kh.__importDefault||function(s){return s&&s.__esModule?s:{default:s}};Object.defineProperty(Mg,"__esModule",{value:!0});Mg.PostgrestError=Mg.PostgrestBuilder=Mg.PostgrestTransformBuilder=Mg.PostgrestFilterBuilder=Mg.PostgrestQueryBuilder=Mg.PostgrestClient=void 0;const wat=ID(cAe);Mg.PostgrestClient=wat.default;const jat=ID(j0e);Mg.PostgrestQueryBuilder=jat.default;const Nat=ID(D$);Mg.PostgrestFilterBuilder=Nat.default;const kat=ID(N0e);Mg.PostgrestTransformBuilder=kat.default;const Sat=ID(k0e);Mg.PostgrestBuilder=Sat.default;const Cat=ID(S0e);Mg.PostgrestError=Cat.default;var z8t=Mg.default={PostgrestClient:wat.default,PostgrestQueryBuilder:jat.default,PostgrestFilterBuilder:Nat.default,PostgrestTransformBuilder:kat.default,PostgrestBuilder:Sat.default,PostgrestError:Cat.default};const{PostgrestClient:B8t,PostgrestQueryBuilder:Upn,PostgrestFilterBuilder:qpn,PostgrestTransformBuilder:Vpn,PostgrestBuilder:Hpn,PostgrestError:Gpn}=z8t;let YSe;typeof window>"u"?YSe=require("ws"):YSe=window.WebSocket;const $8t=YSe,U8t="2.11.10",q8t={"X-Client-Info":`realtime-js/${U8t}`},V8t="1.0.0",Tat=1e4,H8t=1e3;var jL;(function(s){s[s.connecting=0]="connecting",s[s.open=1]="open",s[s.closing=2]="closing",s[s.closed=3]="closed"})(jL||(jL={}));var Ox;(function(s){s.closed="closed",s.errored="errored",s.joined="joined",s.joining="joining",s.leaving="leaving"})(Ox||(Ox={}));var G1;(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"})(G1||(G1={}));var ZSe;(function(s){s.websocket="websocket"})(ZSe||(ZSe={}));var PE;(function(s){s.Connecting="connecting",s.Open="open",s.Closing="closing",s.Closed="closed"})(PE||(PE={}));class G8t{constructor(){this.HEADER_LENGTH=1}decode(t,n){return t.constructor===ArrayBuffer?n(this._binaryDecode(t)):n(typeof t=="string"?JSON.parse(t):{})}_binaryDecode(t){const n=new DataView(t),r=new TextDecoder;return this._decodeBroadcast(t,n,r)}_decodeBroadcast(t,n,r){const a=n.getUint8(1),i=n.getUint8(2);let l=this.HEADER_LENGTH+2;const o=r.decode(t.slice(l,l+a));l=l+a;const c=r.decode(t.slice(l,l+i));l=l+i;const d=JSON.parse(r.decode(t.slice(l,t.byteLength)));return{ref:null,topic:o,event:c,payload:d}}}class Eat{constructor(t,n){this.callback=t,this.timerCalc=n,this.timer=void 0,this.tries=0,this.callback=t,this.timerCalc=n}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries=this.tries+1,this.callback()},this.timerCalc(this.tries+1))}}var hd;(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"})(hd||(hd={}));const aze=(s,t,n={})=>{var r;const a=(r=n.skipTypes)!==null&&r!==void 0?r:[];return Object.keys(t).reduce((i,l)=>(i[l]=W8t(l,s,t,a),i),{})},W8t=(s,t,n,r)=>{const a=t.find(o=>o.name===s),i=a==null?void 0:a.type,l=n[s];return i&&!r.includes(i)?Aat(i,l):QSe(l)},Aat=(s,t)=>{if(s.charAt(0)==="_"){const n=s.slice(1,s.length);return Q8t(t,n)}switch(s){case hd.bool:return K8t(t);case hd.float4:case hd.float8:case hd.int2:case hd.int4:case hd.int8:case hd.numeric:case hd.oid:return Y8t(t);case hd.json:case hd.jsonb:return Z8t(t);case hd.timestamp:return X8t(t);case hd.abstime:case hd.date:case hd.daterange:case hd.int4range:case hd.int8range:case hd.money:case hd.reltime:case hd.text:case hd.time:case hd.timestamptz:case hd.timetz:case hd.tsrange:case hd.tstzrange:return QSe(t);default:return QSe(t)}},QSe=s=>s,K8t=s=>{switch(s){case"t":return!0;case"f":return!1;default:return s}},Y8t=s=>{if(typeof s=="string"){const t=parseFloat(s);if(!Number.isNaN(t))return t}return s},Z8t=s=>{if(typeof s=="string")try{return JSON.parse(s)}catch(t){return console.log(`JSON parse error: ${t}`),s}return s},Q8t=(s,t)=>{if(typeof s!="string")return s;const n=s.length-1,r=s[n];if(s[0]==="{"&&r==="}"){let i;const l=s.slice(1,n);try{i=JSON.parse("["+l+"]")}catch{i=l?l.split(","):[]}return i.map(o=>Aat(t,o))}return s},X8t=s=>typeof s=="string"?s.replace(" ","T"):s,Mat=s=>{let t=s;return t=t.replace(/^ws/i,"http"),t=t.replace(/(\/socket\/websocket|\/socket|\/websocket)\/?$/i,""),t.replace(/\/+$/,"")};class Cwe{constructor(t,n,r={},a=Tat){this.channel=t,this.event=n,this.payload=r,this.timeout=a,this.sent=!1,this.timeoutTimer=void 0,this.ref="",this.receivedResp=null,this.recHooks=[],this.refEvent=null}resend(t){this.timeout=t,this._cancelRefEvent(),this.ref="",this.refEvent=null,this.receivedResp=null,this.sent=!1,this.send()}send(){this._hasReceived("timeout")||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload,ref:this.ref,join_ref:this.channel._joinRef()}))}updatePayload(t){this.payload=Object.assign(Object.assign({},this.payload),t)}receive(t,n){var r;return this._hasReceived(t)&&n((r=this.receivedResp)===null||r===void 0?void 0:r.response),this.recHooks.push({status:t,callback:n}),this}startTimeout(){if(this.timeoutTimer)return;this.ref=this.channel.socket._makeRef(),this.refEvent=this.channel._replyEventName(this.ref);const t=n=>{this._cancelRefEvent(),this._cancelTimeout(),this.receivedResp=n,this._matchReceive(n)};this.channel._on(this.refEvent,{},t),this.timeoutTimer=setTimeout(()=>{this.trigger("timeout",{})},this.timeout)}trigger(t,n){this.refEvent&&this.channel._trigger(this.refEvent,{status:t,response:n})}destroy(){this._cancelRefEvent(),this._cancelTimeout()}_cancelRefEvent(){this.refEvent&&this.channel._off(this.refEvent,{})}_cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=void 0}_matchReceive({status:t,response:n}){this.recHooks.filter(r=>r.status===t).forEach(r=>r.callback(n))}_hasReceived(t){return this.receivedResp&&this.receivedResp.status===t}}var ize;(function(s){s.SYNC="sync",s.JOIN="join",s.LEAVE="leave"})(ize||(ize={}));class P9{constructor(t,n){this.channel=t,this.state={},this.pendingDiffs=[],this.joinRef=null,this.caller={onJoin:()=>{},onLeave:()=>{},onSync:()=>{}};const r=(n==null?void 0:n.events)||{state:"presence_state",diff:"presence_diff"};this.channel._on(r.state,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.joinRef=this.channel._joinRef(),this.state=P9.syncState(this.state,a,i,l),this.pendingDiffs.forEach(c=>{this.state=P9.syncDiff(this.state,c,i,l)}),this.pendingDiffs=[],o()}),this.channel._on(r.diff,{},a=>{const{onJoin:i,onLeave:l,onSync:o}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(a):(this.state=P9.syncDiff(this.state,a,i,l),o())}),this.onJoin((a,i,l)=>{this.channel._trigger("presence",{event:"join",key:a,currentPresences:i,newPresences:l})}),this.onLeave((a,i,l)=>{this.channel._trigger("presence",{event:"leave",key:a,currentPresences:i,leftPresences:l})}),this.onSync(()=>{this.channel._trigger("presence",{event:"sync"})})}static syncState(t,n,r,a){const i=this.cloneDeep(t),l=this.transformState(n),o={},c={};return this.map(i,(d,u)=>{l[d]||(c[d]=u)}),this.map(l,(d,u)=>{const h=i[d];if(h){const p=u.map(v=>v.presence_ref),f=h.map(v=>v.presence_ref),y=u.filter(v=>f.indexOf(v.presence_ref)<0),_=h.filter(v=>p.indexOf(v.presence_ref)<0);y.length>0&&(o[d]=y),_.length>0&&(c[d]=_)}else o[d]=u}),this.syncDiff(i,{joins:o,leaves:c},r,a)}static syncDiff(t,n,r,a){const{joins:i,leaves:l}={joins:this.transformState(n.joins),leaves:this.transformState(n.leaves)};return r||(r=()=>{}),a||(a=()=>{}),this.map(i,(o,c)=>{var d;const u=(d=t[o])!==null&&d!==void 0?d:[];if(t[o]=this.cloneDeep(c),u.length>0){const h=t[o].map(f=>f.presence_ref),p=u.filter(f=>h.indexOf(f.presence_ref)<0);t[o].unshift(...p)}r(o,u,c)}),this.map(l,(o,c)=>{let d=t[o];if(!d)return;const u=c.map(h=>h.presence_ref);d=d.filter(h=>u.indexOf(h.presence_ref)<0),t[o]=d,a(o,d,c),d.length===0&&delete t[o]}),t}static map(t,n){return Object.getOwnPropertyNames(t).map(r=>n(r,t[r]))}static transformState(t){return t=this.cloneDeep(t),Object.getOwnPropertyNames(t).reduce((n,r)=>{const a=t[r];return"metas"in a?n[r]=a.metas.map(i=>(i.presence_ref=i.phx_ref,delete i.phx_ref,delete i.phx_ref_prev,i)):n[r]=a,n},{})}static cloneDeep(t){return JSON.parse(JSON.stringify(t))}onJoin(t){this.caller.onJoin=t}onLeave(t){this.caller.onLeave=t}onSync(t){this.caller.onSync=t}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel._joinRef()}}var oze;(function(s){s.ALL="*",s.INSERT="INSERT",s.UPDATE="UPDATE",s.DELETE="DELETE"})(oze||(oze={}));var lze;(function(s){s.BROADCAST="broadcast",s.PRESENCE="presence",s.POSTGRES_CHANGES="postgres_changes",s.SYSTEM="system"})(lze||(lze={}));var y2;(function(s){s.SUBSCRIBED="SUBSCRIBED",s.TIMED_OUT="TIMED_OUT",s.CLOSED="CLOSED",s.CHANNEL_ERROR="CHANNEL_ERROR"})(y2||(y2={}));class dAe{constructor(t,n={config:{}},r){this.topic=t,this.params=n,this.socket=r,this.bindings={},this.state=Ox.closed,this.joinedOnce=!1,this.pushBuffer=[],this.subTopic=t.replace(/^realtime:/i,""),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:""},private:!1},n.config),this.timeout=this.socket.timeout,this.joinPush=new Cwe(this,G1.join,this.params,this.timeout),this.rejoinTimer=new Eat(()=>this._rejoinUntilConnected(),this.socket.reconnectAfterMs),this.joinPush.receive("ok",()=>{this.state=Ox.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=Ox.closed,this.socket._remove(this)}),this._onError(a=>{this._isLeaving()||this._isClosed()||(this.socket.log("channel",`error ${this.topic}`,a),this.state=Ox.errored,this.rejoinTimer.scheduleTimeout())}),this.joinPush.receive("timeout",()=>{this._isJoining()&&(this.socket.log("channel",`timeout ${this.topic}`,this.joinPush.timeout),this.state=Ox.errored,this.rejoinTimer.scheduleTimeout())}),this._on(G1.reply,{},(a,i)=>{this._trigger(this._replyEventName(i),a)}),this.presence=new P9(this),this.broadcastEndpointURL=Mat(this.socket.endPoint)+"/api/broadcast",this.private=this.params.config.private||!1}subscribe(t,n=this.timeout){var r,a;if(this.socket.isConnected()||this.socket.connect(),this.joinedOnce)throw"tried to subscribe multiple times. 'subscribe' can only be called a single time per channel instance";{const{config:{broadcast:i,presence:l,private:o}}=this.params;this._onError(u=>t==null?void 0:t(y2.CHANNEL_ERROR,u)),this._onClose(()=>t==null?void 0:t(y2.CLOSED));const c={},d={broadcast:i,presence:l,postgres_changes:(a=(r=this.bindings.postgres_changes)===null||r===void 0?void 0:r.map(u=>u.filter))!==null&&a!==void 0?a:[],private:o};this.socket.accessTokenValue&&(c.access_token=this.socket.accessTokenValue),this.updateJoinPayload(Object.assign({config:d},c)),this.joinedOnce=!0,this._rejoin(n),this.joinPush.receive("ok",async({postgres_changes:u})=>{var h;if(this.socket.setAuth(),u===void 0){t==null||t(y2.SUBSCRIBED);return}else{const p=this.bindings.postgres_changes,f=(h=p==null?void 0:p.length)!==null&&h!==void 0?h:0,y=[];for(let _=0;_{this.state=Ox.errored,t==null||t(y2.CHANNEL_ERROR,new Error(JSON.stringify(Object.values(u).join(", ")||"error")))}).receive("timeout",()=>{t==null||t(y2.TIMED_OUT)})}return this}presenceState(){return this.presence.state}async track(t,n={}){return await this.send({type:"presence",event:"track",payload:t},n.timeout||this.timeout)}async untrack(t={}){return await this.send({type:"presence",event:"untrack"},t)}on(t,n,r){return this._on(t,n,r)}async send(t,n={}){var r,a;if(!this._canPush()&&t.type==="broadcast"){const{event:i,payload:l}=t,c={method:"POST",headers:{Authorization:this.socket.accessTokenValue?`Bearer ${this.socket.accessTokenValue}`:"",apikey:this.socket.apiKey?this.socket.apiKey:"","Content-Type":"application/json"},body:JSON.stringify({messages:[{topic:this.subTopic,event:i,payload:l,private:this.private}]})};try{const d=await this._fetchWithTimeout(this.broadcastEndpointURL,c,(r=n.timeout)!==null&&r!==void 0?r:this.timeout);return await((a=d.body)===null||a===void 0?void 0:a.cancel()),d.ok?"ok":"error"}catch(d){return d.name==="AbortError"?"timed out":"error"}}else return new Promise(i=>{var l,o,c;const d=this._push(t.type,t,n.timeout||this.timeout);t.type==="broadcast"&&!(!((c=(o=(l=this.params)===null||l===void 0?void 0:l.config)===null||o===void 0?void 0:o.broadcast)===null||c===void 0)&&c.ack)&&i("ok"),d.receive("ok",()=>i("ok")),d.receive("error",()=>i("error")),d.receive("timeout",()=>i("timed out"))})}updateJoinPayload(t){this.joinPush.updatePayload(t)}unsubscribe(t=this.timeout){this.state=Ox.leaving;const n=()=>{this.socket.log("channel",`leave ${this.topic}`),this._trigger(G1.close,"leave",this._joinRef())};return this.joinPush.destroy(),new Promise(r=>{const a=new Cwe(this,G1.leave,{},t);a.receive("ok",()=>{n(),r("ok")}).receive("timeout",()=>{n(),r("timed out")}).receive("error",()=>{r("error")}),a.send(),this._canPush()||a.trigger("ok",{})})}teardown(){this.pushBuffer.forEach(t=>t.destroy()),this.rejoinTimer&&clearTimeout(this.rejoinTimer.timer),this.joinPush.destroy()}async _fetchWithTimeout(t,n,r){const a=new AbortController,i=setTimeout(()=>a.abort(),r),l=await this.socket.fetch(t,Object.assign(Object.assign({},n),{signal:a.signal}));return clearTimeout(i),l}_push(t,n,r=this.timeout){if(!this.joinedOnce)throw`tried to push '${t}' to '${this.topic}' before joining. Use channel.subscribe() before pushing events`;let a=new Cwe(this,t,n,r);return this._canPush()?a.send():(a.startTimeout(),this.pushBuffer.push(a)),a}_onMessage(t,n,r){return n}_isMember(t){return this.topic===t}_joinRef(){return this.joinPush.ref}_trigger(t,n,r){var a,i;const l=t.toLocaleLowerCase(),{close:o,error:c,leave:d,join:u}=G1;if(r&&[o,c,d,u].indexOf(l)>=0&&r!==this._joinRef())return;let p=this._onMessage(l,n,r);if(n&&!p)throw"channel onMessage callbacks must return the payload, modified or unmodified";["insert","update","delete"].includes(l)?(a=this.bindings.postgres_changes)===null||a===void 0||a.filter(f=>{var y,_,v;return((y=f.filter)===null||y===void 0?void 0:y.event)==="*"||((v=(_=f.filter)===null||_===void 0?void 0:_.event)===null||v===void 0?void 0:v.toLocaleLowerCase())===l}).map(f=>f.callback(p,r)):(i=this.bindings[l])===null||i===void 0||i.filter(f=>{var y,_,v,j,w,S;if(["broadcast","presence","postgres_changes"].includes(l))if("id"in f){const A=f.id,E=(y=f.filter)===null||y===void 0?void 0:y.event;return A&&((_=n.ids)===null||_===void 0?void 0:_.includes(A))&&(E==="*"||(E==null?void 0:E.toLocaleLowerCase())===((v=n.data)===null||v===void 0?void 0:v.type.toLocaleLowerCase()))}else{const A=(w=(j=f==null?void 0:f.filter)===null||j===void 0?void 0:j.event)===null||w===void 0?void 0:w.toLocaleLowerCase();return A==="*"||A===((S=n==null?void 0:n.event)===null||S===void 0?void 0:S.toLocaleLowerCase())}else return f.type.toLocaleLowerCase()===l}).map(f=>{if(typeof p=="object"&&"ids"in p){const y=p.data,{schema:_,table:v,commit_timestamp:j,type:w,errors:S}=y;p=Object.assign(Object.assign({},{schema:_,table:v,commit_timestamp:j,eventType:w,new:{},old:{},errors:S}),this._getPayloadRecords(y))}f.callback(p,r)})}_isClosed(){return this.state===Ox.closed}_isJoined(){return this.state===Ox.joined}_isJoining(){return this.state===Ox.joining}_isLeaving(){return this.state===Ox.leaving}_replyEventName(t){return`chan_reply_${t}`}_on(t,n,r){const a=t.toLocaleLowerCase(),i={type:a,filter:n,callback:r};return this.bindings[a]?this.bindings[a].push(i):this.bindings[a]=[i],this}_off(t,n){const r=t.toLocaleLowerCase();return this.bindings[r]=this.bindings[r].filter(a=>{var i;return!(((i=a.type)===null||i===void 0?void 0:i.toLocaleLowerCase())===r&&dAe.isEqual(a.filter,n))}),this}static isEqual(t,n){if(Object.keys(t).length!==Object.keys(n).length)return!1;for(const r in t)if(t[r]!==n[r])return!1;return!0}_rejoinUntilConnected(){this.rejoinTimer.scheduleTimeout(),this.socket.isConnected()&&this._rejoin()}_onClose(t){this._on(G1.close,{},t)}_onError(t){this._on(G1.error,{},n=>t(n))}_canPush(){return this.socket.isConnected()&&this._isJoined()}_rejoin(t=this.timeout){this._isLeaving()||(this.socket._leaveOpenTopic(this.topic),this.state=Ox.joining,this.joinPush.resend(t))}_getPayloadRecords(t){const n={new:{},old:{}};return(t.type==="INSERT"||t.type==="UPDATE")&&(n.new=aze(t.columns,t.record)),(t.type==="UPDATE"||t.type==="DELETE")&&(n.old=aze(t.columns,t.old_record)),n}}const cze=()=>{},J8t=` addEventListener("message", (e) => { if (e.data.event === "start") { setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval); } });`;class eDt{constructor(t,n){var r;this.accessTokenValue=null,this.apiKey=null,this.channels=new Array,this.endPoint="",this.httpEndpoint="",this.headers=q8t,this.params={},this.timeout=Tat,this.heartbeatIntervalMs=25e3,this.heartbeatTimer=void 0,this.pendingHeartbeatRef=null,this.heartbeatCallback=cze,this.ref=0,this.logger=cze,this.conn=null,this.sendBuffer=[],this.serializer=new G8t,this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.accessToken=null,this._resolveFetch=i=>{let l;return i?l=i:typeof fetch>"u"?l=(...o)=>xi(async()=>{const{default:c}=await Promise.resolve().then(()=>MD);return{default:c}},void 0).then(({default:c})=>c(...o)):l=fetch,(...o)=>l(...o)},this.endPoint=`${t}/${ZSe.websocket}`,this.httpEndpoint=Mat(t),n!=null&&n.transport?this.transport=n.transport:this.transport=null,n!=null&&n.params&&(this.params=n.params),n!=null&&n.headers&&(this.headers=Object.assign(Object.assign({},this.headers),n.headers)),n!=null&&n.timeout&&(this.timeout=n.timeout),n!=null&&n.logger&&(this.logger=n.logger),(n!=null&&n.logLevel||n!=null&&n.log_level)&&(this.logLevel=n.logLevel||n.log_level,this.params=Object.assign(Object.assign({},this.params),{log_level:this.logLevel})),n!=null&&n.heartbeatIntervalMs&&(this.heartbeatIntervalMs=n.heartbeatIntervalMs);const a=(r=n==null?void 0:n.params)===null||r===void 0?void 0:r.apikey;if(a&&(this.accessTokenValue=a,this.apiKey=a),this.reconnectAfterMs=n!=null&&n.reconnectAfterMs?n.reconnectAfterMs:i=>[1e3,2e3,5e3,1e4][i-1]||1e4,this.encode=n!=null&&n.encode?n.encode:(i,l)=>l(JSON.stringify(i)),this.decode=n!=null&&n.decode?n.decode:this.serializer.decode.bind(this.serializer),this.reconnectTimer=new Eat(async()=>{this.disconnect(),this.connect()},this.reconnectAfterMs),this.fetch=this._resolveFetch(n==null?void 0:n.fetch),n!=null&&n.worker){if(typeof window<"u"&&!window.Worker)throw new Error("Web Worker is not supported");this.worker=(n==null?void 0:n.worker)||!1,this.workerUrl=n==null?void 0:n.workerUrl}this.accessToken=(n==null?void 0:n.accessToken)||null}connect(){if(!this.conn){if(this.transport||(this.transport=$8t),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 tDt(this.endpointURL(),void 0,{close:()=>{this.conn=null}})}}endpointURL(){return this._appendParams(this.endPoint,Object.assign({},this.params,{vsn:V8t}))}disconnect(t,n){this.conn&&(this.conn.onclose=function(){},t?this.conn.close(t,n??""):this.conn.close(),this.conn=null,this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.reset(),this.channels.forEach(r=>r.teardown()))}getChannels(){return this.channels}async removeChannel(t){const n=await t.unsubscribe();return this.channels=this.channels.filter(r=>r._joinRef!==t._joinRef),this.channels.length===0&&this.disconnect(),n}async removeAllChannels(){const t=await Promise.all(this.channels.map(n=>n.unsubscribe()));return this.channels=[],this.disconnect(),t}log(t,n,r){this.logger(t,n,r)}connectionState(){switch(this.conn&&this.conn.readyState){case jL.connecting:return PE.Connecting;case jL.open:return PE.Open;case jL.closing:return PE.Closing;default:return PE.Closed}}isConnected(){return this.connectionState()===PE.Open}channel(t,n={config:{}}){const r=`realtime:${t}`,a=this.getChannels().find(i=>i.topic===r);if(a)return a;{const i=new dAe(`realtime:${t}`,n,this);return this.channels.push(i),i}}push(t){const{topic:n,event:r,payload:a,ref:i}=t,l=()=>{this.encode(t,o=>{var c;(c=this.conn)===null||c===void 0||c.send(o)})};this.log("push",`${n} ${r} (${i})`,a),this.isConnected()?l():this.sendBuffer.push(l)}async setAuth(t=null){let n=t||this.accessToken&&await this.accessToken()||this.accessTokenValue;this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(r=>{n&&r.updateJoinPayload({access_token:n,version:this.headers&&this.headers["X-Client-Info"]}),r.joinedOnce&&r._isJoined()&&r._push(G1.access_token,{access_token:n})}))}async sendHeartbeat(){var t;if(!this.isConnected()){this.heartbeatCallback("disconnected");return}if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.log("transport","heartbeat timeout. Attempting to re-establish connection"),this.heartbeatCallback("timeout"),(t=this.conn)===null||t===void 0||t.close(H8t,"hearbeat timeout");return}this.pendingHeartbeatRef=this._makeRef(),this.push({topic:"phoenix",event:"heartbeat",payload:{},ref:this.pendingHeartbeatRef}),this.heartbeatCallback("sent"),await this.setAuth()}onHeartbeat(t){this.heartbeatCallback=t}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(t=>t()),this.sendBuffer=[])}_makeRef(){let t=this.ref+1;return t===this.ref?this.ref=0:this.ref=t,this.ref.toString()}_leaveOpenTopic(t){let n=this.channels.find(r=>r.topic===t&&(r._isJoined()||r._isJoining()));n&&(this.log("transport",`leaving duplicate topic "${t}"`),n.unsubscribe())}_remove(t){this.channels=this.channels.filter(n=>n.topic!==t.topic)}setupConnection(){this.conn&&(this.conn.binaryType="arraybuffer",this.conn.onopen=()=>this._onConnOpen(),this.conn.onerror=t=>this._onConnError(t),this.conn.onmessage=t=>this._onConnMessage(t),this.conn.onclose=t=>this._onConnClose(t))}_onConnMessage(t){this.decode(t.data,n=>{let{topic:r,event:a,payload:i,ref:l}=n;r==="phoenix"&&a==="phx_reply"&&this.heartbeatCallback(n.payload.status=="ok"?"ok":"error"),l&&l===this.pendingHeartbeatRef&&(this.pendingHeartbeatRef=null),this.log("receive",`${i.status||""} ${r} ${a} ${l&&"("+l+")"||""}`,i),Array.from(this.channels).filter(o=>o._isMember(r)).forEach(o=>o._trigger(a,i,l)),this.stateChangeCallbacks.message.forEach(o=>o(n))})}_onConnOpen(){if(this.log("transport",`connected to ${this.endpointURL()}`),this.flushSendBuffer(),this.reconnectTimer.reset(),!this.worker)this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.heartbeatTimer=setInterval(()=>this.sendHeartbeat(),this.heartbeatIntervalMs);else{this.workerUrl?this.log("worker",`starting worker for from ${this.workerUrl}`):this.log("worker","starting default worker");const t=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(t),this.workerRef.onerror=n=>{this.log("worker","worker error",n.message),this.workerRef.terminate()},this.workerRef.onmessage=n=>{n.data.event==="keepAlive"&&this.sendHeartbeat()},this.workerRef.postMessage({event:"start",interval:this.heartbeatIntervalMs})}this.stateChangeCallbacks.open.forEach(t=>t())}_onConnClose(t){this.log("transport","close",t),this._triggerChanError(),this.heartbeatTimer&&clearInterval(this.heartbeatTimer),this.reconnectTimer.scheduleTimeout(),this.stateChangeCallbacks.close.forEach(n=>n(t))}_onConnError(t){this.log("transport",t.message),this._triggerChanError(),this.stateChangeCallbacks.error.forEach(n=>n(t))}_triggerChanError(){this.channels.forEach(t=>t._trigger(G1.error))}_appendParams(t,n){if(Object.keys(n).length===0)return t;const r=t.match(/\?/)?"&":"?",a=new URLSearchParams(n);return`${t}${r}${a}`}_workerObjectUrl(t){let n;if(t)n=t;else{const r=new Blob([J8t],{type:"application/javascript"});n=URL.createObjectURL(r)}return n}}class tDt{constructor(t,n,r){this.binaryType="arraybuffer",this.onclose=()=>{},this.onerror=()=>{},this.onmessage=()=>{},this.onopen=()=>{},this.readyState=jL.connecting,this.send=()=>{},this.url=null,this.url=t,this.close=r.close}}class uAe extends Error{constructor(t){super(t),this.__isStorageError=!0,this.name="StorageError"}}function fp(s){return typeof s=="object"&&s!==null&&"__isStorageError"in s}class sDt extends uAe{constructor(t,n){super(t),this.name="StorageApiError",this.status=n}toJSON(){return{name:this.name,message:this.message,status:this.status}}}class XSe extends uAe{constructor(t,n){super(t),this.name="StorageUnknownError",this.originalError=n}}var nDt=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const Iat=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>xi(async()=>{const{default:r}=await Promise.resolve().then(()=>MD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},rDt=()=>nDt(void 0,void 0,void 0,function*(){return typeof Response>"u"?(yield xi(()=>Promise.resolve().then(()=>MD),void 0)).Response:Response}),JSe=s=>{if(Array.isArray(s))return s.map(n=>JSe(n));if(typeof s=="function"||s!==Object(s))return s;const t={};return Object.entries(s).forEach(([n,r])=>{const a=n.replace(/([-_][a-z])/gi,i=>i.toUpperCase().replace(/[-_]/g,""));t[a]=JSe(r)}),t};var FM=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const Twe=s=>s.msg||s.message||s.error_description||s.error||JSON.stringify(s),aDt=(s,t,n)=>FM(void 0,void 0,void 0,function*(){const r=yield rDt();s instanceof r&&!(n!=null&&n.noResolveJson)?s.json().then(a=>{t(new sDt(Twe(a),s.status||500))}).catch(a=>{t(new XSe(Twe(a),a))}):t(new XSe(Twe(s),s))}),iDt=(s,t,n,r)=>{const a={method:s,headers:(t==null?void 0:t.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json"},t==null?void 0:t.headers),r&&(a.body=JSON.stringify(r)),Object.assign(Object.assign({},a),n))};function R$(s,t,n,r,a,i){return FM(this,void 0,void 0,function*(){return new Promise((l,o)=>{s(n,iDt(t,r,a,i)).then(c=>{if(!c.ok)throw c;return r!=null&&r.noResolveJson?c:c.json()}).then(c=>l(c)).catch(c=>aDt(c,o,r))})})}function Upe(s,t,n,r){return FM(this,void 0,void 0,function*(){return R$(s,"GET",t,n,r)})}function qk(s,t,n,r,a){return FM(this,void 0,void 0,function*(){return R$(s,"POST",t,r,a,n)})}function oDt(s,t,n,r,a){return FM(this,void 0,void 0,function*(){return R$(s,"PUT",t,r,a,n)})}function lDt(s,t,n,r){return FM(this,void 0,void 0,function*(){return R$(s,"HEAD",t,Object.assign(Object.assign({},n),{noResolveJson:!0}),r)})}function Pat(s,t,n,r,a){return FM(this,void 0,void 0,function*(){return R$(s,"DELETE",t,r,a,n)})}var _g=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const cDt={limit:100,offset:0,sortBy:{column:"name",order:"asc"}},dze={cacheControl:"3600",contentType:"text/plain;charset=UTF-8",upsert:!1};class dDt{constructor(t,n={},r,a){this.url=t,this.headers=n,this.bucketId=r,this.fetch=Iat(a)}uploadOrUpdate(t,n,r,a){return _g(this,void 0,void 0,function*(){try{let i;const l=Object.assign(Object.assign({},dze),a);let o=Object.assign(Object.assign({},this.headers),t==="POST"&&{"x-upsert":String(l.upsert)});const c=l.metadata;typeof Blob<"u"&&r instanceof Blob?(i=new FormData,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c)),i.append("",r)):typeof FormData<"u"&&r instanceof FormData?(i=r,i.append("cacheControl",l.cacheControl),c&&i.append("metadata",this.encodeMetadata(c))):(i=r,o["cache-control"]=`max-age=${l.cacheControl}`,o["content-type"]=l.contentType,c&&(o["x-metadata"]=this.toBase64(this.encodeMetadata(c)))),a!=null&&a.headers&&(o=Object.assign(Object.assign({},o),a.headers));const d=this._removeEmptyFolders(n),u=this._getFinalPath(d),h=yield this.fetch(`${this.url}/object/${u}`,Object.assign({method:t,body:i,headers:o},l!=null&&l.duplex?{duplex:l.duplex}:{})),p=yield h.json();return h.ok?{data:{path:d,id:p.Id,fullPath:p.Key},error:null}:{data:null,error:p}}catch(i){if(fp(i))return{data:null,error:i};throw i}})}upload(t,n,r){return _g(this,void 0,void 0,function*(){return this.uploadOrUpdate("POST",t,n,r)})}uploadToSignedUrl(t,n,r,a){return _g(this,void 0,void 0,function*(){const i=this._removeEmptyFolders(t),l=this._getFinalPath(i),o=new URL(this.url+`/object/upload/sign/${l}`);o.searchParams.set("token",n);try{let c;const d=Object.assign({upsert:dze.upsert},a),u=Object.assign(Object.assign({},this.headers),{"x-upsert":String(d.upsert)});typeof Blob<"u"&&r instanceof Blob?(c=new FormData,c.append("cacheControl",d.cacheControl),c.append("",r)):typeof FormData<"u"&&r instanceof FormData?(c=r,c.append("cacheControl",d.cacheControl)):(c=r,u["cache-control"]=`max-age=${d.cacheControl}`,u["content-type"]=d.contentType);const h=yield this.fetch(o.toString(),{method:"PUT",body:c,headers:u}),p=yield h.json();return h.ok?{data:{path:i,fullPath:p.Key},error:null}:{data:null,error:p}}catch(c){if(fp(c))return{data:null,error:c};throw c}})}createSignedUploadUrl(t,n){return _g(this,void 0,void 0,function*(){try{let r=this._getFinalPath(t);const a=Object.assign({},this.headers);n!=null&&n.upsert&&(a["x-upsert"]="true");const i=yield qk(this.fetch,`${this.url}/object/upload/sign/${r}`,{},{headers:a}),l=new URL(this.url+i.url),o=l.searchParams.get("token");if(!o)throw new uAe("No token returned by API");return{data:{signedUrl:l.toString(),path:t,token:o},error:null}}catch(r){if(fp(r))return{data:null,error:r};throw r}})}update(t,n,r){return _g(this,void 0,void 0,function*(){return this.uploadOrUpdate("PUT",t,n,r)})}move(t,n,r){return _g(this,void 0,void 0,function*(){try{return{data:yield qk(this.fetch,`${this.url}/object/move`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers}),error:null}}catch(a){if(fp(a))return{data:null,error:a};throw a}})}copy(t,n,r){return _g(this,void 0,void 0,function*(){try{return{data:{path:(yield qk(this.fetch,`${this.url}/object/copy`,{bucketId:this.bucketId,sourceKey:t,destinationKey:n,destinationBucket:r==null?void 0:r.destinationBucket},{headers:this.headers})).Key},error:null}}catch(a){if(fp(a))return{data:null,error:a};throw a}})}createSignedUrl(t,n,r){return _g(this,void 0,void 0,function*(){try{let a=this._getFinalPath(t),i=yield qk(this.fetch,`${this.url}/object/sign/${a}`,Object.assign({expiresIn:n},r!=null&&r.transform?{transform:r.transform}:{}),{headers:this.headers});const l=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return i={signedUrl:encodeURI(`${this.url}${i.signedURL}${l}`)},{data:i,error:null}}catch(a){if(fp(a))return{data:null,error:a};throw a}})}createSignedUrls(t,n,r){return _g(this,void 0,void 0,function*(){try{const a=yield qk(this.fetch,`${this.url}/object/sign/${this.bucketId}`,{expiresIn:n,paths:t},{headers:this.headers}),i=r!=null&&r.download?`&download=${r.download===!0?"":r.download}`:"";return{data:a.map(l=>Object.assign(Object.assign({},l),{signedUrl:l.signedURL?encodeURI(`${this.url}${l.signedURL}${i}`):null})),error:null}}catch(a){if(fp(a))return{data:null,error:a};throw a}})}download(t,n){return _g(this,void 0,void 0,function*(){const a=typeof(n==null?void 0:n.transform)<"u"?"render/image/authenticated":"object",i=this.transformOptsToQueryString((n==null?void 0:n.transform)||{}),l=i?`?${i}`:"";try{const o=this._getFinalPath(t);return{data:yield(yield Upe(this.fetch,`${this.url}/${a}/${o}${l}`,{headers:this.headers,noResolveJson:!0})).blob(),error:null}}catch(o){if(fp(o))return{data:null,error:o};throw o}})}info(t){return _g(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{const r=yield Upe(this.fetch,`${this.url}/object/info/${n}`,{headers:this.headers});return{data:JSe(r),error:null}}catch(r){if(fp(r))return{data:null,error:r};throw r}})}exists(t){return _g(this,void 0,void 0,function*(){const n=this._getFinalPath(t);try{return yield lDt(this.fetch,`${this.url}/object/${n}`,{headers:this.headers}),{data:!0,error:null}}catch(r){if(fp(r)&&r instanceof XSe){const a=r.originalError;if([400,404].includes(a==null?void 0:a.status))return{data:!1,error:r}}throw r}})}getPublicUrl(t,n){const r=this._getFinalPath(t),a=[],i=n!=null&&n.download?`download=${n.download===!0?"":n.download}`:"";i!==""&&a.push(i);const o=typeof(n==null?void 0:n.transform)<"u"?"render/image":"object",c=this.transformOptsToQueryString((n==null?void 0:n.transform)||{});c!==""&&a.push(c);let d=a.join("&");return d!==""&&(d=`?${d}`),{data:{publicUrl:encodeURI(`${this.url}/${o}/public/${r}${d}`)}}}remove(t){return _g(this,void 0,void 0,function*(){try{return{data:yield Pat(this.fetch,`${this.url}/object/${this.bucketId}`,{prefixes:t},{headers:this.headers}),error:null}}catch(n){if(fp(n))return{data:null,error:n};throw n}})}list(t,n,r){return _g(this,void 0,void 0,function*(){try{const a=Object.assign(Object.assign(Object.assign({},cDt),n),{prefix:t||""});return{data:yield qk(this.fetch,`${this.url}/object/list/${this.bucketId}`,a,{headers:this.headers},r),error:null}}catch(a){if(fp(a))return{data:null,error:a};throw a}})}encodeMetadata(t){return JSON.stringify(t)}toBase64(t){return typeof Buffer<"u"?Buffer.from(t).toString("base64"):btoa(t)}_getFinalPath(t){return`${this.bucketId}/${t}`}_removeEmptyFolders(t){return t.replace(/^\/|\/$/g,"").replace(/\/+/g,"/")}transformOptsToQueryString(t){const n=[];return t.width&&n.push(`width=${t.width}`),t.height&&n.push(`height=${t.height}`),t.resize&&n.push(`resize=${t.resize}`),t.format&&n.push(`format=${t.format}`),t.quality&&n.push(`quality=${t.quality}`),n.join("&")}}const uDt="2.7.1",hDt={"X-Client-Info":`storage-js/${uDt}`};var oI=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class mDt{constructor(t,n={},r){this.url=t,this.headers=Object.assign(Object.assign({},hDt),n),this.fetch=Iat(r)}listBuckets(){return oI(this,void 0,void 0,function*(){try{return{data:yield Upe(this.fetch,`${this.url}/bucket`,{headers:this.headers}),error:null}}catch(t){if(fp(t))return{data:null,error:t};throw t}})}getBucket(t){return oI(this,void 0,void 0,function*(){try{return{data:yield Upe(this.fetch,`${this.url}/bucket/${t}`,{headers:this.headers}),error:null}}catch(n){if(fp(n))return{data:null,error:n};throw n}})}createBucket(t,n={public:!1}){return oI(this,void 0,void 0,function*(){try{return{data:yield qk(this.fetch,`${this.url}/bucket`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(fp(r))return{data:null,error:r};throw r}})}updateBucket(t,n){return oI(this,void 0,void 0,function*(){try{return{data:yield oDt(this.fetch,`${this.url}/bucket/${t}`,{id:t,name:t,public:n.public,file_size_limit:n.fileSizeLimit,allowed_mime_types:n.allowedMimeTypes},{headers:this.headers}),error:null}}catch(r){if(fp(r))return{data:null,error:r};throw r}})}emptyBucket(t){return oI(this,void 0,void 0,function*(){try{return{data:yield qk(this.fetch,`${this.url}/bucket/${t}/empty`,{},{headers:this.headers}),error:null}}catch(n){if(fp(n))return{data:null,error:n};throw n}})}deleteBucket(t){return oI(this,void 0,void 0,function*(){try{return{data:yield Pat(this.fetch,`${this.url}/bucket/${t}`,{},{headers:this.headers}),error:null}}catch(n){if(fp(n))return{data:null,error:n};throw n}})}}class pDt extends mDt{constructor(t,n={},r){super(t,n,r)}from(t){return new dDt(this.url,this.headers,t,this.fetch)}}const fDt="2.49.10";let XF="";typeof Deno<"u"?XF="deno":typeof document<"u"?XF="web":typeof navigator<"u"&&navigator.product==="ReactNative"?XF="react-native":XF="node";const xDt={"X-Client-Info":`supabase-js-${XF}/${fDt}`},gDt={headers:xDt},yDt={schema:"public"},vDt={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:"implicit"},bDt={};var _Dt=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};const wDt=s=>{let t;return s?t=s:typeof fetch>"u"?t=gat:t=fetch,(...n)=>t(...n)},jDt=()=>typeof Headers>"u"?yat:Headers,NDt=(s,t,n)=>{const r=wDt(n),a=jDt();return(i,l)=>_Dt(void 0,void 0,void 0,function*(){var o;const c=(o=yield t())!==null&&o!==void 0?o:s;let d=new a(l==null?void 0:l.headers);return d.has("apikey")||d.set("apikey",s),d.has("Authorization")||d.set("Authorization",`Bearer ${c}`),r(i,Object.assign(Object.assign({},l),{headers:d}))})};var kDt=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};function SDt(s){return s.endsWith("/")?s:s+"/"}function CDt(s,t){var n,r;const{db:a,auth:i,realtime:l,global:o}=s,{db:c,auth:d,realtime:u,global:h}=t,p={db:Object.assign(Object.assign({},c),a),auth:Object.assign(Object.assign({},d),i),realtime:Object.assign(Object.assign({},u),l),global:Object.assign(Object.assign(Object.assign({},h),o),{headers:Object.assign(Object.assign({},(n=h==null?void 0:h.headers)!==null&&n!==void 0?n:{}),(r=o==null?void 0:o.headers)!==null&&r!==void 0?r:{})}),accessToken:()=>kDt(this,void 0,void 0,function*(){return""})};return s.accessToken?p.accessToken=s.accessToken:delete p.accessToken,p}const Lat="2.69.1",XI=30*1e3,e4e=3,Ewe=e4e*XI,TDt="http://localhost:9999",EDt="supabase.auth.token",ADt={"X-Client-Info":`gotrue-js/${Lat}`},t4e="X-Supabase-Api-Version",Dat={"2024-01-01":{timestamp:Date.parse("2024-01-01T00:00:00.0Z"),name:"2024-01-01"}},MDt=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,IDt=6e5;class hAe extends Error{constructor(t,n,r){super(t),this.__isAuthError=!0,this.name="AuthError",this.status=n,this.code=r}}function $o(s){return typeof s=="object"&&s!==null&&"__isAuthError"in s}class PDt extends hAe{constructor(t,n,r){super(t,n,r),this.name="AuthApiError",this.status=n,this.code=r}}function LDt(s){return $o(s)&&s.name==="AuthApiError"}class Rat extends hAe{constructor(t,n){super(t),this.name="AuthUnknownError",this.originalError=n}}class F4 extends hAe{constructor(t,n,r,a){super(t,r,a),this.name=n,this.status=r}}class Ik extends F4{constructor(){super("Auth session missing!","AuthSessionMissingError",400,void 0)}}function DDt(s){return $o(s)&&s.name==="AuthSessionMissingError"}class Awe extends F4{constructor(){super("Auth session or user missing","AuthInvalidTokenResponseError",500,void 0)}}class DV extends F4{constructor(t){super(t,"AuthInvalidCredentialsError",400,void 0)}}class RV extends F4{constructor(t,n=null){super(t,"AuthImplicitGrantRedirectError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}function RDt(s){return $o(s)&&s.name==="AuthImplicitGrantRedirectError"}class uze extends F4{constructor(t,n=null){super(t,"AuthPKCEGrantCodeExchangeError",500,void 0),this.details=null,this.details=n}toJSON(){return{name:this.name,message:this.message,status:this.status,details:this.details}}}class s4e extends F4{constructor(t,n){super(t,"AuthRetryableFetchError",n,void 0)}}function Mwe(s){return $o(s)&&s.name==="AuthRetryableFetchError"}class hze extends F4{constructor(t,n,r){super(t,"AuthWeakPasswordError",n,"weak_password"),this.reasons=r}}class L9 extends F4{constructor(t){super(t,"AuthInvalidJwtError",400,"invalid_jwt")}}const mze="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".split(""),pze=` \r=`.split(""),ODt=(()=>{const s=new Array(128);for(let t=0;t-1)for(t.queue=t.queue<<6|r,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else{if(r===-2)return;throw new Error(`Invalid Base64-URL character "${String.fromCharCode(s)}"`)}}function fze(s){const t=[],n=l=>{t.push(String.fromCodePoint(l))},r={utf8seq:0,codepoint:0},a={queue:0,queuedBits:0},i=l=>{BDt(l,r,n)};for(let l=0;l>6),t(128|s&63);return}else if(s<=65535){t(224|s>>12),t(128|s>>6&63),t(128|s&63);return}else if(s<=1114111){t(240|s>>18),t(128|s>>12&63),t(128|s>>6&63),t(128|s&63);return}throw new Error(`Unrecognized Unicode codepoint: ${s.toString(16)}`)}function zDt(s,t){for(let n=0;n55295&&r<=56319){const a=(r-55296)*1024&65535;r=(s.charCodeAt(n+1)-56320&65535|a)+65536,n+=1}FDt(r,t)}}function BDt(s,t,n){if(t.utf8seq===0){if(s<=127){n(s);return}for(let r=1;r<6;r+=1)if(!(s>>7-r&1)){t.utf8seq=r;break}if(t.utf8seq===2)t.codepoint=s&31;else if(t.utf8seq===3)t.codepoint=s&15;else if(t.utf8seq===4)t.codepoint=s&7;else throw new Error("Invalid UTF-8 sequence");t.utf8seq-=1}else if(t.utf8seq>0){if(s<=127)throw new Error("Invalid UTF-8 sequence");t.codepoint=t.codepoint<<6|s&63,t.utf8seq-=1,t.utf8seq===0&&n(t.codepoint)}}function $Dt(s){const t=[],n={queue:0,queuedBits:0},r=a=>{t.push(a)};for(let a=0;at.push(n)),new Uint8Array(t)}function qDt(s){return Math.round(Date.now()/1e3)+s}function VDt(){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 M_=()=>typeof window<"u"&&typeof document<"u",e3={tested:!1,writable:!1},D9=()=>{if(!M_())return!1;try{if(typeof globalThis.localStorage!="object")return!1}catch{return!1}if(e3.tested)return e3.writable;const s=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(s,s),globalThis.localStorage.removeItem(s),e3.tested=!0,e3.writable=!0}catch{e3.tested=!0,e3.writable=!1}return e3.writable};function HDt(s){const t={},n=new URL(s);if(n.hash&&n.hash[0]==="#")try{new URLSearchParams(n.hash.substring(1)).forEach((a,i)=>{t[i]=a})}catch{}return n.searchParams.forEach((r,a)=>{t[a]=r}),t}const Fat=s=>{let t;return s?t=s:typeof fetch>"u"?t=(...n)=>xi(async()=>{const{default:r}=await Promise.resolve().then(()=>MD);return{default:r}},void 0).then(({default:r})=>r(...n)):t=fetch,(...n)=>t(...n)},GDt=s=>typeof s=="object"&&s!==null&&"status"in s&&"ok"in s&&"json"in s&&typeof s.json=="function",zat=async(s,t,n)=>{await s.setItem(t,JSON.stringify(n))},OV=async(s,t)=>{const n=await s.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return n}},FV=async(s,t)=>{await s.removeItem(t)};class E0e{constructor(){this.promise=new E0e.promiseConstructor((t,n)=>{this.resolve=t,this.reject=n})}}E0e.promiseConstructor=Promise;function Iwe(s){const t=s.split(".");if(t.length!==3)throw new L9("Invalid JWT structure");for(let r=0;r{setTimeout(()=>t(null),s)})}function KDt(s,t){return new Promise((r,a)=>{(async()=>{for(let i=0;i<1/0;i++)try{const l=await s(i);if(!t(i,null,l)){r(l);return}}catch(l){if(!t(i,l)){a(l);return}}})()})}function YDt(s){return("0"+s.toString(16)).substr(-2)}function ZDt(){const t=new Uint32Array(56);if(typeof crypto>"u"){const n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~",r=n.length;let a="";for(let i=0;i<56;i++)a+=n.charAt(Math.floor(Math.random()*r));return a}return crypto.getRandomValues(t),Array.from(t,YDt).join("")}async function QDt(s){const n=new TextEncoder().encode(s),r=await crypto.subtle.digest("SHA-256",n),a=new Uint8Array(r);return Array.from(a).map(i=>String.fromCharCode(i)).join("")}async function XDt(s){if(!(typeof crypto<"u"&&typeof crypto.subtle<"u"&&typeof TextEncoder<"u"))return console.warn("WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256."),s;const n=await QDt(s);return btoa(n).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}async function lI(s,t,n=!1){const r=ZDt();let a=r;n&&(a+="/PASSWORD_RECOVERY"),await zat(s,`${t}-code-verifier`,a);const i=await XDt(r);return[i,r===i?"plain":"s256"]}const JDt=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function eRt(s){const t=s.headers.get(t4e);if(!t||!t.match(JDt))return null;try{return new Date(`${t}T00:00:00.0Z`)}catch{return null}}function tRt(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 sRt(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 nRt=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);as.msg||s.message||s.error_description||s.error||JSON.stringify(s),rRt=[502,503,504];async function xze(s){var t;if(!GDt(s))throw new s4e(jE(s),0);if(rRt.includes(s.status))throw new s4e(jE(s),s.status);let n;try{n=await s.json()}catch(i){throw new Rat(jE(i),i)}let r;const a=eRt(s);if(a&&a.getTime()>=Dat["2024-01-01"].timestamp&&typeof n=="object"&&n&&typeof n.code=="string"?r=n.code:typeof n=="object"&&n&&typeof n.error_code=="string"&&(r=n.error_code),r){if(r==="weak_password")throw new hze(jE(n),s.status,((t=n.weak_password)===null||t===void 0?void 0:t.reasons)||[]);if(r==="session_not_found")throw new Ik}else if(typeof n=="object"&&n&&typeof n.weak_password=="object"&&n.weak_password&&Array.isArray(n.weak_password.reasons)&&n.weak_password.reasons.length&&n.weak_password.reasons.reduce((i,l)=>i&&typeof l=="string",!0))throw new hze(jE(n),s.status,n.weak_password.reasons);throw new PDt(jE(n),s.status||500,r)}const aRt=(s,t,n,r)=>{const a={method:s,headers:(t==null?void 0:t.headers)||{}};return s==="GET"?a:(a.headers=Object.assign({"Content-Type":"application/json;charset=UTF-8"},t==null?void 0:t.headers),a.body=JSON.stringify(r),Object.assign(Object.assign({},a),n))};async function bl(s,t,n,r){var a;const i=Object.assign({},r==null?void 0:r.headers);i[t4e]||(i[t4e]=Dat["2024-01-01"].name),r!=null&&r.jwt&&(i.Authorization=`Bearer ${r.jwt}`);const l=(a=r==null?void 0:r.query)!==null&&a!==void 0?a:{};r!=null&&r.redirectTo&&(l.redirect_to=r.redirectTo);const o=Object.keys(l).length?"?"+new URLSearchParams(l).toString():"",c=await iRt(s,t,n+o,{headers:i,noResolveJson:r==null?void 0:r.noResolveJson},{},r==null?void 0:r.body);return r!=null&&r.xform?r==null?void 0:r.xform(c):{data:Object.assign({},c),error:null}}async function iRt(s,t,n,r,a,i){const l=aRt(t,r,a,i);let o;try{o=await s(n,Object.assign({},l))}catch(c){throw console.error(c),new s4e(jE(c),0)}if(o.ok||await xze(o),r!=null&&r.noResolveJson)return o;try{return await o.json()}catch(c){await xze(c)}}function Pk(s){var t;let n=null;dRt(s)&&(n=Object.assign({},s),s.expires_at||(n.expires_at=qDt(s.expires_in)));const r=(t=s.user)!==null&&t!==void 0?t:s;return{data:{session:n,user:r},error:null}}function gze(s){const t=Pk(s);return!t.error&&s.weak_password&&typeof s.weak_password=="object"&&Array.isArray(s.weak_password.reasons)&&s.weak_password.reasons.length&&s.weak_password.message&&typeof s.weak_password.message=="string"&&s.weak_password.reasons.reduce((n,r)=>n&&typeof r=="string",!0)&&(t.data.weak_password=s.weak_password),t}function rS(s){var t;return{data:{user:(t=s.user)!==null&&t!==void 0?t:s},error:null}}function oRt(s){return{data:s,error:null}}function lRt(s){const{action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i}=s,l=nRt(s,["action_link","email_otp","hashed_token","redirect_to","verification_type"]),o={action_link:t,email_otp:n,hashed_token:r,redirect_to:a,verification_type:i},c=Object.assign({},l);return{data:{properties:o,user:c},error:null}}function cRt(s){return s}function dRt(s){return s.access_token&&s.refresh_token&&s.expires_in}var uRt=function(s,t){var n={};for(var r in s)Object.prototype.hasOwnProperty.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&typeof Object.getOwnPropertySymbols=="function")for(var a=0,r=Object.getOwnPropertySymbols(s);a0&&(f.forEach(y=>{const _=parseInt(y.split(";")[0].split("=")[1].substring(0,1)),v=JSON.parse(y.split(";")[1].split("=")[1]);d[`${v}Page`]=_}),d.total=parseInt(p)),{data:Object.assign(Object.assign({},h),d),error:null}}catch(d){if($o(d))return{data:{users:[]},error:d};throw d}}async getUserById(t){try{return await bl(this.fetch,"GET",`${this.url}/admin/users/${t}`,{headers:this.headers,xform:rS})}catch(n){if($o(n))return{data:{user:null},error:n};throw n}}async updateUserById(t,n){try{return await bl(this.fetch,"PUT",`${this.url}/admin/users/${t}`,{body:n,headers:this.headers,xform:rS})}catch(r){if($o(r))return{data:{user:null},error:r};throw r}}async deleteUser(t,n=!1){try{return await bl(this.fetch,"DELETE",`${this.url}/admin/users/${t}`,{headers:this.headers,body:{should_soft_delete:n},xform:rS})}catch(r){if($o(r))return{data:{user:null},error:r};throw r}}async _listFactors(t){try{const{data:n,error:r}=await bl(this.fetch,"GET",`${this.url}/admin/users/${t.userId}/factors`,{headers:this.headers,xform:a=>({data:{factors:a},error:null})});return{data:n,error:r}}catch(n){if($o(n))return{data:null,error:n};throw n}}async _deleteFactor(t){try{return{data:await bl(this.fetch,"DELETE",`${this.url}/admin/users/${t.userId}/factors/${t.id}`,{headers:this.headers}),error:null}}catch(n){if($o(n))return{data:null,error:n};throw n}}}const mRt={getItem:s=>D9()?globalThis.localStorage.getItem(s):null,setItem:(s,t)=>{D9()&&globalThis.localStorage.setItem(s,t)},removeItem:s=>{D9()&&globalThis.localStorage.removeItem(s)}};function yze(s={}){return{getItem:t=>s[t]||null,setItem:(t,n)=>{s[t]=n},removeItem:t=>{delete s[t]}}}function pRt(){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 cI={debug:!!(globalThis&&D9()&&globalThis.localStorage&&globalThis.localStorage.getItem("supabase.gotrue-js.locks.debug")==="true")};class Bat extends Error{constructor(t){super(t),this.isAcquireTimeout=!0}}class fRt extends Bat{}async function xRt(s,t,n){cI.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquire lock",s,t);const r=new globalThis.AbortController;return t>0&&setTimeout(()=>{r.abort(),cI.debug&&console.log("@supabase/gotrue-js: navigatorLock acquire timed out",s)},t),await Promise.resolve().then(()=>globalThis.navigator.locks.request(s,t===0?{mode:"exclusive",ifAvailable:!0}:{mode:"exclusive",signal:r.signal},async a=>{if(a){cI.debug&&console.log("@supabase/gotrue-js: navigatorLock: acquired",s,a.name);try{return await n()}finally{cI.debug&&console.log("@supabase/gotrue-js: navigatorLock: released",s,a.name)}}else{if(t===0)throw cI.debug&&console.log("@supabase/gotrue-js: navigatorLock: not immediately available",s),new fRt(`Acquiring an exclusive Navigator LockManager lock "${s}" immediately failed`);if(cI.debug)try{const i=await globalThis.navigator.locks.query();console.log("@supabase/gotrue-js: Navigator LockManager state",JSON.stringify(i,null," "))}catch(i){console.warn("@supabase/gotrue-js: Error when querying Navigator LockManager state",i)}return console.warn("@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request"),await n()}}))}pRt();const gRt={url:TDt,storageKey:EDt,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:ADt,flowType:"implicit",debug:!1,hasCustomAuthorizationHeader:!1};async function vze(s,t,n){return await n()}class Zz{constructor(t){var n,r;this.memoryStorage=null,this.stateChangeEmitters=new Map,this.autoRefreshTicker=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.initializePromise=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log,this.instanceID=Zz.nextInstanceID,Zz.nextInstanceID+=1,this.instanceID>0&&M_()&&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({},gRt),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 hRt({url:a.url,headers:a.headers,fetch:a.fetch}),this.url=a.url,this.headers=a.headers,this.fetch=Fat(a.fetch),this.lock=a.lock||vze,this.detectSessionInUrl=a.detectSessionInUrl,this.flowType=a.flowType,this.hasCustomAuthorizationHeader=a.hasCustomAuthorizationHeader,a.lock?this.lock=a.lock:M_()&&(!((n=globalThis==null?void 0:globalThis.navigator)===null||n===void 0)&&n.locks)?this.lock=xRt:this.lock=vze,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:D9()?this.storage=mRt:(this.memoryStorage={},this.storage=yze(this.memoryStorage)):(this.memoryStorage={},this.storage=yze(this.memoryStorage)),M_()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(i){console.error("Failed to create a new BroadcastChannel, multi-tab state changes will not be available",i)}(r=this.broadcastChannel)===null||r===void 0||r.addEventListener("message",async i=>{this._debug("received broadcast notification from other tab or client",i),await this._notifyAllSubscribers(i.data.event,i.data.session,!1)})}this.initialize()}_debug(...t){return this.logDebugMessages&&this.logger(`GoTrueClient@${this.instanceID} (${Lat}) ${new Date().toISOString()}`,...t),this}async initialize(){return this.initializePromise?await this.initializePromise:(this.initializePromise=(async()=>await this._acquireLock(-1,async()=>await this._initialize()))(),await this.initializePromise)}async _initialize(){var t;try{const n=HDt(window.location.href);let r="none";if(this._isImplicitGrantCallback(n)?r="implicit":await this._isPKCECallback(n)&&(r="pkce"),M_()&&this.detectSessionInUrl&&r!=="none"){const{data:a,error:i}=await this._getSessionFromURL(n,r);if(i){if(this._debug("#_initialize()","error detecting session from URL",i),RDt(i)){const c=(t=i.details)===null||t===void 0?void 0:t.code;if(c==="identity_already_exists"||c==="identity_not_found"||c==="single_identity_not_deletable")return{error:i}}return await this._removeSession(),{error:i}}const{session:l,redirectType:o}=a;return this._debug("#_initialize()","detected session in URL",l,"redirect type",o),await this._saveSession(l),setTimeout(async()=>{o==="recovery"?await this._notifyAllSubscribers("PASSWORD_RECOVERY",l):await this._notifyAllSubscribers("SIGNED_IN",l)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(n){return $o(n)?{error:n}:{error:new Rat("Unexpected error during initialization",n)}}finally{await this._handleVisibilityChange(),this._debug("#_initialize()","end")}}async signInAnonymously(t){var n,r,a;try{const i=await bl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{data:(r=(n=t==null?void 0:t.options)===null||n===void 0?void 0:n.data)!==null&&r!==void 0?r:{},gotrue_meta_security:{captcha_token:(a=t==null?void 0:t.options)===null||a===void 0?void 0:a.captchaToken}},xform:Pk}),{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($o(i))return{data:{user:null,session:null},error:i};throw i}}async signUp(t){var n,r,a;try{let i;if("email"in t){const{email:u,password:h,options:p}=t;let f=null,y=null;this.flowType==="pkce"&&([f,y]=await lI(this.storage,this.storageKey)),i=await bl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,redirectTo:p==null?void 0:p.emailRedirectTo,body:{email:u,password:h,data:(n=p==null?void 0:p.data)!==null&&n!==void 0?n:{},gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken},code_challenge:f,code_challenge_method:y},xform:Pk})}else if("phone"in t){const{phone:u,password:h,options:p}=t;i=await bl(this.fetch,"POST",`${this.url}/signup`,{headers:this.headers,body:{phone:u,password:h,data:(r=p==null?void 0:p.data)!==null&&r!==void 0?r:{},channel:(a=p==null?void 0:p.channel)!==null&&a!==void 0?a:"sms",gotrue_meta_security:{captcha_token:p==null?void 0:p.captchaToken}},xform:Pk})}else throw new DV("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($o(i))return{data:{user:null,session:null},error:i};throw i}}async signInWithPassword(t){try{let n;if("email"in t){const{email:i,password:l,options:o}=t;n=await bl(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:gze})}else if("phone"in t){const{phone:i,password:l,options:o}=t;n=await bl(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:gze})}else throw new DV("You must provide either an email or phone number and a password");const{data:r,error:a}=n;return a?{data:{user:null,session:null},error:a}:!r||!r.session||!r.user?{data:{user:null,session:null},error:new Awe}:(r.session&&(await this._saveSession(r.session),await this._notifyAllSubscribers("SIGNED_IN",r.session)),{data:Object.assign({user:r.user,session:r.session},r.weak_password?{weakPassword:r.weak_password}:null),error:a})}catch(n){if($o(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOAuth(t){var n,r,a,i;return await this._handleProviderSignIn(t.provider,{redirectTo:(n=t.options)===null||n===void 0?void 0:n.redirectTo,scopes:(r=t.options)===null||r===void 0?void 0:r.scopes,queryParams:(a=t.options)===null||a===void 0?void 0:a.queryParams,skipBrowserRedirect:(i=t.options)===null||i===void 0?void 0:i.skipBrowserRedirect})}async exchangeCodeForSession(t){return await this.initializePromise,this._acquireLock(-1,async()=>this._exchangeCodeForSession(t))}async _exchangeCodeForSession(t){const n=await OV(this.storage,`${this.storageKey}-code-verifier`),[r,a]=(n??"").split("/");try{const{data:i,error:l}=await bl(this.fetch,"POST",`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:t,code_verifier:r},xform:Pk});if(await FV(this.storage,`${this.storageKey}-code-verifier`),l)throw l;return!i||!i.session||!i.user?{data:{user:null,session:null,redirectType:null},error:new Awe}:(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($o(i))return{data:{user:null,session:null,redirectType:null},error:i};throw i}}async signInWithIdToken(t){try{const{options:n,provider:r,token:a,access_token:i,nonce:l}=t,o=await bl(this.fetch,"POST",`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:r,id_token:a,access_token:i,nonce:l,gotrue_meta_security:{captcha_token:n==null?void 0:n.captchaToken}},xform:Pk}),{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 Awe}:(c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers("SIGNED_IN",c.session)),{data:c,error:d})}catch(n){if($o(n))return{data:{user:null,session:null},error:n};throw n}}async signInWithOtp(t){var n,r,a,i,l;try{if("email"in t){const{email:o,options:c}=t;let d=null,u=null;this.flowType==="pkce"&&([d,u]=await lI(this.storage,this.storageKey));const{error:h}=await bl(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{email:o,data:(n=c==null?void 0:c.data)!==null&&n!==void 0?n:{},create_user:(r=c==null?void 0:c.shouldCreateUser)!==null&&r!==void 0?r:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},code_challenge:d,code_challenge_method:u},redirectTo:c==null?void 0:c.emailRedirectTo});return{data:{user:null,session:null},error:h}}if("phone"in t){const{phone:o,options:c}=t,{data:d,error:u}=await bl(this.fetch,"POST",`${this.url}/otp`,{headers:this.headers,body:{phone:o,data:(a=c==null?void 0:c.data)!==null&&a!==void 0?a:{},create_user:(i=c==null?void 0:c.shouldCreateUser)!==null&&i!==void 0?i:!0,gotrue_meta_security:{captcha_token:c==null?void 0:c.captchaToken},channel:(l=c==null?void 0:c.channel)!==null&&l!==void 0?l:"sms"}});return{data:{user:null,session:null,messageId:d==null?void 0:d.message_id},error:u}}throw new DV("You must provide either an email or phone number.")}catch(o){if($o(o))return{data:{user:null,session:null},error:o};throw o}}async verifyOtp(t){var n,r;try{let a,i;"options"in t&&(a=(n=t.options)===null||n===void 0?void 0:n.redirectTo,i=(r=t.options)===null||r===void 0?void 0:r.captchaToken);const{data:l,error:o}=await bl(this.fetch,"POST",`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},t),{gotrue_meta_security:{captcha_token:i}}),redirectTo:a,xform:Pk});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($o(a))return{data:{user:null,session:null},error:a};throw a}}async signInWithSSO(t){var n,r,a;try{let i=null,l=null;return this.flowType==="pkce"&&([i,l]=await lI(this.storage,this.storageKey)),await bl(this.fetch,"POST",`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},"providerId"in t?{provider_id:t.providerId}:null),"domain"in t?{domain:t.domain}:null),{redirect_to:(r=(n=t.options)===null||n===void 0?void 0:n.redirectTo)!==null&&r!==void 0?r:void 0}),!((a=t==null?void 0:t.options)===null||a===void 0)&&a.captchaToken?{gotrue_meta_security:{captcha_token:t.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:i,code_challenge_method:l}),headers:this.headers,xform:oRt})}catch(i){if($o(i))return{data:null,error:i};throw i}}async reauthenticate(){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async t=>{const{data:{session:n},error:r}=t;if(r)throw r;if(!n)throw new Ik;const{error:a}=await bl(this.fetch,"GET",`${this.url}/reauthenticate`,{headers:this.headers,jwt:n.access_token});return{data:{user:null,session:null},error:a}})}catch(t){if($o(t))return{data:{user:null,session:null},error:t};throw t}}async resend(t){try{const n=`${this.url}/resend`;if("email"in t){const{email:r,type:a,options:i}=t,{error:l}=await bl(this.fetch,"POST",n,{headers:this.headers,body:{email:r,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}},redirectTo:i==null?void 0:i.emailRedirectTo});return{data:{user:null,session:null},error:l}}else if("phone"in t){const{phone:r,type:a,options:i}=t,{data:l,error:o}=await bl(this.fetch,"POST",n,{headers:this.headers,body:{phone:r,type:a,gotrue_meta_security:{captcha_token:i==null?void 0:i.captchaToken}}});return{data:{user:null,session:null,messageId:l==null?void 0:l.message_id},error:o}}throw new DV("You must provide either an email or phone number and a type")}catch(n){if($o(n))return{data:{user:null,session:null},error:n};throw n}}async getSession(){return await this.initializePromise,await this._acquireLock(-1,async()=>this._useSession(async n=>n))}async _acquireLock(t,n){this._debug("#_acquireLock","begin",t);try{if(this.lockAcquired){const r=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),a=(async()=>(await r,await n()))();return this.pendingInLock.push((async()=>{try{await a}catch{}})()),a}return await this.lock(`lock:${this.storageKey}`,t,async()=>{this._debug("#_acquireLock","lock acquired for storage key",this.storageKey);try{this.lockAcquired=!0;const r=n();for(this.pendingInLock.push((async()=>{try{await r}catch{}})()),await r;this.pendingInLock.length;){const a=[...this.pendingInLock];await Promise.all(a),this.pendingInLock.splice(0,a.length)}return await r}finally{this._debug("#_acquireLock","lock released for storage key",this.storageKey),this.lockAcquired=!1}})}finally{this._debug("#_acquireLock","end")}}async _useSession(t){this._debug("#_useSession","begin");try{const n=await this.__loadSession();return await t(n)}finally{this._debug("#_useSession","end")}}async __loadSession(){this._debug("#__loadSession()","begin"),this.lockAcquired||this._debug("#__loadSession()","used outside of an acquired lock!",new Error().stack);try{let t=null;const n=await OV(this.storage,this.storageKey);if(this._debug("#getSession()","session from storage",n),n!==null&&(this._isValidSession(n)?t=n:(this._debug("#getSession()","session from storage is not valid"),await this._removeSession())),!t)return{data:{session:null},error:null};const r=t.expires_at?t.expires_at*1e3-Date.now()(!l&&d==="user"&&(console.warn("Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server."),l=!0,this.suppressGetSessionWarning=!0),Reflect.get(c,d,u))})}return{data:{session:t},error:null}}const{session:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{session:null},error:i}:{data:{session:a},error:null}}finally{this._debug("#__loadSession()","end")}}async getUser(t){return t?await this._getUser(t):(await this.initializePromise,await this._acquireLock(-1,async()=>await this._getUser()))}async _getUser(t){try{return t?await bl(this.fetch,"GET",`${this.url}/user`,{headers:this.headers,jwt:t,xform:rS}):await this._useSession(async n=>{var r,a,i;const{data:l,error:o}=n;if(o)throw o;return!(!((r=l.session)===null||r===void 0)&&r.access_token)&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new Ik}:await bl(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:rS})})}catch(n){if($o(n))return DDt(n)&&(await this._removeSession(),await FV(this.storage,`${this.storageKey}-code-verifier`)),{data:{user:null},error:n};throw n}}async updateUser(t,n={}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._updateUser(t,n))}async _updateUser(t,n={}){try{return await this._useSession(async r=>{const{data:a,error:i}=r;if(i)throw i;if(!a.session)throw new Ik;const l=a.session;let o=null,c=null;this.flowType==="pkce"&&t.email!=null&&([o,c]=await lI(this.storage,this.storageKey));const{data:d,error:u}=await bl(this.fetch,"PUT",`${this.url}/user`,{headers:this.headers,redirectTo:n==null?void 0:n.emailRedirectTo,body:Object.assign(Object.assign({},t),{code_challenge:o,code_challenge_method:c}),jwt:l.access_token,xform:rS});if(u)throw u;return l.user=d.user,await this._saveSession(l),await this._notifyAllSubscribers("USER_UPDATED",l),{data:{user:l.user},error:null}})}catch(r){if($o(r))return{data:{user:null},error:r};throw r}}async setSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._setSession(t))}async _setSession(t){try{if(!t.access_token||!t.refresh_token)throw new Ik;const n=Date.now()/1e3;let r=n,a=!0,i=null;const{payload:l}=Iwe(t.access_token);if(l.exp&&(r=l.exp,a=r<=n),a){const{session:o,error:c}=await this._callRefreshToken(t.refresh_token);if(c)return{data:{user:null,session:null},error:c};if(!o)return{data:{user:null,session:null},error:null};i=o}else{const{data:o,error:c}=await this._getUser(t.access_token);if(c)throw c;i={access_token:t.access_token,refresh_token:t.refresh_token,user:o.user,token_type:"bearer",expires_in:r-n,expires_at:r},await this._saveSession(i),await this._notifyAllSubscribers("SIGNED_IN",i)}return{data:{user:i.user,session:i},error:null}}catch(n){if($o(n))return{data:{session:null,user:null},error:n};throw n}}async refreshSession(t){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._refreshSession(t))}async _refreshSession(t){try{return await this._useSession(async n=>{var r;if(!t){const{data:l,error:o}=n;if(o)throw o;t=(r=l.session)!==null&&r!==void 0?r:void 0}if(!(t!=null&&t.refresh_token))throw new Ik;const{session:a,error:i}=await this._callRefreshToken(t.refresh_token);return i?{data:{user:null,session:null},error:i}:a?{data:{user:a.user,session:a},error:null}:{data:{user:null,session:null},error:null}})}catch(n){if($o(n))return{data:{user:null,session:null},error:n};throw n}}async _getSessionFromURL(t,n){try{if(!M_())throw new RV("No browser detected.");if(t.error||t.error_description||t.error_code)throw new RV(t.error_description||"Error in URL with unspecified error_description",{error:t.error||"unspecified_error",code:t.error_code||"unspecified_code"});switch(n){case"implicit":if(this.flowType==="pkce")throw new uze("Not a valid PKCE flow url.");break;case"pkce":if(this.flowType==="implicit")throw new RV("Not a valid implicit grant flow url.");break;default:}if(n==="pkce"){if(this._debug("#_initialize()","begin","is PKCE flow",!0),!t.code)throw new uze("No code detected.");const{data:w,error:S}=await this._exchangeCodeForSession(t.code);if(S)throw S;const A=new URL(window.location.href);return A.searchParams.delete("code"),window.history.replaceState(window.history.state,"",A.toString()),{data:{session:w.session,redirectType:null},error:null}}const{provider_token:r,provider_refresh_token:a,access_token:i,refresh_token:l,expires_in:o,expires_at:c,token_type:d}=t;if(!i||!o||!l||!d)throw new RV("No session defined in URL");const u=Math.round(Date.now()/1e3),h=parseInt(o);let p=u+h;c&&(p=parseInt(c));const f=p-u;f*1e3<=XI&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${f}s, should have been closer to ${h}s`);const y=p-h;u-y>=120?console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale",y,p,u):u-y<0&&console.warn("@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew",y,p,u);const{data:_,error:v}=await this._getUser(i);if(v)throw v;const j={provider_token:r,provider_refresh_token:a,access_token:i,expires_in:h,expires_at:p,refresh_token:l,token_type:d,user:_.user};return window.location.hash="",this._debug("#_getSessionFromURL()","clearing window.location.hash"),{data:{session:j,redirectType:t.type},error:null}}catch(r){if($o(r))return{data:{session:null,redirectType:null},error:r};throw r}}_isImplicitGrantCallback(t){return!!(t.access_token||t.error_description)}async _isPKCECallback(t){const n=await OV(this.storage,`${this.storageKey}-code-verifier`);return!!(t.code&&n)}async signOut(t={scope:"global"}){return await this.initializePromise,await this._acquireLock(-1,async()=>await this._signOut(t))}async _signOut({scope:t}={scope:"global"}){return await this._useSession(async n=>{var r;const{data:a,error:i}=n;if(i)return{error:i};const l=(r=a.session)===null||r===void 0?void 0:r.access_token;if(l){const{error:o}=await this.admin.signOut(l,t);if(o&&!(LDt(o)&&(o.status===404||o.status===401||o.status===403)))return{error:o}}return t!=="others"&&(await this._removeSession(),await FV(this.storage,`${this.storageKey}-code-verifier`)),{error:null}})}onAuthStateChange(t){const n=VDt(),r={id:n,callback:t,unsubscribe:()=>{this._debug("#unsubscribe()","state change callback with id removed",n),this.stateChangeEmitters.delete(n)}};return this._debug("#onAuthStateChange()","registered callback with id",n),this.stateChangeEmitters.set(n,r),(async()=>(await this.initializePromise,await this._acquireLock(-1,async()=>{this._emitInitialSession(n)})))(),{data:{subscription:r}}}async _emitInitialSession(t){return await this._useSession(async n=>{var r,a;try{const{data:{session:i},error:l}=n;if(l)throw l;await((r=this.stateChangeEmitters.get(t))===null||r===void 0?void 0:r.callback("INITIAL_SESSION",i)),this._debug("INITIAL_SESSION","callback id",t,"session",i)}catch(i){await((a=this.stateChangeEmitters.get(t))===null||a===void 0?void 0:a.callback("INITIAL_SESSION",null)),this._debug("INITIAL_SESSION","callback id",t,"error",i),console.error(i)}})}async resetPasswordForEmail(t,n={}){let r=null,a=null;this.flowType==="pkce"&&([r,a]=await lI(this.storage,this.storageKey,!0));try{return await bl(this.fetch,"POST",`${this.url}/recover`,{body:{email:t,code_challenge:r,code_challenge_method:a,gotrue_meta_security:{captcha_token:n.captchaToken}},headers:this.headers,redirectTo:n.redirectTo})}catch(i){if($o(i))return{data:null,error:i};throw i}}async getUserIdentities(){var t;try{const{data:n,error:r}=await this.getUser();if(r)throw r;return{data:{identities:(t=n.user.identities)!==null&&t!==void 0?t:[]},error:null}}catch(n){if($o(n))return{data:null,error:n};throw n}}async linkIdentity(t){var n;try{const{data:r,error:a}=await this._useSession(async i=>{var l,o,c,d,u;const{data:h,error:p}=i;if(p)throw p;const f=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,t.provider,{redirectTo:(l=t.options)===null||l===void 0?void 0:l.redirectTo,scopes:(o=t.options)===null||o===void 0?void 0:o.scopes,queryParams:(c=t.options)===null||c===void 0?void 0:c.queryParams,skipBrowserRedirect:!0});return await bl(this.fetch,"GET",f,{headers:this.headers,jwt:(u=(d=h.session)===null||d===void 0?void 0:d.access_token)!==null&&u!==void 0?u:void 0})});if(a)throw a;return M_()&&!(!((n=t.options)===null||n===void 0)&&n.skipBrowserRedirect)&&window.location.assign(r==null?void 0:r.url),{data:{provider:t.provider,url:r==null?void 0:r.url},error:null}}catch(r){if($o(r))return{data:{provider:t.provider,url:null},error:r};throw r}}async unlinkIdentity(t){try{return await this._useSession(async n=>{var r,a;const{data:i,error:l}=n;if(l)throw l;return await bl(this.fetch,"DELETE",`${this.url}/user/identities/${t.identity_id}`,{headers:this.headers,jwt:(a=(r=i.session)===null||r===void 0?void 0:r.access_token)!==null&&a!==void 0?a:void 0})})}catch(n){if($o(n))return{data:null,error:n};throw n}}async _refreshAccessToken(t){const n=`#_refreshAccessToken(${t.substring(0,5)}...)`;this._debug(n,"begin");try{const r=Date.now();return await KDt(async a=>(a>0&&await WDt(200*Math.pow(2,a-1)),this._debug(n,"refreshing attempt",a),await bl(this.fetch,"POST",`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:t},headers:this.headers,xform:Pk})),(a,i)=>{const l=200*Math.pow(2,a);return i&&Mwe(i)&&Date.now()+l-r{try{await o.callback(t,n)}catch(c){i.push(c)}});if(await Promise.all(l),i.length>0){for(let o=0;othis._autoRefreshTokenTick(),XI);this.autoRefreshTicker=t,t&&typeof t=="object"&&typeof t.unref=="function"?t.unref():typeof Deno<"u"&&typeof Deno.unrefTimer=="function"&&Deno.unrefTimer(t),setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0)}async _stopAutoRefresh(){this._debug("#_stopAutoRefresh()");const t=this.autoRefreshTicker;this.autoRefreshTicker=null,t&&clearInterval(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async _autoRefreshTokenTick(){this._debug("#_autoRefreshTokenTick()","begin");try{await this._acquireLock(0,async()=>{try{const t=Date.now();try{return await this._useSession(async n=>{const{data:{session:r}}=n;if(!r||!r.refresh_token||!r.expires_at){this._debug("#_autoRefreshTokenTick()","no session");return}const a=Math.floor((r.expires_at*1e3-t)/XI);this._debug("#_autoRefreshTokenTick()",`access token expires in ${a} ticks, a tick lasts ${XI}ms, refresh threshold is ${e4e} ticks`),a<=e4e&&await this._callRefreshToken(r.refresh_token)})}catch(n){console.error("Auto refresh tick failed with error. This is likely a transient error.",n)}}finally{this._debug("#_autoRefreshTokenTick()","end")}})}catch(t){if(t.isAcquireTimeout||t instanceof Bat)this._debug("auto refresh token tick lock not available");else throw t}}async _handleVisibilityChange(){if(this._debug("#_handleVisibilityChange()"),!M_()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>await this._onVisibilityChanged(!1),window==null||window.addEventListener("visibilitychange",this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(t){console.error("_handleVisibilityChange",t)}}async _onVisibilityChanged(t){const n=`#_onVisibilityChanged(${t})`;this._debug(n,"visibilityState",document.visibilityState),document.visibilityState==="visible"?(this.autoRefreshToken&&this._startAutoRefresh(),t||(await this.initializePromise,await this._acquireLock(-1,async()=>{if(document.visibilityState!=="visible"){this._debug(n,"acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting");return}await this._recoverAndRefresh()}))):document.visibilityState==="hidden"&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(t,n,r){const a=[`provider=${encodeURIComponent(n)}`];if(r!=null&&r.redirectTo&&a.push(`redirect_to=${encodeURIComponent(r.redirectTo)}`),r!=null&&r.scopes&&a.push(`scopes=${encodeURIComponent(r.scopes)}`),this.flowType==="pkce"){const[i,l]=await lI(this.storage,this.storageKey),o=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(l)}`});a.push(o.toString())}if(r!=null&&r.queryParams){const i=new URLSearchParams(r.queryParams);a.push(i.toString())}return r!=null&&r.skipBrowserRedirect&&a.push(`skip_http_redirect=${r.skipBrowserRedirect}`),`${t}?${a.join("&")}`}async _unenroll(t){try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;return i?{data:null,error:i}:await bl(this.fetch,"DELETE",`${this.url}/factors/${t.factorId}`,{headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if($o(n))return{data:null,error:n};throw n}}async _enroll(t){try{return await this._useSession(async n=>{var r,a;const{data:i,error:l}=n;if(l)return{data:null,error:l};const o=Object.assign({friendly_name:t.friendlyName,factor_type:t.factorType},t.factorType==="phone"?{phone:t.phone}:{issuer:t.issuer}),{data:c,error:d}=await bl(this.fetch,"POST",`${this.url}/factors`,{body:o,headers:this.headers,jwt:(r=i==null?void 0:i.session)===null||r===void 0?void 0:r.access_token});return d?{data:null,error:d}:(t.factorType==="totp"&&(!((a=c==null?void 0:c.totp)===null||a===void 0)&&a.qr_code)&&(c.totp.qr_code=`data:image/svg+xml;utf-8,${c.totp.qr_code}`),{data:c,error:null})})}catch(n){if($o(n))return{data:null,error:n};throw n}}async _verify(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;if(i)return{data:null,error:i};const{data:l,error:o}=await bl(this.fetch,"POST",`${this.url}/factors/${t.factorId}/verify`,{body:{code:t.code,challenge_id:t.challengeId},headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token});return o?{data:null,error:o}:(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+l.expires_in},l)),await this._notifyAllSubscribers("MFA_CHALLENGE_VERIFIED",l),{data:l,error:o})})}catch(n){if($o(n))return{data:null,error:n};throw n}})}async _challenge(t){return this._acquireLock(-1,async()=>{try{return await this._useSession(async n=>{var r;const{data:a,error:i}=n;return i?{data:null,error:i}:await bl(this.fetch,"POST",`${this.url}/factors/${t.factorId}/challenge`,{body:{channel:t.channel},headers:this.headers,jwt:(r=a==null?void 0:a.session)===null||r===void 0?void 0:r.access_token})})}catch(n){if($o(n))return{data:null,error:n};throw n}})}async _challengeAndVerify(t){const{data:n,error:r}=await this._challenge({factorId:t.factorId});return r?{data:null,error:r}:await this._verify({factorId:t.factorId,challengeId:n.id,code:t.code})}async _listFactors(){const{data:{user:t},error:n}=await this.getUser();if(n)return{data:null,error:n};const r=(t==null?void 0:t.factors)||[],a=r.filter(l=>l.factor_type==="totp"&&l.status==="verified"),i=r.filter(l=>l.factor_type==="phone"&&l.status==="verified");return{data:{all:r,totp:a,phone:i},error:null}}async _getAuthenticatorAssuranceLevel(){return this._acquireLock(-1,async()=>await this._useSession(async t=>{var n,r;const{data:{session:a},error:i}=t;if(i)return{data:null,error:i};if(!a)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};const{payload:l}=Iwe(a.access_token);let o=null;l.aal&&(o=l.aal);let c=o;((r=(n=a.user.factors)===null||n===void 0?void 0:n.filter(h=>h.status==="verified"))!==null&&r!==void 0?r:[]).length>0&&(c="aal2");const u=l.amr||[];return{data:{currentLevel:o,nextLevel:c,currentAuthenticationMethods:u},error:null}}))}async fetchJwk(t,n={keys:[]}){let r=n.keys.find(l=>l.kid===t);if(r||(r=this.jwks.keys.find(l=>l.kid===t),r&&this.jwks_cached_at+IDt>Date.now()))return r;const{data:a,error:i}=await bl(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 L9("JWKS is empty");if(this.jwks=a,this.jwks_cached_at=Date.now(),r=a.keys.find(l=>l.kid===t),!r)throw new L9("No matching signing key found in JWKS");return r}async getClaims(t,n={keys:[]}){try{let r=t;if(!r){const{data:f,error:y}=await this.getSession();if(y||!f.session)return{data:null,error:y};r=f.session.access_token}const{header:a,payload:i,signature:l,raw:{header:o,payload:c}}=Iwe(r);if(tRt(i.exp),!a.kid||a.alg==="HS256"||!("crypto"in globalThis&&"subtle"in globalThis.crypto)){const{error:f}=await this.getUser(r);if(f)throw f;return{data:{claims:i,header:a,signature:l},error:null}}const d=sRt(a.alg),u=await this.fetchJwk(a.kid,n),h=await crypto.subtle.importKey("jwk",u,d,!0,["verify"]);if(!await crypto.subtle.verify(d,h,l,UDt(`${o}.${c}`)))throw new L9("Invalid JWT signature");return{data:{claims:i,header:a,signature:l},error:null}}catch(r){if($o(r))return{data:null,error:r};throw r}}}Zz.nextInstanceID=0;const yRt=Zz;class vRt extends yRt{constructor(t){super(t)}}var bRt=function(s,t,n,r){function a(i){return i instanceof n?i:new n(function(l){l(i)})}return new(n||(n=Promise))(function(i,l){function o(u){try{d(r.next(u))}catch(h){l(h)}}function c(u){try{d(r.throw(u))}catch(h){l(h)}}function d(u){u.done?i(u.value):a(u.value).then(o,c)}d((r=r.apply(s,t||[])).next())})};class _Rt{constructor(t,n,r){var a,i,l;if(this.supabaseUrl=t,this.supabaseKey=n,!t)throw new Error("supabaseUrl is required.");if(!n)throw new Error("supabaseKey is required.");const o=SDt(t),c=new URL(o);this.realtimeUrl=new URL("realtime/v1",c),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace("http","ws"),this.authUrl=new URL("auth/v1",c),this.storageUrl=new URL("storage/v1",c),this.functionsUrl=new URL("functions/v1",c);const d=`sb-${c.hostname.split(".")[0]}-auth-token`,u={db:yDt,realtime:bDt,auth:Object.assign(Object.assign({},vDt),{storageKey:d}),global:gDt},h=CDt(r??{},u);this.storageKey=(a=h.auth.storageKey)!==null&&a!==void 0?a:"",this.headers=(i=h.global.headers)!==null&&i!==void 0?i:{},h.accessToken?(this.accessToken=h.accessToken,this.auth=new Proxy({},{get:(p,f)=>{throw new Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(f)} is not possible`)}})):this.auth=this._initSupabaseAuthClient((l=h.auth)!==null&&l!==void 0?l:{},this.headers,h.global.fetch),this.fetch=NDt(n,this._getAccessToken.bind(this),h.global.fetch),this.realtime=this._initRealtimeClient(Object.assign({headers:this.headers,accessToken:this._getAccessToken.bind(this)},h.realtime)),this.rest=new B8t(new URL("rest/v1",c).href,{headers:this.headers,schema:h.db.schema,fetch:this.fetch}),h.accessToken||this._listenForAuthEvents()}get functions(){return new x8t(this.functionsUrl.href,{headers:this.headers,customFetch:this.fetch})}get storage(){return new pDt(this.storageUrl.href,this.headers,this.fetch)}from(t){return this.rest.from(t)}schema(t){return this.rest.schema(t)}rpc(t,n={},r={}){return this.rest.rpc(t,n,r)}channel(t,n={config:{}}){return this.realtime.channel(t,n)}getChannels(){return this.realtime.getChannels()}removeChannel(t){return this.realtime.removeChannel(t)}removeAllChannels(){return this.realtime.removeAllChannels()}_getAccessToken(){var t,n;return bRt(this,void 0,void 0,function*(){if(this.accessToken)return yield this.accessToken();const{data:r}=yield this.auth.getSession();return(n=(t=r.session)===null||t===void 0?void 0:t.access_token)!==null&&n!==void 0?n:null})}_initSupabaseAuthClient({autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:a,storageKey:i,flowType:l,lock:o,debug:c},d,u){const h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new vRt({url:this.authUrl.href,headers:Object.assign(Object.assign({},h),d),storageKey:i,autoRefreshToken:t,persistSession:n,detectSessionInUrl:r,storage:a,flowType:l,lock:o,debug:c,fetch:u,hasCustomAuthorizationHeader:"Authorization"in this.headers})}_initRealtimeClient(t){return new eDt(this.realtimeUrl.href,Object.assign(Object.assign({},t),{params:Object.assign({apikey:this.supabaseKey},t==null?void 0:t.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((n,r)=>{this._handleTokenChanged(n,"CLIENT",r==null?void 0:r.access_token)})}_handleTokenChanged(t,n,r){(t==="TOKEN_REFRESHED"||t==="SIGNED_IN")&&this.changedAccessToken!==r?this.changedAccessToken=r:t==="SIGNED_OUT"&&(this.realtime.setAuth(),n=="STORAGE"&&this.auth.signOut(),this.changedAccessToken=void 0)}}const wRt=(s,t,n)=>new _Rt(s,t,n),jRt="https://relzejiswnotikjgvjhz.supabase.co",NRt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM",q=wRt(jRt,NRt,{auth:{storage:localStorage,persistSession:!0,autoRefreshToken:!0}}),kRt=Object.freeze(Object.defineProperty({__proto__:null,supabase:q},Symbol.toStringTag,{value:"Module"})),$at=N.createContext(void 0),SRt=({children:s})=>{const[t,n]=N.useState(null),[r,a]=N.useState(null),[i,l]=N.useState(!0),[o,c]=N.useState(!0),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,y]=N.useState(!1),[_,v]=N.useState(null),[j,w]=N.useState([]),[S,A]=N.useState(null),E=N.useRef(null),O=N.useRef(!1),D=N.useRef(!1),I=Ln(),F=()=>{u(!1),p(!1),y(!1),v(null),w([]),A(null),E.current=null,O.current=!1},z=async W=>{if(!(O.current&&E.current===W)&&!D.current){D.current=!0,c(!0);try{console.log("Checking roles via RPC for user:",W);const[{data:ee,error:se},{data:oe,error:he},{data:ce,error:me}]=await Promise.all([q.rpc("has_role",{_user_id:W,_role:"admin"}),q.rpc("has_role",{_user_id:W,_role:"brokerage_manager"}),q.rpc("has_role",{_user_id:W,_role:"coach"})]);if(se||he)console.error("Role RPC errors:",{isAdminError:se,isBrokerError:he,isCoachError:me}),u(!1),p(!1),y(!1);else{const ge=!!ee,Te=!!oe,Ie=!!ce;console.log("RPC roles result:",{adminValue:ge,brokerValue:Te,coachValue:Ie}),u(ge),p(Te),y(Ie)}const{data:le,error:ve}=await q.from("profiles").select("brokerage_id").eq("id",W).single();if(v(!ve&&le?le.brokerage_id:null),oe){console.log("Fetching managed brokerages for user:",W);const{data:ge,error:Te}=await q.from("brokerage_manager_assignments").select("brokerage_id").eq("user_id",W);if(console.log("Managed brokerage assignments result:",{assignments:ge,assignmentsError:Te}),Te||!ge){console.error("Error fetching managed brokerage assignments:",Te),w([]);return}const Ie=Array.from(new Set(ge.map(Re=>Re.brokerage_id).filter(Boolean)));if(Ie.length===0){w([]);return}const{data:Ce,error:Me}=await q.from("brokerages").select("id, name").in("id",Ie);if(console.log("Managed brokerages details result:",{brokeragesData:Ce,brokeragesError:Me}),Me||!Ce){console.error("Error fetching managed brokerages details:",Me),w([]);return}const Pe=Ce.map(Re=>({id:Re.id,name:Re.name})).sort((Re,Ae)=>Ie.indexOf(Re.id)-Ie.indexOf(Ae.id));console.log("Parsed managed brokerages:",Pe),w(Pe),Pe.length>0&&A(Re=>Re??Pe[0].id)}else console.log("User is not a brokerage manager, skipping managed brokerages fetch"),w([]);E.current=W,O.current=!0}catch(ee){console.error("Unexpected error in checkRoles:",ee),F()}finally{D.current=!1,c(!1)}}};N.useEffect(()=>{let W=!0,ee=!1;const se=()=>{!W||ee||(ee=!0,l(!1))},{data:{subscription:oe}}=q.auth.onAuthStateChange((me,le)=>{console.log("Auth event:",me),W&&(a(le),n((le==null?void 0:le.user)??null),se(),me==="PASSWORD_RECOVERY"&&(console.log("Password recovery detected, redirecting to profile"),setTimeout(()=>{I("/profile?reset=true")},100)),le!=null&&le.user?(!O.current||E.current!==le.user.id)&&setTimeout(()=>{z(le.user.id)},0):(F(),c(!1)))}),he=window.setTimeout(()=>{console.warn("Auth initialization timeout reached. Continuing without blocking UI."),se()},4e3);return(async()=>{try{const{data:{session:me}}=await q.auth.getSession();if(!W)return;a(me),n((me==null?void 0:me.user)??null),me!=null&&me.user?await z(me.user.id):F()}catch(me){console.error("Error restoring auth session:",me),W&&(a(null),n(null),F())}finally{se()}})(),()=>{W=!1,window.clearTimeout(he),oe.unsubscribe()}},[]);const H=async(W,ee)=>{const{error:se}=await q.auth.signInWithPassword({email:W,password:ee});if(se)throw ae.error(se.message),se;ae.success("Welcome back!")},Z=async(W,ee,se)=>{var le;const oe=`${window.location.origin}/dashboard`,he=localStorage.getItem("levelup_referral_code")||null,{data:ce,error:me}=await q.auth.signUp({email:W,password:ee,options:{emailRedirectTo:oe,data:{name:se,referred_by_code:he}}});if(me)throw ae.error(me.message),me;if(he&&((le=ce.user)!=null&&le.id))try{await q.from("profiles").update({referred_by_code:he}).eq("id",ce.user.id),localStorage.removeItem("levelup_referral_code")}catch(ve){console.warn("Failed to attach referral code to profile",ve)}ae.success("Account created! Welcome to LevelUp."),I("/dashboard")},Y=async()=>{try{const{data:{session:W}}=await q.auth.getSession();if(W){const{error:ee}=await q.auth.signOut();ee?ee.message==="Auth session missing!"?console.warn("Sign out warning (ignored):",ee.message):(console.error("Sign out error:",ee),ae.error(ee.message)):ae.success("Signed out successfully")}else console.log("No active session found, redirecting to auth");n(null),a(null),u(!1),p(!1),v(null),w([]),A(null),I("/auth")}catch(W){console.error("Unexpected sign out error:",W),I("/auth")}};return e.jsx($at.Provider,{value:{user:t,session:r,loading:i,rolesLoading:o,signIn:H,signUp:Z,signOut:Y,isAdmin:d,isBrokerageManager:h,isCoach:f,brokerageId:_,managedBrokerages:j,selectedBrokerageId:S,setSelectedBrokerageId:A},children:s})},vs=()=>{const s=N.useContext($at);if(s===void 0)throw new Error("useAuth must be used within an AuthProvider");return s},Uat=N.createContext({onlineUsers:[],totalOnline:0}),CRt=async s=>{try{const{data:t}=await q.storage.from("avatars").list(`${s}`);if(t&&t.length>0){const{data:n}=q.storage.from("avatars").getPublicUrl(`${s}/${t[0].name}`);return n.publicUrl}}catch{}},TRt=({children:s})=>{const{user:t,brokerageId:n,isAdmin:r}=vs(),[a,i]=N.useState([]),[l,o]=N.useState(null);N.useEffect(()=>{if(!t)return;let d=!1;q.auth.getSession().then(({data:h})=>{var f;const p=(f=h.session)==null?void 0:f.access_token;if(p)try{q.realtime.setAuth(p)}catch{}});const u=q.channel("app-presence-v2",{config:{presence:{key:t.id},broadcast:{self:!0}}});return u.on("presence",{event:"sync"},()=>{const h=u.presenceState(),p=[];Object.entries(h).forEach(([f,y])=>{if(y&&y.length>0){const _=y[0];p.push({id:f,name:_.name||"Unknown",avatarUrl:_.avatarUrl,brokerageId:_.brokerageId,onlineSince:_.onlineSince})}}),console.log("[Presence] sync, users:",p.length,p),i(p)}).on("presence",{event:"join"},({key:h,newPresences:p})=>{console.log("[Presence] join",h,p)}).on("presence",{event:"leave"},({key:h})=>{console.log("[Presence] leave",h)}).subscribe(async(h,p)=>{var f;if(console.log("[Presence] subscribe status:",h,p),h==="SUBSCRIBED"&&!d){const{data:y}=await q.from("profiles").select("name, brokerage_id").eq("id",t.id).maybeSingle(),_=await CRt(t.id),v=await u.track({name:(y==null?void 0:y.name)||((f=t.email)==null?void 0:f.split("@")[0])||"User",avatarUrl:_,brokerageId:y==null?void 0:y.brokerage_id,onlineSince:new Date().toISOString()});console.log("[Presence] track result:",v)}}),o(u),()=>{d=!0;try{u.untrack()}catch{}q.removeChannel(u)}},[t==null?void 0:t.id]);const c=a.filter(d=>d.id===(t==null?void 0:t.id)?!1:!!(r||n&&d.brokerageId===n||!n&&!d.brokerageId));return e.jsx(Uat.Provider,{value:{onlineUsers:c,totalOnline:a.length},children:s})},qat=()=>N.useContext(Uat),Vat=N.createContext(void 0),t3="levelup_admin_session",yk="levelup_impersonation",Pwe="levelup_impersonation_return",ERt=({children:s})=>{const[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(!1);N.useEffect(()=>{const d=sessionStorage.getItem(yk);if(d)try{const u=JSON.parse(d);n(!0),a(u)}catch{sessionStorage.removeItem(yk)}},[]);const o=async(d,u)=>{l(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)return ae.error("No active session found"),!1;const p={access_token:h.access_token,refresh_token:h.refresh_token};sessionStorage.setItem(t3,JSON.stringify(p)),u&&sessionStorage.setItem(Pwe,u);const f=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/impersonate-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({targetUserId:d})}),y=await f.json();if(!f.ok)throw new Error(y.error||"Failed to impersonate user");const _={id:y.targetUser.id,name:y.targetUser.name,email:y.targetUser.email};if(sessionStorage.setItem(yk,JSON.stringify(_)),y.method==="session"){const{error:v}=await q.auth.setSession({access_token:y.access_token,refresh_token:y.refresh_token});if(v)throw console.error("Set session error:",v),sessionStorage.removeItem(t3),sessionStorage.removeItem(yk),new Error("Failed to establish impersonation session")}else{const v=y.type||"recovery",{error:j}=await q.auth.verifyOtp({token_hash:y.token_hash,type:v});if(j)throw console.error("Verify OTP error:",j),sessionStorage.removeItem(t3),sessionStorage.removeItem(yk),new Error("Failed to establish impersonation session")}return n(!0),a(_),ae.success(`Now viewing as ${_.name}`),window.location.href="/dashboard",!0}catch(h){return console.error("Impersonation error:",h),ae.error(h.message||"Failed to impersonate user"),sessionStorage.removeItem(t3),sessionStorage.removeItem(yk),!1}finally{l(!1)}},c=async()=>{l(!0);try{const d=sessionStorage.getItem(t3);if(!d){await q.auth.signOut(),window.location.href="/auth";return}const u=JSON.parse(d);await q.auth.signOut();const{error:h}=await q.auth.setSession({access_token:u.access_token,refresh_token:u.refresh_token});if(sessionStorage.removeItem(t3),sessionStorage.removeItem(yk),h){console.error("Failed to restore admin session:",h),ae.error("Admin session expired, please sign in again"),window.location.href="/auth";return}n(!1),a(null),ae.success("Returned to your account");const p=sessionStorage.getItem(Pwe)||"/admin/members";sessionStorage.removeItem(Pwe),window.location.href=p}catch(d){console.error("Stop impersonation error:",d),ae.error("Failed to restore admin session"),sessionStorage.removeItem(t3),sessionStorage.removeItem(yk),window.location.href="/auth"}finally{l(!1)}};return e.jsx(Vat.Provider,{value:{isImpersonating:t,impersonatedUser:r,startImpersonation:o,stopImpersonation:c,isLoading:i},children:s})},A0e=()=>{const s=N.useContext(Vat);if(s===void 0)throw new Error("useImpersonation must be used within an ImpersonationProvider");return s},m8=OM("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-full text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0",{variants:{variant:{default:"bg-primary text-primary-foreground hover:bg-primary/90",destructive:"bg-destructive text-destructive-foreground hover:bg-destructive/90",outline:"border border-input bg-background hover:bg-accent hover:text-accent-foreground",secondary:"bg-secondary text-secondary-foreground hover:bg-secondary/80",ghost:"hover:bg-accent hover:text-accent-foreground",link:"text-primary underline-offset-4 hover:underline"},size:{default:"h-10 px-4 py-2",sm:"h-9 rounded-md px-3",lg:"h-11 rounded-full px-8",icon:"h-10 w-10"}},defaultVariants:{variant:"default",size:"default"}}),B=N.forwardRef(({className:s,variant:t,size:n,asChild:r=!1,...a},i)=>{const l=r?BEe:"button";return e.jsx(l,{className:Mt(m8({variant:t,size:n,className:s})),ref:i,...a})});B.displayName="Button";const ARt=()=>{const{isImpersonating:s,impersonatedUser:t,stopImpersonation:n,isLoading:r}=A0e();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(ic,{className:"h-5 w-5 flex-shrink-0"}),e.jsxs("span",{className:"font-medium text-sm md:text-base",children:[e.jsx("span",{className:"hidden sm:inline",children:"You are viewing as "}),e.jsx("strong",{children:t.name}),e.jsxs("span",{className:"hidden md:inline text-amber-800",children:[" (",t.email,")"]})]})]}),e.jsx(B,{size:"sm",variant:"secondary",onClick:n,disabled:r,className:"bg-amber-100 hover:bg-amber-200 text-amber-950 border-0",children:r?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx($n,{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"})]})})]})})},Hat=N.createContext(void 0),dI="levelup_acting_as",zV="levelup_acting_as_self",MRt=({children:s})=>{const{user:t}=vs(),[n,r]=N.useState(!1),[a,i]=N.useState([]),[l,o]=N.useState(null),[c,d]=N.useState({}),[u,h]=N.useState(!0),[p,f]=N.useState(()=>sessionStorage.getItem(zV)==="true");N.useEffect(()=>{if(!(t!=null&&t.id)){r(!1),i([]),o(null),d({}),h(!1);return}(async()=>{h(!0);try{const{data:S}=await q.rpc("has_role",{_user_id:t.id,_role:"assistant"});if(!S){r(!1),i([]),o(null),d({}),h(!1);return}r(!0);const{data:A,error:E}=await q.from("agent_assistant_assignments").select("agent_id, permissions").eq("assistant_id",t.id);if(E||!A||A.length===0){i([]),h(!1);return}const O=A.map(F=>F.agent_id),{data:D}=await q.from("profiles").select("id, name, email, avatar_url").in("id",O),I=(D||[]).map(F=>({id:F.id,name:F.name||F.email||"Unknown",email:F.email||"",avatar_url:F.avatar_url}));if(i(I),sessionStorage.getItem(zV)==="true")f(!0),o(null),d({});else{const F=sessionStorage.getItem(dI);if(F){const z=I.find(H=>H.id===F);if(z){o(z);const H=A.find(Z=>Z.agent_id===F);d((H==null?void 0:H.permissions)||{})}else if(I.length>0){o(I[0]);const H=A.find(Z=>Z.agent_id===I[0].id);d((H==null?void 0:H.permissions)||{}),sessionStorage.setItem(dI,I[0].id)}}else if(I.length>0){o(I[0]);const z=A.find(H=>H.agent_id===I[0].id);d((z==null?void 0:z.permissions)||{}),sessionStorage.setItem(dI,I[0].id)}}}catch(S){console.error("Error loading assistant data:",S)}finally{h(!1)}})()},[t==null?void 0:t.id]);const y=w=>{o(w),f(!1),sessionStorage.removeItem(zV),w?(sessionStorage.setItem(dI,w.id),q.from("agent_assistant_assignments").select("permissions").eq("assistant_id",(t==null?void 0:t.id)||"").eq("agent_id",w.id).single().then(({data:S})=>{d((S==null?void 0:S.permissions)||{})})):(sessionStorage.removeItem(dI),d({}))},_=()=>{f(!0),o(null),d({}),sessionStorage.setItem(zV,"true"),sessionStorage.removeItem(dI)},v=w=>!n||p?!0:c[w]===!0,j=n&&l&&!p?l.id:(t==null?void 0:t.id)||null;return e.jsx(Hat.Provider,{value:{isAssistant:n,assignedAgents:a,actingAsAgent:l,setActingAsAgent:y,effectiveUserId:j,permissions:c,hasPermission:v,isLoading:u,isActingAsSelf:p,setActingAsSelf:_},children:s})},mAe=()=>{const s=N.useContext(Hat);if(s===void 0)throw new Error("useActingAs must be used within an ActingAsProvider");return s},wa=()=>{const{effectiveUserId:s}=mAe();return s};var Gat={exports:{}},Wat={};/** * @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 p8=N;function IRt(s,t){return s===t&&(s!==0||1/s===1/t)||s!==s&&t!==t}var PRt=typeof Object.is=="function"?Object.is:IRt,LRt=p8.useState,DRt=p8.useEffect,RRt=p8.useLayoutEffect,ORt=p8.useDebugValue;function FRt(s,t){var n=t(),r=LRt({inst:{value:n,getSnapshot:t}}),a=r[0].inst,i=r[1];return RRt(function(){a.value=n,a.getSnapshot=t,Lwe(a)&&i({inst:a})},[s,n,t]),DRt(function(){return Lwe(a)&&i({inst:a}),s(function(){Lwe(a)&&i({inst:a})})},[s]),ORt(n),n}function Lwe(s){var t=s.getSnapshot;s=s.value;try{var n=t();return!PRt(s,n)}catch{return!0}}function zRt(s,t){return t()}var BRt=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?zRt:FRt;Wat.useSyncExternalStore=p8.useSyncExternalStore!==void 0?p8.useSyncExternalStore:BRt;Gat.exports=Wat;var $Rt=Gat.exports;function URt(){return $Rt.useSyncExternalStore(qRt,()=>!0,()=>!1)}function qRt(){return()=>{}}var pAe="Avatar",[VRt,Wpn]=uu(pAe),[HRt,Kat]=VRt(pAe),Yat=N.forwardRef((s,t)=>{const{__scopeAvatar:n,...r}=s,[a,i]=N.useState("idle");return e.jsx(HRt,{scope:n,imageLoadingStatus:a,onImageLoadingStatusChange:i,children:e.jsx(Yr.span,{...r,ref:t})})});Yat.displayName=pAe;var Zat="AvatarImage",Qat=N.forwardRef((s,t)=>{const{__scopeAvatar:n,src:r,onLoadingStatusChange:a=()=>{},...i}=s,l=Kat(Zat,n),o=GRt(r,i),c=rh(d=>{a(d),l.onImageLoadingStatusChange(d)});return lh(()=>{o!=="idle"&&c(o)},[o,c]),o==="loaded"?e.jsx(Yr.img,{...i,ref:t,src:r}):null});Qat.displayName=Zat;var Xat="AvatarFallback",Jat=N.forwardRef((s,t)=>{const{__scopeAvatar:n,delayMs:r,...a}=s,i=Kat(Xat,n),[l,o]=N.useState(r===void 0);return N.useEffect(()=>{if(r!==void 0){const c=window.setTimeout(()=>o(!0),r);return()=>window.clearTimeout(c)}},[r]),l&&i.imageLoadingStatus!=="loaded"?e.jsx(Yr.span,{...a,ref:t}):null});Jat.displayName=Xat;function bze(s,t){return s?t?(s.src!==t&&(s.src=t),s.complete&&s.naturalWidth>0?"loaded":"loading"):"error":"idle"}function GRt(s,{referrerPolicy:t,crossOrigin:n}){const r=URt(),a=N.useRef(null),i=r?(a.current||(a.current=new window.Image),a.current):null,[l,o]=N.useState(()=>bze(i,s));return lh(()=>{o(bze(i,s))},[i,s]),lh(()=>{const c=h=>()=>{o(h)};if(!i)return;const d=c("loaded"),u=c("error");return i.addEventListener("load",d),i.addEventListener("error",u),t&&(i.referrerPolicy=t),typeof n=="string"&&(i.crossOrigin=n),()=>{i.removeEventListener("load",d),i.removeEventListener("error",u)}},[i,n,t]),l}var eit=Yat,tit=Qat,sit=Jat;const Jr=N.forwardRef(({className:s,...t},n)=>e.jsx(eit,{ref:n,className:Mt("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",s),...t}));Jr.displayName=eit.displayName;const ti=N.forwardRef(({className:s,...t},n)=>e.jsx(tit,{ref:n,className:Mt("aspect-square h-full w-full",s),...t}));ti.displayName=tit.displayName;const ea=N.forwardRef(({className:s,...t},n)=>e.jsx(sit,{ref:n,className:Mt("flex h-full w-full items-center justify-center rounded-full bg-muted",s),...t}));ea.displayName=sit.displayName;const WRt=OM("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 Ue({className:s,variant:t,...n}){return e.jsx("div",{className:Mt(WRt({variant:t}),s),...n})}var KRt=N.createContext(void 0);function vN(s){const t=N.useContext(KRt);return s||t||"ltr"}var Dwe=0;function M0e(){N.useEffect(()=>{const s=document.querySelectorAll("[data-radix-focus-guard]");return document.body.insertAdjacentElement("afterbegin",s[0]??_ze()),document.body.insertAdjacentElement("beforeend",s[1]??_ze()),Dwe++,()=>{Dwe===1&&document.querySelectorAll("[data-radix-focus-guard]").forEach(t=>t.remove()),Dwe--}},[])}function _ze(){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 Rwe="focusScope.autoFocusOnMount",Owe="focusScope.autoFocusOnUnmount",wze={bubbles:!1,cancelable:!0},YRt="FocusScope",O$=N.forwardRef((s,t)=>{const{loop:n=!1,trapped:r=!1,onMountAutoFocus:a,onUnmountAutoFocus:i,...l}=s,[o,c]=N.useState(null),d=rh(a),u=rh(i),h=N.useRef(null),p=ji(t,_=>c(_)),f=N.useRef({paused:!1,pause(){this.paused=!0},resume(){this.paused=!1}}).current;N.useEffect(()=>{if(r){let _=function(S){if(f.paused||!o)return;const A=S.target;o.contains(A)?h.current=A:Lk(h.current,{select:!0})},v=function(S){if(f.paused||!o)return;const A=S.relatedTarget;A!==null&&(o.contains(A)||Lk(h.current,{select:!0}))},j=function(S){if(document.activeElement===document.body)for(const E of S)E.removedNodes.length>0&&Lk(o)};document.addEventListener("focusin",_),document.addEventListener("focusout",v);const w=new MutationObserver(j);return o&&w.observe(o,{childList:!0,subtree:!0}),()=>{document.removeEventListener("focusin",_),document.removeEventListener("focusout",v),w.disconnect()}}},[r,o,f.paused]),N.useEffect(()=>{if(o){Nze.add(f);const _=document.activeElement;if(!o.contains(_)){const j=new CustomEvent(Rwe,wze);o.addEventListener(Rwe,d),o.dispatchEvent(j),j.defaultPrevented||(ZRt(tOt(nit(o)),{select:!0}),document.activeElement===_&&Lk(o))}return()=>{o.removeEventListener(Rwe,d),setTimeout(()=>{const j=new CustomEvent(Owe,wze);o.addEventListener(Owe,u),o.dispatchEvent(j),j.defaultPrevented||Lk(_??document.body,{select:!0}),o.removeEventListener(Owe,u),Nze.remove(f)},0)}}},[o,d,u,f]);const y=N.useCallback(_=>{if(!n&&!r||f.paused)return;const v=_.key==="Tab"&&!_.altKey&&!_.ctrlKey&&!_.metaKey,j=document.activeElement;if(v&&j){const w=_.currentTarget,[S,A]=QRt(w);S&&A?!_.shiftKey&&j===A?(_.preventDefault(),n&&Lk(S,{select:!0})):_.shiftKey&&j===S&&(_.preventDefault(),n&&Lk(A,{select:!0})):j===w&&_.preventDefault()}},[n,r,f.paused]);return e.jsx(Yr.div,{tabIndex:-1,...l,ref:p,onKeyDown:y})});O$.displayName=YRt;function ZRt(s,{select:t=!1}={}){const n=document.activeElement;for(const r of s)if(Lk(r,{select:t}),document.activeElement!==n)return}function QRt(s){const t=nit(s),n=jze(t,s),r=jze(t.reverse(),s);return[n,r]}function nit(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>{const a=r.tagName==="INPUT"&&r.type==="hidden";return r.disabled||r.hidden||a?NodeFilter.FILTER_SKIP:r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP}});for(;n.nextNode();)t.push(n.currentNode);return t}function jze(s,t){for(const n of s)if(!XRt(n,{upTo:t}))return n}function XRt(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 JRt(s){return s instanceof HTMLInputElement&&"select"in s}function Lk(s,{select:t=!1}={}){if(s&&s.focus){const n=document.activeElement;s.focus({preventScroll:!0}),s!==n&&JRt(s)&&t&&s.select()}}var Nze=eOt();function eOt(){let s=[];return{add(t){const n=s[0];t!==n&&(n==null||n.pause()),s=kze(s,t),s.unshift(t)},remove(t){var n;s=kze(s,t),(n=s[0])==null||n.resume()}}}function kze(s,t){const n=[...s],r=n.indexOf(t);return r!==-1&&n.splice(r,1),n}function tOt(s){return s.filter(t=>t.tagName!=="A")}var Fwe="rovingFocusGroup.onEntryFocus",sOt={bubbles:!1,cancelable:!0},F$="RovingFocusGroup",[n4e,rit,nOt]=wD(F$),[rOt,z4]=uu(F$,[nOt]),[aOt,iOt]=rOt(F$),ait=N.forwardRef((s,t)=>e.jsx(n4e.Provider,{scope:s.__scopeRovingFocusGroup,children:e.jsx(n4e.Slot,{scope:s.__scopeRovingFocusGroup,children:e.jsx(oOt,{...s,ref:t})})}));ait.displayName=F$;var oOt=N.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,orientation:r,loop:a=!1,dir:i,currentTabStopId:l,defaultCurrentTabStopId:o,onCurrentTabStopIdChange:c,onEntryFocus:d,preventScrollOnEntryFocus:u=!1,...h}=s,p=N.useRef(null),f=ji(t,p),y=vN(i),[_,v]=cm({prop:l,defaultProp:o??null,onChange:c,caller:F$}),[j,w]=N.useState(!1),S=rh(d),A=rit(n),E=N.useRef(!1),[O,D]=N.useState(0);return N.useEffect(()=>{const I=p.current;if(I)return I.addEventListener(Fwe,S),()=>I.removeEventListener(Fwe,S)},[S]),e.jsx(aOt,{scope:n,orientation:r,dir:y,loop:a,currentTabStopId:_,onItemFocus:N.useCallback(I=>v(I),[v]),onItemShiftTab:N.useCallback(()=>w(!0),[]),onFocusableItemAdd:N.useCallback(()=>D(I=>I+1),[]),onFocusableItemRemove:N.useCallback(()=>D(I=>I-1),[]),children:e.jsx(Yr.div,{tabIndex:j||O===0?-1:0,"data-orientation":r,...h,ref:f,style:{outline:"none",...s.style},onMouseDown:xr(s.onMouseDown,()=>{E.current=!0}),onFocus:xr(s.onFocus,I=>{const F=!E.current;if(I.target===I.currentTarget&&F&&!j){const z=new CustomEvent(Fwe,sOt);if(I.currentTarget.dispatchEvent(z),!z.defaultPrevented){const H=A().filter(se=>se.focusable),Z=H.find(se=>se.active),Y=H.find(se=>se.id===_),ee=[Z,Y,...H].filter(Boolean).map(se=>se.ref.current);lit(ee,u)}}E.current=!1}),onBlur:xr(s.onBlur,()=>w(!1))})})}),iit="RovingFocusGroupItem",oit=N.forwardRef((s,t)=>{const{__scopeRovingFocusGroup:n,focusable:r=!0,active:a=!1,tabStopId:i,children:l,...o}=s,c=om(),d=i||c,u=iOt(iit,n),h=u.currentTabStopId===d,p=rit(n),{onFocusableItemAdd:f,onFocusableItemRemove:y,currentTabStopId:_}=u;return N.useEffect(()=>{if(r)return f(),()=>y()},[r,f,y]),e.jsx(n4e.ItemSlot,{scope:n,id:d,focusable:r,active:a,children:e.jsx(Yr.span,{tabIndex:h?0:-1,"data-orientation":u.orientation,...o,ref:t,onMouseDown:xr(s.onMouseDown,v=>{r?u.onItemFocus(d):v.preventDefault()}),onFocus:xr(s.onFocus,()=>u.onItemFocus(d)),onKeyDown:xr(s.onKeyDown,v=>{if(v.key==="Tab"&&v.shiftKey){u.onItemShiftTab();return}if(v.target!==v.currentTarget)return;const j=dOt(v,u.orientation,u.dir);if(j!==void 0){if(v.metaKey||v.ctrlKey||v.altKey||v.shiftKey)return;v.preventDefault();let S=p().filter(A=>A.focusable).map(A=>A.ref.current);if(j==="last")S.reverse();else if(j==="prev"||j==="next"){j==="prev"&&S.reverse();const A=S.indexOf(v.currentTarget);S=u.loop?uOt(S,A+1):S.slice(A+1)}setTimeout(()=>lit(S))}}),children:typeof l=="function"?l({isCurrentTabStop:h,hasTabStop:_!=null}):l})})});oit.displayName=iit;var lOt={ArrowLeft:"prev",ArrowUp:"prev",ArrowRight:"next",ArrowDown:"next",PageUp:"first",Home:"first",PageDown:"last",End:"last"};function cOt(s,t){return t!=="rtl"?s:s==="ArrowLeft"?"ArrowRight":s==="ArrowRight"?"ArrowLeft":s}function dOt(s,t,n){const r=cOt(s.key,n);if(!(t==="vertical"&&["ArrowLeft","ArrowRight"].includes(r))&&!(t==="horizontal"&&["ArrowUp","ArrowDown"].includes(r)))return lOt[r]}function lit(s,t=!1){const n=document.activeElement;for(const r of s)if(r===n||(r.focus({preventScroll:t}),document.activeElement!==n))return}function uOt(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var I0e=ait,P0e=oit,hOt=function(s){if(typeof document>"u")return null;var t=Array.isArray(s)?s[0]:s;return t.ownerDocument.body},uI=new WeakMap,BV=new WeakMap,$V={},zwe=0,cit=function(s){return s&&(s.host||cit(s.parentNode))},mOt=function(s,t){return t.map(function(n){if(s.contains(n))return n;var r=cit(n);return r&&s.contains(r)?r:(console.error("aria-hidden",n,"in not contained inside",s,". Doing nothing"),null)}).filter(function(n){return!!n})},pOt=function(s,t,n,r){var a=mOt(t,Array.isArray(s)?s:[s]);$V[n]||($V[n]=new WeakMap);var i=$V[n],l=[],o=new Set,c=new Set(a),d=function(h){!h||o.has(h)||(o.add(h),d(h.parentNode))};a.forEach(d);var u=function(h){!h||c.has(h)||Array.prototype.forEach.call(h.children,function(p){if(o.has(p))u(p);else try{var f=p.getAttribute(r),y=f!==null&&f!=="false",_=(uI.get(p)||0)+1,v=(i.get(p)||0)+1;uI.set(p,_),i.set(p,v),l.push(p),_===1&&y&&BV.set(p,!0),v===1&&p.setAttribute(n,"true"),y||p.setAttribute(r,"true")}catch(j){console.error("aria-hidden: cannot operate on ",p,j)}})};return u(t),o.clear(),zwe++,function(){l.forEach(function(h){var p=uI.get(h)-1,f=i.get(h)-1;uI.set(h,p),i.set(h,f),p||(BV.has(h)||h.removeAttribute(r),BV.delete(h)),f||h.removeAttribute(n)}),zwe--,zwe||(uI=new WeakMap,uI=new WeakMap,BV=new WeakMap,$V={})}},L0e=function(s,t,n){n===void 0&&(n="data-aria-hidden");var r=Array.from(Array.isArray(s)?s:[s]),a=hOt(s);return a?(r.push.apply(r,Array.from(a.querySelectorAll("[aria-live]"))),pOt(r,a,n,"aria-hidden")):function(){return null}},K_=function(){return K_=Object.assign||function(t){for(var n,r=1,a=arguments.length;r"u")return MOt;var t=IOt(s),n=document.documentElement.clientWidth,r=window.innerWidth;return{left:t[0],top:t[1],right:t[2],gap:Math.max(0,r-n+t[2]-t[0])}},LOt=mit(),NL="data-scroll-locked",DOt=function(s,t,n,r){var a=s.left,i=s.top,l=s.right,o=s.gap;return n===void 0&&(n="margin"),` .`.concat(xOt,` { overflow: hidden `).concat(r,`; padding-right: `).concat(o,"px ").concat(r,`; } body[`).concat(NL,`] { overflow: hidden `).concat(r,`; overscroll-behavior: contain; `).concat([t&&"position: relative ".concat(r,";"),n==="margin"&&` padding-left: `.concat(a,`px; padding-top: `).concat(i,`px; padding-right: `).concat(l,`px; margin-left:0; margin-top:0; margin-right: `).concat(o,"px ").concat(r,`; `),n==="padding"&&"padding-right: ".concat(o,"px ").concat(r,";")].filter(Boolean).join(""),` } .`).concat(xme,` { right: `).concat(o,"px ").concat(r,`; } .`).concat(gme,` { margin-right: `).concat(o,"px ").concat(r,`; } .`).concat(xme," .").concat(xme,` { right: 0 `).concat(r,`; } .`).concat(gme," .").concat(gme,` { margin-right: 0 `).concat(r,`; } body[`).concat(NL,`] { `).concat(gOt,": ").concat(o,`px; } `)},Cze=function(){var s=parseInt(document.body.getAttribute(NL)||"0",10);return isFinite(s)?s:0},ROt=function(){N.useEffect(function(){return document.body.setAttribute(NL,(Cze()+1).toString()),function(){var s=Cze()-1;s<=0?document.body.removeAttribute(NL):document.body.setAttribute(NL,s.toString())}},[])},OOt=function(s){var t=s.noRelative,n=s.noImportant,r=s.gapMode,a=r===void 0?"margin":r;ROt();var i=N.useMemo(function(){return POt(a)},[a]);return N.createElement(LOt,{styles:DOt(i,!t,a,n?"":"!important")})},r4e=!1;if(typeof window<"u")try{var UV=Object.defineProperty({},"passive",{get:function(){return r4e=!0,!0}});window.addEventListener("test",UV,UV),window.removeEventListener("test",UV,UV)}catch{r4e=!1}var hI=r4e?{passive:!1}:!1,FOt=function(s){return s.tagName==="TEXTAREA"},pit=function(s,t){if(!(s instanceof Element))return!1;var n=window.getComputedStyle(s);return n[t]!=="hidden"&&!(n.overflowY===n.overflowX&&!FOt(s)&&n[t]==="visible")},zOt=function(s){return pit(s,"overflowY")},BOt=function(s){return pit(s,"overflowX")},Tze=function(s,t){var n=t.ownerDocument,r=t;do{typeof ShadowRoot<"u"&&r instanceof ShadowRoot&&(r=r.host);var a=fit(s,r);if(a){var i=xit(s,r),l=i[1],o=i[2];if(l>o)return!0}r=r.parentNode}while(r&&r!==n.body);return!1},$Ot=function(s){var t=s.scrollTop,n=s.scrollHeight,r=s.clientHeight;return[t,n,r]},UOt=function(s){var t=s.scrollLeft,n=s.scrollWidth,r=s.clientWidth;return[t,n,r]},fit=function(s,t){return s==="v"?zOt(t):BOt(t)},xit=function(s,t){return s==="v"?$Ot(t):UOt(t)},qOt=function(s,t){return s==="h"&&t==="rtl"?-1:1},VOt=function(s,t,n,r,a){var i=qOt(s,window.getComputedStyle(t).direction),l=i*r,o=n.target,c=t.contains(o),d=!1,u=l>0,h=0,p=0;do{if(!o)break;var f=xit(s,o),y=f[0],_=f[1],v=f[2],j=_-v-i*y;(y||j)&&fit(s,o)&&(h+=j,p+=y);var w=o.parentNode;o=w&&w.nodeType===Node.DOCUMENT_FRAGMENT_NODE?w.host:w}while(!c&&o!==document.body||c&&(t.contains(o)||t===o));return(u&&(Math.abs(h)<1||!a)||!u&&(Math.abs(p)<1||!a))&&(d=!0),d},qV=function(s){return"changedTouches"in s?[s.changedTouches[0].clientX,s.changedTouches[0].clientY]:[0,0]},Eze=function(s){return[s.deltaX,s.deltaY]},Aze=function(s){return s&&"current"in s?s.current:s},HOt=function(s,t){return s[0]===t[0]&&s[1]===t[1]},GOt=function(s){return` .block-interactivity-`.concat(s,` {pointer-events: none;} .allow-interactivity-`).concat(s,` {pointer-events: all;} `)},WOt=0,mI=[];function KOt(s){var t=N.useRef([]),n=N.useRef([0,0]),r=N.useRef(),a=N.useState(WOt++)[0],i=N.useState(mit)[0],l=N.useRef(s);N.useEffect(function(){l.current=s},[s]),N.useEffect(function(){if(s.inert){document.body.classList.add("block-interactivity-".concat(a));var _=fOt([s.lockRef.current],(s.shards||[]).map(Aze),!0).filter(Boolean);return _.forEach(function(v){return v.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),_.forEach(function(v){return v.classList.remove("allow-interactivity-".concat(a))})}}},[s.inert,s.lockRef.current,s.shards]);var o=N.useCallback(function(_,v){if("touches"in _&&_.touches.length===2||_.type==="wheel"&&_.ctrlKey)return!l.current.allowPinchZoom;var j=qV(_),w=n.current,S="deltaX"in _?_.deltaX:w[0]-j[0],A="deltaY"in _?_.deltaY:w[1]-j[1],E,O=_.target,D=Math.abs(S)>Math.abs(A)?"h":"v";if("touches"in _&&D==="h"&&O.type==="range")return!1;var I=Tze(D,O);if(!I)return!0;if(I?E=D:(E=D==="v"?"h":"v",I=Tze(D,O)),!I)return!1;if(!r.current&&"changedTouches"in _&&(S||A)&&(r.current=E),!E)return!0;var F=r.current||E;return VOt(F,v,_,F==="h"?S:A,!0)},[]),c=N.useCallback(function(_){var v=_;if(!(!mI.length||mI[mI.length-1]!==i)){var j="deltaY"in v?Eze(v):qV(v),w=t.current.filter(function(E){return E.name===v.type&&(E.target===v.target||v.target===E.shadowParent)&&HOt(E.delta,j)})[0];if(w&&w.should){v.cancelable&&v.preventDefault();return}if(!w){var S=(l.current.shards||[]).map(Aze).filter(Boolean).filter(function(E){return E.contains(v.target)}),A=S.length>0?o(v,S[0]):!l.current.noIsolation;A&&v.cancelable&&v.preventDefault()}}},[]),d=N.useCallback(function(_,v,j,w){var S={name:_,delta:v,target:j,should:w,shadowParent:YOt(j)};t.current.push(S),setTimeout(function(){t.current=t.current.filter(function(A){return A!==S})},1)},[]),u=N.useCallback(function(_){n.current=qV(_),r.current=void 0},[]),h=N.useCallback(function(_){d(_.type,Eze(_),_.target,o(_,s.lockRef.current))},[]),p=N.useCallback(function(_){d(_.type,qV(_),_.target,o(_,s.lockRef.current))},[]);N.useEffect(function(){return mI.push(i),s.setCallbacks({onScrollCapture:h,onWheelCapture:h,onTouchMoveCapture:p}),document.addEventListener("wheel",c,hI),document.addEventListener("touchmove",c,hI),document.addEventListener("touchstart",u,hI),function(){mI=mI.filter(function(_){return _!==i}),document.removeEventListener("wheel",c,hI),document.removeEventListener("touchmove",c,hI),document.removeEventListener("touchstart",u,hI)}},[]);var f=s.removeScrollBar,y=s.inert;return N.createElement(N.Fragment,null,y?N.createElement(i,{styles:GOt(a)}):null,f?N.createElement(OOt,{noRelative:s.noRelative,gapMode:s.gapMode}):null)}function YOt(s){for(var t=null;s!==null;)s instanceof ShadowRoot&&(t=s.host,s=s.host),s=s.parentNode;return t}const ZOt=NOt(hit,KOt);var z$=N.forwardRef(function(s,t){return N.createElement(D0e,K_({},s,{ref:t,sideCar:ZOt}))});z$.classNames=D0e.classNames;var a4e=["Enter"," "],QOt=["ArrowDown","PageUp","Home"],git=["ArrowUp","PageDown","End"],XOt=[...QOt,...git],JOt={ltr:[...a4e,"ArrowRight"],rtl:[...a4e,"ArrowLeft"]},eFt={ltr:["ArrowLeft"],rtl:["ArrowRight"]},B$="Menu",[Qz,tFt,sFt]=wD(B$),[zM,yit]=uu(B$,[sFt,qw,z4]),R0e=qw(),vit=z4(),[nFt,BM]=zM(B$),[rFt,$$]=zM(B$),bit=s=>{const{__scopeMenu:t,open:n=!1,children:r,dir:a,onOpenChange:i,modal:l=!0}=s,o=R0e(t),[c,d]=N.useState(null),u=N.useRef(!1),h=rh(i),p=vN(a);return N.useEffect(()=>{const f=()=>{u.current=!0,document.addEventListener("pointerdown",y,{capture:!0,once:!0}),document.addEventListener("pointermove",y,{capture:!0,once:!0})},y=()=>u.current=!1;return document.addEventListener("keydown",f,{capture:!0}),()=>{document.removeEventListener("keydown",f,{capture:!0}),document.removeEventListener("pointerdown",y,{capture:!0}),document.removeEventListener("pointermove",y,{capture:!0})}},[]),e.jsx(I$,{...o,children:e.jsx(nFt,{scope:t,open:n,onOpenChange:h,content:c,onContentChange:d,children:e.jsx(rFt,{scope:t,onClose:N.useCallback(()=>h(!1),[h]),isUsingKeyboardRef:u,dir:p,modal:l,children:r})})})};bit.displayName=B$;var aFt="MenuAnchor",fAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=R0e(n);return e.jsx(CD,{...a,...r,ref:t})});fAe.displayName=aFt;var xAe="MenuPortal",[iFt,_it]=zM(xAe,{forceMount:void 0}),wit=s=>{const{__scopeMenu:t,forceMount:n,children:r,container:a}=s,i=BM(xAe,t);return e.jsx(iFt,{scope:t,forceMount:n,children:e.jsx(Lh,{present:n||i.open,children:e.jsx(jD,{asChild:!0,container:a,children:r})})})};wit.displayName=xAe;var Rv="MenuContent",[oFt,gAe]=zM(Rv),jit=N.forwardRef((s,t)=>{const n=_it(Rv,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=BM(Rv,s.__scopeMenu),l=$$(Rv,s.__scopeMenu);return e.jsx(Qz.Provider,{scope:s.__scopeMenu,children:e.jsx(Lh,{present:r||i.open,children:e.jsx(Qz.Slot,{scope:s.__scopeMenu,children:l.modal?e.jsx(lFt,{...a,ref:t}):e.jsx(cFt,{...a,ref:t})})})})}),lFt=N.forwardRef((s,t)=>{const n=BM(Rv,s.__scopeMenu),r=N.useRef(null),a=ji(t,r);return N.useEffect(()=>{const i=r.current;if(i)return L0e(i)},[]),e.jsx(yAe,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:n.open,disableOutsideScroll:!0,onFocusOutside:xr(s.onFocusOutside,i=>i.preventDefault(),{checkForDefaultPrevented:!1}),onDismiss:()=>n.onOpenChange(!1)})}),cFt=N.forwardRef((s,t)=>{const n=BM(Rv,s.__scopeMenu);return e.jsx(yAe,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,disableOutsideScroll:!1,onDismiss:()=>n.onOpenChange(!1)})}),dFt=v4("MenuContent.ScrollLock"),yAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,loop:r=!1,trapFocus:a,onOpenAutoFocus:i,onCloseAutoFocus:l,disableOutsidePointerEvents:o,onEntryFocus:c,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,disableOutsideScroll:y,..._}=s,v=BM(Rv,n),j=$$(Rv,n),w=R0e(n),S=vit(n),A=tFt(n),[E,O]=N.useState(null),D=N.useRef(null),I=ji(t,D,v.onContentChange),F=N.useRef(0),z=N.useRef(""),H=N.useRef(0),Z=N.useRef(null),Y=N.useRef("right"),W=N.useRef(0),ee=y?z$:N.Fragment,se=y?{as:dFt,allowPinchZoom:!0}:void 0,oe=ce=>{var Me,Pe;const me=z.current+ce,le=A().filter(Re=>!Re.disabled),ve=document.activeElement,ge=(Me=le.find(Re=>Re.ref.current===ve))==null?void 0:Me.textValue,Te=le.map(Re=>Re.textValue),Ie=wFt(Te,me,ge),Ce=(Pe=le.find(Re=>Re.textValue===Ie))==null?void 0:Pe.ref.current;(function Re(Ae){z.current=Ae,window.clearTimeout(F.current),Ae!==""&&(F.current=window.setTimeout(()=>Re(""),1e3))})(me),Ce&&setTimeout(()=>Ce.focus())};N.useEffect(()=>()=>window.clearTimeout(F.current),[]),M0e();const he=N.useCallback(ce=>{var le,ve;return Y.current===((le=Z.current)==null?void 0:le.side)&&NFt(ce,(ve=Z.current)==null?void 0:ve.area)},[]);return e.jsx(oFt,{scope:n,searchRef:z,onItemEnter:N.useCallback(ce=>{he(ce)&&ce.preventDefault()},[he]),onItemLeave:N.useCallback(ce=>{var me;he(ce)||((me=D.current)==null||me.focus(),O(null))},[he]),onTriggerLeave:N.useCallback(ce=>{he(ce)&&ce.preventDefault()},[he]),pointerGraceTimerRef:H,onPointerGraceIntentChange:N.useCallback(ce=>{Z.current=ce},[]),children:e.jsx(ee,{...se,children:e.jsx(O$,{asChild:!0,trapped:a,onMountAutoFocus:xr(i,ce=>{var me;ce.preventDefault(),(me=D.current)==null||me.focus({preventScroll:!0})}),onUnmountAutoFocus:l,children:e.jsx(O4,{asChild:!0,disableOutsidePointerEvents:o,onEscapeKeyDown:d,onPointerDownOutside:u,onFocusOutside:h,onInteractOutside:p,onDismiss:f,children:e.jsx(I0e,{asChild:!0,...S,dir:j.dir,orientation:"vertical",loop:r,currentTabStopId:E,onCurrentTabStopIdChange:O,onEntryFocus:xr(c,ce=>{j.isUsingKeyboardRef.current||ce.preventDefault()}),preventScrollOnEntryFocus:!0,children:e.jsx(P$,{role:"menu","aria-orientation":"vertical","data-state":zit(v.open),"data-radix-menu-content":"",dir:j.dir,...w,..._,ref:I,style:{outline:"none",..._.style},onKeyDown:xr(_.onKeyDown,ce=>{const le=ce.target.closest("[data-radix-menu-content]")===ce.currentTarget,ve=ce.ctrlKey||ce.altKey||ce.metaKey,ge=ce.key.length===1;le&&(ce.key==="Tab"&&ce.preventDefault(),!ve&&ge&&oe(ce.key));const Te=D.current;if(ce.target!==Te||!XOt.includes(ce.key))return;ce.preventDefault();const Ce=A().filter(Me=>!Me.disabled).map(Me=>Me.ref.current);git.includes(ce.key)&&Ce.reverse(),bFt(Ce)}),onBlur:xr(s.onBlur,ce=>{ce.currentTarget.contains(ce.target)||(window.clearTimeout(F.current),z.current="")}),onPointerMove:xr(s.onPointerMove,Xz(ce=>{const me=ce.target,le=W.current!==ce.clientX;if(ce.currentTarget.contains(me)&&le){const ve=ce.clientX>W.current?"right":"left";Y.current=ve,W.current=ce.clientX}}))})})})})})})});jit.displayName=Rv;var uFt="MenuGroup",vAe=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Yr.div,{role:"group",...r,ref:t})});vAe.displayName=uFt;var hFt="MenuLabel",Nit=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Yr.div,{...r,ref:t})});Nit.displayName=hFt;var qpe="MenuItem",Mze="menu.itemSelect",O0e=N.forwardRef((s,t)=>{const{disabled:n=!1,onSelect:r,...a}=s,i=N.useRef(null),l=$$(qpe,s.__scopeMenu),o=gAe(qpe,s.__scopeMenu),c=ji(t,i),d=N.useRef(!1),u=()=>{const h=i.current;if(!n&&h){const p=new CustomEvent(Mze,{bubbles:!0,cancelable:!0});h.addEventListener(Mze,f=>r==null?void 0:r(f),{once:!0}),$Ee(h,p),p.defaultPrevented?d.current=!1:l.onClose()}};return e.jsx(kit,{...a,ref:c,disabled:n,onClick:xr(s.onClick,u),onPointerDown:h=>{var p;(p=s.onPointerDown)==null||p.call(s,h),d.current=!0},onPointerUp:xr(s.onPointerUp,h=>{var p;d.current||(p=h.currentTarget)==null||p.click()}),onKeyDown:xr(s.onKeyDown,h=>{const p=o.searchRef.current!=="";n||p&&h.key===" "||a4e.includes(h.key)&&(h.currentTarget.click(),h.preventDefault())})})});O0e.displayName=qpe;var kit=N.forwardRef((s,t)=>{const{__scopeMenu:n,disabled:r=!1,textValue:a,...i}=s,l=gAe(qpe,n),o=vit(n),c=N.useRef(null),d=ji(t,c),[u,h]=N.useState(!1),[p,f]=N.useState("");return N.useEffect(()=>{const y=c.current;y&&f((y.textContent??"").trim())},[i.children]),e.jsx(Qz.ItemSlot,{scope:n,disabled:r,textValue:a??p,children:e.jsx(P0e,{asChild:!0,...o,focusable:!r,children:e.jsx(Yr.div,{role:"menuitem","data-highlighted":u?"":void 0,"aria-disabled":r||void 0,"data-disabled":r?"":void 0,...i,ref:d,onPointerMove:xr(s.onPointerMove,Xz(y=>{r?l.onItemLeave(y):(l.onItemEnter(y),y.defaultPrevented||y.currentTarget.focus({preventScroll:!0}))})),onPointerLeave:xr(s.onPointerLeave,Xz(y=>l.onItemLeave(y))),onFocus:xr(s.onFocus,()=>h(!0)),onBlur:xr(s.onBlur,()=>h(!1))})})})}),mFt="MenuCheckboxItem",Sit=N.forwardRef((s,t)=>{const{checked:n=!1,onCheckedChange:r,...a}=s;return e.jsx(Mit,{scope:s.__scopeMenu,checked:n,children:e.jsx(O0e,{role:"menuitemcheckbox","aria-checked":Vpe(n)?"mixed":n,...a,ref:t,"data-state":_Ae(n),onSelect:xr(a.onSelect,()=>r==null?void 0:r(Vpe(n)?!0:!n),{checkForDefaultPrevented:!1})})})});Sit.displayName=mFt;var Cit="MenuRadioGroup",[pFt,fFt]=zM(Cit,{value:void 0,onValueChange:()=>{}}),Tit=N.forwardRef((s,t)=>{const{value:n,onValueChange:r,...a}=s,i=rh(r);return e.jsx(pFt,{scope:s.__scopeMenu,value:n,onValueChange:i,children:e.jsx(vAe,{...a,ref:t})})});Tit.displayName=Cit;var Eit="MenuRadioItem",Ait=N.forwardRef((s,t)=>{const{value:n,...r}=s,a=fFt(Eit,s.__scopeMenu),i=n===a.value;return e.jsx(Mit,{scope:s.__scopeMenu,checked:i,children:e.jsx(O0e,{role:"menuitemradio","aria-checked":i,...r,ref:t,"data-state":_Ae(i),onSelect:xr(r.onSelect,()=>{var l;return(l=a.onValueChange)==null?void 0:l.call(a,n)},{checkForDefaultPrevented:!1})})})});Ait.displayName=Eit;var bAe="MenuItemIndicator",[Mit,xFt]=zM(bAe,{checked:!1}),Iit=N.forwardRef((s,t)=>{const{__scopeMenu:n,forceMount:r,...a}=s,i=xFt(bAe,n);return e.jsx(Lh,{present:r||Vpe(i.checked)||i.checked===!0,children:e.jsx(Yr.span,{...a,ref:t,"data-state":_Ae(i.checked)})})});Iit.displayName=bAe;var gFt="MenuSeparator",Pit=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s;return e.jsx(Yr.div,{role:"separator","aria-orientation":"horizontal",...r,ref:t})});Pit.displayName=gFt;var yFt="MenuArrow",Lit=N.forwardRef((s,t)=>{const{__scopeMenu:n,...r}=s,a=R0e(n);return e.jsx(L$,{...a,...r,ref:t})});Lit.displayName=yFt;var vFt="MenuSub",[Kpn,Dit]=zM(vFt),JF="MenuSubTrigger",Rit=N.forwardRef((s,t)=>{const n=BM(JF,s.__scopeMenu),r=$$(JF,s.__scopeMenu),a=Dit(JF,s.__scopeMenu),i=gAe(JF,s.__scopeMenu),l=N.useRef(null),{pointerGraceTimerRef:o,onPointerGraceIntentChange:c}=i,d={__scopeMenu:s.__scopeMenu},u=N.useCallback(()=>{l.current&&window.clearTimeout(l.current),l.current=null},[]);return N.useEffect(()=>u,[u]),N.useEffect(()=>{const h=o.current;return()=>{window.clearTimeout(h),c(null)}},[o,c]),e.jsx(fAe,{asChild:!0,...d,children:e.jsx(kit,{id:a.triggerId,"aria-haspopup":"menu","aria-expanded":n.open,"aria-controls":a.contentId,"data-state":zit(n.open),...s,ref:iN(t,a.onTriggerChange),onClick:h=>{var p;(p=s.onClick)==null||p.call(s,h),!(s.disabled||h.defaultPrevented)&&(h.currentTarget.focus(),n.open||n.onOpenChange(!0))},onPointerMove:xr(s.onPointerMove,Xz(h=>{i.onItemEnter(h),!h.defaultPrevented&&!s.disabled&&!n.open&&!l.current&&(i.onPointerGraceIntentChange(null),l.current=window.setTimeout(()=>{n.onOpenChange(!0),u()},100))})),onPointerLeave:xr(s.onPointerLeave,Xz(h=>{var f,y;u();const p=(f=n.content)==null?void 0:f.getBoundingClientRect();if(p){const _=(y=n.content)==null?void 0:y.dataset.side,v=_==="right",j=v?-5:5,w=p[v?"left":"right"],S=p[v?"right":"left"];i.onPointerGraceIntentChange({area:[{x:h.clientX+j,y:h.clientY},{x:w,y:p.top},{x:S,y:p.top},{x:S,y:p.bottom},{x:w,y:p.bottom}],side:_}),window.clearTimeout(o.current),o.current=window.setTimeout(()=>i.onPointerGraceIntentChange(null),300)}else{if(i.onTriggerLeave(h),h.defaultPrevented)return;i.onPointerGraceIntentChange(null)}})),onKeyDown:xr(s.onKeyDown,h=>{var f;const p=i.searchRef.current!=="";s.disabled||p&&h.key===" "||JOt[r.dir].includes(h.key)&&(n.onOpenChange(!0),(f=n.content)==null||f.focus(),h.preventDefault())})})})});Rit.displayName=JF;var Oit="MenuSubContent",Fit=N.forwardRef((s,t)=>{const n=_it(Rv,s.__scopeMenu),{forceMount:r=n.forceMount,...a}=s,i=BM(Rv,s.__scopeMenu),l=$$(Rv,s.__scopeMenu),o=Dit(Oit,s.__scopeMenu),c=N.useRef(null),d=ji(t,c);return e.jsx(Qz.Provider,{scope:s.__scopeMenu,children:e.jsx(Lh,{present:r||i.open,children:e.jsx(Qz.Slot,{scope:s.__scopeMenu,children:e.jsx(yAe,{id:o.contentId,"aria-labelledby":o.triggerId,...a,ref:d,align:"start",side:l.dir==="rtl"?"left":"right",disableOutsidePointerEvents:!1,disableOutsideScroll:!1,trapFocus:!1,onOpenAutoFocus:u=>{var h;l.isUsingKeyboardRef.current&&((h=c.current)==null||h.focus()),u.preventDefault()},onCloseAutoFocus:u=>u.preventDefault(),onFocusOutside:xr(s.onFocusOutside,u=>{u.target!==o.trigger&&i.onOpenChange(!1)}),onEscapeKeyDown:xr(s.onEscapeKeyDown,u=>{l.onClose(),u.preventDefault()}),onKeyDown:xr(s.onKeyDown,u=>{var f;const h=u.currentTarget.contains(u.target),p=eFt[l.dir].includes(u.key);h&&p&&(i.onOpenChange(!1),(f=o.trigger)==null||f.focus(),u.preventDefault())})})})})})});Fit.displayName=Oit;function zit(s){return s?"open":"closed"}function Vpe(s){return s==="indeterminate"}function _Ae(s){return Vpe(s)?"indeterminate":s?"checked":"unchecked"}function bFt(s){const t=document.activeElement;for(const n of s)if(n===t||(n.focus(),document.activeElement!==t))return}function _Ft(s,t){return s.map((n,r)=>s[(t+r)%s.length])}function wFt(s,t,n){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?s.indexOf(n):-1;let l=_Ft(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==n));const c=l.find(d=>d.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function jFt(s,t){const{x:n,y:r}=s;let a=!1;for(let i=0,l=t.length-1;ir!=p>r&&n<(h-d)*(r-u)/(p-u)+d&&(a=!a)}return a}function NFt(s,t){if(!t)return!1;const n={x:s.clientX,y:s.clientY};return jFt(n,t)}function Xz(s){return t=>t.pointerType==="mouse"?s(t):void 0}var kFt=bit,SFt=fAe,CFt=wit,TFt=jit,EFt=vAe,AFt=Nit,MFt=O0e,IFt=Sit,PFt=Tit,LFt=Ait,DFt=Iit,RFt=Pit,OFt=Lit,FFt=Rit,zFt=Fit,F0e="DropdownMenu",[BFt,Ypn]=uu(F0e,[yit]),ig=yit(),[$Ft,Bit]=BFt(F0e),$it=s=>{const{__scopeDropdownMenu:t,children:n,dir:r,open:a,defaultOpen:i,onOpenChange:l,modal:o=!0}=s,c=ig(t),d=N.useRef(null),[u,h]=cm({prop:a,defaultProp:i??!1,onChange:l,caller:F0e});return e.jsx($Ft,{scope:t,triggerId:om(),triggerRef:d,contentId:om(),open:u,onOpenChange:h,onOpenToggle:N.useCallback(()=>h(p=>!p),[h]),modal:o,children:e.jsx(kFt,{...c,open:u,onOpenChange:h,dir:r,modal:o,children:n})})};$it.displayName=F0e;var Uit="DropdownMenuTrigger",qit=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,disabled:r=!1,...a}=s,i=Bit(Uit,n),l=ig(n);return e.jsx(SFt,{asChild:!0,...l,children:e.jsx(Yr.button,{type:"button",id:i.triggerId,"aria-haspopup":"menu","aria-expanded":i.open,"aria-controls":i.open?i.contentId:void 0,"data-state":i.open?"open":"closed","data-disabled":r?"":void 0,disabled:r,...a,ref:iN(t,i.triggerRef),onPointerDown:xr(s.onPointerDown,o=>{!r&&o.button===0&&o.ctrlKey===!1&&(i.onOpenToggle(),i.open||o.preventDefault())}),onKeyDown:xr(s.onKeyDown,o=>{r||(["Enter"," "].includes(o.key)&&i.onOpenToggle(),o.key==="ArrowDown"&&i.onOpenChange(!0),["Enter"," ","ArrowDown"].includes(o.key)&&o.preventDefault())})})})});qit.displayName=Uit;var UFt="DropdownMenuPortal",Vit=s=>{const{__scopeDropdownMenu:t,...n}=s,r=ig(t);return e.jsx(CFt,{...r,...n})};Vit.displayName=UFt;var Hit="DropdownMenuContent",Git=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=Bit(Hit,n),i=ig(n),l=N.useRef(!1);return e.jsx(TFt,{id:a.contentId,"aria-labelledby":a.triggerId,...i,...r,ref:t,onCloseAutoFocus:xr(s.onCloseAutoFocus,o=>{var c;l.current||(c=a.triggerRef.current)==null||c.focus(),l.current=!1,o.preventDefault()}),onInteractOutside:xr(s.onInteractOutside,o=>{const c=o.detail.originalEvent,d=c.button===0&&c.ctrlKey===!0,u=c.button===2||d;(!a.modal||u)&&(l.current=!0)}),style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});Git.displayName=Hit;var qFt="DropdownMenuGroup",VFt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(EFt,{...a,...r,ref:t})});VFt.displayName=qFt;var HFt="DropdownMenuLabel",Wit=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(AFt,{...a,...r,ref:t})});Wit.displayName=HFt;var GFt="DropdownMenuItem",Kit=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(MFt,{...a,...r,ref:t})});Kit.displayName=GFt;var WFt="DropdownMenuCheckboxItem",Yit=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(IFt,{...a,...r,ref:t})});Yit.displayName=WFt;var KFt="DropdownMenuRadioGroup",YFt=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(PFt,{...a,...r,ref:t})});YFt.displayName=KFt;var ZFt="DropdownMenuRadioItem",Zit=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(LFt,{...a,...r,ref:t})});Zit.displayName=ZFt;var QFt="DropdownMenuItemIndicator",Qit=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(DFt,{...a,...r,ref:t})});Qit.displayName=QFt;var XFt="DropdownMenuSeparator",Xit=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(RFt,{...a,...r,ref:t})});Xit.displayName=XFt;var JFt="DropdownMenuArrow",e7t=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(OFt,{...a,...r,ref:t})});e7t.displayName=JFt;var t7t="DropdownMenuSubTrigger",Jit=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(FFt,{...a,...r,ref:t})});Jit.displayName=t7t;var s7t="DropdownMenuSubContent",eot=N.forwardRef((s,t)=>{const{__scopeDropdownMenu:n,...r}=s,a=ig(n);return e.jsx(zFt,{...a,...r,ref:t,style:{...s.style,"--radix-dropdown-menu-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-dropdown-menu-content-available-width":"var(--radix-popper-available-width)","--radix-dropdown-menu-content-available-height":"var(--radix-popper-available-height)","--radix-dropdown-menu-trigger-width":"var(--radix-popper-anchor-width)","--radix-dropdown-menu-trigger-height":"var(--radix-popper-anchor-height)"}})});eot.displayName=s7t;var n7t=$it,r7t=qit,a7t=Vit,tot=Git,sot=Wit,not=Kit,rot=Yit,aot=Zit,iot=Qit,oot=Xit,lot=Jit,cot=eot;const Mc=n7t,Ic=r7t,i7t=N.forwardRef(({className:s,inset:t,children:n,...r},a)=>e.jsxs(lot,{ref:a,className:Mt("flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none data-[state=open]:bg-accent focus:bg-accent",t&&"pl-8",s),...r,children:[n,e.jsx(ga,{className:"ml-auto h-4 w-4"})]}));i7t.displayName=lot.displayName;const o7t=N.forwardRef(({className:s,...t},n)=>e.jsx(cot,{ref:n,className:Mt("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}));o7t.displayName=cot.displayName;const gc=N.forwardRef(({className:s,sideOffset:t=4,...n},r)=>e.jsx(a7t,{children:e.jsx(tot,{ref:r,sideOffset:t,className:Mt("z-50 min-w-[8rem] overflow-hidden rounded-md border bg-popover p-1 text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...n})}));gc.displayName=tot.displayName;const Kr=N.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(not,{ref:r,className:Mt("relative flex cursor-default select-none items-center rounded-sm px-2 py-1.5 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",t&&"pl-8",s),...n}));Kr.displayName=not.displayName;const l7t=N.forwardRef(({className:s,children:t,checked:n,...r},a)=>e.jsxs(rot,{ref:a,className:Mt("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),checked:n,...r,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(iot,{children:e.jsx(Lr,{className:"h-4 w-4"})})}),t]}));l7t.displayName=rot.displayName;const c7t=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(aot,{ref:r,className:Mt("relative flex cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none transition-colors data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(iot,{children:e.jsx(am,{className:"h-2 w-2 fill-current"})})}),t]}));c7t.displayName=aot.displayName;const cM=N.forwardRef(({className:s,inset:t,...n},r)=>e.jsx(sot,{ref:r,className:Mt("px-2 py-1.5 text-sm font-semibold",t&&"pl-8",s),...n}));cM.displayName=sot.displayName;const Kg=N.forwardRef(({className:s,...t},n)=>e.jsx(oot,{ref:n,className:Mt("-mx-1 my-1 h-px bg-muted",s),...t}));Kg.displayName=oot.displayName;const d7t=()=>{const{isAssistant:s,actingAsAgent:t,assignedAgents:n,setActingAsAgent:r,isActingAsSelf:a,setActingAsSelf:i}=mAe();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(Wi,{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(An,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"font-medium text-sm",children:"Acting as"})]}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"secondary",size:"sm",className:"gap-2 bg-primary-foreground/20 hover:bg-primary-foreground/30 text-primary-foreground border-0",children:[a?e.jsxs(e.Fragment,{children:[e.jsx(Wi,{className:"h-4 w-4"}),e.jsx("strong",{children:"My Account"})]}):t?e.jsxs(e.Fragment,{children:[e.jsxs(Jr,{className:"h-5 w-5",children:[e.jsx(ti,{src:t.avatar_url||void 0}),e.jsx(ea,{className:"text-[10px] bg-primary-foreground/30",children:l(t.name)})]}),e.jsx("strong",{children:t.name})]}):e.jsx("strong",{children:"Select..."}),e.jsx(ao,{className:"h-3 w-3"})]})}),e.jsxs(gc,{align:"start",className:"z-[2147483647]",children:[e.jsxs(Kr,{onClick:i,className:"gap-2",children:[e.jsx(Wi,{className:"h-4 w-4"}),e.jsx("span",{children:"My Account"}),a&&e.jsx(Ue,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]}),e.jsx(Kg,{}),n.map(o=>e.jsxs(Kr,{onClick:()=>r(o),className:"gap-2",children:[e.jsxs(Jr,{className:"h-6 w-6",children:[e.jsx(ti,{src:o.avatar_url||void 0}),e.jsx(ea,{className:"text-[10px]",children:l(o.name)})]}),e.jsx("span",{children:o.name}),!a&&o.id===(t==null?void 0:t.id)&&e.jsx(Ue,{variant:"secondary",className:"ml-auto text-[10px]",children:"Current"})]},o.id))]})]})]}),e.jsx(Ue,{variant:"secondary",className:"bg-primary-foreground/20 text-primary-foreground border-0 text-xs",children:a?"Personal Mode":"Assistant Mode"})]})})},nn=({children:s,requireAdmin:t=!1,requireBrokerageManager:n=!1})=>{const{user:r,loading:a,rolesLoading:i,isAdmin:l,isBrokerageManager:o}=vs(),c=Xl();if(a||(t||n)&&i)return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading..."})]})});if(!r){const d=c.pathname+c.search+c.hash;return d&&d!=="/auth"&&sessionStorage.setItem("redirectAfterLogin",d),e.jsx(o4,{to:"/auth",replace:!0})}return t&&!l?e.jsx(o4,{to:"/dashboard",replace:!0}):n&&!o&&!l?e.jsx(o4,{to:"/dashboard",replace:!0}):e.jsx(e.Fragment,{children:s})};var wAe={};(function s(t,n,r,a){var i=!!(t.Worker&&t.Blob&&t.Promise&&t.OffscreenCanvas&&t.OffscreenCanvasRenderingContext2D&&t.HTMLCanvasElement&&t.HTMLCanvasElement.prototype.transferControlToOffscreen&&t.URL&&t.URL.createObjectURL),l=typeof Path2D=="function"&&typeof DOMMatrix=="function",o=function(){if(!t.OffscreenCanvas)return!1;try{var me=new OffscreenCanvas(1,1),le=me.getContext("2d");le.fillRect(0,0,1,1);var ve=me.transferToImageBitmap();le.createPattern(ve,"no-repeat")}catch{return!1}return!0}();function c(){}function d(me){var le=n.exports.Promise,ve=le!==void 0?le:t.Promise;return typeof ve=="function"?new ve(me):(me(c,c),null)}var u=function(me,le){return{transform:function(ve){if(me)return ve;if(le.has(ve))return le.get(ve);var ge=new OffscreenCanvas(ve.width,ve.height),Te=ge.getContext("2d");return Te.drawImage(ve,0,0),le.set(ve,ge),ge},clear:function(){le.clear()}}}(o,new Map),h=function(){var me=Math.floor(16.666666666666668),le,ve,ge={},Te=0;return typeof requestAnimationFrame=="function"&&typeof cancelAnimationFrame=="function"?(le=function(Ie){var Ce=Math.random();return ge[Ce]=requestAnimationFrame(function Me(Pe){Te===Pe||Te+me-1{const{data:t,error:n}=await q.from("celebration_queue").select("*").eq("user_id",s.id).is("seen_at",null).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!(s!=null&&s.id),refetchOnWindowFocus:!0,staleTime:0})}function h7t(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("celebration_queue").update({seen_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}function m7t(){const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{const{error:r}=await q.from("celebration_queue").insert({user_id:n.user_id,celebration_type:n.celebration_type,title:n.title,message:n.message||null,points_amount:n.points_amount||null,created_by:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["celebrations"]})}})}var z0e="Dialog",[dot,uot]=uu(z0e),[p7t,Tb]=dot(z0e),hot=s=>{const{__scopeDialog:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!0}=s,o=N.useRef(null),c=N.useRef(null),[d,u]=cm({prop:r,defaultProp:a??!1,onChange:i,caller:z0e});return e.jsx(p7t,{scope:t,triggerRef:o,contentRef:c,contentId:om(),titleId:om(),descriptionId:om(),open:d,onOpenChange:u,onOpenToggle:N.useCallback(()=>u(h=>!h),[u]),modal:l,children:n})};hot.displayName=z0e;var mot="DialogTrigger",pot=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Tb(mot,n),i=ji(t,a.triggerRef);return e.jsx(Yr.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":kAe(a.open),...r,ref:i,onClick:xr(s.onClick,a.onOpenToggle)})});pot.displayName=mot;var jAe="DialogPortal",[f7t,fot]=dot(jAe,{forceMount:void 0}),xot=s=>{const{__scopeDialog:t,forceMount:n,children:r,container:a}=s,i=Tb(jAe,t);return e.jsx(f7t,{scope:t,forceMount:n,children:N.Children.map(r,l=>e.jsx(Lh,{present:n||i.open,children:e.jsx(jD,{asChild:!0,container:a,children:l})}))})};xot.displayName=jAe;var Hpe="DialogOverlay",got=N.forwardRef((s,t)=>{const n=fot(Hpe,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=Tb(Hpe,s.__scopeDialog);return i.modal?e.jsx(Lh,{present:r||i.open,children:e.jsx(g7t,{...a,ref:t})}):null});got.displayName=Hpe;var x7t=v4("DialogOverlay.RemoveScroll"),g7t=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Tb(Hpe,n);return e.jsx(z$,{as:x7t,allowPinchZoom:!0,shards:[a.contentRef],children:e.jsx(Yr.div,{"data-state":kAe(a.open),...r,ref:t,style:{pointerEvents:"auto",...r.style}})})}),dM="DialogContent",yot=N.forwardRef((s,t)=>{const n=fot(dM,s.__scopeDialog),{forceMount:r=n.forceMount,...a}=s,i=Tb(dM,s.__scopeDialog);return e.jsx(Lh,{present:r||i.open,children:i.modal?e.jsx(y7t,{...a,ref:t}):e.jsx(v7t,{...a,ref:t})})});yot.displayName=dM;var y7t=N.forwardRef((s,t)=>{const n=Tb(dM,s.__scopeDialog),r=N.useRef(null),a=ji(t,n.contentRef,r);return N.useEffect(()=>{const i=r.current;if(i)return L0e(i)},[]),e.jsx(vot,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:xr(s.onCloseAutoFocus,i=>{var l;i.preventDefault(),(l=n.triggerRef.current)==null||l.focus()}),onPointerDownOutside:xr(s.onPointerDownOutside,i=>{const l=i.detail.originalEvent,o=l.button===0&&l.ctrlKey===!0;(l.button===2||o)&&i.preventDefault()}),onFocusOutside:xr(s.onFocusOutside,i=>i.preventDefault())})}),v7t=N.forwardRef((s,t)=>{const n=Tb(dM,s.__scopeDialog),r=N.useRef(!1),a=N.useRef(!1);return e.jsx(vot,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(r.current||(o=n.triggerRef.current)==null||o.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),vot=N.forwardRef((s,t)=>{const{__scopeDialog:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,...l}=s,o=Tb(dM,n),c=N.useRef(null),d=ji(t,c);return M0e(),e.jsxs(e.Fragment,{children:[e.jsx(O$,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(O4,{role:"dialog",id:o.contentId,"aria-describedby":o.descriptionId,"aria-labelledby":o.titleId,"data-state":kAe(o.open),...l,ref:d,onDismiss:()=>o.onOpenChange(!1)})}),e.jsxs(e.Fragment,{children:[e.jsx(_7t,{titleId:o.titleId}),e.jsx(j7t,{contentRef:c,descriptionId:o.descriptionId})]})]})}),NAe="DialogTitle",bot=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Tb(NAe,n);return e.jsx(Yr.h2,{id:a.titleId,...r,ref:t})});bot.displayName=NAe;var _ot="DialogDescription",wot=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Tb(_ot,n);return e.jsx(Yr.p,{id:a.descriptionId,...r,ref:t})});wot.displayName=_ot;var jot="DialogClose",Not=N.forwardRef((s,t)=>{const{__scopeDialog:n,...r}=s,a=Tb(jot,n);return e.jsx(Yr.button,{type:"button",...r,ref:t,onClick:xr(s.onClick,()=>a.onOpenChange(!1))})});Not.displayName=jot;function kAe(s){return s?"open":"closed"}var kot="DialogTitleWarning",[b7t,Sot]=jAt(kot,{contentName:dM,titleName:NAe,docsSlug:"dialog"}),_7t=({titleId:s})=>{const t=Sot(kot),n=`\`${t.contentName}\` requires a \`${t.titleName}\` for the component to be accessible for screen reader users. If you want to hide the \`${t.titleName}\`, you can wrap it with our VisuallyHidden component. For more information, see https://radix-ui.com/primitives/docs/components/${t.docsSlug}`;return N.useEffect(()=>{s&&(document.getElementById(s)||console.error(n))},[n,s]),null},w7t="DialogDescriptionWarning",j7t=({contentRef:s,descriptionId:t})=>{const r=`Warning: Missing \`Description\` or \`aria-describedby={undefined}\` for {${Sot(w7t).contentName}}.`;return N.useEffect(()=>{var i;const a=(i=s.current)==null?void 0:i.getAttribute("aria-describedby");t&&a&&(document.getElementById(t)||console.warn(r))},[r,s,t]),null},B0e=hot,SAe=pot,$0e=xot,PD=got,LD=yot,U$=bot,q$=wot,V$=Not;const _s=B0e,ki=SAe,N7t=$0e,Zpn=V$,Cot=N.forwardRef(({className:s,...t},n)=>e.jsx(PD,{ref:n,className:Mt("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}));Cot.displayName=PD.displayName;const bs=N.forwardRef(({className:s,children:t,overlayClassName:n,...r},a)=>e.jsxs(N7t,{children:[e.jsx(Cot,{className:n}),e.jsxs(LD,{ref:a,className:Mt("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...r,children:[t,e.jsxs(V$,{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($n,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));bs.displayName=LD.displayName;const js=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col space-y-1.5 text-center sm:text-left",s),...t});js.displayName="DialogHeader";const Xn=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Xn.displayName="DialogFooter";const ws=N.forwardRef(({className:s,...t},n)=>e.jsx(U$,{ref:n,className:Mt("text-lg font-semibold leading-none tracking-tight",s),...t}));ws.displayName=U$.displayName;const Jn=N.forwardRef(({className:s,...t},n)=>e.jsx(q$,{ref:n,className:Mt("text-sm text-muted-foreground",s),...t}));Jn.displayName=q$.displayName;const k7t={points_earned:xo,listing_created:Or,deal_closed:Yl,custom:oa},Pze={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"},Lze=()=>{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 S7t(){const{user:s}=vs(),t=Kt(),{data:n}=u7t(),r=h7t(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=N.useCallback(()=>{const f=Date.now()+3e3,y={startVelocity:30,spread:360,ticks:60,zIndex:9999},_=(j,w)=>Math.random()*(w-j)+j,v=setInterval(()=>{const j=f-Date.now();if(j<=0){clearInterval(v);return}const w=50*(j/3e3);Ize({...y,particleCount:w,origin:{x:_(.1,.3),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]}),Ize({...y,particleCount:w,origin:{x:_(.7,.9),y:Math.random()-.2},colors:["#ff6b6b","#feca57","#48dbfb","#ff9ff3","#54a0ff","#5f27cd"]})},250)},[]);N.useEffect(()=>{Lze()||n&&n.length>0&&!a&&(i(n[0]),o(!0),setTimeout(c,100))},[n,a,c]);const d=async()=>{if(a){const p=a.id;o(!1),i(null),t.setQueryData(["celebrations","pending",s==null?void 0:s.id],f=>(f==null?void 0:f.filter(y=>y.id!==p))??[]),await r.mutateAsync(p)}};if(Lze()||!a)return null;const u=k7t[a.celebration_type]||oa,h=Pze[a.celebration_type]||Pze.custom;return e.jsx(_s,{open:l,onOpenChange:p=>!p&&d(),children:e.jsxs(bs,{className:"sm:max-w-md text-center border-0 overflow-hidden",children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-br ${h} opacity-10`}),e.jsxs("div",{className:"relative z-10 py-6",children:[e.jsx("div",{className:"flex justify-center mb-4",children:e.jsx("div",{className:`w-20 h-20 rounded-full bg-gradient-to-br ${h} flex items-center justify-center animate-bounce`,children:e.jsx(u,{className:"w-10 h-10 text-white"})})}),e.jsxs("div",{className:"flex justify-center gap-1 mb-4",children:[e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse"}),e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-75"}),e.jsx(un,{className:"w-5 h-5 text-yellow-500 animate-pulse delay-150"})]}),e.jsxs("h2",{className:"text-2xl font-bold mb-2 bg-gradient-to-r from-primary to-secondary bg-clip-text text-transparent",children:["🎉 ",a.title]}),a.points_amount&&a.points_amount>0&&e.jsxs("div",{className:"text-4xl font-bold text-primary mb-2",children:["+",a.points_amount," points!"]}),a.message&&e.jsx("p",{className:"text-muted-foreground mb-6",children:a.message}),e.jsx(B,{onClick:d,className:"w-full",size:"lg",children:"Awesome! 🙌"}),n&&n.length>1&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-3",children:["+",n.length-1," more celebration",n.length>2?"s":""," waiting"]})]})]})})}function Ws({className:s,...t}){return e.jsx("div",{className:Mt("animate-pulse rounded-md bg-muted",s),...t})}const ye=N.forwardRef(({className:s,type:t,...n},r)=>e.jsx("input",{type:t,className:Mt("flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",s),ref:r,...n}));ye.displayName="Input";var C7t="Label",Tot=N.forwardRef((s,t)=>e.jsx(Yr.label,{...s,ref:t,onMouseDown:n=>{var a;n.target.closest("button, input, select, textarea")||((a=s.onMouseDown)==null||a.call(s,n),!n.defaultPrevented&&n.detail>1&&n.preventDefault())}}));Tot.displayName=C7t;var Eot=Tot;const T7t=OM("text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"),ne=N.forwardRef(({className:s,...t},n)=>e.jsx(Eot,{ref:n,className:Mt(T7t(),s),...t}));ne.displayName=Eot.displayName;const Ms=N.forwardRef(({className:s,...t},n)=>e.jsx("textarea",{className:Mt("flex min-h-[80px] w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50",s),ref:n,...t}));Ms.displayName="Textarea";var U0e="Tabs",[E7t,Qpn]=uu(U0e,[z4]),Aot=z4(),[A7t,CAe]=E7t(U0e),Mot=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,onValueChange:a,defaultValue:i,orientation:l="horizontal",dir:o,activationMode:c="automatic",...d}=s,u=vN(o),[h,p]=cm({prop:r,onChange:a,defaultProp:i??"",caller:U0e});return e.jsx(A7t,{scope:n,baseId:om(),value:h,onValueChange:p,orientation:l,dir:u,activationMode:c,children:e.jsx(Yr.div,{dir:u,"data-orientation":l,...d,ref:t})})});Mot.displayName=U0e;var Iot="TabsList",Pot=N.forwardRef((s,t)=>{const{__scopeTabs:n,loop:r=!0,...a}=s,i=CAe(Iot,n),l=Aot(n);return e.jsx(I0e,{asChild:!0,...l,orientation:i.orientation,dir:i.dir,loop:r,children:e.jsx(Yr.div,{role:"tablist","aria-orientation":i.orientation,...a,ref:t})})});Pot.displayName=Iot;var Lot="TabsTrigger",Dot=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,disabled:a=!1,...i}=s,l=CAe(Lot,n),o=Aot(n),c=Fot(l.baseId,r),d=zot(l.baseId,r),u=r===l.value;return e.jsx(P0e,{asChild:!0,...o,focusable:!a,active:u,children:e.jsx(Yr.button,{type:"button",role:"tab","aria-selected":u,"aria-controls":d,"data-state":u?"active":"inactive","data-disabled":a?"":void 0,disabled:a,id:c,...i,ref:t,onMouseDown:xr(s.onMouseDown,h=>{!a&&h.button===0&&h.ctrlKey===!1?l.onValueChange(r):h.preventDefault()}),onKeyDown:xr(s.onKeyDown,h=>{[" ","Enter"].includes(h.key)&&l.onValueChange(r)}),onFocus:xr(s.onFocus,()=>{const h=l.activationMode!=="manual";!u&&!a&&h&&l.onValueChange(r)})})})});Dot.displayName=Lot;var Rot="TabsContent",Oot=N.forwardRef((s,t)=>{const{__scopeTabs:n,value:r,forceMount:a,children:i,...l}=s,o=CAe(Rot,n),c=Fot(o.baseId,r),d=zot(o.baseId,r),u=r===o.value,h=N.useRef(u);return N.useEffect(()=>{const p=requestAnimationFrame(()=>h.current=!1);return()=>cancelAnimationFrame(p)},[]),e.jsx(Lh,{present:a||u,children:({present:p})=>e.jsx(Yr.div,{"data-state":u?"active":"inactive","data-orientation":o.orientation,role:"tabpanel","aria-labelledby":c,hidden:!p,id:d,tabIndex:0,...l,ref:t,style:{...s.style,animationDuration:h.current?"0s":void 0},children:p&&i})})});Oot.displayName=Rot;function Fot(s,t){return`${s}-trigger-${t}`}function zot(s,t){return`${s}-content-${t}`}var M7t=Mot,Bot=Pot,$ot=Dot,Uot=Oot;const Fr=M7t,Rr=N.forwardRef(({className:s,...t},n)=>e.jsx(Bot,{ref:n,className:Mt("inline-flex h-10 items-center justify-center rounded-md bg-muted p-1 text-muted-foreground",s),...t}));Rr.displayName=Bot.displayName;const Zt=N.forwardRef(({className:s,...t},n)=>e.jsx($ot,{ref:n,className:Mt("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}));Zt.displayName=$ot.displayName;const is=N.forwardRef(({className:s,...t},n)=>e.jsx(Uot,{ref:n,className:Mt("mt-2 ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2",s),...t}));is.displayName=Uot.displayName;const Jz="#0d0d0d",Gpe="#1a1a1a",af="#c9a84c",H$="#f0d78c",Tw={captured:"lup_lead_captured_v1",stickyDismissed:"lup_sticky_dismissed_v1",exitShown:"lup_exit_shown_v1",savedListings:"lup_saved_listings_v1"};async function q0e(s){const t={...s,source_page:typeof window<"u"?window.location.pathname:null,user_agent:typeof navigator<"u"?navigator.userAgent:null,referrer:typeof document<"u"?document.referrer:null},{data:n,error:r}=await q.functions.invoke("public-site-lead",{body:t});if(r)throw r;try{localStorage.setItem(Tw.captured,JSON.stringify({email:s.email,ts:Date.now()}))}catch{}return n}function TAe(){try{return!!localStorage.getItem(Tw.captured)}catch{return!1}}function I7t(){try{const s=localStorage.getItem(Tw.captured);return s?JSON.parse(s).email??null:null}catch{return null}}function EAe({open:s,onClose:t,children:n}){return N.useEffect(()=>{if(!s)return;const r=document.body.style.overflow;return document.body.style.overflow="hidden",()=>{document.body.style.overflow=r}},[s]),s?qx.createPortal(e.jsx("div",{className:"fixed inset-0 z-[100] flex items-center justify-center p-4 animate-in fade-in",style:{background:"rgba(0,0,0,0.82)",backdropFilter:"blur(6px)"},onClick:t,children:e.jsxs("div",{onClick:r=>r.stopPropagation(),className:"relative w-full max-w-md rounded-2xl overflow-hidden animate-in zoom-in-95",style:{background:`linear-gradient(180deg, ${Gpe} 0%, ${Jz} 100%)`,border:`1px solid ${af}33`,boxShadow:`0 30px 80px rgba(0,0,0,0.6), 0 0 0 1px ${af}22 inset`},children:[e.jsx("button",{onClick:t,className:"absolute right-4 top-4 z-10 rounded-full p-2 text-white/60 hover:text-white hover:bg-white/10 transition","aria-label":"Close",children:e.jsx($n,{className:"h-4 w-4"})}),n]})}),document.body):null}function AAe(){const[s,t]=N.useState({first_name:"",email:"",phone:"",area:""}),[n,r]=N.useState(!1),[a,i]=N.useState("");return{values:s,setValues:t,loading:n,setLoading:r,honeypot:a,setHoneypot:i}}function MAe({values:s,setValues:t,honeypot:n,setHoneypot:r,showPhone:a=!0,showArea:i=!0,areaPlaceholder:l="City, ZIP, or neighborhood"}){const o="w-full rounded-lg px-11 py-3 text-sm text-white placeholder:text-white/40 border transition focus:outline-none",c={background:"rgba(255,255,255,0.04)",borderColor:"rgba(255,255,255,0.12)"};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(Wi,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:"First name",value:s.first_name,onChange:d=>t({...s,first_name:d.target.value}),className:o,style:c})]}),e.jsxs("div",{className:"relative",children:[e.jsx(Gs,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:s.email,onChange:d=>t({...s,email:d.target.value}),className:o,style:c})]}),a&&e.jsxs("div",{className:"relative",children:[e.jsx(Cr,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:s.phone,onChange:d=>t({...s,phone:d.target.value}),className:o,style:c})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsx(ka,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-white/40"}),e.jsx("input",{type:"text",placeholder:l,value:s.area,onChange:d=>t({...s,area:d.target.value}),className:o,style:c})]}),e.jsx("input",{type:"text",value:n,onChange:d=>r(d.target.value),tabIndex:-1,autoComplete:"off",className:"absolute -left-[9999px] w-0 h-0 opacity-0","aria-hidden":"true"})]})}function IAe({children:s,disabled:t,onClick:n,type:r="button"}){return e.jsx("button",{type:r,disabled:t,onClick:n,className:"w-full rounded-lg py-3 text-sm font-semibold uppercase tracking-widest transition disabled:opacity-60 disabled:cursor-not-allowed",style:{background:`linear-gradient(180deg, ${H$} 0%, ${af} 100%)`,color:Jz,boxShadow:`0 8px 24px ${af}55`},children:s})}function Dze({open:s,onClose:t,initialCriteria:n}){const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=AAe(),[d,u]=N.useState(!1),h=async p=>{if(p.preventDefault(),!!r.email){l(!0);try{await q0e({lead_type:"new_listing_alerts",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:{...n||{},...r.area.trim()?{area:r.area.trim()}:{}}}),u(!0);try{localStorage.setItem(Tw.stickyDismissed,"1")}catch{}setTimeout(t,2200)}catch{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(EAe,{open:s,onClose:t,children:e.jsxs("div",{className:"p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(nm,{className:"h-4 w-4",style:{color:af}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:H$},children:"New Listing Alerts"})]}),e.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"Be the first to know."}),e.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"The best homes go before they hit the market. Get instant alerts the moment new listings match your search."}),d?e.jsxs("div",{className:"py-6 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full flex items-center justify-center",style:{background:`${af}22`,border:`1px solid ${af}55`},children:e.jsx(un,{className:"h-5 w-5",style:{color:af}})}),e.jsx("div",{className:"text-white font-medium",children:"You're on the list."}),e.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Check your inbox for confirmation."})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(MAe,{values:r,setValues:a,honeypot:o,setHoneypot:c}),e.jsx(IAe,{type:"submit",disabled:i||!r.email,children:i?"Activating…":"Activate Alerts"}),e.jsx("p",{className:"text-[10px] text-white/40 text-center leading-relaxed",children:"We respect your inbox. Unsubscribe any time."})]})]})})}function P7t(){const[s,t]=N.useState(!0),[n,r]=N.useState(!1);N.useEffect(()=>{try{const i=!!localStorage.getItem(Tw.stickyDismissed)||TAe();t(i)}catch{t(!1)}},[]);const a=()=>{t(!0);try{localStorage.setItem(Tw.stickyDismissed,"1")}catch{}};return s?e.jsx(Dze,{open:n,onClose:()=>r(!1)}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-40 animate-in slide-in-from-bottom",style:{background:`linear-gradient(180deg, ${Gpe} 0%, ${Jz} 100%)`,borderTop:`1px solid ${af}44`,boxShadow:"0 -8px 30px rgba(0,0,0,0.5)"},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 sm:px-6 py-3 flex items-center gap-3",children:[e.jsx("div",{className:"hidden sm:flex h-9 w-9 rounded-full items-center justify-center flex-shrink-0",style:{background:`${af}22`,border:`1px solid ${af}55`},children:e.jsx(nm,{className:"h-4 w-4",style:{color:af}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-white text-sm font-medium truncate",children:"Be the first to know when new homes hit the market"}),e.jsx("div",{className:"text-white/50 text-xs hidden sm:block",children:"Instant alerts. No spam. Unsubscribe anytime."})]}),e.jsx("button",{onClick:()=>r(!0),className:"rounded-lg px-4 py-2 text-xs font-semibold uppercase tracking-wider whitespace-nowrap transition hover:brightness-110",style:{background:`linear-gradient(180deg, ${H$} 0%, ${af} 100%)`,color:Jz},children:"Get Alerts"}),e.jsx("button",{onClick:a,className:"p-2 text-white/50 hover:text-white transition","aria-label":"Dismiss",children:e.jsx($n,{className:"h-4 w-4"})})]})}),e.jsx(Dze,{open:n,onClose:()=>r(!1)})]})}function L7t(){const[s,t]=N.useState(!1),n=N.useRef(!1);N.useEffect(()=>{try{if(sessionStorage.getItem(Tw.exitShown)||TAe())return}catch{}const p=setTimeout(()=>{n.current=!0},8e3),f=y=>{if(n.current&&!(y.clientY>0)){t(!0);try{sessionStorage.setItem(Tw.exitShown,"1")}catch{}window.removeEventListener("mouseleave",f),document.removeEventListener("mouseleave",f)}};return document.addEventListener("mouseleave",f),()=>{clearTimeout(p),document.removeEventListener("mouseleave",f)}},[]);const{values:r,setValues:a,loading:i,setLoading:l,honeypot:o,setHoneypot:c}=AAe(),[d,u]=N.useState(!1),h=async p=>{if(p.preventDefault(),!!r.email){l(!0);try{await q0e({lead_type:"exit_intent",email:r.email.trim().toLowerCase(),first_name:r.first_name.trim()||void 0,phone:r.phone.trim()||void 0,criteria:r.area.trim()?{area:r.area.trim()}:void 0}),u(!0),setTimeout(()=>t(!1),2200)}catch{ae.error("Something went wrong. Please try again.")}finally{l(!1)}}};return e.jsx(EAe,{open:s,onClose:()=>t(!1),children:e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"h-32 w-full",style:{background:`linear-gradient(135deg, ${Jz} 0%, ${Gpe} 60%, ${af} 130%)`},children:e.jsx("div",{className:"absolute top-4 left-6",children:e.jsx("span",{className:"text-[10px] uppercase tracking-[0.25em]",style:{color:H$},children:"Before You Go"})})}),e.jsxs("div",{className:"p-8 -mt-10",children:[e.jsx("div",{className:"mx-auto mb-5 h-16 w-16 rounded-full flex items-center justify-center",style:{background:Gpe,border:`1px solid ${af}55`,boxShadow:"0 8px 24px rgba(0,0,0,0.5)"},children:e.jsx(un,{className:"h-6 w-6",style:{color:af}})}),e.jsx("h2",{className:"text-2xl font-serif text-white text-center leading-tight mb-2",children:"Wait — get a fresh list of homes."}),e.jsx("p",{className:"text-sm text-white/60 text-center mb-6 leading-relaxed",children:"Drop your email and we'll send you a curated list of homes matching your area, updated weekly."}),d?e.jsxs("div",{className:"py-4 text-center",children:[e.jsx("div",{className:"text-white font-medium",children:"Sent — check your inbox."}),e.jsx("div",{className:"text-white/50 text-xs mt-1",children:"Your list is on its way."})]}):e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(MAe,{values:r,setValues:a,honeypot:o,setHoneypot:c,showPhone:!1}),e.jsx(IAe,{type:"submit",disabled:i||!r.email,children:i?"Sending…":"Send My List"})]})]})]})})}function D7t(){const[s,t]=N.useState([]);N.useEffect(()=>{try{const o=localStorage.getItem(Tw.savedListings);o&&t(JSON.parse(o))}catch{}},[]);const n=o=>{t(o);try{localStorage.setItem(Tw.savedListings,JSON.stringify(o))}catch{}},r=N.useCallback(o=>s.includes(o),[s]),a=o=>{s.includes(o)||n([...s,o])},i=o=>n(s.filter(c=>c!==o));return{ids:s,has:r,add:a,remove:i,toggle:o=>s.includes(o)?i(o):a(o)}}function R7t({listingId:s,listingAddress:t,className:n}){const{has:r,add:a,remove:i}=D7t(),l=r(s),[o,c]=N.useState(!1),d=()=>{if(l){i(s);return}if(TAe()){a(s),ae.success("Saved to your favorites"),q0e({lead_type:"saved_listing",email:I7t()||"unknown@local",listing_id:s,listing_address:t}).catch(()=>{});return}c(!0)};return e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:d,className:n,"aria-label":l?"Remove from favorites":"Save to favorites",children:e.jsx(gi,{className:`h-5 w-5 ${l?"fill-current":""}`})}),e.jsx(O7t,{open:o,onClose:()=>c(!1),listingId:s,listingAddress:t,onSaved:()=>a(s)})]})}function O7t({open:s,onClose:t,listingId:n,listingAddress:r,onSaved:a}){const{values:i,setValues:l,loading:o,setLoading:c,honeypot:d,setHoneypot:u}=AAe(),h=async p=>{if(p.preventDefault(),!!i.email){c(!0);try{await q0e({lead_type:"saved_listing",email:i.email.trim().toLowerCase(),first_name:i.first_name.trim()||void 0,phone:i.phone.trim()||void 0,listing_id:n,listing_address:r}),a(),ae.success("Saved to your favorites"),t()}catch{ae.error("Something went wrong. Please try again.")}finally{c(!1)}}};return e.jsx(EAe,{open:s,onClose:t,children:e.jsxs("div",{className:"p-8",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(gi,{className:"h-4 w-4",style:{color:af}}),e.jsx("span",{className:"text-xs uppercase tracking-[0.2em]",style:{color:H$},children:"Save This Home"})]}),e.jsx("h2",{className:"text-2xl font-serif text-white leading-tight mb-2",children:"One click to save."}),e.jsx("p",{className:"text-sm text-white/60 mb-6 leading-relaxed",children:"Get an alert if the price drops or the status changes. No spam — just the updates that matter."}),e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsx(MAe,{values:i,setValues:l,honeypot:d,setHoneypot:u}),e.jsx(IAe,{type:"submit",disabled:o||!i.email,children:o?"Saving…":"Save Home"})]})]})})}function eB(s,[t,n]){return Math.min(n,Math.max(t,s))}function G$(s){const t=N.useRef({value:s,previous:s});return N.useMemo(()=>(t.current.value!==s&&(t.current.previous=t.current.value,t.current.value=s),t.current.previous),[s])}var qot=["PageUp","PageDown"],Vot=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],Hot={"from-left":["Home","PageDown","ArrowDown","ArrowLeft"],"from-right":["Home","PageDown","ArrowDown","ArrowRight"],"from-bottom":["Home","PageDown","ArrowDown","ArrowLeft"],"from-top":["Home","PageDown","ArrowUp","ArrowLeft"]},DD="Slider",[i4e,F7t,z7t]=wD(DD),[Got,Xpn]=uu(DD,[z7t]),[B7t,V0e]=Got(DD),Wot=N.forwardRef((s,t)=>{const{name:n,min:r=0,max:a=100,step:i=1,orientation:l="horizontal",disabled:o=!1,minStepsBetweenThumbs:c=0,defaultValue:d=[r],value:u,onValueChange:h=()=>{},onValueCommit:p=()=>{},inverted:f=!1,form:y,..._}=s,v=N.useRef(new Set),j=N.useRef(0),S=l==="horizontal"?$7t:U7t,[A=[],E]=cm({prop:u,defaultProp:d,onChange:H=>{var Y;(Y=[...v.current][j.current])==null||Y.focus(),h(H)}}),O=N.useRef(A);function D(H){const Z=W7t(A,H);z(H,Z)}function I(H){z(H,j.current)}function F(){const H=O.current[j.current];A[j.current]!==H&&p(A)}function z(H,Z,{commit:Y}={commit:!1}){const W=Q7t(i),ee=X7t(Math.round((H-r)/i)*i+r,W),se=eB(ee,[r,a]);E((oe=[])=>{const he=H7t(oe,se,Z);if(Z7t(he,c*i)){j.current=he.indexOf(se);const ce=String(he)!==String(oe);return ce&&Y&&p(he),ce?he:oe}else return oe})}return e.jsx(B7t,{scope:s.__scopeSlider,name:n,disabled:o,min:r,max:a,valueIndexToChangeRef:j,thumbs:v.current,values:A,orientation:l,form:y,children:e.jsx(i4e.Provider,{scope:s.__scopeSlider,children:e.jsx(i4e.Slot,{scope:s.__scopeSlider,children:e.jsx(S,{"aria-disabled":o,"data-disabled":o?"":void 0,..._,ref:t,onPointerDown:xr(_.onPointerDown,()=>{o||(O.current=A)}),min:r,max:a,inverted:f,onSlideStart:o?void 0:D,onSlideMove:o?void 0:I,onSlideEnd:o?void 0:F,onHomeKeyDown:()=>!o&&z(r,0,{commit:!0}),onEndKeyDown:()=>!o&&z(a,A.length-1,{commit:!0}),onStepKeyDown:({event:H,direction:Z})=>{if(!o){const ee=qot.includes(H.key)||H.shiftKey&&Vot.includes(H.key)?10:1,se=j.current,oe=A[se],he=i*ee*Z;z(oe+he,se,{commit:!0})}}})})})})});Wot.displayName=DD;var[Kot,Yot]=Got(DD,{startEdge:"left",endEdge:"right",size:"width",direction:1}),$7t=N.forwardRef((s,t)=>{const{min:n,max:r,dir:a,inverted:i,onSlideStart:l,onSlideMove:o,onSlideEnd:c,onStepKeyDown:d,...u}=s,[h,p]=N.useState(null),f=ji(t,S=>p(S)),y=N.useRef(void 0),_=vN(a),v=_==="ltr",j=v&&!i||!v&&i;function w(S){const A=y.current||h.getBoundingClientRect(),E=[0,A.width],D=PAe(E,j?[n,r]:[r,n]);return y.current=A,D(S-A.left)}return e.jsx(Kot,{scope:s.__scopeSlider,startEdge:j?"left":"right",endEdge:j?"right":"left",direction:j?1:-1,size:"width",children:e.jsx(Zot,{dir:_,"data-orientation":"horizontal",...u,ref:f,style:{...u.style,"--radix-slider-thumb-transform":"translateX(-50%)"},onSlideStart:S=>{const A=w(S.clientX);l==null||l(A)},onSlideMove:S=>{const A=w(S.clientX);o==null||o(A)},onSlideEnd:()=>{y.current=void 0,c==null||c()},onStepKeyDown:S=>{const E=Hot[j?"from-left":"from-right"].includes(S.key);d==null||d({event:S,direction:E?-1:1})}})})}),U7t=N.forwardRef((s,t)=>{const{min:n,max:r,inverted:a,onSlideStart:i,onSlideMove:l,onSlideEnd:o,onStepKeyDown:c,...d}=s,u=N.useRef(null),h=ji(t,u),p=N.useRef(void 0),f=!a;function y(_){const v=p.current||u.current.getBoundingClientRect(),j=[0,v.height],S=PAe(j,f?[r,n]:[n,r]);return p.current=v,S(_-v.top)}return e.jsx(Kot,{scope:s.__scopeSlider,startEdge:f?"bottom":"top",endEdge:f?"top":"bottom",size:"height",direction:f?1:-1,children:e.jsx(Zot,{"data-orientation":"vertical",...d,ref:h,style:{...d.style,"--radix-slider-thumb-transform":"translateY(50%)"},onSlideStart:_=>{const v=y(_.clientY);i==null||i(v)},onSlideMove:_=>{const v=y(_.clientY);l==null||l(v)},onSlideEnd:()=>{p.current=void 0,o==null||o()},onStepKeyDown:_=>{const j=Hot[f?"from-bottom":"from-top"].includes(_.key);c==null||c({event:_,direction:j?-1:1})}})})}),Zot=N.forwardRef((s,t)=>{const{__scopeSlider:n,onSlideStart:r,onSlideMove:a,onSlideEnd:i,onHomeKeyDown:l,onEndKeyDown:o,onStepKeyDown:c,...d}=s,u=V0e(DD,n);return e.jsx(Yr.span,{...d,ref:t,onKeyDown:xr(s.onKeyDown,h=>{h.key==="Home"?(l(h),h.preventDefault()):h.key==="End"?(o(h),h.preventDefault()):qot.concat(Vot).includes(h.key)&&(c(h),h.preventDefault())}),onPointerDown:xr(s.onPointerDown,h=>{const p=h.target;p.setPointerCapture(h.pointerId),h.preventDefault(),u.thumbs.has(p)?p.focus():r(h)}),onPointerMove:xr(s.onPointerMove,h=>{h.target.hasPointerCapture(h.pointerId)&&a(h)}),onPointerUp:xr(s.onPointerUp,h=>{const p=h.target;p.hasPointerCapture(h.pointerId)&&(p.releasePointerCapture(h.pointerId),i(h))})})}),Qot="SliderTrack",Xot=N.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=V0e(Qot,n);return e.jsx(Yr.span,{"data-disabled":a.disabled?"":void 0,"data-orientation":a.orientation,...r,ref:t})});Xot.displayName=Qot;var o4e="SliderRange",Jot=N.forwardRef((s,t)=>{const{__scopeSlider:n,...r}=s,a=V0e(o4e,n),i=Yot(o4e,n),l=N.useRef(null),o=ji(t,l),c=a.values.length,d=a.values.map(p=>slt(p,a.min,a.max)),u=c>1?Math.min(...d):0,h=100-Math.max(...d);return e.jsx(Yr.span,{"data-orientation":a.orientation,"data-disabled":a.disabled?"":void 0,...r,ref:o,style:{...s.style,[i.startEdge]:u+"%",[i.endEdge]:h+"%"}})});Jot.displayName=o4e;var l4e="SliderThumb",elt=N.forwardRef((s,t)=>{const n=F7t(s.__scopeSlider),[r,a]=N.useState(null),i=ji(t,o=>a(o)),l=N.useMemo(()=>r?n().findIndex(o=>o.ref.current===r):-1,[n,r]);return e.jsx(q7t,{...s,ref:i,index:l})}),q7t=N.forwardRef((s,t)=>{const{__scopeSlider:n,index:r,name:a,...i}=s,l=V0e(l4e,n),o=Yot(l4e,n),[c,d]=N.useState(null),u=ji(t,w=>d(w)),h=c?l.form||!!c.closest("form"):!0,p=M$(c),f=l.values[r],y=f===void 0?0:slt(f,l.min,l.max),_=G7t(r,l.values.length),v=p==null?void 0:p[o.size],j=v?K7t(v,y,o.direction):0;return N.useEffect(()=>{if(c)return l.thumbs.add(c),()=>{l.thumbs.delete(c)}},[c,l.thumbs]),e.jsxs("span",{style:{transform:"var(--radix-slider-thumb-transform)",position:"absolute",[o.startEdge]:`calc(${y}% + ${j}px)`},children:[e.jsx(i4e.ItemSlot,{scope:s.__scopeSlider,children:e.jsx(Yr.span,{role:"slider","aria-label":s["aria-label"]||_,"aria-valuemin":l.min,"aria-valuenow":f,"aria-valuemax":l.max,"aria-orientation":l.orientation,"data-orientation":l.orientation,"data-disabled":l.disabled?"":void 0,tabIndex:l.disabled?void 0:0,...i,ref:u,style:f===void 0?{display:"none"}:s.style,onFocus:xr(s.onFocus,()=>{l.valueIndexToChangeRef.current=r})})}),h&&e.jsx(tlt,{name:a??(l.name?l.name+(l.values.length>1?"[]":""):void 0),form:l.form,value:f},r)]})});elt.displayName=l4e;var V7t="RadioBubbleInput",tlt=N.forwardRef(({__scopeSlider:s,value:t,...n},r)=>{const a=N.useRef(null),i=ji(a,r),l=G$(t);return N.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLInputElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("input",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(Yr.input,{style:{display:"none"},...n,ref:i,defaultValue:t})});tlt.displayName=V7t;function H7t(s=[],t,n){const r=[...s];return r[n]=t,r.sort((a,i)=>a-i)}function slt(s,t,n){const i=100/(n-t)*(s-t);return eB(i,[0,100])}function G7t(s,t){return t>2?`Value ${s+1} of ${t}`:t===2?["Minimum","Maximum"][s]:void 0}function W7t(s,t){if(s.length===1)return 0;const n=s.map(a=>Math.abs(a-t)),r=Math.min(...n);return n.indexOf(r)}function K7t(s,t,n){const r=s/2,i=PAe([0,50],[0,r]);return(r-i(t)*n)*n}function Y7t(s){return s.slice(0,-1).map((t,n)=>s[n+1]-t)}function Z7t(s,t){if(t>0){const n=Y7t(s);return Math.min(...n)>=t}return!0}function PAe(s,t){return n=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(s[1]-s[0]);return t[0]+r*(n-s[0])}}function Q7t(s){return(String(s).split(".")[1]||"").length}function X7t(s,t){const n=Math.pow(10,t);return Math.round(s*n)/n}var nlt=Wot,J7t=Xot,e9t=Jot,t9t=elt;const jp=N.forwardRef(({className:s,...t},n)=>e.jsxs(nlt,{ref:n,className:Mt("relative flex w-full touch-none select-none items-center",s),...t,children:[e.jsx(J7t,{className:"relative h-2 w-full grow overflow-hidden rounded-full bg-secondary",children:e.jsx(e9t,{className:"absolute h-full bg-primary"})}),e.jsx(t9t,{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"})]}));jp.displayName=nlt.displayName;var s9t=[" ","Enter","ArrowUp","ArrowDown"],n9t=[" ","Enter"],uM="Select",[H0e,G0e,r9t]=wD(uM),[RD,Jpn]=uu(uM,[r9t,qw]),W0e=qw(),[a9t,B4]=RD(uM),[i9t,o9t]=RD(uM),rlt=s=>{const{__scopeSelect:t,children:n,open:r,defaultOpen:a,onOpenChange:i,value:l,defaultValue:o,onValueChange:c,dir:d,name:u,autoComplete:h,disabled:p,required:f,form:y}=s,_=W0e(t),[v,j]=N.useState(null),[w,S]=N.useState(null),[A,E]=N.useState(!1),O=vN(d),[D,I]=cm({prop:r,defaultProp:a??!1,onChange:i,caller:uM}),[F,z]=cm({prop:l,defaultProp:o,onChange:c,caller:uM}),H=N.useRef(null),Z=v?y||!!v.closest("form"):!0,[Y,W]=N.useState(new Set),ee=Array.from(Y).map(se=>se.props.value).join(";");return e.jsx(I$,{..._,children:e.jsxs(a9t,{required:f,scope:t,trigger:v,onTriggerChange:j,valueNode:w,onValueNodeChange:S,valueNodeHasChildren:A,onValueNodeHasChildrenChange:E,contentId:om(),value:F,onValueChange:z,open:D,onOpenChange:I,dir:O,triggerPointerDownPosRef:H,disabled:p,children:[e.jsx(H0e.Provider,{scope:t,children:e.jsx(i9t,{scope:s.__scopeSelect,onNativeOptionAdd:N.useCallback(se=>{W(oe=>new Set(oe).add(se))},[]),onNativeOptionRemove:N.useCallback(se=>{W(oe=>{const he=new Set(oe);return he.delete(se),he})},[]),children:n})}),Z?e.jsxs(Tlt,{"aria-hidden":!0,required:f,tabIndex:-1,name:u,autoComplete:h,value:F,onChange:se=>z(se.target.value),disabled:p,form:y,children:[F===void 0?e.jsx("option",{value:""}):null,Array.from(Y)]},ee):null]})})};rlt.displayName=uM;var alt="SelectTrigger",ilt=N.forwardRef((s,t)=>{const{__scopeSelect:n,disabled:r=!1,...a}=s,i=W0e(n),l=B4(alt,n),o=l.disabled||r,c=ji(t,l.onTriggerChange),d=G0e(n),u=N.useRef("touch"),[h,p,f]=Alt(_=>{const v=d().filter(S=>!S.disabled),j=v.find(S=>S.value===l.value),w=Mlt(v,_,j);w!==void 0&&l.onValueChange(w.value)}),y=_=>{o||(l.onOpenChange(!0),f()),_&&(l.triggerPointerDownPosRef.current={x:Math.round(_.pageX),y:Math.round(_.pageY)})};return e.jsx(CD,{asChild:!0,...i,children:e.jsx(Yr.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":Elt(l.value)?"":void 0,...a,ref:c,onClick:xr(a.onClick,_=>{_.currentTarget.focus(),u.current!=="mouse"&&y(_)}),onPointerDown:xr(a.onPointerDown,_=>{u.current=_.pointerType;const v=_.target;v.hasPointerCapture(_.pointerId)&&v.releasePointerCapture(_.pointerId),_.button===0&&_.ctrlKey===!1&&_.pointerType==="mouse"&&(y(_),_.preventDefault())}),onKeyDown:xr(a.onKeyDown,_=>{const v=h.current!=="";!(_.ctrlKey||_.altKey||_.metaKey)&&_.key.length===1&&p(_.key),!(v&&_.key===" ")&&s9t.includes(_.key)&&(y(),_.preventDefault())})})})});ilt.displayName=alt;var olt="SelectValue",llt=N.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,children:i,placeholder:l="",...o}=s,c=B4(olt,n),{onValueNodeHasChildrenChange:d}=c,u=i!==void 0,h=ji(t,c.onValueNodeChange);return lh(()=>{d(u)},[d,u]),e.jsx(Yr.span,{...o,ref:h,style:{pointerEvents:"none"},children:Elt(c.value)?e.jsx(e.Fragment,{children:l}):i})});llt.displayName=olt;var l9t="SelectIcon",clt=N.forwardRef((s,t)=>{const{__scopeSelect:n,children:r,...a}=s;return e.jsx(Yr.span,{"aria-hidden":!0,...a,ref:t,children:r||"▼"})});clt.displayName=l9t;var c9t="SelectPortal",dlt=s=>e.jsx(jD,{asChild:!0,...s});dlt.displayName=c9t;var hM="SelectContent",ult=N.forwardRef((s,t)=>{const n=B4(hM,s.__scopeSelect),[r,a]=N.useState();if(lh(()=>{a(new DocumentFragment)},[]),!n.open){const i=r;return i?qx.createPortal(e.jsx(hlt,{scope:s.__scopeSelect,children:e.jsx(H0e.Slot,{scope:s.__scopeSelect,children:e.jsx("div",{children:s.children})})}),i):null}return e.jsx(mlt,{...s,ref:t})});ult.displayName=hM;var z1=10,[hlt,$4]=RD(hM),d9t="SelectContentImpl",u9t=v4("SelectContent.RemoveScroll"),mlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,position:r="item-aligned",onCloseAutoFocus:a,onEscapeKeyDown:i,onPointerDownOutside:l,side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:p,collisionPadding:f,sticky:y,hideWhenDetached:_,avoidCollisions:v,...j}=s,w=B4(hM,n),[S,A]=N.useState(null),[E,O]=N.useState(null),D=ji(t,Me=>A(Me)),[I,F]=N.useState(null),[z,H]=N.useState(null),Z=G0e(n),[Y,W]=N.useState(!1),ee=N.useRef(!1);N.useEffect(()=>{if(S)return L0e(S)},[S]),M0e();const se=N.useCallback(Me=>{const[Pe,...Re]=Z().map(we=>we.ref.current),[Ae]=Re.slice(-1),Be=document.activeElement;for(const we of Me)if(we===Be||(we==null||we.scrollIntoView({block:"nearest"}),we===Pe&&E&&(E.scrollTop=0),we===Ae&&E&&(E.scrollTop=E.scrollHeight),we==null||we.focus(),document.activeElement!==Be))return},[Z,E]),oe=N.useCallback(()=>se([I,S]),[se,I,S]);N.useEffect(()=>{Y&&oe()},[Y,oe]);const{onOpenChange:he,triggerPointerDownPosRef:ce}=w;N.useEffect(()=>{if(S){let Me={x:0,y:0};const Pe=Ae=>{var Be,we;Me={x:Math.abs(Math.round(Ae.pageX)-(((Be=ce.current)==null?void 0:Be.x)??0)),y:Math.abs(Math.round(Ae.pageY)-(((we=ce.current)==null?void 0:we.y)??0))}},Re=Ae=>{Me.x<=10&&Me.y<=10?Ae.preventDefault():S.contains(Ae.target)||he(!1),document.removeEventListener("pointermove",Pe),ce.current=null};return ce.current!==null&&(document.addEventListener("pointermove",Pe),document.addEventListener("pointerup",Re,{capture:!0,once:!0})),()=>{document.removeEventListener("pointermove",Pe),document.removeEventListener("pointerup",Re,{capture:!0})}}},[S,he,ce]),N.useEffect(()=>{const Me=()=>he(!1);return window.addEventListener("blur",Me),window.addEventListener("resize",Me),()=>{window.removeEventListener("blur",Me),window.removeEventListener("resize",Me)}},[he]);const[me,le]=Alt(Me=>{const Pe=Z().filter(Be=>!Be.disabled),Re=Pe.find(Be=>Be.ref.current===document.activeElement),Ae=Mlt(Pe,Me,Re);Ae&&setTimeout(()=>Ae.ref.current.focus())}),ve=N.useCallback((Me,Pe,Re)=>{const Ae=!ee.current&&!Re;(w.value!==void 0&&w.value===Pe||Ae)&&(F(Me),Ae&&(ee.current=!0))},[w.value]),ge=N.useCallback(()=>S==null?void 0:S.focus(),[S]),Te=N.useCallback((Me,Pe,Re)=>{const Ae=!ee.current&&!Re;(w.value!==void 0&&w.value===Pe||Ae)&&H(Me)},[w.value]),Ie=r==="popper"?c4e:plt,Ce=Ie===c4e?{side:o,sideOffset:c,align:d,alignOffset:u,arrowPadding:h,collisionBoundary:p,collisionPadding:f,sticky:y,hideWhenDetached:_,avoidCollisions:v}:{};return e.jsx(hlt,{scope:n,content:S,viewport:E,onViewportChange:O,itemRefCallback:ve,selectedItem:I,onItemLeave:ge,itemTextRefCallback:Te,focusSelectedItem:oe,selectedItemText:z,position:r,isPositioned:Y,searchRef:me,children:e.jsx(z$,{as:u9t,allowPinchZoom:!0,children:e.jsx(O$,{asChild:!0,trapped:w.open,onMountAutoFocus:Me=>{Me.preventDefault()},onUnmountAutoFocus:xr(a,Me=>{var Pe;(Pe=w.trigger)==null||Pe.focus({preventScroll:!0}),Me.preventDefault()}),children:e.jsx(O4,{asChild:!0,disableOutsidePointerEvents:!0,onEscapeKeyDown:i,onPointerDownOutside:l,onFocusOutside:Me=>Me.preventDefault(),onDismiss:()=>w.onOpenChange(!1),children:e.jsx(Ie,{role:"listbox",id:w.contentId,"data-state":w.open?"open":"closed",dir:w.dir,onContextMenu:Me=>Me.preventDefault(),...j,...Ce,onPlaced:()=>W(!0),ref:D,style:{display:"flex",flexDirection:"column",outline:"none",...j.style},onKeyDown:xr(j.onKeyDown,Me=>{const Pe=Me.ctrlKey||Me.altKey||Me.metaKey;if(Me.key==="Tab"&&Me.preventDefault(),!Pe&&Me.key.length===1&&le(Me.key),["ArrowUp","ArrowDown","Home","End"].includes(Me.key)){let Ae=Z().filter(Be=>!Be.disabled).map(Be=>Be.ref.current);if(["ArrowUp","End"].includes(Me.key)&&(Ae=Ae.slice().reverse()),["ArrowUp","ArrowDown"].includes(Me.key)){const Be=Me.target,we=Ae.indexOf(Be);Ae=Ae.slice(we+1)}setTimeout(()=>se(Ae)),Me.preventDefault()}})})})})})})});mlt.displayName=d9t;var h9t="SelectItemAlignedPosition",plt=N.forwardRef((s,t)=>{const{__scopeSelect:n,onPlaced:r,...a}=s,i=B4(hM,n),l=$4(hM,n),[o,c]=N.useState(null),[d,u]=N.useState(null),h=ji(t,D=>u(D)),p=G0e(n),f=N.useRef(!1),y=N.useRef(!0),{viewport:_,selectedItem:v,selectedItemText:j,focusSelectedItem:w}=l,S=N.useCallback(()=>{if(i.trigger&&i.valueNode&&o&&d&&_&&v&&j){const D=i.trigger.getBoundingClientRect(),I=d.getBoundingClientRect(),F=i.valueNode.getBoundingClientRect(),z=j.getBoundingClientRect();if(i.dir!=="rtl"){const Be=z.left-I.left,we=F.left-Be,Je=D.left-we,ke=D.width+Je,it=Math.max(ke,I.width),je=window.innerWidth-z1,He=eB(we,[z1,Math.max(z1,je-it)]);o.style.minWidth=ke+"px",o.style.left=He+"px"}else{const Be=I.right-z.right,we=window.innerWidth-F.right-Be,Je=window.innerWidth-D.right-we,ke=D.width+Je,it=Math.max(ke,I.width),je=window.innerWidth-z1,He=eB(we,[z1,Math.max(z1,je-it)]);o.style.minWidth=ke+"px",o.style.right=He+"px"}const H=p(),Z=window.innerHeight-z1*2,Y=_.scrollHeight,W=window.getComputedStyle(d),ee=parseInt(W.borderTopWidth,10),se=parseInt(W.paddingTop,10),oe=parseInt(W.borderBottomWidth,10),he=parseInt(W.paddingBottom,10),ce=ee+se+Y+he+oe,me=Math.min(v.offsetHeight*5,ce),le=window.getComputedStyle(_),ve=parseInt(le.paddingTop,10),ge=parseInt(le.paddingBottom,10),Te=D.top+D.height/2-z1,Ie=Z-Te,Ce=v.offsetHeight/2,Me=v.offsetTop+Ce,Pe=ee+se+Me,Re=ce-Pe;if(Pe<=Te){const Be=H.length>0&&v===H[H.length-1].ref.current;o.style.bottom="0px";const we=d.clientHeight-_.offsetTop-_.offsetHeight,Je=Math.max(Ie,Ce+(Be?ge:0)+we+oe),ke=Pe+Je;o.style.height=ke+"px"}else{const Be=H.length>0&&v===H[0].ref.current;o.style.top="0px";const Je=Math.max(Te,ee+_.offsetTop+(Be?ve:0)+Ce)+Re;o.style.height=Je+"px",_.scrollTop=Pe-Te+_.offsetTop}o.style.margin=`${z1}px 0`,o.style.minHeight=me+"px",o.style.maxHeight=Z+"px",r==null||r(),requestAnimationFrame(()=>f.current=!0)}},[p,i.trigger,i.valueNode,o,d,_,v,j,i.dir,r]);lh(()=>S(),[S]);const[A,E]=N.useState();lh(()=>{d&&E(window.getComputedStyle(d).zIndex)},[d]);const O=N.useCallback(D=>{D&&y.current===!0&&(S(),w==null||w(),y.current=!1)},[S,w]);return e.jsx(p9t,{scope:n,contentWrapper:o,shouldExpandOnScrollRef:f,onScrollButtonChange:O,children:e.jsx("div",{ref:c,style:{display:"flex",flexDirection:"column",position:"fixed",zIndex:A},children:e.jsx(Yr.div,{...a,ref:h,style:{boxSizing:"border-box",maxHeight:"100%",...a.style}})})})});plt.displayName=h9t;var m9t="SelectPopperPosition",c4e=N.forwardRef((s,t)=>{const{__scopeSelect:n,align:r="start",collisionPadding:a=z1,...i}=s,l=W0e(n);return e.jsx(P$,{...l,...i,ref:t,align:r,collisionPadding:a,style:{boxSizing:"border-box",...i.style,"--radix-select-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-select-content-available-width":"var(--radix-popper-available-width)","--radix-select-content-available-height":"var(--radix-popper-available-height)","--radix-select-trigger-width":"var(--radix-popper-anchor-width)","--radix-select-trigger-height":"var(--radix-popper-anchor-height)"}})});c4e.displayName=m9t;var[p9t,LAe]=RD(hM,{}),d4e="SelectViewport",flt=N.forwardRef((s,t)=>{const{__scopeSelect:n,nonce:r,...a}=s,i=$4(d4e,n),l=LAe(d4e,n),o=ji(t,i.onViewportChange),c=N.useRef(0);return e.jsxs(e.Fragment,{children:[e.jsx("style",{dangerouslySetInnerHTML:{__html:"[data-radix-select-viewport]{scrollbar-width:none;-ms-overflow-style:none;-webkit-overflow-scrolling:touch;}[data-radix-select-viewport]::-webkit-scrollbar{display:none}"},nonce:r}),e.jsx(H0e.Slot,{scope:n,children:e.jsx(Yr.div,{"data-radix-select-viewport":"",role:"presentation",...a,ref:o,style:{position:"relative",flex:1,overflow:"hidden auto",...a.style},onScroll:xr(a.onScroll,d=>{const u=d.currentTarget,{contentWrapper:h,shouldExpandOnScrollRef:p}=l;if(p!=null&&p.current&&h){const f=Math.abs(c.current-u.scrollTop);if(f>0){const y=window.innerHeight-z1*2,_=parseFloat(h.style.minHeight),v=parseFloat(h.style.height),j=Math.max(_,v);if(j0?A:0,h.style.justifyContent="flex-end")}}}c.current=u.scrollTop})})})]})});flt.displayName=d4e;var xlt="SelectGroup",[f9t,x9t]=RD(xlt),g9t=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=om();return e.jsx(f9t,{scope:n,id:a,children:e.jsx(Yr.div,{role:"group","aria-labelledby":a,...r,ref:t})})});g9t.displayName=xlt;var glt="SelectLabel",ylt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=x9t(glt,n);return e.jsx(Yr.div,{id:a.id,...r,ref:t})});ylt.displayName=glt;var Wpe="SelectItem",[y9t,vlt]=RD(Wpe),blt=N.forwardRef((s,t)=>{const{__scopeSelect:n,value:r,disabled:a=!1,textValue:i,...l}=s,o=B4(Wpe,n),c=$4(Wpe,n),d=o.value===r,[u,h]=N.useState(i??""),[p,f]=N.useState(!1),y=ji(t,w=>{var S;return(S=c.itemRefCallback)==null?void 0:S.call(c,w,r,a)}),_=om(),v=N.useRef("touch"),j=()=>{a||(o.onValueChange(r),o.onOpenChange(!1))};if(r==="")throw new Error("A must have a value prop that is not an empty string. This is because the Select value can be set to an empty string to clear the selection and show the placeholder.");return e.jsx(y9t,{scope:n,value:r,disabled:a,textId:_,isSelected:d,onItemTextChange:N.useCallback(w=>{h(S=>S||((w==null?void 0:w.textContent)??"").trim())},[]),children:e.jsx(H0e.ItemSlot,{scope:n,value:r,disabled:a,textValue:u,children:e.jsx(Yr.div,{role:"option","aria-labelledby":_,"data-highlighted":p?"":void 0,"aria-selected":d&&p,"data-state":d?"checked":"unchecked","aria-disabled":a||void 0,"data-disabled":a?"":void 0,tabIndex:a?void 0:-1,...l,ref:y,onFocus:xr(l.onFocus,()=>f(!0)),onBlur:xr(l.onBlur,()=>f(!1)),onClick:xr(l.onClick,()=>{v.current!=="mouse"&&j()}),onPointerUp:xr(l.onPointerUp,()=>{v.current==="mouse"&&j()}),onPointerDown:xr(l.onPointerDown,w=>{v.current=w.pointerType}),onPointerMove:xr(l.onPointerMove,w=>{var S;v.current=w.pointerType,a?(S=c.onItemLeave)==null||S.call(c):v.current==="mouse"&&w.currentTarget.focus({preventScroll:!0})}),onPointerLeave:xr(l.onPointerLeave,w=>{var S;w.currentTarget===document.activeElement&&((S=c.onItemLeave)==null||S.call(c))}),onKeyDown:xr(l.onKeyDown,w=>{var A;((A=c.searchRef)==null?void 0:A.current)!==""&&w.key===" "||(n9t.includes(w.key)&&j(),w.key===" "&&w.preventDefault())})})})})});blt.displayName=Wpe;var e7="SelectItemText",_lt=N.forwardRef((s,t)=>{const{__scopeSelect:n,className:r,style:a,...i}=s,l=B4(e7,n),o=$4(e7,n),c=vlt(e7,n),d=o9t(e7,n),[u,h]=N.useState(null),p=ji(t,j=>h(j),c.onItemTextChange,j=>{var w;return(w=o.itemTextRefCallback)==null?void 0:w.call(o,j,c.value,c.disabled)}),f=u==null?void 0:u.textContent,y=N.useMemo(()=>e.jsx("option",{value:c.value,disabled:c.disabled,children:f},c.value),[c.disabled,c.value,f]),{onNativeOptionAdd:_,onNativeOptionRemove:v}=d;return lh(()=>(_(y),()=>v(y)),[_,v,y]),e.jsxs(e.Fragment,{children:[e.jsx(Yr.span,{id:c.textId,...i,ref:p}),c.isSelected&&l.valueNode&&!l.valueNodeHasChildren?qx.createPortal(i.children,l.valueNode):null]})});_lt.displayName=e7;var wlt="SelectItemIndicator",jlt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return vlt(wlt,n).isSelected?e.jsx(Yr.span,{"aria-hidden":!0,...r,ref:t}):null});jlt.displayName=wlt;var u4e="SelectScrollUpButton",Nlt=N.forwardRef((s,t)=>{const n=$4(u4e,s.__scopeSelect),r=LAe(u4e,s.__scopeSelect),[a,i]=N.useState(!1),l=ji(t,r.onScrollButtonChange);return lh(()=>{if(n.viewport&&n.isPositioned){let o=function(){const d=c.scrollTop>0;i(d)};const c=n.viewport;return o(),c.addEventListener("scroll",o),()=>c.removeEventListener("scroll",o)}},[n.viewport,n.isPositioned]),a?e.jsx(Slt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop-c.offsetHeight)}}):null});Nlt.displayName=u4e;var h4e="SelectScrollDownButton",klt=N.forwardRef((s,t)=>{const n=$4(h4e,s.__scopeSelect),r=LAe(h4e,s.__scopeSelect),[a,i]=N.useState(!1),l=ji(t,r.onScrollButtonChange);return lh(()=>{if(n.viewport&&n.isPositioned){let o=function(){const d=c.scrollHeight-c.clientHeight,u=Math.ceil(c.scrollTop)c.removeEventListener("scroll",o)}},[n.viewport,n.isPositioned]),a?e.jsx(Slt,{...s,ref:l,onAutoScroll:()=>{const{viewport:o,selectedItem:c}=n;o&&c&&(o.scrollTop=o.scrollTop+c.offsetHeight)}}):null});klt.displayName=h4e;var Slt=N.forwardRef((s,t)=>{const{__scopeSelect:n,onAutoScroll:r,...a}=s,i=$4("SelectScrollButton",n),l=N.useRef(null),o=G0e(n),c=N.useCallback(()=>{l.current!==null&&(window.clearInterval(l.current),l.current=null)},[]);return N.useEffect(()=>()=>c(),[c]),lh(()=>{var u;const d=o().find(h=>h.ref.current===document.activeElement);(u=d==null?void 0:d.ref.current)==null||u.scrollIntoView({block:"nearest"})},[o]),e.jsx(Yr.div,{"aria-hidden":!0,...a,ref:t,style:{flexShrink:0,...a.style},onPointerDown:xr(a.onPointerDown,()=>{l.current===null&&(l.current=window.setInterval(r,50))}),onPointerMove:xr(a.onPointerMove,()=>{var d;(d=i.onItemLeave)==null||d.call(i),l.current===null&&(l.current=window.setInterval(r,50))}),onPointerLeave:xr(a.onPointerLeave,()=>{c()})})}),v9t="SelectSeparator",Clt=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s;return e.jsx(Yr.div,{"aria-hidden":!0,...r,ref:t})});Clt.displayName=v9t;var m4e="SelectArrow",b9t=N.forwardRef((s,t)=>{const{__scopeSelect:n,...r}=s,a=W0e(n),i=B4(m4e,n),l=$4(m4e,n);return i.open&&l.position==="popper"?e.jsx(L$,{...a,...r,ref:t}):null});b9t.displayName=m4e;var _9t="SelectBubbleInput",Tlt=N.forwardRef(({__scopeSelect:s,value:t,...n},r)=>{const a=N.useRef(null),i=ji(r,a),l=G$(t);return N.useEffect(()=>{const o=a.current;if(!o)return;const c=window.HTMLSelectElement.prototype,u=Object.getOwnPropertyDescriptor(c,"value").set;if(l!==t&&u){const h=new Event("change",{bubbles:!0});u.call(o,t),o.dispatchEvent(h)}},[l,t]),e.jsx(Yr.select,{...n,style:{...Int,...n.style},ref:i,defaultValue:t})});Tlt.displayName=_9t;function Elt(s){return s===""||s===void 0}function Alt(s){const t=rh(s),n=N.useRef(""),r=N.useRef(0),a=N.useCallback(l=>{const o=n.current+l;t(o),function c(d){n.current=d,window.clearTimeout(r.current),d!==""&&(r.current=window.setTimeout(()=>c(""),1e3))}(o)},[t]),i=N.useCallback(()=>{n.current="",window.clearTimeout(r.current)},[]);return N.useEffect(()=>()=>window.clearTimeout(r.current),[]),[n,a,i]}function Mlt(s,t,n){const a=t.length>1&&Array.from(t).every(d=>d===t[0])?t[0]:t,i=n?s.indexOf(n):-1;let l=w9t(s,Math.max(i,0));a.length===1&&(l=l.filter(d=>d!==n));const c=l.find(d=>d.textValue.toLowerCase().startsWith(a.toLowerCase()));return c!==n?c:void 0}function w9t(s,t){return s.map((n,r)=>s[(t+r)%s.length])}var j9t=rlt,Ilt=ilt,N9t=llt,k9t=clt,S9t=dlt,Plt=ult,C9t=flt,Llt=ylt,Dlt=blt,T9t=_lt,E9t=jlt,Rlt=Nlt,Olt=klt,Flt=Clt;const us=j9t,hs=N9t,ls=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Ilt,{ref:r,className:Mt("flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",s),...n,children:[t,e.jsx(k9t,{asChild:!0,children:e.jsx(ao,{className:"h-4 w-4 opacity-50"})})]}));ls.displayName=Ilt.displayName;const zlt=N.forwardRef(({className:s,...t},n)=>e.jsx(Rlt,{ref:n,className:Mt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(ex,{className:"h-4 w-4"})}));zlt.displayName=Rlt.displayName;const Blt=N.forwardRef(({className:s,...t},n)=>e.jsx(Olt,{ref:n,className:Mt("flex cursor-default items-center justify-center py-1",s),...t,children:e.jsx(ao,{className:"h-4 w-4"})}));Blt.displayName=Olt.displayName;const cs=N.forwardRef(({className:s,children:t,position:n="popper",...r},a)=>e.jsx(S9t,{children:e.jsxs(Plt,{ref:a,className:Mt("relative z-50 max-h-96 min-w-[8rem] overflow-hidden rounded-md border bg-popover text-popover-foreground shadow-md data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",n==="popper"&&"data-[side=bottom]:translate-y-1 data-[side=left]:-translate-x-1 data-[side=right]:translate-x-1 data-[side=top]:-translate-y-1",s),position:n,...r,children:[e.jsx(zlt,{}),e.jsx(C9t,{className:Mt("p-1",n==="popper"&&"h-[var(--radix-select-trigger-height)] w-full min-w-[var(--radix-select-trigger-width)]"),children:t}),e.jsx(Blt,{})]})}));cs.displayName=Plt.displayName;const A9t=N.forwardRef(({className:s,...t},n)=>e.jsx(Llt,{ref:n,className:Mt("py-1.5 pl-8 pr-2 text-sm font-semibold",s),...t}));A9t.displayName=Llt.displayName;const Ze=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(Dlt,{ref:r,className:Mt("relative flex w-full cursor-default select-none items-center rounded-sm py-1.5 pl-8 pr-2 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50 focus:bg-accent focus:text-accent-foreground",s),...n,children:[e.jsx("span",{className:"absolute left-2 flex h-3.5 w-3.5 items-center justify-center",children:e.jsx(E9t,{children:e.jsx(Lr,{className:"h-4 w-4"})})}),e.jsx(T9t,{children:t})]}));Ze.displayName=Dlt.displayName;const M9t=N.forwardRef(({className:s,...t},n)=>e.jsx(Flt,{ref:n,className:Mt("-mx-1 my-1 h-px bg-muted",s),...t}));M9t.displayName=Flt.displayName;const I9t=s=>dt({queryKey:["public-listings",s],queryFn:async()=>{let t=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, latitude, longitude, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0).order("created_at",{ascending:!1});if(s!=null&&s.status&&(t=t.eq("status",s.status)),s!=null&&s.propertyType&&(t=t.eq("property_type",s.propertyType)),s!=null&&s.city){const a=s.city.replace(/[%,()]/g," ").trim();if(a){const i=`%${a}%`;t=t.or(`city.ilike.${i},neighborhood.ilike.${i},property_address.ilike.${i}`)}}s!=null&&s.minPrice&&(t=t.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(t=t.lte("price",s.maxPrice));const{data:n,error:r}=await t;if(r)throw r;return n}}),P9t=()=>dt({queryKey:["public-listings-search-index"],staleTime:5*60*1e3,queryFn:async()=>{const{data:s,error:t}=await q.from("listings").select("city, state, neighborhood, property_address").eq("is_approved",!0).eq("is_public",!0);if(t)throw t;const n=new Map,r=new Map,a=new Map;return(s||[]).forEach(i=>{if(i.city){const l=`${i.city}|${i.state||""}`.toLowerCase(),o=i.state?`${i.city}, ${i.state}`:i.city,c=n.get(l);c?c.count++:n.set(l,{label:o,city:i.city,state:i.state,count:1})}if(i.neighborhood){const l=`${i.neighborhood}|${i.city||""}`.toLowerCase(),o=i.city?`${i.neighborhood} — ${i.city}`:i.neighborhood,c=r.get(l);c?c.count++:r.set(l,{label:o,city:i.city||"",neighborhood:i.neighborhood,count:1})}if(i.property_address){const l=String(i.property_address).match(/\b(\d{5})(?:-\d{4})?\b/);if(l){const o=l[1],c=a.get(o);c?c.count++:a.set(o,{label:o,zip:o,count:1})}}}),{cities:Array.from(n.values()).sort((i,l)=>l.count-i.count),neighborhoods:Array.from(r.values()).sort((i,l)=>l.count-i.count),zips:Array.from(a.values()).sort((i,l)=>l.count-i.count)}}}),L9t=s=>dt({queryKey:["public-listing",s],queryFn:async()=>{const t=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s);let n=q.from("listings").select(` id, slug, agent_id, property_address, city, state, neighborhood, price, property_type, status, bedrooms, bathrooms, square_footage, lot_size, year_built, has_hoa, description, agent_notes, agent_notes_public, mls_link, video_link, video_id, latitude, longitude, page_config, page_theme, created_at, updated_at, photos:listing_photos(id, photo_url, is_primary, sort_order), agent:profiles!listings_agent_id_fkey(id, name, email, phone, avatar_url, brokerage_name, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds, bunny_video_id) `).eq("is_approved",!0).eq("is_public",!0);t?n=n.eq("id",s):n=n.eq("slug",s);const{data:r,error:a}=await n.single();if(a)throw a;return r},enabled:!!s}),D9t=()=>yt({mutationFn:async({listingId:s,agentId:t,firstName:n,lastName:r,email:a,phone:i,shareToken:l,leadType:o="info_request",preferredDate:c,preferredTime:d,showingMode:u,message:h})=>{let p=null,f=null;if(l){const{data:j}=await q.from("listing_shares").select("id, sharing_agent_id").eq("share_token",l).eq("listing_id",s).maybeSingle();j&&(p=j.id,f=j.sharing_agent_id)}const{data:y,error:_}=await q.from("listing_leads").insert({listing_id:s,agent_id:f||t,first_name:n,last_name:r,email:a,phone:i,share_id:p,referred_by_agent_id:f,lead_type:o,preferred_date:c||null,preferred_time:d||null,showing_mode:u||null,message:h||null}).select().single();if(_)throw _;const{error:v}=await q.functions.invoke("process-listing-lead",{body:{leadId:y.id}});return v&&console.error("Error processing lead:",v),y}}),R9t=()=>yt({mutationFn:async s=>{const{error:t}=await q.rpc("increment_listing_share_click",{p_share_token:s});if(t)throw t}}),Rze="/assets/levelup-logo-color-BeKd2k_g.png",O9t={active:"bg-emerald-500",coming_soon:"bg-sky-500",office_exclusive:"bg-indigo-500",pre_market:"bg-cyan-500",price_improvement:"bg-orange-500",under_contract:"bg-purple-500",sold:"bg-gray-600"},F9t={active:"For Sale",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},Oze={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},VV=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),ZO=s=>new Intl.NumberFormat("en-US").format(s);function $lt({slugOverride:s}={}){var $t,Yt,Ds,Ls,xs;const t=bi(),n=s||t.slugOrId,[r]=xl(),{data:a,isLoading:i}=L9t(n||""),l=D9t(),o=R9t(),c=r.get("ref"),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState(""),[E,O]=N.useState(""),[D,I]=N.useState("in_person"),[F,z]=N.useState("info"),[H,Z]=N.useState(!1),[Y,W]=N.useState(!1),[ee,se]=N.useState(null),[oe,he]=N.useState(!1);N.useState(!1);const[ce,me]=N.useState(!1),[le,ve]=N.useState(20),[ge,Te]=N.useState(6.5),[Ie,Ce]=N.useState(30),Me=N.useRef(null),[Pe,Re]=N.useState(!1);N.useEffect(()=>{const Lt=()=>Re(window.scrollY>300);return window.addEventListener("scroll",Lt,{passive:!0}),()=>window.removeEventListener("scroll",Lt)},[]),N.useEffect(()=>{c&&o.mutate(c)},[c]),N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[n]);const Ae=(a==null?void 0:a.photos)||[],Be=Ae.find(Lt=>Lt.is_primary)||Ae[0],we=N.useMemo(()=>{if(!(a!=null&&a.price))return 0;const Lt=a.price*(1-le/100),Jt=ge/100/12,gt=Ie*12;return Jt===0?Lt/gt:Lt*Jt/(1-Math.pow(1+Jt,-gt))},[a==null?void 0:a.price,le,ge,Ie]),Je=async()=>{const Lt=window.location.href;if(navigator.share)try{await navigator.share({title:document.title,url:Lt})}catch{}else await navigator.clipboard.writeText(Lt),ae.success("Link copied to clipboard")},ke=async Lt=>{if(Lt.preventDefault(),!d.trim()||!f.trim()||!a)return;const Jt=F==="showing";if(Jt&&!S){ae.error("Please pick a preferred date for your showing");return}Z(!0);try{await l.mutateAsync({listingId:a.id,agentId:a.agent_id,firstName:d.trim(),lastName:h.trim(),email:f.trim(),phone:_.trim(),shareToken:c,leadType:Jt?"showing_request":"info_request",preferredDate:Jt?S:null,preferredTime:Jt&&E||null,showingMode:Jt?D:null,message:j.trim()||null}),W(!0),ae.success(Jt?"Showing request sent! The agent will confirm details shortly.":"Thanks! The agent will be in touch soon.")}catch(gt){console.error("Lead submission error:",gt),ae.error(`Failed to submit: ${gt.message||"Please try again"}`)}finally{Z(!1)}},it=()=>{ee!==null&&se(ee===0?Ae.length-1:ee-1)},je=()=>{ee!==null&&se(ee===Ae.length-1?0:ee+1)};if(i)return e.jsx("div",{className:"min-h-screen bg-neutral-950",children:e.jsx(Ws,{className:"h-[100svh] w-full rounded-none bg-neutral-900"})});if(!a)return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsx(In,{to:"/public/listings",className:"flex items-center gap-2",children:e.jsx("img",{src:Rze,alt:"LevelUp",className:"h-8"})})})}),e.jsxs("div",{className:"container mx-auto px-4 py-24 text-center",children:[e.jsx(Or,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Listing Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"This listing may no longer be available."}),e.jsx(B,{asChild:!0,children:e.jsx(In,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",children:"Browse All Listings"})})]})]});const He=a.property_address?`${a.property_address} — ${a.city}, ${a.state}`:`${a.city}, ${a.state} Home for Sale`,$e=((Yt=($t=a.agent)==null?void 0:$t.brokerage)==null?void 0:Yt.name)||((Ds=a.agent)==null?void 0:Ds.brokerage_name),Ke=a.latitude&&a.longitude?`https://maps.google.com/maps?q=${a.latitude},${a.longitude}&z=15&output=embed`:a.property_address?`https://maps.google.com/maps?q=${encodeURIComponent(`${a.property_address}, ${a.city}, ${a.state}`)}&z=15&output=embed`:null,Ge=a.description||"",rt=Ge.length>420,tt=ce||!rt?Ge:Ge.slice(0,420).trimEnd()+"…",at=a.page_config||{},Ye=Lt=>{var Jt;return(((Jt=at.sections)==null?void 0:Jt[Lt])??!0)!==!1},ut=Array.isArray(at.addons)?at.addons:[],_t=at.custom_note||"",bt=at.accent_color||null;return e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{children:[e.jsxs("title",{children:[He," | LevelUp Listings"]}),e.jsx("meta",{name:"description",content:`${VV(a.price)} · ${a.bedrooms||""}BD ${a.bathrooms||""}BA ${a.square_footage?a.square_footage.toLocaleString()+" sqft · ":""}${Oze[a.property_type]} in ${a.city}, ${a.state}. ${Ge.slice(0,140)}`}),e.jsx("link",{rel:"canonical",href:`https://listings.relevelup.com/${a.slug||a.id}`}),e.jsx("link",{rel:"preconnect",href:"https://fonts.googleapis.com"}),e.jsx("link",{rel:"preconnect",href:"https://fonts.gstatic.com",crossOrigin:""}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Fraunces:opsz,wght@9..144,300;9..144,400;9..144,500;9..144,600&display=swap",rel:"stylesheet"}),e.jsx("meta",{property:"og:title",content:He}),e.jsx("meta",{property:"og:description",content:`${VV(a.price)} · ${a.city}, ${a.state}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:`https://listings.relevelup.com/${a.slug||a.id}`}),Be&&e.jsx("meta",{property:"og:image",content:Be.photo_url}),e.jsx("meta",{property:"og:site_name",content:"LevelUp Listings"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:He}),e.jsx("meta",{name:"twitter:description",content:`${VV(a.price)} · ${a.city}, ${a.state}`}),Be&&e.jsx("meta",{name:"twitter:image",content:Be.photo_url}),e.jsx("meta",{name:"robots",content:"index, follow"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"RealEstateListing",name:a.property_address||`${a.city}, ${a.state} Home`,description:Ge,url:`https://listings.relevelup.com/${a.slug||a.id}`,datePosted:a.created_at,image:Ae.map(Lt=>Lt.photo_url),address:{"@type":"PostalAddress",streetAddress:a.property_address||void 0,addressLocality:a.city,addressRegion:a.state,addressCountry:"US"},offers:{"@type":"Offer",price:a.price,priceCurrency:"USD",availability:a.status==="sold"?"https://schema.org/SoldOut":a.status==="under_contract"?"https://schema.org/LimitedAvailability":"https://schema.org/InStock"},numberOfRooms:a.bedrooms||void 0,numberOfBathroomsTotal:a.bathrooms||void 0,floorSize:a.square_footage?{"@type":"QuantitativeValue",value:a.square_footage,unitCode:"FTK"}:void 0,yearBuilt:a.year_built||void 0})}),e.jsx("style",{children:` .font-display { font-family: 'Fraunces', ui-serif, Georgia, serif; font-optical-sizing: auto; letter-spacing: -0.02em; } @keyframes kb-zoom { from { transform: scale(1.08); } to { transform: scale(1); } } .kb-zoom { animation: kb-zoom 12s ease-out forwards; } .noscroll::-webkit-scrollbar { display: none; } `})]}),e.jsxs("div",{className:"bg-neutral-950 text-neutral-100 min-h-screen",children:[e.jsx("header",{className:`fixed inset-x-0 top-0 z-40 transition-all duration-300 ${Pe?"bg-neutral-950/85 backdrop-blur-xl border-b border-white/10 py-3":"bg-gradient-to-b from-black/60 to-transparent py-4"}`,children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-6 flex items-center justify-between gap-3",children:[e.jsxs(In,{to:typeof window<"u"&&window.location.host==="listings.relevelup.com"?"/":"/public/listings",className:"flex items-center gap-2 text-white/90 hover:text-white",children:[e.jsx(qr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium hidden sm:inline",children:"All Listings"})]}),Pe&&e.jsx("div",{className:"hidden md:flex items-center gap-1 text-sm",children:[["overview","Overview"],["gallery","Gallery"],["story","The Story"],["video","Video"],["map","Location"],["payment","Payment"],["agent","Agent"]].map(([Lt,Jt])=>e.jsx("a",{href:`#${Lt}`,className:"px-3 py-1.5 rounded-full text-white/70 hover:text-white hover:bg-white/10 transition",children:Jt},Lt))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(R7t,{listingId:a.id,listingAddress:a.property_address?`${a.property_address}, ${a.city}, ${a.state}`:`${a.city}, ${a.state}`,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition text-white"}),e.jsx("button",{onClick:Je,className:"h-9 w-9 rounded-full border border-white/20 bg-white/5 backdrop-blur hover:bg-white/15 flex items-center justify-center transition","aria-label":"Share",children:e.jsx(Vl,{className:"h-4 w-4 text-white"})}),e.jsx(B,{size:"sm",onClick:()=>he(!0),className:"hidden sm:inline-flex bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4 font-medium",children:"Request Tour"})]})]})}),e.jsxs("section",{ref:Me,id:"overview",className:"relative h-[100svh] min-h-[620px] w-full overflow-hidden",children:[Be?e.jsx("img",{src:Be.photo_url,alt:a.property_address||`${a.city}, ${a.state}`,className:"absolute inset-0 h-full w-full object-cover kb-zoom"}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-neutral-800 to-neutral-950"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black via-black/50 to-black/20"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/40 via-transparent to-transparent"}),e.jsxs("div",{className:"absolute top-24 right-4 sm:right-8 z-10 flex flex-col items-end gap-2",children:[e.jsx(Ue,{className:`${O9t[a.status]} text-white border-0 uppercase tracking-widest text-[10px] px-3 py-1 rounded-full shadow-lg`,children:F9t[a.status]}),Ae.length>0&&e.jsxs("button",{onClick:()=>se(0),className:"flex items-center gap-1.5 text-xs text-white/90 bg-black/40 backdrop-blur border border-white/20 rounded-full px-3 py-1.5 hover:bg-black/60 transition",children:[e.jsx(Jf,{className:"h-3.5 w-3.5"}),Ae.length," photos"]})]}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 z-10 px-4 sm:px-8 pb-10 sm:pb-14",children:e.jsxs("div",{className:"max-w-7xl mx-auto",children:[e.jsxs("div",{className:"flex items-end justify-between gap-6 flex-wrap",children:[e.jsxs("div",{className:"max-w-3xl",children:[a.neighborhood&&e.jsxs("p",{className:"text-white/70 uppercase tracking-[0.25em] text-xs mb-3 font-medium",children:[a.neighborhood," · ",a.city,", ",a.state]}),a.property_address&&e.jsx("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:a.property_address}),!a.property_address&&e.jsxs("h1",{className:"font-display text-white text-4xl sm:text-6xl md:text-7xl leading-[0.95] mb-4 font-light",children:[a.city,", ",a.state]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx("p",{className:"font-display text-white text-3xl sm:text-4xl md:text-5xl font-medium",children:VV(a.price)}),e.jsx("div",{className:"h-8 w-px bg-white/30 hidden sm:block"}),e.jsxs("div",{className:"flex items-center gap-4 text-white/80 text-sm sm:text-base",children:[a.bedrooms&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:a.bedrooms})," bd"]}),a.bathrooms&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:a.bathrooms})," ba"]}),a.square_footage&&e.jsxs("span",{children:[e.jsx("span",{className:"font-semibold text-white",children:ZO(a.square_footage)})," sqft"]})]})]})]}),a.agent&&e.jsxs("div",{className:"hidden md:flex items-center gap-3 bg-white/10 backdrop-blur-xl border border-white/20 rounded-2xl px-4 py-3 shadow-2xl",children:[a.agent.avatar_url?e.jsx("img",{src:a.agent.avatar_url,alt:a.agent.name,className:"h-12 w-12 rounded-full object-cover"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 flex items-center justify-center",children:e.jsx(Wi,{className:"h-6 w-6 text-white"})}),e.jsxs("div",{className:"pr-2",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/60",children:"Listing Agent"}),e.jsx("p",{className:"text-white font-medium leading-tight",children:a.agent.name}),$e&&e.jsx("p",{className:"text-xs text-white/60",children:$e})]}),e.jsx(B,{size:"sm",onClick:()=>he(!0),className:"bg-white text-neutral-900 hover:bg-white/90 rounded-full h-9 px-4",children:"Contact"})]})]}),e.jsxs("div",{className:"mt-10 flex items-center gap-2 text-white/50 text-xs uppercase tracking-widest",children:[e.jsx("span",{className:"h-px w-8 bg-white/30"}),"Scroll to explore"]})]})})]}),Ye("stats")&&e.jsx("section",{className:"border-b border-white/10 bg-neutral-950",children:e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-8 grid grid-cols-2 md:grid-cols-5 gap-6",children:[a.bedrooms&&{icon:J0,label:"Bedrooms",value:a.bedrooms},a.bathrooms&&{icon:kp,label:"Bathrooms",value:a.bathrooms},a.square_footage&&{icon:ay,label:"Interior",value:`${ZO(a.square_footage)} sqft`},a.lot_size&&{icon:Z2,label:"Lot Size",value:a.lot_size},a.year_built&&{icon:yr,label:"Year Built",value:a.year_built},!a.year_built&&a.square_footage&&{icon:dw,label:"Price / sqft",value:`$${ZO(Math.round(a.price/a.square_footage))}`}].filter(Boolean).slice(0,5).map((Lt,Jt)=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-white/5 border border-white/10 flex items-center justify-center shrink-0",children:e.jsx(Lt.icon,{className:"h-4 w-4 text-white/70"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-widest text-white/50",children:Lt.label}),e.jsx("p",{className:"font-display text-2xl text-white font-light",children:Lt.value})]})]},Jt))})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 py-16 grid lg:grid-cols-3 gap-12",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-20",children:[Ye("story")&&Ge&&e.jsxs("section",{id:"story",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-3",children:"The Story"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light mb-6 text-white",children:"A closer look at this home"}),e.jsx("div",{className:"prose prose-invert prose-lg max-w-none",children:e.jsx("p",{className:"text-white/75 leading-relaxed whitespace-pre-wrap",children:tt})}),rt&&e.jsx("button",{onClick:()=>me(!ce),className:"mt-4 text-sm text-white/60 hover:text-white underline underline-offset-4",children:ce?"Show less":"Read more"}),e.jsxs("div",{className:"mt-8 flex flex-wrap gap-2",children:[e.jsxs(Ue,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1.5"}),Oze[a.property_type]]}),a.has_hoa&&e.jsx(Ue,{variant:"outline",className:"border-white/20 text-white/80 bg-white/5",children:"HOA"}),a.mls_link&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"ml-2 border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:a.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1.5"})," MLS"]})})]}),(_t||a.agent_notes&&a.agent_notes_public)&&e.jsxs("div",{className:"mt-10 rounded-2xl border border-white/10 bg-white/5 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(un,{className:"h-4 w-4 text-amber-300"}),e.jsx("p",{className:"text-[11px] uppercase tracking-[0.25em] text-white/60",children:"A note from the agent"})]}),e.jsxs("p",{className:"text-white/80 whitespace-pre-wrap leading-relaxed italic font-display",children:['"',_t||a.agent_notes,'"']})]})]}),Ye("gallery")&&Ae.length>1&&e.jsxs("section",{id:"gallery",children:[e.jsxs("div",{className:"flex items-end justify-between mb-6",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Gallery"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white",children:"Every angle, every detail"})]}),e.jsxs("button",{onClick:()=>se(0),className:"text-sm text-white/60 hover:text-white underline underline-offset-4 hidden sm:inline",children:["View all ",Ae.length]})]}),e.jsx("div",{className:"grid grid-cols-4 gap-2 sm:gap-3",children:Ae.slice(0,7).map((Lt,Jt)=>{const gt=["col-span-4 sm:col-span-2 sm:row-span-2 aspect-square sm:aspect-auto","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-2 aspect-[4/3]","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square","col-span-2 sm:col-span-1 aspect-square"],zt=Jt===6&&Ae.length>7;return e.jsxs("button",{onClick:()=>se(Jt),className:`${gt[Jt]} relative rounded-xl overflow-hidden group bg-neutral-900`,children:[e.jsx("img",{src:Lt.photo_url,alt:`Photo ${Jt+1}`,className:"absolute inset-0 h-full w-full object-cover group-hover:scale-[1.04] transition-transform duration-500"}),zt&&e.jsxs("div",{className:"absolute inset-0 bg-black/60 flex flex-col items-center justify-center text-white",children:[e.jsx(Jf,{className:"h-6 w-6 mb-1"}),e.jsxs("span",{className:"font-medium",children:["+",Ae.length-7," more"]})]})]},Lt.id)})})]}),Ye("video")&&((Ls=a.video)==null?void 0:Ls.playback_url)&&e.jsxs("section",{id:"video",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Video Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Walk through the home"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:a.video.playback_url,className:"absolute inset-0 h-full w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Video Tour"})})]}),Ye("map")&&Ke&&e.jsxs("section",{id:"map",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Location"}),e.jsxs("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:[a.neighborhood?a.neighborhood:a.city,", ",a.state]}),e.jsx("div",{className:"rounded-2xl overflow-hidden border border-white/10 shadow-2xl aspect-[16/10]",children:e.jsx("iframe",{src:Ke,className:"w-full h-full grayscale-[.2] contrast-[1.05]",loading:"lazy",title:"Map"})}),e.jsxs("div",{className:"mt-4 flex items-center gap-2 text-white/60 text-sm",children:[e.jsx(ka,{className:"h-4 w-4"}),a.property_address?`${a.property_address}, `:"",a.city,", ",a.state]})]}),Ye("payment")&&e.jsxs("section",{id:"payment",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Payment"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:"Estimate your monthly"}),e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-gradient-to-br from-white/5 to-transparent p-6 sm:p-8",children:[e.jsxs("div",{className:"flex items-baseline gap-3 mb-8",children:[e.jsxs("p",{className:"font-display text-5xl sm:text-6xl font-light text-white",children:["$",ZO(Math.round(we))]}),e.jsx("p",{className:"text-white/60",children:"/ month"})]}),e.jsxs("div",{className:"grid sm:grid-cols-3 gap-8",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Down Payment"}),e.jsxs("span",{className:"text-white font-medium",children:[le,"%"]})]}),e.jsx(jp,{value:[le],onValueChange:Lt=>ve(Lt[0]),min:0,max:50,step:1}),e.jsxs("p",{className:"text-xs text-white/50 mt-2",children:["$",ZO(Math.round(a.price*le/100))," down"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Interest Rate"}),e.jsxs("span",{className:"text-white font-medium",children:[ge.toFixed(2),"%"]})]}),e.jsx(jp,{value:[ge],onValueChange:Lt=>Te(Lt[0]),min:2,max:10,step:.125})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-white/70 text-xs uppercase tracking-widest",children:"Loan Term"}),e.jsxs("span",{className:"text-white font-medium",children:[Ie," yr"]})]}),e.jsx(jp,{value:[Ie],onValueChange:Lt=>Ce(Lt[0]),min:10,max:30,step:5})]})]}),e.jsx("p",{className:"text-xs text-white/40 mt-6",children:"Estimated principal & interest only. Taxes, insurance, and HOA not included."})]})]}),ut.map(Lt=>{const Jt=Lt.type,gt=Lt.data||{};if(Jt==="extra_video"&>.url){const zt=String(gt.url).includes("youtu")?`https://www.youtube.com/embed/${String(gt.url).split(/[/=]/).pop()}`:gt.url;return e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:gt.eyebrow||"Featured Video"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:gt.title||"Watch"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:zt,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:gt.title||"Video"})})]},Lt.id)}return Jt==="3d_tour"&>.url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"3D Tour"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:gt.title||"Step inside"}),e.jsx("div",{className:"relative rounded-2xl overflow-hidden bg-black shadow-2xl aspect-video",children:e.jsx("iframe",{src:gt.url,className:"absolute inset-0 h-full w-full",allowFullScreen:!0,title:"3D Tour"})})]},Lt.id):Jt==="floor_plan"&>.image_url?e.jsxs("section",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-[0.3em] text-white/40 mb-2",children:"Floor Plan"}),e.jsx("h2",{className:"font-display text-3xl sm:text-4xl font-light text-white mb-6",children:gt.title||"Layout"}),e.jsx("img",{src:gt.image_url,alt:"Floor plan",className:"w-full rounded-2xl border border-white/10"})]},Lt.id):Jt==="testimonial"&>.quote?e.jsxs("section",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-8",children:[e.jsxs("p",{className:"font-display italic text-2xl text-white/90 leading-relaxed",children:['"',gt.quote,'"']}),gt.author&&e.jsxs("p",{className:"mt-4 text-sm text-white/60",children:["— ",gt.author]})]},Lt.id):Jt==="custom_cta"&>.label?e.jsxs("section",{className:"rounded-2xl p-8 text-center",style:{background:bt?`${bt}22`:"rgba(255,255,255,0.05)",border:`1px solid ${bt||"rgba(255,255,255,0.1)"}`},children:[gt.title&&e.jsx("h3",{className:"font-display text-3xl text-white mb-4",children:gt.title}),e.jsx(B,{asChild:!0,size:"lg",style:bt?{background:bt}:void 0,children:e.jsx("a",{href:gt.url||"#agent",children:gt.label})})]},Lt.id):null})]}),e.jsxs("aside",{id:"agent",className:"lg:sticky lg:top-24 lg:self-start space-y-6",children:[a.agent&&e.jsxs("div",{className:"rounded-2xl border border-white/10 bg-white/[0.03] p-6 backdrop-blur",children:[e.jsxs("div",{className:"flex items-start gap-4",children:[a.agent.avatar_url?e.jsx("img",{src:a.agent.avatar_url,alt:a.agent.name,className:"h-16 w-16 rounded-full object-cover border-2 border-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-full bg-white/10 flex items-center justify-center border-2 border-white/20",children:e.jsx(Wi,{className:"h-7 w-7 text-white/70"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-white/50",children:"Listing Agent"}),e.jsx("p",{className:"font-display text-xl text-white font-medium leading-tight",children:a.agent.name}),$e&&e.jsx("p",{className:"text-sm text-white/60 mt-0.5",children:$e})]})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-2 gap-2",children:[a.agent.phone&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(Cr,{className:"h-3.5 w-3.5 mr-1.5"}),"Call"]})}),a.agent.email&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15",children:e.jsxs("a",{href:`mailto:${a.agent.email}`,children:[e.jsx(Gs,{className:"h-3.5 w-3.5 mr-1.5"}),"Email"]})})]})]}),e.jsx("div",{id:"contact",className:"rounded-2xl border border-white/10 bg-white text-neutral-900 p-6 shadow-2xl",children:e.jsx(Fze,{submitted:Y,activeTab:F,setActiveTab:z,firstName:d,setFirstName:u,lastName:h,setLastName:p,email:f,setEmail:y,phone:_,setPhone:v,message:j,setMessage:w,preferredDate:S,setPreferredDate:A,preferredTime:E,setPreferredTime:O,showingMode:D,setShowingMode:I,isSubmitting:H,onSubmit:ke})})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-neutral-950/95 backdrop-blur-xl border-t border-white/10 px-4 py-3 flex items-center gap-2 safe-area-inset-bottom",children:[((xs=a.agent)==null?void 0:xs.phone)&&e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"border-white/20 bg-white/5 text-white hover:bg-white/15 flex-1",children:e.jsxs("a",{href:`tel:${a.agent.phone}`,children:[e.jsx(Cr,{className:"h-4 w-4 mr-1.5"}),"Call"]})}),e.jsxs(B,{onClick:()=>he(!0),className:"bg-white text-neutral-900 hover:bg-white/90 flex-[2] font-medium",children:[e.jsx(Xf,{className:"h-4 w-4 mr-1.5"}),"Request Tour"]})]}),e.jsx("footer",{className:"border-t border-white/10 py-10 mt-24 mb-16 lg:mb-0",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-4 sm:px-8 flex flex-col sm:flex-row items-center justify-between gap-4 text-sm text-white/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("img",{src:Rze,alt:"LevelUp",className:"h-6 opacity-80"}),e.jsxs("span",{children:["© ",new Date().getFullYear()," LevelUp"]})]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"hover:text-white",children:"relevelup.com"})]})}),e.jsx(_s,{open:ee!==null,onOpenChange:()=>se(null),children:e.jsxs(bs,{className:"max-w-6xl p-0 bg-black/95 border-0",children:[e.jsx(js,{className:"sr-only",children:e.jsx(ws,{children:"Photo Gallery"})}),e.jsx("button",{onClick:()=>se(null),className:"absolute right-4 top-4 z-50 rounded-full bg-white/10 hover:bg-white/20 p-2 text-white",children:e.jsx($n,{className:"h-5 w-5"})}),ee!==null&&Ae[ee]&&e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:Ae[ee].photo_url,alt:`Photo ${ee+1}`,className:"w-full max-h-[85vh] object-contain"}),Ae.length>1&&e.jsxs(e.Fragment,{children:[e.jsx("button",{onClick:it,className:"absolute left-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(ml,{className:"h-6 w-6"})}),e.jsx("button",{onClick:je,className:"absolute right-4 top-1/2 -translate-y-1/2 rounded-full bg-white/10 hover:bg-white/20 p-3 text-white",children:e.jsx(ga,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white bg-black/60 px-3 py-1 rounded-full text-sm",children:[ee+1," / ",Ae.length]})]})]})]})}),e.jsx(_s,{open:oe,onOpenChange:he,children:e.jsxs(bs,{className:"max-w-md p-0 bg-white text-neutral-900",children:[e.jsx(js,{className:"sr-only",children:e.jsx(ws,{children:"Contact the agent"})}),e.jsx("div",{className:"p-6",children:e.jsx(Fze,{submitted:Y,activeTab:F,setActiveTab:z,firstName:d,setFirstName:u,lastName:h,setLastName:p,email:f,setEmail:y,phone:_,setPhone:v,message:j,setMessage:w,preferredDate:S,setPreferredDate:A,preferredTime:E,setPreferredTime:O,showingMode:D,setShowingMode:I,isSubmitting:H,onSubmit:ke})})]})})]})]})}function Fze(s){const{submitted:t,activeTab:n,setActiveTab:r,firstName:a,setFirstName:i,lastName:l,setLastName:o,email:c,setEmail:d,phone:u,setPhone:h,message:p,setMessage:f,preferredDate:y,setPreferredDate:_,preferredTime:v,setPreferredTime:j,showingMode:w,setShowingMode:S,isSubmitting:A,onSubmit:E}=s;return t?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("div",{className:"h-14 w-14 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(Lr,{className:"h-7 w-7 text-emerald-600"})}),e.jsx("p",{className:"font-display text-2xl font-medium mb-1",children:n==="showing"?"Showing request sent!":"Thanks — you're all set!"}),e.jsx("p",{className:"text-sm text-neutral-600",children:n==="showing"?"The listing agent will reach out to confirm your showing time.":"The listing agent will contact you shortly with more details."})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-[0.25em] text-neutral-500 mb-1",children:"Interested?"}),e.jsx("h3",{className:"font-display text-2xl font-medium",children:"Talk to the listing agent"})]}),e.jsxs(Fr,{value:n,onValueChange:O=>r(O),children:[e.jsxs(Rr,{className:"grid w-full grid-cols-2 mb-4",children:[e.jsxs(Zt,{value:"info",className:"gap-1.5",children:[e.jsx(Ai,{className:"h-3.5 w-3.5"})," Get Info"]}),e.jsxs(Zt,{value:"showing",className:"gap-1.5",children:[e.jsx(Xf,{className:"h-3.5 w-3.5"})," Request Tour"]})]}),e.jsxs("form",{onSubmit:E,className:"space-y-3",children:[e.jsxs(is,{value:"showing",className:"mt-0 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"preferredDate",children:"Preferred Date *"}),e.jsx(ye,{id:"preferredDate",type:"date",value:y,onChange:O=>_(O.target.value),min:new Date().toISOString().split("T")[0],required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"preferredTime",children:"Preferred Time"}),e.jsxs(us,{value:v,onValueChange:j,children:[e.jsx(ls,{id:"preferredTime",children:e.jsx(hs,{placeholder:"Any time"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"morning",children:"Morning (9am–12pm)"}),e.jsx(Ze,{value:"afternoon",children:"Afternoon (12pm–5pm)"}),e.jsx(Ze,{value:"evening",children:"Evening (5pm–8pm)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"showingMode",children:"Tour Type"}),e.jsxs(us,{value:w,onValueChange:O=>S(O),children:[e.jsx(ls,{id:"showingMode",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"in_person",children:"🏡 In-person showing"}),e.jsx(Ze,{value:"video",children:"📱 Video tour (FaceTime/Zoom)"}),e.jsx(Ze,{value:"either",children:"Either works for me"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"firstName",children:"First Name *"}),e.jsx(ye,{id:"firstName",value:a,onChange:O=>i(O.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"lastName",children:"Last Name"}),e.jsx(ye,{id:"lastName",value:l,onChange:O=>o(O.target.value)})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"email",children:"Email *"}),e.jsx(ye,{id:"email",type:"email",value:c,onChange:O=>d(O.target.value),required:!0})]}),e.jsxs("div",{children:[e.jsxs(ne,{htmlFor:"phone",children:["Phone ",n==="showing"&&"*"]}),e.jsx(ye,{id:"phone",type:"tel",value:u,onChange:O=>h(O.target.value),required:n==="showing"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"message",children:n==="showing"?"Anything else?":"Message (optional)"}),e.jsx(Ms,{id:"message",value:p,onChange:O=>f(O.target.value),rows:2})]}),e.jsx(B,{type:"submit",disabled:A,className:"w-full bg-neutral-900 hover:bg-neutral-800 text-white h-11",children:A?"Sending…":n==="showing"?"Request Showing":"Get More Info"}),e.jsx("p",{className:"text-[11px] text-neutral-500 text-center",children:"The listing agent will contact you directly. No spam."})]})]})]})}const Kpe="/assets/levelup-logo-white-C2RAgAoG.png",z9t="/assets/listings-hero-noir-BHCJrhvU.jpg";var Ult={exports:{}};(function(s,t){(function(n,r){s.exports=r()})(kh,function(){let n,r,a;function i(o,c){if(!n)n=c;else if(!r)r=c;else{const d={};n(d),a=c(d);const u="self.onerror = function() { console.error('An error occurred while parsing the WebWorker bundle. This is most likely due to improper transpilation by Babel; please see https://docs.mapbox.com/mapbox-gl-js/guides/install/#transpiling'); }; var sharedChunk = {}; ("+n+")(sharedChunk); ("+r+")(undefined, sharedChunk); self.onerror = null;";typeof window<"u"&&window&&window.URL&&window.URL.createObjectURL&&(a.workerUrl=window.URL.createObjectURL(new Blob([u],{type:"text/javascript"})))}}i(["exports"],function(o){var c=1e-6,d=typeof Float32Array<"u"?Float32Array:Array;function u(b,m){var x=m[0],k=m[1],T=m[2],P=m[3],R=x*P-T*k;return R?(b[0]=P*(R=1/R),b[1]=-k*R,b[2]=-T*R,b[3]=x*R,b):null}function h(){var b=new d(9);return d!=Float32Array&&(b[1]=0,b[2]=0,b[3]=0,b[5]=0,b[6]=0,b[7]=0),b[0]=1,b[4]=1,b[8]=1,b}function p(b,m){var x=m[0],k=m[1],T=m[2],P=m[3],R=m[4],U=m[5],V=m[6],X=m[7],ie=m[8];return b[0]=R*ie-U*X,b[1]=T*X-k*ie,b[2]=k*U-T*R,b[3]=U*V-P*ie,b[4]=x*ie-T*V,b[5]=T*P-x*U,b[6]=P*X-R*V,b[7]=k*V-x*X,b[8]=x*R-k*P,b}function f(b,m,x){var k=m[0],T=m[1],P=m[2],R=m[3],U=m[4],V=m[5],X=m[6],ie=m[7],ue=m[8],pe=x[0],be=x[1],Se=x[2],Le=x[3],ze=x[4],We=x[5],ct=x[6],nt=x[7],ft=x[8];return b[0]=pe*k+be*R+Se*X,b[1]=pe*T+be*U+Se*ie,b[2]=pe*P+be*V+Se*ue,b[3]=Le*k+ze*R+We*X,b[4]=Le*T+ze*U+We*ie,b[5]=Le*P+ze*V+We*ue,b[6]=ct*k+nt*R+ft*X,b[7]=ct*T+nt*U+ft*ie,b[8]=ct*P+nt*V+ft*ue,b}function y(){var b=new d(16);return d!=Float32Array&&(b[1]=0,b[2]=0,b[3]=0,b[4]=0,b[6]=0,b[7]=0,b[8]=0,b[9]=0,b[11]=0,b[12]=0,b[13]=0,b[14]=0),b[0]=1,b[5]=1,b[10]=1,b[15]=1,b}function _(b){var m=new d(16);return m[0]=b[0],m[1]=b[1],m[2]=b[2],m[3]=b[3],m[4]=b[4],m[5]=b[5],m[6]=b[6],m[7]=b[7],m[8]=b[8],m[9]=b[9],m[10]=b[10],m[11]=b[11],m[12]=b[12],m[13]=b[13],m[14]=b[14],m[15]=b[15],m}function v(b){return b[0]=1,b[1]=0,b[2]=0,b[3]=0,b[4]=0,b[5]=1,b[6]=0,b[7]=0,b[8]=0,b[9]=0,b[10]=1,b[11]=0,b[12]=0,b[13]=0,b[14]=0,b[15]=1,b}function j(b,m){var x=m[0],k=m[1],T=m[2],P=m[3],R=m[4],U=m[5],V=m[6],X=m[7],ie=m[8],ue=m[9],pe=m[10],be=m[11],Se=m[12],Le=m[13],ze=m[14],We=m[15],ct=x*U-k*R,nt=x*V-T*R,ft=x*X-P*R,wt=k*V-T*U,Nt=k*X-P*U,Wt=T*X-P*V,Ft=ie*Le-ue*Se,Gt=ie*ze-pe*Se,Ut=ie*We-be*Se,qt=ue*ze-pe*Le,zs=ue*We-be*Le,qs=pe*We-be*ze,Xs=ct*qs-nt*zs+ft*qt+wt*Ut-Nt*Gt+Wt*Ft;return Xs?(b[0]=(U*qs-V*zs+X*qt)*(Xs=1/Xs),b[1]=(T*zs-k*qs-P*qt)*Xs,b[2]=(Le*Wt-ze*Nt+We*wt)*Xs,b[3]=(pe*Nt-ue*Wt-be*wt)*Xs,b[4]=(V*Ut-R*qs-X*Gt)*Xs,b[5]=(x*qs-T*Ut+P*Gt)*Xs,b[6]=(ze*ft-Se*Wt-We*nt)*Xs,b[7]=(ie*Wt-pe*ft+be*nt)*Xs,b[8]=(R*zs-U*Ut+X*Ft)*Xs,b[9]=(k*Ut-x*zs-P*Ft)*Xs,b[10]=(Se*Nt-Le*ft+We*ct)*Xs,b[11]=(ue*ft-ie*Nt-be*ct)*Xs,b[12]=(U*Gt-R*qt-V*Ft)*Xs,b[13]=(x*qt-k*Gt+T*Ft)*Xs,b[14]=(Le*nt-Se*wt-ze*ct)*Xs,b[15]=(ie*wt-ue*nt+pe*ct)*Xs,b):null}function w(b,m,x){var k=m[0],T=m[1],P=m[2],R=m[3],U=m[4],V=m[5],X=m[6],ie=m[7],ue=m[8],pe=m[9],be=m[10],Se=m[11],Le=m[12],ze=m[13],We=m[14],ct=m[15],nt=x[0],ft=x[1],wt=x[2],Nt=x[3];return b[0]=nt*k+ft*U+wt*ue+Nt*Le,b[1]=nt*T+ft*V+wt*pe+Nt*ze,b[2]=nt*P+ft*X+wt*be+Nt*We,b[3]=nt*R+ft*ie+wt*Se+Nt*ct,b[4]=(nt=x[4])*k+(ft=x[5])*U+(wt=x[6])*ue+(Nt=x[7])*Le,b[5]=nt*T+ft*V+wt*pe+Nt*ze,b[6]=nt*P+ft*X+wt*be+Nt*We,b[7]=nt*R+ft*ie+wt*Se+Nt*ct,b[8]=(nt=x[8])*k+(ft=x[9])*U+(wt=x[10])*ue+(Nt=x[11])*Le,b[9]=nt*T+ft*V+wt*pe+Nt*ze,b[10]=nt*P+ft*X+wt*be+Nt*We,b[11]=nt*R+ft*ie+wt*Se+Nt*ct,b[12]=(nt=x[12])*k+(ft=x[13])*U+(wt=x[14])*ue+(Nt=x[15])*Le,b[13]=nt*T+ft*V+wt*pe+Nt*ze,b[14]=nt*P+ft*X+wt*be+Nt*We,b[15]=nt*R+ft*ie+wt*Se+Nt*ct,b}function S(b,m,x){var k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le=x[0],ze=x[1],We=x[2];return m===b?(b[12]=m[0]*Le+m[4]*ze+m[8]*We+m[12],b[13]=m[1]*Le+m[5]*ze+m[9]*We+m[13],b[14]=m[2]*Le+m[6]*ze+m[10]*We+m[14],b[15]=m[3]*Le+m[7]*ze+m[11]*We+m[15]):(T=m[1],P=m[2],R=m[3],U=m[4],V=m[5],X=m[6],ie=m[7],ue=m[8],pe=m[9],be=m[10],Se=m[11],b[0]=k=m[0],b[1]=T,b[2]=P,b[3]=R,b[4]=U,b[5]=V,b[6]=X,b[7]=ie,b[8]=ue,b[9]=pe,b[10]=be,b[11]=Se,b[12]=k*Le+U*ze+ue*We+m[12],b[13]=T*Le+V*ze+pe*We+m[13],b[14]=P*Le+X*ze+be*We+m[14],b[15]=R*Le+ie*ze+Se*We+m[15]),b}function A(b,m,x){var k=x[0],T=x[1],P=x[2];return b[0]=m[0]*k,b[1]=m[1]*k,b[2]=m[2]*k,b[3]=m[3]*k,b[4]=m[4]*T,b[5]=m[5]*T,b[6]=m[6]*T,b[7]=m[7]*T,b[8]=m[8]*P,b[9]=m[9]*P,b[10]=m[10]*P,b[11]=m[11]*P,b[12]=m[12],b[13]=m[13],b[14]=m[14],b[15]=m[15],b}function E(b,m,x){var k=Math.sin(x),T=Math.cos(x),P=m[4],R=m[5],U=m[6],V=m[7],X=m[8],ie=m[9],ue=m[10],pe=m[11];return m!==b&&(b[0]=m[0],b[1]=m[1],b[2]=m[2],b[3]=m[3],b[12]=m[12],b[13]=m[13],b[14]=m[14],b[15]=m[15]),b[4]=P*T+X*k,b[5]=R*T+ie*k,b[6]=U*T+ue*k,b[7]=V*T+pe*k,b[8]=X*T-P*k,b[9]=ie*T-R*k,b[10]=ue*T-U*k,b[11]=pe*T-V*k,b}function O(b,m,x){var k=Math.sin(x),T=Math.cos(x),P=m[0],R=m[1],U=m[2],V=m[3],X=m[8],ie=m[9],ue=m[10],pe=m[11];return m!==b&&(b[4]=m[4],b[5]=m[5],b[6]=m[6],b[7]=m[7],b[12]=m[12],b[13]=m[13],b[14]=m[14],b[15]=m[15]),b[0]=P*T-X*k,b[1]=R*T-ie*k,b[2]=U*T-ue*k,b[3]=V*T-pe*k,b[8]=P*k+X*T,b[9]=R*k+ie*T,b[10]=U*k+ue*T,b[11]=V*k+pe*T,b}function D(b,m,x){var k=Math.sin(x),T=Math.cos(x),P=m[0],R=m[1],U=m[2],V=m[3],X=m[4],ie=m[5],ue=m[6],pe=m[7];return m!==b&&(b[8]=m[8],b[9]=m[9],b[10]=m[10],b[11]=m[11],b[12]=m[12],b[13]=m[13],b[14]=m[14],b[15]=m[15]),b[0]=P*T+X*k,b[1]=R*T+ie*k,b[2]=U*T+ue*k,b[3]=V*T+pe*k,b[4]=X*T-P*k,b[5]=ie*T-R*k,b[6]=ue*T-U*k,b[7]=pe*T-V*k,b}function I(b,m){return b[0]=m[0],b[1]=0,b[2]=0,b[3]=0,b[4]=0,b[5]=m[1],b[6]=0,b[7]=0,b[8]=0,b[9]=0,b[10]=m[2],b[11]=0,b[12]=0,b[13]=0,b[14]=0,b[15]=1,b}function F(b,m,x){var k,T,P,R=x[0],U=x[1],V=x[2],X=Math.sqrt(R*R+U*U+V*V);return X0&&(P=1/Math.sqrt(P)),b[0]=m[0]*P,b[1]=m[1]*P,b[2]=m[2]*P,b}function Ae(b,m){return b[0]*m[0]+b[1]*m[1]+b[2]*m[2]}function Be(b,m,x){var k=m[0],T=m[1],P=m[2],R=x[0],U=x[1],V=x[2];return b[0]=T*V-P*U,b[1]=P*R-k*V,b[2]=k*U-T*R,b}function we(b,m,x,k){var T=m[0],P=m[1],R=m[2];return b[0]=T+k*(x[0]-T),b[1]=P+k*(x[1]-P),b[2]=R+k*(x[2]-R),b}function Je(b,m,x){var k=m[0],T=m[1],P=m[2],R=x[3]*k+x[7]*T+x[11]*P+x[15];return b[0]=(x[0]*k+x[4]*T+x[8]*P+x[12])/(R=R||1),b[1]=(x[1]*k+x[5]*T+x[9]*P+x[13])/R,b[2]=(x[2]*k+x[6]*T+x[10]*P+x[14])/R,b}function ke(b,m,x){var k=m[0],T=m[1],P=m[2];return b[0]=k*x[0]+T*x[3]+P*x[6],b[1]=k*x[1]+T*x[4]+P*x[7],b[2]=k*x[2]+T*x[5]+P*x[8],b}function it(b,m,x){var k=x[0],T=x[1],P=x[2],R=x[3],U=m[0],V=m[1],X=m[2],ie=T*X-P*V,ue=P*U-k*X,pe=k*V-T*U;return b[0]=U+R*(ie+=ie)+T*(pe+=pe)-P*(ue+=ue),b[1]=V+R*ue+P*ie-k*pe,b[2]=X+R*pe+k*ue-T*ie,b}function je(b){return b[0]=0,b[1]=0,b[2]=0,b}function He(b,m){return b[0]===m[0]&&b[1]===m[1]&&b[2]===m[2]}var $e=ce,Ke=me,Ge=ee;function rt(){var b=new d(4);return d!=Float32Array&&(b[0]=0,b[1]=0,b[2]=0,b[3]=0),b}function tt(b,m,x){return b[0]=m[0]*x,b[1]=m[1]*x,b[2]=m[2]*x,b[3]=m[3]*x,b}function at(b,m){var x=m[0],k=m[1],T=m[2],P=m[3],R=x*x+k*k+T*T+P*P;return R>0&&(R=1/Math.sqrt(R)),b[0]=x*R,b[1]=k*R,b[2]=T*R,b[3]=P*R,b}function Ye(b,m){return b[0]*m[0]+b[1]*m[1]+b[2]*m[2]+b[3]*m[3]}function ut(b,m,x){var k=m[0],T=m[1],P=m[2],R=m[3];return b[0]=x[0]*k+x[4]*T+x[8]*P+x[12]*R,b[1]=x[1]*k+x[5]*T+x[9]*P+x[13]*R,b[2]=x[2]*k+x[6]*T+x[10]*P+x[14]*R,b[3]=x[3]*k+x[7]*T+x[11]*P+x[15]*R,b}function _t(){var b=new d(4);return d!=Float32Array&&(b[0]=0,b[1]=0,b[2]=0),b[3]=1,b}function bt(b){return b[0]=0,b[1]=0,b[2]=0,b[3]=1,b}function $t(b,m,x){x*=.5;var k=m[0],T=m[1],P=m[2],R=m[3],U=Math.sin(x),V=Math.cos(x);return b[0]=k*V+R*U,b[1]=T*V+P*U,b[2]=P*V-T*U,b[3]=R*V-k*U,b}function Yt(b,m,x){x*=.5;var k=m[0],T=m[1],P=m[2],R=m[3],U=Math.sin(x),V=Math.cos(x);return b[0]=k*V-P*U,b[1]=T*V+R*U,b[2]=P*V+k*U,b[3]=R*V-T*U,b}Y(),rt();var Ds,Ls,xs,Lt=at,Jt=(Ds=Y(),Ls=se(1,0,0),xs=se(0,1,0),function(b,m,x){var k=Ae(m,x);return k<-.999999?(Be(Ds,Ls,m),Ge(Ds)<1e-6&&Be(Ds,xs,m),Re(Ds,Ds),function(T,P,R){R*=.5;var U=Math.sin(R);T[0]=U*P[0],T[1]=U*P[1],T[2]=U*P[2],T[3]=Math.cos(R)}(b,Ds,Math.PI),b):k>.999999?(b[0]=0,b[1]=0,b[2]=0,b[3]=1,b):(Be(Ds,m,x),b[0]=Ds[0],b[1]=Ds[1],b[2]=Ds[2],b[3]=1+k,Lt(b,b))});function gt(){var b=new d(2);return d!=Float32Array&&(b[0]=0,b[1]=0),b}function zt(b,m){var x=new d(2);return x[0]=b,x[1]=m,x}function As(b,m,x){return b[0]=m,b[1]=x,b}function Xt(b,m,x){return b[0]=m[0]+x[0],b[1]=m[1]+x[1],b}function Qs(b,m,x){return b[0]=m[0]-x[0],b[1]=m[1]-x[1],b}function ks(b,m,x){return b[0]=m[0]*x,b[1]=m[1]*x,b}function $s(b){var m=b[0],x=b[1];return Math.sqrt(m*m+x*x)}function an(b,m){var x=m[0],k=m[1],T=x*x+k*k;return T>0&&(T=1/Math.sqrt(T)),b[0]=m[0]*T,b[1]=m[1]*T,b}function tn(b,m){return b[0]*m[0]+b[1]*m[1]}_t(),_t(),h();var er,xn,Pn=Qs;function Qn(b){return b&&b.__esModule&&Object.prototype.hasOwnProperty.call(b,"default")?b.default:b}gt();var sa=function(){if(xn)return er;function b(m,x,k,T){this.cx=3*m,this.bx=3*(k-m)-this.cx,this.ax=1-this.cx-this.bx,this.cy=3*x,this.by=3*(T-x)-this.cy,this.ay=1-this.cy-this.by,this.p1x=m,this.p1y=x,this.p2x=k,this.p2y=T}return xn=1,er=b,b.prototype={sampleCurveX:function(m){return((this.ax*m+this.bx)*m+this.cx)*m},sampleCurveY:function(m){return((this.ay*m+this.by)*m+this.cy)*m},sampleCurveDerivativeX:function(m){return(3*this.ax*m+2*this.bx)*m+this.cx},solveCurveX:function(m,x){if(x===void 0&&(x=1e-6),m<0)return 0;if(m>1)return 1;for(var k=m,T=0;T<8;T++){var P=this.sampleCurveX(k)-m;if(Math.abs(P)P?U=k:V=k,k=.5*(V-U)+U;return k},solve:function(m,x){return this.sampleCurveY(this.solveCurveX(m,x))}},er}(),na=Qn(sa);function Es(b,m){this.x=b,this.y=m}function mi(b,m){if(Array.isArray(b)){if(!Array.isArray(m)||b.length!==m.length)return!1;for(let x=0;x=1)return 1;const m=b*b,x=m*b;return 4*(b<.5?x:3*(b-m)+x-.75)}function ts(b,m,x,k){const T=new na(b,m,x,k);return function(P){return T.solve(P)}}const Fe=ts(.25,.1,.25,1);function Qe(b,m,x){return Math.min(x,Math.max(m,b))}function ot(b,m,x){return(x=Qe((x-b)/(m-b),0,1))*x*(3-2*x)}function St(b,m,x){const k=x-m,T=((b-m)%k+k)%k+m;return T===m?x:T}function Bt(b,m,x){if(!b.length)return x(null,[]);let k=b.length;const T=new Array(b.length);let P=null;b.forEach((R,U)=>{m(R,(V,X)=>{V&&(P=V),T[U]=X,--k===0&&x(P,T)})})}let Vt=1;function fs(){return Vt++}function lt(b){return b<=1?1:Math.pow(2,Math.ceil(Math.log2(b)))}function ns(b,m){b.forEach(x=>{m[x]&&(m[x]=m[x].bind(m))})}function Vs(b,m,x){const k={};for(const T in b)k[T]=m.call(this,b[T],T,b);return k}function ys(b,m,x){const k={};for(const T in b)m.call(this,b[T],T,b)&&(k[T]=b[T]);return k}function mn(b){return Array.isArray(b)?b.map(mn):typeof b=="object"&&b?Vs(b,mn):b}function On(b,m){for(let x=0;x=0)return!0;return!1}const vn={};function Yn(b){vn[b]||(typeof console<"u"&&console.warn(b),vn[b]=!0)}function _r(b,m,x){return(x.y-b.y)*(m.x-b.x)>(m.y-b.y)*(x.x-b.x)}function wr(b){let m=0;for(let x,k,T=0,P=b.length,R=P-1;T@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)(?:\=(?:([^\x00-\x20\(\)<>@\,;\:\\"\/\[\]\?\=\{\}\x7F]+)|(?:\"((?:[^"\\]|\\.)*)\")))?/g,(x,k,T,P)=>{const R=T||P;return m[k]=!R||R.toLowerCase(),""}),m["max-age"]){const x=parseInt(m["max-age"],10);isNaN(x)?delete m["max-age"]:m["max-age"]=x}return m}let io,Xa=null;function Mr(b,m){return[b[4*m],b[4*m+1],b[4*m+2],b[4*m+3]]}function qi(b,m,x,k){for(;m>1;b[T]>1;b[T]<=k?m=T+1:x=T}return m}function si(b){return b>0?1/(1.001-b):1+b}function Yi(b){return b>0?1-1/(1.001-b):-b}function Zi(b,m,x){return(b-m.min)*(x.max-x.min)/(m.max-m.min)+x.min}const aa={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(!aa.API_URL)return null;try{const b=new URL(aa.API_URL);return b.hostname==="api.mapbox.cn"?"https://events.mapbox.cn/events/v2":b.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 Nn(){return new URL(aa.DRACO_URL,aa.API_URL).href}function La(){if(typeof WebAssembly!="object")throw new Error("WebAssembly not supported, cannot instantiate meshoptimizer");return new URL(function(){if(io===void 0){if(typeof WebAssembly!="object")return!1;const b=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]);io=WebAssembly.validate(b)}return io}()?aa.MESHOPT_SIMD_URL:aa.MESHOPT_URL,aa.API_URL).href}function so(){return new URL(aa.BUILDING_GEN_URL,aa.API_URL).href}function tl(b){return aa.API_URL_REGEX.test(b)}function jl(b){return aa.API_SPRITE_REGEX.test(b)}let No,jd,Bu,kf,$u,um;function Uu(){return No==null&&(No=self.OffscreenCanvas&&new OffscreenCanvas(1,1).getContext("2d")&&typeof self.createImageBitmap=="function"),No}const $d={now:()=>kf!==void 0?kf:performance.now(),setNow(b){kf=b},restoreNow(){kf=void 0},frame(b){const m=requestAnimationFrame(b);return{cancel:()=>cancelAnimationFrame(m)}},getImageData(b,m=0){const{width:x,height:k}=b;$u||($u=document.createElement("canvas"));const T=$u.getContext("2d",{willReadFrequently:!0});if(!T)throw new Error("failed to create canvas 2d context");return(x>$u.width||k>$u.height)&&($u.width=x,$u.height=k),T.clearRect(-m,-m,x+2*m,k+2*m),T.drawImage(b,0,0,x,k),T.getImageData(-m,-m,x+2*m,k+2*m)},resolveURL:b=>(jd||(jd=document.createElement("a")),jd.href=b,jd.href),get devicePixelRatio(){return window.devicePixelRatio},get prefersReducedMotion(){return!!window.matchMedia&&(Bu==null&&(Bu=window.matchMedia("(prefers-reduced-motion: reduce)")),Bu.matches)},hasCanvasFingerprintNoise(){if(um!==void 0)return um;if(!Uu())return um=!1,!1;const b=new OffscreenCanvas(85,1),m=b.getContext("2d",{willReadFrequently:!0});let x=0;for(let T=0;T0?`?${P}`:""}`}const hm="mapbox-tiles";let Ey=500,Ay=50;const Sf=["language","worldview","jobid"];let mh;function ux(){try{return caches}catch{}}function mo(){const b=ux();b&&mh==null&&(mh=b.open(hm))}let zb=1/0;const mm={supported:!1,testSupport:function(b){!qu&&hx&&(sl?mu(b):Rh=b)}};let Rh,hx,qu=!1,sl=!1;const o0=typeof self<"u"?self:{};function mu(b){const m=b.createTexture();b.bindTexture(b.TEXTURE_2D,m);try{if(b.texImage2D(b.TEXTURE_2D,0,b.RGBA,b.RGBA,b.UNSIGNED_BYTE,hx),b.isContextLost())return;mm.supported=!0}catch{}b.deleteTexture(m),qu=!0}o0.document&&(hx=o0.document.createElement("img"),hx.onload=function(){Rh&&mu(Rh),Rh=null,sl=!0},hx.onerror=function(){qu=!0,Rh=null},hx.src="data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAQAAAAfQ//73v/+BiOh/AAA=");const l0={Unknown:"Unknown",Style:"Style",Source:"Source",Tile:"Tile",Glyphs:"Glyphs",SpriteImage:"SpriteImage",SpriteJSON:"SpriteJSON",Iconset:"Iconset",Image:"Image",Model:"Model"};Object.freeze(l0);class aj extends Error{constructor(m,x,k){x===401&&tl(k)&&(m+=": you may have provided an invalid Mapbox access token. See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes"),super(m),this.status=x,this.url=k}toString(){return`${this.name}: ${this.message} (${this.status}): ${this.url}`}}function Cf(b){return typeof b=="object"&&b!==null&&"status"in b&&b.status===404}const Ka=xa()?()=>self.worker.referrer:()=>(location.protocol==="blob:"?parent:self).location.href,My=function(b,m){return/^file:/.test(x=b.url)||/^file:/.test(Ka())&&!/^\w+:/.test(x)?function(k,T){const P=new XMLHttpRequest;P.open(k.method||"GET",k.url,!0),k.type==="arrayBuffer"&&(P.responseType="arraybuffer");for(const R in k.headers)P.setRequestHeader(R,k.headers[R]);return k.type==="json"&&(P.responseType="text",P.setRequestHeader("Accept","application/json")),P.withCredentials=k.credentials==="include",P.onerror=()=>{T(new Error(P.statusText))},P.onload=()=>{if((P.status>=200&&P.status<300||P.status===0)&&P.response!==null){let R=P.response;if(k.type==="json")try{R=JSON.parse(P.response)}catch(V){return T(V)}const U=new Headers;P.getAllResponseHeaders().trim().split(/[\r\n]+/).forEach(V=>{const X=V.split(": "),ie=X.shift(),ue=X.join(": ");U.append(ie,ue)}),T(null,R,U)}else T(new aj(P.statusText,P.status,k.url))},P.send(k.body),{cancel:()=>P.abort()}}(b,m):function(k,T){const P=new AbortController,R=new Request(k.url,{method:k.method||"GET",body:k.body,credentials:k.credentials,headers:k.headers,referrer:Ka(),referrerPolicy:k.referrerPolicy,signal:P.signal});let U=!1,V=!1;const X=(ie=R.url).indexOf("sku=")>0&&tl(ie);var ie;k.type==="json"&&R.headers.set("Accept","application/json");const ue=(be,Se,Le)=>{if(V)return;if(be&&be.message!=="SecurityError"&&Yn(be.toString()),Se&&Le)return pe(Se);const ze=Date.now();fetch(R).then(We=>{if(We.ok){const ct=X?We.clone():null;return pe(We,ct,ze)}return T(new aj(We.statusText,We.status,k.url))}).catch(We=>{We.name!=="AbortError"&&T(new Error(`${We.message} ${k.url}`))})},pe=(be,Se,Le)=>{(k.type==="arrayBuffer"?be.arrayBuffer():k.type==="json"?be.json():be.text()).then(ze=>{V||(Se&&Le&&function(We,ct,nt){if(mo(),mh==null)return;const ft=Ki(ct.headers.get("cache-control")||"");if(ft["no-store"])return;const wt={status:ct.status,statusText:ct.statusText,headers:new Headers};ct.headers.forEach((Ut,qt)=>wt.headers.set(qt,Ut)),ft["max-age"]&&wt.headers.set("Expires",new Date(nt+1e3*ft["max-age"]).toUTCString());const Nt=wt.headers.get("expires");if(!Nt||new Date(Nt).getTime()-nt<42e4)return;let Wt=rj(We.url,{persistentParams:Sf});if(ct.status===206){const Ut=We.headers.get("Range");if(!Ut)return;wt.status=200,Wt=s1(Wt,{range:Ut})}const Ft=new Response((Gt=ct.status)!==200&&Gt!==404&&[101,103,204,205,304].includes(Gt)?null:ct.body,wt);var Gt;mo(),mh!=null&&mh.then(Ut=>Ut.put(Wt,Ft)).catch(Ut=>Yn(Ut.message))}(R,Se,Le),U=!0,T(null,ze,be.headers))}).catch(ze=>{V||T(new Error(ze.message))})};return X?function(be,Se){if(mo(),mh==null)return Se(null);mh.then(Le=>{let ze=rj(be.url,{persistentParams:Sf});const We=be.headers.get("Range");We&&(ze=s1(ze,{range:We})),Le.match(ze).then(ct=>{const nt=function(ft){if(!ft)return!1;const wt=new Date(ft.headers.get("expires")||0),Nt=Ki(ft.headers.get("cache-control")||"");return Number(wt)>Date.now()&&!Nt["no-cache"]}(ct);Le.delete(ze).catch(Se),nt&&Le.put(ze,ct.clone()).catch(Se),Se(null,ct,nt)}).catch(Se)}).catch(Se)}(R,ue):ue(null,null),{cancel:()=>{V=!0,U||P.abort()}}}(b,m);var x},Iy=function(b,m){return My(Object.assign(b,{type:"arrayBuffer"}),m)};function Ym(b){const m=document.createElement("a");return m.href=b,m.protocol===location.protocol&&m.host===location.host}let Zm,Ip;Zm=[],Ip=0;const mx=function(b,m){if(mm.supported&&(b.headers||(b.headers={}),b.headers.accept="image/webp,*/*"),Ip>=aa.MAX_PARALLEL_IMAGE_REQUESTS){const P={requestParameters:b,callback:m,cancelled:!1,cancel(){this.cancelled=!0}};return Zm.push(P),P}Ip++;let x=!1;const k=()=>{if(!x)for(x=!0,Ip--;Zm.length&&Ip{k(),P?m(P):R&&function(V,X){const ie=new Blob([new Uint8Array(V)],{type:"image/png"});createImageBitmap(ie).then(ue=>{X(null,ue)}).catch(ue=>{X(new Error(`Could not load image because of ${ue.message}. Please make sure to use a supported image type such as PNG or JPEG. Note that SVGs are not supported.`))})}(R,(V,X)=>m(V,X,U))});return{cancel:()=>{T.cancel(),k()}}};var lg,Bb,Pp,Qm={exports:{}},Tf={exports:{}},Py={exports:{}},$b=function(){if(Pp)return Qm.exports;Pp=1;var b=(lg||(lg=1,Tf.exports=function(x,k){var T,P,R,U,V,X,ie,ue;for(P=x.length-(T=3&x.length),R=k,V=3432918353,X=461845907,ue=0;ue>>16)*V&65535)<<16)&4294967295)<<15|ie>>>17))*X+(((ie>>>16)*X&65535)<<16)&4294967295)<<13|R>>>19))+((5*(R>>>16)&65535)<<16)&4294967295))+(((U>>>16)+58964&65535)<<16);switch(ie=0,T){case 3:ie^=(255&x.charCodeAt(ue+2))<<16;case 2:ie^=(255&x.charCodeAt(ue+1))<<8;case 1:R^=ie=(65535&(ie=(ie=(65535&(ie^=255&x.charCodeAt(ue)))*V+(((ie>>>16)*V&65535)<<16)&4294967295)<<15|ie>>>17))*X+(((ie>>>16)*X&65535)<<16)&4294967295}return R^=x.length,R=2246822507*(65535&(R^=R>>>16))+((2246822507*(R>>>16)&65535)<<16)&4294967295,R=3266489909*(65535&(R^=R>>>13))+((3266489909*(R>>>16)&65535)<<16)&4294967295,(R^=R>>>16)>>>0}),Tf.exports),m=(Bb||(Bb=1,Py.exports=function(x,k){for(var T,P=x.length,R=k^P,U=0;P>=4;)T=1540483477*(65535&(T=255&x.charCodeAt(U)|(255&x.charCodeAt(++U))<<8|(255&x.charCodeAt(++U))<<16|(255&x.charCodeAt(++U))<<24))+((1540483477*(T>>>16)&65535)<<16),R=1540483477*(65535&R)+((1540483477*(R>>>16)&65535)<<16)^(T=1540483477*(65535&(T^=T>>>24))+((1540483477*(T>>>16)&65535)<<16)),P-=4,++U;switch(P){case 3:R^=(255&x.charCodeAt(U+2))<<16;case 2:R^=(255&x.charCodeAt(U+1))<<8;case 1:R=1540483477*(65535&(R^=255&x.charCodeAt(U)))+((1540483477*(R>>>16)&65535)<<16)}return R=1540483477*(65535&(R^=R>>>13))+((1540483477*(R>>>16)&65535)<<16),(R^=R>>>15)>>>0}),Py.exports);return Qm.exports=b,Qm.exports.murmur3=b,Qm.exports.murmur2=m,Qm.exports}(),Nd=Qn($b);class Lc{constructor(m,...x){Object.assign(this,x[0]||{}),this.type=m}}class Xm extends Lc{constructor(m,x={}){super("error",Object.assign({error:m},x))}}function Kc(b,m,x){x[b]&&x[b].indexOf(m)!==-1||(x[b]=x[b]||[],x[b].push(m))}function Jm(b,m,x){if(x&&x[b]){const k=x[b].indexOf(m);k!==-1&&x[b].splice(k,1)}}class Lp{on(m,x){return this._listeners=this._listeners||{},Kc(m,x,this._listeners),this}off(m,x){return Jm(m,x,this._listeners),Jm(m,x,this._oneTimeListeners),this}once(m,x){return x?(this._oneTimeListeners=this._oneTimeListeners||{},Kc(m,x,this._oneTimeListeners),this):new Promise(k=>{this.once(m,k)})}fire(m,x){const k=typeof m=="string"?new Lc(m,x):m,T=k.type;if(this.listens(T)){k.target=this;const P=this._listeners&&this._listeners[T]?this._listeners[T].slice():[];for(const V of P)V.call(this,k);const R=this._oneTimeListeners&&this._oneTimeListeners[T]?this._oneTimeListeners[T].slice():[];for(const V of R)Jm(T,V,this._oneTimeListeners),V.call(this,k);const U=this._eventedParent;if(U){const V=typeof this._eventedParentData=="function"?this._eventedParentData():this._eventedParentData;Object.assign(k,V),U.fire(k)}}else k instanceof Xm&&console.error(k.error);return this}listens(m){return!!(this._listeners&&this._listeners[m]&&this._listeners[m].length>0||this._oneTimeListeners&&this._oneTimeListeners[m]&&this._oneTimeListeners[m].length>0||this._eventedParent&&this._eventedParent.listens(m))}setEventedParent(m,x){return this._eventedParent=m,this._eventedParentData=x,this}}class Pt{constructor(m){typeof m=="string"?this.name=m:(this.name=m.name,this.iconsetId=m.iconsetId)}static from(m){return new Pt(m)}static toString(m){return m.iconsetId?`${m.name}${m.iconsetId}`:m.name}static parse(m){const[x,k]=m.split("");return new Pt({name:x,iconsetId:k})}static isEqual(m,x){return m.name===x.name&&m.iconsetId===x.iconsetId}toString(){return Pt.toString(this)}serialize(){return{name:this.name,iconsetId:this.iconsetId}}}var dn,zn={},Ir=function(){if(dn)return zn;dn=1;var b={transparent:[0,0,0,0],aliceblue:[240,248,255,1],antiquewhite:[250,235,215,1],aqua:[0,255,255,1],aquamarine:[127,255,212,1],azure:[240,255,255,1],beige:[245,245,220,1],bisque:[255,228,196,1],black:[0,0,0,1],blanchedalmond:[255,235,205,1],blue:[0,0,255,1],blueviolet:[138,43,226,1],brown:[165,42,42,1],burlywood:[222,184,135,1],cadetblue:[95,158,160,1],chartreuse:[127,255,0,1],chocolate:[210,105,30,1],coral:[255,127,80,1],cornflowerblue:[100,149,237,1],cornsilk:[255,248,220,1],crimson:[220,20,60,1],cyan:[0,255,255,1],darkblue:[0,0,139,1],darkcyan:[0,139,139,1],darkgoldenrod:[184,134,11,1],darkgray:[169,169,169,1],darkgreen:[0,100,0,1],darkgrey:[169,169,169,1],darkkhaki:[189,183,107,1],darkmagenta:[139,0,139,1],darkolivegreen:[85,107,47,1],darkorange:[255,140,0,1],darkorchid:[153,50,204,1],darkred:[139,0,0,1],darksalmon:[233,150,122,1],darkseagreen:[143,188,143,1],darkslateblue:[72,61,139,1],darkslategray:[47,79,79,1],darkslategrey:[47,79,79,1],darkturquoise:[0,206,209,1],darkviolet:[148,0,211,1],deeppink:[255,20,147,1],deepskyblue:[0,191,255,1],dimgray:[105,105,105,1],dimgrey:[105,105,105,1],dodgerblue:[30,144,255,1],firebrick:[178,34,34,1],floralwhite:[255,250,240,1],forestgreen:[34,139,34,1],fuchsia:[255,0,255,1],gainsboro:[220,220,220,1],ghostwhite:[248,248,255,1],gold:[255,215,0,1],goldenrod:[218,165,32,1],gray:[128,128,128,1],green:[0,128,0,1],greenyellow:[173,255,47,1],grey:[128,128,128,1],honeydew:[240,255,240,1],hotpink:[255,105,180,1],indianred:[205,92,92,1],indigo:[75,0,130,1],ivory:[255,255,240,1],khaki:[240,230,140,1],lavender:[230,230,250,1],lavenderblush:[255,240,245,1],lawngreen:[124,252,0,1],lemonchiffon:[255,250,205,1],lightblue:[173,216,230,1],lightcoral:[240,128,128,1],lightcyan:[224,255,255,1],lightgoldenrodyellow:[250,250,210,1],lightgray:[211,211,211,1],lightgreen:[144,238,144,1],lightgrey:[211,211,211,1],lightpink:[255,182,193,1],lightsalmon:[255,160,122,1],lightseagreen:[32,178,170,1],lightskyblue:[135,206,250,1],lightslategray:[119,136,153,1],lightslategrey:[119,136,153,1],lightsteelblue:[176,196,222,1],lightyellow:[255,255,224,1],lime:[0,255,0,1],limegreen:[50,205,50,1],linen:[250,240,230,1],magenta:[255,0,255,1],maroon:[128,0,0,1],mediumaquamarine:[102,205,170,1],mediumblue:[0,0,205,1],mediumorchid:[186,85,211,1],mediumpurple:[147,112,219,1],mediumseagreen:[60,179,113,1],mediumslateblue:[123,104,238,1],mediumspringgreen:[0,250,154,1],mediumturquoise:[72,209,204,1],mediumvioletred:[199,21,133,1],midnightblue:[25,25,112,1],mintcream:[245,255,250,1],mistyrose:[255,228,225,1],moccasin:[255,228,181,1],navajowhite:[255,222,173,1],navy:[0,0,128,1],oldlace:[253,245,230,1],olive:[128,128,0,1],olivedrab:[107,142,35,1],orange:[255,165,0,1],orangered:[255,69,0,1],orchid:[218,112,214,1],palegoldenrod:[238,232,170,1],palegreen:[152,251,152,1],paleturquoise:[175,238,238,1],palevioletred:[219,112,147,1],papayawhip:[255,239,213,1],peachpuff:[255,218,185,1],peru:[205,133,63,1],pink:[255,192,203,1],plum:[221,160,221,1],powderblue:[176,224,230,1],purple:[128,0,128,1],rebeccapurple:[102,51,153,1],red:[255,0,0,1],rosybrown:[188,143,143,1],royalblue:[65,105,225,1],saddlebrown:[139,69,19,1],salmon:[250,128,114,1],sandybrown:[244,164,96,1],seagreen:[46,139,87,1],seashell:[255,245,238,1],sienna:[160,82,45,1],silver:[192,192,192,1],skyblue:[135,206,235,1],slateblue:[106,90,205,1],slategray:[112,128,144,1],slategrey:[112,128,144,1],snow:[255,250,250,1],springgreen:[0,255,127,1],steelblue:[70,130,180,1],tan:[210,180,140,1],teal:[0,128,128,1],thistle:[216,191,216,1],tomato:[255,99,71,1],turquoise:[64,224,208,1],violet:[238,130,238,1],wheat:[245,222,179,1],white:[255,255,255,1],whitesmoke:[245,245,245,1],yellow:[255,255,0,1],yellowgreen:[154,205,50,1]};function m(P){return(P=Math.round(P))<0?0:P>255?255:P}function x(P){return m(P[P.length-1]==="%"?parseFloat(P)/100*255:parseInt(P))}function k(P){return(R=P[P.length-1]==="%"?parseFloat(P)/100:parseFloat(P))<0?0:R>1?1:R;var R}function T(P,R,U){return U<0?U+=1:U>1&&(U-=1),6*U<1?P+(R-P)*U*6:2*U<1?R:3*U<2?P+(R-P)*(2/3-U)*6:P}try{zn.parseCSSColor=function(P){var R,U=P.replace(/ /g,"").toLowerCase();if(U in b)return b[U].slice();if(U[0]==="#")return U.length===4?(R=parseInt(U.substr(1),16))>=0&&R<=4095?[(3840&R)>>4|(3840&R)>>8,240&R|(240&R)>>4,15&R|(15&R)<<4,1]:null:U.length===7&&(R=parseInt(U.substr(1),16))>=0&&R<=16777215?[(16711680&R)>>16,(65280&R)>>8,255&R,1]:null;var V=U.indexOf("("),X=U.indexOf(")");if(V!==-1&&X+1===U.length){var ie=U.substr(0,V),ue=U.substr(V+1,X-(V+1)).split(","),pe=1;switch(ie){case"rgba":if(ue.length!==4)return null;pe=k(ue.pop());case"rgb":return ue.length!==3?null:[x(ue[0]),x(ue[1]),x(ue[2]),pe];case"hsla":if(ue.length!==4)return null;pe=k(ue.pop());case"hsl":if(ue.length!==3)return null;var be=(parseFloat(ue[0])%360+360)%360/360,Se=k(ue[1]),Le=k(ue[2]),ze=Le<=.5?Le*(Se+1):Le+Se-Le*Se,We=2*Le-ze;return[m(255*T(We,ze,be+1/3)),m(255*T(We,ze,be)),m(255*T(We,ze,be-1/3)),pe];default:return null}}return null}}catch{}return zn}();class Gn{constructor(m,x,k,T=1){this.r=m,this.g=x,this.b=k,this.a=T}static parse(m){if(!m)return;if(m instanceof Gn)return m;if(typeof m!="string")return;const x=Ir.parseCSSColor(m);return x?new Gn(x[0]/255,x[1]/255,x[2]/255,x[3]):void 0}toString(){const[m,x,k,T]=[this.r,this.g,this.b,this.a];return`rgba(${Math.round(255*m)},${Math.round(255*x)},${Math.round(255*k)},${T})`}toNonPremultipliedRenderColor(m){const{r:x,g:k,b:T,a:P}=this;return new Ya(m,x,k,T,P)}toPremultipliedRenderColor(m){const{r:x,g:k,b:T,a:P}=this;return new ai(m,x*P,k*P,T*P,P)}clone(){return new Gn(this.r,this.g,this.b,this.a)}}class ha{constructor(m,x,k,T,P,R=!1){if(this.premultiplied=!1,this.premultiplied=R,m){const U=m.image.height,V=U*U;this.premultiplied?(x=P===0?0:x/P*(U-1),k=P===0?0:k/P*(U-1),T=P===0?0:T/P*(U-1)):(x*=U-1,k*=U-1,T*=U-1),x=Math.max(0,Math.min(U-1,x)),k=Math.max(0,Math.min(U-1,k)),T=Math.max(0,Math.min(U-1,T));const X=Math.floor(x),ie=Math.floor(k),ue=Math.floor(T),pe=Math.ceil(x),be=Math.ceil(k),Se=Math.ceil(T),Le=x-X,ze=k-ie,We=T-ue,ct=m.image.data,nt=4*(X+ie*V+ue*U),ft=4*(X+ie*V+Se*U),wt=4*(X+be*V+ue*U),Nt=4*(X+be*V+Se*U),Wt=4*(pe+ie*V+ue*U),Ft=4*(pe+ie*V+Se*U),Gt=4*(pe+be*V+ue*U),Ut=4*(pe+be*V+Se*U);this.r=Dr(Dr(Dr(ct[nt],ct[ft],We),Dr(ct[wt],ct[Nt],We),ze),Dr(Dr(ct[Wt],ct[Ft],We),Dr(ct[Gt],ct[Ut],We),ze),Le)/255*(this.premultiplied?P:1),this.g=Dr(Dr(Dr(ct[nt+1],ct[ft+1],We),Dr(ct[wt+1],ct[Nt+1],We),ze),Dr(Dr(ct[Wt+1],ct[Ft+1],We),Dr(ct[Gt+1],ct[Ut+1],We),ze),Le)/255*(this.premultiplied?P:1),this.b=Dr(Dr(Dr(ct[nt+2],ct[ft+2],We),Dr(ct[wt+2],ct[Nt+2],We),ze),Dr(Dr(ct[Wt+2],ct[Ft+2],We),Dr(ct[Gt+2],ct[Ut+2],We),ze),Le)/255*(this.premultiplied?P:1),this.a=P}else this.r=x,this.g=k,this.b=T,this.a=P}toArray(){const{r:m,g:x,b:k,a:T}=this;return[255*m,255*x,255*k,T]}toHslaArray(){let{r:m,g:x,b:k,a:T}=this;if(this.premultiplied){if(T===0)return[0,0,0,0];const Se=1/T;m*=Se,x*=Se,k*=Se}const P=Math.min(Math.max(m,0),1),R=Math.min(Math.max(x,0),1),U=Math.min(Math.max(k,0),1),V=Math.min(P,R,U),X=Math.max(P,R,U),ie=X-V,ue=.5*(V+X);if(ie===0)return[0,0,100*ue,T];const pe=ue>.5?ie/(2-X-V):ie/(X+V);let be;switch(X){case P:be=60*((R-U)/ie+(RDr(k,m[T],x))}Gn.black=new Gn(0,0,0,1),Gn.white=new Gn(1,1,1,1),Gn.transparent=new Gn(0,0,0,0),Gn.red=new Gn(1,0,0,1),Gn.blue=new Gn(0,0,1,1);var pm=Object.freeze({__proto__:null,array:kd,color:function(b,m,x){return new Gn(Dr(b.r,m.r,x),Dr(b.g,m.g,x),Dr(b.b,m.b,x),Dr(b.a,m.a,x))},number:Dr});class Vu extends Error{constructor(m,x){super(x),this.message=x,this.key=m}}class cg{constructor(m,x=[]){this.parent=m,this.bindings={};for(const[k,T]of x)this.bindings[k]=T}concat(m){return new cg(this,m)}get(m){if(this.bindings[m])return this.bindings[m];if(this.parent)return this.parent.get(m);throw new Error(`${m} not found in scope.`)}has(m){return!!this.bindings[m]||!!this.parent&&this.parent.has(m)}}const Ef={kind:"null"},kr={kind:"number"},Si={kind:"string"},Hi={kind:"boolean"},Oh={kind:"color"},px={kind:"object"},Ji={kind:"value"},fx={kind:"collator"},Ly={kind:"formatted"},Ub={kind:"resolvedImage"};function Hu(b,m){return{kind:"array",itemType:b,N:m}}function Dl(b){if(b.kind==="array"){const m=Dl(b.itemType);return typeof b.N=="number"?`array<${m}, ${b.N}>`:b.itemType.kind==="value"?"array":`array<${m}>`}return b.kind}const c6=[Ef,kr,Si,Hi,Oh,Ly,px,Hu(Ji),Ub];function Dy(b,m){if(m.kind==="error")return null;if(b.kind==="array"){if(m.kind==="array"&&(m.N===0&&m.itemType.kind==="value"||!Dy(b.itemType,m.itemType))&&(typeof b.N!="number"||b.N===m.N))return null}else{if(b.kind===m.kind)return null;if(b.kind==="value"){for(const x of c6)if(!Dy(x,m))return null}}return`Expected ${Dl(b)} but found ${Dl(m)} instead.`}function qb(b,m){return m.some(x=>x.kind===b.kind)}function xx(b,m){return m.some(x=>x==="null"?b===null:x==="array"?Array.isArray(b):x==="object"?b&&!Array.isArray(b)&&typeof b=="object":x===typeof b)}function gx(b,m){return b.kind==="array"&&m.kind==="array"?b.N===m.N&&gx(b.itemType,m.itemType):b.kind===m.kind}class ij{constructor(m,x,k){this.sensitivity=m?x?"variant":"case":x?"accent":"base",this.locale=k,this.collator=new Intl.Collator(this.locale?this.locale:[],{sensitivity:this.sensitivity,usage:"search"})}compare(m,x){return this.collator.compare(m,x)}resolvedLocale(){return new Intl.Collator(this.locale?this.locale:[]).resolvedOptions().locale}}class Vb{constructor(m,x,k,T,P){this.text=m.normalize?m.normalize():m,this.image=x,this.scale=k,this.fontStack=T,this.textColor=P}}class Ud{constructor(m){this.sections=m}static fromString(m){return new Ud([new Vb(m,null,null,null,null)])}isEmpty(){return this.sections.length===0||!this.sections.some(m=>m.text.length!==0||!!m.image&&m.image.hasPrimary())}static factory(m){return m instanceof Ud?m:Ud.fromString(m)}toString(){return this.sections.length===0?"":this.sections.map(m=>m.text).join("")}serialize(){const m=["format"];for(const x of this.sections){if(x.image){const T=x.image.getPrimary().id.toString();m.push(["image",T]);continue}m.push(x.text);const k={};x.fontStack&&(k["text-font"]=["literal",x.fontStack.split(",")]),x.scale&&(k["font-scale"]=x.scale),x.textColor&&(k["text-color"]=["rgba"].concat(x.textColor.toNonPremultipliedRenderColor(null).toArray())),m.push(k)}return m}}class ep{constructor(m,x={}){this.id=Pt.from(m),this.params=x.params,this.sx=x.sx||1,this.sy=x.sy||1}toString(){return JSON.stringify(this)}static parse(m){let x,k,T,P;try{({id:x,params:k,sx:T,sy:P}=JSON.parse(m)||{})}catch{return null}return x?new ep(x,{params:k,sx:T,sy:P}):null}scaleSelf(m,x=m){return this.sx*=m,this.sy*=x,this}}class qd{constructor(m,x,k,T,P=!1){this.primaryId=Pt.from(m),this.primaryOptions=x,k&&(this.secondaryId=Pt.from(k)),this.secondaryOptions=T,this.available=P}toString(){return this.primaryId&&this.secondaryId?`[${this.primaryId.name},${this.secondaryId.name}]`:this.primaryId.name}hasPrimary(){return!!this.primaryId}getPrimary(){return new ep(this.primaryId,this.primaryOptions)}hasSecondary(){return!!this.secondaryId}getSecondary(){return this.secondaryId?new ep(this.secondaryId,this.secondaryOptions):null}static from(m){return typeof m=="string"?qd.build({name:m}):m}static build(m,x,k,T){return!m||typeof m=="object"&&!("name"in m)?null:new qd(m,k,x,T)}}function Dp(b,m,x,k){return typeof b=="number"&&b>=0&&b<=255&&typeof m=="number"&&m>=0&&m<=255&&typeof x=="number"&&x>=0&&x<=255?k===void 0||typeof k=="number"&&k>=0&&k<=1?null:`Invalid rgba value [${[b,m,x,k].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid rgba value [${(typeof k=="number"?[b,m,x,k]:[b,m,x]).join(", ")}]: 'r', 'g', and 'b' must be between 0 and 255.`}function Af(b){if(b===null||typeof b=="string"||typeof b=="boolean"||typeof b=="number"||b instanceof Gn||b instanceof ij||b instanceof Ud||b instanceof qd)return!0;if(Array.isArray(b)){for(const m of b)if(!Af(m))return!1;return!0}if(typeof b=="object"){for(const m in b)if(!Af(b[m]))return!1;return!0}return!1}function Al(b){if(b===null)return Ef;if(typeof b=="string")return Si;if(typeof b=="boolean")return Hi;if(typeof b=="number")return kr;if(b instanceof Gn)return Oh;if(b instanceof ij)return fx;if(b instanceof Ud)return Ly;if(b instanceof qd)return Ub;if(Array.isArray(b)){const m=b.length;let x;for(const k of b){const T=Al(k);if(x){if(x===T)continue;x=Ji;break}x=T}return Hu(x||Ji,m)}return px}function Qr(b){const m=typeof b;return b===null?"":m==="string"||m==="number"||m==="boolean"?String(b):b instanceof Ud||b instanceof qd||b instanceof Gn?b.toString():JSON.stringify(b)}class nr{constructor(m,x){this.type=m,this.value=x}static parse(m,x){if(m.length!==2)return x.error(`'literal' expression requires exactly one argument, but found ${m.length-1} instead.`);if(!Af(m[1]))return x.error("invalid value");const k=m[1];let T=Al(k);const P=x.expectedType;return T.kind!=="array"||T.N!==0||!P||P.kind!=="array"||typeof P.N=="number"&&P.N!==0||(T=P),new nr(T,k)}evaluate(){return this.value}eachChild(){}outputDefined(){return!0}serialize(){return this.type.kind==="array"||this.type.kind==="object"?["literal",this.value]:this.value instanceof Gn?["rgba"].concat(this.value.toNonPremultipliedRenderColor(null).toArray()):this.value instanceof Ud?this.value.serialize():this.value}}class gl{constructor(m){this.name="ExpressionEvaluationError",this.message=m}toJSON(){return this.message}}const ra={string:Si,number:kr,boolean:Hi,object:px};class tp{constructor(m,x){this.type=m,this.args=x}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");let k,T=1;const P=m[0];if(P==="array"){let U,V;if(m.length>2){const X=m[1];if(typeof X!="string"||!(X in ra)||X==="object")return x.error('The item type argument of "array" must be one of string, number, boolean',1);U=ra[X],T++}else U=Ji;if(m.length>3){if(m[2]!==null&&(typeof m[2]!="number"||m[2]<0||m[2]!==Math.floor(m[2])))return x.error('The length argument to "array" must be a positive integer literal',2);V=m[2],T++}k=Hu(U,V)}else k=ra[P];const R=[];for(;Tm.outputDefined())}serialize(){const m=this.type,x=[m.kind];if(m.kind==="array"){const k=m.itemType;if(k.kind==="string"||k.kind==="number"||k.kind==="boolean"){x.push(k.kind);const T=m.N;(typeof T=="number"||this.args.length>1)&&x.push(T)}}return x.concat(this.args.map(k=>k.serialize()))}}class fm{constructor(m){this.type=Ly,this.sections=m}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");const k=m[1];if(!Array.isArray(k)&&typeof k=="object")return x.error("First argument must be an image or text section.");const T=[];let P=!1;for(let R=1;R<=m.length-1;++R){const U=m[R];if(P&&typeof U=="object"&&!Array.isArray(U)){P=!1;let V=null;if(U["font-scale"]&&(V=x.parseObjectValue(U["font-scale"],R,"font-scale",kr),!V))return null;let X=null;if(U["text-font"]&&(X=x.parseObjectValue(U["text-font"],R,"text-font",Hu(Si)),!X))return null;let ie=null;if(U["text-color"]&&(ie=x.parseObjectValue(U["text-color"],R,"text-color",Oh),!ie))return null;const ue=T[T.length-1];ue.scale=V,ue.font=X,ue.textColor=ie}else{const V=x.parse(m[R],R,Ji);if(!V)return null;const X=V.type.kind;if(X!=="string"&&X!=="value"&&X!=="null"&&X!=="resolvedImage")return x.error("Formatted text type must be 'string', 'value', 'image' or 'null'.");P=!0,T.push({content:V,scale:null,font:null,textColor:null})}}return new fm(T)}evaluate(m){return new Ud(this.sections.map(x=>{const k=x.content.evaluate(m);return gx(Al(k),Ub)?new Vb("",k,null,null,null):new Vb(Qr(k),null,x.scale?x.scale.evaluate(m):null,x.font?x.font.evaluate(m).join(","):null,x.textColor?x.textColor.evaluate(m):null)}))}eachChild(m){for(const x of this.sections)m(x.content),x.scale&&m(x.scale),x.font&&m(x.font),x.textColor&&m(x.textColor)}outputDefined(){return!1}serialize(){const m=["format"];for(const x of this.sections){m.push(x.content.serialize());const k={};x.scale&&(k["font-scale"]=x.scale.serialize()),x.font&&(k["text-font"]=x.font.serialize()),x.textColor&&(k["text-color"]=x.textColor.serialize()),m.push(k)}return m}}class Pr{constructor(m,x,k,T){this._imageWarnHistory={},this.type=Ub,this.namePrimary=m,this.nameSecondary=x,k&&(this.paramsPrimary=k.params,this.iconsetIdPrimary=k.iconset?k.iconset.id:void 0),T&&(this.paramsSecondary=T.params,this.iconsetIdSecondary=T.iconset?T.iconset.id:void 0)}static parse(m,x){if(m.length<2)return x.error("Expected two or more arguments.");let k=1;const T=[];function P(){if(kPt.isEqual(R,P)),T.available){const R=T.getSecondary()?T.getSecondary().id:null;R&&(T.available=m.availableImages.some(U=>Pt.isEqual(U,R)))}}return T}eachChild(m){if(m(this.namePrimary),this.paramsPrimary)for(const x in this.paramsPrimary)this.paramsPrimary[x]&&m(this.paramsPrimary[x]);if(this.nameSecondary&&(m(this.nameSecondary),this.paramsSecondary))for(const x in this.paramsSecondary)this.paramsSecondary[x]&&m(this.paramsSecondary[x])}outputDefined(){return!1}serializeOptions(m,x){const k={};if(x&&(k.iconset={id:x}),m){k.params={};for(const T in m)m[T]&&(k.params[T]=m[T].serialize())}return Object.keys(k).length>0?k:void 0}serialize(){const m=["image",this.namePrimary.serialize()];if(this.paramsPrimary||this.iconsetIdPrimary){const x=this.serializeOptions(this.paramsPrimary,this.iconsetIdPrimary);x&&m.push(x)}if(this.nameSecondary&&(m.push(this.nameSecondary.serialize()),this.paramsSecondary||this.iconsetIdSecondary)){const x=this.serializeOptions(this.paramsSecondary,this.iconsetIdSecondary);x&&m.push(x)}return m}}function Ry(b){return n1(b)?"string":Hb(b)?"number":c0(b)?"boolean":Array.isArray(b)?"array":b===null?"null":oj(b)?"object":typeof b}function oj(b){return b!=null&&!Array.isArray(b)&&typeof b!="function"&&!(b instanceof String||b instanceof Number||b instanceof Boolean)&&typeof b=="object"}function n1(b){return typeof b=="string"||b instanceof String}function Hb(b){return typeof b=="number"||b instanceof Number}function c0(b){return typeof b=="boolean"||b instanceof Boolean}const Mf={"to-boolean":Hi,"to-color":Oh,"to-number":kr,"to-string":Si};class xm{constructor(m,x){this.type=m,this.args=x}static parse(m,x){if(m.length<2)return x.error("Expected at least one argument.");const k=m[0],T=[];let P=Ef;if(k==="to-array"){if(!Array.isArray(m[1]))return null;const R=m[1].length;if(x.expectedType){if(x.expectedType.kind!=="array")return x.error(`Expected ${x.expectedType.kind} but found array.`);P=Hu(x.expectedType.itemType,R)}else{if(!(R>0&&Af(m[1][0])))return null;P=Hu(Al(m[1][0]),R)}for(let U=0;U4?`Invalid rbga value ${JSON.stringify(x)}: expected an array containing either three or four numeric values.`:Dp(x[0],x[1],x[2],x[3]),!k))return new Gn(x[0]/255,x[1]/255,x[2]/255,x[3])}throw new gl(k||`Could not parse color from value '${typeof x=="string"?x:String(JSON.stringify(x))}'`)}if(this.type.kind==="number"){let x=null;for(const k of this.args){if(x=k.evaluate(m),x===null)return 0;const T=Number(x);if(!isNaN(T))return T}throw new gl(`Could not convert ${JSON.stringify(x)} to number.`)}return this.type.kind==="formatted"?Ud.fromString(Qr(this.args[0].evaluate(m))):this.type.kind==="resolvedImage"?qd.build(Qr(this.args[0].evaluate(m))):this.type.kind==="array"?this.args.map(x=>x.evaluate(m)):Qr(this.args[0].evaluate(m))}eachChild(m){this.args.forEach(m)}outputDefined(){return this.args.every(m=>m.outputDefined())}serialize(){if(this.type.kind==="formatted")return new fm([{content:this.args[0],scale:null,font:null,textColor:null}]).serialize();if(this.type.kind==="resolvedImage")return new Pr(this.args[0]).serialize();const m=this.type.kind==="array"?[]:[`to-${this.type.kind}`];return this.eachChild(x=>{m.push(x.serialize())}),m}}const If=["Unknown","Point","LineString","Polygon"];class sp{constructor(m,x,k){this.globals=null,this.feature=null,this.featureState=null,this.formattedSection=null,this._parseColorCache={},this.availableImages=null,this.canonical=null,this.featureTileCoord=null,this.featureDistanceData=null,this.scope=m,this.options=x,this.iconImageUseTheme=k}id(){return this.feature&&this.feature.id!==void 0?this.feature.id:null}geometryType(){return this.feature?typeof this.feature.type=="number"?If[this.feature.type]:this.feature.type:null}geometry(){return this.feature&&"geometry"in this.feature?this.feature.geometry:null}canonicalID(){return this.canonical}properties(){return this.feature&&this.feature.properties||{}}measureLight(m){return this.globals.brightness||0}distanceFromCenter(){if(this.featureTileCoord&&this.featureDistanceData){const m=this.featureDistanceData.center,x=this.featureDistanceData.scale,{x:k,y:T}=this.featureTileCoord;return this.featureDistanceData.bearing[0]*(k*x-m[0])+this.featureDistanceData.bearing[1]*(T*x-m[1])}return 0}parseColor(m){let x=this._parseColorCache[m];return x||(x=this._parseColorCache[m]=Gn.parse(m)),x}getConfig(m){return this.options?this.options.get(m):null}}class Dc{constructor(m,x,k,T,P){this.name=m,this.type=x,this._evaluate=k,this.args=T,this._overloadIndex=P}evaluate(m){if(!this._evaluate){const x=Dc.definitions[this.name];this._evaluate=Array.isArray(x)?x[2]:x.overloads[this._overloadIndex][1]}return this._evaluate(m,this.args)}eachChild(m){this.args.forEach(m)}outputDefined(){return!1}serialize(){return[this.name].concat(this.args.map(m=>m.serialize()))}static parse(m,x){const k=m[0],T=Dc.definitions[k];if(!T)return x.error(`Unknown expression "${k}". If you wanted a literal array, use ["literal", [...]].`,0);const P=Array.isArray(T)?T[0]:T.type,R=Array.isArray(T)?[[T[1],T[2]]]:T.overloads,U=[];let V=null,X=-1;for(const[ie,ue]of R){if(Array.isArray(ie)&&ie.length!==m.length-1)continue;U.push(ie),X++,V=new vj(x.registry,x.path,null,x.scope,void 0,x._scope,x.options,x.iconImageUseTheme);const pe=[];let be=!1;for(let Se=1;Sepe)).map(Rp).join(" | "),ue=[];for(let pe=1;pex;){if(k-x>600){const V=k-x+1,X=m-x+1,ie=Math.log(V),ue=.5*Math.exp(2*ie/3),pe=.5*Math.sqrt(ie*ue*(V-ue)/V)*(X-V/2<0?-1:1);TN(b,m,Math.max(x,Math.floor(m-X*ue/V+pe)),Math.min(k,Math.floor(m+(V-X)*ue/V+pe)),T)}const P=b[m];let R=x,U=k;for(Jl(b,x,m),T(b[k],P)>0&&Jl(b,x,k);R0;)U--}T(b[x],P)===0?Jl(b,x,U):(U++,Jl(b,U,k)),U<=m&&(x=U+1),m<=U&&(k=U-1)}}function Jl(b,m,x){const k=b[m];b[m]=b[x],b[x]=k}function r1(b,m){return bm?1:0}function EN(b){let m=0;for(let x,k,T=0,P=b.length,R=P-1;T=m[2]||b[1]<=m[1]||b[3]>=m[3])}function lC(b,m,x){const k=b[0]-m[0],T=b[1]-m[1],P=b[0]-x[0],R=b[1]-x[1];return k*R-P*T===0&&k*P<=0&&T*R<=0}function d0(b,m,x){return m[1]>b[1]!=x[1]>b[1]&&b[0]<(x[0]-m[0])*(b[1]-m[1])/(x[1]-m[1])+m[0]}function Gl(b,m,x=!1){let k=!1;for(let T=0,P=m.length;T0&&U<0||R<0&&U>0}function id(b,m,x,k){return(T=[k[0]-x[0],k[1]-x[1]])[0]*(P=[m[0]-b[0],m[1]-b[1]])[1]-T[1]*P[0]!==0&&!(!Vd(b,m,x,k)||!Vd(x,k,b,m));var T,P}function Gb(b){const m=new Es(Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY),x=new Es(Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY);for(const k of b[0])m.x>k.x&&(m.x=k.x),m.y>k.y&&(m.y=k.y),x.xx[2]){const T=.5*k;let P=b[0]-x[0]>T?-k:x[0]-b[0]>T?k:0;P===0&&(P=b[0]-x[2]>T?-k:x[2]-b[0]>T?k:0),b[0]+=P}Op(m,b)}function i1(b,m,x,k){const T=Math.pow(2,k.z)*Pf,P=[k.x*Pf,k.y*Pf],R=[];if(!b)return R;for(const U of b)for(const V of U){const X=[V.x+P[0],V.y+P[1]];Yc(X,m,x,T),R.push(X)}return R}function uj(b,m,x,k){const T=Math.pow(2,k.z)*Pf,P=[k.x*Pf,k.y*Pf],R=[];if(!b)return R;for(const V of b){const X=[];for(const ie of V){const ue=[ie.x+P[0],ie.y+P[1]];Op(m,ue),X.push(ue)}R.push(X)}if(m[2]-m[0]<=T/2){(U=m)[0]=U[1]=1/0,U[2]=U[3]=-1/0;for(const V of R)for(const X of V)Yc(X,m,x,T)}var U;return R}class dg{constructor(m,x){this.type=Hi,this.geojson=m,this.geometries=x}static parse(m,x){if(m.length!==2)return x.error(`'within' expression requires exactly one argument, but found ${m.length-1} instead.`);if(Af(m[1])){const k=m[1];if(k.type==="FeatureCollection")for(let T=0;Tx)return hj(P,R,(x-(k-U))/U)}return m[m.length-1]}pointToSegmentDistance(m,x,k){let[T,P]=x,R=np(k[0]-T)*this.kx,U=(k[1]-P)*this.ky;if(R!==0||U!==0){const V=(np(m[0]-T)*this.kx*R+(m[1]-P)*this.ky*U)/(R*R+U*U);V>1?(T=k[0],P=k[1]):V>0&&(T+=R/this.kx*V,P+=U/this.ky*V)}return R=np(m[0]-T)*this.kx,U=(m[1]-P)*this.ky,Math.sqrt(R*R+U*U)}pointOnLine(m,x){let k=1/0,T=m[0][0],P=m[0][1],R=0,U=0;for(let V=0;V1?(X=m[V+1][0],ie=m[V+1][1]):be>0&&(X+=ue/this.kx*be,ie+=pe/this.ky*be)),ue=np(x[0]-X)*this.kx,pe=(x[1]-ie)*this.ky;const Se=ue*ue+pe*pe;SeP.index||T.index===P.index&&T.t>P.t){const X=T;T=P,P=X}const R=[T.point],U=T.index+1,V=P.index;!PN(k[U],R[0])&&U<=V&&R.push(k[U]);for(let X=U+1;X<=V;X++)R.push(k[X]);return PN(k[V],P.point)||R.push(P.point),R}lineSliceAlong(m,x,k){let T=0;const P=[];for(let R=0;Rm&&P.length===0&&P.push(hj(U,V,(m-(T-X))/X)),T>=x)return P.push(hj(U,V,(x-(T-X))/X)),P;T>m&&P.push(V)}return P}bufferPoint(m,x){const k=x/this.ky,T=x/this.kx;return[m[0]-T,m[1]-k,m[0]+T,m[1]+k]}bufferBBox(m,x){const k=x/this.ky,T=x/this.kx;return[m[0]-T,m[1]-k,m[2]+T,m[3]+k]}insideBBox(m,x){return np(m[0]-x[0])>=0&&np(m[0]-x[2])<=0&&m[1]>=x[1]&&m[1]<=x[3]}}function PN(b,m){return b[0]===m[0]&&b[1]===m[1]}function hj(b,m,x){const k=np(m[0]-b[0]);return[b[0]+k*x,b[1]+(m[1]-b[1])*x]}function np(b){for(;b<-180;)b+=360;for(;b>180;)b-=360;return b}class u0{constructor(m=[],x=(k,T)=>kT?1:0){if(this.data=m,this.length=this.data.length,this.compare=x,this.length>0)for(let k=(this.length>>1)-1;k>=0;k--)this._down(k)}push(m){this.data.push(m),this._up(this.length++)}pop(){if(this.length===0)return;const m=this.data[0],x=this.data.pop();return--this.length>0&&(this.data[0]=x,this._down(0)),m}peek(){return this.data[0]}_up(m){const{data:x,compare:k}=this,T=x[m];for(;m>0;){const P=m-1>>1,R=x[P];if(k(T,R)>=0)break;x[m]=R,m=P}x[m]=T}_down(m){const{data:x,compare:k}=this,T=this.length>>1,P=x[m];for(;m=0)break;x[m]=x[R],m=R}x[m]=P}}var Bn=8192;function mj(b,m){return m.dist-b.dist}function pj(b){const m=[1/0,1/0,-1/0,-1/0];if(m.length!==b.length)return!1;for(let x=0;x=b[0]&&b[1]b[1])return[null,null];const x=Fy(b);if(m){if(x===2)return[b,null];const k=Math.floor(x/2);return[[b[0],b[0]+k],[b[0]+k,b[1]]]}{if(x===1)return[b,null];const k=Math.floor(x/2)-1;return[[b[0],b[0]+k],[b[0]+k+1,b[1]]]}}function h0(b,m){const x=[1/0,1/0,-1/0,-1/0];if(!Fp(m,b.length))return x;for(let k=m[0];k<=m[1];++k)Op(x,b[k]);return x}function Yb(b){const m=[1/0,1/0,-1/0,-1/0];for(let x=0;xm[2]&&(k=b[0]-m[2]),b[1]>m[3]&&(T=b[1]-m[3]),b[3]=k)return k;if(Oy(T,P)){if(fj(b,m))return 0}else if(fj(m,b))return 0;let R=k;for(const U of b)for(let V=0,X=U.length,ie=X-1;V=P)continue;const ie=X.range1;if(Fy(ie)<=U){if(!Fp(ie,b.length))return NaN;if(m){const ue=ll(b,ie,x,k);if((P=Math.min(P,ue))===0)return P}else for(let ue=ie[0];ue<=ie[1];++ue){const pe=d6(b[ue],x,k);if((P=Math.min(P,pe))===0)return P}}else{const ue=c1(ie,m);if(ue[0]!==null){const pe=d1(h0(b,ue[0]),V,k);pe=R)continue;const ue=ie.range1,pe=ie.range2;if(Fy(ue)<=V&&Fy(pe)<=X){if(!Fp(ue,b.length)||!Fp(pe,x.length))return NaN;if(m&&k?R=Math.min(R,MR(b,ue,x,pe,T)):m||k?m&&!k?R=Math.min(R,hC(x,pe,b,ue,T)):!m&&k&&(R=Math.min(R,hC(b,ue,x,pe,T))):R=Math.min(R,pC(b,ue,x,pe,T)),R===0)return R}else{const be=c1(ue,m),Se=c1(pe,k);LN(U,R,T,b,x,be[0],Se[0]),LN(U,R,T,b,x,be[0],Se[1]),LN(U,R,T,b,x,be[1],Se[0]),LN(U,R,T,b,x,be[1],Se[1])}}return R}function xj(b,m,x,k,T=1/0){let P=T;const R=h0(b,[0,b.length-1]);for(const U of x)if(!(P!==1/0&&d1(R,h0(U,[0,U.length-1]),k)>=P)&&(P=Math.min(P,Df(b,m,U,!0,k,P)),P===0))return P;return P}function u1(b,m,x,k,T=1/0){let P=T;const R=h0(b,[0,b.length-1]);for(const U of x){if(P!==1/0&&d1(R,Yb(U),k)>=P)continue;const V=PR(b,m,U,k,P);if(isNaN(V))return V;if((P=Math.min(P,V))===0)return P}return P}function DN(b){return b==="Point"||b==="MultiPoint"||b==="LineString"||b==="MultiLineString"||b==="Polygon"||b==="MultiPolygon"}class zy{constructor(m,x){this.type=kr,this.geojson=m,this.geometries=x}static parse(m,x){if(m.length!==2)return x.error(`'distance' expression requires either one argument, but found ' ${m.length-1} instead.`);if(Af(m[1])){const k=m[1];if(k.type==="FeatureCollection"){for(let T=0;T{m&&!By(x)&&(m=!1)}),m}function $y(b){if(b instanceof Dc&&b.name==="feature-state")return!1;let m=!0;return b.eachChild(x=>{m&&!$y(x)&&(m=!1)}),m}function gm(b,m){if(b instanceof Dc&&m.indexOf(b.name)>=0)return!1;let x=!0;return b.eachChild(k=>{x&&!gm(k,m)&&(x=!1)}),x}function RN(b,m,x){return[b,m,x].filter(Boolean).join("")}function gj(b,m){switch(b){case"string":return Qr(m);case"number":return+m;case"boolean":return!!m;case"color":return Gn.parse(m);case"formatted":return Ud.fromString(Qr(m));case"resolvedImage":return qd.build(Qr(m))}return m}function u6(b,m,x,k){return k!==void 0&&(b=k*Math.round(b/k)),m!==void 0&&bx&&(b=x),b}class h1{constructor(m,x,k,T=!1){this.type=m,this.key=x,this.scope=k,this.featureConstant=T}static parse(m,x){let k=x.expectedType;if(k==null&&(k=Ji),m.length<2||m.length>3)return x.error("Invalid number of arguments for 'config' expression.");const T=x.parse(m[1],1);if(!(T instanceof nr))return x.error("Key name of 'config' expression must be a string literal.");let P,R=!0;const U=Qr(T.value);if(m.length>=3){const V=x.parse(m[2],2);if(!(V instanceof nr))return x.error("Scope of 'config' expression must be a string literal.");P=Qr(V.value)}if(x.options){const V=RN(U,P,x._scope),X=x.options.get(V);X&&(R=By(X.value||X.default))}return new h1(k,U,P,R)}evaluate(m){const x=RN(this.key,this.scope,m.scope),k=m.getConfig(x);if(!k)return null;const{type:T,value:P,values:R,minValue:U,maxValue:V,stepValue:X}=k,ie=k.default.evaluate(m);let ue=ie;if(P){const pe=m.scope;m.scope=(pe||"").split("").slice(1).join(""),ue=P.evaluate(m),m.scope=pe}return T&&(ue=gj(T,ue)),ue===void 0||U===void 0&&V===void 0&&X===void 0||(typeof ue=="number"?ue=u6(ue,U,V,X):Array.isArray(ue)&&(ue=ue.map(pe=>typeof pe=="number"?u6(pe,U,V,X):pe))),P!==void 0&&ue!==void 0&&R&&!R.includes(ue)&&(ue=ie,T&&(ue=gj(T,ue))),(T&&T!==this.type||ue!==void 0&&!gx(Al(ue),this.type))&&(ue=gj(this.type.kind,ue)),ue}eachChild(){}outputDefined(){return!1}serialize(){const m=["config",this.key];return this.scope&&m.concat(this.scope),m}}class yj{constructor(m,x){this.type=x.type,this.name=m,this.boundExpression=x}static parse(m,x){if(m.length!==2||typeof m[1]!="string")return x.error("'var' expression requires exactly one string literal argument.");const k=m[1];return x.scope.has(k)?new yj(k,x.scope.get(k)):x.error(`Unknown variable "${k}". Make sure "${k}" has been bound in an enclosing "let" expression before using it.`,1)}evaluate(m){return this.boundExpression.evaluate(m)}eachChild(){}outputDefined(){return!1}serialize(){return["var",this.name]}}class vj{constructor(m,x=[],k,T=new cg,P=[],R,U,V){this.registry=m,this.path=x,this.key=x.map(X=>typeof X=="string"?`['${X}']`:`[${X}]`).join(""),this.scope=T,this.errors=P,this.expectedType=k,this._scope=R,this.options=U,this.iconImageUseTheme=V}parse(m,x,k,T,P={}){return x||k?this.concat(x,null,k,T)._parse(m,P):this._parse(m,P)}parseObjectValue(m,x,k,T,P,R={}){return this.concat(x,k,T,P)._parse(m,R)}_parse(m,x){function k(T,P,R){return R==="assert"?new tp(P,[T]):R==="coerce"?new xm(P,[T]):T}if(m!==null&&typeof m!="string"&&typeof m!="boolean"&&typeof m!="number"||(m=["literal",m]),Array.isArray(m)){if(m.length===0)return this.error('Expected an array with at least one element. If you wanted a literal array, use ["literal", []].');const T=typeof m[0]=="string"?this.registry[m[0]]:void 0;if(T){let P=T.parse(m,this);if(!P)return null;if(this.expectedType){const R=this.expectedType,U=P.type;if(R.kind!=="string"&&R.kind!=="number"&&R.kind!=="boolean"&&R.kind!=="object"&&R.kind!=="array"||U.kind!=="value")if(R.kind!=="color"&&R.kind!=="formatted"&&R.kind!=="resolvedImage"||U.kind!=="value"&&U.kind!=="string"){if(this.checkSubtype(R,U))return null}else P=k(P,R,x.typeAnnotation||"coerce");else P=k(P,R,x.typeAnnotation||"assert")}if(!(P instanceof nr)&&P.type.kind!=="resolvedImage"&&ON(P)){const R=new sp(this._scope,this.options,this.iconImageUseTheme);try{P=new nr(P.type,P.evaluate(R))}catch(U){return this.error(U.message),null}}return P}return xm.parse(["to-array",m],this)}return this.error(m===void 0?"'undefined' value invalid. Use null instead.":typeof m=="object"?'Bare objects invalid. Use ["literal", {...}] instead.':`Expected an array, but found ${typeof m} instead.`)}concat(m,x,k,T){let P=typeof m=="number"?this.path.concat(m):this.path;P=typeof x=="string"?P.concat(x):P;const R=T?this.scope.concat(T):this.scope;return new vj(this.registry,P,k||null,R,this.errors,this._scope,this.options,this.iconImageUseTheme)}error(m,...x){const k=`${this.key}${x.map(T=>`[${T}]`).join("")}`;this.errors.push(new Vu(k,m))}checkSubtype(m,x){const k=Dy(m,x);return k&&this.error(k),k}}function ON(b){if(b instanceof yj)return ON(b.boundExpression);if(b instanceof Dc&&b.name==="error"||b instanceof lj||b instanceof dg||b instanceof zy||b instanceof h1)return!1;const m=b instanceof xm||b instanceof tp;let x=!0;return b.eachChild(k=>{x=m?x&&ON(k):x&&k instanceof nr}),!!x&&By(b)&&gm(b,["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 bj(b,m){const x=b.length-1;let k,T,P=0,R=x,U=0;for(;P<=R;)if(U=Math.floor((P+R)/2),k=b[U],T=b[U+1],k<=m){if(U===x||mm))throw new gl("Input is not a number.");R=U-1}return 0}class _j{constructor(m,x,k){this.type=m,this.input=x,this.labels=[],this.outputs=[];for(const[T,P]of k)this.labels.push(T),this.outputs.push(P)}static parse(m,x){if(m.length-1<4)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if((m.length-1)%2!=0)return x.error("Expected an even number of arguments.");const k=x.parse(m[1],1,kr);if(!k)return null;const T=[];let P=null;x.expectedType&&x.expectedType.kind!=="value"&&(P=x.expectedType);for(let R=1;R=U)return x.error('Input/output pairs for "step" expressions must be arranged with input values in strictly ascending order.',X);const ue=x.parse(V,ie,P);if(!ue)return null;P=P||ue.type,T.push([U,ue])}return new _j(P,k,T)}evaluate(m){const x=this.labels,k=this.outputs;if(x.length===1)return k[0].evaluate(m);const T=this.input.evaluate(m);if(T<=x[0])return k[0].evaluate(m);const P=x.length;return T>=x[P-1]?k[P-1].evaluate(m):k[bj(x,T)].evaluate(m)}eachChild(m){m(this.input);for(const x of this.outputs)m(x)}outputDefined(){return this.outputs.every(m=>m.outputDefined())}serialize(){const m=["step",this.input.serialize()];for(let x=0;x0&&m.push(this.labels[x]),m.push(this.outputs[x].serialize());return m}}const ym=.95047,zh=1.08883,fC=4/29,m1=6/29,xC=3*m1*m1,h6=m1*m1*m1,m6=Math.PI/180,gC=180/Math.PI;function FN(b){return b>h6?Math.pow(b,1/3):b/xC+fC}function wj(b){return b>m1?b*b*b:xC*(b-fC)}function Zb(b){return 255*(b<=.0031308?12.92*b:1.055*Math.pow(b,1/2.4)-.055)}function p1(b){return(b/=255)<=.04045?b/12.92:Math.pow((b+.055)/1.055,2.4)}function jj(b){const m=p1(b.r),x=p1(b.g),k=p1(b.b),T=FN((.4124564*m+.3575761*x+.1804375*k)/ym),P=FN((.2126729*m+.7151522*x+.072175*k)/1);return{l:116*P-16,a:500*(T-P),b:200*(P-FN((.0193339*m+.119192*x+.9503041*k)/zh)),alpha:b.a}}function zN(b){let m=(b.l+16)/116,x=isNaN(b.a)?m:m+b.a/500,k=isNaN(b.b)?m:m-b.b/200;return m=1*wj(m),x=ym*wj(x),k=zh*wj(k),new Gn(Zb(3.2404542*x-1.5371385*m-.4985314*k),Zb(-.969266*x+1.8760108*m+.041556*k),Zb(.0556434*x-.2040259*m+1.0572252*k),b.alpha)}function p6(b,m,x){const k=m-b;return b+x*(k>180||k<-180?k-360*Math.round(k/360):k)}const f1={forward:jj,reverse:zN,interpolate:function(b,m,x){return{l:Dr(b.l,m.l,x),a:Dr(b.a,m.a,x),b:Dr(b.b,m.b,x),alpha:Dr(b.alpha,m.alpha,x)}}},m0={forward:function(b){const{l:m,a:x,b:k}=jj(b),T=Math.atan2(k,x)*gC;return{h:T<0?T+360:T,c:Math.sqrt(x*x+k*k),l:m,alpha:b.a}},reverse:function(b){const m=b.h*m6,x=b.c;return zN({l:b.l,a:Math.cos(m)*x,b:Math.sin(m)*x,alpha:b.alpha})},interpolate:function(b,m,x){return{h:p6(b.h,m.h,x),c:Dr(b.c,m.c,x),l:Dr(b.l,m.l,x),alpha:Dr(b.alpha,m.alpha,x)}}};var yC=Object.freeze({__proto__:null,hcl:m0,lab:f1});class pu{constructor(m,x,k,T,P){this.type=m,this.operator=x,this.interpolation=k,this.input=T,this.labels=[],this.outputs=[];for(const[R,U]of P)this.labels.push(R),this.outputs.push(U)}static interpolationFactor(m,x,k,T){let P=0;if(m.name==="exponential")P=Qb(x,m.base,k,T);else if(m.name==="linear")P=Qb(x,1,k,T);else if(m.name==="cubic-bezier"){const R=m.controlPoints;P=new na(R[0],R[1],R[2],R[3]).solve(Qb(x,1,k,T))}return P}static parse(m,x){let[k,T,P,...R]=m;if(!Array.isArray(T)||T.length===0)return x.error("Expected an interpolation type expression.",1);if(T[0]==="linear")T={name:"linear"};else if(T[0]==="exponential"){const X=T[1];if(typeof X!="number")return x.error("Exponential interpolation requires a numeric base.",1,1);T={name:"exponential",base:X}}else{if(T[0]!=="cubic-bezier")return x.error(`Unknown interpolation type ${String(T[0])}`,1,0);{const X=T.slice(1);if(X.length!==4||X.some(ie=>typeof ie!="number"||ie<0||ie>1))return x.error("Cubic bezier interpolation requires four numeric arguments with values between 0 and 1.",1);T={name:"cubic-bezier",controlPoints:X}}}if(m.length-1<4)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if(m.length-1>3&&(m.length-1)%2!=0)return x.error("Expected an even number of arguments.");if(P=x.parse(P,2,kr),!P)return null;const U=[];let V=null;k==="interpolate-hcl"||k==="interpolate-lab"?V=Oh:x.expectedType&&x.expectedType.kind!=="value"&&(V=x.expectedType);for(let X=0;X=ie)return x.error('Input/output pairs for "interpolate" expressions must be arranged with input values in strictly ascending order.',pe);const Se=x.parse(ue,be,V);if(!Se)return null;V=V||Se.type,U.push([ie,Se])}return V.kind==="number"||V.kind==="color"||V.kind==="array"&&V.itemType.kind==="number"&&typeof V.N=="number"?new pu(V,k,T,P,U):x.error(`Type ${Dl(V)} is not interpolatable.`)}evaluate(m){const x=this.labels,k=this.outputs;if(x.length===1)return k[0].evaluate(m);const T=this.input.evaluate(m);if(T<=x[0])return k[0].evaluate(m);const P=x.length;if(T>=x[P-1])return k[P-1].evaluate(m);const R=bj(x,T),U=pu.interpolationFactor(this.interpolation,T,x[R],x[R+1]),V=k[R].evaluate(m),X=k[R+1].evaluate(m);return this.operator==="interpolate"?pm[this.type.kind.toLowerCase()](V,X,U):this.operator==="interpolate-hcl"?m0.reverse(m0.interpolate(m0.forward(V),m0.forward(X),U)):f1.reverse(f1.interpolate(f1.forward(V),f1.forward(X),U))}eachChild(m){m(this.input);for(const x of this.outputs)m(x)}outputDefined(){return this.outputs.every(m=>m.outputDefined())}serialize(){let m;m=this.interpolation.name==="linear"?["linear"]:this.interpolation.name==="exponential"?this.interpolation.base===1?["linear"]:["exponential",this.interpolation.base]:["cubic-bezier",...this.interpolation.controlPoints];const x=[this.operator,m,this.input.serialize()];for(let k=0;kDy(T,U.type));return new Xb(R?Ji:k,P)}evaluate(m){let x,k=null,T=0;for(const P of this.args){if(T++,k=P.evaluate(m),k&&k instanceof qd&&!k.available&&(x||(x=k),k=null,T===this.args.length))return x;if(k!==null)break}return k}eachChild(m){this.args.forEach(m)}outputDefined(){return this.args.every(m=>m.outputDefined())}serialize(){const m=["coalesce"];return this.eachChild(x=>{m.push(x.serialize())}),m}}class x1{constructor(m,x){this.type=x.type,this.bindings=[].concat(m),this.result=x}evaluate(m){return this.result.evaluate(m)}eachChild(m){for(const x of this.bindings)m(x[1]);m(this.result)}static parse(m,x){if(m.length<4)return x.error(`Expected at least 3 arguments, but found ${m.length-1} instead.`);const k=[];for(let P=1;P=k.length)throw new gl("Array index out of bounds: index exceeds array size");if(x!==Math.floor(x))throw new gl("Array index must be an integer. Use at-interpolated for fractional indices");return k[x]}eachChild(m){m(this.index),m(this.input)}outputDefined(){return!1}serialize(){return["at",this.index.serialize(),this.input.serialize()]}}class Nj{constructor(m,x,k){this.type=m,this.index=x,this.input=k}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`);const k=x.parse(m[1],1,kr),T=x.parse(m[2],2,Hu(x.expectedType||Ji));return k&&T?new Nj(T.type.itemType,k,T):null}evaluate(m){const x=this.index.evaluate(m),k=this.input.evaluate(m);if(x<0)throw new gl(`Array index out of bounds: ${x} < 0.`);if(x>k.length-1)throw new gl(`Array index out of bounds: ${x} > ${k.length-1}.`);if(x===Math.floor(x))return k[x];const T=Math.floor(x),P=Math.ceil(x),R=k[T],U=k[P];if(typeof R!="number"||typeof U!="number")throw new gl(`Cannot interpolate between non-number values at index ${x}.`);const V=x-T;return R*(1-V)+U*V}eachChild(m){m(this.index),m(this.input)}outputDefined(){return!1}serialize(){return["at-interpolated",this.index.serialize(),this.input.serialize()]}}class rp{constructor(m,x){this.type=Hi,this.needle=m,this.haystack=x}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,Ji),T=x.parse(m[2],2,Ji);return k&&T?qb(k.type,[Hi,Si,kr,Ef,Ji])?new rp(k,T):(x.error(`Expected first argument to be of type boolean, string, number or null, but found ${Dl(k.type)} instead`),null):null}evaluate(m){const x=this.needle.evaluate(m),k=this.haystack.evaluate(m);if(k==null)return!1;if(!xx(x,["boolean","string","number","null"]))throw new gl(`Expected first argument to be of type boolean, string, number or null, but found ${Dl(Al(x))} instead.`);if(!xx(k,["string","array"]))throw new gl(`Expected second argument to be of type array or string, but found ${Dl(Al(k))} instead.`);return k.indexOf(x)>=0}eachChild(m){m(this.needle),m(this.haystack)}outputDefined(){return!0}serialize(){return["in",this.needle.serialize(),this.haystack.serialize()]}}class kj{constructor(m,x,k){this.type=kr,this.needle=m,this.haystack=x,this.fromIndex=k}static parse(m,x){if(m.length<=2||m.length>=5)return x.error(`Expected 3 or 4 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,Ji),T=x.parse(m[2],2,Ji);if(!k||!T)return null;if(!qb(k.type,[Hi,Si,kr,Ef,Ji]))return x.error(`Expected first argument to be of type boolean, string, number or null, but found ${Dl(k.type)} instead`),null;if(m.length===4){const P=x.parse(m[3],3,kr);return P?new kj(k,T,P):null}return new kj(k,T)}evaluate(m){const x=this.needle.evaluate(m),k=this.haystack.evaluate(m);if(!xx(x,["boolean","string","number","null"]))throw new gl(`Expected first argument to be of type boolean, string, number or null, but found ${Dl(Al(x))} instead.`);if(!xx(k,["string","array"]))throw new gl(`Expected second argument to be of type array or string, but found ${Dl(Al(k))} instead.`);if(this.fromIndex){const T=this.fromIndex.evaluate(m);return k.indexOf(x,T)}return k.indexOf(x)}eachChild(m){m(this.needle),m(this.haystack),this.fromIndex&&m(this.fromIndex)}outputDefined(){return!1}serialize(){if(this.fromIndex!=null&&this.fromIndex!==void 0){const m=this.fromIndex.serialize();return["index-of",this.needle.serialize(),this.haystack.serialize(),m]}return["index-of",this.needle.serialize(),this.haystack.serialize()]}}class g1{constructor(m,x,k,T,P,R){this.inputType=m,this.type=x,this.input=k,this.cases=T,this.outputs=P,this.otherwise=R}static parse(m,x){if(m.length<5)return x.error(`Expected at least 4 arguments, but found only ${m.length-1}.`);if(m.length%2!=1)return x.error("Expected an even number of arguments.");let k,T;x.expectedType&&x.expectedType.kind!=="value"&&(T=x.expectedType);const P={},R=[];for(let X=2;XNumber.MAX_SAFE_INTEGER)return pe.error(`Branch labels must be integers no larger than ${Number.MAX_SAFE_INTEGER}.`);if(typeof Se=="number"&&Math.floor(Se)!==Se)return pe.error("Numeric branch labels must be integer values.");if(k){if(pe.checkSubtype(k,Al(Se)))return null}else k=Al(Se);if(P[String(Se)]!==void 0)return pe.error("Branch labels must be unique.");P[String(Se)]=R.length}const be=x.parse(ue,X,T);if(!be)return null;T=T||be.type,R.push(be)}const U=x.parse(m[1],1,Ji);if(!U)return null;const V=x.parse(m[m.length-1],m.length-1,T);return V?U.type.kind!=="value"&&x.concat(1).checkSubtype(k,U.type)?null:new g1(k,T,U,P,R,V):null}evaluate(m){const x=this.input.evaluate(m);return(gx(Al(x),this.inputType)&&this.outputs[this.cases[x]]||this.otherwise).evaluate(m)}eachChild(m){m(this.input),this.outputs.forEach(m),m(this.otherwise)}outputDefined(){return this.outputs.every(m=>m.outputDefined())&&this.otherwise.outputDefined()}serialize(){const m=["match",this.input.serialize()],x=Object.keys(this.cases).sort(),k=[],T={};for(const R of x){const U=T[this.cases[R]];U===void 0?(T[this.cases[R]]=k.length,k.push([this.cases[R],[R]])):k[U][1].push(R)}const P=R=>this.inputType.kind==="number"?Number(R):R;for(const[R,U]of k)m.push(U.length===1?P(U[0]):U.map(P)),m.push(this.outputs[R].serialize());return m.push(this.otherwise.serialize()),m}}class Uy{constructor(m,x,k){this.type=m,this.branches=x,this.otherwise=k}static parse(m,x){if(m.length<4)return x.error(`Expected at least 3 arguments, but found only ${m.length-1}.`),null;if(m.length%2!=0)return x.error("Expected an odd number of arguments."),null;let k;x.expectedType&&x.expectedType.kind!=="value"&&(k=x.expectedType);const T=[];for(let R=1;Rx.outputDefined())&&this.otherwise.outputDefined()}serialize(){const m=["case"];return this.eachChild(x=>{m.push(x.serialize())}),m}}class qy{constructor(m,x,k,T){this.type=m,this.input=x,this.beginIndex=k,this.endIndex=T}static parse(m,x){if(m.length<=2||m.length>=5)return x.error(`Expected 3 or 4 arguments, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1,Ji),T=x.parse(m[2],2,kr);if(!k||!T)return null;if(!qb(k.type,[Hu(Ji),Si,Ji]))return x.error(`Expected first argument to be of type array or string, but found ${Dl(k.type)} instead`),null;if(m.length===4){const P=x.parse(m[3],3,kr);return P?new qy(k.type,k,T,P):null}return new qy(k.type,k,T)}evaluate(m){const x=this.input.evaluate(m),k=this.beginIndex.evaluate(m);if(!xx(x,["string","array"]))throw new gl(`Expected first argument to be of type array or string, but found ${Dl(Al(x))} instead.`);if(this.endIndex){const T=this.endIndex.evaluate(m);return x.slice(k,T)}return x.slice(k)}eachChild(m){m(this.input),m(this.beginIndex),this.endIndex&&m(this.endIndex)}outputDefined(){return!1}serialize(){if(this.endIndex!=null&&this.endIndex!==void 0){const m=this.endIndex.serialize();return["slice",this.input.serialize(),this.beginIndex.serialize(),m]}return["slice",this.input.serialize(),this.beginIndex.serialize()]}}class Jb{constructor(m,x){this.type=Hu(Si),this.str=m,this.delimiter=x}static parse(m,x){if(m.length!==3)return x.error(`Expected 2 arguments, but found ${m.length-1} instead.`);const k=x.parse(m[1],1,Si),T=x.parse(m[2],2,Si);return k&&T?new Jb(k,T):void 0}evaluate(m){const x=this.str.evaluate(m),k=this.delimiter.evaluate(m);return x.split(k)}eachChild(m){m(this.str),m(this.delimiter)}outputDefined(){return!1}serialize(){return["split",this.str.serialize(),this.delimiter.serialize()]}}function vC(b,m){return b==="=="||b==="!="?m.kind==="boolean"||m.kind==="string"||m.kind==="number"||m.kind==="null"||m.kind==="value":m.kind==="string"||m.kind==="number"||m.kind==="value"}function e_(b,m,x,k){return k.compare(m,x)===0}function od(b,m,x){const k=b!=="=="&&b!=="!=";return class qlt{constructor(P,R,U){this.type=Hi,this.lhs=P,this.rhs=R,this.collator=U,this.hasUntypedArgument=P.type.kind==="value"||R.type.kind==="value"}static parse(P,R){if(P.length!==3&&P.length!==4)return R.error("Expected two or three arguments.");const U=P[0];let V=R.parse(P[1],1,Ji);if(!V)return null;if(!vC(U,V.type))return R.concat(1).error(`"${U}" comparisons are not supported for type '${Dl(V.type)}'.`);let X=R.parse(P[2],2,Ji);if(!X)return null;if(!vC(U,X.type))return R.concat(2).error(`"${U}" comparisons are not supported for type '${Dl(X.type)}'.`);if(V.type.kind!==X.type.kind&&V.type.kind!=="value"&&X.type.kind!=="value")return R.error(`Cannot compare types '${Dl(V.type)}' and '${Dl(X.type)}'.`);k&&(V.type.kind==="value"&&X.type.kind!=="value"?V=new tp(X.type,[V]):V.type.kind!=="value"&&X.type.kind==="value"&&(X=new tp(V.type,[X])));let ie=null;if(P.length===4){if(V.type.kind!=="string"&&X.type.kind!=="string"&&V.type.kind!=="value"&&X.type.kind!=="value")return R.error("Cannot use collator to compare non-string types.");if(ie=R.parse(P[3],3,fx),!ie)return null}return new qlt(V,X,ie)}evaluate(P){const R=this.lhs.evaluate(P),U=this.rhs.evaluate(P);if(k&&this.hasUntypedArgument){const V=Al(R),X=Al(U);if(V.kind!==X.kind||V.kind!=="string"&&V.kind!=="number")throw new gl(`Expected arguments for "${b}" to be (string, string) or (number, number), but found (${V.kind}, ${X.kind}) instead.`)}if(this.collator&&!k&&this.hasUntypedArgument){const V=Al(R),X=Al(U);if(V.kind!=="string"||X.kind!=="string")return m(P,R,U)}return this.collator?x(P,R,U,this.collator.evaluate(P)):m(P,R,U)}eachChild(P){P(this.lhs),P(this.rhs),this.collator&&P(this.collator)}outputDefined(){return!0}serialize(){const P=[b];return this.eachChild(R=>{P.push(R.serialize())}),P}}}const f6=od("==",function(b,m,x){return m===x},e_),BN=od("!=",function(b,m,x){return m!==x},function(b,m,x,k){return!e_(0,m,x,k)}),$N=od("<",function(b,m,x){return m",function(b,m,x){return m>x},function(b,m,x,k){return k.compare(m,x)>0}),LR=od("<=",function(b,m,x){return m<=x},function(b,m,x,k){return k.compare(m,x)<=0}),za=od(">=",function(b,m,x){return m>=x},function(b,m,x,k){return k.compare(m,x)>=0});class p0{constructor(m,x,k,T,P,R){this.type=Si,this.number=m,this.locale=x,this.currency=k,this.unit=T,this.minFractionDigits=P,this.maxFractionDigits=R}static parse(m,x){if(m.length!==3)return x.error("Expected two arguments.");const k=x.parse(m[1],1,kr);if(!k)return null;const T=m[2];if(typeof T!="object"||Array.isArray(T))return x.error("NumberFormat options argument must be an object.");let P=null;if(T.locale&&(P=x.parseObjectValue(T.locale,2,"locale",Si),!P))return null;let R=null;if(T.currency&&(R=x.parseObjectValue(T.currency,2,"currency",Si),!R))return null;let U=null;if(T.unit&&(U=x.parseObjectValue(T.unit,2,"unit",Si),!U))return null;let V=null;if(T["min-fraction-digits"]&&(V=x.parseObjectValue(T["min-fraction-digits"],2,"min-fraction-digits",kr),!V))return null;let X=null;return T["max-fraction-digits"]&&(X=x.parseObjectValue(T["max-fraction-digits"],2,"max-fraction-digits",kr),!X)?null:new p0(k,P,R,U,V,X)}evaluate(m){return new Intl.NumberFormat(this.locale?this.locale.evaluate(m):[],{style:(this.currency?"currency":this.unit&&"unit")||"decimal",currency:this.currency?this.currency.evaluate(m):void 0,unit:this.unit?this.unit.evaluate(m):void 0,minimumFractionDigits:this.minFractionDigits?this.minFractionDigits.evaluate(m):void 0,maximumFractionDigits:this.maxFractionDigits?this.maxFractionDigits.evaluate(m):void 0}).format(this.number.evaluate(m))}eachChild(m){m(this.number),this.locale&&m(this.locale),this.currency&&m(this.currency),this.unit&&m(this.unit),this.minFractionDigits&&m(this.minFractionDigits),this.maxFractionDigits&&m(this.maxFractionDigits)}outputDefined(){return!1}serialize(){const m={};return this.locale&&(m.locale=this.locale.serialize()),this.currency&&(m.currency=this.currency.serialize()),this.unit&&(m.unit=this.unit.serialize()),this.minFractionDigits&&(m["min-fraction-digits"]=this.minFractionDigits.serialize()),this.maxFractionDigits&&(m["max-fraction-digits"]=this.maxFractionDigits.serialize()),["number-format",this.number.serialize(),m]}}class t_{constructor(m){this.type=kr,this.input=m}static parse(m,x){if(m.length!==2)return x.error(`Expected 1 argument, but found ${m.length-1} instead.`),null;const k=x.parse(m[1],1);return k?k.type.kind!=="array"&&k.type.kind!=="string"&&k.type.kind!=="value"?(x.error(`Expected argument of type string or array, but found ${Dl(k.type)} instead.`),null):new t_(k):null}evaluate(m){const x=this.input.evaluate(m);if(typeof x=="string"||Array.isArray(x))return x.length;throw new gl(`Expected value to be of type string or array, but found ${Dl(Al(x))} instead.`)}eachChild(m){m(this.input)}outputDefined(){return!1}serialize(){const m=["length"];return this.eachChild(x=>{m.push(x.serialize())}),m}}function bC(b){return function(){b=1831565813+(b|=0)|0;let m=Math.imul(b^b>>>15,1|b);return m=m+Math.imul(m^m>>>7,61|m)^m,((m^m>>>14)>>>0)/4294967296}}const s_={"==":f6,"!=":BN,">":ph,"<":$N,">=":za,"<=":LR,array:tp,at:zp,"at-interpolated":Nj,boolean:tp,case:Uy,coalesce:Xb,collator:lj,format:fm,image:Pr,in:rp,"index-of":kj,interpolate:pu,"interpolate-hcl":pu,"interpolate-lab":pu,length:t_,let:x1,literal:nr,match:g1,number:tp,"number-format":p0,object:tp,slice:qy,step:_j,string:tp,"to-boolean":xm,"to-color":xm,"to-number":xm,"to-string":xm,var:yj,within:dg,distance:zy,config:h1,split:Jb};function n_(b,[m,x,k,T]){m=m.evaluate(b),x=x.evaluate(b),k=k.evaluate(b);const P=T?T.evaluate(b):1,R=Dp(m,x,k,P);if(R)throw new gl(R);return new Gn(m/255,x/255,k/255,P)}function Sj(b,[m,x,k,T]){m=m.evaluate(b),x=x.evaluate(b),k=k.evaluate(b);const P=T?T.evaluate(b):1,R=function(X,ie,ue,pe){return typeof X=="number"&&X>=0&&X<=360?typeof ie=="number"&&ie>=0&&ie<=100&&typeof ue=="number"&&ue>=0&&ue<=100?pe===void 0||typeof pe=="number"&&pe>=0&&pe<=1?null:`Invalid hsla value [${[X,ie,ue,pe].join(", ")}]: 'a' must be between 0 and 1.`:`Invalid hsla value [${(typeof pe=="number"?[X,ie,ue,pe]:[X,ie,ue]).join(", ")}]: 's', and 'l' must be between 0 and 100.`:`Invalid hsla value [${(typeof pe=="number"?[X,ie,ue,pe]:[X,ie,ue]).join(", ")}]: 'h' must be between 0 and 360.`}(m,x,k,P);if(R)throw new gl(R);const U=`hsla(${m}, ${x}%, ${k}%, ${P})`,V=Gn.parse(U);if(!V)throw new gl(`Failed to parse HSLA color: ${U}`);return V}function y1(b,m){return b in m}function Cj(b,m){const x=m[b];return x===void 0?null:x}function f0(b){return{type:b}}function Tj(b){if(b instanceof h1)return new Set([b.key]);let m=new Set;return b.eachChild(x=>{m=new Set([...m,...Tj(x)])}),m}function r_(b){if(b instanceof Dc&&b.name==="is-active-floor")return!0;let m=!1;return b.eachChild(x=>{!m&&r_(x)&&(m=!0)}),m}function UN(b){return{result:"success",value:b}}function Rc(b){return{result:"error",value:b}}function vm(b,m){return!!b&&!!b.parameters&&b.parameters.indexOf(m)>-1}function Bp(b){return b["property-type"]==="data-driven"}function qN(b){return vm(b.expression,"measure-light")}function VN(b){return vm(b.expression,"zoom")}function ap(b){return!!b.expression&&b.expression.interpolated}function HN(b){return typeof b=="object"&&b!==null&&!Array.isArray(b)}function yx(b){return b}function x6(b,m){const x=m.type==="color",k=b.stops&&typeof b.stops[0][0]=="object",T=k||!(k||b.property!==void 0),P=b.type||(ap(m)?"exponential":"interval");if(x&&((b=Object.assign({},b)).stops&&(b.stops=b.stops.map(X=>[X[0],Gn.parse(X[1])])),b.default=Gn.parse(b.default?b.default:m.default)),b.colorSpace&&b.colorSpace!=="rgb"&&!yC[b.colorSpace])throw new Error(`Unknown color space: ${b.colorSpace}`);let R,U,V;if(P==="exponential")R=_C;else if(P==="interval")R=y6;else if(P==="categorical"){R=g6,U=Object.create(null);for(const X of b.stops)U[X[0]]=X[1];V=typeof b.stops[0][0]}else{if(P!=="identity")throw new Error(`Unknown function type "${P}"`);R=Ej}if(k){const X={},ie=[];for(let be=0;bebe[0]),evaluate:({zoom:be},Se)=>_C({stops:ue,base:b.base},m,be).evaluate(be,Se)}}if(T){const X=P==="exponential"?{name:"exponential",base:b.base!==void 0?b.base:1}:null;return{kind:"camera",interpolationType:X,interpolationFactor:pu.interpolationFactor.bind(void 0,X),zoomStops:b.stops.map(ie=>ie[0]),evaluate:({zoom:ie})=>R(b,m,ie,U,V)}}return{kind:"source",evaluate(X,ie){const ue=ie&&ie.properties?ie.properties[b.property]:void 0;return ue===void 0?vx(b.default,m.default):R(b,m,ue,U,V)}}}function vx(b,m,x){return b!==void 0?b:m!==void 0?m:x!==void 0?x:void 0}function g6(b,m,x,k,T){return vx(typeof x===T?k[x]:void 0,b.default,m.default)}function y6(b,m,x){if(!Hb(x))return vx(b.default,m.default);const k=b.stops.length;if(k===1||x<=b.stops[0][0])return b.stops[0][1];if(x>=b.stops[k-1][0])return b.stops[k-1][1];const T=bj(b.stops.map(P=>P[0]),x);return b.stops[T][1]}function _C(b,m,x){const k=b.base!==void 0?b.base:1;if(!Hb(x))return vx(b.default,m.default);const T=b.stops.length;if(T===1||x<=b.stops[0][0])return b.stops[0][1];if(x>=b.stops[T-1][0])return b.stops[T-1][1];const P=bj(b.stops.map(ie=>ie[0]),x),R=function(ie,ue,pe,be){const Se=be-pe,Le=ie-pe;return Se===0?0:ue===1?Le/Se:(Math.pow(ue,Le)-1)/(Math.pow(ue,Se)-1)}(x,k,b.stops[P][0],b.stops[P+1][0]),U=b.stops[P][1],V=b.stops[P+1][1];let X=pm[m.type]||yx;if(b.colorSpace&&b.colorSpace!=="rgb"){const ie=yC[b.colorSpace];X=(ue,pe)=>ie.reverse(ie.interpolate(ie.forward(ue),ie.forward(pe),R))}return typeof U.evaluate=="function"?{evaluate(...ie){const ue=U.evaluate.apply(void 0,ie),pe=V.evaluate.apply(void 0,ie);if(ue!==void 0&&pe!==void 0)return X(ue,pe,R)}}:X(U,V,R)}function Ej(b,m,x){return m.type==="color"?x=Gn.parse(x):m.type==="formatted"?x=Ud.fromString(x.toString()):m.type==="resolvedImage"?x=qd.build(x.toString()):Ry(x)===m.type||m.type==="enum"&&m.values[x]||(x=void 0),vx(x,b.default,m.default)}Dc.register(s_,{error:[{kind:"error"},[Si],(b,[m])=>{throw new gl(m.evaluate(b))}],typeof:[Si,[Ji],(b,[m])=>Dl(Al(m.evaluate(b)))],"to-rgba":[Hu(kr,4),[Oh],(b,[m])=>m.evaluate(b).toNonPremultipliedRenderColor(null).toArray()],"to-hsla":[Hu(kr,4),[Oh],(b,[m])=>m.evaluate(b).toNonPremultipliedRenderColor(null).toHslaArray()],rgb:[Oh,[kr,kr,kr],n_],rgba:[Oh,[kr,kr,kr,kr],n_],hsl:[Oh,[kr,kr,kr],Sj],hsla:[Oh,[kr,kr,kr,kr],Sj],has:{type:Hi,overloads:[[[Si],(b,[m])=>y1(m.evaluate(b),b.properties())],[[Si,px],(b,[m,x])=>y1(m.evaluate(b),x.evaluate(b))]]},get:{type:Ji,overloads:[[[Si],(b,[m])=>Cj(m.evaluate(b),b.properties())],[[Si,px],(b,[m,x])=>Cj(m.evaluate(b),x.evaluate(b))]]},"feature-state":[Ji,[Si],(b,[m])=>Cj(m.evaluate(b),b.featureState||{})],properties:[px,[],b=>b.properties()],"geometry-type":[Si,[],b=>b.geometryType()],worldview:[Si,[],b=>b.globals.worldview||""],"is-active-floor":[Hi,f0(Si),(b,m)=>{if(!(b.globals&&b.globals.activeFloors&&b.globals.activeFloors.size>0))return!1;if(m.length===0)return!0;const x=b.globals.activeFloors;return m.some(k=>{const T=k.evaluate(b);return x.has(T)})}],id:[Ji,[],b=>b.id()],zoom:[kr,[],b=>b.globals.zoom],pitch:[kr,[],b=>b.globals.pitch||0],"distance-from-center":[kr,[],b=>b.distanceFromCenter()],"measure-light":[kr,[Si],(b,[m])=>b.measureLight(m.evaluate(b))],"heatmap-density":[kr,[],b=>b.globals.heatmapDensity||0],"line-progress":[kr,[],b=>b.globals.lineProgress||0],"raster-value":[kr,[],b=>b.globals.rasterValue||0],"raster-particle-speed":[kr,[],b=>b.globals.rasterParticleSpeed||0],"sky-radial-progress":[kr,[],b=>b.globals.skyRadialProgress||0],accumulated:[Ji,[],b=>b.globals.accumulated===void 0?null:b.globals.accumulated],"+":[kr,f0(kr),(b,m)=>{let x=0;for(const k of m)x+=k.evaluate(b);return x}],"*":[kr,f0(kr),(b,m)=>{let x=1;for(const k of m)x*=k.evaluate(b);return x}],"-":{type:kr,overloads:[[[kr,kr],(b,[m,x])=>m.evaluate(b)-x.evaluate(b)],[[kr],(b,[m])=>-m.evaluate(b)]]},"/":[kr,[kr,kr],(b,[m,x])=>m.evaluate(b)/x.evaluate(b)],"%":[kr,[kr,kr],(b,[m,x])=>m.evaluate(b)%x.evaluate(b)],ln2:[kr,[],()=>Math.LN2],pi:[kr,[],()=>Math.PI],e:[kr,[],()=>Math.E],"^":[kr,[kr,kr],(b,[m,x])=>Math.pow(m.evaluate(b),x.evaluate(b))],sqrt:[kr,[kr],(b,[m])=>Math.sqrt(m.evaluate(b))],log10:[kr,[kr],(b,[m])=>Math.log(m.evaluate(b))/Math.LN10],ln:[kr,[kr],(b,[m])=>Math.log(m.evaluate(b))],log2:[kr,[kr],(b,[m])=>Math.log2(m.evaluate(b))],sin:[kr,[kr],(b,[m])=>Math.sin(m.evaluate(b))],cos:[kr,[kr],(b,[m])=>Math.cos(m.evaluate(b))],tan:[kr,[kr],(b,[m])=>Math.tan(m.evaluate(b))],asin:[kr,[kr],(b,[m])=>Math.asin(m.evaluate(b))],acos:[kr,[kr],(b,[m])=>Math.acos(m.evaluate(b))],atan:[kr,[kr],(b,[m])=>Math.atan(m.evaluate(b))],min:[kr,f0(kr),(b,m)=>Math.min(...m.map(x=>x.evaluate(b)))],max:[kr,f0(kr),(b,m)=>Math.max(...m.map(x=>x.evaluate(b)))],abs:[kr,[kr],(b,[m])=>Math.abs(m.evaluate(b))],round:[kr,[kr],(b,[m])=>{const x=m.evaluate(b);return x<0?-Math.round(-x):Math.round(x)}],floor:[kr,[kr],(b,[m])=>Math.floor(m.evaluate(b))],ceil:[kr,[kr],(b,[m])=>Math.ceil(m.evaluate(b))],"filter-==":[Hi,[Si,Ji],(b,[m,x])=>b.properties()[m.value]===x.value],"filter-id-==":[Hi,[Ji],(b,[m])=>b.id()===m.value],"filter-type-==":[Hi,[Si],(b,[m])=>b.geometryType()===m.value],"filter-<":[Hi,[Si,Ji],(b,[m,x])=>{const k=b.properties()[m.value],T=x.value;return typeof k==typeof T&&k{const x=b.id(),k=m.value;return typeof x==typeof k&&x":[Hi,[Si,Ji],(b,[m,x])=>{const k=b.properties()[m.value],T=x.value;return typeof k==typeof T&&k>T}],"filter-id->":[Hi,[Ji],(b,[m])=>{const x=b.id(),k=m.value;return typeof x==typeof k&&x>k}],"filter-<=":[Hi,[Si,Ji],(b,[m,x])=>{const k=b.properties()[m.value],T=x.value;return typeof k==typeof T&&k<=T}],"filter-id-<=":[Hi,[Ji],(b,[m])=>{const x=b.id(),k=m.value;return typeof x==typeof k&&x<=k}],"filter->=":[Hi,[Si,Ji],(b,[m,x])=>{const k=b.properties()[m.value],T=x.value;return typeof k==typeof T&&k>=T}],"filter-id->=":[Hi,[Ji],(b,[m])=>{const x=b.id(),k=m.value;return typeof x==typeof k&&x>=k}],"filter-has":[Hi,[Ji],(b,[m])=>m.value in b.properties()],"filter-has-id":[Hi,[],b=>b.id()!==null&&b.id()!==void 0],"filter-type-in":[Hi,[Hu(Si)],(b,[m])=>m.value.indexOf(b.geometryType())>=0],"filter-id-in":[Hi,[Hu(Ji)],(b,[m])=>m.value.indexOf(b.id())>=0],"filter-in-small":[Hi,[Si,Hu(Ji)],(b,[m,x])=>x.value.indexOf(b.properties()[m.value])>=0],"filter-in-large":[Hi,[Si,Hu(Ji)],(b,[m,x])=>function(k,T,P,R){for(;P<=R;){const U=P+R>>1;if(T[U]===k)return!0;T[U]>k?R=U-1:P=U+1}return!1}(b.properties()[m.value],x.value,0,x.value.length-1)],all:{type:Hi,overloads:[[[Hi,Hi],(b,[m,x])=>m.evaluate(b)&&x.evaluate(b)],[f0(Hi),(b,m)=>{for(const x of m)if(!x.evaluate(b))return!1;return!0}]]},any:{type:Hi,overloads:[[[Hi,Hi],(b,[m,x])=>m.evaluate(b)||x.evaluate(b)],[f0(Hi),(b,m)=>{for(const x of m)if(x.evaluate(b))return!0;return!1}]]},"!":[Hi,[Hi],(b,[m])=>!m.evaluate(b)],"is-supported-script":[Hi,[Si],(b,[m])=>{const x=b.globals&&b.globals.isSupportedScript;return!x||x(m.evaluate(b))}],upcase:[Si,[Si],(b,[m])=>m.evaluate(b).toUpperCase()],downcase:[Si,[Si],(b,[m])=>m.evaluate(b).toLowerCase()],concat:[Si,f0(Ji),(b,m)=>m.map(x=>Qr(x.evaluate(b))).join("")],"resolved-locale":[Si,[fx],(b,[m])=>m.evaluate(b).resolvedLocale()],random:[kr,[kr,kr,Ji],(b,m)=>{const[x,k,T]=m.map(R=>R.evaluate(b));if(x>k||x===k)return x;let P;if(typeof T=="string")P=function(R){let U=0;if(R.length===0)return U;for(let V=0;VJSON.stringify(ue)).join(", ")}, but found ${JSON.stringify(ie)} instead.`);return ie}catch(ie){const ue=ie;return this._warningHistory[ue.message]||(this._warningHistory[ue.message]=!0,typeof console<"u"&&console.warn(`Failed to evaluate expression "${JSON.stringify(this.expression.serialize())}". ${ue.message}`)),this._defaultValue}}}function Vy(b){return Array.isArray(b)&&b.length>0&&typeof b[0]=="string"&&b[0]in s_}function bx(b,m,x,k,T){const P=new vj(s_,[],m?function(U){const V={color:Oh,string:Si,number:kr,enum:Si,boolean:Hi,formatted:Ly,resolvedImage:Ub};return U.type==="array"?Hu(V[U.value]||Ji,U.length):V[U.type]}(m):void 0,void 0,void 0,x,k,T),R=P.parse(b,void 0,void 0,void 0,m&&m.type==="string"?{typeAnnotation:"coerce"}:void 0);return R?UN(new v1(R,m,x,k,T)):Rc(P.errors)}class x0{constructor(m,x,k,T){this.kind=m,this._styleExpression=x,this.isLightConstant=k,this.isLineProgressConstant=T,this.isStateDependent=m!=="constant"&&!$y(x.expression),this.configDependencies=Tj(x.expression),this.isIndoorDependent=r_(x.expression)}evaluateWithoutErrorHandling(m,x,k,T,P,R){return this._styleExpression.evaluateWithoutErrorHandling(m,x,k,T,P,R)}evaluate(m,x,k,T,P,R,U){return this._styleExpression.evaluate(m,x,k,T,P,R,void 0,void 0,U)}}class _x{constructor(m,x,k,T,P,R){this.kind=m,this.zoomStops=k,this._styleExpression=x,this.isStateDependent=m!=="camera"&&!$y(x.expression),this.isIndoorDependent=r_(x.expression),this.isLightConstant=P,this.isLineProgressConstant=R,this.configDependencies=Tj(x.expression),this.interpolationType=T}evaluateWithoutErrorHandling(m,x,k,T,P,R){return this._styleExpression.evaluateWithoutErrorHandling(m,x,k,T,P,R)}evaluate(m,x,k,T,P,R){return this._styleExpression.evaluate(m,x,k,T,P,R)}interpolationFactor(m,x,k){return this.interpolationType?pu.interpolationFactor(this.interpolationType,m,x,k):0}}function Aj(b,m,x,k,T){if((b=bx(b,m,x,k,T)).result==="error")return b;const P=b.value.expression,R=By(P);if(!R&&!Bp(m))return Rc([new Vu("","data expressions not supported")]);const U=gm(P,["zoom","pitch","distance-from-center"]);if(!U&&!VN(m))return Rc([new Vu("","zoom expressions not supported")]);const V=gm(P,["measure-light"]);if(!V&&!qN(m))return Rc([new Vu("","measure-light expression not supported")]);const X=gm(P,["line-progress"]);if(!X&&!function(pe){return vm(pe.expression,"line-progress")}(m))return Rc([new Vu("","line-progress expression not supported")]);const ie=m.expression&&m.expression.relaxZoomRestriction,ue=$p(P);return ue||U||ie?ue instanceof Vu?Rc([ue]):ue instanceof pu&&!ap(m)?Rc([new Vu("",'"interpolate" expressions cannot be used with this property')]):UN(ue?new _x(R&&X?"camera":"composite",b.value,ue.labels,ue instanceof pu?ue.interpolation:void 0,V,X):new x0(R&&X?"constant":"source",b.value,V,X)):Rc([new Vu("",'"zoom" expression may only be used as input to a top-level "step" or "interpolate" expression, or in the properties of atmosphere.')])}class a_{constructor(m,x){this._parameters=m,this._specification=x,Object.assign(this,x6(this._parameters,this._specification))}static deserialize(m){return new a_(m._parameters,m._specification)}static serialize(m){return{_parameters:m._parameters,_specification:m._specification}}}function $p(b){let m=null;if(b instanceof x1)m=$p(b.result);else if(b instanceof Xb){for(const x of b.args)if(m=$p(x),m)break}else(b instanceof _j||b instanceof pu)&&b.input instanceof Dc&&b.input.name==="zoom"&&(m=b);return m instanceof Vu||b.eachChild(x=>{const k=$p(x);k instanceof Vu?m=k:m&&k&&m!==k&&(m=new Vu("",'Only one zoom-based "step" or "interpolate" subexpression may be used in an expression.'))}),m}var GN,WN,Mj=function(){if(WN)return GN;WN=1,GN=m;var b=3;function m(x,k,T){var P=this.cells=[];if(x instanceof ArrayBuffer){this.arrayBuffer=x;var R=new Int32Array(this.arrayBuffer);x=R[0],this.d=(k=R[1])+2*(T=R[2]);for(var U=0;U=pe[Le+0]&&P>=pe[Le+1])?(V[Se]=!0,U.push(ue[Se])):V[Se]=!1}}},m.prototype._forEachCell=function(x,k,T,P,R,U,V,X){for(var ie=this._convertToCellCoord(x),ue=this._convertToCellCoord(k),pe=this._convertToCellCoord(T),be=this._convertToCellCoord(P),Se=ie;Se<=pe;Se++)for(var Le=ue;Le<=be;Le++){var ze=this.d*Le+Se;if((!X||X(this._convertFromCellCoord(Se),this._convertFromCellCoord(Le),this._convertFromCellCoord(Se+1),this._convertFromCellCoord(Le+1)))&&R.call(this,x,k,T,P,ze,U,V,X))return}},m.prototype._convertFromCellCoord=function(x){return(x-this.padding)/this.scale},m.prototype._convertToCellCoord=function(x){return Math.max(0,Math.min(this.d-1,Math.floor(x*this.scale)+this.padding))},m.prototype.toArrayBuffer=function(){if(this.arrayBuffer)return this.arrayBuffer;for(var x=this.cells,k=b+this.cells.length+1+1,T=0,P=0;P=0||(T[P]=dc(b[P],m)));b instanceof Error&&(T.message=b.message)}if(T.$name)throw new Error("$name property is reserved for worker serialization logic.");return k!=="Object"&&(T.$name=k),T}throw new Error("can't serialize object of type "+typeof b)}function ec(b){if(b==null||typeof b=="boolean"||typeof b=="number"||typeof b=="string"||b instanceof Boolean||b instanceof Number||b instanceof String||b instanceof Date||b instanceof RegExp||po(b)||b instanceof ImageBitmap||ArrayBuffer.isView(b)||b instanceof ImageData)return b;if(Array.isArray(b))return b.map(ec);if(typeof b=="object"){const m=b.$name||"Object";if(m==="Map"){const T=b.entries||[],P=new Map;for(let R=0;Rb>=1536&&b<=1791,Bh=b=>b>=1872&&b<=1919,v0=b=>b>=2208&&b<=2303,ld=b=>b>=11904&&b<=12031,Up=b=>b>=12032&&b<=12255,b0=b=>b>=12272&&b<=12287,Hy=b=>b>=12288&&b<=12351,b1=b=>b>=12352&&b<=12447,wx=b=>b>=12448&&b<=12543,$h=b=>b>=12544&&b<=12591,i_=b=>b>=12704&&b<=12735,Rf=b=>b>=12736&&b<=12783,hg=b=>b>=12784&&b<=12799,_1=b=>b>=12800&&b<=13055,Ij=b=>b>=13056&&b<=13311,Pj=b=>b>=13312&&b<=19903,jx=b=>b>=19968&&b<=40959,Gy=b=>b>=40960&&b<=42127,mg=b=>b>=42128&&b<=42191,o_=b=>b>=44032&&b<=55215,Wy=b=>b>=63744&&b<=64255,Lj=b=>b>=64336&&b<=65023,Dj=b=>b>=65040&&b<=65055,l_=b=>b>=65072&&b<=65103,fh=b=>b>=65104&&b<=65135,pg=b=>b>=65136&&b<=65279,ip=b=>b>=65280&&b<=65519;function Uh(b){for(const m of b)if(NC(m.charCodeAt(0)))return!0;return!1}function v6(b){for(const m of b)if(!wC(m.charCodeAt(0)))return!1;return!0}function wC(b){return!(Gu(b)||Bh(b)||v0(b)||Lj(b)||pg(b))}function jC(b){return!(b<11904||!(i_(b)||$h(b)||l_(b)||Wy(b)||Ij(b)||ld(b)||Rf(b)||Hy(b)||Pj(b)||jx(b)||_1(b)||ip(b)||b1(b)||b0(b)||Up(b)||hg(b)||wx(b)||Dj(b)||mg(b)||Gy(b)))}function NC(b){return!(b!==746&&b!==747&&(b<4352||!(i_(b)||$h(b)||l_(b)&&!(b>=65097&&b<=65103)||Wy(b)||Ij(b)||ld(b)||Rf(b)||!(!Hy(b)||b>=12296&&b<=12305||b>=12308&&b<=12319||b===12336)||Pj(b)||jx(b)||_1(b)||(m=>m>=12592&&m<=12687)(b)||(m=>m>=43360&&m<=43391)(b)||(m=>m>=55216&&m<=55295)(b)||(m=>m>=4352&&m<=4607)(b)||o_(b)||b1(b)||b0(b)||(m=>m>=12688&&m<=12703)(b)||Up(b)||hg(b)||wx(b)&&b!==12540||!(!ip(b)||b===65288||b===65289||b===65293||b>=65306&&b<=65310||b===65339||b===65341||b===65343||b>=65371&&b<=65503||b===65507||b>=65512&&b<=65519)||!(!fh(b)||b>=65112&&b<=65118||b>=65123&&b<=65126)||(m=>m>=5120&&m<=5759)(b)||(m=>m>=6320&&m<=6399)(b)||Dj(b)||(m=>m>=19904&&m<=19967)(b)||Gy(b)||mg(b))))}function _0(b){return b===12312||b===12313||b===12316||b===12540||b===12448}function Ky(b){return!(NC(b)||function(m){return!!((x=>x>=128&&x<=255)(m)&&(m===167||m===169||m===174||m===177||m===188||m===189||m===190||m===215||m===247)||(x=>x>=8192&&x<=8303)(m)&&(m===8214||m===8224||m===8225||m===8240||m===8241||m===8251||m===8252||m===8258||m===8263||m===8264||m===8265||m===8273)||(x=>x>=8448&&x<=8527)(m)||(x=>x>=8528&&x<=8591)(m)||(x=>x>=8960&&x<=9215)(m)&&(m>=8960&&m<=8967||m>=8972&&m<=8991||m>=8996&&m<=9e3||m===9003||m>=9085&&m<=9114||m>=9150&&m<=9165||m===9167||m>=9169&&m<=9179||m>=9186&&m<=9215)||(x=>x>=9216&&x<=9279)(m)&&m!==9251||(x=>x>=9280&&x<=9311)(m)||(x=>x>=9312&&x<=9471)(m)||(x=>x>=9632&&x<=9727)(m)||(x=>x>=9728&&x<=9983)(m)&&!(m>=9754&&m<=9759)||(x=>x>=11008&&x<=11263)(m)&&(m>=11026&&m<=11055||m>=11088&&m<=11097||m>=11192&&m<=11243)||Hy(m)||wx(m)||(x=>x>=57344&&x<=63743)(m)||l_(m)||fh(m)||ip(m)||m===8734||m===8756||m===8757||m>=9984&&m<=10087||m>=10102&&m<=10131||m===65532||m===65533)}(b))}function kC(b){return Gu(b)||Bh(b)||v0(b)||Lj(b)||pg(b)}function Rj(b){return b>=1424&&b<=2303||Lj(b)||pg(b)}function fg(b,m){return!(!m&&Rj(b)||b>=2304&&b<=3583||b>=3840&&b<=4255||(x=>x>=6016&&x<=6143)(b))}function b6(b){for(const m of b)if(Rj(m.charCodeAt(0)))return!0;return!1}const bm={unavailable:"unavailable",deferred:"deferred",loading:"loading",parsing:"parsing",parsed:"parsed",loaded:"loaded",error:"error"};let Of=null,Hd=bm.unavailable,qp=null;const _6=function(b){b&&typeof b=="string"&&b.indexOf("NetworkError")>-1&&(Hd=bm.error),Of&&Of(b)};function KN(){YN.fire(new Lc("pluginStateChange",{pluginStatus:Hd,pluginURL:qp}))}const YN=new Lp,w0=function(){return Hd},w6=function(){if(Hd!==bm.deferred||!qp)throw new Error("rtl-text-plugin cannot be downloaded unless a pluginURL is specified");Hd=bm.loading,KN(),qp&&Iy({url:qp},b=>{b?_6(b):(Hd=bm.loaded,KN())})},_m={applyArabicShaping:null,processBidirectionalText:null,processStyledBidirectionalText:null,isLoaded:()=>Hd===bm.loaded||_m.applyArabicShaping!=null,isLoading:()=>Hd===bm.loading,setState(b){Hd=b.pluginStatus,qp=b.pluginURL},isParsing:()=>Hd===bm.parsing,isParsed:()=>Hd===bm.parsed,getPluginURL:()=>qp},SC=function(){_m.isLoading()||_m.isLoaded()||w0()!=="deferred"||w6()};class Aa{constructor(m,x){this.zoom=m,x?(this.now=x.now,this.fadeDuration=x.fadeDuration,this.transition=x.transition,this.pitch=x.pitch,this.brightness=x.brightness,this.worldview=x.worldview,this.activeFloors=x.activeFloors):(this.now=0,this.fadeDuration=0,this.transition={},this.pitch=0,this.brightness=0)}isSupportedScript(m){return function(x,k){for(const T of x)if(!fg(T.charCodeAt(0),k))return!1;return!0}(m,_m.isLoaded())}}class c_{constructor(m,x,k,T,P){this.property=m,this.value=x,this.expression=function(R,U,V,X,ie){if(HN(R))return new a_(R,U);if(Vy(R)||Array.isArray(R)&&R.length>0){const ue=Aj(R,U,V,X,ie);if(ue.result==="error")throw new Error(ue.value.map(pe=>`${pe.key}: ${pe.message}`).join(", "));return ue.value}{let ue=R;return typeof R=="string"&&U.type==="color"&&(ue=Gn.parse(R)),{kind:"constant",configDependencies:new Set,isIndoorDependent:!1,evaluate:()=>ue}}}(x===void 0?m.specification.default:x,m.specification,k,T,P)}isIndoorDependent(){return this.expression.isIndoorDependent}isDataDriven(){return this.expression.kind==="source"||this.expression.kind==="composite"}possiblyEvaluate(m,x,k,T){return this.property.possiblyEvaluate(this,m,x,k,T)}}class Oj{constructor(m,x,k,T){this.property=m,this.value=new c_(m,void 0,x,k,T)}transitioned(m,x){return new d_(this.property,this.value,x,Object.assign({},m.transition,this.transition),m.now)}untransitioned(){return new d_(this.property,this.value,null,{},0)}}class ZN{constructor(m,x,k,T){this._properties=m,this._values=Object.create(m.defaultTransitionablePropertyValues),this._scope=x,this._options=k,this._iconImageUseTheme=T,this._isIndoorDependent=!1,this.configDependencies=new Set}getValue(m){return mn(this._values[m].value.value)}setValue(m,x){this._values.hasOwnProperty(m)||(this._values[m]=new Oj(this._values[m].property,this._scope,this._options,this._iconImageUseTheme)),this._values[m].value=new c_(this._values[m].property,x===null?void 0:mn(x),this._scope,this._options,this._iconImageUseTheme),this._values[m].value.expression.configDependencies&&(this.configDependencies=new Set([...this.configDependencies,...this._values[m].value.expression.configDependencies]),this._isIndoorDependent=this._isIndoorDependent||this._values[m].value.isIndoorDependent())}setTransitionOrValue(m,x){x&&(this._options=x);const k=this._properties.properties;if(m)for(const T in m){const P=m[T];if(T.endsWith("-transition")){const R=T.slice(0,-11);k[R]&&this.setTransition(R,P)}else k.hasOwnProperty(T)&&this.setValue(T,P)}}getTransition(m){return mn(this._values[m].transition)}setTransition(m,x){this._values.hasOwnProperty(m)||(this._values[m]=new Oj(this._values[m].property)),this._values[m].transition=mn(x)||void 0}serialize(){const m={};for(const x of Object.keys(this._values)){const k=this.getValue(x);k!==void 0&&(m[x]=k);const T=this.getTransition(x);T!==void 0&&(m[`${x}-transition`]=T)}return m}transitioned(m,x){const k=new QN(this._properties);for(const T of Object.keys(this._values))k._values[T]=this._values[T].transitioned(m,x._values[T]);return k}untransitioned(){const m=new QN(this._properties);for(const x of Object.keys(this._values))m._values[x]=this._values[x].untransitioned();return m}isIndoorDependent(){return this._isIndoorDependent}}class d_{constructor(m,x,k,T,P){const R=T.delay||0,U=T.duration||0;P=P||0,this.property=m,this.value=x,this.begin=P+R,this.end=this.begin+U,m.specification.transition&&(T.delay||T.duration)&&(this.prior=k)}possiblyEvaluate(m,x,k){const T=m.now||0,P=this.value.possiblyEvaluate(m,x,k),R=this.prior;if(R){if(T>this.end)return this.prior=null,P;if(this.value.isDataDriven())return this.prior=null,P;if(T":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 Fj(b){return b instanceof Number||b instanceof String||b instanceof Boolean?b.valueOf():b}function u_(b){if(Array.isArray(b))return b.map(u_);if(b instanceof Object&&!(b instanceof Number||b instanceof String||b instanceof Boolean)){const m={};for(const x in b)m[x]=u_(b[x]);return m}return Fj(b)}function zj(b){if(b===!0||b===!1)return!0;if(!Array.isArray(b)||b.length===0)return!1;switch(b[0]){case"has":return b.length>=2&&b[1]!=="$id"&&b[1]!=="$type";case"in":return b.length>=3&&(typeof b[1]!="string"||Array.isArray(b[2]));case"!in":case"!has":case"none":return!1;case"==":case"!=":case">":case">=":case"<":case"<=":return b.length!==3||Array.isArray(b[1])||Array.isArray(b[2]);case"any":case"all":for(const m of b.slice(1))if(!zj(m)&&typeof m!="boolean")return!1;return!0;default:return!0}}function JN(b,m="",x=null,k="fill"){if(b==null)return{filter:()=>!0,needGeometry:!1,needFeature:!1};zj(b)||(b=tk(b));const T=b;let P=!0;try{P=function(ie){if(!j1(ie))return ie;let ue=u_(ie);return TC(ue),ue=CC(ue),ue}(T)}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(T,null,2)} `)}let R=null,U=null;if(k!=="background"&&k!=="sky"&&k!=="slot"){U=ps[`filter_${k}`];const ie=bx(P,U,m,x);if(ie.result==="error")throw new Error(ie.value.map(ue=>`${ue.key}: ${ue.message}`).join(", "));R=(ue,pe,be)=>ie.value.evaluate(ue,pe,{},be)}let V=null,X=null;if(P!==T){const ie=bx(T,U,m,x);if(ie.result==="error")throw new Error(ie.value.map(ue=>`${ue.key}: ${ue.message}`).join(", "));V=(ue,pe,be,Se,Le)=>ie.value.evaluate(ue,pe,{},be,void 0,void 0,Se,Le),X=!By(ie.value.expression)}return{filter:R,dynamicFilter:V||void 0,needGeometry:j6(P),needFeature:!!X}}function CC(b){if(!Array.isArray(b))return b;const m=function(x){if(EC.has(x[0])){for(let k=1;kCC(x))}function TC(b){let m=!1;const x=[];if(b[0]==="case"){for(let k=1;k",">=","<","<=","to-boolean"]);function ek(b,m){return bm?1:0}function j6(b){if(!Array.isArray(b))return!1;if(b[0]==="within"||b[0]==="distance")return!0;for(let m=1;m"||m==="<="||m===">="?Q(b[1],b[2],m):m==="any"?(x=b.slice(1),["any"].concat(x.map(tk))):m==="all"?["all"].concat(b.slice(1).map(tk)):m==="none"?["all"].concat(b.slice(1).map(tk).map(Ve)):m==="in"?J(b[1],b.slice(2)):m==="!in"?Ve(J(b[1],b.slice(2))):m==="has"?Ne(b[1]):m!=="!has"||Ve(Ne(b[1]));var x}function Q(b,m,x){switch(b){case"$type":return[`filter-type-${x}`,m];case"$id":return[`filter-id-${x}`,m];default:return[`filter-${x}`,b,m]}}function J(b,m){if(m.length===0)return!1;switch(b){case"$type":return["filter-type-in",["literal",m]];case"$id":return["filter-id-in",["literal",m]];default:return m.length>200&&!m.some(x=>typeof x!=typeof m[0])?["filter-in-large",b,["literal",m.sort(ek)]]:["filter-in-small",b,["literal",m]]}}function Ne(b){switch(b){case"$type":return!0;case"$id":return["filter-has-id"];default:return["filter-has",b]}}function Ve(b){return["!",b]}const et="";function vt(b,m){return m?`${b}${et}${m}`:b}function ms(b){const m=b.indexOf(et);return m>=0?b.slice(m+1):""}let pn;const Wn=()=>pn||(pn=new qo({"icon-size":new bn(ps.layout_symbol["icon-size"]),"icon-image":new bn(ps.layout_symbol["icon-image"]),"icon-rotate":new bn(ps.layout_symbol["icon-rotate"]),"icon-offset":new bn(ps.layout_symbol["icon-offset"]),"text-size":new bn(ps.layout_symbol["text-size"]),"text-rotate":new bn(ps.layout_symbol["text-rotate"]),"text-offset":new bn(ps.layout_symbol["text-offset"])}));let zr;const Ba=()=>zr||(zr=new qo({"icon-opacity":new bn(ps.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new bn(ps.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new bn(ps.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new bn(ps.paint_symbol["text-emissive-strength"]),"icon-color":new bn(ps.paint_symbol["icon-color"]),"icon-halo-color":new bn(ps.paint_symbol["icon-halo-color"]),"icon-halo-width":new bn(ps.paint_symbol["icon-halo-width"]),"icon-halo-blur":new bn(ps.paint_symbol["icon-halo-blur"]),"icon-translate":new bn(ps.paint_symbol["icon-translate"]),"text-opacity":new bn(ps.paint_symbol["text-opacity"]),"text-occlusion-opacity":new bn(ps.paint_symbol["text-occlusion-opacity"]),"text-color":new bn(ps.paint_symbol["text-color"],{runtimeType:Oh,getOverride:b=>b.textColor,hasOverride:b=>!!b.textColor}),"text-halo-color":new bn(ps.paint_symbol["text-halo-color"]),"text-halo-width":new bn(ps.paint_symbol["text-halo-width"]),"text-halo-blur":new bn(ps.paint_symbol["text-halo-blur"]),"text-translate":new bn(ps.paint_symbol["text-translate"]),"symbol-z-offset":new bn(ps.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"})}));class oo{constructor(m,x,k,T,P,R){this._conditionSpec=m,this._propertiesSpec=k;const U=bx(m,ps.appearance.condition);if(U.result==="success"&&(this.condition=U.value),this.name=x,k){this.layoutProperties=new Gd(Wn()),this.unevaluatedLayout=new XN(Wn(),T,P,R),this.paintProperties=new Gd(Ba()),this.unevaluatedPaint=new XN(Ba(),T,P,"");for(const V in k)V in this.unevaluatedLayout._values?this.unevaluatedLayout.setValue(V,k[V]):V in this.unevaluatedPaint._values&&this.unevaluatedPaint.setValue(V,k[V])}}isActive(m){return!(this.condition||!m.isHidden||this.name!=="hidden")||this.condition.evaluate(m.globals,m.feature,m.featureState,m.canonical)}getCondition(){return this.condition}getName(){return this.name}getLayoutProperty(m){return this.layoutProperties.get(m)}getPaintProperty(m){return this.paintProperties.get(m)}getUnevaluatedLayoutProperties(){return this.unevaluatedLayout}getUnevaluatedLayoutProperty(m){return this.unevaluatedLayout._values[m]}getUnevaluatedPaintProperty(m){return this.unevaluatedPaint._values[m]}recalculate(m,x,k){this.unevaluatedLayout&&(this.layoutProperties=this.unevaluatedLayout.possiblyEvaluate(m,void 0,x,k)),this.unevaluatedPaint&&(this.paintProperties=this.unevaluatedPaint.possiblyEvaluate(m,void 0,x,""))}serialize(){const m={};m.condition=this.condition.expression.serialize(),this.name&&(m.name=this.name);const x=this.unevaluatedLayout?this.unevaluatedLayout.serialize():{},k=this.unevaluatedPaint?this.unevaluatedPaint.serialize():{},T=Object.assign({},x,k);return Object.keys(T).length>0&&(m.properties=T),m}hasIconLayoutProperties(){const m=this.hasLayoutProperty("icon-image"),x=this.hasLayoutProperty("icon-size"),k=this.hasLayoutProperty("icon-offset"),T=this.hasLayoutProperty("icon-rotate");return m||x||k||T}hasTextLayoutProperties(){const m=this.hasLayoutProperty("text-size"),x=this.hasLayoutProperty("text-offset"),k=this.hasLayoutProperty("text-rotate");return m||x||k}hasIconPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(m=>!m.endsWith("-use-theme")).some(m=>(m.startsWith("icon-")||m==="symbol-z-offset")&&this.hasPaintProperty(m))}hasTextPaintProperties(){return!!this.unevaluatedPaint&&Object.keys(this.unevaluatedPaint._values).filter(m=>!m.endsWith("-use-theme")).some(m=>(m.startsWith("text-")||m==="symbol-z-offset")&&this.hasPaintProperty(m))}hasLayoutProperty(m){return this.unevaluatedLayout&&this.unevaluatedLayout._values[m].value!==void 0}hasPaintProperty(m){return this.unevaluatedPaint&&this.unevaluatedPaint._values[m].value!==void 0}}const ja="-transition",yc=new Set(["fill","line","background","hillshade","raster"]);class lo extends Lp{constructor(m,x,k,T,P,R){if(super(),this.id=m.id,this.fqid=vt(this.id,k),this.type=m.type,this.scope=k,this.lut=T,this.options=P,this.iconImageUseTheme=R,this.appearances=new Array,this.appearancesVersion=0,this._featureFilter={filter:()=>!0,needGeometry:!1,needFeature:!1},this._filterCompiled=!1,this.expressionDependencies={isIndoorDependent:!1,configDependencies:new Set},m.type!=="custom"){if(this.metadata=m.metadata,this.minzoom=m.minzoom,this.maxzoom=m.maxzoom,m.type&&m.type!=="background"&&m.type!=="sky"&&m.type!=="slot"){this.source=m.source,this.sourceLayer=m["source-layer"],this.filter=m.filter;const U=bx(this.filter,ps[`filter_${m.type}`]);U.result!=="error"&&(this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...U.value.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||U.value.isIndoorDependent)}if(m.slot&&(this.slot=m.slot),m.appearances&&this.setAppearances(m.appearances),x.layout&&(this._unevaluatedLayout=new XN(x.layout,this.scope,P,this.iconImageUseTheme),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._unevaluatedLayout.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._unevaluatedLayout.isIndoorDependent()),x.paint){this._transitionablePaint=new ZN(x.paint,this.scope,P);for(const U in m.paint)this.setPaintProperty(U,m.paint[U]);for(const U in m.layout)this.setLayoutProperty(U,m.layout[U]);this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...this._transitionablePaint.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||this._transitionablePaint.isIndoorDependent(),this._transitioningPaint=this._transitionablePaint.untransitioned(),this.paint=new Gd(x.paint)}}}onAdd(m){}onRemove(m){}isDraped(m){return!this.is3D(!0)&&yc.has(this.type)}getLayoutProperty(m){return m==="visibility"?this.visibility:this._unevaluatedLayout.getValue(m)}setLayoutProperty(m,x){if(this.type==="custom"&&m==="visibility")return void(this.visibility=x);const k=this._unevaluatedLayout;k._properties.properties[m]&&(k.setValue(m,x),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.isIndoorDependent(),m==="visibility"&&this.possiblyEvaluateVisibility())}setAppearances(m){this.appearances=[],m.forEach(x=>{this.appearances.push(new oo(x.condition,x.name,x.properties,this.scope,this.options,this.iconImageUseTheme))}),this.appearancesVersion++}possiblyEvaluateVisibility(){this._unevaluatedLayout._values.visibility&&(this.visibility=this._unevaluatedLayout._values.visibility.possiblyEvaluate({zoom:0}))}getPaintProperty(m){return m.endsWith(ja)?this._transitionablePaint.getTransition(m.slice(0,-11)):this._transitionablePaint.getValue(m)}isPaintProperty(m){return!!this._transitionablePaint._properties.properties[m]}setPaintProperty(m,x){const k=this._transitionablePaint,T=k._properties.properties;if(m.endsWith(ja)){const ue=m.slice(0,-11);return T[ue]&&k.setTransition(ue,x||void 0),!1}if(!T[m])return!1;const P=k._values[m],R=P.value.isDataDriven(),U=P.value;k.setValue(m,x),this.expressionDependencies.configDependencies=new Set([...this.expressionDependencies.configDependencies,...k.configDependencies]),this.expressionDependencies.isIndoorDependent=this.expressionDependencies.isIndoorDependent||k.isIndoorDependent(),this._handleSpecialPaintPropertyUpdate(m);const V=k._values[m].value,X=V.isDataDriven(),ie=m.endsWith("pattern")||m==="line-dasharray";return X||R||ie||this._handleOverridablePaintPropertyUpdate(m,U,V)}_handleSpecialPaintPropertyUpdate(m){}getProgramIds(){return null}getDefaultProgramParams(m,x,k){return null}_handleOverridablePaintPropertyUpdate(m,x,k){return!1}isHidden(m){return!!(this.minzoom&&m=this.maxzoom)||this.visibility==="none"}updateTransitions(m){this._transitioningPaint=this._transitionablePaint.transitioned(m,this._transitioningPaint)}hasTransition(){return this._transitioningPaint.hasTransition()}recalculate(m,x){this._unevaluatedLayout&&(this.layout=this._unevaluatedLayout.possiblyEvaluate(m,void 0,x,this.iconImageUseTheme)),this.paint=this._transitioningPaint.possiblyEvaluate(m,void 0,x)}serialize(){const m={id:this.id,type:this.type,slot:this.slot,source:this.source,"source-layer":this.sourceLayer,metadata:this.metadata,minzoom:this.minzoom,maxzoom:this.maxzoom,filter:this.filter,layout:this._unevaluatedLayout&&this._unevaluatedLayout.serialize(),paint:this._transitionablePaint&&this._transitionablePaint.serialize()};return this.appearances.length!==0&&(m.appearances=this.appearances.map(x=>x.serialize())),ys(m,(x,k)=>!(x===void 0||k==="layout"&&!Object.keys(x).length||k==="paint"&&!Object.keys(x).length))}is3D(m){return!1}hasElevation(){return!1}isSky(){return!1}isTileClipped(){return!1}hasOffscreenPass(){return!1}hasShadowPass(){return!1}canCastShadows(){return!1}hasLightBeamPass(){return!1}cutoffRange(){return 0}tileCoverLift(){return 0}resize(){}_clear(){}isStateDependent(){for(const m in this.paint._values){const x=this.paint.get(m);if(x instanceof w1&&Bp(x.property.specification)&&(x.value.kind==="source"||x.value.kind==="composite")&&x.value.isStateDependent)return!0}for(const m of this.appearances)if(!$y(m.condition.expression))return!0;return!1}compileFilter(m){this._filterCompiled||(this._featureFilter=JN(this.filter,this.scope,m),this._filterCompiled=!0)}invalidateCompiledFilter(){this._filterCompiled=!1}dynamicFilter(){return this._featureFilter.dynamicFilter}dynamicFilterNeedsFeature(){return this._featureFilter.needFeature}dynamicFilterNeedsGeometry(){return this._featureFilter.needGeometry}getLayerRenderingStats(){return this._stats}resetLayerRenderingStats(m){this._stats&&(m.renderPass==="shadow"?this._stats.numRenderedVerticesInShadowPass=0:this._stats.numRenderedVerticesInTransparentPass=0)}getAppearances(){return this.appearances}queryRenderedFeatures(m,x,k){return{}}queryRadius(m){}queryIntersectsFeature(m,x,k,T,P,R,U,V,X,ie){}}const xh={Int8:Int8Array,Uint8:Uint8Array,Int16:Int16Array,Uint16:Uint16Array,Int32:Int32Array,Uint32:Uint32Array,Float32:Float32Array};class Hp{constructor(m,x){this._structArray=m,this._pos1=x*this.size,this._pos2=this._pos1/2,this._pos4=this._pos1/4,this._pos8=this._pos1/8}}const qn=new ArrayBuffer(0);class Ks{constructor(){this._reallocCount=0,this.capacity=0,this.length=0}static serialize(m,x){return m._trim(),x&&m.arrayBuffer&&x.add(m.arrayBuffer),{length:m.length,arrayBuffer:m.arrayBuffer}}static deserialize(m){const x=Object.create(this.prototype);return x.arrayBuffer=m.arrayBuffer,x.length=m.length,m.arrayBuffer?x.capacity=m.arrayBuffer.byteLength/x.bytesPerElement:(x.capacity=0,x.arrayBuffer=qn),x._refreshViews(),x}_trim(){this.length!==this.capacity&&(this.capacity=this.length,this.arrayBuffer=this.arrayBuffer.slice(0,this.length*this.bytesPerElement),this._refreshViews())}clear(){this.length=0}resize(m){this.reserve(m),this.length=m}reserve(m){if(m>this.capacity){this._reallocCount++,this.capacity=Math.max(m,Math.floor(5*this.capacity),128),this.arrayBuffer=new ArrayBuffer(this.capacity*this.bytesPerElement);const x=this.uint8;this._refreshViews(),x&&this.uint8.set(x)}}reserveForAdditional(m){this.reserve(this.length+m)}_refreshViews(){throw new Error("StructArray#_refreshViews() must be implemented by each concrete StructArray layout")}emplace(...m){throw new Error("StructArray#emplace() must be implemented by each concrete StructArray layout")}emplaceBack(...m){throw new Error("StructArray#emplaceBack() must be implemented by each concrete StructArray layout")}destroy(){this.int8=this.uint8=this.int16=this.uint16=this.int32=this.uint32=this.float32=null,this.arrayBuffer=null}}function ln(b,m=1){let x=0,k=0;return{members:b.map(T=>{const P=xh[T.type].BYTES_PER_ELEMENT,R=x=Ma(x,Math.max(m,P)),U=T.components||1;return k=Math.max(k,P),x+=P*U,{name:T.name,type:T.type,components:U,offset:R}}),size:Ma(x,Math.max(k,m)),alignment:m}}function Ma(b,m){return Math.ceil(b/m)*m}class qa extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const T=2*m;return this.int16[T+0]=x,this.int16[T+1]=k,m}}qa.prototype.bytesPerElement=4,Kn(qa,"StructArrayLayout2i4");class Di extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k){const T=this.length;return this.resize(T+1),this.emplace(T,m,x,k)}emplace(m,x,k,T){const P=3*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.int16[P+2]=T,m}}Di.prototype.bytesPerElement=6,Kn(Di,"StructArrayLayout3i6");class ni extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,T){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,T)}emplace(m,x,k,T,P){const R=4*m;return this.int16[R+0]=x,this.int16[R+1]=k,this.uint16[R+2]=T,this.uint16[R+3]=P,m}}ni.prototype.bytesPerElement=8,Kn(ni,"StructArrayLayout2i2ui8");class no extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.float32[1*m+0]=x,m}}no.prototype.bytesPerElement=4,Kn(no,"StructArrayLayout1f4");class Wd extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k){const T=this.length;return this.resize(T+1),this.emplace(T,m,x,k)}emplace(m,x,k,T){const P=4*m,R=2*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.float32[R+1]=T,m}}Wd.prototype.bytesPerElement=8,Kn(Wd,"StructArrayLayout2i1f8");class nl extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k){const T=this.length;return this.resize(T+1),this.emplace(T,m,x,k)}emplace(m,x,k,T){const P=4*m;return this.int16[P+0]=x,this.int16[P+1]=k,this.int16[P+2]=T,m}}nl.prototype.bytesPerElement=8,Kn(nl,"StructArrayLayout3i8");class xg extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,T){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,T)}emplace(m,x,k,T,P){const R=4*m;return this.int16[R+0]=x,this.int16[R+1]=k,this.int16[R+2]=T,this.int16[R+3]=P,m}}xg.prototype.bytesPerElement=8,Kn(xg,"StructArrayLayout4i8");class AC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P){const R=this.length;return this.resize(R+1),this.emplace(R,m,x,k,T,P)}emplace(m,x,k,T,P,R){const U=5*m;return this.int16[U+0]=x,this.int16[U+1]=k,this.int16[U+2]=T,this.int16[U+3]=P,this.int16[U+4]=R,m}}AC.prototype.bytesPerElement=10,Kn(AC,"StructArrayLayout5i10");class MC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U){const V=this.length;return this.resize(V+1),this.emplace(V,m,x,k,T,P,R,U)}emplace(m,x,k,T,P,R,U,V){const X=6*m,ie=12*m,ue=3*m;return this.int16[X+0]=x,this.int16[X+1]=k,this.uint8[ie+4]=T,this.uint8[ie+5]=P,this.uint8[ie+6]=R,this.uint8[ie+7]=U,this.float32[ue+2]=V,m}}MC.prototype.bytesPerElement=12,Kn(MC,"StructArrayLayout2i4ub1f12");class gg extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k){const T=this.length;return this.resize(T+1),this.emplace(T,m,x,k)}emplace(m,x,k,T){const P=3*m;return this.float32[P+0]=x,this.float32[P+1]=k,this.float32[P+2]=T,m}}gg.prototype.bytesPerElement=12,Kn(gg,"StructArrayLayout3f12");class Yy extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P){const R=this.length;return this.resize(R+1),this.emplace(R,m,x,k,T,P)}emplace(m,x,k,T,P,R){const U=6*m,V=3*m;return this.uint16[U+0]=x,this.uint16[U+1]=k,this.uint16[U+2]=T,this.uint16[U+3]=P,this.float32[V+2]=R,m}}Yy.prototype.bytesPerElement=12,Kn(Yy,"StructArrayLayout4ui1f12");class sk extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,T){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,T)}emplace(m,x,k,T,P){const R=4*m;return this.uint16[R+0]=x,this.uint16[R+1]=k,this.uint16[R+2]=T,this.uint16[R+3]=P,m}}sk.prototype.bytesPerElement=8,Kn(sk,"StructArrayLayout4ui8");class N6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,T,P,R)}emplace(m,x,k,T,P,R,U){const V=6*m;return this.int16[V+0]=x,this.int16[V+1]=k,this.int16[V+2]=T,this.int16[V+3]=P,this.int16[V+4]=R,this.int16[V+5]=U,m}}N6.prototype.bytesPerElement=12,Kn(N6,"StructArrayLayout6i12");class DR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U,V,X,ie,ue,pe){const be=this.length;return this.resize(be+1),this.emplace(be,m,x,k,T,P,R,U,V,X,ie,ue,pe)}emplace(m,x,k,T,P,R,U,V,X,ie,ue,pe,be){const Se=12*m;return this.int16[Se+0]=x,this.int16[Se+1]=k,this.int16[Se+2]=T,this.int16[Se+3]=P,this.uint16[Se+4]=R,this.uint16[Se+5]=U,this.uint16[Se+6]=V,this.uint16[Se+7]=X,this.int16[Se+8]=ie,this.int16[Se+9]=ue,this.int16[Se+10]=pe,this.int16[Se+11]=be,m}}DR.prototype.bytesPerElement=24,Kn(DR,"StructArrayLayout4i4ui4i24");class RR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,T,P,R)}emplace(m,x,k,T,P,R,U){const V=10*m,X=5*m;return this.int16[V+0]=x,this.int16[V+1]=k,this.int16[V+2]=T,this.float32[X+2]=P,this.float32[X+3]=R,this.float32[X+4]=U,m}}RR.prototype.bytesPerElement=20,Kn(RR,"StructArrayLayout3i3f20");class N1 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,T)}emplace(m,x,k,T,P){const R=4*m;return this.float32[R+0]=x,this.float32[R+1]=k,this.float32[R+2]=T,this.float32[R+3]=P,m}}N1.prototype.bytesPerElement=16,Kn(N1,"StructArrayLayout4f16");class IC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint32[1*m+0]=x,m}}IC.prototype.bytesPerElement=4,Kn(IC,"StructArrayLayout1ul4");class yg extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const T=2*m;return this.uint16[T+0]=x,this.uint16[T+1]=k,m}}yg.prototype.bytesPerElement=4,Kn(yg,"StructArrayLayout2ui4");class k6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U,V,X,ie,ue,pe,be){const Se=this.length;return this.resize(Se+1),this.emplace(Se,m,x,k,T,P,R,U,V,X,ie,ue,pe,be)}emplace(m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se){const Le=20*m,ze=10*m;return this.int16[Le+0]=x,this.int16[Le+1]=k,this.int16[Le+2]=T,this.int16[Le+3]=P,this.int16[Le+4]=R,this.float32[ze+3]=U,this.float32[ze+4]=V,this.float32[ze+5]=X,this.float32[ze+6]=ie,this.int16[Le+14]=ue,this.uint32[ze+8]=pe,this.uint16[Le+18]=be,this.uint16[Le+19]=Se,m}}k6.prototype.bytesPerElement=40,Kn(k6,"StructArrayLayout5i4f1i1ul2ui40");class PC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U){const V=this.length;return this.resize(V+1),this.emplace(V,m,x,k,T,P,R,U)}emplace(m,x,k,T,P,R,U,V){const X=8*m;return this.int16[X+0]=x,this.int16[X+1]=k,this.int16[X+2]=T,this.int16[X+4]=P,this.int16[X+5]=R,this.int16[X+6]=U,this.int16[X+7]=V,m}}PC.prototype.bytesPerElement=16,Kn(PC,"StructArrayLayout3i2i2i16");class OR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P){const R=this.length;return this.resize(R+1),this.emplace(R,m,x,k,T,P)}emplace(m,x,k,T,P,R){const U=4*m,V=8*m;return this.float32[U+0]=x,this.float32[U+1]=k,this.float32[U+2]=T,this.int16[V+6]=P,this.int16[V+7]=R,m}}OR.prototype.bytesPerElement=16,Kn(OR,"StructArrayLayout2f1f2i16");class LC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,T,P,R)}emplace(m,x,k,T,P,R,U){const V=20*m,X=5*m;return this.uint8[V+0]=x,this.uint8[V+1]=k,this.float32[X+1]=T,this.float32[X+2]=P,this.float32[X+3]=R,this.float32[X+4]=U,m}}LC.prototype.bytesPerElement=20,Kn(LC,"StructArrayLayout2ub4f20");class tc extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k){const T=this.length;return this.resize(T+1),this.emplace(T,m,x,k)}emplace(m,x,k,T){const P=3*m;return this.uint16[P+0]=x,this.uint16[P+1]=k,this.uint16[P+2]=T,m}}tc.prototype.bytesPerElement=6,Kn(tc,"StructArrayLayout3ui6");class S6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct,nt,ft,wt){const Nt=this.length;return this.resize(Nt+1),this.emplace(Nt,m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct,nt,ft,wt)}emplace(m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct,nt,ft,wt,Nt){const Wt=30*m,Ft=15*m,Gt=60*m;return this.int16[Wt+0]=x,this.int16[Wt+1]=k,this.int16[Wt+2]=T,this.float32[Ft+2]=P,this.float32[Ft+3]=R,this.uint16[Wt+8]=U,this.uint16[Wt+9]=V,this.uint32[Ft+5]=X,this.uint32[Ft+6]=ie,this.uint32[Ft+7]=ue,this.uint16[Wt+16]=pe,this.uint16[Wt+17]=be,this.uint16[Wt+18]=Se,this.float32[Ft+10]=Le,this.float32[Ft+11]=ze,this.uint8[Gt+48]=We,this.uint8[Gt+49]=ct,this.uint8[Gt+50]=nt,this.uint32[Ft+13]=ft,this.int16[Wt+28]=wt,this.uint8[Gt+58]=Nt,m}}S6.prototype.bytesPerElement=60,Kn(S6,"StructArrayLayout3i2f2ui3ul3ui2f3ub1ul1i1ub60");class FR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct,nt,ft,wt,Nt,Wt,Ft,Gt,Ut,qt,zs,qs,Xs,sn,Js,fn){const Os=this.length;return this.resize(Os+1),this.emplace(Os,m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct,nt,ft,wt,Nt,Wt,Ft,Gt,Ut,qt,zs,qs,Xs,sn,Js,fn)}emplace(m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct,nt,ft,wt,Nt,Wt,Ft,Gt,Ut,qt,zs,qs,Xs,sn,Js,fn,Os){const en=20*m,on=40*m,gn=80*m;return this.float32[en+0]=x,this.float32[en+1]=k,this.int16[on+4]=T,this.int16[on+5]=P,this.int16[on+6]=R,this.int16[on+7]=U,this.int16[on+8]=V,this.int16[on+9]=X,this.int16[on+10]=ie,this.int16[on+11]=ue,this.int16[on+12]=pe,this.uint16[on+13]=be,this.uint16[on+14]=Se,this.uint16[on+15]=Le,this.uint16[on+16]=ze,this.uint16[on+17]=We,this.uint16[on+18]=ct,this.uint16[on+19]=nt,this.uint16[on+20]=ft,this.uint16[on+21]=wt,this.uint16[on+22]=Nt,this.uint16[on+23]=Wt,this.uint16[on+24]=Ft,this.uint16[on+25]=Gt,this.uint16[on+26]=Ut,this.uint16[on+27]=qt,this.uint32[en+14]=zs,this.float32[en+15]=qs,this.float32[en+16]=Xs,this.float32[en+17]=sn,this.float32[en+18]=Js,this.uint8[gn+76]=fn,this.uint16[on+39]=Os,m}}FR.prototype.bytesPerElement=80,Kn(FR,"StructArrayLayout2f9i15ui1ul4f1ub1ui80");class C6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R){const U=this.length;return this.resize(U+1),this.emplace(U,m,x,k,T,P,R)}emplace(m,x,k,T,P,R,U){const V=6*m;return this.float32[V+0]=x,this.float32[V+1]=k,this.float32[V+2]=T,this.float32[V+3]=P,this.float32[V+4]=R,this.float32[V+5]=U,m}}C6.prototype.bytesPerElement=24,Kn(C6,"StructArrayLayout6f24");class Bj extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P){const R=this.length;return this.resize(R+1),this.emplace(R,m,x,k,T,P)}emplace(m,x,k,T,P,R){const U=5*m;return this.float32[U+0]=x,this.float32[U+1]=k,this.float32[U+2]=T,this.float32[U+3]=P,this.float32[U+4]=R,m}}Bj.prototype.bytesPerElement=20,Kn(Bj,"StructArrayLayout5f20");class DC extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U){const V=this.length;return this.resize(V+1),this.emplace(V,m,x,k,T,P,R,U)}emplace(m,x,k,T,P,R,U,V){const X=7*m;return this.float32[X+0]=x,this.float32[X+1]=k,this.float32[X+2]=T,this.float32[X+3]=P,this.float32[X+4]=R,this.float32[X+5]=U,this.float32[X+6]=V,m}}DC.prototype.bytesPerElement=28,Kn(DC,"StructArrayLayout7f28");class zR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U,V,X,ie,ue){const pe=this.length;return this.resize(pe+1),this.emplace(pe,m,x,k,T,P,R,U,V,X,ie,ue)}emplace(m,x,k,T,P,R,U,V,X,ie,ue,pe){const be=11*m;return this.float32[be+0]=x,this.float32[be+1]=k,this.float32[be+2]=T,this.float32[be+3]=P,this.float32[be+4]=R,this.float32[be+5]=U,this.float32[be+6]=V,this.float32[be+7]=X,this.float32[be+8]=ie,this.float32[be+9]=ue,this.float32[be+10]=pe,m}}zR.prototype.bytesPerElement=44,Kn(zR,"StructArrayLayout11f44");class BR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U,V,X){const ie=this.length;return this.resize(ie+1),this.emplace(ie,m,x,k,T,P,R,U,V,X)}emplace(m,x,k,T,P,R,U,V,X,ie){const ue=9*m;return this.float32[ue+0]=x,this.float32[ue+1]=k,this.float32[ue+2]=T,this.float32[ue+3]=P,this.float32[ue+4]=R,this.float32[ue+5]=U,this.float32[ue+6]=V,this.float32[ue+7]=X,this.float32[ue+8]=ie,m}}BR.prototype.bytesPerElement=36,Kn(BR,"StructArrayLayout9f36");class $j extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x){const k=this.length;return this.resize(k+1),this.emplace(k,m,x)}emplace(m,x,k){const T=2*m;return this.float32[T+0]=x,this.float32[T+1]=k,m}}$j.prototype.bytesPerElement=8,Kn($j,"StructArrayLayout2f8");class $R extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint32=new Uint32Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m,x,k,T){const P=this.length;return this.resize(P+1),this.emplace(P,m,x,k,T)}emplace(m,x,k,T,P){const R=6*m;return this.uint32[3*m+0]=x,this.uint16[R+2]=k,this.uint16[R+3]=T,this.uint16[R+4]=P,m}}$R.prototype.bytesPerElement=12,Kn($R,"StructArrayLayout1ul3ui12");class Uj extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint16[1*m+0]=x,m}}Uj.prototype.bytesPerElement=2,Kn(Uj,"StructArrayLayout1ui2");class UR extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze){const We=this.length;return this.resize(We+1),this.emplace(We,m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze)}emplace(m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We){const ct=16*m;return this.float32[ct+0]=x,this.float32[ct+1]=k,this.float32[ct+2]=T,this.float32[ct+3]=P,this.float32[ct+4]=R,this.float32[ct+5]=U,this.float32[ct+6]=V,this.float32[ct+7]=X,this.float32[ct+8]=ie,this.float32[ct+9]=ue,this.float32[ct+10]=pe,this.float32[ct+11]=be,this.float32[ct+12]=Se,this.float32[ct+13]=Le,this.float32[ct+14]=ze,this.float32[ct+15]=We,m}}UR.prototype.bytesPerElement=64,Kn(UR,"StructArrayLayout16f64");class T6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.uint16=new Uint16Array(this.arrayBuffer),this.float32=new Float32Array(this.arrayBuffer)}emplaceBack(m,x,k,T,P,R,U){const V=this.length;return this.resize(V+1),this.emplace(V,m,x,k,T,P,R,U)}emplace(m,x,k,T,P,R,U,V){const X=10*m,ie=5*m;return this.uint16[X+0]=x,this.uint16[X+1]=k,this.uint16[X+2]=T,this.uint16[X+3]=P,this.float32[ie+2]=R,this.float32[ie+3]=U,this.float32[ie+4]=V,m}}T6.prototype.bytesPerElement=20,Kn(T6,"StructArrayLayout4ui3f20");class E6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer),this.int16=new Int16Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.int16[1*m+0]=x,m}}E6.prototype.bytesPerElement=2,Kn(E6,"StructArrayLayout1i2");class A6 extends Ks{_refreshViews(){this.uint8=new Uint8Array(this.arrayBuffer)}emplaceBack(m){const x=this.length;return this.resize(x+1),this.emplace(x,m)}emplace(m,x){return this.uint8[1*m+0]=x,m}}A6.prototype.bytesPerElement=1,Kn(A6,"StructArrayLayout1ub1");class WU extends Hp{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]}}WU.prototype.size=40;class qR extends k6{get(m){return new WU(this,m)}}Kn(qR,"CollisionBoxArray");class KU extends Hp{get projectedAnchorX(){return this._structArray.int16[this._pos2+0]}get projectedAnchorY(){return this._structArray.int16[this._pos2+1]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+2]}get tileAnchorX(){return this._structArray.float32[this._pos4+2]}get tileAnchorY(){return this._structArray.float32[this._pos4+3]}get glyphStartIndex(){return this._structArray.uint16[this._pos2+8]}get numGlyphs(){return this._structArray.uint16[this._pos2+9]}get vertexStartIndex(){return this._structArray.uint32[this._pos4+5]}get lineStartIndex(){return this._structArray.uint32[this._pos4+6]}get lineLength(){return this._structArray.uint32[this._pos4+7]}get segment(){return this._structArray.uint16[this._pos2+16]}get lowerSize(){return this._structArray.uint16[this._pos2+17]}get upperSize(){return this._structArray.uint16[this._pos2+18]}get lineOffsetX(){return this._structArray.float32[this._pos4+10]}get lineOffsetY(){return this._structArray.float32[this._pos4+11]}get writingMode(){return this._structArray.uint8[this._pos1+48]}get placedOrientation(){return this._structArray.uint8[this._pos1+49]}set placedOrientation(m){this._structArray.uint8[this._pos1+49]=m}get hidden(){return this._structArray.uint8[this._pos1+50]}set hidden(m){this._structArray.uint8[this._pos1+50]=m}get crossTileID(){return this._structArray.uint32[this._pos4+13]}set crossTileID(m){this._structArray.uint32[this._pos4+13]=m}get associatedIconIndex(){return this._structArray.int16[this._pos2+28]}get flipState(){return this._structArray.uint8[this._pos1+58]}set flipState(m){this._structArray.uint8[this._pos1+58]=m}}KU.prototype.size=60;class YU extends S6{get(m){return new KU(this,m)}}Kn(YU,"PlacedSymbolArray");class RC extends Hp{get tileAnchorX(){return this._structArray.float32[this._pos4+0]}get tileAnchorY(){return this._structArray.float32[this._pos4+1]}get projectedAnchorX(){return this._structArray.int16[this._pos2+4]}get projectedAnchorY(){return this._structArray.int16[this._pos2+5]}get projectedAnchorZ(){return this._structArray.int16[this._pos2+6]}get rightJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+7]}get centerJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+8]}get leftJustifiedTextSymbolIndex(){return this._structArray.int16[this._pos2+9]}get verticalPlacedTextSymbolIndex(){return this._structArray.int16[this._pos2+10]}get placedIconSymbolIndex(){return this._structArray.int16[this._pos2+11]}get verticalPlacedIconSymbolIndex(){return this._structArray.int16[this._pos2+12]}get key(){return this._structArray.uint16[this._pos2+13]}get textBoxStartIndex(){return this._structArray.uint16[this._pos2+14]}get textBoxEndIndex(){return this._structArray.uint16[this._pos2+15]}get verticalTextBoxStartIndex(){return this._structArray.uint16[this._pos2+16]}get verticalTextBoxEndIndex(){return this._structArray.uint16[this._pos2+17]}get iconBoxStartIndex(){return this._structArray.uint16[this._pos2+18]}get iconBoxEndIndex(){return this._structArray.uint16[this._pos2+19]}get verticalIconBoxStartIndex(){return this._structArray.uint16[this._pos2+20]}get verticalIconBoxEndIndex(){return this._structArray.uint16[this._pos2+21]}get featureIndex(){return this._structArray.uint16[this._pos2+22]}get numHorizontalGlyphVertices(){return this._structArray.uint16[this._pos2+23]}get numVerticalGlyphVertices(){return this._structArray.uint16[this._pos2+24]}get numIconVertices(){return this._structArray.uint16[this._pos2+25]}get numVerticalIconVertices(){return this._structArray.uint16[this._pos2+26]}get useRuntimeCollisionCircles(){return this._structArray.uint16[this._pos2+27]}get crossTileID(){return this._structArray.uint32[this._pos4+14]}set crossTileID(m){this._structArray.uint32[this._pos4+14]=m}get textOffset0(){return this._structArray.float32[this._pos4+15]}get textOffset1(){return this._structArray.float32[this._pos4+16]}get collisionCircleDiameter(){return this._structArray.float32[this._pos4+17]}get zOffset(){return this._structArray.float32[this._pos4+18]}set zOffset(m){this._structArray.float32[this._pos4+18]=m}get hasIconTextFit(){return this._structArray.uint8[this._pos1+76]}get elevationFeatureIndex(){return this._structArray.uint16[this._pos2+39]}}RC.prototype.size=80;class ZU extends FR{get(m){return new RC(this,m)}}Kn(ZU,"SymbolInstanceArray");class QU extends no{getoffsetX(m){return this.float32[1*m+0]}}Kn(QU,"GlyphOffsetArray");class OC extends qa{getx(m){return this.int16[2*m+0]}gety(m){return this.int16[2*m+1]}}Kn(OC,"SymbolLineVertexArray");class XU extends Hp{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]}}XU.prototype.size=12;class VR extends $R{get(m){return new XU(this,m)}}Kn(VR,"FeatureIndexArray");class JU extends yg{geta_centroid_pos0(m){return this.uint16[2*m+0]}geta_centroid_pos1(m){return this.uint16[2*m+1]}}Kn(JU,"FillExtrusionCentroidArray");class HR extends Hp{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]}}HR.prototype.size=6;class GR extends Di{get(m){return new HR(this,m)}}Kn(GR,"FillExtrusionWallArray");const eq=ln([{name:"a_pos",components:2,type:"Int16"}],4),rbe=ln([{name:"a_circle_z_offset",components:1,type:"Float32"}],4),abe=ln([{name:"a_pos_3",components:3,type:"Int16"},{name:"a_pos_normal_3",components:3,type:"Int16"}]);class Po{constructor(m=[]){this.segments=m}_prepareSegment(m,x,k,T,P){let R=this.segments[this.segments.length-1];return m>Po.MAX_VERTEX_ARRAY_LENGTH&&Yn(`Max vertices per segment is ${Po.MAX_VERTEX_ARRAY_LENGTH}: bucket requested ${m}`),(!R||R.vertexLength+m>Po.MAX_VERTEX_ARRAY_LENGTH||R.sortKey!==T||P!==void 0&&R&&R.batchIndex!==void 0&&R.batchIndex!==P)&&(R={vertexOffset:x,primitiveOffset:k,vertexLength:0,primitiveLength:0},T!==void 0&&(R.sortKey=T),P!==void 0&&(R.batchIndex=P),this.segments.push(R)),R}prepareSegment(m,x,k,T,P){return this._prepareSegment(m,x.length,k.length,T,P)}get(){return this.segments}destroy(){for(const m of this.segments)for(const x in m.vaos)m.vaos[x].destroy()}static simpleSegment(m,x,k,T){return new Po([{vertexOffset:m,primitiveOffset:x,vertexLength:k,primitiveLength:T,vaos:{},sortKey:0}])}}function M6(b,m){return 256*(b=Qe(Math.floor(b),0,255))+Qe(Math.floor(m),0,255)}Po.MAX_VERTEX_ARRAY_LENGTH=Math.pow(2,16)-1,Kn(Po,"SegmentVector");const ibe=ln([{name:"a_pattern",components:4,type:"Uint16"},{name:"a_pixel_ratio",components:1,type:"Float32"}]),obe=ln([{name:"a_pattern_b",components:4,type:"Uint16"}]),lbe=ln([{name:"a_dash",components:4,type:"Uint16"}]);class FC{constructor(){this.ids=[],this.uniqueIds=[],this.positions=[],this.indexed=!1}add(m,x,k,T){this.ids.push(WR(m)),this.positions.push(x,k,T)}eachPosition(m,x){const k=WR(m);let T=0,P=this.ids.length-1;for(;T>1;this.ids[R]>=k?P=R:T=R+1}for(;this.ids[T]===k;)x(this.positions[3*T],this.positions[3*T+1],this.positions[3*T+2]),T++}static serialize(m,x){const k=new Float64Array(m.ids),T=new Uint32Array(m.positions);return zC(k,T,0,k.length-1),x&&(x.add(k.buffer),x.add(T.buffer)),{ids:k,positions:T}}static deserialize(m){const x=new FC;let k;x.ids=m.ids,x.positions=m.positions;for(const T of x.ids)T!==k&&x.uniqueIds.push(T),k=T;return x.indexed=!0,x}}function WR(b){const m=+b;return Number.isSafeInteger(m)?m:Nd(String(b))}function zC(b,m,x,k){for(;x>1];let P=x-1,R=k+1;for(;;){do P++;while(b[P]T);if(P>=R)break;Nx(b,P,R),Nx(m,3*P,3*R),Nx(m,3*P+1,3*R+1),Nx(m,3*P+2,3*R+2)}R-x`u_${P}`),this.type=k,this.context=T}setUniform(m,x,k,T,P){const R=T.constantOr(this.value);x.set(m,P,R instanceof Gn?R.toPremultipliedRenderColor(this.lutExpression&&this.lutExpression.kind==="constant"&&this.lutExpression.value==="none"?null:this.context.lut):R)}getBinding(m,x){return this.type==="color"?new dbe(m):new cd(m)}}class de{constructor(m,x){this.uniformNames=x.map(k=>`u_${k}`),this.pattern=null,this.patternTransition=null,this.pixelRatio=1}setConstantPatternPositions(m,x){this.pixelRatio=m.pixelRatio||1,this.pattern=m.tl.concat(m.br),this.patternTransition=x?x.tl.concat(x.br):this.pattern}setUniform(m,x,k,T,P){let R=null;P!=="u_pattern"&&P!=="u_dash"||(R=this.pattern),P==="u_pattern_b"&&(R=this.patternTransition),P==="u_pixel_ratio"&&(R=this.pixelRatio),R&&x.set(m,P,R)}getBinding(m,x){return x==="u_pattern"||x==="u_pattern_b"||x==="u_dash"?new cbe(m):new cd(m)}}class xe{constructor(m,x,k,T){this.expression=m,this.type=k,this.maxValue=0,this.paintVertexAttributes=x.map(P=>({name:`a_${P}`,type:"Float32",components:k==="color"?2:1,offset:0})),this.paintVertexArray=new T}populatePaintArray(m,x,k,T,P,R,U,V){const X=this.paintVertexArray.length,ie=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate(new Aa(0,{brightness:R,worldview:V}),x,{},P,T,U):this.expression.kind==="constant"&&this.expression.value,ue=K(this.lutExpression,x,{},T,P,R,U,V);this.paintVertexArray.resize(m),this._setPaintValue(X,m,ie,ue?null:this.context.lut)}updatePaintArray(m,x,k,T,P,R,U,V){const X=this.expression.kind==="composite"||this.expression.kind==="source"?this.expression.evaluate({zoom:0,brightness:U,worldview:V},k,T,void 0,P):this.expression.kind==="constant"&&this.expression.value,ie=K(this.lutExpression,k,T,P,void 0,U,void 0,V);this._setPaintValue(m,x,X,ie?null:this.context.lut)}_setPaintValue(m,x,k,T){if(this.type==="color"){const P=G(k.toPremultipliedRenderColor(T));for(let R=m;R`u_${U}_t`),this.type=k,this.useIntegerZoom=T,this.context=P,this.maxValue=0,this.paintVertexAttributes=x.map(U=>({name:`a_${U}`,type:"Float32",components:k==="color"?4:2,offset:0})),this.paintVertexArray=new R}populatePaintArray(m,x,k,T,P,R,U,V){const X=this.expression.evaluate(new Aa(this.context.zoom,{brightness:R,worldview:V}),x,{},P,T,U),ie=this.expression.evaluate(new Aa(this.context.zoom+1,{brightness:R,worldview:V}),x,{},P,T,U),ue=K(this.lutExpression,x,{},T,P,R,U,V),pe=this.paintVertexArray.length;this.paintVertexArray.resize(m),this._setPaintValue(pe,m,X,ie,ue?null:this.context.lut)}updatePaintArray(m,x,k,T,P,R,U,V){const X=this.expression.evaluate({zoom:this.context.zoom,brightness:U,worldview:V},k,T,void 0,P),ie=this.expression.evaluate({zoom:this.context.zoom+1,brightness:U,worldview:V},k,T,void 0,P),ue=K(this.lutExpression,k,T,P,void 0,U,void 0,V);this._setPaintValue(m,x,X,ie,ue?null:this.context.lut)}_setPaintValue(m,x,k,T,P){if(this.type==="color"){const R=G(k.toPremultipliedRenderColor(P)),U=G(T.toPremultipliedRenderColor(P));for(let V=m;V!0){this.binders={},this._buffers=[],this.context=x;const T=[],P=m;for(const R in m.paint._values){const U=P.paint.get(R);if(R.endsWith("-use-theme")||!k(R)||!(U instanceof w1&&Bp(U.property.specification)))continue;const V=Xe(R,m.type),X=U.value,ie=U.property.specification.type,ue=!!U.property.useIntegerZoom,pe=R==="line-dasharray"||R.endsWith("pattern"),be=P.paint.get(`${R}-use-theme`),Se=R==="line-dasharray"&&P.layout.get("line-cap").value.kind!=="constant"||be&&be.value.kind!=="constant";if(X.kind!=="constant"||Se)if(X.kind==="source"||Se||pe){const Le=kt(R,ie,"source");this.binders[R]=pe?new Oe(X,V,ie,Le,m.id):new xe(X,V,ie,Le),T.push(`/a_${R}`)}else{const Le=kt(R,ie,"composite");this.binders[R]=new _e(X,V,ie,ue,x,Le),T.push(`/z_${R}`)}else this.binders[R]=pe?new de(X.value,V):new te(X.value,V,ie,x),T.push(`/u_${R}`);be&&(this.binders[R].lutExpression=be.value)}this.cacheKey=T.sort().join("")}getMaxValue(m){const x=this.binders[m];return x instanceof xe||x instanceof _e?x.maxValue:0}populatePaintArrays(m,x,k,T,P,R,U,V){for(const X in this.binders){const ie=this.binders[X];ie.context=this.context,(ie instanceof xe||ie instanceof _e||ie instanceof Oe)&&ie.populatePaintArray(m,x,k,T,P,R,U,V)}}setConstantPatternPositions(m,x){for(const k in this.binders){const T=this.binders[k];T instanceof de&&T.setConstantPatternPositions(m,x)}}getPatternTransitionVertexBuffer(m){const x=this.binders[m];return x instanceof Oe?x.paintTransitionVertexBuffer:null}updatePaintArrays(m,x,k,T,P,R,U,V,X,ie){let ue=!1;const pe=Object.keys(m),be=pe.length!==0&&!V,Se=be?pe:x.uniqueIds;this.context.lut=P.lut;for(const Le in this.binders){const ze=this.binders[Le];if(ze.context=this.context,(ze instanceof xe||ze instanceof _e||ze instanceof Oe)&&ze.expression&&ze.expression.kind&&ze.expression.kind!=="constant"&&(ze.expression.isStateDependent===!0||ze.expression.isLightConstant===!1)){const We=P.paint.get(Le);ze.expression=We.value;for(const ct of Se){const nt=m[ct.toString()];x.eachPosition(ct,(ft,wt,Nt)=>{const Wt=T.feature(ft);ze.updatePaintArray(wt,Nt,Wt,nt,R,U,X,ie)})}if(!be)for(const ct of k.uniqueIds){const nt=m[ct.toString()];k.eachPosition(ct,(ft,wt,Nt)=>{const Wt=T.feature(ft);ze.updatePaintArray(wt,Nt,Wt,nt,R,U,X,ie)})}ue=!0}}return ue}defines(){const m=[];for(const x in this.binders){const k=this.binders[x];(k instanceof te||k instanceof de)&&m.push(...k.uniformNames.map(T=>`#define HAS_UNIFORM_${T}`))}return m}getPaintVertexBuffers(){return this._buffers}getUniforms(m){const x=[];for(const k in this.binders){const T=this.binders[k];if(T instanceof te||T instanceof de||T instanceof _e)for(const P of T.uniformNames)x.push({name:P,property:k,binding:T.getBinding(m,P)})}return x}setUniforms(m,x,k,T,P){for(const{name:R,property:U,binding:V}of k)this.binders[U].setUniform(m,V,P,T.get(U),R)}updatePaintBuffers(){this._buffers=[];for(const m in this.binders){const x=this.binders[m];(x instanceof xe||x instanceof _e||x instanceof Oe)&&x.paintVertexBuffer&&this._buffers.push(x.paintVertexBuffer),x instanceof Oe&&x.paintTransitionVertexBuffer&&this._buffers.push(x.paintTransitionVertexBuffer)}}upload(m){for(const x in this.binders){const k=this.binders[x];(k instanceof xe||k instanceof _e||k instanceof Oe)&&k.upload(m)}this.updatePaintBuffers()}destroy(){for(const m in this.binders){const x=this.binders[m];(x instanceof xe||x instanceof _e||x instanceof Oe)&&x.destroy()}}}class qe{constructor(m,x,k=()=>!0){this.programConfigurations={};for(const T of m)this.programConfigurations[T.id]=new De(T,x,k);this.needsUpload=!1,this._featureMap=new FC,this._featureMapWithoutIds=new FC,this._bufferOffset=0,this._idlessCounter=0}populatePaintArrays(m,x,k,T,P,R,U,V,X){for(const ie in this.programConfigurations)this.programConfigurations[ie].populatePaintArrays(m,x,T,P,R,U,V,X);x.id!==void 0?this._featureMap.add(x.id,k,this._bufferOffset,m):(this._featureMapWithoutIds.add(this._idlessCounter,k,this._bufferOffset,m),this._idlessCounter+=1),this._bufferOffset=m,this.needsUpload=!0}updatePaintArrays(m,x,k,T,P,R,U,V){for(const X of k)this.needsUpload=this.programConfigurations[X.id].updatePaintArrays(m,this._featureMap,this._featureMapWithoutIds,x,X,T,P,R,U||0,V)||this.needsUpload}get(m){return this.programConfigurations[m]}upload(m){if(this.needsUpload){for(const x in this.programConfigurations)this.programConfigurations[x].upload(m);this.needsUpload=!1}}destroy(){for(const m in this.programConfigurations)this.programConfigurations[m].destroy()}}const st={"text-opacity":["opacity"],"icon-opacity":["opacity"],"text-occlusion-opacity":["occlusion_opacity"],"icon-occlusion-opacity":["occlusion_opacity"],"text-color":["fill_color"],"icon-color":["fill_color"],"text-emissive-strength":["emissive_strength"],"icon-emissive-strength":["emissive_strength"],"text-halo-color":["halo_color"],"icon-halo-color":["halo_color"],"text-halo-blur":["halo_blur"],"icon-halo-blur":["halo_blur"],"text-halo-width":["halo_width"],"icon-halo-width":["halo_width"],"symbol-z-offset":["z_offset"],"line-gap-width":["gapwidth"],"line-pattern":["pattern","pixel_ratio","pattern_b"],"fill-pattern":["pattern","pixel_ratio","pattern_b"],"fill-extrusion-pattern":["pattern","pixel_ratio","pattern_b"],"line-dasharray":["dash"],"fill-bridge-guard-rail-color":["structure_color"],"fill-tunnel-structure-color":["structure_color"]};function Xe(b,m){return st[b]||[b.replace(`${m}-`,"").replace(/-/g,"_")]}const pt={"line-pattern":{source:Yy,composite:Yy},"fill-pattern":{source:Yy,composite:Yy},"fill-extrusion-pattern":{source:Yy,composite:Yy},"line-dasharray":{source:sk,composite:sk}},mt={color:{source:$j,composite:N1},number:{source:no,composite:$j}};function kt(b,m,x){const k=pt[b];return k&&k[x]||mt[m][x]}Kn(te,"ConstantBinder"),Kn(de,"PatternConstantBinder"),Kn(xe,"SourceExpressionBinder"),Kn(Oe,"PatternCompositeBinder"),Kn(_e,"CompositeExpressionBinder"),Kn(De,"ProgramConfiguration",{omit:["_buffers"]}),Kn(qe,"ProgramConfigurationSet");const Et=Bn/Math.PI/2,xt=64,es=[xt,32,16],Ot=-Et,Qt=Et;function At(b,m,x,k=Et){return x=Ts(x),[b*Math.sin(x)*k,-m*k,b*Math.cos(x)*k]}function Dt(b,m,x){return At(Math.cos(Ts(b)),Math.sin(Ts(b)),m,x)}const Ht=63710088e-1,gs=2*Math.PI*Ht;class ss{constructor(m,x){if(isNaN(m)||isNaN(x))throw new Error(`Invalid LngLat object: (${m}, ${x})`);if(this.lng=+m,this.lat=+x,this.lat>90||this.lat<-90)throw new Error("Invalid LngLat latitude value: must be between -90 and 90")}wrap(){return new ss(St(this.lng,-180,180),this.lat)}toArray(){return[this.lng,this.lat]}toString(){return`LngLat(${this.lng}, ${this.lat})`}distanceTo(m){const x=Math.PI/180,k=this.lat*x,T=m.lat*x,P=Math.sin(k)*Math.sin(T)+Math.cos(k)*Math.cos(T)*Math.cos((m.lng-this.lng)*x);return Ht*Math.acos(Math.min(P,1))}toBounds(m=0){const x=360*m/40075017,k=x/Math.cos(Math.PI/180*this.lat);return new Bs({lng:this.lng-k,lat:this.lat-x},{lng:this.lng+k,lat:this.lat+x})}toEcef(m){return Dt(this.lat,this.lng,Et+m*Et/Ht)}static convert(m){if(m instanceof ss)return m;if(Array.isArray(m)&&(m.length===2||m.length===3))return new ss(Number(m[0]),Number(m[1]));if(!Array.isArray(m)&&typeof m=="object"&&m!==null)return new ss(Number("lng"in m?m.lng:m.lon),Number(m.lat));throw new Error("`LngLatLike` argument must be specified as a LngLat instance, an object {lng: , lat: }, an object {lon: , lat: }, or an array of [, ]")}}class Bs{constructor(m,x){m&&(x?this.setSouthWest(m).setNorthEast(x):Array.isArray(m)&&m.length===4?this.setSouthWest([m[0],m[1]]).setNorthEast([m[2],m[3]]):this.setSouthWest(m[0]).setNorthEast(m[1]))}setNorthEast(m){return this._ne=m instanceof ss?new ss(m.lng,m.lat):ss.convert(m),this}setSouthWest(m){return this._sw=m instanceof ss?new ss(m.lng,m.lat):ss.convert(m),this}extend(m){const x=this._sw,k=this._ne;let T,P;if(m instanceof ss)T=m,P=m;else{if(!(m instanceof Bs))return Array.isArray(m)?m.length===4||m.every(Array.isArray)?this.extend(Bs.convert(m)):this.extend(ss.convert(m)):typeof m=="object"&&m!==null&&m.hasOwnProperty("lat")&&(m.hasOwnProperty("lon")||m.hasOwnProperty("lng"))?this.extend(ss.convert(m)):this;if(T=m._sw,P=m._ne,!T||!P)return this}return x||k?(x.lng=Math.min(T.lng,x.lng),x.lat=Math.min(T.lat,x.lat),k.lng=Math.max(P.lng,k.lng),k.lat=Math.max(P.lat,k.lat)):(this._sw=new ss(T.lng,T.lat),this._ne=new ss(P.lng,P.lat)),this}getCenter(){return new ss((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 ss(this.getWest(),this.getNorth())}getSouthEast(){return new ss(this.getEast(),this.getSouth())}getWest(){return this._sw.lng}getSouth(){return this._sw.lat}getEast(){return this._ne.lng}getNorth(){return this._ne.lat}toArray(){return[this._sw.toArray(),this._ne.toArray()]}toString(){return`LngLatBounds(${this._sw.toString()}, ${this._ne.toString()})`}isEmpty(){return!(this._sw&&this._ne)}contains(m){const{lng:x,lat:k}=ss.convert(m);let T=this._sw.lng<=x&&x<=this._ne.lng;return this._sw.lng>this._ne.lng&&(T=this._sw.lng>=x&&x>=this._ne.lng),this._sw.lat<=k&&k<=this._ne.lat&&T}static convert(m){if(m)return m instanceof Bs?m:new Bs(m)}}function Ps(b){return gs*Math.cos(b*Math.PI/180)}function rn(b){return(180+b)/360}function hn(b){return(180-180/Math.PI*Math.log(Math.tan(Math.PI/4+b*Math.PI/360)))/360}function Ns(b,m){return b/Ps(m)}function ds(b){return 360*b-180}function Fs(b){return 360/Math.PI*Math.atan(Math.exp((180-360*b)*Math.PI/180))-90}function Us(b,m){return b*Ps(Fs(m))}const Ys=85.051129;function Dn(b){return Math.cos(Ts(Qe(b,-85.051129,Ys)))}function kn(b,m){const x=Qe(m,0,25.5),k=Math.pow(2,x);return Dn(b)*gs/(512*k)}function Sn(b){return 1/Math.cos(b*Math.PI/180)}function cn(b,m=0){const x=Math.exp(Math.PI*(1-(b.y+m/Bn)/(1<=V?(Nr(b,m,x,X,ie,P,ue,U,V),Nr(b,X,ie,k,T,ue,R,U,V)):b.push(R)}function rr(b,m,x){let k=b[0],T=k.x,P=k.y;m(k);const R=[k];for(let U=1;Ub.x+1||kb.y+1)&&Yn("Geometry exceeds allowed extent, reduce your vector tile buffer size"),b}function Vr(b,m,x){const k=b.loadGeometry(),T=b.extent,P=Bn/T;if(m&&x&&x.projection.isReprojectedInTileSpace){const R=1<{const be=ds((m.x+pe.x/T)/R),Se=Fs((m.y+pe.y/T)/R),Le=ie.project(be,Se);pe.x=(Le.x*U-V)*T,pe.y=(Le.y*U-X)*T};for(let pe=0;pe=T||Se.y<0||Se.y>=T||(ue(Se),be.push(Se));k[pe]=be}}for(const R of k)for(const U of R)Va(U,P);return k}function Ha(b,m){return{type:b.type,id:b.id,properties:b.properties,geometry:m?Vr(b):[]}}class pa{constructor(m,x,k,T,P){this.properties={},this.extent=k,this.type=0,this.id=void 0,this._pbf=m,this._geometry=-1,this._keys=T,this._values=P,m.readFields(Ci,this,x)}loadGeometry(){const m=this._pbf;m.pos=this._geometry;const x=m.readVarint()+m.pos,k=[];let T,P=1,R=0,U=0,V=0;for(;m.pos>3}if(R--,P===1||P===2)U+=m.readSVarint(),V+=m.readSVarint(),P===1&&(T&&k.push(T),T=[]),T&&T.push(new Es(U,V));else{if(P!==7)throw new Error(`unknown command ${P}`);T&&T.push(T[0].clone())}}return T&&k.push(T),k}bbox(){const m=this._pbf;m.pos=this._geometry;const x=m.readVarint()+m.pos;let k=1,T=0,P=0,R=0,U=1/0,V=-1/0,X=1/0,ie=-1/0;for(;m.pos>3}if(T--,k===1||k===2)P+=m.readSVarint(),R+=m.readSVarint(),PV&&(V=P),Rie&&(ie=R);else if(k!==7)throw new Error(`unknown command ${k}`)}return[U,X,V,ie]}toGeoJSON(m,x,k){const T=this.extent*Math.pow(2,k),P=this.extent*m,R=this.extent*x,U=this.loadGeometry();function V(pe){return[360*(pe.x+P)/T-180,360/Math.PI*Math.atan(Math.exp((1-2*(pe.y+R)/T)*Math.PI))-90]}function X(pe){return pe.map(V)}let ie;if(this.type===1){const pe=[];for(const Se of U)pe.push(Se[0]);const be=X(pe);ie=pe.length===1?{type:"Point",coordinates:be[0]}:{type:"MultiPoint",coordinates:be}}else if(this.type===2){const pe=U.map(X);ie=pe.length===1?{type:"LineString",coordinates:pe[0]}:{type:"MultiLineString",coordinates:pe}}else{if(this.type!==3)throw new Error("unknown feature type");{const pe=function(Se){const Le=Se.length;if(Le<=1)return[Se];const ze=[];let We,ct;for(let nt=0;nt=this._features.length)throw new Error("feature index out of bounds");this._pbf.pos=this._features[m];const x=this._pbf.readVarint()+this._pbf.pos;return new pa(this._pbf,x,this.extent,this._keys,this._values)}}function Lo(b,m,x){b===15?m.version=x.readVarint():b===1?m.name=x.readString():b===5?m.extent=x.readVarint():b===2?m._features.push(x.pos):b===3?m._keys.push(x.readString()):b===4&&m._values.push(function(k){let T=null;const P=k.readVarint()+k.pos;for(;k.pos>3;T=R===1?k.readString():R===2?k.readFloat():R===3?k.readDouble():R===4?k.readVarint64():R===5?k.readVarint():R===6?k.readSVarint():R===7?k.readBoolean():null}if(T==null)throw new Error("unknown feature value");return T}(x))}class Fi{constructor(m,x){this.layers=m.readFields(Da,{},x)}}function Da(b,m,x){if(b===3){const k=new yl(x,x.readVarint()+x.pos);k.length&&(m[k.name]=k)}}const Ra="3d_elevation_id",Do="level";class Nl{constructor(){this._valid=!1}reset(m){return this.feature=m,this._valid=!0,this._geometry=m.loadGeometry(),this._geometry.length!==0&&this._geometry[0].length!==0||(this._valid=!1),this}geometry(m,x){return this._valid&&m(x(this._geometry)),this}require(m,x,k){return this.get(m,!0,x,k)}optional(m,x,k){return this.get(m,!1,x,k)}success(){return this._valid}get(m,x,k,T){const P=this.feature.properties.hasOwnProperty(m)?+this.feature.properties[m]:void 0;return this._valid&&P!==void 0&&!Number.isNaN(P)?k(T?T(P):P):x&&(this._valid=!1),this}}class zi{constructor(m,x){this.featureFunc=m,this.vertexFunc=x}parseFeature(m,x,k){return this.featureFunc(m,x,k)}parseVertex(m,x,k){return this.vertexFunc(m,x,k)}}const Na=new zi((b,m,x)=>b.reset(m).require(Ra,k=>{x.id=k}).optional("fixed_height_relative",k=>{x.constantHeight=k},vo.decodeRelativeHeight).geometry(k=>{x.bounds=k},Gb).success(),(b,m,x)=>b.reset(m).require(Ra,k=>{x.id=k}).require("elevation_idx",k=>{x.idx=k}).require("extent",k=>{x.extent=k}).require("height_relative",k=>{x.height=k},vo.decodeRelativeHeight).geometry(k=>{x.position=k},vo.getPoint).success()),cl=new zi((b,m,x)=>b.reset(m).require(Ra,k=>{x.id=k}).optional("fixed_height",k=>{x.constantHeight=k},vo.decodeMetricHeight).geometry(k=>{x.bounds=k},Gb).success(),(b,m,x)=>b.reset(m).require(Ra,k=>{x.id=k}).require("elevation_idx",k=>{x.idx=k}).require("extent",k=>{x.extent=k}).require("height",k=>{x.height=k},vo.decodeMetricHeight).geometry(k=>{x.position=k},vo.getPoint).success());class vo{static getPoint(m){return zt(m[0][0].x,m[0][0].y)}static decodeRelativeHeight(m){return 1e-4*m*5}static decodeMetricHeight(m){return 1e-4*m}static getVersionSchema(m){return m?m==="1.0.1"?cl:void 0:Na}static parse(m){const x=[],k=[],T=m.length,P=new Nl;for(let R=0;R=0);if(P===0)return 0;P!==m.length&&(x=!1)}return x?2:1}function dd(b,m){for(const x of b.projections){const k=Zc(m,b.points[0],x.axis);if(x.projection[1]k[1])return 0}return 1}function fu(b,m){let x=0;const k=[0,0,0,0];for(let T=0;T=0&&x++;return x}class Ff{constructor(m,x){this.points=m||new Array(8).fill([0,0,0]),this.planes=x||new Array(6).fill([0,0,0,0]),this.bounds=eo.fromPoints(this.points),this.projections=[],this.frustumEdges=[$e([],this.points[2],this.points[3]),$e([],this.points[0],this.points[3]),$e([],this.points[4],this.points[0]),$e([],this.points[5],this.points[1]),$e([],this.points[6],this.points[2]),$e([],this.points[7],this.points[3])];for(const k of this.frustumEdges){const T=[0,-k[2],k[1]],P=[k[2],0,-k[0]];this.projections.push({axis:T,projection:Zc(this.points,this.points[0],T)}),this.projections.push({axis:P,projection:Zc(this.points,this.points[0],P)})}}static fromInvProjectionMatrix(m,x,k,T){const P=Math.pow(2,k),R=[[-1,1,-1,1],[1,1,-1,1],[1,-1,-1,1],[-1,-1,-1,1],[-1,1,1,1],[1,1,1,1],[1,-1,1,1],[-1,-1,1,1]].map(X=>{const ie=ut([],X,m),ue=1/ie[3]/x*P;return(pe=ie)[0]=(be=ie)[0]*(Se=[ue,ue,T?1/ie[3]:ue,ue])[0],pe[1]=be[1]*Se[1],pe[2]=be[2]*Se[2],pe[3]=be[3]*Se[3],pe;var pe,be,Se}),U=[[0,1,2],[6,5,4],[0,3,7],[2,1,5],[3,2,6],[0,4,5]].map(X=>{const ie=Re([],Be([],$e([],R[X[0]],R[X[1]]),$e([],R[X[2]],R[X[1]]))),ue=-Ae(ie,R[X[1]]);return ie.concat(ue)}),V=[];for(let X=0;XX[1]||X[0]>V[1])return 0}return 1}containsPoint(m){for(const x of this.planes){const k=x[3];if(Ae([x[0],x[1],x[2]],m)+k<0)return!1}return!0}}class eo{static fromPoints(m){const x=[1/0,1/0,1/0],k=[-1/0,-1/0,-1/0];for(const T of m)le(x,x,T),ve(k,k,T);return new eo(x,k)}static fromTileIdAndHeight(m,x,k){const T=1<m.max[x]||m.min[x]>this.max[x])return!1;return!0}intersectsAabbXY(m){return!(this.min[0]>m.max[0]||m.min[0]>this.max[0]||this.min[1]>m.max[1]||m.min[1]>this.max[1])}encapsulate(m){for(let x=0;x<3;x++)this.min[x]=Math.min(this.min[x],m.min[x]),this.max[x]=Math.max(this.max[x],m.max[x])}encapsulatePoint(m){for(let x=0;x<3;x++)this.min[x]=Math.min(this.min[x],m[x]),this.max[x]=Math.max(this.max[x],m[x])}closestPoint(m){return[Math.max(Math.min(this.max[0],m[0]),this.min[0]),Math.max(Math.min(this.max[1],m[1]),this.min[1]),Math.max(Math.min(this.max[2],m[2]),this.min[2])]}}Kn(eo,"Aabb");class kx{constructor(m,x){this.feature=m,this.metersToTile=x,this.index=0}get(){const m=this.feature.vertices[this.index],x=this.feature.vertexProps[this.index].dir,k=x[1],T=-x[0],P=(m.extent+1)*this.metersToTile;return[new Es(Math.trunc(m.position[0]+k*P),Math.trunc(m.position[1]+T*P)),new Es(Math.trunc(m.position[0]-k*P),Math.trunc(m.position[1]-T*P))]}next(){this.index++}valid(){return this.index{return U.a0?ge(V,V,1/X):oe(V,0,0,1)}getSafeArea(){return this.safeArea}isTunnel(){return this.heightRange.max<=-5}getClosestEdge(m){if(this.edges.length===0)return;let x=0,k=Number.POSITIVE_INFINITY,T=0;const[P,R,U,V,X,ie,ue]=this._tmpVec2;As(ue,m.x,m.y);const pe=new vc(ue,null);for(let be=0;be0?tn(V,U)/ft:0,Nt=Qe(wt,0,1),Wt=Math.abs((wt-Nt)*this.edgeProps[be].len);Qs(X,ue,ze),As(ie,Le[1],-Le[0]);const Ft=Wt+Math.abs(tn(X,ie));Ft=0;--R){const U=this.edges[R].a,V=this.edges[R].b,{position:X,height:ie,extent:ue}=this.vertices[U],{position:pe,height:be,extent:Se}=this.vertices[V],Le=this.vertexProps[U].dir,ze=this.vertexProps[V].dir;if(oe(x,X[0]/m,X[1]/m,ie),oe(k,pe[0]/m,pe[1]/m,be),oe(T,Le[1],-Le[0],0),ge(T,T,ue),oe(P,ze[1],-ze[0],0),ge(P,P,Se),this.distSqLines(se(x[0]+.5*T[0],x[1]+.5*T[1],x[2]+.5*T[2]),se(k[0]-.5*P[0],k[1]-.5*P[1],k[2]-.5*P[2]),se(x[0]-.5*T[0],x[1]-.5*T[1],x[2]-.5*T[2]),se(k[0]+.5*P[0],k[1]+.5*P[1],k[2]+.5*P[2]))<=.0025000000000000005)continue;const We=this.vertices.length,ct=Xt(gt(),X,pe);this.vertices.push({position:ks(ct,ct,.5),height:.5*(ie+be),extent:.5*(ue+Se)});const nt=Xt(gt(),Le,ze);this.vertexProps.push({dir:an(nt,nt)}),this.edges.splice(R,1),this.edgeProps.splice(R,1),this.edges.push({a:U,b:We}),this.edges.push({a:We,b:V});const ft=Qs(gt(),this.vertices[We].position,X),wt=$s(ft),Nt={vec:ft,dir:ks(gt(),ft,1/wt),len:wt};this.edgeProps.push(Nt),this.edgeProps.push(Nt)}}distSqLines(m,x,k,T){const P=ce(Y(),x,m),R=ce(Y(),T,k),U=ce(Y(),m,k),V=Ae(P,P),X=Ae(P,R),ie=Ae(P,U),ue=Ae(R,R),pe=Ae(R,U),be=V*ue-X*X;if(be===0)return Ce(we(P,k,T,Ae(U,R)/Ae(R,R)),m);const Se=(V*pe-X*ie)/be;return Ce(we(P,m,x,(X*pe-ie*ue)/be),we(R,k,T,Se))}}class zo{static parseFrom(m,x){const k=vo.parse(m);if(!k)return[];let{vertices:T,features:P}=k;const R=1/cn(x);P.sort((ie,ue)=>ie.id-ue.id),T.sort((ie,ue)=>ie.id-ue.id||ie.idx-ue.idx),T=T.filter((ie,ue,pe)=>ue===pe.findIndex(be=>be.id===ie.id&&be.idx===ie.idx));const U=new Array;let V=0;const X=T.length;for(const ie of P){if(ie.constantHeight){U.push(new Sx(ie.id,ie.bounds,ie.constantHeight));continue}for(;V!==X&&T[V].idT.id===k)}}class Vo{constructor(m,x){this.zScale=1,this.xOffset=0,this.yOffset=0,m.equals(x)||(this.zScale=Math.pow(2,x.z-m.z),this.xOffset=(m.x*this.zScale-x.x)*Bn,this.yOffset=(m.y*this.zScale-x.y)*Bn)}constantElevation(m,x){if(m.constantHeight!=null)return this.computeBiasedHeight(m.constantHeight,x)}pointElevation(m,x,k){const T=this.constantElevation(x,k);return T??(m.x=m.x*this.zScale+this.xOffset,m.y=m.y*this.zScale+this.yOffset,this.computeBiasedHeight(x.pointElevation(m),k))}computeBiasedHeight(m,x){return x<=0?m:m+x*ot(0,x,m>=0?m:Math.abs(.5*m))}}Kn(Sx,"ElevationFeature");class co{constructor(m){this.zoom=m.zoom,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.projection=m.projection,this.layoutVertexArray=new qa,this.indexArray=new tc,this.segments=new Po,this.programConfigurations=new qe(m.layers,{zoom:m.zoom,lut:m.lut}),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.elevationMode=this.layers[0].layout.get("circle-elevation-reference"),this.hasElevation=!1,this.elevationMode!=="none"&&(this.elevatedLayoutVertexArray=new no),this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,T){const P=this.layers[0],R=[];let U=null;P.type==="circle"&&(U=P.layout.get("circle-sort-key"));for(const{feature:X,id:ie,index:ue,sourceLayerIndex:pe}of m){const be=this.layers[0]._featureFilter.needGeometry,Se=Ha(X,be);if(!this.layers[0]._featureFilter.filter(new Aa(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),Se,k))continue;const Le=U?U.evaluate(Se,{},k):void 0,ze={id:ie,properties:X.properties,type:X.type,sourceLayerIndex:pe,index:ue,geometry:be?Se.geometry:Vr(X,k,T),patterns:{},sortKey:Le};R.push(ze)}U&&R.sort((X,ie)=>X.sortKey-ie.sortKey);let V=null;T.projection.name==="globe"&&(this.globeExtVertexArray=new N6,V=T.projection);for(const X of R){const{geometry:ie,index:ue,sourceLayerIndex:pe}=X,be=m[ue].feature;this.addFeature(X,ie,ue,x.availableImages,k,V,x.brightness,x.elevationFeatures),x.featureIndex.insert(be,ie,ue,pe,this.index)}this.hasElevation||(this.elevatedLayoutVertexArray=void 0)}update(m,x,k,T,P,R,U){this.programConfigurations.updatePaintArrays(m,x,P,k,T,R,U,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,eq.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.globeExtVertexArray&&(this.globeExtVertexBuffer=m.createVertexBuffer(this.globeExtVertexArray,abe.members)),this.elevatedLayoutVertexArray&&(this.elevatedLayoutVertexBuffer=m.createVertexBuffer(this.elevatedLayoutVertexArray,rbe.members))),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy())}addFeature(m,x,k,T,P,R,U,V){let X;this.elevationMode!=="none"&&(X=zo.getElevationFeature(m,V));for(const ie of x)for(const ue of ie){const pe=ue.x,be=ue.y;if(pe<0||pe>=Bn||be<0||be>=Bn)continue;if(R){const ze=R.projectTilePoint(pe,be,P),We=R.upVector(P,pe,be);this.addGlobeExtVertex(ze,We),this.addGlobeExtVertex(ze,We),this.addGlobeExtVertex(ze,We),this.addGlobeExtVertex(ze,We)}const Se=this.segments.prepareSegment(4,this.layoutVertexArray,this.indexArray,m.sortKey),Le=Se.vertexLength;if(this.addCircleVertex(pe,be,-1,-1),this.addCircleVertex(pe,be,1,-1),this.addCircleVertex(pe,be,1,1),this.addCircleVertex(pe,be,-1,1),this.elevationMode!=="none"){const ze=X?X.pointElevation(new Es(pe,be)):0;this.hasElevation=this.hasElevation||ze!==0;for(let We=0;We<4;We++)this.elevatedLayoutVertexArray.emplaceBack(ze)}this.indexArray.emplaceBack(Le,Le+1,Le+2),this.indexArray.emplaceBack(Le,Le+2,Le+3),Se.vertexLength+=4,Se.primitiveLength+=2}this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,k,{},T,P,U,void 0,this.worldview)}addCircleVertex(m,x,k,T){this.layoutVertexArray.emplaceBack(2*m+(k+1)/2,2*x+(T+1)/2)}addGlobeExtVertex(m,x){this.globeExtVertexArray.emplaceBack(m.x,m.y,m.z,x[0]*16384,x[1]*16384,x[2]*16384)}}function uc(b,m){for(let x=0;x1){if(h_(b,m))return!0;for(let k=0;k1?x:x.sub(m)._mult(T)._add(m))}function rk(b,m){let x,k,T,P=!1;for(let R=0;Rm.y!=T.y>m.y&&m.x<(T.x-k.x)*(m.y-k.y)/(T.y-k.y)+k.x&&(P=!P)}return P}function Gp(b,m){let x=!1;for(let k=0,T=b.length-1;km.y!=R.y>m.y&&m.x<(R.x-P.x)*(m.y-P.y)/(R.y-P.y)+P.x&&(x=!x)}return x}function m_(b,m,x,k,T){for(const R of b)if(m<=R.x&&x<=R.y&&k>=R.x&&T>=R.y)return!0;const P=[new Es(m,x),new Es(m,T),new Es(k,T),new Es(k,x)];if(b.length>2){for(const R of P)if(Gp(b,R))return!0}for(let R=0;RT.x&&m.x>T.x||b.yT.y&&m.y>T.y)return!1;const P=_r(b,m,x[0]);return P!==_r(b,m,x[1])||P!==_r(b,m,x[2])||P!==_r(b,m,x[3])}function f_(b,m,x,k,T,P){let R=m.y-b.y,U=b.x-m.x;if(P=P||0){const V=R*R+U*U;if(V===0)return!0;const X=Math.sqrt(V);R/=X,U/=X}return!((x.x-b.x)*R+(x.y-b.y)*U-P<0||(k.x-b.x)*R+(k.y-b.y)*U-P<0||(T.x-b.x)*R+(T.y-b.y)*U-P<0)}function P6(b,m,x,k,T,P,R){return!(f_(b,m,k,T,P,R)||f_(m,x,k,T,P,R)||f_(x,b,k,T,P,R)||f_(k,T,b,m,x,R)||f_(T,P,b,m,x,R)||f_(P,k,b,m,x,R))}function ak(b,m,x){const k=m.paint.get(b).value;return k.kind==="constant"?k.value:x.programConfigurations.get(m.id).getMaxValue(b)}function tq(b){return Math.sqrt(b[0]*b[0]+b[1]*b[1])}function Q8e(b,m,x,k,T){if(!m[0]&&!m[1])return b;const P=Es.convert(m)._mult(T);x==="viewport"&&P._rotate(-k);const R=[];for(let U=0;U>x&&m.y===this.y>>x}url(m,x){const k=function(P,R,U){const V=2**U,X=2*Math.PI*6378137,ie=X*(P/V-.5),ue=X*(.5-(R+1)/V);return`${ie},${ue},${ie+X/V},${ue+X/V}`}(this.x,this.y,this.z),T=function(P,R,U){let V,X="";for(let ie=P;ie>0;ie--)V=1<this.canonical.z?new op(m,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y):new op(m,this.wrap,m,this.canonical.x>>x,this.canonical.y>>x)}calculateScaledKey(m,x=!0){if(this.overscaledZ===m&&x)return this.key;if(m>this.canonical.z)return L6(this.wrap*+x,m,this.canonical.z,this.canonical.x,this.canonical.y);{const k=this.canonical.z-m;return L6(this.wrap*+x,m,m,this.canonical.x>>k,this.canonical.y>>k)}}isChildOf(m){if(m.wrap!==this.wrap)return!1;const x=this.canonical.z-m.canonical.z;return m.overscaledZ===0||m.overscaledZ>x&&m.canonical.y===this.canonical.y>>x}children(m){if(this.overscaledZ>=m)return[new op(this.overscaledZ+1,this.wrap,this.canonical.z,this.canonical.x,this.canonical.y)];const x=this.canonical.z+1,k=2*this.canonical.x,T=2*this.canonical.y;return[new op(x,this.wrap,x,k,T),new op(x,this.wrap,x,k+1,T),new op(x,this.wrap,x,k,T+1),new op(x,this.wrap,x,k+1,T+1)]}isLessThan(m){return this.wrapm.wrap)&&(this.overscaledZm.overscaledZ)&&(this.canonical.xm.canonical.x)&&this.canonical.y{let m=b.canonical.x-1,x=b.wrap;return m<0&&(m=(1<{let m=b.canonical.x+1,x=b.wrap;return m===1<new op(b.overscaledZ,b.wrap,b.canonical.z,b.canonical.x,(b.canonical.y===0?1<new op(b.overscaledZ,b.wrap,b.canonical.z,b.canonical.x,b.canonical.y===(1<1?null:function(k,T,P,R){const U=Math.sin(P);return k*(Math.sin((1-R)*P)/U)+T*(Math.sin(R*P)/U)}(b.a[m],b.b[m],b.angle,Qe(x,0,1))+b.center[m]}function x_(b){if(b.z<=1)return GSt[b.z+2*b.y+b.x];const m=hbe(rq(b));return eo.fromPoints(m)}function Hj(b,m,x){return ge(b,b,1-x),Te(b,b,m,x)}function rDe(b,m){const x=Gj(m.zoom);if(x===0)return x_(b);const k=rq(b),T=hbe(k),P=rn(k.getWest())*m.worldSize,R=rn(k.getEast())*m.worldSize,U=hn(k.getNorth())*m.worldSize,V=hn(k.getSouth())*m.worldSize,X=[P,U,0],ie=[R,U,0],ue=[P,V,0],pe=[R,V,0],be=j([],m.globeMatrix);return Je(X,X,be),Je(ie,ie,be),Je(ue,ue,be),Je(pe,pe,be),T[0]=Hj(T[0],ue,x),T[1]=Hj(T[1],pe,x),T[2]=Hj(T[2],ie,x),T[3]=Hj(T[3],X,x),eo.fromPoints(T)}function aDe(b,m,x){for(const k of b)Je(k,k,m),ge(k,k,x)}function iDe(b,m,x,k){const T=m/b.worldSize,P=b.globeMatrix;if(x.z<=1){const Gt=x_(x).getCorners();return aDe(Gt,P,T),eo.fromPoints(Gt)}const R=rq(x,k),U=hbe(R,Et+nq(b._tileCoverLift));aDe(U,P,T);const V=Number.MAX_VALUE,X=[-V,-V,-V],ie=[V,V,V];if(R.contains(b.center)){for(const qt of U)le(ie,ie,qt),ve(X,X,qt);X[2]=0;const Gt=b.point,Ut=[Gt.x*T,Gt.y*T,0];return le(ie,ie,Ut),ve(X,X,Ut),new eo(ie,X)}if(b._tileCoverLift>0){for(const Gt of U)le(ie,ie,Gt),ve(X,X,Gt);return new eo(ie,X)}const ue=[P[12]*T,P[13]*T,P[14]*T],pe=R.getCenter(),be=Qe(b.center.lat,-85.051129,Ys),Se=Qe(pe.lat,-85.051129,Ys),Le=rn(b.center.lng),ze=hn(be);let We=Le-rn(pe.lng);const ct=ze-hn(Se);We>.5?We-=1:We<-.5&&(We+=1);let nt=0;Math.abs(We)>Math.abs(ct)?nt=We>=0?1:3:(nt=ct>=0?0:2,Te(ue,ue,[P[4]*T,P[5]*T,P[6]*T],-Math.sin(Ts(ct>=0?R.getSouth():R.getNorth()))*Et));const ft=U[nt],wt=U[(nt+1)%4],Nt=new WSt(ft,wt,ue),Wt=[ube(Nt,0)||ft[0],ube(Nt,1)||ft[1],ube(Nt,2)||ft[2]],Ft=Gj(b.zoom);if(Ft>0){const Gt=function({x:qt,y:zs,z:qs},Xs,sn,Js,fn){const Os=1/(1<.5?ar=-1:Fn<-.5&&(ar=1),en=((en+ar)*Xs-(Js*=Xs))*sn+Js,on=((on+ar)*Xs-Js)*sn+Js,gn=(gn*Xs-(fn*=Xs))*sn+fn,Cn=(Cn*Xs-fn)*sn+fn,[[en,Cn,0],[on,Cn,0],[on,gn,0],[en,gn,0]]}(x,m,b._pixelsPerMercatorPixel,Le,ze);for(let qt=0;qtMath.PI/2*1.01}const uDe=Ts(85),KSt=Math.cos(uDe),YSt=Math.sin(uDe),ZSt=y(),hDe=b=>{const m=[];return b.paint.get("circle-pitch-alignment")==="map"&&m.push("PITCH_WITH_MAP"),b.paint.get("circle-pitch-scale")==="map"&&m.push("SCALE_WITH_MAP"),m};function mDe(b,m,x,k,T,P,R,U,V){if(P&&b.queryGeometry.isAboveHorizon)return!1;P&&(V*=b.pixelToTileUnitsFactor);const X=b.tileID.canonical,ie=x.projection.upVectorScale(X,x.center.lat,x.worldSize).metersToTile;for(const ue of m)for(const pe of ue){const be=pe.add(U),Se=T&&x.elevation?x.elevation.exaggeration()*T.getElevationAt(be.x,be.y,!0):0,Le=x.projection.projectTilePoint(be.x,be.y,X);if(Se>0){const nt=x.projection.upVector(X,be.x,be.y);Le.x+=nt[0]*ie*Se,Le.y+=nt[1]*ie*Se,Le.z+=nt[2]*ie*Se}const ze=P?be:QSt(Le.x,Le.y,Le.z,k),We=P?b.tilespaceRays.map(nt=>JSt(nt,Se)):b.queryGeometry.screenGeometry,ct=ut([],[Le.x,Le.y,Le.z,1],k);if(!R&&P?V*=ct[3]/x.cameraToCenterDistance:R&&!P&&(V*=x.cameraToCenterDistance/ct[3]),P){const nt=Fs((pe.y/Bn+X.y)/(1<b.width||T.height>b.height||x.x>b.width-T.width||x.y>b.height-T.height)throw new RangeError("out of range source coordinates for image copy");if(T.width>m.width||T.height>m.height||k.x>m.width-T.width||k.y>m.height-T.height)throw new RangeError("out of range destination coordinates for image copy");const V=b.data,X=m.data,ie=P===4&&U;for(let ue=0;ue{m[b.evaluationKey]=V;const X=b.expression.evaluate(m),ie=X?X.toNonPremultipliedRenderColor(null):null;ie&&(T.data[R+U+0]=Math.floor(255*ie.r),T.data[R+U+1]=Math.floor(255*ie.g),T.data[R+U+2]=Math.floor(255*ie.b),T.data[R+U+3]=Math.floor(255*ie.a))};if(b.clips)for(let R=0,U=0;R80*x){U=b[0],V=b[1];let ie=U,ue=V;for(let pe=x;peie&&(ie=be),Se>ue&&(ue=Se)}X=Math.max(ie-U,ue-V),X=X!==0?32767/X:0}return XR(P,R,x,U,V,X,0),R}function jDe(b,m,x,k,T){let P;if(T===function(R,U,V,X){let ie=0;for(let ue=U,pe=V-X;ue0)for(let R=m;R=m;R-=k)P=CDe(R/k|0,b[R],b[R+1],P);return P&&R6(P,P.next)&&(tO(P),P=P.next),P}function qC(b,m){if(!b)return b;m||(m=b);let x,k=b;do if(x=!1,k.steiner||!R6(k,k.next)&&xu(k.prev,k,k.next)!==0)k=k.next;else{if(tO(k),k=m=k.prev,k===k.next)break;x=!0}while(x||k!==m);return m}function XR(b,m,x,k,T,P,R){if(!b)return;!R&&P&&function(V,X,ie,ue){let pe=V;do pe.z===0&&(pe.z=gbe(pe.x,pe.y,X,ie,ue)),pe.prevZ=pe.prev,pe.nextZ=pe.next,pe=pe.next;while(pe!==V);pe.prevZ.nextZ=null,pe.prevZ=null,function(be){let Se,Le=1;do{let ze,We=be;be=null;let ct=null;for(Se=0;We;){Se++;let nt=We,ft=0;for(let Nt=0;Nt0||wt>0&&nt;)ft!==0&&(wt===0||!nt||We.z<=nt.z)?(ze=We,We=We.nextZ,ft--):(ze=nt,nt=nt.nextZ,wt--),ct?ct.nextZ=ze:be=ze,ze.prevZ=ct,ct=ze;We=nt}ct.nextZ=null,Le*=2}while(Se>1)}(pe)}(b,k,T,P);let U=b;for(;b.prev!==b.next;){const V=b.prev,X=b.next;if(P?a4t(b,k,T,P):r4t(b))m.push(V.i,b.i,X.i),tO(b),b=X.next,U=X.next;else if((b=X)===U){R?R===1?XR(b=i4t(qC(b),m),m,x,k,T,P,2):R===2&&o4t(b,m,x,k,T,P):XR(qC(b),m,x,k,T,P,1);break}}}function r4t(b){const m=b.prev,x=b,k=b.next;if(xu(m,x,k)>=0)return!1;const T=m.x,P=x.x,R=k.x,U=m.y,V=x.y,X=k.y,ie=Math.min(T,P,R),ue=Math.min(U,V,X),pe=Math.max(T,P,R),be=Math.max(U,V,X);let Se=k.next;for(;Se!==m;){if(Se.x>=ie&&Se.x<=pe&&Se.y>=ue&&Se.y<=be&&JR(T,U,P,V,R,X,Se.x,Se.y)&&xu(Se.prev,Se,Se.next)>=0)return!1;Se=Se.next}return!0}function a4t(b,m,x,k){const T=b.prev,P=b,R=b.next;if(xu(T,P,R)>=0)return!1;const U=T.x,V=P.x,X=R.x,ie=T.y,ue=P.y,pe=R.y,be=Math.min(U,V,X),Se=Math.min(ie,ue,pe),Le=Math.max(U,V,X),ze=Math.max(ie,ue,pe),We=gbe(be,Se,m,x,k),ct=gbe(Le,ze,m,x,k);let nt=b.prevZ,ft=b.nextZ;for(;nt&&nt.z>=We&&ft&&ft.z<=ct;){if(nt.x>=be&&nt.x<=Le&&nt.y>=Se&&nt.y<=ze&&nt!==T&&nt!==R&&JR(U,ie,V,ue,X,pe,nt.x,nt.y)&&xu(nt.prev,nt,nt.next)>=0||(nt=nt.prevZ,ft.x>=be&&ft.x<=Le&&ft.y>=Se&&ft.y<=ze&&ft!==T&&ft!==R&&JR(U,ie,V,ue,X,pe,ft.x,ft.y)&&xu(ft.prev,ft,ft.next)>=0))return!1;ft=ft.nextZ}for(;nt&&nt.z>=We;){if(nt.x>=be&&nt.x<=Le&&nt.y>=Se&&nt.y<=ze&&nt!==T&&nt!==R&&JR(U,ie,V,ue,X,pe,nt.x,nt.y)&&xu(nt.prev,nt,nt.next)>=0)return!1;nt=nt.prevZ}for(;ft&&ft.z<=ct;){if(ft.x>=be&&ft.x<=Le&&ft.y>=Se&&ft.y<=ze&&ft!==T&&ft!==R&&JR(U,ie,V,ue,X,pe,ft.x,ft.y)&&xu(ft.prev,ft,ft.next)>=0)return!1;ft=ft.nextZ}return!0}function i4t(b,m){let x=b;do{const k=x.prev,T=x.next.next;!R6(k,T)&&kDe(k,x,x.next,T)&&eO(k,T)&&eO(T,k)&&(m.push(k.i,x.i,T.i),tO(x),tO(x.next),x=b=T),x=x.next}while(x!==b);return qC(x)}function o4t(b,m,x,k,T,P){let R=b;do{let U=R.next.next;for(;U!==R.prev;){if(R.i!==U.i&&h4t(R,U)){let V=SDe(R,U);return R=qC(R,R.next),V=qC(V,V.next),XR(R,m,x,k,T,P,0),void XR(V,m,x,k,T,P,0)}U=U.next}R=R.next}while(R!==b)}function l4t(b,m){let x=b.x-m.x;return x===0&&(x=b.y-m.y,x===0)&&(x=(b.next.y-b.y)/(b.next.x-b.x)-(m.next.y-m.y)/(m.next.x-m.x)),x}function c4t(b,m){const x=function(T,P){let R=P;const U=T.x,V=T.y;let X,ie=-1/0;if(R6(T,R))return R;do{if(R6(T,R.next))return R.next;if(V<=R.y&&V>=R.next.y&&R.next.y!==R.y){const Le=R.x+(V-R.y)*(R.next.x-R.x)/(R.next.y-R.y);if(Le<=U&&Le>ie&&(ie=Le,X=R.x=R.x&&R.x>=pe&&U!==R.x&&NDe(VX.x||R.x===X.x&&d4t(X,R)))&&(X=R,Se=Le)}R=R.next}while(R!==ue);return X}(b,m);if(!x)return m;const k=SDe(x,b);return qC(k,k.next),qC(x,x.next)}function d4t(b,m){return xu(b.prev,b,m.prev)<0&&xu(m.next,b,b.next)<0}function gbe(b,m,x,k,T){return(b=1431655765&((b=858993459&((b=252645135&((b=16711935&((b=(b-x)*T|0)|b<<8))|b<<4))|b<<2))|b<<1))|(m=1431655765&((m=858993459&((m=252645135&((m=16711935&((m=(m-k)*T|0)|m<<8))|m<<4))|m<<2))|m<<1))<<1}function u4t(b){let m=b,x=b;do(m.x=(b-R)*(P-U)&&(b-R)*(k-U)>=(x-R)*(m-U)&&(x-R)*(P-U)>=(T-R)*(k-U)}function JR(b,m,x,k,T,P,R,U){return!(b===R&&m===U)&&NDe(b,m,x,k,T,P,R,U)}function h4t(b,m){return b.next.i!==m.i&&b.prev.i!==m.i&&!function(x,k){let T=x;do{if(T.i!==x.i&&T.next.i!==x.i&&T.i!==k.i&&T.next.i!==k.i&&kDe(T,T.next,x,k))return!0;T=T.next}while(T!==x);return!1}(b,m)&&(eO(b,m)&&eO(m,b)&&function(x,k){let T=x,P=!1;const R=(x.x+k.x)/2,U=(x.y+k.y)/2;do T.y>U!=T.next.y>U&&T.next.y!==T.y&&R<(T.next.x-T.x)*(U-T.y)/(T.next.y-T.y)+T.x&&(P=!P),T=T.next;while(T!==x);return P}(b,m)&&(xu(b.prev,b,m.prev)||xu(b,m.prev,m))||R6(b,m)&&xu(b.prev,b,b.next)>0&&xu(m.prev,m,m.next)>0)}function xu(b,m,x){return(m.y-b.y)*(x.x-m.x)-(m.x-b.x)*(x.y-m.y)}function R6(b,m){return b.x===m.x&&b.y===m.y}function kDe(b,m,x,k){const T=oq(xu(b,m,x)),P=oq(xu(b,m,k)),R=oq(xu(x,k,b)),U=oq(xu(x,k,m));return T!==P&&R!==U||!(T!==0||!iq(b,x,m))||!(P!==0||!iq(b,k,m))||!(R!==0||!iq(x,b,k))||!(U!==0||!iq(x,m,k))}function iq(b,m,x){return m.x<=Math.max(b.x,x.x)&&m.x>=Math.min(b.x,x.x)&&m.y<=Math.max(b.y,x.y)&&m.y>=Math.min(b.y,x.y)}function oq(b){return b>0?1:b<0?-1:0}function eO(b,m){return xu(b.prev,b,b.next)<0?xu(b,m,b.next)>=0&&xu(b,b.prev,m)>=0:xu(b,m,b.prev)<0||xu(b,b.next,m)<0}function SDe(b,m){const x=ybe(b.i,b.x,b.y),k=ybe(m.i,m.x,m.y),T=b.next,P=m.prev;return b.next=m,m.prev=b,x.next=T,T.prev=x,k.next=x,x.prev=k,P.next=k,k.prev=P,k}function CDe(b,m,x,k){const T=ybe(b,m,x);return k?(T.next=k.next,T.prev=k,k.next.prev=T,k.next=T):(T.prev=T,T.next=T),T}function tO(b){b.next.prev=b.prev,b.prev.next=b.next,b.prevZ&&(b.prevZ.nextZ=b.nextZ),b.nextZ&&(b.nextZ.prevZ=b.prevZ)}function ybe(b,m,x){return{i:b,x:m,y:x,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function sO(b,m){const x=b.length;if(x<=1)return[b];const k=[];let T,P;for(let R=0;R1)for(let R=0;R=Bn&&x>=Bn}static evaluate(m){if(m.length===0)return new Wj;let x=[];for(const V of m)x.push(...V.portals);if(x.length===0)return new Wj;for(const V of x){const X=V.va,ie=V.vb;(Wj.isOnBorder(X.x,ie.x)||Wj.isOnBorder(X.y,ie.y))&&(V.type="border")}const k=x.filter(V=>V.type!=="unevaluated"),T=x.filter(V=>V.type==="unevaluated");if(T.length===0)return new Wj;T.sort((V,X)=>V.hash===X.hash?V.isTunnel===X.isTunnel?0:V.isTunnel?-1:1:V.hashV.hashP!=="fill-tunnel-structure-color"),this.tunnelProgramConfigurations=new qe(x,{zoom:k,lut:T},P=>P!=="fill-bridge-guard-rail-color")}addVertices(m,x){const k=this.unevalVertices.length;for(let T=0;T=P.min.x&&ue.x<=P.max.x&&ue.y>=P.min.y&&ue.y<=P.max.y||pe.x>=P.min.x&&pe.x<=P.max.x&&pe.y>=P.min.y&&pe.y<=P.max.y||p_(ue,pe,U))||this.isOnBorder(ue.x,pe.x)||this.isOnBorder(ue.y,pe.y))continue;const be=Cx.computeEdgeHash(this.unevalVertices[X],this.unevalVertices[ie]);let Se,Le=this.vertexHashLookup.get(Cx.computePosHash(ue));Le!=null?Se=Le.next:(Le=this.vertexHashLookup.get(Cx.computePosHash(pe)),Se=Le!=null?Le.prev:be),this.unevalEdges.push({polygonIdx:m,a:X,b:ie,hash:be,portalHash:Se,isTunnel:T,type:"unevaluated",featureInfo:R})}}addPortalCandidates(m,x,k,T,P){if(x.length!==0){this.vertexHashLookup.clear();for(const R of x){if(R.length===0)continue;const U=R[0];let V=Cx.computeEdgeHash(U[U.length-2],U[U.length-1]);for(let X=0;X({vertexOffset:0,primitiveOffset:this.indexArray.length}),k=pe=>{pe.primitiveLength=this.indexArray.length-pe.primitiveOffset},T=new p4t(this.vertexPositions,this.vertexNormals,this.indexArray);this.prepareEdges(m.portals,this.unevalEdges);const P=x(),R=x(),U=x(),V=(pe,be)=>{pe.sort((Le,ze)=>Le.type===be&&ze.type!==be?-1:Le.type!==be&&ze.type===be?1:0);const Se=pe.findIndex(Le=>Le.type!==be);return Se>=0?Se:pe.length};let X=0;this.unevalEdges.length>0&&(X=V(this.unevalEdges,"none"),this.constructBridgeStructures(T,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},this.tileToMeters)),k(U);const ie=x(),ue=x();if(this.unevalEdges.length>0){const pe=this.unevalEdges.splice(X),be=V(pe,"tunnel")+X;this.unevalEdges.push(...pe),this.constructTunnelStructures(T,this.unevalVertices,this.unevalHeights,this.unevalEdges,{min:0,max:X},{min:X,max:be})}k(ie),T.addTriangles(this.unevalTriangles,this.unevalVertices,this.unevalHeights),k(ue),T.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,this.unevalHeights),k(R),T.addTriangles(this.unevalTunnelTriangles,this.unevalVertices,[-.1]),k(P),this.maskSegments=Po.simpleSegment(0,ue.primitiveOffset,0,ue.primitiveLength),this.depthSegments=Po.simpleSegment(0,R.primitiveOffset,0,R.primitiveLength),this.renderableBridgeSegments=Po.simpleSegment(0,U.primitiveOffset,0,U.primitiveLength),this.renderableTunnelSegments=Po.simpleSegment(0,ie.primitiveOffset,0,ie.primitiveLength),this.shadowCasterSegments=Po.simpleSegment(0,P.primitiveOffset,0,P.primitiveLength)}update(m,x,k,T,P,R,U,V){this.bridgeProgramConfigurations.updatePaintArrays(m,x,P,k,T,R,U,V),this.tunnelProgramConfigurations.updatePaintArrays(m,x,P,k,T,R,U,V)}upload(m){this.vertexBuffer||this.vertexPositions.length===0||this.vertexNormals.length===0||this.indexArray.length===0||(this.vertexBuffer=m.createVertexBuffer(this.vertexPositions,s4t.members),this.vertexBufferNormal=m.createVertexBuffer(this.vertexNormals,n4t.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.bridgeProgramConfigurations.upload(m),this.tunnelProgramConfigurations.upload(m))}destroy(){this.vertexBuffer&&(this.vertexBuffer.destroy(),this.vertexBufferNormal.destroy(),this.indexBuffer.destroy()),this.maskSegments&&(this.maskSegments.destroy(),this.depthSegments.destroy(),this.renderableBridgeSegments.destroy(),this.renderableTunnelSegments.destroy(),this.shadowCasterSegments.destroy()),this.bridgeProgramConfigurations.destroy(),this.tunnelProgramConfigurations.destroy()}populatePaintArrays(m,x,k,T,P){const R=(U,V)=>{for(let X=0;Xoe(sn,x[Js].x,x[Js].y,k[Js]*V),ue=Y(),pe=Y(),be=Y(),Se=Y(),Le=Y(),ze=(sn,Js)=>{const fn=U.get(Cx.computePosHash(x[Js])),Os=fn.from,en=fn.to;if(!Os||!en)return;ie(ue,Os),ie(pe,Js),ie(be,en),je(Se),He(ue,pe)||($e(Le,pe,ue),Re(Se,Le)),He(be,pe)||($e(Le,be,pe),he(Se,Se,Re(Le,Le)));const on=Ge(Se);return on>0?ge(sn,Se,1/on):void 0};let We=Number.POSITIVE_INFINITY;this.sortSubarray(T,P.min,P.max,(sn,Js)=>sn.featureInfo.featureIndex-Js.featureInfo.featureIndex);const ct=Y(),nt=Y(),ft=Y(),wt=Y(),Nt=Y(),Wt=Y(),Ft=Y(),Gt=Y(),Ut=Y(),qt=[Y(),Y(),Y(),Y()],zs=[Y(),Y(),Y(),Y()],qs=[{coord:new Es(0,0),height:0},{coord:new Es(0,0),height:0}],Xs=(sn,Js)=>sn>Js;for(let sn=P.min;snWe.featureInfo.featureIndex-ct.featureInfo.featureIndex;this.sortSubarray(T,P.min,P.max,V),this.sortSubarray(T,R.min,R.max,V);const X=We=>Re(We,We),ie=[{coord:new Es(0,0),height:0},{coord:new Es(0,0),height:0}],ue=(We,ct)=>WeU.hash===V.hash?V.polygonIdx-U.polygonIdx:V.hash>U.hash?1:-1);let k=0,T=0,P=0,R=x[k].polygonIdx;do T++,(T===x.length||x[k].hash!==x[T].hash)&&((T-k===1||x[T-1].polygonIdx!==R)&&(PX.portalHashie.hash?U++:ie.hash>X.portalHash?V++:(X.type=ie.type,U++)}}}isOnBorder(m,x){return m<=0&&x<=0||m>=Bn&&x>=Bn}addFeatureSection(m,x,k,T){return m!==x&&(x=m,k.push({featureIndex:m,vertexStart:T.getVertexCount()}),T.clearVertexLookup()),x}sortSubarray(m,x,k,T){const P=m.slice(x,k);P.sort(T),m.splice(x,P.length,...P)}static computeEdgeHash(m,x){return(m.y===x.y&&m.x>x.x||m.y>x.y)&&([m,x]=[x,m]),BigInt(Cx.computePosHash(m))<<32n|BigInt(Cx.computePosHash(x))}static computePosHash(m){return((65535&m.x)<<16|65535&m.y)>>>0}}function f4t(b,m){return b>m?1:b0))return x;x=x.left}}return null}contains(m){for(var x=this._root,k=this._compare;x;){var T=k(m,x.key);if(T===0)return!0;x=T<0?x.left:x.right}return!1}remove(m){var x=this.find(m);if(!x)return!1;if(this.splay(x),x.left)if(x.right){var k=this.minNode(x.right);k.parent!==x&&(this.replace(k,k.right),k.right=x.right,k.right.parent=k),this.replace(x,k),k.left=x.left,k.left.parent=k}else this.replace(x,x.left);else this.replace(x,x.right);return this._size--,!0}removeNode(m){if(!m)return!1;if(this.splay(m),m.left)if(m.right){var x=this.minNode(m.right);x.parent!==m&&(this.replace(x,x.right),x.right=m.right,x.right.parent=x),this.replace(m,x),x.left=m.left,x.left.parent=x}else this.replace(m,m.left);else this.replace(m,m.right);return this._size--,!0}erase(m){var x=this.find(m);if(x){this.splay(x);var k=x.left,T=x.right,P=null;k&&(k.parent=null,P=this.maxNode(k),this.splay(P),this._root=P),T&&(k?P.right=T:this._root=T,T.parent=P),this._size--}}pop(){var m=this._root,x=null;if(m){for(;m.left;)m=m.left;x={key:m.key,data:m.data},this.remove(m.key)}return x}next(m){var x=m;if(x)if(x.right)for(x=x.right;x&&x.left;)x=x.left;else for(x=m.parent;x&&x.right===m;)m=x,x=x.parent;return x}prev(m){var x=m;if(x)if(x.left)for(x=x.left;x&&x.right;)x=x.right;else for(x=m.parent;x&&x.left===m;)m=x,x=x.parent;return x}forEach(m){for(var x=this._root,k=[],T=!1,P=0;!T;)x?(k.push(x),x=x.left):k.length>0?(m(x=k.pop(),P++),x=x.right):T=!0;return this}range(m,x,k,T){const P=[],R=this._compare;let U,V=this._root;for(;P.length!==0||V;)if(V)P.push(V),V=V.left;else{if(V=P.pop(),U=R(V.key,x),U>0)break;if(R(V.key,m)>=0&&k.call(T,V))return this;V=V.right}return this}keys(){for(var m=this._root,x=[],k=[],T=!1;!T;)m?(x.push(m),m=m.left):x.length>0?(m=x.pop(),k.push(m.key),m=m.right):T=!0;return k}values(){for(var m=this._root,x=[],k=[],T=!1;!T;)m?(x.push(m),m=m.left):x.length>0?(m=x.pop(),k.push(m.data),m=m.right):T=!0;return k}at(m){for(var x=this._root,k=[],T=!1,P=0;!T;)if(x)k.push(x),x=x.left;else if(k.length>0){if(x=k.pop(),P===m)return x;P++,x=x.right}else T=!0;return null}load(m=[],x=[],k=!1){if(this._size!==0)throw new Error("bulk-load: tree is not empty");const T=m.length;return k&&jbe(m,x,0,T-1,this._compare),this._root=wbe(null,m,x,0,T),this._size=T,this}min(){var m=this.minNode(this._root);return m?m.key:null}max(){var m=this.maxNode(this._root);return m?m.key:null}isEmpty(){return this._root===null}get size(){return this._size}static createTree(m,x,k,T,P){return new _be(k,P).load(m,x,T)}}function wbe(b,m,x,k,T){const P=T-k;if(P>0){const R=k+Math.floor(P/2),U={key:m[R],data:x[R],parent:b};return U.left=wbe(U,m,x,k,R),U.right=wbe(U,m,x,R+1,T),U}return null}function jbe(b,m,x,k,T){if(x>=k)return;const P=b[x+k>>1];let R=x-1,U=k+1;for(;;){do R++;while(T(b[R],P)<0);do U--;while(T(b[U],P)>0);if(R>=U)break;let V=b[R];b[R]=b[U],b[U]=V,V=m[R],m[R]=m[U],m[U]=V}jbe(b,m,x,U,T),jbe(b,m,U+1,k,T)}const EDe=11102230246251565e-32,Bf=134217729,x4t=(3+8*EDe)*EDe;function Nbe(b,m,x,k,T){let P,R,U,V,X=m[0],ie=k[0],ue=0,pe=0;ie>X==ie>-X?(P=X,X=m[++ue]):(P=ie,ie=k[++pe]);let be=0;if(ueX==ie>-X?(R=X+P,U=P-(R-X),X=m[++ue]):(R=ie+P,U=P-(R-ie),ie=k[++pe]),P=R,U!==0&&(T[be++]=U);ueX==ie>-X?(R=P+X,V=R-P,U=P-(R-V)+(X-V),X=m[++ue]):(R=P+ie,V=R-P,U=P-(R-V)+(ie-V),ie=k[++pe]),P=R,U!==0&&(T[be++]=U);for(;ue0:(k[0]-m[0])*(x[1]-m[1])-(x[0]-m[0])*(k[1]-m[1])>0}isAbove(m){return!this.isBelow(m)}isVertical(){return this.point[0]===this.otherEvent.point[0]}get inResult(){return this.resultTransition!==0}clone(){const m=new F6(this.point,this.left,this.otherEvent,this.isSubject,this.type);return m.contourId=this.contourId,m.resultTransition=this.resultTransition,m.prevInResult=this.prevInResult,m.isExteriorRing=this.isExteriorRing,m.inOut=this.inOut,m.otherInOut=this.otherInOut,m}}function g_(b,m){return b[0]===m[0]&&b[1]===m[1]}function kbe(b,m,x){const k=function(T,P,R,U,V,X){const ie=(P-X)*(R-V),ue=(T-V)*(U-X),pe=ie-ue;if(ie===0||ue===0||ie>0!=ue>0)return pe;const be=Math.abs(ie+ue);return Math.abs(pe)>=33306690738754716e-32*be?pe:-function(Se,Le,ze,We,ct,nt,ft){let wt,Nt,Wt,Ft,Gt,Ut,qt,zs,qs,Xs,sn,Js,fn,Os,en,on,gn,Cn;const ar=Se-ct,Fn=ze-ct,Rn=Le-nt,Tn=We-nt;Os=ar*Tn,Ut=Bf*ar,qt=Ut-(Ut-ar),zs=ar-qt,Ut=Bf*Tn,qs=Ut-(Ut-Tn),Xs=Tn-qs,en=zs*Xs-(Os-qt*qs-zs*qs-qt*Xs),on=Rn*Fn,Ut=Bf*Rn,qt=Ut-(Ut-Rn),zs=Rn-qt,Ut=Bf*Fn,qs=Ut-(Ut-Fn),Xs=Fn-qs,gn=zs*Xs-(on-qt*qs-zs*qs-qt*Xs),sn=en-gn,Gt=en-sn,O6[0]=en-(sn+Gt)+(Gt-gn),Js=Os+sn,Gt=Js-Os,fn=Os-(Js-Gt)+(sn-Gt),sn=fn-on,Gt=fn-sn,O6[1]=fn-(sn+Gt)+(Gt-on),Cn=Js+sn,Gt=Cn-Js,O6[2]=Js-(Cn-Gt)+(sn-Gt),O6[3]=Cn;let sr=function(_i,Ca){let Ni=Ca[0];for(let Ga=1;Ga<4;Ga++)Ni+=Ca[Ga];return Ni}(0,O6),hr=22204460492503146e-32*ft;if(sr>=hr||-sr>=hr||(Gt=Se-ar,wt=Se-(ar+Gt)+(Gt-ct),Gt=ze-Fn,Wt=ze-(Fn+Gt)+(Gt-ct),Gt=Le-Rn,Nt=Le-(Rn+Gt)+(Gt-nt),Gt=We-Tn,Ft=We-(Tn+Gt)+(Gt-nt),wt===0&&Nt===0&&Wt===0&&Ft===0)||(hr=11093356479670487e-47*ft+x4t*Math.abs(sr),sr+=ar*Ft+Tn*wt-(Rn*Wt+Fn*Nt),sr>=hr||-sr>=hr))return sr;Os=wt*Tn,Ut=Bf*wt,qt=Ut-(Ut-wt),zs=wt-qt,Ut=Bf*Tn,qs=Ut-(Ut-Tn),Xs=Tn-qs,en=zs*Xs-(Os-qt*qs-zs*qs-qt*Xs),on=Nt*Fn,Ut=Bf*Nt,qt=Ut-(Ut-Nt),zs=Nt-qt,Ut=Bf*Fn,qs=Ut-(Ut-Fn),Xs=Fn-qs,gn=zs*Xs-(on-qt*qs-zs*qs-qt*Xs),sn=en-gn,Gt=en-sn,Tx[0]=en-(sn+Gt)+(Gt-gn),Js=Os+sn,Gt=Js-Os,fn=Os-(Js-Gt)+(sn-Gt),sn=fn-on,Gt=fn-sn,Tx[1]=fn-(sn+Gt)+(Gt-on),Cn=Js+sn,Gt=Cn-Js,Tx[2]=Js-(Cn-Gt)+(sn-Gt),Tx[3]=Cn;const Ur=Nbe(4,O6,4,Tx,ADe);Os=ar*Ft,Ut=Bf*ar,qt=Ut-(Ut-ar),zs=ar-qt,Ut=Bf*Ft,qs=Ut-(Ut-Ft),Xs=Ft-qs,en=zs*Xs-(Os-qt*qs-zs*qs-qt*Xs),on=Rn*Wt,Ut=Bf*Rn,qt=Ut-(Ut-Rn),zs=Rn-qt,Ut=Bf*Wt,qs=Ut-(Ut-Wt),Xs=Wt-qs,gn=zs*Xs-(on-qt*qs-zs*qs-qt*Xs),sn=en-gn,Gt=en-sn,Tx[0]=en-(sn+Gt)+(Gt-gn),Js=Os+sn,Gt=Js-Os,fn=Os-(Js-Gt)+(sn-Gt),sn=fn-on,Gt=fn-sn,Tx[1]=fn-(sn+Gt)+(Gt-on),Cn=Js+sn,Gt=Cn-Js,Tx[2]=Js-(Cn-Gt)+(sn-Gt),Tx[3]=Cn;const jr=Nbe(Ur,ADe,4,Tx,MDe);Os=wt*Ft,Ut=Bf*wt,qt=Ut-(Ut-wt),zs=wt-qt,Ut=Bf*Ft,qs=Ut-(Ut-Ft),Xs=Ft-qs,en=zs*Xs-(Os-qt*qs-zs*qs-qt*Xs),on=Nt*Wt,Ut=Bf*Nt,qt=Ut-(Ut-Nt),zs=Nt-qt,Ut=Bf*Wt,qs=Ut-(Ut-Wt),Xs=Wt-qs,gn=zs*Xs-(on-qt*qs-zs*qs-qt*Xs),sn=en-gn,Gt=en-sn,Tx[0]=en-(sn+Gt)+(Gt-gn),Js=Os+sn,Gt=Js-Os,fn=Os-(Js-Gt)+(sn-Gt),sn=fn-on,Gt=fn-sn,Tx[1]=fn-(sn+Gt)+(Gt-on),Cn=Js+sn,Gt=Cn-Js,Tx[2]=Js-(Cn-Gt)+(sn-Gt),Tx[3]=Cn;const Sa=Nbe(jr,MDe,4,Tx,IDe);return IDe[Sa-1]}(T,P,R,U,V,X,be)}(b[0],b[1],m[0],m[1],x[0],x[1]);return k>0?-1:k<0?1:0}function ok(b,m){const x=b.point,k=m.point;return x[0]>k[0]?1:x[0]k[1]?1:-1:function(T,P,R){return T.left!==P.left?T.left?1:-1:kbe(R,T.otherEvent.point,P.otherEvent.point)!==0?T.isBelow(P.otherEvent.point)?-1:1:!T.isSubject&&P.isSubject?1:-1}(b,m,x)}function lk(b,m,x){const k=new F6(m,!1,b,b.isSubject),T=new F6(m,!0,b.otherEvent,b.isSubject);return g_(b.point,b.otherEvent.point)&&console.warn("what is that, a collapsed segment?",b),k.contourId=T.contourId=b.contourId,ok(T,b.otherEvent)>0&&(b.otherEvent.left=!0,T.left=!1),b.otherEvent.otherEvent=T,b.otherEvent=k,x.push(T),x.push(k),x}function lq(b,m){return b[0]*m[1]-b[1]*m[0]}function Sbe(b,m){return b[0]*m[0]+b[1]*m[1]}function Cbe(b,m,x){const k=function(V,X,ie,ue){const pe=[X[0]-V[0],X[1]-V[1]],be=[ue[0]-ie[0],ue[1]-ie[1]];function Se(Wt,Ft,Gt){return[Wt[0]+Ft*Gt[0],Wt[1]+Ft*Gt[1]]}const Le=[ie[0]-V[0],ie[1]-V[1]];let ze=lq(pe,be),We=ze*ze;const ct=Sbe(pe,pe);if(We>0){const Wt=lq(Le,be)/ze;if(Wt<0||Wt>1)return null;const Ft=lq(Le,pe)/ze;return Ft<0||Ft>1?null:Wt===0||Wt===1?[Se(V,Wt,pe)]:Ft===0||Ft===1?[Se(ie,Ft,be)]:[Se(V,Wt,pe)]}if(ze=lq(Le,pe),We=ze*ze,We>0)return null;const nt=Sbe(pe,Le)/ct,ft=nt+Sbe(pe,be)/ct,wt=Math.min(nt,ft),Nt=Math.max(nt,ft);return wt<=1&&Nt>=0?wt===1?[Se(V,wt>0?wt:0,pe)]:Nt===0?[Se(V,Nt<1?Nt:1,pe)]:[Se(V,wt>0?wt:0,pe),Se(V,Nt<1?Nt:1,pe)]:null}(b.point,b.otherEvent.point,m.point,m.otherEvent.point),T=k?k.length:0;if(T===0||T===1&&(g_(b.point,m.point)||g_(b.otherEvent.point,m.otherEvent.point))||T===2&&b.isSubject===m.isSubject)return 0;if(T===1)return!g_(b.point,k[0])&&!g_(b.otherEvent.point,k[0])&&lk(b,k[0],x),!g_(m.point,k[0])&&!g_(m.otherEvent.point,k[0])&&lk(m,k[0],x),1;const P=[];let R=!1,U=!1;return g_(b.point,m.point)?R=!0:ok(b,m)===1?P.push(m,b):P.push(b,m),g_(b.otherEvent.point,m.otherEvent.point)?U=!0:ok(b.otherEvent,m.otherEvent)===1?P.push(m.otherEvent,b.otherEvent):P.push(b.otherEvent,m.otherEvent),R&&U||R?(m.type=1,b.type=m.inOut===b.inOut?2:3,R&&!U&&lk(P[1].otherEvent,P[0].point,x),2):U?(lk(P[0],P[1].point,x),3):P[0]!==P[3].otherEvent?(lk(P[0],P[1].point,x),lk(P[1],P[2].point,x),3):(lk(P[0],P[1].point,x),lk(P[3].otherEvent,P[2].point,x),3)}function g4t(b,m){if(b===m)return 0;if(kbe(b.point,b.otherEvent.point,m.point)!==0||kbe(b.point,b.otherEvent.point,m.otherEvent.point)!==0)return g_(b.point,m.point)?b.isBelow(m.otherEvent.point)?-1:1:b.point[0]===m.point[0]?b.point[1](m.contourId??0)?1:-1}return ok(b,m)===1?1:-1}class y4t{constructor(){this.points=[],this.holeIds=[],this.holeOf=null,this.depth=null}isExterior(){return this.holeOf==null}}function v4t(b,m,x,k){let T,P=b+1,R=m[b].point;const U=m.length;for(Pk;)P--;return P}function b4t(b,m,x){const k=new y4t;if(b.prevInResult!=null){const T=b.prevInResult,P=T.outputContourId;if(T.resultTransition>0){const R=m[P];if(R.holeOf!=null){const U=R.holeOf;m[U].holeIds.push(x),k.holeOf=U,k.depth=m[P].depth}else m[P].holeIds.push(x),k.holeOf=P,k.depth=m[P].depth+1}else k.holeOf=null,k.depth=m[P].depth}else k.holeOf=null,k.depth=0;return k}const LDe=Math.max,DDe=Math.min;let cq=0;function RDe(b,m,x,k,T,P){let R,U,V,X,ie,ue;for(R=0,U=b.length-1;R0?ue.left=!0:ie.left=!0;const pe=V[0],be=V[1];T[0]=DDe(T[0],pe),T[1]=DDe(T[1],be),T[2]=LDe(T[2],pe),T[3]=LDe(T[3],be),k.push(ie),k.push(ue)}}const dq=[];function ODe(b,m,x){let k=b,T=m;typeof b[0][0][0]=="number"&&(k=[b]),typeof m[0][0][0]=="number"&&(T=[m]);let P=function(pe,be,Se){let Le=null;return pe.length*be.length===0&&(Se===0?Le=dq:Se===2?Le=pe:(Se===1||Se===3)&&(Le=pe.length===0?be:pe)),Le}(k,T,x);if(P)return P===dq?null:P;const R=[1/0,1/0,-1/0,-1/0],U=[1/0,1/0,-1/0,-1/0],V=function(pe,be,Se,Le,ze){const We=new u0(void 0,ok);let ct,nt,ft,wt,Nt,Wt;for(ft=0,wt=pe.length;ftLe[2]||Le[0]>Se[2]||Se[1]>Le[3]||Le[1]>Se[3])&&(ze===0?We=dq:ze===2?We=pe:(ze===1||ze===3)&&(We=pe.concat(be))),We}(k,T,R,U,x),P)return P===dq?null:P;const X=function(pe,be,Se,Le,ze,We){const ct=new _be(g4t),nt=[],ft=Math.min(Le[2],ze[2]);let wt,Nt,Wt;for(;pe.length!==0;){let Ft=pe.pop();if(nt.push(Ft),We===0&&Ft.point[0]>ft||We===2&&Ft.point[0]>Le[2])break;if(Ft.left){Nt=wt=ct.insert(Ft),Wt=ct.minNode(),wt=wt!==Wt?ct.prev(wt):null,Nt=ct.next(Nt);const Gt=wt?wt.key:null;let Ut;if(rO(Ft,Gt,We),Nt&&Cbe(Ft,Nt.key,pe)===2&&(rO(Ft,Gt,We),rO(Nt.key,Ft,We)),wt&&Cbe(wt.key,Ft,pe)===2){let qt=wt;qt=qt!==Wt?ct.prev(qt):null,Ut=qt?qt.key:null,rO(Gt,Ut,We),rO(Ft,Gt,We)}}else Ft=Ft.otherEvent,Nt=wt=ct.find(Ft),wt&&Nt&&(wt=wt!==Wt?ct.prev(wt):null,Nt=ct.next(Nt),ct.remove(Ft),Nt&&wt&&Cbe(wt.key,Nt.key,pe))}return nt}(V,0,0,R,U,x),ie=function(pe){let be,Se;const Le=function(ct){let nt,ft,wt,Nt,Wt;const Ft=[];for(ft=0,wt=ct.length;ft{ze[Wt]=!0,Wt=Le.length)&&Le[wt];);We.push(nt)}return We}(X),ue=[];for(let pe=0;pe{R.push(new Es(ue,V+(ue-U)/(X-U)*(ie-V)))}:(R,U,V,X,ie,ue)=>{R.push(new Es(U+(ue-V)/(ie-V)*(X-U),ue))};for(const R of b){const U=[];for(const V of R){if(V.length<=2)continue;const X=[];for(let pe=0;pem&&P(X,be,Se,Le,ze,m):We>x?ct=m&&P(X,be,Se,Le,ze,m),ct>x&&We<=x&&P(X,be,Se,Le,ze,x)}let ie=V[V.length-1];const ue=k===0?ie.x:ie.y;ue>=m&&ue<=x&&X.push(ie),X.length&&(ie=X[X.length-1],X[0].x===ie.x&&X[0].y===ie.y||X.push(X[0]),U.push(X))}U.length&&T.push(U)}return T}function _4t(b,m){const x=ODe(Tbe(b),Tbe([m]),0);return x==null?[]:FDe(x)}function w4t(b,m,x=0){let T=Tbe(b,65536);const P=[];for(;m.valid();m.next()){const[R,U]=m.get();let V=R.x*65536,X=R.y*65536,ie=U.x*65536,ue=U.y*65536;const pe=ie-V,be=ue-X,Se=Math.hypot(pe,be);if(Se===0)continue;V-=pe*x,X-=be*x,ie+=pe*x,ue+=be*x;const Le=Math.trunc(be/Se*3),ze=-Math.trunc(pe/Se*3);P.push([[[V,X],[ie,ue],[ie+Le,ue+ze],[V+Le,X+ze],[V,X]]])}return P.length>0&&(T=ODe(T,P,2)),FDe(T,1/65536,128)}function Tbe(b,m=1){return[b.map(x=>x.map(k=>[k.x*m,k.y*m]))]}function FDe(b,m=1,x){return b.map(k=>k.map((T,P)=>{const R=T.map(U=>{let V=U[0],X=U[1];return x&&(V=Math.round(V/x)*x,X=Math.round(X/x)*x),new Es(V*m,X*m)._round()});return P>0&&R.reverse(),R}))}class Ebe{constructor(m,x){this.layoutVertexArray=new qa,this.indexArray=new tc,this.lineIndexArray=new yg,this.triangleSegments=new Po,this.lineSegments=new Po,this.programConfigurations=new qe(m.layers,{zoom:m.zoom,lut:m.lut}),this.uploaded=!1,x&&(this.elevatedLayoutVertexArray=new no)}update(m,x,k,T,P,R,U,V){this.programConfigurations.updatePaintArrays(m,x,P,k,T,R,U,V)}isEmpty(){return this.layoutVertexArray.length===0}needsUpload(){return this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,e4t.members),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.lineIndexBuffer=m.createIndexBuffer(this.lineIndexArray),this.elevatedLayoutVertexArray&&this.elevatedLayoutVertexArray.length>0&&(this.elevatedLayoutVertexBuffer=m.createVertexBuffer(this.elevatedLayoutVertexArray,t4t.members))),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.elevatedLayoutVertexBuffer&&this.elevatedLayoutVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.lineIndexBuffer.destroy(),this.programConfigurations.destroy(),this.triangleSegments.destroy(),this.lineSegments.destroy())}populatePaintArrays(m,x,k,T,P,R,U){this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,x,k,T,P,R,void 0,U)}}class hq{constructor(m){this.zoom=m.zoom,this.pixelRatio=m.pixelRatio,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.patternFeatures=[],this.lut=m.lut,this.bufferData=new Ebe(m,!1),this.elevationBufferData=new Ebe(m,!0),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.projection=m.projection,this.elevationMode=this.layers[0].layout.get("fill-elevation-reference"),this.sourceLayerIndex=m.sourceLayerIndex,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,T){this.hasPattern=vbe("fill",this.layers,this.pixelRatio,x);const P=this.layers[0].layout.get("fill-sort-key"),R=[];for(const{feature:U,id:V,index:X,sourceLayerIndex:ie}of m){const ue=this.layers[0]._featureFilter.needGeometry,pe=Ha(U,ue);if(!this.layers[0]._featureFilter.filter(new Aa(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),pe,k))continue;const be=P?P.evaluate(pe,{},k,x.availableImages):void 0,Se={id:V,properties:U.properties,type:U.type,sourceLayerIndex:ie,index:X,geometry:ue?pe.geometry:Vr(U,k,T),patterns:{},sortKey:be};R.push(Se)}P&&R.sort((U,V)=>U.sortKey-V.sortKey);for(const U of R){const{geometry:V,index:X,sourceLayerIndex:ie}=U;if(this.hasPattern){const ue=bbe("fill",this.layers,U,this.zoom,this.pixelRatio,x);this.patternFeatures.push(ue)}else this.addFeature(U,V,X,k,{},x.availableImages,x.brightness,x.elevationFeatures);x.featureIndex.insert(m[X].feature,V,X,ie,this.index)}}update(m,x,k,T,P,R,U){this.bufferData.update(m,x,k,T,P,R,U,this.worldview),this.elevationBufferData.update(m,x,k,T,P,R,U,this.worldview),this.elevatedStructures&&this.elevatedStructures.update(m,x,k,T,P,R,U,this.worldview)}addFeatures(m,x,k,T,P,R){for(const U of this.patternFeatures)this.addFeature(U,U.geometry,U.index,x,k,T,R,m.elevationFeatures)}isEmpty(){return this.bufferData.isEmpty()&&this.elevationBufferData.isEmpty()}uploadPending(){return!this.uploaded||this.bufferData.needsUpload()||this.elevationBufferData.needsUpload()}upload(m){this.bufferData.upload(m),this.elevationBufferData.upload(m),this.elevatedStructures&&this.elevatedStructures.upload(m)}destroy(){this.bufferData.destroy(),this.elevationBufferData.destroy(),this.elevatedStructures&&this.elevatedStructures.destroy()}addFeature(m,x,k,T,P,R=[],U,V){const X=sO(x,500);this.elevationMode!=="none"?this.addElevatedRoadFeature(m,X,T,k,V):this.addGeometry(X,this.bufferData),this.bufferData.populatePaintArrays(m,k,P,R,T,U,this.worldview),this.elevationBufferData.populatePaintArrays(m,k,P,R,T,U,this.worldview)}getUnevaluatedPortalGraph(){return this.elevatedStructures?this.elevatedStructures.unevaluatedPortals:void 0}setEvaluatedPortalGraph(m,x,k,T,P){this.elevatedStructures&&(this.elevatedStructures.construct(m),this.elevatedStructures.populatePaintArrays(x,k,T,P,this.worldview))}addElevatedRoadFeature(m,x,k,T,P){const R=new Array,U=zo.getElevationFeature(m,P);if(!U)return void this.addGeometry(x,this.bufferData);{const X=this.clipPolygonsToTile(x,1);X.length>0&&R.push({polygons:X,elevationFeature:U,elevationTileID:k})}const V={guardRailEnabled:this.layers[0].layout.get("fill-construct-bridge-guard-rail").evaluate(m,{},k),featureIndex:T};for(const X of R)if(X.elevationFeature){if(this.elevationMode==="hd-road-base"){this.elevatedStructures||(this.elevatedStructures=new Cx(X.elevationTileID,this.layers,this.zoom,this.lut));const ue=X.elevationFeature.isTunnel();let pe=0;m.properties.hasOwnProperty(Do)&&(pe=+m.properties[Do]),this.elevatedStructures.addPortalCandidates(X.elevationFeature.id,X.polygons,ue,X.elevationFeature,pe)}X.elevationFeature.constantHeight==null&&(X.polygons=this.prepareElevatedPolygons(X.polygons,X.elevationFeature,X.elevationTileID));const ie=new Vo(k,X.elevationTileID);this.addElevatedGeometry(X.polygons,ie,X.elevationFeature,this.elevationMode==="hd-road-base"?0:.05,T,V)}}addElevatedGeometry(m,x,k,T,P,R){const U={elevation:k,elevationSampler:x,bias:T,index:P,featureInfo:R},[V,X]=this.addGeometry(m,this.elevationBufferData,U);this.elevationBufferData.heightRange==null?this.elevationBufferData.heightRange={min:V,max:X}:(this.elevationBufferData.heightRange.min=Math.min(this.elevationBufferData.heightRange.min,V),this.elevationBufferData.heightRange.max=Math.max(this.elevationBufferData.heightRange.max,X))}addGeometry(m,x,k){let T=Number.POSITIVE_INFINITY,P=Number.NEGATIVE_INFINITY,R=null;k&&(R=k.elevationSampler.constantElevation(k.elevation,k.bias),R!=null&&(T=R,P=R));const U=(V,X,ie)=>{if(k!=null)if(X.push(V),R!=null)x.elevatedLayoutVertexArray.emplaceBack(R),ie.push(R);else{const ue=k.elevationSampler.pointElevation(V,k.elevation,k.bias);x.elevatedLayoutVertexArray.emplaceBack(ue),ie.push(ue),T=Math.min(T,ue),P=Math.max(P,ue)}};for(const V of m){let X=0;for(const nt of V)X+=nt.length;const ie=x.triangleSegments.prepareSegment(X,x.layoutVertexArray,x.indexArray),ue=ie.vertexLength,pe=[],be=[],Se=[],Le=[],ze=[],We=x.layoutVertexArray.length;for(const nt of V){if(nt.length===0)continue;nt!==V[0]&&be.push(pe.length/2);const ft=x.lineSegments.prepareSegment(nt.length,x.layoutVertexArray,x.lineIndexArray),wt=ft.vertexLength;k&&ze.push(x.layoutVertexArray.length-We),U(nt[0],Se,Le),x.layoutVertexArray.emplaceBack(nt[0].x,nt[0].y),x.lineIndexArray.emplaceBack(wt+nt.length-1,wt),pe.push(nt[0].x),pe.push(nt[0].y);for(let Nt=1;Nt0&&k&&this.elevationMode==="hd-road-base"){const nt=k.elevation.isTunnel(),ft=k.elevation.safeArea,wt=this.elevatedStructures.addVertices(Se,Le);this.elevatedStructures.addTriangles(ct,wt,nt);const Nt=ze.length;if(Nt>0){for(let Wt=0;Wt=k&&be.max.x<=P&&be.min.y>=T&&be.max.y<=R?V:X).push(pe)}if(V.length===m.length)return m;const ie=[new Es(k,T),new Es(P,T),new Es(P,R),new Es(k,R),new Es(k,T)],ue=V;for(const pe of X)ue.push(..._4t(pe,ie));return ue}}let zDe,BDe,$De,UDe;Kn(hq,"FillBucket",{omit:["layers","patternFeatures"]}),Kn(Ebe,"FillBufferData"),Kn(Cx,"ElevatedStructures");class mq{constructor(m,x,k,T){if(this.triangleCount=x.length/3,this.min=new Es(0,0),this.max=new Es(0,0),this.xScale=0,this.yScale=0,this.cellsX=0,this.cellsY=0,this.cells=[],this.payload=[],this.triangleCount===0||m.length===0)return;const[P,R]=[m[0].clone(),m[0].clone()];for(let ue=1;ueue.cellIdx-pe.cellIdx||ue.triIdx-pe.triIdx);let ie=0;for(;iethis.max.x||this.min.x>m.x||m.y>this.max.y||this.min.y>m.y)return;const k=y_(m.x-this.min.x,this.xScale,this.cellsX),T=y_(m.y-this.min.y,this.yScale,this.cellsY),P=this.cells[T*this.cellsX+k];if(P){this._lazyInitLookup();for(let R=0;Rthis.max.x||this.min.x>x.x||m.y>this.max.y||this.min.y>x.y)return;this._lazyInitLookup();const T=y_(m.x-this.min.x,this.xScale,this.cellsX),P=y_(x.x-this.min.x,this.xScale,this.cellsX),R=y_(m.y-this.min.y,this.yScale,this.cellsY),U=y_(x.y-this.min.y,this.yScale,this.cellsY);for(let V=R;V<=U;V++)for(let X=T;X<=P;X++){const ie=this.cells[V*this.cellsX+X];if(ie)for(let ue=0;uex.fqid),this.index=m.index,this.hasPattern=!1,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.footprints=[],this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){for(const k of this.footprints)x.push({footprint:k,id:m})}updateAppearances(m,x,k,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,T){const P=[];for(const{feature:R,id:U,index:V,sourceLayerIndex:X}of m){const ie=this.layers[0]._featureFilter.needGeometry,ue=Ha(R,ie);if(!this.layers[0]._featureFilter.filter(new Aa(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),ue,k))continue;const pe={id:U,properties:R.properties,type:R.type,sourceLayerIndex:X,index:V,geometry:ie?ue.geometry:Vr(R,k,T),patterns:{}};P.push(pe)}for(const R of P){const{geometry:U,index:V,sourceLayerIndex:X}=R;this.addFeature(R,U,V,k,{},x.availableImages,x.brightness),x.featureIndex.insert(m[V].feature,U,V,X,this.index)}}isEmpty(){return this.footprints.length===0}uploadPending(){return!1}upload(m){}update(m,x,k,T,P,R,U){}destroy(){}addFeature(m,x,k,T,P,R=[],U){for(const V of sO(x,2)){const X=[],ie=[],ue=[],pe=new Es(1/0,1/0),be=new Es(-1/0,-1/0);for(const ze of V)if(ze.length!==0){ze!==V[0]&&ue.push(ie.length/2);for(let We=0;Wem.max.x||b.max.xm.max.y||b.max.ynew Es((V.x+P.x*Bn)*U-R.x*Bn,(V.y+P.y*Bn)*U-R.y*Bn))}return Mbe(x,T,b.indices,0,b.indices.length,0,0)}function KDe(b,m,x,k){const T=Math.pow(2,k.z-x.z);return new Es((b+x.x*Bn)*T-k.x*Bn,(m+x.y*Bn)*T-k.y*Bn)}function YDe(b,m){const x=[];m.grid.queryPoint(b,x);const k=m.indices,T=m.vertices;for(let P=0;P0&&(k.length>1&&x.push(k),k=[])}return k.length>1&&x.push(k),x}const Pbe=pa.types,P4t=["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"],L4t=["fill-extrusion-flood-light-ground-radius"],D4t=Math.pow(2,13),R4t=Math.pow(2,15)-1,gq=new Es(0,1),Kj=2147483648,yq=1073741824;function iO(b,m,x,k,T,P,R,U){b.emplaceBack((m<<1)+R,(x<<1)+P,(Math.floor(k*D4t)<<1)+T,Math.round(U))}function oO(b,m,x){b.emplaceBack(m.x*Bn,m.y*Bn,x?1:0)}function vq(b,m,x,k,T,P){b.emplaceBack(m.x,m.y,(x.x<<1)+k,(x.y<<1)+T,P)}function lO(b,m,x){b.emplaceBack(m.x,m.y,m.z,x[0]*16384,x[1]*16384,x[2]*16384)}class QDe{constructor(){this.vertexOffset=0,this.vertexCount=0,this.indexOffset=0,this.indexCount=0}}class Lbe{constructor(){this.centroidXY=new Es(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 Es(Number.MAX_VALUE,Number.MAX_VALUE),this.max=new Es(-Number.MAX_VALUE,-Number.MAX_VALUE),this.height=0,this.buildingId=0,this.groupCentroidPos=new Es(0,0)}span(){return new Es(this.max.x-this.min.x,this.max.y-this.min.y)}}class Dbe{constructor(){this.acc=new Es(0,0),this.accCount=0,this.centroidDataIndex=0}startRing(m,x){m.min.x===Number.MAX_VALUE&&(m.min.x=m.max.x=x.x,m.min.y=m.max.y=x.y)}appendEdge(m,x,k){this.accCount++,this.acc._add(x);let T=!!this.borders;x.xm.max.x&&(m.max.x=x.x,T=!0),x.ym.max.y&&(m.max.y=x.y,T=!0),((x.x===0||x.x===Bn)&&x.x===k.x)!=((x.y===0||x.y===Bn)&&x.y===k.y)&&this.processBorderOverlap(x,k),T&&this.checkBorderIntersection(x,k)}checkBorderIntersection(m,x){x.x<0!=m.x<0&&this.addBorderIntersection(0,Dr(x.y,m.y,(0-x.x)/(m.x-x.x))),x.x>Bn!=m.x>Bn&&this.addBorderIntersection(1,Dr(x.y,m.y,(Bn-x.x)/(m.x-x.x))),x.y<0!=m.y<0&&this.addBorderIntersection(2,Dr(x.x,m.x,(0-x.y)/(m.y-x.y))),x.y>Bn!=m.y>Bn&&this.addBorderIntersection(3,Dr(x.x,m.x,(Bn-x.y)/(m.y-x.y)))}addBorderIntersection(m,x){this.borders||(this.borders=[[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE],[Number.MAX_VALUE,-Number.MAX_VALUE]]);const k=this.borders[m];xk[1]&&(k[1]=x)}processBorderOverlap(m,x){if(m.x===x.x){if(m.y===x.y)return;const k=m.x===0?0:1;this.addBorderIntersection(k,x.y),this.addBorderIntersection(k,m.y)}else{const k=m.y===0?2:3;this.addBorderIntersection(k,x.x),this.addBorderIntersection(k,m.x)}}centroid(){return this.accCount===0?new Es(0,0):new Es(Math.floor(Math.max(0,this.acc.x)/this.accCount),Math.floor(Math.max(0,this.acc.y)/this.accCount))}intersectsCount(){return this.borders?this.borders.reduce((m,x)=>m+ +(x[0]!==Number.MAX_VALUE),0):0}}function XDe(b,m){const x=b.add(m)._unit(),k=Qe(b.x*x.x+b.y*x.y,-1,1);var T,P,R;return R=Math.acos(k),Math.min(4,Math.max(-4,Math.tan(R)))/4*R4t*((T=b).x*(P=m).y-T.y*P.x<0?-1:1)}const O4t=[b=>b.x<0,b=>b.x>Bn,b=>b.y<0,b=>b.y>Bn];function F4t(b,m,x,k){const T=[4];if(k===0)return T;x._mult(k);const P=b.sub(x),R=m.sub(x),U=[b,m,P,R];for(let V=0;V<4;V++)for(const X of U)if(O4t[V](X)){T.push(V);break}return T}class Rbe{constructor(m){this.groundRadiusArray=null,this.groundRadiusBuffer=null,this.vertexArray=new AC,this.indexArray=new tc,this.programConfigurations=new qe(m.layers,{zoom:m.zoom,lut:m.lut},x=>L4t.includes(x)),this._segments=new Po,this.hiddenByLandmarkVertexArray=new A6,this._segmentToGroundQuads={},this._segmentToGroundQuads[0]=[],this._segmentToRegionTriCounts={},this._segmentToRegionTriCounts[0]=[0,0,0,0,0],this.regionSegments={},this.regionSegments[4]=new Po}getDefaultSegment(){return this.regionSegments[4]}hasData(){return this.vertexArray.length!==0}addData(m,x,k,T=!1){const P=m.length;if(P>2){let R=Math.max(0,this._segments.get().length-1);const U=this._segments._prepareSegment(4*P,this.vertexArray.length,2*this._segmentToGroundQuads[R].length);let V;R!==this._segments.get().length-1&&(R++,this._segmentToGroundQuads[R]=[],this._segmentToRegionTriCounts[R]=[0,0,0,0,0]);{const X=m[0],ie=m[1];V=XDe(X.sub(m[P-1])._perp()._unit(),ie.sub(X)._perp()._unit())}for(let X=0;XT.region-P.region);for(let k=0;kV+X,0);let U=0;for(let V=0;V<=4;V++){const X=R[V];if(X!==0){let ie=this.regionSegments[V];ie||(ie=this.regionSegments[V]=new Po);const ue={vertexOffset:P.vertexOffset,primitiveOffset:P.primitiveOffset+U,vertexLength:P.vertexLength,primitiveLength:X};ie.get().push(ue)}U+=X}for(let V=0;V0?this.hiddenByLandmarkVertexBuffer=m.createVertexBuffer(this.hiddenByLandmarkVertexArray,T4t.members,!0):this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.updateData(this.hiddenByLandmarkVertexArray),this._needsHiddenByLandmarkUpdate=!1)}destroy(){if(this.vertexBuffer){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.hiddenByLandmarkVertexBuffer&&this.hiddenByLandmarkVertexBuffer.destroy(),this.groundRadiusBuffer&&this.groundRadiusBuffer.destroy(),this._segments&&this._segments.destroy(),this.programConfigurations.destroy();for(let m=0;m<=4;m++){const x=this.regionSegments[m];x&&x.destroy()}}}}class bq{constructor(m){this.zoom=m.zoom,this.canonical=m.canonical,this.overscaling=m.overscaling,this.layers=m.layers,this.pixelRatio=m.pixelRatio,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.edgeRadius=0,this.projection=m.projection,this.activeReplacements=[],this.replacementUpdateTime=0,this.centroidData=[],this.footprintIndices=new tc,this.footprintVertices=new qa,this.footprintSegments=[],this.layoutVertexArray=new xg,this.centroidVertexArray=new JU,this.wallVertexArray=new GR,this.indexArray=new tc,this.programConfigurations=new qe(m.layers,{zoom:m.zoom,lut:m.lut},x=>P4t.includes(x)),this.segments=new Po,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.groundEffect=new Rbe(m),this.maxHeight=0,this.partLookup={},this.triangleSubSegments=[],this.polygonSegments=[],this.buildingGroups=new Map,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,T){this.features=[],this.hasPattern=vbe("fill-extrusion",this.layers,this.pixelRatio,x),this.featuresOnBorder=[],this.borderFeatureIndices=[[],[],[],[]],this.borderDoneWithNeighborZ=[-1,-1,-1,-1],this.selfDEMTileTimestamp=Number.MAX_VALUE,this.borderDEMTileTimestamp=[Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE],this.tileToMeter=cn(k),this.edgeRadius=this.layers[0].layout.get("fill-extrusion-edge-radius")/this.tileToMeter,this.wallMode=this.layers[0].paint.get("fill-extrusion-line-width").constantOr(1)!==0;for(const{feature:P,id:R,index:U,sourceLayerIndex:V}of m){const X=this.layers[0]._featureFilter.needGeometry,ie=Ha(P,X);if(!this.layers[0]._featureFilter.filter(new Aa(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),ie,k))continue;const ue={id:R,sourceLayerIndex:V,index:U,geometry:X?ie.geometry:Vr(P,k,T),properties:P.properties,type:P.type,patterns:{}},pe=this.layoutVertexArray.length,be=Pbe[ue.type]==="Polygon";if(this.hasPattern)this.features.push({featureId:P.id,feature:bbe("fill-extrusion",this.layers,ue,this.zoom,this.pixelRatio,x)});else if(this.wallMode)for(const Se of ue.geometry)for(const Le of ZDe(Se,be))this.addFeature(P.id,ue,[Le],U,k,{},x.availableImages,T,x.brightness);else this.addFeature(P.id,ue,ue.geometry,U,k,{},x.availableImages,T,x.brightness);x.featureIndex.insert(P,ue.geometry,U,V,this.index,pe)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles(),this.groundEffect.prepareBorderSegments(),this.polygonSegments.length=0}addFeatures(m,x,k,T,P,R){for(const{featureId:U,feature:V}of this.features){const X=Pbe[V.type]==="Polygon",{geometry:ie}=V;if(this.wallMode)for(const ue of ie)for(const pe of ZDe(ue,X))this.addFeature(U,V,[pe],V.index,x,k,T,P,R);else this.addFeature(U,V,ie,V.index,x,k,T,P,R)}this._finalizeBuildingGroups(),this.sortBorders(),this.projection.name==="mercator"&&this.splitToSubtiles()}update(m,x,k,T,P,R,U){this.programConfigurations.updatePaintArrays(m,x,P,k,T,R,U,this.worldview),this.groundEffect.update(m,x,P,k,T,R,U,this.worldview)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,A4t),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.wallVertexBuffer=m.createVertexBuffer(this.wallVertexArray,C4t.members),this.layoutVertexExtArray&&(this.layoutVertexExtBuffer=m.createVertexBuffer(this.layoutVertexExtArray,E4t.members,!0)),this.groundEffect.upload(m)),this.groundEffect.uploadPaintProperties(m),this.programConfigurations.upload(m),this.uploaded=!0}uploadCentroid(m){this.groundEffect.uploadHiddenByLandmark(m),this.needsCentroidUpdate&&(!this.centroidVertexBuffer&&this.centroidVertexArray.length>0?this.centroidVertexBuffer=m.createVertexBuffer(this.centroidVertexArray,S4t.members,!0):this.centroidVertexBuffer&&this.centroidVertexBuffer.updateData(this.centroidVertexArray),this.needsCentroidUpdate=!1)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.centroidVertexBuffer&&this.centroidVertexBuffer.destroy(),this.layoutVertexExtBuffer&&this.layoutVertexExtBuffer.destroy(),this.groundEffect.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}addFeature(m,x,k,T,P,R,U,V,X){const ie=this.layers[0].paint.get("fill-extrusion-flood-light-ground-radius").evaluate(x,{})/this.tileToMeter,ue=[new Es(0,0),new Es(Bn,Bn)],pe=V.projection,be=pe.name==="globe",Se=this.wallMode||Pbe[x.type]==="Polygon",Le=new Dbe;Le.centroidDataIndex=this.centroidData.length;const ze=new Lbe;ze.buildingId=m,x.properties&&x.properties.hasOwnProperty("building_id")&&(ze.buildingId=Number(x.properties.building_id)),Le.buildingId=ze.buildingId;const We=this.layers[0].paint.get("fill-extrusion-base").evaluate(x,{},P)<=0,ct=this.layers[0].paint.get("fill-extrusion-height").evaluate(x,{},P);let nt;if(ze.height=ct,ze.vertexArrayOffset=this.layoutVertexArray.length,ze.groundVertexArrayOffset=this.groundEffect.vertexArray.length,be&&!this.layoutVertexExtArray&&(this.layoutVertexExtArray=new N6),this.wallMode){if(be)return void Yn("Non zero fill-extrusion-line-width is not yet supported on globe.");if(k.length!==1)return;nt=function(Ut){const qt=Ut[0].x===Ut[Ut.length-1].x&&Ut[0].y===Ut[Ut.length-1].y;(function(Rn){let Tn=0;const sr=Rn.length;for(let hr=0;hr=0})(Ut)||(Ut=Ut.reverse());const qs={geometry:[],joinNormals:[],indices:[]},Xs=[],sn=[],Js=[];let fn=Ut.length;for(;fn>=2&&Ut[fn-1].equals(Ut[fn-2]);)fn--;if(fn<(qt?3:2))return qs;let Os,en,on,gn,Cn,ar=0;for(;ar0;let jr="miter";const Sa=2;jr==="miter"&&hr>Sa&&(jr="bevel"),jr==="bevel"&&(hr>100&&(jr="flipbevel"),hr{const Qi=new Es(Ca.x,Ca.y),Ii=new Es(Ca.x,Ca.y);Qi.x+=Ni.x*Ol,Qi.y+=Ni.y*Ol,Ii.x-=Ni.x*Math.max(Ga,1),Ii.y-=Ni.y*Math.max(Ga,1),Js.push(Ni),Xs.push(Qi),sn.push(Ii)};if(jr==="miter")Tn._mult(hr),_i(Os,Tn,0,0);else if(jr==="flipbevel")Tn=Cn.mult(-1),_i(Os,Tn,0,0),_i(Os,Tn.mult(-1),0,0);else{const Ca=-Math.sqrt(hr*hr-1),Ni=Ur?Ca:0,Ga=Ur?0:Ca;en&&_i(Os,gn,Ni,Ga),on&&_i(Os,Cn,Ni,Ga)}}qs.geometry=[...Xs,...sn.reverse(),Xs[0]],qs.joinNormals=[...Js,...Js.reverse(),Js[Js.length-1]];const Fn=qs.geometry.length-1;for(let Rn=0;RnUt<(qt.length-1)/2||Ut===qt.length-1,wt=this.wallMode?[k]:sO(k,500);for(let Ut=wt.length-1;Ut>=0;Ut--){const qt=wt[Ut];(qt.length===0||B4t(qt[0]))&&wt.splice(Ut,1)}let Nt;if(be)Nt=aRe(wt,ue,P);else{Nt=[];for(const Ut of wt)Nt.push({polygon:Ut,bounds:ue})}const Wt=Se?this.edgeRadius:0,Ft=Wt>0&&this.zoom<17,Gt=(Ut,qt)=>{if(Ut.length===0)return!1;const zs=Ut[Ut.length-1];return qt.x===zs.x&&qt.y===zs.y};for(const{polygon:Ut,bounds:qt}of Nt){let zs=0,qs=0;for(const fn of Ut)Se&&!fn[0].equals(fn[fn.length-1])&&fn.push(fn[0]),qs+=Se?fn.length-1:fn.length;const Xs=this.segments.prepareSegment((Se?5:4)*qs,this.layoutVertexArray,this.indexArray);ze.footprintSegIdx<0&&(ze.footprintSegIdx=this.footprintSegments.length),ze.polygonSegIdx<0&&(ze.polygonSegIdx=this.polygonSegments.length);const sn={triangleArrayOffset:this.indexArray.length,triangleCount:0,triangleSegIdx:this.segments.segments.length-1},Js=new QDe;if(Js.vertexOffset=this.footprintVertices.length,Js.indexOffset=3*this.footprintIndices.length,Js.ringIndices=[],Se){const fn=[],Os=[];zs=Xs.vertexLength;for(let on=0;on4&&sRe(Os[Os.length-2],Os[0],Os[1]),on=Wt?z4t(Os[Os.length-2],Os[0],Os[1],Wt):0;const gn=[];let Cn,ar,Fn;ar=Os[1].sub(Os[0])._perp()._unit();let Rn=!0;for(let Tn=1,sr=0;Tn0?1:0,Ni=hr.dist(Ur);if(sr+Ni>32768&&(sr=0),Wt){Fn=jr.sub(Ur)._perp()._unit();let Ii=eRe(hr,Ur,jr,JDe(ar,Fn),Wt);isNaN(Ii)&&(Ii=0);const Ro=Ur.sub(hr)._unit();hr=hr.add(Ro.mult(on))._round(),Ur=Ur.add(Ro.mult(-Ii))._round(),on=Ii,ar=Fn,We&&this.zoom>=17&&(Gt(gn,hr)||gn.push(hr),Gt(gn,Ur)||gn.push(Ur))}const Ga=Xs.vertexLength,Ol=Os.length>4&&sRe(hr,Ur,jr);let Qi=nRe(sr,en,Rn);if(iO(this.layoutVertexArray,hr.x,hr.y,_i,Ca,0,0,Qi),iO(this.layoutVertexArray,hr.x,hr.y,_i,Ca,0,1,Qi),this.wallMode){const Ii=ft(Tn-1,Os),Ro=nt.joinNormals[Tn-1];oO(this.wallVertexArray,Ro,Ii),oO(this.wallVertexArray,Ro,Ii)}if(sr+=Ni,Qi=nRe(sr,Ol,!Rn),en=Ol,iO(this.layoutVertexArray,Ur.x,Ur.y,_i,Ca,0,0,Qi),iO(this.layoutVertexArray,Ur.x,Ur.y,_i,Ca,0,1,Qi),this.wallMode){const Ii=ft(Tn,Os),Ro=nt.joinNormals[Tn];oO(this.wallVertexArray,Ro,Ii),oO(this.wallVertexArray,Ro,Ii)}if(Xs.vertexLength+=4,this.indexArray.emplaceBack(Ga+0,Ga+1,Ga+2),this.indexArray.emplaceBack(Ga+1,Ga+3,Ga+2),Xs.primitiveLength+=2,Wt){const Ii=zs+(Tn===1?Os.length-2:Tn-2),Ro=Tn===1?zs:Ii+1;if(this.indexArray.emplaceBack(Ga+1,Ii,Ga+3),this.indexArray.emplaceBack(Ii,Ro,Ga+3),Xs.primitiveLength+=2,Cn===void 0&&(Cn=Ga),!Obe(jr,Os[Tn],qt)){const Ml=Tn===Os.length-1?Cn:Xs.vertexLength;this.indexArray.emplaceBack(Ga+2,Ga+3,Ml),this.indexArray.emplaceBack(Ga+3,Ml+1,Ml),this.indexArray.emplaceBack(Ga+3,Ro,Ml+1),Xs.primitiveLength+=3}Rn=!Rn}if(be){const Ii=this.layoutVertexExtArray,Ro=pe.projectTilePoint(hr.x,hr.y,P),Ml=pe.projectTilePoint(Ur.x,Ur.y,P),Yd=pe.upVector(P,hr.x,hr.y),Il=pe.upVector(P,Ur.x,Ur.y);lO(Ii,Ro,Yd),lO(Ii,Ro,Yd),lO(Ii,Ml,Il),lO(Ii,Ml,Il)}}Se&&(zs+=Os.length-1),We&&Wt&&this.zoom>=17&&(gn.length!==0&&Gt(gn,gn[0])&&gn.pop(),this.groundEffect.addData(gn,qt,ie,Wt>0))}this.footprintSegments.push(Js),sn.triangleCount=this.indexArray.length-sn.triangleArrayOffset,this.polygonSegments.push(sn),++ze.footprintSegLen,++ze.polygonSegLen}if(ze.vertexCount=this.layoutVertexArray.length-ze.vertexArrayOffset,ze.groundVertexCount=this.groundEffect.vertexArray.length-ze.groundVertexArrayOffset,ze.vertexCount!==0){if(ze.centroidXY=Le.borders?gq:this.encodeCentroid(Le,ze),x.properties&&x.properties.hasOwnProperty("building_id")){const Ut=ze.buildingId;let qt=this.buildingGroups.get(Ut);qt||(qt={accX:0,accY:0,accCount:0,mergedMin:new Es(Number.MAX_VALUE,Number.MAX_VALUE),mergedMax:new Es(-Number.MAX_VALUE,-Number.MAX_VALUE),partIndices:[]},this.buildingGroups.set(Ut,qt)),qt.accX+=Le.acc.x,qt.accY+=Le.acc.y,qt.accCount+=Le.accCount,qt.mergedMin.x=Math.min(qt.mergedMin.x,ze.min.x),qt.mergedMin.y=Math.min(qt.mergedMin.y,ze.min.y),qt.mergedMax.x=Math.max(qt.mergedMax.x,ze.max.x),qt.mergedMax.y=Math.max(qt.mergedMax.y,ze.max.y),qt.partIndices.push(this.centroidData.length)}if(this.centroidData.push(ze),Le.borders){this.featuresOnBorder.push(Le);const Ut=this.featuresOnBorder.length-1;for(let qt=0;qtthis.featuresOnBorder[x].borders[m][0]-this.featuresOnBorder[k].borders[m][0])}splitToSubtiles(){const m=[];for(let U=0;UBn),ie=2*X+(+(V.min.x+V.max.x>Bn)^X);for(let ue=0;ueU.triangleSegmentIdx===V.triangleSegmentIdx?U.subtile-V.subtile:U.triangleSegmentIdx-V.triangleSegmentIdx);let k=0,T=0,P=0;for(const U of m){if(U.triangleSegmentIdx!==k)break;P++}const R=m.length;for(;T!==m.length;){k=m[T].triangleSegmentIdx;let U=0,V=T,X=T;for(let ie=V;ie0&&this.triangleSubSegments.push({segment:be,min:ue,max:pe}),V=X;for(let Se=V;Se[Le[0]*(1-We[0])+ze[0]*We[0],Le[1]*(1-We[1])+ze[1]*We[1]],be=[],Se=[];for(const Le of this.triangleSubSegments){be[0]=Le.min.x/Bn,be[1]=Le.min.y/Bn,Se[0]=Le.max.x/Bn,Se[1]=Le.max.y/Bn;const ze=pe(ie,ue,be),We=pe(ie,ue,Se);if(new eo([ze[0],ze[1],P],[We[0],We[1],R]).intersectsPrecise(k)===0){X&&(T.segments.push(X),X=void 0);continue}const ct=Le.segment;X&&X.vertexOffset!==ct.vertexOffset&&(T.segments.push(X),X=void 0),X?(X.vertexLength+=ct.vertexLength,X.primitiveLength+=ct.primitiveLength):X={vertexOffset:ct.vertexOffset,primitiveLength:ct.primitiveLength,vertexLength:ct.vertexLength,primitiveOffset:ct.primitiveOffset,sortKey:void 0,vaos:{}}}return X&&T.segments.push(X),T}encodeCentroid(m,x){const k=m.centroid(),T=x.span(),P=Math.min(7,Math.round(T.x*this.tileToMeter/10)),R=Math.min(6,Math.round(T.y*this.tileToMeter/10));return new Es(Qe(k.x,1,8191)<<3|P,Qe(k.y,1,8191)<<3|R)}encodeBorderCentroid(m){if(!m.borders)return new Es(0,0);const x=m.borders,k=Number.MAX_VALUE;if(x[0][0]!==k||x[1][0]!==k){const T=x[0][0]!==k?0:1;return new Es(6|(x[0][0]!==k?0:65528),(x[T][0]+x[T][1])/2<<3|6)}{const T=x[2][0]!==k?2:3;return new Es((x[T][0]+x[T][1])/2<<3|6,6|(x[2][0]!==k?0:65528))}}showCentroid(m){const x=this.centroidData[m.centroidDataIndex];if(x.flags&=Kj,x.groupCentroidPos.x!==0||x.groupCentroidPos.y!==0){const k=x.span(),T=Math.min(7,Math.round(k.x*this.tileToMeter/10)),P=Math.min(6,Math.round(k.y*this.tileToMeter/10));x.centroidXY=new Es(Qe(x.groupCentroidPos.x,1,8191)<<3|T,Qe(x.groupCentroidPos.y,1,8191)<<3|P)}else x.centroidXY=new Es(0,0);this.writeCentroidToBuffer(x)}writeCentroidToBuffer(m){this.groundEffect.updateHiddenByLandmark(m);const x=m.vertexArrayOffset,k=m.vertexCount+m.vertexArrayOffset,T=-1073741824&m.flags?gq:m.centroidXY,P=this.centroidVertexArray.geta_centroid_pos0(x);if(this.centroidVertexArray.geta_centroid_pos1(x)!==T.y||P!==T.x){for(let R=x;RV.max.x||V.min.x>R.max.x||R.min.y>V.max.y||V.min.y>R.max.y||R.footprint.buildingIds.has(V.buildingId)&&(V.flags|=R.clipMask!==xq.None?-1073741824:Kj);else for(const V of this.centroidData)if(!(V.flags&Kj||V.flags&yq||R.min.x>V.max.x||V.min.x>R.max.x||R.min.y>V.max.y||V.min.y>R.max.y))for(let X=0;Xx!=be>x&&m<(this.footprintVertices.int16[2*(ie+R.vertexOffset)+0]-ue)*(x-pe)/(be-pe)+ue&&(T=!T)}U=V}}return T}getHeightAtTileCoord(m,x){let k=Number.NEGATIVE_INFINITY,T=!0;const P=4*(m+Bn)*Bn+(x+Bn);if(this.partLookup.hasOwnProperty(P)){const R=this.partLookup[P];return R?{height:R.height,hidden:!!(R.flags&Kj)}:void 0}for(const R of this.centroidData)m>R.max.x||R.min.x>m||x>R.max.y||R.min.y>x||R.height<=k||this.footprintContainsPoint(m,x,R)&&(k=R.height,this.partLookup[P]=R,T=!!(R.flags&Kj));if(k!==Number.NEGATIVE_INFINITY)return{height:k,hidden:T};this.partLookup[P]=void 0}}function JDe(b,m){const x=b.add(m)._unit();return b.x*x.x+b.y*x.y}function z4t(b,m,x,k){const T=m.sub(b)._perp()._unit(),P=x.sub(m)._perp()._unit();return eRe(b,m,x,JDe(T,P),k)}function eRe(b,m,x,k,T){const P=Math.sqrt(1-k*k);return Math.min(b.dist(m)/3,m.dist(x)/3,T*P/k)}function Obe(b,m,x){return b.xx[1].x&&m.x>x[1].x||b.yx[1].y&&m.y>x[1].y}function tRe(b,m){return b.xm[1].x||b.ym[1].y}function B4t(b){return b.every(m=>m.x<=0)||b.every(m=>m.x>=Bn)||b.every(m=>m.y<=0)||b.every(m=>m.y>=Bn)}function sRe(b,m,x){if(b.x<0||b.x>=Bn||m.x<0||m.x>=Bn||x.x<0||x.x>=Bn)return!1;const k=x.sub(m),T=k.perp(),P=b.sub(m);return(k.x*P.x+k.y*P.y)/Math.sqrt((k.x*k.x+k.y*k.y)*(P.x*P.x+P.y*P.y))>-.866&&T.x*P.x+T.y*P.y<0}function nRe(b,m,x){const k=m?2|b:-3&b;return x?1|k:-2&k}function rRe(){const b=Math.PI/32,m=Math.tan(b),x=Ht;return x*Math.sqrt(1+2*m*m)-x}function aRe(b,m,x){const k=1<{for(const Ft of Nt)Se.push({polygon:Ft,bounds:Wt})},ze=Math.ceil(Math.log2(ie)),We=Math.ceil(Math.log2(ue)),ct=ze-We,nt=[];for(let Nt=0;Nt0?0:1);for(let Nt=0;NtWt+1?wt.push({polygons:Xs,bounds:Js,depth:Wt+1}):Le(Xs,Js)}if(sn.length){const Js=[new Es(Ft===0?qs:Gt.x,Ft===1?qs:Gt.y),Ut];nt.length>Wt+1?wt.push({polygons:sn,bounds:Js,depth:Wt+1}):Le(sn,Js)}}return Se}(b,m,Math.ceil((P-T)/11.25),Math.ceil((R-U)/11.25),1,(V,X,ie)=>{if(V===0)return .5*(X+ie);{const ue=Fs((x.y+X/Bn)/k);return(hn(.5*(Fs((x.y+ie/Bn)/k)+ue))*k-x.y)*Bn}})}function $4t(b,m,x,k,T,P){const R=Math.pow(2,k.z-T.z);for(let U=0;U=V[R]&&(U=m,V=b),U[R]T&&cRe(U,V,R,T),U[R]P&&cRe(V,U,R,P)}}function _q(b,m,x,k,T,P){const R=[];for(let U=0;U=k&&Se.x>=k||(be.x>=k?be=new Es(k,be.y+(k-be.x)/(Se.x-be.x)*(Se.y-be.y))._round():Se.x>=k&&(Se=new Es(k,be.y+(k-be.x)/(Se.x-be.x)*(Se.y-be.y))._round()),be.y>=T&&Se.y>=T||(be.y>=T?be=new Es(be.x+(T-be.y)/(Se.y-be.y)*(Se.x-be.x),T)._round():Se.y>=T&&(Se=new Es(be.x+(T-be.y)/(Se.y-be.y)*(Se.x-be.x),T)._round()),X&&be.equals(X[X.length-1])||(X=[be],R.push(X),P&&P.push({progress:{min:ze+uRe(We,ct,be)*Le,max:1},parentIndex:U,prevPoint:We,nextPoint:ct})),X.push(Se),P&&(P[P.length-1].progress.max=ze+uRe(We,ct,Se)*Le,P[P.length-1].nextPoint=ct)))))}if(P&&ue>0)for(let pe=ie;peX.t-ie.t);let R=0,U=0,V=[];for(k.push(V);R!==b.length;){if(U===P.length){for(;R!==b.length;)V.length!==0&&V[V.length-1].equals(b[R])||V.push(b[R]),R++;break}P[U].t<=R?(V.length!==0&&V[V.length-1].equals(P[U].point)||V.push(P[U].point),Math.trunc(P[U].t),U++):(V.length!==0&&V[V.length-1].equals(b[R])||V.push(b[R]),R++)}}function uRe(b,m,x){return b.x!==m.x?(x.x-b.x)/(m.x-b.x):b.y!==m.y?(x.y-b.y)/(m.y-b.y):0}function cO(b,m){return b.x*m.x+b.y*m.y}function hRe(b,m){if(b.length===1){let x=0;const k=m[x++];let T;for(;!T||k.equals(T);)if(T=m[x++],!T)return 1/0;for(;x{qs[0]=Xs,qs[1]=sn,qs[2]=Js,qs[3]=1},zs=rRe();be>0&&(be+=zs),Se+=zs;for(const qs of pe){const Xs=[],sn=[];for(const Js of qs){const fn=Js.x+Le.x,Os=Js.y+Le.y,en=ue.projection.projectTilePoint(fn,Os,wt),on=ue.projection.upVector(wt,Js.x,Js.y);let gn=be,Cn=Se;if(We){const ar=fRe(fn,Os,be,Se,We,ct,nt,ft);gn+=ar.base,Cn+=ar.top}be!==0?qt(Gt,en.x+on[0]*Ft*gn,en.y+on[1]*Ft*gn,en.z+on[2]*Ft*gn):qt(Gt,en.x,en.y,en.z),qt(Ut,en.x+on[0]*Ft*Cn,en.y+on[1]*Ft*Cn,en.z+on[2]*Ft*Cn),Je(Gt,Gt,ze),Je(Ut,Ut,ze),Xs.push(new VC(Gt[0],Gt[1],Gt[2])),sn.push(new VC(Ut[0],Ut[1],Ut[2]))}Nt.push(Xs),Wt.push(sn)}return[Nt,Wt]}(b,m,x,k,T,P,R,U,V,X,ie):R?function(ue,pe,be,Se,Le,ze,We,ct,nt){const ft=[],wt=[],Nt=[0,0,0,1];for(const Wt of ue){const Ft=[],Gt=[];for(const Ut of Wt){const qt=Ut.x+Se.x,zs=Ut.y+Se.y,qs=fRe(qt,zs,pe,be,ze,We,ct,nt);Nt[0]=qt,Nt[1]=zs,Nt[2]=qs.base,Nt[3]=1,ut(Nt,Nt,Le),Nt[3]=Math.max(Nt[3],1e-5);const Xs=new VC(Nt[0]/Nt[3],Nt[1]/Nt[3],Nt[2]/Nt[3]);Nt[0]=qt,Nt[1]=zs,Nt[2]=qs.top,Nt[3]=1,ut(Nt,Nt,Le),Nt[3]=Math.max(Nt[3],1e-5);const sn=new VC(Nt[0]/Nt[3],Nt[1]/Nt[3],Nt[2]/Nt[3]);Ft.push(Xs),Gt.push(sn)}ft.push(Ft),wt.push(Gt)}return[ft,wt]}(m,x,k,T,P,R,U,V,X):function(ue,pe,be,Se,Le){const ze=[],We=[],ct=Le[8]*pe,nt=Le[9]*pe,ft=Le[10]*pe,wt=Le[11]*pe,Nt=Le[8]*be,Wt=Le[9]*be,Ft=Le[10]*be,Gt=Le[11]*be;for(const Ut of ue){const qt=[],zs=[];for(const qs of Ut){const Xs=qs.x+Se.x,sn=qs.y+Se.y,Js=Le[0]*Xs+Le[4]*sn+Le[12],fn=Le[1]*Xs+Le[5]*sn+Le[13],Os=Le[2]*Xs+Le[6]*sn+Le[14],en=Le[3]*Xs+Le[7]*sn+Le[15],on=Js+ct,gn=fn+nt,Cn=Os+ft,ar=Math.max(en+wt,1e-5),Fn=Js+Nt,Rn=fn+Wt,Tn=Os+Ft,sr=Math.max(en+Gt,1e-5);qt.push(new VC(on/ar,gn/ar,Cn/ar)),zs.push(new VC(Fn/sr,Rn/sr,Tn/sr))}ze.push(qt),We.push(zs)}return[ze,We]}(m,x,k,T,P)}function fRe(b,m,x,k,T,P,R,U){const V=R*T.getElevationAt(b,m,!0,!0),X=P[0]!==0,ie=X?P[1]===0?R*(P[0]/7-450):R*function(ue,pe,be){const Se=Math.floor(pe[0]/8),Le=Math.floor(pe[1]/8),ze=10*(pe[0]-8*Se),We=10*(pe[1]-8*Le),ct=ue.getElevationAt(Se,Le,!0,!0),nt=ue.getMeterToDEM(be),ft=Math.floor(.5*(ze*nt-1)),wt=Math.floor(.5*(We*nt-1)),Nt=ue.tileCoordToPixel(Se,Le),Wt=2*ft+1,Ft=2*wt+1,Gt=function(sn,Js,fn,Os,en){return[sn.getElevationAtPixel(Js,fn,!0),sn.getElevationAtPixel(Js+en,fn,!0),sn.getElevationAtPixel(Js,fn+en,!0),sn.getElevationAtPixel(Js+Os,fn+en,!0)]}(ue,Nt.x-ft,Nt.y-wt,Wt,Ft),Ut=Math.abs(Gt[0]-Gt[1]),qt=Math.abs(Gt[2]-Gt[3]),zs=Math.abs(Gt[0]-Gt[2])+Math.abs(Gt[1]-Gt[3]),qs=Math.min(.25,.5*nt*(Ut+qt)/Wt),Xs=Math.min(.25,.5*nt*zs/Ft);return ct+Math.max(qs*ze,Xs*We)}(T,P,U):V;return{base:V+(x===0?-1:x),top:X?Math.max(ie+k,V+x+2):V+k}}const Fbe=4096;class q4t{constructor(m){this.module=m,this.memoryStack=this.module.malloc(Fbe),this.memoryStackNextFree=this.memoryStack}createIntArray(m){const x=this.memoryStackNextFree;return this.memoryStackNextFree+=m.length*Int32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>Fbe?-1:(new Int32Array(this.module.heap32.buffer,x,m.length).set(m),x)}createFloatArray(m){const x=this.memoryStackNextFree;return this.memoryStackNextFree+=m.length*Float32Array.BYTES_PER_ELEMENT,this.memoryStackNextFree-this.memoryStack>Fbe?-1:(new Float32Array(this.module.heapF32.buffer,x,m.length).set(m),x)}readStringBuffer(m){let x="";for(;this.module.heapU8[m]!==0;)x+=String.fromCharCode(this.module.heapU8[m]),++m;return x}setStyle(m){const x=m.normalScale;this.module.setStyle(x[0],x[1],x[2],m.tileToMeters)}setAOOptions(m,x){this.module.setAOOptions(m?1:0,x)}setMetricOptions(m,x){this.module.setMetricOptions(m?1:0,x)}setStructuralOptions(m){this.module.setStructuralOptions(m?1:0)}setFacadeOptions(m,x){this.module.setFacadeOptions(m,x?1:0)}setFauxFacadeOptions(m,x,k){this.module.setFauxFacadeOptions(m?1:0,x?1:0,k)}setFacadeClassifierOptions(m){this.module.setFacadeClassifierOptions(m)}generateMesh(m,x){this.memoryStackNextFree=this.memoryStack;for(const U of m){const V=this.createIntArray(U.ringIndices),X=this.createFloatArray(U.coordinates);if(V===-1||X===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFeature(U.id,U.sourceId,U.minHeight,U.height,U.roofType,X,V,U.ringIndices.length-1)}for(const U of x){let V;V=U.entrances?JSON.parse(U.entrances):[];const X=this.createFloatArray(V),ie=this.createFloatArray(U.coordinates);if(X===-1||ie===-1)return`building_gen: Out of stack memory: ${this.memoryStackNextFree-this.memoryStack}/4096`;this.module.addFacade(U.sourceId,U.crossPerc,U.distanceToRoad,X,V.length,ie,U.coordinates.length)}if(!this.module.generateMesh()){const U=this.module.getLastError();return this.readStringBuffer(U)}const k=this.module.getMeshCount(),T=new Array(k);for(let U=0;U>2)-3,ze=be[Se++]>>2;if(Se++,T.json=JSON.parse(kRe.decode(be.subarray(Se,Se+ze))),Se+=ze,Se>>0,Math.ceil(1.2*ft)),Nt=Math.ceil((wt-ft)/65536);try{return Le.grow(Nt),ze(),!0}catch{return!1}},b:We}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(be,ct):be.then(nt=>nt.arrayBuffer()).then(nt=>WebAssembly.instantiate(nt,ct))).then(nt=>{const{Rb:ft,Qb:wt,P:Nt,T:Wt,X:Ft,Ja:Gt,La:Ut,Qa:qt,Va:zs,Wa:qs,eb:Xs,jb:sn,f:Js,e:fn,yb:Os,zb:en,Ab:on,Bb:gn,Db:Cn,Gb:ar}=nt.instance.exports;Le=fn;const Fn=(()=>{let Rn=0,Tn=0,sr=0,hr=0;return Ur=>{sr&&(ft(hr),ft(Rn),Tn+=sr,sr=Rn=0),Rn||(Tn+=128,Rn=wt(Tn));const jr=Ur.length+7&-8;let Sa=Rn;jr>=Tn&&(sr=jr,Sa=hr=wt(jr));for(let _i=0;_i{S1=be,dO=void 0}))}()),pe&&ie.push(function(){if(zbe)return;const be=function(Se){let Le;const ze=WebAssembly.instantiateStreaming(Se,{}).then(nt=>{Le=nt.instance,Le.exports.__wasm_call_ctors()}),We={NONE:"",OCTAHEDRAL:"meshopt_decodeFilterOct",QUATERNION:"meshopt_decodeFilterQuat",EXPONENTIAL:"meshopt_decodeFilterExp"},ct={ATTRIBUTES:"meshopt_decodeVertexBuffer",TRIANGLES:"meshopt_decodeIndexBuffer",INDICES:"meshopt_decodeIndexSequence"};return{ready:ze,supported:!0,decodeGltfBuffer(nt,ft,wt,Nt,Wt,Ft){(function(Gt,Ut,qt,zs,qs,Xs,sn){const Js=Gt.exports.sbrk,fn=zs+3&-4,Os=Js(fn*qs),en=Js(Xs.length),on=new Uint8Array(Gt.exports.memory.buffer);on.set(Xs,en);const gn=Ut(Os,zs,qs,en,Xs.length);if(gn===0&&sn&&sn(Os,fn,qs),qt.set(on.subarray(Os,Os+zs*qs)),Js(Os-Js(0)),gn!==0)throw new Error(`Malformed buffer data: ${gn}`)})(Le,Le.exports[ct[Wt]],nt,ft,wt,Nt,Le.exports[We[Ft]])}}}(fetch(La()));return be.ready.then(()=>{zbe=be})}()),R)for(let be=0;be{const U=My(k,(V,X)=>{V?R(V):P(X)});T&&T.addEventListener("abort",()=>{U.cancel(),R(new DOMException("Aborted","AbortError"))},{once:!0})})}({url:b,type:"arrayBuffer"},m);return TRe(x,0,b,m)}function $be(b){switch(b){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 Ube(b){switch(b){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 v_{constructor(m,x,k,T){this.context=m,this.format=k,this.useMipmap=T&&T.useMipmap,this.texture=m.gl.createTexture(),this.update(x,{premultiply:T&&T.premultiply})}update(m,x){const k=m&&m instanceof HTMLVideoElement&&m.width===0?m.videoWidth:m.width,T=m&&m instanceof HTMLVideoElement&&m.height===0?m.videoHeight:m.height,{context:P}=this,{gl:R}=P,{x:U,y:V}=x&&x.position?x.position:{x:0,y:0},X=U+k,ie=V+T;this.size&&(this.size[0]!==X||this.size[1]!==ie)&&(!x||x.recreateWhenResize===void 0||x.recreateWhenResize)&&(R.bindTexture(R.TEXTURE_2D,null),R.deleteTexture(this.texture),this.texture=R.createTexture(),this.size=null),R.bindTexture(R.TEXTURE_2D,this.texture),P.pixelStoreUnpackFlipY.set(!1),P.pixelStoreUnpack.set(1),P.pixelStoreUnpackPremultiplyAlpha.set(this.format===R.RGBA8&&(!x||x.premultiply!==!1));const ue=m instanceof HTMLImageElement||m instanceof HTMLCanvasElement||m instanceof HTMLVideoElement||m instanceof ImageData||ImageBitmap&&m instanceof ImageBitmap;if(!this.size&&X>0&&ie>0){const pe=this.useMipmap?Math.floor(Math.log2(Math.max(X,ie)))+1:1;R.texStorage2D(R.TEXTURE_2D,pe,this.format,X,ie),this.size=[X,ie]}this.size&&(ue?R.texSubImage2D(R.TEXTURE_2D,0,U,V,$be(this.format),Ube(this.format),m):"data"in m&&m.data&&R.texSubImage2D(R.TEXTURE_2D,0,U,V,k,T,$be(this.format),Ube(this.format),m.data)),this.useMipmap&&R.generateMipmap(R.TEXTURE_2D)}bind(m,x,k=!1){const{context:T}=this,{gl:P}=T;P.bindTexture(P.TEXTURE_2D,this.texture),m!==this.minFilter&&(P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MAG_FILTER,m),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_MIN_FILTER,this.useMipmap&&!k?m===P.NEAREST?P.NEAREST_MIPMAP_NEAREST:P.LINEAR_MIPMAP_LINEAR:m),this.minFilter=m),x!==this.wrapS&&(P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_S,x),P.texParameteri(P.TEXTURE_2D,P.TEXTURE_WRAP_T,x),this.wrapS=x)}bindExtraParam(m,x,k,T,P){const{context:R}=this,{gl:U}=R;U.bindTexture(U.TEXTURE_2D,this.texture),x!==this.magFilter&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_MAG_FILTER,x),this.magFilter=x),m!==this.minFilter&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_MIN_FILTER,this.useMipmap?m===U.NEAREST?U.NEAREST_MIPMAP_NEAREST:U.LINEAR_MIPMAP_LINEAR:m),this.minFilter=m),k!==this.wrapS&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_WRAP_S,k),this.wrapS=k),T!==this.wrapT&&(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_WRAP_T,T),this.wrapT=T),P!==this.compareMode&&(P?(U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_MODE,U.COMPARE_REF_TO_TEXTURE),U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_FUNC,P)):U.texParameteri(U.TEXTURE_2D,U.TEXTURE_COMPARE_MODE,U.NONE),this.compareMode=P)}destroy(){const{gl:m}=this.context;m.deleteTexture(this.texture),this.texture=null}}class hO{constructor(m,x){this.context=m,this.texture=x}bind(m,x){const{context:k}=this,{gl:T}=k;T.bindTexture(T.TEXTURE_2D,this.texture),m!==this.minFilter&&(T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MAG_FILTER,m),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_MIN_FILTER,m),this.minFilter=m),x!==this.wrapS&&(T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_S,x),T.texParameteri(T.TEXTURE_2D,T.TEXTURE_WRAP_T,x),this.wrapS=x)}}const Z4t=ln([{name:"a_pos_3f",components:3,type:"Float32"}]),Q4t=ln([{name:"a_color_3f",components:3,type:"Float32"}]),X4t=ln([{name:"a_color_4f",components:4,type:"Float32"}]),J4t=ln([{name:"a_uv_2f",components:2,type:"Float32"}]),eCt=ln([{name:"a_normal_3f",components:3,type:"Float32"}]),tCt=ln([{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"}]),sCt=ln([{name:"a_pbr",components:4,type:"Uint16"},{name:"a_heightBasedEmissiveStrength",components:3,type:"Float32"}]);function ARe(b,m){const x=kq(b.projection,b.zoom,b.width,b.height),k=function(P,R,U,V,X){const ie=new ss(U.lng-180*ck,U.lat),ue=new ss(U.lng+180*ck,U.lat),pe=P.project(ie.lng,ie.lat),be=P.project(ue.lng,ue.lat),Se=-Math.atan2(be.y-pe.y,be.x-pe.x),Le=ur.fromLngLat(U);Le.y=Qe(Le.y,-1+ck,1-ck);const ze=Le.toLngLat(),We=P.project(ze.lng,ze.lat),ct=ur.fromLngLat(ze);ct.x+=ck;const nt=ct.toLngLat(),ft=P.project(nt.lng,nt.lat),wt=IRe(ft.x-We.x,ft.y-We.y,Se),Nt=ur.fromLngLat(ze);Nt.y+=ck;const Wt=Nt.toLngLat(),Ft=P.project(Wt.lng,Wt.lat),Gt=IRe(Ft.x-We.x,Ft.y-We.y,Se),Ut=Math.abs(wt.x)/Math.abs(Gt.y),qt=v([]);D(qt,qt,-Se*(1-(X?0:V)));const zs=v([]);return A(zs,zs,[1,1-(1-Ut)*V,1]),zs[4]=-Gt.x/Gt.y*V,D(zs,zs,Se),w(zs,qt,zs),zs}(b.projection,0,b.center,x,m),T=MRe(b);return A(k,k,[T,T,1]),k}function MRe(b){const m=b.projection,x=kq(b.projection,b.zoom,b.width,b.height),k=qbe(m,b.center),T=qbe(m,ss.convert(m.center));return Math.pow(2,k*x+(1-x)*T)}function kq(b,m,x,k,T=1/0){const P=b.range;if(!P)return 0;const R=Math.min(T,Math.max(x,k)),U=Math.log2(R/1024);return ot(P[0]+U,P[1]+U,m)}const ck=1/4e4;function qbe(b,m){const x=Qe(m.lat,-85.051129,Ys),k=new ss(m.lng-180*ck,x),T=new ss(m.lng+180*ck,x),P=b.project(k.lng,x),R=b.project(T.lng,x),U=ur.fromLngLat(k),V=ur.fromLngLat(T),X=R.x-P.x,ie=R.y-P.y,ue=V.x-U.x,pe=V.y-U.y,be=Math.sqrt((ue*ue+pe*pe)/(X*X+ie*ie));return Math.log2(be)}function IRe(b,m,x){const k=Math.cos(x),T=Math.sin(x);return{x:b*k-m*T,y:b*T+m*k}}function PRe(b,m,x){v(b),D(b,b,Ts(m[2])),E(b,b,Ts(m[0])),O(b,b,Ts(m[1])),A(b,b,x),w(b,b,[1,0,0,0,0,0,1,0,0,1,0,0,0,0,0,1])}function Sq(b,m,x,k,T,P,R,U){const V=[x[0]-m[0],x[1]-m[1],0],X=[k[0]-m[0],k[1]-m[1],0];if(ee(V)<1e-12||ee(X)<1e-12)return bt(b);const ie=Be([],V,X);Re(ie,ie),ce(X,k,m),V[2]=(P-T)*U,X[2]=(R-T)*U;const ue=V;return Be(ue,V,X),Re(ue,ue),Jt(b,ie,ue)}function Cq(b,m,x=!1){const k=Gj(m.zoom),T=function(P,R,U){const V=R.worldSize,X=[P[12],P[13],P[14]],ie=Fs(X[1]/V),ue=ds(X[0]/V),pe=v([]),be=Ns(1,ie)*V,Se=Ns(1,0)*V*kn(ie,R.zoom),Le=1/pbe(V);let ze=Se*Le;if(U){const ft=kq(R.projection,R.zoom,R.width,R.height,1024);ze=Le*R.projection.pixelSpaceConversion(R.center.lat,V,ft)}const We=Dt(ie,ue);he(We,We,ge([],Re([],We),be*ze*X[2]));const ct=function(ft){const wt=[ft[0],ft[1],ft[2]];let Nt=[0,1,0];const Wt=Be([],Nt,wt);return Be(Nt,wt,Wt),Me(Nt)===0&&(Nt=[0,1,0],Be(Wt,wt,Nt)),Re(Wt,Wt),Re(Nt,Nt),Re(wt,wt),[Wt[0],Wt[1],Wt[2],0,Nt[0],Nt[1],Nt[2],0,wt[0],wt[1],wt[2],0,ft[0],ft[1],ft[2],1]}(We);A(pe,pe,[ze,ze,ze*be]),S(pe,pe,[-X[0],-X[1],-X[2]]);const nt=w([],R.globeMatrix,ct);return w(nt,nt,pe),w(nt,nt,P),nt}(b,m,x);if(k>0){const P=function(R,U){const V=U.worldSize,X=Ns(1,0)*V*kn(U.center.lat,U.zoom)/pbe(V),ie=Ns(1,U.center.lat)*V,ue=v([]);O(ue,ue,Ts(U.center.lng)),E(ue,ue,Ts(U.center.lat)),S(ue,ue,[0,0,Et]),A(ue,ue,[X,X,X*ie]);const pe=U.point;return S(ue,ue,[-pe.x,-pe.y,0]),w(ue,ue,R),w(ue,U.globeMatrix,ue)}(b,m);return function(R,U,V){const X=(Se,Le,ze)=>{const We=ee(Se),ct=ee(Le),nt=Hj(Se,Le,ze);return ge(nt,nt,1/ee(nt)*Dr(We,ct,ze))},ie=X([R[0],R[1],R[2]],[U[0],U[1],U[2]],V),ue=X([R[4],R[5],R[6]],[U[4],U[5],U[6]],V),pe=X([R[8],R[9],R[10]],[U[8],U[9],U[10]],V),be=Hj([R[12],R[13],R[14]],[U[12],U[13],U[14]],V);return[ie[0],ie[1],ie[2],0,ue[0],ue[1],ue[2],0,pe[0],pe[1],pe[2],0,be[0],be[1],be[2],1]}(T,P,k)}return T}function Vbe(b,m,x,k){const T=eo.projectAabbCorners(k,x);let P=Number.MAX_VALUE;for(let U=0;U0||ze===0&&Se[0]*Le[0]+Se[1]*Le[1]>=0&&Se[0]*Se[0]+Se[1]*Se[1]>Le[0]*Le[0]+Le[1]*Le[1])&&(ie=be)}ue=ie}while(ue!==X);return V.length>0&&V.push(V[0]),V}(T);if(uc(b,R))return P}const HC=64,B6={CoordinateSpaceTile:1,HasMapboxMeshFeatures:4,HasMeshoptCompression:8};function Tq(b,m,x,k,T,P,R,U,V,X=!1){const ie=x.zoom,ue=x.project(k),pe=kn(k.lat,ie),be=1/pe;v(b),S(b,b,[ue.x+R[0]*be,ue.y+R[1]*be,R[2]]);let Se=1,Le=1;const ze=x.worldSize;if(X){if(x.projection.name==="mercator"){let ft=0;x.elevation&&(ft=x.elevation.getAtPointOrZero(new ur(ue.x/ze,ue.y/ze),0));const wt=ut([],[ue.x,ue.y,ft,1],x.projMatrix)[3]/x.cameraToCenterDistance;Se=wt,Le=wt*kn(x.center.lat,ie)}else if(x.projection.name==="globe"){const ft=Cq(b,x),wt=[0,0,0,1];ut(wt,wt,w([],x.projMatrix,ft));const Nt=wt[3]/x.cameraToCenterDistance,Wt=Gj(ie),Ft=x.projection.pixelsPerMeter(k.lat,ze)*kn(k.lat,ie),Gt=x.projection.pixelsPerMeter(x.center.lat,ze)*kn(x.center.lat,ie);Se=Nt/Dr(Ft,Dn(x.center.lat),Wt),Le=Nt*pe/Ft,Se*=Gt,Le*=Gt}}else Se=be;A(b,b,[Se,Se,Le]);const We=[...b],ct=m.orientation,nt=[];if(PRe(nt,[ct[0]+(T?T[0]:0),ct[1]+(T?T[1]:0),ct[2]+(T?T[2]:0)],P),w(b,We,nt),U&&x.elevation){let ft=0;const wt=[];if(V&&x.elevation){ft=function(Wt,Ft,Gt,Ut,qt){const zs=Ft.elevation;if(!zs)return 0;const qs=eo.projectAabbCorners(Gt,Ut),Xs=Ns(1,qt.lat)*Ft.worldSize,sn=function(Tn,sr){const hr=[0,0,1],Ur=[{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 jr of Ur){const Sa=Tn[jr.corners[0]],_i=Tn[jr.corners[1]],Ca=Tn[jr.corners[2]],Ni=[_i[0]-Sa[0],_i[1]-Sa[1],sr*(_i[2]-Sa[2])],Ga=Be(Ni,Ni,[Ca[0]-Sa[0],Ca[1]-Sa[1],sr*(Ca[2]-Sa[2])]);Re(Ga,Ga),jr.dotProductWithUp=Ae(Ga,hr)}return Ur.sort((jr,Sa)=>jr.dotProductWithUp-Sa.dotProductWithUp),Ur[0].corners}(qs,Xs),Js=qs[sn[0]],fn=qs[sn[1]],Os=qs[sn[2]],en=qs[sn[3]],on=zs.getAtPointOrZero(new ur(Js[0]/Ft.worldSize,Js[1]/Ft.worldSize),0),gn=zs.getAtPointOrZero(new ur(fn[0]/Ft.worldSize,fn[1]/Ft.worldSize),0),Cn=zs.getAtPointOrZero(new ur(Os[0]/Ft.worldSize,Os[1]/Ft.worldSize),0),ar=zs.getAtPointOrZero(new ur(en[0]/Ft.worldSize,en[1]/Ft.worldSize),0),Fn=(on+ar)/2,Rn=(gn+Cn)/2;return Fn>Rn?gn=m.gl.NEAREST_MIPMAP_NEAREST}),b.uploaded=!0,b.image=null)}function nCt(b,m,x){b.indexBuffer=m.createIndexBuffer(b.indexArray,!1,!0),b.vertexBuffer=m.createVertexBuffer(b.vertexArray,Z4t.members,!1,!0),b.normalArray&&(b.normalBuffer=m.createVertexBuffer(b.normalArray,eCt.members,!1,!0)),b.texcoordArray&&(b.texcoordBuffer=m.createVertexBuffer(b.texcoordArray,J4t.members,!1,!0)),b.colorArray&&(b.colorBuffer=m.createVertexBuffer(b.colorArray,(b.colorArray.bytesPerElement===12?Q4t:X4t).members,!1,!0)),b.featureArray&&(b.pbrBuffer=m.createVertexBuffer(b.featureArray,sCt.members,!0)),b.segments=Po.simpleSegment(0,0,b.vertexArray.length,b.indexArray.length);const k=b.material;k.pbrMetallicRoughness.baseColorTexture&&mO(k.pbrMetallicRoughness.baseColorTexture,m),k.pbrMetallicRoughness.metallicRoughnessTexture&&mO(k.pbrMetallicRoughness.metallicRoughnessTexture,m),k.normalTexture&&mO(k.normalTexture,m),k.occlusionTexture&&mO(k.occlusionTexture,m,x),k.emissionTexture&&mO(k.emissionTexture,m)}function Hbe(b,m,x){if(b.meshes)for(const k of b.meshes)nCt(k,m,x);if(b.children)for(const k of b.children)Hbe(k,m,x)}function Eq(b){if(b.meshes)for(const m of b.meshes)m.indexArray.destroy(),m.vertexArray.destroy(),m.colorArray&&m.colorArray.destroy(),m.normalArray&&m.normalArray.destroy(),m.texcoordArray&&m.texcoordArray.destroy(),m.featureArray&&m.featureArray.destroy();if(b.children)for(const m of b.children)Eq(m)}function rCt(b){b.pbrMetallicRoughness.baseColorTexture&&b.pbrMetallicRoughness.baseColorTexture.gfxTexture&&b.pbrMetallicRoughness.baseColorTexture.gfxTexture.destroy(),b.pbrMetallicRoughness.metallicRoughnessTexture&&b.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture&&b.pbrMetallicRoughness.metallicRoughnessTexture.gfxTexture.destroy(),b.normalTexture&&b.normalTexture.gfxTexture&&b.normalTexture.gfxTexture.destroy(),b.emissionTexture&&b.emissionTexture.gfxTexture&&b.emissionTexture.gfxTexture.destroy(),b.occlusionTexture&&b.occlusionTexture.gfxTexture&&b.occlusionTexture.gfxTexture.destroy()}function Gbe(b){if(b.meshes)for(const m of b.meshes)m.vertexBuffer&&(m.vertexBuffer.destroy(),m.indexBuffer.destroy(),m.normalBuffer&&m.normalBuffer.destroy(),m.texcoordBuffer&&m.texcoordBuffer.destroy(),m.colorBuffer&&m.colorBuffer.destroy(),m.pbrBuffer&&m.pbrBuffer.destroy(),m.segments.destroy(),m.material&&rCt(m.material));if(b.footprintDebugMesh&&(b.footprintDebugMesh.vertexBuffer.destroy(),b.footprintDebugMesh.indexBuffer.destroy(),b.footprintDebugMesh.segments.destroy()),b.children)for(const m of b.children)Gbe(m)}function GC(b,m){const x=b.json.bufferViews[m.bufferView],k=jq[m.componentType];return new k(b.buffers[x.buffer],(m.byteOffset||0)+(x.byteOffset||0),m.count*(x.byteStride&&x.byteStride!==uO[m.type]*k.BYTES_PER_ELEMENT?x.byteStride/k.BYTES_PER_ELEMENT:uO[m.type]))}function Wbe(b,m,x,k){const T=jq[m.componentType],P=function(ie){switch(ie){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:return 1}}(T),R=b.json.bufferViews[m.bufferView],U=R.byteStride?R.byteStride/T.BYTES_PER_ELEMENT:uO[m.type],V=x.float32,X=V.length/x.capacity;for(let ie=0,ue=0;ie0){for(let ze=0;ze0){P.texcoordArray=new $j;const pe=m.json.accessors[T.TEXCOORD_0];P.texcoordArray.resize(pe.count);const be=GC(m,pe);Wbe(m,pe,P.texcoordArray,be)}if(T._FEATURE_ID_RGBA4444!==void 0){const pe=m.json.accessors[T._FEATURE_ID_RGBA4444];m.json.extensionsUsed&&m.json.extensionsUsed.includes("EXT_meshopt_compression")&&(P.featureData=GC(m,pe))}T._FEATURE_RGBA4444!==void 0&&(P.featureData=new Uint32Array(GC(m,m.json.accessors[T._FEATURE_RGBA4444]).buffer));const ue=b.material;return P.material=function(pe,be){const{emissiveFactor:Se=[0,0,0],alphaMode:Le="OPAQUE",alphaCutoff:ze=.5,normalTexture:We,occlusionTexture:ct,emissiveTexture:nt,doubleSided:ft,name:wt}=pe,{baseColorFactor:Nt=[1,1,1,1],metallicFactor:Wt=1,roughnessFactor:Ft=1,baseColorTexture:Gt,metallicRoughnessTexture:Ut}=pe.pbrMetallicRoughness||{},qt=ct?be[ct.index]:void 0;if(ct&&ct.extensions&&ct.extensions.KHR_texture_transform&&qt){const zs=ct.extensions.KHR_texture_transform;qt.offsetScale=[zs.offset[0],zs.offset[1],zs.scale[0],zs.scale[1]]}return{name:wt,pbrMetallicRoughness:{baseColorFactor:new Gn(...Nt),metallicFactor:Wt,roughnessFactor:Ft,baseColorTexture:Gt?be[Gt.index]:void 0,metallicRoughnessTexture:Ut?be[Ut.index]:void 0},doubleSided:ft,emissiveFactor:new Gn(...Se),alphaMode:Le,alphaCutoff:ze,normalTexture:We?be[We.index]:void 0,occlusionTexture:qt,emissionTexture:nt?be[nt.index]:void 0,defined:pe.defined===void 0}}(ue!==void 0?m.json.materials[ue]:{defined:!1},x),P}function DRe(b,m,x){const{matrix:k,rotation:T,translation:P,scale:R,mesh:U,extras:V,children:X,name:ie}=b,ue={};if(ue.name=ie,ue.localMatrix=k||function(pe,be,Se,Le){var ze=be[0],We=be[1],ct=be[2],nt=be[3],ft=ze+ze,wt=We+We,Nt=ct+ct,Wt=ze*ft,Ft=ze*wt,Gt=ze*Nt,Ut=We*wt,qt=We*Nt,zs=ct*Nt,qs=nt*ft,Xs=nt*wt,sn=nt*Nt,Js=Le[0],fn=Le[1],Os=Le[2];return pe[0]=(1-(Ut+zs))*Js,pe[1]=(Ft+sn)*Js,pe[2]=(Gt-Xs)*Js,pe[3]=0,pe[4]=(Ft-sn)*fn,pe[5]=(1-(Wt+zs))*fn,pe[6]=(qt+qs)*fn,pe[7]=0,pe[8]=(Gt+Xs)*Os,pe[9]=(qt-qs)*Os,pe[10]=(1-(Wt+Ut))*Os,pe[11]=0,pe[12]=Se[0],pe[13]=Se[1],pe[14]=Se[2],pe[15]=1,pe}([],T||[0,0,0,1],P||[0,0,0],R||[1,1,1]),ue.globalMatrix=_(ue.localMatrix),U!==void 0){ue.meshes=x[U];const pe=ue.anchor=[0,0];for(const be of ue.meshes){const{min:Se,max:Le}=be.aabb;pe[0]+=Se[0]+Le[0],pe[1]+=Se[1]+Le[1]}pe[0]=Math.floor(pe[0]/ue.meshes.length/2),pe[1]=Math.floor(pe[1]/ue.meshes.length/2)}if(V&&(V.id&&(ue.id=V.id),V.lights&&(ue.lights=function(pe){if(!pe.length)return[];const be=function(ct){const nt=atob(ct),ft=new Uint8Array(nt.length);for(let wt=0;wt1&&k[k.length-1].equals(k[0])&&k.pop();let T=0;for(let R=0;R0&&k.reverse();const P=D6(k.flatMap(R=>[R.x,R.y]),[]);return P.length===0?null:{vertices:k,indices:P}}function lCt(b,m){const x=[],k=[];let T=0;const P=[];for(const R of b){T=x.length;const U=R.vertexArray.float32,V=R.indexArray.uint16;for(let X=0;X0&&([k[R+1],k[R+2]]=[k[R+2],k[R+1]])}return{vertices:x,indices:k}}function Kbe(b){const m=function(V,X){const ie=[],ue=WebGL2RenderingContext;if(V.json.textures)for(const pe of V.json.textures){const be={magFilter:ue.LINEAR,minFilter:ue.NEAREST,wrapS:ue.REPEAT,wrapT:ue.REPEAT};pe.sampler!==void 0&&Object.assign(be,V.json.samplers[pe.sampler]),ie.push({image:X[pe.source],sampler:be,uploaded:!1})}return ie}(b,b.images),x=function(V,X){const ie=[];for(const ue of V.json.meshes){const pe=[];for(const be of ue.primitives)pe.push(aCt(be,V,X));ie.push(pe)}return ie}(b,m),{scenes:k,scene:T,nodes:P}=b.json,R=k?k[T||0].nodes:[...P.keys()],U=[];for(const V of R)U.push(DRe(P[V],b,x));return function(V,X,ie){const ue={},pe=new Set;for(let be=0;be0){const be=Array.from(pe.values()).sort((Se,Le)=>Se-Le);for(let Se=be.length-1;Se>=0;Se--)V.splice(be[Se],1)}}(U,R,b.json.nodes),U}function cCt(b){b.heightmap=new Float32Array(4096),b.heightmap.fill(-1);const m=b.vertexArray.float32,x=b.aabb.min[0]-1,k=b.aabb.min[1]-1,T=HC/(b.aabb.max[0]-x+2),P=HC/(b.aabb.max[1]-k+2);for(let R=0;Rb.heightmap[X*HC+V]&&(b.heightmap[X*HC+V]=U)}}function RRe(b,m,x,k,T){x.reserve(x.length+4*b.length),k.reserve(k.length+10*b.length),T.reserve(T.length+10*b.length);let P=k.length;for(const R of b){const U=Math.min(10,Math.max(4,1.3*R.height))*m,V=[-R.normal[1],R.normal[0],0],X=Math.min(.29,.1*R.width/R.depth),ie=R.width-2*R.depth*m*(X+.01),ue=Te([],R.pos,V,ie/2),pe=Te([],R.pos,V,-ie/2),be=[ue[0],ue[1],ue[2]+R.height],Se=[pe[0],pe[1],pe[2]+R.height],Le=Te([],R.normal,V,X);ge(Le,Le,U);const ze=Te([],R.normal,V,-X);ge(ze,ze,U),he(Le,ue,Le),he(ze,pe,ze),ue[2]+=.1,pe[2]+=.1,k.emplaceBack(Le[0],Le[1],Le[2]),k.emplaceBack(ze[0],ze[1],ze[2]),k.emplaceBack(ue[0],ue[1],ue[2]),k.emplaceBack(pe[0],pe[1],pe[2]),k.emplaceBack(be[0],be[1],be[2]),k.emplaceBack(Se[0],Se[1],Se[2]),k.emplaceBack(ue[0],ue[1],ue[2]),k.emplaceBack(pe[0],pe[1],pe[2]),k.emplaceBack(Le[0],Le[1],Le[2]),k.emplaceBack(ze[0],ze[1],ze[2]);const We=ie/U/2;T.emplaceBack(-We-X,-1,We,.8),T.emplaceBack(We+X,-1,We,.8),T.emplaceBack(-We,0,We,1.3),T.emplaceBack(We,0,We,1.3),T.emplaceBack(We+X,-.8,We,.7),T.emplaceBack(We+X,-.8,We,.7),T.emplaceBack(0,0,We,1.3),T.emplaceBack(0,0,We,1.3),T.emplaceBack(We+X,-1.2,We,.8),T.emplaceBack(We+X,-1.2,We,.8),x.emplaceBack(6+P,4+P,8+P),x.emplaceBack(7+P,9+P,5+P),x.emplaceBack(0+P,1+P,2+P),x.emplaceBack(1+P,3+P,2+P),P+=10}}function dCt(b,m){const x={};x.indexArray=new tc,x.vertexArray=new gg,x.colorArray=new N1,RRe(b,m,x.indexArray,x.vertexArray,x.colorArray);const k={defined:!0};k.emissiveFactor=Gn.black;const T={};return T.baseColorFactor=Gn.white,k.pbrMetallicRoughness=T,x.material=k,x.aabb=new eo([1/0,1/0,1/0],[-1/0,-1/0,-1/0]),x}const ORe=ln([{name:"a_pos_3f",components:3,type:"Float32"}]),uCt=ln([{name:"a_normal_3",components:3,type:"Int16"}]),hCt=ln([{name:"a_centroid_3",components:3,type:"Int16"}]),FRe=ln([{name:"a_part_color_emissive",components:2,type:"Uint16"}]),mCt=ln([{name:"a_faux_facade_color_emissive",components:2,type:"Uint16"}]),pCt=ln([{name:"a_faux_facade_data",components:4,type:"Uint16"}]),fCt=ln([{name:"a_faux_facade_vertical_range",components:2,type:"Uint16"}]),xCt=ln([{name:"a_bloom_attenuation",components:4,type:"Float32"}]),gCt=ln([{name:"a_flood_light_wall_radius_1i16",components:1,type:"Int16"}]),zRe=pa.types,Aq=32767;function yCt(b,m){const x=Bn+m;for(const k of b)for(const T of k)if(T.x<-m||T.x>x||T.y<-m||T.y>x)return!1;return!0}function vCt(b){switch(b){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: ${b}`)}}class Ybe{constructor(){this.layoutVertexArray=new gg,this.layoutAttenuationArray=new N1,this.layoutColorArray=new yg,this.indexArray=new tc,this.indexArrayForConflation=new tc,this.segmentsBucket=new Po}}class Zbe{constructor(m){this.layoutFacadePaintArray=null,this.layoutFacadeDataArray=null,this.layoutFacadeVerticalRangeArray=null,this.segmentsBucket=new Po,this.entranceBloom=new Ybe;const x=66560;this.layoutVertexArray=new gg,this.layoutVertexArray.reserve(x),this.layoutNormalArray=new Di,this.layoutNormalArray.reserve(x),this.layoutCentroidArray=new Di,this.layoutCentroidArray.reserve(x),this.layoutColorArray=new yg,this.layoutColorArray.reserve(x),this.layoutFloodLightDataArray=new E6,this.layoutFloodLightDataArray.reserve(x),this.layoutAOArray=new A6,this.layoutAOArray.reserve(x),this.indexArray=new tc,this.indexArray.reserve(66560),this.indexArrayForConflation=new tc,this.segmentsBucket=new Po,this.entranceBloom=new Ybe,m&&(this.layoutFacadePaintArray=new yg,this.layoutFacadeDataArray=new sk,this.layoutFacadeVerticalRangeArray=new yg)}reserve(m,x,k){this.layoutVertexArray.reserveForAdditional(m),this.layoutCentroidArray.reserveForAdditional(m),this.layoutFloodLightDataArray.reserveForAdditional(m),this.layoutNormalArray.reserveForAdditional(m),this.layoutAOArray.reserveForAdditional(m),this.layoutColorArray.reserveForAdditional(m),this.indexArray.reserveForAdditional(x),k&&(this.layoutFacadePaintArray.reserveForAdditional(m),this.layoutFacadeDataArray.reserveForAdditional(m),this.layoutFacadeVerticalRangeArray.reserveForAdditional(m))}}class BRe{constructor(m){this.colorBufferUploaded=!1,this.maxHeight=0,this.replacementUpdateTime=0,this.activeReplacements=[],this.footprints=[],this.footprintsVertices=new $j,this.footprintsIndices=new Uj,this.footprintsMin=new Es(1/0,1/0),this.footprintsMax=new Es(-1/0,-1/0),this.featuresOnBorder=[],this.buildingWithoutFacade=new Zbe(!1),this.buildingWithFacade=new Zbe(!0),this.indexArrayForConflationUploaded=!1,this.featureFootprintLookup=new Map,this.buildingIds=new Set,this.footprintLookup={},this.zoom=m.zoom,this.canonical=m.canonical,this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.index=m.index,this.hasPattern=!1,this.worldview=m.worldview,this.lut=m.lut,this.programConfigurations=new qe(m.layers,{zoom:m.zoom,lut:m.lut}),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.projection=m.projection,this.groundEffect=new Rbe(m),this.groundEffect.groundRadiusArray=new no,this.hasAppearances=null}updateFootprints(m,x){const k=new mq([],[],1),T={vertices:[],indices:new Uint32Array(0),grid:k,min:this.footprintsMin,max:this.footprintsMax,buildingIds:this.buildingIds};x.push({footprint:T,id:m})}updateAppearances(m,x,k,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}prepare(){return function(){if(wq!=null||xRe!=null)return null;if(z6!=null)return z6;const m=fetch(so());return z6=function(x){let k,T,P,R,U;function V(){k=new Uint8Array(U.buffer),T=new Int16Array(U.buffer),P=new Int32Array(U.buffer),R=new Float32Array(U.buffer)}function X(){throw new Error("Unexpected BuildingGen error.")}const ie=()=>{},ue={a:{a:X,f:function(pe){const be=k.length,Se=Math.max(pe>>>0,Math.ceil(1.2*be)),Le=Math.ceil((Se-be)/65536);try{return U.grow(Le),V(),!0}catch{return!1}},g:X,b:ie,c:ie,d:ie,e:ie}};return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(x,ue):x.then(pe=>pe.arrayBuffer()).then(pe=>WebAssembly.instantiate(pe,ue))).then(pe=>{const be=pe.instance.exports;return(0,be.g)(),U=be.f,V(),new q4t({setStyle:be.h,setAOOptions:be.i,setMetricOptions:be.j,setStructuralOptions:be.k,setFacadeOptions:be.l,setFauxFacadeOptions:be.m,setFacadeClassifierOptions:be.n,addFeature:be.o,addFacade:be.p,generateMesh:be.q,getLastError:be.r,getOuterRingLength:be.s,getMeshCount:be.t,getPositionsPtr:be.u,getPositionsLength:be.v,getNormalsPtr:be.w,getNormalsLength:be.x,getAOPtr:be.y,getAOLength:be.z,getUVPtr:be.A,getUVLength:be.B,getFauxFacadePtr:be.C,getFauxFacadeLength:be.D,getIndicesPtr:be.E,getIndicesLength:be.F,getBuildingPart:be.G,getRingCount:be.H,getRingPtr:be.I,getRingLength:be.J,malloc:be.K,free:be.L,heapU8:k,heap16:T,heap32:P,heapF32:R})})}(m).then(x=>(z6=null,wq=x,wq)).catch(x=>{Yn("Could not load building-gen"),z6=null,xRe=x instanceof Error?x:new Error("Unknown error")}),z6}()}populate(m,x,k,T){const P=V4t();if(!P)return;const R=cn(k);this.tileToMeter=R,this.brightness=x.brightness,P.setStyle({normalScale:[1,-1,R],tileToMeters:R}),P.setAOOptions(!1,.3),P.setMetricOptions(!1,16),P.setStructuralOptions(!0),P.setFacadeClassifierOptions(3);const U=new Map,V=new Map;let X=0;for(const{feature:We}of m){if(zRe[We.type]!=="LineString"){U.set(We.id,We.properties.source_id);continue}const ct=this.layers[0]._featureFilter.needGeometry;if(ct&&!this.layers[0]._featureFilter.filter(new Aa(this.zoom),We,k))continue;const nt=Ha(We,ct);if(!ct&&!this.layers[0]._featureFilter.filter(new Aa(this.zoom),nt,k))continue;const ft=ct?nt.geometry:Vr(We,k,T),wt=[];for(const Gt of ft)for(const Ut of Gt)wt.push(Ut.x),wt.push(Ut.y);const Nt={coordinates:wt,crossPerc:We.properties.cross_perc,distanceToRoad:We.properties.distance_to_road,entrances:We.properties.entrances,sourceId:0},Wt=We.properties.source_id;let Ft=V.get(Wt);Ft||(Ft=[],V.set(Wt,Ft)),Ft.push(Nt),++X}this.maxHeight=0;const ie=new Array,ue=new Set,pe=We=>{We!=null&&ue.add(We)},be=(We,ct)=>{We!=null&&ie.push({buildingId:We,footprintIndex:ct})},Se=64*(m.length-X),Le=Se/2;this.buildingWithFacade.reserve(Se,Le,!0),this.buildingWithoutFacade.reserve(2*Se,2*Le,!1),this.footprintsIndices.reserve(16*(m.length-X)),this.footprintsVertices.reserve(8*(m.length-X));for(const{feature:We,id:ct,index:nt,sourceLayerIndex:ft}of m){if(zRe[We.type]==="LineString")continue;const wt=this.layers[0]._featureFilter.needGeometry;if(wt&&!this.layers[0]._featureFilter.filter(new Aa(this.zoom),We,k))continue;let Nt=null;if(We.properties&&We.properties.hasOwnProperty("building_id")&&(Nt=Number(We.properties.building_id),ue.has(Nt)))continue;const Wt=Ha(We,wt);if(!wt&&!this.layers[0]._featureFilter.filter(new Aa(this.zoom),Wt,k))continue;const Ft=wt?Wt.geometry:Vr(We,k,T),Gt=sO(Ft,500);let Ut=!1;for(const ri of Gt)if(ri.length!==1){Ut=!0;break}if(Ut){pe(Nt);continue}if(!yCt(Ft,163)){pe(Nt);continue}const qt=this.layers[0],zs=vCt(qt.layout.get("building-roof-shape").evaluate(We,{},k)),qs=qt.layout.get("building-base").evaluate(We,{},k),Xs=qt.layout.get("building-height").evaluate(We,{},k),sn=qt.layout.get("building-flood-light-ground-radius").evaluate(We,{},k),Js=qt.paint.get("building-ambient-occlusion-intensity"),fn=sn/this.tileToMeter;We.properties["building-part"]="roof";const Os=qt.paint.get("building-color").evaluate(We,{},this.canonical).toPremultipliedRenderColor(this.lut),en=qt.paint.get("building-emissive-strength").evaluate(We,{},this.canonical);We.properties["building-part"]="wall";const on=qt.paint.get("building-color").evaluate(We,{},this.canonical).toPremultipliedRenderColor(this.lut),gn=qt.paint.get("building-emissive-strength").evaluate(We,{},this.canonical);We.properties["building-part"]="window";const Cn=qt.paint.get("building-color").evaluate(We,{},this.canonical).toPremultipliedRenderColor(this.lut),ar=qt.paint.get("building-emissive-strength").evaluate(We,{},this.canonical);We.properties["building-part"]="door";const Fn=qt.paint.get("building-color").evaluate(We,{},this.canonical).toPremultipliedRenderColor(this.lut),Rn=qt.paint.get("building-emissive-strength").evaluate(We,{},this.canonical);let Tn=qt.layout.get("building-flood-light-wall-radius").evaluate(We,{},k);Tn=Qe(Tn,0,2048);const sr=Tn/2048*Aq,hr=U.get(ct),Ur=V.get(hr)||[],jr=Ur.length!==0&&qt.layout.get("building-facade").evaluate(We,{},k);P.setFacadeOptions(4,!0),P.setFauxFacadeOptions(jr,!1,1);let Sa=0,_i=0,Ca=0,Ni=0,Ga=0,Ol=0,Qi=0,Ii=0,Ro=0,Ml=0,Yd=0;if(jr){let ri=Math.round(qt.layout.get("building-facade-floors").evaluate(We,{},k));if(qs===0){ri=Math.max(1,ri-(Ur.length>0?1:0));let rc=4;if(Xs>100){const Cd=[10,13,15];rc=Cd[We.id?We.id%Cd.length:0]}else Xs<=10&&(rc=3);P.setFacadeOptions(rc,!0),Ga=(Xs<15?1.3:1.61803)*rc/R}else Ga=qs/R;Ol=Xs/R,Ga=Math.min(Ga,Ol),Ca=qt.layout.get("building-facade-unit-width").evaluate(We,{},k)/R,Ni=(Ol-Ga)/ri,P.setFauxFacadeOptions(!0,!0,Ca);const vu=qt.layout.get("building-facade-window").evaluate(We,{},k);Sa=vu[0],_i=vu[1],Qi=Math.floor(65535*Math.min(1,Ga/Bn)),Ii=Math.floor(65535*Math.min(1,Ol/Bn)),Ro=Math.floor(255*Sa)<<8|Math.floor(255*_i),Ml=Math.floor(65535*Math.min(1,Ca/Bn)),Yd=Math.floor(65535*Math.min(1,Ni/Bn))}const Il=Array(Gt.length),sc={x:1/0,y:1/0},Oc={x:-1/0,y:-1/0},nc={x:0,y:0};let yh=0;for(let ri=0;ri0){const rc=[],Cd=Array(vu.length+1);Cd[0]=0;for(let S0=0;S0Bn||sc.y<0||Oc.y>Bn)&&this.featuresOnBorder.push({featureId:We.id,footprintIndex:this.footprints.length});{const ri=D6(Xj,null,2);this.footprintsIndices.resize(this.footprintsIndices.length+ri.length),this.footprintsIndices.uint16.set(ri,J6),this.buildingIds.add(Nt??We.id),this.footprintsMin.x=Math.min(this.footprintsMin.x,N0.x),this.footprintsMin.y=Math.min(this.footprintsMin.y,N0.y),this.footprintsMax.x=Math.max(this.footprintsMax.x,k0.x),this.footprintsMax.y=Math.max(this.footprintsMax.y,k0.y);const vu={footprintVertexOffset:Qj,footprintVertexLength:this.footprintsVertices.length-Qj,footprintIndexOffset:J6,footprintIndexLength:this.footprintsIndices.length-J6,min:N0,max:k0,hiddenFlags:0,indicesOffset:aV,indicesLength:B_e,bloomIndicesOffset:vh,bloomIndicesLength:Fl,groundEffectVertexOffset:JC,groundEffectVertexLength:eI,hasFauxFacade:jr,height:X6,promoteId:ct,feature:Wt,parts:gu,buildingBloom:cp},rc=this.footprints.length;We.id!==void 0&&this.featureFootprintLookup.set(We.id,rc),be(Nt,rc),this.footprints.push(vu)}this.programConfigurations.populatePaintArrays(Za.layoutVertexArray.length,We,nt,{},x.availableImages,k,x.brightness),this.groundEffect.addPaintPropertiesData(We,nt,{},x.availableImages,k,x.brightness),x.featureIndex.insert(We,Ft,nt,ft,this.index,wm)}ie.forEach(({buildingId:We,footprintIndex:ct})=>{ue.has(We)&&(this.footprints[ct].hiddenFlags|=4)});const ze=new Set;this.buildingIds.forEach((We,ct,nt)=>{ue.has(We)||ze.add(We)}),this.buildingIds=ze,this.groundEffect.prepareBorderSegments()}update(m,x,k,T,P,R,U){this.programConfigurations.updatePaintArrays(m,x,P,k,T,R,U),this.groundEffect.update(m,x,P,k,T,R,U),this.evaluate(this.layers[0],m),this.colorBufferUploaded=!1}isEmpty(){return this.buildingWithoutFacade.layoutVertexArray.length===0&&this.buildingWithFacade.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload||this.groundEffect.programConfigurations.needsUpload}upload(m){const x=k=>{k.layoutVertexBuffer=m.createVertexBuffer(k.layoutVertexArray,ORe.members),k.layoutNormalBuffer=m.createVertexBuffer(k.layoutNormalArray,uCt.members),k.layoutCentroidBuffer=m.createVertexBuffer(k.layoutCentroidArray,hCt.members),k.layoutFloodLightDataBuffer=m.createVertexBuffer(k.layoutFloodLightDataArray,gCt.members),k.layoutFacadeDataArray&&k.layoutFacadeDataArray.length&&(k.layoutFacadeDataBuffer=m.createVertexBuffer(k.layoutFacadeDataArray,pCt.members)),k.layoutFacadeVerticalRangeArray&&k.layoutFacadeVerticalRangeArray.length&&(k.layoutFacadeVerticalRangeBuffer=m.createVertexBuffer(k.layoutFacadeVerticalRangeArray,fCt.members)),k.entranceBloom.layoutVertexArray.length&&(k.entranceBloom.layoutVertexBuffer=m.createVertexBuffer(k.entranceBloom.layoutVertexArray,ORe.members),k.entranceBloom.layoutAttenuationBuffer=m.createVertexBuffer(k.entranceBloom.layoutAttenuationArray,xCt.members)),this.uploadUpdatedColorBuffer(m),this.uploadUpdatedIndexBuffer(m)};this.uploaded||(x(this.buildingWithoutFacade),x(this.buildingWithFacade),this.groundEffect.upload(m)),this.groundEffect.uploadPaintProperties(m),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){const m=x=>{x.layoutVertexBuffer&&(x.layoutVertexBuffer.destroy(),x.layoutNormalBuffer.destroy(),x.layoutColorBuffer.destroy(),x.segmentsBucket.destroy(),x.indexBuffer&&x.indexBuffer.destroy(),x.entranceBloom.layoutVertexBuffer&&(x.entranceBloom.layoutVertexBuffer.destroy(),x.entranceBloom.layoutColorBuffer.destroy(),x.entranceBloom.layoutAttenuationBuffer.destroy(),x.entranceBloom.indexBuffer.destroy(),x.entranceBloom.segmentsBucket.destroy()))};m(this.buildingWithoutFacade),m(this.buildingWithFacade),this.groundEffect.destroy(),this.programConfigurations.destroy()}updateFootprintHiddenFlags(m,x,k=!0){let T=!1;const P=k?x:0,R=0|(k?-1:~x);this.groundEffect.hiddenByLandmarkVertexArray.length===0&&this.groundEffect.hiddenByLandmarkVertexArray.resize(this.groundEffect.vertexArray.length);for(const U of m){const V=this.footprints[U],X=V.hiddenFlags&R|P;V.hiddenFlags!==X&&(V.hiddenFlags=X,T=!0,this.groundEffect.updateHiddenByLandmarkRange(V.groundEffectVertexOffset,V.groundEffectVertexLength,V.hiddenFlags!==0))}return T&&(this.indexArrayForConflationUploaded=!1),T}uploadUpdatedIndexBuffer(m){if(this.groundEffect.uploadHiddenByLandmark(m),this.indexArrayForConflationUploaded)return;const x=T=>{T.indexArray.length!==0&&(T.indexArrayForConflation.resize(T.indexArray.length),T.indexArrayForConflation.uint16.set(T.indexArray.uint16),T.entranceBloom.indexArrayForConflation.resize(T.entranceBloom.indexArray.length),T.entranceBloom.indexArrayForConflation.uint16.set(T.entranceBloom.indexArray.uint16))};x(this.buildingWithoutFacade),x(this.buildingWithFacade);for(const T of this.footprints){const P=T.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade,R=T.indicesOffset+T.indicesLength;if(T.hiddenFlags!==0){for(let V=T.indicesOffset;V{T.indexArray.length!==0&&(T.indexBuffer?T.indexBuffer.updateData(T.indexArrayForConflation):T.indexBuffer=m.createIndexBuffer(T.indexArrayForConflation,!0),T.entranceBloom.indexBuffer?T.entranceBloom.indexBuffer.updateData(T.entranceBloom.indexArrayForConflation):T.entranceBloom.indexBuffer=m.createIndexBuffer(T.entranceBloom.indexArrayForConflation,!0))};k(this.buildingWithoutFacade),k(this.buildingWithFacade),this.indexArrayForConflationUploaded=!0}uploadUpdatedColorBuffer(m){const x=k=>{k.layoutColorBuffer?k.layoutColorBuffer.updateData(k.layoutColorArray):k.layoutColorBuffer=m.createVertexBuffer(k.layoutColorArray,FRe.members,!0),k.layoutFacadePaintArray&&(k.layoutFacadePaintBuffer?k.layoutFacadePaintBuffer.updateData(k.layoutFacadePaintArray):k.layoutFacadePaintBuffer=m.createVertexBuffer(k.layoutFacadePaintArray,mCt.members,!0)),k.entranceBloom.layoutColorBuffer?k.entranceBloom.layoutColorBuffer.updateData(k.entranceBloom.layoutColorArray):k.entranceBloom.layoutColorBuffer=m.createVertexBuffer(k.entranceBloom.layoutColorArray,FRe.members,!0)};x(this.buildingWithoutFacade),x(this.buildingWithFacade),this.colorBufferUploaded=!0}evaluate(m,x){const k=m.paint.get("building-ambient-occlusion-intensity");for(const T of this.footprints){if(4&T.hiddenFlags)continue;const P=x[T.promoteId],R=T.feature;R.properties["building-part"]="roof";const U=m.paint.get("building-color").evaluate(R,P,this.canonical).toPremultipliedRenderColor(this.lut),V=m.paint.get("building-emissive-strength").evaluate(R,P,this.canonical);R.properties["building-part"]="wall";const X=m.paint.get("building-color").evaluate(R,P,this.canonical).toPremultipliedRenderColor(this.lut),ie=m.paint.get("building-emissive-strength").evaluate(R,P,this.canonical);R.properties["building-part"]="window";const ue=m.paint.get("building-color").evaluate(R,P,this.canonical).toPremultipliedRenderColor(this.lut),pe=m.paint.get("building-emissive-strength").evaluate(R,P,this.canonical);R.properties["building-part"]="door";const be=m.paint.get("building-color").evaluate(R,P,this.canonical).toPremultipliedRenderColor(this.lut),Se=m.paint.get("building-emissive-strength").evaluate(R,P,this.canonical),Le=T.hasFauxFacade?this.buildingWithFacade:this.buildingWithoutFacade;for(const We of T.parts){let ct,nt=U;We.part===1?(nt=U,ct=V):We.part===0?(nt=X,ct=ie):We.part===2?(nt=ue,ct=pe):We.part===3&&(nt=be,ct=Se),ct=Qe(ct,0,1);for(let ft=0;ftR.max.x||V.max.xR.max.y||V.max.yU.max.x||U.min.x>m||x>U.max.y||U.min.y>x||U.height<=k||bCt(R,this.footprintsVertices.float32.subarray(2*U.footprintVertexOffset,2*(U.footprintVertexOffset+U.footprintVertexLength)),this.footprintsIndices.uint16.subarray(U.footprintIndexOffset,U.footprintIndexOffset+U.footprintIndexLength))&&(k=U.height,this.footprintLookup[P]=U,T=U.hiddenFlags!==0);if(k!==Number.NEGATIVE_INFINITY)return{height:k,hidden:T};this.footprintLookup[P]=void 0}}function bCt(b,m,x){for(let k=0;k1&&(V=m[++U]);const ie=Math.abs(X-V.left),ue=Math.abs(X-V.right),pe=Math.min(ie,ue);let be;const Se=P/k*(T+1);if(V.isDash){const Le=T-Math.abs(Se);be=Math.sqrt(pe*pe+Le*Le)}else be=T-Math.sqrt(pe*pe+Se*Se);this.image.data[R+X]=Math.max(0,Math.min(255,be+128))}}}addRegularDash(m,x){for(let V=m.length-1;V>=0;--V){const X=m[V],ie=m[V+1];X.zeroLength?m.splice(V,1):ie&&ie.isDash===X.isDash&&(ie.left=X.left,m.splice(V,1))}const k=m[0],T=m[m.length-1];k.isDash===T.isDash&&(k.left=T.left-this.width,T.right=k.right+this.width);const P=this.width*this.nextRow;let R=0,U=m[R];for(let V=0;V1&&(U=m[++R]);const X=Math.abs(V-U.left),ie=Math.abs(V-U.right),ue=Math.min(X,ie);this.image.data[P+V]=Math.max(0,Math.min(255,(U.isDash?ue:-ue)+x+128))}}addDash(m,x){const k=this.getKey(m,x);if(this.positions[k])return this.positions[k];const T=x==="round",P=T?7:0,R=2*P+1;if(this.nextRow+R>this.height)return Yn("LineAtlas out of space"),null;m.length===0&&m.push(1);let U=0;for(let ue=0;uex.fqid),this.index=m.index,this.projection=m.projection,this.hasPattern=!1,this.hasCrossSlope=!1,this.patternFeatures=[],this.lineClipsArray=[],this.gradients={},this.layers.forEach(x=>{this.gradients[x.id]={}}),this.layoutVertexArray=new MC,this.layoutVertexArray2=new gg,this.patternVertexArray=new gg,this.indexArray=new tc,this.programConfigurations=new qe(m.layers,{zoom:m.zoom,lut:m.lut}),this.segments=new Po,this.maxLineLength=0,this.zOffsetVertexArray=new gg,this.elevationGroundScaleVertexArray=new no,this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.tessellationStep=m.tessellationStep?m.tessellationStep:128,this.worldview=m.worldview,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,T){this.hasPattern=vbe("line",this.layers,this.pixelRatio,x);const P=this.layers[0].layout.get("line-sort-key");this.tileToMeter=cn(k);const R=this.layers[0].layout.get("line-elevation-reference");if(R==="hd-road-markup")this.elevationType="road";else{const pe=this.layers[0].layout.get("line-z-offset"),be=pe.isConstant()&&!pe.constantOr(0);this.elevationType=R!=="sea"&&R!=="ground"&&be?"none":"offset",this.elevationType==="offset"&&R==="none"&&Yn(`line-elevation-reference: ground is used for the layer ${this.layerIds[0]} because non-zero line-z-offset value was found.`),this.isSeaLevelReference=R==="sea"}const U=this.layers[0].layout.get("line-cross-slope");this.hasCrossSlope=this.elevationType==="offset"&&U!==void 0;const V=[];for(const{feature:pe,id:be,index:Se,sourceLayerIndex:Le}of m){const ze=this.layers[0]._featureFilter.needGeometry,We=Ha(pe,ze);if(!this.layers[0]._featureFilter.filter(new Aa(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),We,k))continue;const ct=P?P.evaluate(We,{},k):void 0,nt={id:be,properties:pe.properties,type:pe.type,sourceLayerIndex:Le,index:Se,geometry:ze?We.geometry:Vr(pe,k,T),patterns:{},sortKey:ct};V.push(nt)}P&&V.sort((pe,be)=>pe.sortKey-be.sortKey);const{lineAtlas:X,featureIndex:ie}=x,ue=this.addConstantDashes(X);for(const pe of V){const{geometry:be,index:Se,sourceLayerIndex:Le}=pe;if(ue&&this.addFeatureDashes(pe,X),this.hasPattern){const ze=bbe("line",this.layers,pe,this.zoom,this.pixelRatio,x);this.patternFeatures.push(ze)}else this.addFeature(pe,be,Se,k,X.positions,x.availableImages,x.brightness,x.elevationFeatures);ie.insert(m[Se].feature,be,Se,Le,this.index)}}addConstantDashes(m){let x=!1;for(const k of this.layers){const T=k.paint.get("line-dasharray").value,P=k.layout.get("line-cap").value;if(T.kind!=="constant"||P.kind!=="constant")x=!0;else{const R=P.value,U=T.value;if(!U)continue;m.addDash(U,R)}}return x}addFeatureDashes(m,x){const k=this.zoom;for(const T of this.layers){const P=T.paint.get("line-dasharray").value,R=T.layout.get("line-cap").value;if(P.kind==="constant"&&R.kind==="constant")continue;let U,V;if(P.kind==="constant"){if(U=P.value,!U)continue}else U=P.evaluate({zoom:k},m);V=R.kind==="constant"?R.value:R.evaluate({zoom:k},m),x.addDash(U,V),m.patterns[T.id]=[x.getKey(U,V)]}}update(m,x,k,T,P,R,U,V,X){this.programConfigurations.updatePaintArrays(m,x,P,k,T,R,U,X)}addFeatures(m,x,k,T,P,R){for(const U of this.patternFeatures)this.addFeature(U,U.geometry,U.index,x,k,T,R,m.elevationFeatures)}isEmpty(){return this.layoutVertexArray.length===0}uploadPending(){return!this.uploaded||this.programConfigurations.needsUpload}upload(m){this.uploaded||(this.layoutVertexArray2.length!==0&&(this.layoutVertexBuffer2=m.createVertexBuffer(this.layoutVertexArray2,CCt)),this.patternVertexArray.length!==0&&(this.patternVertexBuffer=m.createVertexBuffer(this.patternVertexArray,ECt)),!this.zOffsetVertexBuffer&&this.zOffsetVertexArray.length>0&&(this.zOffsetVertexBuffer=m.createVertexBuffer(this.zOffsetVertexArray,jCt.members,!0)),!this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexArray.length>0&&(this.elevationGroundScaleVertexBuffer=m.createVertexBuffer(this.elevationGroundScaleVertexArray,NCt.members,!0)),this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,kCt),this.indexBuffer=m.createIndexBuffer(this.indexArray)),this.programConfigurations.upload(m),this.uploaded=!0}destroy(){this.layoutVertexBuffer&&(this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.elevationGroundScaleVertexBuffer&&this.elevationGroundScaleVertexBuffer.destroy(),this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy())}lineFeatureClips(m,x){let k,T;if(x&&x>0?(k=`mapbox_clip_start_${x}`,T=`mapbox_clip_end_${x}`):(k="mapbox_clip_start",T="mapbox_clip_end"),m.properties&&m.properties.hasOwnProperty(k)&&m.properties.hasOwnProperty(T))return{start:+m.properties[k],end:+m.properties[T]}}addFeature(m,x,k,T,P,R,U,V){const X=this.layers[0].layout,ie=X.get("line-join").evaluate(m,{}),ue=X.get("line-cap").evaluate(m,{}),pe=X.get("line-miter-limit"),be=X.get("line-round-limit");this.lineClips=this.lineFeatureClips(m),this.lineFeature=m;const Se=!(!m.properties||!m.properties.hasOwnProperty("mapbox_line_metrics"))&&m.properties.mapbox_line_metrics;this.zOffsetValue=X.get("line-z-offset").value;const Le=this.layers[0].paint.get("line-width").value;if(Le.kind!=="constant"&&Le.isLineProgressConstant===!1&&(this.variableWidthValue=Le),this.isSeaLevelReference){const ze=X.get("line-elevation-ground-scale").value;ze.kind==="constant"&&ze.value===0||(this.elevationGroundScaleValue=ze)}if(this.elevationType==="road"){const ze=this.layoutVertexArray.length;if(!this.addElevatedRoadFeature(m,x,T,V,ie,ue,pe,be)){const[We,ct]=this.clipRuntimeLinesToTile(x,1);for(let nt=0;nt0?wt.parentIndex:null)}this.fillNonElevatedRoadSegment(ze)}}else for(let ze=0;ze0?ze:null);this.programConfigurations.populatePaintArrays(this.layoutVertexArray.length,m,k,P,R,T,U,void 0,this.worldview)}computeSegNextDir(m,x){return m.nextPoint.sub(x.at(-2)).unit()}computeSegPrevDir(m,x){return x[1].sub(m.prevPoint).unit()}clipLinesToTile(m,x){return _q(m,-x,-x,Bn+x,Bn+x)}clipRuntimeLinesToTile(m,x){const k=[];return[_q(m,-x,-x,Bn+x,Bn+x,k),k]}addElevatedRoadFeature(m,x,k,T,P,R,U,V){const X=[],ie=zo.getElevationFeature(m,T);if(ie){const ue=this.clipLinesToTile(x,1),pe=this.prepareElevatedLines(ue,ie,k);for(const be of pe)X.push({geometry:be,elevation:ie,elevationTileID:k,segment:{progress:{min:0,max:1},nextDir:void 0,prevDir:void 0}})}if(X.length===0)return!1;for(const ue of X){const pe=this.layoutVertexArray.length;this.addLine(ue.geometry,m,k,P,R,U,V);const be=new Vo(k,ue.elevationTileID);if(ue.elevation)for(let Se=pe;Se>1,this.layoutVertexArray.int16[6*Se+1]>>1),ze=be.pointElevation(Le,ue.elevation,.05);this.updateHeightRange(ze),this.zOffsetVertexArray.emplaceBack(ze,0,0)}else this.fillNonElevatedRoadSegment(pe)}return!0}prepareElevatedLines(m,x,k){if(x.constantHeight!=null)return m;const T=[],P=1/cn(k);for(const R of m)U4t(R,new kx(x,P),0,T);return T}fillNonElevatedRoadSegment(m){for(let x=m;x0,pe=V&&V.progress.max<1;if(this.lineClips){let Gt={min:this.lineClips.start,max:this.lineClips.end},Ut=1;if(V){const qs=this.lineClips.end-this.lineClips.start;Gt=function(Xs,sn,Js){return{min:Zi(Xs.min,sn,Js),max:Zi(Xs.max,sn,Js)}}(V.progress,{min:0,max:1},Gt),qs>0&&(Ut=(Gt.max-Gt.min)/qs)}const qt=+x.properties.mapbox_clip_feature_len,zs=+x.properties.mapbox_clip_seg_len;if(Number.isNaN(qt)||Number.isNaN(zs)){for(let Xs=0;Xs=2&&m[Se-1].equals(m[Se-2]);)Se--;let Le=0;for(;Le0,en=this.overscaling<=16?122880/(512*this.overscaling):0;if(Ut&&qt==="round"){if(snR&&(qt="bevel"),qt==="bevel"&&(sn>2&&(qt="flipbevel"),sn2*en){const Cn=We.sub(We.sub(ct)._mult(en/on)._round());this.updateDistance(ct,Cn),this.addCurrentVertex(Cn,ft,0,0,ze,Ft),ct=Cn}this.updateDistance(ct,We),qs._mult(sn),this.addCurrentVertex(We,qs,0,0,ze,Ft);const gn=We.dist(nt);if(gn>2*en){const Cn=We.add(nt.sub(We)._mult(en/gn)._round());this.updateDistance(We,Cn),this.addCurrentVertex(Cn,wt,0,0,ze,Ft),We=Cn}}else qs._mult(sn),this.addCurrentVertex(We,qs,0,0,ze,Ft);else if(qt==="flipbevel"){if(sn>100)qs=wt.mult(-1);else{const on=sn*ft.add(wt).mag()/ft.sub(wt).mag();qs._perp()._mult(on*(Os?-1:1))}this.addCurrentVertex(We,qs,0,0,ze,Ft),this.addCurrentVertex(We,qs.mult(-1),0,0,ze,Ft)}else if(qt==="bevel"||qt==="fakeround"){const on=We.dist(ct);let gn=1;if(this.elevationType==="offset"&&qt==="bevel"&&this.currentLineJoinType!=="round"&&!this.patternJoinNone&&Ft!=null&&ct&&nt){const sr=4*en;on1){this.lineSoFar=m.w;const Le=(x.x-m.x)/ue,ze=(x.y-m.y)/ue,We=(x.z-m.z)/ue,ct=(x.w-m.w)/ue,nt=x.x-m.x,ft=x.y-m.y,wt=Math.sqrt(nt*nt+ft*ft);if(wt===0)return;const Nt=-ft/wt,Wt=nt/wt,Ft=Nt,Gt=Wt,Ut=-Nt,qt=-Wt;for(let zs=1;zs=0&&this.e2>=0&&(this.indexArray.emplaceBack(this.e1,this.e2,ie),V.primitiveLength++),R?this.e2=ie:this.e1=ie,X!=null&&this.zOffsetVertexArray.emplaceBack(X.zOffset,X.variableWidth,X.variableWidth),this.elevationGroundScaleValue){const ue=X?X.elevationGroundScale:this.evaluateElevationGroundScale();this.elevationGroundScaleVertexArray.emplaceBack(ue)}}updateScaledDistance(){this.lineClips?(this.scaledDistance=this.distance/this.totalDistance,this.lineSoFar=this.totalFeatureLength*this.lineClips.start+this.distance):this.lineSoFar=this.distance}updateDistance(m,x){this.prevDistance=this.distance,this.distance+=m.dist(x),this.updateScaledDistance()}}function Qbe(b,m,x){return b.xx||b.yx}let VRe,HRe;function GRe(b,m,x){return m*(Bn/(b.tileSize*Math.pow(2,x-b.tileID.overscaledZ)))}Kn(Mq,"LineBucket",{omit:["layers","patternFeatures","currentVertex","currentVertexIsOutside"]});const WRe=(b,m,x)=>(1-x)*b+x*m;function KRe(b,m){return 1/GRe(b,1,m.tileZoom)}function YRe(b,m,x,k){return b.translatePosMatrix(k||m.tileID.projMatrix,m,x.paint.get("line-translate"),x.paint.get("line-translate-anchor"))}const ZRe=b=>{const m=[];QRe(b)&&m.push("RENDER_LINE_DASH"),b.paint.get("line-gradient")&&m.push("RENDER_LINE_GRADIENT"),b.paint.get("line-blend-mode")==="multiply"&&m.push("LINE_BLEND_MULTIPLY");const x=b.paint.get("line-trim-offset");x[0]===0&&x[1]===0||m.push("RENDER_LINE_TRIM_OFFSET"),b.paint.get("line-border-width").constantOr(1)!==0&&m.push("RENDER_LINE_BORDER");const k=b.layout.get("line-join").constantOr("miter")==="none",T=!!b.paint.get("line-pattern").constantOr(1);return k&&T&&m.push("LINE_JOIN_NONE"),m};function QRe(b){const m=b.paint.get("line-dasharray").value;return m.kind!=="constant"||m.value}let Xbe;const XRe=()=>Xbe||(Xbe={layout:VRe||(VRe=new qo({"line-cap":new bn(ps.layout_line["line-cap"]),"line-join":new bn(ps.layout_line["line-join"]),"line-miter-limit":new wn(ps.layout_line["line-miter-limit"]),"line-round-limit":new wn(ps.layout_line["line-round-limit"]),"line-sort-key":new bn(ps.layout_line["line-sort-key"]),"line-z-offset":new bn(ps.layout_line["line-z-offset"]),"line-elevation-reference":new wn(ps.layout_line["line-elevation-reference"]),"line-cross-slope":new wn(ps.layout_line["line-cross-slope"]),visibility:new wn(ps.layout_line.visibility),"line-width-unit":new wn(ps.layout_line["line-width-unit"]),"line-elevation-ground-scale":new bn(ps.layout_line["line-elevation-ground-scale"])})),paint:HRe||(HRe=new qo({"line-opacity":new bn(ps.paint_line["line-opacity"]),"line-color":new bn(ps.paint_line["line-color"]),"line-translate":new wn(ps.paint_line["line-translate"]),"line-translate-anchor":new wn(ps.paint_line["line-translate-anchor"]),"line-width":new bn(ps.paint_line["line-width"]),"line-gap-width":new bn(ps.paint_line["line-gap-width"]),"line-offset":new bn(ps.paint_line["line-offset"]),"line-blur":new bn(ps.paint_line["line-blur"]),"line-dasharray":new bn(ps.paint_line["line-dasharray"]),"line-pattern":new bn(ps.paint_line["line-pattern"]),"line-pattern-cross-fade":new wn(ps.paint_line["line-pattern-cross-fade"]),"line-gradient":new Vp(ps.paint_line["line-gradient"]),"line-trim-offset":new wn(ps.paint_line["line-trim-offset"]),"line-trim-fade-range":new wn(ps.paint_line["line-trim-fade-range"]),"line-trim-color":new wn(ps.paint_line["line-trim-color"]),"line-emissive-strength":new bn(ps.paint_line["line-emissive-strength"]),"line-border-width":new bn(ps.paint_line["line-border-width"]),"line-border-color":new bn(ps.paint_line["line-border-color"]),"line-occlusion-opacity":new wn(ps.paint_line["line-occlusion-opacity"]),"line-blend-mode":new wn(ps.paint_line["line-blend-mode"]),"line-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"line-gradient-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"line-trim-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"line-border-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"})}))},Xbe);class PCt extends bn{possiblyEvaluate(m,x){return x=new Aa(Math.floor(x.zoom),{now:x.now,fadeDuration:x.fadeDuration,transition:x.transition,worldview:x.worldview}),super.possiblyEvaluate(m,x)}evaluate(m,x,k,T){return x=Object.assign({},x,{zoom:Math.floor(x.zoom)}),super.evaluate(m,x,k,T)}}let pO;function JRe(b,m){return m>0?m+2*b:b}const LCt=ln([{name:"a_pos_offset",components:4,type:"Int16"},{name:"a_tex_size",components:4,type:"Uint16"},{name:"a_pixeloffset",components:4,type:"Int16"}],4),DCt=ln([{name:"a_globe_anchor",components:3,type:"Int16"},{name:"a_globe_normal",components:3,type:"Float32"}],4),RCt=ln([{name:"a_projected_pos",components:4,type:"Float32"}],4);ln([{name:"a_fade_opacity",components:1,type:"Uint32"}],4);const OCt=ln([{name:"a_auto_z_offset",components:1,type:"Float32"}],4),FCt=ln([{name:"a_feature_index",components:1,type:"Float32"}],4),zCt=ln([{name:"a_x_axis",components:3,type:"Float32"},{name:"a_y_axis",components:3,type:"Float32"}]),BCt=ln([{name:"a_texb",components:2,type:"Uint16"}]),$Ct=ln([{name:"a_placed",components:2,type:"Uint8"},{name:"a_shift",components:2,type:"Float32"},{name:"a_elevation_from_sea",components:2,type:"Float32"}]),UCt=ln([{name:"a_size_scale",components:1,type:"Float32"},{name:"a_padding",components:2,type:"Float32"},{name:"a_auto_z_offset",components:1,type:"Float32"}]);ln([{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 eOe=ln([{name:"a_pos",components:3,type:"Int16"},{name:"a_anchor_pos",components:2,type:"Int16"},{name:"a_extrude",components:2,type:"Int16"}],4),qCt=ln([{name:"a_pos_2f",components:2,type:"Float32"},{name:"a_radius",components:1,type:"Float32"},{name:"a_flags",components:2,type:"Int16"}],4);ln([{name:"triangle",components:3,type:"Uint16"}]),ln([{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"}]),ln([{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"}]),ln([{type:"Float32",name:"offsetX"}]),ln([{type:"Int16",name:"x"},{type:"Int16",name:"y"}]);const Jbe=class yme{constructor(m=null,x=0,k=4096){this.batchIndex=x,this.headerBuffer=null,this.propertiesBuffer=null,this.blockIndicesBuffer=null,this.context=m||null,this.propsDwords=k,this.totalBytes=4*this.propsDwords,this.headerData=new Uint32Array(yme.HEADER_DWORDS),this.propertiesData=new Float32Array(this.propsDwords),this.blockIndicesData=new Uint32Array(this.propsDwords);for(let T=0;Tm.maxUniformBlockSize)throw new Error(`UBO size ${this.totalBytes} exceeds device limit ${m.maxUniformBlockSize}`);if(this.headerBuffer=x.createBuffer(),!this.headerBuffer)throw new Error("Failed to create header UBO buffer");if(x.bindBuffer(x.UNIFORM_BUFFER,this.headerBuffer),x.bufferData(x.UNIFORM_BUFFER,yme.HEADER_BYTES,x.DYNAMIC_DRAW),this.propertiesBuffer=x.createBuffer(),!this.propertiesBuffer)throw new Error("Failed to create properties UBO buffer");if(x.bindBuffer(x.UNIFORM_BUFFER,this.propertiesBuffer),x.bufferData(x.UNIFORM_BUFFER,this.totalBytes,x.DYNAMIC_DRAW),this.blockIndicesBuffer=x.createBuffer(),!this.blockIndicesBuffer)throw new Error("Failed to create block-indices UBO buffer");x.bindBuffer(x.UNIFORM_BUFFER,this.blockIndicesBuffer),x.bufferData(x.UNIFORM_BUFFER,this.totalBytes,x.DYNAMIC_DRAW),x.bindBuffer(x.UNIFORM_BUFFER,null)}writeHeader(m){const x=this.headerData;x[0]=m.dataDrivenMask,x[1]=m.zoomDependentMask,x[2]=m.dataDrivenBlockSizeVec4,x[3]=m.offsets[0],x[4]=m.offsets[1],x[5]=m.offsets[2],x[6]=m.offsets[3],x[7]=m.offsets[4],x[8]=m.offsets[5],x[9]=m.offsets[6],x[10]=m.offsets[7],x[11]=m.offsets[8]}writeDataDrivenBlock(m,x,k){const T=4*k.dataDrivenBlockSizeVec4;if(T===0)return;const P=x*T;if(P+T>this.propertiesData.length)throw new Error(`UBO write out of bounds: feature index ${x} exceeds propertiesData capacity`);for(let R=0;R<9;R++)k.dataDrivenMask&1<{if(!U)return;const X=k.getUniformBlockIndex(x,R);X!==k.INVALID_INDEX&&(k.uniformBlockBinding(x,X,V),k.bindBufferBase(k.UNIFORM_BUFFER,V,U))},P=3*this.batchIndex;T("SymbolPaintPropertiesHeaderUniform",this.headerBuffer,P),T("SymbolPaintPropertiesUniform",this.propertiesBuffer,P+1),T("SymbolPaintPropertiesIndexUniform",this.blockIndicesBuffer,P+2)}destroy(){if(this.context){const m=this.context.gl;this.headerBuffer&&(m.deleteBuffer(this.headerBuffer),this.headerBuffer=null),this.propertiesBuffer&&(m.deleteBuffer(this.propertiesBuffer),this.propertiesBuffer=null),this.blockIndicesBuffer&&(m.deleteBuffer(this.blockIndicesBuffer),this.blockIndicesBuffer=null)}}};Jbe.HEADER_DWORDS=12,Jbe.HEADER_BYTES=48;let e_e=Jbe;function t_e(b,m,x,k){return[M6(255*b,255*m),M6(255*x,255*k)]}function tOe(b,m,x,k,T,P,R,U){return!!b&&(b.kind==="constant"?b.value==="none":b.kind==="composite"||b.kind==="source"?b.evaluate({zoom:0,brightness:P,worldview:U},m,x,T,k,R)==="none":typeof b=="string"&&b==="none")}Kn(e_e,"SymbolPropertiesUBO",{omit:["headerBuffer","propertiesBuffer","blockIndicesBuffer"]});class s_e{constructor(m,x,k,T,P="",R,U){this.layer=m,this.zoom=x,this.lut=k,this.isText=T,this.propDefs=this._getPropDefs(),this.worldview=P,this.maxUniformBufferBindings=R||24,this.uboSizeDwords=U||4096,this.featureVertexRangesFromId=new Map,this.allFeatures=[],this.ubos=[],this.featureCount=0,this.cachedHeader=null,this.maxFeaturesPerBatch=0,this.propertyHashToUBOIndex=new Map,this.canDeduplicate=this._checkIfAllPropertiesAreConstant(m,T),this.cachedParams=null,this.cachedParamsNext=null,this.cachedBrightness=void 0,this.cachedConstantUniforms=null,this.cachedConstantRenderZoom=null,this.cachedConstantBrightness=void 0,this.activeAppearanceByVtIndex=new Map}_getPropDefs(){const m=this.isText?"text":"icon";return[{name:`${m}-color`,useThemeName:`${m}-color-use-theme`,isColor:!0},{name:`${m}-halo-color`,useThemeName:`${m}-halo-color-use-theme`,isColor:!0},{name:`${m}-opacity`,useThemeName:null,isColor:!1},{name:`${m}-halo-width`,useThemeName:null,isColor:!1},{name:`${m}-halo-blur`,useThemeName:null,isColor:!1},{name:`${m}-emissive-strength`,useThemeName:null,isColor:!1},{name:`${m}-occlusion-opacity`,useThemeName:null,isColor:!1},{name:"symbol-z-offset",useThemeName:null,isColor:!1},{name:`${m}-translate`,useThemeName:null,isColor:!1,isVec2:!0}]}buildHeader(){const m=this.layer.paint,x=this.propDefs;let k=0,T=0,P=0,R=0;const U=[0,0,0,0,0,0,0,0,0];for(let V=0;V<9;V++){const{name:X,isColor:ie,isVec2:ue}=x[V],pe=m.get(X),be=!(!pe||typeof pe.isConstant!="function"||pe.isConstant()),Se=this._appearancesHavePaintProperties(X),Le=be||Se,ze=!(!pe||!pe.value||pe.value.kind!=="composite"),We=this.layer._transitionablePaint._values[X],ct=!Le&&(We&&We.value&&We.value.expression&&We.value.expression.kind)==="camera";Le?(k|=1<x.hasPaintProperty(m):this.isText?x=>x.hasTextPaintProperties():x=>x.hasIconPaintProperties())}_checkIfAllPropertiesAreConstant(m,x){const k=m.paint,T=x?"text":"icon",P=[`${T}-color`,`${T}-halo-color`,`${T}-opacity`,`${T}-halo-width`,`${T}-halo-blur`,`${T}-emissive-strength`,`${T}-occlusion-opacity`,"symbol-z-offset",`${T}-translate`];for(const R of P){const U=k.get(R);if(U&&typeof U=="object"&&"isConstant"in U&&!U.isConstant())return!1}return!this._appearancesHavePaintProperties()}_hashDataDrivenValues(m,x){if(x.dataDrivenMask===0)return"";const k=[];for(let T=0;T<9;T++){if(!(x.dataDrivenMask&1<=Se){Yn(`Too many symbol features: batch ${pe} requires binding points up to ${3*pe+2}, device limit ${Se}. Some features will render incorrectly.`);const ze={batchIndex:0,localFeatureIndex:0,vtFeatureIndex:x,featureId:V};return this.allFeatures.push(ze),V!=null&&(this.featureVertexRangesFromId.has(V)||this.featureVertexRangesFromId.set(V,[]),this.featureVertexRangesFromId.get(V).push(ze)),0}this.ubos[pe]||(this.ubos[pe]=new e_e(U,pe,this.uboSizeDwords),this.ubos[pe].writeHeader(X)),this.ubos[pe].writeDataDrivenBlock(ie,be,X);const Le={batchIndex:pe,localFeatureIndex:be,vtFeatureIndex:x,featureId:V};return this.allFeatures.push(Le),V!=null&&(this.featureVertexRangesFromId.has(V)||this.featureVertexRangesFromId.set(V,[]),this.featureVertexRangesFromId.get(V).push(Le)),be}updateFeatures(m,x,k,T,P,R,U){if(this.layer=x,this.cachedConstantUniforms=null,!this.cachedHeader)return;const V=this.cachedHeader;for(const X of m){const ie=this.featureVertexRangesFromId.get(X);if(!ie)continue;const ue=R[X]||{};for(const pe of ie){if(!k)continue;const be=k.feature(pe.vtFeatureIndex);if(!be)continue;const Se={type:be.type,id:X,properties:be.properties||{},geometry:[]},Le=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(pe.vtFeatureIndex):void 0,ze=this.evaluateAllProperties(Se,ue,T,P,U,void 0,Le);this.ubos[pe.batchIndex]&&this.ubos[pe.batchIndex].writeDataDrivenBlock(ze,pe.localFeatureIndex,V)}}}updateDynamicExpressions(m,x,k,T,P,R){if(this.layer=m,this.cachedConstantUniforms=null,!this.cachedHeader)return;const U=this.cachedHeader;for(const V of this.allFeatures){if(!x)continue;const X=x.feature(V.vtFeatureIndex);if(!X)continue;const ie=V.featureId!=null&&P[V.featureId]||{},ue={type:X.type,id:V.featureId,properties:X.properties||{},geometry:[]},pe=this.activeAppearanceByVtIndex?this.activeAppearanceByVtIndex.get(V.vtFeatureIndex):void 0,be=this.evaluateAllProperties(ue,ie,k,T,R,void 0,pe);this.ubos[V.batchIndex]&&this.ubos[V.batchIndex].writeDataDrivenBlock(be,V.localFeatureIndex,U)}}updateFeaturePaintForAppearance(m,x,k,T,P,R,U){if(!this.layer||(this.activeAppearanceByVtIndex||(this.activeAppearanceByVtIndex=new Map),this.activeAppearanceByVtIndex.set(m,U||null),!this.cachedHeader))return!1;const V=this.cachedHeader;if(V.dataDrivenMask===0)return!1;let X=!1;for(const ie of this.allFeatures){if(ie.vtFeatureIndex!==m)continue;const ue=this.evaluateAllProperties(x,k,T,P,R,void 0,U);this.ubos[ie.batchIndex]&&(this.ubos[ie.batchIndex].writeDataDrivenBlock(ue,ie.localFeatureIndex,V),X=!0)}return X}getConstantUniformValues(m,x){const k=this.cachedHeader,T=!(!k||!k.cameraMask);if(this.cachedConstantUniforms&&this.cachedConstantBrightness===x&&(!T||this.cachedConstantRenderZoom===m))return this.cachedConstantUniforms;const P=this.layer.paint,R=this.propDefs,U=T?new Aa(m,{brightness:x,worldview:this.worldview}):null,V={type:1,id:void 0,properties:{},geometry:[]},X=pe=>{const be=R[pe],Se=P.get(be.name);if(!Se)return[0,0,0,1];const Le=be.useThemeName?P.get(be.useThemeName):void 0,ze=tOe(Le&&typeof Le!="string"?Le.value:void 0,V,{},[],void 0,x,void 0,this.worldview)?null:this.lut;let We;We=k&&k.cameraMask&1<{const Se=P.get(R[pe].name);if(!Se)return be;if(k&&k.cameraMask&1<{k.text=function(T,P,R){const U=P.layout.get("text-transform").evaluate(R,{});return U==="uppercase"?T=T.toLocaleUpperCase():U==="lowercase"&&(T=T.toLocaleLowerCase()),_m.applyArabicShaping&&(T=_m.applyArabicShaping(T)),T}(k.text,m,x)}),b}const fO={"!":"︕","#":"#",$:"$","%":"%","&":"&","(":"︵",")":"︶","*":"*","+":"+",",":"︐","-":"︲",".":"・","/":"/",":":"︓",";":"︔","<":"︿","=":"=",">":"﹀","?":"︖","@":"@","[":"﹇","\\":"\","]":"﹈","^":"^",_:"︳","`":"`","{":"︷","|":"―","}":"︸","~":"~","¢":"¢","£":"£","¥":"¥","¦":"¦","¬":"¬","¯":" ̄","–":"︲","—":"︱","‘":"﹃","’":"﹄","“":"﹁","”":"﹂","…":"︙","‧":"・","₩":"₩","、":"︑","。":"︒","〈":"︿","〉":"﹀","《":"︽","》":"︾","「":"﹁","」":"﹂","『":"﹃","』":"﹄","【":"︻","】":"︼","〔":"︹","〕":"︺","〖":"︗","〗":"︘","!":"︕","(":"︵",")":"︶",",":"︐","-":"︲",".":"・",":":"︓",";":"︔","<":"︿",">":"﹀","?":"︖","[":"﹇","]":"﹈","_":"︳","{":"︷","|":"―","}":"︸","⦅":"︵","⦆":"︶","。":"︒","「":"﹁","」":"﹂","←":"↑","→":"↓"};function HCt(b){return b==="︶"||b==="﹈"||b==="︸"||b==="﹄"||b==="﹂"||b==="︾"||b==="︼"||b==="︺"||b==="︘"||b==="﹀"||b==="︐"||b==="︓"||b==="︔"||b==="`"||b===" ̄"||b==="︑"||b==="︒"}function GCt(b){return b==="︵"||b==="﹇"||b==="︷"||b==="﹃"||b==="﹁"||b==="︽"||b==="︻"||b==="︹"||b==="︗"||b==="︿"}const n_e=4294967296,sOe=1/n_e,nOe=typeof TextDecoder>"u"?null:new TextDecoder("utf-8");let Iq=class{constructor(b=new Uint8Array(16)){this.buf=ArrayBuffer.isView(b)?b:new Uint8Array(b),this.dataView=new DataView(this.buf.buffer),this.pos=0,this.type=0,this.length=this.buf.length}readFields(b,m,x=this.length){for(;this.pos>3,P=this.pos;this.type=7&k,b(T,m,this),this.pos===P&&this.skip(k)}return m}readMessage(b,m){return this.readFields(b,m,this.readVarint()+this.pos)}readFixed32(){const b=this.dataView.getUint32(this.pos,!0);return this.pos+=4,b}readSFixed32(){const b=this.dataView.getInt32(this.pos,!0);return this.pos+=4,b}readFixed64(){const b=this.dataView.getUint32(this.pos,!0)+this.dataView.getUint32(this.pos+4,!0)*n_e;return this.pos+=8,b}readSFixed64(){const b=this.dataView.getUint32(this.pos,!0)+this.dataView.getInt32(this.pos+4,!0)*n_e;return this.pos+=8,b}readFloat(){const b=this.dataView.getFloat32(this.pos,!0);return this.pos+=4,b}readDouble(){const b=this.dataView.getFloat64(this.pos,!0);return this.pos+=8,b}readVarint(b){const m=this.buf;let x,k;return k=m[this.pos++],x=127&k,k<128?x:(k=m[this.pos++],x|=(127&k)<<7,k<128?x:(k=m[this.pos++],x|=(127&k)<<14,k<128?x:(k=m[this.pos++],x|=(127&k)<<21,k<128?x:(k=m[this.pos],x|=(15&k)<<28,function(T,P,R){const U=R.buf;let V,X;if(X=U[R.pos++],V=(112&X)>>4,X<128||(X=U[R.pos++],V|=(127&X)<<3,X<128)||(X=U[R.pos++],V|=(127&X)<<10,X<128)||(X=U[R.pos++],V|=(127&X)<<17,X<128)||(X=U[R.pos++],V|=(127&X)<<24,X<128)||(X=U[R.pos++],V|=(1&X)<<31,X<128))return $6(T,V,P);throw new Error("Expected varint not more than 10 bytes")}(x,b,this)))))}readVarint64(){return this.readVarint(!0)}readSVarint(){const b=this.readVarint();return b%2==1?(b+1)/-2:b/2}readBoolean(){return!!this.readVarint()}readString(){const b=this.readVarint()+this.pos,m=this.pos;return this.pos=b,b-m>=12&&nOe?nOe.decode(this.buf.subarray(m,b)):function(x,k,T){let P="",R=k;for(;R239?4:U>223?3:U>191?2:1;if(R+pe>T)break;pe===1?U<128&&(ue=U):pe===2?(V=x[R+1],(192&V)==128&&(ue=(31&U)<<6|63&V,ue<=127&&(ue=null))):pe===3?(V=x[R+1],X=x[R+2],(192&V)==128&&(192&X)==128&&(ue=(15&U)<<12|(63&V)<<6|63&X,(ue<=2047||ue>=55296&&ue<=57343)&&(ue=null))):pe===4&&(V=x[R+1],X=x[R+2],ie=x[R+3],(192&V)==128&&(192&X)==128&&(192&ie)==128&&(ue=(15&U)<<18|(63&V)<<12|(63&X)<<6|63&ie,(ue<=65535||ue>=1114112)&&(ue=null))),ue===null?(ue=65533,pe=1):ue>65535&&(ue-=65536,P+=String.fromCharCode(ue>>>10&1023|55296),ue=56320|1023&ue),P+=String.fromCharCode(ue),R+=pe}return P}(this.buf,m,b)}readBytes(){const b=this.readVarint()+this.pos,m=this.buf.subarray(this.pos,b);return this.pos=b,m}readPackedVarint(b=[],m){const x=this.readPackedEnd();for(;this.pos127;);else if(m===2)this.pos=this.readVarint()+this.pos;else if(m===5)this.pos+=4;else{if(m!==1)throw new Error(`Unimplemented type: ${m}`);this.pos+=8}}writeTag(b,m){this.writeVarint(b<<3|m)}realloc(b){let m=this.length||16;for(;m268435455||b<0?function(m,x){let k,T;if(m>=0?(k=m%4294967296|0,T=m/4294967296|0):(k=~(-m%4294967296),T=~(-m/4294967296),4294967295^k?k=k+1|0:(k=0,T=T+1|0)),m>=18446744073709552e3||m<-18446744073709552e3)throw new Error("Given varint doesn't fit into 10 bytes");x.realloc(10),function(P,R,U){U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,P>>>=7,U.buf[U.pos++]=127&P|128,U.buf[U.pos]=127&(P>>>=7)}(k,0,x),function(P,R){const U=(7&P)<<4;R.buf[R.pos++]|=U|((P>>>=3)?128:0),P&&(R.buf[R.pos++]=127&P|((P>>>=7)?128:0),P&&(R.buf[R.pos++]=127&P|((P>>>=7)?128:0),P&&(R.buf[R.pos++]=127&P|((P>>>=7)?128:0),P&&(R.buf[R.pos++]=127&P|((P>>>=7)?128:0),P&&(R.buf[R.pos++]=127&P)))))}(T,x)}(b,this):(this.realloc(4),this.buf[this.pos++]=127&b|(b>127?128:0),b<=127||(this.buf[this.pos++]=127&(b>>>=7)|(b>127?128:0),b<=127||(this.buf[this.pos++]=127&(b>>>=7)|(b>127?128:0),b<=127||(this.buf[this.pos++]=b>>>7&127))))}writeSVarint(b){this.writeVarint(b<0?2*-b-1:2*b)}writeBoolean(b){this.writeVarint(+b)}writeString(b){b=String(b),this.realloc(4*b.length),this.pos++;const m=this.pos;this.pos=function(k,T,P){for(let R,U,V=0;V55295&&R<57344){if(!U){R>56319||V+1===T.length?(k[P++]=239,k[P++]=191,k[P++]=189):U=R;continue}if(R<56320){k[P++]=239,k[P++]=191,k[P++]=189,U=R;continue}R=U-55296<<10|R-56320|65536,U=null}else U&&(k[P++]=239,k[P++]=191,k[P++]=189,U=null);R<128?k[P++]=R:(R<2048?k[P++]=R>>6|192:(R<65536?k[P++]=R>>12|224:(k[P++]=R>>18|240,k[P++]=R>>12&63|128),k[P++]=R>>6&63|128),k[P++]=63&R|128)}return P}(this.buf,b,this.pos);const x=this.pos-m;x>=128&&rOe(m,x,this),this.pos=m-1,this.writeVarint(x),this.pos+=x}writeFloat(b){this.realloc(4),this.dataView.setFloat32(this.pos,b,!0),this.pos+=4}writeDouble(b){this.realloc(8),this.dataView.setFloat64(this.pos,b,!0),this.pos+=8}writeBytes(b){const m=b.length;this.writeVarint(m),this.realloc(m);for(let x=0;x=128&&rOe(x,k,this),this.pos=x-1,this.writeVarint(k),this.pos+=k}writeMessage(b,m,x){this.writeTag(b,2),this.writeRawMessage(m,x)}writePackedVarint(b,m){m.length&&this.writeMessage(b,WCt,m)}writePackedSVarint(b,m){m.length&&this.writeMessage(b,KCt,m)}writePackedBoolean(b,m){m.length&&this.writeMessage(b,QCt,m)}writePackedFloat(b,m){m.length&&this.writeMessage(b,YCt,m)}writePackedDouble(b,m){m.length&&this.writeMessage(b,ZCt,m)}writePackedFixed32(b,m){m.length&&this.writeMessage(b,XCt,m)}writePackedSFixed32(b,m){m.length&&this.writeMessage(b,JCt,m)}writePackedFixed64(b,m){m.length&&this.writeMessage(b,e3t,m)}writePackedSFixed64(b,m){m.length&&this.writeMessage(b,t3t,m)}writeBytesField(b,m){this.writeTag(b,2),this.writeBytes(m)}writeFixed32Field(b,m){this.writeTag(b,5),this.writeFixed32(m)}writeSFixed32Field(b,m){this.writeTag(b,5),this.writeSFixed32(m)}writeFixed64Field(b,m){this.writeTag(b,1),this.writeFixed64(m)}writeSFixed64Field(b,m){this.writeTag(b,1),this.writeSFixed64(m)}writeVarintField(b,m){this.writeTag(b,0),this.writeVarint(m)}writeSVarintField(b,m){this.writeTag(b,0),this.writeSVarint(m)}writeStringField(b,m){this.writeTag(b,2),this.writeString(m)}writeFloatField(b,m){this.writeTag(b,5),this.writeFloat(m)}writeDoubleField(b,m){this.writeTag(b,1),this.writeDouble(m)}writeBooleanField(b,m){this.writeVarintField(b,+m)}};function $6(b,m,x){return x?4294967296*m+(b>>>0):4294967296*(m>>>0)+(b>>>0)}function rOe(b,m,x){const k=m<=16383?1:m<=2097151?2:m<=268435455?3:Math.floor(Math.log(m)/(7*Math.LN2));x.realloc(k);for(let T=x.pos-1;T>=b;T--)x.buf[T+k]=x.buf[T]}function WCt(b,m){for(let x=0;x=0&&k>=m&&Pq[this.text.charCodeAt(k)];k--)x--;this.text=this.text.substring(m,x),this.sectionIndex=this.sectionIndex.slice(m,x)}substring(m,x){const k=new U6;return k.text=this.text.substring(m,x),k.sectionIndex=this.sectionIndex.slice(m,x),k.sections=this.sections,k}toString(){return this.text}getMaxScale(){return this.sectionIndex.reduce((m,x)=>Math.max(m,this.sections[x].scale),0)}addTextSection(m,x){this.text+=m.text,this.sections.push(xO.forText(m.scale,m.fontStack||x));const k=this.sections.length-1;for(let T=0;T=63743?null:++this.imageSectionID:(this.imageSectionID=57344,this.imageSectionID)}}function r_e(b,m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le=1,ze=1){const We=U6.fromFeature(b,T,Le,ze);ue===Ex.vertical&&We.verticalizePunctuation(pe);let ct=[];const nt=function(Ft,Gt,Ut,qt,zs,qs,Xs=1){if(!Ft)return[];const sn=[],Js=function(en,on,gn,Cn,ar,Fn,Rn=1){let Tn=0;for(let sr=0;sr=0;let Os=0;for(let en=0;en0&&wm>Ga&&(Ga=wm)}else{const gu=Ut[Ml.fontStack];if(!gu)continue;gu[Il]&&(nc=gu[Il]);const cp=Gt[Ml.fontStack];if(!cp)continue;const vh=cp.glyphs[Il];if(!vh)continue;if(Oc=vh.metrics,Zd=Il!==8203?Kd:0,Rn){const Fl=cp.ascender!==void 0?Math.abs(cp.ascender):0,wm=cp.descender!==void 0?Math.abs(cp.descender):0,yu=(Fl+wm)*sc;Ol-x/2;){if(R--,R<0)return!1;U-=b[R].dist(P),P=b[R]}U+=b[R].dist(b[R+1]),R++;const V=[];let X=0;for(;Uk;)X-=V.shift().angleDelta;if(X>T)return!1;R++,U+=ie.dist(ue)}return!0}function pOe(b){let m=0;for(let x=0;xX){const Se=(X-V)/be,Le=Dr(ue.x,pe.x,Se),ze=Dr(ue.y,pe.y,Se),We=new Zj(Le,ze,0,pe.angleTo(ue),ie);return!R||mOe(b,We,U,R,m)?We:void 0}V+=be}}function l3t(b,m,x,k,T,P,R,U,V){const X=fOe(k,P,R),ie=xOe(k,T),ue=ie*R,pe=b[0].x===0||b[0].x===V||b[0].y===0||b[0].y===V;return m-ue=0&&ft=0&&wt=0&&pe+X<=ie){const Nt=new Zj(ft,wt,0,ct,Se);k&&!mOe(b,Nt,P,k,T)||be.push(Nt)}}ue+=We}return U||be.length||R||(be=gOe(b,ue/2,x,k,T,P,R,!0,V)),be}function yOe(b){let m=0,x=0;for(const R of b)m+=R.w*R.h,x=Math.max(x,R.w);b.sort((R,U)=>U.h-R.h);const k=[{x:0,y:0,w:Math.max(Math.ceil(Math.sqrt(m/.95)),x),h:1/0}];let T=0,P=0;for(const R of b)for(let U=k.length-1;U>=0;U--){const V=k[U];if(!(R.w>V.w||R.h>V.h)){if(R.x=V.x,R.y=V.y,P=Math.max(P,R.y+R.h),T=Math.max(T,R.x+R.w),R.w===V.w&&R.h===V.h){const X=k.pop();X&&Um.id?1:b.versionm.version?1:b.sxm.sx?1:b.sym.sy?1:0}function c_e(b){let m=0;for(let x=0;x0,vOe(m,k,this.iconDescriptors,P),vOe(x,k,this.patternDescriptors,P),this.iconDescriptors.sort(Dq),this.patternDescriptors.sort(Dq);let R=0;const U=T?T.data:"";U&&(R=C1(R,c_e(U))),R=C1(R,1);for(const V of this.iconDescriptors)R=C1(R,c_e(V.id)),R=C1(R,V.version),R=C1(R,V.sx),R=C1(R,V.sy);R=C1(R,1);for(const V of this.patternDescriptors)R=C1(R,c_e(V.id)),R=C1(R,V.version),R=C1(R,V.sx),R=C1(R,V.sy);this.hash=R}subsetOf(m){return this.isSubsetArray(this.iconDescriptors,m.iconDescriptors,Dq)&&this.isSubsetArray(this.patternDescriptors,m.patternDescriptors,Dq)}isSubsetArray(m,x,k){let T=0,P=0;if(m.length>x.length)return!1;for(;T{const R=T.variant.id.toString().localeCompare(P.variant.id.toString());return R!==0?R:T.variant.sx!==P.variant.sx?T.variant.sx-P.variant.sx:T.variant.sy!==P.variant.sy?T.variant.sy-P.variant.sy:0});const k=new Map;for(const T of x)k.set(T.key,T.value);return k}class bOe{constructor(m){this.sourceAtlasHash=m}}class _Oe{constructor(m,x,k,T){const P=new Map,R=new Map;this.haveRenderCallbacks=[];const U=[],V=T!==void 0,X=V?new Map:void 0,ie=V?h_e(m,X):m,ue=V?h_e(x,X):x;this.addImages(ie,P,1,U),this.addImages(ue,R,2,U);const{w:pe,h:be}=yOe(U),Se=new Vh({width:pe||1,height:be||1});for(const[Le,ze]of ie.entries()){const We=P.get(Le).paddedRect;Vh.copy(ze.data,Se,{x:0,y:0},{x:We.x+1,y:We.y+1},ze.data,null,ze.sdf)}for(const[Le,ze]of ue.entries()){const We=R.get(Le),ct=We.paddedRect;let nt=We.padding;const ft=ct.x+nt,wt=ct.y+nt,Nt=ze.data.width,Wt=ze.data.height;nt=nt>1?nt-1:nt,Vh.copy(ze.data,Se,{x:0,y:0},{x:ft,y:wt},ze.data,k),Vh.copy(ze.data,Se,{x:0,y:Wt-nt},{x:ft,y:wt-nt},{width:Nt,height:nt},k),Vh.copy(ze.data,Se,{x:0,y:0},{x:ft,y:wt+Wt},{width:Nt,height:nt},k),Vh.copy(ze.data,Se,{x:Nt-nt,y:0},{x:ft-nt,y:wt},{width:nt,height:Wt},k),Vh.copy(ze.data,Se,{x:0,y:0},{x:ft+Nt,y:wt},{width:nt,height:Wt},k),Vh.copy(ze.data,Se,{x:Nt-nt,y:Wt-nt},{x:ft-nt,y:wt-nt},{width:nt,height:nt},k),Vh.copy(ze.data,Se,{x:0,y:Wt-nt},{x:ft+Nt,y:wt-nt},{width:nt,height:nt},k),Vh.copy(ze.data,Se,{x:0,y:0},{x:ft+Nt,y:wt+Wt},{width:nt,height:nt},k),Vh.copy(ze.data,Se,{x:Nt-nt,y:0},{x:ft-nt,y:wt+Wt},{width:nt,height:nt},k)}this.lut=k,this.image=Se,this.iconPositions=P,this.patternPositions=R,V&&(this.contentDescriptor=new d_e(ie,ue,T,k,X))}addImages(m,x,k,T){for(const[P,R]of m.entries()){const{bin:U,imagePosition:V,imageVariant:X}=u_e(P,R,k);x.set(P,V),T.push(U),R.hasRenderCallback&&this.haveRenderCallbacks.push(X.id)}}patchUpdatedImages(m,x,k,T){this.haveRenderCallbacks=this.haveRenderCallbacks.filter(P=>m.hasImage(P,k)),m.dispatchRenderCallbacks(this.haveRenderCallbacks,k);for(const P of m.getUpdatedImages(k)){for(const R of this.iconPositions.keys()){const U=ep.parse(R);if(Pt.isEqual(U.id,P)){const V=m.getImage(P,k);this.patchUpdatedImage(this.iconPositions.get(R),V,x,null)}}for(const R of this.patternPositions.keys()){const U=ep.parse(R);if(Pt.isEqual(U.id,P)){const V=m.getImage(P,k);this.patchUpdatedImage(this.patternPositions.get(R),V,x,T||this.lut)}}}}patchUpdatedImage(m,x,k,T=null){if(!m||!x||m.version===x.version)return;m.version=x.version;const[P,R]=m.tl,U=m.sdf;if(this.lut||U){const V={width:x.data.width,height:x.data.height},X=new Vh(V);Vh.copy(x.data,X,{x:0,y:0},{x:0,y:0},V,T,U),k.update(X,{position:{x:P,y:R},recreateWhenResize:!1})}else k.update(x.data,{position:{x:P,y:R},recreateWhenResize:!1})}}Kn(gO,"ImagePosition"),Kn(_Oe,"ImageAtlas",{omit:["lut"]}),Kn(bOe,"ImageAtlasReference");class yO{constructor(m){this.pendingRequests=new Map,this.cachedRanges=new Map,this.useServerFontComposition=!m||m.useServerFontComposition===void 0||m.useServerFontComposition}loadGlyphRange(m,x,k,T,P){if(this.useServerFontComposition)return void yO.loadGlyphRange(m,x,k,T,P);const R=m.split(",").map(U=>U.trim()).filter(U=>U.length>0);R.length!==0?R.length!==1?this._loadMultipleFonts(R,x,k,T,P):this._loadFont(R[0],x,k,T,P):P(new Error("Empty fontstack"))}_loadMultipleFonts(m,x,k,T,P){const R=m.map(()=>null),U={completed:0,firstError:null,callbackCalled:!1},V=(X,ie,ue)=>{if(!U.callbackCalled&&(ie&&!U.firstError&&(U.firstError=ie),ue&&(R[X]=ue),U.completed++,U.completed===m.length)){U.callbackCalled=!0;const pe=R.filter(Se=>Se!==null);if(pe.length===0)return void P(U.firstError||new Error("All fonts failed to load"));const be=this._composeGlyphs(pe);P(null,be)}};for(let X=0;X{V(X,ie,ue)})}_loadFont(m,x,k,T,P){const R=`${m}:${x}`;if(this.cachedRanges.has(R)){const V=this.cachedRanges.get(R);return void $d.frame(()=>P(null,V))}const U=this.pendingRequests.get(R);U?U.push(P):(this.pendingRequests.set(R,[P]),yO.loadGlyphRange(m,x,k,T,(V,X)=>{V||this.cachedRanges.set(R,X||null);const ie=this.pendingRequests.get(R);if(this.pendingRequests.delete(R),ie)for(const ue of ie)ue(V,X)}))}_composeGlyphs(m){const x={};let k,T;for(const P of m)if(k===void 0&&P.ascender!==void 0&&(k=P.ascender),T===void 0&&P.descender!==void 0&&(T=P.descender),P.glyphs)for(const R in P.glyphs)x[R]===void 0&&(x[R]=P.glyphs[R]);return{glyphs:x,ascender:k,descender:T}}}yO.loadGlyphRange=function(b,m,x,k,T){const P=256*m,R=P+255,U=k.transformRequest(k.normalizeGlyphsURL(x).replace("{fontstack}",b).replace("{range}",`${P}-${R}`),l0.Glyphs);Iy(U,(V,X)=>{if(V)T(V);else if(X){const ie={},ue=function(pe){return new Iq(pe).readFields(s3t,{})}(X);for(const pe of ue.glyphs)ie[pe.id]=pe;T(null,{glyphs:ie,ascender:ue.ascender,descender:ue.descender})}})};const vO=1e20;function wOe(b,m,x,k,T,P,R,U,V){for(let X=m;X-1);V++,P[V]=U,R[V]=X,R[V+1]=vO}for(let U=0,V=0;U{if(R){T.ascender=R.ascender,T.descender=R.descender;for(const U in R.glyphs)this._doesCharSupportLocalGlyph(+U)||(T.glyphs[+U]=R.glyphs[+U]);T.ranges[x]=!0}for(const U of T.requests[x]||[])U(P,R);delete T.requests[x]}))}getGlyphs(m,x){const k=[],T=this.url||aa.GLYPHS_URL;for(const P in m)for(const R of m[P])k.push({stack:P,id:R});Bt(k,({stack:P,id:R},U)=>{let V=this.entries[P];V||(V=this.entries[P]={glyphs:{},requests:{},ranges:{},ascender:void 0,descender:void 0});let X=V.glyphs[R];if(X!==void 0)return void U(null,{stack:P,id:R,glyph:X});if(X=this._tinySDF(V,P,R),X)return V.glyphs[R]=X,void U(null,{stack:P,id:R,glyph:X});const ie=Math.floor(R/256);if(256*ie>65535)return Yn("glyphs > 65535 not supported"),void U(null,{stack:P,id:R,glyph:X});if(V.ranges[ie])return void U(null,{stack:P,id:R,glyph:X});let ue=V.requests[ie];ue||(ue=V.requests[ie]=[],this.glyphLoader.loadGlyphRange(P,ie,T,this.requestManager,(pe,be)=>{if(be){V.ascender=be.ascender,V.descender=be.descender;for(const Se in be.glyphs)this._doesCharSupportLocalGlyph(+Se)||(V.glyphs[+Se]=be.glyphs[+Se]);V.ranges[ie]=!0}for(const Se of ue)Se(pe,be);delete V.requests[ie]})),ue.push((pe,be)=>{pe?U(pe):be&&U(null,{stack:P,id:R,glyph:be.glyphs[R]||null})})},(P,R)=>{if(P)x(P);else if(R){const U={};for(const{stack:V,id:X,glyph:ie}of R)U[V]===void 0&&(U[V]={}),U[V].glyphs===void 0&&(U[V].glyphs={}),U[V].glyphs[X]=ie&&{id:ie.id,bitmap:ie.bitmap.clone(),metrics:ie.metrics},U[V].ascender=this.entries[V].ascender,U[V].descender=this.entries[V].descender;x(null,U)}})}_doesCharSupportLocalGlyph(m){return this.localGlyphMode!==m_e.none&&(this.localGlyphMode===m_e.all?!!this.localFontFamily:!!this.localFontFamily&&(jx(m)||o_(m)||b1(m)||wx(m)||Hy(m)||Pj(m)||(x=m)>=131072&&x<=173791||(k=>k>=66736&&k<=66815)(m)));var x}_tinySDF(m,x,k){const T=this.localFontFamily;if(!T||!this._doesCharSupportLocalGlyph(k))return;let P=m.tinySDF;if(!P){let ze="400";/bold/i.test(x)?ze="900":/medium/i.test(x)?ze="500":/light/i.test(x)&&(ze="200"),P=m.tinySDF=new Rq.TinySDF({fontFamily:T,fontWeight:ze,fontSize:48,buffer:6,radius:16}),P.fontWeight=ze}const R=P.fontWeight;if(this.localGlyphs[R][k])return this.localGlyphs[R][k];const U=String.fromCodePoint(k),{data:V,width:X,height:ie,glyphWidth:ue,glyphHeight:pe,glyphLeft:be,glyphTop:Se,glyphAdvance:Le}=P.draw(U);return this.localGlyphs[R][k]={id:k,bitmap:new ik({width:X,height:ie},V),metrics:{width:ue/2,height:pe/2,left:be/2,top:Se/2-27,advance:Le/2,localGlyph:!0}}}}function NOe(b,m){return b+m[1]-m[0]}function p_e(b,m,x,k,T=1){const P=[],R=b.imagePrimary,U=R.pixelRatio,V=R.paddedRect.w-2,X=R.paddedRect.h-2,ie=(b.right-b.left)*T,ue=(b.bottom-b.top)*T,pe=R.stretchX||[[0,V]],be=R.stretchY||[[0,X]],Se=pe.reduce(NOe,0),Le=be.reduce(NOe,0),ze=V-Se,We=X-Le;let ct=0,nt=Se,ft=0,wt=Le,Nt=0,Wt=ze,Ft=0,Gt=We;if(R.content&&k){const qt=R.content;ct=Oq(pe,0,qt[0]),ft=Oq(be,0,qt[1]),nt=Oq(pe,qt[0],qt[2]),wt=Oq(be,qt[1],qt[3]),Nt=qt[0]-ct,Ft=qt[1]-ft,Wt=qt[2]-qt[0]-nt,Gt=qt[3]-qt[1]-wt}const Ut=(qt,zs,qs,Xs)=>{const sn=Fq(qt.stretch-ct,nt,ie,b.left*T),Js=zq(qt.fixed-Nt,Wt,qt.stretch,Se),fn=Fq(zs.stretch-ft,wt,ue,b.top*T),Os=zq(zs.fixed-Ft,Gt,zs.stretch,Le),en=Fq(qs.stretch-ct,nt,ie,b.left*T),on=zq(qs.fixed-Nt,Wt,qs.stretch,Se),gn=Fq(Xs.stretch-ft,wt,ue,b.top*T),Cn=zq(Xs.fixed-Ft,Gt,Xs.stretch,Le),ar=new Es(sn,fn),Fn=new Es(en,fn),Rn=new Es(en,gn),Tn=new Es(sn,gn),sr=new Es(Js/U,Os/U),hr=new Es(on/U,Cn/U),Ur=m*Math.PI/180;if(Ur){const Ga=Math.sin(Ur),Ol=Math.cos(Ur),Qi=[Ol,-Ga,Ga,Ol];ar._matMult(Qi),Fn._matMult(Qi),Tn._matMult(Qi),Rn._matMult(Qi)}const jr=qt.stretch+qt.fixed,Sa=qs.stretch+qs.fixed,_i=zs.stretch+zs.fixed,Ca=Xs.stretch+Xs.fixed,Ni=b.imageSecondary;return{tl:ar,tr:Fn,bl:Tn,br:Rn,texPrimary:{x:R.paddedRect.x+1+jr,y:R.paddedRect.y+1+_i,w:Sa-jr,h:Ca-_i},texSecondary:Ni?{x:Ni.paddedRect.x+1+jr,y:Ni.paddedRect.y+1+_i,w:Sa-jr,h:Ca-_i}:void 0,writingMode:void 0,glyphOffset:[0,0],sectionIndex:0,pixelOffsetTL:sr,pixelOffsetBR:hr,minFontScaleX:Wt/U/ie,minFontScaleY:Gt/U/ue,isSDF:x}};if(R.stretchX||R.stretchY){const qt=kOe(pe,ze,Se),zs=kOe(be,We,Le);for(let qs=0;qs0?[ct,-nt]:ft<0?[-ct,nt]:ct===0?[nt,ct]:[nt,-ct]}(x);let be=Math.abs(m.top-m.bottom);for(const We of m.positionedLines)be-=We.lineOffset;const Se=m.positionedLines.length,Le=be/Se;let ze=m.top-x[1];for(let We=0;WeP)&&(P=Se.x),(!be||Se.y>R)&&(R=Se.y)}const V=Math.min(P-k,R-T);let X=V/2;const ie=new u0([],h3t);if(V===0)return new Es(k,T);for(let be=k;beue.d||!ue.d)&&(ue=be,x&&console.log("found best %d after %d probes",Math.round(1e4*be.d)/1e4,pe)),be.max-ue.d<=m||(X=be.h/2,ie.push(new V6(be.p.x-X,be.p.y-X,X,b)),ie.push(new V6(be.p.x+X,be.p.y-X,X,b)),ie.push(new V6(be.p.x-X,be.p.y+X,X,b)),ie.push(new V6(be.p.x+X,be.p.y+X,X,b)),pe+=4)}return x&&(console.log(`num probes: ${pe}`),console.log(`best distance: ${ue.d}`)),ue.p}function h3t(b,m){return m.max-b.max}Rq.TinySDF=class{constructor({fontSize:b=24,buffer:m=3,radius:x=8,cutoff:k=.25,fontFamily:T="sans-serif",fontWeight:P="normal",fontStyle:R="normal",lang:U=null}={}){this.buffer=m,this.cutoff=k,this.radius=x,this.lang=U;const V=this.size=b+4*m,X=this._createCanvas(V),ie=this.ctx=X.getContext("2d",{willReadFrequently:!0});ie.font=`${R} ${P} ${b}px ${T}`,ie.textBaseline="alphabetic",ie.textAlign="left",ie.fillStyle="black",this.gridOuter=new Float64Array(V*V),this.gridInner=new Float64Array(V*V),this.f=new Float64Array(V),this.z=new Float64Array(V+1),this.v=new Uint16Array(V)}_createCanvas(b){const m=document.createElement("canvas");return m.width=m.height=b,m}draw(b){const{width:m,actualBoundingBoxAscent:x,actualBoundingBoxDescent:k,actualBoundingBoxLeft:T,actualBoundingBoxRight:P}=this.ctx.measureText(b),R=Math.ceil(x),U=Math.max(0,Math.min(this.size-this.buffer,Math.ceil(P-T))),V=Math.min(this.size-this.buffer,R+Math.ceil(k)),X=U+2*this.buffer,ie=V+2*this.buffer,ue=Math.max(X*ie,0),pe=new Uint8ClampedArray(ue),be={data:pe,width:X,height:ie,glyphWidth:U,glyphHeight:V,glyphTop:R,glyphLeft:0,glyphAdvance:m};if(U===0||V===0)return be;const{ctx:Se,buffer:Le,gridInner:ze,gridOuter:We}=this;this.lang&&(Se.lang=this.lang),Se.clearRect(Le,Le,U,V),Se.fillText(b,Le,Le+R);const ct=Se.getImageData(Le,Le,U,V);We.fill(vO,0,ue),ze.fill(0,0,ue);for(let nt=0;nt0?Wt*Wt:0,ze[Nt]=Wt<0?Wt*Wt:0}}wOe(We,0,0,X,ie,X,this.f,this.v,this.z),wOe(ze,Le,Le,U,V,X,this.f,this.v,this.z);for(let nt=0;ntP.y!=Le.y>P.y&&P.x<(Le.x-Se.x)*(P.y-Se.y)/(Le.y-Se.y)+Se.x&&(U=!U),V=Math.min(V,Zy(P,Se,Le))}}return(U?1:-1)*Math.sqrt(V)}(this.p,T),this.max=this.d+this.h*Math.SQRT2}}const m3t=Object.keys,f_e=Number.POSITIVE_INFINITY,p3t=Math.sqrt(2);function dk(b,m,x,k,T,P){const R=i_e(b)&&b.collisionPadding?b.collisionPadding:[0,0,0,0],U={top:b.top-R[1],bottom:b.bottom+R[3],left:b.left-R[0],right:b.right+R[2],scaled:!1};return k!==void 0&&function(V,X){V.top*=X,V.bottom*=X,V.left*=X,V.right*=X,V.scaled=!0}(U,k),P&&(U.left+=P[0],U.right+=P[0],U.top+=P[1],U.bottom+=P[1]),x&&function(V,X,ie){if(!X)return;const ue=Ts(X),pe=new Es(ie?ie[0]:0,ie?ie[1]:0),be=new Es(V.left,V.top),Se=new Es(V.right,V.top),Le=new Es(V.left,V.bottom),ze=new Es(V.right,V.bottom);be._rotateAround(ue,pe),Se._rotateAround(ue,pe),Le._rotateAround(ue,pe),ze._rotateAround(ue,pe),V.left=Math.min(be.x,Se.x,Le.x,ze.x),V.right=Math.max(be.x,Se.x,Le.x,ze.x),V.top=Math.min(be.y,Se.y,Le.y,ze.y),V.bottom=Math.max(be.y,Se.y,Le.y,ze.y)}(U,x,T),m?{top:Math.min(m.top,U.top),bottom:Math.max(m.bottom,U.bottom),left:Math.min(m.left,U.left),right:Math.max(m.right,U.right),scaled:m.scaled||U.scaled}:U}function TOe(b,[m,x]){let k=0,T=0;if(x===f_e){m<0&&(m=0);const P=m/p3t;switch(b){case"top-right":case"top-left":T=P-7;break;case"bottom-right":case"bottom-left":T=7-P;break;case"bottom":T=7-m;break;case"top":T=m-7}switch(b){case"top-right":case"bottom-right":k=-P;break;case"top-left":case"bottom-left":k=P;break;case"left":k=m;break;case"right":k=-m}}else{switch(m=Math.abs(m),x=Math.abs(x),b){case"top-right":case"top-left":case"top":T=x-7;break;case"bottom-right":case"bottom-left":case"bottom":T=7-x}switch(b){case"top-right":case"bottom-right":case"right":k=-m;break;case"top-left":case"bottom-left":case"left":k=m}}return[k,T]}function f3t(b,m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se){const Le=b.layers[0],ze=Le.appearances;if(ze.length===0)return{iconBBox:null,iconVerticalBBox:null,textBBox:null,textVerticalBBox:null};const We={iconBBox:null,iconVerticalBBox:null},ct={textBBox:null,textVerticalBBox:null},{baseIconRotate:nt,baseTextRotate:ft,iconScaleFactor:wt}=function(Wt,Ft,Gt){const Ut=Wt.get("icon-rotate").evaluate(Ft,{},Gt),qt=Wt.get("text-rotate").evaluate(Ft,{},Gt),[zs,qs]=Wt.get("icon-size-scale-range");return{baseIconRotate:Ut,baseTextRotate:qt,iconScaleFactor:Qe(1,zs,qs)}}(k,T,P);m&&(We.iconBBox=dk(m,We.iconBBox,nt),x)&&(We.iconVerticalBBox=dk(x,We.iconVerticalBBox,nt+90));const Nt=$q(ue.horizontal);Nt&&(ct.textBBox=dk(Nt,ct.textBBox,ft,1,be)),ue.vertical&&(ct.textVerticalBBox=dk(ue.vertical,ct.textVerticalBBox,ft+90,1,be));for(const Wt of ze)Wt.hasIconLayoutProperties()&&x3t(We,b,Le,Wt,T,P,U,nt,R,V,m,X,wt,ie,Se),Wt.hasTextLayoutProperties()&&g3t(ct,Le,Wt,T,P,be,ft,pe,Nt,ue.vertical);return{iconBBox:We.iconBBox,iconVerticalBBox:We.iconVerticalBBox,textBBox:ct.textBBox,textVerticalBBox:ct.textVerticalBBox}}function x3t(b,m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se){const{appearanceIconOffset:Le,appearanceIconRotate:ze,appearanceIconSize:We}=EOe(k,x,T,P,R,U,V,X.iconScaleFactor);let ct=null,nt=null,ft=null;k.hasLayoutProperty("icon-image")?ft=function(Nt,Wt,Ft,Gt,Ut,qt,zs,qs){let Xs=null;const sn=Wt.getAppearanceValueAndResolveTokens(Ft,"icon-image",Gt,Ut,qs);if(sn){const Js=Nt.getResolvedImageFromTokens(sn),fn=Ft.hasLayoutProperty("icon-size")?Ft.getUnevaluatedLayoutProperty("icon-size"):Wt._unevaluatedLayout._values["icon-size"],Os=bO(Js,WC(Nt.zoom,fn,Nt.worldview,qs),fn,Ut,Nt.zoom,Gt,Nt.pixelRatio,zs,Nt.worldview,qs);Xs=qt.get(Os.iconPrimary.toString())}return Xs}(m,x,k,T,P,ue,pe,Se):ie&&(ft=ie.imagePrimary),ft&&(ct=Lq(ft,null,Le,be),m.allowVerticalPlacement&&(nt=Lq(ft,null,Le,be)));const wt=V>0?We/V:1;ct&&(b.iconBBox=dk(ct,b.iconBBox,ze,wt!==1?wt:void 0)),nt&&(b.iconVerticalBBox=dk(nt,b.iconVerticalBBox,ze+90,wt!==1?wt:void 0))}function EOe(b,m,x,k,T,P,R,U){const V=b.hasLayoutProperty("icon-offset")?m.getAppearanceValueAndResolveTokens(b,"icon-offset",x,k,[]):null,X=V&&Array.isArray(V)?V:T,ie=b.hasLayoutProperty("icon-rotate")?m.getAppearanceValueAndResolveTokens(b,"icon-rotate",x,k,[]):null,ue=typeof ie=="number"?ie:P,pe=b.hasLayoutProperty("icon-size")?m.getAppearanceValueAndResolveTokens(b,"icon-size",x,k,[]):null;return{appearanceIconOffset:X,appearanceIconRotate:ue,appearanceIconSize:typeof pe=="number"?pe*U:R}}function g3t(b,m,x,k,T,P,R,U,V,X){const{appearanceTextOffset:ie,appearanceTextRotate:ue,appearanceTextSize:pe}=AOe(x,m,k,T,P,R,U),be=pe/U,Se=[(ie[0]-P[0])*be,(ie[1]-P[1])*be],Le=Se[0]!==0||Se[1]!==0;V&&(b.textBBox=dk(V,b.textBBox,ue,be,ie,Le?Se:void 0)),X&&(b.textVerticalBBox=dk(X,b.textVerticalBBox,ue+90,be,ie,Le?Se:void 0))}function AOe(b,m,x,k,T,P,R){const U=b.hasLayoutProperty("text-offset")?m.getAppearanceValueAndResolveTokens(b,"text-offset",x,k,[]):null,V=U&&Array.isArray(U)?[U[0]*Kd,U[1]*Kd]:T,X=b.hasLayoutProperty("text-rotate")?m.getAppearanceValueAndResolveTokens(b,"text-rotate",x,k,[]):null,ie=typeof X=="number"?X:P,ue=b.hasLayoutProperty("text-size")?m.getAppearanceValueAndResolveTokens(b,"text-size",x,k,[]):null;return{appearanceTextOffset:V,appearanceTextRotate:ie,appearanceTextSize:typeof ue=="number"?ue:R}}function Bq(b,m,x,k,T,P,R,U,V){if(!m||!m.usvg)return;const X=hOe(k),ie=hOe(T),ue=P!=="both"&&P!=="width"||!dOe(k)?1:ie.width/X.width,pe=P!=="both"&&P!=="height"||!uOe(k)?1:ie.height/X.height;x.scaleSelf(ue,pe);const be=x.toString();R.set(be,x),U.set(be,m);const{imagePosition:Se}=u_e(be,m,1);V.set(be,Se)}function MOe(b,m,x,k,T,P,R,U,V,X){if(!b)return;const ie=function(ue,pe,be,Se,Le,ze,We){if(ue.kind==="camera")return ue.maxSize;if(ue.kind==="composite"){const ct=pe.possiblyEvaluate(new Aa(ue.maxZoom,{worldview:ze}),be,We).evaluate(Le,{},be,We),nt=pe.possiblyEvaluate(new Aa(ue.minZoom,{worldview:ze}),be,We).evaluate(Le,{},be,We);return Math.max(ct,nt)}return pe.possiblyEvaluate(new Aa(Se,{worldview:ze}),be,We).evaluate(Le,{},be,We)}(m,x,k,T,P,V,X);return b.scaleSelf(ie*U*R)}function bO(b,m,x,k,T,P,R,U,V,X){return{iconPrimary:MOe(b.getPrimary(),m,x,k,T,P,R,U,V,X),iconSecondary:MOe(b.getSecondary(),m,x,k,T,P,R,U,V,X)}}function y3t(b,m,x){if(!m)return;const k=x.get(b.toString()),T=x.get(m.toString());k&&T&&(k.paddedRect.w===T.paddedRect.w&&k.paddedRect.h===T.paddedRect.h||Yn(`Mismatch in icon variant sizes: ${b.toString()} and ${m.toString()}`),k.usvg!==T.usvg&&Yn(`Mismatch in icon variant image types: ${b.id} and ${m.id}`))}function IOe(b,m,x,k){if(!b)return;const T=m.get(x.toString());if(T&&(b.imagePrimary=T),k){const P=m.get(k.toString());b.imageSecondary=P}}function v3t(b,m){for(const x in b.horizontal)POe(b.horizontal[x],m);POe(b.vertical,m)}function POe(b,m){if(b){for(const x of b.positionedLines)for(const k of x.positionedGlyphs)if(k.image!==null){const T=k.image.toString();k.rect=m.get(T).paddedRect}}}function x_e(b){switch(b){case"right":case"top-right":case"bottom-right":return"right";case"left":case"top-left":case"bottom-left":return"left"}return"center"}function b3t(b,m,x,k,T,P,R,U,V){const X=$q(P.horizontal)||P.vertical,ie=x.get("icon-text-fit-padding").evaluate(k,{},T);let ue,pe=m;return m&&V!=="none"&&(b.allowVerticalPlacement&&P.vertical&&(ue=o_e(m,P.vertical,V,ie,U,R)),X&&(pe=o_e(m,X,V,ie,U,R))),{defaultShapedIcon:pe,verticallyShapedIcon:ue}}function LOe(b,m){return b*m/24}function _3t(b,m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct,nt,ft,wt,Nt,Wt){let Ft=R.textMaxSize.evaluate(m,{},pe);Ft===void 0?Ft=U*R.textScaleFactor:Ft*=R.textScaleFactor;const Gt=b.layers[0].layout,Ut=LOe(U,R.textScaleFactor),qt=$q(x.horizontal)||x.vertical,zs=b.hasAnyAppearanceLayoutProperty(["text-size","text-offset","text-rotate"]),qs=b.getAppearanceFeatureData(m.index);(ze!=="none"||zs)&&qs&&(qs.textShaping=qt,qs.iconTextFitPadding=Gt.get("icon-text-fit-padding").evaluate(m,{},pe),qs.fontScale=Ut,qs.textScaleFactor=R.textScaleFactor);const Xs=be.name==="globe",sn=b.tilePixelRatio*Ft/24,Js=(Cn=b.overscaling,b.zoom>18&&Cn>2&&(Cn>>=1),Math.max(Bn/(512*Cn),1)*Gt.get("symbol-spacing")),fn=Gt.get("text-padding")*b.tilePixelRatio,Os=Gt.get("icon-padding")*b.tilePixelRatio,en=Ts(Gt.get("text-max-angle")),on=Gt.get("icon-rotation-alignment")==="map"&&nt!=="point",gn=Js/2;var Cn;b.hasAnyIconTextFit===!1&&ze!=="none"&&(b.hasAnyIconTextFit=!0);const ar=m.properties?+m.properties[Ra]:null,Fn=ar&&b.elevationFeatureIdToIndex?b.elevationFeatureIdToIndex.get(ar):65535,Rn=(Tn,sr,hr)=>{if(sr.x<0||sr.x>=Bn||sr.y<0||sr.y>=Bn)return;let Ur=null;if(Xs){const{x:jr,y:Sa,z:_i}=be.projectTilePoint(sr.x,sr.y,hr);Ur={anchor:new Zj(jr,Sa,_i,0,void 0),up:be.upVector(hr,sr.x,sr.y)}}(function(jr,Sa,_i,Ca,Ni,Ga,Ol,Qi,Ii,Ro,Ml,Yd,Il,sc,Oc,nc,yh,Zd,Za,lp,hc,gu,cp,vh,Fl,wm,yu,aV,X6,Wp,B_e,J6){const Qj=jr.addToLineVertexArray(Sa,Ca);let Xj,N0,k0,JC,eI,ri,vu,rc=0,Cd=0,S0=0,Ax=0,Mx=-1,Ix=-1;const Jy={};let iV=Nd("");const M1=_i?_i.anchor:Sa,tI=aV!=="none";let sI=0,ud=0;if(Ii._unevaluatedLayout.getValue("text-radial-offset")===void 0){const mc=Ii.layout.get("text-offset").evaluate(hc,{},Fl);sI=mc[0]*Kd,ud=mc[1]*Kd}else sI=Ii.layout.get("text-radial-offset").evaluate(hc,{},Fl)*Kd,ud=f_e;if(jr.allowVerticalPlacement&&Ni.vertical){const mc=Ni.vertical;if(Oc)ri=v_e(mc),Qi&&(vu=v_e(Qi));else{const dp=Ii.layout.get("text-rotate").evaluate(hc,{},Fl)+90;k0=Uq(Ro,M1,Sa,Ml,Yd,Il,mc,sc,dp,nc,J6),Qi&&(JC=Uq(Ro,M1,Sa,Ml,Yd,Il,Qi,Zd,dp,null,B_e))}}if(Ga){const mc=Ii.layout.get("icon-rotate").evaluate(hc,{},Fl),dp=p_e(Ga,mc,cp,tI,gu.iconScaleFactor),Kp=Qi?p_e(Qi,mc,cp,tI,gu.iconScaleFactor):void 0;N0=Uq(Ro,M1,Sa,Ml,Yd,Il,Ga,Zd,mc,null,Wp);const tv=function(I1,DO,nI,R5t,O5t,t7e,s7e,F5t,Apn,U_e){const n7e=I1.layers[0],r7e=n7e.appearances;let rI=DO.length;if(nI&&(rI=Math.max(rI,nI.length)),r7e.length===0)return rI;const[z5t,B5t]=R5t.get("icon-size-scale-range"),$5t=Qe(1,z5t,B5t);for(const dV of r7e)if(dV.hasLayoutProperty("icon-image")){const a7e=n7e.getAppearanceValueAndResolveTokens(dV,"icon-image",t7e,s7e,U_e);if(a7e){const i7e=I1.getResolvedImageFromTokens(a7e);if(i7e){const o7e=dV.hasLayoutProperty("icon-size")?dV.getUnevaluatedLayoutProperty("icon-size"):O5t._values["icon-size"],U5t=bO(i7e,WC(I1.zoom,o7e,I1.worldview,U_e),o7e,s7e,I1.zoom,t7e,I1.pixelRatio,$5t,I1.worldview,U_e),l7e=F5t.get(U5t.iconPrimary.toString());l7e&&(rI=Math.max(rI,c3t(l7e)))}}}return rI}(jr,dp,Kp,Ii.layout,Ii._unevaluatedLayout,hc,Fl,jr.iconAtlasPositions,0,vh);rc=4*tv;const oV=Ii.layout.get("icon-size").evaluate(hc,{},Fl,vh),lV=gu.compositeIconSizes?gu.compositeIconSizes[0].evaluate(hc,{},Fl,vh):0,$_e=gu.compositeIconSizes?gu.compositeIconSizes[1].evaluate(hc,{},Fl,vh):0,cV=y_e(jr.layerIds[0],jr.iconSizeData,oV,gu.iconScaleFactor,lV,$_e);jr.addSymbols(jr.icon,dp,cV,lp,Za,hc,void 0,_i,Sa,Qj.lineStartIndex,Qj.lineLength,-1,vh,Fl,wm,yu,jr.symbolInstances.length,tv),Mx=jr.icon.placedSymbolArray.length-1,Kp&&(Cd=4*tv,jr.addSymbols(jr.icon,Kp,cV,lp,Za,hc,Ex.vertical,_i,Sa,Qj.lineStartIndex,Qj.lineLength,-1,vh,Fl,wm,yu,jr.symbolInstances.length,tv),Ix=jr.icon.placedSymbolArray.length-1)}for(const mc in Ni.horizontal){const dp=mc,Kp=Ni.horizontal[dp];Xj||(iV=Nd(Kp.text),Oc?eI=v_e(Kp):Xj=Uq(Ro,M1,Sa,Ml,Yd,Il,Kp,sc,Ii.layout.get("text-rotate").evaluate(hc,{},Fl),nc,J6));const tv=Kp.positionedLines.length===1;if(S0+=DOe(jr,_i,Sa,Kp,Ol,Ii,Oc,hc,nc,Qj,Ni.vertical?Ex.horizontal:Ex.horizontalOnly,tv?m3t(Ni.horizontal):[dp],Jy,Mx,gu,vh,Fl,jr.symbolInstances.length,wm),tv)break}Ni.vertical&&(Ax+=DOe(jr,_i,Sa,Ni.vertical,Ol,Ii,Oc,hc,nc,Qj,Ex.vertical,["vertical"],Jy,Ix,gu,vh,Fl,jr.symbolInstances.length,wm));let Qc=-1;const Td=(mc,dp)=>mc?Math.max(mc,dp):dp;Qc=Td(eI,Qc),Qc=Td(ri,Qc),Qc=Td(vu,Qc);const ev=Qc>-1?1:0;jr.glyphOffsetArray.length>=65535&&Yn("Too many glyphs being rendered in a tile. See https://github.com/mapbox/mapbox-gl-js/issues/2907"),hc.sortKey!==void 0&&jr.addToSortKeyRanges(jr.symbolInstances.length,hc.sortKey),jr.symbolInstances.emplaceBack(Sa.x,Sa.y,M1.x,M1.y,M1.z,Jy.right>=0?Jy.right:-1,Jy.center>=0?Jy.center:-1,Jy.left>=0?Jy.left:-1,Jy.vertical>=0?Jy.vertical:-1,Mx,Ix,iV,Xj!==void 0?Xj:jr.collisionBoxArray.length,Xj!==void 0?Xj+1:jr.collisionBoxArray.length,k0!==void 0?k0:jr.collisionBoxArray.length,k0!==void 0?k0+1:jr.collisionBoxArray.length,N0!==void 0?N0:jr.collisionBoxArray.length,N0!==void 0?N0+1:jr.collisionBoxArray.length,JC||jr.collisionBoxArray.length,JC?JC+1:jr.collisionBoxArray.length,Ml,S0,Ax,rc,Cd,ev,0,sI,ud,Qc,0,tI?1:0,X6)})(b,sr,Ur,Tn,x,k,P,T,b.layers[0],b.collisionBoxArray,m.index,m.sourceLayerIndex,b.index,fn,ct,X,0,Os,on,We,m,R,ie,ue,pe,Se,Le,ze,Fn,ft,wt,Nt)};if(nt==="line")for(const Tn of _q(m.geometry,0,0,Bn,Bn)){const sr=l3t(Tn,Js,en,x.vertical||qt,k,24,sn,b.overscaling,Bn);for(const hr of sr)qt&&w3t(b,qt.text,gn,hr)||Rn(Tn,hr,pe)}else if(nt==="line-center"){for(const Tn of m.geometry)if(Tn.length>1){const sr=o3t(Tn,en,x.vertical||qt,k,24,sn);sr&&Rn(Tn,sr,pe)}}else if(m.type==="Polygon")for(const Tn of sO(m.geometry,0)){const sr=u3t(Tn,16);Rn(Tn[0],new Zj(sr.x,sr.y,0,0,void 0),pe)}else if(m.type==="LineString")for(const Tn of m.geometry)Rn(Tn,new Zj(Tn[0].x,Tn[0].y,0,0,void 0),pe);else if(m.type==="Point")for(const Tn of m.geometry)for(const sr of Tn)Rn([sr],new Zj(sr.x,sr.y,0,0,void 0),pe)}const g_e=255,KC=g_e*Yj;function DOe(b,m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct){const nt=COe(0,k,V,P,R,U,T,b.allowVerticalPlacement,void 0,Se.textScaleFactor),ft=P.layout.get("text-size").evaluate(U,{},ze),wt=Se.compositeTextSizes?Se.compositeTextSizes[0].evaluate(U,{},ze):0,Nt=Se.compositeTextSizes?Se.compositeTextSizes[1].evaluate(U,{},ze):0,Wt=y_e(b.layerIds[0],b.textSizeData,ft,Se.textScaleFactor,wt,Nt);b.addSymbols(b.text,nt,Wt,V,R,U,ie,m,x,X.lineStartIndex,X.lineLength,be,Le,ze,ct,!1,We,nt.length);for(const Ft of ue)pe[Ft]=b.text.placedSymbolArray.length-1;return 4*nt.length}function y_e(b,m,x,k,T,P){const R=m;let U=null;return R.kind==="source"?(U=[Yj*x*k],U[0]>KC&&Yn(`${b}: Value for "text-size" is >= ${g_e}. Reduce your "text-size".`)):R.kind==="composite"&&(U=[Yj*T*k,Yj*P*k],(U[0]>KC||U[1]>KC)&&Yn(`${b}: Value for "text-size" is >= ${g_e}. Reduce your "text-size".`)),U}function $q(b){for(const m in b)return b[m];return null}function Uq(b,m,x,k,T,P,R,U,V,X,ie){let ue,pe,be,Se;if(ue=ie?ie.top:R.top,pe=ie?ie.bottom:R.bottom,be=ie?ie.left:R.left,Se=ie?ie.right:R.right,i_e(R)&&R.collisionPadding){const Le=R.collisionPadding;be-=Le[0],ue-=Le[1],Se+=Le[2],pe+=Le[3]}if(V){const Le=new Es(be,ue),ze=new Es(Se,ue),We=new Es(be,pe),ct=new Es(Se,pe),nt=Ts(V);let ft=new Es(0,0);X&&(ft=new Es(X[0],X[1])),Le._rotateAround(nt,ft),ze._rotateAround(nt,ft),We._rotateAround(nt,ft),ct._rotateAround(nt,ft),be=Math.min(Le.x,ze.x,We.x,ct.x),Se=Math.max(Le.x,ze.x,We.x,ct.x),ue=Math.min(Le.y,ze.y,We.y,ct.y),pe=Math.max(Le.y,ze.y,We.y,ct.y)}return b.emplaceBack(m.x,m.y,m.z,x.x,x.y,be,ue,Se,pe,U,k,T,P),b.length-1}function v_e(b){i_e(b)&&b.collisionPadding&&(b.top-=b.collisionPadding[1],b.bottom+=b.collisionPadding[3]);const m=b.bottom-b.top;return m>0?Math.max(10,m):null}function w3t(b,m,x,k){const T=b.compareText;if(m in T){const P=T[m];for(let R=P.length-1;R>=0;R--)if(k.dist(P[R])nt&&(ft(Nt,Xs,Ft,Gt,zs,qs),ft(Xs,Wt,zs,qs,Ut,qt))}ft(ue,pe,k,P,T,P),ft(pe,be,T,P,T,R),ft(be,Se,T,R,k,R),ft(Se,ue,k,R,k,P),Le-=nt,ze-=nt,We+=nt,ct+=nt;const wt=1/Math.max(We-Le,ct-ze);return{scale:wt,x:Le*wt,y:ze*wt,x2:We*wt,y2:ct*wt,projection:m}}function OOe(b,{x:m,y:x},k=0){return new Es(((m-k)*b.scale-b.x)*Bn,(x*b.scale-b.y)*Bn)}const j3t=v(new Float32Array(16));class uk{constructor(m){this.spec=m,this.name=m.name,this.wrap=!1,this.requiresDraping=!1,this.supportsWorldCopies=!1,this.supportsTerrain=!1,this.supportsFog=!1,this.supportsFreeCamera=!1,this.zAxisUnit="meters",this.isReprojectedInTileSpace=!0,this.unsupportedLayers=["custom"],this.center=[0,0],this.range=[3.5,7]}project(m,x){return{x:0,y:0,z:0}}unproject(m,x){return new ss(0,0)}projectTilePoint(m,x,k){return{x:m,y:x,z:0}}locationPoint(m,x,k,T=!0){return m._coordinatePoint(m.locationCoordinate(x,k),T)}pixelsPerMeter(m,x){return Ns(1,m)*x}pixelSpaceConversion(m,x,k){return 1}farthestPixelDistance(m){return ROe(m,m.pixelsPerMeter)}pointCoordinate(m,x,k,T){const P=m.horizonLineFromTop(!1),R=new Es(x,Math.max(P,k));return m.rayIntersectionCoordinate(m.pointRayIntersection(R,T))}pointCoordinate3D(m,x,k){const T=new Es(x,k);if(m.elevation)return m.elevation.pointCoordinate(T);{const P=this.pointCoordinate(m,T.x,T.y,0);return[P.x,P.y,P.z]}}isPointAboveHorizon(m,x){if(m.elevation&&m.elevation.visibleDemTiles.length)return!this.pointCoordinate3D(m,x.x,x.y);const k=m.horizonLineFromTop();return x.y0?x<-H6+k&&(x=-H6+k):x>H6-k&&(x=H6-k);const R=P/Math.pow(Vq(x),T);let U=R*Math.sin(T*m),V=P-R*Math.cos(T*m);return U=.5*(U/Math.PI+.5),V=.5*(V/Math.PI+.5),{x:U,y:this.southernCenter?V:1-V,z:0}}unproject(m,x){m=(2*m-.5)*Math.PI,this.southernCenter&&(x=1-x),x=(2*(1-x)-.5)*Math.PI;const{n:k,f:T}=this,P=T-x,R=Math.sign(P),U=Math.sign(k)*Math.sqrt(m*m+P*P);let V=Math.atan2(m,Math.abs(P))*R;P*k<0&&(V-=Math.PI*Math.sign(m)*R);const X=Qe(Un(V/k)+this.center[0],-180,180),ie=Qe(Un(2*Math.atan(Math.pow(T/U,1/k))-H6),-85.051129,Ys);return new ss(X,this.southernCenter?-ie:ie)}}class FOe extends uk{constructor(m){super(m),this.wrap=!0,this.supportsWorldCopies=!0,this.supportsTerrain=!0,this.supportsFog=!0,this.supportsFreeCamera=!0,this.isReprojectedInTileSpace=!1,this.unsupportedLayers=[],this.range=null}project(m,x){return{x:rn(m),y:hn(x),z:0}}unproject(m,x){const k=ds(m),T=Fs(x);return new ss(k,T)}}const zOe=Ts(Ys);class T3t extends uk{project(m,x){const k=(x=Ts(x))*x,T=k*k;return{x:.5*((m=Ts(m))*(.8707-.131979*k+T*(T*(.003971*k-.001529*T)-.013791))/Math.PI+.5),y:1-.5*(x*(1.007226+k*(.015085+T*(.028874*k-.044475-.005916*T)))/Math.PI+1),z:0}}unproject(m,x){m=(2*m-.5)*Math.PI;let k=x=(2*(1-x)-1)*Math.PI,T=25,P=0,R=k*k;do{R=k*k;const X=R*R;P=(k*(1.007226+R*(.015085+X*(.028874*R-.044475-.005916*X)))-x)/(1.007226+R*(.045255+X*(.259866*R-.311325-.005916*11*X))),k=Qe(k-P,-zOe,zOe)}while(Math.abs(P)>1e-6&&--T>0);R=k*k;const U=Qe(Un(m/(.8707+R*(R*(R*R*R*(.003971-.001529*R)-.013791)-.131979))),-180,180),V=Un(k);return new ss(U,V)}}const BOe=Ts(Ys);class E3t extends uk{project(m,x){x=Ts(x),m=Ts(m);const k=Math.cos(x),T=2/Math.PI,P=Math.acos(k*Math.cos(m/2)),R=Math.sin(P)/P,U=.5*(m*T+2*k*Math.sin(m/2)/R)||0,V=.5*(x+Math.sin(x)/R)||0;return{x:.5*(U/Math.PI+.5),y:1-.5*(V/Math.PI+1),z:0}}unproject(m,x){let k=m=(2*m-.5)*Math.PI,T=x=(2*(1-x)-1)*Math.PI,P=25;const R=1e-6;let U=0,V=0;do{const X=Math.cos(T),ie=Math.sin(T),ue=2*ie*X,pe=ie*ie,be=X*X,Se=Math.cos(k/2),Le=Math.sin(k/2),ze=2*Se*Le,We=Le*Le,ct=1-be*Se*Se,nt=ct?1/ct:0,ft=ct?Math.acos(X*Se)*Math.sqrt(1/ct):0,wt=.5*(2*ft*X*Le+2*k/Math.PI)-m,Nt=.5*(ft*ie+T)-x,Wt=.5*nt*(be*We+ft*X*Se*pe)+1/Math.PI,Ft=nt*(ze*ue/4-ft*ie*Le),Gt=.125*nt*(ue*Le-ft*ie*be*ze),Ut=.5*nt*(pe*Se+ft*We*X)+.5,qt=Ft*Gt-Ut*Wt;U=(Nt*Ft-wt*Ut)/qt,V=(wt*Gt-Nt*Wt)/qt,k=Qe(k-U,-Math.PI,Math.PI),T=Qe(T-V,-BOe,BOe)}while((Math.abs(U)>R||Math.abs(V)>R)&&--P>0);return new ss(Un(k),Un(T))}}class $Oe extends uk{constructor(m){super(m),this.center=m.center||[0,0],this.parallels=m.parallels||[0,0],this.cosPhi=Math.max(.01,Math.cos(Ts(this.parallels[0]))),this.scale=1/(2*Math.max(Math.PI*this.cosPhi,1/this.cosPhi)),this.wrap=!0,this.supportsWorldCopies=!0}project(m,x){const{scale:k,cosPhi:T}=this;return{x:Ts(m)*T*k+.5,y:-Math.sin(Ts(x))/T*k+.5,z:0}}unproject(m,x){const{scale:k,cosPhi:T}=this,P=-(x-.5)/k,R=Qe(Un((m-.5)/k)/T,-180,180),U=Math.asin(Qe(P*T,-1,1)),V=Qe(Un(U),-85.051129,Ys);return new ss(R,V)}}class A3t extends FOe{constructor(m){super(m),this.requiresDraping=!0,this.supportsWorldCopies=!1,this.supportsFog=!0,this.zAxisUnit="pixels",this.unsupportedLayers=["debug"],this.range=[3,5]}projectTilePoint(m,x,k){const T=YR(m,x,k);return Je(T,T,ZR(x_(k))),{x:T[0],y:T[1],z:T[2]}}locationPoint(m,x,k){const T=Dt(x.lat,x.lng),P=Re([],T),R=k?m._centerAltitude+k:m.elevation?m.elevation.getAtPointOrZero(m.locationCoordinate(x),m._centerAltitude):m._centerAltitude;Te(T,T,P,Ns(1,0)*Bn*R);const U=v(new Float64Array(16));return w(U,m.pixelMatrix,m.globeMatrix),Je(T,T,U),new Es(T[0],T[1])}pixelsPerMeter(m,x){return Ns(1,0)*x}pixelSpaceConversion(m,x,k){const T=Ns(1,m)*x,P=Dr(Ns(1,45)*x,T,k);return this.pixelsPerMeter(m,x)/P}createTileMatrix(m,x,k){const T=mbe(x_(k.canonical));return w(new Float64Array(16),m.globeMatrix,T)}createInversionMatrix(m,x){const{center:k}=m,T=ZR(x_(x));return O(T,T,Ts(k.lng)),E(T,T,Ts(k.lat)),A(T,T,[m._pixelsPerMercatorPixel,m._pixelsPerMercatorPixel,1]),Float32Array.from(T)}pointCoordinate(m,x,k,T){return nDe(m,x,k,!0)||new ur(0,0)}pointCoordinate3D(m,x,k){const T=this.pointCoordinate(m,x,k,0);return[T.x,T.y,T.z]}isPointAboveHorizon(m,x){return!nDe(m,x.x,x.y,!1)}farthestPixelDistance(m){const x=function(T,P){const R=T.cameraToCenterDistance,U=T._centerAltitude*P,V=T._camera,X=T._camera.forward(),ie=he([],ge([],X,-R),[0,0,U]),ue=T.worldSize/(2*Math.PI),pe=[0,0,-ue],be=T.width/T.height,Se=Math.tan(T.fovAboveCenter),Le=ge([],V.up(),Se),ze=ge([],V.right(),Se*be),We=Re([],he([],he([],X,Le),ze)),ct=[];let nt;if(new ii(ie,We).closestPointOnSphere(pe,ue,ct)){const ft=he([],ct,pe),wt=$e([],ft,ie);nt=Math.cos(T.fovAboveCenter)*ee(wt)}else{const ft=$e([],ie,pe),wt=$e([],pe,ie);Re(wt,wt);const Nt=ee(ft)-ue;nt=Math.sqrt(Nt*(Nt+2*ue));const Wt=Math.acos(nt/(ue+Nt))-Math.acos(Ae(X,wt));nt*=Math.cos(Wt)}return 1.01*nt}(m,this.pixelsPerMeter(m.center.lat,m.worldSize)),k=Gj(m.zoom);if(k>0){const T=ROe(m,Ns(1,m.center.lat)*m.worldSize),P=m.worldSize/(2*Math.PI),R=Math.max(m.width,m.height)/m.worldSize*Math.PI;return Dr(x,T+P*(1-Math.cos(R)),Math.pow(k,10))}return x}upVector(m,x,k){return YR(x,k,m,1)}upVectorScale(m){return{metersToTile:nq(aq(x_(m)))}}}function UOe(b){const m=b.parallels,x=!!m&&Math.abs(m[0]+m[1])<.01;switch(b.name){case"mercator":return new FOe(b);case"equirectangular":return new S3t(b);case"naturalEarth":return new T3t(b);case"equalEarth":return new k3t(b);case"winkelTripel":return new E3t(b);case"albers":return x?new $Oe(b):new N3t(b);case"lambertConformalConic":return x?new $Oe(b):new C3t(b);case"globe":return new A3t(b)}throw new Error(`Invalid projection name: ${b.name}`)}class M3t{constructor(m,x){this.lastParams=null,this.lastAllFeaturesIndex=-2,this.appearancesVersion=x,this.appearances=m;const k=m.map(T=>function(P){if(!P.condition)return{featureDependent:!1,stateDependent:!1,zoomDependent:!1,pitchDependent:!1,brightnessDependent:!1,worldviewDependent:!1};const R=P.condition.expression;return{featureDependent:!By(R),stateDependent:!$y(R),zoomDependent:!gm(R,["zoom"]),pitchDependent:!gm(R,["pitch"]),brightnessDependent:!gm(R,["brightness","measure-light"]),worldviewDependent:!gm(R,["worldview"])}}(T));this.anyFeatureDependent=k.some(T=>T.featureDependent),this.anyStateDependent=k.some(T=>T.stateDependent)}update(m,x){const k=this.lastParams,T=!k||k.zoom!==m.zoom||k.pitch!==(m.pitch||0)||k.brightness!==(m.brightness||0)||k.worldview!==m.worldview;this.lastParams={zoom:m.zoom,pitch:m.pitch||0,brightness:m.brightness||0,worldview:m.worldview};const P=x&&this.anyStateDependent;if(!T&&!P&&this.lastAllFeaturesIndex!==-2)return{kind:"no-changes"};if(!this.anyFeatureDependent&&!P){const R=this.evaluateAllFeatures(m);return R===this.lastAllFeaturesIndex?{kind:"no-changes"}:(this.lastAllFeaturesIndex=R,{kind:"all-features",appearanceIndex:R})}return{kind:"per-feature"}}evaluateAllFeatures(m){for(let x=0;x{for(let T=0;TR-U),P=new Map;for(const R of T){const U=k.get(R);P.set(R,new Po(U))}return x&&(this.cachedBatchIndices=T,this.cachedBatchSegments=P),{batchIndices:T,batchSegments:P}}snapshotSymbolVertexData(m,x){const k=m*W6;return this.layoutVertexArray.uint16.slice(k,k+x*W6)}restoreSymbolVertexData(m,x){this.layoutVertexArray.uint16.set(x,m*W6)}updateSymbolVertexData(m,x,k,T,P,R,U,V,X,ie,ue,pe,be){const Se=this.layoutVertexArray.uint16,Le=m*W6;Se[Le]=x,Se[Le+1]=k,Se[Le+2]=T,Se[Le+3]=P,Se[Le+4]=R,Se[Le+5]=U,Se[Le+6]=V,Se[Le+7]=X,Se[Le+8]=ie,Se[Le+9]=ue,Se[Le+10]=pe,Se[Le+11]=be}upload(m,x,k,T,P,R){this.isEmpty()||(k&&(this.cachedBatchIndices=null,this.cachedBatchSegments=null,this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,LCt.members,!!R),this.indexBuffer=m.createIndexBuffer(this.indexArray,x),this.dynamicLayoutVertexBuffer=m.createVertexBuffer(this.dynamicLayoutVertexArray,RCt.members,!0),this.opacityVertexBuffer=m.createVertexBuffer(this.opacityVertexArray,P3t,!0),this.iconTransitioningVertexArray.length>0&&(this.iconTransitioningVertexBuffer=m.createVertexBuffer(this.iconTransitioningVertexArray,BCt.members,!0)),this.globeExtVertexArray.length>0&&(this.globeExtVertexBuffer=m.createVertexBuffer(this.globeExtVertexArray,DCt.members,!0)),!this.zOffsetVertexBuffer&&(this.zOffsetVertexArray.length>0||P)&&(this.zOffsetVertexBuffer=m.createVertexBuffer(this.zOffsetVertexArray,OCt.members,!0)),!this.orientationVertexBuffer&&this.orientationVertexArray&&this.orientationVertexArray.length>0&&(this.orientationVertexBuffer=m.createVertexBuffer(this.orientationVertexArray,zCt.members,!0)),this.opacityVertexBuffer.itemSize=1,this.featureIdArray&&this.featureIdArray.length>0&&(this.featureIdBuffer=m.createVertexBuffer(this.featureIdArray,FCt.members,!1))),(k||T)&&(this.programConfigurations.upload(m),this.uboBinder&&this.uboBinder.upload(m)))}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.programConfigurations.destroy(),this.segments.destroy(),this.dynamicLayoutVertexBuffer.destroy(),this.opacityVertexBuffer.destroy(),this.iconTransitioningVertexBuffer&&this.iconTransitioningVertexBuffer.destroy(),this.globeExtVertexBuffer&&this.globeExtVertexBuffer.destroy(),this.zOffsetVertexBuffer&&this.zOffsetVertexBuffer.destroy(),this.orientationVertexBuffer&&this.orientationVertexBuffer.destroy(),this.featureIdBuffer&&this.featureIdBuffer.destroy(),this.uboBinder&&this.uboBinder.destroy())}}Kn(b_e,"SymbolBuffers",{omit:["cachedBatchIndices","cachedBatchSegments"]});class __e{constructor(m,x,k){this.layoutVertexArray=new m,this.layoutAttributes=x,this.indexArray=new k,this.segments=new Po,this.collisionVertexArray=new LC,this.collisionVertexArrayExt=new N1}upload(m){this.layoutVertexBuffer=m.createVertexBuffer(this.layoutVertexArray,this.layoutAttributes),this.indexBuffer=m.createIndexBuffer(this.indexArray),this.collisionVertexBuffer=m.createVertexBuffer(this.collisionVertexArray,$Ct.members,!0),this.collisionVertexBufferExt=m.createVertexBuffer(this.collisionVertexArrayExt,UCt.members,!0)}destroy(){this.layoutVertexBuffer&&(this.layoutVertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy(),this.collisionVertexBuffer.destroy(),this.collisionVertexBufferExt.destroy())}}Kn(__e,"CollisionBuffers");class T1{constructor(m){this.collisionBoxArray=m.collisionBoxArray,this.zoom=m.zoom,this.overscaling=m.overscaling,this.layers=m.layers,this.layerIds=this.layers.map(R=>R.fqid),this.index=m.index,this.pixelRatio=m.pixelRatio,this.sourceLayerIndex=m.sourceLayerIndex,this.hasPattern=!1,this.hasRTLText=!1,this.fullyClipped=!1,this.hasAnyIconTextFit=!1,this.sortKeyRanges=[],this.collisionCircleArray=[],this.placementInvProjMatrix=v([]),this.placementViewportMatrix=v([]);const x=this.layers[0]._unevaluatedLayout._values;this.worldview=m.worldview,this.localizable=m.localizable,this.maxUniformBufferBindings=m.maxUniformBufferBindings,this.maxUniformBlockSizeDwords=m.maxUniformBlockSizeDwords,this.disableSymbolUBO=m.disableSymbolUBO,this.textSizeData=WC(this.zoom,x["text-size"],this.worldview,m.availableImages),this.iconSizeData=WC(this.zoom,x["icon-size"],this.worldview,m.availableImages);const k=this.layers[0].layout,T=k.get("symbol-sort-key"),P=k.get("symbol-z-order");this.lut=m.lut,this.canOverlap=k.get("text-allow-overlap")||k.get("icon-allow-overlap")||k.get("text-ignore-placement")||k.get("icon-ignore-placement"),this.sortFeaturesByKey=P!=="viewport-y"&&T.constantOr(1)!==void 0,this.sortFeaturesByY=(P==="viewport-y"||P==="auto"&&!this.sortFeaturesByKey)&&this.canOverlap,this.writingModes=k.get("text-writing-mode").map(R=>Ex[R]),this.stateDependentLayerIds=this.layers.filter(R=>R.isStateDependent()).map(R=>R.id),this.sourceID=m.sourceID,this.projection=m.projection,this.hasAnyZOffset=!1,this.zOffsetSortDirty=!1,this.zOffsetBuffersNeedUpload=!1,this.elevationType="none",this.elevationStateComplete=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.hasAnySecondaryIcon=!1,this.hasAppearances=null,this.featureAppearances=null,this.featureAppearanceData=new Map}hasAnyAppearanceLayoutProperty(m){const x=this.layers[0].getAppearances();if(!x||x.length===0)return!1;const k=Array.isArray(m)?m:[m];return x.some(T=>k.some(P=>T.hasLayoutProperty(P)))}getAppearanceFeatureData(m){return this.featureAppearanceData.get(m)}createArrays(){this.text=new b_e(new qe(this.layers,{zoom:this.zoom,lut:this.lut},m=>m.startsWith("text")||m.startsWith("symbol"))),this.icon=new b_e(new qe(this.layers,{zoom:this.zoom,lut:this.lut},m=>m.startsWith("icon")||m.startsWith("symbol"))),this.disableSymbolUBO||(this.text.uboBinder=new s_e(this.layers[0],this.zoom,this.lut,!0,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords),this.icon.uboBinder=new s_e(this.layers[0],this.zoom,this.lut,!1,"",this.maxUniformBufferBindings,this.maxUniformBlockSizeDwords)),this.glyphOffsetArray=new QU,this.lineVertexArray=new OC,this.symbolInstances=new ZU}calculateGlyphDependencies(m,x,k,T,P){for(const R of m){const U=R.codePointAt(0);if(U===void 0)break;if(x[U]=!0,T&&P&&U<=65535){const V=fO[R];V&&(x[V.charCodeAt(0)]=!0)}}}calculateEffectiveAppearanceIconSize(m,x,k,T,P,R,U){if(!m.hasLayoutProperty("icon-size"))return U*R;let V=1;const X=m.getUnevaluatedLayoutProperty("icon-size"),ie=WC(this.zoom,X,this.worldview,P),ue=q6(ie,x);if(ie.kind!=="constant"&&ie.kind!=="camera"||(V=ue.uSize),ie.kind==="composite"){const{minZoom:pe,maxZoom:be}=ie,Se=X.possiblyEvaluate(new Aa(pe,{worldview:this.worldview}),T),Le=X.possiblyEvaluate(new Aa(be,{worldview:this.worldview}),T),ze=Se.evaluate(k,{},T,P);V=ze+(Le.evaluate(k,{},T,P)-ze)*ue.uSizeT}return ie.kind==="source"&&(V=X.possiblyEvaluate(new Aa(this.zoom,{worldview:this.worldview}),T).evaluate(k,{},T,P)),V*R}updateFootprints(m,x){}updateReplacement(m,x){if(x.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=x.updateTime;const k=x.getReplacementRegionsForTile(m.toUnwrapped(),!0);return!fq(this.activeReplacements,k)&&(this.activeReplacements=k,!0)}getResolvedImageFromTokens(m){return typeof m=="string"?qd.build(m):m}populate(m,x,k,T){const P=this.layers[0],R=P.layout,U=this.projection.name==="globe",V=R.get("text-font"),X=R.get("text-field"),ie=R.get("icon-image"),[ue,pe]=R.get("icon-size-scale-range"),be=Qe(x.scaleFactor||1,ue,pe),[Se,Le]=R.get("text-size-scale-range"),ze=Qe(x.scaleFactor||1,Se,Le),We=(X.value.kind!=="constant"||X.value.value instanceof Ud&&!X.value.value.isEmpty()||X.value.value.toString().length>0)&&(V.value.kind!=="constant"||V.value.value.length>0),ct=ie.value.kind!=="constant"||!!ie.value.value||Object.keys(ie.parameters).length>0,nt=this.hasAnyAppearanceLayoutProperty("icon-image"),ft=R.get("symbol-sort-key");if(this.features=[],this.featureAppearanceData=new Map,!We&&!ct&&!nt)return;const wt=x.iconDependencies,Nt=x.glyphDependencies,Wt=x.availableImages,Ft=new Aa(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),Gt=Ut=>{const qt=Ut.id.toString();wt.has(qt)?wt.get(qt).push(Ut):wt.set(qt,[Ut])};for(const Ut of m){const{feature:qt,id:zs,index:qs,sourceLayerIndex:Xs}=Ut,sn=P._featureFilter.needGeometry,Js=Ha(qt,sn);if(!P._featureFilter.filter(Ft,Js,k))continue;if(sn||(Js.geometry=Vr(qt,k,T)),U&&qt.type!==1&&k.z<=5){const Fn=Js.geometry,Rn=.98078528056,Tn=(sr,hr)=>Ae(YR(sr.x,sr.y,k,1),YR(hr.x,hr.y,k,1)){if(!Fn.getLayoutProperty("icon-image"))return;const Rn=this.getCombinedIconPrimary(Fn,en,Js,k,Wt,Cn,be);Rn&&Gt(Rn)}),fn){const Fn=V.evaluate(Js,{},k).join(","),Rn=R.get("text-rotation-alignment")==="map"&&R.get("symbol-placement")!=="point";this.allowVerticalPlacement=this.writingModes&&this.writingModes.indexOf(Ex.vertical)>=0;for(const Tn of fn.sections)if(Tn.image){const sr=Tn.image.getPrimary().scaleSelf(this.pixelRatio*ze),hr=sr.id.toString(),Ur=wt.get(hr)||[];Ur.push(sr),wt.set(hr,Ur)}else{const sr=Uh(fn.toString()),hr=Tn.fontStack||Fn,Ur=Nt[hr]=Nt[hr]||{};this.calculateGlyphDependencies(Tn.text,Ur,Rn,this.allowVerticalPlacement,sr)}}}if(R.get("symbol-placement")==="line"&&(this.features=function(Ut){const qt={},zs={},qs=[];let Xs=0;function sn(en){qs.push(Ut[en]),Xs++}function Js(en,on,gn){const Cn=zs[en];return delete zs[en],zs[on]=Cn,qs[Cn].geometry[0].pop(),qs[Cn].geometry[0]=qs[Cn].geometry[0].concat(gn[0]),Cn}function fn(en,on,gn){const Cn=qt[on];return delete qt[on],qt[en]=Cn,qs[Cn].geometry[0].shift(),qs[Cn].geometry[0]=gn[0].concat(qs[Cn].geometry[0]),Cn}function Os(en,on,gn){const Cn=gn?on[0][on[0].length-1]:on[0][0];return`${en}:${Cn.x}:${Cn.y}`}for(let en=0;enen.geometry)}(this.features)),R.get("symbol-elevation-reference")==="hd-road-markup"){if(this.elevationType="road",x.elevationFeatures){!this.elevationFeatures&&x.elevationFeatures.length>0&&(this.elevationFeatures=[],this.elevationFeatureIdToIndex=new Map);for(const Ut of x.elevationFeatures)this.elevationFeatureIdToIndex.set(Ut.id,this.elevationFeatures.length),this.elevationFeatures.push(Ut)}}else R.get("symbol-z-elevate")&&(this.elevationType="offset");this.elevationType!=="none"&&(this.zOffsetBuffersNeedUpload=!0),this.sortFeaturesByKey&&this.features.sort((Ut,qt)=>Ut.sortKey-qt.sortKey)}getCombinedIconPrimary(m,x,k,T,P,R,U){let V,X;if(m.hasLayoutProperty("icon-image")){const ie=x.getAppearanceValueAndResolveTokens(m,"icon-image",k,T,P);V=this.getResolvedImageFromTokens(ie)}else{const ie=x.getValueAndResolveTokens("icon-image",k,T,P);V=this.getResolvedImageFromTokens(ie)}if(V){const ie=m.hasLayoutProperty("icon-size")?m.getUnevaluatedLayoutProperty("icon-size"):x._unevaluatedLayout._values["icon-size"];X=bO(V,WC(this.zoom,ie,this.worldview,P),ie,T,this.zoom,R,this.pixelRatio,U,this.worldview,P).iconPrimary}return X}updateSymbolInstanceIconVertices(m,x,k,T,P,R){const{canonical:U,availableImages:V,globalProperties:X,layer:ie,iconScaleFactor:ue,featureState:pe,layoutIconOffset:be,layoutIconSize:Se,layoutIconRotate:Le}=R;if(m.placedIconSymbolIndex<0)return{vertexOffsetDelta:0,hasChanges:!1};if(x.activeAppearanceIndex===k)return{vertexOffsetDelta:m.numIconVertices,hasChanges:!1};const ze=k>=0?ie.appearances[k]:null;if(ze){const We=this.getCombinedIconPrimary(ze,ie,T,U,V,{sortKey:void 0,text:void 0,icon:null,index:m.featureIndex,sourceLayerIndex:m.featureIndex,geometry:[],properties:x.properties,type:"Point",id:x.id},ue);if(!We)return{vertexOffsetDelta:0,hasChanges:!1};const ct=We.toString(),nt=this.iconAtlasPositions&&this.iconAtlasPositions.get(ct);if(nt){const{appearanceIconOffset:ft,appearanceIconRotate:wt}=EOe(ze,ie,T,U,be,Le,Se,ue);let Nt=Lq(nt,void 0,ft,ie.layout.get("icon-anchor").evaluate(T,pe,U));const Wt=nt.sdf,Ft=ie.layout.get("icon-text-fit").constantOr("none");Ft!=="none"&&x.textShaping&&x.iconTextFitPadding&&x.fontScale&&(Nt=o_e(Nt,x.textShaping,Ft,x.iconTextFitPadding,ft,x.fontScale));const Gt=this.calculateEffectiveAppearanceIconSize(ze,X.zoom,T,U,V,ue,Se),Ut=0,qt=1+(Math.min(KC,Math.round(Gt*Yj))<<1),zs=p_e(Nt,wt,Wt,Ft!=="none",ue);x.isUsingAppearanceIconVertexData||(x.isUsingAppearanceIconVertexData=!0,x.layoutBasedIconVertexData=this.icon.snapshotSymbolVertexData(P,m.numIconVertices));const qs=Math.floor(m.numIconVertices/4),Xs=Math.min(zs.length,qs);let sn=P;for(let fn=0;fn0||m.numVerticalGlyphVertices>0;if(!ft)return{vertexOffsetDelta:ft?m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices:0,hasChanges:!1};if(x.activeAppearanceIndex===k)return{vertexOffsetDelta:m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices,hasChanges:!1};const wt=k>=0?V.appearances[k]:null;if(wt&&x.textShaping){const{appearanceTextOffset:Nt,appearanceTextRotate:Wt,appearanceTextSize:Ft}=AOe(wt,V,T,U,pe,Se,be);x.fontScale=LOe(Ft,x.textScaleFactor);const Gt=wt.getUnevaluatedLayoutProperty("text-size");let Ut=this.textSizeData,qt=We,zs=ct;wt.hasLayoutProperty("text-size")&&(Ut=WC(this.zoom,Gt,this.worldview,nt),qt=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,zs=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0);const qs=x.textShaping.bottom-pe[1],Xs=x.textShaping.left-pe[0],sn=x.textShaping.right-pe[0];x.textShaping.top=Nt[1]+(x.textShaping.top-pe[1]),x.textShaping.bottom=Nt[1]+qs,x.textShaping.left=Nt[0]+Xs,x.textShaping.right=Nt[0]+sn;const Js=COe(0,x.textShaping,Nt,V,!1,T,ie,this.allowVerticalPlacement,Wt),fn=Ft&&Ut.kind==="composite"?Gt.possiblyEvaluate(new Aa(qt,{}),U).evaluate(T,ue,U):Le,Os=Ft&&Ut.kind==="composite"?Gt.possiblyEvaluate(new Aa(zs,{}),U).evaluate(T,ue,U):ze,en=y_e(wt.name,Ut,Ft,X,fn,Os),on=Array.isArray(en)?en[1]:Ft,gn=0,Cn=1+(Math.min(KC,Math.round(on*Yj))<<1);x.isUsingAppearanceTextVertexData||(x.isUsingAppearanceTextVertexData=!0,x.layoutBasedTextVertexData=this.text.snapshotSymbolVertexData(P,m.numHorizontalGlyphVertices+m.numVerticalGlyphVertices));for(let ar=0;ar0){const X=new Set(Object.keys(m).map(ie=>{const ue=Number(ie);return!isNaN(ue)&&Number.isSafeInteger(ue)&&String(ue)===ie?ue:ie}));this.text.uboBinder&&this.text.uboBinder.updateFeatures(X,P[0],x,V,k,m,U),this.icon.uboBinder&&this.icon.uboBinder.updateFeatures(X,P[0],x,V,k,m,U)}}}updateRoadElevation(m){if(this.elevationType!=="road"||!this.elevationFeatures||this.elevationStateComplete)return;this.elevationStateComplete=!0,this.hasAnyZOffset=!1;let x=!1;const k=cn(m),T=1/k;let P=!1,R=!1;for(let U=0;U0||pe>0,ze=be>0,We=this.elevationFeatures[V.elevationFeatureIndex];if(We){const ct=new Es(V.tileAnchorX,V.tileAnchorY),nt=.075+We.pointElevation(ct);V.zOffset!==nt&&(x=!0,V.zOffset=nt),nt!==0&&(this.hasAnyZOffset=!0);const ft=We.computeSlopeNormal(ct,T),wt=Jt(_t(),se(0,0,1),ft);it(X,X,wt),it(ie,ie,wt),X[2]*=k,ie[2]*=k,X[0]===1&&X[1]===0&&X[2]===0&&ie[0]===0&&ie[1]===1&&ie[2]===0||(P=P||Le,R=R||ze)}if(Le&&(Hq(this.text.orientationVertexArray,ue,X,ie),Hq(this.text.orientationVertexArray,pe,X,ie)),ze){const{placedIconSymbolIndex:ct,verticalPlacedIconSymbolIndex:nt}=V;ct>=0&&Hq(this.icon.orientationVertexArray,be,X,ie),nt>=0&&Hq(this.icon.orientationVertexArray,Se,X,ie)}}P||(this.text.orientationVertexArray=void 0),R||(this.icon.orientationVertexArray=void 0),x&&(this.zOffsetBuffersNeedUpload=!0,this.zOffsetSortDirty=!0)}updateZOffset(){const m=(P,R,U)=>{k+=R,k>P.length&&P.resize(k);for(let V=-R;V<0;V++)P.emplace(V+k,U)},x=(P,R,U)=>{T+=R,T>P.length&&P.resize(T);for(let V=-R;V<0;V++)P.emplace(V+T,U)};if(!this.zOffsetBuffersNeedUpload)return;this.zOffsetBuffersNeedUpload=!1;let k=0,T=0;for(let P=0;P0;if((U>0||V>0)&&(m(this.text.zOffsetVertexArray,U,ie),m(this.text.zOffsetVertexArray,V,ie)),ue){const{placedIconSymbolIndex:pe,verticalPlacedIconSymbolIndex:be}=R;pe>=0&&x(this.icon.zOffsetVertexArray,X,ie),be>=0&&x(this.icon.zOffsetVertexArray,R.numVerticalIconVertices,ie)}}this.text.zOffsetVertexBuffer&&this.text.zOffsetVertexBuffer.updateData(this.text.zOffsetVertexArray),this.icon.zOffsetVertexBuffer&&this.icon.zOffsetVertexBuffer.updateData(this.icon.zOffsetVertexArray)}isEmpty(){return this.symbolInstances.length===0&&!this.hasRTLText}uploadPending(){return!this.uploaded||this.text.programConfigurations.needsUpload||this.icon.programConfigurations.needsUpload}upload(m,x,k,T,P){!this.uploaded&&this.hasDebugData()&&(this.textCollisionBox.upload(m),this.iconCollisionBox.upload(m)),this.text.upload(m,this.sortFeaturesByY,!this.uploaded,this.text.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.hasAppearances===null&&(this.hasAppearances=this.layers.some(R=>R.appearances&&R.appearances.length>0)),this.icon.upload(m,this.sortFeaturesByY,!this.uploaded,this.icon.programConfigurations.needsUpload,this.zOffsetBuffersNeedUpload,this.hasAppearances),this.uploaded=!0}updateAppearances(m,x,k,T,P,R=!1){const U={hasLayoutChanges:!1,hasUboChanges:!1};if(!m||!k||!this.featureAppearanceData)return U;const V=x||{},X=this.icon.layoutVertexArray&&this.icon.layoutVertexArray.length>0&&this.icon.layoutVertexArray.arrayBuffer,ie=this.text.layoutVertexArray&&this.text.layoutVertexArray.length>0&&this.text.layoutVertexArray.arrayBuffer;if(!X&&!ie)return U;const ue=this.layers[0],pe=ue.layout;this.featureAppearances&&this.featureAppearances.appearancesVersion===ue.appearancesVersion||(this.featureAppearances=new M3t(ue.appearances,ue.appearancesVersion));const be=this.featureAppearances.update(T,R);if(be.kind==="no-changes")return U;let Se=1,Le=0,ze=!1,We=!1;if(X){const[Nt,Wt]=pe.get("icon-size-scale-range");Se=Qe(1,Nt,Wt)}let ct=1,nt=0,ft=!1;if(ie){const[Nt,Wt]=pe.get("text-size-scale-range");ct=Qe(1,Nt,Wt)}const wt=new Map;if(P&&k)for(const Nt of k){const Wt=P.getImage(Nt,ue.scope);if(Wt){const Ft=new ep(Nt.toString());wt.set(Ft.toString(),Wt)}}for(let Nt=0;Ntsn.isActive({globals:T,feature:qt,canonical:m,featureState:Ut})):-1;zs=Xs>=0?Xs:-1}const qs=Ft.activeAppearanceIndex!==zs;if(ie){const Xs=pe.get("text-size"),sn=this.textSizeData.kind==="composite"?this.textSizeData.minZoom:0,Js=this.textSizeData.kind==="composite"?this.textSizeData.maxZoom:0,fn={canonical:m,layer:ue,featureState:Ut,availableImages:k,textScaleFactor:ct,imageMap:wt,layoutTextOffset:pe.get("text-offset").evaluate(qt,Ut,m).map(en=>en*Kd),layoutTextSize:Xs.evaluate(qt,Ut,m),layoutTextRotate:pe.get("text-rotate").evaluate(qt,Ut,m),layoutMinZoomSize:Xs.evaluate(qt,{zoom:sn},m),layoutMaxZoomSize:Xs.evaluate(qt,{zoom:Js},m),layoutTextSizeMinZoom:sn,layoutTextSizeMaxZoom:Js},Os=this.updateSymbolInstanceTextVertices(Wt,Ft,zs,qt,nt,fn);nt+=Os.vertexOffsetDelta,ft=ft||Os.hasChanges}if(X){const Xs={canonical:m,layer:ue,featureState:Ut,availableImages:k,globalProperties:T,iconScaleFactor:Se,layoutIconOffset:pe.get("icon-offset").evaluate(qt,Ut,m),layoutIconSize:pe.get("icon-size").evaluate(qt,Ut,m,k),layoutIconRotate:pe.get("icon-rotate").evaluate(qt,Ut,m)},sn=this.updateSymbolInstanceIconVertices(Wt,Ft,zs,qt,Le,Xs);Le+=sn.vertexOffsetDelta,ze=ze||sn.hasChanges}if(qs){const Xs=Wt.featureIndex,sn=T?T.brightness:null,Js=Ut||{},fn=zs>=0?ue.appearances[zs]:null;this.text.uboBinder&&(this.text.uboBinder.layer=ue,We=this.text.uboBinder.updateFeaturePaintForAppearance(Xs,qt,Js,m,k,sn,fn)||We),this.icon.uboBinder&&(this.icon.uboBinder.layer=ue,We=this.icon.uboBinder.updateFeaturePaintForAppearance(Xs,qt,Js,m,k,sn,fn)||We)}Ft.activeAppearanceIndex=zs}return ze&&this.icon.layoutVertexBuffer&&this.icon.layoutVertexArray.arrayBuffer!==null&&this.icon.layoutVertexArray.length===this.icon.layoutVertexBuffer.length&&this.icon.layoutVertexBuffer.updateData(this.icon.layoutVertexArray),ft&&this.text.layoutVertexBuffer&&this.text.layoutVertexArray.arrayBuffer!==null&&this.text.layoutVertexArray.length===this.text.layoutVertexBuffer.length&&this.text.layoutVertexBuffer.updateData(this.text.layoutVertexArray),{hasLayoutChanges:ze||ft,hasUboChanges:We}}destroyDebugData(){this.textCollisionBox.destroy(),this.iconCollisionBox.destroy()}getProjection(){return this.projectionInstance||(this.projectionInstance=UOe(this.projection)),this.projectionInstance}destroy(){this.text.destroy(),this.icon.destroy(),this.hasDebugData()&&this.destroyDebugData()}addToLineVertexArray(m,x){const k=this.lineVertexArray.length;if(m.segment!==void 0)for(const{x:T,y:P}of x)this.lineVertexArray.emplaceBack(T,P);return{lineStartIndex:k,lineLength:this.lineVertexArray.length-k}}addSymbols(m,x,k,T,P,R,U,V,X,ie,ue,pe,be,Se,Le,ze,We,ct){const nt=m.indexArray,ft=m.layoutVertexArray,wt=m.globeExtVertexArray,Nt=ct,Wt=m.uboBinder?m.uboBinder.getCurrentBatchIndex():void 0,Ft=m.segments.prepareSegment(4*Nt,ft,nt,this.canOverlap?R.sortKey:void 0,Wt),Gt=this.glyphOffsetArray.length,Ut=Ft.vertexLength,qt=this.allowVerticalPlacement&&U===Ex.vertical?Math.PI/2:0,zs=R.text&&R.text.sections;let qs=ft.length,Xs=-1;for(let fn=0;fn=0)){const fn=4*sn;for(let Os=0;Os=0?x.rightJustifiedTextSymbolIndex:x.centerJustifiedTextSymbolIndex>=0?x.centerJustifiedTextSymbolIndex:x.leftJustifiedTextSymbolIndex>=0?x.leftJustifiedTextSymbolIndex:x.verticalPlacedTextSymbolIndex>=0?x.verticalPlacedTextSymbolIndex:T),R=l_e(this.textSizeData,m,P)/Kd;return this.tilePixelRatio*R}getSymbolInstanceIconSize(m,x,k){const T=this.icon.placedSymbolArray.get(k),P=l_e(this.iconSizeData,m,T);return this.tilePixelRatio*P}_commitDebugCollisionVertexUpdate(m,x,k,T){m.emplaceBack(x,-k,-k,T),m.emplaceBack(x,k,-k,T),m.emplaceBack(x,k,k,T),m.emplaceBack(x,-k,k,T)}_updateTextDebugCollisionBoxes(m,x,k,T,P,R,U){for(let V=T;V0}hasIconData(){return this.icon.segments.get().length>0}hasDebugData(){return this.textCollisionBox&&this.iconCollisionBox}hasTextCollisionBoxData(){return this.hasDebugData()&&this.textCollisionBox.segments.get().length>0}hasIconCollisionBoxData(){return this.hasDebugData()&&this.iconCollisionBox.segments.get().length>0}hasIconTextFit(){return this.hasAnyIconTextFit}addIndicesForPlacedSymbol(m,x){const k=m.placedSymbolArray.get(x),T=k.vertexStartIndex+4*k.numGlyphs;for(let P=k.vertexStartIndex;PT[U]-T[V]||P[V]-P[U]),R}getSortedIndexesByZOffset(){if(!this.zOffsetSortDirty)return this.symbolInstanceIndexesSortedZOffset;if(!this.symbolInstanceIndexesSortedZOffset){this.symbolInstanceIndexesSortedZOffset=[];for(let m=0;mthis.symbolInstances.get(x).zOffset-this.symbolInstances.get(m).zOffset)}addToSortKeyRanges(m,x){const k=this.sortKeyRanges[this.sortKeyRanges.length-1];k&&k.sortKey===x?k.symbolInstanceEnd=m+1:this.sortKeyRanges.push({sortKey:x,symbolInstanceStart:m,symbolInstanceEnd:m+1})}sortFeatures(m){if(this.sortFeaturesByY&&this.sortedAngle!==m)if(this.text.segments.get().length>1||this.icon.segments.get().length>1)this.sortFeaturesWithinSegments();else{this.symbolInstanceIndexes=this.getSortedSymbolIndexes(m),this.sortedAngle=m,this.text.indexArray.clear(),this.icon.indexArray.clear(),this.featureSortOrder=[];for(const x of this.symbolInstanceIndexes){const k=this.symbolInstances.get(x);this.featureSortOrder.push(k.featureIndex);const{rightJustifiedTextSymbolIndex:T,centerJustifiedTextSymbolIndex:P,leftJustifiedTextSymbolIndex:R,verticalPlacedTextSymbolIndex:U,placedIconSymbolIndex:V,verticalPlacedIconSymbolIndex:X}=k;T>=0&&this.addIndicesForPlacedSymbol(this.text,T),P>=0&&P!==T&&this.addIndicesForPlacedSymbol(this.text,P),R>=0&&R!==P&&R!==T&&this.addIndicesForPlacedSymbol(this.text,R),U>=0&&this.addIndicesForPlacedSymbol(this.text,U),V>=0&&this.addIndicesForPlacedSymbol(this.icon,V),X>=0&&this.addIndicesForPlacedSymbol(this.icon,X)}this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}}getOrCreateSortedSymbolsByBatch(m,x){const k=(this.text.uboBinder&&this.text.uboBinder.maxFeaturesPerBatch>0?this.text.uboBinder:this.icon.uboBinder&&this.icon.uboBinder.maxFeaturesPerBatch>0?this.icon.uboBinder:null).maxFeaturesPerBatch;if(this.symbolsByBatch)for(const T of this.symbolsByBatch.values())for(const P of T){const R=this.symbolInstances.get(P.index);P.rotatedY=0|Math.round(m*R.tileAnchorX+x*R.tileAnchorY)}else{this.symbolsByBatch=new Map;for(let T=0;TP.rotatedY-R.rotatedY||R.featureIndex-P.featureIndex);return this.symbolsByBatch}rebuildTextSegmentIndices(m,x){for(const k of m){const T=k.batchIndex;if(T===void 0)continue;const P=x.get(T);if(!P){k.primitiveOffset=this.text.indexArray.length,k.primitiveLength=0;continue}k.primitiveOffset=this.text.indexArray.length;const R=this.text.indexArray.length;for(const{index:U}of P){const V=this.symbolInstances.get(U),{rightJustifiedTextSymbolIndex:X,centerJustifiedTextSymbolIndex:ie,leftJustifiedTextSymbolIndex:ue,verticalPlacedTextSymbolIndex:pe}=V;X>=0&&this.addIndicesForPlacedSymbol(this.text,X),ie>=0&&ie!==X&&this.addIndicesForPlacedSymbol(this.text,ie),ue>=0&&ue!==ie&&ue!==X&&this.addIndicesForPlacedSymbol(this.text,ue),pe>=0&&this.addIndicesForPlacedSymbol(this.text,pe)}k.primitiveLength=this.text.indexArray.length-R}}rebuildIconSegmentIndices(m,x){for(const k of m){const T=k.batchIndex;if(T===void 0)continue;const P=x.get(T);if(!P){k.primitiveOffset=this.icon.indexArray.length,k.primitiveLength=0;continue}k.primitiveOffset=this.icon.indexArray.length;const R=this.icon.indexArray.length;for(const{index:U}of P){const V=this.symbolInstances.get(U),{placedIconSymbolIndex:X,verticalPlacedIconSymbolIndex:ie}=V;X>=0&&this.addIndicesForPlacedSymbol(this.icon,X),ie>=0&&this.addIndicesForPlacedSymbol(this.icon,ie)}k.primitiveLength=this.icon.indexArray.length-R}}sortFeaturesWithinSegments(){this.featureSortOrder=[];const m=Math.sin(this.sortedAngle),x=Math.cos(this.sortedAngle),k=this.getOrCreateSortedSymbolsByBatch(m,x),T=Array.from(k.keys()).sort((P,R)=>P-R);for(const P of T){const R=k.get(P);for(const{index:U}of R){const V=this.symbolInstances.get(U);this.featureSortOrder.push(V.featureIndex)}}this.text.indexArray.clear(),this.icon.indexArray.clear(),this.rebuildTextSegmentIndices(this.text.segments.get(),k),this.rebuildIconSegmentIndices(this.icon.segments.get(),k),this.text.indexBuffer&&this.text.indexBuffer.updateData(this.text.indexArray),this.icon.indexBuffer&&this.icon.indexBuffer.updateData(this.icon.indexArray)}getElevationFeatureForText(m){const x=this.symbolInstances.get(this.text.symbolInstanceIndices[m]).elevationFeatureIndex;let k;return this.elevationFeatures&&xk in b?String(b[k]):"")}let VOe,HOe,w_e;Kn(T1,"SymbolBucket",{omit:["layers","collisionBoxArray","compareText","features"]}),T1.addDynamicAttributes=G6;class GOe{constructor(m){this.type=m.property.overrides?m.property.overrides.runtimeType:Ef,this.defaultValue=m}evaluate(m){if(m.formattedSection){const x=this.defaultValue.property.overrides;if(x&&x.hasOverride(m.formattedSection))return x.getOverride(m.formattedSection)}return m.feature&&m.featureState?this.defaultValue.evaluate(m.feature,m.featureState):this.defaultValue.property.specification.default}eachChild(m){this.defaultValue.isConstant()||m(this.defaultValue.value._styleExpression.expression)}outputDefined(){return!1}serialize(){return null}}Kn(GOe,"FormatSectionOverride",{omit:["defaultValue"]});const j_e=()=>w_e||(w_e={layout:VOe||(VOe=new qo({"symbol-placement":new wn(ps.layout_symbol["symbol-placement"]),"symbol-spacing":new wn(ps.layout_symbol["symbol-spacing"]),"symbol-avoid-edges":new wn(ps.layout_symbol["symbol-avoid-edges"]),"symbol-sort-key":new bn(ps.layout_symbol["symbol-sort-key"]),"symbol-z-order":new wn(ps.layout_symbol["symbol-z-order"]),"symbol-z-elevate":new wn(ps.layout_symbol["symbol-z-elevate"]),"symbol-elevation-reference":new wn(ps.layout_symbol["symbol-elevation-reference"]),"icon-allow-overlap":new wn(ps.layout_symbol["icon-allow-overlap"]),"icon-ignore-placement":new wn(ps.layout_symbol["icon-ignore-placement"]),"icon-optional":new wn(ps.layout_symbol["icon-optional"]),"icon-rotation-alignment":new wn(ps.layout_symbol["icon-rotation-alignment"]),"icon-size":new bn(ps.layout_symbol["icon-size"]),"icon-size-scale-range":new wn(ps.layout_symbol["icon-size-scale-range"]),"icon-text-fit":new bn(ps.layout_symbol["icon-text-fit"]),"icon-text-fit-padding":new bn(ps.layout_symbol["icon-text-fit-padding"]),"icon-image":new bn(ps.layout_symbol["icon-image"]),"icon-image-use-theme":new wn({type:"string",default:"default","property-type":"data-constant"}),"icon-rotate":new bn(ps.layout_symbol["icon-rotate"]),"icon-padding":new wn(ps.layout_symbol["icon-padding"]),"icon-keep-upright":new wn(ps.layout_symbol["icon-keep-upright"]),"icon-offset":new bn(ps.layout_symbol["icon-offset"]),"icon-anchor":new bn(ps.layout_symbol["icon-anchor"]),"icon-pitch-alignment":new wn(ps.layout_symbol["icon-pitch-alignment"]),"text-pitch-alignment":new wn(ps.layout_symbol["text-pitch-alignment"]),"text-rotation-alignment":new wn(ps.layout_symbol["text-rotation-alignment"]),"text-field":new bn(ps.layout_symbol["text-field"]),"text-font":new bn(ps.layout_symbol["text-font"]),"text-size":new bn(ps.layout_symbol["text-size"]),"text-size-scale-range":new wn(ps.layout_symbol["text-size-scale-range"]),"text-max-width":new bn(ps.layout_symbol["text-max-width"]),"text-line-height":new bn(ps.layout_symbol["text-line-height"]),"text-letter-spacing":new bn(ps.layout_symbol["text-letter-spacing"]),"text-justify":new bn(ps.layout_symbol["text-justify"]),"text-radial-offset":new bn(ps.layout_symbol["text-radial-offset"]),"text-variable-anchor":new wn(ps.layout_symbol["text-variable-anchor"]),"text-anchor":new bn(ps.layout_symbol["text-anchor"]),"text-max-angle":new wn(ps.layout_symbol["text-max-angle"]),"text-writing-mode":new wn(ps.layout_symbol["text-writing-mode"]),"text-rotate":new bn(ps.layout_symbol["text-rotate"]),"text-padding":new wn(ps.layout_symbol["text-padding"]),"text-keep-upright":new wn(ps.layout_symbol["text-keep-upright"]),"text-transform":new bn(ps.layout_symbol["text-transform"]),"text-offset":new bn(ps.layout_symbol["text-offset"]),"text-allow-overlap":new wn(ps.layout_symbol["text-allow-overlap"]),"text-ignore-placement":new wn(ps.layout_symbol["text-ignore-placement"]),"text-optional":new wn(ps.layout_symbol["text-optional"]),visibility:new wn(ps.layout_symbol.visibility)})),paint:HOe||(HOe=new qo({"icon-opacity":new bn(ps.paint_symbol["icon-opacity"]),"icon-occlusion-opacity":new bn(ps.paint_symbol["icon-occlusion-opacity"]),"icon-emissive-strength":new bn(ps.paint_symbol["icon-emissive-strength"]),"text-emissive-strength":new bn(ps.paint_symbol["text-emissive-strength"]),"icon-color":new bn(ps.paint_symbol["icon-color"]),"icon-halo-color":new bn(ps.paint_symbol["icon-halo-color"]),"icon-halo-width":new bn(ps.paint_symbol["icon-halo-width"]),"icon-halo-blur":new bn(ps.paint_symbol["icon-halo-blur"]),"icon-translate":new wn(ps.paint_symbol["icon-translate"]),"icon-translate-anchor":new wn(ps.paint_symbol["icon-translate-anchor"]),"icon-image-cross-fade":new wn(ps.paint_symbol["icon-image-cross-fade"]),"text-opacity":new bn(ps.paint_symbol["text-opacity"]),"text-occlusion-opacity":new bn(ps.paint_symbol["text-occlusion-opacity"]),"text-color":new bn(ps.paint_symbol["text-color"],{runtimeType:Oh,getOverride:b=>b.textColor,hasOverride:b=>!!b.textColor}),"text-halo-color":new bn(ps.paint_symbol["text-halo-color"]),"text-halo-width":new bn(ps.paint_symbol["text-halo-width"]),"text-halo-blur":new bn(ps.paint_symbol["text-halo-blur"]),"text-translate":new wn(ps.paint_symbol["text-translate"]),"text-translate-anchor":new wn(ps.paint_symbol["text-translate-anchor"]),"icon-color-saturation":new wn(ps.paint_symbol["icon-color-saturation"]),"icon-color-contrast":new wn(ps.paint_symbol["icon-color-contrast"]),"icon-color-brightness-min":new wn(ps.paint_symbol["icon-color-brightness-min"]),"icon-color-brightness-max":new wn(ps.paint_symbol["icon-color-brightness-max"]),"symbol-z-offset":new bn(ps.paint_symbol["symbol-z-offset"]),"icon-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"icon-halo-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"text-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"text-halo-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"})}))},w_e);class Gq extends lo{constructor(m,x,k,T){super(m,j_e(),x,k,T,m.layout?m.layout["icon-image-use-theme"]:null),this._colorAdjustmentMatrix=v([]),this.hasOcclusionOpacityProperties=m.paint!==void 0&&("icon-occlusion-opacity"in m.paint||"text-occlusion-opacity"in m.paint)}_handleSpecialPaintPropertyUpdate(m){m!=="icon-occlusion-opacity"&&m!=="text-occlusion-opacity"||(this.hasOcclusionOpacityProperties=!0)}recalculate(m,x){super.recalculate(m,x),this.appearances&&this.appearances.forEach(T=>{T.recalculate(m,x,this.iconImageUseTheme)}),this.layout.get("icon-rotation-alignment")==="auto"&&(this.layout._values["icon-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-rotation-alignment")==="auto"&&(this.layout._values["text-rotation-alignment"]=this.layout.get("symbol-placement")!=="point"?"map":"viewport"),this.layout.get("text-pitch-alignment")==="auto"&&(this.layout._values["text-pitch-alignment"]=this.layout.get("text-rotation-alignment")),this.layout.get("icon-pitch-alignment")==="auto"&&(this.layout._values["icon-pitch-alignment"]=this.layout.get("icon-rotation-alignment"));const k=this.layout.get("text-writing-mode");if(k){const T=[];for(const P of k)T.indexOf(P)<0&&T.push(P);this.layout._values["text-writing-mode"]=T}else this.layout._values["text-writing-mode"]=this.layout.get("symbol-placement")==="point"?["horizontal"]:["horizontal","vertical"];this._setPaintOverrides()}getColorAdjustmentMatrix(m,x,k,T){return this._saturation===m&&this._contrast===x&&this._brightnessMin===k&&this._brightnessMax===T||(this._colorAdjustmentMatrix=function(P,R,U,V){P=Yi(P),R=si(R);const X=y(),ie=P/3,ue=1-2*ie,pe=[ue,ie,ie,0,ie,ue,ie,0,ie,ie,ue,0,0,0,0,1],be=.5-.5*R,Se=V-U;return w(X,[Se,0,0,0,0,Se,0,0,0,0,Se,0,U,U,U,1],[R,0,0,0,0,R,0,0,0,0,R,0,be,be,be,1]),w(X,X,pe),X}(m,x,k,T),this._saturation=m,this._contrast=x,this._brightnessMin=k,this._brightnessMax=T),this._colorAdjustmentMatrix}getValueAndResolveTokens(m,x,k,T){const P=this.layout.get(m).evaluate(x,{},k,T),R=this._unevaluatedLayout._values[m];return R.isDataDriven()||Vy(R.value)||!P?P:qOe(x.properties,P)}getAppearanceValueAndResolveTokens(m,x,k,T,P){const R=m.getLayoutProperty(x);if(!R)return;const U=R.evaluate(k,{},T,P),V=m.getUnevaluatedLayoutProperties()._values[x];return V.isDataDriven()||Vy(V.value)||!U||typeof U!="string"?U:qOe(k.properties,U)}createBucket(m){return new T1(m)}queryRadius(){return 0}queryIntersectsFeature(){return!1}_setPaintOverrides(){for(const m of j_e().paint.overridableProperties){if(!Gq.hasPaintOverride(this.layout,m))continue;const x=this.paint.get(m),k=new GOe(x),T=new v1(k,x.property.specification,this.scope,this.options,this.layout.get("icon-image-use-theme"));let P=null;P=x.value.kind==="constant"||x.value.kind==="source"?new x0("source",T):new _x("composite",T,x.value.zoomStops,x.value.interpolationType),this.paint._values[m]=new w1(x.property,P,x.parameters)}}_handleOverridablePaintPropertyUpdate(m,x,k){return!(!this.layout||x.isDataDriven()||k.isDataDriven())&&Gq.hasPaintOverride(this.layout,m)}static hasPaintOverride(m,x){const k=m.get("text-field"),T=j_e().paint.properties[x];let P=!1;const R=U=>{for(const V of U)if(T.overrides&&T.overrides.hasOverride(V))return void(P=!0)};if(k.value.kind==="constant"&&k.value.value instanceof Ud)R(k.value.value.sections);else if(k.value.kind==="source"){const U=X=>{P||(X instanceof nr&&Al(X.value)===Ly?R(X.value.sections):X instanceof fm?R(X.sections):X.eachChild(U))},V=k.value;V._styleExpression&&U(V._styleExpression.expression)}return P}getProgramIds(){return["symbol"]}getDefaultProgramParams(m,x,k){return{config:new De(this,{zoom:x,lut:k}),overrideFog:!1}}hasElevation(){return this.layout&&this.layout.get("symbol-elevation-reference")==="hd-road-markup"}}let WOe,KOe,YOe,ZOe;var Wq=ln([{name:"a_pos",type:"Int16",components:2},{name:"a_texture_pos",type:"Uint16",components:2}]);function Kq(b,m,x,k,T,P,R,U){const V=[b,m,1,x,k,1,T,P,1],X=[R,U,1],ie=p([],V),[ue,pe,be]=ke(X,X,ie);return f(V,V,[ue,0,0,0,pe,0,0,0,be])}function QOe(b,m,x,k,T,P,R,U){const V=function(X,ie,ue,pe,be,Se,Le,ze){const We=Kq(0,0,1,0,1,1,0,1),ct=Kq(X,ie,ue,pe,be,Se,Le,ze);return f(ct,ct,p([],We))}(b,m,x,k,T,P,R,U);return[V[2]/V[8]/Bn,V[5]/V[8]/Bn]}function Yq(b){return[b[0],Math.min(Math.max(b[1],-85.051129),Ys)]}class XOe extends Lp{constructor(m,x,k,T){super(),this.id=m,this.dispatcher=k,this.coordinates=x.coordinates,this.type="image",this.minzoom=0,this.maxzoom=22,this.tileSize=512,this.tiles={},this._loaded=!1,this.onNorthPole=!1,this.onSouthPole=!1,this.setEventedParent(T),this.options=x,this._dirty=!1}load(m,x){if(this._loaded=x||!1,this.fire(new Lc("dataloading",{dataType:"source"})),this.url=this.options.url,!this.url)return m&&(this.coordinates=m),this._loaded=!0,void this._finishLoading();this._imageRequest=mx(this.map._requestManager.transformRequest(this.url,l0.Image),(k,T)=>{this._imageRequest=null,this._loaded=!0,k?this.fire(new Xm(k)):T&&(this.image=T,this._dirty=!0,this.width=this.image.width,this.height=this.image.height,m&&(this.coordinates=m),this._finishLoading())})}loaded(){return this._loaded}updateImage(m){return m.url?(this._imageRequest&&m.url!==this.options.url&&(this._imageRequest.cancel(),this._imageRequest=null),this.options.url=m.url,this.load(m.coordinates,this._loaded),this):this}setTexture(m){if(!(m.handle instanceof WebGLTexture))throw new Error("The provided handle is not a WebGLTexture instance");return this.texture=new hO(this.map.painter.context,m.handle),this.width=m.dimensions[0],this.height=m.dimensions[1],this._dirty=!1,this._loaded=!0,this._finishLoading(),this}_finishLoading(){this.map&&(this.setCoordinates(this.coordinates),this.fire(new Lc("data",{dataType:"source",sourceDataType:"metadata"})))}onAdd(m){this.map=m,this.load()}onRemove(m){this._imageRequest&&(this._imageRequest.cancel(),this._imageRequest=null),!this.texture||this.texture instanceof hO||this.texture.destroy(),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy())}setCoordinates(m){if(this.coordinates=m,this._boundsArray=void 0,this._unsupportedCoords=!1,!m.length)return this;this.onNorthPole=!1,this.onSouthPole=!1;let x=m[0][1],k=m[0][1];for(const P of m)P[1]>k&&(k=P[1]),P[1]Ys?this.onNorthPole=!0:T<-85.051129&&(this.onSouthPole=!0),!this.onNorthPole&&!this.onSouthPole){const P=m.map(ur.fromLngLat);this.tileID=function(R){let U=1/0,V=1/0,X=-1/0,ie=-1/0;for(const Le of R)U=Math.min(U,Le.x),V=Math.min(V,Le.y),X=Math.max(X,Le.x),ie=Math.max(ie,Le.y);const ue=Math.max(X-U,ie-V),pe=Math.max(0,Math.floor(-Math.log2(ue))),be=Math.pow(2,pe);let Se=Math.floor((U+X)/2*be);return Se>1&&(Se-=1),new UC(pe,Se,Math.floor((V+ie)/2*be))}(P),this.minzoom=this.maxzoom=this.tileID.z}return this.fire(new Lc("data",{dataType:"source",sourceDataType:"content"})),this}_clear(){!this.texture||this.texture instanceof hO||(this.texture.destroy(),this._dirty=!0),this.texture=null,this._boundsArray=void 0,this._unsupportedCoords=!1}_prepareData(m){for(const ze in this.tiles){const We=this.tiles[ze];We.state!=="loaded"&&(We.state="loaded",We.texture=this.texture)}if(this._boundsArray||this.onNorthPole||this.onSouthPole||this._unsupportedCoords)return;const x=YC(new UC(0,0,0),this.map.transform.projection),k=[x.projection.project(this.coordinates[0][0],this.coordinates[0][1]),x.projection.project(this.coordinates[1][0],this.coordinates[1][1]),x.projection.project(this.coordinates[2][0],this.coordinates[2][1]),x.projection.project(this.coordinates[3][0],this.coordinates[3][1])];if(!function(ze){const We=ze[1].x-ze[0].x,ct=ze[1].y-ze[0].y,nt=ze[2].x-ze[1].x,ft=ze[2].y-ze[1].y,wt=ze[3].x-ze[2].x,Nt=ze[3].y-ze[2].y,Wt=ze[0].x-ze[3].x,Ft=ze[0].y-ze[3].y,Gt=We*ft-nt*ct,Ut=nt*Nt-wt*ft,qt=wt*Ft-Wt*Nt,zs=Wt*ct-We*Ft;return Gt>0&&Ut>0&&qt>0&&zs>0||Gt<0&&Ut<0&&qt<0&&zs<0}(k))return console.warn("Image source coordinates are defining non-convex area in the Mercator projection"),void(this._unsupportedCoords=!0);const T=YC(this.tileID,this.map.transform.projection),[P,R,U,V]=this.coordinates.map(ze=>{const We=T.projection.project(ze[0],ze[1]);return OOe(T,We)._round()});this.perspectiveTransform=QOe(P.x,P.y,R.x,R.y,U.x,U.y,V.x,V.y);const X=this._boundsArray=new ni;X.emplaceBack(P.x,P.y,0,0),X.emplaceBack(R.x,R.y,Bn,0),X.emplaceBack(V.x,V.y,0,Bn),X.emplaceBack(U.x,U.y,Bn,Bn),this.boundsBuffer&&(this.boundsBuffer.destroy(),this.elevatedGlobeVertexBuffer&&this.elevatedGlobeVertexBuffer.destroy(),this.elevatedGlobeIndexBuffer&&this.elevatedGlobeIndexBuffer.destroy()),this.boundsBuffer=m.createVertexBuffer(X,Wq.members),this.boundsSegments=Po.simpleSegment(0,0,4,2);const ie=[],ue=function(ze){return[Yq(ze[0]),Yq(ze[1]),Yq(ze[2]),Yq(ze[3])]}(this.coordinates),[pe,be,Se,Le]=function(ze){let We=ze[0][0],ct=We,nt=ze[0][1],ft=nt;for(let wt=1;wtct&&(ct=ze[wt][0]),ze[wt][1]ft&&(ft=ze[wt][1]);return[We,nt,ct-We,ft-nt]}(ue);{const ze=new ni,[We,ct,nt,ft]=function(Js){let fn=Js[0].x,Os=fn,en=Js[0].y,on=en;for(let gn=1;gnOs&&(Os=Js[gn].x),Js[gn].yon&&(on=Js[gn].y);return[fn,en,Os-fn,on-en]}(k),wt=Js=>[(Js.x-We)/nt,(Js.y-ct)/ft],[Nt,Wt,Ft,Gt]=k.map(wt),Ut=function(Js,fn,Os,en,on,gn,Cn,ar){const Fn=Kq(0,0,1,0,1,1,0,1);return f(Fn,Fn,p([],Kq(Js,fn,Os,en,on,gn,Cn,ar)))}(Nt[0],Nt[1],Wt[0],Wt[1],Ft[0],Ft[1],Gt[0],Gt[1]);this.elevatedGlobePerspectiveTransform=QOe(Nt[0],Nt[1],Wt[0],Wt[1],Ft[0],Ft[1],Gt[0],Gt[1]);const qt=(Js,fn)=>{ie.push(Js.lng);const Os=Math.round((Js.lng-pe)/Se*Bn),en=Math.round((Js.lat-be)/Le*Bn),on=wt(fn),gn=ke([],[on[0],on[1],1],Ut),Cn=Math.round(gn[0]/gn[2]*Bn),ar=Math.round(gn[1]/gn[2]*Bn);ze.emplaceBack(Os,en,Cn,ar)},zs=k[3].x-k[0].x,qs=k[3].y-k[0].y,Xs=k[2].x-k[1].x,sn=k[2].y-k[1].y;for(let Js=0;Js<65;Js++){const fn=Js/64,Os=[k[0].x+fn*zs,k[0].y+fn*qs],en=[k[1].x+fn*Xs,k[1].y+fn*sn],on=en[0]-Os[0],gn=en[1]-Os[1];for(let Cn=0;Cn<65;Cn++){const ar=Cn/64,Fn={x:Os[0]+on*ar,y:Os[1]+gn*ar};qt(x.projection.unproject(Fn.x,Fn.y),Fn)}}this.elevatedGlobeVertexBuffer=m.createVertexBuffer(ze,Wq.members)}{this.maxLongitudeTriangleSize=0;let ze=[],We=new tc;const ct=(nt,ft,wt)=>{We.emplaceBack(nt,ft,wt);const Nt=ie[nt],Wt=ie[ft],Ft=ie[wt],Gt=Math.min(Math.min(Nt,Wt),Ft),Ut=Math.max(Math.max(Nt,Wt),Ft)-Gt;Ut>this.maxLongitudeTriangleSize&&(this.maxLongitudeTriangleSize=Ut),ze.push(Gt+Ut/2)};for(let nt=0;nt<64;nt++)for(let ft=0;ft<64;ft++){const wt=65*nt+ft,Nt=wt+1,Wt=wt+65,Ft=Wt+1;ct(wt,Wt,Nt),ct(Nt,Wt,Ft)}[ze,We]=function(nt,ft){const wt=Array.from({length:nt.length},(Ft,Gt)=>Gt);wt.sort((Ft,Gt)=>nt[Ft]-nt[Gt]);const Nt=[],Wt=new tc;for(let Ft=0;Ft{R.segments.push({vertexOffset:0,primitiveOffset:ue,vertexLength:x.segments[0].vertexLength,primitiveLength:pe,sortKey:void 0,vaos:{}})},V=.51*this.maxLongitudeTriangleSize;if(Math.abs(k[0]-T)<=V){const ue=Vi(k,0,k.length,T+V);return ue===k.length||U(ue,qi(k,ue+1,k.length,T+360-V)-ue),R}T0}}let eFe,tFe,sFe,nFe,rFe,aFe,iFe;class oFe extends lo{constructor(m,x,k,T){super(m,{layout:eFe||(eFe=new qo({visibility:new wn(ps["layout_raster-particle"].visibility)})),paint:tFe||(tFe=new qo({"raster-particle-array-band":new wn(ps["paint_raster-particle"]["raster-particle-array-band"]),"raster-particle-count":new wn(ps["paint_raster-particle"]["raster-particle-count"]),"raster-particle-color":new Vp(ps["paint_raster-particle"]["raster-particle-color"]),"raster-particle-max-speed":new wn(ps["paint_raster-particle"]["raster-particle-max-speed"]),"raster-particle-speed-factor":new wn(ps["paint_raster-particle"]["raster-particle-speed-factor"]),"raster-particle-fade-opacity-factor":new wn(ps["paint_raster-particle"]["raster-particle-fade-opacity-factor"]),"raster-particle-reset-rate-factor":new wn(ps["paint_raster-particle"]["raster-particle-reset-rate-factor"]),"raster-particle-elevation":new wn(ps["paint_raster-particle"]["raster-particle-elevation"]),"raster-particle-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"})}))},x,k,T),this._updateColorRamp(),this.lastInvalidatedAt=$d.now()}_clear(){this.colorRampTexture&&(this.colorRampTexture.destroy(),this.colorRampTexture=null),this.tileFramebuffer&&(this.tileFramebuffer.destroy(),this.tileFramebuffer=null),this.particleFramebuffer&&(this.particleFramebuffer.destroy(),this.particleFramebuffer=null)}onRemove(m){this.colorRampTexture&&this.colorRampTexture.destroy(),this.tileFramebuffer&&this.tileFramebuffer.destroy(),this.particleFramebuffer&&this.particleFramebuffer.destroy()}hasColorMap(){return!!this._transitionablePaint._values["raster-particle-color"].value.value}getProgramIds(){return["rasterParticle"]}hasOffscreenPass(){return this.visibility!=="none"}isDraped(m){return!1}_handleSpecialPaintPropertyUpdate(m){m!=="raster-particle-color"&&m!=="raster-particle-max-speed"||(this._updateColorRamp(),this._invalidateAnimationState()),m==="raster-particle-count"&&this._invalidateAnimationState()}_updateColorRamp(){if(!this.hasColorMap())return;const m=this._transitionablePaint._values["raster-particle-color"].value.expression,x=this._transitionablePaint._values["raster-particle-max-speed"].value.expression.evaluate({zoom:0});this.colorRamp=QR({expression:m,evaluationKey:"rasterParticleSpeed",image:this.colorRamp,clips:[{start:0,end:x}],resolution:256}),this.colorRampTexture=null}_invalidateAnimationState(){this.lastInvalidatedAt=$d.now()}tileCoverLift(){return this.paint.get("raster-particle-elevation")}}class R3t extends lo{constructor(m,x){super(m,{},x,null),this.implementation=m,m.slot&&(this.slot=m.slot)}is3D(m){return this.implementation.renderingMode==="3d"}hasOffscreenPass(){return this.implementation.prerender!==void 0}isDraped(m){return this.implementation.renderToTile!==void 0}shouldRedrape(){return!!this.implementation.shouldRerenderTiles&&this.implementation.shouldRerenderTiles()}recalculate(){}updateTransitions(){}hasTransition(){return!1}serialize(){}onAdd(m){this.implementation.onAdd&&this.implementation.onAdd(m,m.painter.context.gl)}onRemove(m){this.implementation.onRemove&&this.implementation.onRemove(m,m.painter.context.gl)}}function k_e(b,m,x){const k=[0,0,1],T=bt([]);return Yt(T,T,x?-Ts(b)+Math.PI:Ts(b)),$t(T,T,-Ts(m)),it(k,k,T),Re(k,k)}class Zq{constructor(m,x,k,T){this.message=(m?`${m}: `:"")+k,T&&(this.identifier=T),x!=null&&x.__line__&&(this.line=x.__line__)}}function S_e(b,m){const x=b.indexOf("://")===-1;try{return new URL(b,x&&m?"http://example.com":void 0),!0}catch{return!1}}class lFe{constructor(m,x){this.feature=m,this.instancedDataOffset=x,this.instancedDataCount=0,this.rotation=[0,0,0],this.scale=[1,1,1],this.translation=[0,0,0]}}class cFe{constructor(){this.maxScale=1,this.maxXYTranslationDistance=0,this.instancedDataArray=new UR,this.instancesEvaluatedElevation=[],this.features=[],this.idToFeaturesIndex={}}colorForInstance(m){const x=16*m,k=this.instancedDataArray.float32;let T=Math.floor(k[x+2]);const P=1.05*(k[x+2]-T);return T/=100,[k[x]%1*1.05,k[x+1]%1*1.05,P,T]}tileCoordinatesForInstance(m){const x=16*m,k=this.instancedDataArray.float32;let T=k[x+0];return T=T>Bn?T-Bn:T,new Es(Math.trunc(T),Math.trunc(k[x+1]))}translationForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+4],k[x+5],k[x+6]]}rotationScaleForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+7],k[x+8],k[x+9],k[x+10],k[x+11],k[x+12],k[x+13],k[x+14],k[x+15]]}transformForInstance(m){const x=16*m,k=this.instancedDataArray.float32;return[k[x+7],k[x+8],k[x+9],k[x+4],k[x+10],k[x+11],k[x+12],k[x+5],k[x+13],k[x+14],k[x+15],k[x+6],0,0,0,1]}}class C_e{constructor(m){this.zoom=m.zoom,this.canonical=m.canonical,this.overscaledZ=this.canonical.z+Math.log2(m.overscaling),this.layers=m.layers,this.layerIds=this.layers.map(x=>x.fqid),this.projection=m.projection,this.index=m.index,this.worldview=m.worldview,this.hasZoomDependentProperties=this.layers[0].isZoomDependent(),this.stateDependentLayerIds=this.layers.filter(x=>x.isStateDependent()).map(x=>x.id),this.hasPattern=!1,this.instancesPerModel={},this.validForExaggeration=0,this.maxVerticalOffset=0,this.maxScale=0,this.maxHeight=0,this.lookupDim=this.zoom>this.canonical.z+1?0:this.zoom>this.canonical.z?256:this.zoom>15?75:100,this.instanceCount=0,this.terrainElevationMin=0,this.terrainElevationMax=0,this.validForDEMTile={id:null,timestamp:0},this.modelUris=[],this.modelsRequested=!1,this.activeReplacements=[],this.replacementUpdateTime=0,this.styleDefinedModelURLs=m.styleDefinedModelURLs,this.hasAppearances=null}updateFootprints(m,x){}updateAppearances(m,x,k,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}populate(m,x,k,T){this.tileToMeter=cn(k);const P=this.layers[0]._featureFilter.needGeometry;this.lookup=new Uint8Array(this.lookupDim*this.lookupDim);const R=this.layers[0].paint.get("model-elevation-reference")==="hd-road-markup"?x.elevationFeatures:void 0;for(const{feature:U,id:V,index:X,sourceLayerIndex:ie}of m){const ue=V??(U.properties&&U.properties.hasOwnProperty("id")?U.properties.id:void 0),pe=Ha(U,P);if(!this.layers[0]._featureFilter.filter(new Aa(this.zoom,{worldview:this.worldview,activeFloors:x.activeFloors}),pe,k))continue;const be={id:ue,sourceLayerIndex:ie,index:X,geometry:P?pe.geometry:Vr(U,k,T),properties:U.properties,type:U.type,patterns:{}},Se=this.addFeature(be,be.geometry,pe,R,k);Se&&x.featureIndex.insert(U,be.geometry,X,ie,this.index,this.instancesPerModel[Se].instancedDataArray.length,256)}this.lookup=null}evaluateQueryRenderedFeaturePadding(){const m=this.layers[0].modelManager,x=this.layers[0].scope;let k=0;for(const T of this.modelUris){const P=m.getModel(T,x);if(!P)continue;const R=this.instancesPerModel[T];if(R){const U=.5*Ie(P.aabb.max,P.aabb.min)*R.maxScale+R.maxXYTranslationDistance,V=Math.min(Bn,Math.max(U/this.tileToMeter,256));k=Math.max(V,k)}}return k}update(m,x,k,T){for(const P in this.instancesPerModel){const R=this.instancesPerModel[P];for(const U in m)R.idToFeaturesIndex.hasOwnProperty(U)&&(this.evaluate(R.features[R.idToFeaturesIndex[U]],m[U],R,!0),this.uploaded=!1)}this.maxHeight=0}updateZoomBasedPaintProperties(){if(!this.hasZoomDependentProperties)return!1;let m=!1;for(const x in this.instancesPerModel){const k=this.instancesPerModel[x];for(const T of k.features){const P=this.layers[0],R=T.feature,U=this.canonical,V=P.paint.get("model-rotation").evaluate(R,{},U),X=P.paint.get("model-scale").evaluate(R,{},U),ie=P.paint.get("model-translation").evaluate(R,{},U);He(T.rotation,V)&&He(T.scale,X)&&He(T.translation,ie)||(this.evaluate(T,T.featureStates,k,!0),m=!0)}}return m}updateReplacement(m,x,k,T){if(x.updateTime===this.replacementUpdateTime)return!1;this.replacementUpdateTime=x.updateTime;const P=x.getReplacementRegionsForTile(m.toUnwrapped(),!0);if(fq(this.activeReplacements,P))return!1;this.activeReplacements=P;let R=!1;for(const U in this.instancesPerModel){const V=this.instancesPerModel[U],X=V.instancedDataArray;for(const ie of V.features){const ue=ie.instancedDataOffset,pe=ie.instancedDataCount;for(let be=0;beBn;Le=ze?Le-Bn:Le;const We=Math.floor(Le),ct=Math.floor(X.float32[Se+1]);let nt=!1;for(const ft of this.activeReplacements)if(!VDe(ft,k,xq.Model,T)&&!(ft.min.x>We||We>ft.max.x||ft.min.y>ct||ct>ft.max.y)&&(nt=YDe(KDe(We,ct,m.canonical,ft.footprintTileId.canonical),ft.footprint),nt))break;X.float32[Se]=nt?Le+Bn:Le,R=R||nt!==ze}}}return R}isEmpty(){for(const m in this.instancesPerModel)if(this.instancesPerModel[m].instancedDataArray.length!==0)return!1;return!0}uploadPending(){return!this.uploaded}upload(m){if(!this.uploaded)for(const x in this.instancesPerModel){const k=this.instancesPerModel[x];k.instancedDataArray.length<0||k.instancedDataArray.length===0||(k.instancedDataBuffer?k.instancedDataBuffer.updateData(k.instancedDataArray):k.instancedDataBuffer=m.createVertexBuffer(k.instancedDataArray,tCt.members,!0,void 0,this.instanceCount))}this.uploaded=!0}destroy(m){for(const k in this.instancesPerModel){const T=this.instancesPerModel[k];T.instancedDataArray.length!==0&&T.instancedDataBuffer&&T.instancedDataBuffer.destroy()}const x=this.layers[0].modelManager;if(m&&x&&this.modelUris&&this.modelsRequested)for(const k of this.modelUris)x.removeModel(k,"",!0)}addFeature(m,x,k,T,P){const R=this.layers[0],U=R.layout.get("model-id"),V=R.layout.get("model-allow-density-reduction"),X=U.evaluate(k,{},this.canonical);if(!X)return Yn(`modelId is not evaluated for layer ${R.id} and it is not going to get rendered.`),X;(S_e(X,!1)||this.styleDefinedModelURLs[X]!==void 0)&&(this.modelUris.includes(X)||this.modelUris.push(X)),this.instancesPerModel[X]||(this.instancesPerModel[X]=new cFe);const ie=this.instancesPerModel[X],ue=ie.instancedDataArray,pe=new lFe(k,ue.length);let be;T&&(be=zo.getElevationFeature(m,T));for(const Se of x)for(const Le of Se){if(Le.x<0||Le.x>=Bn||Le.y<0||Le.y>=Bn)continue;if(this.lookupDim!==0&&V){const We=(this.lookupDim-1)/Bn,ct=this.lookupDim*(Le.y*We|0)+Le.x*We|0;if(this.lookup){if(this.lookup[ct]!==0)continue;this.lookup[ct]=1}}this.instanceCount++;const ze=ue.length;if(ue.resize(ze+1),T){ie.instancesRoadElevation||(ie.instancesRoadElevation=[]);const We=be?be.pointElevation(new Es(Le.x,Le.y)):0;ie.instancesRoadElevation.push(We)}ie.instancesEvaluatedElevation.push(0),ue.float32[16*ze]=Le.x,ue.float32[16*ze+1]=Le.y}return pe.instancedDataCount=ie.instancedDataArray.length-pe.instancedDataOffset,pe.instancedDataCount>0&&(m.id&&(ie.idToFeaturesIndex[m.id]=ie.features.length),ie.features.push(pe),this.evaluate(pe,{},ie,!1)),X}getModelUris(){return this.modelUris}evaluate(m,x,k,T){const P=this.layers[0],R=m.feature,U=this.canonical,V=m.rotation=P.paint.get("model-rotation").evaluate(R,x,U),X=m.scale=P.paint.get("model-scale").evaluate(R,x,U),ie=m.translation=P.paint.get("model-translation").evaluate(R,x,U),ue=Object.assign({},P.paint.get("model-color").evaluate(R,x,U));ue.a=P.paint.get("model-color-mix-intensity").evaluate(R,x,U);const pe=[];this.maxVerticalOffset0?Math.sqrt(be):0;k.maxScale=Math.max(Math.max(k.maxScale,X[0]),Math.max(X[1],X[2])),k.maxXYTranslationDistance=Math.max(k.maxXYTranslationDistance,Se),this.maxScale=Math.max(Math.max(this.maxScale,X[0]),Math.max(X[1],X[2])),PRe(pe,V,X);const Le=Math.round(100*ue.a)+ue.b/1.05;for(let ze=0;ze10?this.tileToMeter:cn(U,wt)),nt[ct+4]=ie[0],nt[ct+5]=ie[1],nt[ct+6]=ie[2]+(k.instancesRoadElevation?k.instancesRoadElevation[We]:0)+ft,nt[ct+7]=pe[0],nt[ct+8]=pe[1],nt[ct+9]=pe[2],nt[ct+10]=pe[4],nt[ct+11]=pe[5],nt[ct+12]=pe[6],nt[ct+13]=pe[8],nt[ct+14]=pe[9],nt[ct+15]=pe[10],k.instancesEvaluatedElevation[We]=ie[2]}}}Kn(C_e,"ModelBucket",{omit:["layers"]}),Kn(cFe,"PerModelAttributes"),Kn(lFe,"ModelFeature");class K6{constructor(m,x,k){this._demTile=m,this._dem=this._demTile.dem,this._scale=x,this._offset=k}static create(m,x,k){const T=k||m.findDEMTileFor(x);if(!T||!T.dem)return;const P=T.dem,R=T.tileID,U=1<X.fqid),this.stateDependentLayerIds=this.layers.filter(X=>X.isStateDependent()).map(X=>X.id),this.modelTraits|=B6.CoordinateSpaceTile,this.uploaded=!1,this.hasPattern=!1,T&&(this.modelTraits|=B6.HasMapboxMeshFeatures),P&&(this.modelTraits|=B6.HasMeshoptCompression),this.zoom=-1,this.terrainExaggeration=1,this.projection={name:"mercator"},this.replacementUpdateTime=0,this.elevationReadFromZ=255,this.brightness=R,this.worldview=V,this.dirty=!0,this.needsUpload=!1,this.filter=null,this.nodesInfo=[];for(const X of x)this.nodesInfo.push(new mFe(X)),uFe(X,U.featureIndexArray.length,U.grid),U.featureIndexArray.emplaceBack(this.nodesInfo.length-1,0,U.bucketLayerIDs.length-1,0);this.states={},this.hasAppearances=null}updateFootprints(m,x){for(const k of this.getNodesInfo()){const T=k.node;T.footprint&&x.push({footprint:T.footprint,id:m})}}updateAppearances(m,x,k,T){return{hasLayoutChanges:!1,hasUboChanges:!1}}update(m){const x=Object.keys(m).length!==0;if(x&&!this.stateDependentLayers.length)return;const k=x?this.stateDependentLayers:this.layers;if(!mi(m,this.states))for(const T of k)this.evaluate(T,m);this.states=structuredClone(m)}populate(){console.log("populate 3D model bucket")}uploadPending(){return!this.uploaded||this.needsUpload}upload(m){if(!this.needsUpload)return;const x=this.getNodesInfo();for(const k of x){const T=k.node;this.uploaded?this.updatePbrBuffer(T):Hbe(T,m,!0)}for(const k of x)Eq(k.node);this.uploaded=!0,this.needsUpload=!1}updatePbrBuffer(m){let x=!1;if(!m.meshes)return x;for(const k of m.meshes)k.pbrBuffer&&(k.pbrBuffer.updateData(k.featureArray),x=!0);return x}needsReEvaluation(m,x,k){const T=m.transform.projectionOptions,P=m.style.getBrightness(),R=this.brightness!==P;if(!this.uploaded||this.dirty||T.name!==this.projection.name||TO(k.paint.get("model-color").value,R)||TO(k.paint.get("model-color-mix-intensity").value,R)||TO(k.paint.get("model-roughness").value,R)||TO(k.paint.get("model-emissive-strength").value,R)||TO(k.paint.get("model-height-based-emissive-strength-multiplier").value,R)){this.projection=T,this.brightness=P;const U=this.getNodesInfo();for(const V of U)V.state=null;return!0}return!1}evaluateTransform(m,x){if(m.transform.zoom===this.zoom)return;this.zoom=m.transform.zoom;const k=this.getNodesInfo(),T=this.id.canonical;for(const P of k){const R=P.feature;P.evaluatedTranslation=x.paint.get("model-translation").evaluate(R,{},T),P.evaluatedScale=x.paint.get("model-scale").evaluate(R,{},T)}}evaluate(m,x){const k=this.getNodesInfo();for(const T of k){if(!T.node.meshes)continue;const P=T.feature,R=x&&x[P.id];if(mi(R,T.state))continue;T.state=structuredClone(R);const U=T.node.meshes&&T.node.meshes[0].featureData,V=T.evaluatedColor[2],X=T.evaluatedRMEA[2],ie=this.id.canonical;if(T.hasTranslucentParts=!1,U){for(let ue=0;ue=Nt)continue;const fn=T_e[Js],Os=Math.abs(fn);Os>qt&&(Ut=fn,qt=Os,zs=sn,qs=Xs)}if(qt>.1){const Xs=1-(Nt+.5*Math.abs(zs*qs))/Se;let sn=x._dem.get(Ft,Wt)+Ut*Xs;const Js=x._dem.get(Ft+zs,Wt+qs),fn=x._dem.get(Ft-zs,Wt-qs,!0);(sn-Js)*(sn-fn)>0&&(sn=(Js+fn)/2),T_e[Gt]=x._dem.set(Ft,Wt,sn),ZC[Gt]=Nt}}}}}U&&(x._demTile.needsDEMTextureUpload=!0,x._dem._timestamp=$d.now())}setFilter(m){this.filter=m?JN(m):null}getNodesInfo(){return this.filter?this.nodesInfo.filter(m=>this.filter.filter(new Aa(this.id.overscaledZ,{worldview:this.worldview}),m.feature,this.id.canonical)):this.nodesInfo}destroy(){const m=this.getNodesInfo();for(const x of m)Eq(x.node),Gbe(x.node)}isEmpty(){return!this.nodesInfo.length}updateReplacement(m,x){if(x.updateTime===this.replacementUpdateTime)return;this.replacementUpdateTime=x.updateTime;const k=x.getReplacementRegionsForTile(m.toUnwrapped());for(const T of this.getNodesInfo()){const P=T.node.footprint;T.hiddenByReplacement=!!P&&!k.find(R=>R.footprint===P)}}getHeightAtTileCoord(m,x){const k=[],T=[0,0,0],P=v([]);for(const R of this.getNodesInfo()){const U=R.node.meshes[0],V=U.transformedAabb;if(mV.max[0]||x>V.max[1])continue;if(R.node.hidden===!0)return{height:1/0,maxHeight:R.feature.properties.height,hidden:!1,verticalScale:R.evaluatedScale[2]};j(P,R.node.globalMatrix),T[0]=m,T[1]=x,Je(T,T,P);const X=(T[0]-U.aabb.min[0])/(U.aabb.max[0]-U.aabb.min[0])*HC|0,ie=Math.min(63,(T[1]-U.aabb.min[1])/(U.aabb.max[1]-U.aabb.min[1])*HC|0)*HC+Math.min(63,X),ue=U.heightmap[ie];if(!(ue<0&&R.node.footprint))return R.hiddenByReplacement?void 0:{height:ue,maxHeight:R.feature.properties.height,hidden:!1,verticalScale:R.evaluatedScale[2]};if(R.node.footprint.grid.query(new Es(m,x),new Es(m,x),k),k.length>0)return{height:void 0,maxHeight:R.feature.properties.height,hidden:R.hiddenByReplacement,verticalScale:R.evaluatedScale[2]}}}}function TO(b,m){return b instanceof x0&&!b.isLightConstant&&m}function O3t(b,m,x,k,T,P,R,U){let V=(61440&m|(61440&m)>>4)>>8,X=(3840&m|(3840&m)>>4)>>4,ie=240&m|(240&m)>>4;x[3]>0&&(V=Dr(V,255*x[0],x[3]),X=Dr(X,255*x[1],x[3]),ie=Dr(ie,255*x[2],x[3]));const ue=V<<8|X,pe=ie<<8|Math.floor(255*k[3]),be=function(Nt){const Wt=Qe(Nt,0,2);return Math.min(Math.round(.5*Wt*255),255)}(k[2])<<8|15*k[0]<<4|15*k[1],Se=Qe(T[0],0,1),Le=Qe(T[1],0,1),ze=Qe(T[2],0,1),We=Qe(T[3],0,1);let ct,nt,ft,wt;if(Se!==Le&&R!==P&&Le!==Se){const Nt=R-P;nt=1/(Nt*(Le-Se)),ft=-(P+Nt*Se)/(Nt*(Le-Se));const Wt=Qe(T[4],-1,1);wt=Math.pow(10,Wt),ct=255*ze<<8|255*We}else ct=65535,nt=0,ft=1,wt=1;if(b.emplaceBack(ue,pe,be,ct,nt,ft,wt),U){const Nt=U.length;U.clear();for(let Wt=0;Wt>16&65535,ie=P?V>>16&65535:65535&V,ue=(15&ie)<8?15&ie:0,pe=b.evaluatedRMEA[ue],be=b.evaluatedColor[ue],Se=b.emissionHeightBasedParams[ue];let Le;if(U&&ue===2&&k.lights&&(Le=new T6,Le.resize(10*k.lights.length)),O3t(R.featureArray,X,be,pe,Se,R.aabb.min[2],R.aabb.max[2],Le),Le&&U){U=!1;const ze=k.meshes[k.lightMeshIndex];ze.featureArray=Le,ze.featureArray._trim()}}R.featureArray._trim(),T++}}Kn(Qq,"Tiled3dModelBucket",{omit:["layers"]}),Kn(mFe,"Tiled3dModelFeature");const z3t=["id","tile","layer","source","sourceLayer","state"];class QC{constructor(m,x,k,T,P){this.type="Feature",this._vectorTileFeature=m,this._z=x,this._x=k,this._y=T,this.properties=m?m.properties:{},this.id=P}clone(){const m=new QC(this._vectorTileFeature,this._z,this._x,this._y,this.id);return this.state&&(m.state=Object.assign({},this.state)),this.layer&&(m.layer=Object.assign({},this.layer)),this.source&&(m.source=this.source),this.sourceLayer&&(m.sourceLayer=this.sourceLayer),m}get geometry(){return this._geometry===void 0&&this._vectorTileFeature&&(this._geometry=this._vectorTileFeature.toGeoJSON(this._x,this._y,this._z).geometry),this._geometry}set geometry(m){this._geometry=m}toJSON(){const m={type:"Feature",state:void 0,geometry:this.geometry,properties:this.properties};for(const x of z3t)this[x]!==void 0&&(m[x]=this[x]);return m}}class XC extends Lp{constructor(m,x,k,T){super(),this.id=m,this.type="model",this.models=[],this._options=x,this._modelsInfo=new Map,this._abortController=null}cancelModelRequests(){this._abortController&&(this._abortController.abort(),this._abortController=null)}loadGLTFFromURI(m,x){return ERe(this.map._requestManager.transformRequest(m,l0.Model).url,x)}async loadModel(m,x,k){try{const T=await this.loadGLTFFromURI(x.uri,k);if(k.aborted)return;const P=this._modelsInfo.get(m);if(!P)return;const R=Kbe(T),U=P.modelSpec,V=new LRe(m,U.uri,U.position,U.orientation,R);XC.applyModelSpecification(V,U),V.computeBoundsAndApplyParent(),this.models.push(V),P.model=V}catch(T){if(T instanceof Error&&T.name==="AbortError")return;const P=T instanceof Error?T.message:"Unknown error";this.fire(new Xm(new Error(`Could not load model ${m} from ${x.uri}: ${P}`)))}}async load(){this._abortController||(this._abortController=new AbortController);const m=this._abortController.signal,x=[];for(const k in this._options.models){const T=this._options.models[k],P=this._modelsInfo.get(k);if(P&&P.model){P.modelSpec=T;const R=P.model;R.position=T.position!=null?new ss(T.position[0],T.position[1]):new ss(0,0),R.orientation=T.orientation!=null?T.orientation:[0,0,0],XC.applyModelSpecification(R,T),R.computeBoundsAndApplyParent(),this.models.push(R)}else P?P.modelSpec=T:(this._modelsInfo.set(k,{modelSpec:T,model:null}),x.push(this.loadModel(k,T,m)))}x.length!==0?(await Promise.allSettled(x),m.aborted||this.fire(new Lc("data",{dataType:"source",sourceDataType:"metadata"}))):this.loaded()&&this.fire(new Lc("data",{dataType:"source",sourceDataType:"metadata"}))}static applyModelSpecification(m,x){x.nodeOverrides&&XC.convertNodeOverrides(m,x.nodeOverrides),x.materialOverrides&&XC.convertMaterialOverrides(m,x.materialOverrides),x.nodeOverrideNames&&(m.nodeOverrideNames=[...x.nodeOverrideNames]),x.materialOverrideNames&&(m.materialOverrideNames=[...x.materialOverrideNames]),x.featureProperties&&(m.featureProperties=x.featureProperties)}static convertNodeOverrides(m,x){if(Array.isArray(x)&&x.every(k=>typeof k=="string")){m.nodeOverrideNames=[];for(const k of x)m.nodeOverrideNames.push(k)}else Object.entries(x).forEach(([k,T])=>{const P={orientation:[0,0,0]};if(T.hasOwnProperty("orientation")){const R=T.orientation;R&&(P.orientation=R)}m.nodeOverrides.set(k,P)})}static convertMaterialOverrides(m,x){if(Array.isArray(x)&&x.every(k=>typeof k=="string")){m.materialOverrideNames=[];for(const k of x)m.materialOverrideNames.push(k)}else Object.entries(x).forEach(([k,T])=>{const P={color:new Gn(1,1,1),colorMix:0,emissionStrength:0,opacity:1},R=T["model-color"];R!==void 0&&(P.color.r=R[0],P.color.g=R[1],P.color.b=R[2]);const U=T["model-color-mix-intensity"];U!==void 0&&(P.colorMix=U);const V=T["model-emissive-strength"];V!==void 0&&(P.emissionStrength=V);const X=T["model-opacity"];X!==void 0&&(P.opacity=X),m.materialOverrides.set(k,P)})}onAdd(m){this.map=m,this.load()}hasTransition(){return!1}loaded(){if(this._modelsInfo.size===0)return!0;for(const m of this._modelsInfo.values())if(m.model==null)return!1;return!0}getModels(){return this.models}loadTile(m,x){}serialize(){return this._options}setProperty(m,x){return!1}reload(){this.cancelModelRequests();const m=vt(this.id,this.scope);this.map.style.clearSource(m),this.models=[],this._modelsInfo.clear(),this.load()}onRemove(m){this.cancelModelRequests()}setModels(m){this.models=[];const x=new Map;for(const k in m){const T=m[k],P=this._modelsInfo.get(k);P&&P.modelSpec.uri===T.uri&&x.set(k,P)}if(this._modelsInfo.size!==x.size){this.cancelModelRequests();for(const[k,T]of x)T.model||x.delete(k)}this._modelsInfo=x,this._options.models=m,this.load()}}function E_e(b,m,x,k){const T=1<V>=wt.vertexArrayOffset&&Vft.polygon).flat());const ze=be?U:null,[We,ct]=pRe(P,k,ue,ie,X,R,ze,pe,Se,P.center.lat,b.tileID.canonical),nt=b.queryGeometry;return mRe(We,ct,nt.isPointQuery()?nt.screenBounds:nt.screenGeometry)}},building:class extends lo{constructor(b,m,x,k){super(b,{layout:$Re||($Re=new qo({visibility:new wn(ps.layout_building.visibility),"building-facade":new bn(ps.layout_building["building-facade"]),"building-facade-floors":new bn(ps.layout_building["building-facade-floors"]),"building-facade-unit-width":new bn(ps.layout_building["building-facade-unit-width"]),"building-facade-window":new bn(ps.layout_building["building-facade-window"]),"building-roof-shape":new bn(ps.layout_building["building-roof-shape"]),"building-height":new bn(ps.layout_building["building-height"]),"building-base":new bn(ps.layout_building["building-base"]),"building-flood-light-wall-radius":new bn(ps.layout_building["building-flood-light-wall-radius"]),"building-flood-light-ground-radius":new bn(ps.layout_building["building-flood-light-ground-radius"]),"building-flip-roof-orientation":new bn(ps.layout_building["building-flip-roof-orientation"])})),paint:URe||(URe=new qo({"building-opacity":new wn(ps.paint_building["building-opacity"]),"building-ambient-occlusion-intensity":new wn(ps.paint_building["building-ambient-occlusion-intensity"]),"building-ambient-occlusion-ground-intensity":new wn(ps.paint_building["building-ambient-occlusion-ground-intensity"]),"building-ambient-occlusion-ground-radius":new wn(ps.paint_building["building-ambient-occlusion-ground-radius"]),"building-ambient-occlusion-ground-attenuation":new wn(ps.paint_building["building-ambient-occlusion-ground-attenuation"]),"building-vertical-scale":new wn(ps.paint_building["building-vertical-scale"]),"building-cast-shadows":new wn(ps.paint_building["building-cast-shadows"]),"building-color":new bn(ps.paint_building["building-color"]),"building-emissive-strength":new bn(ps.paint_building["building-emissive-strength"]),"building-facade-emissive-chance":new wn(ps.paint_building["building-facade-emissive-chance"]),"building-cutoff-fade-range":new wn(ps.paint_building["building-cutoff-fade-range"]),"building-front-cutoff":new wn(ps.paint_building["building-front-cutoff"]),"building-flood-light-color":new wn(ps.paint_building["building-flood-light-color"]),"building-flood-light-intensity":new wn(ps.paint_building["building-flood-light-intensity"]),"building-flood-light-ground-attenuation":new wn(ps.paint_building["building-flood-light-ground-attenuation"]),"building-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"}),"building-flood-light-color-use-theme":new bn({type:"string",default:"default","property-type":"data-driven"})}))},m,x,k),this._stats={numRenderedVerticesInShadowPass:0,numRenderedVerticesInTransparentPass:0}}createBucket(b){return new BRe(b)}cutoffRange(){return this.paint.get("building-cutoff-fade-range")}hasShadowPass(){return this.paint.get("building-cast-shadows")}hasLightBeamPass(){return!0}canCastShadows(){return!0}is3D(b){return!0}queryRadius(b){return 0}queryIntersectsFeature(b,m,x,k,T,P,R,U,V,X){let ie=this.layout.get("building-height").evaluate(m,x);const ue=this.layout.get("building-base").evaluate(m,x),pe=b.tile.getBucket(this).getFootprint(m);if(pe){if(pe.hiddenFlags!==0)return!1;ie=pe.height}const[be,Se]=pRe(P,k,ue,ie,new Es(0,0),R,null,[0,0],1,P.center.lat,b.tileID.canonical),Le=b.queryGeometry;return mRe(be,Se,Le.isPointQuery()?Le.screenBounds:Le.screenGeometry)}},line:class extends lo{constructor(b,m,x,k){const T=XRe();super(b,T,m,x,k),T.layout&&(this.layout=new Gd(T.layout)),this.gradientVersion=0,this.hasElevatedBuckets=!1,this.hasNonElevatedBuckets=!1}_handleSpecialPaintPropertyUpdate(b){if(b==="line-gradient"){const m=this._transitionablePaint._values["line-gradient"].value.expression;this.stepInterpolant=m._styleExpression&&m._styleExpression.expression instanceof _j,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(b,m){super.recalculate(b,m),this.paint._values["line-floorwidth"]=(()=>{if(pO)return pO;const x=XRe();return pO=new PCt(x.paint.properties["line-width"].specification),pO.useIntegerZoom=!0,pO})().possiblyEvaluate(this._transitioningPaint._values["line-width"].value,b)}createBucket(b){return new Mq(b)}getProgramIds(){const b=[this.paint.get("line-pattern").constantOr(1)?"linePattern":"line"];return this.paint.get("line-blend-mode")!=="default"&&b.push("lineBlendComposite"),b}getDefaultProgramParams(b,m,x){if(b==="lineBlendComposite")return{};const k=ZRe(this);return{config:new De(this,{zoom:m,lut:x}),defines:k,overrideFog:!1}}queryRadius(b){const m=b,x=JRe(ak("line-width",this,m),ak("line-gap-width",this,m)),k=ak("line-offset",this,m);return x/2+Math.abs(k)+tq(this.paint.get("line-translate"))}queryIntersectsFeature(b,m,x,k,T,P){if(b.queryGeometry.isAboveHorizon)return!1;const R=Q8e(b.tilespaceGeometry,this.paint.get("line-translate"),this.paint.get("line-translate-anchor"),P.angle,b.pixelToTileUnitsFactor),U=b.pixelToTileUnitsFactor/2*JRe(this.paint.get("line-width").evaluate(m,x),this.paint.get("line-gap-width").evaluate(m,x)),V=this.paint.get("line-offset").evaluate(m,x);return V&&(k=function(X,ie){const ue=[],pe=new Es(0,0);for(let be=0;be=3){for(let Se=0;Se{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 pFe{constructor(m){this._stringToNumber={},this._numberToString=[];for(let x=0;x=0&&pe[3]>=0&&X.insert(V,pe[0],pe[1],pe[2],pe[3])}}loadVTLayers(){if(!this.vtLayers){this.vtLayers=new Fi(new Iq(this.rawTileData)).layers,this.sourceLayerCoder=new pFe(this.vtLayers?Object.keys(this.vtLayers).sort():["_geojsonTileLayer"]),this.vtFeatures={};for(const m in this.vtLayers)this.vtFeatures[m]=[]}return this.vtLayers}query(m,x){const{tilespaceGeometry:k,transform:T,tileTransform:P,pixelPosMatrix:R,availableImages:U,worldview:V}=x;this.loadVTLayers(),this.serializedLayersCache.clear();const X=x.queryRadius?x.queryRadius:0,ie=k.bufferedTilespaceBounds,ue=this.grid.query(ie.min.x,ie.min.y,ie.max.x,ie.max.y,(Le,ze,We,ct)=>m_(k.bufferedTilespaceGeometry,Le-X,ze-X,We+X,ct+X));ue.sort(q3t);let pe=null;T.elevation&&ue.length>0&&(pe=K6.create(T.elevation,this.tileID));const be={};let Se;for(let Le=0;Le(ct||(ct=Vr(nt,this.tileID.canonical,P)),ft.queryIntersectsFeature(k,nt,wt,ct,this.z,T,R,pe,Nt,x.scope)))}return be}loadMatchingFeature(m,x,k,T,P,R){const{featureIndex:U,bucketIndex:V,sourceLayerIndex:X,layoutVertexArrayOffset:ie}=x,ue=this.bucketLayerIDs[V],pe=k.layers,be=Object.keys(pe);if(be.length&&!On(be,ue))return;const Se=k.sourceCache,Le=this.sourceLayerCoder.decode(X),ze=this.vtLayers[Le].feature(U),We=this.getId(ze,Le);for(let ct=0;ct`${U.key}: ${U.message}`).join(", ");return void Yn(`Failed to create expression for promoteId: ${R}`)}this.promoteIdExpression=P.value}k=this.promoteIdExpression.evaluate({zoom:0},m)}else k=m.properties[T];typeof k=="boolean"&&(k=Number(k))}return k}}function xFe(b,m,x,k,T){return Vs(b,(P,R)=>{const U=m instanceof Gd?m.get(R):null;return U&&U.evaluate?U.evaluate(x,k,void 0,T):U})}function q3t(b,m){return m-b}function gFe(b,m){const x={};if(!m)return x;for(const k of b){const T=k.layerIds.map(P=>m.getLayer(P)).filter(Boolean);if(T.length!==0){k.layers=T,k.stateDependentLayerIds&&(k.stateDependentLayers=k.stateDependentLayerIds.map(P=>T.filter(R=>R.id===P)[0]));for(const P of T)x[P.fqid]=k}}return x}Kn(fFe,"FeatureIndex",{omit:["rawTileData","sourceLayerCoder"]});const Qy=32,b_=33,hk=new Uint16Array(8184);for(let b=0;b<2046;b++){let m=b+2,x=0,k=0,T=0,P=0,R=0,U=0;for(1&m?T=P=R=Qy:x=k=U=Qy;(m>>=1)>1;){const X=x+T>>1,ie=k+P>>1;1&m?(T=x,P=k,x=R,k=U):(x=T,k=P,T=R,P=U),R=X,U=ie}const V=4*b;hk[V+0]=x,hk[V+1]=k,hk[V+2]=T,hk[V+3]=P}const __=new Uint16Array(2178),mk=new Uint8Array(1089),Xq=new Uint16Array(1089);function yFe(b){return b===0?-.03125:b===32?.03125:0}const vFe={Other:0,Symbol:1,FillExtrusion:2},bFe={type:2,extent:Bn,loadGeometry:()=>[[new Es(0,0),new Es(8193,0),new Es(8193,8193),new Es(0,8193),new Es(0,0)]]};class V3t{constructor(){this.tasks={},this.taskQueue=[],ns(["process"],this),this.invoker=new U3t(this.process),this.nextId=0}add(m,x){const k=this.nextId++,T=function({type:P,renderSourceType:R,zoom:U}){U=U||0;const V=R===vFe.Symbol;return P==="message"?0:P!=="maybePrepare"||V?P!=="parseTile"||V?P==="parseTile"&&V?300-U:P==="maybePrepare"&&V?400-U:500:200-U:100-U}(x);if(T===0){try{m()}finally{}return null}return this.tasks[k]={fn:m,metadata:x,priority:T,id:k},this.taskQueue.push(k),this.invoker.trigger(),{cancel:()=>{delete this.tasks[k]}}}process(){try{if(this.taskQueue=this.taskQueue.filter(k=>!!this.tasks[k]),!this.taskQueue.length)return;const m=this.pick();if(m===null)return;const x=this.tasks[m];if(delete this.tasks[m],this.taskQueue.length&&this.invoker.trigger(),!x)return;x.fn()}finally{}}pick(){let m=null,x=1/0;for(let T=0;T>16&255)/255,(b>>8&255)/255,(255&b)/255,1)}function s5t(b,m,x){b===1?(m.rgb_color=tV(x.readVarint()),m.paint="rgb_color"):b===2?(m.linear_gradient_idx=x.readVarint(),m.paint="linear_gradient_idx"):b===3?(m.radial_gradient_idx=x.readVarint(),m.paint="radial_gradient_idx"):b===5?x.readPackedFloat(m.dasharray):b===6?m.dashoffset=x.readFloat():b===7?m.miterlimit=x.readFloat():b===8?m.opacity=x.readVarint():b===9?m.width=x.readFloat():b===10?m.linecap=x.readVarint():b===11&&(m.linejoin=x.readVarint())}function n5t(b,m,x){b===1?m.transform=eV(x,x.readVarint()+x.pos):b===2?m.spread_method=x.readVarint():b===3?m.stops.push(jFe(x,x.readVarint()+x.pos)):b===4?m.x1=x.readFloat():b===5?m.y1=x.readFloat():b===6?m.x2=x.readFloat():b===7&&(m.y2=x.readFloat())}function jFe(b,m){return b.readFields(r5t,{offset:0,opacity:255,rgb_color:A_e},m)}function r5t(b,m,x){b===1?m.offset=x.readFloat():b===2?m.opacity=x.readVarint():b===3&&(m.rgb_color=tV(x.readVarint()))}function a5t(b,m,x){b===1?m.transform=eV(x,x.readVarint()+x.pos):b===2?m.spread_method=x.readVarint():b===3?m.stops.push(jFe(x,x.readVarint()+x.pos)):b===4?m.cx=x.readFloat():b===5?m.cy=x.readFloat():b===6?m.r=x.readFloat():b===7?m.fx=x.readFloat():b===8?m.fy=x.readFloat():b===9&&(m.fr=x.readFloat())}function i5t(b,m,x){b===1?m.transform=eV(x,x.readVarint()+x.pos):b===2?m.clip_path_idx=x.readVarint():b===3&&m.children.push(Jq(x,x.readVarint()+x.pos))}function o5t(b,m,x){b===1?m.left=m.top=x.readFloat():b===2?m.width=m.height=x.readFloat():b===3?m.top=x.readFloat():b===4?m.height=x.readFloat():b===5?m.mask_type=x.readVarint():b===6?m.mask_idx=x.readVarint():b===7&&m.children.push(Jq(x,x.readVarint()+x.pos))}class l5t{static calculate(m={},x=[]){const k=new Map,T=new Map;if(Object.keys(m).length===0)return k;x.forEach(P=>{T.set(P.name,P.rgb_color||new Gn(0,0,0))});for(const[P,R]of Object.entries(m))T.has(P)?k.set(T.get(P).toString(),R):console.warn(`Ignoring unknown image variable "${P}"`);return k}}function Y6(b,m=255,x){const k=m/255,T=b.toString(),P=x.has(T)?x.get(T).clone():b.clone();return P.a*=k,P.toString()}function EO(b,m){if(!Uu()){const x=document.createElement("canvas");return x.width=b,x.height=m,x}return new OffscreenCanvas(b,m)}let M_e,AO=null;function I_e(b,m,x,k,T){for(const P of k.children)NFe(b,m,x,P,T)}function NFe(b,m,x,k,T){k.group?(b.save(),function(P,R,U,V,X){const ie=V.mask_idx!=null?U.masks[V.mask_idx]:null,ue=V.clip_path_idx!=null?U.clip_paths[V.clip_path_idx]:null;if(V.transform&&(R=Z6(V.transform).preMultiplySelf(R)),!function(Se,Le,ze){return Se.opacity!==255||Le||ze}(V,ue!=null,ie!=null))return void I_e(P,R,U,V,X);const pe=EO(P.canvas.width,P.canvas.height),be=pe.getContext("2d");I_e(be,R,U,V,X),ue&&MFe(be,R,U,ue),ie&&IFe(be,R,U,ie,X),P.globalAlpha=V.opacity/255,P.drawImage(pe,0,0)}(b,m,x,k.group,T),b.restore()):k.path&&(b.save(),function(P,R,U,V,X){P.setTransform(R),V.paint_order===1?(kFe(P,U,V,X),CFe(P,U,V,X)):(CFe(P,U,V,X),kFe(P,U,V,X))}(b,m,x,k.path,T),b.restore())}function kFe(b,m,x,k){const T=x.fill;if(!T)return;const P=T.opacity/255;switch(b.save(),b.beginPath(),PFe(x,b),T.paint){case"rgb_color":b.fillStyle=Y6(T.rgb_color,T.opacity,k);break;case"linear_gradient_idx":{const R=m.linear_gradients[T.linear_gradient_idx];R.transform&&b.setTransform(Z6(R.transform).preMultiplySelf(b.getTransform())),b.fillStyle=TFe(b,R,P,k);break}case"radial_gradient_idx":{const R=m.radial_gradients[T.radial_gradient_idx];R.transform&&b.setTransform(Z6(R.transform).preMultiplySelf(b.getTransform())),b.fillStyle=EFe(b,R,P,k)}}b.fill(SFe(x)),b.restore()}function SFe(b){return b.rule===1?"nonzero":b.rule===2?"evenodd":void 0}function CFe(b,m,x,k){const T=x.stroke;if(!T)return;const P=LFe(x);b.lineWidth=T.width,b.miterLimit=T.miterlimit,b.setLineDash(T.dasharray),b.lineDashOffset=T.dashoffset;const R=T.opacity/255;switch(T.paint){case"rgb_color":b.strokeStyle=Y6(T.rgb_color,T.opacity,k);break;case"linear_gradient_idx":b.strokeStyle=TFe(b,m.linear_gradients[T.linear_gradient_idx],R,k,!0);break;case"radial_gradient_idx":b.strokeStyle=EFe(b,m.radial_gradients[T.radial_gradient_idx],R,k,!0)}switch(T.linejoin){case 2:case 1:b.lineJoin="miter";break;case 3:b.lineJoin="round";break;case 4:b.lineJoin="bevel"}switch(T.linecap){case 1:b.lineCap="butt";break;case 2:b.lineCap="round";break;case 3:b.lineCap="square"}b.stroke(P)}function TFe(b,m,x,k,T=!1){if(m.stops.length===1){const pe=m.stops[0];return Y6(pe.rgb_color,pe.opacity*x,k)}const{x1:P,y1:R,x2:U,y2:V}=m;let X=new DOMPoint(P,R),ie=new DOMPoint(U,V);if(T){const pe=Z6(m.transform);X=pe.transformPoint(X),ie=pe.transformPoint(ie)}const ue=b.createLinearGradient(X.x,X.y,ie.x,ie.y);for(const pe of m.stops)ue.addColorStop(pe.offset,Y6(pe.rgb_color,pe.opacity*x,k));return ue}function EFe(b,m,x,k,T=!1){if(m.stops.length===1){const We=m.stops[0];return Y6(We.rgb_color,We.opacity*x,k)}const P=Z6(m.transform),{fx:R,fy:U,fr:V,cx:X,cy:ie,r:ue}=m;let pe=new DOMPoint(R,U),be=new DOMPoint(X,ie),Se=V,Le=ue;if(T){pe=P.transformPoint(pe),be=P.transformPoint(be);const We=(P.a+P.d)/2;Se=V*We,Le=m.r*We}const ze=b.createRadialGradient(pe.x,pe.y,Se,be.x,be.y,Le);for(const We of m.stops)ze.addColorStop(We.offset,Y6(We.rgb_color,We.opacity*x,k));return ze}function AFe(b,m,x,k){const T=k.transform?Z6(k.transform).preMultiplySelf(m):m,P=EO(b.canvas.width,b.canvas.height),R=P.getContext("2d");for(const V of k.children)if(V.group)AFe(R,T,x,V.group);else if(V.path){const X=V.path,ie=new Path2D;ie.addPath(LFe(X),T),R.fill(ie,SFe(X))}const U=k.clip_path_idx!=null?x.clip_paths[k.clip_path_idx]:null;U&&MFe(R,T,x,U),b.globalCompositeOperation="source-over",b.drawImage(P,0,0)}function MFe(b,m,x,k){const T=EO(b.canvas.width,b.canvas.height);AFe(T.getContext("2d"),m,x,k),b.globalCompositeOperation="destination-in",b.drawImage(T,0,0)}function IFe(b,m,x,k,T){if(k.children.length===0)return;const P=k.mask_idx!=null?x.masks[k.mask_idx]:null;P&&IFe(b,m,x,P,T);const R=b.canvas.width,U=b.canvas.height,V=EO(R,U),X=V.getContext("2d"),ie=k.width,ue=k.height,pe=k.left,be=k.top,Se=new Path2D,Le=new Path2D;Le.rect(pe,be,ie,ue),Se.addPath(Le,m),X.clip(Se);for(const ct of k.children)NFe(X,m,x,ct,T);const ze=X.getImageData(0,0,R,U),We=ze.data;if(k.mask_type===1)for(let ct=0;ctm[R])return null}else{const U=1/k[R];let V=(b[R]-x[R])*U,X=(m[R]-x[R])*U;if(V>X){const ie=V;V=X,X=ie}if(V>T&&(T=V),XP)return null}return T}function OFe(b,m,x,k,T,P,R,U,V,X,ie){const ue=k-b,pe=T-m,be=P-x,Se=R-b,Le=U-m,ze=V-x,We=ie[1]*ze-ie[2]*Le,ct=ie[2]*Se-ie[0]*ze,nt=ie[0]*Le-ie[1]*Se,ft=ue*We+pe*ct+be*nt;if(Math.abs(ft)<1e-15)return null;const wt=1/ft,Nt=X[0]-b,Wt=X[1]-m,Ft=X[2]-x,Gt=(Nt*We+Wt*ct+Ft*nt)*wt;if(Gt<0||Gt>1)return null;const Ut=Wt*be-Ft*pe,qt=Ft*ue-Nt*be,zs=Nt*pe-Wt*ue,qs=(ie[0]*Ut+ie[1]*qt+ie[2]*zs)*wt;return qs<0||Gt+qs>1?null:(Se*Ut+Le*qt+ze*zs)*wt}function FFe(b,m,x){return(b-m)/(x-m)}function zFe(b,m,x,k,T,P,R,U,V){const X=1<{const ct=ze?1:0,nt=(be+1)*Le-ct,ft=Se*Le,wt=(Se+1)*Le-ct;We[0]=be*Le,We[1]=ft,We[2]=nt,We[3]=wt};let ue=new DFe(V);const pe=[];for(let be=0;be=1;V/=2){const be=U[U.length-1];ue=new DFe(V);for(let Se=0;Se0;){const{idx:Se,t:Le,nodex:ze,nodey:We,depth:ct}=be.pop();if(this.leaves[Se]){zFe(ze,We,ct,m,x,k,T,ue,pe);const ft=1<=Js[2])return Le}continue}let nt=0;for(let ft=0;ft=X[ie[Ft]]&&(ie.splice(Ft,0,ft),Wt=!0);Wt||(ie[nt]=ft),nt++}}for(let ft=0;ft=this.dim+1||x<-1||x>=this.dim+1)throw new RangeError("out of range source coordinates for DEM data");return(x+1)*this.stride+(m+1)}static pack(m,x){const k=[0,0,0,0],T=nV.getUnpackVector(x);let P=Math.floor((m+T[3])/T[2]);return k[2]=P%256,P=Math.floor(P/256),k[1]=P%256,P=Math.floor(P/256),k[0]=P,k}getPixels(){return new wDe({width:this.stride,height:this.stride},this.pixels)}backfillBorder(m,x,k){if(this.dim!==m.dim)throw new Error("dem dimension mismatch");let T=x*this.dim,P=x*this.dim+this.dim,R=k*this.dim,U=k*this.dim+this.dim;switch(x){case-1:T=P-1;break;case 1:P=T+1}switch(k){case-1:R=U-1;break;case 1:U=R+1}const V=-x*this.dim,X=-k*this.dim;for(let ie=R;ie=1;k--){const T=k===1?1:0,P=k===2?1:0;for(let R=0;R>>1^-(1&b[m]);return b}function w5t(b,m){switch(m){case"uint32":return b;case"uint16":for(let x=0;x>4|(61440&k)>>8|(240&T)<<4|61440&T,b[x+1]=15&k|(3840&k)>>4|(15&T)<<8|(3840&T)<<4}return b;case"uint8":for(let x=0;x>6|(192&T)>>4|(192&P)>>2|192&R,b[x+1]=(48&k)>>4|(48&T)>>2|48&P|(48&R)<<2,b[x+2]=(12&k)>>2|12&T|(12&P)<<2|(12&R)<<4,b[x+3]=3&k|(3&T)<<2|(3&P)<<4|(3&R)<<6}return b;default:throw new Error(`Invalid pixel format, "${m}"`)}}Kn(nV,"DEMData"),Kn(BFe,"DemMinMaxQuadTree",{omit:["dem"]});var j0=Uint8Array,MO=Uint16Array,j5t=Int32Array,UFe=new j0([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]),qFe=new j0([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]),N5t=new j0([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),VFe=function(b,m){for(var x=new MO(31),k=0;k<31;++k)x[k]=m+=1<>1|(21845&Sd)<<1;WFe[Sd]=((65280&(Q6=(61680&(Q6=(52428&Q6)>>2|(13107&Q6)<<2))>>4|(3855&Q6)<<4))>>8|(255&Q6)<<8)>>1}var IO=function(b,m,x){for(var k=b.length,T=0,P=new MO(m);T>V]=X;return R},PO=new j0(288);for(Sd=0;Sd<144;++Sd)PO[Sd]=8;for(Sd=144;Sd<256;++Sd)PO[Sd]=9;for(Sd=256;Sd<280;++Sd)PO[Sd]=7;for(Sd=280;Sd<288;++Sd)PO[Sd]=8;var KFe=new j0(32);for(Sd=0;Sd<32;++Sd)KFe[Sd]=5;var C5t=IO(PO,9),T5t=IO(KFe,5),L_e=function(b){for(var m=b[0],x=1;xm&&(m=b[x]);return m},E1=function(b,m,x){var k=m/8|0;return(b[k]|b[k+1]<<8)>>(7&m)&x},D_e=function(b,m){var x=m/8|0;return(b[x]|b[x+1]<<8|b[x+2]<<16)>>(7&m)},E5t=function(b){return(b+7)/8|0},A5t=["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"],A1=function(b,m,x){var k=new Error(m||A5t[b]);if(k.code=b,Error.captureStackTrace&&Error.captureStackTrace(k,A1),!x)throw k;return k},M5t=new j0(0),I5t=typeof TextDecoder<"u"&&new TextDecoder;try{I5t.decode(M5t,{stream:!0})}catch{}const P5t={gzip_data:"gzip"};class Xy extends Error{constructor(m){super(m),this.name="MRTError"}}const L5t={0:"uint32",1:"uint32",2:"uint16",3:"uint8"},YFe={uint32:1,uint16:2,uint8:4},D5t={uint32:Uint32Array,uint16:Uint16Array,uint8:Uint8Array};let R_e;class rV{constructor(m=5){this.x=NaN,this.y=NaN,this.z=NaN,this.layers={},this._cacheSize=m}getLayer(m){const x=this.layers[m];if(!x)throw new Xy(`Layer '${m}' not found`);return x}getHeaderLength(m){const x=new Uint8Array(m),k=new DataView(m);if(x[0]!==13)throw new Xy("File is not a valid MRT.");return k.getUint32(1,!0)}parseHeader(m){const x=new Uint8Array(m),k=this.getHeaderLength(m);if(x.length= ${k} but got buffer of length ${x.length}`);const T=new R_e(x.subarray(0,k)).readFields(h5t,{headerLength:0,x:0,y:0,z:0,layers:[]},void 0);if(!isNaN(this.x)&&(this.x!==T.x||this.y!==T.y||this.z!==T.z))throw new Xy(`Invalid attempt to parse header ${T.z}/${T.x}/${T.y} for tile ${this.z}/${this.x}/${this.y}`);this.x=T.x,this.y=T.y,this.z=T.z;for(const P of T.layers)this.layers[P.name]=new ZFe(P,{cacheSize:this._cacheSize});return this}createDecodingTask(m){const x=[],k=this.getLayer(m.layerName);for(let T of m.blockIndices){const P=k.dataIndex[T],R=P.firstByte-m.firstByte,U=P.lastByte-m.firstByte;if(k._blocksInProgress.has(T))continue;const V={layerName:k.name,firstByte:R,lastByte:U,pixelFormat:k.pixelFormat,blockIndex:T,blockShape:[P.bands.length].concat(k.bandShape),buffer:k.buffer,codec:P.codec.codec,filters:P.filters.map(X=>X.filter)};k._blocksInProgress.add(T),x.push(V)}return new QFe(x,()=>{x.forEach(T=>k._blocksInProgress.delete(T.blockIndex))},(T,P)=>{if(x.forEach(R=>k._blocksInProgress.delete(R.blockIndex)),T)throw T;P.forEach(R=>{this.getLayer(R.layerName).processDecodedData(R)})})}}class ZFe{constructor({version:m,name:x,units:k,tileSize:T,pixelFormat:P,buffer:R,dataIndex:U},V){if(this.version=m,this.version!==1)throw new Xy(`Cannot parse raster layer encoded with MRT version ${m}`);this.name=x,this.units=k,this.tileSize=T,this.buffer=R,this.pixelFormat=L5t[P],this.dataIndex=U,this.bandShape=[T+2*R,T+2*R,YFe[this.pixelFormat]],this._decodedBlocks=new sV(V?V.cacheSize:5),this._blocksInProgress=new Set}get dimension(){return YFe[this.pixelFormat]}get cacheSize(){return this._decodedBlocks.capacity}getBandList(){return this.dataIndex.map(({bands:m})=>m).flat()}processDecodedData(m){const x=m.blockIndex.toString();this._decodedBlocks.get(x)||this._decodedBlocks.put(x,m.data)}getBlockForBand(m){let x=0;switch(typeof m){case"string":for(const[k,T]of this.dataIndex.entries()){for(const[P,R]of T.bands.entries())if(R===m)return{bandIndex:x+P,blockIndex:k,blockBandIndex:P};x+=T.bands.length}break;case"number":for(const[k,T]of this.dataIndex.entries()){if(m>=x&&mthis.cacheSize)throw new Xy(`Number of blocks to decode (${P.size}) exceeds cache size (${this.cacheSize}).`);return{layerName:this.name,firstByte:x,lastByte:k,blockIndices:T}}hasBand(m){const{blockIndex:x}=this.getBlockForBand(m);return x>=0}hasDataForBand(m){const{blockIndex:x}=this.getBlockForBand(m);return x>=0&&!!this._decodedBlocks.get(x.toString())}getBandView(m){const{blockIndex:x,blockBandIndex:k}=this.getBlockForBand(m);if(x<0)throw new Xy(`Band not found: ${JSON.stringify(m)}`);const T=this._decodedBlocks.get(x.toString());if(!T)throw new Xy(`Data for band ${JSON.stringify(m)} of layer "${this.name}" not decoded.`);const P=this.dataIndex[x],R=this.bandShape.reduce((X,ie)=>X*ie,1),U=k*R,V=T.subarray(U,U+R);return{data:V,bytes:new Uint8Array(V.buffer).subarray(V.byteOffset,V.byteOffset+V.byteLength),tileSize:this.tileSize,buffer:this.buffer,pixelFormat:this.pixelFormat,dimension:this.dimension,offset:P.offset,scale:P.scale}}}rV.setPbf=function(b){R_e=b};class QFe{constructor(m,x,k){this.tasks=m,this._onCancel=x,this._onComplete=k,this._finalized=!1}cancel(){this._finalized||(this._onCancel(),this._finalized=!0)}complete(m,x){this._finalized||(this._onComplete(m,x),this._finalized=!0)}}rV.performDecoding=function(b,m){const x=new Uint8Array(b);return Promise.all(m.tasks.map(k=>{const{layerName:T,firstByte:P,lastByte:R,pixelFormat:U,blockShape:V,blockIndex:X,filters:ie,codec:ue}=k,pe=x.subarray(P,R+1),be=new Uint32Array(V[0]*V[1]*V[2]);let Se;if(ue!=="gzip_data")throw new Xy(`Unhandled codec: ${ue}`);return Se=function(Le,ze){if(!globalThis.DecompressionStream&&ze==="gzip_data")return Promise.resolve((wt=function(Ft){Ft[0]==31&&Ft[1]==139&&Ft[2]==8||A1(6,"invalid gzip data");var Gt=Ft[3],Ut=10;4&Gt&&(Ut+=2+(Ft[10]|Ft[11]<<8));for(var qt=(Gt>>3&1)+(Gt>>4&1);qt>0;qt-=!Ft[Ut++]);return Ut+(2&Gt)}(We=Le),wt+8>We.length&&A1(6,"invalid gzip data"),function(Ft,Gt,Ut,qt){var zs=Ft.length;if(!zs||Gt.f&&!Gt.l)return Ut||new j0(0);var qs=!Ut,Xs=qs||Gt.i!=2,sn=Gt.i;qs&&(Ut=new j0(3*zs));var Js=function(Fl){var wm=Ut.length;if(Fl>wm){var yu=new j0(Math.max(2*wm,Fl));yu.set(Ut),Ut=yu}},fn=Gt.f||0,Os=Gt.p||0,en=Gt.b||0,on=Gt.l,gn=Gt.d,Cn=Gt.m,ar=Gt.n,Fn=8*zs;do{if(!on){fn=E1(Ft,Os,1);var Rn=E1(Ft,Os+1,3);if(Os+=3,!Rn){var Tn=Ft[(Qi=E5t(Os)+4)-4]|Ft[Qi-3]<<8,sr=Qi+Tn;if(sr>zs){sn&&A1(0);break}Xs&&Js(en+Tn),Ut.set(Ft.subarray(Qi,sr),en),Gt.b=en+=Tn,Gt.p=Os=8*sr,Gt.f=fn;continue}if(Rn==1)on=C5t,gn=T5t,Cn=9,ar=5;else if(Rn==2){var hr=E1(Ft,Os,31)+257,Ur=E1(Ft,Os+10,15)+4,jr=hr+E1(Ft,Os+5,31)+1;Os+=14;for(var Sa=new j0(jr),_i=new j0(19),Ca=0;Ca>4)<16)Sa[Ca++]=Qi;else{var Ro=0,Ml=0;for(Qi==16?(Ml=3+E1(Ft,Os,3),Os+=2,Ro=Sa[Ca-1]):Qi==17?(Ml=3+E1(Ft,Os,7),Os+=3):Qi==18&&(Ml=11+E1(Ft,Os,127),Os+=7);Ml--;)Sa[Ca++]=Ro}}var Yd=Sa.subarray(0,hr),Il=Sa.subarray(hr);Cn=L_e(Yd),ar=L_e(Il),on=IO(Yd,Cn),gn=IO(Il,ar)}else A1(1);if(Os>Fn){sn&&A1(0);break}}Xs&&Js(en+131072);for(var sc=(1<>4;if((Os+=15&Ro)>Fn){sn&&A1(0);break}if(Ro||A1(2),yh<256)Ut[en++]=yh;else{if(yh==256){nc=Os,on=null;break}var Zd=yh-254;yh>264&&(Zd=E1(Ft,Os,(1<<(hc=UFe[Ca=yh-257]))-1)+GFe[Ca],Os+=hc);var Za=gn[D_e(Ft,Os)&Oc],lp=Za>>4;if(Za||A1(3),Os+=15&Za,Il=S5t[lp],lp>3){var hc=qFe[lp];Il+=D_e(Ft,Os)&(1<Fn){sn&&A1(0);break}Xs&&Js(en+131072);var gu=en+Zd;if(enFl.length)&&(yu=Fl.length),new j0(Fl.subarray(0,yu))}(Ut,0,en):Ut.subarray(0,en)}(We.subarray(wt,-8),{i:2},new j0(((nt=We)[(ft=nt.length)-4]|nt[ft-3]<<8|nt[ft-2]<<16|nt[ft-1]<<24)>>>0),ct)));var We,ct,nt,ft,wt;const Nt=P5t[ze];if(!Nt)throw new Error(`Unhandled codec: ${ze}`);const Wt=new globalThis.DecompressionStream(Nt);return new Response(new Blob([Le]).stream().pipeThrough(Wt)).arrayBuffer().then(Ft=>new Uint8Array(Ft))}(pe,ue).then(Le=>(function(ze,We){ze.readFields(y5t,We)}(new R_e(Le),be),new D5t[U](be.buffer))),Se.then(Le=>{for(let ze=ie.length-1;ze>=0;ze--)switch(ie[ze]){case"delta_filter":b5t(Le,V);break;case"zigzag_filter":_5t(Le);break;case"bitshuffle_filter":w5t(Le,U);break;default:throw new Xy(`Unhandled filter "${ie[ze]}"`)}return{layerName:T,blockIndex:X,data:Le}}).catch(Le=>{throw Le})}))},Kn(QFe,"MRTDecodingBatch",{omit:["_onCancel","_onComplete"]}),Kn(rV,"MapboxRasterTile"),Kn(ZFe,"MapboxRasterLayer",{omit:["_blocksInProgress"]});const XFe=[Int8Array,Uint8Array,Uint8ClampedArray,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array];class O_e{static from(m){if(!(m instanceof ArrayBuffer))throw new Error("Data must be an instance of ArrayBuffer.");const[x,k]=new Uint8Array(m,0,2);if(x!==219)throw new Error("Data does not appear to be in a KDBush format.");const T=k>>4;if(T!==1)throw new Error(`Got v${T} data when expected v1.`);const P=XFe[15&k];if(!P)throw new Error("Unrecognized array type.");const[R]=new Uint16Array(m,2,1),[U]=new Uint32Array(m,4,1);return new O_e(U,R,P,m)}constructor(m,x=64,k=Float64Array,T){if(isNaN(m)||m<0)throw new Error(`Unpexpected numItems value: ${m}.`);this.numItems=+m,this.nodeSize=Math.min(Math.max(+x,2),65535),this.ArrayType=k,this.IndexArrayType=m<65536?Uint16Array:Uint32Array;const P=XFe.indexOf(this.ArrayType),R=2*m*this.ArrayType.BYTES_PER_ELEMENT,U=m*this.IndexArrayType.BYTES_PER_ELEMENT,V=(8-U%8)%8;if(P<0)throw new Error(`Unexpected typed array class: ${k}.`);T&&T instanceof ArrayBuffer?(this.data=T,this.ids=new this.IndexArrayType(this.data,8,m),this.coords=new this.ArrayType(this.data,8+U+V,2*m),this._pos=2*m,this._finished=!0):(this.data=new ArrayBuffer(8+R+U+V),this.ids=new this.IndexArrayType(this.data,8,m),this.coords=new this.ArrayType(this.data,8+U+V,2*m),this._pos=0,this._finished=!1,new Uint8Array(this.data,0,2).set([219,16+P]),new Uint16Array(this.data,2,1)[0]=x,new Uint32Array(this.data,4,1)[0]=m)}add(m,x){const k=this._pos>>1;return this.ids[k]=k,this.coords[this._pos++]=m,this.coords[this._pos++]=x,k}finish(){const m=this._pos>>1;if(m!==this.numItems)throw new Error(`Added ${m} items when expected ${this.numItems}.`);return F_e(this.ids,this.coords,this.nodeSize,0,this.numItems-1,0),this._finished=!0,this}range(m,x,k,T){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:P,coords:R,nodeSize:U}=this,V=[0,P.length-1,0],X=[];for(;V.length;){const ie=V.pop()||0,ue=V.pop()||0,pe=V.pop()||0;if(ue-pe<=U){for(let ze=pe;ze<=ue;ze++){const We=R[2*ze],ct=R[2*ze+1];We>=m&&We<=k&&ct>=x&&ct<=T&&X.push(P[ze])}continue}const be=pe+ue>>1,Se=R[2*be],Le=R[2*be+1];Se>=m&&Se<=k&&Le>=x&&Le<=T&&X.push(P[be]),(ie===0?m<=Se:x<=Le)&&(V.push(pe),V.push(be-1),V.push(1-ie)),(ie===0?k>=Se:T>=Le)&&(V.push(be+1),V.push(ue),V.push(1-ie))}return X}within(m,x,k){if(!this._finished)throw new Error("Data not yet indexed - call index.finish().");const{ids:T,coords:P,nodeSize:R}=this,U=[0,T.length-1,0],V=[],X=k*k;for(;U.length;){const ie=U.pop()||0,ue=U.pop()||0,pe=U.pop()||0;if(ue-pe<=R){for(let ze=pe;ze<=ue;ze++)e7e(P[2*ze],P[2*ze+1],m,x)<=X&&V.push(T[ze]);continue}const be=pe+ue>>1,Se=P[2*be],Le=P[2*be+1];e7e(Se,Le,m,x)<=X&&V.push(T[be]),(ie===0?m-k<=Se:x-k<=Le)&&(U.push(pe),U.push(be-1),U.push(1-ie)),(ie===0?m+k>=Se:x+k>=Le)&&(U.push(be+1),U.push(ue),U.push(1-ie))}return V}}function F_e(b,m,x,k,T,P){if(T-k<=x)return;const R=k+T>>1;JFe(b,m,R,k,T,P),F_e(b,m,x,k,R-1,1-P),F_e(b,m,x,R+1,T,1-P)}function JFe(b,m,x,k,T,P){for(;T>k;){if(T-k>600){const X=T-k+1,ie=x-k+1,ue=Math.log(X),pe=.5*Math.exp(2*ue/3),be=.5*Math.sqrt(ue*pe*(X-pe)/X)*(ie-X/2<0?-1:1);JFe(b,m,x,Math.max(k,Math.floor(x-ie*pe/X+be)),Math.min(T,Math.floor(x+(X-ie)*pe/X+be)),P)}const R=m[2*x+P];let U=k,V=T;for(LO(b,m,k,x),m[2*T+P]>R&&LO(b,m,k,T);UR;)V--}m[2*k+P]===R?LO(b,m,k,V):(V++,LO(b,m,V,T)),V<=x&&(k=V+1),x<=V&&(T=V-1)}}function LO(b,m,x,k){z_e(b,x,k),z_e(m,2*x,2*k),z_e(m,2*x+1,2*k+1)}function z_e(b,m,x){const k=b[m];b[m]=b[x],b[x]=k}function e7e(b,m,x,k){const T=b-x,P=m-k;return T*T+P*P}o.$=$y,o.A=class{constructor(b,m,x){this.target=b,this.parent=m,this.mapId=x,this.callbacks={},this.cancelCallbacks={},ns(["receive"],this),this.target.addEventListener("message",this.receive,!1),this.scheduler=new V3t}send(b,m,x,k,T=!1,P){const R=Math.round(1e18*Math.random()).toString(36).substring(0,10);x&&(x.metadata=P,this.callbacks[R]=x);const U=new Set;return this.target.postMessage({id:R,type:b,hasCallback:!!x,targetMapId:k,mustQueue:T,sourceMapId:this.mapId,data:dc(m,U)},U),{cancel:()=>{x&&delete this.callbacks[R],this.target.postMessage({id:R,type:"",targetMapId:k,sourceMapId:this.mapId})}}}receive(b){const m=b.data;if(!m)return;const x=m.id;if(x&&(!m.targetMapId||this.mapId===m.targetMapId))if(m.type===""){const k=this.cancelCallbacks[x];delete this.cancelCallbacks[x],k&&k.cancel()}else if(m.mustQueue||xa(self)){const k=this.callbacks[x],T=this.scheduler.add(()=>this.processTask(x,m),k&&k.metadata||{type:"message"});T&&(this.cancelCallbacks[x]=T)}else this.processTask(x,m)}processTask(b,m){if(delete this.cancelCallbacks[b],m.type===""){const x=this.callbacks[b];delete this.callbacks[b],x&&(m.error?x(ec(m.error)):x(null,ec(m.data)))}else{const x=new Set,k=m.hasCallback?(P,R)=>{this.target.postMessage({id:b,type:"",sourceMapId:this.mapId,error:P?dc(P):null,data:dc(R,x)},x)}:()=>{},T=ec(m.data);if(this.parent[m.type])this.parent[m.type](m.sourceMapId,T,k);else if(this.parent.getWorkerSource){const P=m.type.split("."),{source:R,scope:U}=T;this.parent.getWorkerSource(m.sourceMapId,{type:P[0],source:R,scope:U,uid:0})[P[1]](T,k)}else k(new Error(`Could not find function ${m.type}`))}}remove(){this.scheduler.remove(),this.target.removeEventListener("message",this.receive,!1)}},o.B=Xm,o.C=Lc,o.D=ep,o.E=Lp,o.F=vt,o.G=2,o.H=gO,o.I=Pt,o.J=yOe,o.K=oj,o.L=Fj,o.M=Ry,o.N=Hb,o.O=ap,o.P=Es,o.Q=Bp,o.R=l0,o.S=VN,o.T=v_,o.U=Vy,o.V=Zq,o.W=u_,o.X=bx,o.Y=Aj,o.Z=gm,o._=By,o.a=function(b){return aa.API_CDN_URL_REGEX.test(b)},o.a$=Iq,o.a0=Dc,o.a1=c0,o.a2=n1,o.a3=Ir,o.a4=zj,o.a5=class extends Zq{},o.a6=HN,o.a7=qN,o.a8=ps,o.a9=function(b){const m=b.value;return m?n1(m)?S_e(m,!0)?[]:[new Zq(b.key,m,`invalid url "${m}"`)]:[new Zq(b.key,m,`string expected, "${Ry(m)}" found`)]:[]},o.aA=GRe,o.aB=function(b){let m=1/0,x=1/0,k=-1/0,T=-1/0;for(const P of b)m=Math.min(m,P.x),x=Math.min(x,P.y),k=Math.max(k,P.x),T=Math.max(T,P.y);return{min:new Es(m,x),max:new Es(k,T)}},o.aC=Qe,o.aD=w,o.aE=ut,o.aF=Et,o.aG=Gp,o.aH=rn,o.aI=rr,o.aJ=function(b,m){const x={};for(let k=0;k=0?m.slice(x+1):""}catch{return""}},o.aN=class{constructor(b){this.entries={},this.scheduler=b}request(b,m,x,k){const T=this.entries[b]=this.entries[b]||{callbacks:[]};if(T.result){const[P,R]=T.result;return this.scheduler?this.scheduler.add(()=>{k(P,R)},m):k(P,R),()=>{}}return T.callbacks.push(k),T.cancel||(T.cancel=x((P,R)=>{T.result=[P,R];for(const U of T.callbacks)this.scheduler?this.scheduler.add(()=>{U(P,R)},m):U(P,R);setTimeout(()=>delete this.entries[b],3e3)})),()=>{T.result||(T.callbacks=T.callbacks.filter(P=>P!==k),T.callbacks.length||(T.cancel(),delete this.entries[b]))}}},o.aO=function(b,m,x){const k=JSON.stringify(b.request);return b.data&&(this.deduped.entries[k]={result:[null,b.data]}),this.deduped.request(k,{type:"parseTile",renderSourceType:b.renderSourceType,zoom:b.tileZoom},T=>{const P=Iy(b.request,(R,U,V)=>{R?Cf(R)?T(null,null):T(R):U&&T(null,{rawData:U,vectorTile:x?void 0:new Fi(new Iq(U)),responseHeaders:new Map(V.entries())})});return()=>{P.cancel(),T(null,null)}},m)},o.aP=function(b){return b?{cacheControl:b.get("cache-control"),expires:b.get("expires")}:{cacheControl:void 0,expires:void 0}},o.aQ=function(b){zb++,zb>Ay&&(b.getActor().send("enforceCacheSizeLimit",Ey),zb=0)},o.aR=op,o.aS=JOe,o.aT=oFe,o.aU=ss,o.aV=XOe,o.aW=function(b,m){const x=document.createElement("video");x.muted=!0,x.onloadstart=function(){m(null,x)};for(let k=0;k{}}},o.aX=hO,o.aY=XC,o.aZ=ns,o.a_=rV,o.aa=ZN,o.ab=qo,o.ac=wn,o.ad=class{constructor(b){this.specification=b}possiblyEvaluate(b,m){return Er(b.expression.evaluate(m))}interpolate(b,m,x){return{x:Dr(b.x,m.x,x),y:Dr(b.y,m.y,x),z:Dr(b.z,m.z,x),azimuthal:Dr(b.azimuthal,m.azimuthal,x),polar:Dr(b.polar,m.polar,x)}}},o.ae=Aa,o.af=_x,o.ag=ur,o.ah=Je,o.ai=ee,o.aj=ot,o.ak=Gd,o.al=Gj,o.am=Dr,o.an=Bn,o.ao=kd,o.ap=Ts,o.aq=Gn,o.ar=class{constructor(b){this.specification=b}possiblyEvaluate(b,m){return function([x,k]){const T=Er([1,x,k]);return{x:T.x,y:T.y,z:T.z}}(b.expression.evaluate(m))}interpolate(b,m,x){return{x:Dr(b.x,m.x,x),y:Dr(b.y,m.y,x),z:Dr(b.z,m.z,x)}}},o.as=function(b,m,x=0,k=!0){const T=new Es(x,x),P=b.sub(T),R=m.add(T),U=[P,new Es(R.x,P.y),R,new Es(P.x,R.y)];return k&&U.push(P.clone()),U},o.at=function(b,m){const x=[];for(let k=0;kthis.buckets[ue].layers.some(pe=>R.has(pe.fqid))),V=Object.keys(this.buckets).some(ue=>this.buckets[ue].layers.some(pe=>pe.hasTransition&&pe.hasTransition())),X=this._firstPrepareComplete&&P!==this._lastAvailableImagesCount;this._hasAppearances===null&&(this._hasAppearances=this.hasAppearances(m));const ie=this._lastUpdatedBrightness!==k;this._lastAvailableImagesCount=P,this._firstPrepareComplete=!0,(this._lastUpdatedBrightness||k||this._hasAppearances||U||V||X)&&(!(this._hasAppearances||U||V||X)&&this._lastUpdatedBrightness&&k&&Math.abs(this._lastUpdatedBrightness-k)<.001||(this.updateBuckets(m,ie,void 0,X||U||V,R,T),this._lastUpdatedBrightness=k))}evaluateQueryRenderedFeaturePadding(){let b=0;for(const m in this.buckets){const x=this.buckets[m];x.evaluateQueryRenderedFeaturePadding&&(b=Math.max(b,x.evaluateQueryRenderedFeaturePadding()))}return b}queryRenderedFeatures(b,m,x,k,T,P,R){if(!this.latestFeatureIndex||!this.latestFeatureIndex.rawTileData&&!this.latestFeatureIndex.is3DTile)return{};const U=this.evaluateQueryRenderedFeaturePadding(),V=function(X,ie){const ue=I([],[.5*X.width,.5*-X.height,1]);return S(ue,ue,[1,-1,0]),w(ue,ue,X.calculateProjMatrix(ie.toUnwrapped())),Float32Array.from(ue)}(T,this.tileID);return this.latestFeatureIndex.query(b,{tilespaceGeometry:m,pixelPosMatrix:V,transform:k,availableImages:x,tileTransform:this.tileTransform,worldview:this.worldview,queryRadius:U,scope:R})}querySourceFeatures(b,m){const x=this.latestFeatureIndex;if(!x||!x.rawTileData)return;const k=x.loadVTLayers(),T=m?m.sourceLayer:"",P=k._geojsonTileLayer||k[T];if(!P)return;const R=JN(m&&m.filter),{z:U,x:V,y:X}=this.tileID.canonical,ie={z:U,x:V,y:X};for(let ue=0;uex)k=!1;else if(m)if(this.expirationTimex.appearances&&x.appearances.length>0))return!0;return!1}updateBuckets(b,m,x,k,T,P){if(!this.latestFeatureIndex||!b.style)return;const R=P||b.style.listImages(),U=b.style.getBrightness(),V=T||new Set;for(const X in this.buckets){if(!b.style.hasLayer(X))continue;const ie=this.buckets[X],ue=ie.layers[0],pe=ue.sourceLayer||"_geojsonTileLayer",be=b.style.getLayerSourceCache(ue),Se=ie.layers.some(wt=>V.has(wt.fqid)),Le=(k||Se)&&ie instanceof T1?b.style.getOwnLayer(X):void 0;let ze=x&&x[pe]||{};be&&!x&&(ze=be._state.getState(pe,void 0));const We=this.imageAtlas?Object.fromEntries(this.imageAtlas.patternPositions):{},ct=Object.keys(ze).length>0&&!m;ie.hasAppearances=ie.layers.some(wt=>wt.appearances&&wt.appearances.length>0);const nt=ct?ie.stateDependentLayers:ie.layers;if(ct&&ie.stateDependentLayers.length!==0||m||Se||k){const wt=this.latestFeatureIndex.loadVTLayers()[pe];if(ie.update(ze,wt,R,We,nt,m,U,this.tileID.canonical),(k||Se)&&!m&&ie instanceof T1&&Le&&Le.type==="symbol"){const Nt=ie;Nt.text&&Nt.text.uboBinder&&Nt.text.uboBinder.updateDynamicExpressions(Le,wt,this.tileID.canonical,R,ze,U),Nt.icon&&Nt.icon.uboBinder&&Nt.icon.uboBinder.updateDynamicExpressions(Le,wt,this.tileID.canonical,R,ze,U)}if(ie instanceof T1){const Nt=ie,Wt=b.context;Nt.text&&Nt.text.uboBinder&&Nt.text.uboBinder.upload(Wt),Nt.icon&&Nt.icon.uboBinder&&Nt.icon.uboBinder.upload(Wt)}}if(ct&&ie.stateDependentLayers.length!==0||m||ie.hasAppearances){const wt={zoom:b.transform.zoom,pitch:b.transform.pitch,brightness:b.style.getBrightness()||0,worldview:b.worldview},Nt=ie.updateAppearances(this.tileID.canonical,ze,R,wt,b.imageManager,ct&&ie.stateDependentLayers.length!==0);if(Nt&&Nt.hasUboChanges){const Wt=b.context;ie instanceof T1&&ie.text&&ie.text.uboBinder&&ie.text.uboBinder.upload(Wt),ie instanceof T1&&ie.icon&&ie.icon.uboBinder&&ie.icon.uboBinder.upload(Wt)}}(ie instanceof Mq||ie instanceof hq)&&b._terrain&&b._terrain.enabled&&be&&ie.uploadPending()&&b._terrain._clearRenderCacheForTile(be.id,this.tileID);const ft=b&&b.style&&b.style.getOwnLayer(X);ft&&(this.queryPadding=Math.max(this.queryPadding,ft.queryRadius(ie)||0))}}holdingForFade(){return this.symbolFadeHoldUntil!==void 0}symbolFadeFinished(){return!this.symbolFadeHoldUntil||this.symbolFadeHoldUntil<$d.now()}clearFadeHold(){this.symbolFadeHoldUntil=void 0}setHoldDuration(b){this.symbolFadeHoldUntil=$d.now()+b}setTexture(b,m){const x=m.context,k=x.gl;this.texture=this.texture||m.getTileTexture(b.width),this.texture&&this.texture instanceof v_?this.texture.update(b):(this.texture=new v_(x,b,k.RGBA8,{useMipmap:!0}),this.texture.bind(k.LINEAR,k.CLAMP_TO_EDGE))}setDependencies(b,m){const x={};for(const k of m)x[k]=!0;this.dependencies[b]=x}hasDependency(b,m){for(const x of b){const k=this.dependencies[x];if(k){for(const T of m)if(k[T])return!0}}return!1}clearQueryDebugViz(){}_makeDebugTileBoundsBuffers(b,m){if(!m||m.name==="mercator"||this._tileDebugBuffer)return;const x=Vr(bFe,this.tileID.canonical,this.tileTransform)[0],k=new qa,T=new Uj;for(let P=0;P=0;Le--){const ze=4*Le,We=hk[ze+0],ct=hk[ze+1],nt=hk[ze+2],ft=hk[ze+3],wt=We+nt>>1,Nt=ct+ft>>1,Wt=wt+Nt-ct,Ft=Nt+We-wt,Gt=ct*b_+We,Ut=ft*b_+nt,qt=Nt*b_+wt,zs=Math.hypot((__[2*Gt+0]+__[2*Ut+0])/2-__[2*qt+0],(__[2*Gt+1]+__[2*Ut+1])/2-__[2*qt+1])>=16;mk[qt]=mk[qt]||(zs?1:0),Le<1022&&(mk[qt]=mk[qt]||mk[(ct+Ft>>1)*b_+(We+Wt>>1)]||mk[(ft+Ft>>1)*b_+(nt+Wt>>1)])}const ie=new ni,ue=new tc;let pe=0;function be(Le,ze){const We=ze*b_+Le;return Xq[We]===0&&(ie.emplaceBack(__[2*We+0],__[2*We+1],Le*Bn/Qy,ze*Bn/Qy),Xq[We]=++pe),Xq[We]-1}function Se(Le,ze,We,ct,nt,ft){const wt=Le+We>>1,Nt=ze+ct>>1;if(Math.abs(Le-nt)+Math.abs(ze-ft)>1&&mk[Nt*b_+wt])Se(nt,ft,Le,ze,wt,Nt),Se(We,ct,nt,ft,wt,Nt);else{const Wt=be(Le,ze),Ft=be(We,ct),Gt=be(nt,ft);ue.emplaceBack(Wt,Ft,Gt)}}return Se(0,0,Qy,Qy,Qy,0),Se(Qy,Qy,0,0,0,Qy),{vertices:ie,indices:ue}}(this.tileID.canonical,m);k=P.vertices,T=P.indices}else{k=new ni,T=new tc;for(const{x:R,y:U}of x)k.emplaceBack(R,U,0,0);const P=D6(k.int16.subarray(0,4*k.length),void 0,4);for(let R=0;R0&&(R=j(new Float64Array(16),m.globeMatrix)),this._makeGlobeTileDebugBorderBuffer(b,k,m,T,R,P),this._makeGlobeTileDebugTextBuffer(b,k,m,T,R,P)}_globePoint(b,m,x,k,T,P,R){let U=YR(b,m,x);if(P){const V=1<.5?pe=-1:ue<-.5&&(pe=1);let be=(b/Bn+x.x)/V+pe,Se=(m/Bn+x.y)/V;be=(be-X)*k._pixelsPerMercatorPixel+X,Se=(Se-ie)*k._pixelsPerMercatorPixel+ie;const Le=[be*k.worldSize,Se*k.worldSize,0];Je(Le,Le,P),U=Hj(U,Le,R)}return Je(U,U,T)}_makeGlobeTileDebugBorderBuffer(b,m,x,k,T,P){const R=new qa,U=new Uj,V=new Di,X=(ue,pe,be,Se,Le)=>{const ze=(be-ue)/(Le-1),We=(Se-pe)/(Le-1),ct=R.length;for(let nt=0;ntX*ue+pe;for(let ue=0;ue1)return!1;const x=m.getSource().maxzoom,k=1<1)return m;const T=k.getSource().maxzoom,P=1<{const U=this.getAtTileOffset(b,T,P,R),V=k.upVector(b.canonical,T.x,T.y);return ge(V,V,U*k.upVectorScale(b.canonical,m,x).metersToTile),V}}getForTilePoints(b,m,x,k){if(this.isUsingMockSource())return!1;const T=K6.create(this,b,k);return!!T&&(m.forEach(P=>{P[2]=this.exaggeration()*T.getElevationAt(P[0],P[1],x)}),!0)}getMinMaxForTile(b){if(this.isUsingMockSource())return null;const m=this.findDEMTileFor(b);if(!m||!m.dem)return null;const x=m.dem.tree,k=m.tileID,T=1<0&&(k+=(b[T]-0)*(b[T]-0)),m[T]<0&&(k+=(0-m[T])*(0-m[T]));return k},o.cL=function(b){return b*b*b*b*b},o.cM=Ps,o.cN=45,o.cO=I6,o.cP=function(b,m,x){const k=Math.sqrt(b*b+m*m+x*x),T=k>0?Math.acos(x/k)*Hn:0;let P=b!==0||m!==0?Math.atan2(-m,-b)*Hn+90:0;return P<0&&(P+=360),[k,P,T]},o.cQ=se,o.cR=Er,o.cS=cn,o.cT=he,o.cU=eo,o.cV=ce,o.cW=function(b){return[Math.pow(b[0],1/2.2),Math.pow(b[1],1/2.2),Math.pow(b[2],1/2.2)]},o.cX=ERe,o.cY=Kbe,o.cZ=LRe,o.c_=S_e,o.ca=2,o.cb=7,o.cc=6,o.cd=we,o.ce=Y,o.cf=W,o.cg=0,o.ch=1,o.ci=4,o.cj=5,o.ck=L6,o.cl=Ff,o.cm=MRe,o.cn=UC,o.co=iDe,o.cp=function(b,m,x,k,T,P,R,U,V){if(V.name==="globe")return iDe(b,m,new UC(x,k,T),!1);const X=YC({z:x,x:k,y:T},V);return new eo([(P+X.x/X.scale)*m,m*(X.y/X.scale),R],[(P+X.x2/X.scale)*m,m*(X.y2/X.scale),U])},o.cq=function(b,m,x){return b[0]=Math.min(m[0],x[0]),b[1]=Math.min(m[1],x[1]),b[2]=Math.min(m[2],x[2]),b[3]=Math.min(m[3],x[3]),b},o.cr=function(b,m,x){return b[0]=Math.max(m[0],x[0]),b[1]=Math.max(m[1],x[1]),b[2]=Math.max(m[2],x[2]),b[3]=Math.max(m[3],x[3]),b},o.cs=function(b){const m=Math.round((b+45+360)%360/90)%4;return ir[m]},o.ct=Ys,o.cu=tt,o.cv=6,o.cw=function(b){const m=v(new Float64Array(16));w(m,b.pixelMatrix,b.globeMatrix);const x=[0,Ot,0],k=[0,Qt,0];return Je(x,x,m),Je(k,k,m),[x[0]>0&&x[0]<=b.width&&x[1]>0&&x[1]<=b.height&&!fbe(b,new ss(b.center.lat,90)),k[0]>0&&k[0]<=b.width&&k[1]>0&&k[1]<=b.height&&!fbe(b,new ss(b.center.lat,-90))]},o.cx=function(b,m){const{scale:x}=b.tileTransform,k=x*Bn/(b.tileSize*Math.pow(2,m.zoom-b.tileID.overscaledZ+b.tileID.canonical.z));return function(T,P,R){var U=P[1],V=P[2],X=P[3],ie=R[0],ue=R[1];return T[0]=P[0]*ie,T[1]=U*ie,T[2]=V*ue,T[3]=X*ue,T}(new Float32Array(4),m.inverseAdjustmentMatrix,[k,k])},o.cy=kq,o.cz=Z,o.d=function(b){return aa.API_TILEJSON_REGEX.test(b)},o.d$=VSt,o.d0=Rl,o.d1=class{static calculate(b,m,x){const k=new Set,T=new Map,P=new Set,R=new Set;for(const V of Object.values(b))for(const[X,ie]of Object.entries(V.floors)){P.add(X),ie.isDefault&&R.add(X),ie.conflicts&&T.set(X,ie.conflicts);const ue=X===m,pe=ie.connections&&m&&ie.connections.has(m);(ue||pe)&&k.add(X)}const U=V=>{const X=T.get(V)||new Set;for(const ie of k)if((T.get(ie)||new Set).has(V)||X.has(ie))return!0;return!1};if(x)for(const V of x)P.has(V)&&(U(V)||k.add(V));for(const V of R)k.has(V)||U(V)||k.add(V);return k}},o.d2=Rq,o.d3=m_e,o.d4=Ka,o.d5=function(){return{API_URL:aa.API_URL,DRACO_URL:aa.DRACO_URL,MESHOPT_URL:aa.MESHOPT_URL,MESHOPT_SIMD_URL:aa.MESHOPT_SIMD_URL,BUILDING_GEN_URL:aa.BUILDING_GEN_URL}},o.d6=_6,o.d7=rj,o.d8=Nd,o.d9=mn,o.dA=nq,o.dB=qa,o.dC=tc,o.dD=function(b,m){return[Math.pow(b[0],2.2)*m,Math.pow(b[1],2.2)*m,Math.pow(b[2],2.2)*m]},o.dE=h,o.dF=function(b,m){var x=Math.sin(m),k=Math.cos(m);return b[0]=k,b[1]=x,b[2]=0,b[3]=-x,b[4]=k,b[5]=0,b[6]=0,b[7]=0,b[8]=1,b},o.dG=ke,o.dH=lDe,o.dI=si,o.dJ=Yi,o.dK=N_e,o.dL=function(b,m){const x=[0,0,0];return Je(x,x,ZR(x_(m.canonical))),Je(x,x,b),x},o.dM=b=>({u_matrix:new g(b),u_texsize:new bg(b),u_pixels_to_tile_units:new $(b),u_device_pixel_ratio:new cd(b),u_width_scale:new cd(b),u_floor_width_scale:new cd(b),u_image:new BC(b),u_units_to_pixels:new bg(b),u_tile_units_to_pixels:new cd(b),u_alpha_discard_threshold:new cd(b),u_trim_offset:new bg(b),u_trim_fade_range:new bg(b),u_trim_gradient_mix_range:new bg(b),u_trim_color:new I6(b),u_zbias_factor:new cd(b),u_tile_to_meter:new cd(b),u_ground_shadow_factor:new $C(b),u_pattern_transition:new cd(b)}),o.dN=b=>({u_matrix:new g(b),u_pixels_to_tile_units:new $(b),u_device_pixel_ratio:new cd(b),u_width_scale:new cd(b),u_floor_width_scale:new cd(b),u_units_to_pixels:new bg(b),u_dash_image:new BC(b),u_gradient_image:new BC(b),u_image_height:new cd(b),u_texsize:new bg(b),u_tile_units_to_pixels:new cd(b),u_alpha_discard_threshold:new cd(b),u_trim_offset:new bg(b),u_trim_fade_range:new bg(b),u_trim_gradient_mix_range:new bg(b),u_trim_color:new I6(b),u_zbias_factor:new cd(b),u_tile_to_meter:new cd(b),u_ground_shadow_factor:new $C(b)}),o.dO=b=>({u_camera_to_center_distance:new cd(b),u_extrude_scale:new $(b),u_device_pixel_ratio:new cd(b),u_matrix:new g(b),u_inv_rot_matrix:new g(b),u_merc_center:new bg(b),u_tile_id:new $C(b),u_zoom_transition:new cd(b),u_up_dir:new $C(b),u_emissive_strength:new cd(b)}),o.dP=OR,o.dQ=qCt,o.dR=class{constructor(b,m,x,k){this.context=b,this.format=k,this.size=x,this.texture=b.gl.createTexture();const[T,P,R]=this.size,{gl:U}=b;U.bindTexture(U.TEXTURE_3D,this.texture),b.pixelStoreUnpackFlipY.set(!1),b.pixelStoreUnpack.set(1),b.pixelStoreUnpackPremultiplyAlpha.set(!1),"data"in m&&m.data&&U.texImage3D(U.TEXTURE_3D,0,this.format,T,P,R,0,$be(this.format),Ube(this.format),m.data)}bind(b,m){const{context:x}=this,{gl:k}=x;k.bindTexture(k.TEXTURE_3D,this.texture),b!==this.minFilter&&(k.texParameteri(k.TEXTURE_3D,k.TEXTURE_MAG_FILTER,b),k.texParameteri(k.TEXTURE_3D,k.TEXTURE_MIN_FILTER,b),this.minFilter=b),m!==this.wrapS&&(k.texParameteri(k.TEXTURE_3D,k.TEXTURE_WRAP_S,m),k.texParameteri(k.TEXTURE_3D,k.TEXTURE_WRAP_T,m),this.wrapS=m)}destroy(){const{gl:b}=this.context;b.deleteTexture(this.texture),this.texture=null}},o.dS=hDe,o.dT=(b,m,x,k,T,P)=>{const R=b.transform,U=R.projection.name==="globe";let V;if(P.paint.get("circle-pitch-alignment")==="map")if(U){const ie=lDe(R.zoom,m.canonical)*R._pixelsPerMercatorPixel;V=Float32Array.from([ie,0,0,ie])}else V=R.calculatePixelsToTileUnitsMatrix(x);else V=new Float32Array([R.pixelsToGLUnits[0],0,0,R.pixelsToGLUnits[1]]);const X={u_camera_to_center_distance:b.transform.getCameraToCenterDistance(R.projection),u_matrix:b.translatePosMatrix(m.projMatrix,x,P.paint.get("circle-translate"),P.paint.get("circle-translate-anchor")),u_device_pixel_ratio:$d.devicePixelRatio,u_extrude_scale:V,u_inv_rot_matrix:ZSt,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0],u_emissive_strength:P.paint.get("circle-emissive-strength")};if(U){X.u_inv_rot_matrix=k,X.u_merc_center=T,X.u_tile_id=[m.canonical.x,m.canonical.y,1<{const ie=b.transform,ue=ie.pitch<15?WRe(.07,.7,Qe((14-ie.zoom)/5,0,1)):.07,pe=x.paint.get("line-trim-color-use-theme").constantOr("default")==="none";return{u_matrix:YRe(b,m,x,k),u_texsize:m.imageAtlasTexture?m.imageAtlasTexture.size:[0,0],u_pixels_to_tile_units:ie.calculatePixelsToTileUnitsMatrix(m),u_device_pixel_ratio:T,u_width_scale:P,u_floor_width_scale:R,u_image:0,u_tile_units_to_pixels:KRe(m,ie),u_units_to_pixels:[1/ie.pixelsToGLUnits[0],1/ie.pixelsToGLUnits[1]],u_alpha_discard_threshold:0,u_trim_offset:U,u_trim_fade_range:x.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:x.paint.get("line-trim-color").toPremultipliedRenderColor(pe?null:x.lut).toArray01(),u_zbias_factor:ue,u_tile_to_meter:cn(m.tileID.canonical,0),u_ground_shadow_factor:V,u_pattern_transition:X}},o.dX=(b,m,x,k,T,P,R,U,V,X)=>{const ie=b.transform,ue=ie.calculatePixelsToTileUnitsMatrix(m),pe=x.paint.get("line-trim-color-use-theme").constantOr("default")==="none",be=ie.pitch<15?WRe(.07,.7,Qe((14-ie.zoom)/5,0,1)):.07;return{u_matrix:YRe(b,m,x,k),u_pixels_to_tile_units:ue,u_device_pixel_ratio:P,u_width_scale:R,u_floor_width_scale:U,u_units_to_pixels:[1/ie.pixelsToGLUnits[0],1/ie.pixelsToGLUnits[1]],u_dash_image:0,u_gradient_image:1,u_image_height:T,u_texsize:QRe(x)&&m.lineAtlasTexture?m.lineAtlasTexture.size:[0,0],u_tile_units_to_pixels:KRe(m,b.transform),u_alpha_discard_threshold:0,u_trim_offset:V,u_trim_fade_range:x.paint.get("line-trim-fade-range"),u_trim_gradient_mix_range:[1,1],u_trim_color:x.paint.get("line-trim-color").toPremultipliedRenderColor(pe?null:x.lut).toArray01(),u_zbias_factor:be,u_tile_to_meter:cn(m.tileID.canonical,0),u_ground_shadow_factor:X}},o.dY=lt,o.dZ=QR,o.d_=Us,o.da=function(b){const m=b.indexOf(et);return m>=0?b.slice(0,m):b},o.db=function(b){return b.indexOf(et)>=0},o.dc=function(b){const m=b.lastIndexOf(et);return m>=0?b.slice(m+1):""},o.dd=function(b){const m=[],x=b.id;return x===void 0&&m.push({message:`layers.${x}: missing required property "id"`}),b.render===void 0&&m.push({message:`layers.${x}: missing required method "render"`}),b.renderingMode&&b.renderingMode!=="2d"&&b.renderingMode!=="3d"&&m.push({message:`layers.${x}: property "renderingMode" must be either "2d" or "3d"`}),m},o.de=function(b,m,x,k){return b.type==="custom"?new R3t(b,m):new $3t[b.type](b,m,x,k)},o.df=ys,o.dg=JN,o.dh=ms,o.di=class extends QC{constructor(b,m){super(b._vectorTileFeature,b._z,b._x,b._y,b.id),b.state&&(this.state=Object.assign({},b.state)),this.target=m.target,this.namespace=m.namespace,m.properties&&(this.properties=m.properties),this.target&&("featuresetId"in this.target&&!this.target.importId||"layerId"in this.target)&&(this.source=b.source,this.sourceLayer=b.sourceLayer,this.layer=b.layer)}toJSON(){const b=super.toJSON();return b.target=this.target,b.namespace=this.namespace,b}},o.dj=YN,o.dk=function(b){return b({pluginStatus:Hd,pluginURL:qp}),YN.on("pluginStateChange",b),b},o.dl=dbe,o.dm=class extends vg{constructor(b){super(b),this.current=C}set(b,m,x){if(this.fetchUniformLocation(b,m)){for(let k=0;k<9;k++)if(x[k]!==this.current[k]){this.current=x,this.gl.uniformMatrix3fv(this.location,!1,x);break}}}},o.dn=Tr,o.dp=function(b,m,x){const k=Gj(x.zoom),T=b.style.map._antialias,P=b.terrain&&b.terrain.exaggeration()>0;return k===0&&!T&&!P},o.dq=function(b){const m=b.pixelsPerMeter,x=m/Ns(1,b.center.lat),k=v(new Float64Array(16));return S(k,k,[b.point.x,b.point.y,0]),A(k,k,[x,x,m]),Float32Array.from(k)},o.dr=rq,o.ds=function(b){const m=80.051129;b=Qe(b,-80.051129,m)/m*90;const x=Math.pow(Math.abs(Math.sin(Ts(b))),3);return Math.round(x*(es.length-1))},o.dt=function(b,m,x,k){const T=m.getNorth(),P=m.getSouth(),R=m.getWest(),U=m.getEast(),V=1<0){const Se=180/k;f(be,be,[Se/X+1,0,0,0,Se/ie+1,0,-.5*Se/ue,.5*Se/pe,1])}return be[2]=V,be[5]=b.x,be[8]=b.y,be},o.du=ZR,o.dv=x_,o.dw=function(b,m,x){const k=v(new Float64Array(16)),T=(m/(1<0&&++this._updateTime,this._activeRegions=[],this._prevRegions=[]}get updateTime(){return this._updateTime}getReplacementRegionsForTile(b,m=!1){const x=GDe(new Es(0,0),new Es(Bn,Bn),b),k=[];if(m&&!Abe(x,this._globalClipBounds))return k;for(const T of this._activeRegions){if(T.hiddenByOverlap||!Abe(x,T))continue;const P=I4t(T.min,T.max,b);k.push({min:P.min,max:P.max,sourceId:this._sourceIds[T.priority],footprint:T.footprint,footprintTileId:T.tileId,order:T.order,clipMask:T.clipMask,clipScope:T.clipScope})}return k}setSources(b){this._setSources(b.map(m=>({getSourceId:()=>m.cache.id,getFootprints:()=>{const x=[];for(const k of m.cache.getVisibleCoordinates()){const T=m.cache.getTile(k).buckets[m.layer];T&&T.updateFootprints(k.toUnwrapped(),x)}return x},getOrder:()=>m.order,getClipMask:()=>m.clipMask,getClipScope:()=>m.clipScope})))}_addSource(b){const m=b.getFootprints();if(m.length===0)return;const x=b.getOrder(),k=b.getClipMask(),T=b.getClipScope();for(const P of m){if(!P.footprint)continue;const R=GDe(P.footprint.min,P.footprint.max,P.id);this._activeRegions.push({min:R.min,max:R.max,hiddenByOverlap:!1,priority:this._sourceIds.length,tileId:P.id,footprint:P.footprint,order:x,clipMask:k,clipScope:T})}this._sourceIds.push(b.getSourceId())}_computeReplacement(){this._activeRegions.sort((m,x)=>m.priority-x.priority||pq(m.min,x.min)||pq(m.max,x.max)||m.order-x.order||m.clipMask-x.clipMask||function(k,T){const P=(R,U)=>R+U;return k.length-T.length||k.reduce(P,"").localeCompare(T.reduce(P,""))}(m.clipScope,x.clipScope));let b=this._activeRegions.length!==this._prevRegions.length;if(!b){let m=0;for(;!b&&m!==this._activeRegions.length;){const x=this._activeRegions[m],k=this._prevRegions[m];b=x.priority!==k.priority||!HDe(x,k)||x.order!==k.order||x.clipMask!==k.clipMask||!mi(x.clipScope,k.clipScope),this._activeRegions[m].hiddenByOverlap=k.hiddenByOverlap,++m}}if(b){++this._updateTime;for(const x of this._activeRegions)x.order!==aO&&(this._globalClipBounds.min.x=Math.min(this._globalClipBounds.min.x,x.min.x),this._globalClipBounds.min.y=Math.min(this._globalClipBounds.min.y,x.min.y),this._globalClipBounds.max.x=Math.max(this._globalClipBounds.max.x,x.max.x),this._globalClipBounds.max.y=Math.max(this._globalClipBounds.max.y,x.max.y));const m=x=>{const k=this._activeRegions;if(x>=k.length)return x;const T=k[x].priority;for(;x1){let x=0,k=m(x);for(;x!==k;){let T=x;const P=x;for(;T!==k;){const R=this._activeRegions[T];R.hiddenByOverlap=!1;for(let U=0;U=0;m--)this._addSource(b[m]);this._computeReplacement()}},o.eH=ni,o.eI=Wq,o.eJ=Uj,o.eK=aO,o.eL=class{constructor(b){this._createGrid(b),this._createPoles(b)}destroy(){this._poleIndexBuffer.destroy(),this._gridBuffer.destroy(),this._gridIndexBuffer.destroy(),this._poleNorthVertexBuffer.destroy(),this._poleSouthVertexBuffer.destroy();for(const b of this._poleSegments)b.destroy();for(const b of this._gridSegments)b.withSkirts.destroy(),b.withoutSkirts.destroy()}_fillGridMeshWithLods(b,m){const x=new qa,k=new tc,T=[],P=b+1+2,R=m[0]+1,U=m[0]+1+(1+m.length),V=(X,ie,ue)=>{let pe=X===P-1?X-2:X===0?X:X-1;return pe+=ue?24575:0,[pe,ie]};for(let X=0;X>>=0,b=Math.imul(2747636419^b,2654435769)>>>0,b=Math.imul(b^b>>>16,2654435769)>>>0,(b=Math.imul(b^b>>>16,2654435769)>>>0)/4294967296},o.ec=rDe,o.ed=mbe,o.ee=gg,o.ef=O,o.eg=function(b,m){return b[0]=m[0],b[1]=m[1],b[2]=m[2],b[3]=m[4],b[4]=m[5],b[5]=m[6],b[6]=m[8],b[7]=m[9],b[8]=m[10],b},o.eh=Bj,o.ei=DC,o.ej=function(b,m,x,k,T){return Qe((b-m)/(x-m)*(T-k)+k,k,T)},o.ek=Yt,o.el=function(b,m){var x=m[0],k=m[1],T=m[2],P=m[3],R=m[4],U=m[5],V=m[6],X=m[7],ie=m[8],ue=ie*R-U*X,pe=-ie*P+U*V,be=X*P-R*V,Se=x*ue+k*pe+T*be;return Se?(b[0]=ue*(Se=1/Se),b[1]=(-ie*k+T*X)*Se,b[2]=(U*k-T*R)*Se,b[3]=pe*Se,b[4]=(ie*x-T*V)*Se,b[5]=(-U*x+T*P)*Se,b[6]=be*Se,b[7]=(-X*x+k*V)*Se,b[8]=(R*x-k*P)*Se,b):null},o.em=bC,o.en=2,o.eo=Pe,o.ep=_t,o.eq=z,o.er=function(b,m){var x=new d(3);z(x,m);var k=1/x[0],T=1/x[1],P=1/x[2],R=m[0]*k,U=m[1]*T,V=m[2]*P,X=m[4]*k,ie=m[5]*T,ue=m[6]*P,pe=m[8]*k,be=m[9]*T,Se=m[10]*P,Le=R+ie+Se,ze=0;return Le>0?(ze=2*Math.sqrt(Le+1),b[3]=.25*ze,b[0]=(ue-be)/ze,b[1]=(pe-V)/ze,b[2]=(U-X)/ze):R>ie&&R>Se?(ze=2*Math.sqrt(1+R-ie-Se),b[3]=(ue-be)/ze,b[0]=.25*ze,b[1]=(U+X)/ze,b[2]=(pe+V)/ze):ie>Se?(ze=2*Math.sqrt(1+ie-R-Se),b[3]=(pe-V)/ze,b[0]=(U+X)/ze,b[1]=.25*ze,b[2]=(ue+be)/ze):(ze=2*Math.sqrt(1+Se-R-ie),b[3]=(U-X)/ze,b[0]=(pe+V)/ze,b[1]=(ue+be)/ze,b[2]=.25*ze),b},o.es=function(b,m){var x=2*Math.acos(m[3]),k=Math.sin(x/2);return k>c?(b[0]=m[0]/k,b[1]=m[1]/k,b[2]=m[2]/k):(b[0]=1,b[1]=0,b[2]=0),x},o.et=E_e,o.eu=Tq,o.ev=Cq,o.ew=[1,1,1],o.ex=K6,o.ey=function(b,m,x,k){var T=m[0],P=m[1],R=m[2],U=m[3];return b[0]=T+k*(x[0]-T),b[1]=P+k*(x[1]-P),b[2]=R+k*(x[2]-R),b[3]=U+k*(x[3]-U),b},o.ez=B6,o.f=tl,o.f0=dDe,o.f1=function(b){const m=[0,0,0],x=v(new Float64Array(16));return w(x,b.pixelMatrix,b.globeMatrix),Je(m,m,x),new Es(m[0],m[1])},o.f2=w0,o.f3=function(b,m,x=!1){if(Hd===bm.deferred||Hd===bm.loading||Hd===bm.loaded)throw new Error("setRTLTextPlugin cannot be called multiple times.");qp=$d.resolveURL(b),Hd=bm.deferred,Of=m,KN(),x||w6()},o.f4=so,o.f5=La,o.f6=Nn,o.f7=function(b){const m=ux();if(!m)return;const x=m.delete(hm);b&&x.then(()=>b()).catch(b)},o.f8=Kn,o.f9=ik,o.fA=pa,o.fB=function(b){let m=0;if(new Uint32Array(b,0,1)[0]!==NRe){const x=new Uint32Array(b,0,7),[,,k,T,P,R]=x;m=x.byteLength+T+P+R+P,(k!==b.byteLength||m>=b.byteLength)&&Yn("Invalid b3dm header information.")}return TRe(b,m)},o.fC=function(b,m){const x=Kbe(b);for(const k of x){for(const T of k.meshes)cCt(T);k.lights&&(k.lightMeshIndex=k.meshes.length,k.meshes.push(dCt(k.lights,m)))}return x},o.fD=Qq,o.fE=xa,o.fF=_m,o.fG=bm,o.fH=function(b){mo(),mh!=null&&mh.then(m=>{m.keys().then(x=>{for(let k=0;kYn(T.message))}).catch(x=>Yn(x.message))}).catch(m=>Yn(m.message))},o.fa=2,o.fb=ug,o.fc=YC,o.fd=qR,o.fe=pFe,o.ff=fFe,o.fg=qRe,o.fh=Ra,o.fi="hd_road_elevation",o.fj=zo,o.fk=Vs,o.fl=hq,o.fm=Wj,o.fn=u_e,o.fo=1,o.fp=T1,o.fq=function(b,m,x,k,T,P,R,U=1,V,X,ie,ue){b.createArrays(),b.tilePixelRatio=Bn/(512*b.overscaling),b.compareText={},b.iconsNeedLinear=!1;const pe=b.layers[0].layout,be=b.layers[0]._unevaluatedLayout._values,Se={};Se.scaleFactor=U,Se.textSizeScaleRange=pe.get("text-size-scale-range"),Se.iconSizeScaleRange=pe.get("icon-size-scale-range");const[Le,ze]=Se.textSizeScaleRange,[We,ct]=Se.iconSizeScaleRange;Se.textScaleFactor=Qe(Se.scaleFactor,Le,ze),Se.iconScaleFactor=Qe(Se.scaleFactor,We,ct);const nt=be["text-size"],ft=be["icon-size"];if(b.textSizeData.kind==="composite"){const{minZoom:Ut,maxZoom:qt}=b.textSizeData;Se.compositeTextSizes=[nt.possiblyEvaluate(new Aa(Ut,{worldview:ie}),P),nt.possiblyEvaluate(new Aa(qt,{worldview:ie}),P)]}if(b.iconSizeData.kind==="composite"){const{minZoom:Ut,maxZoom:qt}=b.iconSizeData;Se.compositeIconSizes=[ft.possiblyEvaluate(new Aa(Ut,{worldview:ie}),P,ue),ft.possiblyEvaluate(new Aa(qt,{worldview:ie}),P,ue)]}Se.layoutTextSize=nt.possiblyEvaluate(new Aa(R+1,{worldview:ie}),P),Se.layoutIconSize=ft.possiblyEvaluate(new Aa(R+1,{worldview:ie}),P,ue),Se.textMaxSize=nt.possiblyEvaluate(new Aa(18,{worldview:ie}),P);const wt=pe.get("symbol-placement"),Nt=pe.get("text-rotation-alignment")==="map"&&wt!=="point",Wt=pe.get("text-size");let Ft=!1;const Gt=[];for(const Ut of b.features){const qt=pe.get("text-font").evaluate(Ut,{},P).join(","),zs=Wt.evaluate(Ut,{},P)*Se.textScaleFactor,qs=Se.layoutTextSize.evaluate(Ut,{},P)*Se.textScaleFactor,Xs=Se.layoutIconSize.evaluate(Ut,{},P,ue)*Se.iconScaleFactor,sn={horizontal:{},vertical:void 0},Js=Ut.text;let fn,Os=[0,0];if(Js){const Ga=Js.toString(),Ol=pe.get("text-letter-spacing").evaluate(Ut,{},P)*Kd,Qi=pe.get("text-line-height").evaluate(Ut,{},P)*Kd,Ii=v6(Ga)?Ol:0,Ro=pe.get("text-anchor").evaluate(Ut,{},P),Ml=pe.get("text-variable-anchor");if(!Ml){const nc=pe.get("text-radial-offset").evaluate(Ut,{},P);if(nc)Os=TOe(Ro,[nc*Kd,f_e]);else{const yh=pe.get("text-offset").evaluate(Ut,{},P);Os=[yh[0]*Kd,yh[1]*Kd]}}let Yd=Nt?"center":pe.get("text-justify").evaluate(Ut,{},P);const Il=wt==="point",sc=Il?pe.get("text-max-width").evaluate(Ut,{},P)*Kd:1/0,Oc=nc=>{b.allowVerticalPlacement&&Uh(Ga)&&(sn.vertical=r_e(Js,m,x,T,qt,sc,Qi,Ro,nc,Ii,Os,Ex.vertical,!0,qs,zs,V,Se.textScaleFactor))};if(!Nt&&Ml){const nc=Yd==="auto"?Ml.map(Zd=>x_e(Zd)):[Yd];let yh=!1;for(let Zd=0;Zd=0||!Uh(Ga)){const nc=r_e(Js,m,x,T,qt,sc,Qi,Ro,Yd,Ii,Os,Ex.horizontal,!1,qs,zs,V,Se.textScaleFactor);nc&&(sn.horizontal[Yd]=nc)}Oc(Il?"left":Yd)}}let en,on,gn,Cn,ar,Fn,Rn=!1;const Tn=pe.get("icon-text-fit").evaluate(Ut,{},P);if(Ut.icon&&Ut.icon.hasPrimary()){const Ga=bO(Ut.icon,b.iconSizeData,be["icon-size"],P,b.zoom,Ut,V,Se.iconScaleFactor,ie,ue);en=Ga.iconPrimary,gn=Ga.iconSecondary;const Ol=en.toString();if(on=k.get(Ol),on&&(ar=pe.get("icon-offset").evaluate(Ut,{},P),Fn=pe.get("icon-anchor").evaluate(Ut,{},P),fn=Lq(T.get(Ol),gn?T.get(gn.toString()):void 0,ar,Fn),Rn=on.sdf,b.sdfIcons===void 0?b.sdfIcons=on.sdf:b.sdfIcons!==on.sdf&&Yn("Style sheet warning: Cannot mix SDF and non-SDF icons in one buffer"),(on.pixelRatio!==b.pixelRatio||pe.get("icon-rotate").constantOr(1)!==0)&&(b.iconsNeedLinear=!0)),gn){const Qi=gn.toString();Cn=k.get(Qi)}}Ft=Ft||!(!Ut.icon||!Ut.icon.hasSecondary());const sr=$q(sn.horizontal)||sn.vertical;b.iconsInText||(b.iconsInText=!!sr&&sr.iconsInText);const hr=qs*Se.textScaleFactor/Kd,{defaultShapedIcon:Ur,verticallyShapedIcon:jr}=b3t(b,fn,pe,Ut,P,sn,hr,ar,Tn);Tn!=="none"&&fn&&(dOe(fn)||uOe(fn))&&(Bq(0,on,en,fn,Ur,Tn,X,k,T),Bq(0,Cn,gn,fn,Ur,Tn,X,k,T),jr&&(Bq(0,on,en,fn,jr,Tn,X,k,T),Bq(0,Cn,gn,fn,jr,Tn,X,k,T))),fn=Ur;const{iconBBox:Sa,iconVerticalBBox:_i,textBBox:Ca,textVerticalBBox:Ni}=f3t(b,fn,jr,pe,Ut,P,Xs,ar,Se,T,Fn,sn,qs,Os,ue);Gt.push({feature:Ut,shapedTextOrientations:sn,shapedText:sr,shapedIcon:fn,iconPrimary:en,iconSecondary:gn,iconOffset:ar,iconAnchor:Fn,verticallyShapedIcon:jr,layoutTextSize:qs,layoutIconSize:Xs,textOffset:Os,isSDFIcon:Rn,iconTextFit:Tn,iconCollisionBounds:Sa,iconVerticalCollisionBounds:_i,textCollisionBounds:Ca,textVerticalCollisionBounds:Ni})}return{featureData:Gt,sizes:Se,hasAnySecondaryIcon:Ft,textAlongLine:Nt,symbolPlacement:wt}},o.fr=h_e,o.fs=d_e,o.ft=bOe,o.fu=_Oe,o.fv=function(b,m,x,k,T,P,R,U,V,X){b.iconAtlasPositions=X.iconPositions;const{featureData:ie,hasAnySecondaryIcon:ue,sizes:pe,textAlongLine:be,symbolPlacement:Se}=m;for(const Le of ie){const{shapedIcon:ze,verticallyShapedIcon:We,feature:ct,shapedTextOrientations:nt,shapedText:ft,layoutTextSize:wt,textOffset:Nt,isSDFIcon:Wt,iconPrimary:Ft,iconSecondary:Gt,iconTextFit:Ut,iconOffset:qt,iconCollisionBounds:zs,iconVerticalCollisionBounds:qs,textCollisionBounds:Xs}=Le;IOe(ze,X.iconPositions,Ft,Gt),IOe(We,X.iconPositions,Ft,Gt),v3t(nt,X.iconPositions),y3t(Ft,Gt,X.iconPositions),(ft||ze)&&_3t(b,ct,nt,ze,We,V,pe,wt,0,Nt,Wt,k,T,R,U,ue,Ut,qt,be,Se,zs,qs,Xs)}x&&b.generateCollisionDebugBuffers(P,b.collisionBoxArray,pe.textScaleFactor)},o.fw=Mq,o.fx=Fi,o.fy=function(b){return b<=1?1:Math.pow(2,Math.floor(Math.log2(b)))},o.fz=nV,o.g=aa,o.h=function(b,m){return My(Object.assign(b,{method:"GET"}),m)},o.i=function(b){return aa.API_STYLE_REGEX.test(b)&&!jl(b)},o.j=function(b){return btoa(encodeURIComponent(b).replace(/%([0-9A-F]{2})/g,(m,x)=>String.fromCharCode(+("0x"+x))))},o.k=mm,o.l=function(b){return decodeURIComponent(atob(b).split("").map(m=>"%"+("00"+m.charCodeAt(0).toString(16)).slice(-2)).join(""))},o.m=function(b,m){return My(Object.assign(b,{type:"json"}),m)},o.n=mx,o.o=$d,o.p=function(b,m){return My(Object.assign(b,{method:"POST"}),m)},o.q=Vh,o.r=fs,o.s=function(b){try{const m=self[b];return m.setItem("_mapbox_test_",1),m.removeItem("_mapbox_test_"),!0}catch{return!1}},o.t=Bt,o.u=function(){return function b(m){return m?(m^Math.random()*(16>>m/4)).toString(16):([1e7]+-[1e3]+-4e3+-8e3+-1e11).replace(/[018]/g,b)}()},o.v=function(b){return!!b&&/^[0-9a-f]{8}-[0-9a-f]{4}-[4][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(b)},o.w=Yn,o.x=class{constructor(b){this.cache=new Map,this.textures=new Map,this.textureAccessTimes=new Map,this.textureMemoryUsed=0,this.maxTextureMemory=1024*(b&&b.maxTextureMemoryMB?b.maxTextureMemoryMB:256)*1024,this.finalizationRegistry=new FinalizationRegistry(m=>{this.cache.delete(m),this.clearExpiredTextures()})}calculateTextureMemory(b){return b.image?Math.ceil(b.image.width*b.image.height*4*(b.patternPositions.size>0?1.33:1)):0}evictTexture(b){const m=this.textures.get(b);if(m){const x=this.calculateTextureMemory(b);m.destroy(),this.textures.delete(b),this.textureAccessTimes.delete(b),this.textureMemoryUsed-=x}}evictTexturesIfNeeded(b){for(;this.textureMemoryUsed+b>this.maxTextureMemory&&this.textures.size>0;){let m=null,x=1/0;for(const[k]of this.textures.entries()){const T=this.textureAccessTimes.get(k)||0;Tthis._layers[mn.id]),fs=Vt[0];if(fs.visibility==="none")continue;const lt=fs.source||"";let ns=this.familiesBySource[lt];ns||(ns=this.familiesBySource[lt]=Object.create(null));const Vs=fs.sourceLayer||"_geojsonTileLayer";let ys=ns[Vs];ys||(ys=ns[Vs]=[]),ys.push(Vt)}}}const y=1*c.fa;class _{constructor(Fe){const Qe={},ot=[];for(const fs in Fe){const lt=Fe[fs],ns=Qe[fs]={};for(const Vs in lt.glyphs){const ys=lt.glyphs[+Vs];if(!ys||ys.bitmap.width===0||ys.bitmap.height===0)continue;const mn=ys.metrics.localGlyph?y:1,On={x:0,y:0,w:ys.bitmap.width+2*mn,h:ys.bitmap.height+2*mn};ot.push(On),ns[Vs]=On}}const{w:St,h:Bt}=c.J(ot),Vt=new c.f9({width:St||1,height:Bt||1});for(const fs in Fe){const lt=Fe[fs];for(const ns in lt.glyphs){const Vs=lt.glyphs[+ns];if(!Vs||Vs.bitmap.width===0||Vs.bitmap.height===0)continue;const ys=Qe[fs][ns],mn=Vs.metrics.localGlyph?y:1;c.f9.copy(Vs.bitmap,Vt,{x:0,y:0},{x:ys.x+mn,y:ys.y+mn},Vs.bitmap)}}this.image=Vt,this.positions=Qe}}function v(ts,Fe,Qe){ts[Fe]?Qe&&(ts[Fe].center=Qe):ts[Fe]={floorIds:new Set,center:Qe||[0,0],floors:{}}}function j(ts,Fe,Qe,ot){for(const St of Fe)v(ts,St),ts[St].floors[Qe]=ot,ts[St].floorIds.add(Qe)}function w(ts){return{id:ts.properties.id.toString(),center:[ts.properties.center_lon||0,ts.properties.center_lat||0]}}function S(ts,Fe){const Qe=ts.properties.id.toString(),ot=!!ts.properties.is_default&&ts.properties.is_default,St=ts.properties.connected_floor_ids?new Set(ts.properties.connected_floor_ids.toString().split(";")):new Set,Bt=ts.properties.conflicted_floor_ids?new Set(ts.properties.conflicted_floor_ids.toString().split(";")):new Set,Vt=ts.properties.structure_ids?new Set(ts.properties.structure_ids.toString().split(";")):new Set,fs=ts.properties.name.toString(),lt=ts.properties.z_index,ns=function(Vs,ys){const mn=Vs.loadGeometry();if(!mn||mn.length===0)return;const On=mn.map(vn=>vn.map(Yn=>c.fb(Yn,ys,Vs.extent)));return On.length===0?void 0:{type:"Polygon",coordinates:[On[0]]}}(ts,Fe);return{id:Qe,isDefault:ot,connections:St,conflicts:Bt,buildings:Vt,name:fs,zIndex:lt,geometry:ns}}function A(ts,Fe){return Fe.every(Qe=>ts.properties&&ts.properties[Qe]!=null)}function E(ts){return A(ts,["type","id","name"])&&ts.properties.type==="structure"}function O(ts){return A(ts,["type","id","name","z_index"])&&ts.properties.type==="floor"}c.f8(_,"GlyphAtlas");class D{constructor(Fe){this.tileID=new c.aR(Fe.tileID.overscaledZ,Fe.tileID.wrap,Fe.tileID.canonical.z,Fe.tileID.canonical.x,Fe.tileID.canonical.y),this.tileZoom=Fe.tileZoom,this.uid=Fe.uid,this.zoom=Fe.zoom,this.lut=Fe.lut,this.canonical=Fe.tileID.canonical,this.pixelRatio=Fe.pixelRatio,this.tileSize=Fe.tileSize,this.source=Fe.source,this.scope=Fe.scope,this.overscaling=this.tileID.overscaleFactor(),this.showCollisionBoxes=Fe.showCollisionBoxes,this.collectResourceTiming=!!Fe.request&&Fe.request.collectResourceTiming,this.promoteId=Fe.promoteId,this.renderSourceType=Fe.renderSourceType,this.tileTransform=c.fc(Fe.tileID.canonical,Fe.projection),this.projection=Fe.projection,this.worldview=Fe.worldview,this.localizableLayerIds=Fe.localizableLayerIds,this.brightness=Fe.brightness,this.extraShadowCaster=!!Fe.extraShadowCaster,this.tessellationStep=Fe.tessellationStep,this.scaleFactor=Fe.scaleFactor,this.worldview=Fe.worldview,this.indoor=Fe.indoor}parse(Fe,Qe,ot,St,Bt,Vt){this.status="parsing",this.data=Fe,this.collisionBoxArray=new c.fd;const fs=new c.fe(Object.keys(Fe.layers).sort()),lt=new c.ff(this.tileID,this.promoteId);lt.bucketLayerIDs=[];const ns={},Vs=new c.fg(256,256),ys={featureIndex:lt,iconDependencies:new Map,patternDependencies:new Map,glyphDependencies:{},lineAtlas:Vs,availableImages:ot,brightness:this.brightness,scaleFactor:this.scaleFactor,elevationFeatures:void 0,activeFloors:void 0};this.indoor&&(ys.activeFloors=function(Yn,_r,wr,Er){const xa=_r.indoorState.activeFloorsVisible;if(!_r.sourceLayers)return xa?_r.indoorState.activeFloors:void 0;const Ki=function(Mr,qi){if(!Mr)return c.w("No source layers defined in indoor specification"),qi;if(Mr.size===0)return qi;const Vi=Mr.difference(qi);for(const si of Vi)c.w(`Missing source layer required in indoor specification: ${si}`);return qi.intersection(qi)}(_r.sourceLayers,new Set(Object.keys(Yn.layers))),io=_r.indoorState,Xa=function(Mr,qi,Vi,si,Yi){const Zi={};for(const aa of qi){const Nn=Mr.layers[aa];if(Nn)for(let La=0;La=si.maxzoom||si.visibility==="none")continue;I(Vi,this.zoom,ys.brightness,ot,this.worldview,ys.activeFloors);const Yi=ns[si.id]=si.createBucket({index:lt.bucketLayerIDs.length,layers:Vi,zoom:this.zoom,lut:this.lut,canonical:this.canonical,pixelRatio:this.pixelRatio,overscaling:this.overscaling,collisionBoxArray:this.collisionBoxArray,sourceLayerIndex:io,sourceID:this.source,projection:this.projection.spec,tessellationStep:this.tessellationStep,styleDefinedModelURLs:St,worldview:this.worldview,localizable:Mr,availableImages:ot,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO});lt.bucketLayerIDs.push(Vi.map(aa=>c.F(aa.id,aa.scope)));let Zi=Yi.prepare?Yi.prepare():null;Zi!=null?(Zi=Zi.then(()=>Yi.populate(Xa,ys,this.tileID.canonical,this.tileTransform)),mn.push(Zi)):Yi.populate(Xa,ys,this.tileID.canonical,this.tileTransform)}}const vn=()=>{Vs.trim();const Yn=!(!ys.elevationFeatures||!ys.elevationFeatures.some(si=>si.heightRange.min<0));let _r,wr,Er,xa,Ki,io,Xa;const Mr={type:"maybePrepare",renderSourceType:this.renderSourceType,zoom:this.zoom},qi=()=>{if(_r)return this.status="done",Vt(_r);if(this.extraShadowCaster)this.status="done",Vt(null,{buckets:Object.values(ns).filter(si=>!si.isEmpty()),featureIndex:lt,collisionBoxArray:null,hasTunnelGeometry:Yn,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:ys.brightness,glyphMap:null,iconMap:null,glyphPositions:null});else if(wr&&Er&&xa&&Xa){const Yi=new _(wr),Zi=new Map;for(const[La,so]of Er.entries()){const{imagePosition:tl}=c.fn(La,so,c.fo);Zi.set(La,tl)}const aa={};for(const La in ns){const so=ns[La];so instanceof c.fp&&(I(so.layers,this.zoom,ys.brightness,ot,this.worldview,ys.activeFloors),aa[La]=c.fq(so,wr,Yi.positions,Er,Zi,this.tileID.canonical,this.tileZoom,this.scaleFactor,this.pixelRatio,Ki,this.worldview,ot))}const Nn={iconsPending:!0,patternsPending:!0};this.rasterizeIfNeeded(Bt,Er,Ki,()=>{Nn.iconsPending=!1,Vi(aa,Yi,Nn,void 0,Xa)}),this.rasterizeIfNeeded(Bt,xa,io,()=>{Nn.patternsPending=!1,Vi(aa,Yi,Nn,void 0,Xa)})}},Vi=(si,Yi,Zi,aa,Nn)=>{if(Zi.iconsPending||Zi.patternsPending)return;const La=Er.size>0||xa.size>0,so=Object.keys(si).length>0;if(!La&&!so)return this.status="done",void Vt(null,{buckets:Object.values(ns).filter(jl=>!jl.isEmpty()),featureIndex:lt,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Yn,glyphAtlasImage:Yi.image,lineAtlas:Vs,imageAtlas:null,brightness:ys.brightness});const tl=(jl,No)=>{for(const jd in ns){const Bu=ns[jd];if(jd in si)c.fv(Bu,si[jd],this.showCollisionBoxes,ot,this.tileID.canonical,this.tileZoom,this.projection,this.brightness,Er,No);else if(Bu.hasPattern&&(Bu instanceof c.fw||Bu instanceof c.fl||Bu instanceof c.e0)){I(Bu.layers,this.zoom,ys.brightness,ot,this.worldview,ys.activeFloors);const kf=Object.fromEntries(No.patternPositions);Bu.addFeatures(ys,this.tileID.canonical,kf,ot,this.tileTransform,this.brightness)}}this.status="done",Vt(null,{buckets:Object.values(ns).filter(jd=>!jd.isEmpty()),featureIndex:lt,collisionBoxArray:this.collisionBoxArray,hasTunnelGeometry:Yn,glyphAtlasImage:Yi.image,lineAtlas:Vs,imageAtlas:jl,brightness:ys.brightness})};if(La){const jl=new Map,No=c.fr(Er,jl),jd=c.fr(xa,jl),Bu=new c.fs(No,jd,Nn,this.lut,jl);Bt.send("checkAtlasCache",{descriptor:Bu,scope:this.scope},(kf,$u)=>{let um,Uu;if(kf&&c.w(`[Worker] Error checking atlas cache: ${kf.message}`),$u)um=new c.ft($u.sourceHash),Uu=$u;else{const $d=new c.fu(Er,xa,this.lut,Nn);um=$d,Uu=$d}tl(um,Uu)})}else tl(null,{iconPositions:new Map,patternPositions:new Map})};if(!this.extraShadowCaster){const si=c.fk(ys.glyphDependencies,aa=>Object.keys(aa).map(Number));Object.keys(si).length?Bt.send("getGlyphs",{uid:this.uid,stacks:si},(aa,Nn)=>{_r||(_r=aa,wr=Nn,qi())},void 0,!1,Mr):wr={},Xa=new Map;const Yi=Array.from(ys.iconDependencies.keys()).map(aa=>c.I.parse(aa));Yi.length?Bt.send("getImages",{images:Yi,source:this.source,scope:this.scope,tileID:this.tileID,type:"icons"},(aa,Nn)=>{if(!_r){_r=aa,Er=new Map,Ki=this.updateImageMapAndGetImageTaskQueue(Er,Nn.images,ys.iconDependencies);for(const[La,so]of Nn.versions.entries())Xa.set(La,so);qi()}},void 0,!1,Mr):(Er=new Map,Ki=new Map);const Zi=Array.from(ys.patternDependencies.keys()).map(aa=>c.I.parse(aa));Zi.length?Bt.send("getImages",{images:Zi,source:this.source,scope:this.scope,tileID:this.tileID,type:"patterns"},(aa,Nn)=>{if(!_r){_r=aa,xa=new Map,io=this.updateImageMapAndGetImageTaskQueue(xa,Nn.images,ys.patternDependencies);for(const[La,so]of Nn.versions.entries())Xa.set(La,so);qi()}},void 0,!1,Mr):(xa=new Map,io=new Map)}if(ys.elevationFeatures&&ys.elevationFeatures.length>0){const si=[];for(const Zi of Object.values(ns))if(Zi instanceof c.fl){const aa=Zi.getUnevaluatedPortalGraph();aa&&si.push(aa)}const Yi=c.fm.evaluate(si);for(const Zi of Object.values(ns))if(Zi instanceof c.fl){const aa=Fe.layers[fs.decode(Zi.sourceLayerIndex)];Zi.setEvaluatedPortalGraph(Yi,aa,this.tileID.canonical,ys.availableImages,ys.brightness)}}qi()};mn.length>0?Promise.allSettled(mn).then(vn).catch(Vt):vn()}updateParameters(Fe){this.scaleFactor=Fe.scaleFactor,this.showCollisionBoxes=Fe.showCollisionBoxes,this.projection=Fe.projection,this.brightness=Fe.brightness,this.tileTransform=c.fc(Fe.tileID.canonical,Fe.projection),this.extraShadowCaster=Fe.extraShadowCaster,this.lut=Fe.lut,this.worldview=Fe.worldview,this.indoor=Fe.indoor}rasterizeIfNeeded(Fe,Qe,ot,St){Array.from(Qe.values()).some(Bt=>Bt.usvg)?this.rasterize(Fe,Qe,ot,St):St()}updateImageMapAndGetImageTaskQueue(Fe,Qe,ot){const St=new Map;for(const Bt of Qe.keys()){const Vt=ot.get(Bt)||[];for(const fs of Vt){const lt=fs.toString(),ns=Qe.get(fs.id.toString());ns.usvg?St.has(lt)||(St.set(lt,fs),Fe.set(lt,Object.assign({},ns))):Fe.set(lt,ns)}}return St}rasterize(Fe,Qe,ot,St){this.rasterizeTask=Fe.send("rasterizeImages",{scope:this.scope,tasks:ot},(Bt,Vt)=>{if(!Bt)for(const[fs,lt]of Vt.entries()){const ns=Object.assign(Qe.get(fs),{data:lt});Qe.set(fs,ns)}St()})}cancelRasterize(){this.rasterizeTask&&this.rasterizeTask.cancel()}}function I(ts,Fe,Qe,ot,St,Bt){const Vt=new c.ae(Fe,{brightness:Qe,worldview:St,activeFloors:Bt});for(const fs of ts)fs.recalculate(Vt,ot)}class F extends c.E{constructor({actor:Fe,layerIndex:Qe,availableImages:ot,availableModels:St,isSpriteLoaded:Bt,tileProvider:Vt,brightness:fs,maxUniformBufferBindings:lt,maxUniformBlockSizeDwords:ns,disableSymbolUBO:Vs}){super(),this.actor=Fe,this.layerIndex=Qe,this.availableImages=ot,this.availableModels=St,this.loadVectorData=c.aO,this.tileProvider=Vt,this.loading={},this.loaded={},this.deduped=new c.aN(Fe.scheduler),this.isSpriteLoaded=Bt,this.scheduler=Fe.scheduler,this.brightness=fs,this.maxUniformBufferBindings=lt,this.maxUniformBlockSizeDwords=ns,this.disableSymbolUBO=Vs}loadTileData(Fe,Qe){if(!this.tileProvider)return this.loadVectorData(Fe,Qe);const ot=new AbortController,{z:St,x:Bt,y:Vt}=Fe.tileID.canonical;return this.tileProvider.loadTile({z:St,x:Bt,y:Vt},{request:Fe.request,signal:ot.signal}).then(fs=>{if(ot.signal.aborted)return;if(fs==null){const ns=new Error("Tile not found");return ns.status=404,Qe(ns)}if(fs.data===null)return Qe(null,null);const lt=new Map;fs.expires&<.set("expires",fs.expires),fs.cacheControl&<.set("cache-control",fs.cacheControl),Qe(null,{rawData:fs.data,responseHeaders:lt})}).catch(fs=>{ot.signal.aborted||Qe(fs instanceof Error?fs:new Error(String(fs)))}),()=>ot.abort()}loadTile(Fe,Qe){const ot=Fe.uid,St=Fe&&Fe.request,Bt=St&&St.collectResourceTiming,Vt=this.loading[ot]=new D(Fe);Vt.maxUniformBufferBindings=this.maxUniformBufferBindings,Vt.maxUniformBlockSizeDwords=this.maxUniformBlockSizeDwords,Vt.disableSymbolUBO=this.disableSymbolUBO,Vt.abort=this.loadTileData(Fe,(fs,lt)=>{const ns=!this.loading[ot];if(delete this.loading[ot],Vt.cancelRasterize(),ns||fs||!lt)return Vt.status="done",ns||(this.loaded[ot]=Vt),Qe(fs);const Vs=lt.rawData,ys={},mn=c.aP(lt.responseHeaders);mn&&mn.expires&&(ys.expires=mn.expires),mn&&mn.cacheControl&&(ys.cacheControl=mn.cacheControl),Vt.vectorTile=lt.vectorTile||new c.fx(new c.a$(Vs));const On=()=>{Vt.parse(Vt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,(vn,Yn)=>{if(vn||!Yn)return Qe(vn);const _r={};if(Bt){const wr=d(St);wr.length>0&&(_r.resourceTiming=JSON.parse(JSON.stringify(wr)))}Qe(null,Object.assign({rawTileData:Vs.slice(0),responseHeaders:lt.responseHeaders},Yn,ys,_r))})};this.isSpriteLoaded?On():this.once("isSpriteLoaded",()=>{this.scheduler?this.scheduler.add(On,{type:"parseTile",renderSourceType:Fe.renderSourceType,zoom:Fe.tileZoom}):On()}),this.loaded=this.loaded||{},this.loaded[ot]=Vt})}reloadTile(Fe,Qe){const ot=this.loaded,St=Fe.uid;if(ot&&ot[St]){const Bt=ot[St];Bt.updateParameters(Fe);const Vt=(fs,lt)=>{const ns=Bt.reloadCallback;ns&&(delete Bt.reloadCallback,Bt.parse(Bt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,ns)),Qe(fs,lt)};Bt.status==="parsing"?Bt.reloadCallback=Vt:Bt.status==="done"&&(Bt.vectorTile?Bt.parse(Bt.vectorTile,this.layerIndex,this.availableImages,this.availableModels,this.actor,Vt):Vt())}else Qe(null,void 0)}abortTile(Fe,Qe){const ot=Fe.uid,St=this.loading[ot];St&&(St.abort&&St.abort(),delete this.loading[ot]),Qe()}removeTile(Fe,Qe){const ot=this.loaded,St=Fe.uid;ot&&ot[St]&&delete ot[St],Qe()}}class z{constructor(Fe){this.loading={}}loadTile(Fe,Qe){const ot=Fe.uid,{cancel:St}=c.b1(Fe.request,(Bt,Vt,fs)=>{const lt=!this.loading[ot];if(delete this.loading[ot],lt||Bt||!Vt)return Qe(Bt);this.decodeTile(ot,Vt,Fe.encoding).then(ns=>{const{expires:Vs,cacheControl:ys}=c.aP(fs);Qe(null,Object.assign(ns,{expires:Vs,cacheControl:ys}))}).catch(ns=>Qe(ns))});this.loading[ot]={cancel:St}}async decodeTile(Fe,Qe,ot){const St=await createImageBitmap(new Blob([new Uint8Array(Qe)],{type:"image/png"})),Bt=1-(St.width-c.fy(St.width))/2,Vt=Bt<1,fs=this.getImageData(St,Bt);return St.close(),{dem:new c.fz(Fe,fs,ot,Vt),borderReady:Vt}}reloadTile(Fe,Qe){Qe(null,null)}abortTile(Fe,Qe){const ot=Fe.uid,St=this.loading[ot];St&&(St.cancel(),delete this.loading[ot]),Qe()}removeTile(Fe,Qe){Qe()}getImageData(Fe,Qe){this.offscreenCanvas&&this.offscreenCanvasContext||(this.offscreenCanvas=new OffscreenCanvas(Fe.width,Fe.height),this.offscreenCanvasContext=this.offscreenCanvas.getContext("2d",{willReadFrequently:!0})),this.offscreenCanvas.width=Fe.width,this.offscreenCanvas.height=Fe.height,this.offscreenCanvasContext.drawImage(Fe,0,0,Fe.width,Fe.height);const ot=this.offscreenCanvasContext.getImageData(-Qe,-Qe,Fe.width+2*Qe,Fe.height+2*Qe);return this.offscreenCanvasContext.clearRect(0,0,this.offscreenCanvas.width,this.offscreenCanvas.height),ot}}c.a_.setPbf(c.a$);class H{constructor(Fe){this._mrt=new c.a_(Fe.partial?30:1/0),this._isHeaderLoaded=!1,this.uid=Fe.uid,this.tileID=Fe.tileID,this.source=Fe.source}parse(Fe,Qe){const ot=this._mrt;this.status="parsing",this._entireBuffer=Fe;try{ot.parseHeader(Fe),this._isHeaderLoaded=!0;const St=[];for(const Bt in ot.layers){const Vt=ot.getLayer(Bt),fs=Vt.getDataRange(Vt.getBandList()),lt=ot.createDecodingTask(fs),ns=Fe.slice(fs.firstByte,fs.lastByte+1),Vs=c.a_.performDecoding(ns,lt).then(ys=>lt.complete(null,ys)).catch(ys=>lt.complete(ys,null));St.push(Vs)}Promise.allSettled(St).then(()=>Qe(null,ot)).catch(Bt=>Qe(Bt))}catch(St){Qe(St)}}}class Z{constructor({actor:Fe}){this.actor=Fe,this.loading={},this.loaded={}}loadTile(Fe,Qe){const ot=Fe.uid,St=Fe.request,Bt=this.loading[ot]=new H(Fe),{cancel:Vt}=c.b1(St,(fs,lt,ns)=>{const Vs=!this.loading[ot];if(delete this.loading[ot],Vs||fs||!lt)return Bt.status="done",Vs||(this.loaded[ot]=Bt),Qe(fs);Bt.parse(lt,(ys,mn)=>{if(ys||!mn)return Qe(ys);Qe(null,mn,ns)}),this.loaded[ot]=Bt});Bt.abort=Vt}reloadTile(Fe,Qe){Qe(null,void 0)}abortTile(Fe,Qe){const ot=Fe.uid,St=this.loading[ot];St&&(St.abort&&St.abort(),delete this.loading[ot]),Qe()}removeTile(Fe,Qe){const ot=Fe.uid;this.loaded[ot]&&delete this.loaded[ot],Qe()}decodeRasterArray(Fe,Qe){c.a_.performDecoding(Fe.buffer,Fe.task).then(ot=>Qe(null,ot)).catch(ot=>Qe(ot))}}const Y=c.fA.prototype.toGeoJSON;class W{constructor(Fe){this._feature=Fe,this.extent=c.an,this.type=Fe.type,this.properties=Fe.tags,"id"in Fe&&!isNaN(Fe.id)&&(this.id=parseInt(Fe.id,10))}loadGeometry(){if(this._feature.type===1){const Fe=[];for(const Qe of this._feature.geometry)Fe.push([new c.P(Qe[0],Qe[1])]);return Fe}{const Fe=[];for(const Qe of this._feature.geometry){const ot=[];for(const St of Qe)ot.push(new c.P(St[0],St[1]));Fe.push(ot)}return Fe}}toGeoJSON(Fe,Qe,ot){return Y.call(this,Fe,Qe,ot)}}class ee{constructor(Fe,Qe){this.name=Fe,this.extent=c.an,this.length=Qe.length,this._jsonFeatures=Qe}feature(Fe){return new W(this._jsonFeatures[Fe])}}class se{constructor(Fe){this.layers={},this.extent=c.an;for(const Qe of Object.keys(Fe))this.layers[Qe]=new ee(Qe,Fe[Qe])}}const oe=64/4096;class he{constructor(){this.features=new Map}clear(){this.features.clear()}load(Fe=[],Qe){for(const ot of Fe){const St=ot.id;if(St==null)continue;let Bt=this.features.get(St);Bt&&this.updateCache(Bt,Qe),ot.geometry?(Bt=me(ot),this.updateCache(Bt,Qe),this.features.set(St,Bt)):this.features.delete(St),this.updateCache(Bt,Qe)}}updateCache(Fe,Qe){for(const{canonical:ot,uid:St}of Object.values(Qe)){const{z:Bt,x:Vt,y:fs}=ot;ce(Fe,Math.pow(2,Bt),Vt,fs)&&delete Qe[St]}}getTile(Fe,Qe,ot){const St=Math.pow(2,Fe),Bt=[];for(const Vt of this.features.values())ce(Vt,St,Qe,ot)&&Bt.push(Te(Vt,St,Qe,ot));return{features:Bt}}getFeatures(){return[...this.features.values()]}}function ce({minX:ts,minY:Fe,maxX:Qe,maxY:ot},St,Bt,Vt){return ts<(Bt+1+oe)/St&&Fe<(Vt+1+oe)/St&&Qe>(Bt-oe)/St&&ot>(Vt-oe)/St}function me(ts){const{id:Fe,geometry:Qe,properties:ot}=ts;if(!Qe)return;if(Qe.type==="GeometryCollection")throw new Error("GeometryCollection not supported in dynamic mode.");const{type:St,coordinates:Bt}=Qe,Vt={id:Fe,type:1,geometry:[],tags:ot,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0},fs=Vt.geometry;if(St==="Point")le(Bt,fs,Vt);else if(St==="MultiPoint")for(const lt of Bt)le(lt,fs,Vt);else if(St==="LineString")Vt.type=2,ve(Bt,fs,Vt);else if(St==="MultiLineString")Vt.type=2,ge(Bt,fs,Vt);else if(St==="Polygon")Vt.type=3,ge(Bt,fs,Vt,!0);else{if(St!=="MultiPolygon")throw new Error("Input data is not a valid GeoJSON object.");Vt.type=3;for(const lt of Bt)ge(lt,fs,Vt,!0)}return Vt}function le([ts,Fe],Qe,ot){const St=c.aH(ts);let Bt=c.aL(Fe);Bt=Bt<0?0:Bt>1?1:Bt,Qe.push(St,Bt),ot.minX=Math.min(ot.minX,St),ot.minY=Math.min(ot.minY,Bt),ot.maxX=Math.max(ot.maxX,St),ot.maxY=Math.max(ot.maxY,Bt)}function ve(ts,Fe,Qe,ot=!1,St=!1){const Bt=[];for(const Vt of ts)le(Vt,Bt,Qe);Fe.push(Bt),ot&&function(Vt,fs){let lt=0;for(let ns=0,Vs=Vt.length,ys=Vs-2;ns0===fs)for(let ns=0,Vs=Vt.length;ns=Vt&&ys>=Vt||(ns>=Vt?(Vs+=Math.round(vn*((Vt-ns)/On)),ns=Vt):ys>=Vt&&(mn=Vs+Math.round(vn*((Vt-ns)/On)),ys=Vt),Vs>=Vt&&mn>=Vt||(Vs>=Vt?(ns+=Math.round(On*((Vt-Vs)/vn)),Vs=Vt):mn>=Vt&&(ys=ns+Math.round(On*((Vt-Vs)/vn)),mn=Vt),fs&&ns===fs[fs.length-1][0]&&Vs===fs[fs.length-1][1]||(fs=[[ns,Vs]],St.push(fs)),fs.push([ys,mn])))))}}function Ce(ts,Fe,Qe,ot,St){const Bt=(Qe-oe)/Fe,Vt=(ot-oe)/Fe,fs=(Qe+1+oe)/Fe,lt=(ot+1+oe)/Fe;function ns(mn,On){let vn=0;return mnfs&&(vn|=2),Onlt&&(vn|=8),vn}let Vs=[];for(let mn=1;mn<=8;mn*=2){let On=ts[ts.length-2],vn=ts[ts.length-1],Yn=!(ns(On,vn)&mn);for(let _r=0;_r>31}function we(ts,Fe){const{geometry:Qe,type:ot}=ts;let St=0,Bt=0;if(ot===1){Fe.writeVarint(Ae(1,Qe.length));for(const Vt of Qe){const fs=Vt[0]-St,lt=Vt[1]-Bt;Fe.writeVarint(Be(fs)),Fe.writeVarint(Be(lt)),St+=fs,Bt+=lt}}else for(const Vt of Qe){if(Vt.length===0)continue;Fe.writeVarint(Ae(1,1));const fs=Vt.length-(ot===3?1:0);for(let lt=0;ltts},it=Math.fround||(je=new Float32Array(1),ts=>(je[0]=+ts,je[0]));var je;class He{constructor(Fe){this.options=Object.assign(Object.create(ke),Fe),this.trees=new Array(this.options.maxZoom+1),this.stride=this.options.reduce?7:6,this.clusterProps=[]}load(Fe){const{log:Qe,minZoom:ot,maxZoom:St}=this.options;Qe&&console.time("total time");const Bt=`prepare ${Fe.length} points`;Qe&&console.time(Bt),this.points=Fe;const Vt=[];for(let lt=0;lt=ot;lt--){const ns=+Date.now();fs=this.trees[lt]=this._createTree(this._cluster(fs,lt)),Qe&&console.log("z%d: %d clusters in %dms",lt,fs.numItems,+Date.now()-ns)}return Qe&&console.timeEnd("total time"),this}getClusters(Fe,Qe){let ot=((Fe[0]+180)%360+360)%360-180;const St=Math.max(-90,Math.min(90,Fe[1]));let Bt=Fe[2]===180?180:((Fe[2]+180)%360+360)%360-180;const Vt=Math.max(-90,Math.min(90,Fe[3]));if(Fe[2]-Fe[0]>=360)ot=-180,Bt=180;else if(ot>Bt){const ys=this.getClusters([ot,St,180,Vt],Qe),mn=this.getClusters([-180,St,Bt,Vt],Qe);return ys.concat(mn)}const fs=this.trees[this._limitZoom(Qe)],lt=fs.range(Ge(ot),rt(Vt),Ge(Bt),rt(St)),ns=fs.data,Vs=[];for(const ys of lt){const mn=this.stride*ys;Vs.push(ns[mn+5]>1?$e(ns,mn,this.clusterProps):this.points[ns[mn+3]])}return Vs}getChildren(Fe){const Qe=this._getOriginId(Fe),ot=this._getOriginZoom(Fe),St="No cluster with the specified id.",Bt=this.trees[ot];if(!Bt)throw new Error(St);const Vt=Bt.data;if(Qe*this.stride>=Vt.length)throw new Error(St);const fs=this.options.radius/(this.options.extent*Math.pow(2,ot-1)),lt=Bt.within(Vt[Qe*this.stride],Vt[Qe*this.stride+1],fs),ns=[];for(const Vs of lt){const ys=Vs*this.stride;Vt[ys+4]===Fe&&ns.push(Vt[ys+5]>1?$e(Vt,ys,this.clusterProps):this.points[Vt[ys+3]])}if(ns.length===0)throw new Error(St);return ns}getLeaves(Fe,Qe,ot){const St=[];return this._appendLeaves(St,Fe,Qe=Qe||10,ot=ot||0,0),St}getTile(Fe,Qe,ot){const St=this.trees[this._limitZoom(Fe)],Bt=Math.pow(2,Fe),{extent:Vt,radius:fs}=this.options,lt=fs/Vt,ns=(ot-lt)/Bt,Vs=(ot+1+lt)/Bt,ys={features:[]};return this._addTileFeatures(St.range((Qe-lt)/Bt,ns,(Qe+1+lt)/Bt,Vs),St.data,Qe,ot,Bt,ys),Qe===0&&this._addTileFeatures(St.range(1-lt/Bt,ns,1,Vs),St.data,Bt,ot,Bt,ys),Qe===Bt-1&&this._addTileFeatures(St.range(0,ns,lt/Bt,Vs),St.data,-1,ot,Bt,ys),ys.features.length?ys:null}getClusterExpansionZoom(Fe){let Qe=this._getOriginZoom(Fe)-1;for(;Qe<=this.options.maxZoom;){const ot=this.getChildren(Fe);if(Qe++,ot.length!==1)break;Fe=ot[0].properties.cluster_id}return Qe}_appendLeaves(Fe,Qe,ot,St,Bt){const Vt=this.getChildren(Qe);for(const fs of Vt){const lt=fs.properties;if(lt&<.cluster?Bt+lt.point_count<=St?Bt+=lt.point_count:Bt=this._appendLeaves(Fe,lt.cluster_id,ot,St,Bt):Bt1;let Vs,ys,mn;if(ns)Vs=Ke(Qe,lt,this.clusterProps),ys=Qe[lt],mn=Qe[lt+1];else{const Yn=this.points[Qe[lt+3]];Vs=Yn.properties;const[_r,wr]=Yn.geometry.coordinates;ys=Ge(_r),mn=rt(wr)}const On={type:1,geometry:[[Math.round(this.options.extent*(ys*Bt-ot)),Math.round(this.options.extent*(mn*Bt-St))]],tags:Vs};let vn;vn=ns||this.options.generateId?Qe[lt+3]:this.points[Qe[lt+3]].id,vn!==void 0&&(On.id=vn),Vt.features.push(On)}}_limitZoom(Fe){return Math.max(this.options.minZoom,Math.min(Math.floor(+Fe),this.options.maxZoom+1))}_cluster(Fe,Qe){const{radius:ot,extent:St,reduce:Bt,minPoints:Vt}=this.options,fs=ot/(St*Math.pow(2,Qe)),lt=Fe.data,ns=[],Vs=this.stride;for(let ys=0;ysQe&&(_r+=lt[Er+5])}if(_r>Yn&&_r>=Vt){let wr,Er=mn*Yn,xa=On*Yn,Ki=-1;const io=(ys/Vs<<5)+(Qe+1)+this.points.length;for(const Xa of vn){const Mr=Xa*Vs;if(lt[Mr+2]<=Qe)continue;lt[Mr+2]=Qe;const qi=lt[Mr+5];Er+=lt[Mr]*qi,xa+=lt[Mr+1]*qi,lt[Mr+4]=io,Bt&&(wr||(wr=this._map(lt,ys,!0),Ki=this.clusterProps.length,this.clusterProps.push(wr)),Bt(wr,this._map(lt,Mr)))}lt[ys+4]=io,ns.push(Er/_r,xa/_r,1/0,io,-1,_r),Bt&&ns.push(Ki)}else{for(let wr=0;wr1)for(const wr of vn){const Er=wr*Vs;if(!(lt[Er+2]<=Qe)){lt[Er+2]=Qe;for(let xa=0;xa>5}_getOriginZoom(Fe){return(Fe-this.points.length)%32}_map(Fe,Qe,ot){if(Fe[Qe+5]>1){const Vt=this.clusterProps[Fe[Qe+6]];return ot?Object.assign({},Vt):Vt}const St=this.points[Fe[Qe+3]].properties,Bt=this.options.map(St);return ot&&Bt===St?Object.assign({},Bt):Bt}}function $e(ts,Fe,Qe){return{type:"Feature",id:ts[Fe+3],properties:Ke(ts,Fe,Qe),geometry:{type:"Point",coordinates:[(ot=ts[Fe],360*(ot-.5)),tt(ts[Fe+1])]}};var ot}function Ke(ts,Fe,Qe){const ot=ts[Fe+5],St=ot>=1e4?`${Math.round(ot/1e3)}k`:ot>=1e3?Math.round(ot/100)/10+"k":ot,Bt=ts[Fe+6],Vt=Bt===-1?{}:Object.assign({},Qe[Bt]);return Object.assign(Vt,{cluster:!0,cluster_id:ts[Fe+3],point_count:ot,point_count_abbreviated:St})}function Ge(ts){return ts/360+.5}function rt(ts){const Fe=Math.sin(ts*Math.PI/180),Qe=.5-.25*Math.log((1+Fe)/(1-Fe))/Math.PI;return Qe<0?0:Qe>1?1:Qe}function tt(ts){const Fe=(180-360*ts)*Math.PI/180;return 360*Math.atan(Math.exp(Fe))/Math.PI-90}function at(ts,Fe,Qe,ot){let St=ot;const Bt=Fe+(Qe-Fe>>1);let Vt,fs=Qe-Fe;const lt=ts[Fe],ns=ts[Fe+1],Vs=ts[Qe],ys=ts[Qe+1];for(let mn=Fe+3;mnSt)Vt=mn,St=On;else if(On===St){const vn=Math.abs(mn-Bt);vnot&&(Vt-Fe>3&&at(ts,Fe,Vt,ot),ts[Vt+2]=St,Qe-Vt>3&&at(ts,Vt,Qe,ot))}function Ye(ts,Fe,Qe,ot,St,Bt){let Vt=St-Qe,fs=Bt-ot;if(Vt!==0||fs!==0){const lt=((ts-Qe)*Vt+(Fe-ot)*fs)/(Vt*Vt+fs*fs);lt>1?(Qe=St,ot=Bt):lt>0&&(Qe+=Vt*lt,ot+=fs*lt)}return Vt=ts-Qe,fs=Fe-ot,Vt*Vt+fs*fs}function ut(ts,Fe,Qe,ot){const St={id:ts??null,type:Fe,geometry:Qe,tags:ot,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if(Fe==="Point"||Fe==="MultiPoint"||Fe==="LineString")_t(St,Qe);else if(Fe==="Polygon")_t(St,Qe[0]);else if(Fe==="MultiLineString")for(const Bt of Qe)_t(St,Bt);else if(Fe==="MultiPolygon")for(const Bt of Qe)_t(St,Bt[0]);return St}function _t(ts,Fe){for(let Qe=0;Qe0&&(Vt+=ot?(St*Vs-ns*Bt)/2:Math.sqrt(Math.pow(ns-St,2)+Math.pow(Vs-Bt,2))),St=ns,Bt=Vs}const fs=Fe.length-3;Fe[2]=1,at(Fe,0,fs,Qe),Fe[fs+2]=1,Fe.size=Math.abs(Vt),Fe.start=0,Fe.end=Fe.size}function Ds(ts,Fe,Qe,ot){for(let St=0;St1?1:Qe}function Lt(ts,Fe,Qe,ot,St,Bt,Vt,fs){if(ot/=Fe,Bt>=(Qe/=Fe)&&Vt=ot)return null;const lt=[];for(const ns of ts){const Vs=ns.geometry;let ys=ns.type;const mn=St===0?ns.minX:ns.minY,On=St===0?ns.maxX:ns.maxY;if(mn>=Qe&&On=ot)continue;let vn=[];if(ys==="Point"||ys==="MultiPoint")Jt(Vs,vn,Qe,ot,St);else if(ys==="LineString")gt(Vs,vn,Qe,ot,St,!1,fs.lineMetrics);else if(ys==="MultiLineString")As(Vs,vn,Qe,ot,St,!1);else if(ys==="Polygon")As(Vs,vn,Qe,ot,St,!0);else if(ys==="MultiPolygon")for(const Yn of Vs){const _r=[];As(Yn,_r,Qe,ot,St,!0),_r.length&&vn.push(_r)}if(vn.length){if(fs.lineMetrics&&ys==="LineString"){for(const Yn of vn)lt.push(ut(ns.id,ys,Yn,ns.tags));continue}ys!=="LineString"&&ys!=="MultiLineString"||(vn.length===1?(ys="LineString",vn=vn[0]):ys="MultiLineString"),ys!=="Point"&&ys!=="MultiPoint"||(ys=vn.length===3?"Point":"MultiPoint"),lt.push(ut(ns.id,ys,vn,ns.tags))}}return lt.length?lt:null}function Jt(ts,Fe,Qe,ot,St){for(let Bt=0;Bt=Qe&&Vt<=ot&&Xt(Fe,ts[Bt],ts[Bt+1],ts[Bt+2])}}function gt(ts,Fe,Qe,ot,St,Bt,Vt){let fs=zt(ts);const lt=St===0?Qs:ks;let ns,Vs,ys=ts.start;for(let _r=0;_rQe&&(Vs=lt(fs,wr,Er,Ki,io,Qe),Vt&&(fs.start=ys+ns*Vs)):Xa>ot?Mr=Qe&&(Vs=lt(fs,wr,Er,Ki,io,Qe),qi=!0),Mr>ot&&Xa<=ot&&(Vs=lt(fs,wr,Er,Ki,io,ot),qi=!0),!Bt&&qi&&(Vt&&(fs.end=ys+ns*Vs),Fe.push(fs),fs=zt(ts)),Vt&&(ys+=ns)}let mn=ts.length-3;const On=ts[mn],vn=ts[mn+1],Yn=St===0?On:vn;Yn>=Qe&&Yn<=ot&&Xt(fs,On,vn,ts[mn+2]),mn=fs.length-3,Bt&&mn>=3&&(fs[mn]!==fs[0]||fs[mn+1]!==fs[1])&&Xt(fs,fs[0],fs[1],fs[2]),fs.length&&Fe.push(fs)}function zt(ts){const Fe=[];return Fe.size=ts.size,Fe.start=ts.start,Fe.end=ts.end,Fe}function As(ts,Fe,Qe,ot,St,Bt){for(const Vt of ts)gt(Vt,Fe,Qe,ot,St,Bt,!1)}function Xt(ts,Fe,Qe,ot){ts.push(Fe,Qe,ot)}function Qs(ts,Fe,Qe,ot,St,Bt){const Vt=(Bt-Fe)/(ot-Fe);return Xt(ts,Bt,Qe+(St-Qe)*Vt,1),Vt}function ks(ts,Fe,Qe,ot,St,Bt){const Vt=(Bt-Qe)/(St-Qe);return Xt(ts,Fe+(ot-Fe)*Vt,Bt,1),Vt}function $s(ts,Fe){const Qe=[];for(let ot=0;ot0&&Fe.size<(St?Vt:ot))return void(Qe.numPoints+=Fe.length/3);const fs=[];for(let lt=0;ltVt)&&(Qe.numSimplified++,fs.push(Fe[lt],Fe[lt+1])),Qe.numPoints++;St&&function(lt,ns){let Vs=0;for(let ys=0,mn=lt.length,On=mn-2;ys0===ns)for(let ys=0,mn=lt.length;ys24)throw new Error("maxZoom should be in the 0-24 range");if(Qe.promoteId&&Qe.generateId)throw new Error("promoteId and generateId cannot be used together.");let St=function(Bt,Vt){const fs=[];if(Bt.type==="FeatureCollection")for(let lt=0;lt1&&console.time("creation"),On=this.tiles[mn]=xn(Fe,Qe,ot,St,ns),this.tileCoords.push({z:Qe,x:ot,y:St}),Vs)){Vs>1&&(console.log("tile z%d-%d-%d (features: %d, points: %d, simplified: %d)",Qe,ot,St,On.numFeatures,On.numPoints,On.numSimplified),console.timeEnd("creation"));const qi=`z${Qe}`;this.stats[qi]=(this.stats[qi]||0)+1,this.total++}if(On.source=Fe,Bt==null){if(Qe===ns.indexMaxZoom||On.numPoints<=ns.indexMaxPoints)continue}else{if(Qe===ns.maxZoom||Qe===Bt)continue;if(Bt!=null){const qi=Bt-Qe;if(ot!==Vt>>qi||St!==fs>>qi)continue}}if(On.source=null,Fe.length===0)continue;Vs>1&&console.time("clipping");const vn=.5*ns.buffer/ns.extent,Yn=.5-vn,_r=.5+vn,wr=1+vn;let Er=null,xa=null,Ki=null,io=null,Xa=Lt(Fe,ys,ot-vn,ot+_r,0,On.minX,On.maxX,ns),Mr=Lt(Fe,ys,ot+Yn,ot+wr,0,On.minX,On.maxX,ns);Fe=null,Xa&&(Er=Lt(Xa,ys,St-vn,St+_r,1,On.minY,On.maxY,ns),xa=Lt(Xa,ys,St+Yn,St+wr,1,On.minY,On.maxY,ns),Xa=null),Mr&&(Ki=Lt(Mr,ys,St-vn,St+_r,1,On.minY,On.maxY,ns),io=Lt(Mr,ys,St+Yn,St+wr,1,On.minY,On.maxY,ns),Mr=null),Vs>1&&console.timeEnd("clipping"),lt.push(Er||[],Qe+1,2*ot,2*St),lt.push(xa||[],Qe+1,2*ot,2*St+1),lt.push(Ki||[],Qe+1,2*ot+1,2*St),lt.push(io||[],Qe+1,2*ot+1,2*St+1)}}getTile(Fe,Qe,ot){Fe=+Fe,Qe=+Qe,ot=+ot;const St=this.options,{extent:Bt,debug:Vt}=St;if(Fe<0||Fe>24)return null;const fs=1<1&&console.log("drilling down to z%d-%d-%d",Fe,Qe,ot);let ns,Vs=Fe,ys=Qe,mn=ot;for(;!ns&&Vs>0;)Vs--,ys>>=1,mn>>=1,ns=this.tiles[Es(Vs,ys,mn)];return ns&&ns.source?(Vt>1&&(console.log("found parent tile z%d-%d-%d",Vs,ys,mn),console.time("drilling down")),this.splitTile(ns.source,Vs,ys,mn,Fe,Qe,ot),Vt>1&&console.timeEnd("drilling down"),this.tiles[lt]?tn(this.tiles[lt],Bt):null):null}}function Es(ts,Fe,Qe){return 32*((1<ns.tags&&"3d_elevation_id"in ns.tags&&"source"in ns.tags&&ns.tags.source==="elevation",Bt=ot.features.filter(ns=>St(ns));let Vt={_geojsonTileLayer:ot.features};Bt.length>0&&(Vt={_geojsonTileLayer:ot.features.filter(ns=>!St(ns)),hd_road_elevation:Bt});const fs=new se(Vt),lt=function(ns){const Vs=new c.a$;for(const ys of Object.keys(ns))Vs.writeMessage(3,Me,{name:ys,features:ns[ys]});return Vs.finish()}(Vt).buffer;Fe(null,{vectorTile:fs,rawData:lt})}class Ar extends F{constructor(Fe){super(Fe),this.loadVectorData=mi,this._dynamicIndex=new he}loadData(Fe,Qe){const ot=Fe&&Fe.request,St=ot&&ot.collectResourceTiming;this._geoJSONIndex=null,this.loadGeoJSON(Fe,(Bt,Vt)=>{if(Bt||!Vt)return Qe(Bt);if(typeof Vt!="object")return Qe(new Error(`Input data given to '${Fe.source}' is not a valid GeoJSON object.`));{try{if(Fe.filter){const lt=c.X(Fe.filter,{type:"boolean","property-type":"data-driven",overridable:!1,transition:!1});if(lt.result==="error")throw new Error(lt.value.map(ns=>`${ns.key}: ${ns.message}`).join(", "));Vt.features=Vt.features.filter(ns=>lt.value.evaluate({zoom:0},ns))}Fe.dynamic?(Vt.type==="Feature"&&(Vt={type:"FeatureCollection",features:[Vt]}),Fe.append||(this._dynamicIndex.clear(),this.loaded={}),this._dynamicIndex.load(Vt.features,this.loaded),Fe.cluster&&(Vt.features=this._dynamicIndex.getFeatures())):this.loaded={},this._geoJSONIndex=Fe.cluster?new He(function({superclusterOptions:lt,clusterProperties:ns}){if(!ns||!lt)return lt;const Vs={},ys={},mn={accumulated:null,zoom:0},On={properties:null},vn=Object.keys(ns);for(const Yn of vn){const[_r,wr]=ns[Yn],Er=c.X(wr),xa=c.X(typeof _r=="string"?[_r,["accumulated"],["get",Yn]]:_r);Vs[Yn]=Er.value,ys[Yn]=xa.value}return lt.map=Yn=>{On.properties=Yn;const _r={};for(const wr of vn)_r[wr]=Vs[wr].evaluate(mn,On);return _r},lt.reduce=(Yn,_r)=>{On.properties=_r;for(const wr of vn)mn.accumulated=Yn[wr],Yn[wr]=ys[wr].evaluate(mn,On)},lt}(Fe)).load(Vt.features):Fe.dynamic?this._dynamicIndex:function(lt,ns){return new na(lt,ns)}(Vt,Fe.geojsonVtOptions)}catch(lt){return Qe(lt)}const fs={};if(St){const lt=d(ot);lt&&(fs.resourceTiming={},fs.resourceTiming[Fe.source]=JSON.parse(JSON.stringify(lt)))}Qe(null,fs)}})}reloadTile(Fe,Qe){const ot=this.loaded;return ot&&ot[Fe.uid]?Fe.partial?Qe(null,void 0):super.reloadTile(Fe,Qe):this.loadTile(Fe,Qe)}loadGeoJSON(Fe,Qe){if(Fe.request)c.m(Fe.request,Qe);else{if(typeof Fe.data!="string")return Qe(new Error(`Input data given to '${Fe.source}' is not a valid GeoJSON object.`));setTimeout(()=>{try{return Qe(null,JSON.parse(Fe.data))}catch{return Qe(new Error(`Input data given to '${Fe.source}' is not a valid GeoJSON object.`))}},0)}}getClusterExpansionZoom(Fe,Qe){try{Qe(null,this._geoJSONIndex.getClusterExpansionZoom(Fe.clusterId))}catch(ot){Qe(ot)}}getClusterChildren(Fe,Qe){try{Qe(null,this._geoJSONIndex.getChildren(Fe.clusterId))}catch(ot){Qe(ot)}}getClusterLeaves(Fe,Qe){try{Qe(null,this._geoJSONIndex.getLeaves(Fe.clusterId,Fe.limit,Fe.offset))}catch(ot){Qe(ot)}}}class Hn{constructor(Fe,Qe,ot){this.tileID=new c.aR(Fe.tileID.overscaledZ,Fe.tileID.wrap,Fe.tileID.canonical.z,Fe.tileID.canonical.x,Fe.tileID.canonical.y),this.tileZoom=Fe.tileZoom,this.uid=Fe.uid,this.zoom=Fe.zoom,this.canonical=Fe.tileID.canonical,this.pixelRatio=Fe.pixelRatio,this.tileSize=Fe.tileSize,this.source=Fe.source,this.overscaling=this.tileID.overscaleFactor(),this.projection=Fe.projection,this.brightness=Qe,this.worldview=ot}parse(Fe,Qe,ot,St){this.status="parsing";const Bt=new c.aR(ot.tileID.overscaledZ,ot.tileID.wrap,ot.tileID.canonical.z,ot.tileID.canonical.x,ot.tileID.canonical.y),Vt=[],fs=Qe.familiesBySource[ot.source],lt=new c.ff(Bt,ot.promoteId);lt.bucketLayerIDs=[],lt.is3DTile=!0,c.fB(Fe).then(ns=>{const Vs=ns.json.extensionsUsed&&ns.json.extensionsUsed.includes("MAPBOX_mesh_features")||ns.json.asset.extras&&ns.json.asset.extras.MAPBOX_mesh_features,ys=ns.json.extensionsUsed&&ns.json.extensionsUsed.includes("EXT_meshopt_compression"),mn=new c.ae(this.zoom,{brightness:this.brightness,worldview:this.worldview});for(const On in fs)for(const vn of fs[On]){const Yn=vn[0];lt.bucketLayerIDs.push(vn.map(Er=>c.F(Er.id,Er.scope))),Yn.recalculate(mn,[]);const _r=c.fC(ns,1/c.cS(ot.tileID.canonical)),wr=new c.fD(vn,_r,Bt,Vs,ys,this.brightness,lt,this.worldview);Vs||(wr.needsUpload=!0),Vt.push(wr),wr.evaluate(Yn)}this.status="done",St(null,{buckets:Vt,featureIndex:lt,collisionBoxArray:null,glyphAtlasImage:null,lineAtlas:null,imageAtlas:null,brightness:null})}).catch(ns=>St(new Error(ns.message)))}}class Ts{constructor({actor:Fe,layerIndex:Qe,availableImages:ot,availableModels:St,brightness:Bt,worldview:Vt}){this.actor=Fe,this.layerIndex=Qe,this.availableImages=ot,this.availableModels=St,this.brightness=Bt,this.loading={},this.loaded={},this.worldview=Vt}loadTile(Fe,Qe){const ot=Fe.uid,St=this.loading[ot]=new Hn(Fe,this.brightness,this.worldview);c.b1(Fe.request,(Bt,Vt)=>{const fs=!this.loading[ot];return delete this.loading[ot],fs||Bt?(St.status="done",fs||(this.loaded[ot]=St),Qe(Bt)):Vt&&Vt.byteLength!==0?void St.parse(Vt,this.layerIndex,Fe,(lt,ns)=>{St.status="done",this.loaded=this.loaded||{},this.loaded[ot]=St,lt||!ns?Qe(lt):Qe(null,ns)}):(St.status="done",this.loaded[ot]=St,Qe())})}reloadTile(Fe,Qe){const ot=this.loaded,St=Fe.uid;if(ot&&ot[St]){const Bt=ot[St];Bt.projection=Fe.projection,Bt.brightness=Fe.brightness;const Vt=(fs,lt)=>{Bt.reloadCallback&&(delete Bt.reloadCallback,this.loadTile(Fe,Qe)),Qe(fs,lt)};Bt.status==="parsing"?Bt.reloadCallback=Vt:Bt.status==="done"&&this.loadTile(Fe,Qe)}}abortTile(Fe,Qe){const ot=Fe.uid;this.loading[ot]&&delete this.loading[ot],Qe()}removeTile(Fe,Qe){const ot=this.loaded,St=Fe.uid;ot&&ot[St]&&delete ot[St],Qe()}}const Un=new Map,ir=new Map;class Tr{constructor(Fe){this.self=Fe,this.actor=new c.A(Fe,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:Ar,"raster-dem":z,"raster-array":Z,"batched-model":Ts},this.workerSources={},this.self.registerWorkerSource=(Qe,ot)=>{if(this.workerSourceTypes[Qe])throw new Error(`Worker source with name "${Qe}" already registered.`);this.workerSourceTypes[Qe]=ot},this.self.registerRTLTextPlugin=Qe=>{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=Qe.applyArabicShaping,c.fF.processBidirectionalText=Qe.processBidirectionalText,c.fF.processStyledBidirectionalText=Qe.processStyledBidirectionalText;for(const ot of this.rtlPluginParsingListeners)ot(null,!0);this.rtlPluginParsingListeners=[]}}clearCaches(Fe,Qe,ot){delete this.layerIndexes[Fe],delete this.availableImages[Fe],delete this.availableModels[Fe],delete this.workerSources[Fe],ot()}checkIfReady(Fe,Qe,ot){ot()}setReferrer(Fe,Qe){this.referrer=Qe}spriteLoaded(Fe,Qe){this.isSpriteLoaded[Fe]||(this.isSpriteLoaded[Fe]={});const{scope:ot,isLoaded:St}=Qe;if(this.isSpriteLoaded[Fe][ot]=St,this.workerSources[Fe]&&this.workerSources[Fe][ot])for(const Bt in this.workerSources[Fe][ot]){const Vt=this.workerSources[Fe][ot][Bt];for(const fs in Vt){const lt=Vt[fs];lt instanceof F&&(lt.isSpriteLoaded=St,lt.fire(new c.C("isSpriteLoaded")))}}}setImages(Fe,Qe,ot){this.availableImages[Fe]||(this.availableImages[Fe]={});const{scope:St,images:Bt}=Qe;if(this.availableImages[Fe][St]=Bt,this.workerSources[Fe]&&this.workerSources[Fe][St]){for(const Vt in this.workerSources[Fe][St]){const fs=this.workerSources[Fe][St][Vt];for(const lt in fs)fs[lt].availableImages=Bt}ot()}else ot()}setModels(Fe,{scope:Qe,models:ot},St){if(this.availableModels[Fe]||(this.availableModels[Fe]={}),this.availableModels[Fe][Qe]=ot,this.workerSources[Fe]&&this.workerSources[Fe][Qe]){for(const Bt in this.workerSources[Fe][Qe]){const Vt=this.workerSources[Fe][Qe][Bt];for(const fs in Vt)Vt[fs].availableModels=ot}St()}else St()}setProjection(Fe,Qe){this.projections[Fe]=c.c0(Qe)}setBrightness(Fe,Qe,ot){this.brightness=Qe,ot()}setContextParams(Fe,Qe,ot){this.maxUniformBufferBindings=Qe.maxBindingPoints,this.maxUniformBlockSizeDwords=Qe.maxUniformBlockSizeDwords,this.disableSymbolUBO=Qe.disableSymbolUBO,ot()}setWorldview(Fe,Qe,ot){this.worldview=Qe,ot()}setLayers(Fe,Qe,ot){this.getLayerIndex(Fe,Qe.scope).replace(Qe.layers,Qe.options),ot()}updateLayers(Fe,Qe,ot){this.getLayerIndex(Fe,Qe.scope).update(Qe.layers,Qe.removedIds,Qe.options),ot()}loadTile(Fe,Qe,ot){Qe.projection=this.projections[Fe]||this.defaultProjection,this.getWorkerSource(Fe,Qe).loadTile(Qe,ot)}decodeRasterArray(Fe,Qe,ot){this.getWorkerSource(Fe,Qe).decodeRasterArray(Qe,ot)}reloadTile(Fe,Qe,ot){Qe.projection=this.projections[Fe]||this.defaultProjection,this.getWorkerSource(Fe,Qe).reloadTile(Qe,ot)}abortTile(Fe,Qe,ot){this.getWorkerSource(Fe,Qe).abortTile(Qe,ot)}removeTile(Fe,Qe,ot){this.getWorkerSource(Fe,Qe).removeTile(Qe,ot)}removeSource(Fe,Qe,ot){if(!(this.workerSources[Fe]&&this.workerSources[Fe][Qe.scope]&&this.workerSources[Fe][Qe.scope][Qe.type]&&this.workerSources[Fe][Qe.scope][Qe.type][Qe.source]))return;const St=this.workerSources[Fe][Qe.scope][Qe.type][Qe.source];delete this.workerSources[Fe][Qe.scope][Qe.type][Qe.source],St.removeSource!==void 0?St.removeSource(Qe,ot):ot()}loadTileProvider(Fe,Qe,ot){(async function(St,Bt){const Vt=ir.get(St);if(Vt)return Vt;const fs=Un.get(St);if(fs!==void 0)return fs;const lt=import(Bt).then(ns=>{const Vs=ns.default;if(typeof Vs!="function")throw new Error(`TileProvider "${St}" module must default-export a class`);if(typeof Vs.prototype.loadTile!="function")throw new Error(`TileProvider "${St}" class must have a loadTile method`);return ir.set(St,Vs),Vs}).finally(()=>{Un.delete(St)});return Un.set(St,lt),lt})(Qe.name,Qe.url).then(St=>{const Bt=new St(Qe.options);return this.getWorkerSource(Fe,{type:Qe.type,source:Qe.source,scope:Qe.scope},Bt),Bt.load&&Qe.request?Bt.load({request:Qe.request}):null}).then(St=>ot(null,St)).catch(St=>ot(St instanceof Error?St:new Error(typeof St=="string"?St:"Unknown error")))}loadWorkerSource(Fe,Qe,ot){try{this.self.importScripts(Qe.url),ot()}catch(St){ot(St)}}syncRTLPluginState(Fe,Qe,ot){if(c.fF.isParsed())ot(null,!0);else if(c.fF.isParsing())this.rtlPluginParsingListeners.push(ot);else try{c.fF.setState(Qe);const St=c.fF.getPluginURL();!c.fF.isLoaded()||c.fF.isParsed()||c.fF.isParsing()||St==null||(c.fF.setState({pluginStatus:c.fG.parsing,pluginURL:c.fF.getPluginURL()}),this.self.importScripts(St),c.fF.isParsed()?ot(null,!0):this.rtlPluginParsingListeners.push(ot))}catch(St){ot(St)}}setConfig(Fe,Qe){Object.assign(c.g,Qe)}getAvailableImages(Fe,Qe){this.availableImages[Fe]||(this.availableImages[Fe]={});let ot=this.availableImages[Fe][Qe];return ot||(ot=[]),ot}getAvailableModels(Fe,Qe){this.availableModels[Fe]||(this.availableModels[Fe]={});let ot=this.availableModels[Fe][Qe];return ot||(ot={}),ot}getLayerIndex(Fe,Qe){this.layerIndexes[Fe]||(this.layerIndexes[Fe]={});let ot=this.layerIndexes[Fe][Qe];return ot||(ot=this.layerIndexes[Fe][Qe]=new f,ot.scope=Qe),ot}getWorkerSource(Fe,Qe,ot){const{type:St,source:Bt,scope:Vt}=Qe,fs=this.workerSources;if(fs[Fe]||(fs[Fe]={}),fs[Fe][Vt]||(fs[Fe][Vt]={}),fs[Fe][Vt][St]||(fs[Fe][Vt][St]={}),this.isSpriteLoaded[Fe]||(this.isSpriteLoaded[Fe]={}),!fs[Fe][Vt][St][Bt]){const lt={send:(Vs,ys,mn,On,vn,Yn)=>this.actor.send(Vs,ys,mn,Fe,vn,Yn),scheduler:this.actor.scheduler},ns=this.workerSourceTypes[St];if(!ns)throw new Error(`Unknown worker source type "${St}".`);fs[Fe][Vt][St][Bt]=new ns({actor:lt,layerIndex:this.getLayerIndex(Fe,Vt),availableImages:this.getAvailableImages(Fe,Vt),availableModels:this.getAvailableModels(Fe,Vt),isSpriteLoaded:this.isSpriteLoaded[Fe][Vt],tileProvider:ot,brightness:this.brightness,worldview:this.worldview,maxUniformBufferBindings:this.maxUniformBufferBindings,maxUniformBlockSizeDwords:this.maxUniformBlockSizeDwords,disableSymbolUBO:this.disableSymbolUBO})}return fs[Fe][Vt][St][Bt]}rasterizeImagesWorker(Fe,Qe,ot){const St=new Map;for(const[Bt,{image:Vt,imageVariant:fs}]of Qe.tasks.entries()){const lt=this.imageRasterizer.rasterize(fs,Vt,Qe.scope,Fe);St.set(Bt,lt)}ot(void 0,St)}removeRasterizedImages(Fe,Qe,ot){this.imageRasterizer.removeImagesFromCacheByIds(Qe.imageIds,Qe.scope,Fe),ot()}enforceCacheSizeLimit(Fe,Qe){c.fH(Qe)}getWorkerPerformanceMetrics(Fe,Qe,ot){ot(void 0,void 0)}}return c.fE(self)&&(self.worker=new Tr(self)),Tr}),i(["./shared"],function(o){var c="3.22.0";const d={create:"create",load:"load",fullLoad:"fullLoad"},u={mark(M){performance.mark(M)},measure(M,g,C){performance.measure(M,g,C)}};function h(M){const g=M.name.split("?")[0];return o.a(g)&&g.includes("mapbox-gl.js")?"javascript":o.a(g)&&g.includes("mapbox-gl.css")?"css":o.b(g)?"fontRange":o.c(g)?"sprite":o.i(g)?"style":o.d(g)?"tilejson":"other"}var p,f={},y=function(){if(p)return f;function M(L){return!g(L)}function g(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 G,K,te=new Blob([""],{type:"text/javascript"}),de=URL.createObjectURL(te);try{K=new Worker(de),G=!0}catch{G=!1}return K&&K.terminate(),URL.revokeObjectURL(de),G}()?function(){var G=document.createElement("canvas");G.width=G.height=1;var K=G.getContext("2d");if(!K)return!1;var te=K.getImageData(0,0,1,1);return te&&te.width===G.width}()?(C[$=L&&L.failIfMajorPerformanceCaveat]===void 0&&(C[$]=function(G){var K,te=function(de){var xe=document.createElement("canvas"),_e=Object.create(M.webGLContextAttributes);return _e.failIfMajorPerformanceCaveat=de,xe.getContext("webgl2",_e)}(G);if(!te)return!1;try{K=te.createShader(te.VERTEX_SHADER)}catch{return!1}return!(!K||te.isContextLost())&&(te.shaderSource(K,"void main() {}"),te.compileShader(K),te.getShaderParameter(K,te.COMPILE_STATUS)===!0)}($)),C[$]?document.documentMode?"insufficient ECMAScript 6 support":void 0:"insufficient WebGL2 support"):"insufficient Canvas/getImageData support":"insufficient worker support";var $}p=1,f.supported=M,f.notSupportedReason=g;var C={};return M.webGLContextAttributes={antialias:!1,alpha:!0,stencil:!0,depth:!0},f}();function _(M,g,C){const L=document.createElement(M);return g!=null&&(L.className=g),C&&C.appendChild(L),L}function v(M,g,C){const L=document.createElementNS("http://www.w3.org/2000/svg",M);for(const $ of Object.keys(g))L.setAttributeNS(null,$,String(g[$]));return C&&C.appendChild(L),L}const j=typeof document<"u"?document.documentElement&&document.documentElement.style:null,w=j&&j.userSelect!==void 0?"userSelect":"WebkitUserSelect";let S;function A(){j&&w&&(S=j[w],j[w]="none")}function E(){j&&w&&(j[w]=S)}function O(M){M.preventDefault(),M.stopPropagation(),window.removeEventListener("click",O,!0)}function D(){window.addEventListener("click",O,!0),window.setTimeout(()=>{window.removeEventListener("click",O,!0)},0)}function I(M,g){const C=M.getBoundingClientRect();return H(M,C,g)}function F(M,g){const C=M.getBoundingClientRect(),L=[];for(let $=0;$this._skuTokenExpiresAt}transformRequest(g,C){return this._transformRequestFn&&this._transformRequestFn(g,C)||{url:g}}normalizeStyleURL(g,C){if(!o.e(g))return g;const L=se(g);return L.params.push(`sdk=js-${c}`),L.path=`/styles/v1${L.path}`,this._makeAPIURL(L,this._customAccessToken||C)}normalizeGlyphsURL(g,C){if(!o.e(g))return g;const L=se(g);return L.path=`/fonts/v1${L.path}`,this._makeAPIURL(L,this._customAccessToken||C)}normalizeModelURL(g,C){if(!o.e(g))return g;const L=se(g);return L.path=`/models/v1${L.path}`,this._makeAPIURL(L,this._customAccessToken||C)}normalizeSourceURL(g,C,L,$){if(!o.e(g))return g;const G=se(g);return G.path=`/v4/${G.authority}.json`,G.params.push("secure"),L&&G.params.push(`language=${L}`),$&&G.params.push(`worldview=${$}`),this._makeAPIURL(G,this._customAccessToken||C)}normalizeIconsetURL(g,C){const L=se(g);return o.e(g)?(L.path=`/styles/v1${L.path}/iconset.pbf`,this._makeAPIURL(L,this._customAccessToken||C)):oe(L)}normalizeSpriteURL(g,C,L,$){const G=se(g);return o.e(g)?(G.path=`/styles/v1${G.path}/sprite${C}${L}`,this._makeAPIURL(G,this._customAccessToken||$)):(G.path+=`${C}${L}`,oe(G))}normalizeTileURL(g,C,L){if(this._isSkuTokenExpired()&&this._createSkuToken(),g&&!o.e(g))return g;const $=se(g);$.path=$.path.replace(/(\.(png|jpg)\d*)(?=$)/,`${C||L&&$.authority!=="raster"&&L===512?"@2x":""}${o.k.supported?".webp":"$1"}`),$.authority==="raster"?$.path=`/${o.g.RASTER_URL_PREFIX}${$.path}`:$.authority==="rasterarrays"?$.path=`/${o.g.RASTERARRAYS_URL_PREFIX}${$.path}`:$.authority==="3dtiles"?$.path=`/${o.g.TILES3D_URL_PREFIX}${$.path}`:($.path=$.path.replace(/^.+\/v4\//,"/"),$.path=`/${o.g.TILE_URL_VERSION}${$.path}`);const G=this._customAccessToken||function(K){for(const te of K){const de=te.match(/^access_token=(.*)$/);if(de)return de[1]}return null}($.params)||o.g.ACCESS_TOKEN;return o.g.REQUIRE_ACCESS_TOKEN&&G&&this._skuToken&&$.params.push(`sku=${this._skuToken}`),this._makeAPIURL($,G)}canonicalizeTileURL(g,C){const L=se(g);if(!L.path.match(/^(\/v4\/|\/(raster|rasterarrays)\/v1\/)/)||!L.path.match(/\.[\w]+$/))return g;let $="mapbox://";L.path.match(/^\/raster\/v1\//)?$+=`raster/${L.path.replace(`/${o.g.RASTER_URL_PREFIX}/`,"")}`:L.path.match(/^\/rasterarrays\/v1\//)?$+=`rasterarrays/${L.path.replace(`/${o.g.RASTERARRAYS_URL_PREFIX}/`,"")}`:$+=`tiles/${L.path.replace(`/${o.g.TILE_URL_VERSION}/`,"")}`;let G=L.params;return C&&(G=G.filter(K=>!K.match(/^access_token=/))),G.length&&($+=`?${G.join("&")}`),$}canonicalizeTileset(g,C){const L=!!C&&o.e(C),$=[];for(const G of g.tiles||[])o.f(G)?$.push(this.canonicalizeTileURL(G,L)):$.push(G);return $}_makeAPIURL(g,C){const L="See https://docs.mapbox.com/api/overview/#access-tokens-and-token-scopes",$=se(o.g.API_URL);if(g.protocol=$.protocol,g.authority=$.authority,g.protocol==="http"){const G=g.params.indexOf("secure");G>=0&&g.params.splice(G,1)}if($.path!=="/"&&(g.path=`${$.path}${g.path}`),!o.g.REQUIRE_ACCESS_TOKEN)return oe(g);if(C=C||o.g.ACCESS_TOKEN,!this._silenceAuthErrors){if(!C)throw new Error(`An API access token is required to use Mapbox GL. ${L}`);if(C[0]==="s")throw new Error(`Use a public access token (pk.*) with Mapbox GL, not a secret access token (sk.*). ${L}`)}return g.params=g.params.filter(G=>G.indexOf("access_token")===-1),g.params.push(`access_token=${C||""}`),oe(g)}}const ee=/^(\w+):\/\/([^/?]*)(\/[^?]+)?\??(.+)?/;function se(M){const g=M.match(ee);if(!g)throw new Error("Unable to parse URL object");return{protocol:g[1],authority:g[2],path:g[3]||"/",params:g[4]?g[4].split("&"):[]}}function oe(M){const g=M.params.length?`?${M.params.join("&")}`:"";return`${M.protocol}://${M.authority}${M.path}${g}`}const he="mapbox.eventData";function ce(M){if(!M)return null;const g=M.split(".");if(!g||g.length!==3)return null;try{return JSON.parse(o.l(g[1]))}catch{return null}}function me(M){return!(!o.g.EVENTS_URL||!M&&!o.g.ACCESS_TOKEN)}class le{constructor(g){this.type=g,this.anonId=null,this.anonIdTimestamp=null,this.eventData={},this.queue=[],this.pendingRequest=null}getStorageKey(g){const C=ce(o.g.ACCESS_TOKEN);let L="";return L=C&&C.u?o.j(C.u):o.g.ACCESS_TOKEN||"",g?`${he}.${g}:${L}`:`${he}:${L}`}fetchEventData(){const g=o.s("localStorage"),C=this.getStorageKey(),L=this.getStorageKey("uuid"),$=this.getStorageKey("uuidTimestamp");if(g)try{const G=localStorage.getItem(C);G&&(this.eventData=JSON.parse(G));const K=localStorage.getItem(L);K&&(this.anonId=K);const te=localStorage.getItem($);te&&(this.anonIdTimestamp=Number(te));const de=Date.now()-864e5;(!this.anonIdTimestamp||this.anonIdTimestamp=1&&localStorage.setItem(C,JSON.stringify(this.eventData)),K&&localStorage.setItem($,K.toString())}catch{o.w("Unable to write to LocalStorage")}}processRequests(g){}postEvent(g,C,L,$){if(!o.g.EVENTS_URL)return;const G=se(o.g.EVENTS_URL);G.params.push(`access_token=${$||o.g.ACCESS_TOKEN||""}`);const K={event:this.type,created:new Date(g).toISOString()},te=C?Object.assign(K,C):K,de={url:oe(G),headers:{"Content-Type":"text/plain"},body:JSON.stringify([te])};this.pendingRequest=o.p(de,xe=>{this.pendingRequest=null,L(xe),this.saveEventData(),this.processRequests($)})}queueRequest(g,C){this.queue.push(g),this.processRequests(C)}}class ve extends le{constructor(g){super("metrics"),g&&(this.data=g)}postMetricsEvent(g){if(!me(g))return;this.anonId||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID();const C=Object.assign({},this.data,{sessionId:this.anonId});this.queueRequest({timestamp:Date.now(),payload:C},g)}processRequests(g){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:C,payload:L}=this.queue.shift();this.postEvent(C,L,()=>{},g)}}const ge=new class extends le{constructor(M){super("appUserTurnstile"),this._customAccessToken=M}postTurnstileEvent(M,g){me(g)&&Array.isArray(M)&&M.some(C=>o.e(C)||o.f(C))&&this.queueRequest(Date.now(),g)}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;this.anonId&&this.anonIdTimestamp&&this.eventData.lastSuccess&&this.eventData.tokenU||this.fetchEventData();const g=ce(o.g.ACCESS_TOKEN),C=g?g.u:o.g.ACCESS_TOKEN;let L=C!==this.eventData.tokenU;o.v(this.anonId)||(this.refreshUUID(),L=!0);const $=this.queue.shift();if(this.eventData.lastSuccess){const G=new Date(this.eventData.lastSuccess),K=new Date($),te=($-this.eventData.lastSuccess)/864e5;L=L||te>=1||te<-1||G.getDate()!==K.getDate()}else L=!0;L?this.postEvent($,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:Z,"enabled.telemetry":!1,userId:this.anonId},G=>{G||(this.eventData.lastSuccess=$,this.eventData.tokenU=C)},M):this.processRequests()}},Te=ge.postTurnstileEvent.bind(ge),Ie=new class extends le{constructor(){super("map.load"),this.success={},this.skuToken=""}postMapLoadEvent(M,g,C,L){this.skuToken=g,this.errorCb=L,o.g.EVENTS_URL&&(C||o.g.ACCESS_TOKEN?this.queueRequest({id:M,timestamp:Date.now()},C):this.errorCb(new Error(Y)))}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{id:g,timestamp:C}=this.queue.shift();g&&this.success[g]||(this.anonId&&this.anonIdTimestamp||this.fetchEventData(),o.v(this.anonId)||this.refreshUUID(),this.postEvent(C,{sdkIdentifier:"mapbox-gl-js",sdkVersion:c,skuId:Z,skuToken:this.skuToken,userId:this.anonId},L=>{L?this.errorCb(L):g&&(this.success[g]=!0)},M))}remove(){this.errorCb=null}},Ce=Ie.postMapLoadEvent.bind(Ie),Me=new class extends le{constructor(){super("style.load"),this.eventIdPerMapInstanceMap=new Map,this.mapInstanceIdMap=new WeakMap}getMapInstanceId(M){let g=this.mapInstanceIdMap.get(M);return g||(g=o.u(),this.mapInstanceIdMap.set(M,g)),g}getEventId(M){const g=this.eventIdPerMapInstanceMap.get(M)||0;return this.eventIdPerMapInstanceMap.set(M,g+1),g}postStyleLoadEvent(M,g){const{map:C,style:L,importedStyles:$}=g;if(!me(M))return;const G=this.getMapInstanceId(C),K={mapInstanceId:G,eventId:this.getEventId(G),style:L};$.length&&(K.importedStyles=$),this.queueRequest({timestamp:Date.now(),payload:K},M)}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:g,payload:C}=this.queue.shift();this.postEvent(g,C,()=>{},M)}},Pe=Me.postStyleLoadEvent.bind(Me),Re=new ve({attributes:[{name:"maps/js/layer-animations/style-with-appearances"}]}),Ae=Re.postMetricsEvent.bind(Re),Be=new ve({attributes:[{name:"maps/js/layer-animations/runtime-appearances"}]}),we=Be.postMetricsEvent.bind(Be),Je=new class extends le{constructor(){super("gljs.performance")}postPerformanceEvent(M,g){me(M)&&this.queueRequest({timestamp:Date.now(),performanceData:g},M)}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{timestamp:g,performanceData:C}=this.queue.shift(),L=function($){const G=performance.getEntriesByType("resource"),K=performance.getEntriesByType("mark"),te=function(qe){const st={};if(qe){for(const Xe in qe)if(Xe!=="other")for(const pt of qe[Xe]){const mt=`${Xe}ResolveRangeMin`,kt=`${Xe}ResolveRangeMax`,Et=`${Xe}RequestCount`,xt=`${Xe}RequestCachedCount`;st[mt]=Math.min(st[mt]||1/0,pt.startTime),st[kt]=Math.max(st[kt]||-1/0,pt.responseEnd);const es=Ot=>{st[Ot]===void 0&&(st[Ot]=0),++st[Ot]};pt.transferSize!==void 0&&pt.transferSize===0&&es(xt),es(Et)}}return st}(function(qe,st){const Xe={};if(qe)for(const pt of qe){const mt=st(pt);Xe[mt]===void 0&&(Xe[mt]=[]),Xe[mt].push(pt)}return Xe}(G,h)),de=window.devicePixelRatio,xe=navigator.connection||navigator.mozConnection||navigator.webkitConnection,_e=xe?xe.effectiveType:void 0,Oe={counters:[],metadata:[],attributes:[]},De=(qe,st,Xe)=>{Xe!=null&&qe.push({name:st,value:Xe.toString()})};for(const qe in te)De(Oe.counters,qe,te[qe]);if($.interactionRange[0]!==1/0&&$.interactionRange[1]!==-1/0&&(De(Oe.counters,"interactionRangeMin",$.interactionRange[0]),De(Oe.counters,"interactionRangeMax",$.interactionRange[1])),K)for(const qe of Object.values(d)){const st=K.find(Xe=>Xe.name===qe);st&&De(Oe.counters,qe,st.startTime)}return De(Oe.counters,"visibilityHidden",$.visibilityHidden),De(Oe.attributes,"style",function(qe){if(qe)for(const st of qe){const Xe=st.name.split("?")[0];if(o.i(Xe)){const pt=Xe.split("/").slice(-2);if(pt.length===2)return`mapbox://styles/${pt[0]}/${pt[1]}`}}}(G)),De(Oe.attributes,"terrainEnabled",$.terrainEnabled?"true":"false"),De(Oe.attributes,"fogEnabled",$.fogEnabled?"true":"false"),De(Oe.attributes,"projection",$.projection),De(Oe.attributes,"zoom",$.zoom),De(Oe.metadata,"devicePixelRatio",de),De(Oe.metadata,"connectionEffectiveType",_e),De(Oe.metadata,"navigatorUserAgent",navigator.userAgent),De(Oe.metadata,"screenWidth",window.screen.width),De(Oe.metadata,"screenHeight",window.screen.height),De(Oe.metadata,"windowWidth",window.innerWidth),De(Oe.metadata,"windowHeight",window.innerHeight),De(Oe.metadata,"mapWidth",$.width/de),De(Oe.metadata,"mapHeight",$.height/de),De(Oe.metadata,"webglRenderer",$.renderer),De(Oe.metadata,"webglVendor",$.vendor),De(Oe.metadata,"sdkVersion",c),De(Oe.metadata,"sdkIdentifier","mapbox-gl-js"),Oe}(C);for(const $ of L.metadata);for(const $ of L.counters);for(const $ of L.attributes);this.postEvent(g,L,()=>{},M)}},ke=Je.postPerformanceEvent.bind(Je),it=new class extends le{constructor(){super("map.auth"),this.success={},this.skuToken=""}getSession(M,g,C,L){if(!o.g.API_URL||!o.g.SESSION_PATH)return;const $=se(o.g.API_URL+o.g.SESSION_PATH);$.params.push(`sku=${g||""}`),$.params.push(`access_token=${L||o.g.ACCESS_TOKEN||""}`);const G={url:oe($),headers:{"Content-Type":"text/plain"}};this.pendingRequest=o.h(G,K=>{this.pendingRequest=null,C(K),this.saveEventData(),this.processRequests(L)})}getSessionAPI(M,g,C,L){this.skuToken=g,this.errorCb=L,o.g.EVENTS_URL&&o.g.SESSION_PATH&&o.g.API_URL&&(C||o.g.ACCESS_TOKEN?this.queueRequest({id:M,timestamp:Date.now()},C):this.errorCb(new Error(Y)))}processRequests(M){if(this.pendingRequest||this.queue.length===0)return;const{id:g,timestamp:C}=this.queue.shift();g&&this.success[g]||this.getSession(C,this.skuToken,L=>{L?this.errorCb(L):g&&(this.success[g]=!0)},M)}remove(){this.errorCb=null}},je=it.getSessionAPI.bind(it),He=new Set;function $e(M,g){g?He.add(M):He.delete(M)}class Ke{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(g,C){this._updatedSourceCaches[g]=C,this.setDirty()}discardSourceCacheUpdate(g){delete this._updatedSourceCaches[g]}updateLayer(g){const C=g.scope;this._updatedLayers[C]=this._updatedLayers[C]||new Set,this._updatedLayers[C].add(g.id),this.setDirty()}removeLayer(g){const C=g.scope;this._removedLayers[C]=this._removedLayers[C]||{},this._updatedLayers[C]=this._updatedLayers[C]||new Set,this._removedLayers[C][g.id]=g,this._updatedLayers[C].delete(g.id),this._updatedPaintProps.delete(g.fqid),this.setDirty()}getRemovedLayer(g){return this._removedLayers[g.scope]?this._removedLayers[g.scope][g.id]:null}discardLayerRemoval(g){this._removedLayers[g.scope]&&delete this._removedLayers[g.scope][g.id]}getLayerUpdatesByScope(){const g={};for(const C in this._updatedLayers)g[C]=g[C]||{},g[C].updatedIds=Array.from(this._updatedLayers[C].values());for(const C in this._removedLayers)g[C]=g[C]||{},g[C].removedIds=Object.keys(this._removedLayers[C]);return g}getUpdatedPaintProperties(){return this._updatedPaintProps}updatePaintProperties(g){this._updatedPaintProps.add(g.fqid),this.setDirty()}getUpdatedImages(g){return this._updatedImages[g]?Array.from(this._updatedImages[g].values()):[]}updateImage(g,C){this._updatedImages[C]=this._updatedImages[C]||new Set,this._updatedImages[C].add(o.I.toString(g)),this.setDirty()}resetUpdatedImages(g){this._updatedImages[g]&&this._updatedImages[g].clear()}reset(){this._changed=!1,this._updatedLayers={},this._removedLayers={},this._updatedSourceCaches={},this._updatedPaintProps.clear(),this._updatedImages={}}}function Ge(M){const{userImage:g}=M;return!!(g&&g.render&&g.render())&&(M.data.replace(new Uint8Array(g.data.buffer)),!0)}const rt={workerUrl:"",workerClass:null,workerParams:void 0};function tt(M){return rt.workerClass!=null?new rt.workerClass:new self.Worker(rt.workerUrl,Object.assign({name:M},rt.workerParams))}const at="mapboxgl_preloaded_worker_pool";class Ye{constructor(g){this.active={},this.name=g}acquire(g,C=Ye.workerCount){if(!this.workers)for(this.workers=[];this.workers.length{C.terminate()}),this.workers=null)}isPreloaded(){return!!this.active[at]}numActive(){return Object.keys(this.active).length}}Ye.workerCount=2;class ut{constructor(g,C,L="Worker",$=Ye.workerCount){this.workerPool=g,this.actors=[],this.currentActor=0,this.id=o.r();const G=this.workerPool.acquire(this.id,$);for(let K=0;K{this.ready=!0})}broadcast(g,C,L){o.t(this.actors,($,G)=>{$.send(g,C,G)},L=L||function(){})}getActor(){return this.currentActor=(this.currentActor+1)%this.actors.length,this.actors[this.currentActor]}remove(){this.actors.forEach(g=>{g.remove()}),this.actors=[],this.workerPool.release(this.id)}}let _t,bt;function $t(){return _t||(_t=new Ye),_t}ut.Actor=o.A;class Yt extends o.E{constructor(g){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=g,g!=="raster"&&o.y()&&(this.imageRasterizerDispatcher=new ut((bt||(bt=new Ye("ImageRasterizer")),bt),this,"Image Rasterizer Worker",1))}addScope(g){this.loaded.set(g,!1),this.imageProviders.set(g,new Map),this.images.set(g,new Map),this.updatedImages.set(g,new Set),this.callbackDispatchedThisFrame.set(g,new Set),this.imageVersions.set(g,new Map),this.patterns.set(g,new Map),this.atlasImage.set(g,new o.q({width:1,height:1}))}removeScope(g){this.loaded.delete(g),this.imageProviders.delete(g),this.images.delete(g),this.updatedImages.delete(g),this.callbackDispatchedThisFrame.delete(g),this.imageVersions.delete(g),this.patterns.delete(g),this.atlasImage.delete(g);const C=this.atlasTexture.get(g);C&&(C.destroy(),this.atlasTexture.delete(g))}addImageProvider(g,C){this.imageProviders.has(C)||this.imageProviders.set(C,new Map),this.imageProviders.get(C).set(g.id,g)}removeImageProvider(g,C){this.imageProviders.has(C)&&this.imageProviders.get(C).delete(g)}getPendingImageProviders(){const g=[];for(const C of this.imageProviders.values())for(const L of C.values())L.hasPendingRequests()&&g.push(L);return g}get imageRasterizer(){return this._imageRasterizer||(this._imageRasterizer=new o.z),this._imageRasterizer}isLoaded(){for(const g of this.loaded.keys())if(!this.loaded.get(g))return!1;return!0}setLoaded(g,C){if(this.loaded.get(C)!==g&&(this.loaded.set(C,g),g)){for(const{ids:L,callback:$}of this.requestors)this._notify(L,C,$);this.requestors=[]}}hasImage(g,C){return!!this.getImage(g,C)}getImage(g,C){return this.images.get(C).get(g.toString())}addImage(g,C,L){if(this._validate(g,L)){this.images.get(C).set(g.toString(),L);const $=this.imageVersions.get(C),G=$.get(g.toString())||0;$.set(g.toString(),G+1)}}_validate(g,C){let L=!0;return this._validateStretch(C.stretchX,C.data&&C.data.width)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "stretchX" value`))),L=!1),this._validateStretch(C.stretchY,C.data&&C.data.height)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "stretchY" value`))),L=!1),this._validateContent(C.content,C)||(this.fire(new o.B(new Error(`Image "${g.name}" has invalid "content" value`))),L=!1),L}_validateStretch(g,C){if(!g)return!0;let L=0;for(const $ of g){if($[0]o.I.from(C))}getImageVersions(g){const C=this.imageVersions.get(g);if(C)return C}getImages(g,C,L){const $=[],G=[],K=this.imageProviders.get(C);for(const _e of g){if(!_e.iconsetId){$.push(_e);continue}const Oe=K.get(_e.iconsetId);Oe&&(this.getImage(_e,C)?G.push(_e):Oe.addPendingRequest(_e))}if($.length===0)return void this._notify(G,C,L);let te=!0;const de=!!this.loaded.get(C),xe=this.images.get(C);if(!de)for(const _e of $)xe.has(_e.toString())||(te=!1);de||te?this._notify($,C,L):this.requestors.push({ids:$,scope:C,callback:L})}rasterizeImages(g,C){const L=new Map,{tasks:$,scope:G}=g;for(const[K,te]of $.entries()){const de=this.getImage(te.id,G);de&&L.set(K,{image:de,imageVariant:te})}this._rasterizeImages(G,L,C)}_rasterizeImages(g,C,L){if(o.y())this.imageRasterizerDispatcher.getActor().send("rasterizeImagesWorker",{tasks:C,scope:g},L);else{const $=new Map;for(const[G,{image:K,imageVariant:te}]of C.entries())$.set(G,this.imageRasterizer.rasterize(te,K,g,0));L(void 0,$)}}getUpdatedImages(g){return this.updatedImages.get(g)||new Set}_notify(g,C,L){const $=this.images.get(C),G=new Map;for(const K of g){if(!$.get(K.toString())){if(K.iconsetId)continue;this.fire(new o.C("styleimagemissing",{id:K.name}))}const te=$.get(K.toString());if(!te){o.w(`Image "${K.name}" could not be loaded. Please make sure you have added the image with map.addImage() or a "sprite" property in your style. You can provide missing images by listening for the "styleimagemissing" map event.`);continue}const de={data:te.usvg?null:te.data.clone(),pixelRatio:te.pixelRatio,sdf:te.sdf,usvg:te.usvg,stretchX:te.stretchX,stretchY:te.stretchY,content:te.content,hasRenderCallback:!!(te.userImage&&te.userImage.render)};te.usvg&&Object.assign(de,{width:te.icon.usvg_tree.width,height:te.icon.usvg_tree.height}),G.set(o.I.toString(K),de)}L(null,{images:G,versions:this.getImageVersions(C)})}getPixelSize(g){const{width:C,height:L}=this.atlasImage.get(g);return{width:C,height:L}}getPattern(g,C,L){const $=g.toString(),G=this.patterns.get(C),K=G.get($),te=this.getImage(g,C);if(!te)return null;if(K){if(K.position.version===te.version)return K.position;K.position.version=te.version}else{if(te.usvg&&!te.data){const de=this.getPatternInFlightId($,C);if(this.patternsInFlight.has(de))return null;this.patternsInFlight.add(de);const xe=new o.D(g).scaleSelf(o.o.devicePixelRatio),_e=new Map([[xe.toString(),{image:te,imageVariant:xe}]]);return this._rasterizeImages(C,_e,(Oe,De)=>this.storePatternImage(xe,C,te,L,De)),null}this.storePattern(g,C,te)}return this._updatePatternAtlas(C,L),G.get($).position}getPatternInFlightId(g,C){return o.F(g,C)}hasPatternsInFlight(){return this.patternsInFlight.size!==0}storePatternImage(g,C,L,$,G){const K=g.toString(),te=G?G.get(K):void 0;te&&(L.data=te,this.storePattern(g.id,C,L),this._updatePatternAtlas(C,$),this.patternsInFlight.delete(this.getPatternInFlightId(g.id.toString(),C)))}storePattern(g,C,L){const $={w:L.data.width+2*o.G,h:L.data.height+2*o.G,x:0,y:0},G=new o.H($,L,o.G);this.patterns.get(C).set(g.toString(),{bin:$,position:G})}destroyAtlasTextures(){for(const g of this.atlasTexture.values())g&&g.destroy();this.atlasTexture.clear()}bind(g,C){const L=g.gl;let $=this.atlasTexture.get(C);$?this.dirty&&($.update(this.atlasImage.get(C)),this.dirty=!1):($=new o.T(g,this.atlasImage.get(C),L.RGBA8),this.atlasTexture.set(C,$)),$.bind(L.LINEAR,L.CLAMP_TO_EDGE)}_updatePatternAtlas(g,C){const L=this.patterns.get(g),$=Array.from(L.values()).map(({bin:xe})=>xe),{w:G,h:K}=o.J($),te=this.atlasImage.get(g);te.resize({width:G||1,height:K||1});const de=this.images.get(g);for(const[xe,{bin:_e,position:Oe}]of L.entries()){let De=Oe.padding;const qe=_e.x+De,st=_e.y+De,Xe=de.get(xe).data,pt=Xe.width,mt=Xe.height;De=De>1?De-1:De,o.q.copy(Xe,te,{x:0,y:0},{x:qe,y:st},{width:pt,height:mt},C),o.q.copy(Xe,te,{x:0,y:mt-De},{x:qe,y:st-De},{width:pt,height:De},C),o.q.copy(Xe,te,{x:0,y:0},{x:qe,y:st+mt},{width:pt,height:De},C),o.q.copy(Xe,te,{x:pt-De,y:0},{x:qe-De,y:st},{width:De,height:mt},C),o.q.copy(Xe,te,{x:0,y:0},{x:qe+pt,y:st},{width:De,height:mt},C),o.q.copy(Xe,te,{x:pt-De,y:mt-De},{x:qe-De,y:st-De},{width:De,height:De},C),o.q.copy(Xe,te,{x:0,y:mt-De},{x:qe+pt,y:st-De},{width:De,height:De},C),o.q.copy(Xe,te,{x:0,y:0},{x:qe+pt,y:st+mt},{width:De,height:De},C),o.q.copy(Xe,te,{x:pt-De,y:0},{x:qe-De,y:st+mt},{width:De,height:De},C)}this.dirty=!0}beginFrame(){for(const g of this.images.keys())this.callbackDispatchedThisFrame.set(g,new Set)}dispatchRenderCallbacks(g,C){const L=this.images.get(C);for(const $ of g){if(this.callbackDispatchedThisFrame.get(C).has($.toString()))continue;this.callbackDispatchedThisFrame.get(C).add($.toString());const G=L.get($.toString());Ge(G)&&this.updateImage($,C,G)}}destroy(){this.imageRasterizerDispatcher&&this.imageRasterizerDispatcher.remove()}}function Ds(M){const g=M.value,C=M.valueSpec,L=M.style,$=M.styleSpec,G=M.key,K=M.arrayElementValidator||Ar;if(!Array.isArray(g))return[new o.V(G,g,`array expected, ${o.M(g)} found`)];if(C.length&&g.length!==C.length)return[new o.V(G,g,`array length ${C.length} expected, length ${g.length} found`)];if(C["min-length"]&&g.length$)return[new o.V(g,C,`${C} is greater than the maximum value ${$}`)]}return[]}function xs(M){const g=M.key,C=M.value;if(!o.K(C))return[new o.V(g,C,`object expected, ${o.M(C)} found`)];const L=M.valueSpec,$=o.L(C.type);let G,K,te,de={};const xe=$!=="categorical"&&C.property===void 0,_e=!xe,Oe=function(Xe){const pt=Xe.stops;return Array.isArray(pt)&&Array.isArray(pt[0])&&o.K(pt[0][0])}(C),De=Hn({key:M.key,value:M.value,valueSpec:M.styleSpec.function,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{stops:function(Xe){if($==="identity")return[new o.V(Xe.key,Xe.value,'identity function may not have a "stops" property')];let pt=[];const mt=Xe.value;return pt=pt.concat(Ds({key:Xe.key,value:mt,valueSpec:Xe.valueSpec,style:Xe.style,styleSpec:Xe.styleSpec,arrayElementValidator:qe})),Array.isArray(mt)&&mt.length===0&&pt.push(new o.V(Xe.key,mt,"array must have at least one stop")),pt},default:function(Xe){return Ar({key:Xe.key,value:Xe.value,valueSpec:L,style:Xe.style,styleSpec:Xe.styleSpec})}}});return $==="identity"&&xe&&De.push(new o.V(M.key,M.value,'missing required property "property"')),$==="identity"||C.stops||De.push(new o.V(M.key,M.value,'missing required property "stops"')),$==="exponential"&&L.expression&&!o.O(L)&&De.push(new o.V(M.key,M.value,"exponential functions not supported")),M.styleSpec.$version>=8&&(_e&&!o.Q(L)?De.push(new o.V(M.key,M.value,"property functions not supported")):xe&&!o.S(L)&&De.push(new o.V(M.key,M.value,"zoom functions not supported"))),$!=="categorical"&&!Oe||C.property!==void 0||De.push(new o.V(M.key,M.value,'"property" property is required')),De;function qe(Xe){let pt=[];const mt=Xe.value,kt=Xe.key;if(!Array.isArray(mt))return[new o.V(kt,mt,`array expected, ${o.M(mt)} found`)];if(mt.length!==2)return[new o.V(kt,mt,`array length 2 expected, length ${mt.length} found`)];if(Oe){if(!o.K(mt[0]))return[new o.V(kt,mt,`object expected, ${o.M(mt[0])} found`)];const Et=mt[0];if(Et.zoom===void 0)return[new o.V(kt,mt,"object stop key must have zoom")];if(Et.value===void 0)return[new o.V(kt,mt,"object stop key must have value")];const xt=o.L(Et.zoom);if(typeof xt!="number")return[new o.V(kt,Et.zoom,"stop zoom values must be numbers")];if(te&&te>xt)return[new o.V(kt,Et.zoom,"stop zoom values must appear in ascending order")];xt!==te&&(te=xt,K=void 0,de={}),pt=pt.concat(Hn({key:`${kt}[0]`,value:mt[0],valueSpec:{zoom:{}},style:Xe.style,styleSpec:Xe.styleSpec,objectElementValidators:{zoom:Ls,value:st}}))}else pt=pt.concat(st({key:`${kt}[0]`,value:mt[0],style:Xe.style,styleSpec:Xe.styleSpec},mt));return o.U(o.W(mt[1]))?pt.concat([new o.V(`${kt}[1]`,mt[1],"expressions are not allowed in function stops.")]):pt.concat(Ar({key:`${kt}[1]`,value:mt[1],valueSpec:L,style:Xe.style,styleSpec:Xe.styleSpec}))}function st(Xe,pt){const mt=o.M(Xe.value),kt=o.L(Xe.value),Et=Xe.value!==null?Xe.value:pt;if(G){if(mt!==G)return[new o.V(Xe.key,Et,`${mt} stop domain type must match previous stop domain type ${G}`)]}else G=mt;if(mt!=="number"&&mt!=="string"&&mt!=="boolean"&&typeof kt!="number"&&typeof kt!="string"&&typeof kt!="boolean")return[new o.V(Xe.key,Et,"stop domain value must be a number, string, or boolean")];if(mt!=="number"&&$!=="categorical"){let xt=`number expected, ${mt} found`;return o.Q(L)&&$===void 0&&(xt+='\nIf you intended to use a categorical function, specify `"type": "categorical"`.'),[new o.V(Xe.key,Et,xt)]}return $!=="categorical"||mt!=="number"||typeof kt=="number"&&isFinite(kt)&&Math.floor(kt)===kt?$!=="categorical"&&mt==="number"&&typeof kt=="number"&&typeof K=="number"&&K!==void 0&&ktnew o.V(`${M.key}${L.key}`,M.value,L.message));const C=g.value.expression||g.value._styleExpression.expression;if(M.expressionContext==="property"&&M.propertyKey==="text-font"&&!C.outputDefined())return[new o.V(M.key,M.value,`Invalid data expression for "${M.propertyKey}". Output values must be contained as literals within the expression.`)];if(M.expressionContext==="property"&&M.propertyType==="layout"&&!o.$(C))return[new o.V(M.key,M.value,'"feature-state" data expressions are not supported with layout properties.')];if(M.expressionContext==="filter")return Jt(C,M);if(M.expressionContext==="appearance")return gt(C,M);if(M.expressionContext&&M.expressionContext.indexOf("cluster")===0){if(!o.Z(C,["zoom","feature-state"]))return[new o.V(M.key,M.value,'"zoom" and "feature-state" expressions are not supported with cluster properties.')];if(M.expressionContext==="cluster-initial"&&!o._(C))return[new o.V(M.key,M.value,"Feature data expressions are not supported with initial expression part of cluster properties.")]}return[]}function Jt(M,g){const C=new Set(["zoom","feature-state","pitch","distance-from-center"]);if(g.valueSpec&&g.valueSpec.expression)for(const $ of g.valueSpec.expression.parameters)C.delete($);if(C.size===0)return[];const L=[];return M instanceof o.a0&&C.has(M.name)?[new o.V(g.key,g.value,`["${M.name}"] expression is not supported in a filter for a ${g.object.type} layer with id: ${g.object.id}`)]:(M.eachChild($=>{L.push(...Jt($,g))}),L)}function gt(M,g){const C=new Set;if(g.valueSpec&&g.valueSpec.expression)for(const $ of g.valueSpec.expression.parameters)C.add($);if(C.size===0)return[];const L=[];return M instanceof o.a0&&!C.has(M.name)?[new o.V(g.key,g.value,`["${M.name}"] is not an allowed parameter`)]:(M.eachChild($=>{L.push(...gt($,g))}),L)}function zt(M){const g=M.key,C=M.value,L=M.valueSpec,$=[];return Array.isArray(L.values)?L.values.indexOf(o.L(C))===-1&&$.push(new o.V(g,C,`expected one of [${L.values.join(", ")}], ${JSON.stringify(C)} found`)):Object.keys(L.values).indexOf(o.L(C))===-1&&$.push(new o.V(g,C,`expected one of [${Object.keys(L.values).join(", ")}], ${JSON.stringify(C)} found`)),$}function As(M){return o.a4(o.W(M.value))?Lt(Object.assign({},M,{expressionContext:"filter",valueSpec:M.styleSpec[`filter_${M.layerType||"fill"}`]})):Xt(M)}function Xt(M){const g=M.value,C=M.key;if(!Array.isArray(g))return[new o.V(C,g,`array expected, ${o.M(g)} found`)];if(g.length<1)return[new o.V(C,g,"filter array must have at least 1 element")];const L=M.styleSpec;let $=zt({key:`${C}[0]`,value:g[0],valueSpec:L.filter_operator});const G=()=>{g.length>=2&&(o.a2(g[1])||$.push(new o.V(`${C}[1]`,g[1],`string expected, ${o.M(g[1])} found`)));for(let K=2;K":case">=":g.length>=2&&o.L(g[1])==="$type"&&$.push(new o.V(C,g,`"$type" cannot be use with operator "${g[0]}"`)),g.length!==3&&$.push(new o.V(C,g,`filter array for operator "${g[0]}" must have 3 elements`)),G();break;case"==":case"!=":g.length!==3&&$.push(new o.V(C,g,`filter array for operator "${g[0]}" must have 3 elements`)),G();break;case"in":case"!in":G();break;case"any":case"all":case"none":for(let K=1;K{xe in C&&g.push(new o.V(L,C[xe],`"${xe}" is prohibited for ref layers`))}),$.layers.forEach(xe=>{o.L(xe.id)===te&&(de=xe)}),de?de.ref?g.push(new o.V(L,C.ref,"ref cannot reference another ref layer")):K=o.L(de.type):typeof te=="string"&&g.push(new o.V(L,C.ref,`ref layer "${te}" not found`))}else if(K!=="background"&&K!=="sky"&&K!=="slot")if(C.source)if(o.a2(C.source)){const de=$.sources&&$.sources[C.source],xe=de&&o.L(de.type);de?xe==="vector"&&K==="raster"?g.push(new o.V(L,C.source,`layer "${C.id}" requires a raster source`)):xe==="raster"&&K!=="raster"?g.push(new o.V(L,C.source,`layer "${C.id}" requires a vector source`)):xe!=="vector"||C["source-layer"]?xe==="raster-dem"&&K!=="hillshade"?g.push(new o.V(L,C.source,"raster-dem source can only be used with layer type 'hillshade'.")):xe!=="raster-array"||["raster","raster-particle"].includes(K)?K==="line"&&C.paint&&(C.paint["line-gradient"]||C.paint["line-trim-offset"])&&xe==="geojson"&&!de.lineMetrics?g.push(new o.V(L,C,`layer "${C.id}" specifies a line-gradient, which requires the GeoJSON source to have \`lineMetrics\` enabled.`)):K==="raster-particle"&&xe!=="raster-array"&&g.push(new o.V(L,C.source,`layer "${C.id}" requires a 'raster-array' source.`)):g.push(new o.V(L,C.source,"raster-array source can only be used with layer type 'raster'.")):g.push(new o.V(L,C,`layer "${C.id}" must specify a "source-layer"`)):g.push(new o.V(L,C.source,`source "${C.source}" not found`))}else g.push(new o.V(`${L}.source`,C.source,'"source" must be a string'));else g.push(new o.V(L,C,'missing required property "source"'));return g=g.concat(Hn({key:L,value:C,valueSpec:G.layer,style:M.style,styleSpec:M.styleSpec,objectElementValidators:{"*":()=>[],type:()=>Ar({key:`${L}.type`,value:C.type,valueSpec:G.layer.type,style:M.style,styleSpec:M.styleSpec,object:C,objectKey:"type"}),filter:de=>As(Object.assign({layerType:K},de)),layout:de=>Hn({layer:C,key:de.key,value:de.value,valueSpec:{},style:de.style,styleSpec:de.styleSpec,objectElementValidators:{"*":xe=>$s(Object.assign({layerType:K},xe))}}),paint:de=>Hn({layer:C,key:de.key,value:de.value,valueSpec:{},style:de.style,styleSpec:de.styleSpec,objectElementValidators:{"*":xe=>ks(Object.assign({layerType:K,layer:C},xe))}}),appearances(de){const xe=Ds({key:de.key,value:de.value,valueSpec:de.valueSpec,style:de.style,styleSpec:de.styleSpec,arrayElementValidator:De=>function(qe){const{key:st,layer:Xe,layerType:pt}=qe,mt=o.L(qe.value),kt=o.L(mt.name),Et=o.L(mt.condition),xt=Hn({key:st,value:mt,valueSpec:qe.styleSpec.appearance,style:qe.style,styleSpec:qe.styleSpec,objectElementValidators:{condition:es=>function(Ot){const Qt=[];return Qt.push(...Lt({key:Ot.key,value:Ot.object.condition,valueSpec:o.a8.appearance.condition,expressionContext:"appearance"})),Qt}(Object.assign({layer:Xe,layerType:pt},es)),properties:es=>function(Ot){const Qt=[],{styleSpec:At,layer:Dt,layerType:Ht}=Ot,gs=At[`paint_${Ht}`],ss=At[`layout_${Ht}`],Bs=Ot.object[Ot.objectKey];for(const Ps in Bs){const rn=Ps in gs?"paint":Ps in ss?"layout":void 0;if(!rn){Qt.push(new o.V(Ot.key,Ps,`unknown property "${Ps}" for layer type "${Ht}"`));continue}const hn=Object.assign({},Ot,{key:`${Ot.key}.${Ps}`,object:Bs,objectKey:Ps,layer:Dt,layerType:Ht,value:Bs[Ps],valueSpec:rn==="paint"?gs[Ps]:ss[Ps]});Qt.push(...Qs(hn,rn))}return Qt}(Object.assign({layer:Xe,layerType:pt},es))}});return kt!=="hidden"&&Et===void 0&&xt.push(new o.V(qe.key,"name",'Appearance with name different than "hidden" must have a condition')),xt}(Object.assign({layerType:K,layer:C},De))}),_e=Array.isArray(de.value)?de.value:[],Oe=new Set;return _e.forEach((De,qe)=>{const st=o.L(De.name);if(st)if(Oe.has(st)){const Xe=o.L(C.id);xe.push(new o.V(de.key,st,`Duplicated appearance name "${st}" for layer "${Xe}"`))}else Oe.add(st)}),xe}}})),g}function tn({key:M,value:g}){return o.a2(g)?[]:[new o.V(M,g,`string expected, ${o.M(g)} found`)]}const er={promoteId:function M({key:g,value:C}){if(o.a2(C))return tn({key:g,value:C});if(Array.isArray(C)){const $=[],G=o.W(C),K=o.X(G);return K.result==="error"?(K.value.forEach(te=>{$.push(new o.V(`${g}${te.key}`,null,`${te.message}`))}),$):(o.Z(K.value.expression,["zoom","heatmap-density","line-progress","raster-value","sky-radial-progress","accumulated","is-supported-script","pitch","distance-from-center","measure-light","raster-particle-speed"])||$.push(new o.V(`${g}`,null,"promoteId expression should be only feature dependent")),$)}if(!o.K(C))return[new o.V(g,C,`string, expression or object expected, "${o.M(C)}" found`)];const L=[];for(const $ in C)L.push(...M({key:`${g}.${$}`,value:C[$]}));return L}};function xn(M){const g=M.value,C=M.key,L=M.styleSpec,$=M.style;if(!o.K(g))return[new o.V(C,g,`object expected, ${o.M(g)} found`)];if(!("type"in g))return[new o.V(C,g,'"type" is required')];const G=o.L(g.type);let K=[];switch(["vector","raster","raster-dem","raster-array"].includes(G)&&("url"in g||"tiles"in g||K.push(new o.a5(C,g,'Either "url" or "tiles" is required.'))),G){case"vector":case"raster":case"raster-dem":case"raster-array":return K=K.concat(Hn({key:C,value:g,valueSpec:L[`source_${G.replace("-","_")}`],style:M.style,styleSpec:L,objectElementValidators:er})),K;case"geojson":if(K=Hn({key:C,value:g,valueSpec:L.source_geojson,style:$,styleSpec:L,objectElementValidators:er}),"cluster"in g&&"clusterProperties"in g){if(!o.K(g.clusterProperties))return[new o.V(`${C}.clusterProperties`,g,`object expected, ${o.M(g)} found`)];for(const te in g.clusterProperties){const de=g.clusterProperties[te];if(!Array.isArray(de))return[new o.V(`${C}.clusterProperties.${te}`,de,"array expected")];const[xe,_e]=de,Oe=typeof xe=="string"?[xe,["accumulated"],["get",te]]:xe;K.push(...Lt({key:`${C}.${te}.map`,value:_e,expressionContext:"cluster-map"})),K.push(...Lt({key:`${C}.${te}.reduce`,value:Oe,expressionContext:"cluster-reduce"}))}}return K;case"video":return Hn({key:C,value:g,valueSpec:L.source_video,style:$,styleSpec:L});case"image":return Hn({key:C,value:g,valueSpec:L.source_image,style:$,styleSpec:L});case"canvas":return[new o.V(C,null,"Please use runtime APIs to add canvas sources, rather than including them in stylesheets.","source.canvas")];default:return zt({key:`${C}.type`,value:g.type,valueSpec:{values:Pn(L)}})}}function Pn(M){return M.source.reduce((g,C)=>{const L=M[C];return L.type.type==="enum"&&(g=g.concat(Object.keys(L.type.values||{}))),g},[])}function Qn(M){const g=M.value,C=M.styleSpec,L=C.light,$=M.style;if(g===void 0)return[];if(!o.K(g))return[new o.V("light",g,`object expected, ${o.M(g)} found`)];let G=[];for(const K in g){const te=K.match(/^(.*)-transition$/),de=K.match(/^(.*)-use-theme$/);G=G.concat(de&&L[de[1]]?Ar({key:K,value:g[K],valueSpec:{type:"string"},style:$,styleSpec:C}):te&&L[te[1]]&&L[te[1]].transition?Ar({key:K,value:g[K],valueSpec:C.transition,style:$,styleSpec:C}):L[K]?Ar({key:K,value:g[K],valueSpec:L[K],style:$,styleSpec:C}):[new o.V(K,g[K],`unknown property "${K}"`)])}return G}function sa(M){const g=M.value;if(!g)return[];const C=M.key;if(!o.K(g))return[new o.V(C,g,`object expected, ${o.M(g)} found`)];let L=[];const $=M.styleSpec,G=$["light-3d"],K=M.style,te=M.style.lights;for(const _e of["type","id"])if(!(_e in g))return L=L.concat([new o.V(C,g,`missing property "${_e}"`)]),L;if(!o.a2(g.type))return L=L.concat([new o.V(`${C}.type`,g.type,"string expected")]),L;if(te)for(let _e=0;_e[],array:Ds,boolean:function(M){const g=M.value,C=M.key;return o.a1(g)?[]:[new o.V(C,g,`boolean expected, ${o.M(g)} found`)]},number:Ls,color:function({key:M,value:g}){return o.a2(g)?o.a3.parseCSSColor(g)===null?[new o.V(M,g,`color expected, "${g}" found`)]:[]:[new o.V(M,g,`color expected, ${o.M(g)} found`)]},enum:zt,filter:As,function:xs,layer:an,object:Hn,source:xn,model:o.a9,light:Qn,"light-3d":sa,terrain:na,fog:Es,string:tn,formatted:function(M){return tn(M).length===0?[]:Lt(M)},resolvedImage:function(M){return tn(M).length===0?[]:Lt(M)},projection:function(M){const g=M.value,C=M.styleSpec,L=C.projection,$=M.style;if(o.K(g)){let G=[];for(const K in g)G=G.concat(Ar({key:K,value:g[K],valueSpec:L[K],style:$,styleSpec:C}));return G}return o.a2(g)?[]:[new o.V("projection",g,`object or string expected, ${o.M(g)} found`)]},import:function(M){const g=M.key,{value:C,styleSpec:L}=M;if(!o.K(C))return[new o.V(g,C,"import must be an object")];const{data:$,...G}=C;Object.defineProperty(G,"__line__",{value:C.__line__,enumerable:!1});let K=Hn(Object.assign({},M,{value:G,valueSpec:L.import}));return o.L(G.id)===""&&K.push(new o.V(`${M.key}.id`,G,"import id can't be an empty string")),$&&(K=K.concat(Un($,L,{key:`${M.key}.data`}))),K},iconset:function(M){const g=M.value,C=M.key,L=M.styleSpec,$=M.style;if(!o.K(g))return[new o.V(C,g,"object expected")];if(!g.type)return[new o.V(C,g,'"type" is required')];const G=o.L(g.type);let K=[];if(K=K.concat(Hn({key:C,value:g,valueSpec:L[`iconset_${G}`],style:$,styleSpec:L})),function(te,de){return!(te!=="source"||!de.source)}(G,g)){const te=$.sources&&$.sources[g.source],de=te&&o.L(te.type);te?de!=="raster-array"&&K.push(new o.V(C,g.source,`iconset cannot be used with a source of type ${String(de)}, it only be used with a "raster-array" source type`)):K.push(new o.V(C,g.source,`source "${g.source}" not found`))}return K}};function Ar(M,g=!1){const C=M.value,L=M.valueSpec,$=M.styleSpec;if(L.expression){if(o.a6(o.L(C)))return xs(M);if(o.U(o.W(C)))return Lt(M)}if(L.type&&mi[L.type]){const G=mi[L.type](M);return g===!0&&G.length>0&&Array.isArray(M.value)?Lt(M):G}return Hn(Object.assign({},M,{valueSpec:L.type?$[L.type]:L}))}function Hn(M){const g=M.key,C=M.value,L=M.valueSpec||{},$=M.objectElementValidators||{},G=M.style,K=M.styleSpec;if(!o.K(C))return[new o.V(g,C,`object expected, ${o.M(C)} found`)];let te=[];for(const de in C){const xe=de.split(".")[0];let _e;$[xe]?_e=$[xe]:L[xe]?_e=Ar:$["*"]?_e=$["*"]:L["*"]&&(_e=Ar),_e?te=te.concat(_e({key:(g&&`${g}.`)+de,value:C[de],valueSpec:L[xe]||L["*"],style:G,styleSpec:K,object:C,objectKey:de},C)):te.push(new o.a5(g,C[de],`unknown property "${de}"`))}for(const de in L){if($[de])continue;const xe=L[de];xe.required&&xe.default===void 0&&C[de]===void 0&&te.push(new o.V(g,C,`missing required property "${de}"`))}return te}function Ts({key:M,value:g}){const C=tn({key:M,value:g});if(C.length)return C;const L=g;return L.indexOf("{fontstack}")===-1&&C.push(new o.V(M,g,'"glyphs" url must include a "{fontstack}" token')),L.indexOf("{range}")===-1&&C.push(new o.V(M,g,'"glyphs" url must include a "{range}" token')),C}function Un(M,g=o.a8,C={}){return Hn({key:C.key||"",value:M,valueSpec:Object.assign(g.$root,{"*":{type:"*"}}),styleSpec:g,style:M,objectElementValidators:{glyphs:Ts}})}function ir(M,g=o.a8){return ys(Un(M,g))}const Tr=M=>ys(xn(M)),ts=M=>ys(Qn(M)),Fe=M=>ys(sa(M)),Qe=M=>ys(na(M)),ot=M=>ys(Es(M)),St=M=>ys(function(g){const C=g.value,L=g.style,$=g.styleSpec,G=$.snow;if(C===void 0)return[];if(!o.K(C))return[new o.V("snow",C,`object expected, ${o.M(C)} found`)];let K=[];for(const te in C){const de=te.match(/^(.*)-transition$/);K=K.concat(de&&G[de[1]]&&G[de[1]].transition?Ar({key:te,value:C[te],valueSpec:$.transition,style:L,styleSpec:$}):G[te]?Ar({key:te,value:C[te],valueSpec:G[te],style:L,styleSpec:$}):[new o.a5(te,C[te],`unknown property "${te}"`)])}return K}(M)),Bt=M=>ys(function(g){const C=g.value,L=g.style,$=g.styleSpec,G=$.rain;if(C===void 0)return[];if(!o.K(C))return[new o.V("rain",C,`object expected, ${o.M(C)} found`)];let K=[];for(const te in C){const de=te.match(/^(.*)-transition$/);K=K.concat(de&&G[de[1]]&&G[de[1]].transition?Ar({key:te,value:C[te],valueSpec:$.transition,style:L,styleSpec:$}):G[te]?Ar({key:te,value:C[te],valueSpec:G[te],style:L,styleSpec:$}):[new o.a5(te,C[te],`unknown property "${te}"`)])}return K}(M)),Vt=M=>ys(an(M)),fs=M=>ys(As(M)),lt=M=>ys(ks(M)),ns=M=>ys($s(M)),Vs=M=>ys(o.a9(M));function ys(M){return M.slice().sort((g,C)=>g.line&&C.line?g.line-C.line:0)}function mn(M,g){let C=!1;if(g&&g.length)for(const L of g)L instanceof o.a5?o.w(L.message):(M.fire(new o.B(new Error(L.message))),C=!0);return C}const On=o.a8.light;let vn;class Yn extends o.E{constructor(g,C="flat"){super(),this._transitionable=new o.aa(vn||(vn=new o.ab({anchor:new o.ac(On.anchor),position:new o.ad(On.position),color:new o.ac(On.color),intensity:new o.ac(On.intensity)}))),this.setLight(g,C),this._transitioning=this._transitionable.untransitioned()}getLight(){return this._transitionable.serialize()}setLight(g,C,L={}){this._validate(ts,g,L)||(this._transitionable.setTransitionOrValue(g),this.id=C)}updateTransitions(g){this._transitioning=this._transitionable.transitioned(g,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(g){this.properties=this._transitioning.possiblyEvaluate(g)}_validate(g,C,L){return(!L||L.validate!==!1)&&mn(this,g.call(ir,Object.assign({value:C,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}const _r=o.a8.terrain;let wr=class extends o.E{constructor(M,g,C,L,$){super(),this.scope=C,this._transitionable=new o.aa(new o.ab({source:new o.ac(_r.source),exaggeration:new o.ac(_r.exaggeration)}),C,L),this._transitionable.setTransitionOrValue(M,L),this._transitioning=this._transitionable.untransitioned(),this.drapeRenderMode=g,this.worldview=$}get(){return this._transitionable.serialize()}set(M,g){this._transitionable.setTransitionOrValue(M,g)}updateTransitions(M){this._transitioning=this._transitionable.transitioned(M,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(M){this.properties=this._transitioning.possiblyEvaluate(M)}getExaggeration(M){return this._transitioning.possiblyEvaluate(new o.ae(M,{worldview:this.worldview})).get("exaggeration")}getAttenuationRange(){if(!this.isZoomDependent())return null;const M=this._transitionable._values.exaggeration;if(!M)return null;const g=M.value.expression;if(!g)return null;let C=-1,L=-1,$=1;for(const G of g.zoomStops)$=g.evaluate(new o.ae(G,{worldview:this.worldview})),$>.01?(C=G,L=-1):L=G;return $<.01&&C>0&&L>C?[C,L]:null}isZoomDependent(){const M=this._transitionable._values.exaggeration;return M!=null&&M.value!=null&&M.value.expression!=null&&M.value.expression instanceof o.af}};const Er=.05;function xa(M,g,C,L){const $=o.aj(45,65,C),[G,K]=Ki(M,L);let te=1-Math.min(1,Math.exp((g-G)/(K-G)*-6));return te*=te*te,te=Math.min(1,1.00747*te),te*$*M.alpha}function Ki(M,g){const C=.5/Math.tan(.5*g);return[M.range[0]+C,M.range[1]+C]}function io(M,g,C,L,$){const G=o.ah([],[g,C,L],$.mercatorFogMatrix);return xa(M,o.ai(G),$.pitch,$._fov)}function Xa(M,g,C,L,$,G,K){const te=[[C,L,0],[$,L,0],[$,G,0],[C,G,0]];let de=Number.MAX_VALUE,xe=-Number.MAX_VALUE;for(const _e of te){const Oe=o.ah([],_e,g),De=o.ai(Oe);de=Math.min(de,De),xe=Math.max(xe,De)}return[xa(M,de,K.pitch,K._fov),xa(M,xe,K.pitch,K._fov)]}const Mr=o.a8.fog;class qi extends o.E{constructor(g,C,L,$){super();const G=new o.ab({range:new o.ac(Mr.range),color:new o.ac(Mr.color),"color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"high-color":new o.ac(Mr["high-color"]),"high-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"space-color":new o.ac(Mr["space-color"]),"space-color-use-theme":new o.ac({type:"string","property-type":"data-constant",default:"default"}),"horizon-blend":new o.ac(Mr["horizon-blend"]),"star-intensity":new o.ac(Mr["star-intensity"]),"vertical-range":new o.ac(Mr["vertical-range"])});this._transitionable=new o.aa(G,L,new Map($)),this.set(g,$),this._transitioning=this._transitionable.untransitioned(),this._transform=C,this.properties=new o.ak(G),this.scope=L}get state(){const g=this._transform,C=g.projection.name==="globe",L=o.al(g.zoom),$=this.properties.get("range"),G=[.5,3];return{range:C?[o.am(G[0],$[0],L),o.am(G[1],$[1],L)]:$,horizonBlend:this.properties.get("horizon-blend"),alpha:this.properties.get("color").a}}get(){return this._transitionable.serialize()}set(g,C,L={}){if(this._validate(ot,g,L))return;const $=Object.assign({},g);for(const G of Object.keys(Mr))$[G]===void 0&&($[G]=Mr[G].default);this._options=$,this._transitionable.setTransitionOrValue(this._options,C)}getOpacity(g){if(!this._transform.projection.supportsFog)return 0;const C=this.properties&&this.properties.get("color")||1;return(this._transform.projection.name==="globe"?1:o.aj(45,65,g))*C.a}getOpacityAtLatLng(g,C){return this._transform.projection.supportsFog?function(L,$,G){const K=o.ag.fromLngLat($),te=G.elevation?G.elevation.getAtPointOrZero(K):0;return io(L,K.x,K.y,te,G)}(this.state,g,C):0}getOpacityForTile(g){if(!this._transform.projection.supportsFog)return[1,1];const C=this._transform.calculateFogTileMatrix(g.toUnwrapped());return Xa(this.state,C,0,0,o.an,o.an,this._transform)}getOpacityForBounds(g,C,L,$,G){return this._transform.projection.supportsFog?Xa(this.state,g,C,L,$,G,this._transform):[1,1]}getFovAdjustedRange(g){return this._transform.projection.supportsFog?Ki(this.state,g):[0,1]}isVisibleOnFrustum(g){if(!this._transform.projection.supportsFog)return!1;const C=[4,5,6,7];for(const L of C){const $=g.points[L];let G;if($[2]>=0)G=$;else{const K=g.points[L-4];G=o.ao(K,$,K[2]/(K[2]-$[2]))}if(io(this.state,G[0],G[1],0,this._transform)>=Er)return!0}return!1}updateConfig(g){this._transitionable.setTransitionOrValue(this._options,new Map(g))}updateTransitions(g){this._transitioning=this._transitionable.transitioned(g,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(g){this.properties=this._transitioning.possiblyEvaluate(g)}_validate(g,C,L){return(!L||L.validate!==!1)&&mn(this,g.call(ir,Object.assign({value:C,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}}let Vi,si,Yi,Zi=class extends o.E{constructor(M,g,C,L){super();const $=Vi||(Vi=new o.ab({density:new o.ac(o.a8.snow.density),intensity:new o.ac(o.a8.snow.intensity),color:new o.ac(o.a8.snow.color),opacity:new o.ac(o.a8.snow.opacity),vignette:new o.ac(o.a8.snow.vignette),"vignette-color":new o.ac(o.a8.snow["vignette-color"]),"center-thinning":new o.ac(o.a8.snow["center-thinning"]),direction:new o.ac(o.a8.snow.direction),"flake-size":new o.ac(o.a8.snow["flake-size"])}));this._transitionable=new o.aa($,C,new Map(L)),this.set(M,L),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak($),this.scope=C}get state(){const M=this.properties.get("opacity"),g=this.properties.get("color"),C=this.properties.get("direction"),L=o.ap(C[0]),$=-Math.max(o.ap(C[1]),.01),G=[Math.cos(L)*Math.cos($),Math.sin(L)*Math.cos($),Math.sin($)],K=this.properties.get("vignette"),te=this.properties.get("vignette-color");return te.a=K,{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(g.r,g.g,g.b,g.a*M),direction:G,centerThinning:this.properties.get("center-thinning"),flakeSize:this.properties.get("flake-size"),vignetteColor:te}}get(){return this._transitionable.serialize()}set(M,g,C={}){if(this._validate(St,M,C))return;const L=Object.assign({},M),$=o.a8.snow;for(const G of Object.keys($))L[G]===void 0&&(L[G]=$[G].default);this._options=L,this._transitionable.setTransitionOrValue(this._options,g)}updateConfig(M){this._transitionable.setTransitionOrValue(this._options,new Map(M))}updateTransitions(M){this._transitioning=this._transitionable.transitioned(M,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(M){this.properties=this._transitioning.possiblyEvaluate(M)}_validate(M,g,C){return(!C||C.validate!==!1)&&mn(this,M.call(ir,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}},aa=class extends o.E{constructor(M,g,C,L){super();const $=si||(si=new o.ab({density:new o.ac(o.a8.rain.density),intensity:new o.ac(o.a8.rain.intensity),color:new o.ac(o.a8.rain.color),opacity:new o.ac(o.a8.rain.opacity),vignette:new o.ac(o.a8.rain.vignette),"vignette-color":new o.ac(o.a8.rain["vignette-color"]),"center-thinning":new o.ac(o.a8.rain["center-thinning"]),direction:new o.ac(o.a8.rain.direction),"droplet-size":new o.ac(o.a8.rain["droplet-size"]),"distortion-strength":new o.ac(o.a8.rain["distortion-strength"])}));this._transitionable=new o.aa($,C,new Map(L)),this.set(M,L),this._transitioning=this._transitionable.untransitioned(),this.properties=new o.ak($),this.scope=C}get state(){const M=this.properties.get("opacity"),g=this.properties.get("color"),C=this.properties.get("direction"),L=o.ap(C[0]),$=-Math.max(o.ap(C[1]),.01),G=[Math.cos(L)*Math.cos($),Math.sin(L)*Math.cos($),Math.sin($)],K=this.properties.get("vignette-color");return K.a=this.properties.get("vignette"),{density:this.properties.get("density"),intensity:this.properties.get("intensity"),color:new o.aq(g.r,g.g,g.b,g.a*M),direction:G,centerThinning:this.properties.get("center-thinning"),dropletSize:this.properties.get("droplet-size"),distortionStrength:this.properties.get("distortion-strength"),vignetteColor:K}}get(){return this._transitionable.serialize()}set(M,g,C={}){if(this._validate(Bt,M,C))return;const L=Object.assign({},M),$=o.a8.rain;for(const G of Object.keys($))L[G]===void 0&&(L[G]=$[G].default);this._options=L,this._transitionable.setTransitionOrValue(this._options,g)}updateConfig(M){this._transitionable.setTransitionOrValue(this._options,new Map(M))}updateTransitions(M){this._transitioning=this._transitionable.transitioned(M,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(M){this.properties=this._transitioning.possiblyEvaluate(M)}_validate(M,g,C){return(!C||C.validate!==!1)&&mn(this,M.call(ir,Object.assign({value:g,style:{glyphs:!0,sprite:!0},styleSpec:o.a8})))}};class Nn extends o.E{constructor(g,C,L,$){super(),this.scope=L,this._options=g,this.properties=new o.ak(C),this._transitionable=new o.aa(C,L,new Map($)),this._transitionable.setTransitionOrValue(g.properties),this._transitioning=this._transitionable.untransitioned()}updateConfig(g){this._transitionable.setTransitionOrValue(this._options.properties,new Map(g))}updateTransitions(g){this._transitioning=this._transitionable.transitioned(g,this._transitioning)}hasTransition(){return this._transitioning.hasTransition()}recalculate(g){this.properties=this._transitioning.possiblyEvaluate(g)}get(){return this._options.properties=this._transitionable.serialize(),this._options}set(g,C){this._options=g,this._transitionable.setTransitionOrValue(g.properties,C)}shadowsEnabled(){return!!this.properties&&this.properties.get("cast-shadows")===!0}}const La=()=>Yi||(Yi=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 so;const tl=()=>so||(so=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 jl{constructor(g,C,L){this.screenBounds=g,this.cameraPoint=L.getCameraPoint(),this._screenRaycastCache={},this._cameraRaycastCache={},this.isAboveHorizon=C,this.screenGeometry=this.bufferedScreenGeometry(0),this.screenGeometryMercator=this._bufferedScreenMercator(0,L)}static createFromScreenPoints(g,C){let L,$;if(g instanceof o.P||typeof g[0]=="number"){const G=o.P.convert(g);L=[G],$=C.isPointAboveHorizon(G)}else{const G=o.P.convert(g[0]),K=o.P.convert(g[1]),te=G.add(K)._div(2);L=[G,K],$=o.as(G,K).every(de=>C.isPointAboveHorizon(de))&&C.isPointAboveHorizon(te)}return new jl(L,$,C)}isPointQuery(){return this.screenBounds.length===1}bufferedScreenGeometry(g){return o.as(this.screenBounds[0],this.screenBounds.length===1?this.screenBounds[0]:this.screenBounds[1],g)}bufferedCameraGeometry(g){const C=this.screenBounds[0],L=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],$=o.as(C,L,0,!1);return this.cameraPoint.y>L.y&&(this.cameraPoint.x>C.x&&this.cameraPoint.x=L.x?$[2]=this.cameraPoint:this.cameraPoint.x<=C.x&&($[3]=this.cameraPoint)),o.at($,g)}bufferedCameraGeometryGlobe(g){const C=this.screenBounds[0],L=this.screenBounds.length===1?this.screenBounds[0].add(new o.P(1,1)):this.screenBounds[1],$=o.as(C,L,g),G=this.cameraPoint.clone(),K=+(G.x>C.x)+ +(G.x>L.x);switch(3*(+(G.y>C.y)+ +(G.y>L.y))+K){case 0:$[0]=G,$[4]=G.clone();break;case 1:$.splice(1,0,G);break;case 2:$[1]=G;break;case 3:$.splice(4,0,G);break;case 5:$.splice(2,0,G);break;case 6:$[3]=G;break;case 7:$.splice(3,0,G);break;case 8:$[2]=G}return $}containsTile(g,C,L,$=0){const G=Math.max(g.queryPadding,g.evaluateQueryRenderedFeaturePadding())/C._pixelsPerMercatorPixel+1,K=L?this._bufferedCameraMercator(G,C):this._bufferedScreenMercator(G,C);let te=g.tileID.wrap+(K.unwrapped?$:0);const de=K.polygon.map(pt=>o.au(g.tileTransform,pt,te));if(!o.av(de,0,0,o.an,o.an))return;te=g.tileID.wrap+(this.screenGeometryMercator.unwrapped?$:0);const xe=this.screenGeometryMercator.polygon.map(pt=>o.aw(g.tileTransform,pt,te)),_e=xe.map(pt=>new o.P(pt[0],pt[1])),Oe=C.getFreeCameraOptions().position||new o.ag(0,0,0),De=o.aw(g.tileTransform,Oe,te),qe=xe.map(pt=>{const mt=o.ax(pt,pt,De);return o.ay(mt,mt),new o.az(De,mt)}),st=o.aA(g,1,C.zoom)*C._pixelsPerMercatorPixel;return{queryGeometry:this,tilespaceGeometry:_e,tilespaceRays:qe,bufferedTilespaceGeometry:de,bufferedTilespaceBounds:(Xe=o.aB(de),Xe.min.x=o.aC(Xe.min.x,0,o.an),Xe.min.y=o.aC(Xe.min.y,0,o.an),Xe.max.x=o.aC(Xe.max.x,0,o.an),Xe.max.y=o.aC(Xe.max.y,0,o.an),Xe),tile:g,tileID:g.tileID,pixelToTileUnitsFactor:st};var Xe}_bufferedScreenMercator(g,C){const L=Bu(g);if(this._screenRaycastCache[L])return this._screenRaycastCache[L];{let $;return $=C.projection.name==="globe"?this._projectAndResample(this.bufferedScreenGeometry(g),C):{polygon:this.bufferedScreenGeometry(g).map(G=>C.pointCoordinate3D(G)),unwrapped:!0},this._screenRaycastCache[L]=$,$}}_bufferedCameraMercator(g,C){const L=Bu(g);if(this._cameraRaycastCache[L])return this._cameraRaycastCache[L];{let $;return $=C.projection.name==="globe"?this._projectAndResample(this.bufferedCameraGeometryGlobe(g),C):{polygon:this.bufferedCameraGeometry(g).map(G=>C.pointCoordinate3D(G)),unwrapped:!0},this._cameraRaycastCache[L]=$,$}}_projectAndResample(g,C){const L=function(G,K){const te=o.aD([],K.pixelMatrix,K.globeMatrix),de=[0,-o.aF,0,1],xe=[0,o.aF,0,1],_e=[0,0,0,1];o.aE(de,de,te),o.aE(xe,xe,te),o.aE(_e,_e,te);const Oe=new o.P(de[0]/de[3],de[1]/de[3]),De=new o.P(xe[0]/xe[3],xe[1]/xe[3]),qe=o.aG(G,Oe)&&de[3]<_e[3],st=o.aG(G,De)&&xe[3]<_e[3];if(!qe&&!st)return null;const Xe=function(Qt,At,Dt){for(let Ht=1;Ht1?No(G.slice(0,pt),K):[],Et=ptnew o.P(jd(Qt.x),Qt.y)),Et=Et.map(Qt=>new o.P(jd(Qt.x),Qt.y));const xt=[...kt];xt.length===0&&xt.push(Et[Et.length-1]);const es=o.am(xt[xt.length-1].y,(Et.length===0?kt[0]:Et[0]).y,mt);let Ot;return Ot=qe?[new o.P(0,es),new o.P(0,0),new o.P(1,0),new o.P(1,es)]:[new o.P(1,es),new o.P(1,1),new o.P(0,1),new o.P(0,es)],xt.push(...Ot),Et.length===0?xt.push(kt[0]):xt.push(...Et),{polygon:xt.map(Qt=>new o.ag(Qt.x,Qt.y)),unwrapped:!1}}(g,C);if(L)return L;const $=function(G,K){let te=!1,de=-1/0,xe=0;for(let Oe=0;Oede&&(de=G[Oe].x,xe=Oe);for(let Oe=0;Oe.5&&(qe.x{Oe.x-=1}),{polygon:G,unwrapped:te}}(No(g,C).map(G=>new o.P(jd(G.x),G.y)),C);return{polygon:$.polygon.map(G=>new o.ag(G.x,G.y)),unwrapped:$.unwrapped}}}function No(M,g){return o.aI(M,C=>{const L=g.pointCoordinate3D(C);C.x=L.x,C.y=L.y},1/256)}function jd(M){return M<0?1+M%1:M%1}function Bu(M){return 100*M|0}function kf(M,g,C){try{g=function($){if(!$.variants)return $;if(!Array.isArray($.variants))throw new Error("variants must be an array");for(const G of $.variants){if(G==null||typeof G!="object"||G.constructor!==Object)throw new Error("variant must be an object");if(!Array.isArray(G.capabilities))throw new Error("capabilities must be an array");if(G.capabilities.length===1&&G.capabilities[0]==="meshopt")return Object.assign($,G)}return $}(g)}catch($){return new Error("Failed to process TileJSON variants",{cause:$})}const L=o.aJ(Object.assign({},g,M),["tilejson","tiles","minzoom","maxzoom","attribution","mapbox_logo","bounds","extra_bounds","scheme","tileSize","encoding","vector_layers","raster_layers","worldview_options","worldview_default","worldview"]);return M.url&&g.tiles&&M.tiles&&(L.tiles=g.tiles),L.tiles=C.canonicalizeTileset(L,M.url),L}function $u(M,g,C,L,$){const G=function(te,de){if(te)return $(te);if(de){M.url&&de.tiles&&M.tiles&&delete M.tiles;const xe=kf(M,de,g);if(xe instanceof Error)return $(xe);$(null,xe)}},K=function(te,de,xe){if(!te)return null;if(!de&&!xe)return te;xe=xe||te.worldview_default;const _e=Object.values(te.language||{});if(_e.length===0)return null;const Oe=Object.values(te.worldview||{});if(Oe.length===0)return null;const De=_e.every(st=>st===de),qe=Oe.every(st=>st===xe);return De&&qe?te:de in(te.language_options||{})||xe in(te.worldview_options||{})?null:te.language_options&&te.worldview_options?te:null}(M.data,C,L);return K?o.o.frame(()=>G(null,K)):M.url?o.m(g.transformRequest(g.normalizeSourceURL(M.url,null,C,L),o.R.Source),G):o.o.frame(()=>{const{data:te,...de}=M;G(null,de)})}function um(M,g){const C=Math.pow(2,g.z),L=Math.floor(o.aH(M.getWest())*C),$=Math.floor(o.aL(M.getNorth())*C),G=Math.ceil(o.aH(M.getEast())*C),K=Math.ceil(o.aL(M.getSouth())*C);return g.x>=L&&g.x=$&&g.ythis.maxzoom||g.z{this._tileJSONRequest=null,this._loaded=!0,K?(C&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${C}`),L&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${L}`),this.fire(new o.B(K))):te&&(this._setTileJSON(te),Te(te.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),g&&g(K)};this.provider=this._options.provider;const G=function(K){if("provider"in K&&!K.provider)return null;let te=K.provider;if(!te&&"url"in K&&K.url&&(te=o.aM(K.url)),!te)return null;const de=o.g.TILE_PROVIDER_URLS[te];if(!de)return null;let xe;try{xe=new URL(de,o.g.API_URL).href}catch{return o.w(`TileProvider "${te}" has an invalid URL: "${de}"`),null}return{name:te,url:xe}}(this._options);if(this.provider&&!G)return this._loaded=!0,this.fire(new o.B(new Error(`TileProvider "${this.provider}" is not registered`))),void(g&&g());this._tileJSONRequest=G?this._loadWithProvider(G,$):$u(this._options,this.map._requestManager,C,L,$)}_loadWithProvider(g,C){this.provider=g.name;const L=new AbortController,$=this._options.url&&!this._options.tiles?this.map._requestManager.transformRequest(this._options.url,o.R.Source):void 0,G=$?Object.assign({},this._options,{url:$.url}):this._options;return this.dispatcher.broadcast("loadTileProvider",{name:g.name,url:g.url,source:this.id,scope:this.scope,type:this.type,options:G,request:$},(K,te)=>{if(L.signal.aborted)return;if(K)return void C(K);const de=te?te.find(xe=>xe!=null):null;if(de){const xe=kf(this._options,de,this.map._requestManager);xe instanceof Error?C(xe):C(null,xe)}else C(null,{tiles:this._options.tiles})}),{cancel:()=>{L.abort()}}}_setTileJSON(g){if(Object.assign(this,g),this.hasWorldviews=!!g.worldview_options,g.worldview_default&&(this.worldviewDefault=g.worldview_default),g.vector_layers){this.vectorLayers=g.vector_layers,this.vectorLayerIds=[],this.localizableLayerIds=new Set;for(const C of g.vector_layers)this.vectorLayerIds.push(C.id),g.worldview&&g.worldview[C.source]&&this.localizableLayerIds.add(C.id)}this.tileBounds=Uu.fromTileJSON(g)}loaded(){return this._loaded}hasTile(g){return!this.tileBounds||this.tileBounds.contains(g.canonical)}onAdd(g){this.map=g,this.load()}reload(){this.cancelTileJSONRequest();const g=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(g))}setTiles(g){return this._options.tiles=g,this.reload(),this}setUrl(g){return this.url=g,this._options.url=g,this.reload(),this}onRemove(g){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}loadTile(g,C){const L=g.tileID.canonical.url(this.tiles,this.scheme),$=this.map._requestManager.normalizeTileURL(L),G=this.map._requestManager.transformRequest($,o.R.Tile),K=this.map.style?this.map.style.getLut(this.scope):null,te=K?{image:K.image.clone()}:null,de={request:G,data:void 0,uid:g.uid,tileID:g.tileID,tileZoom:g.tileZoom,zoom:g.tileID.overscaledZ,maxZoom:this.maxzoom,lut:te,tileSize:this.tileSize*g.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,renderSourceType:g.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:g.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)&&(de.localizableLayerIds=this.localizableLayerIds),de.request.collectResourceTiming=this._collectResourceTiming,g.actor&&g.state!=="expired")g.state==="loading"?g.reloadCallback=C:g.request=g.actor.send("reloadTile",de,xe.bind(this));else if(g.actor=this._tileWorkers[$]=this._tileWorkers[$]||this.dispatcher.getActor(),this.dispatcher.ready||this.provider)g.request=g.actor.send("loadTile",de,xe.bind(this),void 0,!0);else{const _e=o.aO.call({deduped:this._deduped},de,(Oe,De)=>{if(Oe||!De)xe.call(this,Oe);else{const qe=o.aP(De.responseHeaders);de.data={rawData:De.rawData.slice(0),expires:qe.expires,cacheControl:qe.cacheControl},g.actor&&g.actor.send("loadTile",de,xe.bind(this),void 0,!0)}},!0);g.request={cancel:_e}}function xe(_e,Oe){return delete g.request,g.aborted?C(null):_e?C(_e):(Oe&&Oe.resourceTiming&&(g.resourceTiming=Oe.resourceTiming),this.map._refreshExpiredTiles&&Oe&&g.setExpiryData(Oe),g.loadVectorData(Oe,this.map.painter),o.aQ(this.dispatcher),C(null,Oe),void(g.reloadCallback&&(this.loadTile(g,g.reloadCallback),g.reloadCallback=null)))}}abortTile(g){g.request&&(g.request.cancel(),delete g.request),g.actor&&g.actor.send("abortTile",{uid:g.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(g,C){g.actor&&g.actor.send("removeTile",{uid:g.uid,type:this.type,source:this.id,scope:this.scope}),g.destroy()}hasTransition(){return!1}afterUpdate(){this._tileWorkers={}}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}class s1 extends o.E{constructor(g,C,L,$){super(),this.id=g,this.dispatcher=L,this.setEventedParent($),this.type="raster",this.minzoom=0,this.maxzoom=22,this.roundZoom=!0,this.scheme="xyz",this.tileSize=512,this._loaded=!1,this._options=Object.assign({type:"raster"},C),Object.assign(this,o.aJ(C,["url","scheme","tileSize"]))}load(g){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const C=this.map.getWorldview();this._tileJSONRequest=$u(this._options,this.map._requestManager,null,C,(L,$)=>{this._tileJSONRequest=null,this._loaded=!0,L?this.fire(new o.B(L)):$&&(Object.assign(this,$),$.raster_layers&&(this.rasterLayers=$.raster_layers,this.rasterLayerIds=this.rasterLayers.map(G=>G.id)),this.tileBounds=Uu.fromTileJSON($),Te($.tiles),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),g&&g(L)})}loaded(){return this._loaded}onAdd(g){this.map=g,this.load()}reload(){this.cancelTileJSONRequest();const g=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(g))}setTiles(g){return this._options.tiles=g,this.reload(),this}setUrl(g){return this.url=g,this._options.url=g,this.reload(),this}onRemove(g){this.cancelTileJSONRequest()}serialize(){return Object.assign({},this._options)}hasTile(g){return!this.tileBounds||this.tileBounds.contains(g.canonical)}loadTile(g,C){const L=o.o.devicePixelRatio>=2,$=this.map._requestManager.normalizeTileURL(g.tileID.canonical.url(this.tiles,this.scheme),L,this.tileSize);g.request=o.n(this.map._requestManager.transformRequest($,o.R.Tile),(G,K,te)=>{if(delete g.request,g.aborted)return g.state="unloaded",C(null);if(G)return g.state="errored",C(G);if(!K)return C(null);const de=o.aP(te);this.map._refreshExpiredTiles&&g.setExpiryData(de),g.setTexture(K,this.map.painter),g.state="loaded",o.aQ(this.dispatcher),C(null)})}abortTile(g,C){g.request&&(g.request.cancel(),delete g.request),C&&C()}unloadTile(g,C){g.texture&&g.texture instanceof o.T?(g.destroy(!1),g.texture&&g.texture instanceof o.T&&this.map.painter.saveTileTexture(g.texture)):g.destroy(),C&&C()}hasTransition(){return!1}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}}function rj([M,g],C,L,{scaled:$=!0}={}){const{tileSize:G,buffer:K}=L,{x:te,y:de,z:xe}=C;if(!isFinite(te)||!isFinite(de)||!isFinite(xe))throw new Error("Invalid MRT header");const _e=2**xe,Oe=_e*o.aH(M),De=_e*o.aL(g);return function([qe,st],Xe,{scaled:pt=!0}={}){if(!Xe)throw new Error("bandView is undefined");const{data:mt,tileSize:kt,buffer:Et,offset:xt,scale:es,dimension:Ot}=Xe;if(qe<-Et||qe>kt+Et||st<-Et||st>kt+Et)throw new Error(`Point (${qe}, ${st}) out of bounds for tileSize=${kt}, buffer=${Et}`);const Qt=(st+Et)*(kt+2*Et)+(qe+Et);if(new Uint32Array(mt.buffer)[Qt]===4294967295)return null;let At=[];At=pt?[]:new Xe.data.constructor(Ot);for(let Dt=0;Dt{if(delete g.request,g.aborted)return g.state="unloaded",C(null);if(te)return te.name==="AbortError"?void 0:(g.state="errored",C(te));if(this.map._refreshExpiredTiles&&de){const _e=o.aP(xe);g.setExpiryData(_e)}if(this.partial&&g.state!=="expired")g.state="empty";else if(!this.partial){if(!de)return C(null);g.state="loaded",g._isHeaderLoaded=!0,g._mrt=de}C(null)};g.request=this.partial?g.fetchHeader(void 0,K.bind(this)):g.actor.send("loadTile",G,K.bind(this),void 0,!0)}abortTile(g){g.request&&(g.request.cancel(),delete g.request),g.actor&&g.actor.send("abortTile",{uid:g.uid,type:this.type,source:this.id,scope:this.scope})}unloadTile(g,C){const L=g.texturePerLayer;if(g.flushAllQueues(),L.size){g.destroy(!1);for(const $ of L.values())this.map.painter.saveTileTexture($)}else g.destroy()}prepareTile(g,C,L,$){g._isHeaderLoaded&&(g.state!=="empty"&&(g.state="reloading"),g.fetchBandForRender(C,L,$,(G,K)=>{G?(g.state="errored",this.fire(new o.B(G))):K&&(g._isHeaderLoaded=!0,g.setTexturePerLayer(L,K,this.map.painter),g.state="loaded"),this.triggerRepaint(g)}))}getInitialBand(g){if(!this.rasterLayers)return 0;const C=this.rasterLayers.find(({id:G})=>G===g),L=C&&C.fields,$=L&&L.bands&&L.bands;return $?$[0]:0}getTextureDescriptor(g,C,L){if(!g)return;const $=C.sourceLayer||this.rasterLayerIds&&this.rasterLayerIds[0];if(!$)return;let G=null;C instanceof o.aS?G=C.paint.get("raster-array-band"):C instanceof o.aT&&(G=C.paint.get("raster-particle-array-band"));const K=G||this.getInitialBand($);if(K==null)return;if(!g.textureDescriptorPerLayer.get(C.id))return void this.prepareTile(g,$,C.id,K);if(g.updateNeeded(C.id,K)&&!L)return;const te=g.textureDescriptorPerLayer.get(C.id);return Object.assign({},te,{texture:g.texturePerLayer.get(C.id)})}getImages(g,C){const L=new Map;for(const $ of g)for(const G of C){const[K,te]=G.split("/"),de=$.getLayer(K);if(!de||!de.hasBand(te)||!de.hasDataForBand(te))continue;const{bytes:xe,tileSize:_e,buffer:Oe}=de.getBandView(te),De=_e+2*Oe,qe={data:new o.q({width:De,height:De},xe),pixelRatio:2,sdf:!1,usvg:!1,version:0};L.set(G,qe)}return L}queryRasterArrayValueByBandId(g,C,L){const $=C._mrt;return new Promise(G=>{const K={},te=new Set;for(const[de,xe]of Object.entries($.layers)){if(L.layerName&&de!==L.layerName)continue;const _e={};K[de]=_e;for(const{bands:Oe}of xe.dataIndex)for(const De of Oe)L.bands&&!L.bands.includes(De)||(te.add(o.F(de,De)),C.fetchBand(de,null,De,qe=>{o.o.frame(()=>{_e[De]=qe?null:rj([g.lng,g.lat],$,xe.getBandView(De)),te.delete(o.F(de,De)),te.size===0&&G(K)})},!1))}te.size===0&&G(K)})}_loadTileForQuery(g,C){if(this._loadTileLoaded[g.uid])return void C(null,g._mrt);if(this._loadTilePending[g.uid])return void this._loadTilePending[g.uid].push(C);this._loadTilePending[g.uid]=[C];const L=this.map._requestManager.normalizeTileURL(g.tileID.canonical.url(this.tiles,this.scheme),!1,this.tileSize),$=this.map._requestManager.transformRequest(L,o.R.Tile);g.actor.send("loadTile",{request:$,uid:g.uid,tileID:g.tileID,type:this.type,source:this.id,scope:this.scope,partial:!1},(G,K,te)=>{if(G)return this._loadTilePending[g.uid].forEach(de=>de(G,null)),void delete this._loadTilePending[g.uid];if(!K)return this._loadTilePending[g.uid].forEach(de=>de(null,null)),void delete this._loadTilePending[g.uid];if(this.map._refreshExpiredTiles&&K){const de=o.aP(te);g.setExpiryData(de)}g._mrt=K,g._isHeaderLoaded=!0,g.state="loaded",this._loadTilePending[g.uid].forEach(de=>de(null,K)),this._loadTileLoaded[g.uid]=!0,delete this._loadTilePending[g.uid]},void 0,!0)}queryRasterArrayValueByAllBands(g,C,L){return new Promise(($,G)=>{this._loadTileForQuery(C,(K,te)=>{K?G(K):$(te?this.queryRasterArrayValueByBandId(g,C,L):null)})})}queryRasterArrayValue(g,C){const L=o.aU.convert(g),$=this.findLoadedParent(L);return $&&$._mrt?C.bands||!this.partial?this.queryRasterArrayValueByBandId(L,$,C):this.queryRasterArrayValueByAllBands(L,$,C):Promise.resolve(null)}findLoadedParent(g){const C=o.ag.fromLngLat(g,this.map.transform.tileSize),L=this.maxzoom+1,$=1<0&&(te[new o.aR(M.overscaledZ,$,g.z,L,g.y-1).key]={backfilled:!1},te[new o.aR(M.overscaledZ,M.wrap,g.z,g.x,g.y-1).key]={backfilled:!1},te[new o.aR(M.overscaledZ,K,g.z,G,g.y-1).key]={backfilled:!1}),g.y+1{if(this._loaded=!0,this._pendingLoad=null,L)this.fire(new o.B(L));else{const G={dataType:"source",sourceDataType:this._metadataFired?"content":"metadata"};this._collectResourceTiming&&$&&$.resourceTiming&&$.resourceTiming[this.id]&&(G.resourceTiming=$.resourceTiming[this.id]),M&&(this._partialReload=!0),this.fire(new o.C("data",G)),this._partialReload=!1,this._metadataFired=!0}this._coalesce&&(this._updateWorkerData(M),this._coalesce=!1)})}loaded(){return this._loaded}reload(){const M=o.F(this.id,this.scope);this.map.style.clearSource(M),this._updateWorkerData()}loadTile(M,g){const C=M.actor?"reloadTile":"loadTile";M.actor=this.actor;const L=this.map.style?this.map.style.getLut(this.scope):null,$=L?{image:L.image.clone()}:null,G=this._partialReload,K={type:this.type,uid:M.uid,tileID:M.tileID,tileZoom:M.tileZoom,zoom:M.tileID.overscaledZ,maxZoom:this.maxzoom,tileSize:this.tileSize,source:this.id,lut:$,scope:this.scope,pixelRatio:o.o.devicePixelRatio,showCollisionBoxes:this.map.showCollisionBoxes,promoteId:this.promoteId,brightness:this.map.style&&this.map.style.getBrightness()||0,extraShadowCaster:M.isExtraShadowCaster,scaleFactor:this.map.getScaleFactor(),partial:G,worldview:this.map.getWorldview(),indoor:this.map.getIndoorTileOptions(this.id,this.scope)};M.request=this.actor.send(C,K,(te,de)=>G&&!de?(M.state="loaded",g(null)):(delete M.request,M.destroy(!1),M.aborted?g(null):te?g(te):(M.loadVectorData(de,this.map.painter,C==="reloadTile"),g(null))),void 0,C==="loadTile")}abortTile(M){M.request&&(M.request.cancel(),delete M.request),M.aborted=!0}unloadTile(M,g){this.actor.send("removeTile",{uid:M.uid,type:this.type,source:this.id,scope:this.scope}),M.destroy()}onRemove(M){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(M,g,C,L){super(M,g,C,L),this.roundZoom=!0,this.type="video",this.options=g}load(){this._loaded=!1;const M=this.options;this.urls=[];for(const g of M.urls)this.urls.push(this.map._requestManager.transformRequest(g,o.R.Source).url);o.aW(this.urls,(g,C)=>{this._loaded=!0,g?this.fire(new o.B(g)):C&&(this.video=C,this.video.loop=!0,this.video.setAttribute("playsinline",""),this.video.addEventListener("playing",()=>{this.map.triggerRepaint()}),this.map&&this.video.play(),this._finishLoading())})}pause(){this.video&&this.video.pause()}play(){this.video&&this.video.play()}seek(M){if(this.video){const g=this.video.seekable;Mg.end(0)?this.fire(new o.B(new o.V(`sources.${this.id}`,null,`Playback for this video can be set only between the ${g.start(0)} and ${g.end(0)}-second mark.`))):this.video.currentTime=M}}getVideo(){return this.video}onAdd(M){this.map||(this.map=M,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 M=this.map.painter.context,g=M.gl;this.texture?this.video.paused||(this.texture.bind(g.LINEAR,g.CLAMP_TO_EDGE),g.texSubImage2D(g.TEXTURE_2D,0,0,0,g.RGBA,g.UNSIGNED_BYTE,this.video)):(this.texture=new o.T(M,this.video,g.RGBA8),this.texture.bind(g.LINEAR,g.CLAMP_TO_EDGE),this.width=this.video.videoWidth,this.height=this.video.videoHeight),this._prepareData(M)}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(M,g,C,L){super(),this.type="batched-model",this.id=M,this.tileSize=512,this._options=g,this.tiles=this._options.tiles,this.maxzoom=g.maxzoom||19,this.minzoom=g.minzoom||0,this.roundZoom=!0,this.usedInConflation=!0,this.dispatcher=C,this.reparseOverscaled=!1,this.scheme="xyz",this._loaded=!1,this.setEventedParent(L)}onAdd(M){this.map=M,this.load()}reload(){this.cancelTileJSONRequest();const M=o.F(this.id,this.scope);this.load(()=>this.map.style.clearSource(M))}cancelTileJSONRequest(){this._tileJSONRequest&&(this._tileJSONRequest.cancel(),this._tileJSONRequest=null)}load(M){this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"}));const g=Array.isArray(this.map._language)?this.map._language.join():this.map._language,C=this.map.getWorldview();this._tileJSONRequest=$u(this._options,this.map._requestManager,g,C,(L,$)=>{this._tileJSONRequest=null,this._loaded=!0,L?(g&&console.warn(`Ensure that your requested language string is a valid BCP-47 code or list of codes. Found: ${g}`),C&&C.length!==2&&console.warn(`Requested worldview strings must be a valid ISO alpha-2 code. Found: ${C}`),this.fire(new o.B(L))):$&&(Object.assign(this,$),$.bounds&&(this.tileBounds=new Uu($.bounds,this.minzoom,this.maxzoom)),Te($.tiles,this.map._requestManager._customAccessToken),this.fire(new o.C("data",{dataType:"source",sourceDataType:"metadata"})),this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))),M&&M(L)})}hasTransition(){return!1}hasTile(M){return!this.tileBounds||this.tileBounds.contains(M.canonical)}loaded(){return this._loaded}loadTile(M,g){const C=this.map._requestManager.normalizeTileURL(M.tileID.canonical.url(this.tiles,this.scheme)),L={request:this.map._requestManager.transformRequest(C,o.R.Tile),data:void 0,uid:M.uid,tileID:M.tileID,tileZoom:M.tileZoom,zoom:M.tileID.overscaledZ,tileSize:this.tileSize*M.tileID.overscaleFactor(),type:this.type,source:this.id,scope:this.scope,showCollisionBoxes:this.map.showCollisionBoxes,renderSourceType:M.renderSourceType,brightness:this.map.style&&this.map.style.getBrightness()||0,pixelRatio:o.o.devicePixelRatio,promoteId:this.promoteId};if(M.actor&&M.state!=="expired")if(M.state==="loading")M.reloadCallback=g;else{if(M.buckets){const G=Object.values(M.buckets);for(const K of G)K.dirty=!0;return void(M.state="loaded")}M.request=M.actor.send("reloadTile",L,$.bind(this))}else M.actor=this.dispatcher.getActor(),M.request=M.actor.send("loadTile",L,$.bind(this),void 0,!0);function $(G,K){return M.aborted?g(null):G&&G.status!==404?g(G):(this.map._refreshExpiredTiles&&K&&M.setExpiryData(K),M.loadModelData(K,this.map.painter),M.state="loaded",void g(null))}}serialize(){return Object.assign({},this._options)}},canvas:class extends o.aV{constructor(M,g,C,L){super(M,g,C,L),g.coordinates?Array.isArray(g.coordinates)&&g.coordinates.length===4&&!g.coordinates.some($=>!Array.isArray($)||$.length!==2||$.some(G=>typeof G!="number"))||this.fire(new o.B(new o.V(`sources.${M}`,null,'"coordinates" property must be an array of 4 longitude/latitude array pairs'))):this.fire(new o.B(new o.V(`sources.${M}`,null,'missing required property "coordinates"'))),g.animate&&typeof g.animate!="boolean"&&this.fire(new o.B(new o.V(`sources.${M}`,null,'optional "animate" property must be a boolean value'))),g.canvas?typeof g.canvas=="string"||g.canvas instanceof HTMLCanvasElement||this.fire(new o.B(new o.V(`sources.${M}`,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.${M}`,null,'missing required property "canvas"'))),this.options=g,this.animate=g.animate===void 0||g.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(M){this.map=M,this.load(),this.canvas&&this.animate&&this.play()}onRemove(M){this.pause()}prepare(){let M=!1;if(this.canvas.width!==this.width&&(this.width=this.canvas.width,M=!0),this.canvas.height!==this.height&&(this.height=this.canvas.height,M=!0),this._hasInvalidDimensions()||Object.keys(this.tiles).length===0)return;const g=this.map.painter.context;this.texture?!M&&!this._playing||this.texture instanceof o.aX||this.texture.update(this.canvas,{premultiply:!0}):this.texture=new o.T(g,this.canvas,g.gl.RGBA8,{premultiply:!0}),this._prepareData(g)}serialize(){return{type:"canvas",coordinates:this.coordinates}}hasTransition(){return this._playing}_hasInvalidDimensions(){for(const M of[this.canvas.width,this.canvas.height])if(isNaN(M)||M<=0)return!0;return!1}},custom:class extends o.E{constructor(M,g,C,L){super(),this.id=M,this.type="custom",this._dataType="raster",this._dispatcher=C,this._implementation=g,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 Uu(this._implementation.bounds,this.minzoom,this.maxzoom));const $=g;$.update=this._update.bind(this),$.clearTiles=this._clearTiles.bind(this),$.coveringTiles=this._coveringTiles.bind(this),Object.assign(this,o.aJ(g,["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(M){this.map=M,this._loaded=!1,this.fire(new o.C("dataloading",{dataType:"source"})),this._implementation.onAdd&&this._implementation.onAdd(M),this.load()}onRemove(M){this._implementation.onRemove&&this._implementation.onRemove(M)}hasTile(M){if(this._implementation.hasTile){const{x:g,y:C,z:L}=M.canonical;return this._implementation.hasTile({x:g,y:C,z:L})}return!this.tileBounds||this.tileBounds.contains(M.canonical)}loadTile(M,g){const{x:C,y:L,z:$}=M.tileID.canonical,G=new AbortController,K=Promise.resolve(this._implementation.loadTile({x:C,y:L,z:$},{signal:G.signal})).then((function(te){return delete M.request,M.aborted?(M.state="unloaded",g(null)):te===void 0?(M.state="errored",g(null)):te===null?(this.loadTileData(M,{width:this.tileSize,height:this.tileSize,data:null}),M.state="loaded",g(null)):function(de){return de instanceof ImageData||de instanceof HTMLCanvasElement||de instanceof ImageBitmap||de instanceof HTMLImageElement}(te)?(this.loadTileData(M,te),M.state="loaded",void g(null)):(M.state="errored",g(new Error(`Can't infer data type for ${this.id}, only raster data supported at the moment`)))}).bind(this)).catch(te=>{te.name!=="AbortError"&&(M.state="errored",g(te))});K.cancel=()=>G.abort(),M.request=K}loadTileData(M,g){M.setTexture(g,this.map.painter)}unloadTile(M,g){if(M.texture&&M.texture instanceof o.T?(M.destroy(!1),M.texture&&M.texture instanceof o.T&&this.map.painter.saveTileTexture(M.texture)):M.destroy(),this._implementation.unloadTile){const{x:C,y:L,z:$}=M.tileID.canonical;this._implementation.unloadTile({x:C,y:L,z:$})}g&&g()}abortTile(M,g){M.request&&M.request.cancel&&(M.request.cancel(),delete M.request),g&&g()}hasTransition(){return!1}_coveringTiles(){return this.map.transform.coveringTiles({tileSize:this.tileSize,minzoom:this.minzoom,maxzoom:this.maxzoom,roundZoom:this.roundZoom}).map(M=>({x:M.canonical.x,y:M.canonical.y,z:M.canonical.z}))}_clearTiles(){const M=o.F(this.id,this.scope);this.map.style.clearSource(M)}_update(){this.fire(new o.C("data",{dataType:"source",sourceDataType:"content"}))}}},Ay=function(M,g,C,L){const $=new Ey[g.type](M,g,C,L);if($.id!==M)throw new Error(`Expected Source id to be ${M} instead of ${$.id}`);return o.aZ(["load","abort","unload","serialize","prepare"],$),$};function Sf(M,g,C=""){return`${C}:${g.id||""}:${g.layer.id}:${function(L){if("layerId"in L)return`layer:${L.layerId}`;{const{featuresetId:$,importId:G}=L;return`featureset:${$}${G?`:import:${G}`:""}`}}(M.target)}`}function mh(M,g,C,L=""){if(M.uniqueFeatureID){const $=Sf(M,g,L);if(C.has($))return!0;C.add($)}return!1}function ux(M,g,C,L,$=!1,G=void 0){const K=g.sourceCache.transform,te=g.sourceCache.tilesIn(M,g.has3DLayers,$);te.sort(mm);const de=[];for(const xe of te){const _e=xe.tile.queryRenderedFeatures(g,xe,C,L,K,$,G);Object.keys(_e).length&&de.push({wrappedTileID:xe.tile.tileID.wrapped().key,queryResults:_e})}for(const xe in g.layers){const _e=g.layers[xe];if(_e.styleLayer){const Oe=_e.styleLayer.queryRenderedFeatures(M,g.sourceCache,L);Object.keys(Oe).length&&de.push({wrappedTileID:0,queryResults:Oe})}}return de.length===0?{}:function(xe){const _e={},Oe={};for(const De of xe){const qe=De.queryResults,st=De.wrappedTileID,Xe=Oe[st]=Oe[st]||{};for(const pt in qe){const mt=qe[pt],kt=Xe[pt]=Xe[pt]||{},Et=_e[pt]=_e[pt]||[];for(const xt of mt)kt[xt.featureIndex]||(kt[xt.featureIndex]=!0,Et.push(xt))}}return _e}(de)}function mo(M,g,C,L,$,G){const K={},te=L.queryRenderedSymbols(M),de=[];for(const xe of Object.keys(te).map(Number))de.push($[xe]);de.sort(mm);for(const xe of de){const _e=xe.featureIndex.lookupSymbolFeatures(te[xe.bucketInstanceId],xe.bucketIndex,xe.sourceLayerIndex,g,C,G);for(const Oe in _e){const De=K[Oe]=K[Oe]||[],qe=_e[Oe];qe.sort((st,Xe)=>{const pt=xe.featureSortOrder;if(pt){const mt=pt.indexOf(st.featureIndex);return pt.indexOf(Xe.featureIndex)-mt}return Xe.featureIndex-st.featureIndex});for(const st of qe)De.push(st)}}return K}function zb(M,g){const C=M.getRenderableIds().map(G=>M.getTileByID(G)),L=[],$={};for(let G=0;G{if(G)C(G);else try{const de=L.getHeaderLength(K);if(de>g)return void(this.request=this.fetchHeader(de,C));L.parseHeader(K),this._isHeaderLoaded=!0;let xe=0;for(const _e of Object.values(L.layers))xe=Math.max(xe,_e.dataIndex[_e.dataIndex.length-1].lastByte);K.byteLength>=xe&&(this.entireBuffer=K),C(null,this.entireBuffer||K,te)}catch(de){C(de)}}),this.request}fetchBandForRender(g,C,L,$){this.fetchBand(g,C,L,G=>{if(G)return void $(G);this.updateTextureDescriptor(g,C,L);const K=this.textureDescriptorPerLayer.get(C);$(null,K?K.img:null)})}fetchBand(g,C,L,$,G=!0){const K=this._mrt;if(!this._isHeaderLoaded||!K)return void $(new Error("Tile header is not ready"));const te=this.actor;if(!te)return void $(new Error("Can't fetch tile band without an actor"));let de;const xe=o.F(String(L),o.F(this.tileID.key,g));let _e=this._taskQueue.get(xe);_e?_e.add($):(_e=new Set,_e.add($),this._taskQueue.set(xe,_e));const Oe=(Xe,pt)=>{de.complete(Xe,pt),Xe?$(Xe):(_e.forEach(mt=>mt(null,pt)),this._taskQueue.delete(xe))},De=(Xe,pt)=>{if(Xe)return $(Xe);const mt=te.send("decodeRasterArray",{type:"raster-array",source:this.source,scope:this.scope,tileID:this.tileID,uid:this.uid,buffer:pt,task:de},Oe,void 0,!0);if(C!==null){const kt=this._workQueuePerLayer.get(C)||[];kt.push(()=>{mt&&mt.cancel(),de.cancel()}),this._workQueuePerLayer.has(C)||this._workQueuePerLayer.set(C,kt)}};let qe;try{qe=K.getLayer(g)}catch(Xe){if(this.state==="reloading")return;throw Xe}if(!qe)return void $(new Error(`Unknown sourceLayer "${g}"`));if(qe.hasDataForBand(L))return _e.forEach(Xe=>Xe(null,null)),void this._taskQueue.delete(xe);const st=qe.getDataRange([L]);if(de=K.createDecodingTask(st),!de||de.tasks.length)if(C!==null&&this.flushQueues(C),this.entireBuffer)De(null,this.entireBuffer.slice(st.firstByte,st.lastByte+1));else{const Xe=Object.assign({},this.requestParams,{headers:{Range:`bytes=${st.firstByte}-${st.lastByte}`}}),pt=o.b1(Xe,De);if(C!==null){const mt=this._fetchQueuePerLayer.get(C)||[];mt.push(()=>{pt.cancel(),de.cancel()}),this._fetchQueuePerLayer.has(C)||this._fetchQueuePerLayer.set(C,mt)}}}updateNeeded(g,C){return(!this.textureDescriptorPerLayer.get(g)||this.textureDescriptorPerLayer.get(g).band!==C||this.refreshedUponExpiration)&&this.state!=="errored"}updateTextureDescriptor(g,C,L){if(!this._mrt)return;const $=this._mrt.getLayer(g);if(!$||!$.hasBand(L)||!$.hasDataForBand(L))return;const{bytes:G,tileSize:K,buffer:te,offset:de,scale:xe}=$.getBandView(L),_e=K+2*te,Oe=new o.q({width:_e,height:_e},G),De=this.texturePerLayer.get(C);De&&De instanceof o.T&&De.update(Oe,{premultiply:!1}),this.textureDescriptorPerLayer.set(C,{layer:g,band:L,img:Oe,buffer:te,offset:de,tileSize:K,format:$.pixelFormat,mix:[xe,256*xe,65536*xe,16777216*xe]})}destroy(g=!1){if(super.destroy(g),delete this._mrt,!g)for(const C of this.texturePerLayer.values())C&&C instanceof o.T&&C.destroy();this.texturePerLayer.clear(),this.textureDescriptorPerLayer.clear(),this.fbo&&(this.fbo.destroy(),delete this.fbo),delete this.request,delete this.requestParams,this._isHeaderLoaded=!1}}class hx{constructor(g,C){this.max=g,this.onRemove=C,this.reset()}reset(){for(const g in this.data)for(const C of this.data[g])C.timeout&&clearTimeout(C.timeout),this.onRemove(C.value);return this.data={},this.order=[],this}add(g,C,L){const $=g.wrapped().key;this.data[$]===void 0&&(this.data[$]=[]);const G={value:C,timeout:void 0};if(L!==void 0&&(G.timeout=setTimeout(()=>{this.remove(g,G)},L)),this.data[$].push(G),this.order.push($),this.order.length>this.max){const K=this._getAndRemoveByKey(this.order[0]);K&&this.onRemove(K)}return this}has(g){return g.wrapped().key in this.data}getAndRemove(g){return this.has(g)?this._getAndRemoveByKey(g.wrapped().key):null}_getAndRemoveByKey(g){const C=this.data[g].shift();return C.timeout&&clearTimeout(C.timeout),this.data[g].length===0&&delete this.data[g],this.order.splice(this.order.indexOf(g),1),C.value}getByKey(g){const C=this.data[g];return C?C[0].value:null}get(g){return this.has(g)?this.data[g.wrapped().key][0].value:null}remove(g,C){if(!this.has(g))return this;const L=g.wrapped().key,$=C===void 0?0:this.data[L].indexOf(C),G=this.data[L][$];return this.data[L].splice($,1),G.timeout&&clearTimeout(G.timeout),this.data[L].length===0&&delete this.data[L],this.onRemove(G.value),this.order.splice(this.order.indexOf(L),1),this}setMaxSize(g){for(this.max=g;this.order.length>this.max;){const C=this._getAndRemoveByKey(this.order[0]);C&&this.onRemove(C)}return this}filter(g){const C=[];for(const L in this.data)for(const $ of this.data[L])g($.value)||C.push($);for(const L of C)this.remove(L.value.tileID,L)}}class qu{constructor(){this.state={},this.stateChanges={},this.deletedStates={}}updateState(g,C,L){const $=String(C);if(this.stateChanges[g]=this.stateChanges[g]||{},this.stateChanges[g][$]=this.stateChanges[g][$]||{},Object.assign(this.stateChanges[g][$],L),this.deletedStates[g]===null){this.deletedStates[g]={};for(const G in this.state[g])G!==$&&(this.deletedStates[g][G]=null)}else if(this.deletedStates[g]&&this.deletedStates[g][$]===null){this.deletedStates[g][$]={};for(const G in this.state[g][$])L[G]||(this.deletedStates[g][$][G]=null)}else for(const G in L)this.deletedStates[g]&&this.deletedStates[g][$]&&this.deletedStates[g][$][G]===null&&delete this.deletedStates[g][$][G]}removeFeatureState(g,C,L){if(this.deletedStates[g]===null)return;const $=String(C);if(this.deletedStates[g]=this.deletedStates[g]||{},L&&C!==void 0)this.deletedStates[g][$]!==null&&(this.deletedStates[g][$]=this.deletedStates[g][$]||{},this.deletedStates[g][$][L]=null);else if(C!==void 0)if(this.stateChanges[g]&&this.stateChanges[g][$])for(L in this.deletedStates[g][$]={},this.stateChanges[g][$])this.deletedStates[g][$][L]=null;else this.deletedStates[g][$]=null;else this.deletedStates[g]=null}getState(g,C){const L=this.state[g]||{},$=this.stateChanges[g]||{},G=this.deletedStates[g];if(G===null)return{};if(C!==void 0){const te=String(C),de=Object.assign({},L[te],$[te]);if(G){const xe=G[C];if(xe===null)return{};for(const _e in xe)delete de[_e]}return de}const K=Object.assign({},L,$);if(G)for(const te in G)delete K[te];return K}initializeTileState(g,C){g.refreshFeatureState(C)}coalesceChanges(g,C){const L={};for(const $ in this.stateChanges){this.state[$]=this.state[$]||{};const G={};for(const K in this.stateChanges[$])this.state[$][K]||(this.state[$][K]={}),Object.assign(this.state[$][K],this.stateChanges[$][K]),G[K]=this.state[$][K];L[$]=G}for(const $ in this.deletedStates){this.state[$]=this.state[$]||{};const G={};if(this.deletedStates[$]===null)for(const K in this.state[$])G[K]={},this.state[$][K]={};else for(const K in this.deletedStates[$]){if(this.deletedStates[$][K]===null)this.state[$][K]={};else if(this.state[$][K])for(const te of Object.keys(this.deletedStates[$][K]))delete this.state[$][K][te];G[K]=this.state[$][K]}L[$]=L[$]||{},Object.assign(L[$],G)}if(this.stateChanges={},this.deletedStates={},Object.keys(L).length!==0)for(const $ in g)g[$].refreshFeatureState(C,L)}}class sl extends o.E{constructor(g,C,L){super(),this.id=g,this._renderSourceType=L,this._maxzoomOverride=null,C.on("data",$=>{$.dataType==="source"&&$.sourceDataType==="metadata"&&(this._sourceLoaded=!0),this._sourceLoaded&&!this._paused&&$.dataType==="source"&&$.sourceDataType==="content"&&(this.reload(),this.transform&&this.update(this.transform))}),C.on("error",()=>{this._sourceErrored=!0}),this._source=C,this._tiles={},this._cache=new hx(0,this._unloadTile.bind(this)),this._timers={},this._cacheTimers={},this._minTileCacheSize=C.minTileCacheSize,this._maxTileCacheSize=C.maxTileCacheSize,this._loadedParentTiles={},this.castsShadows=!1,this.tileCoverLift=0,this._coveredTiles={},this._shadowCasterTiles={},this._state=new qu,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(g){this.map=g,this._minTileCacheSize=this._minTileCacheSize===void 0&&g?g._minTileCacheSize:this._minTileCacheSize,this._maxTileCacheSize=this._maxTileCacheSize===void 0&&g?g._maxTileCacheSize:this._maxTileCacheSize}loaded(){if(this._sourceErrored)return!0;if(!this._sourceLoaded||!this._source.loaded())return!1;for(const g in this._tiles)if(!this._tiles[g].loaded())return!1;return!0}getSource(){return this._source}pause(){this._paused=!0}resume(){if(!this._paused)return;const g=this._shouldReloadOnResume;this._paused=!1,this._shouldReloadOnResume=!1,g&&this.reload(),this.transform&&this.update(this.transform)}setMaxzoomOverride(g){this._maxzoomOverride=g}_loadTile(g,C){return g.renderSourceType=this._renderSourceType,g.isExtraShadowCaster=this._shadowCasterTiles[g.tileID.key],this._source.loadTile(g,C)}_unloadTile(g){if(this._source.unloadTile)return this._source.unloadTile(g)}_abortTile(g){if(this._source.abortTile)return this._source.abortTile(g)}serialize(){return this._source.serialize()}prepare(g){this._source.prepare&&this._source.prepare(),this._state.coalesceChanges(this._tiles,this.map?this.map.painter:null);for(const C in this._tiles){const L=this._tiles[C];L.upload(g,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(g=>g.tileID).sort(o0).map(g=>g.key)}getRenderableIds(g,C){const L=[];for(const $ in this._tiles)this._isIdRenderable(+$,g,C)&&L.push(this._tiles[$]);return g?L.sort(($,G)=>{const K=$.tileID,te=G.tileID,de=new o.P(K.canonical.x,K.canonical.y)._rotate(this.transform.angle),xe=new o.P(te.canonical.x,te.canonical.y)._rotate(this.transform.angle);return K.overscaledZ-te.overscaledZ||xe.y-de.y||xe.x-de.x}).map($=>$.tileID.key):L.map($=>$.tileID).sort(o0).map($=>$.key)}hasRenderableParent(g){const C=this.findLoadedParent(g,0);return!!C&&this._isIdRenderable(C.tileID.key)}_isIdRenderable(g,C,L){return this._tiles[g]&&this._tiles[g].hasData()&&!this._coveredTiles[g]&&(C||!this._tiles[g].holdingForFade())&&(L||!this._shadowCasterTiles[g])}reload(){if(this._paused)this._shouldReloadOnResume=!0;else{this._cache.reset();for(const g in this._tiles)this._tiles[g].state!=="errored"&&this._reloadTile(+g,"reloading")}}_reloadTile(g,C){const L=this._tiles[g];L&&(L.state!=="loading"&&(L.state=C),this._loadTile(L,this._tileLoaded.bind(this,L,g,C)))}_tileLoaded(g,C,L,$,G){if($){if(g.state="errored",o.b2($)){if(this._source.fire(new o.C("data",{dataType:"source",sourceDataType:"error",sourceId:this._source.id,tile:g})),!(g.tileID.key in this._loadedParentTiles))return;if(this._source.type==="raster-dem"&&this.usedForTerrain&&this.map.painter.terrain){const te=this.map.painter.terrain;this.update(this.transform,te.getScaledDemTileSize(),!0),te.resetTileLookupCache(this.id)}else this.update(this.transform)}else this._source.fire(new o.B($,{tile:g}));return}g.timeAdded=o.o.now(),L==="expired"&&(g.refreshedUponExpiration=!0),this._setTileReloadTimer(C,g),this._source.type==="raster-dem"&&g.dem&&this._backfillDEM(g),this._state.initializeTileState(g,this.map?this.map.painter:null);let K=new Map;G&&G.responseHeaders&&(K=G.responseHeaders),this._source.fire(new o.C("data",{dataType:"source",tile:g,coord:g.tileID,sourceCacheId:this.id,responseHeaders:K}))}_hasTunnelGeometry(){for(const g in this._tiles){const C=this._tiles[g];if(C&&C.hasTunnelGeometry)return!0}return!1}_backfillDEM(g){const C=this.getRenderableIds();for(let $=0;$1||(Math.abs(K)>1&&(Math.abs(K+de)===1?K+=de:Math.abs(K-de)===1&&(K-=de)),G.dem&&$.dem&&($.dem.backfillBorder(G.dem,K,te),$.neighboringTiles&&$.neighboringTiles[xe]&&($.neighboringTiles[xe].backfilled=!0)))}}getTile(g){return this.getTileByID(g.key)}getTileByID(g){return this._tiles[g]}_retainLoadedChildren(g,C,L,$){for(const G in this._tiles){let K=this._tiles[G];if($[G]||!K.hasData()||K.tileID.overscaledZ<=C||K.tileID.overscaledZ>L)continue;let te=K.tileID;for(;K&&K.tileID.overscaledZ>C+1;){const xe=K.tileID.scaledTo(K.tileID.overscaledZ-1);K=this._tiles[xe.key],K&&K.hasData()&&(te=xe)}let de=te;for(;de.overscaledZ>C;)if(de=de.scaledTo(de.overscaledZ-1),g[de.key]){$[te.key]=te;break}}}findLoadedParent(g,C){if(g.key in this._loadedParentTiles){const L=this._loadedParentTiles[g.key];return L&&L.tileID.overscaledZ>=C?L:null}for(let L=g.overscaledZ-1;L>=C;L--){const $=g.scaledTo(L),G=this._getLoadedTile($);if(G)return G}}_getLoadedTile(g){const C=this._tiles[g.key];return C&&C.hasData()?C:this._cache.getByKey(this._source.reparseOverscaled?g.wrapped().key:g.canonical.key)}updateCacheSize(g,C){C=C||this._source.tileSize;const L=Math.ceil(g.width/C)+1,$=Math.ceil(g.height/C)+1,G=Math.floor(L*$*5),K=typeof this._minTileCacheSize=="number"?Math.max(this._minTileCacheSize,G):G,te=typeof this._maxTileCacheSize=="number"?Math.min(this._maxTileCacheSize,K):K;this._cache.setMaxSize(te)}handleWrapJump(g){const C=Math.round((g-(this._prevLng===void 0?g:this._prevLng))/360);if(this._prevLng=g,C){const L={};for(const $ in this._tiles){const G=this._tiles[$];G.tileID=G.tileID.unwrapTo(G.tileID.wrap+C),L[G.tileID.key]=G}this._tiles=L;for(const $ in this._timers)clearTimeout(this._timers[$]),delete this._timers[$];for(const $ in this._tiles)this._setTileReloadTimer(+$,this._tiles[$])}}update(g,C,L,$,G){if(this.transform=g,!this._sourceLoaded||this._paused||this.transform.freezeTileCoverage||this.usedForTerrain&&!L)return;this.updateCacheSize(g,C),this.transform.projection.name!=="globe"&&this.handleWrapJump(this.transform.center.lng),this._shadowCasterTiles={},this._coveredTiles={};const K=this._source.type==="batched-model";let te,de=this._source.maxzoom;this._maxzoomOverride!==null&&(de=Math.min(de,this._maxzoomOverride));const xe=this.map&&this.map.painter?this.map.painter._terrain:null;if(xe&&xe.sourceCache===this&&xe.attenuationRange()){const qe=xe.attenuationRange()[0],st=Math.floor(qe)-Math.log2(xe.getDemUpscale());de>st&&(de=st)}const _e=this._maxzoomOverride===null&&this._source.reparseOverscaled;if(this.used||this.usedForTerrain){if(this._source.tileID)te=g.getVisibleUnwrappedCoordinates(this._source.tileID).map(qe=>new o.aR(qe.canonical.z,qe.wrap,qe.canonical.z,qe.canonical.x,qe.canonical.y));else if(this.tileCoverLift!==0){const qe=g.clone();qe.tileCoverLift=this.tileCoverLift,te=qe.coveringTiles({tileSize:C||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:de,roundZoom:this._source.roundZoom&&!L,reparseOverscaled:_e,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:K}),this._source.minzoom<=1&&g.projection.name==="globe"&&(te.push(new o.aR(1,0,1,0,0)),te.push(new o.aR(1,0,1,1,0)),te.push(new o.aR(1,0,1,0,1)),te.push(new o.aR(1,0,1,1,1)))}else if(te=g.coveringTiles({tileSize:C||this._source.tileSize,minzoom:this._source.minzoom,maxzoom:de,roundZoom:this._source.roundZoom&&!L,reparseOverscaled:_e,isTerrainDEM:this.usedForTerrain,calculateQuadrantVisibility:K}),this._source.hasTile){const qe=this._source.hasTile.bind(this._source);te=te.filter(st=>qe(st))}}else te=[];if(te.length>0&&this.transform.projection.name!=="globe"&&!this.usedForTerrain&&!this._supportsFading){const qe=g.coveringZoomLevel({tileSize:C||this._source.tileSize,roundZoom:this._source.roundZoom&&!L}),st=Math.min(qe,de);if(K){const Xe=g.extendTileCover(te,st);for(const pt of Xe)te.push(pt)}else if(G){const Xe=this.transform.getFrustum(st),pt=g.extendTileCoverToNearPlane(te,Xe,st);for(const mt of pt)te.push(mt);if(st>=18&&this._hasTunnelGeometry()){const mt=g.extendTileCoverForTunnels(te,Xe,st,20);for(const kt of mt)te.push(kt)}}else if(this.castsShadows&&$){const Xe=g.extendTileCover(te,st,$,16);for(const pt of Xe)this._shadowCasterTiles[pt.key]=!0,te.push(pt)}}const Oe=this._updateRetainedTiles(te);if(this._supportsFading&&te.length!==0){const qe={},st={},Xe=o.o.now(),pt=Object.keys(Oe);for(const kt of pt){const Et=Oe[kt],xt=this._tiles[kt];if(!xt||xt.fadeEndTime!==void 0&&xt.fadeEndTime<=Xe)continue;const es=this.findLoadedParent(Et,Math.max(Et.overscaledZ-sl.maxOverzooming,this._source.minzoom));es&&(this._addTile(es.tileID),qe[es.tileID.key]=es.tileID),st[kt]=Et}const mt=te[te.length-1].overscaledZ;for(const kt in this._tiles){const Et=this._tiles[kt];if(Oe[kt]||!Et.hasData())continue;let xt=Et.tileID;for(;xt.overscaledZ>mt;){xt=xt.scaledTo(xt.overscaledZ-1);const es=this._tiles[xt.key];if(es&&es.hasData()&&st[xt.key]){Oe[kt]=Et.tileID;break}}}for(const kt in qe)Oe[kt]||(this._coveredTiles[kt]=!0,Oe[kt]=qe[kt])}for(const qe in Oe)this._tiles[qe].clearFadeHold();const De=o.b3(this._tiles,Oe);for(const qe of De){const st=this._tiles[qe];st.hasSymbolBuckets&&!st.holdingForFade()?st.setHoldDuration(this.map._fadeDuration):st.hasSymbolBuckets&&!st.symbolFadeFinished()||this._removeTile(+qe)}this._updateLoadedParentTileCache(),this._renderSourceType===o.b4.Symbol&&this._source.afterUpdate&&this._source.afterUpdate()}releaseSymbolFadeTiles(){for(const g in this._tiles)this._tiles[g].holdingForFade()&&this._removeTile(+g)}_updateRetainedTiles(g){const C={};if(g.length===0)return C;const L={},$=g.reduce((xe,_e)=>Math.min(xe,_e.overscaledZ),1/0),G=g[0].overscaledZ,K=Math.max(G-sl.maxOverzooming,this._source.minzoom),te=Math.max(G+sl.maxUnderzooming,this._source.minzoom),de={};for(const xe of g){const _e=this._addTile(xe);C[xe.key]=xe,_e.hasData()||$=this._source.maxzoom){const De=xe.children(this._source.maxzoom)[0],qe=this.getTile(De);if(qe&&qe.hasData()){C[De.key]=De;continue}}else{const De=xe.children(this._source.maxzoom);if(C[De[0].key]&&C[De[1].key]&&C[De[2].key]&&C[De[3].key])continue}let Oe=_e.wasRequested();for(let De=xe.overscaledZ-1;De>=K;--De){const qe=xe.scaledTo(De);if(L[qe.key]||(L[qe.key]=!0,_e=this.getTile(qe),!_e&&Oe&&(_e=this._addTile(qe)),_e&&(C[qe.key]=qe,Oe=_e.wasRequested(),_e.hasData())))break}}return C}_updateLoadedParentTileCache(){this._loadedParentTiles={};for(const g in this._tiles){const C=[];let L,$=this._tiles[g].tileID;for(;$.overscaledZ>0;){if($.key in this._loadedParentTiles){L=this._loadedParentTiles[$.key];break}C.push($.key);const G=$.scaledTo($.overscaledZ-1);if(L=this._getLoadedTile(G),L)break;$=G}for(const G of C)this._loadedParentTiles[G]=L}}_addTile(g){let C=this._tiles[g.key];if(C)return C.isExtraShadowCaster!==!0||this._shadowCasterTiles[g.key]||this._reloadTile(g.key,"reloading"),C;C=this._cache.getAndRemove(g),C&&(this._setTileReloadTimer(g.key,C),C.tileID=g,this._state.initializeTileState(C,this.map?this.map.painter:null),this._cacheTimers[g.key]&&(clearTimeout(this._cacheTimers[g.key]),delete this._cacheTimers[g.key],this._setTileReloadTimer(g.key,C)));const L=!!C;if(!L){const $=this.map?this.map.painter:null,G=this._source.tileSize*g.overscaleFactor();C=this._source.type==="raster-array"?new Rh(g,G,this.transform.tileZoom,$,this._isRaster):new o.b0(g,G,this.transform.tileZoom,$,this._isRaster,this._source.worldview),this._loadTile(C,this._tileLoaded.bind(this,C,g.key,C.state))}return C.uses++,this._tiles[g.key]=C,L||this._source.fire(new o.C("dataloading",{tile:C,coord:C.tileID,dataType:"source"})),C}_setTileReloadTimer(g,C){g in this._timers&&(clearTimeout(this._timers[g]),delete this._timers[g]);const L=C.getExpiryTimeout();L&&(this._timers[g]=setTimeout(()=>{this._reloadTile(g,"expired"),delete this._timers[g]},L))}_removeTile(g){const C=this._tiles[g];C&&(C.uses--,delete this._tiles[g],this._timers[g]&&(clearTimeout(this._timers[g]),delete this._timers[g]),C.uses>0||(C.hasData()&&C.state!=="reloading"||C.state==="empty"?this._cache.add(C.tileID,C,C.getExpiryTimeout()):(C.aborted=!0,this._abortTile(C),this._unloadTile(C))))}clearTiles(){this._shouldReloadOnResume=!1,this._paused=!1;for(const g in this._tiles)this._removeTile(+g);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(g,C,L){const $=[],G=this.transform;if(!G)return $;const K=G.projection.name==="globe",te=o.aH(G.center.lng);for(const de in this._tiles){const xe=this._tiles[de];if(L&&xe.clearQueryDebugViz(),xe.holdingForFade())continue;let _e;if(K){const Oe=xe.tileID.canonical;if(Oe.z===0){const De=[Math.abs(o.aC(te,...mu(Oe,-1))-te),Math.abs(o.aC(te,...mu(Oe,1))-te)];_e=[0,2*De.indexOf(Math.min(...De))-1]}else{const De=[Math.abs(o.aC(te,...mu(Oe,-1))-te),Math.abs(o.aC(te,...mu(Oe,0))-te),Math.abs(o.aC(te,...mu(Oe,1))-te)];_e=[De.indexOf(Math.min(...De))-1]}}else _e=[0];for(const Oe of _e){const De=g.containsTile(xe,G,C,Oe);De&&$.push(De)}}return $}getShadowCasterCoordinates(){return this._getRenderableCoordinates(!1,!0)}getVisibleCoordinates(g){return this._getRenderableCoordinates(g)}_getRenderableCoordinates(g,C){const L=this.getRenderableIds(g,C).map(G=>this._tiles[G].tileID),$=this.transform.projection.name==="globe";for(const G of L)G.projMatrix=this.transform.calculateProjMatrix(G.toUnwrapped()),G.expandedProjMatrix=$?this.transform.calculateProjMatrix(G.toUnwrapped(),!1,!0):G.projMatrix;return L}sortCoordinatesByDistance(g){const C=g.slice(),L=this.transform._camera.position,$=this.transform._camera.forward(),G={};for(const K of C){const te=1/(1<G[K.key]-G[te.key]),C}hasTransition(){if(this._source.hasTransition())return!0;if(this._supportsFading){const g=o.o.now();for(const C in this._tiles){const L=this._tiles[C];if(L.fadeEndTime!==void 0&&L.fadeEndTime>=g)return!0}}return!1}setFeatureState(g,C,L){this._state.updateState(g=g||"_geojsonTileLayer",C,L)}removeFeatureState(g,C,L){this._state.removeFeatureState(g=g||"_geojsonTileLayer",C,L)}getFeatureState(g,C){return this._state.getState(g=g||"_geojsonTileLayer",C)}setDependencies(g,C,L){const $=this._tiles[g];$&&$.setDependencies(C,L)}reloadTilesForDependencies(g,C){for(const L in this._tiles)this._tiles[L].hasDependency(g,C)&&this._reloadTile(+L,"reloading");this._cache.filter(L=>!L.hasDependency(g,C))}_preloadTiles(g,C){if(!this._sourceLoaded){const de=()=>{this._sourceLoaded&&(this._source.off("data",de),this._preloadTiles(g,C))};return void this._source.on("data",de)}const L=new Map,$=Array.isArray(g)?g:[g],G=this.map.painter.terrain,K=this.usedForTerrain&&G?G.getScaledDemTileSize():this._source.tileSize;for(const de of $){const xe=de.coveringTiles({tileSize:K,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom&&!this.usedForTerrain,reparseOverscaled:this._source.reparseOverscaled,isTerrainDEM:this.usedForTerrain});for(const _e of xe)L.set(_e.key,_e);this.usedForTerrain&&de.updateElevation(!1)}const te=Array.from(L.values());o.t(te,(de,xe)=>{const _e=new o.b0(de,this._source.tileSize*de.overscaleFactor(),this.transform.tileZoom,this.map.painter,this._isRaster,this._source.worldview);this._loadTile(_e,Oe=>{this._source.type==="raster-dem"&&_e.dem&&this._backfillDEM(_e),xe(Oe,_e)})},C)}}function o0(M,g){const C=Math.abs(2*M.wrap)-+(M.wrap<0),L=Math.abs(2*g.wrap)-+(g.wrap<0);return M.overscaledZ-g.overscaledZ||L-C||g.canonical.y-M.canonical.y||g.canonical.x-M.canonical.x}function mu(M,g){const C=1<0:L.type==="building"?$=!L.isHidden(g)&&L.paint.get("building-opacity")>0:L.type==="model"&&($=!L.isHidden(g)&&L.paint.get("model-opacity").constantOr(1)>0),this.layersGotHidden=this.layersGotHidden||!$&&C.visible,C.visible=$}}updateZOffset(g,C){this.currentBuildingBuckets=[];for(const $ of this.layers){const G=$.layer,K=this.style.getLayerSourceCache(G);let te=1;G.type==="fill-extrusion"?te=$.visible?G.paint.get("fill-extrusion-vertical-scale"):0:G.type==="building"&&(te=$.visible?G.paint.get("building-vertical-scale"):0);let de=K?K.getTile(C):null;if(!de&&K)for(const xe in K._tiles){const _e=K._tiles[xe];if(C.canonical.isChildOf(_e.tileID.canonical)){de=_e;break}}this.currentBuildingBuckets.push({bucket:de?de.getBucket(G):null,tileID:de?de.tileID:C,verticalScale:te})}g.hasAnyZOffset=!1;let L=!1;for(let $=0;${L in g&&(C[L]=g[L])}),C}function Cf(M){M=M.slice();const g=Object.create(null);for(const C of M)g[C.id]=C;for(let C=0;C0?($-K)/te:0;return this.points[G].mult(1-de).add(this.points[C].mult(de))}}class Py{constructor(g,C,L){const $=this.boxCells=[],G=this.circleCells=[];this.xCellCount=Math.ceil(g/L),this.yCellCount=Math.ceil(C/L);for(let K=0;Kthis.width||$<0||C>this.height)return!G&&[];const te=[];if(g<=0&&C<=0&&this.width<=L&&this.height<=$){if(G)return!0;for(let de=0;de0:te}_queryCircle(g,C,L,$,G){const K=g-L,te=g+L,de=C-L,xe=C+L;if(te<0||K>this.width||xe<0||de>this.height)return!$&&[];const _e=[];return this._forEachCell(K,de,te,xe,this._queryCellCircle,_e,{hitTest:$,circle:{x:g,y:C,radius:L},seenUids:{box:{},circle:{}}},G),$?_e.length>0:_e}query(g,C,L,$,G){return this._query(g,C,L,$,!1,G)}hitTest(g,C,L,$,G){return this._query(g,C,L,$,!0,G)}hitTestCircle(g,C,L,$){return this._queryCircle(g,C,L,!0,$)}_queryCell(g,C,L,$,G,K,te,de){const xe=te.seenUids,_e=this.boxCells[G];if(_e!==null){const De=this.bboxes;for(const qe of _e)if(!xe.box[qe]){xe.box[qe]=!0;const st=4*qe;if(g<=De[st+2]&&C<=De[st+3]&&L>=De[st+0]&&$>=De[st+1]&&(!de||de(this.boxKeys[qe]))){if(te.hitTest)return K.push(!0),!0;K.push({key:this.boxKeys[qe],x1:De[st],y1:De[st+1],x2:De[st+2],y2:De[st+3]})}}}const Oe=this.circleCells[G];if(Oe!==null){const De=this.circles;for(const qe of Oe)if(!xe.circle[qe]){xe.circle[qe]=!0;const st=3*qe;if(this._circleAndRectCollide(De[st],De[st+1],De[st+2],g,C,L,$)&&(!de||de(this.circleKeys[qe]))){if(te.hitTest)return K.push(!0),!0;{const Xe=De[st],pt=De[st+1],mt=De[st+2];K.push({key:this.circleKeys[qe],x1:Xe-mt,y1:pt-mt,x2:Xe+mt,y2:pt+mt})}}}}}_queryCellCircle(g,C,L,$,G,K,te,de){const xe=te.circle,_e=te.seenUids,Oe=this.boxCells[G];if(Oe!==null){const qe=this.bboxes;for(const st of Oe)if(!_e.box[st]){_e.box[st]=!0;const Xe=4*st;if(this._circleAndRectCollide(xe.x,xe.y,xe.radius,qe[Xe+0],qe[Xe+1],qe[Xe+2],qe[Xe+3])&&(!de||de(this.boxKeys[st])))return K.push(!0),!0}}const De=this.circleCells[G];if(De!==null){const qe=this.circles;for(const st of De)if(!_e.circle[st]){_e.circle[st]=!0;const Xe=3*st;if(this._circlesCollide(qe[Xe],qe[Xe+1],qe[Xe+2],xe.x,xe.y,xe.radius)&&(!de||de(this.circleKeys[st])))return K.push(!0),!0}}}_forEachCell(g,C,L,$,G,K,te,de){const xe=this._convertToXCellCoord(g),_e=this._convertToYCellCoord(C),Oe=this._convertToXCellCoord(L),De=this._convertToYCellCoord($);for(let qe=xe;qe<=Oe;qe++)for(let st=_e;st<=De;st++)if(G.call(this,g,C,L,$,this.xCellCount*st+qe,K,te,de))return}_convertToXCellCoord(g){return Math.max(0,Math.min(this.xCellCount-1,Math.floor(g*this.xScale)))}_convertToYCellCoord(g){return Math.max(0,Math.min(this.yCellCount-1,Math.floor(g*this.yScale)))}_circlesCollide(g,C,L,$,G,K){const te=$-g,de=G-C,xe=L+K;return xe*xe>te*te+de*de}_circleAndRectCollide(g,C,L,$,G,K,te){const de=(K-$)/2,xe=Math.abs(g-($+de));if(xe>de+L)return!1;const _e=(te-G)/2,Oe=Math.abs(C-(G+_e));if(Oe>_e+L)return!1;if(xe<=de||Oe<=_e)return!0;const De=xe-de,qe=Oe-_e;return De*De+qe*qe<=L*L}}const $b=Math.tan(85*Math.PI/180);function Nd(M,g,C,L,$,G,K){const te=o.bb();if(C)if(G.name==="globe"){const de=o.bc($,g);o.aD(te,te,de)}else{const de=o.bd([],K);te[0]=de[0],te[1]=de[1],te[4]=de[2],te[5]=de[3],L||o.ba(te,te,$.angle)}else o.aD(te,$.labelPlaneMatrix,M);return te}function Lc(M,g,C,L,$,G,K){const te=Nd(M,g,C,L,$,G,K);return G.name==="globe"&&C||(te[2]=te[6]=te[10]=te[14]=0),te}function Xm(M,g,C,L,$,G,K){if(C){if(G.name==="globe"){const te=Nd(M,g,C,L,$,G,K);return o.b7(te,te),o.aD(te,M,te),te}{const te=o.b8(M),de=o.b9([]);return de[0]=K[0],de[1]=K[1],de[4]=K[2],de[5]=K[3],o.aD(te,te,de),L||o.ba(te,te,-$.angle),te}}return $.glCoordMatrix}function Kc(M,g,C,L){const $=[M,g,C,1];C?o.aE($,$,L):Dr($,$,L);const G=$[3];return $[0]/=G,$[1]/=G,$[2]/=G,$}function Jm(M,g){return Math.min(.5+M/g*.5,1.5)}function Lp(M,g){const C=M[0]/M[3],L=M[1]/M[3];return C>=-g[0]&&C<=g[0]&&L>=-g[1]&&L<=g[1]}function Pt(M,g,C,L,$,G,K,te,de,xe,_e=1){const Oe=C.transform,De=L?M.textSizeData:M.iconSizeData,qe=o.bj(De,C.transform.zoom,_e),st=Oe.projection.name==="globe",Xe=[256/C.width*2+1,256/C.height*2+1],pt=L?M.text.dynamicLayoutVertexArray:M.icon.dynamicLayoutVertexArray;pt.clear();let mt=null;st&&(mt=L?M.text.globeExtVertexArray:M.icon.globeExtVertexArray);const kt=M.lineVertexArray,Et=L?M.text.placedSymbolArray:M.icon.placedSymbolArray,xt=C.transform.width/C.transform.height;let es,Ot=!1;for(let Qt=0;QtMath.abs(C)?{useVertical:!0}:M===o.bk.vertical?L>0?{needsFlipping:!0}:null:g!==0&&function($,G){return $===0||Math.abs(G/$)>$b}(C,L)?g===1?{needsFlipping:!0}:null:C<0?{needsFlipping:!0}:null}function Ir(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt,mt,kt,Et){const xt=g/24,es=M.lineOffsetX*xt,Ot=M.lineOffsetY*xt,{lineStartIndex:Qt,glyphStartIndex:At,numGlyphs:Dt,segment:Ht,writingMode:gs,flipState:ss}=M,Bs=Qt+M.lineLength,Ps=rn=>{if(_e){const[Fs,Us,Ys]=rn.up,Dn=xe.length;o.bm(_e,Dn+0,Fs,Us,Ys),o.bm(_e,Dn+1,Fs,Us,Ys),o.bm(_e,Dn+2,Fs,Us,Ys),o.bm(_e,Dn+3,Fs,Us,Ys)}const[hn,Ns,ds]=rn.point;o.bn(xe,hn,Ns,ds,rn.angle)};if(Dt>1){const rn=dn(xt,te,es,Ot,C,Oe,De,M,de,G,qe,Xe,!1,pt,mt,kt,Et);if(!rn)return{notEnoughRoom:!0};if(L&&!C){let[hn,Ns,ds]=rn.first.point,[Fs,Us,Ys]=rn.last.point;[hn,Ns]=Kc(hn,Ns,ds,K),[Fs,Us]=Kc(Fs,Us,Ys,K);const Dn=zn(gs,ss,(Fs-hn)*st,Us-Ns);if(M.flipState=Dn&&Dn.needsFlipping?1:2,Dn)return Dn}Ps(rn.first);for(let hn=At+1;hn0?Fs:ha(De,ds,hn,1,$,void 0,pt,mt.canonical),Ys=zn(gs,ss,(Us[0]-hn[0])*st,Us[1]-hn[1]);if(M.flipState=Ys&&Ys.needsFlipping?1:2,Ys)return Ys}const rn=Ya(xt*te.getoffsetX(At),es,Ot,C,Oe,De,Ht,Qt,Bs,de,G,qe,Xe,!1,!1,pt,mt,kt,Et);if(!rn)return{notEnoughRoom:!0};Ps(rn)}return{}}function Gn(M,g,C,L,$){const{x:G,y:K,z:te}=L.projectTilePoint(M.x,M.y,g);if(!$)return Kc(G,K,te,C);const[de,xe,_e]=$.getElevation(M,$.elevation,$.elevationFeature);return Kc(G+de,K+xe,te+_e,C)}function ha(M,g,C,L,$,G,K,te){const de=Gn(M.sub(g)._unit()._add(M),te,$,K,G);return o.ax(de,C,de),o.ay(de,de),o.bg(de,C,de,L)}function Ya(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt,mt,kt){const Et=L?M-g:M+g;let xt=Et>0?1:-1,es=0;L&&(xt*=-1,es=Math.PI),xt<0&&(es+=Math.PI);let Ot=te+K+(xt>0?0:1)|0,Qt=$,At=$,Dt=0,Ht=0;const gs=Math.abs(Et),ss=[],Bs=[];let Ps=G,rn=Ps,hn=o.be([]);const Ns=()=>ha(rn,Ps,At,gs-Dt+1,_e,De,Xe,pt.canonical);for(;Dt+Ht<=gs;){if(Ot+=xt,Ot=de)return null;if(At=Qt,rn=Ps,ss.push(At),qe&&Bs.push(rn),Ps=new o.P(xe.getx(Ot),xe.gety(Ot)),Qt=Oe[Ot],!Qt){const Nr=Gn(Ps,pt.canonical,_e,Xe,De);Qt=Nr[3]>0?Oe[Ot]=Nr:Ns()}Dt+=Ht;const cn=o.ax([],Qt,At),ur=o.bf(At,Qt);if(C&&ur>0&&Ht>0&&o.bi(hn,cn)/(Ht*ur)0,Et),Qt=xe*Ot.perspectiveRatio,At=(L.x1*C+te.x-L.padding)*Qt+Ot.point.x,Dt=(L.y1*C+te.y-L.padding)*Qt+Ot.point.y,Ht=(L.x2*C+te.x+L.padding)*Qt+Ot.point.x,gs=(L.y2*C+te.y+L.padding)*Qt+Ot.point.y,ss=Ot.perspectiveRatio<=.55||Ot.occluded;return!this.isInsideGrid(At,Dt,Ht,gs)||!de&&this.grid.hitTest(At,Dt,Ht,gs,Oe)||ss?{box:[],offscreen:!1,occluded:Ot.occluded}:{box:[At,Dt,Ht,gs],offscreen:this.isOffscreen(At,Dt,Ht,gs),occluded:!1}}placeCollisionCircles(g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt){const mt=[],kt=this.transform.elevation,Et=g.getProjection(),xt=g.elevationType==="road",es=!!kt||xt,Ot=o.bu.getAtTileOffsetFunc(pt,this.transform.center.lat,this.transform.worldSize,Et),Qt=new o.P(L.tileAnchorX,L.tileAnchorY),At=new o.P(L.tileAnchorX,L.tileAnchorY);let{x:Dt,y:Ht,z:gs}=Et.projectTilePoint(At.x,At.y,pt.canonical),ss=null;if(es){const ur=xt?g.getElevationFeatureForText($):null;ss={getElevation:Ot,elevation:kt,elevationFeature:ur};const[Nr,rr,dr]=Ot(Qt,kt,ur);Dt+=Nr,Ht+=rr,gs+=dr}const Bs=Et.name==="globe",Ps=this.projectAndGetPerspectiveRatio(de,Dt,Ht,gs,pt,Bs||!!kt||this.transform.pitch>0,Et),{perspectiveRatio:rn}=Ps,hn=(De?te/rn:te*rn)/o.by,Ns=Kc(Dt,Ht,gs,xe),ds=L.lineOffsetX*hn,Fs=L.lineOffsetY*hn,Us=o.ap(g.layers[0].layout.get("text-max-angle")),Ys=Math.cos(Us),Dn=Ps.signedDistanceFromCamera>0?dn(hn,K,ds,Fs,xt&&L.flipState===1,Ns,At,L,G,xe,{},es&&!De?ss:null,De&&es,Et,pt,De,Ys):null;let kn=!1,Sn=!1,cn=!0;if(Dn&&!Ps.occluded){const ur=.5*st*rn+Xe,Nr=new o.P(-100,-100),rr=new o.P(this.screenRightBoundary,this.screenBottomBoundary),dr=new Tf,{first:Xr,last:va}=Dn,ma=Xr.path.length;let Va=[];for(let pa=ma-1;pa>=1;pa--)Va.push(Xr.path[pa]);for(let pa=1;pa(es&&!Bs&&(yo=Ot(ylpa[3]<=0)&&(Va=[]));let Ha=[];if(Va.length>0){let pa=1/0,Ci=-1/0,yo=1/0,yl=-1/0;for(const Lo of Va)pa=Math.min(pa,Lo[0]),yo=Math.min(yo,Lo[1]),Ci=Math.max(Ci,Lo[0]),yl=Math.max(yl,Lo[1]);Ci>=Nr.x&&pa<=rr.x&&yl>=Nr.y&&yo<=rr.y&&(Ha=[Va.map(Lo=>new o.P(Lo[0],Lo[1]))],(parr.x||yorr.y)&&(Ha=o.bv(Ha,Nr.x,Nr.y,rr.x,rr.y)))}for(const pa of Ha){dr.reset(pa,.25*ur);let Ci=0;Ci=dr.length<=.5*ur?1:Math.ceil(dr.paddedLength/Vr)+1;for(let yo=0;yo0?(o.aE(de,de,g),this.fogState&&G&&te.name!=="globe"&&(xe=function(De,qe,st,Xe,pt,mt){const kt=mt.calculateFogTileMatrix(pt),Et=[qe,st,Xe];return o.ah(Et,Et,kt),xa(De,o.ai(Et),mt.pitch,mt._fov)}(this.fogState,C,L,$,G.toUnwrapped(),this.transform)>.9)):Dr(de,de,g);const _e=de[3];return{point:new o.P((de[0]/_e+1)/2*this.transform.width+kd,(-de[1]/_e+1)/2*this.transform.height+kd),perspectiveRatio:Math.min(.5+this.transform.getCameraToCenterDistance(te)/_e*.5,1.5),signedDistanceFromCamera:_e,occluded:K&&de[2]>_e||xe}}isOffscreen(g,C,L,$){return L=this.screenRightBoundary||$this.screenBottomBoundary}isInsideGrid(g,C,L,$){return L>=0&&g=0&&CL.collisionGroupID===C}}return this.collisionGroups[g]}}function Oh(M,g,C,L,$){const{horizontalAlign:G,verticalAlign:K}=o.bF(M),te=-(G-.5)*g,de=-(K-.5)*C,xe=o.bG(M,L);return new o.P(te+xe[0]*$,de+xe[1]*$)}function px(M,g,C,L,$){const G=new o.P(M,g);return C&&G._rotate(L?$:-$),G}class Ji{constructor(g,C,L,$,G,K){this.transform=g.clone(),this.projection=g.projection.name,this.collisionIndex=new pm(this.transform,G),this.buildingIndex=K,this.frontCutoffStart=0,this.placements={},this.opacities={},this.variableOffsets={},this.stale=!1,this.commitTime=0,this.fadeDuration=C,this.retainedQueryData={},this.collisionGroups=new Hi(L),this.collisionCircleArrays={},this.prevPlacement=$,$&&($.prevPlacement=void 0),this.placedOrientations={},this.lastReplacementSourceUpdateTime=0}getBucketParts(g,C,L,$,G=1){const K=L.getBucket(C),te=L.latestFeatureIndex;if(!K||!te||C.fqid!==K.layerIds[0])return;const de=K.layers[0].layout,xe=K.layers[0].paint,_e=L.collisionBoxArray,Oe=Math.pow(2,this.transform.zoom-L.tileID.overscaledZ),De=L.tileSize/o.an,qe=L.tileID.toUnwrapped();this.transform.setProjection(K.projection);const st=(Xe=L.tileID,pt=K.getProjection(),mt=this.transform,pt.name===this.projection?mt.calculateProjMatrix(Xe.toUnwrapped()):Bb(mt,pt,Xe));var Xe,pt,mt;const kt=de.get("text-pitch-alignment")==="map",Et=de.get("text-rotation-alignment")==="map";C.compileFilter(C.options);const xt=C.dynamicFilter(),es=C.dynamicFilterNeedsFeature(),Ot=C.dynamicFilterNeedsGeometry(),Qt=this.transform.calculatePixelsToTileUnitsMatrix(L),At=Lc(st,L.tileID.canonical,kt,Et,this.transform,K.getProjection(),Qt);let Dt=null;const Ht=K.getProjection().createInversionMatrix(this.transform,L.tileID.canonical);if(kt){const Fs=Xm(st,L.tileID.canonical,kt,Et,this.transform,K.getProjection(),Qt);Dt=o.aD([],this.transform.labelPlaneMatrix,Fs)}let gs=null;xt&&L.latestFeatureIndex&&(gs={unwrappedTileID:qe,dynamicFilter:xt,dynamicFilterNeedsFeature:es,needGeometry:Ot}),this.retainedQueryData[K.bucketInstanceId]=new Si(K.bucketInstanceId,te,K.sourceLayerIndex,K.index,L.tileID);const[ss,Bs]=K.layers[0].layout.get("text-size-scale-range"),Ps=o.aC(G,ss,Bs),[rn,hn]=de.get("icon-size-scale-range"),Ns=o.aC(G,rn,hn),ds={bucket:K,layout:de,paint:xe,posMatrix:st,invMatrix:Ht,mercatorCenter:[o.aH(this.transform.center.lng),o.aL(this.transform.center.lat)],textLabelPlaneMatrix:At,labelToScreenMatrix:Dt,clippingData:gs,scale:Oe,textPixelRatio:De,holdingForFade:L.holdingForFade(),collisionBoxArray:_e,partiallyEvaluatedTextSize:o.bj(K.textSizeData,this.transform.zoom,Ps),partiallyEvaluatedIconSize:o.bj(K.iconSizeData,this.transform.zoom,Ns),collisionGroup:this.collisionGroups.get(K.sourceID),latestFeatureIndex:L.latestFeatureIndex};if($)for(const Fs of K.sortKeyRanges){const{sortKey:Us,symbolInstanceStart:Ys,symbolInstanceEnd:Dn}=Fs;g.push({sortKey:Us,symbolInstanceStart:Ys,symbolInstanceEnd:Dn,parameters:ds})}else g.push({symbolInstanceStart:0,symbolInstanceEnd:K.symbolInstances.length,parameters:ds})}attemptAnchorPlacement(g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt,mt,kt,Et,xt,es){const{textOffset0:Ot,textOffset1:Qt,crossTileID:At}=Xe,Dt=[Ot,Qt],Ht=Oh(g,K,te,Dt,de),gs=this.collisionIndex.placeCollisionBox(mt,de,C,L,$,G,px(Ht.x,Ht.y,xe,_e,this.transform.angle),st,Oe,De,qe.predicate);if(Et){const ss=mt.getSymbolInstanceIconSize(es,this.transform.zoom,Xe.placedIconSymbolIndex);if(this.collisionIndex.placeCollisionBox(mt,ss,Et,L,$,G,px(Ht.x,Ht.y,xe,_e,this.transform.angle),st,Oe,De,qe.predicate).box.length===0)return}if(gs.box.length>0){let ss;return this.prevPlacement&&this.prevPlacement.variableOffsets[At]&&this.prevPlacement.placements[At]&&this.prevPlacement.placements[At].text&&(ss=this.prevPlacement.variableOffsets[At].anchor),this.variableOffsets[At]={textOffset:Dt,width:K,height:te,anchor:g,textScale:de,prevAnchor:ss},this.markUsedJustification(mt,g,Xe,kt),mt.allowVerticalPlacement&&(this.markUsedOrientation(mt,kt,Xe),this.placedOrientations[At]=kt),{shift:Ht,placedGlyphBoxes:gs}}}placeLayerBucketPart(g,C,L,$,G=1){const{bucket:K,layout:te,paint:de,posMatrix:xe,textLabelPlaneMatrix:_e,labelToScreenMatrix:Oe,clippingData:De,textPixelRatio:qe,mercatorCenter:st,invMatrix:Xe,holdingForFade:pt,collisionBoxArray:mt,partiallyEvaluatedTextSize:kt,partiallyEvaluatedIconSize:Et,collisionGroup:xt,latestFeatureIndex:es}=g.parameters,Ot=te.get("text-optional"),Qt=te.get("icon-optional"),At=te.get("text-allow-overlap"),Dt=te.get("icon-allow-overlap"),Ht=te.get("text-rotation-alignment")==="map",gs=te.get("icon-rotation-alignment")==="map",ss=te.get("text-pitch-alignment")==="map",Bs=de.get("symbol-z-offset"),Ps=te.get("symbol-elevation-reference")==="sea",rn=te.get("symbol-placement"),[hn,Ns]=te.get("text-size-scale-range"),[ds,Fs]=te.get("icon-size-scale-range"),Us=o.aC(G,hn,Ns),Ys=o.aC(G,ds,Fs),Dn=te.get("text-variable-anchor"),kn=Ht&&rn!=="point",Sn=gs&&rn!=="point",cn=Dn&&K.hasTextData(),ur=K.hasIconTextFit()&&cn&&K.hasIconData();this.transform.setProjection(K.projection);const Nr=cn||kn,rr=Sn||ur;let dr=At&&(Dt||!K.hasIconData()||Qt),Xr=Dt&&(At||!K.hasTextData()||Ot);const va=!Bs.isConstant();!K.collisionArrays&&mt&&K.deserializeCollisionBoxes(mt),L&&$&&K.updateCollisionDebugBuffers(this.transform.zoom,mt,Us,Ys);const ma=(Vr,Ha,pa)=>{const{crossTileID:Ci,numVerticalGlyphVertices:yo}=Vr;let yl=null;if(De&&De.dynamicFilterNeedsFeature||va){const zo=this.retainedQueryData[K.bucketInstanceId],Vo=es.loadFeature({featureIndex:Vr.featureIndex,bucketIndex:zo.bucketIndex,sourceLayerIndex:zo.sourceLayerIndex,layoutVertexArrayOffset:0}),co=Vo.properties?Vo.properties.worldview:null;if(K.localizable&&K.worldview&&typeof co=="string")if(co==="all")Vo.properties.$localized=!0;else{if(!co.split(",").includes(K.worldview))return;Vo.properties.$localized=!0,Vo.properties.worldview=K.worldview}yl=De&&De.needGeometry?o.bD(Vo,!0):Vo}if(De&&!(0,De.dynamicFilter)({zoom:this.transform.zoom,pitch:this.transform.pitch,worldview:K.worldview},yl,this.retainedQueryData[K.bucketInstanceId].tileID.canonical,new o.P(Vr.tileAnchorX,Vr.tileAnchorY),this.transform.calculateDistanceTileData(De.unwrappedTileID)))return this.placements[Ci]=new Ef(!1,!1,!1,!0),void C.add(Ci);const Lo=Bs.evaluate(yl,{});if((Vr.zOffset||0)+(Lo||0)>0&&this.frontCutoffStart>0){const zo=2*this.frontCutoffStart-1,Vo=[Vr.tileAnchorX,Vr.tileAnchorY,0,1],co=o.aE(o.bE(),Vo,xe);if(co[1]/co[3]{zo.tileID=this.retainedQueryData[K.bucketInstanceId].tileID;const Vo=this.transform.elevation;zo.elevation=Ps?Lo:Lo+o.bu.getAtTileOffset(zo.tileID,new o.P(zo.tileAnchorX,zo.tileAnchorY),Vo,dd),zo.elevation+=Vr.zOffset},Ff=pa.textBox;if(Ff){fu(Ff);const zo=co=>{let uc=o.bk.horizontal;if(K.allowVerticalPlacement&&!co&&this.prevPlacement){const qh=this.prevPlacement.placedOrientations[Ci];qh&&(this.placedOrientations[Ci]=qh,uc=qh,this.markUsedOrientation(K,uc,Vr))}return uc},Vo=(co,uc)=>{if(K.allowVerticalPlacement&&yo>0&&pa.verticalTextBox){for(const qh of K.writingModes)if(qh===o.bk.vertical?(Na=uc(),cl=Na):Na=co(),Na&&Na.box&&Na.box.length)break}else Na=co()};if(Dn){let co=Dn;if(this.prevPlacement&&this.prevPlacement.variableOffsets[Ci]){const Rl=this.prevPlacement.variableOffsets[Ci];co.indexOf(Rl.anchor)>0&&(co=co.filter(zf=>zf!==Rl.anchor),co.unshift(Rl.anchor))}const uc=(Rl,zf,h_)=>{const qj=K.getSymbolInstanceTextSize(kt,Vr,this.transform.zoom,Ha),Vj=(Rl.x2-Rl.x1)*qj+2*Rl.padding,nk=(Rl.y2-Rl.y1)*qj+2*Rl.padding,k1=Vr.hasIconTextFit&&!Dt?zf:null;k1&&fu(k1);let Zy={box:[],offscreen:!1,occluded:!1};const rk=At?2*co.length:co.length;for(let Gp=0;Gp=co.length,Vr,Ha,K,h_,k1,kt,Et);if(m_&&(Zy=m_.placedGlyphBoxes,Zy&&Zy.box&&Zy.box.length)){Fi=!0,zi=m_.shift;break}}return Zy};Vo(()=>uc(Ff,pa.iconBox,o.bk.horizontal),()=>{const Rl=pa.verticalTextBox;return Rl&&fu(Rl),K.allowVerticalPlacement&&!(Na&&Na.box&&Na.box.length)&&yo>0&&Rl?uc(Rl,pa.verticalIconBox,o.bk.vertical):{box:null,offscreen:null,occluded:null}}),Na&&(Fi=Na.box,Ra=Na.offscreen,Do=Na.occluded);const qh=zo(!(!Na||!Na.box));if(!Fi&&this.prevPlacement){const Rl=this.prevPlacement.variableOffsets[Ci];Rl&&(this.variableOffsets[Ci]=Rl,this.markUsedJustification(K,Rl.anchor,Vr,qh))}}else{const co=(uc,qh)=>{const Rl=K.getSymbolInstanceTextSize(kt,Vr,this.transform.zoom,Ha),zf=this.collisionIndex.placeCollisionBox(K,Rl,uc,st,Xe,Nr,new o.P(0,0),At,qe,xe,xt.predicate);return zf&&zf.box&&zf.box.length&&(this.markUsedOrientation(K,qh,Vr),this.placedOrientations[Ci]=qh),zf};Vo(()=>co(Ff,o.bk.horizontal),()=>{const uc=pa.verticalTextBox;return K.allowVerticalPlacement&&yo>0&&uc?(fu(uc),co(uc,o.bk.vertical)):{box:null,offscreen:null,occluded:null}}),zo(!!(Na&&Na.box&&Na.box.length))}}if(vo=Na,Fi=vo&&vo.box&&vo.box.length>0,Ra=vo&&vo.offscreen,Do=vo&&vo.occluded,Vr.useRuntimeCollisionCircles){const zo=Vr.centerJustifiedTextSymbolIndex>=0?Vr.centerJustifiedTextSymbolIndex:Vr.verticalPlacedTextSymbolIndex,Vo=K.text.placedSymbolArray.get(zo),co=o.bl(K.textSizeData,kt,Vo),uc=te.get("text-padding");vc=this.collisionIndex.placeCollisionCircles(K,At,Vo,zo,K.lineVertexArray,K.glyphOffsetArray,co,xe,_e,Oe,L,ss,xt.predicate,Vr.collisionCircleDiameter*co/o.by,uc,this.retainedQueryData[K.bucketInstanceId].tileID),Fi=At||vc.circles.length>0&&!vc.collisionDetected,Ra=Ra&&vc.offscreen,Do=vc.occluded}if(pa.iconFeatureIndex&&(gh=pa.iconFeatureIndex),pa.iconBox){const zo=Vo=>{fu(Vo);const co=Vr.hasIconTextFit&&zi?px(zi.x,zi.y,Ht,ss,this.transform.angle):new o.P(0,0),uc=K.getSymbolInstanceIconSize(Et,this.transform.zoom,Vr.placedIconSymbolIndex);return this.collisionIndex.placeCollisionBox(K,uc,Vo,st,Xe,rr,co,Dt,qe,xe,xt.predicate)};cl&&cl.box&&cl.box.length&&pa.verticalIconBox?(ii=zo(pa.verticalIconBox),Da=ii.box.length>0):(ii=zo(pa.iconBox),Da=ii.box.length>0),Ra=Ra&&ii.offscreen,Nl=ii.occluded}const eo=Ot||Vr.numHorizontalGlyphVertices===0&&yo===0,kx=Qt||Vr.numIconVertices===0;if(eo||kx?kx?eo||(Da=Da&&Fi):Fi=Da&&Fi:Da=Fi=Da&&Fi,Fi&&vo&&vo.box&&this.collisionIndex.insertCollisionBox(vo.box,te.get("text-ignore-placement"),K.bucketInstanceId,cl&&cl.box&&Zc?Zc:ko,xt.ID),Da&&ii&&this.collisionIndex.insertCollisionBox(ii.box,te.get("icon-ignore-placement"),K.bucketInstanceId,gh,xt.ID),vc&&(Fi&&this.collisionIndex.insertCollisionCircles(vc.circles,te.get("text-ignore-placement"),K.bucketInstanceId,ko,xt.ID),L)){const zo=K.bucketInstanceId;let Vo=this.collisionCircleArrays[zo];Vo===void 0&&(Vo=this.collisionCircleArrays[zo]=new kr);for(let co=0;co=0;--Ha){const pa=Vr[Ha];ma(K.symbolInstances.get(pa),pa,K.collisionArrays[pa])}K.hasAnyZOffset&&o.w(`${K.layerIds[0]} layer symbol-z-elevate: symbols are not sorted by elevation if symbol-z-order is evaluated to viewport-y`)}else if(K.hasAnyZOffset){const Vr=K.getSortedIndexesByZOffset();for(let Ha=0;Ha=0&&(g.text.placedSymbolArray.get(G).crossTileID=Oe>=0&&G!==Oe?0:xe),K>=0&&(g.text.placedSymbolArray.get(K).crossTileID=Oe>=0&&K!==Oe?0:xe),te>=0&&(g.text.placedSymbolArray.get(te).crossTileID=Oe>=0&&te!==Oe?0:xe),de>=0&&(g.text.placedSymbolArray.get(de).crossTileID=Oe>=0&&de!==Oe?0:xe)}markUsedOrientation(g,C,L){const $=C===o.bk.horizontal||C===o.bk.horizontalOnly?C:0,G=C===o.bk.vertical?C:0,{leftJustifiedTextSymbolIndex:K,centerJustifiedTextSymbolIndex:te,rightJustifiedTextSymbolIndex:de,verticalPlacedTextSymbolIndex:xe}=L,_e=g.text.placedSymbolArray;K>=0&&(_e.get(K).placedOrientation=$),te>=0&&(_e.get(te).placedOrientation=$),de>=0&&(_e.get(de).placedOrientation=$),xe>=0&&(_e.get(xe).placedOrientation=G)}commit(g){this.commitTime=g,this.zoomAtLastRecencyCheck=this.transform.zoom;const C=this.prevPlacement;let L=!1;this.prevZoomAdjustment=C?C.zoomAdjustment(this.transform.zoom):0;const $=C?C.symbolFadeChange(g):1,G=C?C.opacities:{},K=C?C.variableOffsets:{},te=C?C.placedOrientations:{};for(const de in this.placements){const xe=this.placements[de],_e=G[de];_e?(this.opacities[de]=new cg(_e,$,xe.text,xe.icon,null,xe.clipped),L=L||xe.text!==_e.text.placed||xe.icon!==_e.icon.placed):(this.opacities[de]=new cg(null,$,xe.text,xe.icon,xe.skipFade,xe.clipped),L=L||xe.text||xe.icon)}for(const de in G){const xe=G[de];if(!this.opacities[de]){const _e=new cg(xe,$,!1,!1);_e.isHidden()||(this.opacities[de]=_e,L=L||xe.text.placed||xe.icon.placed)}}for(const de in K)this.variableOffsets[de]||!this.opacities[de]||this.opacities[de].isHidden()||(this.variableOffsets[de]=K[de]);for(const de in te)this.placedOrientations[de]||!this.opacities[de]||this.opacities[de].isHidden()||(this.placedOrientations[de]=te[de]);L?this.lastPlacementChangeTime=g:typeof this.lastPlacementChangeTime!="number"&&(this.lastPlacementChangeTime=C?C.lastPlacementChangeTime:g)}updateLayerOpacities(g,C,L,$){$&&(this.lastReplacementSourceUpdateTime=$.updateTime);const G=new Set;for(const K of C){const te=K.getBucket(g);te&&K.latestFeatureIndex&&g.fqid===te.layerIds[0]&&(this.updateBucketOpacities(te,G,K,K.collisionBoxArray,L,$,K.tileID,g.scope),te.elevationType==="offset"&&this.buildingIndex&&this.buildingIndex.updateZOffset(te,K.tileID),te.elevationType==="road"&&te.updateRoadElevation(K.tileID.canonical),te.updateZOffset())}}updateBucketOpacities(g,C,L,$,G,K,te,de){g.hasTextData()&&g.text.opacityVertexArray.clear(),g.hasIconData()&&g.icon.opacityVertexArray.clear(),g.hasIconCollisionBoxData()&&g.iconCollisionBox.collisionVertexArray.clear(),g.hasTextCollisionBoxData()&&g.textCollisionBox.collisionVertexArray.clear();const xe=g.layers[0].layout,_e=g.layers[0].paint,Oe=!!g.layers[0].dynamicFilter(),De=new cg(null,0,!1,!1,!0),qe=xe.get("text-allow-overlap"),st=xe.get("icon-allow-overlap"),Xe=xe.get("text-variable-anchor"),pt=xe.get("text-rotation-alignment")==="map",mt=xe.get("text-pitch-alignment")==="map",kt=_e.get("symbol-z-offset"),Et=xe.get("symbol-elevation-reference")==="sea",xt=!kt.isConstant(),es=new cg(null,0,qe&&(st||!g.hasIconData()||xe.get("icon-optional")),st&&(qe||!g.hasTextData()||xe.get("text-optional")),!0);!g.collisionArrays&&$&&(g.hasIconCollisionBoxData()||g.hasTextCollisionBoxData())&&g.deserializeCollisionBoxes($);const Ot=(At,Dt,Ht)=>{for(let gs=0;gs
0||gs>0,Dn=Bs>0,kn=this.placedOrientations[ss],Sn=kn===o.bk.vertical,cn=kn===o.bk.horizontal||kn===o.bk.horizontalOnly;!Ys&&!Dn||Us.isHidden()||Qt++;let ur=!1;if((Ys||Dn)&&K)for(const Nr of g.activeReplacements){if(o.bz(Nr,G,o.bA.Symbol,de)||Nr.min.x>Ps||Ps>Nr.max.x||Nr.min.y>rn||rn>Nr.max.y)continue;const rr=o.bB(Ps,rn,te.canonical,Nr.footprintTileId.canonical);if(ur=o.bC(rr,Nr.footprint),ur)break}if(ur&&this.collisionIndex.markSymbolAsClipped(g.bucketInstanceId,Dt.featureIndex),Ys){const Nr=ur?gx:xx(Us.text);Ot(g.text,Ht,Sn?gx:Nr),Ot(g.text,gs,cn?gx:Nr);const rr=Us.text.isHidden(),{leftJustifiedTextSymbolIndex:dr,centerJustifiedTextSymbolIndex:Xr,rightJustifiedTextSymbolIndex:va,verticalPlacedTextSymbolIndex:ma}=Dt,Va=g.text.placedSymbolArray,Vr=rr||Sn?1:0;dr>=0&&(Va.get(dr).hidden=Vr),Xr>=0&&(Va.get(Xr).hidden=Vr),va>=0&&(Va.get(va).hidden=Vr),ma>=0&&(Va.get(ma).hidden=rr||cn?1:0);const Ha=this.variableOffsets[ss];Ha&&this.markUsedJustification(g,Ha.anchor,Dt,kn);const pa=this.placedOrientations[ss];pa&&(this.markUsedJustification(g,"left",Dt,pa),this.markUsedOrientation(g,pa,Dt))}if(Dn){const Nr=ur?gx:xx(Us.icon),{placedIconSymbolIndex:rr,verticalPlacedIconSymbolIndex:dr}=Dt,Xr=g.icon.placedSymbolArray,va=Us.icon.isHidden()?1:0;rr>=0&&(Ot(g.icon,Bs,Sn?gx:Nr),Xr.get(rr).hidden=va),dr>=0&&(Ot(g.icon,Dt.numVerticalIconVertices,cn?gx:Nr),Xr.get(dr).hidden=va)}if(g.hasIconCollisionBoxData()||g.hasTextCollisionBoxData()){const Nr=g.collisionArrays[At];if(Nr){let rr=new o.P(0,0),dr=!0;if(Nr.textBox||Nr.verticalTextBox){if(Xe){const va=this.variableOffsets[ss];va?(rr=Oh(va.anchor,va.width,va.height,va.textOffset,va.textScale),pt&&rr._rotate(mt?this.transform.angle:-this.transform.angle)):dr=!1}Oe&&(dr=!Us.clipped),Nr.textBox&&fx(g.textCollisionBox.collisionVertexArray,Us.text.placed,!dr||Sn,ds,Et,rr.x,rr.y),Nr.verticalTextBox&&fx(g.textCollisionBox.collisionVertexArray,Us.text.placed,!dr||cn,ds,Et,rr.x,rr.y)}const Xr=dr&&!!(!cn&&Nr.verticalIconBox);Nr.iconBox&&fx(g.iconCollisionBox.collisionVertexArray,Us.icon.placed,Xr,ds,Et,Dt.hasIconTextFit?rr.x:0,Dt.hasIconTextFit?rr.y:0),Nr.verticalIconBox&&fx(g.iconCollisionBox.collisionVertexArray,Us.icon.placed,!Xr,ds,Et,Dt.hasIconTextFit?rr.x:0,Dt.hasIconTextFit?rr.y:0)}}}if(g.fullyClipped=Qt===0,g.sortFeatures(this.transform.angle),this.retainedQueryData[g.bucketInstanceId]&&(this.retainedQueryData[g.bucketInstanceId].featureSortOrder=g.featureSortOrder),g.hasTextData()&&g.text.opacityVertexBuffer&&g.text.opacityVertexBuffer.updateData(g.text.opacityVertexArray),g.hasIconData()&&g.icon.opacityVertexBuffer&&g.icon.opacityVertexBuffer.updateData(g.icon.opacityVertexArray),g.hasIconCollisionBoxData()&&g.iconCollisionBox.collisionVertexBuffer&&g.iconCollisionBox.collisionVertexBuffer.updateData(g.iconCollisionBox.collisionVertexArray),g.hasTextCollisionBoxData()&&g.textCollisionBox.collisionVertexBuffer&&g.textCollisionBox.collisionVertexBuffer.updateData(g.textCollisionBox.collisionVertexArray),g.bucketInstanceId in this.collisionCircleArrays){const At=this.collisionCircleArrays[g.bucketInstanceId];g.placementInvProjMatrix=At.invProjMatrix,g.placementViewportMatrix=At.viewportMatrix,g.collisionCircleArray=At.circles,delete this.collisionCircleArrays[g.bucketInstanceId]}}symbolFadeChange(g){return this.fadeDuration===0?1:(g-this.commitTime)/this.fadeDuration+this.prevZoomAdjustment}zoomAdjustment(g){return Math.max(0,(this.transform.zoom-g)/1.5)}hasTransitions(g){return g-this.lastPlacementChangeTimeg}isStale(){return this.stale}setStale(){this.stale=!0}}function fx(M,g,C,L,$,G,K){M.emplaceBack(g?1:0,C?1:0,G||0,K||0,L,$?1:0),M.emplaceBack(g?1:0,C?1:0,G||0,K||0,L,$?1:0),M.emplaceBack(g?1:0,C?1:0,G||0,K||0,L,$?1:0),M.emplaceBack(g?1:0,C?1:0,G||0,K||0,L,$?1:0)}const Ly=Math.pow(2,25),Ub=Math.pow(2,24),Hu=Math.pow(2,17),Dl=Math.pow(2,16),c6=Math.pow(2,9),Dy=Math.pow(2,8),qb=Math.pow(2,1);function xx(M){if(M.opacity===0&&!M.placed)return 0;if(M.opacity===1&&M.placed)return 4294967295;const g=M.placed?1:0,C=Math.floor(127*M.opacity);return C*Ly+g*Ub+C*Hu+g*Dl+C*c6+g*Dy+C*qb+g}const gx=0;class ij{constructor(g){this._sortAcrossTiles=g.layout.get("symbol-z-order")!=="viewport-y"&&g.layout.get("symbol-sort-key").constantOr(1)!==void 0,this._currentTileIndex=0,this._currentPartIndex=0,this._seenCrossTileIDs=new Set,this._bucketParts=[]}continuePlacement(g,C,L,$,G,K){const te=this._bucketParts;for(;this._currentTileIndexde.sortKey-xe.sortKey));this._currentPartIndex{const de=o.o.now()-K;return!this.isFullPlacementRequested()&&this._fadeDuration!==0&&de>2};for(;this._currentPlacementIndex>=0;){const de=C[g[this._currentPlacementIndex]],xe=this.placement.collisionIndex.transform.zoom;if(de.type==="symbol"&&de.visibility!=="none"&&(!de.minzoom||de.minzoom<=xe)&&(!de.maxzoom||de.maxzoom>xe)){const _e=de,Oe=_e.layout.get("symbol-z-elevate"),De=_e.layout.get("symbol-sort-key").constantOr(1)!==void 0,qe=_e.layout.get("symbol-z-order"),st=qe==="viewport-y"||qe==="auto"&&!(qe!=="viewport-y"&&De),Xe=_e.layout.get("text-allow-overlap")||_e.layout.get("icon-allow-overlap")||_e.layout.get("text-ignore-placement")||_e.layout.get("icon-ignore-placement"),pt=st&&Xe,mt=this._inProgressLayer=this._inProgressLayer||new ij(_e),kt=o.F(de.source,de.scope);if(mt.continuePlacement(Oe||pt?$[kt]:L[kt],this.placement,this._showCollisionBoxes,de,te,G))return;delete this._inProgressLayer}this._currentPlacementIndex--}this._forceFullPlacement=!1,this._done=!0}commit(g){return this.placement.commit(g),this.placement}}const Ud=512/o.an/2;class ep{constructor(g,C,L){this.tileID=g,this.bucketInstanceId=L,this.index=new o.bI(C.length,16,Int32Array),this.keys=[],this.crossTileIDs=[];const $=g.canonical.x*o.an,G=g.canonical.y*o.an;for(let K=0;Kpt-mt);for(const pt of Xe){const mt=this.crossTileIDs[pt];if(this.keys[pt]===_e&&!L.has(mt)){L.add(mt),xe.crossTileID=mt;break}}}}}class qd{constructor(){this.maxCrossTileID=0}generate(){return++this.maxCrossTileID}}class Dp{constructor(){this.indexes={},this.usedCrossTileIDs={},this.lng=0}handleWrapJump(g){const C=Math.round((g-this.lng)/360);if(C!==0)for(const L in this.indexes){const $=this.indexes[L],G={};for(const K in $){const te=$[K];te.tileID=te.tileID.unwrapTo(te.tileID.wrap+C),G[te.tileID.key]=te}this.indexes[L]=G}this.lng=g}addBucket(g,C,L){if(this.indexes[g.overscaledZ]&&this.indexes[g.overscaledZ][g.key]){if(this.indexes[g.overscaledZ][g.key].bucketInstanceId===C.bucketInstanceId)return!1;this.removeBucketCrossTileIDs(g.overscaledZ,this.indexes[g.overscaledZ][g.key])}for(let G=0;Gg.overscaledZ)for(const te in K){const de=K[te];de.tileID.isChildOf(g)&&de.findMatches(C.symbolInstances,g,$)}else{const te=K[g.scaledTo(Number(G)).key];te&&te.findMatches(C.symbolInstances,g,$)}}for(let G=0;G{C[L]=!0});for(const L in this.layerIndexes)C[L]||delete this.layerIndexes[L]}}const Al=771;class Qr{constructor(g,C,L,$){this.blendFunction=g,this.blendColor=C.toNonPremultipliedRenderColor(null),this.mask=L,this.blendEquation=$}}Qr.Replace=[1,0,1,0],Qr.disabled=new Qr(Qr.Replace,o.aq.transparent,[!1,!1,!1,!1]),Qr.unblended=new Qr(Qr.Replace,o.aq.transparent,[!0,!0,!0,!0]),Qr.alphaBlended=new Qr([1,Al,1,Al],o.aq.transparent,[!0,!0,!0,!0]),Qr.alphaBlendedNonPremultiplied=new Qr([770,Al,770,Al],o.aq.transparent,[!0,!0,!0,!0]),Qr.multiply=new Qr([774,0,774,0],o.aq.transparent,[!0,!0,!0,!0]),Qr.multiplyAccumulateAlpha=new Qr([774,0,1,Al],o.aq.transparent,[!0,!0,!0,!0]),Qr.additive=new Qr([1,1,1,1],o.aq.transparent,[!0,!0,!0,!0]);class nr{constructor(g,C,L){this.func=g,this.mask=C,this.range=L}}nr.ReadOnly=!1,nr.ReadWrite=!0,nr.disabled=new nr(519,nr.ReadOnly,[0,1]);const gl=7680;class ra{constructor(g,C,L,$,G,K){this.test=g,this.ref=C,this.mask=L,this.fail=$,this.depthFail=G,this.pass=K}}ra.disabled=new ra({func:519,mask:0},0,0,gl,gl,gl);const tp=1029,fm=2305;class Pr{constructor(g,C,L){this.enable=g,this.mode=C,this.frontFace=L}}function Ry(M,g){const C=o.bO(M,3);o.bR(M,g),o.bW(M,3,C)}function oj(M,g){const C=o.bL([]);return o.bM(C,C,-g),o.bN(C,C,-M),C}function n1(M,g){const C=[M[0],M[1],0],L=[g[0],g[1],0];if(o.ai(C)>=1e-15){const K=o.ay([],C);o.bJ(L,K,o.bi(L,K)),g[0]=L[0],g[1]=L[1]}const $=o.bh([],g,M);if(o.bK($)<1e-15)return null;const G=Math.atan2(-$[1],$[0]);return oj(Math.atan2(Math.sqrt(M[0]*M[0]+M[1]*M[1]),-M[2]),G)}Pr.disabled=new Pr(!1,tp,fm),Pr.backCCW=new Pr(!0,tp,fm),Pr.backCW=new Pr(!0,tp,2304),Pr.frontCW=new Pr(!0,1028,2304),Pr.frontCCW=new Pr(!0,1028,fm);class Hb{constructor(g,C){this.position=g,this.orientation=C}get position(){return this._position}set position(g){if(g){const C=g instanceof o.ag?g:new o.ag(g[0],g[1],g[2]);this._renderWorldCopies&&(C.x=o.bs(C.x,0,1)),this._position=C}else this._position=null}lookAtPoint(g,C,L){if(this.orientation=null,!this.position)return;const $=this.position,G=L||(this._elevation?this._elevation.getAtPointOrZero(o.ag.fromLngLat(g)):0),K=o.ag.fromLngLat(g,G),te=[K.x-$.x,K.y-$.y,K.z-$.z];C||(C=[0,0,1]),C[2]=Math.abs(C[2]),this.orientation=n1(te,C)}setPitchBearing(g,C){this.orientation=oj(o.ap(g),o.ap(-C))}}class c0{constructor(g,C){this._transform=o.b9([]),this.orientation=C,this.position=g}get mercatorPosition(){const g=this.position;return new o.ag(g[0],g[1],g[2])}get position(){const g=o.bO(this._transform,3);return[g[0],g[1],g[2]]}set position(g){var C;g&&o.bW(this._transform,3,[(C=g)[0],C[1],C[2],1])}get orientation(){return this._orientation}set orientation(g){this._orientation=g||o.bL([]),g&&Ry(this._transform,this._orientation)}getPitchBearing(){const g=this.forward(),C=this.right();return{bearing:Math.atan2(-C[1],C[0]),pitch:Math.atan2(Math.sqrt(g[0]*g[0]+g[1]*g[1]),-g[2])}}setPitchBearing(g,C){this._orientation=oj(g,C),Ry(this._transform,this._orientation)}forward(){const g=o.bO(this._transform,2);return[-g[0],-g[1],-g[2]]}up(){const g=o.bO(this._transform,1);return[-g[0],-g[1],-g[2]]}right(){const g=o.bO(this._transform,0);return[g[0],g[1],g[2]]}getCameraToWorld(g,C){const L=new Float64Array(16);return o.b7(L,this.getWorldToCamera(g,C)),L}getCameraToWorldMercator(){return this._transform}getWorldToCameraPosition(g,C,L){const $=this.position;o.bJ($,$,-g);const G=new Float64Array(16);return o.bP(G,[L,L,L]),o.bx(G,G,$),G[10]*=C,G}getWorldToCamera(g,C){const L=new Float64Array(16),$=new Float64Array(4),G=this.position;return o.bQ($,this._orientation),o.bJ(G,G,-g),o.bR(L,$),o.bx(L,L,G),L[1]*=-1,L[5]*=-1,L[9]*=-1,L[13]*=-1,L[8]*=C,L[9]*=C,L[10]*=C,L[11]*=C,L}getCameraToClipPerspective(g,C,L,$){const G=new Float64Array(16);return o.bS(G,g,C,L,$),G}getCameraToClipOrthographic(g,C,L,$,G,K){const te=new Float64Array(16);return o.bT(te,g,C,L,$,G,K),te}getDistanceToElevation(g,C=!1){const L=g===0?0:o.bU(g,C?o.bV(this.position[1]):this.position[1]),$=this.forward();return(L-this.position[2])/$[2]}clone(){return new c0([...this.position],[...this.orientation])}}const Mf=(M,g)=>({u_matrix:M,u_ground_shadow_factor:g});class xm{constructor(g=0,C=0,L=0,$=0){if(isNaN(g)||g<0||isNaN(C)||C<0||isNaN(L)||L<0||isNaN($)||$<0)throw new Error("Invalid value for edge-insets, top, bottom, left and right must all be numbers");this.top=g,this.bottom=C,this.left=L,this.right=$}interpolate(g,C,L){return C.top!=null&&g.top!=null&&(this.top=o.am(g.top,C.top,L)),C.bottom!=null&&g.bottom!=null&&(this.bottom=o.am(g.bottom,C.bottom,L)),C.left!=null&&g.left!=null&&(this.left=o.am(g.left,C.left,L)),C.right!=null&&g.right!=null&&(this.right=o.am(g.right,C.right,L)),this}getCenter(g,C){const L=o.aC((this.left+g-this.right)/2,0,g),$=o.aC((this.top+C-this.bottom)/2,0,C);return new o.P(L,$)}equals(g){return this.top===g.top&&this.bottom===g.bottom&&this.left===g.left&&this.right===g.right}clone(){return new xm(this.top,this.bottom,this.left,this.right)}toJSON(){return{top:this.top,bottom:this.bottom,left:this.left,right:this.right}}}const If=15;class sp{constructor(g,C,L,$,G,K,te){this.tileSize=512,this._renderWorldCopies=G===void 0||G,this._minZoom=g||0,this._maxZoom=C||22,this._minPitch=L??0,this._maxPitch=$??60,this.setProjection(K),this.setMaxBounds(te),this.width=0,this.height=0,this._center=new o.aU(0,0),this.zoom=0,this.angle=0,this._fov=.6435011087932844,this._pitch=0,this._nearZ=0,this._farZ=0,this._nearClipOffset=0,this._unmodified=!0,this._edgeInsets=new xm,this._projMatrixCache={},this._alignedProjMatrixCache={},this._fogTileMatrixCache={},this._expandedProjMatrixCache={},this._distanceTileDataCache={},this._camera=new c0,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 g=new sp(this._minZoom,this._maxZoom,this._minPitch,this.maxPitch,this._renderWorldCopies,this.getProjection(),this.maxBounds);return g._elevation=this._elevation,g._centerAltitude=this._centerAltitude,g._centerAltitudeValidForExaggeration=this._centerAltitudeValidForExaggeration,g.tileSize=this.tileSize,g.mercatorFromTransition=this.mercatorFromTransition,g.width=this.width,g.height=this.height,g.cameraElevationReference=this.cameraElevationReference,g._center=this._center,g._setZoom(this.zoom),g._seaLevelZoom=this._seaLevelZoom,g.angle=this.angle,g._fov=this._fov,g._pitch=this._pitch,g._nearZ=this._nearZ,g._farZ=this._farZ,g._nearClipOffset=this._nearClipOffset,g._averageElevation=this._averageElevation,g._orthographicProjectionAtLowPitch=this._orthographicProjectionAtLowPitch,g._unmodified=this._unmodified,g._edgeInsets=this._edgeInsets.clone(),g._camera=this._camera.clone(),g._calcMatrices(),g.freezeTileCoverage=this.freezeTileCoverage,g.frustumCorners=this.frustumCorners,g._allowWorldUnderZoom=this._allowWorldUnderZoom,g}get isOrthographic(){return this.projection.name!=="globe"&&this._orthographicProjectionAtLowPitch&&this.pitch0&&this.elevation.exaggeration()>0&&this._centerAltitudeValidForExaggeration;if(!this._elevation||g===Number.NEGATIVE_INFINITY&&(!C||!this._centerAltitude))return this._centerAltitude=0,this._seaLevelZoom=null,void(this._centerAltitudeValidForExaggeration=void 0);const L=this._elevation;C||this._centerAltitude&&this._centerAltitudeValidForExaggeration&&L.exaggeration()&&this._centerAltitudeValidForExaggeration!==L.exaggeration()?(this._centerAltitude=this._centerAltitude/this._centerAltitudeValidForExaggeration*L.exaggeration(),this._centerAltitudeValidForExaggeration=L.exaggeration()):(this._centerAltitude=g||0,this._centerAltitudeValidForExaggeration=L.exaggeration()),this._updateSeaLevelZoom()}_updateSeaLevelZoom(){if(this._centerAltitudeValidForExaggeration===void 0)return;const g=Math.max(0,(this.pixelsPerMeter*this._centerAltitude+this.cameraToCenterDistance)/this.worldSize);this._seaLevelZoom=this._zoomFromMercatorZ(g)}sampleAverageElevation(){if(!this._elevation)return 0;const g=this._elevation,C=[[.5,.2],[.3,.5],[.5,.5],[.7,.5],[.5,.8]],L=this.horizonLineFromTop();let $=0,G=0;for(let K=0;K{const pt=o.ck(De,Oe,qe,st,Xe);de.has(pt)||(G.push(new o.aR(Oe,De,qe,st,Xe)),de.add(pt))};for(let Oe=0;OeDe.canonical.z)continue;const qe=De.canonical,st=De.overscaledZ,Xe=De.wrap,pt=1<0,Et=qe.y+10,es=De.wrap-(kt?0:1),Ot=De.wrap+(mt?0:1),Qt=kt?qe.x-1:pt-1,At=mt?qe.x+1:0;if(K)L[0]<0?(xe(st,Ot,qe.z,At,qe.y),L[1]<0&&Et&&(xe(st,Xe,qe.z,qe.x,qe.y+1),xe(st,Ot,qe.z,At,qe.y+1)),L[1]>0&&xt&&(xe(st,Xe,qe.z,qe.x,qe.y-1),xe(st,Ot,qe.z,At,qe.y-1))):L[0]>0?(xe(st,es,qe.z,Qt,qe.y),L[1]<0&&Et&&(xe(st,Xe,qe.z,qe.x,qe.y+1),xe(st,es,qe.z,Qt,qe.y+1)),L[1]>0&&xt&&(xe(st,Xe,qe.z,qe.x,qe.y-1),xe(st,es,qe.z,Qt,qe.y-1))):L[1]<0&&Et?xe(st,Xe,qe.z,qe.x,qe.y+1):xt&&xe(st,Xe,qe.z,qe.x,qe.y-1);else{const Dt=De.visibleQuadrants;1&Dt&&(xe(st,es,qe.z,Qt,qe.y),xt&&(xe(st,Xe,qe.z,qe.x,qe.y-1),xe(st,es,qe.z,Qt,qe.y-1))),2&Dt&&(xe(st,Ot,qe.z,At,qe.y),xt&&(xe(st,Xe,qe.z,qe.x,qe.y-1),xe(st,Ot,qe.z,At,qe.y-1))),4&Dt&&(xe(st,es,qe.z,Qt,qe.y),Et&&(xe(st,Xe,qe.z,qe.x,qe.y+1),xe(st,es,qe.z,Qt,qe.y+1))),8&Dt&&(xe(st,Ot,qe.z,At,qe.y),Et&&(xe(st,Xe,qe.z,qe.x,qe.y+1),xe(st,Ot,qe.z,At,qe.y+1)))}}const _e=[];for(const Oe of G)G.some(De=>Oe.isChildOf(De))||_e.push(Oe);if(G=_e.filter(Oe=>!g.some(De=>!!(Oe.overscaledZ{const mt=pt.canonical.x+.5-qe[0],kt=pt.canonical.y+.5-qe[1];return mt*mt+kt*kt{const Qt=o.ck(Et,kt,xt,es,Ot);G.has(Qt)||($.push(new o.aR(kt,Et,xt,es,Ot)),G.add(Qt))},te=g.reduce((kt,Et)=>Math.max(kt,Et.overscaledZ),L),de=1<{const xt=Math.floor(kt[0]),es=Math.floor(kt[1]),Ot=(kt[0]-xt)*o.an,Qt=(kt[1]-es)*o.an,At=Math.floor(Et[0]),Dt=Math.floor(Et[1]),Ht=(Et[0]-At)*o.an,gs=(Et[1]-Dt)*o.an;for(let ss=-1;ss<=1;ss++){const Bs=xt+ss;if(!(Bs<0||Bs>=de)){_e.x=Ot-ss*o.an,Oe.x=Ht-(Bs-At)*o.an;for(let Ps=-1;Ps<=1;Ps++){const rn=es+Ps;_e.y=Qt-Ps*o.an,Oe.y=gs-(rn-Dt)*o.an,o.cI(_e,Oe,xe)&&K(te,0,L,Bs,rn)}}}},qe=C.points,st=qe[o.c9],Xe=qe[o.ca],pt=this._projectToGround(st,qe[o.cb]),mt=this._projectToGround(Xe,qe[o.cc]);return De(st,pt),De(Xe,mt),$}_projectToGround(g,C){return o.cd(o.ce(),g,C,g[2]/(g[2]-C[2]))}_projectToZ(g,C,L){const $=g[2]-C[2];return Math.abs($)<1e-6?o.cf(g):o.cd(o.ce(),g,C,(g[2]-L)/$)}extendTileCoverForTunnels(g,C,L,$){if(L<18)return[];const G=C.points,K=G[o.cg],te=G[o.ch],de=G[o.ci],xe=G[o.cj];if(de[2]>=0&&xe[2]>=0||K[2]<=0||te[2]<=0)return[];const _e=de[2]<0?this._projectToZ(K,de,0):de,Oe=xe[2]<0?this._projectToZ(te,xe,0):xe,De=-$,qe=de[2]3&&(Xe.length=3),Xe}_findExtensionTilesInQuad(g,C,L,$){const G=[],K=new Set;for(const At of g)K.add(At.key);const te=g.reduce((At,Dt)=>Math.max(At,Dt.overscaledZ),C),de=1<{const Ht=At.canonical.x+.5-Ot,gs=At.canonical.y+.5-Qt,ss=Dt.canonical.x+.5-Ot,Bs=Dt.canonical.y+.5-Qt;return Ht*Ht+gs*gs-(ss*ss+Bs*Bs)||At.canonical.x-Dt.canonical.x||At.canonical.y-Dt.canonical.y}),G}coveringTiles(g){let C=this.coveringZoomLevel(g);const L=C,$=this.elevation&&this.elevation.exaggeration(),G=$&&!g.isTerrainDEM,K=this.projection.name==="mercator";if(g.minzoom!==void 0&&Cg.maxzoom&&(C=g.maxzoom);const te=this.locationCoordinate(this.center),de=this.center.lat,xe=1<{const Us=new o.ag(ds.x+25e-6,ds.y,ds.z),Ys=new o.ag(ds.x,ds.y+25e-6,ds.z),Dn=ds.toLngLat(),kn=Us.toLngLat(),Sn=Ys.toLngLat(),cn=this.locationCoordinate(Dn),ur=this.locationCoordinate(kn),Nr=this.locationCoordinate(Sn),rr=Math.hypot(ur.x-cn.x,ur.y-cn.y),dr=Math.hypot(Nr.x-cn.x,Nr.y-cn.y);return Math.sqrt(rr*dr)*Qt/25e-6},Dt=ds=>{const Fs=es,Us=Ot;return{aabb:o.cp(this,xe,0,0,0,ds,Us,Fs,this.projection),zoom:0,x:0,y:0,minZ:Us,maxZ:Fs,wrap:ds,fullyVisible:!1}},Ht=[];let gs=[];const ss=C,Bs=g.reparseOverscaled?L:C,Ps=(pt-this._centerAltitude)*Xe,rn=ds=>{if(!this._elevation||!ds.tileID||!K)return;const Fs=this._elevation.getMinMaxForTile(ds.tileID),Us=ds.aabb;Fs?(Us.min[2]=Fs.min,Us.max[2]=Fs.max,Us.center[2]=(Us.min[2]+Us.max[2])/2):(ds.shouldSplit=Ns(ds),ds.shouldSplit||(Us.min[2]=Us.max[2]=Us.center[2]=this._centerAltitude))},hn=(ds,Fs)=>{if(.707*Fs{if(ds.zoom=.9)return!0}else if(G&&(Ys=ds.aabb.distanceZ(mt)*Xe),this.projection.isReprojectedInTileSpace&&L<=5){const dr=Math.pow(2,ds.zoom),Xr=At(new o.ag((ds.x+.5)/dr,(ds.y+.5)/dr));Dn=Xr>.85?1:Xr}if(!K&&!Oe){const dr=Math.sqrt(Fs*Fs+Us*Us+Ys*Ys);let Xr=(1<0;){const ds=Ht.pop(),Fs=ds.x,Us=ds.y;let Ys=ds.fullyVisible;const Dn=()=>this.projection.name==="globe"&&(ds.y===0||ds.y===(1<kn)continue;let Sn=0;if(!Ys){let rr=kt?ds.aabb.intersectsPrecise(qe):ds.aabb.intersectsPreciseFlat(qe);if(rr===0&&Dn()){const dr=new o.cn(ds.zoom,Fs,Us);rr=o.co(this,xe,dr,!0).intersectsPrecise(qe)}if(rr===0)continue;if(g.calculateQuadrantVisibility)if(qe.containsPoint(ds.aabb.center))Sn=15;else for(let dr=0;dr<4;dr++)ds.aabb.quadrant(dr).intersects(qe)!==0&&(Sn|=1<>1),ur={aabb:K?ds.aabb.quadrant(kn):o.cp(this,xe,ds.zoom+1,Sn,cn,ds.wrap,ds.minZ,ds.maxZ,this.projection),zoom:ds.zoom+1,x:Sn,y:cn,wrap:ds.wrap,fullyVisible:Ys,tileID:void 0,shouldSplit:void 0,minZ:ds.minZ,maxZ:ds.maxZ};G&&!Oe&&(ur.tileID=new o.aR(ds.zoom+1===ss?Bs:ds.zoom+1,ds.wrap,ds.zoom+1,Sn,cn),rn(ur)),Ht.push(ur)}}if(this.fogCullDistSq){const ds=this.fogCullDistSq,Fs=this.horizonLineFromTop();gs=gs.filter(Us=>{const Ys=[0,0,0,1],Dn=[o.an,o.an,0,1],kn=this.calculateFogTileMatrix(Us.tileID.toUnwrapped());o.aE(Ys,Ys,kn),o.aE(Dn,Dn,kn);const Sn=o.cq([],Ys,Dn),cn=o.cr([],Ys,Dn),ur=o.cK(Sn,cn);if(ur===0)return!0;let Nr=!1;const rr=this._elevation;if(rr&&ur>ds&&Fs!==0){const dr=this.calculateProjMatrix(Us.tileID.toUnwrapped());let Xr;g.isTerrainDEM||(Xr=rr.getMinMaxForTile(Us.tileID)),Xr||(Xr={min:Ot,max:es});const va=o.cs(this.rotation),ma=[va[0]*o.an,va[1]*o.an,Xr.max];o.ah(ma,ma,dr),Nr=(1-ma[1])*this.height*.5ds.distanceSq-Fs.distanceSq).map(ds=>ds.tileID)}resize(g,C){this.width=g,this.height=C,this.pixelsToGLUnits=[2/g,-2/C],this._constrain(),this._calcMatrices()}get unmodified(){return this._unmodified}zoomScale(g){return Math.pow(2,g)}scaleZoom(g){return Math.log2(g)}project(g){const C=o.aC(g.lat,-o.ct,o.ct),L=this.projection.project(g.lng,C);return new o.P(L.x*this.worldSize,L.y*this.worldSize)}unproject(g){return this.projection.unproject(g.x/this.worldSize,g.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(g,C){let L,$;const G=this.centerPoint;if(this.projection.name==="globe"){const te=this.worldSize;L=(C.x-G.x)/te,$=(C.y-G.y)/te}else{const te=this.pointCoordinate(C),de=this.pointCoordinate(G);L=te.x-de.x,$=te.y-de.y}const K=this.locationCoordinate(g);this.setLocation(new o.ag(K.x-L,K.y-$))}setLocation(g){this.center=this.coordinateLocation(g),this.projection.wrap&&(this.center=this.center.wrap())}locationPoint(g,C){return this.projection.locationPoint(this,g,C)}locationPoint3D(g,C){return this.projection.locationPoint(this,g,C,!0)}pointLocation(g){return this.coordinateLocation(this.pointCoordinate(g))}pointLocation3D(g,C){return this.coordinateLocation(this.pointCoordinate3D(g,C))}locationCoordinate(g,C){const L=C?o.bU(C,g.lat):void 0,$=this.projection.project(g.lng,g.lat);return new o.ag($.x,$.y,L)}coordinateLocation(g){return this.projection.unproject(g.x,g.y)}pointRayIntersection(g,C){const L=C??this._centerAltitude,$=[g.x,g.y,0,1],G=[g.x,g.y,1,1];o.aE($,$,this.pixelMatrixInverse),o.aE(G,G,this.pixelMatrixInverse);const K=G[3];o.cu($,$,1/$[3]),o.cu(G,G,1/K);const te=$[2],de=G[2];return{p0:$,p1:G,t:te===de?0:(L-te)/(de-te)}}screenPointToMercatorRay(g){const C=[g.x,g.y,0,1],L=[g.x,g.y,1,1];return o.aE(C,C,this.pixelMatrixInverse),o.aE(L,L,this.pixelMatrixInverse),o.cu(C,C,1/C[3]),o.cu(L,L,1/L[3]),C[2]=o.bU(C[2],this._center.lat)*this.worldSize,L[2]=o.bU(L[2],this._center.lat)*this.worldSize,o.cu(C,C,1/this.worldSize),o.cu(L,L,1/this.worldSize),new o.az([C[0],C[1],C[2]],o.ay([],o.ax([],L,C)))}rayIntersectionCoordinate(g){const{p0:C,p1:L,t:$}=g,G=o.bU(C[2],this._center.lat),K=o.bU(L[2],this._center.lat);return new o.ag(o.am(C[0],L[0],$)/this.worldSize,o.am(C[1],L[1],$)/this.worldSize,o.am(G,K,$))}pointCoordinate(g,C=this._centerAltitude){return this.projection.pointCoordinate(this,g.x,g.y,C)}pointCoordinate3D(g,C){if(!this.elevation)return this.pointCoordinate(g,C);let L=this.projection.pointCoordinate3D(this,g.x,g.y);if(L)return new o.ag(L[0],L[1],L[2]);let $=0,G=this.horizonLineFromTop();if(g.y>G)return this.pointCoordinate(g,C);const K=.02*G,te=g.clone();for(let de=0;de<10&&G-$>K;de++){te.y=o.am($,G,.66);const xe=this.projection.pointCoordinate3D(this,te.x,te.y);xe?(G=te.y,L=xe):$=te.y}return L?new o.ag(L[0],L[1],L[2]):this.pointCoordinate(g)}isPointAboveHorizon(g){return this.projection.isPointAboveHorizon(this,g)}isPointOnSurface(g){if(g.y<0||g.y>this.height||g.x<0||g.x>this.width)return!1;if(this.elevation||this.zoom>=o.cv)return!this.isPointAboveHorizon(g);const C=this.pointCoordinate(g);return C.y>=0&&C.y<=1}_coordinatePoint(g,C){const L=C&&this.elevation?this.elevation.getAtPointOrZero(g,this._centerAltitude):this._centerAltitude,$=[g.x*this.worldSize,g.y*this.worldSize,L+g.toAltitude(),1];return o.aE($,$,this.pixelMatrix),$[3]>0?new o.P($[0]/$[3],$[1]/$[3]):new o.P(Number.MAX_VALUE,Number.MAX_VALUE)}_getBoundsNonRectangular(){const{top:g,left:C}=this._edgeInsets,L=this.height-this._edgeInsets.bottom,$=this.width-this._edgeInsets.right,G=this.pointLocation3D(new o.P(C,g)),K=this.pointLocation3D(new o.P($,g)),te=this.pointLocation3D(new o.P($,L)),de=this.pointLocation3D(new o.P(C,L));let xe=Math.min(G.lng,K.lng,te.lng,de.lng),_e=Math.max(G.lng,K.lng,te.lng,de.lng),Oe=Math.min(G.lat,K.lat,te.lat,de.lat),De=Math.max(G.lat,K.lat,te.lat,de.lat);const qe=Math.pow(2,-this.zoom)/16*270,st=this.projection.name==="globe"?1:4,Xe=(pt,mt,kt,Et,xt)=>{const es=(pt+kt)/2,Ot=(mt+Et)/2,Qt=new o.P(es,Ot),{lng:At,lat:Dt}=this.pointLocation3D(Qt),Ht=Math.max(0,xe-At,Oe-Dt,At-_e,Dt-De);xe=Math.min(xe,At),_e=Math.max(_e,At),Oe=Math.min(Oe,Dt),De=Math.max(De,Dt),(xtqe)&&(Xe(pt,mt,es,Ot,xt+1),Xe(es,Ot,kt,Et,xt+1))};if(Xe(C,g,$,g,1),Xe($,g,$,L,1),Xe($,L,C,L,1),Xe(C,L,C,g,1),this.projection.name==="globe"){const[pt,mt]=o.cw(this);pt?(De=90,_e=180,xe=-180):mt&&(Oe=-90,_e=180,xe=-180)}return new o.aK(new o.aU(xe,Oe),new o.aU(_e,De))}_getBoundsRectangular(g,C){const{top:L,left:$}=this._edgeInsets,G=this.height-this._edgeInsets.bottom,K=this.width-this._edgeInsets.right,te=new o.P($,L),de=new o.P(K,L),xe=new o.P(K,G),_e=new o.P($,G);let Oe=this.pointCoordinate(te,g),De=this.pointCoordinate(de,g);const qe=this.pointCoordinate(xe,C),st=this.pointCoordinate(_e,C),Xe=(pt,mt)=>(mt.y-pt.y)/(mt.x-pt.x);return Oe.y>1&&De.y>=0?Oe=new o.ag((1-st.y)/Xe(st,Oe)+st.x,1):Oe.y<0&&De.y<=1&&(Oe=new o.ag(-st.y/Xe(st,Oe)+st.x,0)),De.y>1&&Oe.y>=0?De=new o.ag((1-qe.y)/Xe(qe,De)+qe.x,1):De.y<0&&Oe.y<=1&&(De=new o.ag(-qe.y/Xe(qe,De)+qe.x,0)),new o.aK().extend(this.coordinateLocation(Oe)).extend(this.coordinateLocation(De)).extend(this.coordinateLocation(st)).extend(this.coordinateLocation(qe))}_getBoundsRectangularTerrain(){const g=this.elevation;if(!g.visibleDemTiles.length||g.isUsingMockSource())return this._getBoundsRectangular(0,0);const C=g.visibleDemTiles.reduce((L,$)=>{if($.dem){const G=$.dem.tree;L.min=Math.min(L.min,G.minimums[0]),L.max=Math.max(L.max,G.maximums[0])}return L},{min:Number.MAX_VALUE,max:0});return this._getBoundsRectangular(C.min*g.exaggeration(),C.max*g.exaggeration())}getBounds(){return this.projection.name==="mercator"||this.projection.name==="equirectangular"?this._terrainEnabled()?this._getBoundsRectangularTerrain():this._getBoundsRectangular(0,0):this._getBoundsNonRectangular()}horizonLineFromTop(g=!0){const C=this.height/2/Math.tan(this._fov/2)/Math.tan(Math.max(this._pitch,.1))-this.centerOffset.y,L=this.height/2-C*(1-this._horizonShift);return g?Math.max(0,L):L}getMaxBounds(){return this.maxBounds}setMaxBounds(g){this.maxBounds=g,this.minLat=-o.ct,this.maxLat=o.ct,this.minLng=-180,this.maxLng=180,g&&(this.minLat=g.getSouth(),this.maxLat=g.getNorth(),this.minLng=g.getWest(),this.maxLng=g.getEast(),this.maxLngOe&&(te=Oe-xe),Oe-_eqe&&(K=qe-de),qe-De{for(let Ns=0;Ns<16;Ns++)Bs[Ns]=o.am(Ps[Ns],rn[Ns],hn)})(te,te,de,o.cL(this.pitch>=If?1:this.pitch/If))}else te=de;const xe=o.cz([],de,K);let _e=o.cz([],te,K);if(this.projection.isReprojectedInTileSpace){const Dt=this.locationCoordinate(this.center),Ht=o.b9([]);o.bx(Ht,Ht,[Dt.x*this.worldSize,Dt.y*this.worldSize,0]),o.aD(Ht,Ht,o.cA(this)),o.bx(Ht,Ht,[-Dt.x*this.worldSize,-Dt.y*this.worldSize,0]),o.aD(_e,_e,Ht),o.aD(xe,xe,Ht),this.inverseAdjustmentMatrix=o.cB(this)}else this.inverseAdjustmentMatrix=[1,0,0,1];if(this.mercatorMatrix=o.cC([],_e,[this.worldSize,this.worldSize,this.worldSize/G,1]),this.projMatrix=_e,this.invProjMatrix=o.b7(new Float64Array(16),this.projMatrix),C){const Dt=this._camera.getCameraToClipPerspective(this._fov,this.width/this.height,this._nearZ,1/0);Dt[8]=2*-g.x/this.width,Dt[9]=2*g.y/this.height,this.expandedFarZProjMatrix=o.cz([],Dt,K)}else this.expandedFarZProjMatrix=this.projMatrix;const Oe=o.b7([],te);this.frustumCorners=o.cD.fromInvProjectionMatrix(Oe,this.horizonLineFromTop(),this.height),this.cameraFrustum=o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,0,!C);const De=new Float32Array(16);o.b9(De),o.cC(De,De,[1,-1,1]),o.cE(De,De,this._pitch),o.ba(De,De,this.angle);const qe=o.bS(new Float32Array(16),this._fov,this.width/this.height,this._nearZ,this._farZ);this.starsProjMatrix=o.b8(qe);const st=(Math.PI/2-this._pitch)*(this.height/this._fov)*this._horizonShift;qe[8]=2*-g.x/this.width,qe[9]=2*(g.y+st)/this.height,this.skyboxMatrix=o.aD(De,qe,De);const Xe=this.point,pt=Xe.x,mt=Xe.y,kt=this.width%2/2,Et=this.height%2/2,xt=Math.cos(this.angle),es=Math.sin(this.angle),Ot=pt-Math.round(pt)+xt*kt+es*Et,Qt=mt-Math.round(mt)+xt*Et+es*kt,At=new Float64Array(_e);if(o.bx(At,At,[Ot>.5?Ot-1:Ot,Qt>.5?Qt-1:Qt,0]),this.alignedProjMatrix=At,_e=o.bb(),o.cC(_e,_e,[this.width/2,-this.height/2,1]),o.bx(_e,_e,[1,-1,0]),this.labelPlaneMatrix=_e,_e=o.bb(),o.cC(_e,_e,[1,-1,1]),o.bx(_e,_e,[-1,-1,0]),o.cC(_e,_e,[2/this.width,2/this.height,1]),this.glCoordMatrix=_e,this.pixelMatrix=o.aD(new Float64Array(16),this.labelPlaneMatrix,xe),this._calcFogMatrices(),this._distanceTileDataCache={},_e=o.b7(new Float64Array(16),this.pixelMatrix),!_e)throw new Error("failed to invert matrix");if(this.pixelMatrixInverse=_e,this.projection.name==="globe"||this.mercatorFromTransition){this.globeMatrix=o.cF(this);const Dt=[this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]];this.globeCenterInViewSpace=o.ah(Dt,Dt,K),this.globeRadius=this.worldSize/2/Math.PI-1}else this.globeMatrix=_e;this._projMatrixCache={},this._alignedProjMatrixCache={},this._pixelsToTileUnitsCache={},this._expandedProjMatrixCache={}}_calcFogMatrices(){this._fogTileMatrixCache={};const g=this.cameraWorldSizeForFog,C=this.cameraPixelsPerMeter,L=this._camera.position,$=1/this.height/this._pixelsPerMercatorPixel,G=[g,g,C];o.bJ(G,G,$),o.bJ(L,L,-1),o.cG(L,L,G);const K=o.bb();o.bx(K,K,L),o.cC(K,K,G),this.mercatorFogMatrix=K,this.worldToFogMatrix=this._camera.getWorldToCameraPosition(g,C,$)}_computeCameraPosition(g){const C=(g=g||this.pixelsPerMeter)/this.pixelsPerMeter,L=this._camera.forward(),$=this.point,G=this._mercatorZfromZoom(this._seaLevelZoom?this._seaLevelZoom:this._zoom)*C-g/this.worldSize*this._centerAltitude;return[$.x/this.worldSize-L[0]*G,$.y/this.worldSize-L[1]*G,g/this.worldSize*this._centerAltitude-L[2]*G]}_updateCameraState(){this.height&&(this._camera.setPitchBearing(this._pitch,this.angle),this._camera.position=this._computeCameraPosition())}_translateCameraConstrained(g){const C=this._maxCameraBoundsDistance()*Math.cos(this._pitch),L=this._camera.position[2],$=g[2];let G=1;this.projection.wrap&&(this.center=this.center.wrap()),$>0&&(G=Math.min((C-L)/$,1)),this._camera.position=o.bg([],this._camera.position,g,G),this._updateStateFromCamera()}_updateStateFromCamera(){const g=this._camera.position,C=this._camera.forward(),{pitch:L,bearing:$}=this._camera.getPitchBearing(),G=o.bU(this._centerAltitude,this.center.lat)*this._pixelsPerMercatorPixel,K=this._mercatorZfromZoom(this._maxZoom)*Math.cos(o.ap(this._maxPitch)),te=Math.max((g[2]-G)/Math.cos(L),K),de=this._zoomFromMercatorZ(te);o.bg(g,g,C,te),this._pitch=o.aC(L,o.ap(this.minPitch),o.ap(this.maxPitch)),this.angle=o.bs($,-Math.PI,Math.PI),this._setZoom(o.aC(de,this._minZoom,this._maxZoom)),this._updateSeaLevelZoom(),this._center=this.coordinateLocation(new o.ag(g[0],g[1],g[2])),this._unmodified=!1,this._constrain(),this._calcMatrices()}_worldSizeFromZoom(g){return Math.pow(2,g)*this.tileSize}_mercatorZfromZoom(g){return this.cameraToCenterDistance/this._worldSizeFromZoom(g)}_minimumHeightOverTerrain(){const g=Math.min(this._seaLevelZoom!=null?this._seaLevelZoom:this._zoom,this._maxZoom)+4;return this._mercatorZfromZoom(g)}_zoomFromMercatorZ(g){return this.scaleZoom(this.cameraToCenterDistance/(Math.max(0,g)*this.tileSize))}zoomFromMercatorZAdjusted(g){let C=0,L=o.cv,$=0,G=1/0;for(;L-C>1e-6&&L>C;){const K=C+.5*(L-C),te=this.tileSize*Math.pow(2,K),de=this.getCameraToCenterDistance(this.projection,K,te),xe=this.scaleZoom(de/(Math.max(0,g)*this.tileSize)),_e=Math.abs(K-xe);_exe||De.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(g,C){const L=o.ai(o.ax([],this._camera.position,g)),$=this._zoomFromMercatorZ(L)+C;return L-this._mercatorZfromZoom($)}getCameraPoint(){if(this.projection.name==="globe"){const g=function([C,L,$],G){const K=[C,L,$,1];o.aE(K,K,G);const te=K[3]=Math.max(K[3],1e-6);return K[0]/=te,K[1]/=te,K[2]/=te,K}([this.globeMatrix[12],this.globeMatrix[13],this.globeMatrix[14]],this.pixelMatrix);return new o.P(g[0],g[1])}{const g=Math.tan(this._pitch)*(this.cameraToCenterDistance||1);return this.centerPoint.add(new o.P(0,g))}}getCameraToCenterDistance(g,C=this.zoom,L=this.worldSize){const $=o.cy(g,C,this.width,this.height,1024),G=g.pixelSpaceConversion(this.center.lat,L,$);let K=.5/Math.tan(.5*this._fov)*this.height*G;return this.isOrthographic&&(K=o.am(1,K,o.cL(this.pitch>=If?1:this.pitch/If))),K}getWorldToCameraMatrix(){const g=this._camera.getWorldToCamera(this.worldSize,this.projection.zAxisUnit==="meters"?this.pixelsPerMeter:1);return this.projection.name==="globe"&&o.aD(g,g,this.globeMatrix),g}getFrustum(g){return o.cl.fromInvProjectionMatrix(this.invProjMatrix,this.worldSize,g,this.projection.zAxisUnit==="meters")}}const Dc=(M,g)=>{if(g>0&&M.terrain&&o.w("Cutoff is currently disabled on terrain"),g<=0||M.terrain)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const C=M.transform,L=C.pitch,$=C.isLODDisabled(!1)?60:30;if(L<$-15)return{shouldRenderCutoff:!1,uniformValues:{u_cutoff_params:[0,0,0,1]}};const G=C._farZ-C._nearZ,K=g*C.height*1.3,te=Math.pow(2,.85*Math.max(C._zoom-M.minCutoffZoom,0)),de=1.4*C.cameraToCenterDistance*te,xe=o.aj($-15,$,L),_e=(1-(Oe=xe))*(C._farZ+K)+Oe*de;var Oe;const De=Math.min(K,_e-C._nearZ);return{shouldRenderCutoff:xe>0,uniformValues:{u_cutoff_params:[C._nearZ,C._farZ,(_e-C._nearZ)/G,(_e-De-C._nearZ)/G]}}},Rp=2048;class lj{constructor(g,C){this.aabb=g,this.lastCascade=C}}class TN{add(g,C){const L=this.receivers[g.key];L!==void 0?(L.aabb.min[0]=Math.min(L.aabb.min[0],C.min[0]),L.aabb.min[1]=Math.min(L.aabb.min[1],C.min[1]),L.aabb.min[2]=Math.min(L.aabb.min[2],C.min[2]),L.aabb.max[0]=Math.max(L.aabb.max[0],C.max[0]),L.aabb.max[1]=Math.max(L.aabb.max[1],C.max[1]),L.aabb.max[2]=Math.max(L.aabb.max[2],C.max[2])):this.receivers[g.key]=new lj(C,null)}clear(){this.receivers={}}get(g){return this.receivers[g.key]}computeRequiredCascades(g,C,L){const $=o.cU.fromPoints(g.points);let G=0;for(const K in this.receivers){const te=this.receivers[K];if(!te||!$.intersectsAabb(te.aabb))continue;te.aabb.min=$.closestPoint(te.aabb.min),te.aabb.max=$.closestPoint(te.aabb.max);const de=te.aabb.getCorners();for(let xe=0;xe1||De[1]<-1||De[1]>1){_e=!1;break}}if(te.lastCascade=xe,G=Math.max(G,xe),_e)break}}return G+1}}class Jl{constructor(g){this.painter=g,this._enabled=!1,this._drawShadowAfterLayer=-1,this._numCascadesToRender=0,this._cascades=[],this._groundShadowTiles=[],this._receivers=new TN,this._depthMode=new nr(g.context.gl.LEQUAL,nr.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 g of this._cascades)g.texture.destroy(),g.framebuffer.destroy();this._cascades=[]}updateShadowParameters(g,C){const L=this.painter;if(this._enabled=!1,this._drawShadowAfterLayer=-1,this._receivers.clear(),!C||!C.properties)return;const $=C.properties.get("shadow-intensity"),G=C.properties.get("shadow-draw-before-layer");if(!C.shadowsEnabled()||$<=0)return;let K=-1,te=0;for(const mt of L.style.order){const kt=L.style._mergedLayers[mt];kt.hasShadowPass()&&!kt.isHidden(g.zoom)&&(K=te),!G||G!==mt&&G!==kt.slot||(this._drawShadowAfterLayer=te>0?te-1:0),te+=1}if(this._enabled=K>=0,!this.enabled)return;this._drawShadowAfterLayer<0&&(this._drawShadowAfterLayer=K);const de=L.context,xe=Rp,_e=Rp;if(this._cascades.length===0||Rp!==this._cascades[0].texture.size[0]){this._cascades=[];for(let mt=0;mt<2;++mt){const kt=de.gl,Et=de.createFramebuffer(xe,_e,0,"texture"),xt=new o.T(de,{width:xe,height:_e,data:null},kt.DEPTH_COMPONENT16);Et.depthAttachment.set(xt.texture),this._cascades.push({framebuffer:Et,texture:xt,matrix:[],far:0,boundingSphereRadius:0,frustum:new o.cl,scale:0})}}this.shadowDirection=EN(C);let Oe=0;if(g.elevation){const mt=g.elevation,kt=[1e4,-1e4];mt.visibleDemTiles.filter(Et=>Et.dem).forEach(Et=>{const xt=Et.dem.tree;kt[0]=Math.min(kt[0],xt.minimums[0]),kt[1]=Math.max(kt[1],xt.maximums[0])}),kt[0]!==1e4&&(Oe=(kt[1]-kt[0])*mt.exaggeration())}const De=1.5*g.cameraToCenterDistance,qe=3*De,st=new Float64Array(16);for(let mt=0;mt=0)return{};const G=function(de,xe,_e){const Oe=_e/(1<0&&(o.cT(G[1],G[1],[$[0]*K,0,0]),o.cT(G[2],G[2],[$[0]*K,0,0])),$[1]<0?(o.cT(G[0],G[0],[0,$[1]*K,0]),o.cT(G[1],G[1],[0,$[1]*K,0])):$[1]>0&&(o.cT(G[2],G[2],[0,$[1]*K,0]),o.cT(G[3],G[3],[0,$[1]*K,0]));const te={};return te.vertices=G,te.planes=[r1(G[1],G[0],G[4]),r1(G[2],G[1],G[5]),r1(G[3],G[2],G[6]),r1(G[0],G[3],G[7])],te}addShadowReceiver(g,C,L){this._receivers.add(g,o.cU.fromTileIdAndHeight(g,C,L))}getMaxCascadeForTile(g){const C=this._receivers.get(g);return C&&C.lastCascade?C.lastCascade:0}}function r1(M,g,C){const L=o.ax([],C,g),$=o.ax([],M,g),G=o.bh([],L,$),K=o.ai(G);return K===0?[0,0,1,0]:(o.bJ(G,G,1/K),[G[0],G[1],G[2],-o.bi(G,g)])}function EN(M){const g=M.properties.get("direction"),C=o.cP(g.x,g.y,g.z);C[2]=o.aC(C[2],0,75);const L=o.cR([C[0],C[1],C[2]]);return o.cQ(L.x,L.y,L.z)}function Op(M,g,C){const L=g.properties.get("color-use-theme")==="none",$=g.properties.get("color"),G=g.properties.get("intensity"),K=g.properties.get("direction"),te=[K.x,K.y,K.z],de=C.properties.get("color-use-theme")==="none",xe=C.properties.get("color"),_e=C.properties.get("intensity"),Oe=Math.max(o.bi([0,0,1],te),0),De=[0,0,0];o.bJ(De,xe.toPremultipliedRenderColor(de?null:M.getLut(g.scope)).toArray01Linear().slice(0,3),_e);const qe=[0,0,0];return o.bJ(qe,$.toPremultipliedRenderColor(L?null:M.getLut(C.scope)).toArray01Linear().slice(0,3),Oe*G),o.cW([De[0]>0?De[0]/(De[0]+qe[0]):0,De[1]>0?De[1]/(De[1]+qe[1]):0,De[2]>0?De[2]/(De[2]+qe[2]):0])}function Oy(M,g,C,L,$,G){const K=M.zoom,te=M.scale,de=M.worldSize,xe=1/de,_e=M.aspect,Oe=Math.sqrt(1+_e*_e)*Math.tan(.5*M.fovX),De=Oe*Oe,qe=L-C,st=L+C;let Xe,pt;De>qe/st?(Xe=L,pt=L*Oe):(Xe=.5*st*(1+De),pt=.5*Math.sqrt(qe*qe+2*(L*L+C*C)*De+st*st*De*De));const mt=M.projection.pixelsPerMeter(M.center.lat,de),kt=M._camera.getCameraToWorldMercator(),Et=[0,0,-Xe*xe];o.ah(Et,Et,kt);let xt=pt*xe;const es=function(Ys){return Ys[0]/=te,Ys[1]/=te,Ys[2]=o.bU(Ys[2],M._center.lat),Ys},Ot=M._edgeInsets;if(!(Ot.left===0&&Ot.top===0&&Ot.right===0&&Ot.bottom===0||Ot.left===Ot.right&&Ot.top===Ot.bottom)){const Ys=M._camera.getWorldToCamera(M.worldSize,M.projection.zAxisUnit==="meters"?mt:1),Dn=M._camera.getCameraToClipPerspective(M._fov,M.width/M.height,C,L);Dn[8]=2*-M.centerOffset.x/M.width,Dn[9]=2*M.centerOffset.y/M.height;const kn=new Float64Array(16);o.cz(kn,Dn,Ys);const Sn=new Float64Array(16);o.b7(Sn,kn);const cn=o.cl.fromInvProjectionMatrix(Sn,de,K,!0);for(const ur of cn.points){const Nr=es(ur);xt=Math.max(xt,o.bK(o.cV([],Et,Nr)))}}xt*=$/($-1);const Qt=Math.acos(g[2]),At=Math.atan2(-g[0],-g[1]),Dt=new c0;Dt.position=Et,Dt.setPitchBearing(Qt,At);const Ht=Dt.getWorldToCamera(de,mt),gs=xt*de,ss=Math.min(M._mercatorZfromZoom(17)*de*-2,-2*gs),Bs=Dt.getCameraToClipOrthographic(-gs,gs,-gs,gs,ss,(gs+G*mt)/g[2]),Ps=new Float64Array(16);o.aD(Ps,Bs,Ht);const rn=o.cQ(Math.floor(1e6*Et[0])/1e6*de,Math.floor(1e6*Et[1])/1e6*de,0),hn=.5*$,Ns=[0,0,0];o.ah(Ns,rn,Ps),o.bJ(Ns,Ns,hn);const ds=[Math.floor(Ns[0]),Math.floor(Ns[1]),Math.floor(Ns[2])],Fs=[0,0,0];o.ax(Fs,Ns,ds),o.bJ(Fs,Fs,-1/hn);const Us=new Float64Array(16);return o.b9(Us),o.bx(Us,Us,Fs),o.aD(Ps,Us,Ps),[Ps,gs]}class lC extends o.E{constructor(g){super(),this.requestManager=g,this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}loadModel(g,C){return o.cX(this.requestManager.transformRequest(C,o.R.Model).url).then(L=>{const $=o.cY(L),G=new o.cZ(g,C,void 0,void 0,$);return G.computeBoundsAndApplyParent(),G}).catch(L=>{if(L&&L.status===404)return null;this.fire(new o.B(new Error(`Could not load model ${g} from ${C}: ${L.message}`)))})}load(g,C,L={forceReload:!1}){this.models[C]||(this.models[C]={});const $=Object.keys(g),G=[],K=[];for(const te of $){const de=g[te];this.hasURLBeenRequested(de)&&!L.forceReload||(this.modelByURL[de]={modelId:te,scope:C},G.push(this.loadModel(te,de)),K.push(te)),this.models[C][te]||(this.models[C][te]={model:null,numReferences:1})}this.numModelsLoading[C]=(this.numModelsLoading[C]||0)+K.length,Promise.allSettled(G).then(te=>{for(let de=0;de{this.fire(new o.B(new Error(`Could not load models: ${te.message}`)))})}isLoaded(){for(const g in this.numModelsLoading)if(this.numModelsLoading[g]>0)return!1;return!0}hasModel(g,C,L={exactIdMatch:!1}){return!!(L.exactIdMatch?this.getModel(g,C):this.getModelByURL(this.modelUris[C][g]))}getModel(g,C){return this.models[C]||(this.models[C]={}),this.models[C][g]?this.models[C][g].model:void 0}getModelByURL(g){if(!g)return null;const C=this.modelByURL[g];return C?this.models[C.scope][C.modelId].model:null}hasModelBeenAdded(g,C){return this.models[C]&&this.models[C][g]!==void 0}getModelURIs(g){return this.modelUris[g]||{}}addModel(g,C,L){this.models[L]||(this.models[L]={}),this.modelUris[L]||(this.modelUris[L]={});const $=this.requestManager.normalizeModelURL(C);if((this.hasModel(g,L,{exactIdMatch:!0})||this.hasModelBeenAdded(g,L))&&this.modelUris[L][g]===$)this.models[L][g].numReferences++;else if(this.hasURLBeenRequested($)){const{scope:G,modelId:K}=this.modelByURL[$];this.models[G][K].numReferences++}else this.modelUris[L][g]=$,this.load({[g]:this.modelUris[L][g]},L)}addModelURLs(g,C){this.models[C]||(this.models[C]={}),this.modelUris[C]||(this.modelUris[C]={});const L=this.modelUris[C];for(const $ in g)L[$]=this.requestManager.normalizeModelURL(g[$])}reloadModels(g){this.load(this.modelUris[g],g,{forceReload:!0})}addModelsFromBucket(g,C){this.models[C]||(this.models[C]={}),this.modelUris[C]||(this.modelUris[C]={});const L={};for(const $ of g)this.hasModel($,C,{exactIdMatch:!0})||this.hasURLBeenRequested($)?this.models[C][$].numReferences++:this.modelUris[C][$]&&!this.hasURLBeenRequested($)?L[$]=this.modelUris[C][$]:!this.hasURLBeenRequested($)&&o.c_($,!1)&&(this.modelUris[C][$]=this.requestManager.normalizeModelURL($),L[$]=this.modelUris[C][$]);this.load(L,C)}hasURLBeenRequested(g){return this.modelByURL[g]!==void 0}removeModel(g,C,L=!1,$=!1){if(this.models[C]&&this.models[C][g]&&(this.models[C][g].numReferences--,this.models[C][g].numReferences===0||$)){const G=this.modelUris[C][g];L||delete this.modelUris[C][g],delete this.modelByURL[G];const K=this.models[C][g].model;if(!K)return;delete this.models[C][g],K.destroy()}}destroy(){for(const g of Object.keys(this.models))for(const C of Object.keys(this.models[g])){const L=this.models[g][C].model;delete this.models[g][C],L&&L.destroy()}this.models={"":{}},this.modelUris={"":{}},this.modelByURL={},this.numModelsLoading={}}listModels(g){return this.models[g]||(this.models[g]={}),Object.keys(this.models[g])}upload(g,C){this.models[C]||(this.models[C]={});for(const L in this.models[C])this.models[C][L].model&&this.models[C][L].model.upload(g.context)}}const d0=o.a8.colorTheme,Gl=new o.ab({data:new o.ac(d0.data)});function Vd(M){if(!M.metadata||!M.metadata.content_area)return;const g=o.o.devicePixelRatio,{left:C,top:L,width:$,height:G}=M.metadata.content_area,K=C*g,te=L*g;return[K,te,K+$*g,te+G*g]}function id(M){if(M)return M.map(([g,C])=>[g*o.o.devicePixelRatio,C*o.o.devicePixelRatio])}class Gb{constructor(g,C,L){this.id=g,this.scope=C,this.sourceCache=L,this.pendingRequests=new Set,this.missingRequests=new Set}addPendingRequest(g){this.missingRequests.has(g.name)||this.pendingRequests.has(g.name)||this.pendingRequests.add(g.name)}hasPendingRequests(){return this.pendingRequests.size>0}resolvePendingRequests(){const g=new Map;if(!this.sourceCache.loaded())return g;const C=this.sourceCache.getVisibleCoordinates();if(C.length===0)return g;const L=this.sourceCache.getSource();if(!(L instanceof hm))return g;const $=C.map(K=>this.sourceCache.getTile(K)),G=L.getImages($,Array.from(this.pendingRequests));for(const[K,te]of G)g.set(o.I.from({name:K,iconsetId:this.id}),te),this.pendingRequests.delete(K);for(const K of this.pendingRequests)this.missingRequests.add(K);return this.pendingRequests.clear(),g}}class Pf{constructor(){this._previousClosestBuildingId=null,this._hysteresisRatio=.8,this._indoorMinimumZoom=16}findClosestBuilding(g,C,L,$,G){if(Lde*this._hysteresisRatio&&(K=this._previousClosestBuildingId):xe&&!K&&(K=this._previousClosestBuildingId),this._previousClosestBuildingId=K,K}_calculateDistance(g,C){if(!C.center)return Number.MAX_VALUE;const L=g.lat-C.center[1],$=g.lng-C.center[0];return L*L+$*$}_isBuildingVisible(g,C,L){if(!L)return!1;for(const $ of g.floorIds){const G=g.floors[$];if(!G.geometry)continue;const K=G.geometry;if(K.type==="Polygon"){const te=this._convertRingToPoints(K.coordinates[0]);if(o.bw(te,L))return!0}else if(K.type==="MultiPolygon"){const te=this._convertMultiPolygonToPoints(K.coordinates);if(o.d0(L,te))return!0}}return!1}_convertRingToPoints(g){return g.map(C=>new o.P(C[0],C[1]))}_convertMultiPolygonToPoints(g){return g.map(C=>C.length===0?[]:C[0].map(L=>new o.P(L[0],L[1])))}}class cj extends o.E{constructor(g){super(),this._style=g,this._buildings={},this._activeFloors=new Set,this._closestBuildingId=null,this._indoorState={selectedFloorId:null,activeFloorsVisible:!0,activeFloors:this._activeFloors},this._buildingDetectionStrategy=new Pf,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(g){g===this._selectedFloorId&&this._indoorState&&this._indoorState.activeFloorsVisible||(this._selectedFloorId=g,this._recalculateActiveFloors())}setActiveFloorsVisibility(g){this._updateActiveFloors(g),this._updateIndoorSelector()}setIndoorData(g){let C=!1;for(const[L,$]of Object.entries(g.buildings))if(this._buildings[L])for(const G of $.floorIds)this._buildings[L].floorIds.add(G),this._buildings[L].floors[G]?this._mergeFloors(this._buildings[L].floors[G],$.floors[G]):(this._buildings[L].floors[G]=$.floors[G],C=!0);else this._buildings[L]=$,C=!0;C&&this._recalculateActiveFloors()}getIndoorTileOptions(g,C){return this._indoorState?{sourceLayers:this._style.getIndoorSourceLayers(g,C),indoorState:this._indoorState}:null}getControlState(){const g=this._buildings,C=this._closestBuildingId,L=C&&g?g[C]:void 0;if(!L)return{selectedFloorId:null,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:[]};let $=null;for(const K of L.floorIds)if(this._activeFloors&&this._activeFloors.has(K)){$=K;break}const G=Array.from(L.floorIds).map(K=>({id:K,name:L.floors[K].name,zIndex:L.floors[K].zIndex})).sort((K,te)=>te.zIndex-K.zIndex).filter((K,te,de)=>te===0||K.zIndex!==de[te-1].zIndex);return{selectedFloorId:$,activeFloorsVisible:!!this._indoorState&&this._indoorState.activeFloorsVisible,floors:G}}_updateUI(){this._initialLoadDone=!0;const g=this._style.map.transform,C=this._buildingDetectionStrategy.findClosestBuilding(this._buildings,g.center,g.zoom,g.getBounds(),this._makeViewportPolygon());if(C!==this._closestBuildingId){const L=this._closestBuildingId;this._closestBuildingId=C,this._onBuildingTransition(L,C),this._updateIndoorSelector()}}_onBuildingTransition(g,C){if(!this._indoorState)return;!C&&g?(this._indoorState.activeFloors=new Set,this._indoorState.activeFloorsVisible=!1,this._style.updateIndoorDependentLayers()):!!C&&!g&&(this._recalculateActiveFloors(),this._updateActiveFloors(!0))}_updateIndoorSelector(){this.fire(new o.C("selector-update",this.getControlState()))}_updateActiveFloors(g){this._indoorState={selectedFloorId:this._selectedFloorId,activeFloorsVisible:g,activeFloors:this._activeFloors},this._initialLoadDone?this._style.updateIndoorDependentLayers():this._indoorState.needsUpdate=!0}_recalculateActiveFloors(){if(!this._buildings)return;const g=o.d1.calculate(this._buildings,this._selectedFloorId,this._activeFloors);(function(C,L){if(C===L)return!0;if(!C||!L||C.size!==L.size)return!1;for(const $ of C)if(!L.has($))return!1;return!0})(g,this._activeFloors)||(this._activeFloors=g,this._updateActiveFloors(!!this._indoorState&&this._indoorState.activeFloorsVisible),this._updateIndoorSelector())}_mergeFloors(g,C){C.geometry&&(g.geometry?(g.geometry.type==="Polygon"&&(g.geometry={type:"MultiPolygon",coordinates:[g.geometry.coordinates]}),C.geometry.type==="Polygon"?g.geometry.coordinates.push(C.geometry.coordinates):C.geometry.type==="MultiPolygon"&&g.geometry.coordinates.push(...C.geometry.coordinates)):g.geometry=C.geometry)}_makeViewportPolygon(){const g=this._style.map.transform,C=g.width,L=g.height;return[g.pointLocation(new o.P(0,0)),g.pointLocation(new o.P(C,0)),g.pointLocation(new o.P(C,L)),g.pointLocation(new o.P(0,L))].map($=>new o.P($.lng,$.lat))}}const a1=(M,g)=>mn(M,g&&g.filter(C=>C.identifier!=="source.canvas")),Fh=o.aJ(Ka,["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"]),AN=o.aJ(Ka,["setCenter","setZoom","setBearing","setPitch"]),dj=new Set(["background","sky","slot","custom"]),Wb={version:8,layers:[],sources:{}},Lf={duration:300,delay:0};class Yc extends o.E{constructor(g,C={}){if(super(),this.map=g,this.scope=C.scope||"",this.globalId=null,this.fragments=[],this.importDepth=C.importDepth||0,this.importsCache=C.importsCache||new Map,this.resolvedImports=C.resolvedImports||new Set,this.transition=Object.assign({},Lf),this._buildingIndex=new l0(this),this.crossTileSymbolIndex=new Af,this._mergedOrder=[],this._drapedFirstOrder=[],this._mergedLayers={},this._mergedIndoor={},this._mergedSourceCaches={},this._mergedOtherSourceCaches={},this._mergedSymbolSourceCaches={},this._mergedFillExtrusionSourceCaches={},this._clipLayerPresent=!1,this._hasAppearances=!1,this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this._importedAsBasemap=!1,this._changes=C.styleChanges||new Ke,this._hasDataDrivenEmissive=!1,this.indoorManager=new cj(this),this.dispatcher=C.dispatcher?C.dispatcher:new ut($t(),this),this.map.painter&&this.map.painter.context){const $=this.map.painter.context.maxUniformBufferBindings,G=Math.floor(this.map.painter.context.maxUniformBlockSize/4);this.dispatcher.broadcast("setContextParams",{maxBindingPoints:$,maxUniformBlockSizeDwords:G,disableSymbolUBO:this.map.painter.context.disableSymbolUBO})}C.imageManager?this.imageManager=C.imageManager:(this.imageManager=new Yt(this.map._spriteFormat),this.imageManager.setEventedParent(this)),this.imageManager.addScope(this.scope),this.glyphManager=C.glyphManager?C.glyphManager:new o.d2(g._requestManager,C.localFontFamily?o.d3.all:C.localIdeographFontFamily?o.d3.ideographs:o.d3.none,C.localFontFamily||C.localIdeographFontFamily,C.useServerFontComposition),C.modelManager?this.modelManager=C.modelManager:(this.modelManager=new lC(g._requestManager),this.modelManager.setEventedParent(this)),this._layers={},this._sourceCaches={},this._otherSourceCaches={},this._symbolSourceCaches={},this._fillExtrusionSourceCaches={},this._loaded=!1,this._precompileDone=!1,this._shouldPrecompile=!1,this._availableImages=[],this._availableModels={},this._order=[],this._markersNeedUpdate=!1,this.options=C.configOptions?C.configOptions:new Map,this._configDependentLayers=C.configDependentLayers?C.configDependentLayers:new Set,this._indoorDependentLayers=C.indoorDependentLayers?C.indoorDependentLayers:new Set,this._config=C.config,this._styleColorTheme={lut:null,lutLoading:!1,lutLoadingCorrelationID:0,colorTheme:null,colorThemeOverride:C.colorThemeOverride},this._styleColorThemeForScope={},this._initialConfig=C.initialConfig,this.dispatcher.broadcast("setReferrer",o.d4()),this.dispatcher.broadcast("setConfig",o.d5());const L=this;this._rtlTextPluginCallback=Yc.registerForPluginStateChange($=>{L.dispatcher.broadcast("syncRTLPluginState",{pluginStatus:$.pluginStatus,pluginURL:$.pluginURL},(G,K)=>{if(o.d6(G),K&&K.every(te=>te))for(const te in L._sourceCaches){const de=L._sourceCaches[te],xe=de.getSource().type;xe!=="vector"&&xe!=="geojson"||de.reload()}})}),this.on("data",$=>{if($.dataType!=="source"||$.sourceDataType!=="metadata")return;const G=this.getOwnSource($.sourceId);if(G&&G.vectorLayerIds)for(const K in this._layers){const te=this._layers[K];te.source===G.id&&this._validateLayer(te)}})}load(g){return g?(typeof g=="string"?this.loadURL(g):this.loadJSON(g),this):this}_getGlobalId(g){if(!g)return null;if(typeof g=="string"){if(o.e(g))return g;const C=o.d7(g);if(!C.startsWith("http"))try{return new URL(C,location.href).toString()}catch{return C}return C}return`json://${o.d8(JSON.stringify(g))}`}_diffStyle(g,C,L){this.globalId=this._getGlobalId(g);const $=(G,K)=>{try{K(null,this.setState(G,L))}catch(te){K(te,!1)}};if(typeof g=="string"){const G=this.map._requestManager.normalizeStyleURL(g),K=this.map._requestManager.transformRequest(G,o.R.Style);o.m(K,(te,de)=>{te?this.fire(new o.B(te)):de&&$(de,C)})}else typeof g=="object"&&$(g,C)}loadURL(g,C={}){this.fire(new o.C("dataloading",{dataType:"style"}));const L=typeof C.validate=="boolean"?C.validate:!o.e(g);this.globalId=this._getGlobalId(g),g=this.map._requestManager.normalizeStyleURL(g,C.accessToken),this.resolvedImports.add(g);const $=this.importsCache.get(g);if($)return this._load($,L);const G=this.map._requestManager.transformRequest(g,o.R.Style);this._request=o.m(G,(K,te)=>{if(this._request=null,K)this.fire(new o.B(K));else if(te)return this.importsCache.set(g,te),this._load(te,L)})}loadJSON(g,C={}){this.fire(new o.C("dataloading",{dataType:"style"})),this.globalId=this._getGlobalId(g),this._request=o.o.frame(()=>{this._request=null,this._load(g,C.validate!==!1)})}loadEmpty(){this.fire(new o.C("dataloading",{dataType:"style"})),this._load(Wb,!1)}_loadImports(g,C,L){if(this.importDepth>=4)return o.w("Style doesn't support nesting deeper than 5"),Promise.resolve();const $=[];for(const G of g){const K=this._createFragmentStyle(G),te=new Promise(_e=>{K.once("style.import.load",_e),K.once("error",_e)}).then(()=>{this.mergeAll(),this.fire(new o.C("data",{dataType:"style"}))});if($.push(te),this.resolvedImports.has(G.url)){K.loadEmpty();continue}const de=G.data||this.importsCache.get(G.url);de?(G.data?(K.fire(new o.C("dataloading",{dataType:"style"})),K.globalId=K._getGlobalId(de),queueMicrotask(()=>K._load(de,C))):K.loadJSON(de,{validate:C}),this._isInternalStyle(de)&&(K.globalId=null)):G.url?K.loadURL(G.url,{validate:C}):K.loadEmpty();const xe={style:K,id:G.id,config:G.config};if(L){const _e=this.fragments.findIndex(({id:Oe})=>Oe===L);this.fragments=this.fragments.slice(0,_e).concat(xe).concat(this.fragments.slice(_e))}else this.fragments.push(xe)}return Promise.allSettled($)}getImportGlobalIds(g=this,C=new Set){for(const L of g.fragments)L.style.globalId&&C.add(L.style.globalId),this.getImportGlobalIds(L.style,C);return[...C.values()]}_createFragmentStyle(g){const C=this.scope?o.F(g.id,this.scope):g.id;let L;const $=this._initialConfig&&this._initialConfig[C];(g.config||$)&&(L=Object.assign({},g.config,$));const G=new Yc(this.map,{scope:C,styleChanges:this._changes,importDepth:this.importDepth+1,importsCache:this.importsCache,resolvedImports:new Set(this.resolvedImports),dispatcher:this.dispatcher,imageManager:this.imageManager,glyphManager:this.glyphManager,modelManager:this.modelManager,config:L,configOptions:this.options,colorThemeOverride:g["color-theme"],configDependentLayers:this._configDependentLayers,indoorDependentLayers:this._indoorDependentLayers});return G.setEventedParent(this.map,{style:G}),G}_reloadImports(){this.mergeAll(),this._updateMapProjection(),this.updateConfigDependencies(),this._updateLayers(this._indoorDependentLayers),this.map._triggerCameraUpdate(this.camera),this.dispatcher.broadcast("setLayers",{layers:this._serializeLayers(this._order),scope:this.scope,options:this.options}),this._shouldPrecompile=this.map._precompilePrograms&&this.isRootStyle()}_isInternalStyle(g){return this.isRootStyle()&&(g.fragment||!!g.schema&&g.fragment!==!1)}_load(g,C){if(this._isInternalStyle(g)){const G=Object.assign({},Wb,{imports:[{id:"basemap",data:g,url:""}]},g.center?{center:g.center}:{},g.bearing?{bearing:g.bearing}:{},g.pitch?{pitch:g.pitch}:{},g.zoom?{zoom:g.zoom}:{},g.light?{light:g.light}:{});return this._importedAsBasemap=!0,void this._load(G,C)}if(this.updateConfig(this._config,g.schema),C&&a1(this,ir(g)))return;this._loaded=!0;for(const G in g.sources)this.addSource(G,g.sources[G],{validate:!1,isInitialLoad:!0});this.stylesheet=o.d9(g);const L=()=>{if(g.iconsets)for(const de in g.iconsets)this.addIconset(de,g.iconsets[de]);g.sprite?this._loadIconset(g.sprite):(this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0})),!this.glyphManager.url&&g.glyphs&&this.glyphManager.setURL(g.glyphs);const G=Cf(this.stylesheet.layers);if(this._order=G.map(de=>de.id),this.stylesheet.light&&o.w("The `light` root property is deprecated, prefer using `lights` with `flat` light type instead."),this.stylesheet.lights)if(this.stylesheet.lights.length===1&&this.stylesheet.lights[0].type==="flat"){const de=this.stylesheet.lights[0];this.light=new Yn(de.properties,de.id)}else this.setLights(this.stylesheet.lights);this.light||(this.light=new Yn(this.stylesheet.light)),this._layers={};for(const de of G){const xe=o.de(de,this.scope,this._styleColorTheme.lut,this.options);xe.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(xe.fqid),xe.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(xe.fqid),this._hasAppearances=this._hasAppearances||xe.getAppearances().length!==0,xe.setEventedParent(this,{layer:{id:xe.id}}),this._layers[xe.id]=xe;const _e=this.getOwnLayerSourceCache(xe),Oe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();_e&&xe.canCastShadows()&&Oe&&(_e.castsShadows=!0)}if(this.glyphManager.url){const de=new Set;for(const xe in this._layers){const _e=this._layers[xe];if(_e.type==="symbol"&&_e.layout){const Oe=_e.layout.get("text-font");Oe&&Oe.value&&Oe.value.kind==="constant"&&de.add(Oe.value.value.join(","))}}for(const xe of de)this.glyphManager.prefetchRange(xe,0)}this.stylesheet.featuresets&&this.setFeaturesetSelectors(this.stylesheet.featuresets),this.stylesheet.models&&this.addModelURLs(this.stylesheet.models);const K=this.stylesheet.terrain;K&&(this.checkCanvasFingerprintNoise(),this.disableElevatedTerrain||this.terrainSetForDrapingOnly()||this._createTerrain(K,1)),this.stylesheet.fog&&this._createFog(this.stylesheet.fog),this.stylesheet.snow&&this._createSnow(this.stylesheet.snow),this.stylesheet.rain&&this._createRain(this.stylesheet.rain),this.stylesheet.transition&&this.setTransition(this.stylesheet.transition),this.fire(new o.C("data",{dataType:"style"}));const te=this.isRootStyle();g.imports?this._loadImports(g.imports,C).then(()=>{this._reloadImports(),this.fire(new o.C(te?"style.load":"style.import.load"))}).catch(de=>{this.fire(new o.B(new Error("Failed to load imports",de))),this.fire(new o.C(te?"style.load":"style.import.load"))}):(this._reloadImports(),this.fire(new o.C(te?"style.load":"style.import.load")))};this._styleColorTheme.colorTheme=this.stylesheet["color-theme"];const $=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if($){const G=this._evaluateColorThemeData($);this._loadColorTheme(G).then(()=>{L()}).catch(K=>{o.w(`Couldn't load color theme from the stylesheet: ${K}`),L()})}else this._styleColorTheme.lut=null,L()}isRootStyle(){return this.importDepth===0}hasAppearances(){return this._hasAppearances||this.fragments.some(g=>g.style.hasAppearances())}mergeAll(){let g,C,L,$,G,K,te,de,xe,_e;const Oe={};this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(De=>{if(De.stylesheet){if(De.light!=null&&(g=De.light),De.stylesheet.lights)for(const qe of De.stylesheet.lights)qe.type==="ambient"&&De.ambientLight!=null&&(C=De.ambientLight),qe.type==="directional"&&De.directionalLight!=null&&(L=De.directionalLight);$=this._prioritizeTerrain($,De.terrain,De.stylesheet.terrain),De.stylesheet.fog&&De.fog!=null&&(G=De.fog),De.stylesheet.snow&&De.snow!=null&&(K=De.snow),De.stylesheet.rain&&De.rain!=null&&(te=De.rain),De.stylesheet.camera!=null&&(_e=De.stylesheet.camera),De.stylesheet.projection!=null&&(de=De.stylesheet.projection),De.stylesheet.transition!=null&&(xe=De.stylesheet.transition),Oe[De.scope]=De._styleColorTheme}}),this.light=g,this.ambientLight=C,this.directionalLight=L,this.fog=G,this.snow=K,this.rain=te,this._styleColorThemeForScope=Oe,$===null?delete this.terrain:this.terrain=$,this.camera=_e||{"camera-projection":"perspective"},this.projection=de||{name:"mercator"},this.transition=Object.assign({},Lf,xe),this.mergeSources(),this.mergeLayers(),this.mergeIndoor()}forEachFragmentStyle(g){const C=L=>{for(const $ of L.fragments)C($.style);g(L)};C(this)}_prioritizeTerrain(g,C,L){const $=g&&g.drapeRenderMode===0;return L===null?C&&C.drapeRenderMode===0?C:$?g:null:C!=null&&(!g||$||C&&C.drapeRenderMode===1)?C:g}mergeTerrain(){let g;this.terrain&&this.terrain.scope!==this.scope&&delete this.terrain,this.forEachFragmentStyle(C=>{g=this._prioritizeTerrain(g,C.terrain,C.stylesheet.terrain)}),g===null?delete this.terrain:this.terrain=g}mergeProjection(){let g;this.forEachFragmentStyle(C=>{C.stylesheet.projection!=null&&(g=C.stylesheet.projection)}),this.projection=g||{name:"mercator"}}mergeSources(){const g={},C={},L={},$={};this.forEachFragmentStyle(G=>{for(const K in G._sourceCaches){const te=o.F(K,G.scope);g[te]=G._sourceCaches[K]}for(const K in G._otherSourceCaches){const te=o.F(K,G.scope);C[te]=G._otherSourceCaches[K]}for(const K in G._symbolSourceCaches){const te=o.F(K,G.scope);L[te]=G._symbolSourceCaches[K]}for(const K in G._fillExtrusionSourceCaches){const te=o.F(K,G.scope);$[te]=G._fillExtrusionSourceCaches[K]}}),this._mergedSourceCaches=g,this._mergedOtherSourceCaches=C,this._mergedSymbolSourceCaches=L,this._mergedFillExtrusionSourceCaches=$}mergeIndoor(){this.forEachFragmentStyle(g=>{if(g.stylesheet&&g.stylesheet.indoor)for(const C of Object.values(g.stylesheet.indoor)){const L=C,$=o.F(L.sourceId,g.scope);this._mergedIndoor[$]=new Set(L.sourceLayers||[])}})}mergeLayers(){const g={},C=[],L={};this._mergedSlots=[],this._has3DLayers=!1,this._hasCircleLayers=!1,this._hasSymbolLayers=!1,this.forEachFragmentStyle(K=>{for(const te of K._order){const de=K._layers[te];if(de.type==="slot"){const xe=o.da(te);if(g[xe])continue;g[xe]=[]}de.slot&&g[de.slot]?g[de.slot].push(de):C.push(de)}}),this._mergedOrder=[];let $=-1;const G=(K=[])=>{for(const te of K)if(te.type==="slot"){const de=o.da(te.id);g[de]&&G(g[de]),this._mergedSlots.push(de)}else{const de=o.F(te.id,te.scope);this._mergedOrder.push(de),L[de]=te,te.is3D(!!this.terrain)&&(this._has3DLayers=!0,$=this._mergedOrder.length-1),te.type==="circle"&&(this._hasCircleLayers=!0),te.type==="symbol"&&(this._hasSymbolLayers=!0),te.type==="clip"&&(this._clipLayerPresent=!0)}};if(G(C),this._has3DLayers){const K={};for(let te=0;teK[te]-K[de])}this._mergedLayers=L,this.updateDrapeFirstLayers(),this._buildingIndex.processLayersChanged(),this._updateDataDrivenEmissiveStrength()}terrainSetForDrapingOnly(){return!!this.terrain&&this.terrain.drapeRenderMode===0}getCamera(){return this.stylesheet.camera}setCamera(g){return this.stylesheet.camera=Object.assign({},this.stylesheet.camera,g),this.camera=this.stylesheet.camera,this}_evaluateColorThemeData(g){return g.data?function(C,L,$){const G=Object.assign({},L);for(const te of Object.keys(d0))G[te]===void 0&&(G[te]=d0[te].default);const K=new o.aa(Gl,C,new Map($));return K.setTransitionOrValue(G,$),K.untransitioned().possiblyEvaluate(new o.ae(0,{worldview:void 0}))}(this.scope,g,this.options).get("data"):null}_loadColorTheme(g){this._styleColorTheme.lutLoading=!0,this._styleColorTheme.lutLoadingCorrelationID+=1;const C=this._styleColorTheme.lutLoadingCorrelationID;return new Promise((L,$)=>{const G="data:image/png;base64,";if(!g||g.length===0)return this._styleColorTheme.lut=null,this._styleColorTheme.lutLoading=!1,void L();let K=g;K.startsWith(G)||(K=G+K);const te=o.I.from("mapbox-reserved-lut"),de=new Image;de.src=K,de.onerror=()=>{this._styleColorTheme.lutLoading=!1,$(new Error("Failed to load image data"))},de.onload=()=>{if(this._styleColorTheme.lutLoadingCorrelationID!==C)return void L();this._styleColorTheme.lutLoading=!1;const{width:xe,height:_e,data:Oe}=o.o.getImageData(de);if(_e>32)return void $(new Error("The height of the image must be less than or equal to 32 pixels."));if(xe!==_e*_e)return void $(new Error("The width of the image must be equal to the height squared."));this.getImage(te)&&this.removeImage(te),this.addImage(te,{data:new o.q({width:xe,height:_e},Oe),pixelRatio:1,sdf:!1,usvg:!1,version:0});const De=this.imageManager.getImage(te,this.scope);De?(this._styleColorTheme.lut={image:De.data,data:g},L()):$(new Error("Missing LUT image."))}})}getLut(g){const C=this._styleColorThemeForScope[g];return C?C.lut:null}setProjection(g){g?this.stylesheet.projection=g: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(g){this._spriteRequest=function(C,L,$){let G,K,te;const de=o.o.devicePixelRatio>1?"@2x":"";let xe=o.m(L.transformRequest(L.normalizeSpriteURL(C,de,".json"),o.R.SpriteJSON),(De,qe)=>{xe=null,te||(te=De,G=qe,Oe())}),_e=o.n(L.transformRequest(L.normalizeSpriteURL(C,de,".png"),o.R.SpriteImage),(De,qe)=>{_e=null,te||(te=De,K=qe,Oe())});function Oe(){if(te)$(te);else if(G&&K){const De=o.o.getImageData(K),qe={};for(const st in G){const{width:Xe,height:pt,x:mt,y:kt,sdf:Et,pixelRatio:xt,stretchX:es,stretchY:Ot,content:Qt}=G[st],At=new o.q({width:Xe,height:pt});o.q.copy(De,At,{x:mt,y:kt},{x:0,y:0},{width:Xe,height:pt},null),qe[st]={data:At,pixelRatio:xt!==void 0?xt:1,sdf:Et!==void 0&&Et,stretchX:es,stretchY:Ot,content:Qt,usvg:!1,version:0}}$(null,qe)}}return{cancel(){xe&&(xe.cancel(),xe=null),_e&&(_e.cancel(),_e=null)}}}(g,this.map._requestManager,(C,L)=>{if(this._spriteRequest=null,C)this.fire(new o.B(C));else if(L){const $=new Map;for(const G in L)$.set(o.I.from(G),L[G]);this.addImages($)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))})}addIconset(g,C){if(C.type==="sprite")return void this._loadSprite(C.url);const L=this.getOwnSourceCache(C.source);if(!L)return void this.fire(new o.B(new Error(`Source "${C.source}" as specified by iconset "${g}" does not exist and cannot be used as an iconset source`)));const $=L.getSource();if($.type!=="raster-array")return void this.fire(new o.B(new Error(`Source "${C.source}" as specified by iconset "${g}" is not a "raster-array" source and cannot be used as an iconset source`)));$.partial=!1;const G=new Gb(g,this.scope,L);this.imageManager.addImageProvider(G,this.scope)}removeIconset(g){this.imageManager.removeImageProvider(g,this.scope)}_loadIconset(g){if(!o.e(g)&&this.map._spriteFormat!=="icon_set"||this.map._spriteFormat==="raster")return void this._loadSprite(g);const C=this.map._spriteFormat==="auto";var L,$;this._spriteRequest=($=(G,K)=>{if(this._spriteRequest=null,G)C?this._loadSprite(g):this.fire(new o.B(G));else if(K){const te=new Map;for(const de in K)te.set(o.I.from(de),K[de]);this.addImages(te)}this.imageManager.setLoaded(!0,this.scope),this.dispatcher.broadcast("spriteLoaded",{scope:this.scope,isLoaded:!0}),this.fire(new o.C("data",{dataType:"style"}))},o.b1((L=this.map._requestManager).transformRequest(L.normalizeIconsetURL(g),o.R.Iconset),(G,K)=>{if(G)return void $(G);const te={},de=o.c$(new o.a$(K));for(const xe of de.icons){const _e={version:1,pixelRatio:o.o.devicePixelRatio,content:Vd(xe),stretchX:xe.metadata?id(xe.metadata.stretch_x_areas):void 0,stretchY:xe.metadata?id(xe.metadata.stretch_y_areas):void 0,sdf:!1,usvg:!0,icon:xe};te[xe.name]=_e}$(null,te)}))}_validateLayer(g){const C=this.getOwnSource(g.source);if(!C)return;const L=g.sourceLayer;L&&(C.type==="geojson"||C.vectorLayerIds&&C.vectorLayerIds.indexOf(L)===-1)&&this.fire(new o.B(new Error(`Source layer "${L}" does not exist on source "${C.id}" as specified by style layer "${g.id}"`)))}loaded(){if(!this._loaded||Object.keys(this._changes.getUpdatedSourceCaches()).length)return!1;for(const g in this._sourceCaches)if(!this._sourceCaches[g].loaded())return!1;if(!this.imageManager.isLoaded()||this.imageManager.hasPatternsInFlight()||!this.modelManager.isLoaded()||this._styleColorTheme.lutLoading)return!1;for(const{style:g}of this.fragments)if(!g.loaded())return!1;return!0}_serializeImports(){if(this.stylesheet.imports)return this.stylesheet.imports.map((g,C)=>{const L=this.fragments[C];return L&&L.style&&(g.data=L.style.serialize()),g})}_serializeSources(){const g={};for(const C in this._sourceCaches){const L=this._sourceCaches[C].getSource();g[L.id]||(g[L.id]=L.serialize())}return g}_serializeLayers(g){const C=[];for(const L of g){const $=this._layers[L];$&&$.type!=="custom"&&C.push($.serialize())}return C}hasLightTransitions(){return!(!this.light||!this.light.hasTransition())||!(!this.ambientLight||!this.ambientLight.hasTransition())||!(!this.directionalLight||!this.directionalLight.hasTransition())}hasFogTransition(){return!!this.fog&&this.fog.hasTransition()}hasSnowTransition(){return!!this.snow&&this.snow.hasTransition()}hasRainTransition(){return!!this.rain&&this.rain.hasTransition()}hasTransitions(){if(this.hasLightTransitions()||this.hasFogTransition()||this.hasSnowTransition()||this.hasRainTransition())return!0;for(const g in this._sourceCaches)if(this._sourceCaches[g].hasTransition())return!0;for(const g in this._layers)if(this._layers[g].hasTransition())return!0;return!1}_updateDataDrivenEmissiveStrength(){for(const g in this._mergedLayers){const C=this._mergedLayers[g];if(C._transitionablePaint&&C._transitionablePaint._values){const L=C._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(g){return g?this.order:this._mergedOrder}isLayerDraped(g){return!!this.terrain&&g.isDraped(this.getLayerSourceCache(g))}_checkLoaded(){if(!this._loaded)throw new Error("Style is not done loading")}_checkLayer(g){const C=this.getOwnLayer(g);if(C)return C;this.fire(new o.B(new Error(`The layer '${g}' does not exist in the map's style.`)))}_checkSource(g){const C=this.getOwnSource(g);if(C)return C;this.fire(new o.B(new Error(`The source '${g}' does not exist in the map's style.`)))}precompilePrograms(g,C){const L=this.map.painter;if(L)for(let $=g.minzoom||0;$<(g.maxzoom||25.5);$++){const G=g.getProgramIds();if(G)for(const K of G){const te=g.getDefaultProgramParams(K,C.zoom,this._styleColorTheme.lut);te&&(L.style=this,this.fog&&(L._fogVisible=!0,te.overrideFog=!0,L.getOrCreateProgram(K,te)),L._fogVisible=!1,te.overrideFog=!1,L.getOrCreateProgram(K,te),(this.stylesheet.terrain||this.stylesheet.projection&&this.stylesheet.projection.name==="globe")&&(te.overrideRtt=!0,L.getOrCreateProgram(K,te)))}}}update(g){if(!this._loaded)return;this.ambientLight&&this.ambientLight.recalculate(g),this.directionalLight&&this.directionalLight.recalculate(g);const C=this.calculateLightsBrightness();g.brightness=C||0,C!==this._brightness&&(this._brightness=C,this.dispatcher.broadcast("setBrightness",C)),g.worldview!==this._worldview&&(this._worldview=g.worldview,this.dispatcher.broadcast("setWorldview",this._worldview));const L=this._changes.isDirty();let $=!1;if(this._changes.isDirty()){const de=this._changes.getLayerUpdatesByScope();for(const xe in de){const{updatedIds:_e,removedIds:Oe}=de[xe];(_e||Oe)&&(this._updateWorkerLayers(xe,_e,Oe),$=!0)}this.updateSourceCaches(),this._updateTilesForChangedImages(),this.updateLayers(g),this.light&&this.light.updateTransitions(g),this.ambientLight&&this.ambientLight.updateTransitions(g),this.directionalLight&&this.directionalLight.updateTransitions(g),this.fog&&this.fog.updateTransitions(g),this.snow&&this.snow.updateTransitions(g),this.rain&&this.rain.updateTransitions(g),this._changes.reset()}const G={};for(const de in this._mergedSourceCaches){const xe=this._mergedSourceCaches[de];G[de]=xe.used,xe.used=!1,xe.tileCoverLift=0}const K={};for(const de of this._mergedOrder){const xe=this._mergedLayers[de];if((xe.visibility!=="none"||xe.hasTransition())&&xe.recalculate(g,this._availableImages),!xe.isHidden(g.zoom)){const _e=this.getLayerSourceCache(xe);_e&&(_e.used=!0,_e.tileCoverLift=Math.max(_e.tileCoverLift,xe.tileCoverLift()))}if(xe.type==="fill-extrusion"){const _e=o.F(xe.source,xe.scope);if(_e in this._mergedFillExtrusionSourceCaches){const Oe=xe.layout&&xe.layout.get("source-max-zoom");if(Oe!=null){const De=K[_e];K[_e]=De==null?Oe:Math.min(De,Oe)}}}!this._precompileDone&&this._shouldPrecompile&&("requestIdleCallback"in window?requestIdleCallback(()=>{this.precompilePrograms(xe,g)}):this.precompilePrograms(xe,g))}this._shouldPrecompile&&(this._precompileDone=!0);for(const de in this._mergedFillExtrusionSourceCaches)this._mergedFillExtrusionSourceCaches[de].setMaxzoomOverride(K[de]!=null?K[de]:null);this.terrain&&$&&this.mergeLayers();const te=this.imageManager.getPendingImageProviders();for(const de of te)de.sourceCache.used=!0;for(const de in G){const xe=this._mergedSourceCaches[de];G[de]!==xe.used&&xe.getSource().fire(new o.C("data",{sourceDataType:"visibility",dataType:"source",sourceId:xe.getSource().id}))}this.light&&this.light.recalculate(g),this.terrain&&this.terrain.recalculate(g),this.fog&&this.fog.recalculate(g),this.snow&&this.snow.recalculate(g),this.rain&&this.rain.recalculate(g),this.z=g.zoom,this._markersNeedUpdate&&(this._updateMarkersOpacity(),this._markersNeedUpdate=!1),this.imageManager.clearUpdatedImages(this.scope),L&&this.fire(new o.C("data",{dataType:"style"}))}updateImageProviders(){const g=this.imageManager.getPendingImageProviders();for(const C of g){const L=C.resolvePendingRequests(),$=this.getFragmentStyle(C.scope);$&&$.addImages(L)}}_updateTilesForChangedImages(){const g={};for(const C in this._mergedSourceCaches){const L=this._mergedSourceCaches[C].getSource().scope;g[L]=g[L]||this._changes.getUpdatedImages(L),g[L].length!==0&&this._mergedSourceCaches[C].reloadTilesForDependencies(["icons","patterns"],g[L])}for(const C in g)this._changes.resetUpdatedImages(C)}_updateWorkerLayers(g,C,L){const $=this.getFragmentStyle(g);$&&this.dispatcher.broadcast("updateLayers",{layers:C?$._serializeLayers(C):[],scope:g,removedIds:L||[],options:$.options})}setState(g,C){if(this._checkLoaded(),a1(this,ir(g)))return!1;(g=o.d9(g)).layers=Cf(g.layers);const L=function(K,te){if(!K)return[{command:Ka.setStyle,args:[te]}];let de=[];try{if(!o.b6(K.version,te.version))return[{command:Ka.setStyle,args:[te]}];if(o.b6(K.center,te.center)||de.push({command:Ka.setCenter,args:[te.center]}),o.b6(K.zoom,te.zoom)||de.push({command:Ka.setZoom,args:[te.zoom]}),o.b6(K.bearing,te.bearing)||de.push({command:Ka.setBearing,args:[te.bearing]}),o.b6(K.pitch,te.pitch)||de.push({command:Ka.setPitch,args:[te.pitch]}),o.b6(K.sprite,te.sprite)||de.push({command:Ka.setSprite,args:[te.sprite]}),o.b6(K.glyphs,te.glyphs)||de.push({command:Ka.setGlyphs,args:[te.glyphs]}),o.b6(K.imports,te.imports)||function(qe=[],st=[],Xe){st=st||[];const pt=(qe=qe||[]).map(mx),mt=st.map(mx),kt=qe.reduce(lg,{}),Et=st.reduce(lg,{}),xt=pt.slice();let es,Ot,Qt,At;for(es=0,Ot=0;es{qe.source&&xe[qe.source]?de.push({command:Ka.removeLayer,args:[qe.id]}):Oe.push(qe)});let De=K.terrain;De&&xe[De.source]&&(de.push({command:Ka.setTerrain,args:[void 0]}),De=void 0),de=de.concat(_e),o.b6(De,te.terrain)||de.push({command:Ka.setTerrain,args:[te.terrain]}),function(qe,st,Xe){st=st||[];const pt=(qe=qe||[]).map(mx),mt=st.map(mx),kt=qe.reduce(lg,{}),Et=st.reduce(lg,{}),xt=pt.slice(),es=Object.create(null);let Ot,Qt,At,Dt,Ht,gs,ss;for(Ot=0,Qt=0;Ot!(K.command in AN));if(L.length===0)return!1;const $=L.filter(K=>!(K.command in Fh));if($.length>0)throw new Error(`Unimplemented: ${$.map(K=>K.command).join(", ")}.`);const G=[];return L.forEach(K=>{G.push(this[K.command](...K.args))}),C&&Promise.all(G).then(C).catch(C),this.stylesheet=g,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(g){if(g.size===0)return this;for(const[C,L]of g.entries()){if(this.getImage(C))return this.fire(new o.B(new Error(`An image with the name "${C.name}" already exists.`)));this.imageManager.addImage(C,this.scope,L),this._changes.updateImage(C,this.scope)}return this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this}addImage(g,C){return this.getImage(g)?this.fire(new o.B(new Error(`An image with the name "${g.name}" already exists.`))):(this.imageManager.addImage(g,this.scope,C),this._changes.updateImage(g,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})),this)}updateImage(g,C,L=!1){this.imageManager.updateImage(g,this.scope,C),L&&(this._changes.updateImage(g,this.scope),this._updateWorkerImages(),this.fire(new o.C("data",{dataType:"style"})))}getImage(g){return this.imageManager.getImage(g,this.scope)}removeImage(g){return this.getImage(g)?(this.imageManager.removeImage(g,this.scope),this._changes.updateImage(g,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(g){return this.modelManager.addModelURLs(g,this.getActualScope()),this._updateWorkerModels(),this.fire(new o.C("data",{dataType:"style"})),this}addModel(g,C,L={}){return this._checkLoaded(),this._validate(Vs,`models.${g}`,C,null,L)||(this.modelManager.addModel(g,C,this.getActualScope()),this.fire(new o.C("data",{dataType:"style"}))),this}hasModel(g){return this.modelManager.hasModel(g,this.getActualScope())}removeModel(g){return this.hasModel(g)?(this.modelManager.removeModel(g,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(g,C,L={}){if(this._checkLoaded(),this.getOwnSource(g)!==void 0)throw new Error(`There is already a source with ID "${g}".`);if(!C.type)throw new Error(`The type property must be defined, but only the following properties were given: ${Object.keys(C).join(", ")}.`);if(["vector","raster","geojson","video","image"].indexOf(C.type)>=0&&this._validate(Tr,`sources.${g}`,C,null,L))return;this.map&&this.map._collectResourceTiming&&(C.collectResourceTiming=!0);const $=Ay(g,C,this.dispatcher,this);$.scope=this.scope,$.setEventedParent(this,()=>({isSourceLoaded:this._isSourceCacheLoaded($.id),source:$.serialize(),sourceId:$.id}));const G=K=>{const te=(K===o.b4.Symbol?"symbol:":K===o.b4.FillExtrusion?"fill-extrusion:":"other:")+$.id,de=o.F(te,this.scope),xe=this._sourceCaches[te]=new sl(de,$,K);K===o.b4.Symbol?this._symbolSourceCaches[$.id]=xe:K===o.b4.FillExtrusion?this._fillExtrusionSourceCaches[$.id]=xe:this._otherSourceCaches[$.id]=xe,xe.onAdd(this.map)};G(o.b4.Other),C.type!=="vector"&&C.type!=="geojson"||(G(o.b4.Symbol),C.type==="vector"&&G(o.b4.FillExtrusion)),$.onAdd&&$.onAdd(this.map),L.isInitialLoad||(this.mergeSources(),this._changes.setDirty())}removeSource(g){this._checkLoaded();const C=this.getOwnSource(g);if(!C)throw new Error("There is no source with this ID");for(const $ in this._layers)if(this._layers[$].source===g)return this.fire(new o.B(new Error(`Source "${g}" cannot be removed while layer "${$}" is using it.`)));if(this.terrain&&this.terrain.scope===this.scope&&this.terrain.get().source===g)return this.fire(new o.B(new Error(`Source "${g}" cannot be removed while terrain is using it.`)));if(this.stylesheet.iconsets){const $=Object.entries(this.stylesheet.iconsets).find(([G,K])=>K.type==="source"&&K.source===g);if($)return this.fire(new o.B(new Error(`Source "${g}" cannot be removed while iconset "${$[0]}" is using it.`)))}const L=this.getOwnSourceCaches(g);for(const $ of L){const G=o.da($.id);delete this._sourceCaches[G],this._changes.discardSourceCacheUpdate($.id),$.fire(new o.C("data",{sourceDataType:"metadata",dataType:"source",sourceId:$.getSource().id})),$.setEventedParent(null),$.clearTiles()}return delete this._otherSourceCaches[g],delete this._symbolSourceCaches[g],delete this._fillExtrusionSourceCaches[g],this.mergeSources(),C.setEventedParent(null),C.onRemove&&C.onRemove(this.map),this._changes.setDirty(),this}setGeoJSONSourceData(g,C){this._checkLoaded(),this.getOwnSource(g).setData(C),this._changes.setDirty()}getOwnSource(g){const C=this.getOwnSourceCache(g);return C&&C.getSource()}getOwnSources(){const g=[];for(const C in this._otherSourceCaches){const L=this.getOwnSourceCache(C);L&&g.push(L.getSource())}return g}areTilesLoaded(){const g=this._mergedSourceCaches;for(const C in g){const L=g[C]._tiles;for(const $ in L){const G=L[$];if(G.state!=="loaded"&&G.state!=="errored")return!1}}return!0}setLights(g){if(this._checkLoaded(),!g)return delete this.ambientLight,void delete this.directionalLight;const C=this._getTransitionParameters();for(const G of g){if(this._validate(Fe,"lights",G))return;switch(G.type){case"ambient":if(this.ambientLight){const K=this.ambientLight;K.set(G),K.updateTransitions(C)}else this.ambientLight=new Nn(G,La(),this.scope,this.options);break;case"directional":if(this.directionalLight){const K=this.directionalLight;K.set(G),K.updateTransitions(C)}else this.directionalLight=new Nn(G,tl(),this.scope,this.options)}}const L=Object.assign(C,{worldview:this.map.getWorldview()}),$=new o.ae(this.z||0,L);this.ambientLight&&this.ambientLight.recalculate($),this.directionalLight&&this.directionalLight.recalculate($),this._brightness=this.calculateLightsBrightness(),this.dispatcher.broadcast("setBrightness",this._brightness)}calculateLightsBrightness(){const g=this.directionalLight,C=this.ambientLight;if(!g||!C)return;const L=De=>.2126*(De[0]<=.03928?De[0]/12.92:Math.pow((De[0]+.055)/1.055,2.4))+.7152*(De[1]<=.03928?De[1]/12.92:Math.pow((De[1]+.055)/1.055,2.4))+.0722*(De[2]<=.03928?De[2]/12.92:Math.pow((De[2]+.055)/1.055,2.4)),$=g.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),G=g.properties.get("intensity"),K=g.properties.get("direction"),te=1-o.cP(K.x,K.y,K.z)[2]/90,de=L($)*G*te,xe=C.properties.get("color").toNonPremultipliedRenderColor(null).toArray01(),_e=C.properties.get("intensity"),Oe=L(xe)*_e;return Number(((de+Oe)/2).toFixed(6))}getBrightness(){return this._brightness}getLights(){if(!this.enable3dLights())return null;const g=[];return this.directionalLight&&g.push(this.directionalLight.get()),this.ambientLight&&g.push(this.ambientLight.get()),g}enable3dLights(){return!!this.ambientLight&&!!this.directionalLight}getFragmentStyle(g){if(g==null||g===""&&this.isRootStyle())return this;if(o.db(g)){const C=o.dc(g),L=this.fragments.find(({id:G})=>G===C);if(!L)return;const $=o.da(g);return L.style.getFragmentStyle($)}{const C=this.fragments.find(({id:L})=>L===g);return C?C.style:void 0}}setFeaturesetSelectors(g){if(!g)return;const C=(L,$="")=>`${L}::${$}`;this._featuresetSelectors={};for(const L in g){const $={},G=this._featuresetSelectors[L]=[];for(const K of g[L].selectors){if(K.featureNamespace){const de=this.getOwnLayer(K.layer);if(!de){o.w(`Layer is undefined for selector: ${K.layer}`);continue}const xe=C(de.source,de.sourceLayer);if(xe in $&&$[xe]!==K.featureNamespace){o.w(`"featureNamespace ${K.featureNamespace} of featureset ${L}'s selector is not associated to the same source, skip this selector`);continue}$[xe]=K.featureNamespace}let te;if(K.properties)for(const de in K.properties){const xe=o.X(K.properties[de]);xe.result==="success"&&(te=te||{},te[de]=xe.value)}G.push({layerId:K.layer,namespace:K.featureNamespace,properties:te,uniqueFeatureID:K._uniqueFeatureID})}}}getFeaturesetDescriptors(g){const C=this.getFragmentStyle(g);if(!C||!C.stylesheet.featuresets)return[];const L=[];for(const $ in C.stylesheet.featuresets)L.push({featuresetId:$,importId:C.scope?C.scope:void 0});return L}getFeaturesetLayers(g,C){const L=this.getFragmentStyle(C),$=L.stylesheet.featuresets;if(!$||!$[g])return this.fire(new o.B(new Error(`The featureset '${g}' does not exist in the map's style and cannot be queried.`))),[];const G=[];for(const K of $[g].selectors){const te=L.getOwnLayer(K.layer);te&&G.push(te)}return G}getConfigProperty(g,C){const L=this.getFragmentStyle(g);if(!L)return null;const $=o.F(C,L.scope),G=L.options.get($),K=G?G.value||G.default:null;return K?K.serialize():null}isIndoorEnabled(){return Object.keys(this._mergedIndoor).length>0}getIndoorSourceLayers(g,C){const L=o.F(g,C);return this._mergedIndoor[L]}setIndoorData(g,C){this.indoorManager.setIndoorData(C)}updateIndoorDependentLayers(){this._updateLayers(this._indoorDependentLayers),this.map._styleDirty=!0,this.map.triggerRepaint()}setConfigProperty(g,C,L){const $=this.getFragmentStyle(g);if(!$)return;const G=$.stylesheet.schema;if(!G||!G[C])return;const K=o.X(L);if(K.result!=="success")return void a1(this,K.value);const te=K.value.expression,de=o.F(C,$.scope),xe=$.options.get(de);if(!xe)return;let _e;const{minValue:Oe,maxValue:De,stepValue:qe,type:st,values:Xe}=G[C],pt=o.X(G[C].default);pt.result==="success"&&(_e=pt.value.expression),_e?(this.options.set(de,Object.assign({},xe,{value:te,default:_e,minValue:Oe,maxValue:De,stepValue:qe,type:st,values:Xe})),this.updateConfigDependencies(C)):this.fire(new o.B(new Error(`No schema defined for the config option "${C}" in the "${g}" fragment.`)))}getConfig(g){const C=this.getFragmentStyle(g);if(!C)return null;const L=C.stylesheet.schema;if(!L)return null;const $={};for(const G in L){const K=o.F(G,C.scope),te=C.options.get(K),de=te?te.value||te.default:null;$[G]=de?de.serialize():null}return $}setConfig(g,C){const L=this.getFragmentStyle(g);L&&(L.updateConfig(C,L.stylesheet.schema),this.updateConfigDependencies())}getSchema(g){const C=this.getFragmentStyle(g);return C?C.stylesheet.schema:null}setSchema(g,C){const L=this.getFragmentStyle(g);L&&(L.stylesheet.schema=C,L.updateConfig(L._config,C),this.updateConfigDependencies())}updateConfig(g,C){if(this._config=g,g||C)if(C)for(const L in C){let $,G;const K=o.X(C[L].default);if(K.result==="success"&&($=K.value.expression),g&&g[L]!==void 0){const De=o.X(g[L]);De.result==="success"&&(G=De.value.expression)}const{minValue:te,maxValue:de,stepValue:xe,type:_e,values:Oe}=C[L];if($){const De=o.F(L,this.scope);this.options.set(De,{default:$,value:G,minValue:te,maxValue:de,stepValue:xe,type:_e,values:Oe})}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(g,C=()=>!0){for(const L of g){const $=this.getLayer(L);$&&C($)&&($.possiblyEvaluateVisibility(),this._updateLayer($),this._changes.setDirty())}}updateConfigDependencies(g){this._updateLayers(this._configDependentLayers,C=>!g||C.expressionDependencies.configDependencies.has(g)),this.ambientLight&&this.ambientLight.updateConfig(this.options),this.directionalLight&&this.directionalLight.updateConfig(this.options),this.fog&&this.fog.updateConfig(this.options),this.snow&&this.snow.updateConfig(this.options),this.rain&&this.rain.updateConfig(this.options),this.forEachFragmentStyle(C=>{const L=C._styleColorTheme.colorThemeOverride?C._styleColorTheme.colorThemeOverride:C._styleColorTheme.colorTheme;if(L){const $=C._evaluateColorThemeData(L);(!C._styleColorTheme.lut&&$!==""||C._styleColorTheme.lut&&$!==C._styleColorTheme.lut.data)&&C.setColorTheme(L)}}),this._changes.setDirty()}addLayer(g,C,L={}){this._checkLoaded();const $=g.id;if(this._layers[$])return void this.fire(new o.B(new Error(`Layer with id "${$}" already exists on this map`)));let G;if(g.type==="custom"){if(a1(this,o.dd(g)))return;G=o.de(g,this.scope,this._styleColorTheme.lut,this.options)}else{if(typeof g.source=="object"&&(this.addSource($,g.source),g=o.d9(g),g=Object.assign(g,{source:$})),this._validate(Vt,`layers.${$}`,g,{arrayIndex:-1},L))return;G=o.de(g,this.scope,this._styleColorTheme.lut,this.options),this._validateLayer(G),G.setEventedParent(this,{layer:{id:$}})}const K=o.F(G.source,G.scope);G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(K),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(K);let te=this._order.length;if(C){const Oe=this._order.indexOf(C);if(Oe===-1)return void this.fire(new o.B(new Error(`Layer with id "${C}" does not exist on this map.`)));G.slot&&G.slot!==this._layers[C].slot?o.w(`Layer with id "${C}" has a different slot. Layers can only be rearranged within the same slot.`):te=Oe}this._order.splice(te,0,$),this._handleLayerOrderChange(),this._layers[$]=G;const de=this.getOwnLayerSourceCache(G),xe=!!this.directionalLight&&this.directionalLight.shadowsEnabled();de&&G.canCastShadows()&&xe&&(de.castsShadows=!0);const _e=this._changes.getRemovedLayer(G);if(_e&&G.source&&de&&G.type!=="custom"){this._changes.discardLayerRemoval(G);const Oe=o.F(G.source,G.scope);_e.type!==G.type?this._changes.updateSourceCache(Oe,"clear"):(this._changes.updateSourceCache(Oe,"reload"),de.pause())}this._updateLayer(G),G.onAdd&&G.onAdd(this.map),G.scope=this.scope,this.mergeLayers()}moveLayer(g,C){this._checkLoaded();const L=this._checkLayer(g);if(!L||g===C)return;const $=this._order.indexOf(g);this._order.splice($,1);let G=this._order.length;if(C){const K=this._order.indexOf(C);if(K===-1)return void this.fire(new o.B(new Error(`Layer with id "${C}" does not exist on this map.`)));L.slot&&L.slot!==this._layers[C].slot?o.w(`Layer with id "${C}" has a different slot. Layers can only be rearranged within the same slot.`):G=K}this._order.splice(G,0,g),this._changes.setDirty(),this._handleLayerOrderChange(),this.mergeLayers()}removeLayer(g){this._checkLoaded();const C=this._checkLayer(g);if(!C)return;C.setEventedParent(null);const L=this._order.indexOf(g);this._order.splice(L,1),delete this._layers[g],this._changes.setDirty(),this._handleLayerOrderChange(),this._configDependentLayers.delete(C.fqid),this._indoorDependentLayers.delete(C.fqid),this._changes.removeLayer(C);const $=this.getOwnLayerSourceCache(C);if($&&$.castsShadows){let G=!1;for(const K in this._layers)if(this._layers[K].source===C.source&&this._layers[K].canCastShadows()){G=!0;break}$.castsShadows=G}C.onRemove&&C.onRemove(this.map),this.mergeLayers()}getOwnLayer(g){return this._layers[g]}hasLayer(g){return g in this._mergedLayers}hasLayerType(g){for(const C in this._layers)if(this._layers[C].type===g)return!0;return!1}setLayerZoomRange(g,C,L){this._checkLoaded();const $=this._checkLayer(g);$&&($.minzoom===C&&$.maxzoom===L||(C!=null&&($.minzoom=C),L!=null&&($.maxzoom=L),this._updateLayer($)))}getSlots(){return this._checkLoaded(),this._mergedSlots}setSlot(g,C){this._checkLoaded();const L=this._checkLayer(g);L&&L.slot!==C&&(L.slot=C,this._updateLayer(L))}setFilter(g,C,L={}){this._checkLoaded();const $=this._checkLayer(g);if($&&!o.b6($.filter,C))return C==null?($.filter=void 0,void this._updateLayer($)):void(this._validate(fs,`layers.${$.id}.filter`,C,{layerType:$.type},L)||($.filter=o.d9(C),this._updateLayer($)))}getFilter(g){const C=this._checkLayer(g);if(C)return o.d9(C.filter)}setLayoutProperty(g,C,L,$={}){this._checkLoaded();const G=this._checkLayer(g);if(G&&!o.b6(G.getLayoutProperty(C),L)){if(L!=null&&(!$||$.validate!==!1)&&a1(G,ns.call(ir,{key:`layers.${g}.layout.${C}`,layerType:G.type,objectKey:C,value:L,styleSpec:o.a8,style:{glyphs:!0,sprite:!0}})))return;G.setLayoutProperty(C,L),G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(G.fqid),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(G.fqid),this._updateLayer(G)}}setLayerProperty(g,C,L,$={}){this._checkLoaded();const G=this._checkLayer(g);G&&(C==="appearances"?(G.setAppearances(L),this._updateLayer(G)):G.isPaintProperty(C)?this.setPaintProperty(g,C,L,$):this.setLayoutProperty(g,C,L,$))}getLayoutProperty(g,C){const L=this._checkLayer(g);if(L)return L.getLayoutProperty(C)}setPaintProperty(g,C,L,$={}){this._checkLoaded();const G=this._checkLayer(g);if(!G||o.b6(G.getPaintProperty(C),L)||L!=null&&(!$||$.validate!==!1)&&a1(G,lt.call(ir,{key:`layers.${g}.paint.${C}`,layerType:G.type,objectKey:C,value:L,styleSpec:o.a8})))return;const K=G.setPaintProperty(C,L);G.expressionDependencies.configDependencies.size!==0&&this._configDependentLayers.add(G.fqid),G.expressionDependencies.isIndoorDependent&&this._indoorDependentLayers.add(G.fqid),K&&this._updateLayer(G),this._changes.updatePaintProperties(G)}getPaintProperty(g,C){const L=this._checkLayer(g);if(L)return L.getPaintProperty(C)}setFeatureState(g,C){if(this._checkLoaded(),"target"in g){if("featuresetId"in g.target){const{featuresetId:de,importId:xe}=g.target,_e=this.getFragmentStyle(xe),Oe=_e.getFeaturesetLayers(de);for(const{source:De,sourceLayer:qe}of Oe)_e.setFeatureState({id:g.id,source:De,sourceLayer:qe},C)}else if("layerId"in g.target){const{layerId:de}=g.target,xe=this.getLayer(de);this.setFeatureState({id:g.id,source:xe.source,sourceLayer:xe.sourceLayer},C)}return}const L=g.source,$=g.sourceLayer,G=this._checkSource(L);if(!G)return;const K=G.type;if(K==="geojson"&&$)return void this.fire(new o.B(new Error("GeoJSON sources cannot have a sourceLayer parameter.")));if(K==="vector"&&!$)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));g.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided.")));const te=this.getOwnSourceCaches(L);for(const de of te)de.setFeatureState($,g.id,C)}removeFeatureState(g,C){if(this._checkLoaded(),"target"in g){if("featuresetId"in g.target){const{featuresetId:de,importId:xe}=g.target,_e=this.getFragmentStyle(xe),Oe=_e.getFeaturesetLayers(de);for(const{source:De,sourceLayer:qe}of Oe)_e.removeFeatureState({id:g.id,source:De,sourceLayer:qe},C)}else if("layerId"in g.target){const{layerId:de}=g.target,xe=this.getLayer(de);this.removeFeatureState({id:g.id,source:xe.source,sourceLayer:xe.sourceLayer},C)}return}const L=g.source,$=this._checkSource(L);if(!$)return;const G=$.type,K=G==="vector"?g.sourceLayer:void 0;if(G==="vector"&&!K)return void this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")));if(C&&typeof g.id!="string"&&typeof g.id!="number")return void this.fire(new o.B(new Error("A feature id is required to remove its specific state property.")));const te=this.getOwnSourceCaches(L);for(const de of te)de.removeFeatureState(K,g.id,C)}getFeatureState(g){if(this._checkLoaded(),"target"in g){let G;if("featuresetId"in g.target){const{featuresetId:K,importId:te}=g.target,de=this.getFragmentStyle(te),xe=de.getFeaturesetLayers(K);for(const{source:_e,sourceLayer:Oe}of xe){const De=de.getFeatureState({id:g.id,source:_e,sourceLayer:Oe});if(De&&!G)G=De;else if(!o.b6(G,De))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 g.target){const{layerId:K}=g.target,te=this.getLayer(K);G=this.getFeatureState({id:g.id,source:te.source,sourceLayer:te.sourceLayer})}return G}const C=g.source,L=g.sourceLayer,$=this._checkSource(C);if($){if($.type!=="vector"||L)return g.id===void 0&&this.fire(new o.B(new Error("The feature id parameter must be provided."))),this.getOwnSourceCaches(C)[0].getFeatureState(L,g.id);this.fire(new o.B(new Error("The sourceLayer parameter must be provided for vector source types.")))}}setTransition(g){return this.stylesheet.transition=Object.assign({},this.stylesheet.transition,g),this.transition=this.stylesheet.transition,this}getTransition(){return Object.assign({},this.stylesheet.transition)}setWorldview(g){g!==this._worldview&&(this._worldview=g,this.dispatcher.broadcast("setWorldview",this._worldview),this.reloadSources())}serialize(){this._checkLoaded();const g=this.getTerrain(),C=g&&this.terrain&&this.terrain.scope===this.scope?g:this.stylesheet.terrain;return o.df({version:this.stylesheet.version,name:this.stylesheet.name,metadata:this.stylesheet.metadata,fragment:this.stylesheet.fragment,iconsets:this.stylesheet.iconsets,featuresets:this.stylesheet.featuresets,imports:this._serializeImports(),schema:this.stylesheet.schema,camera:this.stylesheet.camera,light:this.stylesheet.light,lights:this.stylesheet.lights,terrain:C,fog:this.stylesheet.fog,snow:this.stylesheet.snow,rain:this.stylesheet.rain,indoor:this.stylesheet.indoor,center:this.stylesheet.center,"color-theme":this.stylesheet["color-theme"],zoom:this.stylesheet.zoom,bearing:this.stylesheet.bearing,pitch:this.stylesheet.pitch,sprite:this.stylesheet.sprite,glyphs:this.stylesheet.glyphs,transition:this.stylesheet.transition,projection:this.stylesheet.projection,sources:this._serializeSources(),layers:this._serializeLayers(this._order)},L=>L!==void 0)}_updateFilteredLayers(g){for(const C of Object.values(this._mergedLayers))g(C)&&this._updateLayer(C)}_updateLayer(g){this._changes.updateLayer(g);const C=this.getLayerSourceCache(g),L=o.F(g.source,g.scope),$=this._changes.getUpdatedSourceCaches();g.source&&!$[L]&&C&&C.getSource().type!=="raster"&&(this._changes.updateSourceCache(L,"reload"),C.pause()),g.invalidateCompiledFilter()}_flattenAndSortRenderedFeatures(g){const C=te=>this._mergedLayers[te].is3D(!!this.terrain),L=this.order,$={},G=[];for(let te=L.length-1;te>=0;te--){const de=L[te];if(C(de)){$[de]=te;for(const xe of g){const _e=xe[de];if(_e)for(const Oe of _e)G.push(Oe)}}}G.sort((te,de)=>de.intersectionZ-te.intersectionZ);const K=[];for(let te=L.length-1;te>=0;te--){const de=L[te];if(C(de))for(let xe=G.length-1;xe>=0;xe--){const _e=G[xe].feature;if(_e.layer&&$[_e.layer.id]{if(dj.has(_e.type))return;const Oe=this.getOwnLayerSourceCache(_e),De=G[Oe.id]=G[Oe.id]||{sourceCache:Oe,layers:{},has3DLayers:!1};_e.is3D(!!this.terrain)&&(De.has3DLayers=!0),De.layers[_e.fqid]=De.layers[_e.fqid]||{styleLayer:_e,targets:[]},De.layers[_e.fqid].targets.push({filter:$})};if(C&&C.layers){if(!Array.isArray(C.layers))return this.fire(new o.B(new Error("parameters.layers must be an Array."))),[];for(const _e of C.layers){const Oe=this._layers[_e];if(!Oe)return this.fire(new o.B(new Error(`The layer '${_e}' does not exist in the map's style and cannot be queried for features.`))),[];K(Oe)}}else for(const _e in this._layers)K(this._layers[_e]);const te=this._queryRenderedFeatures(g,G,L),de=this._flattenAndSortRenderedFeatures(te),xe=[];for(const _e of de)o.dh(_e.layer.id)===this.scope&&xe.push(_e);return xe}queryRenderedFeatureset(g,C,L){let $;C&&!Array.isArray(C)&&C.filter&&(this._validate(fs,"queryRenderedFeatures.filter",C.filter,null,C),$=o.dg(C.filter));const G="mock",K=[];if(C&&C.target)K.push(Object.assign({},C,{targetId:G,filter:$}));else{const _e=this.getFeaturesetDescriptors();for(const Oe of _e)K.push({targetId:G,filter:$,target:Oe});for(const{style:Oe}of this.fragments){const De=Oe.getFeaturesetDescriptors();for(const qe of De)K.push({targetId:G,filter:$,target:qe})}}const te=this.queryRenderedTargets(g,K,L),de=[],xe=new Set;for(const _e of te)for(const Oe of _e.variants[G])mh(Oe,_e,xe)||de.push(new o.di(_e,Oe));return de}queryRenderedTargets(g,C,L){const $={},G=(te,de,xe,_e)=>{const Oe=$[de.id]=$[de.id]||{sourceCache:de,layers:{},has3DLayers:!1};if(Oe.layers[te.fqid]=Oe.layers[te.fqid]||{styleLayer:te,targets:[]},te.is3D(!!this.terrain)&&(Oe.has3DLayers=!0),!_e)return xe.uniqueFeatureID=!1,void Oe.layers[te.fqid].targets.push(xe);Oe.layers[te.fqid].targets.push(Object.assign({},xe,{namespace:_e.namespace,properties:_e.properties,uniqueFeatureID:_e.uniqueFeatureID}))};for(const te of C)if("featuresetId"in te.target){const{featuresetId:de,importId:xe}=te.target,_e=this.getFragmentStyle(xe);if(!_e||!_e._featuresetSelectors)continue;const Oe=_e._featuresetSelectors[de];if(!Oe){this.fire(new o.B(new Error(`The featureset '${de}' does not exist in the map's style and cannot be queried for features.`)));continue}for(const De of Oe){const qe=_e.getOwnLayer(De.layerId);qe&&!dj.has(qe.type)&&G(qe,_e.getOwnLayerSourceCache(qe),te,De)}}else if("layerId"in te.target){const{layerId:de}=te.target,xe=this.getLayer(de);if(!xe||dj.has(xe.type))continue;G(xe,this.getLayerSourceCache(xe),te)}const K=this._queryRenderedFeatures(g,$,L);return this._flattenAndSortRenderedFeatures(K)}_queryRenderedFeatures(g,C,L){const $=[],G=!!this.map._showQueryGeometry,K=jl.createFromScreenPoints(g,L);for(const te in C){const de=ux(K,C[te],this._availableImages,L,G,this.getActualScope());Object.keys(de).length&&$.push(de)}if(this.placement)for(const te in C){if(C[te].sourceCache._renderSourceType!==o.b4.Symbol)continue;const de=mo(K.screenGeometry,C[te],this._availableImages,this.placement.collisionIndex,this.placement.retainedQueryData,this.map.getWorldview());Object.keys(de).length&&$.push(de)}return $}querySourceFeatures(g,C){const L=C&&C.filter;L&&this._validate(fs,"querySourceFeatures.filter",L,null,C);let $=[];const G=this.getOwnSourceCaches(g);for(const K of G)$=$.concat(zb(K,C));return $}addSourceType(g,C,L){return Yc.getSourceType(g)?L(new Error(`A source type called "${g}" already exists.`)):(Yc.setSourceType(g,C),C.workerSourceURL?void this.dispatcher.broadcast("loadWorkerSource",{name:g,url:C.workerSourceURL},L):L(null,null))}getFlatLight(){return this.light.getLight()}setFlatLight(g,C,L={}){this._checkLoaded();const $=this.light.getLight();let G=!1;for(const te in g)if(!o.b6(g[te],$[te])){G=!0;break}if(!G)return;const K=this._getTransitionParameters();this.light.setLight(g,C,L),this.light.updateTransitions(K)}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(g,C=1){if(this._checkLoaded(),!g)return this.terrainSetForDrapingOnly()||(delete this.terrain,this.map.transform.projection.requiresDraping&&this.setTerrainForDraping()),C===0&&delete this.terrain,g===null?this.stylesheet.terrain=null:delete this.stylesheet.terrain,this._force3DLayerUpdate(),void(this._markersNeedUpdate=!0);this.checkCanvasFingerprintNoise();let L=g;const $=!("source"in g)||g.source==null;if(C===1){if(this.disableElevatedTerrain)return;if("source"in L&&typeof L.source=="object"){const te="terrain-dem-src";this.addSource(te,L.source),L=o.d9(L),L=Object.assign(L,{source:te})}const G=Object.assign({},L),K={};if(this.terrain&&$){G.source=this.terrain.get().source;const te=this.terrain?this.getFragmentStyle(this.terrain.scope):null;te&&(K.style=te.serialize())}if(this._validate(Qe,"terrain",G,K))return}if(!this.terrain||this.terrain.scope!==this.scope&&!$||this.terrain&&C!==this.terrain.drapeRenderMode){if(!L)return;this._createTerrain(L,C),this.fire(new o.C("data",{dataType:"style"}))}else{const G=this.terrain,K=G.get();for(const te of Object.keys(o.a8.terrain))!L.hasOwnProperty(te)&&o.a8.terrain[te].default&&(L[te]=o.a8.terrain[te].default);for(const te in g)if(!o.b6(g[te],K[te])){G.set(g,this.options),this.stylesheet.terrain=g;const de=this._getTransitionParameters({duration:0});G.updateTransitions(de),this.fire(new o.C("data",{dataType:"style"}));break}}this.mergeTerrain(),this.updateDrapeFirstLayers(),this._markersNeedUpdate=!0}_createFog(g){const C=this.fog=new qi(g,this.map.transform,this.scope,this.options);this.stylesheet.fog=C.get();const L=this._getTransitionParameters({duration:0});C.updateTransitions(L)}_createSnow(g){const C=this.snow=new Zi(g,this.map.transform,this.scope,this.options);this.stylesheet.snow=C.get();const L=this._getTransitionParameters({duration:0});C.updateTransitions(L)}_createRain(g){const C=this.rain=new aa(g,this.map.transform,this.scope,this.options);this.stylesheet.rain=C.get();const L=this._getTransitionParameters({duration:0});C.updateTransitions(L)}_updateMarkersOpacity(){this.map._markers.length!==0&&this.map._requestDomTask(()=>{for(const g of this.map._markers)g._evaluateOpacity()})}getFog(){return this.fog?this.fog.get():null}setFog(g){if(this._checkLoaded(),!g)return delete this.fog,delete this.stylesheet.fog,void(this._markersNeedUpdate=!0);if(this.fog){const C=this.fog;if(!o.b6(C.get(),g)){C.set(g,this.options),this.stylesheet.fog=C.get();const L=this._getTransitionParameters({duration:0});C.updateTransitions(L)}}else this._createFog(g);this._markersNeedUpdate=!0}getSnow(){return this.snow?this.snow.get():null}setSnow(g){if(this._checkLoaded(),!g)return delete this.snow,void delete this.stylesheet.snow;if(this.snow){const C=this.snow;if(!o.b6(C.get(),g)){C.set(g,this.options),this.stylesheet.snow=C.get();const L=this._getTransitionParameters({duration:0});C.updateTransitions(L)}}else this._createSnow(g);this._markersNeedUpdate=!0}getRain(){return this.rain?this.rain.get():null}setRain(g){if(this._checkLoaded(),!g)return delete this.rain,void delete this.stylesheet.rain;if(this.rain){const C=this.rain;if(!o.b6(C.get(),g)){C.set(g,this.options),this.stylesheet.rain=C.get();const L=this._getTransitionParameters({duration:0});C.updateTransitions(L)}}else this._createRain(g);this._markersNeedUpdate=!0}_reloadColorTheme(){const g=()=>{for(const $ in this._layers)this._layers[$].lut=this._styleColorTheme.lut;for(const $ in this._sourceCaches)this._sourceCaches[$].clearTiles()},C=this._styleColorTheme.colorThemeOverride?this._styleColorTheme.colorThemeOverride:this._styleColorTheme.colorTheme;if(!C)return this._styleColorTheme.lut=null,void g();const L=this._evaluateColorThemeData(C);this._loadColorTheme(L).then(()=>{this.fire(new o.C("colorthemeset")),g()}).catch($=>{o.w(`Couldn't set color theme: ${$}`)})}setColorTheme(g){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=g,this._reloadColorTheme()}setImportColorTheme(g,C){const L=this.getFragmentStyle(g);L&&(L._styleColorTheme.colorThemeOverride=C,L._reloadColorTheme())}_getTransitionParameters(g){return{now:o.o.now(),transition:Object.assign(this.transition,g)}}updateDrapeFirstLayers(){if(!this.terrain)return;const g=[],C=[];for(const L of this._mergedOrder)this.isLayerDraped(this._mergedLayers[L])?g.push(L):C.push(L);this._drapedFirstOrder=[],this._drapedFirstOrder.push(...g),this._drapedFirstOrder.push(...C)}_createTerrain(g,C){const L=this.terrain=new wr(g,C,this.scope,this.options,this.map.getWorldview());C===1&&(this.stylesheet.terrain=g),this.mergeTerrain(),this.updateDrapeFirstLayers(),this._force3DLayerUpdate();const $=this._getTransitionParameters({duration:0});L.updateTransitions($)}_force3DLayerUpdate(){for(const g in this._layers){const C=this._layers[g];C.type==="fill-extrusion"&&this._updateLayer(C)}}_forceSymbolLayerUpdate(){for(const g in this._layers){const C=this._layers[g];C.type==="symbol"&&this._updateLayer(C)}}_validate(g,C,L,$,G={}){if(G&&G.validate===!1)return!1;const K=Object.assign({},this.serialize());return a1(this,g.call(ir,Object.assign({key:C,style:K,value:L,styleSpec:o.a8},$)))}_remove(){this._request&&(this._request.cancel(),this._request=null),this._spriteRequest&&(this._spriteRequest.cancel(),this._spriteRequest=null),o.dj.off("pluginStateChange",this._rtlTextPluginCallback);for(const g in this._mergedLayers)this._mergedLayers[g].setEventedParent(null);for(const g in this._mergedSourceCaches)this._mergedSourceCaches[g].clearTiles(),this._mergedSourceCaches[g].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(g){const C=this.getSourceCaches(g);for(const L of C)L.clearTiles()}clearSources(){for(const g in this._mergedSourceCaches)this._mergedSourceCaches[g].clearTiles()}clearLayers(){for(const g in this._mergedLayers){const C=this._mergedLayers[g];C._clear&&C._clear()}}reloadSource(g){const C=this.getSourceCaches(g);for(const L of C)L.resume(),L.reload()}reloadSources(){for(const g of this.getSources())g.reload&&g.reload()}reloadModels(){this.modelManager.reloadModels(""),this.forEachFragmentStyle(g=>{g.modelManager.reloadModels(g.scope)})}updateSources(g){let C;this.directionalLight&&(C=EN(this.directionalLight));const L=new Set,$=new Set,G=new Set;for(const K in this._mergedLayers){const te=this._mergedLayers[K];te.type==="building"?L.add(te.source):te.type==="raster"&&te.paint&&te.paint.get("raster-elevation-reference")==="ground"&&G.add(te.source),te.hasElevation()&&!$.has(te.source)&&$.add(te.source)}for(const K in this._mergedSourceCaches){const te=this._mergedSourceCaches[K],de=$.has(te._source.id);te._isRasterElevatedOverTerrain=G.has(te._source.id),L.has(te._source.id)&&(te._source.reparseOverscaled=!1),te.update(g,void 0,void 0,C,de)}}_generateCollisionBoxes(){for(const g in this._sourceCaches){const C=this._sourceCaches[g];C.resume(),C.reload()}}_handleLayerOrderChange(){this._requestFullLabelPlacement(),this.fire(new o.C("neworder"))}_requestFullLabelPlacement(){this.pauseablePlacement||(this.pauseablePlacement=new Vb),this.pauseablePlacement.requestFullPlacement()}_setLabelPlacementStale(){this.placement&&this.placement.setStale()}_updatePlacement(g,C,L,$,G){this.pauseablePlacement||(this.pauseablePlacement=new Vb);let K=!1,te=!1;const de={},xe={};for(const Xe of this._mergedOrder){const pt=this._mergedLayers[Xe];if(pt.type!=="symbol")continue;const mt=o.F(pt.source,pt.scope);let kt=de[mt];if(!kt){const xt=this.getLayerSourceCache(pt);if(!xt)continue;const es=xt.getRenderableIds(!0).map(Ot=>xt.getTileByID(Ot));xe[mt]=es.slice(),kt=de[mt]=es.sort((Ot,Qt)=>Qt.tileID.overscaledZ-Ot.tileID.overscaledZ||(Ot.tileID.isLessThan(Qt.tileID)?-1:1))}const Et=this.crossTileSymbolIndex.addLayer(pt,kt,g.center.lng,g.projection);K=K||Et}this.crossTileSymbolIndex.pruneUnusedLayers(this._mergedOrder);const _e=!!(this.placement&&!g.equals(this.placement.transform)),Oe=!!(this.placement&&(this.placement.lastReplacementSourceUpdateTime!==0&&!G||this.placement.lastReplacementSourceUpdateTime!==G.updateTime)),De=_e||Oe||K,qe=(De||this.pauseablePlacement.isStale())&&L===0,st=this.pauseablePlacement.isDone()&&!this.placement.stillRecent(o.o.now(),g.zoom)&&L!==0;if((this.pauseablePlacement.isFullPlacementRequested()||!this.pauseablePlacement.placement||qe||st)&&(this.pauseablePlacement=this.pauseablePlacement.startNewPlacement(g,this._mergedOrder,C,L,$,this.placement,this.fog&&g.projection.supportsFog?this.fog.state:null,this._buildingIndex),this.map.painter)){const Xe=this.map.painter.maxFrontCutoffRawStart;if(Xe>0){const pt=180*g.pitch/Math.PI;if(pt>=15){const mt=Math.min(1,Math.max(0,(pt-15)/5)),kt=mt*mt*(3-2*mt);this.pauseablePlacement.placement.frontCutoffStart=-.5*(1-kt)+Xe*kt}}}if(this.pauseablePlacement.isDone()?De&&L!==0&&this.pauseablePlacement.setStale():(this.pauseablePlacement.continuePlacement(this._mergedOrder,this._mergedLayers,de,xe,this.map.painter.scaleFactor),this.pauseablePlacement.isDone()&&(this.placement=this.pauseablePlacement.commit(o.o.now()),te=!0),K&&this.pauseablePlacement.setStale()),te||K){this._buildingIndex.onNewFrame(g.zoom);for(let Xe=0;XeG===g.id)!==-1)return void this.fire(new o.B(new Error(`Import with id '${g.id}' already exists in the map's style.`)));if(!C)return L.push(g),this._loadImports([g],!0);const $=L.findIndex(({id:G})=>G===C);return $===-1&&this.fire(new o.B(new Error(`Import with id "${C}" does not exist on this map.`))),this.stylesheet.imports=L.slice(0,$).concat(g).concat(L.slice($)),this._loadImports([g],!0,C)}updateImport(g,C){this._checkLoaded();const L=this.stylesheet.imports||[],$=this.getImportIndex(g);return $===-1?this:typeof C=="string"?(this.setImportUrl(g,C),this):(C.url&&C.url!==L[$].url&&this.setImportUrl(g,C.url),o.b6(C.config,L[$].config)||this.setImportConfig(g,C.config,C.data.schema),o.b6(C.data,L[$].data)||this.setImportData(g,C.data),this)}moveImport(g,C){this._checkLoaded();let L=this.stylesheet.imports||[];const $=this.getImportIndex(g);if($===-1)return this;const G=this.getImportIndex(C);if(G===-1)return this;const K=L[$],te=this.fragments[$];return L=L.filter(({id:de})=>de!==g),this.fragments=this.fragments.filter(({id:de})=>de!==g),this.stylesheet.imports=L.slice(0,G).concat(K).concat(L.slice(G)),this.fragments=this.fragments.slice(0,G).concat(te).concat(this.fragments.slice(G)),this.mergeLayers(),this}setImportUrl(g,C){this._checkLoaded();const L=this.stylesheet.imports||[],$=this.getImportIndex(g);if($===-1)return this;L[$].url=C;const G=this.fragments[$];return G.style=this._createFragmentStyle(L[$]),G.style.on("style.import.load",()=>this.mergeAll()),G.style.loadURL(C),this}setImportData(g,C){this._checkLoaded();const L=this.getImportIndex(g),$=this.stylesheet.imports||[];return L===-1?this:C?(this.fragments[L].style.setState(C),this._reloadImports(),this):(delete $[L].data,this.setImportUrl(g,$[L].url))}setImportConfig(g,C,L){this._checkLoaded();const $=this.getImportIndex(g),G=this.stylesheet.imports||[];if($===-1)return this;C?G[$].config=C:delete G[$].config;const K=this.fragments[$];L&&K.style.stylesheet&&(K.style.stylesheet.schema=L);const te=K.style.stylesheet&&K.style.stylesheet.schema;return K.config=C,K.style.updateConfig(C,te),this.updateConfigDependencies(),this}removeImport(g){this._checkLoaded();const C=this.stylesheet.imports||[],L=this.getImportIndex(g);L!==-1&&(C.splice(L,1),this.fragments[L].style._remove(),this.fragments.splice(L,1),this._reloadImports())}getImportIndex(g){const C=(this.stylesheet.imports||[]).findIndex(L=>L.id===g);return C===-1&&this.fire(new o.B(new Error(`Import '${g}' does not exist in the map's style and cannot be updated.`))),C}getLayer(g){return this._mergedLayers[g]}getSources(){const g=[];for(const C in this._mergedOtherSourceCaches){const L=this._mergedOtherSourceCaches[C];L&&g.push(L.getSource())}return g}getSource(g,C){const L=this.getSourceCache(g,C);return L&&L.getSource()}getLayerSource(g){const C=this.getLayerSourceCache(g);return C&&C.getSource()}getSourceCache(g,C){const L=o.F(g,C);return this._mergedOtherSourceCaches[L]}getLayerSourceCache(g){const C=o.F(g.source,g.scope);return g.type==="symbol"?this._mergedSymbolSourceCaches[C]:g.type==="fill-extrusion"&&this._mergedFillExtrusionSourceCaches[C]||this._mergedOtherSourceCaches[C]}getSourceCaches(g){if(g==null)return Object.values(this._mergedSourceCaches);const C=[];return this._mergedOtherSourceCaches[g]&&C.push(this._mergedOtherSourceCaches[g]),this._mergedSymbolSourceCaches[g]&&C.push(this._mergedSymbolSourceCaches[g]),this._mergedFillExtrusionSourceCaches[g]&&C.push(this._mergedFillExtrusionSourceCaches[g]),C}updateSourceCaches(){const g=this._changes.getUpdatedSourceCaches();for(const C in g){const L=g[C];L==="reload"?this.reloadSource(C):L==="clear"&&this.clearSource(C)}}updateLayers(g){const C=this._changes.getUpdatedPaintProperties();for(const L of C){const $=this.getLayer(L);$&&$.updateTransitions(g)}}getGlyphsUrl(){return this.stylesheet.glyphs}setGlyphsUrl(g){this.stylesheet.glyphs=g,this.glyphManager.setURL(g)}getImages(g,C,L){this.imageManager.getImages(C.images,C.scope,L),this._updateTilesForChangedImages();const $=K=>{if(K){const te=C.images.map(de=>o.I.toString(de));K.setDependencies(C.tileID.key,C.type,te)}},G=o.F(C.source,C.scope);$(this._mergedOtherSourceCaches[G]),$(this._mergedSymbolSourceCaches[G]),C.images.some(K=>K.iconsetId)&&this.fire(new o.C("data",{dataType:"style"}))}rasterizeImages(g,C,L){this.imageManager.rasterizeImages(C,L)}checkAtlasCache(g,C,L){const $=this.imageManager.imageAtlasCache.findCachedAtlas(C.descriptor);L(null,$&&$.contentDescriptor?{iconPositions:$.iconPositions,patternPositions:$.patternPositions,sourceHash:$.contentDescriptor.hash}:null)}getGlyphs(g,C,L){this.glyphManager.getGlyphs(C.stacks,L)}getOwnSourceCache(g){return this._otherSourceCaches[g]}getOwnLayerSourceCache(g){return g.type==="symbol"?this._symbolSourceCaches[g.source]:g.type==="fill-extrusion"&&this._fillExtrusionSourceCaches[g.source]||this._otherSourceCaches[g.source]}getOwnSourceCaches(g){const C=[];return this._otherSourceCaches[g]&&C.push(this._otherSourceCaches[g]),this._symbolSourceCaches[g]&&C.push(this._symbolSourceCaches[g]),this._fillExtrusionSourceCaches[g]&&C.push(this._fillExtrusionSourceCaches[g]),C}_isSourceCacheLoaded(g){const C=this.getOwnSourceCaches(g);return C.length===0?(this.fire(new o.B(new Error(`There is no source with ID '${g}'`))),!1):C.every(L=>L.loaded())}has3DLayers(){return this._has3DLayers}hasSymbolLayers(){return this._hasSymbolLayers}hasCircleLayers(){return this._hasCircleLayers}isLayerClipped(g,C){if(!this._clipLayerPresent&&g.type!=="fill-extrusion"&&g.type!=="building")return!1;const L=g.type==="fill-extrusion"&&(g.sourceLayer==="building"||g.sourceLayer==="procedural_buildings"),$=g.type==="building";if(g.is3D(!!this.terrain)){if(L||$||C&&C.type==="batched-model"||g.type==="model")return!0}else if(g.type==="symbol")return!0;return!1}_clearWorkerCaches(){this.dispatcher.broadcast("clearCaches")}getBOMObject(){}destroy(){this._clearWorkerCaches(),this.imageManager.imageAtlasCache.clear(),this.fragments.forEach(g=>{g.style._remove()}),this.terrainSetForDrapingOnly()&&(delete this.terrain,delete this.stylesheet.terrain)}}Yc.getSourceType=function(M){return Ey[M]},Yc.setSourceType=function(M,g){Ey[M]=g},Yc.registerForPluginStateChange=o.dk;var i1=` #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`,uj=` #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;}`,dg=` #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`,Kb="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;}",MN=` #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`,IN=`#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`,o1=`#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`,l1=`#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`,PN=`#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;}`,hj=`#ifdef RENDER_SHADOWS uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_normal_offset;vec3 shadow_normal_offset(vec3 normal) {float tileInMeters=u_shadow_normal_offset[0];vec3 n=vec3(-normal.xy,tileInMeters*normal.z);float dotScale=min(1.0-dot(normal,u_shadow_direction),1.0)*0.5+0.5;return n*dotScale;}vec3 shadow_normal_offset_model(vec3 normal) {vec3 transformed_normal=vec3(-normal.xy,normal.z);float NDotL=dot(normalize(transformed_normal),u_shadow_direction);float dotScale=min(1.0-NDotL,1.0)*0.5+0.5;return normal*dotScale;}float shadow_normal_offset_multiplier0() {return u_shadow_normal_offset[1];}float shadow_normal_offset_multiplier1() {return u_shadow_normal_offset[2];} #endif`,np=`#ifdef RENDER_SHADOWS precision highp sampler2DShadow;uniform sampler2DShadow u_shadowmap_0;uniform sampler2DShadow u_shadowmap_1;uniform float u_shadow_intensity;uniform float u_shadow_map_resolution;uniform float u_shadow_texel_size;uniform highp vec3 u_shadow_normal_offset;uniform vec2 u_fade_range;uniform mediump vec3 u_shadow_direction;uniform highp vec3 u_shadow_bias;float shadow_sample(sampler2DShadow shadowmap,highp vec3 pos,highp float bias) { #ifdef CLIP_ZERO_TO_ONE highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z-bias); #else highp vec3 coord=vec3(pos.xy*0.5+0.5,pos.z*0.5+0.5-bias); #endif return texture(shadowmap,coord);}float shadow_occlusion(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,highp float bias) {light_view_pos0.xyz/=light_view_pos0.w; #ifdef SHADOWS_SINGLE_CASCADE vec2 abs_bounds=abs(light_view_pos0.xy);if (abs_bounds.x >=1.0 || abs_bounds.y >=1.0) {return 0.0;}return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias); #else light_view_pos1.xyz/=light_view_pos1.w;vec4 abs_bounds=abs(vec4(light_view_pos0.xy,light_view_pos1.xy));if (abs_bounds.x < 1.0 && abs_bounds.y < 1.0) {return shadow_sample(u_shadowmap_0,light_view_pos0.xyz,bias);}if (abs_bounds.z >=1.0 || abs_bounds.w >=1.0) {return 0.0;}float occlusion1=shadow_sample(u_shadowmap_1,light_view_pos1.xyz,bias);return clamp(mix(occlusion1,0.0,smoothstep(u_fade_range.x,u_fade_range.y,view_depth)),0.0,1.0); #endif }highp float calculate_shadow_bias(float NDotL) { #ifdef NORMAL_OFFSET return 0.5*u_shadow_bias.x; #else return 0.5*(u_shadow_bias.x+clamp(u_shadow_bias.y*tan(acos(NDotL)),0.0,u_shadow_bias.z)); #endif }float shadowed_light_factor_normal(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_opacity(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth,float shadow_opacity) {float NDotL=dot(N,u_shadow_direction);float bias=calculate_shadow_bias(NDotL);float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias)*shadow_opacity;return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}float shadowed_light_factor_normal_unbiased(vec3 N,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float NDotL=dot(N,u_shadow_direction);float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return mix(0.0,(1.0-(u_shadow_intensity*occlusion))*NDotL,step(0.0,NDotL));}highp vec2 compute_receiver_plane_depth_bias(highp vec3 pos_dx,highp vec3 pos_dy) {highp vec2 biasUV=vec2( pos_dy.y*pos_dx.z-pos_dx.y*pos_dy.z,pos_dx.x*pos_dy.z-pos_dy.x*pos_dx.z);biasUV*=1.0/((pos_dx.x*pos_dy.y)-(pos_dx.y*pos_dy.x));return biasUV;}float shadowed_light_factor_plane_bias(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {highp vec3 light_view_pos0_xyz=light_view_pos0.xyz/light_view_pos0.w*0.5+0.5;highp vec3 light_view_pos0_ddx=dFdx(light_view_pos0_xyz);highp vec3 light_view_pos0_ddy=dFdy(light_view_pos0_xyz);highp vec2 plane_depth_bias=compute_receiver_plane_depth_bias(light_view_pos0_ddx,light_view_pos0_ddy);highp float bias=dot(vec2(u_shadow_texel_size,u_shadow_texel_size),plane_depth_bias)+0.0001;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadowed_light_factor(highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=0.0;float occlusion=shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);return 1.0-(u_shadow_intensity*occlusion);}float shadow_occlusion(float ndotl,highp vec4 light_view_pos0,highp vec4 light_view_pos1,float view_depth) {float bias=calculate_shadow_bias(ndotl);return shadow_occlusion(light_view_pos0,light_view_pos1,view_depth,bias);} #endif`;const u0=/#include\s+"([^"]+)"/g,Bn=/#pragma mapbox: ([\w\-]+) ([\w]+) ([\w]+) ([\w]+)/g,mj=/\b[A-Za-z_][A-Za-z0-9_]*\b/g,pj=new Set(["ifdef","ifndef","elif","if","defined"]),Fy=new Set;ug(i1,Fy),ug(dg,Fy),ug(uj,Fy);const Fp={"_prelude_fog.vertex.glsl":IN,"_prelude_terrain.vertex.glsl":MN,"_prelude_shadow.vertex.glsl":hj,"_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":o1,"_prelude_shadow.fragment.glsl":np,"_prelude_lighting.glsl":` #ifdef LIGHTING_3D_MODE uniform mediump vec3 u_lighting_ambient_color;uniform mediump vec3 u_lighting_directional_dir;uniform mediump vec3 u_lighting_directional_color;uniform mediump vec3 u_ground_radiance;float calculate_ambient_directional_factor(vec3 normal) {float NdotL=dot(normal,u_lighting_directional_dir);const float factor_reduction_max=0.3;float dir_luminance=dot(u_lighting_directional_color,vec3(0.2126,0.7152,0.0722));float directional_factor_min=1.0-factor_reduction_max*min(dir_luminance,1.0);float ambient_directional_factor=mix(directional_factor_min,1.0,min((NdotL+1.0),1.0));const float vertical_factor_min=0.92;float vertical_factor=mix(vertical_factor_min,1.0,normal.z*0.5+0.5);return vertical_factor*ambient_directional_factor;}vec3 linearProduct(vec3 srgbIn,vec3 k) {return srgbIn*pow(k,vec3(1./2.2));}vec3 apply_lighting(vec3 color,vec3 normal,float dir_factor) {float ambient_directional_factor=calculate_ambient_directional_factor(normal);vec3 ambient_contrib=ambient_directional_factor*u_lighting_ambient_color;vec3 directional_contrib=u_lighting_directional_color*dir_factor;return linearProduct(color,ambient_contrib+directional_contrib);}vec4 apply_lighting(vec4 color,vec3 normal,float dir_factor) {return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting(vec3 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return apply_lighting(color.rgb,normal,dir_factor);}vec4 apply_lighting(vec4 color,vec3 normal) {float dir_factor=max(dot(normal,u_lighting_directional_dir),0.0);return vec4(apply_lighting(color.rgb,normal,dir_factor),color.a);}vec3 apply_lighting_ground(vec3 color) {return color*u_ground_radiance;}vec4 apply_lighting_ground(vec4 color) {return vec4(apply_lighting_ground(color.rgb),color.a);}float calculate_NdotL(vec3 normal) {const float ext=0.70710678118;return (clamp(dot(normal,u_lighting_directional_dir),-ext,1.0)+ext)/(1.0+ext);}vec4 apply_lighting_with_emission_ground(vec4 color,float emissive_strength) {return mix(apply_lighting_ground(color),color,emissive_strength);}vec3 compute_flood_lighting(vec3 flood_light_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=flood_light_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);float occlusion_ramp=smoothstep(0.0,0.2,1.0-occlusion);return mix(fully_occluded_color,flood_light_color,occlusion_ramp);}vec3 compute_emissive_draped(vec3 unlit_color,float fully_occluded_factor,float occlusion,vec3 ground_shadow_factor) {vec3 fully_occluded_color=unlit_color*mix(ground_shadow_factor,vec3(1.0),fully_occluded_factor);return mix(fully_occluded_color,unlit_color,1.0-occlusion);} #endif`,"_prelude_raster_array.glsl":l1,"_prelude_raster_particle.glsl":PN},c1={};pi("",MN),pi(o1,IN),pi(np,hj),pi(l1,""),pi(PN,"");const h0=pi(uj,dg),Yb=i1,d1=[` #if defined(GL_EXT_blend_func_extended) && defined(DUAL_SOURCE_BLENDING) #extension GL_EXT_blend_func_extended : require #endif`,"precision mediump float;",Yb,h0.fragmentSource].join(` `),cC=["precision highp float;",Yb,h0.vertexSource].join(` `);var dC={background:pi(`#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:pi(`#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:pi(`#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:pi(`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:pi("void main() {}","in vec3 a_pos_3f;uniform mat4 u_matrix;void main() {gl_Position=u_matrix*vec4(a_pos_3f,1.0);}"),circle:pi(`#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:pi("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:pi(`#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:pi(`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:pi("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:pi("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:pi("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:pi("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:pi(`#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:pi(`#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:pi(`#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:pi(`#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:pi(`#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:pi(`#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:pi(`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:pi(`#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:pi("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:pi(`#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:pi(`#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:pi(`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:pi(`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:pi(`#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:pi(`#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:pi(`#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:pi(`#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:pi(`#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:pi("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:pi("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:pi(`#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:pi(`#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:pi(`#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:pi("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:pi(`#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 }`,Kb),skyboxGradient:pi(`#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 }`,Kb),skyboxCapture:pi(` 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:pi(`#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:pi(`#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:pi(`#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:pi("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:pi(`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:pi("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:pi("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:pi("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:pi("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 ug(M,g){const C=M.split(` `);for(let L of C){if(L=L.trimStart(),L[0]!=="#"||!L.includes("if")||L.startsWith("#endif"))continue;const $=L.match(mj);if($)for(const G of $)pj.has(G)||g.add(G)}}function uC(M){return new Set(["uint","int","uvec2","ivec2","uvec3","ivec3","uvec4","ivec4"]).has(M)}function pi(M,g){const C=new Set,L=[],$=[];M=M.replace(u0,(K,te)=>($.push(te),"")),g=g.replace(u0,(K,te)=>(L.push(te),""));let G=new Set(Fy);ug(M,G),ug(g,G);for(const K of[...L,...$])c1[K]||(c1[K]=new Set,ug(Fp[K],c1[K])),G=new Set([...G,...c1[K]]);return{fragmentSource:M=M.replace(Bn,(K,te,de,xe,_e)=>(C.add(_e),te==="define"?` #ifndef HAS_UNIFORM_u_${_e} ${uC(xe)?"flat ":""}in ${de} ${xe} ${_e}; #else uniform ${de} ${xe} u_${_e}; #endif `:te==="initialize"?` #ifdef HAS_UNIFORM_u_${_e} ${de} ${xe} ${_e} = u_${_e}; #endif `:te==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${_e} in ${de} ${xe} ${_e}; #endif `:te==="initialize-attribute"?"":void 0)),vertexSource:g=g.replace(Bn,(K,te,de,xe,_e)=>{const Oe=`MATERIAL_ATTRIBUTE_OFFSET_${_e}`,De=xe==="float"?"vec2":xe,qe=`GET_ATTRIBUTE_${De}(a_${_e}, materialInfo, ${Oe})`,st=_e.match(/color/)?"color":De;return te==="define-attribute-vertex-shader-only"?` #ifdef HAS_ATTRIBUTE_a_${_e} in ${de} ${xe} a_${_e}; #endif `:C.has(_e)?te==="define"?` #ifndef HAS_UNIFORM_u_${_e} uniform lowp float u_${_e}_t; #if !defined(${Oe}) in ${de} ${De} a_${_e}; #endif ${uC(xe)?"flat ":""}out ${de} ${xe} ${_e}; #else uniform ${de} ${xe} u_${_e}; #endif `:te==="initialize"?st==="vec4"||st==="uvec4"?` #ifndef HAS_UNIFORM_u_${_e} ${_e} = a_${_e}; #else ${de} ${xe} ${_e} = u_${_e}; #endif `:` #if !defined(HAS_UNIFORM_u_${_e}) #ifdef ${Oe} ${_e} = unpack_mix_${st}(${qe}, u_${_e}_t); #else ${_e} = unpack_mix_${st}(a_${_e}, u_${_e}_t); #endif #else ${de} ${xe} ${_e} = u_${_e}; #endif `:te==="define-attribute"?` #ifdef HAS_ATTRIBUTE_a_${_e} in ${de} ${xe} a_${_e}; out ${de} ${xe} ${_e}; #endif `:te==="initialize-attribute"?` #ifdef HAS_ATTRIBUTE_a_${_e} ${_e} = a_${_e}; #endif `:void 0:te==="define"?` #ifndef HAS_UNIFORM_u_${_e} uniform lowp float u_${_e}_t; #if !defined(${Oe}) in ${de} ${De} a_${_e}; #endif #else uniform ${de} ${xe} u_${_e}; #endif `:te==="define-instanced"?st==="mat4"?` #ifdef INSTANCED_ARRAYS in vec4 a_${_e}0; in vec4 a_${_e}1; in vec4 a_${_e}2; in vec4 a_${_e}3; #else uniform ${de} ${xe} u_${_e}; #endif `:` #ifdef INSTANCED_ARRAYS in ${de} ${De} a_${_e}; #else uniform ${de} ${xe} u_${_e}; #endif `:te==="initialize-attribute-custom"?` #ifdef HAS_ATTRIBUTE_a_${_e} ${de} ${xe} ${_e} = a_${_e}; #endif `:st==="vec4"||st==="uvec4"?` #ifndef HAS_UNIFORM_u_${_e} #ifdef ${Oe} ${de} ${xe} ${_e} = ${qe}; #else ${de} ${xe} ${_e} = a_${_e}; #endif #else ${de} ${xe} ${_e} = u_${_e}; #endif `:` #ifndef HAS_UNIFORM_u_${_e} #ifdef ${Oe} ${de} ${xe} ${_e} = unpack_mix_${st}(${qe}, u_${_e}_t); #else ${de} ${xe} ${_e} = unpack_mix_${st}(a_${_e}, u_${_e}_t); #endif #else ${de} ${xe} ${_e} = u_${_e}; #endif `}),usedDefines:G,vertexIncludes:L,fragmentIncludes:$}}class hC{constructor(){this.boundProgram=null,this.boundLayoutVertexBuffer=null,this.boundPaintVertexBuffers=[],this.boundIndexBuffer=null,this.boundVertexOffset=null,this.boundDynamicVertexBuffers=[],this.vao=null}bind(g,C,L,$,G,K,te,de){this.context=g;let xe=this.boundPaintVertexBuffers.length!==$.length;for(let Oe=0;!xe&&Oe<$.length;Oe++)this.boundPaintVertexBuffers[Oe]!==$[Oe]&&(xe=!0);let _e=this.boundDynamicVertexBuffers.length!==te.length;for(let Oe=0;!_e&&Oe{const es=Et.paint.get("hillshade-shadow-color"),Ot=Et.paint.get("hillshade-shadow-color-use-theme").constantOr("default")==="none",Qt=Et.paint.get("hillshade-highlight-color"),At=Et.paint.get("hillshade-highlight-color-use-theme").constantOr("default")==="none",Dt=Et.paint.get("hillshade-accent-color"),Ht=Et.paint.get("hillshade-accent-color-use-theme").constantOr("default")==="none",gs=Et.paint.get("hillshade-emissive-strength");let ss=o.ap(Et.paint.get("hillshade-illumination-direction"));if(Et.paint.get("hillshade-illumination-anchor")==="viewport")ss-=mt.transform.angle;else if(mt.style&&mt.style.enable3dLights()&&mt.style.directionalLight){const Ps=mt.style.directionalLight.properties.get("direction"),rn=o.cP(Ps.x,Ps.y,Ps.z);ss=o.ap(rn[1])}const Bs=!mt.options.moving;return{u_matrix:xt||mt.transform.calculateProjMatrix(kt.tileID.toUnwrapped(),Bs),u_image:0,u_latrange:mC(0,kt.tileID),u_light:[Et.paint.get("hillshade-exaggeration"),ss],u_shadow:es.toPremultipliedRenderColor(Ot?null:Et.lut),u_highlight:Qt.toPremultipliedRenderColor(At?null:Et.lut),u_emissive_strength:gs,u_accent:Dt.toPremultipliedRenderColor(Ht?null:Et.lut)}})(M,C,L,M.terrain?g.projMatrix:null);M.uploadCommonUniforms(te,De,g.toUnwrapped());const{tileBoundsBuffer:st,tileBoundsIndexBuffer:Xe,tileBoundsSegments:pt}=M.getTileBoundsBuffers(C);De.draw(M,de.TRIANGLES,$,G,K,Pr.disabled,qe,L.id,st,Xe,pt)}function pC(M,g,C){if(!g.needsDEMTextureUpload)return;const L=M.context,$=L.gl;L.pixelStoreUnpackPremultiplyAlpha.set(!1),g.demTexture=g.demTexture||M.getTileTexture(C.stride);const G=C.getPixels();g.demTexture?g.demTexture.update(G,{premultiply:!1}):g.demTexture=new o.T(L,G,$.R32F,{premultiply:!1}),g.needsDEMTextureUpload=!1}function d6(M,g,C){const L=M.context,$=L.gl;if(!g.dem)return;const G=g.dem;if(L.activeTexture.set($.TEXTURE1),pC(M,g,G),!g.demTexture)return;g.demTexture.bind($.NEAREST,$.CLAMP_TO_EDGE);const K=G.dim;L.activeTexture.set($.TEXTURE0);let te=g.hillshadeFBO;if(!te){const De=new o.T(L,{width:K,height:K,data:null},$.RGBA8);De.bind($.LINEAR,$.CLAMP_TO_EDGE),te=g.hillshadeFBO=L.createFramebuffer(K,K,1,"renderbuffer"),te.colorAttachment0.set(De.texture)}L.bindFramebuffer.set(te.framebuffer),L.viewport.set([0,0,K,K]);const{tileBoundsBuffer:de,tileBoundsIndexBuffer:xe,tileBoundsSegments:_e}=M.getMercatorTileBoundsBuffers(),Oe=[];M.linearFloatFilteringSupported()&&Oe.push("TERRAIN_DEM_FLOAT_FORMAT"),M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback"&&Oe.push("USE_MRT1"),M.getOrCreateProgram("hillshadePrepare",{defines:Oe}).draw(M,$.TRIANGLES,nr.disabled,ra.disabled,Qr.unblended,Pr.disabled,((De,qe)=>{const st=qe.stride,Xe=o.bb();return o.bT(Xe,0,o.an,-o.an,0,0,1),o.bx(Xe,Xe,[0,-o.an,0]),{u_matrix:Xe,u_image:1,u_dimension:[st,st],u_zoom:De.overscaledZ}})(g.tileID,G),C.id,de,xe,_e),g.needsHillshadePrepare=!1}class ll{constructor(g){this.gl=g.gl,this.default=this.getDefault(),this.current=this.default,this.dirty=!1}get(){return this.current}set(g){}getDefault(){return this.default}setDefault(){this.set(this.default)}}class fj extends ll{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(g){const C=this.current;(g.r!==C.r||g.g!==C.g||g.b!==C.b||g.a!==C.a||this.dirty)&&(this.gl.clearColor(g.r,g.g,g.b,g.a),this.current=g,this.dirty=!1)}}class IR extends ll{getDefault(){return 1}set(g){(g!==this.current||this.dirty)&&(this.gl.clearDepth(g),this.current=g,this.dirty=!1)}}class LN extends ll{getDefault(){return 0}set(g){(g!==this.current||this.dirty)&&(this.gl.clearStencil(g),this.current=g,this.dirty=!1)}}class PR extends ll{getDefault(){return[!0,!0,!0,!0]}set(g){const C=this.current;(g[0]!==C[0]||g[1]!==C[1]||g[2]!==C[2]||g[3]!==C[3]||this.dirty)&&(this.gl.colorMask(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class Df extends ll{getDefault(){return!0}set(g){(g!==this.current||this.dirty)&&(this.gl.depthMask(g),this.current=g,this.dirty=!1)}}class xj extends ll{getDefault(){return 255}set(g){(g!==this.current||this.dirty)&&(this.gl.stencilMask(g),this.current=g,this.dirty=!1)}}class u1 extends ll{getDefault(){return{func:this.gl.ALWAYS,ref:0,mask:255}}set(g){const C=this.current;(g.func!==C.func||g.ref!==C.ref||g.mask!==C.mask||this.dirty)&&(this.gl.stencilFunc(g.func,g.ref,g.mask),this.current=g,this.dirty=!1)}}class DN extends ll{getDefault(){const g=this.gl;return[g.KEEP,g.KEEP,g.KEEP]}set(g){const C=this.current;(g[0]!==C[0]||g[1]!==C[1]||g[2]!==C[2]||this.dirty)&&(this.gl.stencilOp(g[0],g[1],g[2]),this.current=g,this.dirty=!1)}}class zy extends ll{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;g?C.enable(C.STENCIL_TEST):C.disable(C.STENCIL_TEST),this.current=g,this.dirty=!1}}class By extends ll{getDefault(){return[0,1]}set(g){const C=this.current;(g[0]!==C[0]||g[1]!==C[1]||this.dirty)&&(this.gl.depthRange(g[0],g[1]),this.current=g,this.dirty=!1)}}class $y extends ll{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;g?C.enable(C.DEPTH_TEST):C.disable(C.DEPTH_TEST),this.current=g,this.dirty=!1}}class gm extends ll{getDefault(){return this.gl.LESS}set(g){(g!==this.current||this.dirty)&&(this.gl.depthFunc(g),this.current=g,this.dirty=!1)}}class RN extends ll{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;g?C.enable(C.BLEND):C.disable(C.BLEND),this.current=g,this.dirty=!1}}class gj extends ll{getDefault(){const g=this.gl;return[g.ONE,g.ZERO,g.ONE,g.ZERO]}set(g){const C=this.current;(g[0]!==C[0]||g[1]!==C[1]||g[2]!==C[2]||g[3]!==C[3]||this.dirty)&&(this.gl.blendFuncSeparate(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class u6 extends ll{getDefault(){return o.aq.transparent.toNonPremultipliedRenderColor(null)}set(g){const C=this.current;(g.r!==C.r||g.g!==C.g||g.b!==C.b||g.a!==C.a||this.dirty)&&(this.gl.blendColor(g.r,g.g,g.b,g.a),this.current=g,this.dirty=!1)}}class h1 extends ll{getDefault(){return this.gl.FUNC_ADD}set(g){(g!==this.current||this.dirty)&&(this.gl.blendEquationSeparate(g,g),this.current=g,this.dirty=!1)}}class yj extends ll{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;g?C.enable(C.CULL_FACE):C.disable(C.CULL_FACE),this.current=g,this.dirty=!1}}class vj extends ll{getDefault(){return this.gl.BACK}set(g){(g!==this.current||this.dirty)&&(this.gl.cullFace(g),this.current=g,this.dirty=!1)}}class ON extends ll{getDefault(){return this.gl.CCW}set(g){(g!==this.current||this.dirty)&&(this.gl.frontFace(g),this.current=g,this.dirty=!1)}}let bj=class extends ll{getDefault(){return null}set(M){(M!==this.current||this.dirty)&&(this.gl.useProgram(M),this.current=M,this.dirty=!1)}};class _j extends ll{getDefault(){return this.gl.TEXTURE0}set(g){(g!==this.current||this.dirty)&&(this.gl.activeTexture(g),this.current=g,this.dirty=!1)}}class ym extends ll{getDefault(){const g=this.gl;return[0,0,g.drawingBufferWidth,g.drawingBufferHeight]}set(g){const C=this.current;(g[0]!==C[0]||g[1]!==C[1]||g[2]!==C[2]||g[3]!==C[3]||this.dirty)&&(this.gl.viewport(g[0],g[1],g[2],g[3]),this.current=g,this.dirty=!1)}}class zh extends ll{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;C.bindFramebuffer(C.FRAMEBUFFER,g),this.current=g,this.dirty=!1}}class fC extends ll{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;C.bindRenderbuffer(C.RENDERBUFFER,g),this.current=g,this.dirty=!1}}class m1 extends ll{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;C.bindTexture(C.TEXTURE_2D,g),this.current=g,this.dirty=!1}}class xC extends ll{getDefault(){return null}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;C.bindBuffer(C.ARRAY_BUFFER,g),this.current=g,this.dirty=!1}}class h6 extends ll{getDefault(){return null}set(g){const C=this.gl;C.bindBuffer(C.ELEMENT_ARRAY_BUFFER,g),this.current=g,this.dirty=!1}}class m6 extends ll{getDefault(){return null}set(g){this.gl&&(g!==this.current||this.dirty)&&(this.gl.bindVertexArray(g),this.current=g,this.dirty=!1)}}class gC extends ll{getDefault(){return 4}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_ALIGNMENT,g),this.current=g,this.dirty=!1}}class FN extends ll{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_PREMULTIPLY_ALPHA_WEBGL,g),this.current=g,this.dirty=!1}}class wj extends ll{getDefault(){return!1}set(g){if(g===this.current&&!this.dirty)return;const C=this.gl;C.pixelStorei(C.UNPACK_FLIP_Y_WEBGL,g),this.current=g,this.dirty=!1}}class Zb extends ll{constructor(g,C){super(g),this.context=g,this.parent=C}getDefault(){return null}}class p1 extends Zb{constructor(g,C,L=0){super(g,C),this.attachmentPoint=g.gl.COLOR_ATTACHMENT0+L}setDirty(){this.dirty=!0}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferTexture2D(C.FRAMEBUFFER,this.attachmentPoint,C.TEXTURE_2D,g,0),this.current=g,this.dirty=!1}}class jj extends Zb{attachment(){return this.gl.DEPTH_ATTACHMENT}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferRenderbuffer(C.FRAMEBUFFER,this.attachment(),C.RENDERBUFFER,g),this.current=g,this.dirty=!1}}class zN extends Zb{attachment(){return this.gl.DEPTH_ATTACHMENT}set(g){if(g===this.current&&!this.dirty)return;this.context.bindFramebuffer.set(this.parent);const C=this.gl;C.framebufferTexture2D(C.FRAMEBUFFER,this.attachment(),C.TEXTURE_2D,g,0),this.current=g,this.dirty=!1}}class p6 extends jj{attachment(){return this.gl.DEPTH_STENCIL_ATTACHMENT}}const f1=(M,g,C,L)=>({u_matrix:M,u_image0:0,u_image1:1,u_skirt_height:g,u_ground_shadow_factor:C,u_emissive_texture_available:L}),m0=(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt)=>({u_proj_matrix:Float32Array.from(M),u_globe_matrix:g,u_normalize_matrix:Float32Array.from(L),u_merc_matrix:C,u_zoom_transition:$,u_merc_center:G,u_image0:0,u_image1:1,u_frustum_tl:K,u_frustum_tr:te,u_frustum_br:de,u_frustum_bl:xe,u_globe_pos:_e,u_globe_radius:Oe,u_viewport:De,u_grid_matrix:pt?Float32Array.from(pt):new Float32Array(9),u_skirt_height:qe,u_far_z_cutoff:st,u_emissive_texture_available:Xe});function yC(M,g){return M!=null&&g!=null&&!(!M.hasData()||!g.hasData())&&M.demTexture!=null&&g.demTexture!=null&&M.tileID.key!==g.tileID.key}const pu=new class{constructor(){this.operations={}}newMorphing(M,g,C,L,$){if(M in this.operations){const G=this.operations[M];G.to.tileID.key!==C.tileID.key&&(G.queued=C)}else this.operations[M]={startTime:L,phase:0,duration:$,from:g,to:C,queued:null}}getMorphValuesForProxy(M){if(!(M in this.operations))return null;const g=this.operations[M];return{from:g.from,to:g.to,phase:g.phase}}update(M){for(const g in this.operations){const C=this.operations[g];for(C.phase=(M-C.startTime)/C.duration;C.phase>=1||!this._validOp(C);)if(!this._nextOp(C,M)){delete this.operations[g];break}}}_nextOp(M,g){return!!M.queued&&(M.from=M.to,M.to=M.queued,M.queued=null,M.phase=0,M.startTime=g,!0)}_validOp(M){return M.from.hasData()&&M.to.hasData()}},Qb={0:null,1:"TERRAIN_VERTEX_MORPHING"};function Xb(M,g,C){if(g===0)return 0;const L=g<1&&C===514?.25/g:1;return 6*Math.pow(1.5,22-M)*Math.max(g,1)*L}function x1(M,g){const C=1<({u_matrix:M});function rp(M,g,C,L,$){if($>0){const G=o.o.now(),K=(G-M.timeAdded)/$,te=g?(G-g.timeAdded)/$:-1,de=C.getSource(),xe=L.coveringZoomLevel({tileSize:de.tileSize,roundZoom:de.roundZoom}),_e=!g||Math.abs(g.tileID.overscaledZ-xe)>Math.abs(M.tileID.overscaledZ-xe),Oe=_e&&M.refreshedUponExpiration?1:o.aC(_e?K:1-te,0,1);return g?{opacity:1,mix:1-Oe,isFading:K<1}:{opacity:Oe,mix:0,isFading:K<1}}return{opacity:1,mix:0,isFading:!1}}class kj extends sl{constructor(g){const C={type:"raster-dem",maxzoom:Math.ceil(g.transform.maxZoom)},L=Ay("mock-dem",C,g.style.dispatcher,g.style);super("mock-dem",L,null),L.setEventedParent(this),this._sourceLoaded=!0}_loadTile(g,C){g.state="loaded",C(null)}}class g1 extends sl{constructor(g){const C=Ay("proxy",{type:"geojson",maxzoom:Math.ceil(g.transform.maxZoom)},g.style.dispatcher,g.style);super("proxy",C,null),C.setEventedParent(this),this.map=this.getSource().map=g,this.used=this._sourceLoaded=!0,this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}update(g,C,L){if(g.freezeTileCoverage)return;this.transform=g;const $=g.coveringTiles({tileSize:this._source.tileSize,minzoom:this._source.minzoom,maxzoom:this._source.maxzoom,roundZoom:this._source.roundZoom,reparseOverscaled:this._source.reparseOverscaled}).reduce((G,K)=>{if(G[K.key]="",!this._tiles[K.key]){const te=new o.b0(K,this._source.tileSize*K.overscaleFactor(),g.tileZoom,void 0,void 0,this._source.worldview);te.state="loaded",this._tiles[K.key]=te}return G},{});for(const G in this._tiles)G in $||(this.freeFBO(G),this._tiles[G].unloadVectorData(),delete this._tiles[G])}freeFBO(g){const C=this.proxyCachedFBO[g];if(C!==void 0){const L=Object.values(C);this.renderCachePool.push(...L),delete this.proxyCachedFBO[g]}}deallocRenderCache(){this.renderCache.forEach(g=>g.fb.destroy()),this.renderCache=[],this.renderCachePool=[],this.proxyCachedFBO={}}}class Uy extends o.aR{constructor(g,C,L){super(g.overscaledZ,g.wrap,g.canonical.z,g.canonical.x,g.canonical.y),this.proxyTileKey=C,this.projMatrix=L}}class qy extends o.bu{constructor(g,C){super(),this._debugParams={sortTilesHiZFirst:!0,disableRenderCache:!1},this.painter=g,this.terrainTileForTile={},this.prevTerrainTileForTile={};const[L,$,G]=function(){const de=new o.dB,xe=new o.dC,_e=131;de.reserve(17161),xe.reserve(33800);const Oe=o.an/128,De=o.an+Oe/2,qe=De+Oe;for(let Xe=-Oe;XeDe||Xe<0||Xe>De?24575:0,kt=o.aC(Math.round(pt),0,o.an),Et=o.aC(Math.round(Xe),0,o.an);de.emplaceBack(kt+mt,Et)}const st=(Xe,pt)=>{const mt=pt*_e+Xe;xe.emplaceBack(mt+1,mt,mt+_e),xe.emplaceBack(mt+_e,mt+_e+1,mt+1)};for(let Xe=1;Xe<129;Xe++)for(let pt=1;pt<129;pt++)st(pt,Xe);return[0,129].forEach(Xe=>{for(let pt=0;pt<130;pt++)st(pt,Xe),st(Xe,pt)}),[de,xe,32768]}(),K=g.context;this.gridBuffer=K.createVertexBuffer(L,o.dx.members),this.gridIndexBuffer=K.createIndexBuffer($),this.gridSegments=o.dy.simpleSegment(0,0,L.length,$.length),this.gridNoSkirtSegments=o.dy.simpleSegment(0,0,L.length,G),this.proxyCoords=[],this.proxiedCoords={},this._visibleDemTiles=[],this._drapedRenderBatches=[],this._sourceTilesOverlap={},this.proxySourceCache=new g1(C.map),this.orthoMatrix=o.bb(),o.bT(this.orthoMatrix,this.painter.transform.projection.name==="globe"?.015:0,o.an,0,o.an,0,1);const te=K.gl;this._overlapStencilMode=new ra({func:te.GEQUAL,mask:255},0,255,te.KEEP,te.KEEP,te.REPLACE),this._previousZoom=g.transform.zoom,this.pool=[],this._findCoveringTileCache={},this._tilesDirty={},this.style=C,this._useVertexMorphing=!0,this._exaggeration=1,this._mockSourceCache=new kj(C.map),this._pendingGroundEffectLayers=[],this._emissiveTexture=!1}set style(g){g.on("data",this._onStyleDataEvent.bind(this)),this._style=g,this._style.map.on("moveend",()=>{this._clearLineLayersFromRenderCache()})}update(g,C,L){if(g&&g.terrain){this._style!==g&&(this.style=g,this._evaluationZoom=void 0);const $=g.terrain.properties,G=g.terrain.drapeRenderMode===0,K=g.terrain.isZoomDependent();this._previousUpdateTimestamp=this.enabled?this._updateTimestamp:void 0,this._updateTimestamp=o.o.now();const te=g.terrain&&g.terrain.scope,de=$.get("source"),xe=G?this._mockSourceCache:g.getSourceCache(de,te);if(!xe)return void o.w(`Couldn't find terrain source "${de}".`);if(this.sourceCache=xe,this._attenuationRange=g.terrain.getAttenuationRange(),this._exaggeration=K?this.calculateExaggeration(C):$.get("exaggeration"),!C.projection.requiresDraping&&K&&this._exaggeration===0)return void this._disable();this.enabled=!0;const _e=()=>{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 Oe=this.getScaledDemTileSize();this.sourceCache.update(C,Oe,!0),this.resetTileLookupCache(this.sourceCache.id)};this.sourceCache.usedForTerrain||(this.resetTileLookupCache(this.sourceCache.id),this.sourceCache.usedForTerrain=!0,_e(),this._initializing=!0),_e(),C.updateElevation(!0,L),this.resetTileLookupCache(this.proxySourceCache.id),this.proxySourceCache.update(C),this._emptyDEMTextureDirty=!0,this._previousZoom=C.zoom}else this._disable()}calculateExaggeration(g){if(this._attenuationRange&&g.zoom>=Math.ceil(this._attenuationRange[1]))return this._style.terrain.getExaggeration(g.zoom);const C=this._previousCameraAltitude,L=g.getFreeCameraOptions().position.z/g.pixelsPerMeter*g.worldSize;this._previousCameraAltitude=L;const $=C!=null?L-C:Number.MAX_VALUE;if(Math.abs($)<2)return this._exaggeration;const G=g.zoom,K=this._style.terrain;if(!this._previousUpdateTimestamp)return K.getExaggeration(G);let te=G-this._previousZoom;const de=this._previousUpdateTimestamp;let xe=G;this._evaluationZoom!=null&&(xe=this._evaluationZoom,Math.abs(G-xe)>.5&&(te=.5*(G-xe+te)),te*$<0&&(xe+=te)),this._evaluationZoom=xe;const _e=K.getExaggeration(xe),Oe=_e===K.getExaggeration(Math.max(0,xe-.1));if(Oe&&Math.abs(_e-this._exaggeration)<.01)return _e;let De=Math.min(.1,.00375*(this._updateTimestamp-de));return(Oe||_e<.1||Math.abs(te)<1e-4)&&(De=Math.min(.2,4*De)),o.am(this._exaggeration,_e,De)}resetTileLookupCache(g){this._findCoveringTileCache[g]={}}attenuationRange(){return this._attenuationRange}getDemUpscale(){return this.proxySourceCache.getSource().tileSize/128}getScaledDemTileSize(){return this.sourceCache.getSource().tileSize/128*this.proxySourceCache.getSource().tileSize}_onStyleDataEvent(g){g.dataType==="source"&&g.coord?this._clearRenderCacheForTile(g.sourceCacheId,g.coord):g.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 g in this._style._mergedSourceCaches)this._style._mergedSourceCaches[g].usedForTerrain=!1}destroy(){this._disable(),this._emptyDEMTexture&&this._emptyDEMTexture.destroy(),this.pool.forEach(g=>g.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 g=2*this.proxySourceCache.getSource().tileSize;return[g,g]}set useVertexMorphing(g){this._useVertexMorphing=g}updateTileBinding(g){if(!this.enabled)return;this.prevTerrainTileForTile=this.terrainTileForTile;const C=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 $=this.proxyCoords=C.getIds().map(de=>{const xe=C.getTileByID(de).tileID;return xe.projMatrix=L.calculateProjMatrix(xe.toUnwrapped()),xe});(function(de,xe){const _e=xe.transform.pointCoordinate(xe.transform.getCameraPoint()),Oe=new o.P(_e.x,_e.y);de.sort((De,qe)=>{if(qe.overscaledZ-De.overscaledZ)return qe.overscaledZ-De.overscaledZ;const st=new o.P(De.canonical.x+(1<{this.proxyToSource[de.key]={}}),this.terrainTileForTile={};const K=this._style._mergedSourceCaches;for(const de in K){const xe=K[de];if(!xe.used||(xe!==this.sourceCache&&this.resetTileLookupCache(xe.id),this._setupProxiedCoordsForOrtho(xe,g[de],G),xe.usedForTerrain))continue;const _e=g[de];(xe.getSource().reparseOverscaled||xe._isRasterElevatedOverTerrain)&&this._assignTerrainTiles(_e)}this.proxiedCoords[C.id]=$.map(de=>new Uy(de,de.key,this.orthoMatrix)),this._assignTerrainTiles($),this._prepareDEMTextures(),this._setupDrapedRenderBatches(),this._initFBOPool(),this._setupRenderCache(G),this.renderingToTexture=!1;const te={};this._visibleDemTiles=[];for(const de of this.proxyCoords){const xe=this.terrainTileForTile[de.key];if(!xe)continue;const _e=xe.tileID.key;_e in te||(this._visibleDemTiles.push(xe),te[_e]=_e)}}_assignTerrainTiles(g){this._initializing||g.forEach(C=>{if(this.terrainTileForTile[C.key])return;const L=this._findTileCoveringTileID(C,this.sourceCache);L&&(this.terrainTileForTile[C.key]=L)})}_prepareDEMTextures(){const g=this.painter.context,C=g.gl;for(const L in this.terrainTileForTile){const $=this.terrainTileForTile[L],G=$.dem;!G||$.demTexture&&!$.needsDEMTextureUpload||(g.activeTexture.set(C.TEXTURE1),pC(this.painter,$,G))}}_prepareDemTileUniforms(g,C,L,$){if(!C||C.demTexture==null)return!1;const G=g.tileID.canonical,K=Math.pow(2,C.tileID.canonical.z-G.z),te=$||"";return L[`u_dem_tl${te}`]=[G.x*K%1,G.y*K%1],L[`u_dem_scale${te}`]=K,!0}get emptyDEMTexture(){return!this._emptyDEMTextureDirty&&this._emptyDEMTexture?this._emptyDEMTexture:this._updateEmptyDEMTexture()}_getLoadedAreaMinimum(){if(!this.enabled)return 0;let g=0;const C=this._visibleDemTiles.reduce((L,$)=>{if(!$.dem)return L;const G=$.dem.tree.minimums[0];return G>0&&g++,L+G},0);return g?C/g:0}_updateEmptyDEMTexture(){const g=this.painter.context,C=g.gl;g.activeTexture.set(C.TEXTURE2);const L=this._getLoadedAreaMinimum(),$=new o.dz({width:1,height:1},new Float32Array([L]));this._emptyDEMTextureDirty=!1;let G=this._emptyDEMTexture;return G?G.update($,{premultiply:!1}):G=this._emptyDEMTexture=new o.T(g,$,C.R32F,{premultiply:!1}),G}setupElevationDraw(g,C,L){const $=this.painter.context,G=$.gl,K={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};K.u_exaggeration=this.exaggeration();let te=null,de=null,xe=1;if(L&&L.morphing&&this._useVertexMorphing){const qe=L.morphing.srcDemTile,st=L.morphing.dstDemTile;xe=L.morphing.phase,qe&&st&&(this._prepareDemTileUniforms(g,qe,K,"_prev")&&(de=qe),this._prepareDemTileUniforms(g,st,K)&&(te=st))}const _e=qe=>qe&&qe.demTexture&&this.painter.linearFloatFilteringSupported()?G.LINEAR:G.NEAREST;let Oe=null;var De;if(this.enabled?de&&te?(Oe=te.demTexture,$.activeTexture.set(G.TEXTURE4),de.demTexture.bind(_e(de),G.CLAMP_TO_EDGE),K.u_dem_lerp=xe):(te=this.terrainTileForTile[g.tileID.key],Oe=this._prepareDemTileUniforms(g,te,K)?te.demTexture:this.emptyDEMTexture):Oe=this.emptyDEMTexture,$.activeTexture.set(G.TEXTURE2),Oe&&(K.u_dem_size=(De=Oe).size[0]===1?1:De.size[0]-2,Oe.bind(_e(te),G.CLAMP_TO_EDGE)),this.painter.setupDepthForOcclusion(L&&L.useDepthForOcclusion,C,K),L&&L.useMeterToDem&&te){const qe=(1<{if(mt===Ps)return;const rn=[Qb[Ps],"PROJECTION_GLOBE_VIEW"];Et&&rn.push("CUSTOM_ANTIALIASING");const hn=xe.isTileAffectedByFog(Bs);pt=xe.getOrCreateProgram("globeRaster",{defines:rn,overrideFog:hn}),mt=Ps},es=xe.colorModeForRenderPass(),Ot=new nr(Xe.LEQUAL,nr.ReadWrite,xe.depthRangeFor3D);pu.update(qe);const Qt=o.dq(kt),At=[o.aH(kt.center.lng),o.aL(kt.center.lat)],Dt=xe.globeSharedBuffers,Ht=[kt.width*o.o.devicePixelRatio,kt.height*o.o.devicePixelRatio],gs=Float32Array.from(kt.globeMatrix),ss={useDenormalizedUpVectorScale:!0};{const Bs=xe.transform,Ps=Xb(Bs.zoom,_e.exaggeration(),_e.sourceCache._source.tileSize);mt=-1;const rn=Xe.TRIANGLES;for(const hn of De){const Ns=Oe.getTile(hn),ds=ra.disabled,Fs=_e.prevTerrainTileForTile[hn.key],Us=_e.terrainTileForTile[hn.key];yC(Fs,Us)&&pu.newMorphing(hn.key,Fs,Us,qe,250),zp(xe,Ns.emissiveTexture),st.activeTexture.set(Xe.TEXTURE0),Ns.texture&&Ns.texture.bind(Xe.LINEAR,Xe.CLAMP_TO_EDGE);const Ys=pu.getMorphValuesForProxy(hn.key),Dn=Ys?1:0;Ys&&Object.assign(ss,{morphing:{srcDemTile:Ys.from,dstDemTile:Ys.to,phase:o.dn(Ys.phase)}});const kn=o.dr(hn.canonical),Sn=o.ds(kn.getCenter().lat),cn=o.dt(hn.canonical,kn,Sn,Bs.worldSize/Bs._pixelsPerMercatorPixel),ur=o.du(o.dv(hn.canonical)),Nr=xe.emissiveMode==="mrt-fallback"?1:0,rr=m0(Bs.expandedFarZProjMatrix,gs,Qt,ur,o.al(Bs.zoom),At,Bs.frustumCorners.TL,Bs.frustumCorners.TR,Bs.frustumCorners.BR,Bs.frustumCorners.BL,Bs.globeCenterInViewSpace,Bs.globeRadius,Ht,Ps,Bs._farZ,Nr,cn);if(xt(hn,Dn),pt&&(_e.setupElevationDraw(Ns,pt,ss),xe.uploadCommonUniforms(st,pt,hn.toUnwrapped()),Dt)){const[dr,Xr,va]=Dt.getGridBuffers(Sn,Ps!==0);pt.draw(xe,rn,Ot,ds,es,Pr.backCCW,rr,"globe_raster",dr,Xr,va)}}}if(Dt&&(xe.renderDefaultNorthPole||xe.renderDefaultSouthPole)){const Bs=["GLOBE_POLES","PROJECTION_GLOBE_VIEW"];Et&&Bs.push("CUSTOM_ANTIALIASING"),pt=xe.getOrCreateProgram("globeRaster",{defines:Bs});for(const Ps of De){const{x:rn,y:hn,z:Ns}=Ps.canonical,ds=hn===0,Fs=hn===(1<dr.draw(xe,Xe.TRIANGLES,Ot,ra.disabled,es,Pr.disabled,m0(kt.expandedFarZProjMatrix,cn,cn,ur,0,At,kt.frustumCorners.TL,kt.frustumCorners.TR,kt.frustumCorners.BR,kt.frustumCorners.BL,kt.globeCenterInViewSpace,kt.globeRadius,Ht,0,kt._farZ,Nr),"globe_pole_raster",Xr,Dn,kn);_e.setupElevationDraw(Sn,pt,ss),xe.uploadCommonUniforms(st,pt,Ps.toUnwrapped()),ds&&xe.renderDefaultNorthPole&&rr(pt,Us),Fs&&xe.renderDefaultSouthPole&&(cn=o.cC(o.bb(),cn,[1,-1,1]),rr(pt,Ys))}}}})($,G,K,te,de);else{const xe=$.context,_e=xe.gl;let Oe,De;const qe=$.shadowRenderer,st=Dc($,$.longestCutoffRange),Xe=es=>{if(De===es)return;const Ot=[];Ot.push(Qb[es]),st.shouldRenderCutoff&&Ot.push("RENDER_CUTOFF"),qe&&(Ot.push("RENDER_SHADOWS"),qe.useNormalOffset&&Ot.push("NORMAL_OFFSET")),Oe=$.getOrCreateProgram("terrainRaster",{defines:Ot}),De=es},pt=$.colorModeForRenderPass(),mt=new nr(_e.LEQUAL,nr.ReadWrite,$.depthRangeFor3D);pu.update(de);const kt=$.transform,Et=Xb(kt.zoom,G.exaggeration(),G.sourceCache._source.tileSize);let xt=[0,0,0];if(qe){const es=$.style.directionalLight,Ot=$.style.ambientLight;es&&Ot&&(xt=Op($.style,es,Ot))}{De=-1;const es=_e.TRIANGLES,[Ot,Qt]=[G.gridIndexBuffer,G.gridSegments];for(const At of te){const Dt=K.getTile(At),Ht=ra.disabled,gs=G.prevTerrainTileForTile[At.key],ss=G.terrainTileForTile[At.key];yC(gs,ss)&&pu.newMorphing(At.key,gs,ss,de,250),zp($,Dt.emissiveTexture),xe.activeTexture.set(_e.TEXTURE0),Dt.texture&&Dt.texture.bind(_e.LINEAR,_e.CLAMP_TO_EDGE);const Bs=pu.getMorphValuesForProxy(At.key),Ps=Bs?1:0;let rn;Bs&&(rn={morphing:{srcDemTile:Bs.from,dstDemTile:Bs.to,phase:o.dn(Bs.phase)}});const hn=$.emissiveMode==="mrt-fallback"?1:0,Ns=f1(At.projMatrix,x1(At.canonical,kt.renderWorldCopies)?Et/10:Et,xt,hn);if(Xe(Ps),!Oe)continue;G.setupElevationDraw(Dt,Oe,rn);const ds=At.toUnwrapped();qe&&qe.setupShadows(ds,Oe),$.uploadCommonUniforms(xe,Oe,ds,null,st),Oe.draw($,es,mt,Ht,pt,Pr.backCCW,Ns,"terrain_raster",G.gridBuffer,Ot,Qt)}}}}(C,this,this.proxySourceCache,g,this._updateTimestamp),this.renderingToTexture=!0,C.gpuTimingDeferredRenderEnd(),g.splice(0,g.length))}renderBatch(g){if(this._drapedRenderBatches.length===0)return g+1;this.renderingToTexture=!0;const C=this.painter,L=this.painter.context,$=this.proxySourceCache,G=this.proxiedCoords[$.id],K=this._drapedRenderBatches.shift(),te=C.style.order,de=[];this._updateFBOs(C.emissiveMode==="mrt-fallback");let xe=0;for(const _e of G){const Oe=$.getTileByID(_e.proxyTileKey),De=$.proxyCachedFBO[_e.key]?$.proxyCachedFBO[_e.key][g]:void 0,qe=De!==void 0?$.renderCache[De]:this.pool[xe++],st=De!==void 0;if(Oe.texture=qe.tex,Oe.emissiveTexture=qe.emissiveTex,st&&!qe.dirty){de.push(Oe.tileID);continue}L.bindFramebuffer.set(qe.fb.framebuffer);const Xe=L.gl;let pt;Xe.drawBuffers(C.emissiveMode==="mrt-fallback"?[Xe.COLOR_ATTACHMENT0,Xe.COLOR_ATTACHMENT1]:[Xe.COLOR_ATTACHMENT0]),this.renderedToTile=!1,qe.dirty&&(L.clear({color:o.aq.transparent,stencil:0}),qe.dirty=!1);for(let mt=K.start;mt<=K.end;++mt){const kt=C.style._mergedLayers[te[mt]];if(kt.isHidden(C.transform.zoom))continue;const Et=C.style.getLayerSourceCache(kt),xt=Et?this.proxyToSource[_e.key][Et.id]:[_e];if(!xt)continue;const es=xt;L.viewport.set([0,0,qe.fb.width,qe.fb.height]),pt!==(Et?Et.id:null)&&(this._setupStencil(qe,xt,kt,Et),pt=Et?Et.id:null),C.renderLayer(C,Et,kt,es)}if(Xe.drawBuffers([Xe.COLOR_ATTACHMENT0]),this._drapedRenderBatches.length===0)for(const mt of this._pendingGroundEffectLayers){const kt=C.style._mergedLayers[te[mt]];if(kt.isHidden(C.transform.zoom))continue;const Et=C.style.getLayerSourceCache(kt),xt=Et?this.proxyToSource[_e.key][Et.id]:[_e];if(!xt)continue;const es=xt;L.viewport.set([0,0,qe.fb.width,qe.fb.height]),pt!==(Et?Et.id:null)&&(this._setupStencil(qe,xt,kt,Et),pt=Et?Et.id:null),C.renderLayer(C,Et,kt,es)}this.renderedToTile?(qe.dirty=!0,de.push(Oe.tileID)):st||--xe,xe===5&&(xe=0,this.renderToBackBuffer(de))}return this.renderToBackBuffer(de),this.renderingToTexture=!1,L.bindFramebuffer.set(null),L.viewport.set([0,0,C.width,C.height]),K.end+1}postRender(){}isLayerOrderingCorrect(g){const C=g.order.length;let L=-1,$=C;for(let G=0;GL}getMinElevationBelowMSL(){let g=0;return this._visibleDemTiles.filter(C=>C.dem).forEach(C=>{g=Math.min(g,C.dem.tree.minimums[0])}),g===0?g:(g-30)*this._exaggeration}raycast(g,C,L){if(!this._visibleDemTiles)return null;const $=this._visibleDemTiles.filter(G=>G.dem).map(G=>{const K=G.tileID,te=1<(G.t!==null?G.t:Number.MAX_VALUE)-(K.t!==null?K.t:Number.MAX_VALUE));for(const G of $){if(G.t==null)return null;const K=G.tile.dem.tree.raycast(G.minx,G.miny,G.maxx,G.maxy,g,C,L);if(K!=null)return K}return null}_createFBO(){const g=this.painter.context,C=g.gl,L=this.drapeBufferSize;g.activeTexture.set(C.TEXTURE0);const $=new o.T(g,{width:L[0],height:L[1],data:null},C.RGBA8);$.bind(C.LINEAR,C.CLAMP_TO_EDGE);const G=g.createFramebuffer(L[0],L[1],1,null);let K;return G.colorAttachment0.set($.texture),this._emissiveTexture&&(K=new o.T(g,{width:L[0],height:L[1],data:null},C.R8),K.bind(C.LINEAR,C.CLAMP_TO_EDGE),G.createColorAttachment(g,1),G.colorAttachment1.set(K.texture)),G.depthAttachment=new p6(g,G.framebuffer),this._sharedDepthStencil===void 0?(this._sharedDepthStencil=g.createRenderbuffer(g.gl.DEPTH_STENCIL,L[0],L[1]),this._stencilRef=0,G.depthAttachment.set(this._sharedDepthStencil),g.clear({stencil:0})):G.depthAttachment.set(this._sharedDepthStencil),g.extTextureFilterAnisotropic&&C.texParameterf(C.TEXTURE_2D,g.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,g.extTextureFilterAnisotropicMax),{fb:G,tex:$,emissiveTex:K,dirty:!1}}_updateFBOs(g){if(this._emissiveTexture!==g){for(const C of this.pool)this._updateFBO(C,g);for(const C of this.proxySourceCache.renderCache)this._updateFBO(C,g);this._emissiveTexture=g}}_updateFBO(g,C){const L=g.fb,$=this.painter.context,G=$.gl,K=this.drapeBufferSize;if(C){const te=new o.T($,{width:K[0],height:K[1],data:null},G.R8);te.bind(G.LINEAR,G.CLAMP_TO_EDGE),g.emissiveTex=te,L.createColorAttachment($,1),L.colorAttachment1.set(te.texture)}else g.emissiveTex=void 0,L.removeColorAttachment($,1);g.dirty=!0}_initFBOPool(){for(;this.pool.length{const C=this._style._mergedLayers[g],L=C.isHidden(this.painter.transform.zoom);return C.type==="hillshade"||C.type==="custom"?!L&&C.shouldRedrape():!L&&C.hasTransition()})}_clearLineLayersFromRenderCache(){let g=!1;for(const L of this._style.getSources())if(L instanceof $d){g=!0;break}if(!g)return;const C={};for(let L=0;Lde>te.end)||o.w("fill-extrusion with flood lighting and/or ground ambient occlusion should be moved to be on top of all draped layers.")}this._drapedRenderBatches=L}_setupRenderCache(g){const C=this.proxySourceCache;if(this._shouldDisableRenderCache()||this.invalidateRenderCache){if(this.invalidateRenderCache=!1,C.renderCache.length>C.renderCachePool.length){const K=Object.values(C.proxyCachedFBO);C.proxyCachedFBO={};for(let te=0;te=0;K--){const te=L[K];if(C.getTileByID(te.key),C.proxyCachedFBO[te.key]!==void 0){const de=g[te.key],xe=this.proxyToSource[te.key];let _e=0;for(const Oe in xe){const De=xe[Oe],qe=de[Oe];if(!qe||qe.length!==De.length||De.some((st,Xe)=>st!==qe[Xe]||$[Oe]&&$[Oe].hasOwnProperty(st.key))){_e=-1;break}++_e}for(const Oe in C.proxyCachedFBO[te.key])C.renderCache[C.proxyCachedFBO[te.key][Oe]].dirty=_e<0||_e!==Object.values(de).length}}const G=[...this._drapedRenderBatches];G.sort((K,te)=>te.end-te.start-(K.end-K.start));for(const K of G)for(const te of L){if(C.proxyCachedFBO[te.key])continue;let de=C.renderCachePool.pop();de===void 0&&C.renderCache.length<50&&(de=C.renderCache.length,C.renderCache.push(this._createFBO())),de!==void 0&&(C.proxyCachedFBO[te.key]={},C.proxyCachedFBO[te.key][K.start]=de,C.renderCache[de].dirty=!0)}this._tilesDirty={}}_setupStencil(g,C,L,$){if(!$||!this._sourceTilesOverlap[$.id])return void(this._overlapStencilType&&(this._overlapStencilType=!1));const G=this.painter.context,K=G.gl;if(C.length<=1)return void(this._overlapStencilType=!1);let te;if(L.isTileClipped())te=C.length,this._overlapStencilMode.test={func:K.EQUAL,mask:255},this._overlapStencilType="Clip";else{if(!(C[0].overscaledZ>C[C.length-1].overscaledZ))return void(this._overlapStencilType=!1);te=1,this._overlapStencilMode.test={func:K.GREATER,mask:255},this._overlapStencilType="Mask"}this._stencilRef+te>255&&(G.clear({stencil:0}),this._stencilRef=0),this._stencilRef+=te,this._overlapStencilMode.ref=this._stencilRef,L.isTileClipped()&&this._renderTileClippingMasks(C,this._overlapStencilMode.ref)}clipOrMaskOverlapStencilType(){return this._overlapStencilType==="Clip"||this._overlapStencilType==="Mask"}stencilModeForRTTOverlap(g){return this.renderingToTexture&&this._overlapStencilType?(this._overlapStencilType==="Clip"&&(this._overlapStencilMode.ref=this.painter._tileClippingMaskIDs[g.key]),this._overlapStencilMode):ra.disabled}_renderTileClippingMasks(g,C){const L=this.painter,$=this.painter.context,G=$.gl;L._tileClippingMaskIDs={},$.setColorMode(Qr.disabled),$.setDepthMode(nr.disabled);const K=L.getOrCreateProgram("clippingMask");for(const te of g){const de=L._tileClippingMaskIDs[te.key]=--C;K.draw(L,G.TRIANGLES,nr.disabled,new ra({func:G.ALWAYS,mask:0},de,255,G.KEEP,G.KEEP,G.REPLACE),Qr.disabled,Pr.disabled,Nj(te.projMatrix),"$clipping",L.tileExtentBuffer,L.quadTriangleIndexBuffer,L.tileExtentSegments)}}pointCoordinate(g){const C=this.painter.transform;if(g.x<0||g.x>C.width||g.y<0||g.y>C.height)return null;const L=[g.x,g.y,1,1];o.aE(L,L,C.pixelMatrixInverse),o.cu(L,L,1/L[3]),L[0]/=C.worldSize,L[1]/=C.worldSize;const $=C._camera.position,G=o.bU(1,C.center.lat),K=[$[0],$[1],$[2]/G,0],te=o.cV([],L.slice(0,3),K);o.ay(te,te);const de=this.raycast(K,te,this._exaggeration);return de!==null&&de?(o.bg(K,K,te,de),K[3]=K[2],K[2]*=G,K):null}_setupProxiedCoordsForOrtho(g,C,L){if(g.getSource()instanceof o.aV)return this._setupProxiedCoordsForImageSource(g,C,L);this._findCoveringTileCache[g.id]=this._findCoveringTileCache[g.id]||{};const $=this.proxiedCoords[g.id]=[],G=this.proxyCoords;for(let de=0;de_e.overscaledZ-xe.overscaledZ)}_setupProxiedCoordsForImageSource(g,C,L){if(!g.getSource().loaded())return;const $=this.proxiedCoords[g.id]=[],G=this.proxyCoords,K=g.getSource(),te=K.tileID;if(!te)return;const de=new o.P(te.x,te.y)._div(1<(Oe.min.x=Math.min(Oe.min.x,De.x-de.x),Oe.min.y=Math.min(Oe.min.y,De.y-de.y),Oe.max.x=Math.max(Oe.max.x,De.x-de.x),Oe.max.y=Math.max(Oe.max.y,De.y-de.y),Oe),{min:new o.P(Number.MAX_VALUE,Number.MAX_VALUE),max:new o.P(-Number.MAX_VALUE,-Number.MAX_VALUE)}),_e=(Oe,De)=>{const qe=Oe.wrap+Oe.canonical.x/(1<pt+xe.max.x||st+Xemt+xe.max.y};for(let Oe=0;OeK.key===C.tileID.key);if(G)return G}if(C.tileID.key!==g.key){const G=g.canonical.z-C.tileID.canonical.z;let K,te,de;$=o.bb();const xe=C.tileID.wrap-g.wrap<0?(K=o.an>>G,te=K*((C.tileID.canonical.x<=Oe){const De=g.canonical.z-Oe;C.getSource().reparseOverscaled?(te=Math.max(g.canonical.z+2,C.transform.tileZoom),K=new o.aR(te,g.wrap,Oe,g.canonical.x>>De,g.canonical.y>>De)):De!==0&&(te=Oe,K=new o.aR(te,g.wrap,Oe,g.canonical.x>>De,g.canonical.y>>De))}K.key!==g.key&&(xe.push(K.key),L=C.getTile(K))}const _e=Oe=>{xe.forEach(De=>{$[De]=Oe}),xe.length=0};for(te-=1;te>=de&&(!L||!L.hasData());te--){L&&_e(L.tileID.key);const Oe=K.calculateScaledKey(te);if(L=C.getTileByID(Oe),L&&L.hasData())break;const De=$[Oe];if(De===null)break;De===void 0?xe.push(Oe):L=C.getTileByID(De)}return _e(L?L.tileID.key:null),L&&L.hasData()?L:null}findDEMTileFor(g){return this.enabled?this._findTileCoveringTileID(g,this.sourceCache):null}prepareDrawTile(){this.renderedToTile=!0}_clearRenderCacheForTile(g,C){let L=this._tilesDirty[g];L||(L=this._tilesDirty[g]={}),L[C.key]=!0}}function Jb(M,g,C){const L=function(te,de,xe){const _e=o.bi(de,te),Oe=o.bi(xe,[.2126,.7152,.0722]),De=(st,Xe,pt)=>(1-pt)*st+pt*Xe,qe=De(1-.3*Math.min(Oe,1),1,Math.min(_e+1,1));return De(.92,1,Math.asin(o.aC(de[2],-1,1))/Math.PI+.5)*qe}(M,[0,0,1],g),$=[0,0,0];o.bJ($,C.slice(0,3),L);const G=[0,0,0];o.bJ(G,g.slice(0,3),M[2]);const K=[0,0,0];return o.cT(K,$,G),o.cW(K)}const vC=["fill","fillOutline","fillPattern","line","linePattern","background","backgroundPattern","hillshade","raster"],e_=["stars","rainParticle","snowParticle","fillExtrusion","fillExtrusionGroundEffect","building","buildingBloom","elevatedStructures","model","symbol"];class od{static cacheKey(g,C,L,$){const G=[C];$&&G.push($.cacheKey);for(const K of L)(typeof K=="string"&&K.includes(" ")||g.usedDefines.has(K))&&G.push(K);return G.join("/")}constructor(g,C,L,$,G,K){const te=g.gl;this.program=te.createProgram(),this.configuration=$,this.name=C,this.fixedDefines=[...K];const de=`#version 300 es ${($?$.defines():[]).concat(K.map(Xe=>`#define ${Xe}`)).join(` `)}`,xe=[de,d1];for(const Xe of L.fragmentIncludes)xe.push(Fp[Xe]);xe.push(L.fragmentSource);const _e=xe.join(` `),Oe=[de,cC];for(const Xe of L.vertexIncludes)Oe.push(Fp[Xe]);this.forceManualRenderingForInstanceIDShaders=g.forceManualRenderingForInstanceIDShaders&&L.vertexSource.includes("gl_InstanceID"),this.forceManualRenderingForInstanceIDShaders&&Oe.push("uniform int u_instanceID;"),Oe.push(L.vertexSource);let De=Oe.join(` `);this.forceManualRenderingForInstanceIDShaders&&(De=De.replaceAll("gl_InstanceID","u_instanceID"));const qe=te.createShader(te.FRAGMENT_SHADER);if(te.isContextLost())return void(this.failedToCreate=!0);te.shaderSource(qe,_e),te.compileShader(qe),te.attachShader(this.program,qe);const st=te.createShader(te.VERTEX_SHADER);te.isContextLost()?this.failedToCreate=!0:(te.shaderSource(st,De),te.compileShader(st),te.attachShader(this.program,st),this.attributes={},te.linkProgram(this.program),te.deleteShader(st),te.deleteShader(qe),this.fixedUniforms=G(g),this.fixedUniformsEntries=Object.entries(this.fixedUniforms),this.binderUniforms=$?$.getUniforms(g):[],this.forceManualRenderingForInstanceIDShaders&&(this.instancingUniforms=(Xe=>({u_instanceID:new o.bX(Xe)}))(g)),(K.includes("TERRAIN")||K.includes("ELEVATED")||C.includes("symbol")||C.includes("circle"))&&(this.terrainUniforms=(Xe=>({u_dem:new o.bX(Xe),u_dem_prev:new o.bX(Xe),u_dem_tl:new o.b_(Xe),u_dem_scale:new o.bZ(Xe),u_dem_tl_prev:new o.b_(Xe),u_dem_scale_prev:new o.bZ(Xe),u_dem_size:new o.bZ(Xe),u_dem_lerp:new o.bZ(Xe),u_exaggeration:new o.bZ(Xe),u_depth:new o.bX(Xe),u_depth_size_inv:new o.b_(Xe),u_depth_range_unpack:new o.b_(Xe),u_occluder_half_size:new o.bZ(Xe),u_occlusion_depth_offset:new o.bZ(Xe),u_meter_to_dem:new o.bZ(Xe),u_label_plane_matrix_inv:new o.b$(Xe)}))(g)),K.includes("GLOBE")&&(this.globeUniforms=(Xe=>({u_tile_tl_up:new o.bY(Xe),u_tile_tr_up:new o.bY(Xe),u_tile_br_up:new o.bY(Xe),u_tile_bl_up:new o.bY(Xe),u_tile_up_scale:new o.bZ(Xe)}))(g)),K.includes("FOG")&&(this.fogUniforms=(Xe=>({u_fog_matrix:new o.b$(Xe),u_fog_range:new o.b_(Xe),u_fog_color:new o.cO(Xe),u_fog_horizon_blend:new o.bZ(Xe),u_fog_vertical_limit:new o.b_(Xe),u_fog_temporal_offset:new o.bZ(Xe),u_frustum_tl:new o.bY(Xe),u_frustum_tr:new o.bY(Xe),u_frustum_br:new o.bY(Xe),u_frustum_bl:new o.bY(Xe),u_globe_pos:new o.bY(Xe),u_globe_radius:new o.bZ(Xe),u_globe_transition:new o.bZ(Xe),u_is_globe:new o.bX(Xe),u_viewport:new o.b_(Xe)}))(g)),K.includes("RENDER_CUTOFF")&&(this.cutoffUniforms=(Xe=>({u_cutoff_params:new o.cO(Xe)}))(g)),K.includes("LIGHTING_3D_MODE")&&(this.lightsUniforms=(Xe=>({u_lighting_ambient_color:new o.bY(Xe),u_lighting_directional_dir:new o.bY(Xe),u_lighting_directional_color:new o.bY(Xe),u_ground_radiance:new o.bY(Xe)}))(g)),K.includes("RENDER_SHADOWS")&&(this.shadowUniforms=(Xe=>({u_light_matrix_0:new o.b$(Xe),u_light_matrix_1:new o.b$(Xe),u_fade_range:new o.b_(Xe),u_shadow_normal_offset:new o.bY(Xe),u_shadow_intensity:new o.bZ(Xe),u_shadow_texel_size:new o.bZ(Xe),u_shadow_map_resolution:new o.bZ(Xe),u_shadow_direction:new o.bY(Xe),u_shadow_bias:new o.bY(Xe),u_shadowmap_0:new o.bX(Xe),u_shadowmap_1:new o.bX(Xe)}))(g)))}getAttributeLocation(g,C){let L=this.attributes[C];return L===void 0&&(L=this.attributes[C]=g.getAttribLocation(this.program,C)),L}setTerrainUniformValues(g,C){if(!this.terrainUniforms)return;const L=this.terrainUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const $ in C)L[$]&&L[$].set(this.program,$,C[$])}}setGlobeUniformValues(g,C){if(!this.globeUniforms)return;const L=this.globeUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const $ in C)L[$]&&L[$].set(this.program,$,C[$])}}setFogUniformValues(g,C){if(!this.fogUniforms)return;const L=this.fogUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const $ in C)L[$].set(this.program,$,C[$])}}setCutoffUniformValues(g,C){if(!this.cutoffUniforms)return;const L=this.cutoffUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const $ in C)L[$].set(this.program,$,C[$])}}setLightsUniformValues(g,C){if(!this.lightsUniforms)return;const L=this.lightsUniforms;if(!this.failedToCreate){g.program.set(this.program);for(const $ in C)L[$].set(this.program,$,C[$])}}setShadowUniformValues(g,C){if(this.failedToCreate||!this.shadowUniforms)return;const L=this.shadowUniforms;g.program.set(this.program);for(const $ in C)L[$].set(this.program,$,C[$])}_drawDebugWireframe(g,C,L,$,G,K,te,de,xe,_e){const Oe=g.options.wireframe;if(Oe.terrain===!1&&Oe.layers2D===!1&&Oe.layers3D===!1)return;const De=g.context;if(!(!(!Oe.terrain||this.name!=="terrainRaster"&&this.name!=="globeRaster")||!(!Oe.layers2D||g._terrain&&g._terrain.renderingToTexture||!vC.includes(this.name))||!(!Oe.layers3D||!e_.includes(this.name))))return;const qe=De.gl,st=g.wireframeDebugCache.getLinesFromTrianglesBuffer(g.frameCounter,G,De);if(!st)return;const Xe=[...this.fixedDefines,"DEBUG_WIREFRAME"],pt=g.getOrCreateProgram(this.name,{config:this.configuration,defines:Xe});De.program.set(pt.program);const mt=(xt,es,Ot)=>{if(es[xt]&&Ot[xt])for(const Qt in es[xt])Ot[xt][Qt]&&Ot[xt][Qt].set(Ot.program,Qt,es[xt][Qt].current)};xe&&xe.setUniforms(pt.program,De,pt.binderUniforms,te,{zoom:de}),mt("fixedUniforms",this,pt),mt("terrainUniforms",this,pt),mt("globeUniforms",this,pt),mt("fogUniforms",this,pt),mt("lightsUniforms",this,pt),mt("shadowUniforms",this,pt),st.bind(),De.setColorMode(new Qr([qe.ONE,qe.ONE_MINUS_SRC_ALPHA,qe.ZERO,qe.ONE],o.aq.transparent,[!0,!0,!0,!1])),De.setDepthMode(new nr(C.func===qe.LESS?qe.LEQUAL:C.func,nr.ReadOnly,C.range)),De.setStencilMode(ra.disabled);const kt=3*K.primitiveLength*2,Et=3*K.primitiveOffset*2*2;if(this.forceManualRenderingForInstanceIDShaders){const xt=_e||1;for(let es=0;es1?qe.drawElementsInstanced(qe.LINES,kt,qe.UNSIGNED_SHORT,Et,_e):qe.drawElements(qe.LINES,kt,qe.UNSIGNED_SHORT,Et);G.bind(),De.program.set(this.program),De.setDepthMode(C),De.setStencilMode(L),De.setColorMode($)}checkUniforms(g,C,L){if(this.fixedDefines.includes(C)){for(const $ of Object.keys(L))if(!L[$].initialized)throw new Error(`Program '${this.name}', from draw '${g}': uniform ${$} not set but required by ${C} being defined`)}}draw(g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt){const mt=g.context,kt=mt.gl;if(this.failedToCreate)return;mt.program.set(this.program),mt.setDepthMode(L),mt.setStencilMode($),mt.setColorMode(G),mt.setCullFace(K);for(const[At,Dt]of this.fixedUniformsEntries)Dt.set(this.program,At,te[At]);st&&st.setUniforms(this.program,mt,this.binderUniforms,De,{zoom:qe});const Et={[kt.POINTS]:1,[kt.LINES]:2,[kt.TRIANGLES]:3,[kt.LINE_STRIP]:1}[C];this.checkUniforms(de,"RENDER_SHADOWS",this.shadowUniforms);const xt=Xe||[],es=st?st.getPaintVertexBuffers():[],Ot=C===kt.TRIANGLES&&_e,Qt=pt&&pt>0?1:void 0;for(const At of Oe.get()){const Dt=At.vaos||(At.vaos={});if((Dt[de]||(Dt[de]=new hC)).bind(mt,this,xe,es,_e,At.vertexOffset,xt,Qt),this.forceManualRenderingForInstanceIDShaders){const Ht=pt||1;for(let gs=0;gs1?kt.drawElementsInstanced(C,At.primitiveLength*Et,kt.UNSIGNED_SHORT,At.primitiveOffset*Et*2,pt):_e?kt.drawElements(C,At.primitiveLength*Et,kt.UNSIGNED_SHORT,At.primitiveOffset*Et*2):kt.drawArrays(C,At.vertexOffset,At.vertexLength);Ot&&this._drawDebugWireframe(g,L,$,G,_e,At,De,qe,st,pt)}}}function f6(M,g,C=0){const L=Math.pow(2,g.tileID.overscaledZ),$=g.tileSize*Math.pow(2,M.transform.tileZoom)/L,G=$*(g.tileID.canonical.x+g.tileID.wrap*L),K=$*g.tileID.canonical.y;return{u_image:0,u_texsize:g.imageAtlasTexture?g.imageAtlasTexture.size:[0,0],u_tile_units_to_pixels:1/o.aA(g,1,M.transform.tileZoom),u_pixel_coord_upper:[G>>16,K>>16],u_pixel_coord_lower:[65535&G,65535&K],u_pattern_transition:C}}const BN={terrain:0,flat:1},$N=o.bb(),ph=(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt,mt,kt=[0,0,1])=>{const Et=g.style.light,xt=Et.properties.get("position"),es=[xt.x,xt.y,xt.z],Ot=o.dE();Et.properties.get("anchor")==="viewport"&&(o.dF(Ot,-g.transform.angle),o.dG(es,es,Ot));const Qt=Et.properties.get("color").toPremultipliedRenderColor(null),At=g.transform,Dt={u_matrix:M,u_lightpos:es,u_lightintensity:Et.properties.get("intensity"),u_lightcolor:[Qt.r,Qt.g,Qt.b],u_vertical_gradient:+C,u_opacity:L,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:$N,u_merc_center:[0,0],u_up_dir:[0,0,0],u_height_lift:0,u_height_type:BN[xe],u_base_type:BN[_e],u_ao:$,u_edge_radius:G,u_width_scale:K,u_flood_light_color:st,u_vertical_scale:Xe,u_flood_light_intensity:pt,u_ground_shadow_factor:mt,u_front_cutoff_params:kt};return At.projection.name==="globe"&&(Dt.u_tile_id=[te.canonical.x,te.canonical.y,1<({u_matrix:M,u_edge_radius:g,u_width_scale:C,u_vertical_scale:L,u_height_type:BN[$],u_base_type:BN[G]}),za=(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt,mt)=>{const kt=ph(M,g,C,L,$,G,K,te,xe,_e,Oe,De,qe,st,Xe,pt,1,[0,0,0]),Et={u_height_factor:-Math.pow(2,te.overscaledZ)/de.tileSize/8};return Object.assign(kt,f6(g,de,mt),Et)},p0=(M,g,C)=>({u_matrix:M,u_emissive_strength:g,u_ground_shadow_factor:C}),t_=(M,g,C,L,$,G=0)=>Object.assign(p0(M,g,$),f6(C,L,G)),bC=(M,g,C,L)=>({u_matrix:M,u_world:C,u_emissive_strength:g,u_ground_shadow_factor:L}),s_=(M,g,C,L,$,G,K=0)=>Object.assign(t_(M,g,C,L,G,K),{u_world:$}),n_=(M,g)=>({u_matrix:M,u_depth_bias:g}),Sj=(M,g)=>({u_matrix:M,u_ground_shadow_factor:g}),y1=(M,g,C,L,$)=>({u_matrix:M,u_camera_pos:[g[0],g[1],g[2]],u_depth_bias:C,u_height_scale:L,u_reset_depth:$}),Cj=(M,g,C)=>({u_image:M,u_opacity:g,u_blend_mode:C}),f0=(M,g,C,L,$,G,K,te,de,xe=[0,0,1])=>({u_matrix:M,u_normal_matrix:g,u_opacity:C,u_faux_facade_ao_intensity:L,u_camera_pos:$,u_tile_to_meter:G,u_facade_emissive_chance:K,u_flood_light_color:te,u_flood_light_intensity:de,u_front_cutoff_params:xe}),Tj=M=>({u_matrix:M}),r_=M=>({u_matrix:M}),UN=(M,g,C,L,$,G,K,te)=>{const de=o.an/G.tileSize;return{u_matrix:M,u_inv_rot_matrix:g,u_camera_to_center_distance:C.getCameraToCenterDistance(te),u_extrude_scale:[C.pixelsToGLUnits[0]/de,C.pixelsToGLUnits[1]/de],u_zoom_transition:L,u_tile_id:K,u_merc_center:$}},Rc=(M,g,C,L)=>({u_matrix:M,u_inv_matrix:g,u_camera_to_center_distance:C.getCameraToCenterDistance(L),u_viewport_size:[C.width,C.height]}),vm=(M,g,C=1)=>({u_matrix:M,u_color:g,u_overlay:0,u_overlay_scale:C}),Bp=o.bb(),qN=(M,g,C,L,$,G,K)=>{const te=M.transform,de=te.projection.name==="globe",xe=de?o.dH(te.zoom,g.canonical)*te._pixelsPerMercatorPixel:o.aA(C,1,G),_e={u_matrix:g.projMatrix,u_extrude_scale:xe,u_intensity:K,u_inv_rot_matrix:Bp,u_merc_center:[0,0],u_tile_id:[0,0,0],u_zoom_transition:0,u_up_dir:[0,0,0]};if(de){_e.u_inv_rot_matrix=L,_e.u_merc_center=$,_e.u_tile_id=[g.canonical.x,g.canonical.y,1<({u_matrix:g,u_normalize_matrix:C,u_globe_matrix:L,u_merc_matrix:$,u_grid_matrix:G,u_tl_parent:K,u_scale_parent:_e,u_fade_t:Oe.mix,u_opacity:Oe.opacity*De.paint.get("raster-opacity"),u_image0:0,u_image1:1,u_brightness_low:De.paint.get("raster-brightness-min"),u_brightness_high:De.paint.get("raster-brightness-max"),u_saturation_factor:o.dJ(De.paint.get("raster-saturation")),u_contrast_factor:o.dI(De.paint.get("raster-contrast")),u_spin_weights:x6(De.paint.get("raster-hue-rotate")),u_perspective_transform:qe,u_raster_elevation:st,u_zoom_transition:te,u_merc_center:de,u_cutoff_params:xe,u_colorization_mix:VN(o.dK,pt,kt),u_colorization_offset:ap(o.dK,mt,kt),u_color_ramp:Xe,u_texture_offset:[xt/(Et+2*xt),Et/(Et+2*xt)],u_texture_res:[Et+2*xt,Et+2*xt],u_emissive_strength:es,u_zbias_factor:HN(M)});function x6(M){M*=Math.PI/180;const g=Math.sin(M),C=Math.cos(M);return[(2*C+1)/3,(-Math.sqrt(3)*g-C+1)/3,(Math.sqrt(3)*g-C+1)/3]}const vx=.05,g6=(M,g,C,L,$,G,K,te,de,xe,_e,Oe)=>({u_matrix:M,u_normalize_matrix:g,u_globe_matrix:C,u_merc_matrix:L,u_grid_matrix:$,u_tl_parent:G,u_scale_parent:xe,u_fade_t:_e.mix,u_opacity:_e.opacity,u_image0:0,u_image1:1,u_raster_elevation:Oe,u_zoom_transition:K,u_merc_center:te,u_cutoff_params:de}),y6=(M,g,C,L,$,G,K,te,de,xe)=>({u_particle_texture:M,u_particle_texture_side_len:g,u_tile_offset:C,u_velocity:L,u_color_ramp:G,u_velocity_res:$,u_max_speed:K,u_uv_offset:te,u_data_scale:[255*de[0],255*de[1]],u_data_offset:xe,u_particle_pos_scale:1.1,u_particle_pos_offset:[vx,vx]}),_C=(M,g,C,L,$,G,K,te,de,xe)=>({u_particle_texture:M,u_particle_texture_side_len:g,u_velocity:C,u_velocity_res:L,u_max_speed:$,u_speed_factor:G,u_reset_rate:K,u_rand_seed:Math.random(),u_uv_offset:te,u_data_scale:[255*de[0],255*de[1]],u_data_offset:xe,u_particle_pos_scale:1.1,u_particle_pos_offset:[vx,vx]}),Ej=o.bb(),v1=(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt,mt,kt,Et,xt,es,Ot,Qt)=>{const At=$.transform,Dt={u_is_size_zoom_constant:+(M==="constant"||M==="source"),u_is_size_feature_constant:+(M==="constant"||M==="camera"),u_size_t:g?g.uSizeT:0,u_size:g?g.uSize:0,u_camera_to_center_distance:At.getCameraToCenterDistance(kt),u_rotate_symbol:+C,u_aspect_ratio:At.width/At.height,u_fade_change:$.options.fadeDuration?$.symbolFadeChange:1,u_matrix:G,u_label_plane_matrix:K,u_coord_matrix:te,u_is_text:+xe,u_elevation_from_sea:de?1:0,u_pitch_with_map:+L,u_texsize:_e,u_texsize_icon:Oe,u_texture:0,u_texture_icon:1,u_tile_id:[0,0,0],u_zoom_transition:0,u_inv_rot_matrix:Ej,u_merc_center:[0,0],u_camera_forward:[0,0,0],u_ecef_origin:[0,0,0],u_tile_matrix:Ej,u_up_vector:[0,-1,0],u_color_adj_mat:es,u_icon_transition:Ot||0,u_gamma_scale:L?$.transform.getCameraToCenterDistance(kt)*Math.cos($.terrain?0:$.transform._pitch):1,u_device_pixel_ratio:o.o.devicePixelRatio,u_is_halo:1,u_scale_factor:Qt||1,u_ground_shadow_factor:Et,u_inv_matrix:o.b7(o.bb(),K),u_normal_scale:xt,u_lutTexture:10,u_zoom:At.zoom-Math.floor(At.zoom),u_spp_fill_np_color:[0,0,0,1],u_spp_halo_np_color:[0,0,0,0],u_spp_opacity:1,u_spp_halo_width:0,u_spp_halo_blur:0,u_spp_emissive_strength:0,u_spp_occlusion_opacity:1,u_spp_z_offset:0,u_spp_translate_rotation:[1,0]};return kt.name==="globe"&&(Dt.u_tile_id=[qe.canonical.x,qe.canonical.y,1<({u_matrix:M,u_emissive_strength:g,u_opacity:C,u_color:L}),bx=(M,g,C,L,$,G,K,te,de)=>Object.assign(function(xe,_e,Oe,De,qe,st){const{width:Xe,height:pt}=De.imageManager.getPixelSize(_e),mt=Math.pow(2,st.tileID.overscaledZ),kt=st.tileSize*Math.pow(2,De.transform.tileZoom)/mt,Et=kt*(st.tileID.canonical.x+st.tileID.wrap*mt),xt=kt*st.tileID.canonical.y;return{u_image:0,u_pattern_tl:Oe.tl,u_pattern_br:Oe.br,u_texsize:[Xe,pt],u_pattern_size:Oe.displaySize,u_pattern_units_to_pixels:qe?[De.transform.width,-1*De.transform.height]:[1/o.aA(st,1,De.transform.tileZoom),1/o.aA(st,1,De.transform.tileZoom)],u_pixel_coord_upper:[Et>>16,xt>>16],u_pixel_coord_lower:[65535&Et,65535&xt]}}(0,G,K,L,te,de),{u_matrix:M,u_emissive_strength:g,u_opacity:C}),x0=new Float32Array(o.b9([])),_x=(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe=[0,0,0],st,Xe,pt)=>{const mt=$.style.light,kt=mt.properties.get("position"),Et=[-kt.x,-kt.y,kt.z],xt=o.dE();mt.properties.get("anchor")==="viewport"&&(o.dF(xt,-$.transform.angle),o.dG(Et,Et,xt));const es=_e.alphaMode==="MASK",Ot=mt.properties.get("color").toNonPremultipliedRenderColor(null),Qt=De.paint.get("model-ambient-occlusion-intensity"),At=De.paint.get("model-color").constantOr(o.aq.white).toNonPremultipliedRenderColor(null);return At.a=De.paint.get("model-color-mix-intensity").constantOr(0),pt&&(At.r=pt[0],At.g=pt[1],At.b=pt[2],At.a=pt[3]),Xe&&(At.r=Xe.color.r,At.g=Xe.color.g,At.b=Xe.color.b,At.a=Xe.colorMix,Oe=Xe.emissionStrength,G*=Xe.opacity),{u_matrix:M,u_lighting_matrix:g,u_normal_matrix:C,u_node_matrix:L||x0,u_lightpos:Et,u_lightintensity:mt.properties.get("intensity"),u_lightcolor:[Ot.r,Ot.g,Ot.b],u_camera_pos:qe,u_opacity:G,u_baseTextureIsAlpha:0,u_alphaMask:+es,u_alphaCutoff:_e.alphaCutoff,u_baseColorFactor:K.toNonPremultipliedRenderColor(null).toArray01(),u_emissiveFactor:te.toNonPremultipliedRenderColor(null).toArray01(),u_metallicFactor:de,u_roughnessFactor:xe,u_baseColorTexture:5,u_metallicRoughnessTexture:6,u_normalTexture:7,u_occlusionTexture:8,u_emissionTexture:9,u_lutTexture:10,u_color_mix:At.toArray01(),u_aoIntensity:Qt,u_emissive_strength:Oe,u_occlusionTextureTransform:st||[0,0,0,0]}},Aj=(M,g=x0,C=x0)=>({u_matrix:M,u_instance:g,u_node_matrix:C}),a_={fillExtrusion:M=>({u_matrix:new o.b$(M),u_lightpos:new o.bY(M),u_lightintensity:new o.bZ(M),u_lightcolor:new o.bY(M),u_vertical_gradient:new o.bZ(M),u_opacity:new o.bZ(M),u_edge_radius:new o.bZ(M),u_width_scale:new o.bZ(M),u_ao:new o.b_(M),u_height_type:new o.bX(M),u_base_type:new o.bX(M),u_tile_id:new o.bY(M),u_zoom_transition:new o.bZ(M),u_inv_rot_matrix:new o.b$(M),u_merc_center:new o.b_(M),u_up_dir:new o.bY(M),u_height_lift:new o.bZ(M),u_flood_light_color:new o.bY(M),u_vertical_scale:new o.bZ(M),u_flood_light_intensity:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_front_cutoff_params:new o.bY(M)}),fillExtrusionDepth:M=>({u_matrix:new o.b$(M),u_edge_radius:new o.bZ(M),u_width_scale:new o.bZ(M),u_vertical_scale:new o.bZ(M),u_height_type:new o.bX(M),u_base_type:new o.bX(M)}),fillExtrusionPattern:M=>({u_matrix:new o.b$(M),u_lightpos:new o.bY(M),u_lightintensity:new o.bZ(M),u_lightcolor:new o.bY(M),u_vertical_gradient:new o.bZ(M),u_height_factor:new o.bZ(M),u_edge_radius:new o.bZ(M),u_width_scale:new o.bZ(M),u_ao:new o.b_(M),u_height_type:new o.bX(M),u_base_type:new o.bX(M),u_tile_id:new o.bY(M),u_zoom_transition:new o.bZ(M),u_inv_rot_matrix:new o.b$(M),u_merc_center:new o.b_(M),u_up_dir:new o.bY(M),u_height_lift:new o.bZ(M),u_image:new o.bX(M),u_texsize:new o.b_(M),u_pixel_coord_upper:new o.b_(M),u_pixel_coord_lower:new o.b_(M),u_tile_units_to_pixels:new o.bZ(M),u_opacity:new o.bZ(M),u_pattern_transition:new o.bZ(M)}),fillExtrusionGroundEffect:M=>({u_matrix:new o.b$(M),u_opacity:new o.bZ(M),u_ao_pass:new o.bZ(M),u_meter_to_tile:new o.bZ(M),u_ao:new o.b_(M),u_flood_light_intensity:new o.bZ(M),u_flood_light_color:new o.bY(M),u_attenuation:new o.bZ(M),u_edge_radius:new o.bZ(M),u_fb:new o.bX(M),u_fb_size:new o.bZ(M),u_dynamic_offset:new o.bZ(M)}),fill:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_ground_shadow_factor:new o.bY(M)}),fillPattern:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_image:new o.bX(M),u_texsize:new o.b_(M),u_pixel_coord_upper:new o.b_(M),u_pixel_coord_lower:new o.b_(M),u_tile_units_to_pixels:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_pattern_transition:new o.bZ(M)}),fillOutline:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_world:new o.b_(M),u_ground_shadow_factor:new o.bY(M)}),fillOutlinePattern:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_world:new o.b_(M),u_image:new o.bX(M),u_texsize:new o.b_(M),u_pixel_coord_upper:new o.b_(M),u_pixel_coord_lower:new o.b_(M),u_tile_units_to_pixels:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_pattern_transition:new o.bZ(M)}),lineBlendComposite:M=>({u_image:new o.bX(M),u_opacity:new o.bZ(M),u_blend_mode:new o.bX(M)}),building:M=>({u_matrix:new o.b$(M),u_normal_matrix:new o.b$(M),u_opacity:new o.bZ(M),u_faux_facade_ao_intensity:new o.bZ(M),u_camera_pos:new o.bY(M),u_tile_to_meter:new o.bZ(M),u_facade_emissive_chance:new o.bZ(M),u_flood_light_color:new o.bY(M),u_flood_light_intensity:new o.bZ(M),u_front_cutoff_params:new o.bY(M)}),buildingBloom:M=>({u_matrix:new o.b$(M)}),buildingDepth:M=>({u_matrix:new o.b$(M)}),elevatedStructuresDepth:M=>({u_matrix:new o.b$(M),u_depth_bias:new o.bZ(M)}),elevatedStructures:M=>({u_matrix:new o.b$(M),u_ground_shadow_factor:new o.bY(M)}),elevatedStructuresDepthReconstruct:M=>({u_matrix:new o.b$(M),u_camera_pos:new o.bY(M),u_depth_bias:new o.bZ(M),u_height_scale:new o.bZ(M),u_reset_depth:new o.bZ(M)}),circle:o.dO,collisionBox:M=>({u_matrix:new o.b$(M),u_inv_rot_matrix:new o.b$(M),u_camera_to_center_distance:new o.bZ(M),u_extrude_scale:new o.b_(M),u_zoom_transition:new o.bZ(M),u_merc_center:new o.b_(M),u_tile_id:new o.bY(M)}),collisionCircle:M=>({u_matrix:new o.b$(M),u_inv_matrix:new o.b$(M),u_camera_to_center_distance:new o.bZ(M),u_viewport_size:new o.b_(M)}),debug:M=>({u_color:new o.dl(M),u_matrix:new o.b$(M),u_overlay:new o.bX(M),u_overlay_scale:new o.bZ(M)}),clippingMask:M=>({u_matrix:new o.b$(M)}),heatmap:M=>({u_extrude_scale:new o.bZ(M),u_intensity:new o.bZ(M),u_matrix:new o.b$(M),u_inv_rot_matrix:new o.b$(M),u_merc_center:new o.b_(M),u_tile_id:new o.bY(M),u_zoom_transition:new o.bZ(M),u_up_dir:new o.bY(M)}),heatmapTexture:M=>({u_image:new o.bX(M),u_color_ramp:new o.bX(M),u_opacity:new o.bZ(M)}),hillshade:M=>({u_matrix:new o.b$(M),u_image:new o.bX(M),u_latrange:new o.b_(M),u_light:new o.b_(M),u_shadow:new o.dl(M),u_highlight:new o.dl(M),u_emissive_strength:new o.bZ(M),u_accent:new o.dl(M)}),hillshadePrepare:M=>({u_matrix:new o.b$(M),u_image:new o.bX(M),u_dimension:new o.b_(M),u_zoom:new o.bZ(M)}),line:o.dN,linePattern:o.dM,raster:M=>({u_matrix:new o.b$(M),u_normalize_matrix:new o.b$(M),u_globe_matrix:new o.b$(M),u_merc_matrix:new o.b$(M),u_grid_matrix:new o.dm(M),u_tl_parent:new o.b_(M),u_scale_parent:new o.bZ(M),u_fade_t:new o.bZ(M),u_opacity:new o.bZ(M),u_image0:new o.bX(M),u_image1:new o.bX(M),u_brightness_low:new o.bZ(M),u_brightness_high:new o.bZ(M),u_saturation_factor:new o.bZ(M),u_contrast_factor:new o.bZ(M),u_spin_weights:new o.bY(M),u_perspective_transform:new o.b_(M),u_raster_elevation:new o.bZ(M),u_zoom_transition:new o.bZ(M),u_merc_center:new o.b_(M),u_cutoff_params:new o.cO(M),u_colorization_mix:new o.cO(M),u_colorization_offset:new o.bZ(M),u_color_ramp:new o.bX(M),u_texture_offset:new o.b_(M),u_texture_res:new o.b_(M),u_emissive_strength:new o.bZ(M),u_zbias_factor:new o.bZ(M)}),rasterParticle:M=>({u_matrix:new o.b$(M),u_normalize_matrix:new o.b$(M),u_globe_matrix:new o.b$(M),u_merc_matrix:new o.b$(M),u_grid_matrix:new o.dm(M),u_tl_parent:new o.b_(M),u_scale_parent:new o.bZ(M),u_fade_t:new o.bZ(M),u_opacity:new o.bZ(M),u_image0:new o.bX(M),u_image1:new o.bX(M),u_raster_elevation:new o.bZ(M),u_zoom_transition:new o.bZ(M),u_merc_center:new o.b_(M),u_cutoff_params:new o.cO(M)}),rasterParticleTexture:M=>({u_texture:new o.bX(M),u_opacity:new o.bZ(M)}),rasterParticleDraw:M=>({u_particle_texture:new o.bX(M),u_particle_texture_side_len:new o.bZ(M),u_tile_offset:new o.b_(M),u_velocity:new o.bX(M),u_color_ramp:new o.bX(M),u_velocity_res:new o.b_(M),u_max_speed:new o.bZ(M),u_uv_offset:new o.b_(M),u_data_scale:new o.b_(M),u_data_offset:new o.bZ(M),u_particle_pos_scale:new o.bZ(M),u_particle_pos_offset:new o.b_(M)}),rasterParticleUpdate:M=>({u_particle_texture:new o.bX(M),u_particle_texture_side_len:new o.bZ(M),u_velocity:new o.bX(M),u_velocity_res:new o.b_(M),u_max_speed:new o.bZ(M),u_speed_factor:new o.bZ(M),u_reset_rate:new o.bZ(M),u_rand_seed:new o.bZ(M),u_uv_offset:new o.b_(M),u_data_scale:new o.b_(M),u_data_offset:new o.bZ(M),u_particle_pos_scale:new o.bZ(M),u_particle_pos_offset:new o.b_(M)}),symbol:M=>({u_is_size_zoom_constant:new o.bX(M),u_is_size_feature_constant:new o.bX(M),u_size_t:new o.bZ(M),u_size:new o.bZ(M),u_camera_to_center_distance:new o.bZ(M),u_rotate_symbol:new o.bX(M),u_aspect_ratio:new o.bZ(M),u_fade_change:new o.bZ(M),u_matrix:new o.b$(M),u_label_plane_matrix:new o.b$(M),u_coord_matrix:new o.b$(M),u_is_text:new o.bX(M),u_elevation_from_sea:new o.bX(M),u_pitch_with_map:new o.bX(M),u_texsize:new o.b_(M),u_texsize_icon:new o.b_(M),u_texture:new o.bX(M),u_texture_icon:new o.bX(M),u_gamma_scale:new o.bZ(M),u_device_pixel_ratio:new o.bZ(M),u_tile_id:new o.bY(M),u_zoom_transition:new o.bZ(M),u_inv_rot_matrix:new o.b$(M),u_merc_center:new o.b_(M),u_camera_forward:new o.bY(M),u_tile_matrix:new o.b$(M),u_up_vector:new o.bY(M),u_ecef_origin:new o.bY(M),u_is_halo:new o.bX(M),u_icon_transition:new o.bZ(M),u_color_adj_mat:new o.b$(M),u_scale_factor:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_inv_matrix:new o.b$(M),u_normal_scale:new o.bZ(M),u_lutTexture:new o.bX(M),u_zoom:new o.bZ(M),u_spp_fill_np_color:new o.cO(M),u_spp_halo_np_color:new o.cO(M),u_spp_opacity:new o.bZ(M),u_spp_halo_width:new o.bZ(M),u_spp_halo_blur:new o.bZ(M),u_spp_emissive_strength:new o.bZ(M),u_spp_occlusion_opacity:new o.bZ(M),u_spp_z_offset:new o.bZ(M),u_spp_translate_rotation:new o.b_(M)}),background:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_opacity:new o.bZ(M),u_color:new o.dl(M)}),backgroundPattern:M=>({u_matrix:new o.b$(M),u_emissive_strength:new o.bZ(M),u_opacity:new o.bZ(M),u_image:new o.bX(M),u_pattern_tl:new o.b_(M),u_pattern_br:new o.b_(M),u_texsize:new o.b_(M),u_pattern_size:new o.b_(M),u_pixel_coord_upper:new o.b_(M),u_pixel_coord_lower:new o.b_(M),u_pattern_units_to_pixels:new o.b_(M)}),terrainRaster:M=>({u_matrix:new o.b$(M),u_image0:new o.bX(M),u_image1:new o.bX(M),u_skirt_height:new o.bZ(M),u_ground_shadow_factor:new o.bY(M),u_emissive_texture_available:new o.bZ(M)}),skybox:M=>({u_matrix:new o.b$(M),u_sun_direction:new o.bY(M),u_cubemap:new o.bX(M),u_opacity:new o.bZ(M),u_temporal_offset:new o.bZ(M)}),skyboxGradient:M=>({u_matrix:new o.b$(M),u_color_ramp:new o.bX(M),u_center_direction:new o.bY(M),u_radius:new o.bZ(M),u_opacity:new o.bZ(M),u_temporal_offset:new o.bZ(M)}),skyboxCapture:M=>({u_matrix_3f:new o.dm(M),u_sun_direction:new o.bY(M),u_sun_intensity:new o.bZ(M),u_color_tint_r:new o.cO(M),u_color_tint_m:new o.cO(M),u_luminance:new o.bZ(M)}),globeRaster:M=>({u_proj_matrix:new o.b$(M),u_globe_matrix:new o.b$(M),u_normalize_matrix:new o.b$(M),u_merc_matrix:new o.b$(M),u_zoom_transition:new o.bZ(M),u_merc_center:new o.b_(M),u_image0:new o.bX(M),u_image1:new o.bX(M),u_grid_matrix:new o.dm(M),u_skirt_height:new o.bZ(M),u_far_z_cutoff:new o.bZ(M),u_frustum_tl:new o.bY(M),u_frustum_tr:new o.bY(M),u_frustum_br:new o.bY(M),u_frustum_bl:new o.bY(M),u_globe_pos:new o.bY(M),u_globe_radius:new o.bZ(M),u_viewport:new o.b_(M),u_emissive_texture_available:new o.bZ(M)}),globeAtmosphere:M=>({u_frustum_tl:new o.bY(M),u_frustum_tr:new o.bY(M),u_frustum_br:new o.bY(M),u_frustum_bl:new o.bY(M),u_horizon:new o.bZ(M),u_transition:new o.bZ(M),u_fadeout_range:new o.bZ(M),u_atmosphere_fog_color:new o.cO(M),u_high_color:new o.cO(M),u_space_color:new o.cO(M),u_temporal_offset:new o.bZ(M),u_horizon_angle:new o.bZ(M)}),model:M=>({u_matrix:new o.b$(M),u_lighting_matrix:new o.b$(M),u_normal_matrix:new o.b$(M),u_node_matrix:new o.b$(M),u_lightpos:new o.bY(M),u_lightintensity:new o.bZ(M),u_lightcolor:new o.bY(M),u_camera_pos:new o.bY(M),u_opacity:new o.bZ(M),u_baseColorFactor:new o.cO(M),u_emissiveFactor:new o.cO(M),u_metallicFactor:new o.bZ(M),u_roughnessFactor:new o.bZ(M),u_baseTextureIsAlpha:new o.bX(M),u_alphaMask:new o.bX(M),u_alphaCutoff:new o.bZ(M),u_baseColorTexture:new o.bX(M),u_metallicRoughnessTexture:new o.bX(M),u_normalTexture:new o.bX(M),u_occlusionTexture:new o.bX(M),u_emissionTexture:new o.bX(M),u_lutTexture:new o.bX(M),u_color_mix:new o.cO(M),u_aoIntensity:new o.bZ(M),u_emissive_strength:new o.bZ(M),u_occlusionTextureTransform:new o.cO(M)}),modelDepth:M=>({u_matrix:new o.b$(M),u_instance:new o.b$(M),u_node_matrix:new o.b$(M)}),groundShadow:M=>({u_matrix:new o.b$(M),u_ground_shadow_factor:new o.bY(M)}),stars:M=>({u_matrix:new o.b$(M),u_up:new o.bY(M),u_right:new o.bY(M),u_intensity_multiplier:new o.bZ(M)}),snowParticle:M=>({u_modelview:new o.b$(M),u_projection:new o.b$(M),u_time:new o.bZ(M),u_cam_pos:new o.bY(M),u_velocityConeAperture:new o.bZ(M),u_velocity:new o.bZ(M),u_horizontalOscillationRadius:new o.bZ(M),u_horizontalOscillationRate:new o.bZ(M),u_boxSize:new o.bZ(M),u_billboardSize:new o.bZ(M),u_simpleShapeParameters:new o.b_(M),u_screenSize:new o.b_(M),u_thinningCenterPos:new o.b_(M),u_thinningShape:new o.bY(M),u_thinningAffectedRatio:new o.bZ(M),u_thinningParticleOffset:new o.bZ(M),u_particleColor:new o.cO(M),u_direction:new o.bY(M)}),rainParticle:M=>({u_modelview:new o.b$(M),u_projection:new o.b$(M),u_time:new o.bZ(M),u_cam_pos:new o.bY(M),u_texScreen:new o.bX(M),u_velocityConeAperture:new o.bZ(M),u_velocity:new o.bZ(M),u_boxSize:new o.bZ(M),u_rainDropletSize:new o.b_(M),u_distortionStrength:new o.bZ(M),u_rainDirection:new o.bY(M),u_color:new o.cO(M),u_screenSize:new o.b_(M),u_thinningCenterPos:new o.b_(M),u_thinningShape:new o.bY(M),u_thinningAffectedRatio:new o.bZ(M),u_thinningParticleOffset:new o.bZ(M),u_shapeDirectionalPower:new o.bZ(M),u_shapeNormalPower:new o.bZ(M),u_mode:new o.bZ(M)}),vignette:M=>({u_vignetteShape:new o.bY(M),u_vignetteColor:new o.cO(M)}),occlusion:M=>({u_matrix:new o.b$(M),u_anchorPos:new o.bY(M),u_screenSizePx:new o.b_(M),u_occluderSizePx:new o.b_(M),u_color:new o.cO(M)})};class $p{constructor(g,C,L,$){this.id=$p.uniqueIdxCounter,$p.uniqueIdxCounter++,this.context=g;const G=g.gl;this.buffer=G.createBuffer(),this.dynamicDraw=!!L,this.context.unbindVAO(),g.bindElementBuffer.set(this.buffer),G.bufferData(G.ELEMENT_ARRAY_BUFFER,C.arrayBuffer,this.dynamicDraw?G.DYNAMIC_DRAW:G.STATIC_DRAW),this.dynamicDraw||$||C.destroy()}bind(){this.context.bindElementBuffer.set(this.buffer)}updateData(g){this.id=$p.uniqueIdxCounter,$p.uniqueIdxCounter++;const C=this.context.gl;this.context.unbindVAO(),this.bind(),C.bufferSubData(C.ELEMENT_ARRAY_BUFFER,0,g.arrayBuffer)}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}$p.uniqueIdxCounter=0;const GN={Int8:"BYTE",Uint8:"UNSIGNED_BYTE",Int16:"SHORT",Uint16:"UNSIGNED_SHORT",Int32:"INT",Uint32:"UNSIGNED_INT",Float32:"FLOAT"};class WN{constructor(g,C,L,$,G,K){this.length=C.length,this.attributes=L,this.itemSize=C.bytesPerElement,this.dynamicDraw=$,this.instanceCount=K,this.context=g;const te=g.gl;this.buffer=te.createBuffer(),g.bindVertexBuffer.set(this.buffer),te.bufferData(te.ARRAY_BUFFER,C.arrayBuffer,this.dynamicDraw?te.DYNAMIC_DRAW:te.STATIC_DRAW),this.dynamicDraw||G||C.destroy()}bind(){this.context.bindVertexBuffer.set(this.buffer)}updateData(g){const C=this.context.gl;this.bind(),C.bufferSubData(C.ARRAY_BUFFER,0,g.arrayBuffer)}enableAttributes(g,C){for(const L of this.attributes){const $=C.getAttributeLocation(g,L.name);$!==-1&&g.enableVertexAttribArray($)}}setVertexAttribPointers(g,C,L){for(const $ of this.attributes){const G=C.getAttributeLocation(g,$.name);if(G!==-1){const K=$.offset+this.itemSize*(L||0);$.type==="Float32"?g.vertexAttribPointer(G,$.components,g.FLOAT,!1,this.itemSize,K):g.vertexAttribIPointer(G,$.components,g[GN[$.type]],this.itemSize,K)}}}setVertexAttribDivisor(g,C,L){for(let $=0;$0&&g.vertexAttribDivisor(G,L)}}destroy(){this.buffer&&(this.context.gl.deleteBuffer(this.buffer),delete this.buffer)}}class Mj{constructor(g,C,L,$,G){this.context=g,this.width=C,this.height=L;const K=this.framebuffer=g.gl.createFramebuffer();$>0&&(this.colorAttachment0=new p1(g,K,0)),$>1&&(this.colorAttachment1=new p1(g,K,1)),G&&(this.depthAttachmentType=G,this.depthAttachment=G==="renderbuffer"?new jj(g,K):new zN(g,K))}static createWithTexture(g,C,L,$,G){const K=g.gl;if(g.activeTexture.set(K.TEXTURE1),g.viewport.set([0,0,L,$]),C&&C.width===L&&C.height===$)return K.bindTexture(K.TEXTURE_2D,C.colorAttachment0.get()),g.bindFramebuffer.set(C.framebuffer),C;C&&C.destroy();const te=new o.T(g,{width:L,height:$,data:null},g.extRenderToTextureHalfFloat?g.gl.RGBA16F:g.gl.RGBA8);te.bind(K.LINEAR,K.CLAMP_TO_EDGE);const de=g.createFramebuffer(L,$,1,null);if(de.colorAttachment0.set(te.texture),G){const xe=g.createRenderbuffer(K.DEPTH24_STENCIL8,L,$);g.bindFramebuffer.set(de.framebuffer),K.framebufferRenderbuffer(K.FRAMEBUFFER,K.DEPTH_STENCIL_ATTACHMENT,K.RENDERBUFFER,xe),de._stencilRbo=xe}return de}createColorAttachment(g,C){C===0?this.colorAttachment0=new p1(g,this.framebuffer,0):C===1&&(this.colorAttachment1=new p1(g,this.framebuffer,1))}removeColorAttachment(g,C){const L=this.context.gl;let $;C===0?($=this.colorAttachment0.get(),this.colorAttachment0=void 0):C===1&&($=this.colorAttachment1.get(),this.colorAttachment1=void 0),$&&L.deleteTexture($)}destroy(){const g=this.context.gl;if(this.colorAttachment0){const C=this.colorAttachment0.get();C&&g.deleteTexture(C)}if(this.colorAttachment1){const C=this.colorAttachment1.get();C&&g.deleteTexture(C)}if(this.depthAttachment&&this.depthAttachmentType)if(this.depthAttachmentType==="renderbuffer"){const C=this.depthAttachment.get();C&&g.deleteRenderbuffer(C)}else{const C=this.depthAttachment.get();C&&g.deleteTexture(C)}this._stencilRbo&&(g.deleteRenderbuffer(this._stencilRbo),this._stencilRbo=null),g.deleteFramebuffer(this.framebuffer)}}class g0{constructor(g,C){this.gl=g,this.clearColor=new fj(this),this.clearDepth=new IR(this),this.clearStencil=new LN(this),this.colorMask=new PR(this),this.depthMask=new Df(this),this.stencilMask=new xj(this),this.stencilFunc=new u1(this),this.stencilOp=new DN(this),this.stencilTest=new zy(this),this.depthRange=new By(this),this.depthTest=new $y(this),this.depthFunc=new gm(this),this.blend=new RN(this),this.blendFunc=new gj(this),this.blendColor=new u6(this),this.blendEquation=new h1(this),this.cullFace=new yj(this),this.cullFaceSide=new vj(this),this.frontFace=new ON(this),this.program=new bj(this),this.activeTexture=new _j(this),this.viewport=new ym(this),this.bindFramebuffer=new zh(this),this.bindRenderbuffer=new fC(this),this.bindTexture=new m1(this),this.bindVertexBuffer=new xC(this),this.bindElementBuffer=new h6(this),this.bindVertexArrayOES=new m6(this),this.pixelStoreUnpack=new gC(this),this.pixelStoreUnpackPremultiplyAlpha=new FN(this),this.pixelStoreUnpackFlipY=new wj(this),this.options=C?Object.assign({},C):{},this.options.extTextureFilterAnisotropicForceOff||(this.extTextureFilterAnisotropic=g.getExtension("EXT_texture_filter_anisotropic")||g.getExtension("MOZ_EXT_texture_filter_anisotropic")||g.getExtension("WEBKIT_EXT_texture_filter_anisotropic"),this.extTextureFilterAnisotropic&&(this.extTextureFilterAnisotropicMax=g.getParameter(this.extTextureFilterAnisotropic.MAX_TEXTURE_MAX_ANISOTROPY_EXT))),this.extDebugRendererInfo=g.getExtension("WEBGL_debug_renderer_info"),this.extDebugRendererInfo&&(this.renderer=g.getParameter(this.extDebugRendererInfo.UNMASKED_RENDERER_WEBGL),this.vendor=g.getParameter(this.extDebugRendererInfo.UNMASKED_VENDOR_WEBGL)),this.forceManualRenderingForInstanceIDShaders=C&&!!C.forceManualRenderingForInstanceIDShaders||this.renderer&&this.renderer.indexOf("PowerVR")!==-1,this.disableSymbolUBO=C&&!!C.forceDisableSymbolUBO,this.options.extTextureFloatLinearForceOff||(this.extTextureFloatLinear=g.getExtension("OES_texture_float_linear")),this.extRenderToTextureHalfFloat=g.getExtension("EXT_color_buffer_half_float"),this.extTimerQuery=g.getExtension("EXT_disjoint_timer_query_webgl2"),this.maxTextureSize=g.getParameter(g.MAX_TEXTURE_SIZE),this.maxUniformBlockSize=Math.min(g.getParameter(g.MAX_UNIFORM_BLOCK_SIZE),32768),this.maxUniformBufferBindings=g.getParameter(g.MAX_UNIFORM_BUFFER_BINDINGS),this.extBlendFuncExtended=g.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(g,C,L){return new $p(this,g,C,L)}createVertexBuffer(g,C,L,$,G){return new WN(this,g,C,L,$,G)}createRenderbuffer(g,C,L){const $=this.gl,G=$.createRenderbuffer();return this.bindRenderbuffer.set(G),$.renderbufferStorage($.RENDERBUFFER,g,C,L),this.bindRenderbuffer.set(null),G}createFramebuffer(g,C,L,$){return new Mj(this,g,C,L,$)}clear({color:g,depth:C,stencil:L,colorMask:$}){const G=this.gl;let K=0;g&&(K|=G.COLOR_BUFFER_BIT,this.clearColor.set(g.toNonPremultipliedRenderColor(null)),this.colorMask.set($||[!0,!0,!0,!0])),C!==void 0&&(K|=G.DEPTH_BUFFER_BIT,this.depthRange.set([0,1]),this.clearDepth.set(C),this.depthMask.set(!0)),L!==void 0&&(K|=G.STENCIL_BUFFER_BIT,this.clearStencil.set(L),this.stencilMask.set(255)),G.clear(K)}setCullFace(g){g.enable===!1?this.cullFace.set(!1):(this.cullFace.set(!0),this.cullFaceSide.set(g.mode),this.frontFace.set(g.frontFace))}setDepthMode(g){g.func!==this.gl.ALWAYS||g.mask?(this.depthTest.set(!0),this.depthFunc.set(g.func),this.depthMask.set(g.mask),this.depthRange.set(g.range)):this.depthTest.set(!1)}setStencilMode(g){g.test.func!==this.gl.ALWAYS||g.mask?(this.stencilTest.set(!0),this.stencilMask.set(g.mask),this.stencilOp.set([g.fail,g.depthFail,g.pass]),this.stencilFunc.set({func:g.test.func,ref:g.ref,mask:g.test.mask})):this.stencilTest.set(!1)}setColorMode(g){o.b6(g.blendFunction,Qr.Replace)?this.blend.set(!1):(this.blend.set(!0),this.blendFunc.set(g.blendFunction),this.blendColor.set(g.blendColor),g.blendEquation?this.blendEquation.set(g.blendEquation):this.blendEquation.setDefault()),this.colorMask.set(g.mask)}unbindVAO(){this.bindVertexArrayOES.set(null)}}let y0;function Kn(M,g,C,L,$,G,K){const te=M.context,de=te.gl,xe=M.transform,_e=[o.aH(xe.center.lng),o.aL(xe.center.lat)],Oe=C.layout.get("symbol-placement"),De=C.layout.get("text-variable-anchor"),qe=C.layout.get("icon-rotation-alignment")==="map",st=C.layout.get("text-rotation-alignment")==="map",Xe=Oe!=="point",pt=[];let mt=0,kt=0;for(let At=0;At0){const Nr=o.bb(),rr=kn;o.cz(Nr,gs.placementInvProjMatrix,xe.glCoordMatrix),o.cz(Nr,Nr,gs.placementViewportMatrix),pt.push({circleArray:cn,circleOffset:kt,transform:rr,invTransform:Nr,projection:gs.getProjection()}),mt+=cn.length/4,kt=mt}if(!Sn)continue;M.terrain&&M.terrain.setupElevationDraw(Ht,Dn);const ur=Us?[Dt.canonical.x,Dt.canonical.y,1<=0&&(qe[Et.associatedIconIndex]={x:ss,y:Bs,z:Ps,angle:Fs})}else ai(Ot,Oe)}if(xe){De.clear();const kt=M.icon.placedSymbolArray;for(let Et=0;Et{let Na=[0,0,0];if(zi){const cl=M.style.directionalLight,vo=M.style.ambientLight;cl&&vo&&(Na=Op(M.style,cl,vo))}return Na},Ha=zi=>{if(M.context.disableSymbolUBO)return;zi.push("USE_PAINT_PROPERTIES_UBO");const Na=Math.floor(M.context.maxUniformBlockSize/4),cl=Math.floor(Na/4);zi.push(`MAX_UBO_SIZE_VEC4 ${cl}u`)},pa=zi=>{Dt.depthOcclusionForSymbolsAndCircles&&(C.hasOcclusionOpacityProperties||M.terrain)&&(zi.push("DEPTH_D24"),zi.push("DEPTH_OCCLUSION"))},Ci=zi=>{C.lut&&!Ot&&(C.lut.texture||(C.lut.texture=new o.dR(M.context,C.lut.image,[C.lut.image.height,C.lut.image.height,C.lut.image.height],Qt.gl.RGBA8)),Qt.activeTexture.set(Qt.gl.TEXTURE0+10),C.lut.texture&&C.lut.texture.bind(Qt.gl.LINEAR,Qt.gl.CLAMP_TO_EDGE),zi.push("APPLY_LUT_ON_GPU"))},yo=()=>{const zi=Ht&&C.layout.get("symbol-placement")!=="point",Na=[];pa(Na),Ci(Na);const cl=zi||va,vo=cn.elevationType==="road",vc=M.shadowRenderer,ii=vo&&ss&&!!vc&&vc.enabled,ko=Vr(ii),Zc=vo&&ss&&!M.terrain?Ns:hn,gh=C.paint.get("icon-image-cross-fade");M.terrainRenderModeElevated()&&ss&&Na.push("PITCH_WITH_MAP_TERRAIN"),ur&&(Na.push("PROJECTION_GLOBE_VIEW"),cl&&Na.push("PROJECTED_POS_ON_VIEWPORT")),gh>0&&cn.hasAnySecondaryIcon&&Na.push("ICON_TRANSITION"),!cn.icon.zOffsetVertexBuffer||vo&&M.terrain||Na.push("Z_OFFSET"),mt===0&&kt===0&&Et===0&&xt===1||Na.push("COLOR_ADJUSTMENT"),cn.sdfIcons&&Na.push("RENDER_SDF"),ii&&Na.push("RENDER_SHADOWS","NORMAL_OFFSET"),vo&&ss&&!M.terrain&&cn.icon.orientationVertexBuffer&&Na.push("ELEVATED_ROADS"),Ha(Na);const dd=Qt.disableSymbolUBO?cn.icon.programConfigurations.get(C.id):null,fu=M.getOrCreateProgram("symbol",{config:dd,defines:Na}),Ff=Sn.imageAtlasTexture?Sn.imageAtlasTexture.size:[0,0],eo=cn.iconSizeData,kx=o.bj(eo,Dt.zoom),Sx=ss||!Dt.isOrthographic,zo=Nd(rr,Sn.tileID.canonical,ss,Ht,Dt,cn.getProjection(),dr),Vo=Xm(rr,Sn.tileID.canonical,ss,Ht,Dt,cn.getProjection(),dr),co=cn.icon.uboBinder&&cn.icon.uboBinder.cachedHeader&&256&cn.icon.uboBinder.cachedHeader.dataDrivenMask?[0,0]:te,uc=M.translatePosMatrix(Vo,Sn,co,xe,!0),qh=M.translatePosMatrix(rr,Sn,co,xe),Rl=cl?po:zo,zf=Ht&&!ss&&!zi;let h_=Dn;!Us&&!Dt.mercatorFromTransition||Ht||(h_=dc(Dt));const qj=ur?h_:Dn,Vj=C.getColorAdjustmentMatrix(mt,kt,Et,xt),nk=v1(eo.kind,kx,zf,ss,M,qh,Rl,uc,es,!1,Ff,[0,0],0,kn,Nr,ds,ma,qj,cn.getProjection(),ko,Va,Vj,gh,null),k1=Sn.imageAtlasTexture?Sn.imageAtlasTexture:null,Zy=C.layout.get("icon-size").constantOr(0)!==1||cn.iconsNeedLinear,rk=cn.sdfIcons||M.options.rotating||M.options.zooming||Zy||Sx?At.LINEAR:At.NEAREST,Gp=cn.sdfIcons&&C.paint.get("icon-halo-width").constantOr(1)!==0,m_=M.terrain&&ss&&zi?o.b7(o.bb(),zo):po;if(zi&&cn.icon){const p_=o.bu.getAtTileOffsetFunc(kn,Dt.center.lat,Dt.worldSize,cn.getProjection()),f_=Lc(rr,Sn.tileID.canonical,ss,Ht,Dt,cn.getProjection(),dr),P6=C.layout.get("icon-size-scale-range"),ak=o.aC(M.scaleFactor,P6[0],P6[1]);Pt(cn,rr,M,!1,f_,Vo,ss,Xe,p_,kn,ak)}return{program:fu,buffers:cn.icon,uniformValues:nk,atlasTexture:k1,atlasTextureIcon:null,atlasInterpolation:rk,atlasInterpolationIcon:null,isSDF:cn.sdfIcons,hasHalo:Gp,depthMode:Zc,tile:Sn,renderWithShadows:ii,labelPlaneMatrixInv:m_}},yl=()=>{const zi=gs&&C.layout.get("symbol-placement")!=="point",Na=[],cl=zi||Fs||va,vo=cn.elevationType==="road",vc=M.shadowRenderer,ii=vo&&Bs&&!!vc&&vc.enabled,ko=Vr(ii),Zc=vo&&Bs&&!M.terrain?Ns:hn;M.terrainRenderModeElevated()&&Bs&&Na.push("PITCH_WITH_MAP_TERRAIN"),ur&&(Na.push("PROJECTION_GLOBE_VIEW"),cl&&Na.push("PROJECTED_POS_ON_VIEWPORT")),!cn.text.zOffsetVertexBuffer||vo&&M.terrain||Na.push("Z_OFFSET"),cn.iconsInText&&Na.push("RENDER_TEXT_AND_SYMBOL"),Na.push("RENDER_SDF"),ii&&Na.push("RENDER_SHADOWS","NORMAL_OFFSET"),vo&&Bs&&!M.terrain&&cn.text.orientationVertexBuffer&&Na.push("ELEVATED_ROADS"),pa(Na),Ha(Na);const gh=Qt.disableSymbolUBO?cn.text.programConfigurations.get(C.id):null,dd=M.getOrCreateProgram("symbol",{config:gh,defines:Na});let fu,Ff=[0,0],eo=null;const kx=cn.textSizeData;cn.iconsInText&&(Ff=Sn.imageAtlasTexture?Sn.imageAtlasTexture.size:[0,0],eo=Sn.imageAtlasTexture?Sn.imageAtlasTexture:null,fu=Bs||!Dt.isOrthographic||M.options.rotating||M.options.zooming||kx.kind==="composite"||kx.kind==="camera"?At.LINEAR:At.NEAREST);const Sx=Sn.glyphAtlasTexture?Sn.glyphAtlasTexture.size:[0,0],zo=C.layout.get("text-size-scale-range"),Vo=o.aC(M.scaleFactor,zo[0],zo[1]),co=o.bj(kx,Dt.zoom,Vo),uc=Nd(rr,Sn.tileID.canonical,Bs,gs,Dt,cn.getProjection(),dr),qh=Xm(rr,Sn.tileID.canonical,Bs,gs,Dt,cn.getProjection(),dr),Rl=cn.text.uboBinder&&cn.text.uboBinder.cachedHeader&&256&cn.text.uboBinder.cachedHeader.dataDrivenMask?[0,0]:de,zf=M.translatePosMatrix(qh,Sn,Rl,_e,!0),h_=M.translatePosMatrix(rr,Sn,Rl,_e),qj=cl?po:uc,Vj=gs&&!Bs&&!zi;let nk=Dn;!Us&&!Dt.mercatorFromTransition||gs||(nk=dc(Dt));const k1=v1(kx.kind,co,Vj,Bs,M,h_,qj,zf,es,!0,Sx,Ff,0,kn,Nr,ds,ma,ur?nk:Dn,cn.getProjection(),ko,Va,null,null,Vo),Zy=Sn.glyphAtlasTexture?Sn.glyphAtlasTexture:null,rk=At.LINEAR,Gp=C.paint.get("text-halo-width").constantOr(1)!==0,m_=M.terrain&&Bs&&zi?o.b7(o.bb(),uc):po;if(zi&&cn.text){const p_=o.bu.getAtTileOffsetFunc(kn,Dt.center.lat,Dt.worldSize,cn.getProjection()),f_=Lc(rr,Sn.tileID.canonical,Bs,gs,Dt,cn.getProjection(),dr);Pt(cn,rr,M,!0,f_,qh,Bs,pt,p_,kn,Vo)}return{program:dd,buffers:cn.text,uniformValues:k1,atlasTexture:Zy,atlasTextureIcon:eo,atlasInterpolation:rk,atlasInterpolationIcon:fu,isSDF:!0,hasHalo:Gp,depthMode:Zc,tile:Sn,renderWithShadows:ii,labelPlaneMatrixInv:m_}},Lo=cn.icon.segments.get().length,Fi=cn.text.segments.get().length,Da=Lo&&!K.onlyText?yo():null,Ra=Fi&&!K.onlyIcons?yl():null,Do=C.paint.get("icon-opacity").constantOr(1),Nl=C.paint.get("text-opacity").constantOr(1);if(Ps&&cn.canOverlap){rn=!0;const zi=Do&&!K.onlyText?cn.icon.segments.get():[],Na=Nl&&!K.onlyIcons?cn.text.segments.get():[];for(const cl of zi)Ys.push({segments:new o.dy([cl]),sortKey:cl.sortKey,state:Da});for(const cl of Na)Ys.push({segments:new o.dy([cl]),sortKey:cl.sortKey,state:Ra})}else K.onlyText||Ys.push({segments:Do?cn.icon.segments:new o.dy([]),sortKey:0,state:Da}),K.onlyIcons||Ys.push({segments:Nl?cn.text.segments:new o.dy([]),sortKey:0,state:Ra})}rn&&Ys.sort((kn,Sn)=>kn.sortKey-Sn.sortKey);for(const kn of Ys){const Sn=kn.state;if(Sn)if(M.terrain?M.terrain.setupElevationDraw(Sn.tile,Sn.program,{useDepthForOcclusion:Dt.depthOcclusionForSymbolsAndCircles,labelPlaneMatrixInv:Sn.labelPlaneMatrixInv}):M.setupDepthForOcclusion(Dt.depthOcclusionForSymbolsAndCircles,Sn.program),Qt.activeTexture.set(At.TEXTURE0),Sn.atlasTexture&&Sn.atlasTexture.bind(Sn.atlasInterpolation,At.CLAMP_TO_EDGE,!0),Sn.atlasTextureIcon&&(Qt.activeTexture.set(At.TEXTURE1),Sn.atlasTextureIcon&&Sn.atlasTextureIcon.bind(Sn.atlasInterpolationIcon,At.CLAMP_TO_EDGE,!0)),Sn.renderWithShadows&&M.shadowRenderer.setupShadows(Sn.tile.tileID.toUnwrapped(),Sn.program,"vector-tile"),M.uploadCommonLightUniforms(M.context,Sn.program),Sn.hasHalo){const cn=Sn.uniformValues;cn.u_is_halo=1,v0(Sn.buffers,kn.segments,C,M,Sn.program,Sn.depthMode,$,G,cn,2),cn.u_is_halo=0}else{if(Sn.isSDF){const cn=Sn.uniformValues;Sn.hasHalo&&(cn.u_is_halo=1,v0(Sn.buffers,kn.segments,C,M,Sn.program,Sn.depthMode,$,G,cn,1)),cn.u_is_halo=0}v0(Sn.buffers,kn.segments,C,M,Sn.program,Sn.depthMode,$,G,Sn.uniformValues,1)}}}function v0(M,g,C,L,$,G,K,te,de,xe){const _e=L.context,Oe=_e.gl,De=[M.dynamicLayoutVertexBuffer,M.opacityVertexBuffer,M.iconTransitioningVertexBuffer,M.globeExtVertexBuffer,M.zOffsetVertexBuffer,M.orientationVertexBuffer];M.featureIdBuffer&&De.push(M.featureIdBuffer);const qe=M.uboBinder?null:M.programConfigurations.get(C.id);if(M.uboBinder){M.uboBinder.layer=C;const pt=L.transform.zoom,mt=L.style.getBrightness?L.style.getBrightness():null,kt=M.uboBinder.getConstantUniformValues(pt,mt);de.u_spp_fill_np_color=kt.fill_np_color,de.u_spp_halo_np_color=kt.halo_np_color,de.u_spp_opacity=kt.opacity,de.u_spp_halo_width=kt.halo_width,de.u_spp_halo_blur=kt.halo_blur,de.u_spp_emissive_strength=kt.emissive_strength,de.u_spp_occlusion_opacity=kt.occlusion_opacity,de.u_spp_z_offset=kt.z_offset;const Et=C.paint.get(M.uboBinder.isText?"text-translate-anchor":"icon-translate-anchor"),xt=M.uboBinder.cachedHeader&&256&M.uboBinder.cachedHeader.dataDrivenMask&&Et==="map"?L.transform.angle:0;de.u_spp_translate_rotation=[Math.cos(xt),Math.sin(xt)]}const{batchIndices:st,batchSegments:Xe}=M.getBatchGrouping(g);for(const pt of st){const mt=Xe.get(pt);M.uboBinder&&M.uboBinder.bind(_e,$.program,pt),$.draw(L,Oe.TRIANGLES,G,K,te,Pr.disabled,de,C.id,M.layoutVertexBuffer,M.indexBuffer,mt,C.paint,L.transform.zoom,qe,De,xe)}}function ld(M,g,C,L,$,G){const K=C.paint.get("line-width"),te=C.paint.get("line-emissive-strength").isConstant(),de=C.paint.get("line-emissive-strength").constantOr(0),xe=C.paint.get("line-occlusion-opacity"),_e=C.layout.get("line-elevation-reference"),Oe=C.layout.get("line-width-unit")==="meters",De=_e==="sea",qe=!(!M.terrain||!M.terrain.enabled),st=M.context,Xe=st.gl;if(C.hasElevatedBuckets&&M.transform.projection.name==="globe")return;const pt=C.layout.get("line-cross-slope"),mt=pt!==void 0,kt=pt<1,Et=$||M.colorModeForDrapableLayerRenderPass(te?de:null),xt=M.terrain&&M.terrain.renderingToTexture||G,es=xt?1:o.o.devicePixelRatio,Ot=C.paint.get("line-dasharray"),Qt=Ot.constantOr(1),At=C.layout.get("line-cap"),Dt=Ot.constantOr(null),Ht=At.constantOr(null),gs=C.paint.get("line-pattern"),ss=gs.constantOr(1),Bs=C.paint.get("line-pattern-cross-fade"),Ps=gs.constantOr(null),rn=C.paint.get("line-opacity").constantOr(1);let hn=!ss&&rn!==1||M.depthOcclusion&&xe>0&&xe<1;const Ns=C.paint.get("line-gradient"),ds=ss?"linePattern":"line",Fs=o.dU(C);let Us;if(xt&&M.terrain&&M.terrain.clipOrMaskOverlapStencilType()&&(hn=!1),xe!==0&&M.depthOcclusion){const cn=C.paint._values["line-opacity"];cn&&cn.value&&cn.value.kind==="constant"?Us=cn.value:o.w(`Occlusion opacity for layer ${C.id} is supported only when line-opacity isn't data-driven.`)}K.value.kind!=="constant"&&K.value.isLineProgressConstant===!1&&Fs.push("VARIABLE_LINE_WIDTH"),xt&&(M.emissiveMode!=="dual-source-blending"||te?M.emissiveMode==="mrt-fallback"&&Fs.push("USE_MRT1"):Fs.push("DUAL_SOURCE_BLENDING"));const Ys={},Dn=(cn,ur,Nr,rr,dr,Xr)=>{for(const va of cn){const ma=g.getTile(va);if(ss&&!ma.patternsLoaded())continue;const Va=ma.getBucket(C);if(!Va||Va.elevationType!=="none"&&!dr||Va.elevationType==="none"&&dr)continue;M.prepareDrawTile();const Vr=[...ur],Ha=M.shadowRenderer,pa=Va.elevationType==="road"&&!!Ha&&Ha.enabled;let Ci=[0,0,0];if(pa){const ii=M.style.directionalLight,ko=M.style.ambientLight;ii&&ko&&(Ci=Op(M.style,ii,ko)),Vr.push("RENDER_SHADOWS","NORMAL_OFFSET")}const yo=Va.programConfigurations.get(C.id);let yl=!1;if(Ps&&ma.imageAtlas){const ii=o.dV.from(Ps),ko=ii.getPrimary().scaleSelf(es).toString(),Zc=ma.imageAtlas.patternPositions.get(ko),gh=ii.getSecondary(),dd=gh?ma.imageAtlas.patternPositions.get(gh.scaleSelf(es).toString()):null;yl=!!Zc&&!!dd,Zc&&yo.setConstantPatternPositions(Zc,dd)}Bs>0&&(yl||yo.getPatternTransitionVertexBuffer("line-pattern"))&&Vr.push("LINE_PATTERN_TRANSITION"),Va.elevationGroundScaleVertexBuffer&&Vr.push("ELEVATION_GROUND_SCALE");const Lo=M.isTileAffectedByFog(va),Fi=M.getOrCreateProgram(ds,{config:yo,defines:Vr,overrideFog:Lo});if(!ss&&Dt&&Ht&&ma.lineAtlas){const ii=ma.lineAtlas.getDash(Dt,Ht);ii&&yo.setConstantPatternPositions(ii)}pa&&Ha.setupShadows(ma.tileID.toUnwrapped(),Fi,"vector-tile");let[Da,Ra]=C.paint.get("line-trim-offset");(Ht==="round"||Ht==="square")&&Da!==Ra&&(Da===0&&(Da-=1),Ra===1&&(Ra+=1));const Do=xt?va.projMatrix:null,Nl=Oe?1/Va.tileToMeter/o.aA(ma,1,M.transform.zoom):1,zi=Oe?1/Va.tileToMeter/o.aA(ma,1,Math.floor(M.transform.zoom)):1,Na=Qt?C.paint._values["line-floorwidth"]:null;let cl;if(Na&&Na.value.kind==="constant"){const ii=Va.zoom;ii in Ys||(Ys[ii]=Math.max(.01,C.widthExpression().evaluate({zoom:ii}))),cl=Na.value.value;const ko=Math.floor(M.transform.zoom);Na.value.value=Ys[ii]*Math.pow(2,ko-ma.tileID.overscaledZ)}const vo=ss?o.dW(M,ma,C,Do,es,Nl,zi,[Da,Ra],Ci,Bs):o.dX(M,ma,C,Do,Va.lineClipsArray.length,es,Nl,zi,[Da,Ra],Ci);if(Ns){const ii=Va.gradients[C.id];let ko=ii.texture;if(C.gradientVersion!==ii.version){let Zc=256;if(C.stepInterpolant){const gh=g.getSource().maxzoom,dd=va.canonical.z===gh?Math.ceil(1<{Us!=null&&(Us.value=rn*xe),Fi.draw(M,Xe.TRIANGLES,Nr,ii,Et,Pr.disabled,vo,C.id,Va.layoutVertexBuffer,Va.indexBuffer,Va.segments,C.paint,M.transform.zoom,yo,[Va.layoutVertexBuffer2,Va.patternVertexBuffer,Va.zOffsetVertexBuffer,Va.elevationGroundScaleVertexBuffer]),Us!=null&&(Us.value=rn)};if(hn&&!dr){const ii=M.stencilModeForClipping(va).ref;ii===0&&xt&&st.clear({stencil:0});const ko={func:Xe.EQUAL,mask:255};vo.u_alpha_discard_threshold=.8,vc(new ra(ko,ii,255,Xe.KEEP,Xe.KEEP,Xe.INVERT)),vo.u_alpha_discard_threshold=0,vc(new ra(ko,ii,255,Xe.KEEP,Xe.KEEP,Xe.KEEP))}else vo.u_alpha_discard_threshold=hn&&dr&&Xr?.8:0,vc(dr?rr:M.stencilModeForClipping(va));cl!==void 0&&(Na.value.value=cl)}};let kn=M.depthModeForSublayer(0,nr.ReadOnly);const Sn=new nr(M.depthOcclusion?Xe.GREATER:Xe.LEQUAL,nr.ReadOnly,M.depthRangeFor3D);if(C.hasNonElevatedBuckets){const cn=!xt&&M.terrain;xe!==0&&cn?o.w(`Occlusion opacity for layer ${C.id} is supported on terrain only if the layer has line-z-offset enabled.`):cn?o.w(`Cannot render non-elevated lines in immediate mode when terrain is enabled. Layer: ${C.id}.`):Dn(L,Fs,kn,ra.disabled,!1,!0)}if(C.hasElevatedBuckets){_e==="hd-road-markup"?qe||(kn=Sn,Fs.push("ELEVATED_ROADS")):(Fs.push("ELEVATED"),kn=Sn,mt&&Fs.push(kt?"CROSS_SLOPE_HORIZONTAL":"CROSS_SLOPE_VERTICAL"),De&&Fs.push("ELEVATION_REFERENCE_SEA"));const cn=hn?M.stencilModeFor3D():ra.disabled;M.forceTerrainMode=!0,Dn(L,Fs,kn,cn,!0,!0),hn&&Dn(L,Fs,kn,cn,!0,!1),M.forceTerrainMode=!1}hn&&(M.resetStencilClippingMasks(),xt&&st.clear({stencil:0})),xe===0||M.depthOcclusion||xt||M.layersWithOcclusionOpacity.push(M.currentLayer)}const Up={additive:{clearColor:new o.aq(0,0,0,0),colorMode:Qr.additive,compositeUniformValue:1},multiply:{clearColor:new o.aq(1,1,1,1),colorMode:Qr.multiply,compositeUniformValue:0}};function b0(M,g){const C=1<=If?1:qe.pitch/If))),2*st}(M.transform),xe=M.transform.getFreeCameraOptions().position,_e="elevatedStructuresDepthReconstruct",Oe=M.getOrCreateProgram(_e,{defines:["DEPTH_RECONSTRUCTION"]}),De=M.getOrCreateProgram(_e);for(const qe of L){const st=g.getTile(qe),Xe=st.getBucket(C);if(!Xe)continue;const pt=Xe.elevatedStructures;if(!pt)continue;const mt=Xe.elevationBufferData.heightRange,kt=b0(qe.toUnwrapped(),xe),Et=M.translatePosMatrix(qe.projMatrix,st,C.paint.get("fill-translate"),C.paint.get("fill-translate-anchor"));let xt,es,Ot,Qt;if($==="initialize"){if(!mt||mt.min>=1||pt.depthSegments.segments[0].primitiveLength===0)continue;xt=y1(Et,kt,de,1,0),es=K,Ot=pt.depthSegments,Qt=Oe}else if($==="reset"){if(!mt||mt.min>=0||pt.maskSegments.segments[0].primitiveLength===0)continue;xt=y1(Et,kt,0,0,1),es=te,Ot=pt.maskSegments,Qt=Oe}else if($==="geometry"){if(pt.depthSegments.segments[0].primitiveLength===0)continue;xt=y1(Et,kt,de,1,0),es=K,Ot=pt.depthSegments,Qt=De}Qt.draw(M,G.TRIANGLES,es,ra.disabled,Qr.disabled,Pr.disabled,xt,C.id,pt.vertexBuffer,pt.indexBuffer,Ot,C.paint,M.transform.zoom)}}function b1(M,g,C,L){const{painter:$,sourceCache:G,layer:K,coords:te,colorMode:de,elevationType:xe,terrainEnabled:_e,pass:Oe}=M,De=$.context.gl,qe=K.paint.get("fill-pattern"),st=K.paint.get("fill-pattern-cross-fade"),Xe=qe.constantOr(null);let pt=xe;xe!=="road"||g&&!_e||(pt="none");const mt=pt==="road",kt=M.painter.shadowRenderer,Et=mt&&!!kt&&kt.enabled,xt=new nr($.context.gl.LEQUAL,nr.ReadOnly,$.depthRangeFor3D);let es=[0,0,0];if(Et){const Dt=$.style.directionalLight,Ht=$.style.ambientLight;Dt&&Ht&&(es=Op($.style,Dt,Ht))}const Ot=qe&&qe.constantOr(1),Qt=$.terrain&&$.terrain.renderingToTexture,At=(Dt,Ht)=>{let gs,ss,Bs,Ps,rn;Ht?(gs=Ot&&!K.getPaintProperty("fill-outline-color")?"fillOutlinePattern":"fillOutline",Bs=De.LINES):(gs=Ot?"fillPattern":"fill",Bs=De.TRIANGLES);for(const hn of te){const Ns=G.getTile(hn);if(Ot&&!Ns.patternsLoaded())continue;const ds=Ns.getBucket(K);if(!ds)continue;const Fs=g?ds.elevationBufferData:ds.bufferData;if(Fs.isEmpty())continue;$.prepareDrawTile();const Us=Fs.programConfigurations.get(K.id),Ys=$.isTileAffectedByFog(hn),Dn=[],kn=[];mt&&(Dn.push("ELEVATED_ROADS"),kn.push(Fs.elevatedLayoutVertexBuffer)),Et&&Dn.push("RENDER_SHADOWS","NORMAL_OFFSET"),Qt&&C&&Dn.push("USE_MRT1"),Ot&&($.context.activeTexture.set(De.TEXTURE0),Ns.imageAtlasTexture&&Ns.imageAtlasTexture.bind(De.LINEAR,De.CLAMP_TO_EDGE),Us.updatePaintBuffers());let Sn=!1;if(Xe&&Ns.imageAtlas){const dr=Ns.imageAtlas,Xr=o.dV.from(Xe),va=Xr.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),ma=Xr.getSecondary(),Va=dr.patternPositions.get(va),Vr=ma?dr.patternPositions.get(ma.scaleSelf(o.o.devicePixelRatio).toString()):null;Sn=!!Va&&!!Vr,Va&&Us.setConstantPatternPositions(Va,Vr)}st>0&&(Sn||Us.getPatternTransitionVertexBuffer("fill-pattern"))&&Dn.push("FILL_PATTERN_TRANSITION");const cn=$.getOrCreateProgram(gs,{config:Us,overrideFog:Ys,defines:Dn}),ur=$.translatePosMatrix(hn.projMatrix,Ns,K.paint.get("fill-translate"),K.paint.get("fill-translate-anchor"));Et&&kt.setupShadows(Ns.tileID.toUnwrapped(),cn,"vector-tile");const Nr=K.paint.get("fill-emissive-strength");if(Ht){Ps=Fs.lineIndexBuffer,rn=Fs.lineSegments;const dr=$.terrain&&$.terrain.renderingToTexture?$.terrain.drapeBufferSize:[De.drawingBufferWidth,De.drawingBufferHeight];ss=gs==="fillOutlinePattern"&&Ot?s_(ur,Nr,$,Ns,dr,es,st):bC(ur,Nr,dr,es)}else Ps=Fs.indexBuffer,rn=Fs.triangleSegments,ss=Ot?t_(ur,Nr,$,Ns,es,st):p0(ur,Nr,es);$.uploadCommonUniforms($.context,cn,hn.toUnwrapped());let rr=Dt;(xe==="road"&&!_e||xe==="offset")&&(rr=xt),cn.draw($,Bs,rr,L||$.stencilModeForClipping(hn),de,Pr.disabled,ss,K.id,Fs.layoutVertexBuffer,Ps,rn,K.paint,$.transform.zoom,Us,kn)}};$.renderPass===Oe&&At($.depthModeForSublayer(1,$.renderPass==="opaque"?nr.ReadWrite:nr.ReadOnly),!1),pt==="none"&&$.renderPass==="translucent"&&K.paint.get("fill-antialias")&&At($.depthModeForSublayer(K.getPaintProperty("fill-outline-color")?2:0,nr.ReadOnly),!0)}function wx(M,g,C,L,$,G,K,te){C.resetLayerRenderingStats(M);const de=M.context,xe=de.gl,_e=M.transform,Oe=C.paint.get("fill-extrusion-pattern"),De=C.paint.get("fill-extrusion-pattern-cross-fade"),qe=Oe.constantOr(null),st=Oe.constantOr(1),Xe=C.paint.get("fill-extrusion-opacity"),pt=M.style.enable3dLights(),mt=C.paint.get(pt&&!st?"fill-extrusion-ambient-occlusion-wall-radius":"fill-extrusion-ambient-occlusion-radius"),kt=[C.paint.get("fill-extrusion-ambient-occlusion-intensity"),mt],Et=C.layout.get("fill-extrusion-edge-radius"),xt=Et>0&&!C.paint.get("fill-extrusion-rounded-roof"),es=xt?0:Et,Ot=_e.projection.name==="globe"?o.e1():0,Qt=_e.projection.name==="globe",At=Qt?o.al(_e.zoom):0,Dt=[o.aH(_e.center.lng),o.aL(_e.center.lat)],Ht=C.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",gs=C.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(Ht?null:C.lut).toArray01().slice(0,3),ss=C.paint.get("fill-extrusion-flood-light-intensity"),Bs=C.paint.get("fill-extrusion-vertical-scale"),Ps=C.paint.get("fill-extrusion-line-width").constantOr(1)!==0,rn=C.paint.get("fill-extrusion-height-alignment"),hn=C.paint.get("fill-extrusion-base-alignment"),Ns=Dc(M,C.paint.get("fill-extrusion-cutoff-fade-range")),ds=C.paint.get("fill-extrusion-front-cutoff"),Fs=i_(_e.pitch,ds,!!M.terrain),Us=Fs[2]<1;Us&&(M.maxFrontCutoffRawStart=Math.max(M.maxFrontCutoffRawStart,ds[0]));const Ys=[];let Dn;Qt&&Ys.push("PROJECTION_GLOBE_VIEW"),kt[0]>0&&Ys.push("FAUX_AO"),xt&&Ys.push("ZERO_ROOF_RADIUS"),te&&Ys.push("HAS_CENTROID"),ss>0&&Ys.push("FLOOD_LIGHT"),Ns.shouldRenderCutoff&&Ys.push("RENDER_CUTOFF"),Us&&Ys.push("RENDER_FRONT_CUTOFF"),Ps&&Ys.push("RENDER_WALL_MODE");const kn=M.renderPass==="shadow",Sn=M.shadowRenderer,cn=kn&&!!Sn,ur=kn?Pr.disabled:Pr.backCCW;M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!0);let Nr=[0,0,0];if(Sn){const Xr=M.style.directionalLight,va=M.style.ambientLight;Xr&&va&&(Nr=Op(M.style,Xr,va)),kn||(Ys.push("RENDER_SHADOWS"),Sn.useNormalOffset&&Ys.push("NORMAL_OFFSET")),Dn=Ys.concat(["SHADOWS_SINGLE_CASCADE"])}const rr=cn?"fillExtrusionDepth":st?"fillExtrusionPattern":"fillExtrusion",dr=C.getLayerRenderingStats();for(const Xr of L){const va=g.getTile(Xr),ma=va.getBucket(C);if(!ma||ma.projection.name!==_e.projection.name)continue;let Va=!1;Sn&&(Va=Sn.getMaxCascadeForTile(Xr.toUnwrapped())===0);const Vr=M.isTileAffectedByFog(Xr),Ha=ma.programConfigurations.get(C.id);let pa=!1;if(qe&&va.imageAtlas){const Ra=va.imageAtlas,Do=o.dV.from(qe),Nl=Do.getPrimary().scaleSelf(o.o.devicePixelRatio).toString(),zi=Do.getSecondary(),Na=Ra.patternPositions.get(Nl),cl=zi?Ra.patternPositions.get(zi.scaleSelf(o.o.devicePixelRatio).toString()):null;pa=!!Na&&!!cl,Na&&Ha.setConstantPatternPositions(Na,cl)}De>0&&(pa||Ha.getPatternTransitionVertexBuffer("fill-extrusion-pattern"))&&Ys.push("FILL_EXTRUSION_PATTERN_TRANSITION");const Ci=M.getOrCreateProgram(rr,{config:Ha,defines:Va?Dn:Ys,overrideFog:Vr});if(M.terrain&&M.terrain.setupElevationDraw(va,Ci,{useMeterToDem:!0}),!ma.centroidVertexBuffer){const Ra=Ci.getAttributeLocation(xe,"a_centroid_pos");Ra!==-1&&xe.vertexAttribI4ui(Ra,0,0,0,0)}!kn&&Sn&&Sn.setupShadows(va.tileID.toUnwrapped(),Ci,"vector-tile"),st&&(M.context.activeTexture.set(xe.TEXTURE0),va.imageAtlasTexture&&va.imageAtlasTexture.bind(xe.LINEAR,xe.CLAMP_TO_EDGE),Ha.updatePaintBuffers());const yo=C.paint.get("fill-extrusion-vertical-gradient"),yl=1/ma.tileToMeter;let Lo;if(kn&&Sn){if(jx(va.tileID,ma.maxHeight,M))continue;const Ra=Sn.calculateShadowPassMatrixFromTile(va.tileID.toUnwrapped());Lo=LR(Ra,es,yl,Bs,rn,hn)}else{const Ra=M.translatePosMatrix(Xr.expandedProjMatrix,va,C.paint.get("fill-extrusion-translate"),C.paint.get("fill-extrusion-translate-anchor")),Do=_e.projection.createInversionMatrix(_e,Xr.canonical);Lo=st?za(Ra,M,yo,Xe,kt,es,yl,Xr,va,Ot,rn,hn,At,Dt,Do,gs,Bs,De):ph(Ra,M,yo,Xe,kt,es,yl,Xr,Ot,rn,hn,At,Dt,Do,gs,Bs,ss,Nr,Fs)}M.uploadCommonUniforms(de,Ci,Xr.toUnwrapped(),null,Ns);let Fi=ma.segments;if(_e.projection.name==="mercator"&&!kn&&(Fi=ma.getVisibleSegments(va.tileID,M.terrain,M.transform.getFrustum(0)),!Fi.get().length))continue;if(dr)if(kn)for(const Ra of Fi.get())dr.numRenderedVerticesInShadowPass+=Ra.primitiveLength;else for(const Ra of Fi.get())dr.numRenderedVerticesInTransparentPass+=Ra.primitiveLength;const Da=[];(M.terrain||te)&&Da.push(ma.centroidVertexBuffer),Qt&&Da.push(ma.layoutVertexExtBuffer),Ps&&Da.push(ma.wallVertexBuffer),Ci.draw(M,de.gl.TRIANGLES,$,G,K,ur,Lo,C.id,ma.layoutVertexBuffer,ma.indexBuffer,Fi,C.paint,M.transform.zoom,Ha,Da)}M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!1)}class $h{constructor(){this.translate=[0,0],this.translateAnchor="map",this.edgeRadius=0,this.cutoffFadeRange=0}}function i_(M,g,C){if(!(g[2]<1)||C)return[0,0,1];const L=180*M/Math.PI;if(L<15)return[-.5,g[1],g[2]];const $=Math.min(1,Math.max(0,(L-15)/5)),G=$*$*(3-2*$);return[-.5*(1-G)+g[0]*G,g[1],g[2]]}function Rf(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe,st,Xe,pt,mt,kt,Et,xt){const es=g.context,Ot=es.gl,Qt=g.transform,At=g.transform.zoom,Dt=[],Ht=M.translate,gs=M.translateAnchor,ss=M.edgeRadius,Bs=Dc(g,M.cutoffFadeRange);_e==="clear"?(Dt.push("CLEAR_SUBPASS"),Et&&(Dt.push("CLEAR_FROM_TEXTURE"),es.activeTexture.set(Ot.TEXTURE0),Et.bind(Ot.LINEAR,Ot.CLAMP_TO_EDGE))):_e==="sdf"?Dt.push("SDF_SUBPASS"):_e==="emissive"&&(Dt.push("USE_MRT1"),es.activeTexture.set(Ot.TEXTURE0),Et.bind(Ot.LINEAR,Ot.CLAMP_TO_EDGE)),mt&&Dt.push("HAS_CENTROID"),Bs.shouldRenderCutoff&&Dt.push("RENDER_CUTOFF");const Ps=(rn,hn,Ns,ds,Fs)=>{let Us=Dt;hn.groundRadiusBuffer!=null&&(Us=Dt.concat("HAS_ATTRIBUTE_a_flood_light_ground_radius"));const Ys=hn.programConfigurations.get(L.id),Dn=g.isTileAffectedByFog(rn),kn=g.getOrCreateProgram("fillExtrusionGroundEffect",{config:Ys,defines:Us,overrideFog:Dn}),Sn=((ur,Nr,rr,dr,Xr,va,ma,Va,Vr,Ha,pa)=>({u_matrix:Nr,u_opacity:rr,u_ao_pass:dr?1:0,u_meter_to_tile:Xr,u_ao:va,u_flood_light_intensity:ma,u_flood_light_color:Va,u_attenuation:Vr,u_edge_radius:Ha,u_fb:0,u_fb_size:pa,u_dynamic_offset:1}))(0,ds,Oe,xe,Fs,[De,qe*Fs],st,Xe,pt,At>=17?0:ss*Fs,Et?Et.size[0]:0),cn=[];mt&&cn.push(hn.hiddenByLandmarkVertexBuffer),hn.groundRadiusBuffer!=null&&cn.push(hn.groundRadiusBuffer),g.uploadCommonUniforms(es,kn,rn.toUnwrapped(),null,Bs),kn.draw(g,es.gl.TRIANGLES,G,K,te,de,Sn,L.id,hn.vertexBuffer,hn.indexBuffer,Ns,L.paint,At,Ys,cn)};for(const rn of $){const hn=C.getTile(rn),Ns=hn.getBucket(L);if(!Ns||Ns.projection.name!==Qt.projection.name||!Ns.groundEffect||Ns.groundEffect&&!Ns.groundEffect.hasData())continue;const ds=Ns.groundEffect,Fs=1/Ns.tileToMeter;{const Us=g.translatePosMatrix(rn.projMatrix,hn,Ht,gs),Ys=ds.getDefaultSegment();Ps(rn,ds,Ys,Us,Fs)}if(kt)for(let Us=0;Us<4;Us++){const Ys=o.d$[Us](rn),Dn=C.getTile(Ys);if(!Dn)continue;const kn=Dn.getBucket(L);if(!kn||kn.projection.name!==Qt.projection.name||!kn.groundEffect||kn.groundEffect&&!kn.groundEffect.hasData())continue;const Sn=kn.groundEffect;let cn,ur;Us===0?(cn=[-o.an,0,0],ur=1):Us===1?(cn=[o.an,0,0],ur=0):Us===2?(cn=[0,-o.an,0],ur=3):(cn=[0,o.an,0],ur=2);const Nr=Sn.regionSegments[ur];if(!Nr)continue;const rr=new Float32Array(16);o.bx(rr,rn.projMatrix,cn),Ps(rn,Sn,Nr,g.translatePosMatrix(rr,hn,Ht,gs),Fs)}}}function hg(M,g,C,L,$,G,K){L.centroidVertexArray.length===0&&L.createCentroidsBuffer();const te=G?G.findDEMTileFor(C):null;if(!(te&&te.dem||K))return;G&&te&&te.dem&&L.selfDEMTileTimestamp!==te.dem._timestamp&&(L.borderDoneWithNeighborZ=[-1,-1,-1,-1],L.selfDEMTileTimestamp=te.dem._timestamp);const de=(mt,kt)=>{(mt.flags|kt.flags)&o.e3?(mt.flags|=o.e3,kt.flags|=o.e3):(mt.flags&=~o.e3,kt.flags&=~o.e3)},xe=mt=>new o.P(Math.ceil((mt+o.e4)*o.e5),0),_e=(mt,kt,Et)=>{const xt=Math.ceil((mt+o.e4)*o.e5),es=Math.floor(Math.max(0,Math.min(o.an-1,Et))/4);return new o.P(xt,es<<5|(3&kt)<<3|7)},Oe=mt=>{const kt=g.getSource().minzoom,Et=es=>{const Ot=g.getTileByID(es);if(Ot&&Ot.hasData())return Ot.getBucket($)},xt=[0,-1,1];for(const es of xt){if(mt.overscaledZ+es(De[0]=Math.min(mt.min.y,kt.min.y),De[1]=Math.max(mt.max.y,kt.max.y),De[2]=o.an-kt.min.x>mt.max.x?kt.min.x-o.an:mt.max.x,De),st=(mt,kt)=>(De[0]=Math.min(mt.min.x,kt.min.x),De[1]=Math.max(mt.max.x,kt.max.x),De[2]=o.an-kt.min.y>mt.max.y?kt.min.y-o.an:mt.max.y,De),Xe=[(mt,kt)=>qe(mt,kt),(mt,kt)=>qe(kt,mt),(mt,kt)=>st(mt,kt),(mt,kt)=>st(kt,mt)],pt=(mt,kt,Et,xt,es,Ot,Qt)=>{if(!G)return 0;const At=[[Ot?Et:mt,Ot?mt:Et,0],[Ot?Et:kt,Ot?kt:Et,0]],Dt=Qt<0?o.an+Qt:Qt,Ht=[Ot?Dt:(mt+kt)/2,Ot?(mt+kt)/2:Dt,0];return Et===0&&Qt<0||Et!==0&&Qt>0?G.getForTilePoints(es,[Ht],!0,xt):At.push(Ht),G.getForTilePoints(C,At,!0,te),Math.max(At[0][2],At[1][2],Ht[2])/G.exaggeration()};for(let mt=0;mt<4;mt++){const kt=L.borderFeatureIndices[mt];if(kt.length===0)continue;const Et=o.d$[mt](C),xt=Oe(Et);if(!(xt&&xt instanceof o.e0))continue;const es=G?G.findDEMTileFor(Et):null;if(!(es&&es.dem||K)||(G&&es&&es.dem&&L.borderDEMTileTimestamp[mt]!==es.dem._timestamp&&(L.borderDoneWithNeighborZ[mt]=-1,L.borderDEMTileTimestamp[mt]=es.dem._timestamp),L.borderDoneWithNeighborZ[mt]===xt.canonical.z))continue;xt.centroidVertexArray.length===0&&xt.createCentroidsBuffer();const Ot=(mt<2?1:5)-mt,Qt=xt.borderDoneWithNeighborZ[Ot]!==L.canonical.z,At=xt.borderFeatureIndices[Ot];let Dt=0;if(L.canonical.z!==xt.canonical.z){for(const Bs of kt)L.showCentroid(L.featuresOnBorder[Bs]);if(Qt)for(const Bs of At)xt.showCentroid(xt.featuresOnBorder[Bs]);L.borderDoneWithNeighborZ[mt]=xt.canonical.z,xt.borderDoneWithNeighborZ[Ot]=L.canonical.z;continue}const Ht=new Map,gs=new Set,ss=new Set;for(let Bs=0;Bs1||Ns.intersectsCount()>1;{let kn=0;if(es&&es.dem&&!Dn){const Sn=Xe[mt](rn,ds),cn=mt%2?o.an-1:0;kn=pt(Sn[0],Math.min(o.an-1,Sn[1]),cn,es,Et,mt<2,Sn[2])}rn.centroidXY=_e(kn,mt,Ys),ds.centroidXY=_e(kn,Ot,Ys)}if(L.writeCentroidToBuffer(rn),xt.writeCentroidToBuffer(ds),Ps.buildingId!==void 0){for(const kn of L.centroidData)kn.buildingId===Ps.buildingId&&kn!==rn&&(kn.centroidXY=rn.centroidXY,L.writeCentroidToBuffer(kn));for(const kn of xt.centroidData)kn.buildingId===Ps.buildingId&&kn!==ds&&(kn.centroidXY=ds.centroidXY,xt.writeCentroidToBuffer(kn))}}for(const Bs of kt){if(gs.has(Bs))continue;const Ps=L.featuresOnBorder[Bs],rn=L.centroidData[Ps.centroidDataIndex],hn=Ps.borders[mt];let Ns;for(;Dthn[0]+3||ds[0]>hn[0]-3)break;xt.showCentroid(Ns),Dt++}if(Ns&&Dthn[1]-3||(Fs++,++Dt===At.length))break;Ns=xt.featuresOnBorder[At[Dt]]}for(;ds=At.length){L.showCentroid(Ps);continue}Ns=xt.featuresOnBorder[At[ds]];let Us=!1;if(Fs>=1){const kn=Ns.borders[Ot];Math.abs(hn[0]-kn[0])<3&&Math.abs(hn[1]-kn[1])<3&&(Fs=1,Us=!0,Dt=ds+1)}else if(Fs===0){L.showCentroid(Ps);continue}const Ys=xt.centroidData[Ns.centroidDataIndex];K&&Us&&de(rn,Ys);const Dn=Ps.intersectsCount()>1||Ns.intersectsCount()>1;if(Fs>1)Dt=ds,rn.centroidXY=Ys.centroidXY=new o.P(0,0);else if(es&&es.dem&&!Dn){const kn=Xe[mt](rn,Ys),Sn=mt%2?o.an-1:0,cn=pt(kn[0],Math.min(o.an-1,kn[1]),Sn,es,Et,mt<2,kn[2]);rn.centroidXY=Ys.centroidXY=xe(cn)}else Dn?rn.centroidXY=Ys.centroidXY=new o.P(0,0):(rn.centroidXY=L.encodeBorderCentroid(Ps),Ys.centroidXY=xt.encodeBorderCentroid(Ns));L.writeCentroidToBuffer(rn),xt.writeCentroidToBuffer(Ys)}else L.showCentroid(Ps)}L.borderDoneWithNeighborZ[mt]=xt.canonical.z,xt.borderDoneWithNeighborZ[Ot]=L.canonical.z}(L.needsCentroidUpdate||!L.centroidVertexBuffer&&L.centroidVertexArray.length!==0)&&L.uploadCentroid(M)}const _1=[1,0,0],Ij=[0,1,0],Pj=[0,0,1];function jx(M,g,C){const L=C.transform,$=C.shadowRenderer;if(!$)return!0;const G=M.toUnwrapped(),K=L.tileSize*$._cascades[C.currentShadowCascade].scale;let te=g;if(L.elevation){const st=L.elevation.getMinMaxForTile(M);st&&(te+=st.max)}const de=L.scaleZoom(K);te/=o.e2(L.center.lat,de);const xe=[...$.shadowDirection];xe[2]=-xe[2];const _e=$.computeSimplifiedTileShadowVolume(G,te,K,xe);if(!_e)return!1;const Oe=[_1,Ij,Pj,xe,[xe[0],0,xe[2]],[0,xe[1],xe[2]]],De=o.cl.fromInvProjectionMatrix(L.invProjMatrix,L.worldSize,de,L.projection.name!=="globe"),qe=$.getCurrentCascadeFrustum();return De.intersectsPrecise(_e.vertices,_e.planes,Oe)===0||qe.intersectsPrecise(_e.vertices,_e.planes,Oe)===0}function Gy(M){const{painter:g,source:C,layer:L,coords:$}=M;let G=M.defines;const K=g.context,te=g.renderPass==="shadow",de=g.renderPass==="light-beam",xe=g.shadowRenderer,_e=o.e2(g.transform.center.lat,g.transform.zoom),Oe=Dc(g,L.paint.get("building-cutoff-fade-range"));Oe.shouldRenderCutoff&&(G=G.concat("RENDER_CUTOFF"));const De=L.paint.get("building-front-cutoff"),qe=De[2]<1&&!g.terrain,st=i_(g.transform.pitch,De,!!g.terrain);qe&&(G=G.concat("RENDER_FRONT_CUTOFF"),g.maxFrontCutoffRawStart=Math.max(g.maxFrontCutoffRawStart,De[0])),M.floodLightIntensity>0&&(G=G.concat("FLOOD_LIGHT"));for(const Xe of $){const pt=C.getTile(Xe),mt=pt.getBucket(L);if(!mt)continue;xe&&xe.getMaxCascadeForTile(Xe.toUnwrapped())===0&&(G=G.concat("SHADOWS_SINGLE_CASCADE"));const kt=mt.programConfigurations.get(L.id);let Et,xt,es,Ot=g.translatePosMatrix(Xe.expandedProjMatrix,pt,[0,0],"map");if(Ot=o.cC(o.bb(),Ot,[1,1,M.verticalScale]),te&&xe){if(jx(pt.tileID,mt.maxHeight*_e,g))continue;let At=xe.calculateShadowPassMatrixFromTile(pt.tileID.toUnwrapped());At=o.cC(o.bb(),At,[1,1,M.verticalScale]),es=r_(At),Et=xt=g.getOrCreateProgram("buildingDepth",{config:kt,defines:G,overrideFog:!1})}else if(de)Et=xt=g.getOrCreateProgram("buildingBloom",{config:kt,defines:G,overrideFog:!1}),es=Tj(Ot);else{const At=g.transform.calculatePosMatrix(Xe.toUnwrapped(),g.transform.worldSize);o.cC(At,At,[1,1,M.verticalScale]);const Dt=o.bb();o.cC(Dt,At,[1,-1,1/_e]),o.b7(Dt,Dt),o.e6(Dt,Dt);const Ht=g.transform.getFreeCameraOptions().position,gs=1<{if(de){const Ht=At.entranceBloom;Dt.draw(g,K.gl.TRIANGLES,M.depthMode,ra.disabled,M.blendMode,Pr.disabled,es,L.id,Ht.layoutVertexBuffer,Ht.indexBuffer,Ht.segmentsBucket,L.paint,g.transform.zoom,kt,[Ht.layoutAttenuationBuffer,Ht.layoutColorBuffer])}else{const Ht=At.segmentsBucket;let gs=[At.layoutNormalBuffer,At.layoutCentroidBuffer,At.layoutColorBuffer,At.layoutFloodLightDataBuffer];At.layoutFacadePaintBuffer&&(gs=gs.concat([At.layoutFacadeDataBuffer,At.layoutFacadeVerticalRangeBuffer,At.layoutFacadePaintBuffer])),Dt.draw(g,K.gl.TRIANGLES,M.depthMode,ra.disabled,M.blendMode,te?Pr.disabled:Pr.backCW,es,L.id,At.layoutVertexBuffer,At.indexBuffer,Ht,L.paint,g.transform.zoom,kt,gs)}};g.uploadCommonUniforms(K,xt,Xe.toUnwrapped(),null,Oe),mt.buildingWithoutFacade&&Qt(mt.buildingWithoutFacade,xt),mt.buildingWithFacade&&(Et!==xt&&g.uploadCommonUniforms(K,Et,Xe.toUnwrapped(),null,Oe),Qt(mt.buildingWithFacade,Et))}}function mg(M,g,C,L,$,G,K,te,de,xe,_e,Oe,De,qe){const st=M.context.gl,Xe=M.depthModeForSublayer(1,nr.ReadOnly,st.LEQUAL,!0),pt=.1*(1-(mt=_e))+3*mt;var mt;const kt=M._showOverdrawInspector,Et=Oe,xt=new $h;kt||Rf(xt,M,g,C,L,Xe,new ra({func:st.ALWAYS,mask:255},255,255,st.KEEP,st.KEEP,st.REPLACE),new Qr([st.ONE,st.ONE,st.ONE,st.ONE],o.aq.transparent,[!1,!1,!1,!0],st.MIN),Pr.disabled,$,"sdf",G,K,te,de,xe,pt,Et,!1,void 0);{const es=kt?ra.disabled:new ra({func:st.EQUAL,mask:255},255,255,st.KEEP,st.DECR,st.DECR),Ot=kt?M.colorModeForRenderPass():new Qr([st.ONE_MINUS_DST_ALPHA,st.DST_ALPHA,st.ONE,st.ONE],o.aq.transparent,[!0,!0,!0,!0]);Rf(xt,M,g,C,L,Xe,es,Ot,Pr.disabled,$,"color",G,K,te,de,xe,pt,Et,!1,void 0)}}function o_(M){return[M[0]*o.e7,M[1]*o.e7,M[2]*o.e7,0]}function Wy(M,g,C,L,$,G,K,te,de){const xe=L.getSource(),_e=C.globeSharedBuffers;if(!_e)return;let Oe,De,qe;if(g&&(Oe=L.getTile(g)),xe instanceof o.aV?(De=xe.texture,qe=o.dw(0,0,C.transform)):Oe&&g&&(De=Oe.texture,qe=o.dw(g.canonical.z,g.canonical.x,C.transform)),!De||!qe)return;M||(qe=o.cC(o.bb(),qe,[1,-1,1]));const st=C.context,Xe=st.gl,pt=$.paint.get("raster-resampling")==="nearest"?Xe.NEAREST:Xe.LINEAR,mt=C.colorModeForDrapableLayerRenderPass(G),kt=K.defines;kt.push("GLOBE_POLES");const Et=new nr(Xe.LEQUAL,nr.ReadWrite,C.depthRangeFor3D),xt=Float32Array.from(C.transform.expandedFarZProjMatrix),es=Float32Array.from(o.du(o.dv(new o.cn(0,0,0))));C.terrain&&C.terrain.prepareDrawTile(),st.activeTexture.set(Xe.TEXTURE0),De.bind(pt,Xe.CLAMP_TO_EDGE),st.activeTexture.set(Xe.TEXTURE1),De.bind(pt,Xe.CLAMP_TO_EDGE),"useMipmap"in De&&st.extTextureFilterAnisotropic&&C.transform.pitch>20&&Xe.texParameterf(Xe.TEXTURE_2D,st.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,st.extTextureFilterAnisotropicMax);const[Ot,Qt,At,Dt]=g?_e.getPoleBuffers(g.canonical.z,!1):_e.getPoleBuffers(0,!0),Ht=$.paint.get("raster-elevation");let gs;M?(gs=Ot,C.renderDefaultNorthPole=Ht!==0):(gs=Qt,C.renderDefaultSouthPole=Ht!==0);const ss=o_(K.mix),Bs=((rn,hn,Ns,ds,Fs,Us,Ys,Dn,kn,Sn,cn,ur,Nr,rr)=>yx(rn,hn,Ns,ds,new Float32Array(16),new Float32Array(9),[0,0],Fs,[0,0],[0,0,0,0],1,{opacity:1,mix:0},Ys,[0,0],kn,2,cn,ur,Nr,1,0,rr))(C,xt,es,qe,o.al(C.transform.zoom),0,$,0,Ht,0,ss,K.offset,K.range,G),Ps=C.getOrCreateProgram("raster",{defines:kt});C.uploadCommonUniforms(st,Ps,null),Ps.draw(C,Xe.TRIANGLES,Et,de,mt,te,Bs,$.id,gs,At,Dt)}function Lj(M){if(M.isOrthographic)return[0,0,0,0];const g=M._nearZ,C=M.projection.farthestPixelDistance(M),L=C-g,$=.2*M.height,G=g+$;return[g,C,(G-$-g)/L,(G-g)/L]}function Dj(M,g,C,L){if(M)return g instanceof hm&&M instanceof Rh?g.getTextureDescriptor(M,C,!0):{texture:M.texture,mix:o_(L.mix),offset:L.offset,buffer:0,tileSize:1}}var l_=o.e8([{name:"a_index",type:"Int16",components:1}]);class fh{constructor(g,C,L,$){const G={width:L[0],height:L[1],data:null},K=g.gl;this.targetColorTexture=new o.T(g,G,K.RGBA8,{useMipmap:!1}),this.backgroundColorTexture=new o.T(g,G,K.RGBA8,{useMipmap:!1}),this.context=g,this.updateParticleTexture(C,$),this.lastInvalidatedAt=0}updateParticleTexture(g,C){if(this.particleTextureDimension===C.width)return;(this.particleTexture0||this.particleTexture1||this.particleIndexBuffer||this.particleSegment)&&(this.particleTexture0.destroy(),this.particleTexture1.destroy(),this.particleIndexBuffer.destroy(),this.particleSegment.destroy());const L=this.context.gl,$=C.width*C.height;this.particleTexture0=new o.T(this.context,C,L.RGBA8,{premultiply:!1,useMipmap:!1}),this.particleTexture1=new o.T(this.context,C,L.RGBA8,{premultiply:!1,useMipmap:!1});const G=new o.e9;G.reserve($);for(let K=0;K<$;K++)G.emplaceBack(K);this.particleIndexBuffer=this.context.createVertexBuffer(G,l_.members,!0),this.particleSegment=o.dy.simpleSegment(0,0,this.particleIndexBuffer.length,0),this.particleTextureDimension=C.width}update(g){return!(this.lastInvalidatedAt0){const ss=o.ec(C.canonical,de),Bs=o.ed(ss);De=o.aD(new Float32Array(16),de.globeMatrix,Bs),o.aD(De,de.projMatrix,De)}const qe=o.bb();qe[12]+=2*$/(o.o.devicePixelRatio*de.width),qe[13]+=2*G/(o.o.devicePixelRatio*de.height),o.aD(De,qe,De);const st=M.getOrCreateProgram("debug",{defines:Oe}),Xe=g.getTileByID(C.key);M.terrain&&M.terrain.setupElevationDraw(Xe,st);const pt=nr.disabled,mt=ra.disabled,kt=M.colorModeForRenderPass(),Et="$debug";te.activeTexture.set(xe.TEXTURE0),M.emptyTexture.bind(xe.LINEAR,xe.CLAMP_TO_EDGE),_e?Xe._makeGlobeTileDebugBuffers(M.context,de):Xe._makeDebugTileBoundsBuffers(M.context,de.projection);const xt=Xe._tileDebugBuffer||M.debugBuffer,es=Xe._tileDebugIndexBuffer||M.debugIndexBuffer,Ot=Xe._tileDebugSegments||M.debugSegments;if(st.draw(M,xe.LINE_STRIP,pt,mt,kt,Pr.disabled,vm(De,L.toPremultipliedRenderColor(null)),Et,xt,es,Ot,null,null,null,[Xe._globeTileDebugBorderBuffer]),K){const ss=Xe.latestRawTileData,Bs=Math.floor((ss&&ss.byteLength||0)/1024);let Ps=C.canonical.toString();C.overscaledZ!==C.canonical.z&&(Ps+=` => ${C.overscaledZ}`),Ps+=` ${Xe.state}`,Ps+=` ${Bs}kb`,function(rn,hn){rn.initDebugOverlayCanvas();const Ns=rn.debugOverlayCanvas,ds=rn.context.gl,Fs=rn.debugOverlayCanvas.getContext("2d");Fs.clearRect(0,0,Ns.width,Ns.height),Fs.shadowColor="white",Fs.shadowBlur=2,Fs.lineWidth=1.5,Fs.strokeStyle="white",Fs.textBaseline="top",Fs.font="bold 36px Open Sans, sans-serif",Fs.fillText(hn,5,5),Fs.strokeText(hn,5,5),rn.debugOverlayTexture.update(Ns),rn.debugOverlayTexture.bind(ds.LINEAR,ds.CLAMP_TO_EDGE)}(M,Ps)}const Qt=g.getTile(C).tileSize,At=512/Math.min(Qt,512)*(C.overscaledZ/de.zoom)*.5,Dt=Xe._tileDebugTextBuffer||M.debugBuffer,Ht=Xe._tileDebugTextIndexBuffer||M.quadTriangleIndexBuffer,gs=Xe._tileDebugTextSegments||M.debugSegments;st.draw(M,xe.TRIANGLES,pt,mt,Qr.alphaBlended,Pr.disabled,vm(De,o.aq.transparent.toPremultipliedRenderColor(null),At),Et,Dt,Ht,gs,null,null,null,[Xe._globeTileDebugTextBuffer])}function kC(M,g,C,L){fg(M,0,g+C/2,M.transform.width,C,L)}function Rj(M,g,C,L){fg(M,g-C/2,0,C,M.transform.height,L)}function fg(M,g,C,L,$,G){const K=M.context,te=K.gl;te.enable(te.SCISSOR_TEST),te.scissor(g*o.o.devicePixelRatio,C*o.o.devicePixelRatio,L*o.o.devicePixelRatio,$*o.o.devicePixelRatio),K.clear({color:G}),te.disable(te.SCISSOR_TEST)}const b6=o.e8([{name:"a_pos_3f",components:3,type:"Float32"}]),{members:bm}=b6;function Of(M,g,C,L){M.emplaceBack(g,C,L)}class Hd{constructor(g){this.vertexArray=new o.ee,this.indices=new o.dC,Of(this.vertexArray,-1,-1,1),Of(this.vertexArray,1,-1,1),Of(this.vertexArray,-1,1,1),Of(this.vertexArray,1,1,1),Of(this.vertexArray,-1,-1,-1),Of(this.vertexArray,1,-1,-1),Of(this.vertexArray,-1,1,-1),Of(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=g.createVertexBuffer(this.vertexArray,bm),this.indexBuffer=g.createIndexBuffer(this.indices),this.segment=o.dy.simpleSegment(0,0,36,12)}}function qp(M,g,C,L,$,G){const K=M.context.gl,te=g.paint.get("sky-atmosphere-color"),de=g.paint.get("sky-atmosphere-halo-color"),xe=g.paint.get("sky-atmosphere-sun-intensity"),_e=((Oe,De,qe,st,Xe)=>({u_matrix_3f:Oe,u_sun_direction:De,u_sun_intensity:qe,u_color_tint_r:[st.r,st.g,st.b,st.a],u_color_tint_m:[Xe.r,Xe.g,Xe.b,Xe.a],u_luminance:5e-5}))(o.eg(o.dE(),L),$,xe,te.toPremultipliedRenderColor(null),de.toPremultipliedRenderColor(null));K.framebufferTexture2D(K.FRAMEBUFFER,K.COLOR_ATTACHMENT0,K.TEXTURE_CUBE_MAP_POSITIVE_X+G,g.skyboxTexture,0),C.draw(M,K.TRIANGLES,nr.disabled,ra.disabled,Qr.unblended,Pr.frontCW,_e,"skyboxCapture",g.skyboxGeometry.vertexBuffer,g.skyboxGeometry.indexBuffer,g.skyboxGeometry.segment)}const _6=o.e8([{type:"Float32",name:"a_pos",components:3},{type:"Float32",name:"a_uv",components:2}]);class KN{constructor(g){const C=new o.eh;C.emplaceBack(-1,1,1,0,0),C.emplaceBack(1,1,1,1,0),C.emplaceBack(1,-1,1,1,1),C.emplaceBack(-1,-1,1,0,1);const L=new o.dC;L.emplaceBack(0,1,2),L.emplaceBack(2,3,0),this.vertexBuffer=g.createVertexBuffer(C,_6.members),this.indexBuffer=g.createIndexBuffer(L),this.segments=o.dy.simpleSegment(0,0,4,2)}destroy(){this.vertexBuffer.destroy(),this.indexBuffer.destroy(),this.segments.destroy()}}const YN=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 w0{constructor(){this.starsCount=16e3,this.sizeMultiplier=.15,this.sizeRange=100,this.intensityRange=200}}class w6{constructor(g){this.colorModeAlphaBlendedWriteRGB=new Qr([1,Al,1,Al],o.aq.transparent,[!0,!0,!0,!1]),this.colorModeWriteAlpha=new Qr([1,0,1,0],o.aq.transparent,[!1,!1,!1,!0]),this.params=new w0,this.updateNeeded=!0}update(g){const C=g.context;if(!this.atmosphereBuffer||this.updateNeeded){this.updateNeeded=!1,this.atmosphereBuffer=new KN(C);const L=this.params.sizeRange,$=this.params.intensityRange,G=function(_e){const Oe=o.em(30),De=[];for(let qe=0;qe<_e;++qe){const st=2*Math.PI*Oe(),Xe=Math.acos(1-2*Oe())-.5*Math.PI;De.push(o.cQ(Math.cos(Xe)*Math.cos(st),Math.cos(Xe)*Math.sin(st),Math.sin(Xe)))}return De}(this.params.starsCount),K=o.em(300),te=new o.ei,de=new o.dC;let xe=0;for(let _e=0;_e{const At=G.projection.name==="globe"?["PROJECTION_GLOBE_VIEW","FOG"]:["FOG"];Qt&&At.push("ALPHA_PASS");const Dt=g.getOrCreateProgram("globeAtmosphere",{defines:At}),Ht=((ss,Bs,Ps,rn,hn,Ns,ds,Fs,Us,Ys,Dn,kn)=>({u_frustum_tl:ss,u_frustum_tr:Bs,u_frustum_br:Ps,u_frustum_bl:rn,u_horizon:hn,u_transition:Ns,u_fadeout_range:ds,u_atmosphere_fog_color:Fs.toArray01(),u_high_color:Us.toArray01(),u_space_color:Ys.toArray01(),u_temporal_offset:Dn,u_horizon_angle:kn}))(G.frustumCorners.TL,G.frustumCorners.TR,G.frustumCorners.BR,G.frustumCorners.BL,G.frustumCorners.horizon,te,pt,_e,De,st,kt,es);g.uploadCommonUniforms(L,Dt);const gs=this.atmosphereBuffer;gs&&Dt.draw(g,$.TRIANGLES,K,ra.disabled,Qt?this.colorModeWriteAlpha:this.colorModeAlphaBlendedWriteRGB,Pr.backCW,Ht,Qt?"atmosphere_glow_alpha":"atmosphere_glow",gs.vertexBuffer,gs.indexBuffer,gs.segments)};Ot(!1),Ot(!0)}drawStars(g,C){const L=o.aC(C.properties.get("star-intensity"),0,1);if(L===0)return;const $=g.context,G=$.gl,K=g.transform,te=g.getOrCreateProgram("stars"),de=o.bL([]);o.bN(de,de,-K._pitch),o.bM(de,de,-K.angle),o.bN(de,de,o.ap(K._center.lat)),o.ek(de,de,-o.ap(K._center.lng));const xe=o.bR(new Float32Array(16),de),_e=o.aD([],K.starsProjMatrix,xe),Oe=o.eg([],xe),De=o.el([],Oe),qe=[0,1,0];o.dG(qe,qe,De),o.bJ(qe,qe,this.params.sizeMultiplier);const st=[1,0,0];o.dG(st,st,De),o.bJ(st,st,this.params.sizeMultiplier);const Xe=(pt=qe,mt=st,kt=L,{u_matrix:Float32Array.from(_e),u_up:pt,u_right:mt,u_intensity_multiplier:kt});var pt,mt,kt;g.uploadCommonUniforms($,te),this.starsVx&&this.starsIdx&&te.draw(g,G.TRIANGLES,nr.disabled,ra.disabled,this.colorModeAlphaBlendedWriteRGB,Pr.disabled,Xe,"atmosphere_stars",this.starsVx,this.starsIdx,this.starsSegments)}}class _m{constructor(){this.visibleTiles=[]}updateBorders(g,C){const L=[],$=[],G=g._getRenderableCoordinates(!1,!0);for(const de of G){const xe=g.getTile(de);if(!xe.hasData())continue;const _e=xe.getBucket(C);_e&&(_e.isEmpty()||(L.push(de.key),$.push({bucket:_e,tileID:de.canonical})))}let K=L.length!==this.visibleTiles.length;if(!K){L.sort();for(let de=0;dede.tileID.z-xe.tileID.z||de.tileID.x-xe.tileID.x||de.tileID.y-xe.tileID.y);for(const de of $){const xe=new Array,_e=new Array,Oe=de.bucket;for(const De of Oe.featuresOnBorder)te.has(De.featureId)?_e.push(De.footprintIndex):(te.add(De.featureId),xe.push(De.footprintIndex));Oe.updateFootprintHiddenFlags(xe,o.en,!1),Oe.updateFootprintHiddenFlags(_e,o.en,!0)}}}function SC(M,g){const C=[...M],L=g.cameraWorldSizeForFog/g.worldSize,$=o.b9([]);return o.cC($,$,[L,L,1]),o.aD(C,$,C),o.aD(C,g.worldToFogMatrix,C),C}function Aa(M,g,C,L,$){const G=C.material,K=L.context,{baseColorTexture:te,metallicRoughnessTexture:de}=G.pbrMetallicRoughness,{normalTexture:xe,occlusionTexture:_e,emissionTexture:Oe}=G;function De(st,Xe,pt){if(st&&(M.push(Xe),K.activeTexture.set(K.gl.TEXTURE0+pt),st.gfxTexture)){const{minFilter:mt,magFilter:kt,wrapS:Et,wrapT:xt}=st.sampler;st.gfxTexture.bindExtraParam(mt,kt,Et,xt)}}De(te,"HAS_TEXTURE_u_baseColorTexture",5),De(de,"HAS_TEXTURE_u_metallicRoughnessTexture",6),De(xe,"HAS_TEXTURE_u_normalTexture",7),De(_e,"HAS_TEXTURE_u_occlusionTexture",8),De(Oe,"HAS_TEXTURE_u_emissionTexture",9),$&&($.texture||($.texture=new o.dR(L.context,$.image,[$.image.height,$.image.height,$.image.height],K.gl.RGBA8)),K.activeTexture.set(K.gl.TEXTURE0+10),$.texture&&$.texture.bind(K.gl.LINEAR,K.gl.CLAMP_TO_EDGE),M.push("APPLY_LUT_ON_GPU")),C.texcoordBuffer&&(M.push("HAS_ATTRIBUTE_a_uv_2f"),g.push(C.texcoordBuffer)),C.colorBuffer&&(M.push(C.colorBuffer.itemSize===12?"HAS_ATTRIBUTE_a_color_3f":"HAS_ATTRIBUTE_a_color_4f"),g.push(C.colorBuffer)),C.normalBuffer&&(M.push("HAS_ATTRIBUTE_a_normal_3f"),g.push(C.normalBuffer)),C.pbrBuffer&&(M.push("HAS_ATTRIBUTE_a_pbr"),M.push("HAS_ATTRIBUTE_a_heightBasedEmissiveStrength"),g.push(C.pbrBuffer)),G.alphaMode!=="OPAQUE"&&G.alphaMode!=="MASK"||M.push("UNPREMULT_TEXTURE_IN_SHADER"),G.defined||M.push("DIFFUSE_SHADED");const qe=L.shadowRenderer;qe&&(M.push("RENDER_SHADOWS"),qe.useNormalOffset&&M.push("NORMAL_OFFSET"))}function c_(M,g,C,L,$,G){const K=M.modelOpacity,te=g.context,de=new nr(g.context.gl.LEQUAL,M.isLightMesh?nr.ReadOnly:nr.ReadWrite,g.depthRangeFor3D),xe=g.transform,_e=M.mesh,Oe=_e.material,De=Oe.pbrMetallicRoughness,qe=g.style.fog;let st;st=g.transform.projection.zAxisUnit==="pixels"?[...M.nodeModelMatrix]:o.aD([],L.zScaleMatrix,M.nodeModelMatrix),o.aD(st,L.negCameraPosMatrix,st);const Xe=o.b7([],st);o.e6(Xe,Xe);const pt=C.paint.get("model-color-use-theme").constantOr("default")==="none",mt=C.paint.get("model-emissive-strength").constantOr(0),kt=_x(new Float32Array(M.worldViewProjection),new Float32Array(st),new Float32Array(Xe),null,g,K,De.baseColorFactor,Oe.emissiveFactor,De.metallicFactor,De.roughnessFactor,Oe,mt,C,void 0,void 0,M.materialOverride,M.modelColor),Et={defines:[]},xt=[],es=g.shadowRenderer;es&&(es.useNormalOffset=!1),Aa(Et.defines,xt,_e,g,pt?null:C.lut);let Ot=null;if(qe){const Dt=SC(M.nodeModelMatrix,g.transform);if(Ot=new Float32Array(Dt),xe.projection.name!=="globe"){const Ht=_e.aabb.min,gs=_e.aabb.max,[ss,Bs]=qe.getOpacityForBounds(Dt,Ht[0],Ht[1],gs[0],gs[1]);Et.overrideFog=ss>=Er||Bs>=Er}}const Qt=Dc(g,C.paint.get("model-cutoff-fade-range"));Qt.shouldRenderCutoff&&Et.defines.push("RENDER_CUTOFF");const At=g.getOrCreateProgram("model",Et);g.uploadCommonUniforms(te,At,null,Ot,Qt),g.renderPass!=="shadow"&&es&&es.setupShadowsFromMatrix(M.nodeModelMatrix,At),At.draw(g,te.gl.TRIANGLES,de,$,G,_e.material.doubleSided?Pr.disabled:Pr.backCCW,kt,C.id,_e.vertexBuffer,_e.indexBuffer,_e.segments,C.paint,g.transform.zoom,void 0,xt)}function Oj(M,g){return M.style._importedAsBasemap?"basemap":g.scope}function ZN(M,g,C,L,$,G,K,te,de,xe){const _e=M.transform,Oe=!!g.isGeometryBloom&&g.isGeometryBloom;if(Oe&&M.renderPass==="shadow")return;const De=_e.projection.name==="globe"?o.ev(C,_e):[...C];o.aD(De,De,g.globalMatrix);const qe=o.aD([],L,De);if(g.meshes)for(const st of g.meshes){const Xe=te.get(st.material.name);if(Xe&&Xe.opacity<=0)continue;if(st.material.alphaMode!=="BLEND"){K.push({mesh:st,depth:0,modelIndex:$,worldViewProjection:qe,nodeModelMatrix:De,isLightMesh:Oe,materialOverride:Xe,modelOpacity:de,modelColor:xe,node:g,modelMatrix:C});continue}const pt=o.ah([],st.centroid,qe);!_e.isOrthographic&&pt[2]<=0||G.push({mesh:st,depth:pt[2],modelIndex:$,worldViewProjection:qe,nodeModelMatrix:De,isLightMesh:Oe,materialOverride:Xe,modelOpacity:de,modelColor:xe,node:g,modelMatrix:C})}if(g.children)for(const st of g.children)ZN(M,st,C,L,$,G,K,te,de,xe)}function d_(M,g,C,L){const $=C.shadowRenderer;if(!$)return;const G=$.getShadowPassDepthMode(),K=$.calculateShadowPassMatrixFromMatrix(g),te=Aj(K);C.getOrCreateProgram("modelDepth").draw(C,C.context.gl.TRIANGLES,G,ra.disabled,Qr.disabled,Pr.disabled,te,L.id,M.vertexBuffer,M.indexBuffer,M.segments,L.paint,C.transform.zoom,void 0,void 0)}function QN(M,g,C,L){const $=function(_e,Oe){if(Oe.footprintDebugMesh)return Oe.footprintDebugMesh;if(!Oe.footprint)return null;const De=_e.context,qe=Oe.footprint.vertices,st=Oe.footprint.indices,Xe=new o.dB;Xe.reserve(qe.length);for(const Ht of qe)Xe.emplaceBack(Ht.x,Ht.y);const pt=new o.dC;pt.reserve(st.length);for(let Ht=0;Ht0){const De=G.terrain,qe=De.findDEMTileFor(te);qe&&qe.dem?de=o.ex.create(De,te,qe):Oe=0}if(Oe===0&&(K.terrainElevationMin=0,K.terrainElevationMax=0),Oe===K.validForExaggeration&&(Oe===0||de&&de._demTile&&de._demTile.tileID===K.validForDEMTile.id&&de._dem._timestamp===K.validForDEMTile.timestamp))return!1;for(const De in K.instancesPerModel){const qe=K.instancesPerModel[De];for(let st=0;stxe&&(xe=qe.max)}const _e=o.aC(L.x,G,K)-L.x,Oe=o.aC(L.y,te,de)-L.y,De=o.bU(xe,g.center.lat)-L.z;return g._zoomFromMercatorZ(Math.sqrt(_e*_e+Oe*Oe+De*De))}function qo(M,g,C,L,$,G,K){const te=M.context,de=M.renderPass==="shadow",xe=M.shadowRenderer,_e=de&&xe?xe.getShadowPassDepthMode():new nr(te.gl.LEQUAL,nr.ReadWrite,M.depthRangeFor3D),Oe=M.isTileAffectedByFog(G),De=M.transform.projection.name==="globe";if(C.meshes)for(const qe of C.meshes){const st=De?[]:["MODEL_POSITION_ON_GPU"],Xe=[];let pt,mt,kt;const Et=!De&&L.instancedDataArray.length>20;Et&&st.push("INSTANCED_ARRAYS");const xt=Dc(M,g.paint.get("model-cutoff-fade-range"));if(xt.shouldRenderCutoff&&st.push("RENDER_CUTOFF"),de&&xe)pt=M.getOrCreateProgram("modelDepth",{defines:st}),mt=Aj(K.shadowTileMatrix,K.shadowTileMatrix,Float32Array.from(C.globalMatrix)),kt=Qr.disabled;else{Aa(st,Xe,qe,M,g.paint.get("model-color-use-theme").constantOr("default")==="none"?null:g.lut),pt=M.getOrCreateProgram("model",{defines:st,overrideFog:Oe});const Ot=qe.material,Qt=Ot.pbrMetallicRoughness,At=g.paint.get("model-opacity").constantOr(1),Dt=g.paint.get("model-emissive-strength").constantOr(0);mt=_x(G.expandedProjMatrix,Float32Array.from(C.globalMatrix),new Float32Array(16),null,M,At,Qt.baseColorFactor,Ot.emissiveFactor,Qt.metallicFactor,Qt.roughnessFactor,Ot,Dt,g,$),xe&&(K.shadowUniformsInitialized?pt.setShadowUniformValues(te,xe.getShadowUniformValues()):(xe.setupShadows(G.toUnwrapped(),pt,"model-tile"),K.shadowUniformsInitialized=!0)),kt=xt.shouldRenderCutoff||At<1||Ot.alphaMode!=="OPAQUE"?Qr.alphaBlended:Qr.unblended}M.uploadCommonUniforms(te,pt,G.toUnwrapped(),null,xt);const es=qe.material.doubleSided?Pr.disabled:Pr.backCCW;if(Et)Xe.push(L.instancedDataBuffer),pt.draw(M,te.gl.TRIANGLES,_e,ra.disabled,kt,es,mt,g.id,qe.vertexBuffer,qe.indexBuffer,qe.segments,g.paint,M.transform.zoom,void 0,Xe,L.instancedDataArray.length);else{const Ot=de?"u_instance":"u_normal_matrix";for(let Qt=0;Qtde[1]?K:de,G[0]=C.max[0],K=o.aE(o.bE(),G,$),te=K[1]de[1]?K:de,G[1]=C.min[1],K=o.aE(o.bE(),G,$),te=K[1]de[1]?K:de;const xe=o.aC(L[0],0,1),_e=100*g.pixelsPerMeter*o.aC(L[1],0,1),Oe=o.aC(L[2],0,1),De=o.ey(o.bE(),te,de,xe),qe=Math.tan(.5*g.fovX),st=-De[2]*qe;if(_e===0)return De[1]<-Math.abs(st)?Oe:1;const Xe=(-Math.abs(st)-De[1])/_e,pt=(kt,Et,xt)=>(1-xt)*kt+xt*Et,mt=o.aC(pt(1,Oe,Xe),Oe,1);return pt(1,mt,o.aC((g.pitch-20)/20,0,1))}class JN{}class CC{constructor(){this._storage=new Map}getLinesFromTrianglesBuffer(g,C,L){{const Oe=this._storage.get(C.id);if(Oe)return Oe.lastUsedFrameIdx=g,Oe.buf}const $=L.gl,G=$.getBufferParameter($.ELEMENT_ARRAY_BUFFER,$.BUFFER_SIZE),K=new ArrayBuffer(G),te=new Int16Array(K);$.getBufferSubData($.ELEMENT_ARRAY_BUFFER,0,new Int16Array(K));const de=new o.eA;for(let Oe=0;Oe30&&(L.buf.destroy(),this._storage.delete(C))}destroy(){for(const[g,C]of this._storage)C.buf.destroy(),this._storage.delete(g)}}class TC{constructor(){this.occluderSize=30,this.depthOffset=-1e-4}}const j1=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 EC{constructor(g){this.revealStart=11,this.revealRange=2}}const ek=o.e8([{type:"Float32",name:"a_pos_2f",components:2}]);class j6{destroy(){this.vignetteVx&&this.vignetteVx.destroy(),this.vignetteIdx&&this.vignetteIdx.destroy()}draw(g,C){const L=g.getOrCreateProgram("vignette");if(!this.vignetteVx||!this.vignetteIdx){const K=new o.eB,te=new o.dC;K.emplaceBack(-1,-1),K.emplaceBack(1,-1),K.emplaceBack(1,1),K.emplaceBack(-1,1),te.emplaceBack(0,1,2),te.emplaceBack(0,2,3),this.vignetteVx=g.context.createVertexBuffer(K,ek.members),this.vignetteIdx=g.context.createIndexBuffer(te)}const $=o.dy.simpleSegment(0,0,4,6);if(this.vignetteVx&&this.vignetteIdx){g.uploadCommonUniforms(g.context,L);const K={u_vignetteShape:(G={vignetteShape:[C.start,C.range,Math.pow(10,C.fadePower)],vignetteColor:[C.color.r,C.color.g,C.color.b,C.color.a*C.strength]}).vignetteShape,u_vignetteColor:G.vignetteColor};L.draw(g,g.context.gl.TRIANGLES,nr.disabled,ra.disabled,Qr.alphaBlended,Pr.disabled,K,"vignette",this.vignetteVx,this.vignetteIdx,$)}var G}}class tk{constructor(){this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0}update(g,C){const L=g.getFreeCameraOptions().position,$=L.toAltitude(),G=L.toLngLat(),K=o.ap(G.lng),te=o.ap(G.lat),de=g.pixelsPerMeter/C,xe=K*o.eD,_e=o.eD*Math.log(Math.tan(Math.PI/4+te/2));if(this._offsetXPrev===void 0)this._offsetXPrev=0,this._offsetYPrev=0,this._elevationPrev=0,this._accumulatedOffsetX=0,this._accumulatedOffsetY=0,this._accumulatedElevation=0;else{const Oe=-this._offsetYPrev+_e,De=-this._elevationPrev+$;this._accumulatedOffsetX+=(-this._offsetXPrev+xe)*de,this._accumulatedOffsetY+=Oe*de,this._accumulatedElevation+=De*de,this._offsetXPrev=xe,this._offsetYPrev=_e,this._elevationPrev=$}}getPosition(){return[this._accumulatedOffsetX,this._accumulatedOffsetY,this._accumulatedElevation]}}function Q(M,g){return[-(M[0]-Math.floor(M[0]/g)*g),-(M[1]-Math.floor(M[1]/g)*g),-(M[2]-Math.floor(M[2]/g)*g)]}function J(M){const g=o.em(1323123451230),C=[];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(g){const C=g.context;if(!this.particlesVx){const L=J(this.particlesCount),$=new o.eE,G=new o.dC;let K=0;const te=o.em(1323123451230);for(let de=0;deL)return;const $=Ne(0,1,C.revealStart,C.revealStart+C.revealRange,L);if(!this.particlesVx||!this.particlesIdx)return;const G=structuredClone(this._params);let K=[-G.direction.x,G.direction.y,-100];o.ay(K,K);const te=structuredClone(this._vignetteParams);te.strength*=$,G.overrideStyleParameters||(G.intensity=g.style.rain.state.density,G.timeFactor=g.style.rain.state.intensity,G.color=structuredClone(g.style.rain.state.color),K=structuredClone(g.style.rain.state.direction),G.screenThinning.intensity=g.style.rain.state.centerThinning,G.dropletSizeX=g.style.rain.state.dropletSize[0],G.dropletSizeYScale=g.style.rain.state.dropletSize[1]/g.style.rain.state.dropletSize[0],G.distortionStrength=100*g.style.rain.state.distortionStrength,te.strength=1,te.color=structuredClone(g.style.rain.state.vignetteColor));const de=this.updateOnRender(g,G.timeFactor),xe=g.context,_e=xe.gl,Oe=g.transform;this.screenTexture&&this.screenTexture.size[0]===g.width&&this.screenTexture.size[1]===g.height||(this.screenTexture=new o.T(xe,{width:g.width,height:g.height,data:null},_e.RGBA8)),G.distortionStrength>0&&(xe.activeTexture.set(_e.TEXTURE0),this.screenTexture.bind(_e.LINEAR,_e.CLAMP_TO_EDGE),_e.copyTexSubImage2D(_e.TEXTURE_2D,0,0,0,0,0,g.width,g.height));const De=g.getOrCreateProgram("rainParticle");g.uploadCommonUniforms(xe,De),xe.activeTexture.set(_e.TEXTURE0),this.screenTexture.bind(_e.LINEAR,_e.CLAMP_TO_EDGE);const qe=[G.color.r,G.color.g,G.color.b,G.color.a],st=(Xe,pt)=>{const mt=Q(this._movement.getPosition(),Xe),kt=G.dropletSizeX,Et=G.dropletSizeX*G.dropletSizeYScale,xt=g.width/2,es=g.height/2,Ot=Ne(0,G.screenThinning.start,0,1,G.screenThinning.intensity),Qt=Ne(.001,G.screenThinning.range,0,1,G.screenThinning.intensity),At=Ne(0,G.screenThinning.particleOffset,0,1,G.screenThinning.intensity),Dt=(Ht={modelview:de.modelviewMatrix,projection:de.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:mt,velocityConeAperture:G.velocityConeAperture,velocity:G.velocity,boxSize:Xe,rainDropletSize:[kt,Et],distortionStrength:G.distortionStrength,rainDirection:K,color:qe,screenSize:[Oe.width,Oe.height],thinningCenterPos:[xt,es],thinningShape:[Ot,Qt,Math.pow(10,G.screenThinning.fadePower)],thinningAffectedRatio:G.screenThinning.affectedRatio,thinningParticleOffset:At,shapeDirectionalPower:G.shapeDirPower,shapeNormalPower:G.shapeNormalPower,mode:pt?0:1},{u_modelview:Float32Array.from(Ht.modelview),u_projection:Float32Array.from(Ht.projection),u_time:Ht.time,u_cam_pos:Ht.camPos,u_texScreen:0,u_velocityConeAperture:Ht.velocityConeAperture,u_velocity:Ht.velocity,u_boxSize:Ht.boxSize,u_rainDropletSize:Ht.rainDropletSize,u_distortionStrength:Ht.distortionStrength,u_rainDirection:Ht.rainDirection,u_color:Ht.color,u_screenSize:Ht.screenSize,u_thinningCenterPos:Ht.thinningCenterPos,u_thinningShape:Ht.thinningShape,u_thinningAffectedRatio:Ht.thinningAffectedRatio,u_thinningParticleOffset:Ht.thinningParticleOffset,u_shapeDirectionalPower:Ht.shapeDirectionalPower,u_shapeNormalPower:Ht.shapeNormalPower,u_mode:Ht.mode});var Ht;const gs=Math.round(G.intensity*this.particlesCount),ss=o.dy.simpleSegment(0,0,4*gs,2*gs);De.draw(g,_e.TRIANGLES,nr.disabled,ra.disabled,Qr.alphaBlended,Pr.disabled,Dt,"rain_particles",this.particlesVx,this.particlesIdx,ss)};G.distortionStrength>0&&st(G.boxSize,!0),st(G.boxSize,!1),this._vignette.draw(g,te)}}const vt=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 ms extends Ve{constructor(g){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 EC("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(g){const C=g.context;if(!this.particlesVx){const L=J(this.particlesCount),$=new o.eF,G=new o.dC;let K=0;const te=o.em(1323123451230);for(let de=0;deK)return;const te=Ne(0,1,G.revealStart,G.revealStart+G.revealRange,K);$.strength*=te,C.overrideStyleParameters||(C.intensity=g.style.snow.state.density,C.timeFactor=g.style.snow.state.intensity,C.color=structuredClone(g.style.snow.state.color),L=structuredClone(g.style.snow.state.direction),C.screenThinning.intensity=g.style.snow.state.centerThinning,C.billboardSize=2.79*g.style.snow.state.flakeSize,$.strength=1,$.color=structuredClone(g.style.snow.state.vignetteColor));const de=this.updateOnRender(g,C.timeFactor);if(!this.particlesVx||!this.particlesIdx)return;const xe=g.context,_e=xe.gl,Oe=g.transform,De=g.getOrCreateProgram("snowParticle");g.uploadCommonUniforms(xe,De),((qe,st,Xe)=>{const pt=Q(this._movement.getPosition(),qe),mt=Oe.width/2,kt=Oe.height/2,Et=Ne(0,Xe.screenThinning.start,0,1,Xe.screenThinning.intensity),xt=Ne(.001,Xe.screenThinning.range,0,1,Xe.screenThinning.intensity),es=Ne(0,Xe.screenThinning.particleOffset,0,1,Xe.screenThinning.intensity),Ot=(Qt={modelview:de.modelviewMatrix,projection:de.projectionMatrix,time:this._accumulatedTimeFromStart,camPos:pt,velocityConeAperture:Xe.velocityConeAperture,velocity:Xe.velocity,horizontalOscillationRadius:Xe.horizontalOscillationRadius,horizontalOscillationRate:Xe.horizontalOscillationRate,boxSize:qe,billboardSize:1*Xe.billboardSize,simpleShapeParameters:[Xe.shapeFadeStart,Xe.shapeFadePower],screenSize:[Oe.width,Oe.height],thinningCenterPos:[mt,kt],thinningShape:[Et,xt,Math.pow(10,Xe.screenThinning.fadePower)],thinningAffectedRatio:Xe.screenThinning.affectedRatio,thinningParticleOffset:es,color:[Xe.color.r,Xe.color.g,Xe.color.b,Xe.color.a],direction:L},{u_modelview:Float32Array.from(Qt.modelview),u_projection:Float32Array.from(Qt.projection),u_time:Qt.time,u_cam_pos:Qt.camPos,u_velocityConeAperture:Qt.velocityConeAperture,u_velocity:Qt.velocity,u_horizontalOscillationRadius:Qt.horizontalOscillationRadius,u_horizontalOscillationRate:Qt.horizontalOscillationRate,u_boxSize:Qt.boxSize,u_billboardSize:Qt.billboardSize,u_simpleShapeParameters:Qt.simpleShapeParameters,u_screenSize:Qt.screenSize,u_thinningCenterPos:Qt.thinningCenterPos,u_thinningShape:Qt.thinningShape,u_thinningAffectedRatio:Qt.thinningAffectedRatio,u_thinningParticleOffset:Qt.thinningParticleOffset,u_particleColor:Qt.color,u_direction:Qt.direction});var Qt;const At=Math.round(Xe.intensity*this.particlesCount),Dt=o.dy.simpleSegment(0,0,4*At,2*At);this.particlesVx&&this.particlesIdx&&De.draw(g,_e.TRIANGLES,nr.disabled,ra.disabled,Qr.alphaBlended,Pr.disabled,Ot,"snow_particles",this.particlesVx,this.particlesIdx,Dt)})(C.boxSize,0,C),this._vignette.draw(g,$)}}const pn={symbol:function(M,g,C,L,$){if(M.renderPass!=="translucent")return;const G=ra.disabled,K=M.colorModeForRenderPass(),te=C.layout.get("text-variable-anchor"),de=C.layout.get("text-size-scale-range"),xe=o.aC(M.scaleFactor,de[0],de[1]);te&&function(De,qe,st,Xe,pt,mt,kt,Et){const xt=qe.transform,es=pt==="map",Ot=mt==="map";for(const Qt of De){const At=Xe.getTile(Qt),Dt=At.getBucket(st);if(!Dt||!Dt.text||!Dt.text.segments.get().length)continue;const Ht=o.bj(Dt.textSizeData,xt.zoom,Et),gs=Qm(Qt,Dt.getProjection(),xt),ss=xt.calculatePixelsToTileUnitsMatrix(At),Bs=Nd(gs,At.tileID.canonical,Ot,es,xt,Dt.getProjection(),ss),Ps=Dt.hasIconTextFit()&&Dt.hasIconData();Ht&&Gu(Dt,es,Ot,kt,xt,Bs,Qt,Math.pow(2,xt.zoom-At.tileID.overscaledZ),Ht,Ps)}}(L,M,C,g,C.layout.get("text-rotation-alignment"),C.layout.get("text-pitch-alignment"),$,xe);const _e=C.paint.get("icon-opacity").constantOr(1)!==0,Oe=C.paint.get("text-opacity").constantOr(1)!==0;C.layout.get("symbol-sort-key").constantOr(1)!==void 0&&(_e||Oe)?Bh(M,g,C,L,G,K):(_e&&Bh(M,g,C,L,G,K,{onlyIcons:!0}),Oe&&Bh(M,g,C,L,G,K,{onlyText:!0})),g.map.showCollisionBoxes&&(Kn(M,g,C,L,C.paint.get("text-translate"),C.paint.get("text-translate-anchor"),!0),Kn(M,g,C,L,C.paint.get("icon-translate"),C.paint.get("icon-translate-anchor"),!1))},circle:function(M,g,C,L){if(M.renderPass!=="translucent")return;const $=C.paint.get("circle-opacity"),G=C.paint.get("circle-stroke-width"),K=C.paint.get("circle-stroke-opacity"),te=C.layout.get("circle-sort-key").constantOr(1)!==void 0,de=C.paint.get("circle-emissive-strength");if($.constantOr(1)===0&&(G.constantOr(1)===0||K.constantOr(1)===0))return;const xe=M.context,_e=xe.gl,Oe=M.transform,De=!(!M.terrain||!M.terrain.enabled),qe=C.layout.get("circle-elevation-reference"),st=M.depthModeForSublayer(0,nr.ReadOnly),Xe=new nr(M.context.gl.LEQUAL,nr.ReadOnly,M.depthRangeFor3D),pt=qe==="none"||De?st:Xe,mt=ra.disabled,kt=M.colorModeForDrapableLayerRenderPass(de),Et=Oe.projection.name==="globe",xt=[o.aH(Oe.center.lng),o.aL(Oe.center.lat)],es=[];for(let Qt=0;QtQt.sortKey-At.sortKey);const Ot={useDepthForOcclusion:Oe.depthOcclusionForSymbolsAndCircles};for(const Qt of es){const{programConfiguration:At,program:Dt,layoutVertexBuffer:Ht,dynamicBuffers:gs,indexBuffer:ss,uniformValues:Bs,tile:Ps}=Qt.state,rn=Qt.segments;M.terrain&&M.terrain.setupElevationDraw(Ps,Dt,Ot),M.uploadCommonUniforms(xe,Dt,Ps.tileID.toUnwrapped()),Dt.draw(M,_e.TRIANGLES,pt,mt,kt,Pr.disabled,Bs,C.id,Ht,ss,rn,C.paint,Oe.zoom,At,gs)}},heatmap:function(M,g,C,L){if(C.paint.get("heatmap-opacity")!==0)if(M.renderPass==="offscreen"){const $=M.context,G=$.gl,K=ra.disabled,te=new Qr([G.ONE,G.ONE,G.ONE,G.ONE],o.aq.transparent,[!0,!0,!0,!0]),de=M.transform.projection.name==="globe"?.5:.25;C.heatmapFbo=Mj.createWithTexture($,C.heatmapFbo,M.width*de,M.height*de),$.clear({color:o.aq.transparent});const xe=M.transform,_e=xe.projection.name==="globe",Oe=_e?["PROJECTION_GLOBE_VIEW"]:[],De=_e?Pr.frontCCW:Pr.disabled,qe=[o.aH(xe.center.lng),o.aL(xe.center.lat)];for(let st=0;st({u_image:0,u_color_ramp:1,u_opacity:Oe.paint.get("heatmap-opacity")}))(0,G),G.id,$.viewportBuffer,$.quadTriangleIndexBuffer,$.viewportSegments,G.paint,$.transform.zoom)}(M,C))},line:function(M,g,C,L){const $=C.paint.get("line-opacity"),G=C.paint.get("line-width");if($.constantOr(1)===0||G.constantOr(1)===0)return;const K=C.paint.get("line-blend-mode");if(K!=="default"&&M.transform.projection.name!=="globe")return M.terrain&&M.terrain.renderingToTexture?void function(te,de,xe,_e,Oe){if(te.renderPass!=="translucent")return;const De=te.context,qe=De.gl,st=te.terrain;if(!st)return;const Xe=De.bindFramebuffer.current,pt=te.emissiveMode==="mrt-fallback";xe.lineBlendDrapeFbo=Mj.createWithTexture(De,xe.lineBlendDrapeFbo,st.drapeBufferSize[0],st.drapeBufferSize[1],!0),xe.lineBlendDrapeStencil=xe.lineBlendDrapeFbo._stencilRbo,pt&&qe.drawBuffers([qe.COLOR_ATTACHMENT0]),De.clear({color:Up[Oe].clearColor,depth:1,stencil:0});const mt=te.currentStencilSource,kt=te._tileClippingMaskIDs,Et=te.nextStencilID;te.currentStencilSource=void 0,te._tileClippingMaskIDs={},te.nextStencilID=1;const xt=te._terrain;te._terrain=null,te._renderTileClippingMasks(xe,de,_e),ld(te,de,xe,_e,Up[Oe].colorMode,!0),te._terrain=xt,te.currentStencilSource=mt,te._tileClippingMaskIDs=kt,te.nextStencilID=Et,De.bindFramebuffer.set(Xe),pt&&qe.drawBuffers([qe.COLOR_ATTACHMENT0,qe.COLOR_ATTACHMENT1]);const es=st.drapeBufferSize;De.viewport.set([0,0,es[0],es[1]]);const Ot=xe.lineBlendDrapeFbo;if(!Ot)return;De.activeTexture.set(qe.TEXTURE0),qe.bindTexture(qe.TEXTURE_2D,Ot.colorAttachment0.get());const Qt=Oe==="additive"?1:xe.paint.get("line-opacity").constantOr(1),At=xe.paint.get("line-emissive-strength").constantOr(0),Dt=Oe==="additive"?te.colorModeForDrapableLayerRenderPass(At):Up[Oe].colorMode;te.getOrCreateProgram("lineBlendComposite").draw(te,qe.TRIANGLES,nr.disabled,ra.disabled,Dt,Pr.disabled,Cj(0,Qt,Up[Oe].compositeUniformValue),xe.id,te.viewportBuffer,te.quadTriangleIndexBuffer,te.viewportSegments,xe.paint,te.transform.zoom)}(M,g,C,L,K):M.renderPass==="offscreen"?void function(te,de,xe,_e,Oe){const De=te.context,qe=Math.ceil(te.width),st=Math.ceil(te.height);xe.lineBlendFbo=Mj.createWithTexture(De,xe.lineBlendFbo,qe,st,!0),xe.lineBlendStencil=xe.lineBlendFbo._stencilRbo,De.clear({color:Up[Oe].clearColor,depth:1,stencil:0});const Xe=te.currentStencilSource,pt=te._tileClippingMaskIDs,mt=te.nextStencilID;te.currentStencilSource=void 0,te._tileClippingMaskIDs={},te.nextStencilID=1,te._renderTileClippingMasks(xe,de,_e);const kt=te.renderPass;te.renderPass="translucent",ld(te,de,xe,_e,Up[Oe].colorMode),te.renderPass=kt,te.currentStencilSource=Xe,te._tileClippingMaskIDs=pt,te.nextStencilID=mt,De.viewport.set([0,0,te.width,te.height])}(M,g,C,L,K):M.renderPass==="translucent"?void function(te,de,xe){const _e=te.context,Oe=_e.gl,De=de.lineBlendFbo;if(!De)return;_e.activeTexture.set(Oe.TEXTURE0),Oe.bindTexture(Oe.TEXTURE_2D,De.colorAttachment0.get());const qe=xe==="additive"?1:de.paint.get("line-opacity").constantOr(1),st=xe==="additive"?te.colorModeForDrapableLayerRenderPass(de.paint.get("line-emissive-strength").constantOr(0)):Up[xe].colorMode;te.getOrCreateProgram("lineBlendComposite").draw(te,Oe.TRIANGLES,nr.disabled,ra.disabled,st,Pr.disabled,Cj(0,qe,Up[xe].compositeUniformValue),de.id,te.viewportBuffer,te.quadTriangleIndexBuffer,te.viewportSegments,de.paint,te.transform.zoom)}(M,C,K):void 0;M.renderPass==="translucent"&&ld(M,g,C,L)},fill:function(M,g,C,L){const $=C.paint.get("fill-color"),G=C.paint.get("fill-opacity");if(G.constantOr(1)===0)return;const K=C.paint.get("fill-emissive-strength"),te=M.colorModeForDrapableLayerRenderPass(K),de=C.paint.get("fill-pattern"),xe=M.opaquePassEnabledForLayer()&&!de.constantOr(1)&&$.constantOr(o.aq.transparent).a===1&&G.constantOr(0)===1?"opaque":"translucent";let _e="none";C.layout.get("fill-elevation-reference")!=="none"?_e="road":C.paint.get("fill-z-offset").constantOr(1)!==0&&(_e="offset");const Oe=!(!M.terrain||!M.terrain.enabled),De={painter:M,sourceCache:g,layer:C,coords:L,colorMode:te,elevationType:_e,terrainEnabled:Oe,pass:xe};if(M.renderPass==="shadow")return void(M.shadowRenderer&&_e==="road"&&!Oe&&function(st){const{painter:Xe,sourceCache:pt,layer:mt,coords:kt}=st,Et=Xe.context.gl,xt=st.painter.shadowRenderer;for(const es of kt){const Ot=pt.getTile(es),Qt=Ot.getBucket(mt);if(!Qt)continue;const At=Qt.elevatedStructures;if(!At||!At.shadowCasterSegments||At.shadowCasterSegments.segments[0].primitiveLength===0)continue;Xe.prepareDrawTile();const Dt=Qt.bufferData.programConfigurations.get(mt.id),Ht=Xe.isTileAffectedByFog(es),gs=Xe.getOrCreateProgram("elevatedStructuresDepth",{config:Dt,overrideFog:Ht}),ss=xt.calculateShadowPassMatrixFromTile(Ot.tileID.toUnwrapped());Xe.uploadCommonUniforms(Xe.context,gs,es.toUnwrapped());const Bs=n_(ss,0);gs.draw(Xe,Et.TRIANGLES,xt.getShadowPassDepthMode(),ra.disabled,Qr.disabled,Pr.disabled,Bs,mt.id,At.vertexBuffer,At.indexBuffer,At.shadowCasterSegments,mt.paint,Xe.transform.zoom,Dt)}}(De));const qe=M.emissiveMode==="mrt-fallback";if(_e!=="offset"){if(b1(De,!1,qe),_e==="road"){const st=!Oe&&M.renderPass==="translucent";st&&Hy(M,g,C,L,"geometry"),b1(De,!0,qe,ra.disabled),st&&function(Xe){const{painter:pt,sourceCache:mt,layer:kt,coords:Et,colorMode:xt}=Xe,es=pt.context.gl,Ot=Xe.painter.shadowRenderer,Qt=!!Ot&&Ot.enabled,At=new nr(pt.context.gl.LEQUAL,nr.ReadOnly,pt.depthRangeFor3D);let Dt=[0,0,0];if(Qt){const gs=pt.style.directionalLight,ss=pt.style.ambientLight;gs&&ss&&(Dt=Op(pt.style,gs,ss))}const Ht=gs=>{for(const ss of Et){const Bs=mt.getTile(ss),Ps=Bs.getBucket(kt);if(!Ps)continue;const rn=Ps.elevatedStructures;if(!rn)continue;let hn,Ns;if(gs?(hn=rn.renderableBridgeSegments,Ns=rn.bridgeProgramConfigurations.get(kt.id)):(hn=rn.renderableTunnelSegments,Ns=rn.tunnelProgramConfigurations.get(kt.id)),!hn||hn.segments[0].primitiveLength===0)continue;Ns.updatePaintBuffers(),pt.prepareDrawTile();const ds=pt.isTileAffectedByFog(ss),Fs=[];Qt&&Fs.push("RENDER_SHADOWS","NORMAL_OFFSET");const Us=pt.getOrCreateProgram("elevatedStructures",{config:Ns,overrideFog:ds,defines:Fs}),Ys=pt.translatePosMatrix(ss.projMatrix,Bs,kt.paint.get("fill-translate"),kt.paint.get("fill-translate-anchor"));Qt&&Ot.setupShadows(Bs.tileID.toUnwrapped(),Us,"vector-tile");const Dn=Sj(Ys,Dt);pt.uploadCommonUniforms(pt.context,Us,ss.toUnwrapped()),Us.draw(pt,es.TRIANGLES,At,ra.disabled,xt,Pr.backCCW,Dn,kt.id,rn.vertexBuffer,rn.indexBuffer,hn,kt.paint,pt.transform.zoom,Ns,[rn.vertexBufferNormal])}};Ht(!0),Ht(!1)}(De)}}else b1(De,!1,qe,M.stencilModeFor3D())},"fill-extrusion":function(M,g,C,L){const $=C.paint.get("fill-extrusion-opacity"),G=M.context,K=G.gl,te=M.terrain,de=te&&te.renderingToTexture;if($===0)return;const xe=M.emissiveMode==="mrt-fallback",_e=M.conflationActive&&M.style.isLayerClipped(C,g.getSource()),Oe=M.style.order.indexOf(C.fqid);if(_e&&function(De,qe,st,Xe,pt){for(const mt of Xe){const kt=qe.getTile(mt).getBucket(st);kt&&(kt.updateReplacement(mt,De.replacementSource,pt),kt.uploadCentroid(De.context))}}(M,g,C,L,Oe),te||_e)for(const De of L){const qe=g.getTile(De).getBucket(C);qe&&hg(M.context,g,De,qe,C,te,_e)}if(M.renderPass==="shadow"&&M.shadowRenderer){if(te&&$<.65&&C._transitionablePaint._values["fill-extrusion-opacity"].value.expression instanceof o.af)return;const De=M.shadowRenderer.getShadowPassDepthMode();wx(M,g,C,L,De,ra.disabled,Qr.disabled,_e)}else if(M.renderPass==="translucent"){const De=!C.paint.get("fill-extrusion-pattern").constantOr(1),qe=C.paint.get("fill-extrusion-color").constantOr(o.aq.white);if(!de&&qe.a!==0){const st=new nr(M.context.gl.LEQUAL,nr.ReadWrite,M.depthRangeFor3D);$===1&&De?wx(M,g,C,L,st,ra.disabled,Qr.unblended,_e):(wx(M,g,C,L,st,ra.disabled,Qr.disabled,_e),wx(M,g,C,L,st,M.stencilModeFor3D(),M.colorModeForRenderPass(),_e),M.resetStencilClippingMasks())}if(M.style.enable3dLights()&&De&&(!te&&M.transform.projection.name!=="globe"||de)){const st=C.paint.get("fill-extrusion-opacity"),Xe=C.paint.get("fill-extrusion-ambient-occlusion-intensity"),pt=C.paint.get("fill-extrusion-ambient-occlusion-ground-radius"),mt=C.paint.get("fill-extrusion-flood-light-intensity"),kt=C.paint.get("fill-extrusion-flood-light-color-use-theme").constantOr("default")==="none",Et=C.paint.get("fill-extrusion-flood-light-color").toNonPremultipliedRenderColor(kt?null:C.lut).toArray01().slice(0,3),xt=Xe>0&&pt>0,es=mt>0,Ot=(Dt,Ht,gs)=>(1-gs)*Dt+gs*Ht,Qt=new $h;Qt.translate=C.paint.get("fill-extrusion-translate"),Qt.translateAnchor=C.paint.get("fill-extrusion-translate-anchor"),Qt.edgeRadius=C.layout.get("fill-extrusion-edge-radius"),Qt.cutoffFadeRange=C.paint.get("fill-extrusion-cutoff-fade-range");const At=Dt=>{const Ht=M.depthModeForSublayer(1,nr.ReadOnly,K.LEQUAL,!0),gs=C.paint.get(Dt?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),ss=Ot(.1,3,gs),Bs=M._showOverdrawInspector;if(!Bs){const Ps=new ra({func:K.ALWAYS,mask:255},255,255,K.KEEP,K.KEEP,K.REPLACE),rn=new Qr([K.ONE,K.ONE,K.ONE,K.ONE],o.aq.transparent,[!1,!1,!1,!0],K.MIN);Rf(Qt,M,g,C,L,Ht,Ps,rn,Pr.disabled,Dt,"sdf",st,Xe,pt,mt,Et,ss,_e,!1)}{const Ps=Bs?ra.disabled:new ra({func:K.EQUAL,mask:255},255,255,K.KEEP,K.DECR,K.DECR),rn=Bs?M.colorModeForRenderPass():new Qr([K.ONE_MINUS_DST_ALPHA,K.DST_ALPHA,K.ONE,K.ONE],o.aq.transparent,[!0,!0,!0,!0]);Rf(Qt,M,g,C,L,Ht,Ps,rn,Pr.disabled,Dt,"color",st,Xe,pt,mt,Et,ss,_e,!1)}};if(de){const Dt=()=>{const gs=te.drapeBufferSize[0],ss=te.drapeBufferSize[1];let Bs=te.framebufferCopyTexture;return Bs&&(!Bs||Bs.size[0]===gs&&Bs.size[1]===ss)||(Bs&&Bs.destroy(),Bs=te.framebufferCopyTexture=new o.T(G,new o.q({width:gs,height:ss}),K.RGBA8)),Bs.bind(K.LINEAR,K.CLAMP_TO_EDGE),K.copyTexSubImage2D(K.TEXTURE_2D,0,0,0,0,0,gs,ss),Bs},Ht=(gs,ss,Bs)=>{const Ps=M.depthModeForSublayer(1,nr.ReadOnly,K.LEQUAL,!1),rn=C.paint.get(gs?"fill-extrusion-ambient-occlusion-ground-attenuation":"fill-extrusion-flood-light-ground-attenuation"),hn=Ot(.1,3,rn);{const Ns=new Qr([K.ONE,K.ONE,K.ONE,K.ONE],o.aq.transparent,[!1,!1,!1,!0]);Rf(Qt,M,g,C,L,Ps,ra.disabled,Ns,Pr.disabled,gs,"clear",st,Xe,pt,mt,Et,hn,_e,ss)}{const Ns=new ra({func:K.ALWAYS,mask:255},255,255,K.KEEP,K.KEEP,K.REPLACE),ds=new Qr([K.ONE,K.ONE,K.ONE,K.ONE],o.aq.transparent,[!1,!1,!1,!0],K.MIN);Rf(Qt,M,g,C,L,Ps,Ns,ds,Pr.disabled,gs,"sdf",st,Xe,pt,mt,Et,hn,_e,ss)}xe&&!gs&&(Bs=Dt());{const Ns=gs?K.ZERO:K.ONE_MINUS_DST_ALPHA,ds=new ra({func:K.EQUAL,mask:255},255,255,K.KEEP,K.DECR,K.DECR),Fs=new Qr([Ns,K.DST_ALPHA,K.ONE_MINUS_DST_ALPHA,K.ZERO],o.aq.transparent,[!0,!0,!0,!0]);Rf(Qt,M,g,C,L,Ps,ds,Fs,Pr.disabled,gs,"color",st,Xe,pt,mt,Et,hn,_e,ss)}if(!xe||gs){const Ns=new Qr([K.ONE,K.ONE,K.ONE,gs?K.ZERO:K.ONE],o.aq.transparent,[!1,!1,!1,!0],gs?K.FUNC_ADD:K.MAX);Rf(Qt,M,g,C,L,Ps,ra.disabled,Ns,Pr.disabled,gs,"clear",st,Xe,pt,mt,Et,hn,_e,ss,Bs)}else{K.drawBuffers([K.NONE,K.COLOR_ATTACHMENT1]);const Ns=new ra({func:K.EQUAL,mask:255},254,255,K.KEEP,K.DECR,K.DECR),ds=new Qr([K.ONE,K.ONE,K.ONE,K.ONE],o.aq.transparent,[!0,!1,!1,!1],K.MAX);Rf(Qt,M,g,C,L,Ps,Ns,ds,Pr.disabled,gs,"emissive",st,Xe,pt,mt,Et,hn,_e,ss,Bs),K.drawBuffers([K.COLOR_ATTACHMENT0])}};if(xt||es){let gs;M.prepareDrawTile(),xe&&!xt||(gs=Dt()),xt&&Ht(!0,!1,gs),es&&Ht(!1,!0,gs)}}else xt&&At(!0),es&&At(!1),(xt||es)&&M.resetStencilClippingMasks()}}},building:function(M,g,C,L){M.currentLayer0&&G>0,xe=!0;const _e=C.paint.get("building-vertical-scale");if(_e<=0)return;M.shadowRenderer||(xe=!1);const Oe=M.conflationActive&&M.style.isLayerClipped(C,g.getSource()),De=M.style.order.indexOf(C.fqid);if(function(qe,st,Xe,pt,mt,kt){for(const Et of kt){const xt=st.getTile(Et).getBucket(Xe);xt&&(mt&&xt.updateReplacement(Et,qe.replacementSource,pt),xt.uploadUpdatedIndexBuffer(qe.context))}}(M,g,C,De,Oe,L),function(qe,st,Xe,pt){for(const mt of pt){const kt=st.getTile(mt).getBucket(Xe);kt&&kt.needsEvaluation()&&kt.uploadUpdatedColorBuffer(qe.context)}}(M,g,C,L),C.resetLayerRenderingStats(M),M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!0),M.renderPass==="shadow"&&M.shadowRenderer){const qe=[],st=M.shadowRenderer.getShadowPassDepthMode();Gy({painter:M,source:g,layer:C,coords:L,defines:qe,blendMode:Qr.disabled,depthMode:st,opacity:te,verticalScale:_e,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}else if(M.renderPass==="translucent"){let qe=["HAS_ATTRIBUTE_a_part_color_emissive","LIGHTING_3D_MODE"];xe&&(qe=qe.concat("RENDER_SHADOWS")),M.shadowRenderer&&M.shadowRenderer.useNormalOffset&&(qe=qe.concat("NORMAL_OFFSET"));const st=C.paint.get("building-facade-emissive-chance"),Xe=C.paint.get("building-ambient-occlusion-intensity"),pt=C.paint.get("building-flood-light-intensity"),mt=C.paint.get("building-flood-light-color-use-theme").constantOr("default")==="none",kt=C.paint.get("building-flood-light-color").toNonPremultipliedRenderColor(mt?null:C.lut).toArray01().slice(0,3),Et=C.paint.get("building-flood-light-ground-attenuation"),xt=pt>0,es=new nr(M.context.gl.LEQUAL,nr.ReadWrite,M.depthRangeFor3D);te<1&&Gy({painter:M,source:g,layer:C,coords:L,defines:qe,blendMode:Qr.disabled,depthMode:es,opacity:te,verticalScale:_e,facadeEmissiveChance:st,facadeAOIntensity:Xe,floodLightIntensity:pt,floodLightColor:kt,depthOnly:!0});const Ot=M.colorModeForRenderPass();Gy({painter:M,source:g,layer:C,coords:L,defines:qe,blendMode:Ot,depthMode:es,opacity:te,verticalScale:_e,facadeEmissiveChance:st,facadeAOIntensity:Xe,floodLightIntensity:pt,floodLightColor:kt});const Qt=C.paint.get("building-front-cutoff");i_(M.transform.pitch,Qt,!!M.terrain),de&&mg(M,g,C,L,!0,te,$,G,pt,kt,K,Oe),xt&&mg(M,g,C,L,!1,te,$,G,pt,kt,Et,Oe)}else if(M.renderPass==="light-beam"){const qe=["HAS_ATTRIBUTE_a_part_color_emissive","HAS_ATTRIBUTE_a_bloom_attenuation"],st=new nr(M.context.gl.LEQUAL,nr.ReadOnly,M.depthRangeFor3D);Gy({painter:M,source:g,layer:C,coords:L,defines:qe,blendMode:Qr.alphaBlended,depthMode:st,opacity:te,verticalScale:_e,facadeEmissiveChance:0,facadeAOIntensity:0,floodLightIntensity:0,floodLightColor:[0,0,0]})}M.shadowRenderer&&(M.shadowRenderer.useNormalOffset=!1),M.resetStencilClippingMasks()},hillshade:function(M,g,C,L){if(M.renderPass!=="offscreen"&&M.renderPass!=="translucent"||M.style.disableElevatedTerrain)return;const $=M.context,G=M.terrain&&M.terrain.renderingToTexture,[K,te]=M.renderPass!=="translucent"||G?[{},L]:M.stencilConfigForOverlap(L);for(const de of te){const xe=g.getTile(de);if(xe.needsHillshadePrepare&&M.renderPass==="offscreen")d6(M,xe,C);else if(M.renderPass==="translucent"){const _e=M.depthModeForSublayer(0,nr.ReadOnly),Oe=C.paint.get("hillshade-emissive-strength"),De=M.colorModeForDrapableLayerRenderPass(Oe),qe=G&&M.terrain?M.terrain.stencilModeForRTTOverlap(de):K[de.overscaledZ];MR(M,de,xe,C,_e,qe,De)}}$.viewport.set([0,0,M.width,M.height]),M.resetStencilClippingMasks()},raster:function(M,g,C,L,$,G){if(M.renderPass!=="translucent")return;const K=C.paint.get("raster-opacity");if(K===0)return;const te=M.transform.projection.name==="globe",de=C.paint.get("raster-elevation")!==0,xe=de&&te,_e=M.terrain&&M.terrain.exaggeration()>0&&de&&C.paint.get("raster-elevation-reference")==="ground",Oe=!te&&_e;if(M.renderElevatedRasterBackface&&!xe)return;const De=M.context,qe=De.gl,st=g.getSource(),Xe=function(Dt,Ht,gs,ss,Bs){const Ps=Ht.paint.get("raster-color"),rn=Dt.type==="raster-array",hn=[],Ns=Ht.paint.get("raster-resampling"),ds=Ht.paint.get("raster-color-mix");let Fs=Ht.paint.get("raster-color-range");const Us=[ds[0],ds[1],ds[2],0],Ys=ds[3];let Dn=Ns==="nearest"?ss.NEAREST:ss.LINEAR;if(rn&&(hn.push("RASTER_ARRAY"),Ps||hn.push("RASTER_COLOR"),Ns==="linear"&&hn.push("RASTER_ARRAY_LINEAR"),Dn=ss.NEAREST,!Fs&&Dt.rasterLayers)){const kn=Dt.rasterLayers.find(({id:Sn})=>Sn===Ht.sourceLayer);kn&&kn.fields&&kn.fields.range&&(Fs=kn.fields.range)}if(Fs=Fs||[0,1],Ps){hn.push("RASTER_COLOR"),gs.activeTexture.set(ss.TEXTURE2),Ht.updateColorRamp(Fs);let kn=Ht.colorRampTexture;kn||(kn=Ht.colorRampTexture=new o.T(gs,Ht.colorRamp,ss.RGBA8)),kn.bind(Dn,ss.CLAMP_TO_EDGE)}return Bs&&hn.push("USE_MRT1"),{mix:Us,range:Fs,offset:Ys,defines:hn,resampling:Dn}}(st,C,De,qe,M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback");if(st instanceof o.aV&&!L.length&&!te)return;const pt=C.paint.get("raster-emissive-strength"),mt=M.colorModeForDrapableLayerRenderPass(pt),kt=M.terrain&&M.terrain.renderingToTexture,Et=!M.options.moving,xt=C.paint.get("raster-resampling")==="nearest"?qe.NEAREST:qe.LINEAR;if(st instanceof o.aV&&!L.length&&(st.onNorthPole||st.onSouthPole)){const Dt=de?M.stencilModeFor3D():ra.disabled;return void Wy(!!st.onNorthPole,null,M,g,C,pt,Xe,Pr.disabled,Dt)}if(!L.length)return;const[es,Ot]=st instanceof o.aV||kt?[{},L]:M.stencilConfigForOverlap(L),Qt=Ot[Ot.length-1].overscaledZ;xe&&Xe.defines.push("PROJECTION_GLOBE_VIEW"),de&&Xe.defines.push("RENDER_CUTOFF","ELEVATED"),_e&&Xe.defines.push("ELEVATION_REFERENCE_GROUND");const At=(Dt,Ht,gs)=>{for(const ss of Dt){const Bs=ss.toUnwrapped(),Ps=g.getTile(ss);if(kt&&(!Ps||!Ps.hasData()))continue;De.activeTexture.set(qe.TEXTURE0);const rn=Dj(Ps,st,C,Xe);if(!rn||!rn.texture)continue;const{texture:hn,mix:Ns,offset:ds,tileSize:Fs,buffer:Us}=rn;let Ys,Dn;kt?(Ys=nr.disabled,Dn=ss.projMatrix):de?(Ys=new nr(qe.LEQUAL,nr.ReadWrite,M.depthRangeFor3D),Dn=te?Float32Array.from(M.transform.expandedFarZProjMatrix):M.transform.calculateProjMatrix(Bs,Et)):(Ys=M.depthModeForSublayer(ss.overscaledZ-Qt,K===1?nr.ReadWrite:nr.ReadOnly,qe.LESS),Dn=M.transform.calculateProjMatrix(Bs,Et));const kn=M.terrain&&kt?M.terrain.stencilModeForRTTOverlap(ss):es[ss.overscaledZ],Sn=G?0:C.paint.get("raster-fade-duration");Ps.registerFadeDuration(Sn);const cn=g.findLoadedParent(ss,0),ur=rp(Ps,cn,g,M.transform,Sn);let Nr,rr;!ur.isFading&&Ps.refreshedUponExpiration&&(Ps.refreshedUponExpiration=!1),M.terrain&&M.terrain.prepareDrawTile(),De.activeTexture.set(qe.TEXTURE0),hn.bind(xt,qe.CLAMP_TO_EDGE),De.activeTexture.set(qe.TEXTURE1),cn?(cn.texture&&cn.texture.bind(xt,qe.CLAMP_TO_EDGE),Nr=Math.pow(2,cn.tileID.overscaledZ-Ps.tileID.overscaledZ),rr=[Ps.tileID.canonical.x*Nr%1,Ps.tileID.canonical.y*Nr%1]):hn.bind(xt,qe.CLAMP_TO_EDGE),"useMipmap"in hn&&De.extTextureFilterAnisotropic&&M.transform.pitch>20&&qe.texParameterf(qe.TEXTURE_2D,De.extTextureFilterAnisotropic.TEXTURE_MAX_ANISOTROPY_EXT,De.extTextureFilterAnisotropicMax);const dr=M.transform;let Xr;const va=de?Lj(dr):[0,0,0,0];let ma,Va,Vr,Ha,pa,Ci=0;if(xe&&st instanceof o.aV&&st.coordinates.length>3)ma=Float32Array.from(o.du(o.dv(new o.cn(0,0,0)))),Va=Float32Array.from(dr.globeMatrix),Vr=Float32Array.from(o.dq(dr)),Ha=[o.aH(dr.center.lng),o.aL(dr.center.lat)],Xr=st.elevatedGlobePerspectiveTransform,pa=st.elevatedGlobeGridMatrix||new Float32Array(9);else if(xe){const Fi=o.dr(ss.canonical);Ci=o.ds(Fi.getCenter().lat),ma=Float32Array.from(o.du(o.dv(ss.canonical))),Va=Float32Array.from(dr.globeMatrix),Vr=Float32Array.from(o.dq(dr)),Ha=[o.aH(dr.center.lng),o.aL(dr.center.lat)],Xr=[0,0],pa=Float32Array.from(o.dt(ss.canonical,Fi,Ci,dr.worldSize/dr._pixelsPerMercatorPixel))}else Xr=st instanceof o.aV?st.perspectiveTransform:[0,0],ma=new Float32Array(16),Va=new Float32Array(9),Vr=new Float32Array(16),Ha=[0,0],pa=new Float32Array(9);const yo=yx(M,Dn,ma,Va,Vr,pa,rr||[0,0],o.al(M.transform.zoom),Ha,va,Nr||1,ur,C,Xr,de?C.paint.get("raster-elevation"):0,2,Ns,ds,Xe.range,Fs,Us,pt),yl=M.isTileAffectedByFog(ss),Lo=M.getOrCreateProgram("raster",{defines:Xe.defines,overrideFog:yl});if(M.uploadCommonUniforms(De,Lo,Bs),st instanceof o.aV){const Fi=st.elevatedGlobeVertexBuffer,Da=st.elevatedGlobeIndexBuffer;if(kt||!te)st.boundsBuffer&&st.boundsSegments&&Lo.draw(M,qe.TRIANGLES,Ys,ra.disabled,mt,Pr.disabled,yo,C.id,st.boundsBuffer,M.quadTriangleIndexBuffer,st.boundsSegments);else if(Fi&&Da){const Ra=dr.zoom<=o.cJ?st.elevatedGlobeSegments:st.getSegmentsForLongitude(dr.center.lng);Ra&&Lo.draw(M,qe.TRIANGLES,Ys,ra.disabled,mt,Ht,yo,C.id,Fi,Da,Ra)}}else if(xe){Ys=new nr(qe.LEQUAL,nr.ReadOnly,M.depthRangeFor3D);const Fi=M.globeSharedBuffers;if(Fi){_e&&(M.terrain.setupElevationDraw(Ps,Lo),M.uploadCommonUniforms(De,Lo,Ps.tileID.toUnwrapped()));const[Da,Ra,Do]=Fi.getGridBuffers(Ci,!1),Nl=Lo.getAttributeLocation(qe,"a_texture_pos");Nl!==-1&&qe.vertexAttribI4ui(Nl,0,0,0,0),Lo.draw(M,qe.TRIANGLES,Ys,gs||kn,M.colorModeForRenderPass(),Ht,yo,C.id,Da,Ra,Do)}}else if(Oe)Ys=new nr(qe.LEQUAL,nr.ReadWrite,M.depthRangeFor3D),M.terrain.setupElevationDraw(Ps,Lo),M.uploadCommonUniforms(De,Lo,Ps.tileID.toUnwrapped()),dr.pitch>20&&Lo.draw(M,qe.TRIANGLES,Ys,ra.disabled,Qr.disabled,Pr.frontCCW,yo,C.id,M.terrain.gridBuffer,M.terrain.gridIndexBuffer,M.terrain.gridSegments),Lo.draw(M,qe.TRIANGLES,Ys,kn,mt,Pr.backCCW,yo,C.id,M.terrain.gridBuffer,M.terrain.gridIndexBuffer,M.terrain.gridSegments);else{const{tileBoundsBuffer:Fi,tileBoundsIndexBuffer:Da,tileBoundsSegments:Ra}=M.getTileBoundsBuffers(Ps);Lo.draw(M,qe.TRIANGLES,Ys,kn,mt,Pr.disabled,yo,C.id,Fi,Da,Ra)}}if(!(st instanceof o.aV)&&xe)for(const ss of Dt){const Bs=ss.canonical.y===(1<o.d$[Us](Bs));Ns.push(Bs);const ds=Bs.canonical.x,Fs=Bs.canonical.y;for(const Us of Ns){const Ys=xt.getTile(Ht?Us.wrapped():Us);if(!Ys)continue;const Dn=Ys.rasterParticleState;if(!Dn)continue;const kn=Us.canonical.x+(1<Qt.tileID)),qe&&(xe.activeTexture.set(_e.TEXTURE0),M.imageManager.bind(M.context,C.scope));const Ot=[];if(M.terrain&&M.terrain.renderingToTexture&&M.emissiveMode==="mrt-fallback"&&Ot.push("USE_MRT1"),de){const Qt=M.getOrCreateProgram(Et,{overrideFog:!1,overrideRtt:!0,defines:Ot}),At=new Float32Array(o.b9([])),Dt=new o.aR(0,0,0,0,0),Ht=qe?bx(At,te,K,M,0,C.scope,st,de,{tileID:Dt,tileSize:De}):Vy(At,te,K,$.toPremultipliedRenderColor(G?null:C.lut));return void Qt.draw(M,_e.TRIANGLES,mt,pt,kt,Pr.disabled,Ht,C.id,M.viewportBuffer,M.quadTriangleIndexBuffer,M.viewportSegments)}for(const Qt of es){const At=M.isTileAffectedByFog(Qt),Dt=M.getOrCreateProgram(Et,{overrideFog:At,defines:Ot}),Ht=Qt.toUnwrapped(),gs=L?Qt.projMatrix:M.transform.calculateProjMatrix(Ht);M.prepareDrawTile();const ss=g?g.getTile(Qt):xt?xt[Qt.key]:new o.b0(Qt,De,Oe.zoom,M),Bs=qe?bx(gs,te,K,M,0,C.scope,st,de,{tileID:Qt,tileSize:De}):Vy(gs,te,K,$.toPremultipliedRenderColor(G?null:C.lut));M.uploadCommonUniforms(xe,Dt,Ht);const{tileBoundsBuffer:Ps,tileBoundsIndexBuffer:rn,tileBoundsSegments:hn}=M.getTileBoundsBuffers(ss);Dt.draw(M,_e.TRIANGLES,mt,pt,kt,Pr.disabled,Bs,C.id,Ps,rn,hn)}},sky:function(M,g,C){const L=M._atmosphere?o.al(M.transform.zoom):1,$=C.paint.get("sky-opacity")*L;if($===0)return;const G=M.context,K=C.paint.get("sky-type"),te=new nr(G.gl.LEQUAL,nr.ReadOnly,[0,1]),de=M.frameCounter/1e3%1;K==="atmosphere"?M.renderPass==="offscreen"?C.needsSkyboxCapture(M)&&(function(xe,_e){const Oe=xe.context,De=Oe.gl;let qe=_e.skyboxFbo;if(!qe){qe=_e.skyboxFbo=Oe.createFramebuffer(32,32,1,null),_e.skyboxGeometry=new Hd(Oe),_e.skyboxTexture=Oe.gl.createTexture(),De.bindTexture(De.TEXTURE_CUBE_MAP,_e.skyboxTexture),De.texParameteri(De.TEXTURE_CUBE_MAP,De.TEXTURE_WRAP_S,De.CLAMP_TO_EDGE),De.texParameteri(De.TEXTURE_CUBE_MAP,De.TEXTURE_WRAP_T,De.CLAMP_TO_EDGE),De.texParameteri(De.TEXTURE_CUBE_MAP,De.TEXTURE_MIN_FILTER,De.LINEAR),De.texParameteri(De.TEXTURE_CUBE_MAP,De.TEXTURE_MAG_FILTER,De.LINEAR);for(let mt=0;mt<6;++mt)De.texImage2D(De.TEXTURE_CUBE_MAP_POSITIVE_X+mt,0,De.RGBA,32,32,0,De.RGBA,De.UNSIGNED_BYTE,null)}Oe.bindFramebuffer.set(qe.framebuffer),Oe.viewport.set([0,0,32,32]);const st=_e.getCenter(xe,!0),Xe=xe.getOrCreateProgram("skyboxCapture"),pt=new Float64Array(16);o.b9(pt),o.ef(pt,pt,.5*-Math.PI),qp(xe,_e,Xe,pt,st,0),o.b9(pt),o.ef(pt,pt,.5*Math.PI),qp(xe,_e,Xe,pt,st,1),o.b9(pt),o.cE(pt,pt,.5*-Math.PI),qp(xe,_e,Xe,pt,st,2),o.b9(pt),o.cE(pt,pt,.5*Math.PI),qp(xe,_e,Xe,pt,st,3),o.b9(pt),qp(xe,_e,Xe,pt,st,4),o.b9(pt),o.ef(pt,pt,Math.PI),qp(xe,_e,Xe,pt,st,5),Oe.viewport.set([0,0,xe.width,xe.height])}(M,C),C.markSkyboxValid(M)):M.renderPass==="sky"&&function(xe,_e,Oe,De,qe){const st=xe.context,Xe=st.gl,pt=xe.transform,mt=xe.getOrCreateProgram("skybox");st.activeTexture.set(Xe.TEXTURE0),Xe.bindTexture(Xe.TEXTURE_CUBE_MAP,_e.skyboxTexture);const kt=((Et,xt,es,Ot,Qt)=>({u_matrix:Et,u_sun_direction:xt,u_cubemap:0,u_opacity:Ot,u_temporal_offset:Qt}))(pt.skyboxMatrix,_e.getCenter(xe,!1),0,De,qe);xe.uploadCommonUniforms(st,mt),mt.draw(xe,Xe.TRIANGLES,Oe,ra.disabled,xe.colorModeForRenderPass(),Pr.backCW,kt,"skybox",_e.skyboxGeometry.vertexBuffer,_e.skyboxGeometry.indexBuffer,_e.skyboxGeometry.segment)}(M,C,te,$,de):K==="gradient"&&M.renderPass==="sky"&&function(xe,_e,Oe,De,qe){const st=xe.context,Xe=st.gl,pt=xe.transform,mt=xe.getOrCreateProgram("skyboxGradient");_e.skyboxGeometry||(_e.skyboxGeometry=new Hd(st)),st.activeTexture.set(Xe.TEXTURE0);let kt=_e.colorRampTexture;kt||(kt=_e.colorRampTexture=new o.T(st,_e.colorRamp,Xe.RGBA8)),kt.bind(Xe.LINEAR,Xe.CLAMP_TO_EDGE);const Et=((xt,es,Ot,Qt,At)=>({u_matrix:xt,u_color_ramp:0,u_center_direction:es,u_radius:o.ap(Ot),u_opacity:Qt,u_temporal_offset:At}))(pt.skyboxMatrix,_e.getCenter(xe,!1),_e.paint.get("sky-gradient-radius"),De,qe);xe.uploadCommonUniforms(st,mt),mt.draw(xe,Xe.TRIANGLES,Oe,ra.disabled,xe.colorModeForRenderPass(),Pr.backCW,Et,"skyboxGradient",_e.skyboxGeometry.vertexBuffer,_e.skyboxGeometry.indexBuffer,_e.skyboxGeometry.segment)}(M,C,te,$,de)},custom:function(M,g,C,L){const $=M.context,G=C.implementation;if(!M.transform.projection.unsupportedLayers||!M.transform.projection.unsupportedLayers.includes("custom")||M.terrain&&(M.terrain.renderingToTexture||M.renderPass==="offscreen")&&C.isDraped(g)){if(M.renderPass==="offscreen"){const K=G.prerender;if(K){if(M.setCustomLayerDefaults(),$.setColorMode(M.colorModeForRenderPass()),M.transform.projection.name==="globe"){const te=M.transform.pointMerc;K.call(G,$.gl,M.transform.customLayerMatrix(),M.transform.getProjection(),M.transform.globeToMercatorMatrix(),o.al(M.transform.zoom),[te.x,te.y],M.transform.pixelsPerMeterRatio)}else K.call(G,$.gl,M.transform.customLayerMatrix());$.setDirty(),M.setBaseState()}}else if(M.renderPass==="translucent"){if(M.terrain&&M.terrain.renderingToTexture){const te=G.renderToTile;if(te){const de=L[0].canonical,xe={x:de.x+L[0].wrap*(G.wrapTileId?0:1<{xe&&(xe.useNormalOffset=!0,_e||(xe.enabled=!0))},De=g.getSource();if(M.renderPass==="light-beam"&&De.type!=="batched-model")return;if(De.type==="vector"||De.type==="geojson")return function(xt,es,Ot,Qt,At){const Dt=xt.transform,Ht=Dt.projection.name==="globe",gs=Dt.getFreeCameraOptions().position;if(!xt.modelManager)return;const ss=xt.modelManager;Ot.modelManager=ss;const Bs=xt.shadowRenderer;if(!Ot._unevaluatedLayout._values.hasOwnProperty("model-id"))return;const Ps=Ot._unevaluatedLayout._values["model-id"],rn=Object.assign({},Ot.layout.get("model-id").parameters),hn=xt.style.order.indexOf(Ot.fqid),Ns=Ot.paint.get("model-opacity").constantOr(1);for(const ds of Qt){const Fs=es.getTile(ds).getBucket(Ot);if(!Fs||Fs.projection.name!==Dt.projection.name)continue;const Us=Fs.getModelUris();if(Us&&!Fs.modelsRequested&&(ss.addModelsFromBucket(Us,At),Fs.modelsRequested=!0),Ht)rn.zoom=ds.overscaledZ;else{const rr=Vp(ds,Dt);rn.zoom=rr}const Ys=Ps.possiblyEvaluate(rn);if(wn(xt,Fs,ds),bn.shadowUniformsInitialized=!1,bn.useSingleShadowCascade=!!Bs&&Bs.getMaxCascadeForTile(ds.toUnwrapped())===0,xt.renderPass==="shadow"&&Bs){if(xt.currentShadowCascade===1&&Fs.isInsideFirstShadowMapFrustum)continue;const rr=Dt.calculatePosMatrix(ds.toUnwrapped(),Dt.worldSize);if(bn.tileMatrix.set(rr),bn.shadowTileMatrix=Float32Array.from(Bs.calculateShadowPassMatrixFromMatrix(rr)),bn.aabb.min=[0,0,0],bn.aabb.max[0]=bn.aabb.max[1]=o.an,bn.aabb.max[2]=0,Fj(Fs,bn,xt,Ot.scope))continue}const Dn=1<0&&xt.style.isLayerClipped(Ot,es.getSource())&&Fs.updateReplacement(ds,xt.replacementSource,hn,Ot.scope)&&(Fs.uploaded=!1,Fs.upload(xt.context));let Sn=0;const cn=new Array,ur=new Array,Nr=new Array;for(let rr in Fs.instancesPerModel){const dr=Fs.instancesPerModel[rr];dr.features.length>0&&!Ht&&(rr=Ys.evaluate(dr.features[0].feature,{}));const Xr=ss.getModel(rr,At);if(Xr||ss.hasURLBeenRequested(rr)||Fs.modelUris.includes(rr)||(Fs.modelUris.push(rr),Fs.modelsRequested=!1),Xr&&Xr.uploaded)if(Ht){const va=o.bJ([],[gs.x,gs.y,gs.z],xt.transform.worldSize);o.eo(va,va);for(let ma=0;ma0&&Ha.elevationUpdate(rr.terrain,ma,Vr,Xr.source),Ha.needsReEvaluation(rr,Va,Xr)&&Ha.evaluate(Xr))}})(xt,es,Ot,Qt),function(){const rr=new Map;let dr,Xr,va;cn?(dr=Qt.length-1,Xr=-1,va=-1):(dr=0,Xr=Qt.length,va=1);const ma=new Float64Array(16),Va=o.ce(),Vr=new o.P(0,0);for(let Ha=dr;Ha!==Xr;Ha+=va){const pa=Qt[Ha],Ci=es.getTile(pa).getBucket(Ot);if(!Ci||!Ci.uploaded)continue;let yo=!1;gs&&(yo=gs.getMaxCascadeForTile(pa.toUnwrapped())===0);const yl=Dt.calculatePosMatrix(pa.toUnwrapped(),Dt.worldSize),Lo=Ci.modelTraits;!Dn&&cn&&(o.b7(ma,yl),o.ah(Va,Bs,ma),Vr.x=Va[0],Vr.y=Va[1]);const Fi=[];Ci.setFilter(Ot.filter);for(const Da of Ci.getNodesInfo()){if(Da.hiddenByReplacement||!Da.node.meshes)continue;const Ra=Da.node;let Do=0;xt.terrain&&Ra.elevation&&(Do=Ra.elevation*xt.terrain.exaggeration());const Nl=(()=>{const fu=Da.aabb;return Ys.min=[...fu.min],Ys.max=[...fu.max],Ys.min[2]+=Do,Ys.max[2]+=Do,o.ah(Ys.min,Ys.min,yl),o.ah(Ys.max,Ys.max,yl),Ys})(),zi=Da.evaluatedScale;if(zi[0]<=1&&zi[1]<=1&&zi[2]<=1&&Nl.intersects(kn)===0)continue;if(!Dn&&cn){const fu=.16666666666666666;Da.cameraCollisionOpacity=Bs[0]>Nl.min[0]&&Bs[0]Nl.min[1]&&Bs[1]!cn||Da.opacity===1&&Ra.opacity===1?Da.depthRa.depth?-1:1);for(const Da of Fi){const Ra=Da.nodeInfo,Do=Ra.node;if(xt._debugParams.show3DModelFootprints&&Do.footprint){const ii=Do.id||Do.name||"footprint";rr.has(ii)||rr.set(ii,{node:Do,mvp:Da.wvpForTile})}let Nl=o.aD([],Ns,Da.tileModelMatrix);o.aD(Nl,rn,Nl);const zi=o.b7([],Nl);o.e6(zi,zi),o.cC(zi,zi,ps),Nl=o.aD(Nl,Nl,Do.globalMatrix);const Na=xt.renderPass==="light-beam",cl=Ot.paint.get("model-color-use-theme").constantOr("default")==="none",vo=Lo&o.ez.HasMapboxMeshFeatures,vc=vo?0:Ra.evaluatedRMEA[0][2];for(let ii=0;ii=Er||zf>=Er}}const eo=ko.material;let kx;eo.occlusionTexture&&eo.occlusionTexture.offsetScale&&(kx=eo.occlusionTexture.offsetScale,dd.defines.push("OCCLUSION_TEXTURE_TRANSFORM"));const Sx=xt.getOrCreateProgram("model",dd);!Dn&&gs&&gs.setupShadowsFromMatrix(Da.tileModelMatrix,Sx,gs.useNormalOffset),xt.uploadCommonUniforms(At,Sx,null,Ff);const zo=eo.pbrMetallicRoughness;zo.metallicFactor=.9,zo.roughnessFactor=.5;const Vo=_x(new Float32Array(gh),new Float32Array(Nl),new Float32Array(zi),new Float32Array(Do.globalMatrix),xt,Da.opacity,zo.baseColorFactor,eo.emissiveFactor,zo.metallicFactor,zo.roughnessFactor,eo,vc,Ot,[0,0,0],kx);!Zc&&(Ra.hasTranslucentParts||Da.opacity<1)&&Sx.draw(xt,At.gl.TRIANGLES,Fs,ra.disabled,Qr.disabled,Pr.backCCW,Vo,Ot.id,ko.vertexBuffer,ko.indexBuffer,ko.segments,Ot.paint,xt.transform.zoom,void 0,fu),Sx.draw(xt,At.gl.TRIANGLES,Zc?Us:Fs,ra.disabled,Zc||Da.opacity<1||Ra.hasTranslucentParts?Qr.alphaBlended:Qr.unblended,Pr.backCCW,Vo,Ot.id,ko.vertexBuffer,ko.indexBuffer,ko.segments,Ot.paint,xt.transform.zoom,void 0,fu)}}}if(xt._debugParams.show3DModelFootprints&&rr.size>0){const Ha=Array.from(rr.keys()).sort();for(const pa of Ha){const{node:Ci,mvp:yo}=rr.get(pa);QN(xt,0,Ci,yo)}}}()}(M,g,C,L),void Oe();if(De.type!=="model")return;const qe=De.getModels(),st=[],Xe=M.transform.getFreeCameraOptions().position,pt=o.bJ([],[Xe.x,Xe.y,Xe.z],M.transform.worldSize);o.eo(pt,pt);const mt=[],kt=[];let Et=0;for(const xt of qe){const es=g.getFeatureState("",xt.id),Ot={type:"Unknown",id:xt.id,properties:xt.featureProperties},Qt=C.paint.get("model-rotation").evaluate(Ot,es),At=C.paint.get("model-scale").evaluate(Ot,es),Dt=C.paint.get("model-translation").evaluate(Ot,es),Ht=C.paint.get("model-opacity").evaluate(Ot,es);XN(C,xt.id,es,xt.featureProperties,xt.nodeOverrideNames,xt.nodeOverrides),w1(C,xt.id,es,xt.featureProperties,xt.materialOverrideNames,xt.materialOverrides),xt.nodeOverrides.size>0&&xt.computeBoundsAndApplyParent(),xt.computeModelMatrix(M,Qt,At,Dt,te,K,!1);const gs=o.b9([]),ss=o.e2(xt.position.lat,M.transform.zoom),Bs=o.bP([],[1,1,1/ss]);o.bx(gs,gs,pt),st.push({zScaleMatrix:Bs,negCameraPosMatrix:gs});for(const Ps of xt.nodes)ZN(M,Ps,xt.matrix,M.transform.expandedFarZProjMatrix,Et,mt,kt,xt.materialOverrides,Ht);Et++}if(mt.sort((xt,es)=>es.depth-xt.depth),M.renderPass!=="shadow"){if(M._debugParams.show3DModelFootprints){const xt=M.transform.projMatrix,es=new Map,Ot=(At,Dt)=>{if(At.footprint){const Ht=At.id||At.name||"footprint";if(!es.has(Ht)){const gs=o.aD([],xt,Dt);es.set(Ht,{node:At,mvp:gs})}}};for(const At of kt)Ot(At.node,At.modelMatrix);for(const At of mt)Ot(At.node,At.modelMatrix);const Qt=Array.from(es.keys()).sort();for(const At of Qt){const{node:Dt,mvp:Ht}=es.get(At);QN(M,0,Dt,Ht)}}Gd(M,C,mt,kt,st),Oe()}else{for(const xt of kt)d_(xt.mesh,xt.nodeModelMatrix,M,C);for(const xt of mt)d_(xt.mesh,xt.nodeModelMatrix,M,C);Oe()}}},Wn={line:function(M,g,C){if(M.hasElevatedBuckets=!1,M.hasNonElevatedBuckets=!1,M._unevaluatedLayout.getValue("line-elevation-reference")!==void 0||M._unevaluatedLayout.getValue("line-z-offset")!==void 0){if(g){const L=g.getVisibleCoordinates();for(const $ of L){const G=g.getTile($).getBucket(M);if(G&&(G.elevationType!=="none"?M.hasElevatedBuckets=!0:M.hasNonElevatedBuckets=!0,M.hasElevatedBuckets&&M.hasNonElevatedBuckets))break}}}else M.hasNonElevatedBuckets=!0},model:function(M,g,C){const L=g.getSource();if(!L.loaded())return;if(L.type==="vector"||L.type==="geojson")return void(C.modelManager&&C.modelManager.upload(C,Oj(C,M)));if(L.type==="batched-model"||L.type!=="model")return;const $=L.getModels();for(const G of $)G.upload(C.context)},raster:function(M,g,C){const L=g.getSource();if(!(L instanceof hm&&L.loaded()))return;const $=M.sourceLayer||L.rasterLayerIds&&L.rasterLayerIds[0];if(!$)return;const G=M.paint.get("raster-array-band")||L.getInitialBand($);if(G==null)return;const K=g.getIds().map(te=>g.getTileByID(te));for(const te of K)te.updateNeeded(M.id,G)&&L.prepareTile(te,$,M.id,G)},"raster-particle":function(M,g,C){const L=g.getSource();if(!(L instanceof hm&&L.loaded()))return;const $=M.sourceLayer||L.rasterLayerIds&&L.rasterLayerIds[0];if(!$)return;const G=M.paint.get("raster-particle-array-band")||L.getInitialBand($);if(G==null)return;const K=g.getIds().map(te=>g.getTileByID(te));for(const te of K)te.updateNeeded(M.id,G)&&L.prepareTile(te,$,M.id,G)}},zr={fill:Hy},Ba={fill:function(M,g,C,L){if(!C.layout||C.layout.get("fill-elevation-reference")==="none"||C.paint.get("fill-opacity").constantOr(1)===0)return;const $=M.context.gl,G=new nr($.LEQUAL,nr.ReadOnly,M.depthRangeFor3D),K=new ra({func:$.ALWAYS,mask:255},255,255,$.KEEP,$.KEEP,$.REPLACE),te=M.transform.getFreeCameraOptions().position,de=M.getOrCreateProgram("elevatedStructuresDepthReconstruct");for(const xe of L){const _e=g.getTile(xe),Oe=_e.getBucket(C);if(!Oe)continue;const De=Oe.elevatedStructures;if(!De||De.depthSegments.segments[0].primitiveLength===0)continue;const qe=b0(xe.toUnwrapped(),te),st=M.translatePosMatrix(xe.projMatrix,_e,C.paint.get("fill-translate"),C.paint.get("fill-translate-anchor")),Xe=y1(st,qe,0,1,0);de.draw(M,$.TRIANGLES,G,K,Qr.disabled,Pr.disabled,Xe,C.id,De.vertexBuffer,De.indexBuffer,De.depthSegments,C.paint,M.transform.zoom)}}};class oo{constructor(g,C,L,$,G){this.context=new g0(g,C),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 K=["fill","line","symbol","circle","heatmap","fill-extrusion","building","raster","raster-particle","hillshade","model","background","sky"];for(const de of K)this._debugParams.enabledLayers[de]=!0;for(const de of K);this.occlusionParams=new TC,this.setup(),this.numSublayers=sl.maxUnderzooming+sl.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 Jl(this),this._wireframeDebugCache=new CC,this.renderDefaultNorthPole=!0,this.renderDefaultSouthPole=!0,this.layersWithOcclusionOpacity=[];const te=new o.q({width:1,height:1},Uint8Array.of(0,0,0,0));this.emptyDepthTexture=new o.T(this.context,te,g.RGBA8),this._clippingActiveLastFrame=!1,this.scaleFactor=$,this.maxFrontCutoffRawStart=0,this.worldview=G,this._forceEmissiveMode=!1,this.emissiveMode="constant"}updateTerrain(g,C){const L=!!g&&!!g.terrain&&this.transform.projection.supportsTerrain;if(!(L||this._terrain&&this._terrain.enabled))return;this._terrain||(this._terrain=new qy(this,g));const $=this._terrain;this.transform.elevation=L?$:null,$.update(g,this.transform,C),this.transform.elevation&&!$.enabled&&(this.transform.elevation=null)}_updateFog(g){const C=g.fog;if(!C||this.transform.projection.name==="globe"||C.getOpacity(this.transform.pitch)<1||C.properties.get("horizon-blend")<.03)return void(this.transform.fogCullDistSq=null);const[L,$]=C.getFovAdjustedRange(this.transform._fov);if(L>$)return void(this.transform.fogCullDistSq=null);const G=L+.78*($-L);this.transform.fogCullDistSq=G*G}get terrain(){return this.transform._terrainEnabled()&&this._terrain&&this._terrain.enabled||this._forceTerrainMode?this._terrain:null}get forceTerrainMode(){return this._forceTerrainMode}set forceTerrainMode(g){g&&!this._terrain&&(this._terrain=new qy(this,this.style)),this._forceTerrainMode=g}get shadowRenderer(){return this._shadowRenderer&&this._shadowRenderer.enabled?this._shadowRenderer:null}get wireframeDebugCache(){return this._wireframeDebugCache}resize(g,C){if(this.width=g*o.o.devicePixelRatio,this.height=C*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 g=this.context,C=new o.dB;C.emplaceBack(0,0),C.emplaceBack(o.an,0),C.emplaceBack(0,o.an),C.emplaceBack(o.an,o.an),this.tileExtentBuffer=g.createVertexBuffer(C,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=g.createVertexBuffer(L,o.dx.members),this.debugSegments=o.dy.simpleSegment(0,0,4,5);const $=new o.dB;$.emplaceBack(-1,-1),$.emplaceBack(1,-1),$.emplaceBack(-1,1),$.emplaceBack(1,1),this.viewportBuffer=g.createVertexBuffer($,o.dx.members),this.viewportSegments=o.dy.simpleSegment(0,0,4,2);const G=new o.eH;G.emplaceBack(0,0,0,0),G.emplaceBack(o.an,0,o.an,0),G.emplaceBack(0,o.an,0,o.an),G.emplaceBack(o.an,o.an,o.an,o.an),this.mercatorBoundsBuffer=g.createVertexBuffer(G,o.eI.members),this.mercatorBoundsSegments=o.dy.simpleSegment(0,0,4,2);const K=new o.dC;K.emplaceBack(0,1,2),K.emplaceBack(2,1,3),this.quadTriangleIndexBuffer=g.createIndexBuffer(K);const te=new o.eJ;for(const xe of[0,1,3,2,0])te.emplaceBack(xe);this.debugIndexBuffer=g.createIndexBuffer(te),this.emptyTexture=new o.T(g,new o.q({width:1,height:1},Uint8Array.of(0,0,0,0)),g.gl.RGBA8),this.identityMat=o.bb();const de=this.context.gl;this.stencilClearMode=new ra({func:de.ALWAYS,mask:0},0,255,de.ZERO,de.ZERO,de.ZERO),this.loadTimeStamps.push(performance.now())}getMercatorTileBoundsBuffers(){return{tileBoundsBuffer:this.mercatorBoundsBuffer,tileBoundsIndexBuffer:this.quadTriangleIndexBuffer,tileBoundsSegments:this.mercatorBoundsSegments}}getTileBoundsBuffers(g){return g._makeTileBoundsBuffers(this.context,this.transform.projection),g._tileBoundsBuffer?{tileBoundsBuffer:g._tileBoundsBuffer,tileBoundsIndexBuffer:g._tileBoundsIndexBuffer,tileBoundsSegments:g._tileBoundsSegments}:this.getMercatorTileBoundsBuffers()}clearStencil(){const g=this.context.gl;this.nextStencilID=1,this.currentStencilSource=void 0,this._tileClippingMaskIDs={},this.getOrCreateProgram("clippingMask").draw(this,g.TRIANGLES,nr.disabled,this.stencilClearMode,Qr.disabled,Pr.disabled,Nj(this.identityMat),"$clipping",this.viewportBuffer,this.quadTriangleIndexBuffer,this.viewportSegments)}resetStencilClippingMasks(){this.terrain||(this.currentStencilSource=void 0,this._tileClippingMaskIDs={})}_renderTileClippingMasks(g,C,L){if(!C||this.currentStencilSource===C.id||!g.isTileClipped()||!L||L.length===0)return;if(this._tileClippingMaskIDs&&!this.terrain){let te=!1;for(const de of L)if(this._tileClippingMaskIDs[de.key]===void 0){te=!0;break}if(!te)return}this.currentStencilSource=C.id;const $=this.context,G=$.gl;this.nextStencilID+L.length>256&&this.clearStencil(),$.setColorMode(Qr.disabled),$.setDepthMode(nr.disabled);const K=this.getOrCreateProgram("clippingMask");this._tileClippingMaskIDs={};for(const te of L){const de=C.getTile(te),xe=this._tileClippingMaskIDs[te.key]=this.nextStencilID++,{tileBoundsBuffer:_e,tileBoundsIndexBuffer:Oe,tileBoundsSegments:De}=this.getTileBoundsBuffers(de);K.draw(this,G.TRIANGLES,nr.disabled,new ra({func:G.ALWAYS,mask:0},xe,255,G.KEEP,G.KEEP,G.REPLACE),Qr.disabled,Pr.disabled,Nj(te.projMatrix),"$clipping",_e,Oe,De)}}stencilModeFor3D(){this.currentStencilSource=void 0,this.nextStencilID+1>256&&this.clearStencil();const g=this.nextStencilID++,C=this.context.gl;return new ra({func:C.NOTEQUAL,mask:255},g,255,C.KEEP,C.KEEP,C.REPLACE)}stencilModeForClipping(g){if(this.terrain)return this.terrain.stencilModeForRTTOverlap(g);const C=this.context.gl;return new ra({func:C.EQUAL,mask:255},this._tileClippingMaskIDs[g.key],0,C.KEEP,C.KEEP,C.REPLACE)}stencilConfigForOverlap(g){const C=this.context.gl,L=g.sort((K,te)=>te.overscaledZ-K.overscaledZ),$=L[L.length-1].overscaledZ,G=L[0].overscaledZ-$+1;if(G>1){this.currentStencilSource=void 0,this.nextStencilID+G>256&&this.clearStencil();const K={};for(let te=0;tethis._debugParams.fpsWindow&&this._fpsHistory.splice(0,this._fpsHistory.length-this._debugParams.fpsWindow),this._averageFPS=Math.round(this._fpsHistory.reduce((g,C)=>g+C/this._fpsHistory.length,0))}render(g,C){const L=o.o.now();this._dt=L-this._timeStamp,this._timeStamp=L,this._wireframeDebugCache.update(this.frameCounter),this._debugParams.continousRedraw=g.map.repaint,this.style=g,this.options=C;const $=this.style._mergedLayers,G=!(!this.terrain||!this.terrain.enabled),K=()=>this.style._getOrder(G).filter(Ns=>{const ds=$[Ns];return!(ds.type in this._debugParams.enabledLayers)||this._debugParams.enabledLayers[ds.type]});let te=K(),de=!1,xe=!1,_e=null,Oe=0,De=!1;for(const Ns of te){const ds=$[Ns];ds.visibility!=="none"&&(ds.type==="circle"?de=!0:ds.type==="building"?(_e=ds,++Oe):ds.type==="symbol"&&(ds.hasOcclusionOpacityProperties?xe=!0:de=!0))}this.updateEmissiveMode();let qe=te.map(Ns=>$[Ns]);const st=this.style._mergedSourceCaches;this.imageManager=g.imageManager,this.modelManager=g.modelManager,this.symbolFadeChange=g.placement.symbolFadeChange(o.o.now()),this.imageManager.beginFrame();for(const Ns in st){const ds=st[Ns];ds.used&&(ds.prepare(this.context),ds.getSource().usedInConflation&&++Oe)}let Xe=!1;for(const Ns of qe)Ns.isHidden(this.transform.zoom)||(Ns.type==="clip"&&(Xe=!0),this.prepareLayer(Ns));const pt={},mt={},kt={},Et={},xt={};for(const Ns in st){const ds=st[Ns];pt[Ns]=ds.getVisibleCoordinates(),mt[Ns]=pt[Ns].slice().reverse(),kt[Ns]=ds.getVisibleCoordinates(!0).reverse(),Et[Ns]=ds.getShadowCasterCoordinates(),xt[Ns]=ds.sortCoordinatesByDistance(pt[Ns])}const es=Ns=>{const ds=this.style.getLayerSourceCache(Ns);return ds&&ds.used?ds.getSource():null};if(Oe||Xe||this._clippingActiveLastFrame){const Ns=[],ds=[];let Fs=0;for(const Us of qe)this.isSourceForClippingOrConflation(Us,es(Us))&&(Ns.push(Us),ds.push(Fs)),Fs++;if(Ns&&(Xe||Ns.length>1)||this._clippingActiveLastFrame){Xe=!1;const Us=[];for(let Ys=0;Ys0){const Us=es(ds);Us&&(this.minCutoffZoom=Math.max(Us.minzoom,this.minCutoffZoom)),ds.minzoom&&(this.minCutoffZoom=Math.max(ds.minzoom,this.minCutoffZoom))}ds.is3D(G)&&(this.opaquePassCutoff===1/0&&(this.opaquePassCutoff=Ns),this._lastOcclusionLayer=Ns)}const Ot=this.style&&this.style.fog;Ot?(this._fogVisible=Ot.getOpacity(this.transform.pitch)!==0,this._fogVisible&&this.transform.projection.name!=="globe"&&(this._fogVisible=Ot.isVisibleOnFrustum(this.transform.cameraFrustum))):this._fogVisible=!1,this._cachedTileFogOpacities={},this.terrain&&(this.terrain.updateTileBinding(kt),this.opaquePassCutoff=0,te=K(),qe=te.map(Ns=>$[Ns]));const Qt=this._shadowRenderer;if(Qt){Qt.updateShadowParameters(this.transform,this.style.directionalLight);for(const Ns in st)for(const ds of pt[Ns]){let Fs={min:0,max:0};this.terrain&&(Fs=this.terrain.getMinMaxForTile(ds)||Fs),Qt.addShadowReceiver(ds.toUnwrapped(),Fs.min,Fs.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 w6(this)),this._atmosphere.update(this)):this._atmosphere&&(this._atmosphere.destroy(),this._atmosphere=void 0);const At=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.snow),Dt=this._debugParams.forceEnablePrecipitation||!(!this.style||!this.style.rain);if(At&&!this._snow&&(this._snow=new ms(this)),!At&&this._snow&&(this._snow.destroy(),delete this._snow),Dt&&!this._rain&&(this._rain=new et(this)),!Dt&&this._rain&&(this._rain.destroy(),delete this._rain),this._snow&&this._snow.update(this),this._rain&&this._rain.update(this),_e){this.buildingTileBorderManager||(this.buildingTileBorderManager=new _m);const Ns=this.style.getLayerSourceCache(_e);this.buildingTileBorderManager.updateBorders(Ns,_e)}if(!He.has(this.context.gl))return;this.renderPass="offscreen";for(const Ns of qe){const ds=g.getLayerSourceCache(Ns);if(!Ns.hasOffscreenPass()||Ns.isHidden(this.transform.zoom))continue;const Fs=ds?mt[ds.id]:void 0;(Ns.type==="custom"||Ns.type==="raster"||Ns.type==="raster-particle"||Ns.isSky()||Fs&&Fs.length)&&this.renderLayer(this,ds,Ns,Fs)}this.depthRangeFor3D=[0,1-(qe.length+2)*this.numSublayers*this.depthEpsilon],this._shadowRenderer&&(this.renderPass="shadow",this._shadowRenderer.drawShadowPass(this.style,Et)),this.context.bindFramebuffer.set(null),this.context.viewport.set([0,0,this.width,this.height]);const Ht=this.transform.projection.name==="globe"||this.transform.isHorizonVisible(),gs=(()=>{if(C.showOverdrawInspector)return o.aq.black;const Ns=this.style.fog;if(Ns&&this.transform.projection.supportsFog){const ds=this.style.getLut(Ns.scope);if(!Ht){const Fs=Ns.properties.get("color-use-theme")==="none",Us=Ns.properties.get("color").toNonPremultipliedRenderColor(Fs?null:ds).toArray01();return new o.aq(...Us)}if(Ht){const Fs=Ns.properties.get("space-color-use-theme")==="none",Us=Ns.properties.get("space-color").toNonPremultipliedRenderColor(Fs?null:ds).toArray01();return new o.aq(...Us)}}return o.aq.transparent})();if(this.context.clear({color:gs,depth:1}),this.clearStencil(),this._showOverdrawInspector=C.showOverdrawInspector,this.renderPass="opaque",this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ht&&this._atmosphere.drawStars(this,this.style.fog),!this.terrain)for(this.currentLayer=te.length-1;this.currentLayer>=0;this.currentLayer--){const Ns=qe[this.currentLayer],ds=g.getLayerSourceCache(Ns);if(Ns.isSky())continue;const Fs=ds?(Ns.is3D(G)?xt:mt)[ds.id]:void 0;this._renderTileClippingMasks(Ns,ds,Fs),this.renderLayer(this,ds,Ns,Fs)}if(this.style.fog&&this.transform.projection.supportsFog&&this._atmosphere&&!this._showOverdrawInspector&&Ht&&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 Fs=this.currentLayer;this.depthOcclusion=!0;for(const Us of this.layersWithOcclusionOpacity){this.currentLayer=Us;const Ys=qe[this.currentLayer],Dn=g.getLayerSourceCache(Ys),kn=Dn?mt[Dn.id]:void 0;this.terrain||this._renderTileClippingMasks(Ys,Dn,Dn?pt[Dn.id]:void 0),this.renderLayer(this,Dn,Ys,kn)}this.depthOcclusion=!1,this.currentLayer=Fs,this.renderPass="translucent",this.layersWithOcclusionOpacity=[]}++this.currentLayer}}if(this.terrain&&this.terrain.postRender(),this._snow&&this._snow.draw(this),this._rain&&this._rain.draw(this),this.options.showTileBoundaries||this.options.showQueryGeometry||this.options.showTileAABBs){let Ns=null;qe.forEach(ds=>{const Fs=g.getLayerSourceCache(ds);Fs&&!ds.isHidden(this.transform.zoom)&&Fs.getVisibleCoordinates().length&&(!Ns||Ns.getSource().maxzoom0?C.pop():null}terrainRenderModeElevated(){return this.style&&!!this.style.getTerrain()&&!!this.terrain&&!this.terrain.renderingToTexture||this.forceTerrainMode}linearFloatFilteringSupported(){return this.context.extTextureFloatLinear!=null}currentGlobalDefines(g,C,L){const $=L===void 0?this.terrain&&this.terrain.renderingToTexture:L,G=[];return this.style&&this.style.enable3dLights()&&(g==="globeRaster"||g==="terrainRaster"?(G.push("LIGHTING_3D_MODE"),G.push("LIGHTING_3D_ALPHA_EMISSIVENESS")):$||G.push("LIGHTING_3D_MODE")),this.terrainRenderModeElevated()&&(G.push("TERRAIN"),this.linearFloatFilteringSupported()&&G.push("TERRAIN_DEM_FLOAT_FORMAT")),this.transform.projection.name==="globe"&&G.push("GLOBE"),!this._fogVisible||$||C!==void 0&&!C||G.push("FOG"),$&&G.push("RENDER_TO_TEXTURE"),this._showOverdrawInspector&&G.push("OVERDRAW_INSPECTOR"),G}getOrCreateProgram(g,C){this.cache=this.cache||{};const L=C&&C.defines||[],$=C&&C.config,G=this.currentGlobalDefines(g,C&&C.overrideFog,C&&C.overrideRtt).concat(L),K=od.cacheKey(dC[g],g,G,$);return this.cache[K]||(this.cache[K]=new od(this.context,g,dC[g],$,a_[g],G)),this.cache[K]}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 g=this.context.gl;this.context.cullFace.set(!1),this.context.viewport.set([0,0,this.width,this.height]),this.context.blendEquation.set(g.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(g,C){if(this.style.enable3dLights()){const L=this.style.directionalLight,$=this.style.ambientLight;if(L&&$){const G=((K,te,de)=>{const xe=K.properties.get("direction"),_e=K.properties.get("color-use-theme")==="none",Oe=K.properties.get("color").toNonPremultipliedRenderColor(_e?null:de.getLut(K.scope)).toArray01(),De=K.properties.get("intensity"),qe=te.properties.get("color-use-theme")==="none",st=te.properties.get("color").toNonPremultipliedRenderColor(qe?null:de.getLut(te.scope)).toArray01(),Xe=te.properties.get("intensity"),pt=[xe.x,xe.y,xe.z],mt=o.dD(st,Xe),kt=o.dD(Oe,De);return{u_lighting_ambient_color:mt,u_lighting_directional_dir:pt,u_lighting_directional_color:kt,u_ground_radiance:Jb(pt,kt,mt)}})(L,$,this.style);C.setLightsUniformValues(g,G)}}}uploadCommonUniforms(g,C,L,$,G){if(this.uploadCommonLightUniforms(g,C),this.terrain&&this.terrain.renderingToTexture)return;const K=this.style.fog;if(K){const te=K.getOpacity(this.transform.pitch),de=((xe,_e,Oe,De,qe,st,Xe,pt,mt,kt,Et,xt)=>{const es=xe.transform,Ot=_e.properties.get("color-use-theme")==="none",Qt=_e.properties.get("color").toNonPremultipliedRenderColor(Ot?null:xe.style.getLut(_e.scope)).toArray01();Qt[3]=De;const At=xe.frameCounter/1e3%1,[Dt,Ht]=_e.properties.get("vertical-range");return{u_fog_matrix:Oe?es.calculateFogTileMatrix(Oe):xt||xe.identityMat,u_fog_range:_e.getFovAdjustedRange(es._fov),u_fog_color:Qt,u_fog_horizon_blend:_e.properties.get("horizon-blend"),u_fog_vertical_limit:[Math.min(Dt,Ht),Ht],u_fog_temporal_offset:At,u_frustum_tl:qe,u_frustum_tr:st,u_frustum_br:Xe,u_frustum_bl:pt,u_globe_pos:mt,u_globe_radius:kt,u_viewport:Et,u_globe_transition:o.al(es.zoom),u_is_globe:+(es.projection.name==="globe")}})(this,K,L,te,this.transform.frustumCorners.TL,this.transform.frustumCorners.TR,this.transform.frustumCorners.BR,this.transform.frustumCorners.BL,this.transform.globeCenterInViewSpace,this.transform.globeRadius,[this.transform.width*o.o.devicePixelRatio,this.transform.height*o.o.devicePixelRatio],$);C.setFogUniformValues(g,de)}G&&C.setCutoffUniformValues(g,G.uniformValues)}setTileLoadedFlag(g){this.tileLoaded=g}saveCanvasCopy(){const g=this.canvasCopy();g&&(this.frameCopies.push(g),this.tileLoaded=!1)}canvasCopy(){const g=this.context.gl,C=g.createTexture();return g.bindTexture(g.TEXTURE_2D,C),g.copyTexImage2D(g.TEXTURE_2D,0,g.RGBA,0,0,g.drawingBufferWidth,g.drawingBufferHeight,0),C}getCanvasCopiesAndTimestamps(){return{canvasCopies:this.frameCopies,timeStamps:this.loadTimeStamps}}averageElevationNeedsEasing(){if(!this.transform._elevation)return!1;const g=this.style&&this.style.fog;return!!g&&g.getOpacity(this.transform.pitch)!==0}getBackgroundTiles(){const g=this._backgroundTiles,C=this._backgroundTiles={},L=this.transform.coveringTiles({tileSize:512});for(const $ of L)C[$.key]=g[$.key]||new o.b0($,512,this.transform.tileZoom,this,void 0,this.worldview);return C}clearBackgroundTiles(){this._backgroundTiles={}}isSourceForClippingOrConflation(g,C){return!(!g.is3D(!(!this.terrain||!this.terrain.enabled))||g.type!=="clip"&&g.type!=="building"&&(g.minzoom&&g.minzoom>this.transform.zoom||(this.style._clipLayerPresent||g.sourceLayer!=="building"&&g.sourceLayer!=="procedural_buildings")&&(!C||C.type!=="batched-model")))}isTileAffectedByFog(g){if(!this.style||!this.style.fog)return!1;if(this.transform.projection.name==="globe")return!0;let C=this._cachedTileFogOpacities[g.key];return C||(this._cachedTileFogOpacities[g.key]=C=this.style.fog.getOpacityForTile(g)),C[0]>=Er||C[1]>=Er}setupDepthForOcclusion(g,C,L){const $=this.context,G=$.gl,K=!!L;var te;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}),$.activeTexture.set(G.TEXTURE3),g&&this.depthFBO&&this.depthTexture?(this.depthTexture.bind(G.NEAREST,G.CLAMP_TO_EDGE),L.u_depth_size_inv=[1/this.depthFBO.width,1/this.depthFBO.height],L.u_depth_range_unpack=[2/((te=this.depthRangeFor3D)[1]-te[0]),-1-2*te[0]/(te[1]-te[0])],L.u_occluder_half_size=.5*this.occlusionParams.occluderSize,L.u_occlusion_depth_offset=this.occlusionParams.depthOffset):this.emptyDepthTexture.bind(G.NEAREST,G.CLAMP_TO_EDGE),$.activeTexture.set(G.TEXTURE0),K||C.setTerrainUniformValues($,L)}updateEmissiveMode(){if(this._forceEmissiveMode)return;const g=this.style.hasDataDrivenEmissiveStrength();this.emissiveMode=g?this.context.extBlendFuncExtended?"dual-source-blending":"mrt-fallback":"constant"}}function ja(M,g){let C=!1,L=null;const $=()=>{L=null,C&&(M(),L=setTimeout($,g),C=!1)};return()=>(C=!0,L||$(),L)}class yc{constructor(g){this._hashName=g&&encodeURIComponent(g),o.aZ(["_getCurrentHash","_onHashChange","_updateHash"],this),this._updateHash=ja(this._updateHashUnthrottled.bind(this),300)}addTo(g){return this._map=g,window.addEventListener("hashchange",this._onHashChange,!1),g.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 g=this._map;if(!g)return"";const C=lo(g);if(this._hashName){const L=this._hashName;let $=!1;const G=location.hash.slice(1).split("&").map(K=>{const te=K.split("=")[0];return te===L?($=!0,`${te}=${C}`):K}).filter(K=>K);return $||G.push(`${L}=${C}`),`#${G.join("&")}`}return`#${C}`}_getCurrentHash(){const g=location.hash.replace("#","");if(this._hashName){let C;return g.split("&").map(L=>L.split("=")).forEach(L=>{L[0]===this._hashName&&(C=L)}),(C&&C[1]||"").split("/")}return g.split("/")}_onHashChange(){const g=this._map;if(!g)return!1;const C=this._getCurrentHash();if(C.length>=3&&!C.some(L=>isNaN(Number(L)))){const L=g.dragRotate.isEnabled()&&g.touchZoomRotate.isEnabled()?+(C[3]||0):g.getBearing();return g.jumpTo({center:[+C[2],+C[1]],zoom:+C[0],bearing:L,pitch:+(C[4]||0)}),!0}return!1}_updateHashUnthrottled(){history.replaceState(history.state,"",location.href.replace(/(#.+)?$/,this.getHashString()))}}function lo(M,g){const C=M.getCenter(),L=Math.round(100*M.getZoom())/100,$=Math.ceil((L*Math.LN2+Math.log(512/360/.5))/Math.LN10),G=Math.pow(10,$),K=Math.round(C.lng*G)/G,te=Math.round(C.lat*G)/G,de=M.getBearing(),xe=M.getPitch();let _e=g?`/${K}/${te}/${L}`:`${L}/${te}/${K}`;return(de||xe)&&(_e+="/"+Math.round(10*de)/10),xe&&(_e+=`/${Math.round(xe)}`),_e}const xh={linearity:.3,easing:o.eN(0,0,.3,1)},Hp=Object.assign({deceleration:2500,maxSpeed:1400},xh),qn=Object.assign({deceleration:20,maxSpeed:1400},xh),Ks=Object.assign({deceleration:1e3,maxSpeed:360},xh),ln=Object.assign({deceleration:1e3,maxSpeed:90},xh);class Ma{constructor(g){this._map=g,this.clear()}clear(){this._inertiaBuffer=[]}record(g){this._drainInertiaBuffer(),this._inertiaBuffer.push({time:o.o.now(),settings:g})}_drainInertiaBuffer(){const g=this._inertiaBuffer,C=o.o.now();for(;g.length>0&&C-g[0].time>160;)g.shift()}_onMoveEnd(g){if(this._map._prefersReducedMotion()||(this._drainInertiaBuffer(),this._inertiaBuffer.length<2))return;const C={zoom:0,bearing:0,pitch:0,pan:new o.P(0,0),pinchAround:void 0,around:void 0};for(const{settings:G}of this._inertiaBuffer)C.zoom+=G.zoomDelta||0,C.bearing+=G.bearingDelta||0,C.pitch+=G.pitchDelta||0,G.panDelta&&C.pan._add(G.panDelta),G.around&&(C.around=G.around),G.pinchAround&&(C.pinchAround=G.pinchAround);const L=this._inertiaBuffer[this._inertiaBuffer.length-1].time-this._inertiaBuffer[0].time,$={};if(C.pan.mag()){const G=Di(C.pan.mag(),L,Object.assign({},Hp,g||{}));$.offset=C.pan.mult(G.amount/C.pan.mag()),$.center=this._map.transform.center,qa($,G)}if(C.zoom){const G=Di(C.zoom,L,qn);$.zoom=this._map.transform.zoom+G.amount,qa($,G)}if(C.bearing){const G=Di(C.bearing,L,Ks);$.bearing=this._map.transform.bearing+o.aC(G.amount,-179,179),qa($,G)}if(C.pitch){const G=Di(C.pitch,L,ln);$.pitch=this._map.transform.pitch+G.amount,qa($,G)}if($.zoom||$.bearing){const G=C.pinchAround===void 0?C.around:C.pinchAround;$.around=G?this._map.unproject(G):this._map.getCenter()}return this.clear(),$.noMoveStart=!0,$}}function qa(M,g){(!M.duration||M.durationC.unproject(de)),te=G.reduce((de,xe,_e,Oe)=>de.add(xe.div(Oe.length)),new o.P(0,0));super(g,{points:G,point:te,lngLats:K,lngLat:C.unproject(te),originalEvent:L}),this._defaultPrevented=!1}}class Wd extends o.C{preventDefault(){this._defaultPrevented=!0}get defaultPrevented(){return this._defaultPrevented}constructor(g,C){super("wheel",{originalEvent:C}),this._defaultPrevented=!1}}class nl{constructor(g,C){this._map=g,this._clickTolerance=C.clickTolerance}reset(){this._mousedownPos=void 0}wheel(g){return this._firePreventable(new Wd(this._map,g))}mousedown(g,C){return this._mousedownPos=C,this._firePreventable(new ni(g.type,this._map,g))}mouseup(g){this._map.fire(new ni(g.type,this._map,g))}preclick(g){const C=new MouseEvent("preclick",g);this._map.fire(new ni(C.type,this._map,C))}click(g,C){this._mousedownPos&&this._mousedownPos.dist(C)>=this._clickTolerance||(this.preclick(g),this._map.fire(new ni(g.type,this._map,g)))}dblclick(g){return this._firePreventable(new ni(g.type,this._map,g))}mouseover(g){this._map.fire(new ni(g.type,this._map,g))}mouseout(g){this._map.fire(new ni(g.type,this._map,g))}touchstart(g){return this._firePreventable(new no(g.type,this._map,g))}touchmove(g){this._map.fire(new no(g.type,this._map,g))}touchend(g){this._map.fire(new no(g.type,this._map,g))}touchcancel(g){this._map.fire(new no(g.type,this._map,g))}_firePreventable(g){if(this._map.fire(g),g.defaultPrevented)return{}}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class xg{constructor(g){this._map=g}reset(){this._delayContextMenu=!1,this._contextMenuEvent=void 0}mousemove(g){this._map.fire(new ni(g.type,this._map,g))}mousedown(){this._delayContextMenu=!0}mouseup(){this._delayContextMenu=!1,this._contextMenuEvent&&(this._map.fire(new ni("contextmenu",this._map,this._contextMenuEvent)),delete this._contextMenuEvent)}contextmenu(g){this._delayContextMenu?this._contextMenuEvent=g:this._map.fire(new ni(g.type,this._map,g)),this._map.listens("contextmenu")&&g.preventDefault()}isEnabled(){return!0}isActive(){return!1}enable(){}disable(){}}class AC{constructor(g,C){this._map=g,this._el=g.getCanvasContainer(),this._container=g.getContainer(),this._clickTolerance=C.clickTolerance||1}isEnabled(){return!!this._enabled}isActive(){return!!this._active}enable(){this.isEnabled()||(this._enabled=!0)}disable(){this.isEnabled()&&(this._enabled=!1)}mousedown(g,C){this.isEnabled()&&g.shiftKey&&g.button===0&&(A(),this._startPos=this._lastPos=C,this._active=!0)}mousemoveWindow(g,C){if(!this._active)return;const L=C,$=this._startPos,G=this._lastPos;if(!$||!G||G.equals(L)||!this._box&&L.dist($){this._box&&(this._box.style.transform=`translate(${K}px,${de}px)`,this._box.style.width=te-K+"px",this._box.style.height=xe-de+"px")})}mouseupWindow(g,C){if(!this._active)return;const L=this._startPos,$=C;if(L&&g.button===0){if(this.reset(),D(),L.x!==$.x||L.y!==$.y)return this._map.fire(new o.C("boxzoomend",{originalEvent:g})),{cameraAnimation:G=>G.fitScreenCoordinates(L,$,this._map.getBearing(),{linear:!1})};this._fireEvent("boxzoomcancel",g)}}keydown(g){this._active&&g.keyCode===27&&(this.reset(),this._fireEvent("boxzoomcancel",g))}blur(){this.reset()}reset(){this._active=!1,this._container.classList.remove("mapboxgl-crosshair"),this._box&&(this._box.remove(),this._box=null),E(),delete this._startPos,delete this._lastPos}_fireEvent(g,C){return this._map.fire(new o.C(g,{originalEvent:C}))}}function MC(M,g){const C={};for(let L=0;Lthis.numTouches)&&(this.aborted=!0),this.aborted||(this.startTime===0&&(this.startTime=g.timeStamp),L.length===this.numTouches&&(this.centroid=function($){const G=new o.P(0,0);for(const K of $)G._add(K);return G.div($.length)}(C),this.touches=MC(L,C)))}touchmove(g,C,L){if(this.aborted||!this.centroid)return;const $=MC(L,C);for(const G in this.touches){const K=$[G];(!K||K.dist(this.touches[G])>30)&&(this.aborted=!0)}}touchend(g,C,L){if((!this.centroid||g.timeStamp-this.startTime>500)&&(this.aborted=!0),L.length===0){const $=!this.aborted&&this.centroid;if(this.reset(),$)return $}}}class Yy{constructor(g){this.singleTap=new gg(g),this.numTaps=g.numTaps,this.reset()}reset(){this.lastTime=1/0,this.lastTap=void 0,this.count=0,this.singleTap.reset()}touchstart(g,C,L){this.singleTap.touchstart(g,C,L)}touchmove(g,C,L){this.singleTap.touchmove(g,C,L)}touchend(g,C,L){const $=this.singleTap.touchend(g,C,L);if($){const G=g.timeStamp-this.lastTime<500,K=!this.lastTap||this.lastTap.dist($)<30;if(G&&K||this.reset(),this.count++,this.lastTime=g.timeStamp,this.lastTap=$,this.count===this.numTaps)return this.reset(),$}}}class sk{constructor(){this._zoomIn=new Yy({numTouches:1,numTaps:2}),this._zoomOut=new Yy({numTouches:2,numTaps:1}),this.reset()}reset(){this._active=!1,this._zoomIn.reset(),this._zoomOut.reset()}touchstart(g,C,L){this._zoomIn.touchstart(g,C,L),this._zoomOut.touchstart(g,C,L)}touchmove(g,C,L){this._zoomIn.touchmove(g,C,L),this._zoomOut.touchmove(g,C,L)}touchend(g,C,L){const $=this._zoomIn.touchend(g,C,L),G=this._zoomOut.touchend(g,C,L);return $?(this._active=!0,g.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:K=>K.easeTo({duration:300,zoom:K.getZoom()+1,around:K.unproject($)},{originalEvent:g})}):G?(this._active=!0,g.preventDefault(),setTimeout(()=>this.reset(),0),{cameraAnimation:K=>K.easeTo({duration:300,zoom:K.getZoom()-1,around:K.unproject(G)},{originalEvent:g})}):void 0}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}const N6=0,DR=2,RR={[N6]:1,[DR]:2},N1={Control:"ctrlKey",Alt:"altKey",Shift:"shiftKey",Meta:"metaKey"};class IC{constructor(g){this.reset(),this._clickTolerance=g.clickTolerance||1}blur(){this.reset()}reset(){this._active=!1,this._moved=!1,this._lastPoint=void 0,this._eventButton=void 0}_correctButton(g,C){return!1}_move(g,C){return{}}mousedown(g,C){if(this._lastPoint)return;const L=z(g);this._correctButton(g,L)&&(this._lastPoint=C,this._eventButton=L)}mousemoveWindow(g,C){const L=this._lastPoint;if(L){if(g.preventDefault(),this._eventButton!=null&&function($,G){const K=RR[G];return $.buttons===void 0||($.buttons&K)!==K}(g,this._eventButton))this.reset();else if(this._moved||!(C.dist(L)0&&(this._active=!0);const $=MC(L,C),G=new o.P(0,0),K=new o.P(0,0);let te=0;for(const xe in $){const _e=$[xe],Oe=this._touches[xe];Oe&&(G._add(_e),K._add(_e.sub(Oe)),te++,$[xe]=_e)}if(this._touches=$,te{this._alertContainer.classList.remove("mapboxgl-touch-pan-blocker-show"),this._alertContainer.removeAttribute("role")},500)}}class LC{constructor(){this.reset()}reset(){this._active=!1,this._firstTwoTouches=void 0}_start(g){}_move(g,C,L){return{}}touchstart(g,C,L){this._firstTwoTouches||L.length<2||(this._firstTwoTouches=[L[0].identifier,L[1].identifier],this._start([C[0],C[1]]))}touchmove(g,C,L){const $=this._firstTwoTouches;if(!$)return;g.preventDefault();const[G,K]=$,te=tc(L,C,G),de=tc(L,C,K);if(!te||!de)return;const xe=this._aroundCenter?null:te.add(de).div(2);return this._move([te,de],xe,g)}touchend(g,C,L){if(!this._firstTwoTouches)return;const[$,G]=this._firstTwoTouches,K=tc(L,C,$),te=tc(L,C,G);K&&te||(this._active&&D(),this.reset())}touchcancel(){this.reset()}enable(g){this._enabled=!0,this._aroundCenter=!!g&&g.around==="center"}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}function tc(M,g,C){for(let L=0;LMath.abs(M.x)}class zR extends LC{constructor(g){super(),this._map=g}reset(){super.reset(),this._valid=void 0,this._firstMove=void 0,this._lastPoints=void 0}_start(g){this._lastPoints=g,DC(g[0].sub(g[1]))&&(this._valid=!1)}_move(g,C,L){const $=this._lastPoints;if(!$)return;const G=g[0].sub($[0]),K=g[1].sub($[1]);return this._map._cooperativeGestures&&!o.eO()&&L.touches.length<3||(this._valid=this.gestureBeginsVertically(G,K,L.timeStamp),!this._valid)?void 0:(this._lastPoints=g,this._active=!0,{pitchDelta:(G.y+K.y)/2*-.5})}gestureBeginsVertically(g,C,L){if(this._valid!==void 0)return this._valid;const $=g.mag()>=2,G=C.mag()>=2;if(!$&&!G)return;if(!$||!G)return this._firstMove==null&&(this._firstMove=L),L-this._firstMove<100&&void 0;const K=g.y>0==C.y>0;return DC(g)&&DC(C)&&K}}const BR={panStep:100,bearingStep:15,pitchStep:10};class $j{constructor(){const g=BR;this._panStep=g.panStep,this._bearingStep=g.bearingStep,this._pitchStep=g.pitchStep,this._rotationDisabled=!1}blur(){this.reset()}reset(){this._active=!1}keydown(g){if(g.altKey||g.ctrlKey||g.metaKey)return;let C=0,L=0,$=0,G=0,K=0;switch(g.keyCode){case 61:case 107:case 171:case 187:C=1;break;case 189:case 109:case 173:C=-1;break;case 37:g.shiftKey?L=-1:(g.preventDefault(),G=-1);break;case 39:g.shiftKey?L=1:(g.preventDefault(),G=1);break;case 38:g.shiftKey?$=1:(g.preventDefault(),K=-1);break;case 40:g.shiftKey?$=-1:(g.preventDefault(),K=1);break;default:return}return this._rotationDisabled&&(L=0,$=0),{cameraAnimation:te=>{const de=te.getZoom();te.easeTo({duration:300,easeId:"keyboardHandler",easing:$R,zoom:C?Math.round(de)+C*(g.shiftKey?2:1):de,bearing:te.getBearing()+L*this._bearingStep,pitch:te.getPitch()+$*this._pitchStep,offset:[-G*this._panStep,-K*this._panStep],center:te.getCenter()},{originalEvent:g})}}}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 $R(M){return M*(2-M)}const Uj=4.000244140625,UR=1/450;class T6{constructor(g,C){this._map=g,this._el=g.getCanvasContainer(),this._handler=C,this._delta=0,this._lastDelta=0,this._defaultZoomRate=.01,this._wheelZoomRate=UR,o.aZ(["_onTimeout","_addScrollZoomBlocker","_showBlockerAlert"],this)}setZoomRate(g){this._defaultZoomRate=g}setWheelZoomRate(g){this._wheelZoomRate=g}isEnabled(){return!!this._enabled}isActive(){return this._active||this._finishTimeout!==void 0}isZooming(){return!!this._zooming}enable(g){this.isEnabled()||(this._enabled=!0,this._aroundCenter=!!g&&g.around==="center",this._map._cooperativeGestures&&this._addScrollZoomBlocker())}disable(){this.isEnabled()&&(this._enabled=!1,this._map._cooperativeGestures&&(clearTimeout(this._alertTimer),this._alertContainer.remove()))}wheel(g){if(!this.isEnabled())return;if(this._map._cooperativeGestures){if(!(g.ctrlKey||g.metaKey||this.isZooming()||o.eO()))return void this._showBlockerAlert();this._alertContainer.style.visibility!=="hidden"&&(this._alertContainer.style.visibility="hidden",clearTimeout(this._alertTimer))}let C=g.deltaMode===WheelEvent.DOM_DELTA_LINE?40*g.deltaY:g.deltaY;const L=o.o.now(),$=L-(this._lastWheelEventTime||0);this._lastWheelEventTime=L,C!==0&&C%Uj===0?this._type="wheel":C!==0&&Math.abs(C)<4?this._type="trackpad":$>400?(this._type=null,this._lastValue=C,this._timeout=window.setTimeout(this._onTimeout,40,g)):this._type||(this._type=Math.abs($*C)<200?"trackpad":"wheel",this._timeout&&(clearTimeout(this._timeout),this._timeout=null,C+=this._lastValue)),g.shiftKey&&C&&(C/=4),this._type&&(this._lastWheelEvent=g,this._delta-=C,this._active||this._start(g)),g.preventDefault()}_onTimeout(g){this._type="wheel",this._delta-=this._lastValue,this._active||this._start(g)}_start(g){if(!this._delta)return;this._frameId&&(this._frameId=null),this._active=!0,this.isZooming()||(this._zooming=!0),this._finishTimeout&&(clearTimeout(this._finishTimeout),delete this._finishTimeout);const C=I(this._el,g);this._aroundPoint=this._aroundCenter?this._map.transform.centerPoint:C,this._aroundCoord=this._map.transform.pointCoordinate3D(this._aroundPoint),this._targetZoom=void 0,this._frameId||(this._frameId=!0,this._handler._triggerRenderFrame())}renderFrame(){if(!this._frameId||(this._frameId=null,!this.isActive()))return;const g=this._map.transform;this._type==="wheel"&&g.projection.wrap&&(g._center.lng>=180||g._center.lng<=-180)&&(this._prevEase=null,this._easing=null,this._lastWheelEvent=null,this._lastWheelEventTime=0);const C=()=>g._terrainEnabled()&&this._aroundCoord?g.computeZoomRelativeTo(this._aroundCoord):g.zoom;if(this._delta!==0){const xe=this._type==="wheel"&&Math.abs(this._delta)>Uj?this._wheelZoomRate:this._defaultZoomRate;let _e=2/(1+Math.exp(-Math.abs(this._delta*xe)));this._delta<0&&_e!==0&&(_e=1/_e);const Oe=C(),De=Math.pow(2,Oe),qe=typeof this._targetZoom=="number"?g.zoomScale(this._targetZoom):De;this._targetZoom=Math.min(g.maxZoom,Math.max(g.minZoom,g.scaleZoom(qe*_e))),this._type==="wheel"&&(this._startZoom=Oe,this._easing=this._smoothOutEasing(200)),this._lastDelta=this._delta,this._delta=0}const L=typeof this._targetZoom=="number"?this._targetZoom:C(),$=this._startZoom,G=this._easing;let K,te=!1;if(this._type==="wheel"&&$&&G){const xe=Math.min((o.o.now()-this._lastWheelEventTime)/200,1),_e=G(xe);K=o.am($,L,_e),xe<1?this._frameId||(this._frameId=!0):te=!0}else K=L,te=!0;this._active=!0,te&&(this._active=!1,this._finishTimeout=window.setTimeout(()=>{this._zooming=!1,this._handler._triggerRenderFrame(),delete this._targetZoom,delete this._finishTimeout},200));let de=K-C();return de*this._lastDelta<0&&(de=0),{noInertia:!0,needsRenderFrame:!te,zoomDelta:de,around:this._aroundPoint,aroundCoord:this._aroundCoord,originalEvent:this._lastWheelEvent}}_smoothOutEasing(g){let C=o.eP;if(this._prevEase){const L=this._prevEase,$=(o.o.now()-L.start)/L.duration,G=L.easing($+.01)-L.easing($),K=.27/Math.sqrt(G*G+1e-4)*.01,te=Math.sqrt(.0729-K*K);C=o.eN(K,te,.25,1)}return this._prevEase={start:o.o.now(),duration:g,easing:C},C}blur(){this.reset()}reset(){this._active=!1}_addScrollZoomBlocker(){this._map&&!this._alertContainer&&(this._alertContainer=_("div","mapboxgl-scroll-zoom-blocker",this._map._container),this._alertContainer.textContent=/(Mac|iPad)/i.test(navigator.userAgent)?this._map._getUIString("ScrollZoomBlocker.CmdMessage"):this._map._getUIString("ScrollZoomBlocker.CtrlMessage"),this._alertContainer.style.fontSize=`${Math.max(10,Math.min(24,Math.floor(.05*this._el.clientWidth)))}px`)}_showBlockerAlert(){this._alertContainer.style.visibility="visible",this._alertContainer.classList.add("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.setAttribute("role","alert"),clearTimeout(this._alertTimer),this._alertTimer=window.setTimeout(()=>{this._alertContainer.classList.remove("mapboxgl-scroll-zoom-blocker-show"),this._alertContainer.removeAttribute("role")},200)}}class E6{constructor(g,C){this._clickZoom=g,this._tapZoom=C}enable(){this._clickZoom.enable(),this._tapZoom.enable()}disable(){this._clickZoom.disable(),this._tapZoom.disable()}isEnabled(){return this._clickZoom.isEnabled()&&this._tapZoom.isEnabled()}isActive(){return this._clickZoom.isActive()||this._tapZoom.isActive()}}class A6{constructor(){this.reset()}reset(){this._active=!1}blur(){this.reset()}dblclick(g,C){return g.preventDefault(),{cameraAnimation:L=>{L.easeTo({duration:300,zoom:L.getZoom()+(g.shiftKey?-1:1),around:L.unproject(C)},{originalEvent:g})}}}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class WU{constructor(){this._tap=new Yy({numTouches:1,numTaps:1}),this.reset()}reset(){this._active=!1,this._swipePoint=void 0,this._swipeTouch=0,this._tapTime=0,this._tap.reset()}touchstart(g,C,L){this._swipePoint||(this._tapTime&&g.timeStamp-this._tapTime>500&&this.reset(),this._tapTime?L.length>0&&(this._swipePoint=C[0],this._swipeTouch=L[0].identifier):this._tap.touchstart(g,C,L))}touchmove(g,C,L){if(this._tapTime){if(this._swipePoint){if(L[0].identifier!==this._swipeTouch)return;const $=C[0],G=$.y-this._swipePoint.y;return this._swipePoint=$,g.preventDefault(),this._active=!0,{zoomDelta:G/128}}}else this._tap.touchmove(g,C,L)}touchend(g,C,L){this._tapTime?this._swipePoint&&L.length===0&&this.reset():this._tap.touchend(g,C,L)&&(this._tapTime=g.timeStamp)}touchcancel(){this.reset()}enable(){this._enabled=!0}disable(){this._enabled=!1,this.reset()}isEnabled(){return this._enabled}isActive(){return this._active}}class qR{constructor(g,C,L){this._el=g,this._mousePan=C,this._touchPan=L}enable(g){this._inertiaOptions=g||{},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 KU{constructor(g,C,L){this._pitchWithRotate=g.pitchWithRotate,this._mouseRotate=C,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 YU{constructor(g,C,L,$){this._el=g,this._touchZoom=C,this._touchRotate=L,this._tapDragZoom=$,this._rotationDisabled=!1,this._enabled=!0}enable(g){this._touchZoom.enable(g),this._rotationDisabled||this._touchRotate.enable(g),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 RC=M=>M.zoom||M.drag||M.pitch||M.rotate;class ZU extends o.C{}class QU{constructor(){this.constants=[1,1,.01],this.radius=0}setup(g,C){const L=o.ax([],C,g);this.radius=o.ai(L[2]<0?o.eR([],L,this.constants):[L[0],L[1],0])}projectRay(g){o.eR(g,g,this.constants),o.ay(g,g),o.eS(g,g,this.constants);const C=o.bJ([],g,this.radius);if(C[2]>0){const L=o.bJ([],[0,0,1],o.bi(C,[0,0,1])),$=o.bJ([],o.ay([],[C[0],C[1],0]),this.radius),G=o.cT([],C,o.bJ([],o.ax([],o.cT([],$,L),C),2));C[0]=G[0],C[1]=G[1]}return C}}function OC(M){return M.panDelta&&M.panDelta.mag()||M.zoomDelta||M.bearingDelta||M.pitchDelta}class XU{constructor(g,C){this._map=g,this._el=this._map.getCanvasContainer(),this._handlers=[],this._handlersById={},this._changes=[],this._inertia=new Ma(g),this._bearingSnap=C.bearingSnap,this._previousActiveHandlers={},this._trackingEllipsoid=new QU,this._dragOrigin=null,this._eventsInProgress={},this._addDefaultHandlers(C),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[$,G,K]of this._listeners){const te=$===document?this.handleWindowEvent:this.handleEvent;$.addEventListener(G,te,K)}}destroy(){for(const[g,C,L]of this._listeners){const $=g===document?this.handleWindowEvent:this.handleEvent;g.removeEventListener(C,$,L)}}_addDefaultHandlers(g){const C=this._map,L=C.getCanvasContainer();this._add("mapEvent",new nl(C,g));const $=C.boxZoom=new AC(C,g);this._add("boxZoom",$);const G=new sk,K=new A6;C.doubleClickZoom=new E6(K,G),this._add("tapZoom",G),this._add("clickZoom",K);const te=new WU;this._add("tapDragZoom",te);const de=C.touchPitch=new zR(C);this._add("touchPitch",de);const xe=new k6(g),_e=new PC(g);C.dragRotate=new KU(g,xe,_e),this._add("mouseRotate",xe,["mousePitch"]),this._add("mousePitch",_e,["mouseRotate"]);const Oe=new yg(g),De=new OR(C,g);C.dragPan=new qR(L,Oe,De),this._add("mousePan",Oe),this._add("touchPan",De,["touchZoom","touchRotate"]);const qe=new Bj,st=new FR;C.touchZoomRotate=new YU(L,st,qe,te),this._add("touchRotate",qe,["touchPan","touchZoom"]),this._add("touchZoom",st,["touchPan","touchRotate"]),this._add("blockableMapEvent",new xg(C));const Xe=C.scrollZoom=new T6(C,this);this._add("scrollZoom",Xe,["mousePan"]);const pt=C.keyboard=new $j;this._add("keyboard",pt);for(const mt of["boxZoom","doubleClickZoom","tapDragZoom","touchPitch","dragRotate","dragPan","touchZoomRotate","scrollZoom","keyboard"])g.interactive&&g[mt]&&C[mt].enable(g[mt])}_add(g,C,L){this._handlers.push({handlerName:g,handler:C,allowed:L}),this._handlersById[g]=C}stop(g){if(!this._updatingCamera){for(const{handler:C}of this._handlers)C.reset();this._inertia.clear(),this._fireEvents({},{},g),this._changes=[],this._originalZoom=void 0}}isActive(){for(const{handler:g}of this._handlers)if(g.isActive())return!0;return!1}isZooming(){return!!this._eventsInProgress.zoom||this._map.scrollZoom.isZooming()}isRotating(){return!!this._eventsInProgress.rotate}isMoving(){return!!RC(this._eventsInProgress)||this.isZooming()}_isDragging(){return!!this._eventsInProgress.drag}_blockedByActive(g,C,L){for(const $ in g)if($!==L&&(!C||C.indexOf($)<0))return!0;return!1}handleWindowEvent(g){this.handleEvent(g,`${g.type}Window`)}_getMapTouches(g){const C=[];for(const L of g)this._el.contains(L.target)&&C.push(L);return C}handleEvent(g,C){this._updatingCamera=!0;const L=g.type==="renderFrame",$=L?void 0:g,G={needsRenderFrame:!1},K={},te={},de=g.touches?this._getMapTouches(g.touches):void 0,xe=de?F(this._el,de):L?void 0:I(this._el,g);for(const{handlerName:De,handler:qe,allowed:st}of this._handlers){if(!qe.isEnabled())continue;let Xe;this._blockedByActive(te,st,De)?qe.reset():qe[C||g.type]&&(Xe=qe[C||g.type](g,xe,de),this.mergeHandlerResult(G,K,Xe,De,$),Xe&&Xe.needsRenderFrame&&this._triggerRenderFrame()),(Xe||qe.isActive())&&(te[De]=qe)}const _e={};for(const De in this._previousActiveHandlers)te[De]||(_e[De]=$);this._previousActiveHandlers=te,(Object.keys(_e).length||OC(G))&&(this._changes.push([G,K,_e]),this._triggerRenderFrame()),(Object.keys(te).length||OC(G))&&this._map._stop(!0),this._updatingCamera=!1;const{cameraAnimation:Oe}=G;Oe&&(this._inertia.clear(),this._fireEvents({},{},!0),this._changes=[],Oe(this._map))}mergeHandlerResult(g,C,L,$,G){if(!L)return;Object.assign(g,L);const K={handlerName:$,originalEvent:L.originalEvent||G};L.zoomDelta!==void 0&&(C.zoom=K),L.panDelta!==void 0&&(C.drag=K),L.pitchDelta!==void 0&&(C.pitch=K),L.bearingDelta!==void 0&&(C.rotate=K)}_applyChanges(){const g={},C={},L={};for(const[$,G,K]of this._changes)$.panDelta&&(g.panDelta=(g.panDelta||new o.P(0,0))._add($.panDelta)),$.zoomDelta&&(g.zoomDelta=(g.zoomDelta||0)+$.zoomDelta),$.bearingDelta&&(g.bearingDelta=(g.bearingDelta||0)+$.bearingDelta),$.pitchDelta&&(g.pitchDelta=(g.pitchDelta||0)+$.pitchDelta),$.around!==void 0&&(g.around=$.around),$.aroundCoord!==void 0&&(g.aroundCoord=$.aroundCoord),$.pinchAround!==void 0&&(g.pinchAround=$.pinchAround),$.noInertia&&(g.noInertia=$.noInertia),Object.assign(C,G),Object.assign(L,K);this._updateMapTransform(g,C,L),this._changes=[]}_updateMapTransform(g,C,L){const $=this._map,G=$.transform,K=kt=>[kt.x,kt.y,kt.z];if((()=>{const kt=this._eventsInProgress.drag;return kt&&!this._handlersById[kt.handlerName].isActive()})()&&!OC(g)){const kt=G.zoom;G.cameraElevationReference="sea",this._originalZoom!=null&&G._orthographicProjectionAtLowPitch&&G.projection.name!=="globe"&&G.pitch===0?(G.cameraElevationReference="ground",G.zoom=this._originalZoom):(G.recenterOnTerrain(),G.cameraElevationReference="ground"),kt!==G.zoom&&this._map._update(!0)}if(G._isCameraConstrained&&$._stop(!0),!OC(g))return void this._fireEvents(C,L,!0);let{panDelta:te,zoomDelta:de,bearingDelta:xe,pitchDelta:_e,around:Oe,aroundCoord:De,pinchAround:qe}=g;G._isCameraConstrained&&(de>0&&(de=0),G._isCameraConstrained=!1),qe!==void 0&&(Oe=qe),(de||(kt=>C[kt]&&!this._eventsInProgress[kt])("drag"))&&Oe&&(this._dragOrigin=K(G.pointCoordinate3D(Oe)),this._originalZoom=G.zoom,this._trackingEllipsoid.setup(G._camera.position,this._dragOrigin)),G.cameraElevationReference="sea",$._stop(!0),Oe=Oe||$.transform.centerPoint,xe&&(G.bearing+=xe),_e&&(G.pitch+=_e),G._updateCameraState();const st=[0,0,0];if(te)if(G.projection.name==="mercator"){const kt=this._trackingEllipsoid.projectRay(G.screenPointToMercatorRay(Oe).dir),Et=this._trackingEllipsoid.projectRay(G.screenPointToMercatorRay(Oe.sub(te)).dir);st[0]=Et[0]-kt[0],st[1]=Et[1]-kt[1]}else{const kt=G.pointCoordinate(Oe);if(G.projection.name==="globe"){te=te.rotate(-G.angle);const Et=G._pixelsPerMercatorPixel/G.worldSize;st[0]=-te.x*o.eQ(o.bV(kt.y))*Et,st[1]=-te.y*o.eQ(G.center.lat)*Et}else{const Et=G.pointCoordinate(Oe.sub(te));kt&&Et&&(st[0]=Et.x-kt.x,st[1]=Et.y-kt.y)}}const Xe=G.zoom,pt=[0,0,0];if(de){const kt=K(De||G.pointCoordinate3D(Oe)),Et={dir:o.ay([],o.ax([],kt,G._camera.position))};if(Et.dir[2]<0){const xt=G.zoomDeltaToMovement(kt,de);o.bJ(pt,Et.dir,xt)}}const mt=o.cT(st,st,pt);G._translateCameraConstrained(mt),de&&Math.abs(G.zoom-Xe)>1e-4&&G.recenterOnTerrain(),G.cameraElevationReference="ground",this._map._update(),g.noInertia||this._inertia.record(g),this._fireEvents(C,L,!0)}_fireEvents(g,C,L){const $=RC(this._eventsInProgress),G=RC(g),K={};for(const _e in g){const{originalEvent:Oe}=g[_e];this._eventsInProgress[_e]||(K[`${_e}start`]=Oe),this._eventsInProgress[_e]=g[_e]}!$&&G&&this._fireEvent("movestart",G.originalEvent);for(const _e in K)this._fireEvent(_e,K[_e]);G&&this._fireEvent("move",G.originalEvent);for(const _e in g){const{originalEvent:Oe}=g[_e];this._fireEvent(_e,Oe)}const te={};let de;for(const _e in this._eventsInProgress){const{handlerName:Oe,originalEvent:De}=this._eventsInProgress[_e];this._handlersById[Oe].isActive()||(delete this._eventsInProgress[_e],de=C[Oe]||De,te[`${_e}end`]=de)}for(const _e in te)this._fireEvent(_e,te[_e]);const xe=RC(this._eventsInProgress);if(L&&($||G)&&!xe){this._updatingCamera=!0;const _e=this._inertia._onMoveEnd(this._map.dragPan._inertiaOptions),Oe=De=>De!==0&&-this._bearingSnap{this._frameId=void 0,this.handleEvent(new ZU("renderFrame",{timeStamp:g})),this._applyChanges()})}_triggerRenderFrame(){this._frameId===void 0&&(this._frameId=this._requestFrame())}}const VR="map.setFreeCameraOptions(...) and map.getFreeCameraOptions() are not yet supported for non-mercator projections.";class JU extends o.E{constructor(g,C){super(),this._moving=!1,this._zooming=!1,this.transform=g,this._bearingSnap=C.bearingSnap,this._respectPrefersReducedMotion=C.respectPrefersReducedMotion!==!1,o.aZ(["_renderFrameCallback"],this)}getCenter(){return new o.aU(this.transform.center.lng,this.transform.center.lat)}setCenter(g,C){return this.jumpTo({center:g},C)}panBy(g,C,L){return g=o.P.convert(g).mult(-1),this.panTo(this.transform.center,Object.assign({offset:g},C),L)}panTo(g,C,L){return this.easeTo(Object.assign({center:g},C),L)}getZoom(){return this.transform.zoom}setZoom(g,C){return this.jumpTo({zoom:g},C),this}zoomTo(g,C,L){return this.easeTo(Object.assign({zoom:g},C),L)}zoomIn(g,C){return this.zoomTo(this.getZoom()+1,g,C),this}zoomOut(g,C){return this.zoomTo(this.getZoom()-1,g,C),this}getBearing(){return this.transform.bearing}setBearing(g,C){return this.jumpTo({bearing:g},C),this}getPadding(){return this.transform.padding}setPadding(g,C){return this.jumpTo({padding:g},C),this}rotateTo(g,C,L){return this.easeTo(Object.assign({bearing:g},C),L)}resetNorth(g,C){return this.rotateTo(0,Object.assign({duration:1e3},g),C),this}resetNorthPitch(g,C){return this.easeTo(Object.assign({bearing:0,pitch:0,duration:1e3},g),C),this}snapToNorth(g,C){return Math.abs(this.getBearing())g.aspect?L/(2*Math.tan(.5*g.fovX)*g.aspect):$/(2*Math.tan(.5*g.fovY)*g.aspect)}_cameraForBoundsOnGlobe(g,C,L,$,G,K){const te=g.clone(),de=this._extendCameraOptions(K);te.bearing=$,te.pitch=G;const xe=o.aU.convert(C),_e=o.aU.convert(L),Oe=.5*(xe.lat+_e.lat),De=.5*(xe.lng+_e.lng),qe=o.eT(Oe,De),st=o.ay([],qe),Xe=o.ay([],o.bh([],st,[0,1,0])),pt=o.bh([],Xe,st),mt=[Xe[0],Xe[1],Xe[2],0,pt[0],pt[1],pt[2],0,st[0],st[1],st[2],0,0,0,0,1],kt=[qe,o.eT(xe.lat,xe.lng),o.eT(_e.lat,xe.lng),o.eT(_e.lat,_e.lng),o.eT(xe.lat,_e.lng),o.eT(Oe,xe.lng),o.eT(Oe,_e.lng),o.eT(xe.lat,De),o.eT(_e.lat,De)];let Et=o.cU.fromPoints(kt.map(Us=>[o.bi(Xe,Us),o.bi(pt,Us),o.bi(st,Us)]));const xt=o.ah([],Et.center,mt);o.eU(xt)===0&&o.eV(xt,0,0,1),o.ay(xt,xt),o.bJ(xt,xt,o.aF),te.center=o.eW(xt);const es=te.getWorldToCameraMatrix(),Ot=o.b7(new Float64Array(16),es);Et=o.cU.applyTransform(Et,o.aD([],es,mt));const Qt=this._extendAABB(Et,te,de,$);if(!Qt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");Et=Qt,o.ah(xt,xt,es);const At=.5*(Et.max[2]-Et.min[2]),Dt=this._minimumAABBFrustumDistance(te,Et),Ht=o.bJ([],[0,0,1],At),gs=o.cT(Ht,xt,Ht),ss=Dt+(te.pitch===0?0:o.bf(xt,gs)),Bs=te.globeCenterInViewSpace,Ps=o.ax([],xt,[Bs[0],Bs[1],Bs[2]]);o.ay(Ps,Ps),o.bJ(Ps,Ps,ss);const rn=o.cT([],xt,Ps);o.ah(rn,rn,Ot);const hn=o.eD/o.aF,Ns=o.ai(rn),ds=o.bU(Math.max(Ns*hn-o.eD,Number.EPSILON),0),Fs=Math.min(te.zoomFromMercatorZAdjusted(ds),de.maxZoom);return Fs>.5*(o.cJ+o.cv)?(te.setProjection({name:"mercator"}),te.zoom=Fs,this._cameraForBounds(te,C,L,$,G,K)):{center:te.center,zoom:Fs,bearing:$,pitch:G}}_extendAABB(g,C,L,$){const G=.5*((L.padding.left||0)+(L.padding.right||0)),K=.5*((L.padding.top||0)+(L.padding.bottom||0)),te=K,de=G,xe=G,_e=K,Oe=C.width-(de+xe),De=C.height-(te+_e),qe=o.ax([],g.max,g.min),st=Math.min(Oe/qe[0],De/qe[1]),Xe=Math.min(C.scaleZoom(C.scale*st),L.maxZoom);if(isNaN(Xe))return null;const pt=C.scale/C.zoomScale(Xe),mt=new o.cU([g.min[0]-de*pt,g.min[1]-_e*pt,g.min[2]],[g.max[0]+xe*pt,g.max[1]+te*pt,g.max[2]]),kt=(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($));return mt.center[0]-=kt.x*pt,mt.center[1]+=kt.y*pt,mt}queryTerrainElevation(g,C){const L=this.transform.elevation;return L?(C=Object.assign({},{exaggerated:!0},C),L.getAtPoint(o.ag.fromLngLat(g),null,C.exaggerated)):null}_cameraForBounds(g,C,L,$,G,K){if(g.projection.name==="globe")return this._cameraForBoundsOnGlobe(g,C,L,$,G,K);const te=g.clone(),de=this._extendCameraOptions(K);te.bearing=$,te.pitch=G;const xe=o.aU.convert(C),_e=o.aU.convert(L),Oe=new o.aU(xe.lng,_e.lat),De=new o.aU(_e.lng,xe.lat),qe=te.project(xe),st=te.project(_e),Xe=this.queryTerrainElevation(xe),pt=this.queryTerrainElevation(_e),mt=this.queryTerrainElevation(Oe),kt=this.queryTerrainElevation(De),Et=[[qe.x,qe.y,Math.min(Xe||0,pt||0,mt||0,kt||0)],[st.x,st.y,Math.max(Xe||0,pt||0,mt||0,kt||0)]];let xt=o.cU.fromPoints(Et);const es=te.getWorldToCameraMatrix(),Ot=o.b7(new Float64Array(16),es);xt=o.cU.applyTransform(xt,es);const Qt=this._extendAABB(xt,te,de,$);if(!Qt)return void o.w("Map cannot fit within canvas with the given bounds, padding, and/or offset.");xt=Qt;const At=.5*o.ax([],xt.max,xt.min)[2],Dt=this._minimumAABBFrustumDistance(te,xt),Ht=[0,0,1,0];o.aE(Ht,Ht,es),o.eX(Ht,Ht);const gs=o.bJ([],Ht,Dt+At),ss=o.cT([],xt.center,gs);o.ah(xt.center,xt.center,Ot),o.ah(ss,ss,Ot);const Bs=te.unproject(new o.P(xt.center[0],xt.center[1])),Ps=o.eY(te.projection,Bs),rn=Math.pow(2,Ps),hn=Math.min(te._zoomFromMercatorZ(ss[2]*te.pixelsPerMeter*rn/te.worldSize),de.maxZoom);return te.mercatorFromTransition&&hn<.5*(o.cJ+o.cv)?(te.setProjection({name:"globe"}),te.zoom=hn,this._cameraForBounds(te,C,L,$,G,K)):{center:Bs,zoom:hn,bearing:$,pitch:G}}fitBounds(g,C,L){const $=this.cameraForBounds(g,C);return this._fitInternal($,C,L)}fitScreenCoordinates(g,C,L,$,G){const K=o.P.convert(g),te=o.P.convert(C),de=new o.P(Math.min(K.x,te.x),Math.min(K.y,te.y)),xe=new o.P(Math.max(K.x,te.x),Math.max(K.y,te.y));if(this.transform.projection.name==="mercator"&&this.transform.anyCornerOffEdge(K,te))return this;const _e=this.transform.pointLocation3D(de),Oe=this.transform.pointLocation3D(xe),De=this.transform.pointLocation3D(new o.P(de.x,xe.y)),qe=this.transform.pointLocation3D(new o.P(xe.x,de.y)),st=[Math.min(_e.lng,Oe.lng,De.lng,qe.lng),Math.min(_e.lat,Oe.lat,De.lat,qe.lat)],Xe=[Math.max(_e.lng,Oe.lng,De.lng,qe.lng),Math.max(_e.lat,Oe.lat,De.lat,qe.lat)],pt=$&&$.pitch?$.pitch:this.getPitch(),mt=this._cameraForBounds(this.transform,st,Xe,L,pt,$);return this._fitInternal(mt,$,G)}_fitInternal(g,C,L){return g?(C=Object.assign(g,C)).linear?this.easeTo(C,L):this.flyTo(C,L):this}jumpTo(g,C){this.stop();const L=g.preloadOnly?this.transform.clone():this.transform;let $=!1,G=!1,K=!1;"zoom"in g&&L.zoom!==+g.zoom&&($=!0,L.zoom=+g.zoom),g.center!==void 0&&(L.center=o.aU.convert(g.center)),"bearing"in g&&L.bearing!==+g.bearing&&(G=!0,L.bearing=+g.bearing),"pitch"in g&&L.pitch!==+g.pitch&&(K=!0,L.pitch=+g.pitch);const te=typeof g.padding=="number"?this._extendPadding(g.padding):g.padding;if(g.padding!=null&&!L.isPaddingEqual(te))if(g.retainPadding===!1){const de=L.clone();de.padding=te,L.setLocationAtPoint(L.center,de.centerPoint)}else L.padding=te;return g.preloadOnly?(this._preloadTiles(L),this):(this.fire(new o.C("movestart",C)).fire(new o.C("move",C)),$&&this.fire(new o.C("zoomstart",C)).fire(new o.C("zoom",C)).fire(new o.C("zoomend",C)),G&&this.fire(new o.C("rotatestart",C)).fire(new o.C("rotate",C)).fire(new o.C("rotateend",C)),K&&this.fire(new o.C("pitchstart",C)).fire(new o.C("pitch",C)).fire(new o.C("pitchend",C)),this.fire(new o.C("moveend",C)))}getFreeCameraOptions(){return this.transform.projection.supportsFreeCamera||o.w(VR),this.transform.getFreeCameraOptions()}setFreeCameraOptions(g,C){const L=this.transform;if(!L.projection.supportsFreeCamera)return o.w(VR),this;this.stop();const $=L.zoom,G=L.pitch,K=L.bearing;L.setFreeCameraOptions(g);const te=$!==L.zoom,de=G!==L.pitch,xe=K!==L.bearing;return this.fire(new o.C("movestart",C)).fire(new o.C("move",C)),te&&this.fire(new o.C("zoomstart",C)).fire(new o.C("zoom",C)).fire(new o.C("zoomend",C)),xe&&this.fire(new o.C("rotatestart",C)).fire(new o.C("rotate",C)).fire(new o.C("rotateend",C)),de&&this.fire(new o.C("pitchstart",C)).fire(new o.C("pitch",C)).fire(new o.C("pitchend",C)),this.fire(new o.C("moveend",C)),this}easeTo(g,C){this._stop(!1,g.easeId),((g=Object.assign({offset:[0,0],duration:500,easing:o.eP},g)).animate===!1||this._prefersReducedMotion(g))&&(g.duration=0);const L=this.transform,$=this.getZoom(),G=this.getBearing(),K=this.getPitch(),te=this.getPadding(),de="zoom"in g?+g.zoom:$,xe="bearing"in g?this._normalizeBearing(g.bearing,G):G,_e="pitch"in g?+g.pitch:K,Oe=this._extendPadding(g.padding),De=o.P.convert(g.offset);let qe,st,Xe;if(L.projection.name==="globe"){const Ht=o.ag.fromLngLat(L.center),gs=De.rotate(-L.angle);Ht.x+=gs.x/L.worldSize,Ht.y+=gs.y/L.worldSize;const ss=Ht.toLngLat(),Bs=o.aU.convert(g.center||ss);this._normalizeCenter(Bs),qe=L.centerPoint.add(gs),st=new o.P(Ht.x,Ht.y).mult(L.worldSize),Xe=new o.P(o.aH(Bs.lng),o.aL(Bs.lat)).mult(L.worldSize).sub(st)}else{qe=L.centerPoint.add(De);const Ht=L.pointLocation(qe),gs=o.aU.convert(g.center||Ht);this._normalizeCenter(gs),st=L.project(Ht),Xe=L.project(gs).sub(st)}const pt=L.zoomScale(de-$);let mt,kt;g.around&&(mt=o.aU.convert(g.around),kt=L.locationPoint(mt));const Et=this._zooming||de!==$,xt=this._rotating||G!==xe,es=this._pitching||_e!==K,Ot=!L.isPaddingEqual(Oe),Qt=g.retainPadding===!1?L.clone():L,At=Ht=>gs=>{if(Et&&(Ht.zoom=o.am($,de,gs)),xt&&(Ht.bearing=o.am(G,xe,gs)),es&&(Ht.pitch=o.am(K,_e,gs)),Ot&&(Qt.interpolatePadding(te,Oe,gs),qe=Qt.centerPoint.add(De)),mt)Ht.setLocationAtPoint(mt,kt);else{const ss=Ht.zoomScale(Ht.zoom-$),Bs=de>$?Math.min(2,pt):Math.max(.5,pt),Ps=Math.pow(Bs,1-gs),rn=Ht.unproject(st.add(Xe.mult(gs*Ps)).mult(ss));Ht.setLocationAtPoint(Ht.renderWorldCopies?rn.wrap():rn,qe)}return g.preloadOnly||this._fireMoveEvents(C),Ht};if(g.preloadOnly){const Ht=this._emulate(At,g.duration,L);return this._preloadTiles(Ht),this}const Dt={moving:this._moving,zooming:this._zooming,rotating:this._rotating,pitching:this._pitching};return this._zooming=Et,this._rotating=xt,this._pitching=es,this._padding=Ot,this._easeId=g.easeId,this._prepareEase(C,g.noMoveStart,Dt),this._ease(At(L),Ht=>{L.cameraElevationReference==="sea"&&L.recenterOnTerrain(),this._afterEase(C,Ht)},g),this}_prepareEase(g,C,L={}){this._moving=!0,this.transform.cameraElevationReference="sea",this.transform._orthographicProjectionAtLowPitch&&this.transform.pitch===0&&this.transform.projection.name!=="globe"&&(this.transform.cameraElevationReference="ground"),C||L.moving||this.fire(new o.C("movestart",g)),this._zooming&&!L.zooming&&this.fire(new o.C("zoomstart",g)),this._rotating&&!L.rotating&&this.fire(new o.C("rotatestart",g)),this._pitching&&!L.pitching&&this.fire(new o.C("pitchstart",g))}_fireMoveEvents(g){this.fire(new o.C("move",g)),this._zooming&&this.fire(new o.C("zoom",g)),this._rotating&&this.fire(new o.C("rotate",g)),this._pitching&&this.fire(new o.C("pitch",g))}_afterEase(g,C){if(this._easeId&&C&&this._easeId===C)return;this._easeId=void 0,this.transform.cameraElevationReference="ground";const L=this._zooming,$=this._rotating,G=this._pitching;this._moving=!1,this._zooming=!1,this._rotating=!1,this._pitching=!1,this._padding=!1,L&&this.fire(new o.C("zoomend",g)),$&&this.fire(new o.C("rotateend",g)),G&&this.fire(new o.C("pitchend",g)),this.fire(new o.C("moveend",g))}flyTo(g,C){if(this._prefersReducedMotion(g)){const Us=o.aJ(g,["center","zoom","bearing","pitch","around","padding","retainPadding"]);return this.jumpTo(Us,C)}this.stop(),g=Object.assign({offset:[0,0],speed:1.2,curve:1.42,easing:o.eP},g);const L=this.transform,$=this.getZoom(),G=this.getBearing(),K=this.getPitch(),te=this.getPadding(),de="zoom"in g?o.aC(+g.zoom,L.minZoom,L.maxZoom):$,xe="bearing"in g?this._normalizeBearing(g.bearing,G):G,_e="pitch"in g?+g.pitch:K,Oe=this._extendPadding(g.padding),De=L.zoomScale(de-$),qe=o.P.convert(g.offset);let st=L.centerPoint.add(qe);const Xe=L.pointLocation(st),pt=o.aU.convert(g.center||Xe);this._normalizeCenter(pt);const mt=L.project(Xe),kt=L.project(pt).sub(mt);let Et=g.curve;const xt=Math.max(L.width,L.height),es=xt/De,Ot=kt.mag();if("minZoom"in g){const Us=o.aC(Math.min(g.minZoom,$,de),L.minZoom,L.maxZoom),Ys=xt/L.zoomScale(Us-$);Et=Math.sqrt(Ys/Ot*2)}const Qt=Et*Et;function At(Us){const Ys=(es*es-xt*xt+(Us?-1:1)*Qt*Qt*Ot*Ot)/(2*(Us?es:xt)*Qt*Ot);return Math.log(Math.sqrt(Ys*Ys+1)-Ys)}function Dt(Us){return(Math.exp(Us)-Math.exp(-Us))/2}function Ht(Us){return(Math.exp(Us)+Math.exp(-Us))/2}const gs=At(0);let ss=function(Us){return Ht(gs)/Ht(gs+Et*Us)},Bs=function(Us){return xt*((Ht(gs)*(Dt(Ys=gs+Et*Us)/Ht(Ys))-Dt(gs))/Qt)/Ot;var Ys},Ps=(At(1)-gs)/Et;if(Math.abs(Ot)<1e-6||!isFinite(Ps)){if(Math.abs(xt-es)<1e-6)return this.easeTo(g,C);const Us=esg.maxDuration&&(g.duration=0);const rn=G!==xe,hn=_e!==K,Ns=!L.isPaddingEqual(Oe),ds=g.retainPadding===!1?L.clone():L,Fs=Us=>Ys=>{const Dn=Ys*Ps,kn=1/ss(Dn);Us.zoom=Ys===1?de:$+Us.scaleZoom(kn),rn&&(Us.bearing=o.am(G,xe,Ys)),hn&&(Us.pitch=o.am(K,_e,Ys)),Ns&&(ds.interpolatePadding(te,Oe,Ys),st=ds.centerPoint.add(qe));const Sn=Ys===1?pt:Us.unproject(mt.add(kt.mult(Bs(Dn))).mult(kn));return Us.setLocationAtPoint(Us.renderWorldCopies?Sn.wrap():Sn,st),Us._updateCameraOnTerrain(),g.preloadOnly||this._fireMoveEvents(C),Us};if(g.preloadOnly){const Us=this._emulate(Fs,g.duration,L);return this._preloadTiles(Us),this}return this._zooming=!0,this._rotating=rn,this._pitching=hn,this._padding=Ns,this._prepareEase(C,!1),this._ease(Fs(L),()=>this._afterEase(C),g),this}isEasing(){return!!this._easeFrameId}stop(){return this._stop()}_requestRenderFrame(g){}_cancelRenderFrame(g){}_stop(g,C){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,C)}if(!g){const L=this.handlers;L&&L.stop(!1)}return this}_ease(g,C,L){L.animate===!1||L.duration===0?(g(1),C()):(this._easeStart=o.o.now(),this._easeOptions=L,this._onEaseFrame=g,this._onEaseEnd=C,this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback))}_renderFrameCallback(){const g=Math.min((o.o.now()-this._easeStart)/this._easeOptions.duration,1),C=this._onEaseFrame;C&&C(this._easeOptions.easing(g)),g<1?this._easeFrameId=this._requestRenderFrame(this._renderFrameCallback):this.stop()}_normalizeBearing(g,C){g=o.bs(g,-180,180);const L=Math.abs(g-C);return Math.abs(g-360-C)180?-360:L<-180?360:0}_prefersReducedMotion(g){return this._respectPrefersReducedMotion&&o.o.prefersReducedMotion&&!(g&&g.essential)}_emulate(g,C,L){const $=Math.ceil(15*C/1e3),G=[],K=g(L.clone());for(let te=0;te<=$;te++){const de=K(te/$);G.push(de.clone())}return G}_preloadTiles(g,C){}}class HR{constructor(g={}){this.options=g,o.aZ(["_toggleAttribution","_updateEditLink","_updateData","_updateCompact"],this)}getDefaultPosition(){return"bottom-right"}onAdd(g){const C=this.options&&this.options.compact,L=g._getUIString("AttributionControl.ToggleAttribution");this._map=g,this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-attrib"),this._compactButton=_("button","mapboxgl-ctrl-attrib-button",this._container),this._compactButton.type="button",this._compactButton.addEventListener("click",this._toggleAttribution),this._compactButton.setAttribute("aria-label",L);const $=_("span","mapboxgl-ctrl-icon",this._compactButton);return $.setAttribute("aria-hidden","true"),$.setAttribute("title",L),this._innerContainer=_("div","mapboxgl-ctrl-attrib-inner",this._container),C&&this._container.classList.add("mapboxgl-compact"),this._updateAttributions(),this._updateEditLink(),this._map.on("styledata",this._updateData),this._map.on("sourcedata",this._updateData),this._map.on("moveend",this._updateEditLink),C===void 0&&(this._map.on("resize",this._updateCompact),this._updateCompact()),this._container}onRemove(){this._container.remove(),this._map.off("styledata",this._updateData),this._map.off("sourcedata",this._updateData),this._map.off("moveend",this._updateEditLink),this._map.off("resize",this._updateCompact),this._map=void 0,this._attribHTML=void 0}_toggleAttribution(){this._container.classList.contains("mapboxgl-compact-show")?(this._container.classList.remove("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","false")):(this._container.classList.add("mapboxgl-compact-show"),this._compactButton.setAttribute("aria-expanded","true"))}_updateEditLink(){let g=this._editLink;g||(g=this._editLink=this._container.querySelector(".mapbox-improve-map"));const C=[{key:"owner",value:this.styleOwner},{key:"id",value:this.styleId},{key:"access_token",value:this._map._requestManager._customAccessToken||o.g.ACCESS_TOKEN}];if(g){const L=C.reduce(($,G,K)=>(G.value&&($+=`${G.key}=${G.value}${K$.length-G.length),g=g.filter(($,G)=>{for(let K=G+1;K=0)return!1;return!0}),this.options.customAttribution&&(Array.isArray(this.options.customAttribution)?g=[...this.options.customAttribution,...g]:g.unshift(this.options.customAttribution));const L=g.map($=>function(G){const K=new DOMParser().parseFromString(G,"text/html");return Array.from(K.body.querySelectorAll("*")).reverse().forEach(te=>{const de=te.textContent||"";if(te.tagName!=="A")return void te.replaceWith(...te.childNodes);const xe=te.getAttribute("href");if(!xe||!/^(https?:|mailto:)/i.test(xe))return void te.replaceWith(K.createTextNode(de));const _e=K.createElement("a");_e.href=xe,_e.textContent=de,_e.rel="noopener nofollow";const Oe=te.getAttribute("class");Oe&&(_e.className=Oe),te.replaceWith(_e)}),K.body.innerHTML}($)).join(" | ");L!==this._attribHTML&&(this._attribHTML=L,g.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 GR{constructor(){o.aZ(["_updateLogo","_updateCompact"],this)}onAdd(g){this._map=g,this._container=_("div","mapboxgl-ctrl");const C=_("a","mapboxgl-ctrl-logo");return C.target="_blank",C.rel="noopener nofollow",C.href="https://www.mapbox.com/",C.setAttribute("aria-label",this._map._getUIString("LogoControl.Title")),C.setAttribute("rel","noopener nofollow"),this._container.appendChild(C),this._container.style.display="none",this._map.on("sourcedata",this._updateLogo),this._updateLogo(),this._map.on("resize",this._updateCompact),this._updateCompact(),this._container}onRemove(){this._container.remove(),this._map.off("sourcedata",this._updateLogo),this._map.off("resize",this._updateCompact)}getDefaultPosition(){return"bottom-left"}_updateLogo(g){g&&g.sourceDataType!=="metadata"||(this._container.style.display=this._logoRequired()?"block":"none")}_logoRequired(){if(!this._map.style)return!0;const g=this._map.style._sourceCaches;if(Object.entries(g).length===0)return!0;for(const C in g){const L=g[C].getSource();if(L.hasOwnProperty("mapbox_logo")&&!L.mapbox_logo)return!1}return!0}_updateCompact(){const g=this._container.children;if(g.length){const C=g[0];this._map.getCanvasContainer().offsetWidth<250?C.classList.add("mapboxgl-compact"):C.classList.remove("mapboxgl-compact")}}}class eq{constructor(){this._queue=[],this._id=0,this._cleared=!1,this._currentlyRunning=!1}add(g){const C=++this._id;return this._queue.push({callback:g,id:C,cancelled:!1}),C}remove(g){const C=this._currentlyRunning,L=C?this._queue.concat(C):this._queue;for(const $ of L)if($.id===g)return void($.cancelled=!0)}run(g=0){const C=this._currentlyRunning=this._queue;this._queue=[];for(const L of C)if(!L.cancelled&&(L.callback(g),this._cleared))break;this._cleared=!1,this._currentlyRunning=!1}clear(){this._currentlyRunning&&(this._cleared=!0),this._queue=[]}}class rbe{constructor(g){this.jumpTo(g)}getValue(g){if(g<=this._startTime)return this._start;if(g>=this._endTime)return this._end;const C=o.dn((g-this._startTime)/(this._endTime-this._startTime));return this._start*(1-C)+this._end*C}isEasing(g){return g>=this._startTime&&g<=this._endTime}jumpTo(g){this._startTime=-1/0,this._endTime=-1/0,this._start=g,this._end=g}easeTo(g,C,L){this._start=this.getValue(C),this._end=g,this._startTime=C,this._endTime=C+L}}const abe={"AttributionControl.ToggleAttribution":"Toggle attribution","FullscreenControl.Enter":"Enter fullscreen","FullscreenControl.Exit":"Exit fullscreen","GeolocateControl.FindMyLocation":"Find my location","GeolocateControl.LocationNotAvailable":"Location not available","LogoControl.Title":"Mapbox homepage","Map.Title":"Map","NavigationControl.ResetBearing":"Reset bearing to north","NavigationControl.ZoomIn":"Zoom in","NavigationControl.ZoomOut":"Zoom out","ScrollZoomBlocker.CtrlMessage":"Use ctrl + scroll to zoom the map","ScrollZoomBlocker.CmdMessage":"Use ⌘ + scroll to zoom the map","TouchPanBlocker.Message":"Use two fingers to move the map"};class Po extends o.C{constructor(g,C,L,$){const{point:G,lngLat:K,originalEvent:te,target:de}=g;super(g.type,{point:G,lngLat:K,originalEvent:te,target:de}),this.preventDefault=()=>{g.preventDefault()},this.id=C,this.interaction=L,this.feature=$}}class M6{constructor(g){this.map=g,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(g,C){if(this.typeById.has(g))throw new Error(`Interaction id "${g}" already exists.`);const L=C.filter;let $=C.type;L&&this.filters.set(g,o.dg(L)),$==="mouseover"&&($="mouseenter"),$==="mouseout"&&($="mouseleave");const G=this.interactionsByType.get($)||new Map;$==="mouseenter"||$==="mouseleave"?(this.delegatedInteractions.size===0&&(this.map.on("mousemove",this.handleMove),this.map.on("mouseout",this.handleOut)),this.delegatedInteractions.set(g,C)):G.size===0&&this.map.on($,this.handleType),G.size===0&&this.interactionsByType.set($,G),G.set(g,C),this.typeById.set(g,$)}get(g){const C=this.typeById.get(g);if(!C)return;const L=this.interactionsByType.get(C);return L?L.get(g):void 0}remove(g){const C=this.typeById.get(g);if(!C)return;this.typeById.delete(g),this.filters.delete(g);const L=this.interactionsByType.get(C);L&&(L.delete(g),C==="mouseenter"||C==="mouseleave"?(this.delegatedInteractions.delete(g),this.delegatedInteractions.size===0&&(this.map.off("mousemove",this.handleMove),this.map.off("mouseout",this.handleOut))):L.size===0&&this.map.off(C,this.handleType))}queryTargets(g,C){const L=[];for(const[$,G]of C)G.target&&L.push({targetId:$,target:G.target,filter:this.filters.get($)});return this.map.style.queryRenderedTargets(g,L,this.map.transform)}handleMove(g){this.prevHoveredFeatures=this.hoveredFeatures,this.hoveredFeatures=new Map;const C=this.queryTargets(g.point,Array.from(this.delegatedInteractions).reverse());C.length&&(g.type="mouseenter",this.handleType(g,C));const L=new Map;for(const[$,{feature:G}]of this.prevHoveredFeatures)this.hoveredFeatures.has($)||L.set(G.id,G);L.size&&(g.type="mouseleave",this.handleType(g,Array.from(L.values())))}handleOut(g){const C=Array.from(this.hoveredFeatures.values()).map(({feature:L})=>L);C.length&&(g.type="mouseleave",this.handleType(g,C)),this.hoveredFeatures.clear()}handleType(g,C){const L=g.type==="mouseenter";if(L&&!this.interactionsByType.has(g.type))return void o.w("mouseenter interaction required for mouseleave to work.");const $=Array.from(this.interactionsByType.get(g.type)).reverse(),G=!!C;C=C||this.queryTargets(g.point,$);let K=!1;const te=new Set;for(const de of C){for(const[xe,_e]of $){if(!_e.target)continue;const Oe=de.variants?de.variants[xe]:null;if(Oe){for(const De of Oe){if(mh(De,de,te,xe))continue;const qe=new o.di(de,De),st=Sf(De,de,xe);G&&qe.id!==void 0&&(qe.state=this.map.getFeatureState(qe));const Xe=L?this.prevHoveredFeatures.get(st):null,pt=new Po(g,xe,_e,qe),mt=Xe?Xe.stop:_e.handler(pt);if(L&&this.hoveredFeatures.set(st,{feature:de,stop:mt}),mt!==!1){K=!0;break}}if(K)break}}if(K)break}if(!K)for(const[de,xe]of $){const{handler:_e,target:Oe}=xe;if(!Oe&&_e(new Po(g,de,xe,null))!==!1)break}}}function ibe(M,g){if(Array.isArray(M)&&Array.isArray(g)){const C=new Set(M),L=new Set(g);return C.size===L.size&&M.every($=>L.has($))}return o.b6(M,g)}const obe={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},lbe={showCompass:!0,showZoom:!0,visualizePitch:!1};class FC{constructor(g,C,L=!1){this._clickTolerance=10,this.element=C,this.mouseRotate=new k6({clickTolerance:g.dragRotate._mouseRotate._clickTolerance}),this.map=g,L&&(this.mousePitch=new PC({clickTolerance:g.dragRotate._mousePitch._clickTolerance})),o.aZ(["mousedown","mousemove","mouseup","touchstart","touchmove","touchend","reset"],this),C.addEventListener("mousedown",this.mousedown),C.addEventListener("touchstart",this.touchstart,{passive:!1}),C.addEventListener("touchmove",this.touchmove),C.addEventListener("touchend",this.touchend),C.addEventListener("touchcancel",this.reset)}down(g,C){this.mouseRotate.mousedown(g,C),this.mousePitch&&this.mousePitch.mousedown(g,C),A()}move(g,C){const L=this.map,$=this.mouseRotate.mousemoveWindow(g,C),G=$&&$.bearingDelta;if(G&&L.setBearing(L.getBearing()+G),this.mousePitch){const K=this.mousePitch.mousemoveWindow(g,C),te=K&&K.pitchDelta;te&&L.setPitch(L.getPitch()+te)}}off(){const g=this.element;g.removeEventListener("mousedown",this.mousedown),g.removeEventListener("touchstart",this.touchstart),g.removeEventListener("touchmove",this.touchmove),g.removeEventListener("touchend",this.touchend),g.removeEventListener("touchcancel",this.reset),this.offTemp()}offTemp(){E(),window.removeEventListener("mousemove",this.mousemove),window.removeEventListener("mouseup",this.mouseup)}mousedown(g){this.down(Object.assign({},g,{button:g.button,type:g.type,ctrlKey:!0,preventDefault:()=>g.preventDefault()}),I(this.element,g)),window.addEventListener("mousemove",this.mousemove),window.addEventListener("mouseup",this.mouseup)}mousemove(g){this.move(g,I(this.element,g))}mouseup(g){this.mouseRotate.mouseupWindow(g),this.mousePitch&&this.mousePitch.mouseupWindow(g),this.offTemp()}touchstart(g){g.targetTouches.length!==1?this.reset():(this._startPos=this._lastPos=F(this.element,g.targetTouches)[0],this.down({type:"mousedown",button:0,ctrlKey:!0,preventDefault:()=>g.preventDefault()},this._startPos))}touchmove(g){g.targetTouches.length!==1?this.reset():(this._lastPos=F(this.element,g.targetTouches)[0],this.move({buttons:1,preventDefault:()=>g.preventDefault()},this._lastPos))}touchend(g){g.targetTouches.length===0&&this._startPos&&this._lastPos&&this._startPos.dist(this._lastPos)C.width||g.y>C.height;C.locationPoint3D(L).distSqr(g)180;){const L=C.locationPoint3D(M);if(L.x>=0&&L.y>=0&&L.x<=C.width&&L.y<=C.height)break;M.lng>C.center.lng?M.lng-=360:M.lng+=360}return M}const zC={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%)"},Nx={rotation:0,rotationAlignment:"auto",pitchAlignment:"auto",occludedOpacity:.2,altitude:0};class vg extends o.E{constructor(g,C){super(),(g instanceof HTMLElement||C)&&(g=Object.assign({element:g},C)),o.aZ(["_update","_onMove","_onUp","_addDragHandler","_onMapClick","_onKeyPress","_clearFadeTimer"],this);const{anchor:L="center",color:$="#3FB1CE",scale:G=1,draggable:K=!1,clickTolerance:te=0,rotation:de=Nx.rotation,rotationAlignment:xe=Nx.rotationAlignment,pitchAlignment:_e=Nx.pitchAlignment,occludedOpacity:Oe=Nx.occludedOpacity,altitude:De=Nx.altitude}=g||{};this._anchor=L,this._color=$,this._scale=G,this._draggable=K,this._clickTolerance=te,this._rotation=de,this._rotationAlignment=xe,this._pitchAlignment=_e,this._occludedOpacity=Oe,this._altitude=De,this._state="inactive",this._isDragging=!1,this._updateMoving=()=>this._update(!0),g&&g.element?(this._element=g.element,this._offset=o.P.convert(g&&g.offset||[0,0])):(this._defaultMarker=!0,this._element=this._createDefaultMarker(),this._offset=o.P.convert(g&&g.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",Xe=>{Xe.preventDefault()}),this._element.addEventListener("mousedown",Xe=>{Xe.preventDefault()});const qe=this._element.classList;for(const Xe in zC)qe.remove(`mapboxgl-marker-anchor-${Xe}`);qe.add(`mapboxgl-marker-anchor-${this._anchor}`);const st=g&&g.className?g.className.trim().split(/\s+/):[];qe.add(...st),this._popup=null}_createDefaultMarker(){const g=_("div"),C=v("svg",{display:"block",height:41*this._scale+"px",width:27*this._scale+"px",viewBox:"0 0 27 41"},g);if(this._altitude===0){const L=v("radialGradient",{id:"shadowGradient"},v("defs",{},C));v("stop",{offset:"10%","stop-opacity":.4},L),v("stop",{offset:"100%","stop-opacity":.05},L),v("ellipse",{cx:13.5,cy:34.8,rx:10.5,ry:5.25,fill:"url(#shadowGradient)"},C)}return v("path",{fill:this._color,d:"M27,13.5C27,19.07 20.25,27 14.75,34.5C14.02,35.5 12.98,35.5 12.25,34.5C6.75,27 0,19.22 0,13.5C0,6.04 6.04,0 13.5,0C20.96,0 27,6.04 27,13.5Z"},C),v("path",{opacity:.25,d:"M13.5,0C6.04,0 0,6.04 0,13.5C0,19.22 6.75,27 12.25,34.5C13,35.52 14.02,35.5 14.75,34.5C20.25,27 27,19.07 27,13.5C27,6.04 20.96,0 13.5,0ZM13.5,1C20.42,1 26,6.58 26,13.5C26,15.9 24.5,19.18 22.22,22.74C19.95,26.3 16.71,30.14 13.94,33.91C13.74,34.18 13.61,34.32 13.5,34.44C13.39,34.32 13.26,34.18 13.06,33.91C10.28,30.13 7.41,26.31 5.02,22.77C2.62,19.23 1,15.95 1,13.5C1,6.58 6.58,1 13.5,1Z"},C),v("circle",{fill:"white",cx:13.5,cy:13.5,r:5.5},C),g}addTo(g){return g===this._map||(this.remove(),this._map=g,g.getCanvasContainer().appendChild(this._element),g.on("move",this._updateMoving),g.on("moveend",this._update),g.on("remove",this._clearFadeTimer),g._addMarker(this),this.setDraggable(this._draggable),this._update(),g.on("click",this._onMapClick)),this}remove(){const g=this._map;return g&&(g.off("click",this._onMapClick),g.off("move",this._updateMoving),g.off("moveend",this._update),g.off("mousedown",this._addDragHandler),g.off("touchstart",this._addDragHandler),g.off("mouseup",this._onUp),g.off("touchend",this._onUp),g.off("mousemove",this._onMove),g.off("touchmove",this._onMove),g.off("remove",this._clearFadeTimer),g._removeMarker(this),this._map=void 0),this._clearFadeTimer(),this._element.remove(),this._popup&&this._popup.remove(),this}getLngLat(){return this._lngLat}setLngLat(g){return this._lngLat=o.aU.convert(g),this._pos=null,this._popup&&this._popup.setLngLat(this._lngLat),this._update(!0),this}setAltitude(g){return g===this._altitude||(this._defaultMarker&&(this._altitude===0&&g!==0||this._altitude!==0&&g===0)&&(this._element=this._createDefaultMarker()),this._altitude=g||Nx.altitude,this._update()),this}getAltitude(){return this._altitude}getElement(){return this._element}setPopup(g){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")),g){if(!("offset"in g.options)){const $=Math.sqrt(Math.pow(13.5,2)/2);g.options.offset=this._defaultMarker?{top:[0,0],"top-left":[0,0],"top-right":[0,0],bottom:[0,-38.1],"bottom-left":[$,-1*(38.1-13.5+$)],"bottom-right":[-$,-1*(38.1-13.5+$)],left:[13.5,-1*(38.1-13.5)],right:[-13.5,-1*(38.1-13.5)]}:this._offset}this._popup=g,g._marker=this,g._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(g){const C=g.code,L=g.charCode||g.keyCode;C!=="Space"&&C!=="Enter"&&L!==32&&L!==13||this.togglePopup()}_onMapClick(g){const C=g.originalEvent.target,L=this._element;this._popup&&(C===L||L.contains(C))&&this.togglePopup()}getPopup(){return this._popup}togglePopup(){const g=this._popup;return g?(g.isOpen()?(g.remove(),this._element.setAttribute("aria-expanded","false")):this._map&&(g.addTo(this._map),this._element.setAttribute("aria-expanded","true")),this):this}_behindTerrain(){const g=this._map,C=this._pos;if(!g||!C)return!1;const L=g.unproject(C,this._altitude),$=g.getFreeCameraOptions();if(!$.position)return!1;const G=$.position.toLngLat();return G.distanceTo(L)<.9*G.distanceTo(this._lngLat)}_evaluateOpacity(){const g=this._map;if(!g)return;const C=this._pos;if(!C||C.x<0||C.x>g.transform.width||C.y<0||C.y>g.transform.height)return void this._clearFadeTimer();const L=g.unproject(C,this._altitude);let $;g._showingGlobe()&&o.e$(g.transform,this._lngLat)?$=0:($=1-g._queryFogOpacity(L),g.transform._terrainEnabled()&&g.getTerrain()&&this._behindTerrain()&&($*=this._occludedOpacity)),this._element.style.opacity=`${$}`,this._element.style.pointerEvents=$>0?"auto":"none",this._popup&&this._popup._setOpacity($),this._fadeTimer=null}_clearFadeTimer(){this._fadeTimer&&(clearTimeout(this._fadeTimer),this._fadeTimer=null)}_updateDOM(){const g=this._pos;if(!g||!this._map)return;const C=this._offset.mult(this._scale);this._element.style.transform=` translate(${g.x}px,${g.y}px) ${zC[this._anchor]} ${this._calculateXYTransform()} ${this._calculateZTransform()} translate(${C.x}px,${C.y}px) `}_calculateXYTransform(){const g=this._pos,C=this._map,L=this.getPitchAlignment();if(!C||!g||L!=="map")return"";if(!C._showingGlobe()){const de=C.getPitch();return de?`rotateX(${de}deg)`:""}const $=o.cH(o.f0(C.transform,this._lngLat)),G=g.sub(o.f1(C.transform)),K=Math.abs(G.x)+Math.abs(G.y);if(K===0)return"";const te=$/K;return`rotateX(${-G.y*te}deg) rotateY(${G.x*te}deg)`}_calculateZTransform(){const g=this._pos,C=this._map;if(!C||!g)return"";let L=0;const $=this.getRotationAlignment();if($==="map")if(C._showingGlobe()){const G=C.project(new o.aU(this._lngLat.lng,this._lngLat.lat+.001),this._altitude),K=C.project(new o.aU(this._lngLat.lng,this._lngLat.lat-.001),this._altitude).sub(G);L=o.cH(Math.atan2(K.y,K.x))-90}else L=-C.getBearing();else if($==="horizon"){const G=o.aj(4,6,C.getZoom()),K=o.f1(C.transform);K.y+=G*C.transform.height;const te=g.sub(K),de=o.cH(Math.atan2(te.y,te.x));L=(de>90?de-270:de+90)*(1-G)}return L+=this._rotation,L?`rotateZ(${L}deg)`:""}_update(g){cancelAnimationFrame(this._updateFrameId);const C=this._map;C&&(C.transform.renderWorldCopies&&(this._lngLat=WR(this._lngLat,this._pos,C.transform)),this._pos=C.project(this._lngLat,this._altitude),g===!0?this._updateFrameId=requestAnimationFrame(()=>{this._element&&this._pos&&this._anchor&&(this._pos=this._pos.round(),this._updateDOM())}):this._pos=this._pos.round(),C._requestDomTask(()=>{this._map&&(this._element&&this._pos&&this._anchor&&this._updateDOM(),(C._showingGlobe()||C.getTerrain()||C.getFog())&&!this._fadeTimer&&(this._fadeTimer=window.setTimeout(this._evaluateOpacity.bind(this),60)))}))}getOffset(){return this._offset}setOffset(g){return this._offset=o.P.convert(g),this._update(),this}addClassName(g){return this._element.classList.add(g),this}removeClassName(g){return this._element.classList.remove(g),this}toggleClassName(g){return this._element.classList.toggle(g)}_onMove(g){const C=this._map;if(!C)return;const L=this._pointerdownPos,$=this._positionDelta;if(L&&$){if(!this._isDragging){const G=this._clickTolerance||C._clickTolerance;if(g.point.dist(L)M.maxZoom)throw new Error("maxZoom must be greater than or equal to minZoom");if(M.minPitch!=null&&M.maxPitch!=null&&M.minPitch>M.maxPitch)throw new Error("maxPitch must be greater than or equal to minPitch");if(M.minPitch!=null&&M.minPitch<0)throw new Error("minPitch must be greater than or equal to 0");if(M.maxPitch!=null&&M.maxPitch>85)throw new Error("maxPitch must be less than or equal to 85");M.antialias&&o.eZ(window)&&(M.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 sp(M.minZoom,M.maxZoom,M.minPitch,M.maxPitch,M.renderWorldCopies,null,null),M),this._repaint=!!M.repaint,this._interactive=M.interactive,this._minTileCacheSize=M.minTileCacheSize,this._maxTileCacheSize=M.maxTileCacheSize,this._failIfMajorPerformanceCaveat=M.failIfMajorPerformanceCaveat,this._preserveDrawingBuffer=M.preserveDrawingBuffer,this._antialias=M.antialias,this._trackResize=M.trackResize,this._bearingSnap=M.bearingSnap,this._refreshExpiredTiles=M.refreshExpiredTiles,this._fadeDuration=M.fadeDuration,this._isInitialLoad=!0,this._crossSourceCollisions=M.crossSourceCollisions,this._collectResourceTiming=M.collectResourceTiming,this._language=this._parseLanguage(M.language),this._worldview=M.worldview,this._renderTaskQueue=new eq,this._domRenderTaskQueue=new eq,this._controls=[],this._markers=[],this._popups=[],this._mapId=o.r(),this._locale=Object.assign({},abe,M.locale),this._clickTolerance=M.clickTolerance,this._cooperativeGestures=M.cooperativeGestures,this._performanceMetricsCollection=M.performanceMetricsCollection,this._tessellationStep=M.tessellationStep,this._containerWidth=0,this._containerHeight=0,this._showParseStatus=!0,this._precompilePrograms=M.precompilePrograms,this._averageElevationLastSampledAt=-1/0,this._averageElevationExaggeration=0,this._averageElevation=new rbe(0),this._interactionRange=[1/0,-1/0],this._visibilityHidden=0,this._useExplicitProjection=!1,this._frameId=0,this._scaleFactor=M.scaleFactor,this._requestManager=new W(M.transformRequest,M.accessToken,M.testMode);const C=ce(M.accessToken||o.g.ACCESS_TOKEN);if(C&&"atlas"in C&&typeof C.atlas=="number"&&(this._tokenExpiration=C.atlas),this._silenceAuthErrors=!!M.testMode,this._contextCreateOptions=M.contextCreateOptions?Object.assign({},M.contextCreateOptions):{},typeof M.container=="string"){const L=document.getElementById(M.container);if(!L)throw new Error(`Container '${M.container.toString()}' not found.`);this._container=L}else{if(!(M.container instanceof HTMLElement))throw new Error("Invalid type: 'container' must be a String or HTMLElement.");this._container=M.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."),M.maxBounds&&this.setMaxBounds(M.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 XU(this,M),this._localFontFamily=M.localFontFamily,this._localIdeographFontFamily=M.localIdeographFontFamily,this._useServerFontComposition=M.useServerFontComposition,(M.style||!M.testMode)&&this.setStyle(M.style||o.g.DEFAULT_STYLE,{config:M.config,localFontFamily:this._localFontFamily,localIdeographFontFamily:this._localIdeographFontFamily,useServerFontComposition:this._useServerFontComposition}),M.projection&&this.setProjection(M.projection),M.hash&&(this._hash=new yc(typeof M.hash=="string"&&M.hash||void 0).addTo(this)),!this._hash||!this._hash._onHashChange()){g.center==null&&g.zoom==null||(this.transform._unmodified=!1),this.jumpTo({center:M.center,zoom:M.zoom,bearing:M.bearing,pitch:M.pitch});const L=M.bounds;L&&(this.resize(),this.fitBounds(L,Object.assign({},M.fitBoundsOptions,{duration:0})))}this.resize(),M.attributionControl&&this.addControl(new HR({customAttribution:M.customAttribution})),this._logoControl=new GR,this.addControl(this._logoControl,M.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 M6(this)}_getMapId(){return this._mapId}addControl(M,g){if(g===void 0&&(g=M.getDefaultPosition?M.getDefaultPosition():"top-right"),!M||!M.onAdd)return this.fire(new o.B(new Error("Invalid argument to map.addControl(). Argument must be a control with onAdd and onRemove methods.")));const C=M.onAdd(this);this._controls.push(M);const L=this._controlPositions[g];return g.indexOf("bottom")!==-1?L.insertBefore(C,L.firstChild):L.appendChild(C),this}removeControl(M){if(!M||!M.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 g=this._controls.indexOf(M);return g>-1&&this._controls.splice(g,1),M.onRemove(this),this}hasControl(M){return this._controls.indexOf(M)>-1}getContainer(){return this._container}getCanvasContainer(){return this._canvasContainer}getCanvas(){return this._canvas}resize(M){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 g=!this._moving;return g&&this.fire(new o.C("movestart",M)).fire(new o.C("move",M)),this.fire(new o.C("resize",M)),g&&this.fire(new o.C("moveend",M)),this}getBounds(){return this.transform.getBounds()}getMaxBounds(){return this.transform.getMaxBounds()||null}setMaxBounds(M){return this.transform.setMaxBounds(o.aK.convert(M)),this._update()}setMinZoom(M){if((M=M??-2)>=-2&&M<=this.transform.maxZoom)return this.transform.minZoom=M,this._update(),this.getZoom()=this.transform.minZoom)return this.transform.maxZoom=M,this._update(),this.getZoom()>M?this.setZoom(M):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(M){if((M=M??0)<0)throw new Error("minPitch must be greater than or equal to 0");if(M>=0&&M<=this.transform.maxPitch)return this.transform.minPitch=M,this._update(),this.getPitch()85)throw new Error("maxPitch must be less than or equal to 85");if(M>=this.transform.minPitch)return this.transform.maxPitch=M,this._update(),this.getPitch()>M?this.setPitch(M):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(M){return this._scaleFactor=M,this.painter.scaleFactor=M,this.style&&this.style._setLabelPlacementStale(),this.style._updateFilteredLayers(g=>g.type==="symbol"),this._update(!0),this}getRenderWorldCopies(){return this.transform.renderWorldCopies}setRenderWorldCopies(M){return this.transform.renderWorldCopies=M,this.transform.renderWorldCopies||this._forceMarkerAndPopupUpdate(!0),this._update()}getLanguage(){return this._language}_parseLanguage(M){return M==="auto"?navigator.language:Array.isArray(M)?M.length===0?void 0:M.map(g=>g==="auto"?navigator.language:g):M}setLanguage(M){const g=this._parseLanguage(M);if(!this.style||g===this._language)return this;this._language=g,this.style.reloadSources();for(const C of this._controls)C._setLanguage&&C._setLanguage(this._language);return this}getWorldview(){return this._worldview}setWorldview(M){return this.style&&M!==this._worldview?(this._worldview=M,this._styleDirty=!0,this.style.setWorldview(M),this):this}getProjection(){return this.transform.mercatorFromTransition?{name:"globe",center:[0,0]}:this.transform.getProjection()}_showingGlobe(){return this.transform.projection.name==="globe"}setProjection(M){return this._lazyInitEmptyStyle(),M?typeof M=="string"&&(M={name:M}):M=null,this._useExplicitProjection=!!M,this._prioritizeAndUpdateProjection(M,this.style.projection)}_updateProjectionTransition(){if(this.getProjection().name!=="globe")return;const M=this.transform,g=M.projection.name;let C;g==="globe"&&M.zoom>=o.cv?(M.setMercatorFromTransition(),C=!0):g==="mercator"&&M.zoom=o.cv?this.transform.setMercatorFromTransition():this.transform.setProjection(M),this.style.applyProjectionUpdate();const L=this.transform.getProjection().name==="mercator"&&C!==this.transform.mercatorFromTransition;return(g||L)&&(this.painter.clearBackgroundTiles(),this.style.clearSources(),this._update(!0),this._forceMarkerAndPopupUpdate(!0)),this}project(M,g){return this.transform.locationPoint3D(o.aU.convert(M),g)}unproject(M,g){return this.transform.pointLocation3D(o.P.convert(M),g)}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(M,g,C){const L=$=>{let G=[];if(Array.isArray(g)){const K=g.filter(te=>this.getLayer(te));G=K.length?this.queryRenderedFeatures($,{layers:K}):[]}else G=this.queryRenderedFeatures($,{target:g});return G};if(M==="mouseenter"||M==="mouseover"){let $=!1;return{listener:C,targets:g,delegates:{mousemove:K=>{const te=L(K.point);te.length?$||($=!0,C.call(this,new ni(M,this,K.originalEvent,{features:te}))):$=!1},mouseout:()=>{$=!1}}}}if(M==="mouseleave"||M==="mouseout"){let $=!1;return{listener:C,targets:g,delegates:{mousemove:te=>{L(te.point).length?$=!0:$&&($=!1,C.call(this,new ni(M,this,te.originalEvent)))},mouseout:te=>{$&&($=!1,C.call(this,new ni(M,this,te.originalEvent)))}}}}{const $=G=>{const K=L(G.point);K.length&&(G.features=K,C.call(this,G),delete G.features)};return{listener:C,targets:g,delegates:{[M]:$}}}}on(M,g,C){if(typeof g=="function"||C===void 0)return super.on(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const L=this._createDelegatedListener(M,g,C);this._delegatedListeners=this._delegatedListeners||{},this._delegatedListeners[M]=this._delegatedListeners[M]||[],this._delegatedListeners[M].push(L);for(const $ in L.delegates)this.on($,L.delegates[$]);return this}once(M,g,C){if(typeof g=="function"||C===void 0)return super.once(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const L=this._createDelegatedListener(M,g,C);for(const $ in L.delegates)this.once($,L.delegates[$]);return this}off(M,g,C){if(typeof g=="function"||C===void 0)return super.off(M,g);if(typeof g=="string"&&(g=[g]),!this._areTargetsValid(g))return this;const L=this._delegatedListeners?this._delegatedListeners[M]:void 0;return L&&($=>{for(let G=0;G<$.length;G++){const K=$[G];if(K.listener===C&&ibe(K.targets,g)){for(const te in K.delegates)this.off(te,K.delegates[te]);return $.splice(G,1),this}}})(L),this}queryRenderedFeatures(M,g){if(!this.style)return[];if(M===void 0||M instanceof o.P||Array.isArray(M)||g!==void 0||(g=M,M=void 0),M=M||[[0,0],[this.transform.width,this.transform.height]],!g){const G=this.style.queryRenderedFeatures(M,void 0,this.transform),K=this.style.queryRenderedFeatureset(M,void 0,this.transform);return G.concat(K)}let C=!0;if(g.target&&(C=this._isTargetValid(g.target),C&&!g.layers))return this.style.queryRenderedFeatureset(M,g,this.transform);let L=!0;if(g.layers&&Array.isArray(g.layers)){for(const G of g.layers)if(!this._isValidId(G)){L=!1;break}if(L&&!g.target)return this.style.queryRenderedFeatures(M,g,this.transform)}let $=[];return L&&($=$.concat(this.style.queryRenderedFeatures(M,g,this.transform))),C&&($=$.concat(this.style.queryRenderedFeatureset(M,g,this.transform))),$}querySourceFeatures(M,g){return!M||typeof M=="string"&&!this._isValidId(M)?[]:this.style.querySourceFeatures(M,g)}queryRasterValue(M,g,C){return this._isValidId(M)?this.style.queryRasterValue(M,g,C):Promise.resolve(null)}isPointOnSurface(M){const{name:g}=this.transform.projection;return g!=="globe"&&g!=="mercator"&&o.w(`${g} projection does not support isPointOnSurface, this API may behave unexpectedly.`),this.transform.isPointOnSurface(o.P.convert(M))}addInteraction(M,g){return this._interactions.add(M,g),this}removeInteraction(M){return this._interactions.remove(M),this}getCooperativeGestures(){return this._cooperativeGestures}setCooperativeGestures(M){return this._cooperativeGestures=M,this}setStyle(M,g){return g=Object.assign({},{localIdeographFontFamily:this._localIdeographFontFamily,localFontFamily:this._localFontFamily,useServerFontComposition:this._useServerFontComposition},g),this.style&&M&&g.diff!==!1&&g.localFontFamily===this._localFontFamily&&g.localIdeographFontFamily===this._localIdeographFontFamily&&!g.config?(this.style._diffStyle(M,(C,L)=>{if(C){const $=typeof C=="string"?C:C instanceof Error?C.message:C.error;o.w(`Unable to perform style diff: ${$}. Rebuilding the style from scratch.`),this._updateStyle(M,g)}else L&&this._update(!0)},()=>this._postStyleLoadEvent()),this):(this._localIdeographFontFamily=g.localIdeographFontFamily,this._localFontFamily=g.localFontFamily,this._updateStyle(M,g))}_getUIString(M){const g=this._locale[M];if(g==null)throw new Error(`Missing UI string '${M}'`);return g}_updateStyle(M,g){if(this.style&&(this.style.setEventedParent(null),this.style._remove(),this.style=void 0),M){const C=Object.assign({},g);g&&g.config&&(C.initialConfig=g.config,delete C.config),this.style=new Yc(this,C).load(M),this.style.setEventedParent(this,{style:this.style})}return this._updateTerrain(),this}_lazyInitEmptyStyle(){this.style||(this.style=new Yc(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(M){return M==null?(this.fire(new o.B(new Error("IDs can't be empty."))),!1):!o.db(M)||(this.fire(new o.B(new Error(`IDs can't contain special symbols: "${M}".`))),!1)}_isTargetValid(M){return"featuresetId"in M?this._isValidId("importId"in M?M.importId:M.featuresetId):"layerId"in M&&this._isValidId(M.layerId)}_areTargetsValid(M){if(Array.isArray(M)){for(const g of M)if(!this._isValidId(g))return!1;return!0}return this._isTargetValid(M)}addSource(M,g){return this._isValidId(M)?(this._lazyInitEmptyStyle(),this.style.addSource(M,g),this._update(!0)):this}isSourceLoaded(M){return!!this._isValidId(M)&&!!this.style&&this.style._isSourceCacheLoaded(M)}areTilesLoaded(){return this.style.areTilesLoaded()}addSourceType(M,g,C){this._lazyInitEmptyStyle(),this.style.addSourceType(M,g,C)}removeSource(M){return this._isValidId(M)?(this.style.removeSource(M),this._updateTerrain(),this._update(!0)):this}getSource(M){return this._isValidId(M)?this.style.getOwnSource(M):null}addImage(M,g,{pixelRatio:C=1,sdf:L=!1,stretchX:$,stretchY:G,content:K}={}){this._lazyInitEmptyStyle();const te=o.I.from(M);if(g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap){const{width:de,height:xe,data:_e}=o.o.getImageData(g);this.style.addImage(te,{data:new o.q({width:de,height:xe},_e),pixelRatio:C,stretchX:$,stretchY:G,content:K,sdf:L,version:0,usvg:!1})}else if(g.width===void 0||g.height===void 0)this.fire(new o.B(new Error("Invalid arguments to map.addImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));else{const{width:de,height:xe}=g,_e=g;this.style.addImage(te,{data:new o.q({width:de,height:xe},new Uint8Array(_e.data)),pixelRatio:C,stretchX:$,stretchY:G,content:K,sdf:L,usvg:!1,version:0,userImage:_e}),_e.onAdd&&_e.onAdd(this,M)}}updateImage(M,g){this._lazyInitEmptyStyle();const C=o.I.from(M),L=this.style.getImage(C);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 $=g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap?o.o.getImageData(g):g,{width:G,height:K,data:te}=$;if(G===void 0||K===void 0)return void this.fire(new o.B(new Error("Invalid arguments to map.updateImage(). The second argument must be an `HTMLImageElement`, `ImageData`, `ImageBitmap`, or object with `width`, `height`, and `data` properties with the same format as `ImageData`")));if(G!==(L.usvg?L.icon.usvg_tree.width:L.data.width)||K!==(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 (${G}, ${K}) must be that same as the previous version of the image (${L.data.width}, ${L.data.height})`)));const de=!(g instanceof HTMLImageElement||ImageBitmap&&g instanceof ImageBitmap);let xe=!1;L.usvg?(L.data=new o.q({width:G,height:K},new Uint8Array(te)),L.usvg=!1,L.icon=void 0,xe=!0):L.data.replace(te,de),this.style.updateImage(C,L,xe)}hasImage(M){return M?!!this.style&&!!this.style.getImage(o.I.from(M)):(this.fire(new o.B(new Error("Missing required image id"))),!1)}removeImage(M){this.style.removeImage(o.I.from(M))}loadImage(M,g){o.n(this._requestManager.transformRequest(M,o.R.Image),(C,L)=>{g(C,L)})}listImages(){return this.style.listImages().map(M=>M.name)}addModel(M,g){this._lazyInitEmptyStyle(),this.style.addModel(M,g)}hasModel(M){return M?this.style.hasModel(M):(this.fire(new o.B(new Error("Missing required model id"))),!1)}removeModel(M){this.style.removeModel(M)}listModels(){return this.style.listModels()}addLayer(M,g){return this._isValidId(M.id)?(this._lazyInitEmptyStyle(),this.style.addLayer(M,g),this._update(!0)):this}getSlot(M){const g=this.getLayer(M);return g&&g.slot||null}setSlot(M,g){return this.style.setSlot(M,g),this.style.mergeLayers(),this._update(!0)}addImport(M,g){return this.style.addImport(M,g).catch(C=>this.fire(new o.B(new Error("Failed to add import",C)))),this}updateImport(M,g){return typeof g!="string"&&g.id!==M?(this.removeImport(M),this.addImport(g)):(this.style.updateImport(M,g),this._update(!0))}removeImport(M){return this.style.removeImport(M),this}moveImport(M,g){return this.style.moveImport(M,g),this._update(!0)}moveLayer(M,g){return this._isValidId(M)?(this.style.moveLayer(M,g),this._update(!0)):this}removeLayer(M){return this._isValidId(M)?(this.style.removeLayer(M),this._update(!0)):this}getLayer(M){if(!this._isValidId(M))return null;const g=this.style.getOwnLayer(M);return g?g.type==="custom"?g.implementation:g.serialize():void 0}getSlots(){return this.style.getSlots()}setLayerZoomRange(M,g,C){return this._isValidId(M)?(this.style.setLayerZoomRange(M,g,C),this._update(!0)):this}setFilter(M,g,C={}){return this._isValidId(M)?(this.style.setFilter(M,g,C),this._update(!0)):this}getFilter(M){return this._isValidId(M)?this.style.getFilter(M):null}setPaintProperty(M,g,C,L={}){return this._isValidId(M)?(this.style.setPaintProperty(M,g,C,L),this._update(!0)):this}getPaintProperty(M,g){return this._isValidId(M)?this.style.getPaintProperty(M,g):null}setLayoutProperty(M,g,C,L={}){return this._isValidId(M)?(this.style.setLayoutProperty(M,g,C,L),this._update(!0)):this}getLayoutProperty(M,g){return this._isValidId(M)?this.style.getLayoutProperty(M,g):null}setLayerProperty(M,g,C,L={}){return this._isValidId(M)?(g==="appearances"&&this._postAddingAppearancesToStyleEvent(),this.style.setLayerProperty(M,g,C,L),this._update(!0)):this}getGlyphsUrl(){return this.style.getGlyphsUrl()}setGlyphsUrl(M){return this.style.setGlyphsUrl(M),this._update(!0)}getSchema(M){return this.style.getSchema(M)}setSchema(M,g){return this.style.setSchema(M,g),this._update(!0)}getConfig(M){return this.style.getConfig(M)}setConfig(M,g){return this.style.setConfig(M,g),this._update(!0)}getConfigProperty(M,g){return this.style.getConfigProperty(M,g)}setConfigProperty(M,g,C){return this.style.setConfigProperty(M,g,C),this._update(!0)}getFeaturesetDescriptors(M){return this.style.getFeaturesetDescriptors(M)}setLights(M){if(this._lazyInitEmptyStyle(),M&&M.length===1&&M[0].type==="flat"){const g=M[0];g.properties?this.style.setFlatLight(g.properties,g.id,{}):this.style.setFlatLight({},"flat")}else this.style.setLights(M),this.painter.terrain&&(this.painter.terrain.invalidateRenderCache=!0);return this._update(!0)}getLights(){const M=this.style.getLights()||[];return M.length===0&&M.push({id:this.style.light.id,type:"flat",properties:this.style.getFlatLight()}),M}setLight(M,g={}){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:M}])}getLight(){return console.log("The `map.getLight` function is deprecated, prefer using `map.getLights` instead."),this.style.getFlatLight()}setTerrain(M){return this._lazyInitEmptyStyle(),!M&&this.transform.projection.requiresDraping?this.style.setTerrainForDraping():this.style.setTerrain(M),this._averageElevationLastSampledAt=-1/0,this._update(!0)}getTerrain(){return this.style?this.style.getTerrain():null}setFog(M){return this._lazyInitEmptyStyle(),this.style.setFog(M),this._update(!0)}getFog(){return this.style?this.style.getFog():null}setSnow(M){return this._lazyInitEmptyStyle(),this.style.setSnow(M),this._update(!0)}getSnow(){return this.style?this.style.getSnow():null}setRain(M){return this._lazyInitEmptyStyle(),this.style.setRain(M),this._update(!0)}getRain(){return this.style?this.style.getRain():null}setColorTheme(M){return this._lazyInitEmptyStyle(),this.style.setColorTheme(M),this._update(!0)}setImportColorTheme(M,g){return this._lazyInitEmptyStyle(),this.style.setImportColorTheme(M,g),this._update(!0)}setCamera(M){return this.style.setCamera(M),this._triggerCameraUpdate(M)}getNearClipOffset(){return this.transform.nearClipOffset}setNearClipOffset(M){const g=this.transform.nearClipOffset!==M;return this.transform.nearClipOffset=M,this._update(g)}_triggerCameraUpdate(M){return this._update(this.transform.setOrthographicProjectionAtLowPitch(M["camera-projection"]==="orthographic"))}getCamera(){return this.style.camera}_queryFogOpacity(M){return this.style&&this.style.fog?this.style.fog.getOpacityAtLatLng(o.aU.convert(M),this.transform):0}setFeatureState(M,g){return M.source&&!this._isValidId(M.source)?this:(this.style.setFeatureState(M,g),this._update())}removeFeatureState(M,g){return M.source&&!this._isValidId(M.source)?this:(this.style.removeFeatureState(M,g),this._update())}getFeatureState(M){return M.source&&!this._isValidId(M.source)?null:this.style.getFeatureState(M)}_selectIndoorFloor(M){this.style.indoorManager.selectFloor(M)}_setIndoorActiveFloorsVisibility(M){this.style.indoorManager.setActiveFloorsVisibility(M)}getIndoorTileOptions(M,g){return this.style.isIndoorEnabled()?this.style.indoorManager.getIndoorTileOptions(M,g):null}_updateContainerDimensions(){if(!this._container)return;const M=this._container.getBoundingClientRect().width||400,g=this._container.getBoundingClientRect().height||300;let C,L,$,G=this._container;for(;G&&(!L||!$);){const K=window.getComputedStyle(G).transform;K&&K!=="none"&&(C=K.match(/matrix.*\((.+)\)/)[1].split(", "),C[0]&&C[0]!=="0"&&C[0]!=="1"&&(L=C[0]),C[3]&&C[3]!=="0"&&C[3]!=="1"&&($=C[3])),G=G.parentElement}this._containerWidth=L?Math.abs(M/L):M,this._containerHeight=$?Math.abs(g/$):g}_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 M=this._container;M.classList.add("mapboxgl-map"),(this._missingCSSCanary=_("div","mapboxgl-canary",M)).style.visibility="hidden",this._detectMissingCSS();const g=this._canvasContainer=_("div","mapboxgl-canvas-container",M);this._canvas=_("canvas","mapboxgl-canvas",g),this._interactive&&(g.classList.add("mapboxgl-interactive"),this._canvas.setAttribute("tabindex","0")),this._canvas.addEventListener("webglcontextlost",this._contextLost,!1),this._canvas.addEventListener("webglcontextrestored",this._contextRestored,!1),this._canvas.setAttribute("aria-label",this._getUIString("Map.Title")),this._canvas.setAttribute("role","region"),this._updateContainerDimensions(),this._resizeCanvas(this._containerWidth,this._containerHeight);const C=this._controlContainer=_("div","mapboxgl-control-container",M),L=this._controlPositions={};["top-left","top","top-right","right","bottom-right","bottom","bottom-left","left"].forEach($=>{L[$]=_("div",`mapboxgl-ctrl-${$}`,C)}),this._container.addEventListener("scroll",this._onMapScroll,!1)}_resizeCanvas(M,g){const C=o.o.devicePixelRatio||1;this._canvas.width=C*Math.ceil(M),this._canvas.height=C*Math.ceil(g),this._canvas.style.width=`${M}px`,this._canvas.style.height=`${g}px`}_addMarker(M){this._markers.push(M)}_removeMarker(M){const g=this._markers.indexOf(M);g!==-1&&this._markers.splice(g,1)}_addPopup(M){this._popups.push(M)}_removePopup(M){const g=this._popups.indexOf(M);g!==-1&&this._popups.splice(g,1)}_setupPainter(){const M=Object.assign({},y.supported.webGLContextAttributes,{failIfMajorPerformanceCaveat:this._failIfMajorPerformanceCaveat,preserveDrawingBuffer:this._preserveDrawingBuffer,antialias:this._antialias||!1}),g=this._canvas.getContext("webgl2",M);g?($e(g,!0),this.painter=new oo(g,this._contextCreateOptions,this.transform,this._scaleFactor,this._worldview),this.on("data",C=>{if(C.dataType==="source"){const L=this.transform.elevation?this.transform.elevation._source():null;L&&C.sourceCacheId===L.id&&this.style&&this.style._setLabelPlacementStale(),this.painter.setTileLoadedFlag(!0)}}),o.k.testSupport(g)):this.fire(new o.B(new Error("Failed to initialize WebGL")))}_contextLost(M){M.preventDefault(),this._frame&&(this._frame.cancel(),this._frame=null),this.fire(new o.C("webglcontextlost",{originalEvent:M}))}_contextRestored(M){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:M}))}_onMapScroll(M){if(M.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(M){return this.style?(this._styleDirty=this._styleDirty||M,this._sourcesDirty=!0,this.triggerRepaint(),this):this}_requestRenderFrame(M){return this._update(),this._renderTaskQueue.add(M)}_cancelRenderFrame(M){this._renderTaskQueue.remove(M)}_requestDomTask(M){!this.loaded()||this.loaded()&&!this.isMoving()?M():this._domRenderTaskQueue.add(M)}_render(M){let g;this.fire(new o.C("renderstart")),++this._frameId;const C=this.painter.context.extTimerQuery,L=o.o.now(),$=this.painter.context.gl;if(this.listens("gpu-timing-frame")&&(g=$.createQuery(),$.beginQuery(C.TIME_ELAPSED_EXT,g)),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(M),this._domRenderTaskQueue.run(M),this._removed)return;this._updateProjectionTransition();const G=this._isInitialLoad?0:this._fadeDuration;if(this.style&&this._styleDirty){this._styleDirty=!1;const de=this.transform.zoom,xe=this.transform.pitch,_e=o.o.now(),Oe=new o.ae(de,{now:_e,fadeDuration:G,pitch:xe,transition:this.style.transition,worldview:this._worldview});this.style.update(Oe)}this.style&&this.style.hasFogTransition()&&(this.style._markersNeedUpdate=!0,this._sourcesDirty=!0);let K=!1;if(this.style&&this._sourcesDirty?(this._sourcesDirty=!1,this.painter._updateFog(this.style),this._updateTerrain(),K=this._updateAverageElevation(L),this.style.updateSources(this.transform),this.style.updateImageProviders(),this.isMoving()||this._forceMarkerAndPopupUpdate()):K=this._updateAverageElevation(L),this.style&&(this._placementDirty=this.style._updatePlacement(this.painter.transform,this.showCollisionBoxes,G,this._crossSourceCollisions,this.painter.replacementSource)),this.style&&this.painter.render(this.style,{showTileBoundaries:this.showTileBoundaries,showParseStatus:this.showParseStatus,wireframe:{terrain:this.showTerrainWireframe,layers2D:this.showLayers2DWireframe,layers3D:this.showLayers3DWireframe},showOverdrawInspector:this._showOverdrawInspector,showQueryGeometry:!!this._showQueryGeometry,showTileAABBs:this.showTileAABBs,rotating:this.isRotating(),zooming:this.isZooming(),moving:this.isMoving(),fadeDuration:G,isInitialLoad:this._isInitialLoad,showPadding:this.showPadding,gpuTiming:!!this.listens("gpu-timing-layer"),gpuTimingDeferredRender:!!this.listens("gpu-timing-deferred-render"),speedIndexTiming:this.speedIndexTiming}),this.fire(new o.C("render")),this.loaded()&&!this._loaded&&(this._loaded=!0,u.mark(d.load),this.fire(new o.C("load"))),this.style&&this.style.hasTransitions()&&(this._styleDirty=!0),this.style&&(this.style.snow||this.style.rain)&&(this._styleDirty=!0),this.style&&this.style.imageManager.hasPatternsInFlight()&&(this._styleDirty=!0),this.style&&!this.style.modelManager.isLoaded()&&(this._styleDirty=!0),this.style&&!this._placementDirty&&this.style._releaseSymbolFadeTiles(),g){const de=o.o.now()-L;$.endQuery(C.TIME_ELAPSED_EXT),setTimeout(()=>{const xe=$.getQueryParameter(g,$.QUERY_RESULT)/1e6;$.deleteQuery(g),this.fire(new o.C("gpu-timing-frame",{cpuTime:de,gpuTime:xe}))},50)}if(this.listens("gpu-timing-layer")){const de=this.painter.collectGpuTimers();setTimeout(()=>{const xe=this.painter.queryGpuTimers(de);this.fire(new o.C("gpu-timing-layer",{layerTimes:xe}))},50)}if(this.listens("gpu-timing-deferred-render")){const de=this.painter.collectDeferredRenderGpuQueries();setTimeout(()=>{const xe=this.painter.queryGpuTimeDeferredRender(de);this.fire(new o.C("gpu-timing-deferred-render",{gpuTime:xe}))},50)}const te=this._sourcesDirty||this._styleDirty||this._placementDirty||K;if(te||this._repaint)this.triggerRepaint();else{const de=this.idle();if(de&&(K=this._updateAverageElevation(L,!0)),K)this.triggerRepaint();else if(this._triggerFrame(!1),de&&(this.fire(new o.C("idle")),this._isInitialLoad=!1,this.speedIndexTiming)){const xe=this._calculateSpeedIndex();this.fire(new o.C("speedindexcompleted",{speedIndex:xe})),this.speedIndexTiming=!1}}!this._loaded||this._fullyLoaded||te||(this._fullyLoaded=!0,u.mark(d.fullLoad),this._performanceMetricsCollection&&ke(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(M){for(const g of this._markers)M&&!this.getRenderWorldCopies()&&(g._lngLat=g._lngLat.wrap()),g._update();for(const g of this._popups)!M||this.getRenderWorldCopies()||g._trackPointer||(g._lngLat=g._lngLat.wrap()),g._update()}_updateAverageElevation(M,g=!1){const C=$=>(this.transform.averageElevation=$,this._update(!1),!0);if(!this.painter.averageElevationNeedsEasing())return this.transform.averageElevation!==0&&C(0);const L=this.transform.elevation&&this.transform.elevation.exaggeration()!==this._averageElevationExaggeration;if(L||(g||M-this._averageElevationLastSampledAt>500)&&!this._averageElevation.isEasing(M)){const $=this.transform.averageElevation;let G=this.transform.sampleAverageElevation();this.transform.elevation!=null&&(this._averageElevationExaggeration=this.transform.elevation.exaggeration()),isNaN(G)?G=0:this._averageElevationLastSampledAt=M;const K=Math.abs($-G);if(K>1){if(this._isInitialLoad||L)return this._averageElevation.jumpTo(G),C(G);this._averageElevation.easeTo(G,M,300)}else if(K>1e-4)return this._averageElevation.jumpTo(G),C(G)}return!!this._averageElevation.isEasing(M)&&C(this._averageElevation.getValue(M))}_isTokenExpired(){return this._tokenExpiration!=null&&Date.now()>this._tokenExpiration}_revokeAuth(){const M=this.painter.context.gl;$e(M,!1),this._logoControl instanceof GR&&this._logoControl._updateLogo(),M&&M.clear(M.DEPTH_BUFFER_BIT|M.COLOR_BUFFER_BIT|M.STENCIL_BUFFER_BIT),this._silenceAuthErrors||this.fire(new o.B(new Error("A valid Mapbox access token is required to use Mapbox GL JS. To create an account or a new access token, visit https://account.mapbox.com/")))}_authenticate(){je(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,M=>{M&&(M.message!==Y&&M.status!==401||this._revokeAuth())}),this._isTokenExpired()&&this._revokeAuth(),Ce(this._getMapId(),this._requestManager._skuToken,this._requestManager._customAccessToken,()=>{})}_postStyleLoadEvent(){this.style.globalId&&Pe(this._requestManager._customAccessToken,{map:this,style:this.style.globalId,importedStyles:this.style.getImportGlobalIds()})}_postStyleWithAppearanceEvent(){this.style.globalId&&this.style.hasAppearances()&&Ae(this._requestManager._customAccessToken)}_postAddingAppearancesToStyleEvent(){we(this._requestManager._customAccessToken)}_updateTerrain(){const M=this._isDragging();this.painter.updateTerrain(this.style,M)}_calculateSpeedIndex(){const M=this.painter.canvasCopy(),g=this.painter.getCanvasCopiesAndTimestamps();g.timeStamps.push(performance.now());const C=this.painter.context.gl,L=C.createFramebuffer();function $(G){C.framebufferTexture2D(C.FRAMEBUFFER,C.COLOR_ATTACHMENT0,C.TEXTURE_2D,G,0);const K=new Uint8Array(C.drawingBufferWidth*C.drawingBufferHeight*4);return C.readPixels(0,0,C.drawingBufferWidth,C.drawingBufferHeight,C.RGBA,C.UNSIGNED_BYTE,K),K}return C.bindFramebuffer(C.FRAMEBUFFER,L),this._canvasPixelComparison($(M),g.canvasCopies.map($),g.timeStamps)}_canvasPixelComparison(M,g,C){let L=C[1]-C[0];const $=M.length/4;for(let G=0;G{const C=!!this._renderNextFrame;this._frame=null,this._renderNextFrame=null,C&&this._render(g)}))}_preloadTiles(M){const g=this.style?this.style.getSourceCaches():[];return o.t(g,(C,L)=>C._preloadTiles(M,L),()=>{this.triggerRepaint()}),this}_onWindowOnline(){this._update()}_onWindowResize(M){this._trackResize&&this.resize({originalEvent:M})._update()}_onVisibilityChange(){document.visibilityState==="hidden"&&this._visibilityHidden++}get showTileBoundaries(){return!!this._showTileBoundaries}set showTileBoundaries(M){this._showTileBoundaries!==M&&(this._showTileBoundaries=M,this._update())}get showParseStatus(){return!!this._showParseStatus}set showParseStatus(M){this._showParseStatus!==M&&(this._showParseStatus=M,this._update())}get showTerrainWireframe(){return!!this._showTerrainWireframe}set showTerrainWireframe(M){this._showTerrainWireframe!==M&&(this._showTerrainWireframe=M,this._update())}get showLayers2DWireframe(){return!!this._showLayers2DWireframe}set showLayers2DWireframe(M){this._showLayers2DWireframe!==M&&(this._showLayers2DWireframe=M,this._update())}get showLayers3DWireframe(){return!!this._showLayers3DWireframe}set showLayers3DWireframe(M){this._showLayers3DWireframe!==M&&(this._showLayers3DWireframe=M,this._update())}get speedIndexTiming(){return!!this._speedIndexTiming}set speedIndexTiming(M){this._speedIndexTiming!==M&&(this._speedIndexTiming=M,this._update())}get showPadding(){return!!this._showPadding}set showPadding(M){this._showPadding!==M&&(this._showPadding=M,this._update())}get showCollisionBoxes(){return!!this._showCollisionBoxes}set showCollisionBoxes(M){this._showCollisionBoxes!==M&&(this._showCollisionBoxes=M,this.style&&M?this.style._generateCollisionBoxes():this._update())}get showOverdrawInspector(){return!!this._showOverdrawInspector}set showOverdrawInspector(M){this._showOverdrawInspector!==M&&(this._showOverdrawInspector=M,this._update())}get repaint(){return!!this._repaint}set repaint(M){this._repaint!==M&&(this._repaint=M,this.triggerRepaint())}get vertices(){return!!this._vertices}set vertices(M){this._vertices=M,this._update()}get showTileAABBs(){return!!this._showTileAABBs}set showTileAABBs(M){this._showTileAABBs!==M&&(this._showTileAABBs=M,M&&this._update())}_setCacheLimits(M,g){o.e_(M,g)}get version(){return c}},NavigationControl:class{constructor(M={}){this.options=Object.assign({},lbe,M),this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.addEventListener("contextmenu",g=>g.preventDefault()),this.options.showZoom&&(o.aZ(["_setButtonTitle","_updateZoomButtons"],this),this._zoomInButton=this._createButton("mapboxgl-ctrl-zoom-in",g=>{this._map&&this._map.zoomIn({},{originalEvent:g})}),_("span","mapboxgl-ctrl-icon",this._zoomInButton).setAttribute("aria-hidden","true"),this._zoomOutButton=this._createButton("mapboxgl-ctrl-zoom-out",g=>{this._map&&this._map.zoomOut({},{originalEvent:g})}),_("span","mapboxgl-ctrl-icon",this._zoomOutButton).setAttribute("aria-hidden","true")),this.options.showCompass&&(o.aZ(["_rotateCompassArrow"],this),this._compass=this._createButton("mapboxgl-ctrl-compass",g=>{const C=this._map;C&&(this.options.visualizePitch?C.resetNorthPitch({},{originalEvent:g}):C.resetNorth({},{originalEvent:g}))}),this._compassIcon=_("span","mapboxgl-ctrl-icon",this._compass),this._compassIcon.setAttribute("aria-hidden","true"))}_updateZoomButtons(){const M=this._map;if(!M)return;const g=M.getZoom(),C=g===M.getMaxZoom(),L=g===M.getMinZoom();this._zoomInButton.disabled=C,this._zoomOutButton.disabled=L,this._zoomInButton.setAttribute("aria-disabled",C.toString()),this._zoomOutButton.setAttribute("aria-disabled",L.toString())}_rotateCompassArrow(){const M=this._map;if(!M)return;const g=this.options.visualizePitch?`scale(${1/Math.pow(Math.cos(M.transform.pitch*(Math.PI/180)),.5)}) rotateX(${M.transform.pitch}deg) rotateZ(${M.transform.angle*(180/Math.PI)}deg)`:`rotate(${M.transform.angle*(180/Math.PI)}deg)`;M._requestDomTask(()=>{this._compassIcon&&(this._compassIcon.style.transform=g)})}onAdd(M){return this._map=M,this.options.showZoom&&(this._setButtonTitle(this._zoomInButton,"ZoomIn"),this._setButtonTitle(this._zoomOutButton,"ZoomOut"),M.on("zoom",this._updateZoomButtons),this._updateZoomButtons()),this.options.showCompass&&(this._setButtonTitle(this._compass,"ResetBearing"),this.options.visualizePitch&&M.on("pitch",this._rotateCompassArrow),M.on("rotate",this._rotateCompassArrow),this._rotateCompassArrow(),this._handler=new FC(M,this._compass,this.options.visualizePitch)),this._container}onRemove(){const M=this._map;M&&(this._container.remove(),this.options.showZoom&&M.off("zoom",this._updateZoomButtons),this.options.showCompass&&(this.options.visualizePitch&&M.off("pitch",this._rotateCompassArrow),M.off("rotate",this._rotateCompassArrow),this._handler&&this._handler.off(),this._handler=void 0),this._map=void 0)}_createButton(M,g){const C=_("button",M,this._container);return C.type="button",C.addEventListener("click",g),C}_setButtonTitle(M,g){if(!this._map)return;const C=this._map._getUIString(`NavigationControl.${g}`);M.setAttribute("aria-label",C),M.firstElementChild&&M.firstElementChild.setAttribute("title",C)}},GeolocateControl:class extends o.E{constructor(M={}){super();const g=navigator.geolocation;this.options=Object.assign({geolocation:g},BC,M),o.aZ(["_onSuccess","_onError","_onZoom","_finish","_setupUI","_updateCamera","_updateMarker","_updateMarkerRotation","_onDeviceOrientation"],this),this._updateMarkerRotationThrottled=ja(this._updateMarkerRotation,20),this._numberOfWatches=0}onAdd(M){return this._map=M,this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkGeolocationSupport(this._setupUI),this._container}onRemove(){this._clearRequestTimeout(),this._geolocationWatchID!==void 0&&(this.options.geolocation.clearWatch(this._geolocationWatchID),this._geolocationWatchID=void 0),this.options.showUserLocation&&this._userLocationDotMarker&&this._userLocationDotMarker.remove(),this.options.showAccuracyCircle&&this._accuracyCircleMarker&&this._accuracyCircleMarker.remove(),this._container.remove(),this._map.off("zoom",this._onZoom),this._map=void 0,this._numberOfWatches=0,this._noTimeout=!1}_checkGeolocationSupport(M){const g=(C=!!this.options.geolocation)=>{this._supportsGeolocation=C,M(C)};this._supportsGeolocation!==void 0?M(this._supportsGeolocation):navigator.permissions!==void 0?navigator.permissions.query({name:"geolocation"}).then(C=>g(C.state!=="denied")).catch(()=>g()):g()}_isOutOfMapMaxBounds(M){const g=this._map.getMaxBounds(),C=M.coords;return!!g&&(C.longitudeg.getEast()||C.latitudeg.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(M){if(this._map){if(this._clearRequestTimeout(),this._isOutOfMapMaxBounds(M))return this._setErrorState(),this.fire(new o.C("outofmaxbounds",M)),this._updateMarker(),void this._finish();if(this.options.trackUserLocation)switch(this._lastKnownPosition=M,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(M),this.options.followUserLocation&&(!this.options.trackUserLocation||this._watchState==="ACTIVE_LOCK")&&this._updateCamera(M),this.options.showUserLocation&&this._userLocationDotMarker.removeClassName("mapboxgl-user-location-dot-stale"),this.fire(new o.C("geolocate",Object.assign({coords:M.coords,timestamp:M.timestamp},M.toJSON?{toJSON:M.toJSON.bind(M)}:{}))),this._finish()}}_updateCamera(M){const g=new o.aU(M.coords.longitude,M.coords.latitude),C=M.coords.accuracy,L=this._map.getBearing(),$=Object.assign({bearing:L},this.options.fitBoundsOptions);this._map.fitBounds(g.toBounds(C),$,{geolocateSource:!0})}_updateMarker(M){if(M){const g=new o.aU(M.coords.longitude,M.coords.latitude);this._accuracyCircleMarker.setLngLat(g).addTo(this._map),this._userLocationDotMarker.setLngLat(g).addTo(this._map),this._accuracy=M.coords.accuracy,this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}else this._userLocationDotMarker.remove(),this._accuracyCircleMarker.remove()}_updateCircleRadius(){const M=this._map.transform,g=o.bU(1,M._center.lat)*M.worldSize,C=Math.ceil(2*this._accuracy*g);this._circleElement.style.width=`${C}px`,this._circleElement.style.height=`${C}px`}_onZoom(){this.options.showUserLocation&&this.options.showAccuracyCircle&&this._updateCircleRadius()}_updateMarkerRotation(){this._userLocationDotMarker&&typeof this._heading=="number"?(this._userLocationDotMarker.setRotation(this._heading),this._userLocationDotMarker.addClassName("mapboxgl-user-location-show-heading")):(this._userLocationDotMarker.removeClassName("mapboxgl-user-location-show-heading"),this._userLocationDotMarker.setRotation(0))}_onError(M){if(this._map){if(this._clearRequestTimeout(),this.options.trackUserLocation)if(M.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 g=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.setAttribute("aria-label",g),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",g),this._geolocationWatchID!==void 0&&this._clearWatch()}else{if(M.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:M.code,message:M.message,PERMISSION_DENIED:M.PERMISSION_DENIED,POSITION_UNAVAILABLE:M.POSITION_UNAVAILABLE,TIMEOUT:M.TIMEOUT})),this._finish()}}_finish(){this._timeoutId&&clearTimeout(this._timeoutId),this._timeoutId=void 0}_startRequestTimeout(){this._clearRequestTimeout();const M=this.options.positionOptions.timeout;M&&(this._requestTimeoutId=window.setTimeout(()=>{this._onError({code:3,message:"Geolocation request timed out"})},M))}_clearRequestTimeout(){this._requestTimeoutId!==void 0&&(clearTimeout(this._requestTimeoutId),this._requestTimeoutId=void 0)}_setupUI(M){if(this._map!==void 0){if(this._container.addEventListener("contextmenu",g=>g.preventDefault()),this._geolocateButton=_("button","mapboxgl-ctrl-geolocate",this._container),_("span","mapboxgl-ctrl-icon",this._geolocateButton).setAttribute("aria-hidden","true"),this._geolocateButton.type="button",M===!1){o.w("Geolocation support is not available so the GeolocateControl will be disabled.");const g=this._map._getUIString("GeolocateControl.LocationNotAvailable");this._geolocateButton.disabled=!0,this._geolocateButton.setAttribute("aria-label",g),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",g)}else{const g=this._map._getUIString("GeolocateControl.FindMyLocation");this._geolocateButton.setAttribute("aria-label",g),this._geolocateButton.firstElementChild&&this._geolocateButton.firstElementChild.setAttribute("title",g)}this.options.trackUserLocation&&(this._geolocateButton.setAttribute("aria-pressed","false"),this._watchState="OFF"),this.options.showUserLocation&&(this._dotElement=_("div","mapboxgl-user-location"),this._dotElement.appendChild(_("div","mapboxgl-user-location-dot")),this._dotElement.appendChild(_("div","mapboxgl-user-location-heading")),this._userLocationDotMarker=new vg({element:this._dotElement,rotationAlignment:"map",pitchAlignment:"map"}),this._circleElement=_("div","mapboxgl-user-location-accuracy-circle"),this._accuracyCircleMarker=new vg({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",g=>{g.geolocateSource||this._watchState!=="ACTIVE_LOCK"||g.originalEvent&&g.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(M){this._userLocationDotMarker&&(M.webkitCompassHeading?this._heading=M.webkitCompassHeading:M.absolute===!0&&(this._heading=-1*M.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 M;this._geolocateButton.classList.add("mapboxgl-ctrl-geolocate-waiting"),this._geolocateButton.setAttribute("aria-pressed","true"),this._numberOfWatches++,this._numberOfWatches>1?(M={maximumAge:6e5,timeout:0},this._noTimeout=!0):(M=this.options.positionOptions,this._noTimeout=!1),this._geolocationWatchID=this.options.geolocation.watchPosition(this._onSuccess,this._onError,M),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(M){return this.options.followUserLocation=M??BC.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 M=()=>{const g="ondeviceorientationabsolute"in window?"deviceorientationabsolute":"deviceorientation";window.addEventListener(g,this._onDeviceOrientation)};typeof DeviceOrientationEvent.requestPermission=="function"?DeviceOrientationEvent.requestPermission().then(g=>{g==="granted"&&M()}).catch(console.error):M()}_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:HR,ScaleControl:class{constructor(M={}){this.options=Object.assign({},cd,M),o.aZ(["_update","_setScale","setUnit"],this)}getDefaultPosition(){return"bottom-left"}_update(){const M=this.options.maxWidth||100,g=this._map,C=g._containerHeight/2,L=g._containerWidth/2-M/2,$=g.unproject([L,C]),G=g.unproject([L+M,C]),K=$.distanceTo(G);if(this.options.unit==="imperial"){const te=3.2808*K;te>5280?this._setScale(M,te/5280,"mile"):this._setScale(M,te,"foot")}else this.options.unit==="nautical"?this._setScale(M,K/1852,"nautical-mile"):K>=1e3?this._setScale(M,K/1e3,"kilometer"):this._setScale(M,K,"meter")}_setScale(M,g,C){this._map._requestDomTask(()=>{const L=function(G){const K=Math.pow(10,`${Math.floor(G)}`.length-1);let te=G/K;return te=te>=10?10:te>=5?5:te>=3?3:te>=2?2:te>=1?1:function(de){const xe=Math.pow(10,Math.ceil(-Math.log(de)/Math.LN10));return Math.round(de*xe)/xe}(te),K*te}(g),$=L/g;this._container.innerHTML=C!=="nautical-mile"?new Intl.NumberFormat(this._language,{style:"unit",unitDisplay:"short",unit:C}).format(L):`${L} ${bg[C]}`,this._container.style.width=M*$+"px"})}onAdd(M){return this._map=M,this._language=M.getLanguage(),this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-scale",M.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(M){this._language=M,this._update()}setUnit(M){this.options.unit=M,this._update()}},FullscreenControl:class{constructor(M={}){this._fullscreen=!1,M&&M.container&&(M.container instanceof HTMLElement?this._container=M.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(M){return this._map=M,this._container||(this._container=this._map.getContainer()),this._controlContainer=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._checkFullscreenSupport()?this._setupUI():(this._controlContainer.style.display="none",o.w("This device does not support fullscreen mode.")),this._controlContainer}onRemove(){this._controlContainer.remove(),this._map=null,document.removeEventListener(this._fullscreenchange,this._changeIcon)}_checkFullscreenSupport(){return!(!document.fullscreenEnabled&&!document.webkitFullscreenEnabled)}_setupUI(){const M=this._fullscreenButton=_("button","mapboxgl-ctrl-fullscreen",this._controlContainer);_("span","mapboxgl-ctrl-icon",M).setAttribute("aria-hidden","true"),M.type="button",this._updateTitle(),this._fullscreenButton.addEventListener("click",this._onClickFullscreen),document.addEventListener(this._fullscreenchange,this._changeIcon)}_updateTitle(){const M=this._getTitle();this._fullscreenButton.setAttribute("aria-label",M),this._fullscreenButton.firstElementChild&&this._fullscreenButton.firstElementChild.setAttribute("title",M)}_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(M){return this._map=M,this._container=_("div","mapboxgl-ctrl mapboxgl-ctrl-group"),this._container.style.display="none",this._map.on("styledata",this._onStyleData),this._updateConnection(),this._container}_onStyleData(){this._updateConnection()}_updateConnection(){if(this._map&&this._map.style&&this._map.style.indoorManager){const M=this._map.style.indoorManager;M.off("selector-update",this._onIndoorUpdate),M.on("selector-update",this._onIndoorUpdate),this._onIndoorUpdate(M.getControlState())}}_createButton(M,g){const C=_("button",M,this._container);return C.type="button",C.addEventListener("click",g),C}_setButtonTitle(M,g){M.setAttribute("aria-label",g),M.textContent=g}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(M){if(!M||!M.floors||M.floors.length===0)return this._model=M,void(this._container.style.display="none");const g=this._model;this._model=M,this._container.style.display="inline-block";const C=!g||g.floors.length!==M.floors.length||g.floors.some((L,$)=>L.id!==M.floors[$].id);if(C&&(this._visibleFloorStart=0,this._lastSelectedFloorId=null),M.selectedFloorId){if(M.selectedFloorId!==this._lastSelectedFloorId||C){const L=M.floors.findIndex($=>$.id===M.selectedFloorId);if(L!==-1){const $=M.floors.length;let G,K;$<=5?(G=0,K=$-1):this._visibleFloorStart===0?(G=0,K=3):this._visibleFloorStart>=$-3?(G=$-3-1,K=$-1):(G=this._visibleFloorStart,K=this._visibleFloorStart+3-1),LK&&(this._visibleFloorStart=L-2)}}this._lastSelectedFloorId=M.selectedFloorId}this._render()}_render(){if(!this._container||!this._model||!this._model.floors)return;this._container.innerHTML="";const M=this._createButton("mapboxgl-ctrl-indoor-toggle",this._toggleIndoor);_("span","mapboxgl-ctrl-icon",M).setAttribute("aria-hidden","true"),this._model.activeFloorsVisible||M.classList.add("mapboxgl-ctrl-level-button-selected"),this._container.appendChild(M);const g=this._model.floors,C=g.length;if(C<=5)return void g.forEach(K=>this._createFloorButton(K));const L=this._visibleFloorStart===0,$=this._visibleFloorStart>=C-3;if(L)this._createFloorButton(g[0]);else{const K=this._createButton("mapboxgl-ctrl-arrow-up",this._scrollUp);_("span","mapboxgl-ctrl-icon",K).setAttribute("aria-hidden","true"),this._container.appendChild(K)}let G=[];if(G=L?g.slice(1,4):$?g.slice(this._visibleFloorStart-1,this._visibleFloorStart+3-1):g.slice(this._visibleFloorStart,this._visibleFloorStart+3),G.forEach(K=>this._createFloorButton(K)),$)this._createFloorButton(g[C-1]);else{const K=this._createButton("mapboxgl-ctrl-arrow-down",this._scrollDown);_("span","mapboxgl-ctrl-icon",K).setAttribute("aria-hidden","true"),this._container.appendChild(K)}}_createFloorButton(M){const g=this._createButton("mapboxgl-ctrl-level-button",()=>{const G=M.id;this._model&&this._model.selectedFloorId===G&&this._model.activeFloorsVisible||this._map&&(this._model&&!this._model.activeFloorsVisible&&this._map.style&&this._map.style.indoorManager&&this._map.style.indoorManager.setActiveFloorsVisibility(!0),this._map._selectIndoorFloor(G))}),C=(M.name||"").trim(),L=M.zIndex.toString(),$=C?Array.from(C).slice(0,3).join(""):L;this._setButtonTitle(g,$),this._model&&this._model.activeFloorsVisible&&M.id===this._model.selectedFloorId&&g.classList.add("mapboxgl-ctrl-level-button-selected"),this._container&&this._container.appendChild(g)}_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 M=this._model&&this._model.floors||[];if(M.length>3){const g=M.length-3;this._visibleFloorStart===g-1&&(this._visibleFloorStart=g-2)}this._render()}}_scrollDown(){if(this._model&&this._model.floors){const M=this._model.floors.length-3;this._visibleFloorStartM&&(this._visibleFloorStart=M),this._render())}}},Popup:class extends o.E{constructor(M){super(),this.options=Object.assign(Object.create($C),M),this._altitude=this.options.altitude,o.aZ(["_update","_onClose","remove","_onMouseEvent"],this),this._classList=new Set(M&&M.className?M.className.trim().split(/\s+/):[])}addTo(M){return this._map&&this.remove(),this._map=M,this.options.closeOnClick&&M.on("preclick",this._onClose),this.options.closeOnMove&&M.on("move",this._onClose),M.on("remove",this.remove),this._update(),M._addPopup(this),this._focusFirstElement(),this._trackPointer?(M.on("mousemove",this._onMouseEvent),M.on("mouseup",this._onMouseEvent),M._canvasContainer.classList.add("mapboxgl-track-pointer")):M.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 M=this._map;return M&&(M.off("move",this._update),M.off("move",this._onClose),M.off("preclick",this._onClose),M.off("click",this._onClose),M.off("remove",this.remove),M.off("mousemove",this._onMouseEvent),M.off("mouseup",this._onMouseEvent),M.off("drag",this._onMouseEvent),M._canvasContainer&&M._canvasContainer.classList.remove("mapboxgl-track-pointer"),M._removePopup(this),this._map=void 0),this.fire(new o.C("close")),this}getLngLat(){return this._lngLat}setLngLat(M){this._lngLat=o.aU.convert(M),this._pos=null,this._trackPointer=!1,this._update();const g=this._map;return g&&(g.on("move",this._update),g.off("mousemove",this._onMouseEvent),g._canvasContainer.classList.remove("mapboxgl-track-pointer")),this}getAltitude(){return this._altitude}setAltitude(M){return this._altitude=M,this._update(),this}trackPointer(){this._trackPointer=!0,this._pos=null,this._update();const M=this._map;return M&&(M.off("move",this._update),M.on("mousemove",this._onMouseEvent),M.on("drag",this._onMouseEvent),M._canvasContainer.classList.add("mapboxgl-track-pointer")),this}getElement(){return this._container}setText(M){return this.setDOMContent(document.createTextNode(M))}setHTML(M){const g=document.createDocumentFragment(),C=document.createElement("body");let L;for(C.innerHTML=M;L=C.firstChild,L;)g.appendChild(L);return this.setDOMContent(g)}getMaxWidth(){return this._container&&this._container.style.maxWidth}setMaxWidth(M){return this.options.maxWidth=M,this._update(),this}setDOMContent(M){let g=this._content;if(g)for(;g.hasChildNodes();)g.firstChild&&g.removeChild(g.firstChild);else g=this._content=_("div","mapboxgl-popup-content",this._container||void 0);if(g.appendChild(M),this.options.closeButton){const C=this._closeButton=_("button","mapboxgl-popup-close-button",g);C.type="button",C.setAttribute("aria-label","Close popup"),C.innerHTML='',C.addEventListener("click",this._onClose)}return this._update(),this._focusFirstElement(),this}addClassName(M){return this._classList.add(M),this._updateClassList(),this}removeClassName(M){return this._classList.delete(M),this._updateClassList(),this}setOffset(M){return this.options.offset=M,this._update(),this}toggleClassName(M){let g;return this._classList.delete(M)?g=!1:(this._classList.add(M),g=!0),this._updateClassList(),g}_onMouseEvent(M){this._update(M.point)}_getAnchor(M){if(this.options.anchor)return this.options.anchor;const g=this._map,C=this._container,L=this._pos;if(!g||!C||!L)return"bottom";const $=C.offsetWidth,G=C.offsetHeight,K=L.x<$/2,te=L.x>g.transform.width-$/2;if(L.y+Mg.transform.height-G){if(K)return"bottom-left";if(te)return"bottom-right"}return K?"left":te?"right":"bottom"}_updateClassList(){const M=this._container;if(!M)return;const g=[...this._classList];g.push("mapboxgl-popup"),this._anchor&&g.push(`mapboxgl-popup-anchor-${this._anchor}`),this._trackPointer&&g.push("mapboxgl-popup-track-pointer"),M.className=g.join(" ")}_update(M){const g=this._map,C=this._content;if(!g||!this._lngLat&&!this._trackPointer||!C)return;let L=this._container;if(L||(L=this._container=_("div","mapboxgl-popup",g.getContainer()),this._tip=_("div","mapboxgl-popup-tip",L),L.appendChild(C)),this.options.maxWidth&&L.style.maxWidth!==this.options.maxWidth&&(L.style.maxWidth=this.options.maxWidth),g.transform.renderWorldCopies&&!this._trackPointer&&(this._lngLat=WR(this._lngLat,this._pos,g.transform)),!this._trackPointer||M){const $=this._pos=this._trackPointer&&M instanceof o.P?M:g.project(this._lngLat,this._altitude),G=I6(this.options.offset),K=this._anchor=this._getAnchor(G.y),te=I6(this.options.offset,K),de=$.add(te).round();g._requestDomTask(()=>{this._container&&K&&(this._container.style.transform=`${zC[K]} translate(${de.x}px,${de.y}px)`)})}if(!this._marker&&g._showingGlobe()){const $=o.e$(g.transform,this._lngLat)?0:1;this._setOpacity($)}this._updateClassList()}_focusFirstElement(){if(!this.options.focusAfterOpen||!this._container)return;const M=this._container.querySelector(cbe);M&&M.focus()}_onClose(){this.remove()}_setOpacity(M){this._container&&(this._container.style.opacity=`${M}`),this._content&&(this._content.style.pointerEvents=M?"auto":"none")}},Marker:vg,Style:Yc,LngLat:o.aU,LngLatBounds:o.aK,Point:o.P,MercatorCoordinate:o.ag,FreeCameraOptions:Hb,Evented:o.E,config:o.g,prewarm:function(){$t().acquire(at)},clearPrewarmedResources:function(){const M=_t;M&&(M.isPreloaded()&&M.numActive()===1?(M.release(at),_t=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(M){o.g.ACCESS_TOKEN=M},get baseApiUrl(){return o.g.API_URL},set baseApiUrl(M){o.g.API_URL=M},get workerCount(){return Ye.workerCount},set workerCount(M){Ye.workerCount=M},get maxParallelImageRequests(){return o.g.MAX_PARALLEL_IMAGE_REQUESTS},set maxParallelImageRequests(M){o.g.MAX_PARALLEL_IMAGE_REQUESTS=M},clearStorage(M){o.f7(M)},get workerUrl(){return rt.workerUrl},set workerUrl(M){rt.workerUrl=M},get workerClass(){return rt.workerClass},set workerClass(M){rt.workerClass=M},get workerParams(){return rt.workerParams},set workerParams(M){rt.workerParams=M},get dracoUrl(){return o.f6()},set dracoUrl(M){o.g.DRACO_URL=o.o.resolveURL(M)},get meshoptUrl(){return o.f5()},set meshoptUrl(M){const g=o.o.resolveURL(M);o.g.MESHOPT_URL=g,o.g.MESHOPT_SIMD_URL=g},get buildingGenUrl(){return o.f4()},set buildingGenUrl(M){o.g.BUILDING_GEN_URL=o.o.resolveURL(M)},setNow:o.o.setNow,restoreNow:o.o.restoreNow}});var l=a;return l})})(Ult);var B9t=Ult.exports;const ul=_l(B9t),zze={coming_soon:"#3B82F6",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#F97316",under_contract:"#8B5CF6",sold:"#6B7280"},Bze={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 $9t(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function U9t({listings:s,isLoading:t}){const n=Ln(),r=N.useRef(null),a=N.useRef(null),i=N.useRef([]),[l,o]=N.useState(""),[c,d]=N.useState(!0);return N.useEffect(()=>{(async()=>{d(!0);try{const{data:p}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();p!=null&&p.value&&o(p.value)}catch(p){console.error("Error fetching mapbox token:",p)}d(!1)})()},[]),N.useEffect(()=>{if(!r.current||!l||a.current)return;ul.accessToken=l;const h=s.filter(y=>y.latitude!=null&&y.longitude!=null);let p=[-98.5795,39.8283],f=4;if(h.length>0){const y=h.reduce((v,j)=>v+j.longitude,0)/h.length,_=h.reduce((v,j)=>v+j.latitude,0)/h.length;p=[y,_],f=h.length===1?12:10}return a.current=new ul.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:f,center:p}),a.current.addControl(new ul.NavigationControl,"top-right"),()=>{var y;(y=a.current)==null||y.remove(),a.current=null}},[l]),N.useEffect(()=>{if(!a.current||!l)return;i.current.forEach(p=>p.remove()),i.current=[];const h=s.filter(p=>p.latitude!=null&&p.longitude!=null);if(h.forEach(p=>{var A,E,O;const f=zze[p.status]||"#10B981",y=((A=p.photos)==null?void 0:A.find(D=>D.is_primary))||((E=p.photos)==null?void 0:E[0]),v=window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")?`/${p.slug||p.id}`:`/public/listing/${p.slug||p.id}`,j=document.createElement("div");j.className="cursor-pointer",j.innerHTML=`
`;const w=new ul.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${y!=null&&y.photo_url?``:""}
${$9t(p.price)}
${p.property_address||""}
${p.city}, ${p.state}
${Bze[p.status]||p.status} ${p.bedrooms?`${p.bedrooms} bed`:""} ${p.bathrooms?`${p.bathrooms} bath`:""}
${(O=p.agent)!=null&&O.name?`
Listed by ${p.agent.name}
`:""}
Click to view details →
`),S=new ul.Marker(j).setLngLat([p.longitude,p.latitude]).setPopup(w).addTo(a.current);i.current.push(S)}),h.length>1){const p=new ul.LngLatBounds;h.forEach(f=>p.extend([f.longitude,f.latitude])),a.current.fitBounds(p,{padding:60,maxZoom:13})}else h.length===1&&a.current.flyTo({center:[h[0].longitude,h[0].latitude],zoom:12})},[s,l]),N.useEffect(()=>(window.__navigateToPublicListing__=h=>{n(h)},()=>{delete window.__navigateToPublicListing__}),[n]),c||t?e.jsx(Ws,{className:"w-full h-[500px] rounded-lg"}):!l||s.filter(h=>h.latitude!=null&&h.longitude!=null).length===0?null:e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:Object.entries(zze).map(([h,p])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:p}}),e.jsx("span",{className:"text-xs text-gray-600",children:Bze[h]})]},h))}),e.jsx("div",{ref:r,className:"w-full h-[500px] rounded-lg shadow-lg border border-gray-200"})]})}const qwe={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},q9t={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"},pI="#0d0d0d",$ze="#1a1a1a",vl="#c9a84c",vk="#f0d78c";function Vlt(){const[s,t]=N.useState(""),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(-1),u=N.useRef(null),[h,p]=N.useState({status:"",propertyType:"",minPrice:"",maxPrice:""}),{data:f}=P9t(),y=N.useMemo(()=>{if(!f)return[];const H=s.trim().toLowerCase(),Z=[...f.cities.map(W=>({label:W.label,value:W.city,type:"city",count:W.count})),...f.neighborhoods.map(W=>({label:W.label,value:W.neighborhood,type:"neighborhood",count:W.count})),...f.zips.map(W=>({label:`ZIP ${W.label}`,value:W.zip,type:"zip",count:W.count}))];return(H?Z.filter(W=>W.label.toLowerCase().includes(H)||W.value.toLowerCase().includes(H)):Z).slice(0,8)},[f,s]);N.useEffect(()=>{const H=Z=>{u.current&&!u.current.contains(Z.target)&&o(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[]);const{data:_,isLoading:v}=I9t({city:s||void 0,status:h.status||void 0,propertyType:h.propertyType||void 0,minPrice:h.minPrice?Number(h.minPrice):void 0,maxPrice:h.maxPrice?Number(h.maxPrice):void 0}),j=H=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(H),w=()=>{p({status:"",propertyType:"",minPrice:"",maxPrice:""}),t("")},S=s||h.status||h.propertyType||h.minPrice||h.maxPrice,A=typeof window<"u"&&(window.location.hostname==="listings.relevelup.com"||window.location.hostname.startsWith("listings.")),E=H=>A?`/${H.slug||H.id}`:`/public/listing/${H.slug||H.id}`,{featured:O,restListings:D,luxeCount:I,cities:F,activeCount:z}=N.useMemo(()=>{const H=_||[],Z=H.filter(Te=>Te.status==="active"),Y=Z.length>0?Z:H,W=new Intl.DateTimeFormat("en-CA",{timeZone:"America/New_York",year:"numeric",month:"2-digit",day:"2-digit"}).format(new Date),[ee,se,oe]=W.split("-").map(Number),he=Math.floor(Date.UTC(ee,se-1,oe)/864e5),ce=Y.length>0?Y[he%Y.length]:void 0,me=H.filter(Te=>!ce||Te.id!==ce.id),le=Array.from(new Set(H.map(Te=>Te.city).filter(Boolean))).slice(0,8),ve=H.filter(Te=>(Te.price||0)>=1e6).length,ge=Z.length;return{featured:ce,restListings:me,luxeCount:ve,cities:le,activeCount:ge}},[_]);return e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{children:[e.jsx("title",{children:"LevelUp Listings — Curated Homes for Sale"}),e.jsx("meta",{name:"description",content:"A curated collection of exclusive properties from LevelUp real estate agents. Discover luxury homes, coming soon listings, and market-defining architecture."}),e.jsx("link",{rel:"canonical",href:"https://listings.relevelup.com"}),e.jsx("meta",{property:"og:title",content:"LevelUp Listings — Curated Homes for Sale"}),e.jsx("meta",{property:"og:description",content:"A curated collection of exclusive properties from LevelUp real estate agents."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:"https://listings.relevelup.com"}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify({"@context":"https://schema.org","@type":"WebSite",name:"LevelUp Listings",url:"https://listings.relevelup.com"})})]}),e.jsxs("div",{className:"min-h-screen text-white",style:{backgroundColor:pI,fontFamily:"'Fira Sans', system-ui, sans-serif"},children:[e.jsx("style",{children:` .lu-serif { font-family: 'DM Serif Display', Georgia, serif; font-weight: 400; letter-spacing: -0.01em; } .lu-eyebrow { font-family: 'Fira Sans', sans-serif; font-weight: 500; letter-spacing: 0.3em; text-transform: uppercase; font-size: 11px; } .lu-gold { color: ${vl}; } .lu-gold-line { background: linear-gradient(90deg, transparent, ${vl}, transparent); } .lu-card-hover { transition: transform .6s cubic-bezier(.2,.7,.2,1), box-shadow .6s; } .lu-card-hover:hover { transform: translateY(-6px); } .lu-img-zoom { transition: transform 1.2s cubic-bezier(.2,.7,.2,1); } .group:hover .lu-img-zoom { transform: scale(1.06); } .lu-hero-title { animation: luFadeUp 1.1s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-sub { animation: luFadeUp 1.1s .15s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-search { animation: luFadeUp 1.1s .3s cubic-bezier(.2,.7,.2,1) both; } .lu-hero-stats { animation: luFadeUp 1.1s .45s cubic-bezier(.2,.7,.2,1) both; } @keyframes luFadeUp { from { opacity: 0; transform: translateY(24px); } to { opacity: 1; transform: none; } } .lu-grain::after { content: ''; position: absolute; inset: 0; pointer-events: none; opacity: .18; background-image: url("data:image/svg+xml;utf8,"); } .lu-marquee { display: flex; gap: 3rem; animation: luMarquee 40s linear infinite; } @keyframes luMarquee { to { transform: translateX(-50%); } } .lu-input-dark { background: rgba(255,255,255,0.06) !important; border-color: rgba(201,168,76,0.25) !important; color: #fff !important; } .lu-input-dark::placeholder { color: rgba(255,255,255,0.5) !important; } `}),e.jsxs("header",{className:"sticky top-0 z-50 backdrop-blur-md",style:{backgroundColor:"rgba(13,13,13,0.75)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:[e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between",children:[e.jsxs(In,{to:"/",className:"flex items-center gap-3",children:[e.jsx("img",{src:Kpe,alt:"LevelUp",className:"h-7"}),e.jsx("span",{className:"hidden sm:inline-block h-5 w-px",style:{background:"rgba(255,255,255,0.2)"}}),e.jsx("span",{className:"hidden sm:inline lu-eyebrow lu-gold",children:"Listings"})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-8",children:[e.jsx("a",{href:"#featured",className:"text-sm text-white/80 hover:text-white transition",children:"Featured"}),e.jsx("a",{href:"#collection",className:"text-sm text-white/80 hover:text-white transition",children:"Collection"}),e.jsx("a",{href:"#map",className:"text-sm text-white/80 hover:text-white transition",children:"Map"}),e.jsx(In,{to:"/home-value",className:"text-sm text-white/80 hover:text-white transition",children:"Home Value"}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-sm px-4 py-2 rounded-full transition",style:{border:`1px solid ${vl}`,color:vl},children:"About LevelUp"})]}),e.jsx("button",{type:"button",onClick:()=>i(H=>!H),className:"md:hidden inline-flex items-center justify-center w-10 h-10 rounded-full",style:{border:`1px solid ${vl}`,color:vl},"aria-label":"Toggle menu","aria-expanded":a,children:a?e.jsx($n,{className:"w-5 h-5"}):e.jsx(KS,{className:"w-5 h-5"})})]}),a&&e.jsx("div",{className:"md:hidden border-t",style:{borderColor:"rgba(201,168,76,0.15)"},children:e.jsxs("nav",{className:"max-w-7xl mx-auto px-6 py-4 flex flex-col gap-1",children:[e.jsx("a",{href:"#featured",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Featured"}),e.jsx("a",{href:"#collection",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Collection"}),e.jsx("a",{href:"#map",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Map"}),e.jsx(In,{to:"/home-value",onClick:()=>i(!1),className:"py-3 text-white/85 hover:text-white transition border-b",style:{borderColor:"rgba(255,255,255,0.06)"},children:"Home Value"}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",onClick:()=>i(!1),className:"mt-3 text-center text-sm px-4 py-3 rounded-full",style:{border:`1px solid ${vl}`,color:vl},children:"About LevelUp"})]})})]}),e.jsxs("section",{className:"relative overflow-hidden lu-grain",style:{minHeight:"92vh"},children:[e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:z9t,alt:"Luxury home at dusk",className:"w-full h-full object-cover",style:{filter:"brightness(0.55) contrast(1.05)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(13,13,13,0.55) 0%, rgba(13,13,13,0.25) 40%, rgba(13,13,13,0.9) 100%)"}})]}),e.jsxs("div",{className:"relative max-w-7xl mx-auto px-6 pt-24 md:pt-32 pb-16 flex flex-col justify-center",style:{minHeight:"92vh"},children:[e.jsxs("div",{className:"max-w-4xl",children:[e.jsxs("div",{className:"lu-hero-title flex items-center gap-3 mb-6",children:[e.jsx("span",{className:"h-px w-10",style:{background:vl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The LevelUp Collection"})]}),e.jsxs("h1",{className:"lu-serif lu-hero-title text-white text-5xl sm:text-6xl md:text-7xl lg:text-8xl leading-[1.02] mb-6",children:["Homes with a",e.jsx("br",{}),e.jsx("span",{className:"italic",style:{color:vk},children:"quiet"})," kind of luxury."]}),e.jsx("p",{className:"lu-hero-sub text-white/75 text-lg md:text-xl max-w-2xl mb-10 leading-relaxed",children:"A private, hand-picked collection of properties represented by LevelUp agents — from waterfront estates to architectural landmarks and everything in between."}),e.jsxs("div",{className:"lu-hero-search max-w-3xl",ref:u,children:[e.jsxs("div",{className:"flex items-stretch rounded-full overflow-hidden shadow-2xl relative",style:{background:"rgba(13,13,13,0.7)",border:`1px solid ${vl}`,backdropFilter:"blur(12px)"},children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-5 w-5",style:{color:vl}}),e.jsx(ye,{placeholder:"City, neighborhood, or ZIP",value:s,onChange:H=>{t(H.target.value),o(!0),d(-1)},onFocus:()=>o(!0),onKeyDown:H=>{if(!(!l||y.length===0))if(H.key==="ArrowDown")H.preventDefault(),d(Z=>Math.min(Z+1,y.length-1));else if(H.key==="ArrowUp")H.preventDefault(),d(Z=>Math.max(Z-1,0));else if(H.key==="Enter"&&c>=0){H.preventDefault();const Z=y[c];t(Z.value),o(!1)}else H.key==="Escape"&&o(!1)},className:"pl-16 h-16 text-base md:text-lg border-0 bg-transparent text-white placeholder:text-white/50 focus-visible:ring-0 rounded-none"})]}),e.jsxs("button",{onClick:()=>r(!n),className:"hidden sm:flex items-center gap-2 px-6 border-l text-sm text-white/80 hover:text-white transition",style:{borderColor:"rgba(201,168,76,0.3)"},children:[e.jsx(e4,{className:"h-4 w-4"}),"Filters"]}),e.jsxs("button",{className:"px-8 flex items-center gap-2 font-medium transition hover:brightness-110",style:{background:vl,color:pI},onClick:()=>o(!1),children:[e.jsx(gr,{className:"h-5 w-5"}),e.jsx("span",{className:"hidden md:inline",children:"Search"})]})]}),l&&y.length>0&&e.jsxs("div",{className:"mt-2 rounded-2xl overflow-hidden shadow-2xl animate-fade-in",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.35)",backdropFilter:"blur(12px)"},children:[e.jsx("div",{className:"px-5 pt-3 pb-2 text-[10px] tracking-[0.2em] uppercase",style:{color:vl},children:"Suggestions"}),e.jsx("ul",{className:"max-h-80 overflow-y-auto",children:y.map((H,Z)=>e.jsx("li",{children:e.jsxs("button",{type:"button",onMouseEnter:()=>d(Z),onClick:()=>{t(H.value),o(!1)},className:"w-full flex items-center justify-between gap-3 px-5 py-3 text-left transition",style:{background:c===Z?"rgba(201,168,76,0.12)":"transparent"},children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[H.type==="city"&&e.jsx(ka,{className:"h-4 w-4 shrink-0",style:{color:vl}}),H.type==="neighborhood"&&e.jsx(Ua,{className:"h-4 w-4 shrink-0",style:{color:vl}}),H.type==="zip"&&e.jsx(Or,{className:"h-4 w-4 shrink-0",style:{color:vl}}),e.jsx("span",{className:"text-white/90 truncate",children:H.label})]}),e.jsxs("span",{className:"text-xs text-white/50 shrink-0",children:[H.count," ",H.count===1?"listing":"listings"]})]})},`${H.type}-${H.value}-${Z}`))})]}),l&&s.trim()&&y.length===0&&e.jsx("div",{className:"mt-2 rounded-2xl px-5 py-4 text-sm text-white/70",style:{background:"rgba(13,13,13,0.96)",border:"1px solid rgba(201,168,76,0.25)"},children:"No matches yet — try a nearby city or ZIP."}),n&&e.jsxs("div",{className:"mt-4 p-6 rounded-2xl grid sm:grid-cols-2 md:grid-cols-4 gap-4 animate-fade-in",style:{background:"rgba(26,26,26,0.9)",border:"1px solid rgba(201,168,76,0.25)"},children:[e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Status"}),e.jsxs(us,{value:h.status||"all",onValueChange:H=>p({...h,status:H==="all"?"":H}),children:[e.jsx(ls,{className:"lu-input-dark",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"Any status"}),Object.entries(qwe).map(([H,Z])=>e.jsx(Ze,{value:H,children:Z},H))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Type"}),e.jsxs(us,{value:h.propertyType||"all",onValueChange:H=>p({...h,propertyType:H==="all"?"":H}),children:[e.jsx(ls,{className:"lu-input-dark",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"Any type"}),Object.entries(q9t).map(([H,Z])=>e.jsx(Ze,{value:H,children:Z},H))]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Min Price"}),e.jsx(ye,{type:"number",placeholder:"No min",value:h.minPrice,onChange:H=>p({...h,minPrice:H.target.value}),className:"lu-input-dark"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"lu-eyebrow text-white/60 mb-2 block",children:"Max Price"}),e.jsx(ye,{type:"number",placeholder:"No max",value:h.maxPrice,onChange:H=>p({...h,maxPrice:H.target.value}),className:"lu-input-dark"})]}),S&&e.jsx("div",{className:"sm:col-span-2 md:col-span-4 flex justify-end",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:w,className:"text-white/70 hover:text-white gap-1",children:[e.jsx($n,{className:"h-4 w-4"})," Clear all"]})})]})]}),e.jsx("div",{className:"lu-hero-stats mt-14 grid grid-cols-3 gap-6 max-w-2xl",children:[{label:"Listings",value:((_==null?void 0:_.length)??0).toString()},{label:"Active Now",value:z.toString()},{label:"Luxury $1M+",value:I.toString()}].map(H=>e.jsxs("div",{children:[e.jsx("div",{className:"lu-serif text-4xl md:text-5xl",style:{color:vk},children:H.value}),e.jsx("div",{className:"lu-eyebrow text-white/60 mt-1",children:H.label})]},H.label))})]}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 flex flex-col items-center gap-2 text-white/60",children:[e.jsx("span",{className:"lu-eyebrow",children:"Scroll"}),e.jsx(ao,{className:"h-4 w-4 animate-bounce"})]})]})]}),F.length>0&&e.jsx("section",{className:"py-8 overflow-hidden",style:{background:$ze,borderTop:"1px solid rgba(201,168,76,0.15)",borderBottom:"1px solid rgba(201,168,76,0.15)"},children:e.jsx("div",{className:"lu-marquee whitespace-nowrap",children:[...F,...F,...F].map((H,Z)=>e.jsxs("span",{className:"flex items-center gap-3 lu-serif text-2xl md:text-3xl text-white/40",children:[H,e.jsx("span",{className:"h-1.5 w-1.5 rounded-full",style:{background:vl}})]},Z))})}),O&&e.jsx("section",{id:"featured",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"flex items-end justify-between mb-10 md:mb-14",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx(un,{className:"h-4 w-4",style:{color:vl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Today's Featured Residence"})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl",children:["Today's ",e.jsx("span",{className:"italic",style:{color:vk},children:"standout"}),"."]})]}),e.jsx("div",{className:"hidden md:block h-px flex-1 mx-8 lu-gold-line"})]}),e.jsx(In,{to:E(O),className:"group block",children:e.jsxs("div",{className:"grid lg:grid-cols-5 gap-6 lg:gap-10 items-stretch",children:[e.jsxs("div",{className:"lg:col-span-3 relative overflow-hidden rounded-2xl aspect-[4/3] bg-black",children:[(()=>{var Z,Y;const H=((Z=O.photos)==null?void 0:Z.find(W=>W.is_primary))||((Y=O.photos)==null?void 0:Y[0]);return H?e.jsx("img",{src:H.photo_url,alt:O.property_address||O.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Or,{className:"h-16 w-16 text-white/20"})})})(),e.jsx("div",{className:"absolute top-5 left-5 px-4 py-1.5 rounded-full lu-eyebrow",style:{background:vl,color:pI},children:qwe[O.status]||"Featured"})]}),e.jsxs("div",{className:"lg:col-span-2 flex flex-col justify-center",children:[e.jsxs("div",{className:"lu-eyebrow text-white/60 mb-4 flex items-center gap-2",children:[e.jsx(ka,{className:"h-3.5 w-3.5",style:{color:vl}}),O.city,O.state?`, ${O.state}`:""]}),O.property_address&&e.jsx("h3",{className:"lu-serif text-3xl md:text-4xl mb-4 leading-tight",children:O.property_address}),e.jsx("div",{className:"lu-serif text-5xl md:text-6xl mb-6",style:{color:vk},children:j(O.price)}),e.jsxs("div",{className:"flex items-center gap-6 text-white/70 mb-8",children:[O.bedrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(J0,{className:"h-4 w-4",style:{color:vl}}),O.bedrooms," bd"]}),O.bathrooms&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(kp,{className:"h-4 w-4",style:{color:vl}}),O.bathrooms," ba"]}),O.square_footage&&e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(ay,{className:"h-4 w-4",style:{color:vl}}),O.square_footage.toLocaleString()," sf"]})]}),O.description&&e.jsx("p",{className:"text-white/60 leading-relaxed mb-8 line-clamp-4",children:O.description}),e.jsxs("div",{className:"inline-flex items-center gap-3 lu-eyebrow group-hover:gap-5 transition-all",style:{color:vl},children:["View Residence ",e.jsx(Oa,{className:"h-4 w-4"})]})]})]})})]})}),e.jsx("section",{id:"collection",className:"py-20 md:py-28",style:{background:$ze},children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsxs("div",{className:"text-center mb-14",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-4",children:[e.jsx("span",{className:"h-px w-10",style:{background:vl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"The Collection"}),e.jsx("span",{className:"h-px w-10",style:{background:vl}})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl lg:text-6xl mb-4",children:["Every home, ",e.jsx("span",{className:"italic",style:{color:vk},children:"carefully considered"}),"."]}),e.jsx("p",{className:"text-white/60 max-w-2xl mx-auto",children:"Browse the full catalogue of LevelUp-represented properties. Filter, refine, and find the one that feels like yours."})]}),v?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-8",children:[...Array(6)].map((H,Z)=>e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ws,{className:"aspect-[4/5] bg-white/5"}),e.jsx(Ws,{className:"h-6 w-32 bg-white/5"}),e.jsx(Ws,{className:"h-4 w-full bg-white/5"})]},Z))}):D.length>0?e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-x-8 gap-y-14",children:D.map(H=>{var Y,W,ee,se,oe;const Z=((Y=H.photos)==null?void 0:Y.find(he=>he.is_primary))||((W=H.photos)==null?void 0:W[0]);return e.jsxs(In,{to:E(H),className:"group lu-card-hover block",children:[e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden bg-black mb-5 rounded-lg",children:[Z?e.jsx("img",{src:Z.photo_url,alt:H.property_address||H.city,className:"w-full h-full object-cover lu-img-zoom"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Or,{className:"h-12 w-12 text-white/20"})}),e.jsx("div",{className:"absolute inset-0 opacity-0 group-hover:opacity-100 transition-opacity",style:{background:"linear-gradient(180deg, transparent 40%, rgba(13,13,13,0.85) 100%)"}}),e.jsx("div",{className:"absolute top-4 left-4 px-3 py-1 lu-eyebrow rounded-full",style:{background:"rgba(13,13,13,0.75)",color:vl,border:`1px solid ${vl}`},children:qwe[H.status]}),e.jsxs("div",{className:"absolute bottom-4 left-4 right-4 flex items-center gap-4 text-white/90 text-sm opacity-0 group-hover:opacity-100 translate-y-2 group-hover:translate-y-0 transition-all",children:[H.bedrooms&&e.jsxs("span",{children:[H.bedrooms," bd"]}),H.bathrooms&&e.jsxs("span",{children:[H.bathrooms," ba"]}),H.square_footage&&e.jsxs("span",{children:[H.square_footage.toLocaleString()," sf"]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"lu-eyebrow text-white/50 mb-2 flex items-center gap-2",children:[e.jsx(ka,{className:"h-3 w-3",style:{color:vl}}),H.city,H.state?`, ${H.state}`:""]}),e.jsx("div",{className:"lu-serif text-2xl md:text-3xl mb-1",style:{color:vk},children:j(H.price)}),H.property_address&&e.jsx("p",{className:"text-white/70 text-sm truncate",children:H.property_address}),((ee=H.agent)==null?void 0:ee.name)&&e.jsxs("p",{className:"text-white/40 text-xs mt-3 flex items-center gap-2",children:[e.jsx(Ua,{className:"h-3 w-3"}),H.agent.name,(((se=H.agent.brokerage)==null?void 0:se.name)||H.agent.brokerage_name)&&e.jsxs("span",{className:"truncate",children:["· ",((oe=H.agent.brokerage)==null?void 0:oe.name)||H.agent.brokerage_name]})]})]})]},H.id)})}):e.jsxs("div",{className:"text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 mx-auto mb-6 rounded-full flex items-center justify-center",style:{border:`1px solid ${vl}`},children:e.jsx(Or,{className:"h-8 w-8",style:{color:vl}})}),e.jsx("h3",{className:"lu-serif text-2xl mb-2",children:"No listings match yet"}),e.jsx("p",{className:"text-white/60 mb-6",children:"Adjust your search — or check back soon for new arrivals."}),S&&e.jsx(B,{onClick:w,style:{background:vl,color:pI},className:"hover:brightness-110",children:"Clear filters"})]})]})}),_&&_.length>0&&e.jsx("section",{id:"map",className:"py-20 md:py-28",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6",children:[e.jsx("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-10",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("span",{className:"h-px w-10",style:{background:vl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Explore"})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-5xl",children:["Every listing, ",e.jsx("span",{className:"italic",style:{color:vk},children:"on the map"}),"."]})]})}),e.jsx("div",{className:"rounded-2xl overflow-hidden",style:{border:"1px solid rgba(201,168,76,0.2)"},children:e.jsx(U9t,{listings:_,isLoading:v})})]})}),e.jsxs("section",{className:"relative py-24 md:py-32 overflow-hidden lu-grain",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`radial-gradient(ellipse at center, rgba(201,168,76,0.15) 0%, ${pI} 70%)`}}),e.jsxs("div",{className:"relative max-w-4xl mx-auto px-6 text-center",children:[e.jsxs("div",{className:"flex items-center justify-center gap-3 mb-6",children:[e.jsx("span",{className:"h-px w-10",style:{background:vl}}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"For Agents"}),e.jsx("span",{className:"h-px w-10",style:{background:vl}})]}),e.jsxs("h2",{className:"lu-serif text-4xl md:text-6xl mb-6 leading-tight",children:["Your listings deserve a",e.jsx("br",{}),e.jsx("span",{className:"italic",style:{color:vk},children:"stage this good"}),"."]}),e.jsx("p",{className:"text-white/70 text-lg mb-10 max-w-2xl mx-auto",children:"Join LevelUp and get every listing published to this collection — with a cinematic microsite, lead capture, and marketing tools that do the heavy lifting."}),e.jsxs("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-3 px-8 py-4 rounded-full font-medium transition hover:brightness-110",style:{background:vl,color:pI},children:["Explore LevelUp",e.jsx(Oa,{className:"h-4 w-4"})]})]})]}),e.jsx("footer",{className:"py-14",style:{background:"#080808",borderTop:"1px solid rgba(201,168,76,0.15)"},children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 flex flex-col md:flex-row items-center justify-between gap-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:Kpe,alt:"LevelUp",className:"h-6"}),e.jsx("span",{className:"h-4 w-px bg-white/20"}),e.jsx("span",{className:"lu-eyebrow lu-gold",children:"Listings"})]}),e.jsxs("p",{className:"text-white/40 text-sm",children:["© ",new Date().getFullYear()," LevelUp. All rights reserved."]}),e.jsx("a",{href:"https://relevelup.com",target:"_blank",rel:"noopener noreferrer",className:"text-white/60 hover:text-white text-sm transition",children:"relevelup.com →"})]})})]}),e.jsx(P7t,{}),e.jsx(L7t,{})]})}const V9t=N.lazy(()=>xi(()=>import("./PublicHomeValue-Ddnk4e6h.js"),[]));function H9t(){const s=Xl(),t=window.location.hostname;if(!(t==="listings.relevelup.com"||t.startsWith("listings.")))return null;const r=s.pathname.slice(1);return!r||r===""?e.jsx(Vlt,{}):r==="home-value"||r==="whats-my-home-worth"?e.jsx(N.Suspense,{fallback:e.jsx("div",{}),children:e.jsx(V9t,{})}):r.startsWith("public/")?null:e.jsx($lt,{slugOverride:r})}function K0e({card:s,variant:t}){const n=s.brokerage_display_name||s.brokerage_logo_url,r=s.team_name||s.team_logo_url;if(!n&&!r)return null;const a={standard:{container:"bg-slate-50 border border-slate-100",text:"text-slate-600",subtext:"text-slate-400"},luxury:{container:"bg-[#1e2636] border border-[#c9a84c]/10",text:"text-[#e2e8f0]",subtext:"text-[#4a5568]"},bold:{container:"bg-gray-50 border border-gray-100",text:"text-[#1a1a2e]",subtext:"text-gray-400"},classic:{container:"bg-white border border-[#d4cfc5] shadow-sm",text:"text-[#1b3a4b]",subtext:"text-[#a0aec0]"}}[t];return e.jsx("div",{className:`rounded-2xl p-4 mb-6 ${a.container}`,children:e.jsxs("div",{className:`flex flex-col items-center gap-3 ${n&&r?"divide-y divide-current/10":""}`,children:[n&&e.jsxs("div",{className:"flex flex-col items-center gap-1.5 w-full",children:[s.brokerage_logo_url&&e.jsx("img",{src:s.brokerage_logo_url,alt:s.brokerage_display_name||"Brokerage",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[280px] object-contain"}),s.brokerage_display_name&&!s.brokerage_logo_url&&e.jsx("p",{className:`text-sm font-medium ${a.text}`,children:s.brokerage_display_name})]}),r&&e.jsxs("div",{className:`flex flex-col items-center gap-1.5 w-full ${n?"pt-3":""}`,children:[s.team_logo_url&&e.jsx("img",{src:s.team_logo_url,alt:s.team_name||"Team",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[280px] object-contain"}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:`text-sm font-medium ${a.text}`,children:s.team_name})]})]})})}const Hlt=s=>dt({queryKey:["agent-card-public",s],queryFn:async()=>{if(!s)throw new Error("No slug provided");const{data:t,error:n}=await q.from("agent_cards").select("*").eq("slug",s).eq("is_published",!0).single();if(n)throw n;const{data:r}=await q.from("profiles").select("name, email, phone, brokerage_id").eq("id",t.user_id).single();let a=null;if(r!=null&&r.brokerage_id){const{data:o}=await q.from("brokerages").select("name").eq("id",r.brokerage_id).single();a=(o==null?void 0:o.name)||null}let i=null;try{const{data:o}=await q.from("profiles").select("avatar_url").eq("id",t.user_id).single();if(o!=null&&o.avatar_url)i=o.avatar_url;else{const{data:c}=await q.storage.from("avatars").list(`${t.user_id}`);if(c&&c.length>0){const{data:d}=q.storage.from("avatars").getPublicUrl(`${t.user_id}/${c[0].name}`);i=`${d.publicUrl}?t=${Date.now()}`}}}catch{}const l={...r||{name:null,email:null,phone:null,brokerage_id:null},email:t.display_email||(r==null?void 0:r.email)||null};return{...t,social_links:t.social_links||[],profile:l,brokerage_name:t.brokerage_display_name||a,avatar_url:i}},enabled:!!s}),G9t=()=>dt({queryKey:["agent-cards-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("agent_cards").select("*").order("created_at",{ascending:!1});if(t)throw t;return s}}),W9t=s=>dt({queryKey:["agent-card",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_cards").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),Glt=()=>{const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("agent_cards").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ae.success("Agent card created")},onError:t=>ae.error(t.message)})},Wlt=()=>{const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_cards").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["agent-cards-admin"]}),s.invalidateQueries({queryKey:["agent-card"]}),ae.success("Agent card updated")},onError:t=>ae.error(t.message)})},hl=async(s,t,n,r)=>{const a=new URLSearchParams(window.location.search);await q.from("agent_card_interactions").insert({card_id:s,interaction_type:t,interaction_detail:n||null,referrer:document.referrer||null,user_agent:navigator.userAgent||null,utm_source:a.get("utm_source")||null,utm_medium:a.get("utm_medium")||null,utm_campaign:a.get("utm_campaign")||null,metadata:{}})},K9t=async(s,t)=>{const{error:n}=await q.from("agent_card_leads").insert({card_id:s,...t});if(n)throw n},Klt=s=>dt({queryKey:["agent-card-analytics",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_card_interactions").select("interaction_type, interaction_detail, created_at").eq("card_id",s).order("created_at",{ascending:!1}).limit(500);if(n)throw n;const{data:r,error:a}=await q.from("agent_card_leads").select("*").eq("card_id",s).order("created_at",{ascending:!1});if(a)throw a;const i=(t==null?void 0:t.filter(c=>c.interaction_type==="card_view").length)||0,l=(t==null?void 0:t.filter(c=>c.interaction_type==="button_click").length)||0,o=(t==null?void 0:t.filter(c=>c.interaction_type==="contact_saved").length)||0;return{views:i,clicks:l,saves:o,leads:r||[],interactions:t||[]}},enabled:!!s});function Y0e({open:s,onOpenChange:t,cardId:n,type:r,agentName:a}){const[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(!1),j=async w=>{if(w.preventDefault(),!i.trim()){ae.error("Please enter your name");return}v(!0);try{await K9t(n,{lead_type:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}),hl(n,"lead_submitted",r),q.functions.invoke("card-lead-notify",{body:{cardId:n,leadType:r,name:i.trim(),email:o.trim()||void 0,phone:d.trim()||void 0,message:f.trim()||void 0,intent:h||void 0}}).catch(S=>console.error("Card lead notify failed:",S)),ae.success(r==="booking"?"Request sent! They'll be in touch soon.":r==="connect"?"Info shared! They'll be in touch soon.":"Referral submitted! Thank you."),t(!1),l(""),c(""),u(""),p(""),y("")}catch{ae.error("Something went wrong. Please try again.")}finally{v(!1)}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-md rounded-2xl",children:[e.jsxs(js,{children:[e.jsx(ws,{children:r==="booking"?"Book a Call":r==="connect"?"Connect with Me":"Refer a Friend"}),e.jsx(Jn,{children:r==="booking"?`Let ${a} know you'd like to connect.`:r==="connect"?`Share your info and ${a} will reach out.`:`Know someone who could use ${a}'s help?`})]}),e.jsxs("form",{onSubmit:j,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"lead-name",children:"Name *"}),e.jsx(ye,{id:"lead-name",value:i,onChange:w=>l(w.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"lead-phone",children:"Phone"}),e.jsx(ye,{id:"lead-phone",type:"tel",value:d,onChange:w=>u(w.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"lead-email",children:"Email"}),e.jsx(ye,{id:"lead-email",type:"email",value:o,onChange:w=>c(w.target.value),placeholder:"you@example.com"})]}),r==="booking"&&e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"lead-intent",children:"I'm looking to..."}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select one"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"buy",children:"Buy a home"}),e.jsx(Ze,{value:"sell",children:"Sell my home"}),e.jsx(Ze,{value:"both",children:"Buy & Sell"}),e.jsx(Ze,{value:"other",children:"Something else"})]})]})]}),r!=="connect"&&e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"lead-message",children:r==="referral"?"Tell us about them":"Message (optional)"}),e.jsx(ye,{id:"lead-message",value:f,onChange:w=>y(w.target.value),placeholder:r==="referral"?"Their name, phone, situation...":"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full rounded-2xl",disabled:_,children:_?"Sending...":"Submit"})]})]})})}const Y9t=s=>dt({queryKey:["card-blocks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).eq("is_visible",!0).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Z9t=s=>dt({queryKey:["card-blocks-all",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("card_blocks").select("*").eq("card_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s}),Q9t=()=>{const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("card_blocks").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["card-blocks",n.card_id]}),s.invalidateQueries({queryKey:["card-blocks-all",n.card_id]}),ae.success("Block added")},onError:t=>ae.error(t.message)})},X9t=()=>{const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("card_blocks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block updated")},onError:t=>ae.error(t.message)})},J9t=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("card_blocks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["card-blocks"]}),s.invalidateQueries({queryKey:["card-blocks-all"]}),ae.success("Block removed")},onError:t=>ae.error(t.message)})};function ezt(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 tzt(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 szt={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 nzt({block:s,variant:t}){const n=s.config;if(!n.video_url)return null;const r=n.video_url.includes("mediadelivery.net")||n.video_url.includes("bunnycdn.com"),a=tzt(n.video_url),i=r||!!a,l=r?ezt(n.video_url):a||n.video_url;return e.jsx("div",{className:szt[t],children:i?e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:l,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsx("video",{src:n.video_url,controls:!0,className:"w-full",preload:"metadata"})})}const rzt={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 azt({block:s,variant:t}){const r=s.config.testimonials||[],[a,i]=N.useState(0);if(r.length===0)return null;const l=rzt[t],o=r[a];return e.jsxs("div",{className:l.container,children:[e.jsxs("div",{className:l.card,children:[e.jsx(gw,{className:"h-4 w-4 mb-2 opacity-30"}),e.jsxs("p",{className:`${l.quote} mb-3`,children:['"',o.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:l.name,children:o.name}),o.role&&e.jsx("p",{className:l.role,children:o.role})]})]}),r.length>1&&e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-3",children:[e.jsx("button",{onClick:()=>i(c=>(c-1+r.length)%r.length),className:l.nav,children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex gap-1.5",children:r.map((c,d)=>e.jsx("div",{className:`h-1.5 w-1.5 rounded-full transition-colors cursor-pointer ${d===a?l.dot:l.dotInactive}`,onClick:()=>i(d)},d))}),e.jsx("button",{onClick:()=>i(c=>(c+1)%r.length),className:l.nav,children:e.jsx(ga,{className:"h-4 w-4"})})]})]})}const izt={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 ozt({block:s,variant:t}){const r=s.config.tags||[];if(r.length===0)return null;const a=izt[t];return e.jsx("div",{className:a.container,children:r.map((i,l)=>e.jsx("span",{className:a.tag,children:i},l))})}const lzt={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 czt({block:s,cardId:t,variant:n}){const a=s.config.links||[];if(a.length===0)return null;const i=lzt[n];return e.jsx("div",{className:i.container,children:a.map((l,o)=>e.jsxs("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>hl(t,"button_click",`custom_link_${l.label}`),className:i.link,children:[e.jsx("span",{children:l.label}),e.jsx(tr,{className:`h-4 w-4 ${i.icon}`})]},o))})}const p4e={instagram:{label:"Instagram",icon:"M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zM12 0C8.741 0 8.333.014 7.053.072 2.695.272.273 2.69.073 7.052.014 8.333 0 8.741 0 12c0 3.259.014 3.668.072 4.948.2 4.358 2.618 6.78 6.98 6.98C8.333 23.986 8.741 24 12 24c3.259 0 3.668-.014 4.948-.072 4.354-.2 6.782-2.618 6.979-6.98.059-1.28.073-1.689.073-4.948 0-3.259-.014-3.667-.072-4.947-.196-4.354-2.617-6.78-6.979-6.98C15.668.014 15.259 0 12 0zm0 5.838a6.162 6.162 0 100 12.324 6.162 6.162 0 000-12.324zM12 16a4 4 0 110-8 4 4 0 010 8zm6.406-11.845a1.44 1.44 0 100 2.881 1.44 1.44 0 000-2.881z",color:"#E4405F",hoverBg:"hover:bg-[#E4405F]/10"},facebook:{label:"Facebook",icon:"M24 12.073c0-6.627-5.373-12-12-12s-12 5.373-12 12c0 5.99 4.388 10.954 10.125 11.854v-8.385H7.078v-3.47h3.047V9.43c0-3.007 1.792-4.669 4.533-4.669 1.312 0 2.686.235 2.686.235v2.953H15.83c-1.491 0-1.956.925-1.956 1.874v2.25h3.328l-.532 3.47h-2.796v8.385C19.612 23.027 24 18.062 24 12.073z",color:"#1877F2",hoverBg:"hover:bg-[#1877F2]/10"},linkedin:{label:"LinkedIn",icon:"M20.447 20.452h-3.554v-5.569c0-1.328-.027-3.037-1.852-3.037-1.853 0-2.136 1.445-2.136 2.939v5.667H9.351V9h3.414v1.561h.046c.477-.9 1.637-1.85 3.37-1.85 3.601 0 4.267 2.37 4.267 5.455v6.286zM5.337 7.433c-1.144 0-2.063-.926-2.063-2.065 0-1.138.92-2.063 2.063-2.063 1.14 0 2.064.925 2.064 2.063 0 1.139-.925 2.065-2.064 2.065zm1.782 13.019H3.555V9h3.564v11.452zM22.225 0H1.771C.792 0 0 .774 0 1.729v20.542C0 23.227.792 24 1.771 24h20.451C23.2 24 24 23.227 24 22.271V1.729C24 .774 23.2 0 22.222 0h.003z",color:"#0A66C2",hoverBg:"hover:bg-[#0A66C2]/10"},twitter:{label:"X",icon:"M18.244 2.25h3.308l-7.227 8.26 8.502 11.24H16.17l-5.214-6.817L4.99 21.75H1.68l7.73-8.835L1.254 2.25H8.08l4.713 6.231zm-1.161 17.52h1.833L7.084 4.126H5.117z",color:"#000000",hoverBg:"hover:bg-black/10"},youtube:{label:"YouTube",icon:"M23.498 6.186a3.016 3.016 0 00-2.122-2.136C19.505 3.545 12 3.545 12 3.545s-7.505 0-9.377.505A3.017 3.017 0 00.502 6.186C0 8.07 0 12 0 12s0 3.93.502 5.814a3.016 3.016 0 002.122 2.136c1.871.505 9.376.505 9.376.505s7.505 0 9.377-.505a3.015 3.015 0 002.122-2.136C24 15.93 24 12 24 12s0-3.93-.502-5.814z M9.545 15.568V8.432L15.818 12z",color:"#FF0000",hoverBg:"hover:bg-[#FF0000]/10"},tiktok:{label:"TikTok",icon:"M12.525.02c1.31-.02 2.61-.01 3.91-.02.08 1.53.63 3.09 1.75 4.17 1.12 1.11 2.7 1.62 4.24 1.79v4.03c-1.44-.05-2.89-.35-4.2-.97-.57-.26-1.1-.59-1.62-.93-.01 2.92.01 5.84-.02 8.75-.08 1.4-.54 2.79-1.35 3.94-1.31 1.92-3.58 3.17-5.91 3.21-1.43.08-2.86-.31-4.08-1.03-2.02-1.19-3.44-3.37-3.65-5.71-.02-.5-.03-1-.01-1.49.18-1.9 1.12-3.72 2.58-4.96 1.66-1.44 3.98-2.13 6.15-1.72.02 1.48-.04 2.96-.04 4.44-.99-.32-2.15-.23-3.02.37-.63.41-1.11 1.04-1.36 1.75-.21.51-.15 1.07-.14 1.61.24 1.64 1.82 3.02 3.5 2.87 1.12-.01 2.19-.66 2.77-1.61.19-.33.4-.67.41-1.06.1-1.79.06-3.57.07-5.36.01-4.03-.01-8.05.02-12.07z",color:"#000000",hoverBg:"hover:bg-black/10"},zillow:{label:"Zillow",icon:"M12 0L1 6v12l11 6 11-6V6L12 0zm0 2.18L21 7.5v9L12 21.82 3 16.5v-9L12 2.18z",color:"#006AFF",hoverBg:"hover:bg-[#006AFF]/10"},realtor:{label:"Realtor",icon:"M12 2L2 7v10l10 5 10-5V7L12 2zm0 2.18l8 4v8l-8 4-8-4v-8l8-4z",color:"#D92228",hoverBg:"hover:bg-[#D92228]/10"},spotify:{label:"Spotify",icon:"M12 0C5.4 0 0 5.4 0 12s5.4 12 12 12 12-5.4 12-12S18.66 0 12 0zm5.521 17.34c-.24.359-.66.48-1.021.24-2.82-1.74-6.36-2.101-10.561-1.141-.418.122-.779-.179-.899-.539-.12-.421.18-.78.54-.9 4.56-1.021 8.52-.6 11.64 1.32.42.18.479.659.301 1.02zm1.44-3.3c-.301.42-.841.6-1.262.3-3.239-1.98-8.159-2.58-11.939-1.38-.479.12-1.02-.12-1.14-.6-.12-.48.12-1.021.6-1.141C9.6 9.9 15 10.561 18.72 12.84c.361.181.54.78.241 1.2zm.12-3.36C15.24 8.4 8.82 8.16 5.16 9.301c-.6.179-1.2-.181-1.38-.721-.18-.601.18-1.2.72-1.381 4.26-1.26 11.28-1.02 15.721 1.621.539.3.719 1.02.419 1.56-.299.421-1.02.599-1.559.3z",color:"#1DB954",hoverBg:"hover:bg-[#1DB954]/10"},apple_music:{label:"Apple Music",icon:"M23.994 6.124a9.23 9.23 0 00-.24-2.19c-.317-1.31-1.062-2.31-2.18-3.043A5.022 5.022 0 0019.7.198a10.7 10.7 0 00-1.564-.15C17.637.017 17.14 0 12.002 0h-.004C6.858 0 6.362.017 5.862.047 5.34.08 4.82.13 4.309.325a5.017 5.017 0 00-1.874.826C1.317 2.07.573 3.07.255 4.38A9.234 9.234 0 00.02 6.57C-.013 7.068-.03 7.564 0 12.002v.004c-.03 4.438.013 4.934.047 5.432.033.522.083 1.042.278 1.554a5.017 5.017 0 00.826 1.874c.92 1.118 1.92 1.862 3.23 2.18a9.23 9.23 0 002.19.24c.498.03.994.013 5.432.047h.004c4.438.034 4.934-.013 5.432-.047a9.23 9.23 0 002.19-.24c1.31-.317 2.31-1.062 3.043-2.18a5.022 5.022 0 00.627-1.874c.195-.492.245-1.012.278-1.534.03-.498.047-.994.047-5.432v-.004c.034-4.438-.013-4.934-.047-5.432zM17.42 16.41c0 .612-.15 1.21-.44 1.758a3.58 3.58 0 01-1.207 1.31c-.518.339-1.09.521-1.705.545-.13.005-.26 0-.39-.017a2.617 2.617 0 01-1.653-.772 2.305 2.305 0 01-.668-1.653c-.005-.13 0-.26.017-.39.07-.52.275-.986.602-1.39a2.998 2.998 0 011.218-.94 3.14 3.14 0 011.12-.282c.17-.009.336.002.502.034V9.472L10.2 10.637v7.093c0 .612-.15 1.21-.44 1.758a3.58 3.58 0 01-1.207 1.31c-.518.339-1.09.521-1.705.545-.13.005-.26 0-.39-.017a2.617 2.617 0 01-1.653-.772A2.305 2.305 0 014.137 18.9c-.005-.13 0-.26.017-.39.07-.52.275-.986.602-1.39a2.998 2.998 0 011.218-.94 3.14 3.14 0 011.12-.282c.17-.009.336.002.502.034V8.377c0-.453.066-.903.195-1.34a3.2 3.2 0 01.694-1.204 2.62 2.62 0 011.063-.738c.39-.14.793-.208 1.196-.196l4.84-1.01v10.52z",color:"#FA243C",hoverBg:"hover:bg-[#FA243C]/10"}};function dzt({path:s,color:t,size:n=20}){return e.jsx("svg",{viewBox:"0 0 24 24",width:n,height:n,fill:t,children:e.jsx("path",{d:s})})}const uzt={standard:{container:"bg-white rounded-2xl border border-slate-100 p-5 mb-6 shadow-sm",title:"text-sm font-semibold text-slate-800 mb-3",linkClass:"h-11 w-11 rounded-xl bg-slate-50 border border-slate-100 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:shadow-md"},luxury:{container:"bg-zinc-900/50 backdrop-blur rounded-2xl border border-amber-900/20 p-5 mb-6",title:"text-sm font-semibold text-amber-200/80 mb-3",linkClass:"h-11 w-11 rounded-xl bg-zinc-800/80 border border-amber-900/20 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:border-amber-500/40 hover:shadow-md hover:shadow-amber-500/10"},bold:{container:"bg-white/10 backdrop-blur rounded-2xl border border-white/20 p-5 mb-6",title:"text-sm font-semibold text-white/90 mb-3",linkClass:"h-11 w-11 rounded-xl bg-white/10 border border-white/20 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:bg-white/20 hover:shadow-md"},classic:{container:"bg-stone-50 rounded-2xl border border-stone-200 p-5 mb-6",title:"text-sm font-semibold text-stone-800 mb-3",linkClass:"h-11 w-11 rounded-xl bg-white border border-stone-200 flex items-center justify-center transition-all duration-200 hover:scale-110 hover:shadow-md"}};function hzt({block:s,cardId:t,variant:n}){const a=s.config.platforms||[],i=uzt[n];return a.length===0?null:e.jsxs("div",{className:i.container,children:[e.jsx("h3",{className:i.title,children:"Follow Me"}),e.jsx("div",{className:"flex flex-wrap gap-3 justify-center",children:a.map((l,o)=>{const c=p4e[l.platform.toLowerCase()];return!c||!l.url?null:e.jsx("a",{href:l.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>hl(t,"button_click",`social_${l.platform}`),className:i.linkClass,title:c.label,children:e.jsx(dzt,{path:c.icon,color:c.color})},o)})})]})}function Z0e({cardId:s,variant:t}){const{data:n}=Y9t(s);if(!n||n.length===0)return null;const r=n.filter(l=>l.block_type==="social_media"&&l.is_visible),a=n.filter(l=>l.block_type!=="social_media"),i=r.length>0?{...r[0],config:{platforms:r.flatMap(l=>l.config.platforms||[])}}:null;return n.findIndex(l=>l.block_type==="social_media"),e.jsxs(e.Fragment,{children:[a.map(l=>{switch(l.block_type){case"video_intro":return e.jsx(nzt,{block:l,variant:t},l.id);case"testimonials":return e.jsx(azt,{block:l,variant:t},l.id);case"specialties":return e.jsx(ozt,{block:l,variant:t},l.id);case"custom_links":return e.jsx(czt,{block:l,cardId:s,variant:t},l.id);default:return null}}),i&&e.jsx(hzt,{block:i,cardId:s,variant:t})]})}async function mzt(s){try{const t=await fetch(s);if(!t.ok)return null;const n=await t.blob(),r=n.type||"image/jpeg";return new Promise(a=>{const i=new FileReader;i.onloadend=()=>{const o=i.result.split(",")[1];a({base64:o,mimeType:r})},i.onerror=()=>a(null),i.readAsDataURL(n)})}catch{return null}}function pzt(s){const t=s.trim().split(/\s+/);if(t.length<=1)return{first:t[0]||"",last:""};const n=t.pop();return{first:t.join(" "),last:n}}async function Q0e(s){const{first:t,last:n}=pzt(s.name),r=["BEGIN:VCARD","VERSION:3.0",`FN:${s.name}`,`N:${n};${t};;;`];if(s.phone&&r.push(`TEL;TYPE=CELL:${s.phone}`),s.email&&r.push(`EMAIL;TYPE=INTERNET:${s.email}`),s.brokerage&&r.push(`ORG:${s.brokerage}`),r.push(`URL:${s.cardUrl}`),s.avatarUrl){const o=await mzt(s.avatarUrl);if(o){const d={"image/jpeg":"JPEG","image/jpg":"JPEG","image/png":"PNG","image/gif":"GIF","image/webp":"JPEG"}[o.mimeType]||"JPEG";r.push(`PHOTO;ENCODING=b;TYPE=${d}:${o.base64}`)}}r.push("END:VCARD");const a=new Blob([r.join(`\r `)],{type:"text/vcard"}),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=`${s.name.replace(/\s+/g,"_")}.vcf`,l.click(),URL.revokeObjectURL(i),ae.success("Contact saved!")}function fzt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(w=>w[0]).join("").toUpperCase().slice(0,2),o=(w,S)=>{hl(s.id,"button_click",w),S()},c=()=>o("call",()=>{var w;(w=s.profile)!=null&&w.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var w;(w=s.profile)!=null&&w.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var w;(w=s.profile)!=null&&w.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),hl(s.id,"button_click","book"))},p=()=>{var w,S;hl(s.id,"contact_saved"),Q0e({name:i,phone:(w=s.profile)==null?void 0:w.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{hl(s.id,"share_event");const w=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:w})}catch{}else await navigator.clipboard.writeText(w),ae.success("Link copied!")},y=()=>{a("referral"),n(!0),hl(s.id,"button_click","refer")},_=()=>{a("connect"),n(!0),hl(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 via-white to-slate-50",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Jr,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ti,{src:s.avatar_url||void 0,alt:i}),e.jsx(ea,{className:"text-2xl font-semibold bg-primary text-primary-foreground",children:l})]}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900 mb-0.5",children:i}),s.title&&e.jsx("p",{className:"text-sm font-medium text-primary mb-1",children:s.title}),s.brokerage_name&&!s.brokerage_logo_url&&e.jsx("p",{className:"text-sm font-medium text-slate-500 mb-1",children:s.brokerage_name}),s.team_name&&!s.team_logo_url&&e.jsx("p",{className:"text-xs font-medium text-slate-400 mb-3",children:s.team_name}),s.positioning_statement&&e.jsxs("p",{className:"text-base text-slate-600 italic leading-relaxed max-w-xs mx-auto",children:['"',s.positioning_statement,'"']})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs(B,{onClick:c,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Cr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Call"})]}),e.jsxs(B,{onClick:d,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Ai,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Text"})]}),e.jsxs(B,{onClick:u,className:"flex flex-col items-center gap-1.5 h-auto py-4 bg-primary hover:bg-primary/90 text-primary-foreground rounded-2xl shadow-sm",children:[e.jsx(Gs,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs font-medium",children:"Email"})]})]}),e.jsxs(B,{onClick:h,className:"w-full h-12 text-base font-semibold rounded-2xl shadow-sm mb-6",variant:"outline",children:[e.jsx(yr,{className:"h-5 w-5 mr-2"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm text-slate-600",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(oa,{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(K0e,{card:s,variant:"standard"}),e.jsx(Z0e,{cardId:s.id,variant:"standard"}),e.jsxs("div",{className:"space-y-2 mb-6",children:[s.show_save_contact&&e.jsxs(B,{variant:"ghost",onClick:p,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Ia,{className:"h-4 w-4 mr-3 text-primary"}),"Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs(B,{variant:"ghost",onClick:()=>{hl(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(oa,{className:"h-4 w-4 mr-3 text-amber-500"}),"Leave a Review"]}),s.show_refer_friend&&e.jsxs(B,{variant:"ghost",onClick:y,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(An,{className:"h-4 w-4 mr-3 text-primary"}),"Refer a Friend"]}),e.jsxs(B,{variant:"ghost",onClick:_,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Fo,{className:"h-4 w-4 mr-3 text-primary"}),"Connect with Me"]}),e.jsxs(B,{variant:"ghost",onClick:f,className:"w-full justify-start h-12 rounded-2xl text-slate-700 hover:bg-slate-100",children:[e.jsx(Vl,{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((w,S)=>e.jsx("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>hl(s.id,"button_click",`social_${w.platform}`),className:"h-10 w-10 rounded-full bg-slate-100 hover:bg-slate-200 flex items-center justify-center text-lg transition-colors",children:v[w.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-slate-400",children:"Powered by LevelUp"})})]}),e.jsx(Y0e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function xzt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(w=>w[0]).join("").toUpperCase().slice(0,2),o=(w,S)=>{hl(s.id,"button_click",w),S()},c=()=>o("call",()=>{var w;(w=s.profile)!=null&&w.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var w;(w=s.profile)!=null&&w.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var w;(w=s.profile)!=null&&w.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),hl(s.id,"button_click","book"))},p=()=>{var w,S;hl(s.id,"contact_saved"),Q0e({name:i,phone:(w=s.profile)==null?void 0:w.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{hl(s.id,"share_event");const w=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:w})}catch{}else await navigator.clipboard.writeText(w),ae.success("Link copied!")},y=()=>{a("referral"),n(!0),hl(s.id,"button_click","refer")},_=()=>{a("connect"),n(!0),hl(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-[#0f1419] via-[#1a1f2e] to-[#0f1419]",children:[e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsx("div",{className:"w-16 h-0.5 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] mx-auto mb-8"}),e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Jr,{className:"h-32 w-32 mx-auto mb-5 ring-2 ring-[#c9a84c]/40 shadow-2xl",children:[e.jsx(ti,{src:s.avatar_url||void 0,alt:i}),e.jsx(ea,{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:Cr,label:"Call",handler:c},{icon:Ai,label:"Text",handler:d},{icon:Gs,label:"Email",handler:u}].map(({icon:w,label:S,handler:A})=>e.jsxs("button",{onClick:A,className:"flex flex-col items-center gap-1.5 py-4 bg-[#1e2636] hover:bg-[#252d3f] border border-[#c9a84c]/20 rounded-xl transition-colors",children:[e.jsx(w,{className:"h-5 w-5 text-[#c9a84c]"}),e.jsx("span",{className:"text-xs font-medium text-[#e2e8f0]",children:S})]},S))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-xl mb-6 bg-gradient-to-r from-[#c9a84c] to-[#e8d48b] text-[#0f1419] hover:opacity-90 transition-opacity flex items-center justify-center gap-2",children:[e.jsx(yr,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-4 mb-6 text-sm",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(oa,{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(K0e,{card:s,variant:"luxury"}),e.jsx(Z0e,{cardId:s.id,variant:"luxury"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Ia,{className:"h-4 w-4 text-[#c9a84c]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{hl(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(oa,{className:"h-4 w-4 text-[#c9a84c]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(An,{className:"h-4 w-4 text-[#c9a84c]"})," Refer a Friend"]}),e.jsxs("button",{onClick:_,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Fo,{className:"h-4 w-4 text-[#c9a84c]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 rounded-xl text-[#e2e8f0] hover:bg-[#1e2636] transition-colors text-sm",children:[e.jsx(Vl,{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((w,S)=>e.jsx("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>hl(s.id,"button_click",`social_${w.platform}`),className:"h-10 w-10 rounded-full bg-[#1e2636] border border-[#c9a84c]/20 hover:border-[#c9a84c]/50 flex items-center justify-center text-lg transition-colors",children:v[w.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#4a5568]",children:"Powered by LevelUp"})})]}),e.jsx(Y0e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function gzt({card:s}){var S,A,E,O;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((S=s.profile)==null?void 0:S.name)||"Agent",l=i.split(" ").map(D=>D[0]).join("").toUpperCase().slice(0,2),o={accent:((A=s.bold_theme_colors)==null?void 0:A.accent)||"#ff5722",dark:((E=s.bold_theme_colors)==null?void 0:E.dark)||"#1a1a2e",button:((O=s.bold_theme_colors)==null?void 0:O.button)||"#ff5722"},c=(D,I)=>{const F=parseInt(D.replace("#",""),16),z=Math.max(0,(F>>16)-I),H=Math.max(0,(F>>8&255)-I),Z=Math.max(0,(F&255)-I);return`#${(z<<16|H<<8|Z).toString(16).padStart(6,"0")}`};c(o.accent,25),c(o.dark,-20),c(o.button,25);const d=(D,I)=>{hl(s.id,"button_click",D),I()},u=()=>d("call",()=>{var D;(D=s.profile)!=null&&D.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),h=()=>d("text",()=>{var D;(D=s.profile)!=null&&D.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),p=()=>d("email",()=>{var D;(D=s.profile)!=null&&D.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),f=()=>{s.booking_url?d("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),hl(s.id,"button_click","book"))},y=()=>{var D,I;hl(s.id,"contact_saved"),Q0e({name:i,phone:(D=s.profile)==null?void 0:D.phone,email:(I=s.profile)==null?void 0:I.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},_=async()=>{hl(s.id,"share_event");const D=`https://cards.relevelup.com/${s.slug}`,I="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:I,url:D})}catch{}else await navigator.clipboard.writeText(D),ae.success("Link copied!")},v=()=>{a("referral"),n(!0),hl(s.id,"button_click","refer")},j=()=>{a("connect"),n(!0),hl(s.id,"button_click","connect")},w={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(Jr,{className:"h-28 w-28 mx-auto mb-4 shadow-2xl",style:{boxShadow:`0 0 0 4px ${o.accent}`},children:[e.jsx(ti,{src:s.avatar_url||void 0,alt:i}),e.jsx(ea,{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:Cr,label:"Call",handler:u},{icon:Ai,label:"Text",handler:h},{icon:Gs,label:"Email",handler:p}].map(({icon:D,label:I,handler:F})=>e.jsxs("button",{onClick:F,className:"flex flex-col items-center gap-1.5 py-4 text-white rounded-2xl transition-opacity font-bold hover:opacity-85",style:{backgroundColor:o.dark},children:[e.jsx(D,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:I})]},I))}),e.jsxs("button",{onClick:f,className:"w-full h-14 text-base font-black rounded-2xl mb-6 text-white transition-opacity hover:opacity-90 flex items-center justify-center gap-2 uppercase tracking-wide",style:{backgroundColor:o.button},children:[e.jsx(yr,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"flex items-center justify-center gap-5 mb-6",children:s.review_snippet&&e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(oa,{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(K0e,{card:s,variant:"bold"}),e.jsx(Z0e,{cardId:s.id,variant:"bold"}),e.jsxs("div",{className:"space-y-1 mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Ia,{className:"h-4 w-4",style:{color:o.accent}})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{hl(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(oa,{className:"h-4 w-4",style:{color:o.accent}})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:v,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(An,{className:"h-4 w-4",style:{color:o.accent}})," Refer a Friend"]}),e.jsxs("button",{onClick:j,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Fo,{className:"h-4 w-4",style:{color:o.accent}})," Connect with Me"]}),e.jsxs("button",{onClick:_,className:"w-full flex items-center gap-3 h-12 px-4 rounded-2xl hover:bg-gray-100 transition-colors text-sm font-bold",style:{color:o.dark},children:[e.jsx(Vl,{className:"h-4 w-4",style:{color:o.accent}})," Share My Card"]})]}),s.show_social_links&&s.social_links&&s.social_links.length>0&&e.jsx("div",{className:"flex justify-center gap-4 mb-6",children:s.social_links.slice(0,3).map((D,I)=>e.jsx("a",{href:D.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>hl(s.id,"button_click",`social_${D.platform}`),className:"h-10 w-10 rounded-full flex items-center justify-center text-lg transition-opacity hover:opacity-85",style:{backgroundColor:o.dark},children:w[D.platform.toLowerCase()]||"🔗"},I))})]}),e.jsx("div",{className:"text-center py-6",children:e.jsx("p",{className:"text-xs text-white/50",children:"Powered by LevelUp"})})]}),e.jsx(Y0e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function yzt({card:s}){var j;const[t,n]=N.useState(!1),[r,a]=N.useState("booking"),i=((j=s.profile)==null?void 0:j.name)||"Agent",l=i.split(" ").map(w=>w[0]).join("").toUpperCase().slice(0,2),o=(w,S)=>{hl(s.id,"button_click",w),S()},c=()=>o("call",()=>{var w;(w=s.profile)!=null&&w.phone?window.location.href=`tel:${s.profile.phone}`:ae.error("Phone number not available")}),d=()=>o("text",()=>{var w;(w=s.profile)!=null&&w.phone?window.location.href=`sms:${s.profile.phone}`:ae.error("Phone number not available")}),u=()=>o("email",()=>{var w;(w=s.profile)!=null&&w.email?window.location.href=`mailto:${s.profile.email}`:ae.error("Email not available")}),h=()=>{s.booking_url?o("book",()=>window.open(s.booking_url,"_blank")):(a("booking"),n(!0),hl(s.id,"button_click","book"))},p=()=>{var w,S;hl(s.id,"contact_saved"),Q0e({name:i,phone:(w=s.profile)==null?void 0:w.phone,email:(S=s.profile)==null?void 0:S.email,brokerage:s.brokerage_name,avatarUrl:s.avatar_url,cardUrl:window.location.href})},f=async()=>{hl(s.id,"share_event");const w=`https://cards.relevelup.com/${s.slug}`,S="Here's my contact card — save it so we can stay in touch.";if(navigator.share)try{await navigator.share({title:`${i}`,text:S,url:w})}catch{}else await navigator.clipboard.writeText(w),ae.success("Link copied!")},y=()=>{a("referral"),n(!0),hl(s.id,"button_click","refer")},_=()=>{a("connect"),n(!0),hl(s.id,"button_click","connect")},v={instagram:"📸",facebook:"📘",linkedin:"💼",twitter:"🐦",youtube:"🎬",tiktok:"🎵"};return e.jsxs("div",{className:"min-h-screen bg-[#f5f1eb]",children:[e.jsx("div",{className:"bg-[#1b3a4b] h-2"}),e.jsxs("div",{className:"max-w-md mx-auto px-5 py-10",children:[e.jsxs("div",{className:"text-center mb-8",children:[s.show_photo&&e.jsxs(Jr,{className:"h-28 w-28 mx-auto mb-4 ring-4 ring-white shadow-lg",children:[e.jsx(ti,{src:s.avatar_url||void 0,alt:i}),e.jsx(ea,{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:Cr,label:"Call",handler:c},{icon:Ai,label:"Text",handler:d},{icon:Gs,label:"Email",handler:u}].map(({icon:w,label:S,handler:A})=>e.jsxs("button",{onClick:A,className:"flex flex-col items-center gap-1.5 py-4 bg-white hover:bg-[#e8e3db] border border-[#d4cfc5] rounded-lg transition-colors shadow-sm",children:[e.jsx(w,{className:"h-5 w-5 text-[#1b3a4b]"}),e.jsx("span",{className:"text-xs font-semibold text-[#1b3a4b]",children:S})]},S))}),e.jsxs("button",{onClick:h,className:"w-full h-12 text-base font-semibold rounded-lg mb-6 bg-[#1b3a4b] hover:bg-[#264d61] text-white transition-colors flex items-center justify-center gap-2 shadow-sm",children:[e.jsx(yr,{className:"h-5 w-5"}),s.custom_cta_label||"Book a Call"]}),s.show_credentials&&s.review_snippet&&e.jsx("div",{className:"bg-white rounded-lg border border-[#d4cfc5] p-4 mb-6 shadow-sm",children:e.jsx("div",{className:"flex items-center justify-center gap-6",children:e.jsxs("div",{className:"text-center flex items-center gap-1",children:[e.jsx(oa,{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(K0e,{card:s,variant:"classic"}),e.jsx(Z0e,{cardId:s.id,variant:"classic"}),e.jsxs("div",{className:"bg-white rounded-lg border border-[#d4cfc5] shadow-sm divide-y divide-[#e8e3db] mb-6",children:[s.show_save_contact&&e.jsxs("button",{onClick:p,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Ia,{className:"h-4 w-4 text-[#5a7a6f]"})," Save Contact"]}),s.show_leave_review&&s.review_source_url&&e.jsxs("button",{onClick:()=>{hl(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(oa,{className:"h-4 w-4 text-[#d4a843]"})," Leave a Review"]}),s.show_refer_friend&&e.jsxs("button",{onClick:y,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(An,{className:"h-4 w-4 text-[#5a7a6f]"})," Refer a Friend"]}),e.jsxs("button",{onClick:_,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Fo,{className:"h-4 w-4 text-[#5a7a6f]"})," Connect with Me"]}),e.jsxs("button",{onClick:f,className:"w-full flex items-center gap-3 h-12 px-4 text-[#1b3a4b] hover:bg-[#f5f1eb] transition-colors text-sm font-medium",children:[e.jsx(Vl,{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((w,S)=>e.jsx("a",{href:w.url,target:"_blank",rel:"noopener noreferrer",onClick:()=>hl(s.id,"button_click",`social_${w.platform}`),className:"h-10 w-10 rounded-full bg-white border border-[#d4cfc5] hover:bg-[#e8e3db] flex items-center justify-center text-lg transition-colors shadow-sm",children:v[w.platform.toLowerCase()]||"🔗"},S))}),e.jsx("div",{className:"text-center",children:e.jsx("p",{className:"text-xs text-[#a0aec0]",children:"Powered by LevelUp"})})]}),e.jsx(Y0e,{open:t,onOpenChange:n,cardId:s.id,type:r,agentName:i})]})}function DAe({card:s}){switch(s.theme){case"luxury":return e.jsx(xzt,{card:s});case"bold":return e.jsx(gzt,{card:s});case"classic":return e.jsx(yzt,{card:s});case"standard":default:return e.jsx(fzt,{card:s})}}function vzt(){const s=Xl();N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Agent Cards"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific agent's card URL to view their digital business card."})]})}):e.jsx(bzt,{slug:t})}function bzt({slug:s}){return e.jsx(_zt,{slug:s})}function _zt({slug:s}){var i;const{data:t,isLoading:n,error:r}=Hlt(s);if(N.useEffect(()=>{t!=null&&t.id&&hl(t.id,"card_view")},[t==null?void 0:t.id]),n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Ws,{className:"h-28 w-28 rounded-full"}),e.jsx(Ws,{className:"h-6 w-48"}),e.jsx(Ws,{className:"h-4 w-36"})]}),e.jsx(Ws,{className:"h-12 w-full"}),e.jsx(Ws,{className:"h-12 w-full"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{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(DAe,{card:t})]})}function Ylt({presentationId:s,ctaLabel:t,agentName:n,prefillName:r,prefillEmail:a,prefillPhone:i}){const[l,o]=N.useState(r||""),[c,d]=N.useState(a||""),[u,h]=N.useState(i||""),[p,f]=N.useState(""),[y,_]=N.useState(""),[v,j]=N.useState(!1),[w,S]=N.useState(!1),A=async E=>{if(E.preventDefault(),!l.trim()){ae.error("Please enter your name");return}j(!0);try{const{error:O}=await q.from("smart_presentation_leads").insert({presentation_id:s,name:l.trim(),email:c.trim()||null,phone:u.trim()||null,intent:p||null,message:y.trim()||null});if(O)throw O;try{await q.rpc("log_presentation_view",{p_presentation_id:s,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}q.functions.invoke("presentation-lead-notify",{body:{presentationId:s,name:l.trim(),email:c.trim()||void 0,phone:u.trim()||void 0,intent:p||void 0,message:y.trim()||void 0}}).catch(D=>console.error("Presentation lead notify failed:",D)),S(!0)}catch{ae.error("Something went wrong. Please try again.")}finally{j(!1)}};return w?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(Lr,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h3",{className:"text-xl font-semibold text-gray-900 mb-2",children:"Thank you!"}),e.jsx("p",{className:"text-gray-500",children:n?`${n} will be in touch soon.`:"We'll be in touch soon."})]}):e.jsxs("form",{onSubmit:A,className:"space-y-4 max-w-md mx-auto",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pres-lead-name",children:"Name *"}),e.jsx(ye,{id:"pres-lead-name",value:l,onChange:E=>o(E.target.value),placeholder:"Your name",required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pres-lead-phone",children:"Phone"}),e.jsx(ye,{id:"pres-lead-phone",type:"tel",value:u,onChange:E=>h(E.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pres-lead-email",children:"Email"}),e.jsx(ye,{id:"pres-lead-email",type:"email",value:c,onChange:E=>d(E.target.value),placeholder:"you@example.com"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pres-lead-intent",children:"I'm looking to..."}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select one"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"buy",children:"Buy a home"}),e.jsx(Ze,{value:"sell",children:"Sell my home"}),e.jsx(Ze,{value:"both",children:"Buy & Sell"}),e.jsx(Ze,{value:"other",children:"Something else"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pres-lead-message",children:"Message (optional)"}),e.jsx(ye,{id:"pres-lead-message",value:y,onChange:E=>_(E.target.value),placeholder:"Anything you'd like us to know"})]}),e.jsx(B,{type:"submit",className:"w-full text-lg py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",disabled:v,children:v?"Sending...":t})]})}function wzt(){const s=Xl();N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]);const t=s.pathname.slice(1);return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Smart Presentations"}),e.jsx("p",{className:"text-slate-500",children:"Visit a specific presentation URL to view it."})]})}):e.jsx(jzt,{shareToken:t})}function jzt({shareToken:s}){var y;const[t,n]=N.useState(null),[r,a]=N.useState(!0),[i,l]=N.useState(0),[o,c]=N.useState(!1);N.useEffect(()=>{d()},[s]);const d=async()=>{const{data:_,error:v}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(v||!_){c(!0),a(!1);return}const{data:j}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",_.owner_user_id).single();let w;if(j!=null&&j.brokerage_id){const{data:A}=await q.from("brokerages").select("name").eq("id",j.brokerage_id).single();w=(A==null?void 0:A.name)||void 0}let S=null;if(_.contact_id){const{data:A}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",_.contact_id).single();S=A}n({..._,owner_name:j==null?void 0:j.name,owner_email:j==null?void 0:j.email,owner_phone:j==null?void 0:j.phone,owner_avatar:j==null?void 0:j.avatar_url,owner_title:(j==null?void 0:j.title)||void 0,brokerage_name:w,contact_name:S?[S.first_name,S.last_name].filter(Boolean).join(" "):void 0,contact_email:(S==null?void 0:S.email)||void 0,contact_phone:(S==null?void 0:S.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:_.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}},h=_=>{const v=_.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(v)return`https://www.youtube.com/embed/${v[1]}?rel=0`;if(_.includes("iframe.mediadelivery.net/play/")){const S=_.replace("/play/","/embed/"),A=S.includes("?")?"&":"?";return`${S}${A}responsive=true`}if(_.includes("iframe.mediadelivery.net")){const S=_.includes("?")?"&":"?";return`${_}${S}responsive=true`}const j=_.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(j)return`https://www.loom.com/embed/${j[1]}`;const w=_.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return w?`https://iframe.mediadelivery.net/embed/${w[1]}/${w[2]}?responsive=true`:_};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(Ws,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const p=t.sections.filter(_=>_.is_visible!==!1),f=p[i];return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsx("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-end",children:e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[f!=null&&f.video_url?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:h(f.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):f!=null&&f.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:f.image_url,alt:f.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:f==null?void 0:f.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:f==null?void 0:f.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:f==null?void 0:f.description})]}),(f==null?void 0:f.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:f.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:p.map((_,v)=>e.jsx("button",{onClick:()=>l(v),className:Mt("w-full text-left p-4 rounded-xl border transition-all",i===v?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(v+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:_.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:_.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:_.description})]})]})},v))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),(y=t.cta_url)!=null&&y.trim()?e.jsxs(B,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(tr,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(Ylt,{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 Wv=()=>{const s=wa();return dt({queryKey:["user-team",s],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("id, team_id, role").eq("user_id",s).maybeSingle();if(console.log("[useUserTeam] membership query:",{userId:s,membership:t,error:n}),n)throw n;if(!t)return null;const{data:r,error:a}=await q.from("teams").select("*").eq("id",t.team_id).single();if(a)throw a;return{membershipId:t.id,teamId:t.team_id,role:t.role,team:r}},enabled:!!s,staleTime:5*60*1e3})};function Nzt(){const{user:s}=vs(),t=wa(),{data:n}=Wv();return dt({queryKey:["open-houses",t,n==null?void 0:n.teamId,n==null?void 0:n.role],queryFn:async()=>{const{data:r,error:a}=await q.from("open_houses").select("*").eq("agent_id",t).order("event_date",{ascending:!1});if(a)throw a;let i=r||[];if((n==null?void 0:n.role)==="team_leader"&&n.teamId){const{data:l,error:o}=await q.rpc("get_team_open_houses",{_user_id:t});if(!o&&l){const c=[...new Set(l.map(h=>h.agent_id))],d={};if(c.length>0){const{data:h}=await q.from("profiles").select("id, name").in("id",c);h==null||h.forEach(p=>{p.name&&(d[p.id]=p.name)})}const u=l.map(h=>({...h,agent_name:d[h.agent_id]||void 0}));i=[...i,...u]}}return i.sort((l,o)=>o.event_date.localeCompare(l.event_date)),i},enabled:!!s&&!!t})}function efn(s){const{user:t}=vs();return dt({queryKey:["open-house",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_houses").select("*").eq("id",s).single();if(r)throw r;return n},enabled:!!t&&!!s})}function Zlt(s){const{user:t}=vs(),n=Kt();return N.useEffect(()=>{if(!s)return;const r=`visitors-${s}-${Math.random().toString(36).slice(2,10)}`,a=q.channel(r).on("postgres_changes",{event:"*",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${s}`},()=>{n.invalidateQueries({queryKey:["open-house-visitors",s]}),n.invalidateQueries({queryKey:["open-houses"]})}).subscribe();return()=>{q.removeChannel(a)}},[s,n]),dt({queryKey:["open-house-visitors",s],queryFn:async()=>{const{data:r,error:a}=await q.from("open_house_visitors").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(a)throw a;return r},enabled:!!t&&!!s})}function kzt(){const s=Kt(),t=wa();return yt({mutationFn:async n=>{const{data:r,error:a}=await q.from("open_houses").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Br({title:"Open house created!"})},onError:n=>{Br({title:"Error",description:n.message,variant:"destructive"})}})}function Qlt(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{error:r}=await q.from("open_houses").update(n).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-houses"]}),s.invalidateQueries({queryKey:["open-house",n.id]})}})}function Szt(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("open_houses").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["open-houses"]}),Br({title:"Open house deleted"})}})}function Czt(s){return dt({queryKey:["public-open-house",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_houses").select("*, profiles:agent_id(name, avatar_url, title, email, phone)").eq("slug",s).eq("is_active",!0).single();if(n)throw n;let r=null;if(t.agent_id){const{data:a}=await q.from("agent_cards").select("slug").eq("user_id",t.agent_id).eq("is_published",!0).maybeSingle();a&&(r=a.slug)}return{...t,agent_card_slug:r}},enabled:!!s})}function Tzt(s){const{user:t}=vs();return dt({queryKey:["survey-questions",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;return n},enabled:!!t&&!!s})}function Ezt(s){return dt({queryKey:["public-survey-questions",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).eq("is_active",!0).order("sort_order");if(n)throw n;return t},enabled:!!s})}function Azt(){return yt({mutationFn:async s=>{const{error:t}=await q.from("open_house_survey_responses").insert(s);if(t)throw t}})}function Mzt(s){const{user:t}=vs();return dt({queryKey:["survey-responses",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_survey_questions").select("*").eq("open_house_id",s).order("sort_order");if(r)throw r;const a=(n||[]).map(o=>o.id);if(a.length===0)return{questions:[],responses:[]};const{data:i,error:l}=await q.from("open_house_survey_responses").select("*").in("question_id",a).order("created_at",{ascending:!1});if(l)throw l;return{questions:n,responses:i||[]}},enabled:!!t&&!!s})}function Izt(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_survey_questions").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function Pzt(){const s=Kt();return yt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_survey_questions").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function Lzt(){const s=Kt();return yt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_survey_questions").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n.open_house_id]})}})}function Dzt(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.rpc("seed_default_survey_questions",{_open_house_id:t});if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["survey-questions",n]})}})}function Rzt(){return yt({mutationFn:async s=>{const{data:t,error:n}=await q.from("open_house_visitors").insert(s).select("id").single();if(n)throw n;return t}})}function Ozt(){return yt({mutationFn:async({visitor_id:s,...t})=>{const{error:n}=await q.from("open_house_visitors").update(t).eq("id",s);if(n)throw n}})}function Fzt(){return yt({mutationFn:async s=>{await q.rpc("increment_open_house_scan",{_slug:s})}})}async function Xlt(s){const{data:t,error:n}=await q.from("open_house_rooms").select("*").eq("open_house_id",s).order("sort_order");if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(c=>c.id),{data:i,error:l}=await q.from("open_house_room_media").select("*").in("room_id",a).order("sort_order");if(l)throw l;const o={};return(i||[]).forEach(c=>{var u;const d=c;(o[u=d.room_id]||(o[u]=[])).push(d)}),r.map(c=>({...c,media:o[c.id]||[]}))}function zzt(s){const{user:t}=vs();return dt({queryKey:["open-house-rooms",s],queryFn:()=>Xlt(s),enabled:!!t&&!!s})}function Bzt(s){return dt({queryKey:["public-open-house-rooms",s],queryFn:()=>Xlt(s),enabled:!!s})}function $zt(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("open_house_rooms").insert(t).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function Uzt(){const s=Kt();return yt({mutationFn:async({id:t,open_house_id:n,...r})=>{const{error:a}=await q.from("open_house_rooms").update(r).eq("id",t);if(a)throw a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function qzt(){const s=Kt();return yt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_rooms").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function Vzt(){const s=Kt();return yt({mutationFn:async({open_house_id:t,...n})=>{const{data:r,error:a}=await q.from("open_house_room_media").insert(n).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function Hzt(){const s=Kt();return yt({mutationFn:async({id:t,open_house_id:n})=>{const{error:r}=await q.from("open_house_room_media").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["open-house-rooms",n.open_house_id]})}})}function Gzt(s){const{user:t}=vs();return dt({queryKey:["open-house-leads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_leads").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n||[]},enabled:!!t&&!!s})}function Wzt(){const s=Kt();return yt({mutationFn:async({id:t,status:n,open_house_id:r})=>{const{error:a}=await q.from("open_house_leads").update({status:n}).eq("id",t);if(a)throw a;return{open_house_id:r}},onSuccess:t=>{s.invalidateQueries({queryKey:["open-house-leads",t.open_house_id]})}})}var X0e="Switch",[Kzt,tfn]=uu(X0e),[Yzt,Zzt]=Kzt(X0e),Jlt=N.forwardRef((s,t)=>{const{__scopeSwitch:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c="on",onCheckedChange:d,form:u,...h}=s,[p,f]=N.useState(null),y=ji(t,S=>f(S)),_=N.useRef(!1),v=p?u||!!p.closest("form"):!0,[j,w]=cm({prop:a,defaultProp:i??!1,onChange:d,caller:X0e});return e.jsxs(Yzt,{scope:n,checked:j,disabled:o,children:[e.jsx(Yr.button,{type:"button",role:"switch","aria-checked":j,"aria-required":l,"data-state":nct(j),"data-disabled":o?"":void 0,disabled:o,value:c,...h,ref:y,onClick:xr(s.onClick,S=>{w(A=>!A),v&&(_.current=S.isPropagationStopped(),_.current||S.stopPropagation())})}),v&&e.jsx(sct,{control:p,bubbles:!_.current,name:r,value:c,checked:j,required:l,disabled:o,form:u,style:{transform:"translateX(-100%)"}})]})});Jlt.displayName=X0e;var ect="SwitchThumb",tct=N.forwardRef((s,t)=>{const{__scopeSwitch:n,...r}=s,a=Zzt(ect,n);return e.jsx(Yr.span,{"data-state":nct(a.checked),"data-disabled":a.disabled?"":void 0,...r,ref:t})});tct.displayName=ect;var Qzt="SwitchBubbleInput",sct=N.forwardRef(({__scopeSwitch:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=N.useRef(null),o=ji(l,i),c=G$(n),d=M$(t);return N.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&f){const y=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(y)}},[c,n,r]),e.jsx("input",{type:"checkbox","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});sct.displayName=Qzt;function nct(s){return s?"checked":"unchecked"}var rct=Jlt,Xzt=tct;const jn=N.forwardRef(({className:s,...t},n)=>e.jsx(rct,{className:Mt("peer inline-flex h-6 w-11 shrink-0 cursor-pointer items-center rounded-full border-2 border-transparent transition-colors data-[state=checked]:bg-primary data-[state=unchecked]:bg-input focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background disabled:cursor-not-allowed disabled:opacity-50",s),...t,ref:n,children:e.jsx(Xzt,{className:Mt("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")})}));jn.displayName=rct.displayName;function Qa(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 kc(s,t){return s instanceof Date?new s.constructor(t):new Date(t)}function Bl(s,t){const n=Qa(s);return isNaN(t)?kc(s,NaN):(t&&n.setDate(n.getDate()+t),n)}function _f(s,t){const n=Qa(s);if(isNaN(t))return kc(s,NaN);if(!t)return n;const r=n.getDate(),a=kc(s,n.getTime());a.setMonth(n.getMonth()+t+1,0);const i=a.getDate();return r>=i?a:(n.setFullYear(a.getFullYear(),a.getMonth(),r),n)}function act(s,t){const n=+Qa(s);return kc(s,n+t)}const RAe=6048e5,Jzt=864e5,J0e=6e4,eye=36e5,eBt=1e3,HV=43200,Uze=1440;function qze(s,t){return act(s,t*eye)}let tBt={};function U4(){return tBt}function Vm(s,t){var o,c,d,u;const n=U4(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=Qa(s),i=a.getDay(),l=(i=a.getTime()?n+1:t.getTime()>=l.getTime()?n:n-1}function wf(s){const t=Qa(s);return t.setHours(0,0,0,0),t}function N4(s){const t=Qa(s),n=new Date(Date.UTC(t.getFullYear(),t.getMonth(),t.getDate(),t.getHours(),t.getMinutes(),t.getSeconds(),t.getMilliseconds()));return n.setUTCFullYear(t.getFullYear()),+s-+n}function Vx(s,t){const n=wf(s),r=wf(t),a=+n-N4(n),i=+r-N4(r);return Math.round((a-i)/Jzt)}function sBt(s){const t=ict(s),n=kc(s,0);return n.setFullYear(t,0,4),n.setHours(0,0,0,0),cN(n)}function bP(s,t){return act(s,t*J0e)}function L2(s,t){const n=t*7;return Bl(s,n)}function nBt(s,t){return _f(s,t*12)}function rBt(s){let t;return s.forEach(function(n){const r=Qa(n);(t===void 0||t{const r=Qa(n);(!t||t>r||isNaN(+r))&&(t=r)}),t||new Date(NaN)}function vme(s,t){const n=Qa(s),r=Qa(t),a=n.getTime()-r.getTime();return a<0?-1:a>0?1:a}function tye(s){return kc(s,Date.now())}function ql(s,t){const n=wf(s),r=wf(t);return+n==+r}function OAe(s){return s instanceof Date||typeof s=="object"&&Object.prototype.toString.call(s)==="[object Date]"}function f4e(s){if(!OAe(s)&&typeof s!="number")return!1;const t=Qa(s);return!isNaN(Number(t))}function f8(s,t){const n=Qa(s),r=Qa(t),a=n.getFullYear()-r.getFullYear(),i=n.getMonth()-r.getMonth();return a*12+i}function iBt(s,t,n){const r=Vm(s,n),a=Vm(t,n),i=+r-N4(r),l=+a-N4(a);return Math.round((i-l)/RAe)}function Vv(s,t){const n=Qa(s),r=Qa(t),a=Vze(n,r),i=Math.abs(Vx(n,r));n.setDate(n.getDate()-a*i);const l=+(Vze(n,r)===-a),o=a*(i-l);return o===0?0:o}function Vze(s,t){const n=s.getFullYear()-t.getFullYear()||s.getMonth()-t.getMonth()||s.getDate()-t.getDate()||s.getHours()-t.getHours()||s.getMinutes()-t.getMinutes()||s.getSeconds()-t.getSeconds()||s.getMilliseconds()-t.getMilliseconds();return n<0?-1:n>0?1:n}function oBt(s){return t=>{const r=(s?Math[s]:Math.trunc)(t);return r===0?0:r}}function lBt(s,t){return+Qa(s)-+Qa(t)}function cBt(s){const t=Qa(s);return t.setHours(23,59,59,999),t}function $0(s){const t=Qa(s),n=t.getMonth();return t.setFullYear(t.getFullYear(),n+1,0),t.setHours(23,59,59,999),t}function dBt(s){const t=Qa(s);return+cBt(t)==+$0(t)}function uBt(s,t){const n=Qa(s),r=Qa(t),a=vme(n,r),i=Math.abs(f8(n,r));let l;if(i<1)l=0;else{n.getMonth()===1&&n.getDate()>27&&n.setDate(30),n.setMonth(n.getMonth()-a*i);let o=vme(n,r)===-a;dBt(Qa(s))&&i===1&&vme(s,r)===1&&(o=!1),l=a*(i-Number(o))}return l===0?0:l}function hBt(s,t,n){const r=lBt(s,t)/1e3;return oBt(n==null?void 0:n.roundingMethod)(r)}function x4e(s,t){const n=Qa(s.start),r=Qa(s.end);let a=+n>+r;const i=a?+n:+r,l=a?r:n;l.setHours(0,0,0,0);let o=1;const c=[];for(;+l<=i;)c.push(Qa(l)),l.setDate(l.getDate()+o),l.setHours(0,0,0,0);return a?c.reverse():c}function Rd(s){const t=Qa(s);return t.setDate(1),t.setHours(0,0,0,0),t}function oct(s){const t=Qa(s),n=kc(s,0);return n.setFullYear(t.getFullYear(),0,1),n.setHours(0,0,0,0),n}function x8(s,t){var o,c,d,u;const n=U4(),r=(t==null?void 0:t.weekStartsOn)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.weekStartsOn)??n.weekStartsOn??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.weekStartsOn)??0,a=Qa(s),i=a.getDay(),l=(i{let r;const a=mBt[s];return typeof a=="string"?r=a:t===1?r=a.one:r=a.other.replace("{{count}}",t.toString()),n!=null&&n.addSuffix?n.comparison&&n.comparison>0?"in "+r:r+" ago":r};function Vwe(s){return(t={})=>{const n=t.width?String(t.width):s.defaultWidth;return s.formats[n]||s.formats[s.defaultWidth]}}const fBt={full:"EEEE, MMMM do, y",long:"MMMM do, y",medium:"MMM d, y",short:"MM/dd/yyyy"},xBt={full:"h:mm:ss a zzzz",long:"h:mm:ss a z",medium:"h:mm:ss a",short:"h:mm a"},gBt={full:"{{date}} 'at' {{time}}",long:"{{date}} 'at' {{time}}",medium:"{{date}}, {{time}}",short:"{{date}}, {{time}}"},yBt={date:Vwe({formats:fBt,defaultWidth:"full"}),time:Vwe({formats:xBt,defaultWidth:"full"}),dateTime:Vwe({formats:gBt,defaultWidth:"full"})},vBt={lastWeek:"'last' eeee 'at' p",yesterday:"'yesterday at' p",today:"'today at' p",tomorrow:"'tomorrow at' p",nextWeek:"eeee 'at' p",other:"P"},bBt=(s,t,n,r)=>vBt[s];function QO(s){return(t,n)=>{const r=n!=null&&n.context?String(n.context):"standalone";let a;if(r==="formatting"&&s.formattingValues){const l=s.defaultFormattingWidth||s.defaultWidth,o=n!=null&&n.width?String(n.width):l;a=s.formattingValues[o]||s.formattingValues[l]}else{const l=s.defaultWidth,o=n!=null&&n.width?String(n.width):s.defaultWidth;a=s.values[o]||s.values[l]}const i=s.argumentCallback?s.argumentCallback(t):t;return a[i]}}const _Bt={narrow:["B","A"],abbreviated:["BC","AD"],wide:["Before Christ","Anno Domini"]},wBt={narrow:["1","2","3","4"],abbreviated:["Q1","Q2","Q3","Q4"],wide:["1st quarter","2nd quarter","3rd quarter","4th quarter"]},jBt={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"]},NBt={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"]},kBt={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"}},SBt={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"}},CBt=(s,t)=>{const n=Number(s),r=n%100;if(r>20||r<10)switch(r%10){case 1:return n+"st";case 2:return n+"nd";case 3:return n+"rd"}return n+"th"},TBt={ordinalNumber:CBt,era:QO({values:_Bt,defaultWidth:"wide"}),quarter:QO({values:wBt,defaultWidth:"wide",argumentCallback:s=>s-1}),month:QO({values:jBt,defaultWidth:"wide"}),day:QO({values:NBt,defaultWidth:"wide"}),dayPeriod:QO({values:kBt,defaultWidth:"wide",formattingValues:SBt,defaultFormattingWidth:"wide"})};function XO(s){return(t,n={})=>{const r=n.width,a=r&&s.matchPatterns[r]||s.matchPatterns[s.defaultMatchWidth],i=t.match(a);if(!i)return null;const l=i[0],o=r&&s.parsePatterns[r]||s.parsePatterns[s.defaultParseWidth],c=Array.isArray(o)?ABt(o,h=>h.test(l)):EBt(o,h=>h.test(l));let d;d=s.valueCallback?s.valueCallback(c):c,d=n.valueCallback?n.valueCallback(d):d;const u=t.slice(l.length);return{value:d,rest:u}}}function EBt(s,t){for(const n in s)if(Object.prototype.hasOwnProperty.call(s,n)&&t(s[n]))return n}function ABt(s,t){for(let n=0;n{const r=t.match(s.matchPattern);if(!r)return null;const a=r[0],i=t.match(s.parsePattern);if(!i)return null;let l=s.valueCallback?s.valueCallback(i[0]):i[0];l=n.valueCallback?n.valueCallback(l):l;const o=t.slice(a.length);return{value:l,rest:o}}}const IBt=/^(\d+)(th|st|nd|rd)?/i,PBt=/\d+/i,LBt={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},DBt={any:[/^b/i,/^(a|c)/i]},RBt={narrow:/^[1234]/i,abbreviated:/^q[1234]/i,wide:/^[1234](th|st|nd|rd)? quarter/i},OBt={any:[/1/i,/2/i,/3/i,/4/i]},FBt={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},zBt={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]},BBt={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},$Bt={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]},UBt={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},qBt={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}},VBt={ordinalNumber:MBt({matchPattern:IBt,parsePattern:PBt,valueCallback:s=>parseInt(s,10)}),era:XO({matchPatterns:LBt,defaultMatchWidth:"wide",parsePatterns:DBt,defaultParseWidth:"any"}),quarter:XO({matchPatterns:RBt,defaultMatchWidth:"wide",parsePatterns:OBt,defaultParseWidth:"any",valueCallback:s=>s+1}),month:XO({matchPatterns:FBt,defaultMatchWidth:"wide",parsePatterns:zBt,defaultParseWidth:"any"}),day:XO({matchPatterns:BBt,defaultMatchWidth:"wide",parsePatterns:$Bt,defaultParseWidth:"any"}),dayPeriod:XO({matchPatterns:UBt,defaultMatchWidth:"any",parsePatterns:qBt,defaultParseWidth:"any"})},sye={code:"en-US",formatDistance:pBt,formatLong:yBt,formatRelative:bBt,localize:TBt,match:VBt,options:{weekStartsOn:0,firstWeekContainsDate:1}};function HBt(s){const t=Qa(s);return Vx(t,oct(t))+1}function FAe(s){const t=Qa(s),n=+cN(t)-+sBt(t);return Math.round(n/RAe)+1}function zAe(s,t){var u,h,p,f;const n=Qa(s),r=n.getFullYear(),a=U4(),i=(t==null?void 0:t.firstWeekContainsDate)??((h=(u=t==null?void 0:t.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??a.firstWeekContainsDate??((f=(p=a.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,l=kc(s,0);l.setFullYear(r+1,0,i),l.setHours(0,0,0,0);const o=Vm(l,t),c=kc(s,0);c.setFullYear(r,0,i),c.setHours(0,0,0,0);const d=Vm(c,t);return n.getTime()>=o.getTime()?r+1:n.getTime()>=d.getTime()?r:r-1}function GBt(s,t){var o,c,d,u;const n=U4(),r=(t==null?void 0:t.firstWeekContainsDate)??((c=(o=t==null?void 0:t.locale)==null?void 0:o.options)==null?void 0:c.firstWeekContainsDate)??n.firstWeekContainsDate??((u=(d=n.locale)==null?void 0:d.options)==null?void 0:u.firstWeekContainsDate)??1,a=zAe(s,t),i=kc(s,0);return i.setFullYear(a,0,r),i.setHours(0,0,0,0),Vm(i,t)}function BAe(s,t){const n=Qa(s),r=+Vm(n,t)-+GBt(n,t);return Math.round(r/RAe)+1}function _c(s,t){const n=s<0?"-":"",r=Math.abs(s).toString().padStart(t,"0");return n+r}const bk={y(s,t){const n=s.getFullYear(),r=n>0?n:1-n;return _c(t==="yy"?r%100:r,t.length)},M(s,t){const n=s.getMonth();return t==="M"?String(n+1):_c(n+1,2)},d(s,t){return _c(s.getDate(),t.length)},a(s,t){const n=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.toUpperCase();case"aaa":return n;case"aaaaa":return n[0];case"aaaa":default:return n==="am"?"a.m.":"p.m."}},h(s,t){return _c(s.getHours()%12||12,t.length)},H(s,t){return _c(s.getHours(),t.length)},m(s,t){return _c(s.getMinutes(),t.length)},s(s,t){return _c(s.getSeconds(),t.length)},S(s,t){const n=t.length,r=s.getMilliseconds(),a=Math.trunc(r*Math.pow(10,n-3));return _c(a,t.length)}},fI={am:"am",pm:"pm",midnight:"midnight",noon:"noon",morning:"morning",afternoon:"afternoon",evening:"evening",night:"night"},Hze={G:function(s,t,n){const r=s.getFullYear()>0?1:0;switch(t){case"G":case"GG":case"GGG":return n.era(r,{width:"abbreviated"});case"GGGGG":return n.era(r,{width:"narrow"});case"GGGG":default:return n.era(r,{width:"wide"})}},y:function(s,t,n){if(t==="yo"){const r=s.getFullYear(),a=r>0?r:1-r;return n.ordinalNumber(a,{unit:"year"})}return bk.y(s,t)},Y:function(s,t,n,r){const a=zAe(s,r),i=a>0?a:1-a;if(t==="YY"){const l=i%100;return _c(l,2)}return t==="Yo"?n.ordinalNumber(i,{unit:"year"}):_c(i,t.length)},R:function(s,t){const n=ict(s);return _c(n,t.length)},u:function(s,t){const n=s.getFullYear();return _c(n,t.length)},Q:function(s,t,n){const r=Math.ceil((s.getMonth()+1)/3);switch(t){case"Q":return String(r);case"QQ":return _c(r,2);case"Qo":return n.ordinalNumber(r,{unit:"quarter"});case"QQQ":return n.quarter(r,{width:"abbreviated",context:"formatting"});case"QQQQQ":return n.quarter(r,{width:"narrow",context:"formatting"});case"QQQQ":default:return n.quarter(r,{width:"wide",context:"formatting"})}},q:function(s,t,n){const r=Math.ceil((s.getMonth()+1)/3);switch(t){case"q":return String(r);case"qq":return _c(r,2);case"qo":return n.ordinalNumber(r,{unit:"quarter"});case"qqq":return n.quarter(r,{width:"abbreviated",context:"standalone"});case"qqqqq":return n.quarter(r,{width:"narrow",context:"standalone"});case"qqqq":default:return n.quarter(r,{width:"wide",context:"standalone"})}},M:function(s,t,n){const r=s.getMonth();switch(t){case"M":case"MM":return bk.M(s,t);case"Mo":return n.ordinalNumber(r+1,{unit:"month"});case"MMM":return n.month(r,{width:"abbreviated",context:"formatting"});case"MMMMM":return n.month(r,{width:"narrow",context:"formatting"});case"MMMM":default:return n.month(r,{width:"wide",context:"formatting"})}},L:function(s,t,n){const r=s.getMonth();switch(t){case"L":return String(r+1);case"LL":return _c(r+1,2);case"Lo":return n.ordinalNumber(r+1,{unit:"month"});case"LLL":return n.month(r,{width:"abbreviated",context:"standalone"});case"LLLLL":return n.month(r,{width:"narrow",context:"standalone"});case"LLLL":default:return n.month(r,{width:"wide",context:"standalone"})}},w:function(s,t,n,r){const a=BAe(s,r);return t==="wo"?n.ordinalNumber(a,{unit:"week"}):_c(a,t.length)},I:function(s,t,n){const r=FAe(s);return t==="Io"?n.ordinalNumber(r,{unit:"week"}):_c(r,t.length)},d:function(s,t,n){return t==="do"?n.ordinalNumber(s.getDate(),{unit:"date"}):bk.d(s,t)},D:function(s,t,n){const r=HBt(s);return t==="Do"?n.ordinalNumber(r,{unit:"dayOfYear"}):_c(r,t.length)},E:function(s,t,n){const r=s.getDay();switch(t){case"E":case"EE":case"EEE":return n.day(r,{width:"abbreviated",context:"formatting"});case"EEEEE":return n.day(r,{width:"narrow",context:"formatting"});case"EEEEEE":return n.day(r,{width:"short",context:"formatting"});case"EEEE":default:return n.day(r,{width:"wide",context:"formatting"})}},e:function(s,t,n,r){const a=s.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"e":return String(i);case"ee":return _c(i,2);case"eo":return n.ordinalNumber(i,{unit:"day"});case"eee":return n.day(a,{width:"abbreviated",context:"formatting"});case"eeeee":return n.day(a,{width:"narrow",context:"formatting"});case"eeeeee":return n.day(a,{width:"short",context:"formatting"});case"eeee":default:return n.day(a,{width:"wide",context:"formatting"})}},c:function(s,t,n,r){const a=s.getDay(),i=(a-r.weekStartsOn+8)%7||7;switch(t){case"c":return String(i);case"cc":return _c(i,t.length);case"co":return n.ordinalNumber(i,{unit:"day"});case"ccc":return n.day(a,{width:"abbreviated",context:"standalone"});case"ccccc":return n.day(a,{width:"narrow",context:"standalone"});case"cccccc":return n.day(a,{width:"short",context:"standalone"});case"cccc":default:return n.day(a,{width:"wide",context:"standalone"})}},i:function(s,t,n){const r=s.getDay(),a=r===0?7:r;switch(t){case"i":return String(a);case"ii":return _c(a,t.length);case"io":return n.ordinalNumber(a,{unit:"day"});case"iii":return n.day(r,{width:"abbreviated",context:"formatting"});case"iiiii":return n.day(r,{width:"narrow",context:"formatting"});case"iiiiii":return n.day(r,{width:"short",context:"formatting"});case"iiii":default:return n.day(r,{width:"wide",context:"formatting"})}},a:function(s,t,n){const a=s.getHours()/12>=1?"pm":"am";switch(t){case"a":case"aa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"aaa":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"aaaaa":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"aaaa":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},b:function(s,t,n){const r=s.getHours();let a;switch(r===12?a=fI.noon:r===0?a=fI.midnight:a=r/12>=1?"pm":"am",t){case"b":case"bb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"bbb":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"}).toLowerCase();case"bbbbb":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"bbbb":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},B:function(s,t,n){const r=s.getHours();let a;switch(r>=17?a=fI.evening:r>=12?a=fI.afternoon:r>=4?a=fI.morning:a=fI.night,t){case"B":case"BB":case"BBB":return n.dayPeriod(a,{width:"abbreviated",context:"formatting"});case"BBBBB":return n.dayPeriod(a,{width:"narrow",context:"formatting"});case"BBBB":default:return n.dayPeriod(a,{width:"wide",context:"formatting"})}},h:function(s,t,n){if(t==="ho"){let r=s.getHours()%12;return r===0&&(r=12),n.ordinalNumber(r,{unit:"hour"})}return bk.h(s,t)},H:function(s,t,n){return t==="Ho"?n.ordinalNumber(s.getHours(),{unit:"hour"}):bk.H(s,t)},K:function(s,t,n){const r=s.getHours()%12;return t==="Ko"?n.ordinalNumber(r,{unit:"hour"}):_c(r,t.length)},k:function(s,t,n){let r=s.getHours();return r===0&&(r=24),t==="ko"?n.ordinalNumber(r,{unit:"hour"}):_c(r,t.length)},m:function(s,t,n){return t==="mo"?n.ordinalNumber(s.getMinutes(),{unit:"minute"}):bk.m(s,t)},s:function(s,t,n){return t==="so"?n.ordinalNumber(s.getSeconds(),{unit:"second"}):bk.s(s,t)},S:function(s,t){return bk.S(s,t)},X:function(s,t,n){const r=s.getTimezoneOffset();if(r===0)return"Z";switch(t){case"X":return Wze(r);case"XXXX":case"XX":return NE(r);case"XXXXX":case"XXX":default:return NE(r,":")}},x:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"x":return Wze(r);case"xxxx":case"xx":return NE(r);case"xxxxx":case"xxx":default:return NE(r,":")}},O:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"O":case"OO":case"OOO":return"GMT"+Gze(r,":");case"OOOO":default:return"GMT"+NE(r,":")}},z:function(s,t,n){const r=s.getTimezoneOffset();switch(t){case"z":case"zz":case"zzz":return"GMT"+Gze(r,":");case"zzzz":default:return"GMT"+NE(r,":")}},t:function(s,t,n){const r=Math.trunc(s.getTime()/1e3);return _c(r,t.length)},T:function(s,t,n){const r=s.getTime();return _c(r,t.length)}};function Gze(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=Math.trunc(r/60),i=r%60;return i===0?n+String(a):n+String(a)+t+_c(i,2)}function Wze(s,t){return s%60===0?(s>0?"-":"+")+_c(Math.abs(s)/60,2):NE(s,t)}function NE(s,t=""){const n=s>0?"-":"+",r=Math.abs(s),a=_c(Math.trunc(r/60),2),i=_c(r%60,2);return n+a+t+i}const Kze=(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"})}},cct=(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"})}},WBt=(s,t)=>{const n=s.match(/(P+)(p+)?/)||[],r=n[1],a=n[2];if(!a)return Kze(s,t);let i;switch(r){case"P":i=t.dateTime({width:"short"});break;case"PP":i=t.dateTime({width:"medium"});break;case"PPP":i=t.dateTime({width:"long"});break;case"PPPP":default:i=t.dateTime({width:"full"});break}return i.replace("{{date}}",Kze(r,t)).replace("{{time}}",cct(a,t))},g4e={p:cct,P:WBt},KBt=/^D+$/,YBt=/^Y+$/,ZBt=["D","DD","YY","YYYY"];function dct(s){return KBt.test(s)}function uct(s){return YBt.test(s)}function y4e(s,t,n){const r=QBt(s,t,n);if(console.warn(r),ZBt.includes(s))throw new RangeError(r)}function QBt(s,t,n){const r=s[0]==="Y"?"years":"days of the month";return`Use \`${s.toLowerCase()}\` instead of \`${s}\` (in \`${t}\`) for formatting ${r} to the input \`${n}\`; see: https://github.com/date-fns/date-fns/blob/master/docs/unicodeTokens.md`}const XBt=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,JBt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,e$t=/^'([^]*?)'?$/,t$t=/''/g,s$t=/[a-zA-Z]/;function Ss(s,t,n){var u,h,p,f,y,_,v,j;const r=U4(),a=(n==null?void 0:n.locale)??r.locale??sye,i=(n==null?void 0:n.firstWeekContainsDate)??((h=(u=n==null?void 0:n.locale)==null?void 0:u.options)==null?void 0:h.firstWeekContainsDate)??r.firstWeekContainsDate??((f=(p=r.locale)==null?void 0:p.options)==null?void 0:f.firstWeekContainsDate)??1,l=(n==null?void 0:n.weekStartsOn)??((_=(y=n==null?void 0:n.locale)==null?void 0:y.options)==null?void 0:_.weekStartsOn)??r.weekStartsOn??((j=(v=r.locale)==null?void 0:v.options)==null?void 0:j.weekStartsOn)??0,o=Qa(s);if(!f4e(o))throw new RangeError("Invalid time value");let c=t.match(JBt).map(w=>{const S=w[0];if(S==="p"||S==="P"){const A=g4e[S];return A(w,a.formatLong)}return w}).join("").match(XBt).map(w=>{if(w==="''")return{isToken:!1,value:"'"};const S=w[0];if(S==="'")return{isToken:!1,value:n$t(w)};if(Hze[S])return{isToken:!0,value:w};if(S.match(s$t))throw new RangeError("Format string contains an unescaped latin alphabet character `"+S+"`");return{isToken:!1,value:w}});a.localize.preprocessor&&(c=a.localize.preprocessor(o,c));const d={firstWeekContainsDate:i,weekStartsOn:l,locale:a};return c.map(w=>{if(!w.isToken)return w.value;const S=w.value;(!(n!=null&&n.useAdditionalWeekYearTokens)&&uct(S)||!(n!=null&&n.useAdditionalDayOfYearTokens)&&dct(S))&&y4e(S,t,String(s));const A=Hze[S[0]];return A(o,S,a.localize,d)}).join("")}function n$t(s){const t=s.match(e$t);return t?t[1].replace(t$t,"'"):s}function r$t(s,t,n){const r=U4(),a=(n==null?void 0:n.locale)??r.locale??sye,i=2520,l=vme(s,t);if(isNaN(l))throw new RangeError("Invalid time value");const o=Object.assign({},n,{addSuffix:n==null?void 0:n.addSuffix,comparison:l});let c,d;l>0?(c=Qa(t),d=Qa(s)):(c=Qa(s),d=Qa(t));const u=hBt(d,c),h=(N4(d)-N4(c))/1e3,p=Math.round((u-h)/60);let f;if(p<2)return n!=null&&n.includeSeconds?u<5?a.formatDistance("lessThanXSeconds",5,o):u<10?a.formatDistance("lessThanXSeconds",10,o):u<20?a.formatDistance("lessThanXSeconds",20,o):u<40?a.formatDistance("halfAMinute",0,o):u<60?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",1,o):p===0?a.formatDistance("lessThanXMinutes",1,o):a.formatDistance("xMinutes",p,o);if(p<45)return a.formatDistance("xMinutes",p,o);if(p<90)return a.formatDistance("aboutXHours",1,o);if(pr.getTime()}function yb(s,t){const n=Qa(s),r=Qa(t);return+n<+r}function u$t(s){return+Qa(s)>Date.now()}function h$t(s,t){const n=t instanceof Date?kc(t,0):new t(0);return n.setFullYear(s.getFullYear(),s.getMonth(),s.getDate()),n.setHours(s.getHours(),s.getMinutes(),s.getSeconds(),s.getMilliseconds()),n}const m$t=10;class hct{constructor(){Ta(this,"subPriority",0)}validate(t,n){return!0}}class p$t extends hct{constructor(t,n,r,a,i){super(),this.value=t,this.validateValue=n,this.setValue=r,this.priority=a,i&&(this.subPriority=i)}validate(t,n){return this.validateValue(t,this.value,n)}set(t,n,r){return this.setValue(t,n,this.value,r)}}class f$t extends hct{constructor(){super(...arguments);Ta(this,"priority",m$t);Ta(this,"subPriority",-1)}set(n,r){return r.timestampIsSet?n:kc(n,h$t(n,Date))}}class cc{run(t,n,r,a){const i=this.parse(t,n,r,a);return i?{setter:new p$t(i.value,this.validate,this.set,this.priority,this.subPriority),rest:i.rest}:null}validate(t,n,r){return!0}}class x$t extends cc{constructor(){super(...arguments);Ta(this,"priority",140);Ta(this,"incompatibleTokens",["R","u","t","T"])}parse(n,r,a){switch(r){case"G":case"GG":case"GGG":return a.era(n,{width:"abbreviated"})||a.era(n,{width:"narrow"});case"GGGGG":return a.era(n,{width:"narrow"});case"GGGG":default:return a.era(n,{width:"wide"})||a.era(n,{width:"abbreviated"})||a.era(n,{width:"narrow"})}}set(n,r,a){return r.era=a,n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}const Ch={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}/},Y_={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 Th(s,t){return s&&{value:t(s.value),rest:s.rest}}function Tu(s,t){const n=t.match(s);return n?{value:parseInt(n[0],10),rest:t.slice(n[0].length)}:null}function Z_(s,t){const n=t.match(s);if(!n)return null;if(n[0]==="Z")return{value:0,rest:t.slice(1)};const r=n[1]==="+"?1:-1,a=n[2]?parseInt(n[2],10):0,i=n[3]?parseInt(n[3],10):0,l=n[5]?parseInt(n[5],10):0;return{value:r*(a*eye+i*J0e+l*eBt),rest:t.slice(n[0].length)}}function mct(s){return Tu(Ch.anyDigitsSigned,s)}function ch(s,t){switch(s){case 1:return Tu(Ch.singleDigit,t);case 2:return Tu(Ch.twoDigits,t);case 3:return Tu(Ch.threeDigits,t);case 4:return Tu(Ch.fourDigits,t);default:return Tu(new RegExp("^\\d{1,"+s+"}"),t)}}function Ype(s,t){switch(s){case 1:return Tu(Ch.singleDigitSigned,t);case 2:return Tu(Ch.twoDigitsSigned,t);case 3:return Tu(Ch.threeDigitsSigned,t);case 4:return Tu(Ch.fourDigitsSigned,t);default:return Tu(new RegExp("^-?\\d{1,"+s+"}"),t)}}function $Ae(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 pct(s,t){const n=t>0,r=n?t:1-t;let a;if(r<=50)a=s||100;else{const i=r+50,l=Math.trunc(i/100)*100,o=s>=i%100;a=s+l-(o?100:0)}return n?a:1-a}function fct(s){return s%400===0||s%4===0&&s%100!==0}class g$t extends cc{constructor(){super(...arguments);Ta(this,"priority",130);Ta(this,"incompatibleTokens",["Y","R","u","w","I","i","e","c","t","T"])}parse(n,r,a){const i=l=>({year:l,isTwoDigitYear:r==="yy"});switch(r){case"y":return Th(ch(4,n),i);case"yo":return Th(a.ordinalNumber(n,{unit:"year"}),i);default:return Th(ch(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a){const i=n.getFullYear();if(a.isTwoDigitYear){const o=pct(a.year,i);return n.setFullYear(o,0,1),n.setHours(0,0,0,0),n}const l=!("era"in r)||r.era===1?a.year:1-a.year;return n.setFullYear(l,0,1),n.setHours(0,0,0,0),n}}class y$t extends cc{constructor(){super(...arguments);Ta(this,"priority",130);Ta(this,"incompatibleTokens",["y","R","u","Q","q","M","L","I","d","D","i","t","T"])}parse(n,r,a){const i=l=>({year:l,isTwoDigitYear:r==="YY"});switch(r){case"Y":return Th(ch(4,n),i);case"Yo":return Th(a.ordinalNumber(n,{unit:"year"}),i);default:return Th(ch(r.length,n),i)}}validate(n,r){return r.isTwoDigitYear||r.year>0}set(n,r,a,i){const l=zAe(n,i);if(a.isTwoDigitYear){const c=pct(a.year,l);return n.setFullYear(c,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),Vm(n,i)}const o=!("era"in r)||r.era===1?a.year:1-a.year;return n.setFullYear(o,0,i.firstWeekContainsDate),n.setHours(0,0,0,0),Vm(n,i)}}class v$t extends cc{constructor(){super(...arguments);Ta(this,"priority",130);Ta(this,"incompatibleTokens",["G","y","Y","u","Q","q","M","L","w","d","D","e","c","t","T"])}parse(n,r){return Ype(r==="R"?4:r.length,n)}set(n,r,a){const i=kc(n,0);return i.setFullYear(a,0,4),i.setHours(0,0,0,0),cN(i)}}class b$t extends cc{constructor(){super(...arguments);Ta(this,"priority",130);Ta(this,"incompatibleTokens",["G","y","Y","R","w","I","i","e","c","t","T"])}parse(n,r){return Ype(r==="u"?4:r.length,n)}set(n,r,a){return n.setFullYear(a,0,1),n.setHours(0,0,0,0),n}}class _$t extends cc{constructor(){super(...arguments);Ta(this,"priority",120);Ta(this,"incompatibleTokens",["Y","R","q","M","L","w","I","d","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"Q":case"QQ":return ch(r.length,n);case"Qo":return a.ordinalNumber(n,{unit:"quarter"});case"QQQ":return a.quarter(n,{width:"abbreviated",context:"formatting"})||a.quarter(n,{width:"narrow",context:"formatting"});case"QQQQQ":return a.quarter(n,{width:"narrow",context:"formatting"});case"QQQQ":default:return a.quarter(n,{width:"wide",context:"formatting"})||a.quarter(n,{width:"abbreviated",context:"formatting"})||a.quarter(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=1&&r<=4}set(n,r,a){return n.setMonth((a-1)*3,1),n.setHours(0,0,0,0),n}}class w$t extends cc{constructor(){super(...arguments);Ta(this,"priority",120);Ta(this,"incompatibleTokens",["Y","R","Q","M","L","w","I","d","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"q":case"qq":return ch(r.length,n);case"qo":return a.ordinalNumber(n,{unit:"quarter"});case"qqq":return a.quarter(n,{width:"abbreviated",context:"standalone"})||a.quarter(n,{width:"narrow",context:"standalone"});case"qqqqq":return a.quarter(n,{width:"narrow",context:"standalone"});case"qqqq":default:return a.quarter(n,{width:"wide",context:"standalone"})||a.quarter(n,{width:"abbreviated",context:"standalone"})||a.quarter(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=1&&r<=4}set(n,r,a){return n.setMonth((a-1)*3,1),n.setHours(0,0,0,0),n}}class j$t extends cc{constructor(){super(...arguments);Ta(this,"incompatibleTokens",["Y","R","q","Q","L","w","I","D","i","e","c","t","T"]);Ta(this,"priority",110)}parse(n,r,a){const i=l=>l-1;switch(r){case"M":return Th(Tu(Ch.month,n),i);case"MM":return Th(ch(2,n),i);case"Mo":return Th(a.ordinalNumber(n,{unit:"month"}),i);case"MMM":return a.month(n,{width:"abbreviated",context:"formatting"})||a.month(n,{width:"narrow",context:"formatting"});case"MMMMM":return a.month(n,{width:"narrow",context:"formatting"});case"MMMM":default:return a.month(n,{width:"wide",context:"formatting"})||a.month(n,{width:"abbreviated",context:"formatting"})||a.month(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.setMonth(a,1),n.setHours(0,0,0,0),n}}class N$t extends cc{constructor(){super(...arguments);Ta(this,"priority",110);Ta(this,"incompatibleTokens",["Y","R","q","Q","M","w","I","D","i","e","c","t","T"])}parse(n,r,a){const i=l=>l-1;switch(r){case"L":return Th(Tu(Ch.month,n),i);case"LL":return Th(ch(2,n),i);case"Lo":return Th(a.ordinalNumber(n,{unit:"month"}),i);case"LLL":return a.month(n,{width:"abbreviated",context:"standalone"})||a.month(n,{width:"narrow",context:"standalone"});case"LLLLL":return a.month(n,{width:"narrow",context:"standalone"});case"LLLL":default:return a.month(n,{width:"wide",context:"standalone"})||a.month(n,{width:"abbreviated",context:"standalone"})||a.month(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.setMonth(a,1),n.setHours(0,0,0,0),n}}function k$t(s,t,n){const r=Qa(s),a=BAe(r,n)-t;return r.setDate(r.getDate()-a*7),r}class S$t extends cc{constructor(){super(...arguments);Ta(this,"priority",100);Ta(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","i","t","T"])}parse(n,r,a){switch(r){case"w":return Tu(Ch.week,n);case"wo":return a.ordinalNumber(n,{unit:"week"});default:return ch(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a,i){return Vm(k$t(n,a,i),i)}}function C$t(s,t){const n=Qa(s),r=FAe(n)-t;return n.setDate(n.getDate()-r*7),n}class T$t extends cc{constructor(){super(...arguments);Ta(this,"priority",100);Ta(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","e","c","t","T"])}parse(n,r,a){switch(r){case"I":return Tu(Ch.week,n);case"Io":return a.ordinalNumber(n,{unit:"week"});default:return ch(r.length,n)}}validate(n,r){return r>=1&&r<=53}set(n,r,a){return cN(C$t(n,a))}}const E$t=[31,28,31,30,31,30,31,31,30,31,30,31],A$t=[31,29,31,30,31,30,31,31,30,31,30,31];class M$t extends cc{constructor(){super(...arguments);Ta(this,"priority",90);Ta(this,"subPriority",1);Ta(this,"incompatibleTokens",["Y","R","q","Q","w","I","D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"d":return Tu(Ch.date,n);case"do":return a.ordinalNumber(n,{unit:"date"});default:return ch(r.length,n)}}validate(n,r){const a=n.getFullYear(),i=fct(a),l=n.getMonth();return i?r>=1&&r<=A$t[l]:r>=1&&r<=E$t[l]}set(n,r,a){return n.setDate(a),n.setHours(0,0,0,0),n}}class I$t extends cc{constructor(){super(...arguments);Ta(this,"priority",90);Ta(this,"subpriority",1);Ta(this,"incompatibleTokens",["Y","R","q","Q","M","L","w","I","d","E","i","e","c","t","T"])}parse(n,r,a){switch(r){case"D":case"DD":return Tu(Ch.dayOfYear,n);case"Do":return a.ordinalNumber(n,{unit:"date"});default:return ch(r.length,n)}}validate(n,r){const a=n.getFullYear();return fct(a)?r>=1&&r<=366:r>=1&&r<=365}set(n,r,a){return n.setMonth(0,a),n.setHours(0,0,0,0),n}}function UAe(s,t,n){var h,p,f,y;const r=U4(),a=(n==null?void 0:n.weekStartsOn)??((p=(h=n==null?void 0:n.locale)==null?void 0:h.options)==null?void 0:p.weekStartsOn)??r.weekStartsOn??((y=(f=r.locale)==null?void 0:f.options)==null?void 0:y.weekStartsOn)??0,i=Qa(s),l=i.getDay(),c=(t%7+7)%7,d=7-a,u=t<0||t>6?t-(l+d)%7:(c+d)%7-(l+d)%7;return Bl(i,u)}class P$t extends cc{constructor(){super(...arguments);Ta(this,"priority",90);Ta(this,"incompatibleTokens",["D","i","e","c","t","T"])}parse(n,r,a){switch(r){case"E":case"EE":case"EEE":return a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"EEEEE":return a.day(n,{width:"narrow",context:"formatting"});case"EEEEEE":return a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"EEEE":default:return a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=UAe(n,a,i),n.setHours(0,0,0,0),n}}class L$t extends cc{constructor(){super(...arguments);Ta(this,"priority",90);Ta(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","c","t","T"])}parse(n,r,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(r){case"e":case"ee":return Th(ch(r.length,n),l);case"eo":return Th(a.ordinalNumber(n,{unit:"day"}),l);case"eee":return a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"eeeee":return a.day(n,{width:"narrow",context:"formatting"});case"eeeeee":return a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"});case"eeee":default:return a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=UAe(n,a,i),n.setHours(0,0,0,0),n}}class D$t extends cc{constructor(){super(...arguments);Ta(this,"priority",90);Ta(this,"incompatibleTokens",["y","R","u","q","Q","M","L","I","d","D","E","i","e","t","T"])}parse(n,r,a,i){const l=o=>{const c=Math.floor((o-1)/7)*7;return(o+i.weekStartsOn+6)%7+c};switch(r){case"c":case"cc":return Th(ch(r.length,n),l);case"co":return Th(a.ordinalNumber(n,{unit:"day"}),l);case"ccc":return a.day(n,{width:"abbreviated",context:"standalone"})||a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"});case"ccccc":return a.day(n,{width:"narrow",context:"standalone"});case"cccccc":return a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"});case"cccc":default:return a.day(n,{width:"wide",context:"standalone"})||a.day(n,{width:"abbreviated",context:"standalone"})||a.day(n,{width:"short",context:"standalone"})||a.day(n,{width:"narrow",context:"standalone"})}}validate(n,r){return r>=0&&r<=6}set(n,r,a,i){return n=UAe(n,a,i),n.setHours(0,0,0,0),n}}function R$t(s,t){const n=Qa(s),r=o$t(n),a=t-r;return Bl(n,a)}class O$t extends cc{constructor(){super(...arguments);Ta(this,"priority",90);Ta(this,"incompatibleTokens",["y","Y","u","q","Q","M","L","w","d","D","E","e","c","t","T"])}parse(n,r,a){const i=l=>l===0?7:l;switch(r){case"i":case"ii":return ch(r.length,n);case"io":return a.ordinalNumber(n,{unit:"day"});case"iii":return Th(a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiii":return Th(a.day(n,{width:"narrow",context:"formatting"}),i);case"iiiiii":return Th(a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i);case"iiii":default:return Th(a.day(n,{width:"wide",context:"formatting"})||a.day(n,{width:"abbreviated",context:"formatting"})||a.day(n,{width:"short",context:"formatting"})||a.day(n,{width:"narrow",context:"formatting"}),i)}}validate(n,r){return r>=1&&r<=7}set(n,r,a){return n=R$t(n,a),n.setHours(0,0,0,0),n}}class F$t extends cc{constructor(){super(...arguments);Ta(this,"priority",80);Ta(this,"incompatibleTokens",["b","B","H","k","t","T"])}parse(n,r,a){switch(r){case"a":case"aa":case"aaa":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaaa":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"aaaa":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours($Ae(a),0,0,0),n}}class z$t extends cc{constructor(){super(...arguments);Ta(this,"priority",80);Ta(this,"incompatibleTokens",["a","B","H","k","t","T"])}parse(n,r,a){switch(r){case"b":case"bb":case"bbb":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbbb":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"bbbb":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours($Ae(a),0,0,0),n}}class B$t extends cc{constructor(){super(...arguments);Ta(this,"priority",80);Ta(this,"incompatibleTokens",["a","b","t","T"])}parse(n,r,a){switch(r){case"B":case"BB":case"BBB":return a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBBB":return a.dayPeriod(n,{width:"narrow",context:"formatting"});case"BBBB":default:return a.dayPeriod(n,{width:"wide",context:"formatting"})||a.dayPeriod(n,{width:"abbreviated",context:"formatting"})||a.dayPeriod(n,{width:"narrow",context:"formatting"})}}set(n,r,a){return n.setHours($Ae(a),0,0,0),n}}class $$t extends cc{constructor(){super(...arguments);Ta(this,"priority",70);Ta(this,"incompatibleTokens",["H","K","k","t","T"])}parse(n,r,a){switch(r){case"h":return Tu(Ch.hour12h,n);case"ho":return a.ordinalNumber(n,{unit:"hour"});default:return ch(r.length,n)}}validate(n,r){return r>=1&&r<=12}set(n,r,a){const i=n.getHours()>=12;return i&&a<12?n.setHours(a+12,0,0,0):!i&&a===12?n.setHours(0,0,0,0):n.setHours(a,0,0,0),n}}class U$t extends cc{constructor(){super(...arguments);Ta(this,"priority",70);Ta(this,"incompatibleTokens",["a","b","h","K","k","t","T"])}parse(n,r,a){switch(r){case"H":return Tu(Ch.hour23h,n);case"Ho":return a.ordinalNumber(n,{unit:"hour"});default:return ch(r.length,n)}}validate(n,r){return r>=0&&r<=23}set(n,r,a){return n.setHours(a,0,0,0),n}}class q$t extends cc{constructor(){super(...arguments);Ta(this,"priority",70);Ta(this,"incompatibleTokens",["h","H","k","t","T"])}parse(n,r,a){switch(r){case"K":return Tu(Ch.hour11h,n);case"Ko":return a.ordinalNumber(n,{unit:"hour"});default:return ch(r.length,n)}}validate(n,r){return r>=0&&r<=11}set(n,r,a){return n.getHours()>=12&&a<12?n.setHours(a+12,0,0,0):n.setHours(a,0,0,0),n}}class V$t extends cc{constructor(){super(...arguments);Ta(this,"priority",70);Ta(this,"incompatibleTokens",["a","b","h","H","K","t","T"])}parse(n,r,a){switch(r){case"k":return Tu(Ch.hour24h,n);case"ko":return a.ordinalNumber(n,{unit:"hour"});default:return ch(r.length,n)}}validate(n,r){return r>=1&&r<=24}set(n,r,a){const i=a<=24?a%24:a;return n.setHours(i,0,0,0),n}}class H$t extends cc{constructor(){super(...arguments);Ta(this,"priority",60);Ta(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"m":return Tu(Ch.minute,n);case"mo":return a.ordinalNumber(n,{unit:"minute"});default:return ch(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setMinutes(a,0,0),n}}class G$t extends cc{constructor(){super(...arguments);Ta(this,"priority",50);Ta(this,"incompatibleTokens",["t","T"])}parse(n,r,a){switch(r){case"s":return Tu(Ch.second,n);case"so":return a.ordinalNumber(n,{unit:"second"});default:return ch(r.length,n)}}validate(n,r){return r>=0&&r<=59}set(n,r,a){return n.setSeconds(a,0),n}}class W$t extends cc{constructor(){super(...arguments);Ta(this,"priority",30);Ta(this,"incompatibleTokens",["t","T"])}parse(n,r){const a=i=>Math.trunc(i*Math.pow(10,-r.length+3));return Th(ch(r.length,n),a)}set(n,r,a){return n.setMilliseconds(a),n}}class K$t extends cc{constructor(){super(...arguments);Ta(this,"priority",10);Ta(this,"incompatibleTokens",["t","T","x"])}parse(n,r){switch(r){case"X":return Z_(Y_.basicOptionalMinutes,n);case"XX":return Z_(Y_.basic,n);case"XXXX":return Z_(Y_.basicOptionalSeconds,n);case"XXXXX":return Z_(Y_.extendedOptionalSeconds,n);case"XXX":default:return Z_(Y_.extended,n)}}set(n,r,a){return r.timestampIsSet?n:kc(n,n.getTime()-N4(n)-a)}}class Y$t extends cc{constructor(){super(...arguments);Ta(this,"priority",10);Ta(this,"incompatibleTokens",["t","T","X"])}parse(n,r){switch(r){case"x":return Z_(Y_.basicOptionalMinutes,n);case"xx":return Z_(Y_.basic,n);case"xxxx":return Z_(Y_.basicOptionalSeconds,n);case"xxxxx":return Z_(Y_.extendedOptionalSeconds,n);case"xxx":default:return Z_(Y_.extended,n)}}set(n,r,a){return r.timestampIsSet?n:kc(n,n.getTime()-N4(n)-a)}}class Z$t extends cc{constructor(){super(...arguments);Ta(this,"priority",40);Ta(this,"incompatibleTokens","*")}parse(n){return mct(n)}set(n,r,a){return[kc(n,a*1e3),{timestampIsSet:!0}]}}class Q$t extends cc{constructor(){super(...arguments);Ta(this,"priority",20);Ta(this,"incompatibleTokens","*")}parse(n){return mct(n)}set(n,r,a){return[kc(n,a),{timestampIsSet:!0}]}}const X$t={G:new x$t,y:new g$t,Y:new y$t,R:new v$t,u:new b$t,Q:new _$t,q:new w$t,M:new j$t,L:new N$t,w:new S$t,I:new T$t,d:new M$t,D:new I$t,E:new P$t,e:new L$t,c:new D$t,i:new O$t,a:new F$t,b:new z$t,B:new B$t,h:new $$t,H:new U$t,K:new q$t,k:new V$t,m:new H$t,s:new G$t,S:new W$t,X:new K$t,x:new Y$t,t:new Z$t,T:new Q$t},J$t=/[yYQqMLwIdDecihHKkms]o|(\w)\1*|''|'(''|[^'])+('|$)|./g,eUt=/P+p+|P+|p+|''|'(''|[^'])+('|$)|./g,tUt=/^'([^]*?)'?$/,sUt=/''/g,nUt=/\S/,rUt=/[a-zA-Z]/;function qAe(s,t,n,r){var _,v,j,w;const a=i$t(),i=a.locale??sye,l=a.firstWeekContainsDate??((v=(_=a.locale)==null?void 0:_.options)==null?void 0:v.firstWeekContainsDate)??1,o=a.weekStartsOn??((w=(j=a.locale)==null?void 0:j.options)==null?void 0:w.weekStartsOn)??0;if(t==="")return s===""?Qa(n):kc(n,NaN);const c={firstWeekContainsDate:l,weekStartsOn:o,locale:i},d=[new f$t],u=t.match(eUt).map(S=>{const A=S[0];if(A in g4e){const E=g4e[A];return E(S,i.formatLong)}return S}).join("").match(J$t),h=[];for(let S of u){uct(S)&&y4e(S,t,s),dct(S)&&y4e(S,t,s);const A=S[0],E=X$t[A];if(E){const{incompatibleTokens:O}=E;if(Array.isArray(O)){const I=h.find(F=>O.includes(F.token)||F.token===A);if(I)throw new RangeError(`The format string mustn't contain \`${I.fullToken}\` and \`${S}\` at the same time`)}else if(E.incompatibleTokens==="*"&&h.length>0)throw new RangeError(`The format string mustn't contain \`${S}\` and any other token at the same time`);h.push({token:A,fullToken:S});const D=E.run(s,S,i.match,c);if(!D)return kc(n,NaN);d.push(D.setter),s=D.rest}else{if(A.match(rUt))throw new RangeError("Format string contains an unescaped latin alphabet character `"+A+"`");if(S==="''"?S="'":A==="'"&&(S=aUt(S)),s.indexOf(S)===0)s=s.slice(S.length);else return kc(n,NaN)}}if(s.length>0&&nUt.test(s))return kc(n,NaN);const p=d.map(S=>S.priority).sort((S,A)=>A-S).filter((S,A,E)=>E.indexOf(S)===A).map(S=>d.filter(A=>A.priority===S).sort((A,E)=>E.subPriority-A.subPriority)).map(S=>S[0]);let f=Qa(n);if(isNaN(f.getTime()))return kc(n,NaN);const y={};for(const S of p){if(!S.validate(f,c))return kc(n,NaN);const A=S.set(f,y,c);Array.isArray(A)?(f=A[0],Object.assign(y,A[1])):f=A}return kc(n,f)}function aUt(s){return s.match(tUt)[1].replace(sUt,"'")}function vw(s){return+Qa(s)i-l);return n>=r&&n<=a}function R9(s,t){return Bl(s,-t)}function Zh(s,t){const r=mUt(s);let a;if(r.date){const c=pUt(r.date,2);a=fUt(c.restDateString,c.year)}if(!a||isNaN(a.getTime()))return new Date(NaN);const i=a.getTime();let l=0,o;if(r.time&&(l=xUt(r.time),isNaN(l)))return new Date(NaN);if(r.timezone){if(o=gUt(r.timezone),isNaN(o))return new Date(NaN)}else{const c=new Date(i+l),d=new Date(0);return d.setFullYear(c.getUTCFullYear(),c.getUTCMonth(),c.getUTCDate()),d.setHours(c.getUTCHours(),c.getUTCMinutes(),c.getUTCSeconds(),c.getUTCMilliseconds()),d}return new Date(i+l+o)}const GV={dateTimeDelimiter:/[T ]/,timeZoneDelimiter:/[Z ]/i,timezone:/([Z+-].*)$/},dUt=/^-?(?:(\d{3})|(\d{2})(?:-?(\d{2}))?|W(\d{2})(?:-?(\d{1}))?|)$/,uUt=/^(\d{2}(?:[.,]\d*)?)(?::?(\d{2}(?:[.,]\d*)?))?(?::?(\d{2}(?:[.,]\d*)?))?$/,hUt=/^([+-])(\d{2})(?::?(\d{2}))?$/;function mUt(s){const t={},n=s.split(GV.dateTimeDelimiter);let r;if(n.length>2)return t;if(/:/.test(n[0])?r=n[0]:(t.date=n[0],r=n[1],GV.timeZoneDelimiter.test(t.date)&&(t.date=s.split(GV.timeZoneDelimiter)[0],r=s.substr(t.date.length,s.length))),r){const a=GV.timezone.exec(r);a?(t.time=r.replace(a[1],""),t.timezone=a[1]):t.time=r}return t}function pUt(s,t){const n=new RegExp("^(?:(\\d{4}|[+-]\\d{"+(4+t)+"})|(\\d{2}|[+-]\\d{"+(2+t)+"})$)"),r=s.match(n);if(!r)return{year:NaN,restDateString:""};const a=r[1]?parseInt(r[1]):null,i=r[2]?parseInt(r[2]):null;return{year:i===null?a:i*100,restDateString:s.slice((r[1]||r[2]).length)}}function fUt(s,t){if(t===null)return new Date(NaN);const n=s.match(dUt);if(!n)return new Date(NaN);const r=!!n[4],a=JO(n[1]),i=JO(n[2])-1,l=JO(n[3]),o=JO(n[4]),c=JO(n[5])-1;if(r)return wUt(t,o,c)?yUt(t,o,c):new Date(NaN);{const d=new Date(0);return!bUt(t,i,l)||!_Ut(t,a)?new Date(NaN):(d.setUTCFullYear(t,i,Math.max(a,l)),d)}}function JO(s){return s?parseInt(s):1}function xUt(s){const t=s.match(uUt);if(!t)return NaN;const n=Hwe(t[1]),r=Hwe(t[2]),a=Hwe(t[3]);return jUt(n,r,a)?n*eye+r*J0e+a*1e3:NaN}function Hwe(s){return s&&parseFloat(s.replace(",","."))||0}function gUt(s){if(s==="Z")return 0;const t=s.match(hUt);if(!t)return 0;const n=t[1]==="+"?-1:1,r=parseInt(t[2]),a=t[3]&&parseInt(t[3])||0;return NUt(r,a)?n*(r*eye+a*J0e):NaN}function yUt(s,t,n){const r=new Date(0);r.setUTCFullYear(s,0,4);const a=r.getUTCDay()||7,i=(t-1)*7+n+1-a;return r.setUTCDate(r.getUTCDate()+i),r}const vUt=[31,null,31,30,31,30,31,31,30,31,30,31];function xct(s){return s%400===0||s%4===0&&s%100!==0}function bUt(s,t,n){return t>=0&&t<=11&&n>=1&&n<=(vUt[t]||(xct(s)?29:28))}function _Ut(s,t){return t>=1&&t<=(xct(s)?366:365)}function wUt(s,t,n){return t>=1&&t<=53&&n>=0&&n<=6}function jUt(s,t,n){return s===24?t===0&&n===0:n>=0&&n<60&&t>=0&&t<60&&s>=0&&s<25}function NUt(s,t){return t>=0&&t<=59}function Gwe(s,t){const n=Qa(s),r=n.getFullYear(),a=n.getDate(),i=kc(s,0);i.setFullYear(r,t,15),i.setHours(0,0,0,0);const l=a$t(i);return n.setMonth(t,Math.min(a,l)),n}function O9(s,t){const n=Qa(s);return n.setHours(t),n}function F9(s,t){const n=Qa(s);return n.setMinutes(t),n}function Zze(s,t){const n=Qa(s);return isNaN(+n)?kc(s,NaN):(n.setFullYear(t),n)}function BE(s,t){return _f(s,-t)}var Qze;function mr(s,t,n){function r(o,c){if(o._zod||Object.defineProperty(o,"_zod",{value:{def:c,constr:l,traits:new Set},enumerable:!1}),o._zod.traits.has(s))return;o._zod.traits.add(s),t(o,c);const d=l.prototype,u=Object.keys(d);for(let h=0;h{var c,d;return n!=null&&n.Parent&&o instanceof n.Parent?!0:(d=(c=o==null?void 0:o._zod)==null?void 0:c.traits)==null?void 0:d.has(s)}}),Object.defineProperty(l,"name",{value:s}),l}class kL extends Error{constructor(){super("Encountered Promise during synchronous parse. Use .parseAsync() instead.")}}class gct extends Error{constructor(t){super(`Encountered unidirectional transform during encode: ${t}`),this.name="ZodEncodeError"}}(Qze=globalThis).__zod_globalConfig??(Qze.__zod_globalConfig={});const VAe=globalThis.__zod_globalConfig;function mM(s){return VAe}function yct(s){const t=Object.values(s).filter(r=>typeof r=="number");return Object.entries(s).filter(([r,a])=>t.indexOf(+r)===-1).map(([r,a])=>a)}function v4e(s,t){return typeof t=="bigint"?t.toString():t}function HAe(s){return{get value(){{const t=s();return Object.defineProperty(this,"value",{value:t}),t}}}}function GAe(s){return s==null}function WAe(s){const t=s.startsWith("^")?1:0,n=s.endsWith("$")?s.length-1:s.length;return s.slice(t,n)}function kUt(s,t){const n=s/t,r=Math.round(n),a=Number.EPSILON*Math.max(Math.abs(n),1);return Math.abs(n-r){};function Zpe(s){return typeof s=="object"&&s!==null&&!Array.isArray(s)}const CUt=HAe(()=>{var s;if(VAe.jitless||typeof navigator<"u"&&((s=navigator==null?void 0:navigator.userAgent)!=null&&s.includes("Cloudflare")))return!1;try{const t=Function;return new t(""),!0}catch{return!1}});function tB(s){if(Zpe(s)===!1)return!1;const t=s.constructor;if(t===void 0||typeof t!="function")return!0;const n=t.prototype;return!(Zpe(n)===!1||Object.prototype.hasOwnProperty.call(n,"isPrototypeOf")===!1)}function bct(s){return tB(s)?{...s}:Array.isArray(s)?[...s]:s instanceof Map?new Map(s):s instanceof Set?new Set(s):s}const TUt=new Set(["string","number","symbol"]);function g8(s){return s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function V4(s,t,n){const r=new s._zod.constr(t??s._zod.def);return(!t||n!=null&&n.parent)&&(r._zod.parent=s),r}function Mi(s){const t=s;if(!t)return{};if(typeof t=="string")return{error:()=>t};if((t==null?void 0:t.message)!==void 0){if((t==null?void 0:t.error)!==void 0)throw new Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error=="string"?{...t,error:()=>t.error}:t}function EUt(s){return Object.keys(s).filter(t=>s[t]._zod.optin==="optional"&&s[t]._zod.optout==="optional")}const AUt={safeint:[Number.MIN_SAFE_INTEGER,Number.MAX_SAFE_INTEGER],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function MUt(s,t){const n=s._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".pick() cannot be used on object schemas containing refinements");const i=q4(s._zod.def,{get shape(){const l={};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&(l[o]=n.shape[o])}return $M(this,"shape",l),l},checks:[]});return V4(s,i)}function IUt(s,t){const n=s._zod.def,r=n.checks;if(r&&r.length>0)throw new Error(".omit() cannot be used on object schemas containing refinements");const i=q4(s._zod.def,{get shape(){const l={...s._zod.def.shape};for(const o in t){if(!(o in n.shape))throw new Error(`Unrecognized key: "${o}"`);t[o]&&delete l[o]}return $M(this,"shape",l),l},checks:[]});return V4(s,i)}function PUt(s,t){if(!tB(t))throw new Error("Invalid input to extend: expected a plain object");const n=s._zod.def.checks;if(n&&n.length>0){const i=s._zod.def.shape;for(const l in t)if(Object.getOwnPropertyDescriptor(i,l)!==void 0)throw new Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}const a=q4(s._zod.def,{get shape(){const i={...s._zod.def.shape,...t};return $M(this,"shape",i),i}});return V4(s,a)}function LUt(s,t){if(!tB(t))throw new Error("Invalid input to safeExtend: expected a plain object");const n=q4(s._zod.def,{get shape(){const r={...s._zod.def.shape,...t};return $M(this,"shape",r),r}});return V4(s,n)}function DUt(s,t){var r;if((r=s._zod.def.checks)!=null&&r.length)throw new Error(".merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.");const n=q4(s._zod.def,{get shape(){const a={...s._zod.def.shape,...t._zod.def.shape};return $M(this,"shape",a),a},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]});return V4(s,n)}function RUt(s,t,n){const a=t._zod.def.checks;if(a&&a.length>0)throw new Error(".partial() cannot be used on object schemas containing refinements");const l=q4(t._zod.def,{get shape(){const o=t._zod.def.shape,c={...o};if(n)for(const d in n){if(!(d in o))throw new Error(`Unrecognized key: "${d}"`);n[d]&&(c[d]=s?new s({type:"optional",innerType:o[d]}):o[d])}else for(const d in o)c[d]=s?new s({type:"optional",innerType:o[d]}):o[d];return $M(this,"shape",c),c},checks:[]});return V4(t,l)}function OUt(s,t,n){const r=q4(t._zod.def,{get shape(){const a=t._zod.def.shape,i={...a};if(n)for(const l in n){if(!(l in i))throw new Error(`Unrecognized key: "${l}"`);n[l]&&(i[l]=new s({type:"nonoptional",innerType:a[l]}))}else for(const l in a)i[l]=new s({type:"nonoptional",innerType:a[l]});return $M(this,"shape",i),i}});return V4(t,r)}function _P(s,t=0){var n;if(s.aborted===!0)return!0;for(let r=t;r{var r;return(r=n).path??(r.path=[]),n.path.unshift(s),n})}function WV(s){return typeof s=="string"?s:s==null?void 0:s.message}function pM(s,t,n){var c,d,u,h,p,f;const r=s.message?s.message:WV((u=(d=(c=s.inst)==null?void 0:c._zod.def)==null?void 0:d.error)==null?void 0:u.call(d,s))??WV((h=t==null?void 0:t.error)==null?void 0:h.call(t,s))??WV((p=n.customError)==null?void 0:p.call(n,s))??WV((f=n.localeError)==null?void 0:f.call(n,s))??"Invalid input",{inst:a,continue:i,input:l,...o}=s;return o.path??(o.path=[]),o.message=r,t!=null&&t.reportInput&&(o.input=l),o}function KAe(s){return Array.isArray(s)?"array":typeof s=="string"?"string":"unknown"}function sB(...s){const[t,n,r]=s;return typeof t=="string"?{message:t,code:"custom",input:n,inst:r}:{...t}}const wct=(s,t)=>{s.name="$ZodError",Object.defineProperty(s,"_zod",{value:s._zod,enumerable:!1}),Object.defineProperty(s,"issues",{value:t,enumerable:!1}),s.message=JSON.stringify(t,v4e,2),Object.defineProperty(s,"toString",{value:()=>s.message,enumerable:!1})},jct=mr("$ZodError",wct),Nct=mr("$ZodError",wct,{Parent:Error});function zUt(s,t=n=>n.message){const n={},r=[];for(const a of s.issues)a.path.length>0?(n[a.path[0]]=n[a.path[0]]||[],n[a.path[0]].push(t(a))):r.push(t(a));return{formErrors:r,fieldErrors:n}}function BUt(s,t=n=>n.message){const n={_errors:[]},r=(a,i=[])=>{for(const l of a.issues)if(l.code==="invalid_union"&&l.errors.length)l.errors.map(o=>r({issues:o},[...i,...l.path]));else if(l.code==="invalid_key")r({issues:l.issues},[...i,...l.path]);else if(l.code==="invalid_element")r({issues:l.issues},[...i,...l.path]);else{const o=[...i,...l.path];if(o.length===0)n._errors.push(t(l));else{let c=n,d=0;for(;d(t,n,r,a)=>{const i=r?{...r,async:!1}:{async:!1},l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw new kL;if(l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>pM(c,i,mM())));throw vct(o,a==null?void 0:a.callee),o}return l.value},ZAe=s=>async(t,n,r,a)=>{const i=r?{...r,async:!0}:{async:!0};let l=t._zod.run({value:n,issues:[]},i);if(l instanceof Promise&&(l=await l),l.issues.length){const o=new((a==null?void 0:a.Err)??s)(l.issues.map(c=>pM(c,i,mM())));throw vct(o,a==null?void 0:a.callee),o}return l.value},nye=s=>(t,n,r)=>{const a=r?{...r,async:!1}:{async:!1},i=t._zod.run({value:n,issues:[]},a);if(i instanceof Promise)throw new kL;return i.issues.length?{success:!1,error:new(s??jct)(i.issues.map(l=>pM(l,a,mM())))}:{success:!0,data:i.value}},$Ut=nye(Nct),rye=s=>async(t,n,r)=>{const a=r?{...r,async:!0}:{async:!0};let i=t._zod.run({value:n,issues:[]},a);return i instanceof Promise&&(i=await i),i.issues.length?{success:!1,error:new s(i.issues.map(l=>pM(l,a,mM())))}:{success:!0,data:i.value}},UUt=rye(Nct),qUt=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return YAe(s)(t,n,a)},VUt=s=>(t,n,r)=>YAe(s)(t,n,r),HUt=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return ZAe(s)(t,n,a)},GUt=s=>async(t,n,r)=>ZAe(s)(t,n,r),WUt=s=>(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return nye(s)(t,n,a)},KUt=s=>(t,n,r)=>nye(s)(t,n,r),YUt=s=>async(t,n,r)=>{const a=r?{...r,direction:"backward"}:{direction:"backward"};return rye(s)(t,n,a)},ZUt=s=>async(t,n,r)=>rye(s)(t,n,r),QUt=/^[cC][0-9a-z]{6,}$/,XUt=/^[0-9a-z]+$/,JUt=/^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/,eqt=/^[0-9a-vA-V]{20}$/,tqt=/^[A-Za-z0-9]{27}$/,sqt=/^[a-zA-Z0-9_-]{21}$/,nqt=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,rqt=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,eBe=s=>s?new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${s}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,aqt=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,iqt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$";function oqt(){return new RegExp(iqt,"u")}const lqt=/^(?:(?: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])$/,cqt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,dqt=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,uqt=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,hqt=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,kct=/^[A-Za-z0-9_-]*$/,mqt=/^https?$/,pqt=/^\+[1-9]\d{6,14}$/,Sct="(?:(?:\\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])))",fqt=new RegExp(`^${Sct}$`);function Cct(s){const t="(?:[01]\\d|2[0-3]):[0-5]\\d";return typeof s.precision=="number"?s.precision===-1?`${t}`:s.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${s.precision}}`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function xqt(s){return new RegExp(`^${Cct(s)}$`)}function gqt(s){const t=Cct({precision:s.precision}),n=["Z"];s.local&&n.push(""),s.offset&&n.push("([+-](?:[01]\\d|2[0-3]):[0-5]\\d)");const r=`${t}(?:${n.join("|")})`;return new RegExp(`^${Sct}T(?:${r})$`)}const yqt=s=>{const t=s?`[\\s\\S]{${(s==null?void 0:s.minimum)??0},${(s==null?void 0:s.maximum)??""}}`:"[\\s\\S]*";return new RegExp(`^${t}$`)},vqt=/^-?\d+$/,bqt=/^-?\d+(?:\.\d+)?$/,_qt=/^(?:true|false)$/i,wqt=/^[^A-Z]*$/,jqt=/^[^a-z]*$/,e0=mr("$ZodCheck",(s,t)=>{var n;s._zod??(s._zod={}),s._zod.def=t,(n=s._zod).onattach??(n.onattach=[])}),Tct={number:"number",bigint:"bigint",object:"date"},Ect=mr("$ZodCheckLessThan",(s,t)=>{e0.init(s,t);const n=Tct[typeof t.value];s._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.maximum:a.exclusiveMaximum)??Number.POSITIVE_INFINITY;t.value{(t.inclusive?r.value<=t.value:r.value{e0.init(s,t);const n=Tct[typeof t.value];s._zod.onattach.push(r=>{const a=r._zod.bag,i=(t.inclusive?a.minimum:a.exclusiveMinimum)??Number.NEGATIVE_INFINITY;t.value>i&&(t.inclusive?a.minimum=t.value:a.exclusiveMinimum=t.value)}),s._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:n,code:"too_small",minimum:typeof t.value=="object"?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:s,continue:!t.abort})}}),Nqt=mr("$ZodCheckMultipleOf",(s,t)=>{e0.init(s,t),s._zod.onattach.push(n=>{var r;(r=n._zod.bag).multipleOf??(r.multipleOf=t.value)}),s._zod.check=n=>{if(typeof n.value!=typeof t.value)throw new Error("Cannot mix number and bigint in multiple_of check.");(typeof n.value=="bigint"?n.value%t.value===BigInt(0):kUt(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:"not_multiple_of",divisor:t.value,input:n.value,inst:s,continue:!t.abort})}}),kqt=mr("$ZodCheckNumberFormat",(s,t)=>{var l;e0.init(s,t),t.format=t.format||"float64";const n=(l=t.format)==null?void 0:l.includes("int"),r=n?"int":"number",[a,i]=AUt[t.format];s._zod.onattach.push(o=>{const c=o._zod.bag;c.format=t.format,c.minimum=a,c.maximum=i,n&&(c.pattern=vqt)}),s._zod.check=o=>{const c=o.value;if(n){if(!Number.isInteger(c)){o.issues.push({expected:r,format:t.format,code:"invalid_type",continue:!1,input:c,inst:s});return}if(!Number.isSafeInteger(c)){c>0?o.issues.push({input:c,code:"too_big",maximum:Number.MAX_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:c,code:"too_small",minimum:Number.MIN_SAFE_INTEGER,note:"Integers must be within the safe integer range.",inst:s,origin:r,inclusive:!0,continue:!t.abort});return}}ci&&o.issues.push({origin:"number",input:c,code:"too_big",maximum:i,inclusive:!0,inst:s,continue:!t.abort})}}),Sqt=mr("$ZodCheckMaxLength",(s,t)=>{var n;e0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!GAe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag.maximum??Number.POSITIVE_INFINITY;t.maximum{const a=r.value;if(a.length<=t.maximum)return;const l=KAe(a);r.issues.push({origin:l,code:"too_big",maximum:t.maximum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),Cqt=mr("$ZodCheckMinLength",(s,t)=>{var n;e0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!GAe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag.minimum??Number.NEGATIVE_INFINITY;t.minimum>a&&(r._zod.bag.minimum=t.minimum)}),s._zod.check=r=>{const a=r.value;if(a.length>=t.minimum)return;const l=KAe(a);r.issues.push({origin:l,code:"too_small",minimum:t.minimum,inclusive:!0,input:a,inst:s,continue:!t.abort})}}),Tqt=mr("$ZodCheckLengthEquals",(s,t)=>{var n;e0.init(s,t),(n=s._zod.def).when??(n.when=r=>{const a=r.value;return!GAe(a)&&a.length!==void 0}),s._zod.onattach.push(r=>{const a=r._zod.bag;a.minimum=t.length,a.maximum=t.length,a.length=t.length}),s._zod.check=r=>{const a=r.value,i=a.length;if(i===t.length)return;const l=KAe(a),o=i>t.length;r.issues.push({origin:l,...o?{code:"too_big",maximum:t.length}:{code:"too_small",minimum:t.length},inclusive:!0,exact:!0,input:r.value,inst:s,continue:!t.abort})}}),aye=mr("$ZodCheckStringFormat",(s,t)=>{var n,r;e0.init(s,t),s._zod.onattach.push(a=>{const i=a._zod.bag;i.format=t.format,t.pattern&&(i.patterns??(i.patterns=new Set),i.patterns.add(t.pattern))}),t.pattern?(n=s._zod).check??(n.check=a=>{t.pattern.lastIndex=0,!t.pattern.test(a.value)&&a.issues.push({origin:"string",code:"invalid_format",format:t.format,input:a.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:s,continue:!t.abort})}):(r=s._zod).check??(r.check=()=>{})}),Eqt=mr("$ZodCheckRegex",(s,t)=>{aye.init(s,t),s._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:"string",code:"invalid_format",format:"regex",input:n.value,pattern:t.pattern.toString(),inst:s,continue:!t.abort})}}),Aqt=mr("$ZodCheckLowerCase",(s,t)=>{t.pattern??(t.pattern=wqt),aye.init(s,t)}),Mqt=mr("$ZodCheckUpperCase",(s,t)=>{t.pattern??(t.pattern=jqt),aye.init(s,t)}),Iqt=mr("$ZodCheckIncludes",(s,t)=>{e0.init(s,t);const n=g8(t.includes),r=new RegExp(typeof t.position=="number"?`^.{${t.position}}${n}`:n);t.pattern=r,s._zod.onattach.push(a=>{const i=a._zod.bag;i.patterns??(i.patterns=new Set),i.patterns.add(r)}),s._zod.check=a=>{a.value.includes(t.includes,t.position)||a.issues.push({origin:"string",code:"invalid_format",format:"includes",includes:t.includes,input:a.value,inst:s,continue:!t.abort})}}),Pqt=mr("$ZodCheckStartsWith",(s,t)=>{e0.init(s,t);const n=new RegExp(`^${g8(t.prefix)}.*`);t.pattern??(t.pattern=n),s._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),s._zod.check=r=>{r.value.startsWith(t.prefix)||r.issues.push({origin:"string",code:"invalid_format",format:"starts_with",prefix:t.prefix,input:r.value,inst:s,continue:!t.abort})}}),Lqt=mr("$ZodCheckEndsWith",(s,t)=>{e0.init(s,t);const n=new RegExp(`.*${g8(t.suffix)}$`);t.pattern??(t.pattern=n),s._zod.onattach.push(r=>{const a=r._zod.bag;a.patterns??(a.patterns=new Set),a.patterns.add(n)}),s._zod.check=r=>{r.value.endsWith(t.suffix)||r.issues.push({origin:"string",code:"invalid_format",format:"ends_with",suffix:t.suffix,input:r.value,inst:s,continue:!t.abort})}}),Dqt=mr("$ZodCheckOverwrite",(s,t)=>{e0.init(s,t),s._zod.check=n=>{n.value=t.tx(n.value)}});class Rqt{constructor(t=[]){this.content=[],this.indent=0,this&&(this.args=t)}indented(t){this.indent+=1,t(this),this.indent-=1}write(t){if(typeof t=="function"){t(this,{execution:"sync"}),t(this,{execution:"async"});return}const r=t.split(` `).filter(l=>l),a=Math.min(...r.map(l=>l.length-l.trimStart().length)),i=r.map(l=>l.slice(a)).map(l=>" ".repeat(this.indent*2)+l);for(const l of i)this.content.push(l)}compile(){const t=Function,n=this==null?void 0:this.args,a=[...((this==null?void 0:this.content)??[""]).map(i=>` ${i}`)];return new t(...n,a.join(` `))}}const Oqt={major:4,minor:4,patch:3},uh=mr("$ZodType",(s,t)=>{var a;var n;s??(s={}),s._zod.def=t,s._zod.bag=s._zod.bag||{},s._zod.version=Oqt;const r=[...s._zod.def.checks??[]];s._zod.traits.has("$ZodCheck")&&r.unshift(s);for(const i of r)for(const l of i._zod.onattach)l(s);if(r.length===0)(n=s._zod).deferred??(n.deferred=[]),(a=s._zod.deferred)==null||a.push(()=>{s._zod.run=s._zod.parse});else{const i=(o,c,d)=>{let u=_P(o),h;for(const p of c){if(p._zod.def.when){if(FUt(o)||!p._zod.def.when(o))continue}else if(u)continue;const f=o.issues.length,y=p._zod.check(o);if(y instanceof Promise&&(d==null?void 0:d.async)===!1)throw new kL;if(h||y instanceof Promise)h=(h??Promise.resolve()).then(async()=>{await y,o.issues.length!==f&&(u||(u=_P(o,f)))});else{if(o.issues.length===f)continue;u||(u=_P(o,f))}}return h?h.then(()=>o):o},l=(o,c,d)=>{if(_P(o))return o.aborted=!0,o;const u=i(c,r,d);if(u instanceof Promise){if(d.async===!1)throw new kL;return u.then(h=>s._zod.parse(h,d))}return s._zod.parse(u,d)};s._zod.run=(o,c)=>{if(c.skipChecks)return s._zod.parse(o,c);if(c.direction==="backward"){const u=s._zod.parse({value:o.value,issues:[]},{...c,skipChecks:!0});return u instanceof Promise?u.then(h=>l(h,o,c)):l(u,o,c)}const d=s._zod.parse(o,c);if(d instanceof Promise){if(c.async===!1)throw new kL;return d.then(u=>i(u,r,c))}return i(d,r,c)}}Vc(s,"~standard",()=>({validate:i=>{var l;try{const o=$Ut(s,i);return o.success?{value:o.data}:{issues:(l=o.error)==null?void 0:l.issues}}catch{return UUt(s,i).then(c=>{var d;return c.success?{value:c.data}:{issues:(d=c.error)==null?void 0:d.issues}})}},vendor:"zod",version:1}))}),QAe=mr("$ZodString",(s,t)=>{var n;uh.init(s,t),s._zod.pattern=[...((n=s==null?void 0:s._zod.bag)==null?void 0:n.patterns)??[]].pop()??yqt(s._zod.bag),s._zod.parse=(r,a)=>{if(t.coerce)try{r.value=String(r.value)}catch{}return typeof r.value=="string"||r.issues.push({expected:"string",code:"invalid_type",input:r.value,inst:s}),r}}),hu=mr("$ZodStringFormat",(s,t)=>{aye.init(s,t),QAe.init(s,t)}),Fqt=mr("$ZodGUID",(s,t)=>{t.pattern??(t.pattern=rqt),hu.init(s,t)}),zqt=mr("$ZodUUID",(s,t)=>{if(t.version){const r={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(r===void 0)throw new Error(`Invalid UUID version: "${t.version}"`);t.pattern??(t.pattern=eBe(r))}else t.pattern??(t.pattern=eBe());hu.init(s,t)}),Bqt=mr("$ZodEmail",(s,t)=>{t.pattern??(t.pattern=aqt),hu.init(s,t)}),$qt=mr("$ZodURL",(s,t)=>{hu.init(s,t),s._zod.check=n=>{var r;try{const a=n.value.trim();if(!t.normalize&&((r=t.protocol)==null?void 0:r.source)===mqt.source&&!/^https?:\/\//i.test(a)){n.issues.push({code:"invalid_format",format:"url",note:"Invalid URL format",input:n.value,inst:s,continue:!t.abort});return}const i=new URL(a);t.hostname&&(t.hostname.lastIndex=0,t.hostname.test(i.hostname)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid hostname",pattern:t.hostname.source,input:n.value,inst:s,continue:!t.abort})),t.protocol&&(t.protocol.lastIndex=0,t.protocol.test(i.protocol.endsWith(":")?i.protocol.slice(0,-1):i.protocol)||n.issues.push({code:"invalid_format",format:"url",note:"Invalid protocol",pattern:t.protocol.source,input:n.value,inst:s,continue:!t.abort})),t.normalize?n.value=i.href:n.value=a;return}catch{n.issues.push({code:"invalid_format",format:"url",input:n.value,inst:s,continue:!t.abort})}}}),Uqt=mr("$ZodEmoji",(s,t)=>{t.pattern??(t.pattern=oqt()),hu.init(s,t)}),qqt=mr("$ZodNanoID",(s,t)=>{t.pattern??(t.pattern=sqt),hu.init(s,t)}),Vqt=mr("$ZodCUID",(s,t)=>{t.pattern??(t.pattern=QUt),hu.init(s,t)}),Hqt=mr("$ZodCUID2",(s,t)=>{t.pattern??(t.pattern=XUt),hu.init(s,t)}),Gqt=mr("$ZodULID",(s,t)=>{t.pattern??(t.pattern=JUt),hu.init(s,t)}),Wqt=mr("$ZodXID",(s,t)=>{t.pattern??(t.pattern=eqt),hu.init(s,t)}),Kqt=mr("$ZodKSUID",(s,t)=>{t.pattern??(t.pattern=tqt),hu.init(s,t)}),Yqt=mr("$ZodISODateTime",(s,t)=>{t.pattern??(t.pattern=gqt(t)),hu.init(s,t)}),Zqt=mr("$ZodISODate",(s,t)=>{t.pattern??(t.pattern=fqt),hu.init(s,t)}),Qqt=mr("$ZodISOTime",(s,t)=>{t.pattern??(t.pattern=xqt(t)),hu.init(s,t)}),Xqt=mr("$ZodISODuration",(s,t)=>{t.pattern??(t.pattern=nqt),hu.init(s,t)}),Jqt=mr("$ZodIPv4",(s,t)=>{t.pattern??(t.pattern=lqt),hu.init(s,t),s._zod.bag.format="ipv4"}),eVt=mr("$ZodIPv6",(s,t)=>{t.pattern??(t.pattern=cqt),hu.init(s,t),s._zod.bag.format="ipv6",s._zod.check=n=>{try{new URL(`http://[${n.value}]`)}catch{n.issues.push({code:"invalid_format",format:"ipv6",input:n.value,inst:s,continue:!t.abort})}}}),tVt=mr("$ZodCIDRv4",(s,t)=>{t.pattern??(t.pattern=dqt),hu.init(s,t)}),sVt=mr("$ZodCIDRv6",(s,t)=>{t.pattern??(t.pattern=uqt),hu.init(s,t),s._zod.check=n=>{const r=n.value.split("/");try{if(r.length!==2)throw new Error;const[a,i]=r;if(!i)throw new Error;const l=Number(i);if(`${l}`!==i)throw new Error;if(l<0||l>128)throw new Error;new URL(`http://[${a}]`)}catch{n.issues.push({code:"invalid_format",format:"cidrv6",input:n.value,inst:s,continue:!t.abort})}}});function Mct(s){if(s==="")return!0;if(/\s/.test(s)||s.length%4!==0)return!1;try{return atob(s),!0}catch{return!1}}const nVt=mr("$ZodBase64",(s,t)=>{t.pattern??(t.pattern=hqt),hu.init(s,t),s._zod.bag.contentEncoding="base64",s._zod.check=n=>{Mct(n.value)||n.issues.push({code:"invalid_format",format:"base64",input:n.value,inst:s,continue:!t.abort})}});function rVt(s){if(!kct.test(s))return!1;const t=s.replace(/[-_]/g,r=>r==="-"?"+":"/"),n=t.padEnd(Math.ceil(t.length/4)*4,"=");return Mct(n)}const aVt=mr("$ZodBase64URL",(s,t)=>{t.pattern??(t.pattern=kct),hu.init(s,t),s._zod.bag.contentEncoding="base64url",s._zod.check=n=>{rVt(n.value)||n.issues.push({code:"invalid_format",format:"base64url",input:n.value,inst:s,continue:!t.abort})}}),iVt=mr("$ZodE164",(s,t)=>{t.pattern??(t.pattern=pqt),hu.init(s,t)});function oVt(s,t=null){try{const n=s.split(".");if(n.length!==3)return!1;const[r]=n;if(!r)return!1;const a=JSON.parse(atob(r));return!("typ"in a&&(a==null?void 0:a.typ)!=="JWT"||!a.alg||t&&(!("alg"in a)||a.alg!==t))}catch{return!1}}const lVt=mr("$ZodJWT",(s,t)=>{hu.init(s,t),s._zod.check=n=>{oVt(n.value,t.alg)||n.issues.push({code:"invalid_format",format:"jwt",input:n.value,inst:s,continue:!t.abort})}}),Ict=mr("$ZodNumber",(s,t)=>{uh.init(s,t),s._zod.pattern=s._zod.bag.pattern??bqt,s._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}const a=n.value;if(typeof a=="number"&&!Number.isNaN(a)&&Number.isFinite(a))return n;const i=typeof a=="number"?Number.isNaN(a)?"NaN":Number.isFinite(a)?void 0:"Infinity":void 0;return n.issues.push({expected:"number",code:"invalid_type",input:a,inst:s,...i?{received:i}:{}}),n}}),cVt=mr("$ZodNumberFormat",(s,t)=>{kqt.init(s,t),Ict.init(s,t)}),dVt=mr("$ZodBoolean",(s,t)=>{uh.init(s,t),s._zod.pattern=_qt,s._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}const a=n.value;return typeof a=="boolean"||n.issues.push({expected:"boolean",code:"invalid_type",input:a,inst:s}),n}}),uVt=mr("$ZodUnknown",(s,t)=>{uh.init(s,t),s._zod.parse=n=>n}),hVt=mr("$ZodNever",(s,t)=>{uh.init(s,t),s._zod.parse=(n,r)=>(n.issues.push({expected:"never",code:"invalid_type",input:n.value,inst:s}),n)});function tBe(s,t,n){s.issues.length&&t.issues.push(..._ct(n,s.issues)),t.value[n]=s.value}const mVt=mr("$ZodArray",(s,t)=>{uh.init(s,t),s._zod.parse=(n,r)=>{const a=n.value;if(!Array.isArray(a))return n.issues.push({expected:"array",code:"invalid_type",input:a,inst:s}),n;n.value=Array(a.length);const i=[];for(let l=0;ltBe(d,n,l))):tBe(c,n,l)}return i.length?Promise.all(i).then(()=>n):n}});function Qpe(s,t,n,r,a,i){const l=n in r;if(s.issues.length){if(a&&i&&!l)return;t.issues.push(..._ct(n,s.issues))}if(!l&&!a){s.issues.length||t.issues.push({code:"invalid_type",expected:"nonoptional",input:void 0,path:[n]});return}s.value===void 0?l&&(t.value[n]=void 0):t.value[n]=s.value}function Pct(s){var r,a,i,l;const t=Object.keys(s.shape);for(const o of t)if(!((l=(i=(a=(r=s.shape)==null?void 0:r[o])==null?void 0:a._zod)==null?void 0:i.traits)!=null&&l.has("$ZodType")))throw new Error(`Invalid element at key "${o}": expected a Zod schema`);const n=EUt(s.shape);return{...s,keys:t,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(n)}}function Lct(s,t,n,r,a,i){const l=[],o=a.keySet,c=a.catchall._zod,d=c.def.type,u=c.optin==="optional",h=c.optout==="optional";for(const p in t){if(p==="__proto__"||o.has(p))continue;if(d==="never"){l.push(p);continue}const f=c.run({value:t[p],issues:[]},r);f instanceof Promise?s.push(f.then(y=>Qpe(y,n,p,t,u,h))):Qpe(f,n,p,t,u,h)}return l.length&&n.issues.push({code:"unrecognized_keys",keys:l,input:t,inst:i}),s.length?Promise.all(s).then(()=>n):n}const pVt=mr("$ZodObject",(s,t)=>{uh.init(s,t);const n=Object.getOwnPropertyDescriptor(t,"shape");if(!(n!=null&&n.get)){const o=t.shape;Object.defineProperty(t,"shape",{get:()=>{const c={...o};return Object.defineProperty(t,"shape",{value:c}),c}})}const r=HAe(()=>Pct(t));Vc(s._zod,"propValues",()=>{const o=t.shape,c={};for(const d in o){const u=o[d]._zod;if(u.values){c[d]??(c[d]=new Set);for(const h of u.values)c[d].add(h)}}return c});const a=Zpe,i=t.catchall;let l;s._zod.parse=(o,c)=>{l??(l=r.value);const d=o.value;if(!a(d))return o.issues.push({expected:"object",code:"invalid_type",input:d,inst:s}),o;o.value={};const u=[],h=l.shape;for(const p of l.keys){const f=h[p],y=f._zod.optin==="optional",_=f._zod.optout==="optional",v=f._zod.run({value:d[p],issues:[]},c);v instanceof Promise?u.push(v.then(j=>Qpe(j,o,p,d,y,_))):Qpe(v,o,p,d,y,_)}return i?Lct(u,d,o,c,r.value,s):u.length?Promise.all(u).then(()=>o):o}}),fVt=mr("$ZodObjectJIT",(s,t)=>{pVt.init(s,t);const n=s._zod.parse,r=HAe(()=>Pct(t)),a=p=>{var S,A;const f=new Rqt(["shape","payload","ctx"]),y=r.value,_=E=>{const O=Jze(E);return`shape[${O}]._zod.run({ value: input[${O}], issues: [] }, ctx)`};f.write("const input = payload.value;");const v=Object.create(null);let j=0;for(const E of y.keys)v[E]=`key_${j++}`;f.write("const newResult = {};");for(const E of y.keys){const O=v[E],D=Jze(E),I=p[E],F=((S=I==null?void 0:I._zod)==null?void 0:S.optin)==="optional",z=((A=I==null?void 0:I._zod)==null?void 0:A.optout)==="optional";f.write(`const ${O} = ${_(E)};`),F&&z?f.write(` if (${O}.issues.length) { if (${D} in input) { payload.issues = payload.issues.concat(${O}.issues.map(iss => ({ ...iss, path: iss.path ? [${D}, ...iss.path] : [${D}] }))); } } if (${O}.value === undefined) { if (${D} in input) { newResult[${D}] = undefined; } } else { newResult[${D}] = ${O}.value; } `):F?f.write(` if (${O}.issues.length) { payload.issues = payload.issues.concat(${O}.issues.map(iss => ({ ...iss, path: iss.path ? [${D}, ...iss.path] : [${D}] }))); } if (${O}.value === undefined) { if (${D} in input) { newResult[${D}] = undefined; } } else { newResult[${D}] = ${O}.value; } `):f.write(` const ${O}_present = ${D} in input; if (${O}.issues.length) { payload.issues = payload.issues.concat(${O}.issues.map(iss => ({ ...iss, path: iss.path ? [${D}, ...iss.path] : [${D}] }))); } if (!${O}_present && !${O}.issues.length) { payload.issues.push({ code: "invalid_type", expected: "nonoptional", input: undefined, path: [${D}] }); } if (${O}_present) { if (${O}.value === undefined) { newResult[${D}] = undefined; } else { newResult[${D}] = ${O}.value; } } `)}f.write("payload.value = newResult;"),f.write("return payload;");const w=f.compile();return(E,O)=>w(p,E,O)};let i;const l=Zpe,o=!VAe.jitless,d=o&&CUt.value,u=t.catchall;let h;s._zod.parse=(p,f)=>{h??(h=r.value);const y=p.value;return l(y)?o&&d&&(f==null?void 0:f.async)===!1&&f.jitless!==!0?(i||(i=a(t.shape)),p=i(p,f),u?Lct([],y,p,f,h,s):p):n(p,f):(p.issues.push({expected:"object",code:"invalid_type",input:y,inst:s}),p)}});function sBe(s,t,n,r){for(const i of s)if(i.issues.length===0)return t.value=i.value,t;const a=s.filter(i=>!_P(i));return a.length===1?(t.value=a[0].value,a[0]):(t.issues.push({code:"invalid_union",input:t.value,inst:n,errors:s.map(i=>i.issues.map(l=>pM(l,r,mM())))}),t)}const xVt=mr("$ZodUnion",(s,t)=>{uh.init(s,t),Vc(s._zod,"optin",()=>t.options.some(r=>r._zod.optin==="optional")?"optional":void 0),Vc(s._zod,"optout",()=>t.options.some(r=>r._zod.optout==="optional")?"optional":void 0),Vc(s._zod,"values",()=>{if(t.options.every(r=>r._zod.values))return new Set(t.options.flatMap(r=>Array.from(r._zod.values)))}),Vc(s._zod,"pattern",()=>{if(t.options.every(r=>r._zod.pattern)){const r=t.options.map(a=>a._zod.pattern);return new RegExp(`^(${r.map(a=>WAe(a.source)).join("|")})$`)}});const n=t.options.length===1?t.options[0]._zod.run:null;s._zod.parse=(r,a)=>{if(n)return n(r,a);let i=!1;const l=[];for(const o of t.options){const c=o._zod.run({value:r.value,issues:[]},a);if(c instanceof Promise)l.push(c),i=!0;else{if(c.issues.length===0)return c;l.push(c)}}return i?Promise.all(l).then(o=>sBe(o,r,s,a)):sBe(l,r,s,a)}}),gVt=mr("$ZodIntersection",(s,t)=>{uh.init(s,t),s._zod.parse=(n,r)=>{const a=n.value,i=t.left._zod.run({value:a,issues:[]},r),l=t.right._zod.run({value:a,issues:[]},r);return i instanceof Promise||l instanceof Promise?Promise.all([i,l]).then(([c,d])=>nBe(n,c,d)):nBe(n,i,l)}});function b4e(s,t){if(s===t)return{valid:!0,data:s};if(s instanceof Date&&t instanceof Date&&+s==+t)return{valid:!0,data:s};if(tB(s)&&tB(t)){const n=Object.keys(t),r=Object.keys(s).filter(i=>n.indexOf(i)!==-1),a={...s,...t};for(const i of r){const l=b4e(s[i],t[i]);if(!l.valid)return{valid:!1,mergeErrorPath:[i,...l.mergeErrorPath]};a[i]=l.data}return{valid:!0,data:a}}if(Array.isArray(s)&&Array.isArray(t)){if(s.length!==t.length)return{valid:!1,mergeErrorPath:[]};const n=[];for(let r=0;ro.l&&o.r).map(([o])=>o);if(i.length&&a&&s.issues.push({...a,keys:i}),_P(s))return s;const l=b4e(t.value,n.value);if(!l.valid)throw new Error(`Unmergable intersection. Error path: ${JSON.stringify(l.mergeErrorPath)}`);return s.value=l.data,s}const yVt=mr("$ZodEnum",(s,t)=>{uh.init(s,t);const n=yct(t.entries),r=new Set(n);s._zod.values=r,s._zod.pattern=new RegExp(`^(${n.filter(a=>TUt.has(typeof a)).map(a=>typeof a=="string"?g8(a):a.toString()).join("|")})$`),s._zod.parse=(a,i)=>{const l=a.value;return r.has(l)||a.issues.push({code:"invalid_value",values:n,input:l,inst:s}),a}}),vVt=mr("$ZodLiteral",(s,t)=>{if(uh.init(s,t),t.values.length===0)throw new Error("Cannot create literal schema with no valid values");const n=new Set(t.values);s._zod.values=n,s._zod.pattern=new RegExp(`^(${t.values.map(r=>typeof r=="string"?g8(r):r?g8(r.toString()):String(r)).join("|")})$`),s._zod.parse=(r,a)=>{const i=r.value;return n.has(i)||r.issues.push({code:"invalid_value",values:t.values,input:i,inst:s}),r}}),bVt=mr("$ZodTransform",(s,t)=>{uh.init(s,t),s._zod.optin="optional",s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gct(s.constructor.name);const a=t.transform(n.value,n);if(r.async)return(a instanceof Promise?a:Promise.resolve(a)).then(l=>(n.value=l,n.fallback=!0,n));if(a instanceof Promise)throw new kL;return n.value=a,n.fallback=!0,n}});function rBe(s,t){return t===void 0&&(s.issues.length||s.fallback)?{issues:[],value:void 0}:s}const Dct=mr("$ZodOptional",(s,t)=>{uh.init(s,t),s._zod.optin="optional",s._zod.optout="optional",Vc(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,void 0]):void 0),Vc(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${WAe(n.source)})?$`):void 0}),s._zod.parse=(n,r)=>{if(t.innerType._zod.optin==="optional"){const a=n.value,i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(l=>rBe(l,a)):rBe(i,a)}return n.value===void 0?n:t.innerType._zod.run(n,r)}}),_Vt=mr("$ZodExactOptional",(s,t)=>{Dct.init(s,t),Vc(s._zod,"values",()=>t.innerType._zod.values),Vc(s._zod,"pattern",()=>t.innerType._zod.pattern),s._zod.parse=(n,r)=>t.innerType._zod.run(n,r)}),wVt=mr("$ZodNullable",(s,t)=>{uh.init(s,t),Vc(s._zod,"optin",()=>t.innerType._zod.optin),Vc(s._zod,"optout",()=>t.innerType._zod.optout),Vc(s._zod,"pattern",()=>{const n=t.innerType._zod.pattern;return n?new RegExp(`^(${WAe(n.source)}|null)$`):void 0}),Vc(s._zod,"values",()=>t.innerType._zod.values?new Set([...t.innerType._zod.values,null]):void 0),s._zod.parse=(n,r)=>n.value===null?n:t.innerType._zod.run(n,r)}),jVt=mr("$ZodDefault",(s,t)=>{uh.init(s,t),s._zod.optin="optional",Vc(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);if(n.value===void 0)return n.value=t.defaultValue,n;const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>aBe(i,t)):aBe(a,t)}});function aBe(s,t){return s.value===void 0&&(s.value=t.defaultValue),s}const NVt=mr("$ZodPrefault",(s,t)=>{uh.init(s,t),s._zod.optin="optional",Vc(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(n,r)=>(r.direction==="backward"||n.value===void 0&&(n.value=t.defaultValue),t.innerType._zod.run(n,r))}),kVt=mr("$ZodNonOptional",(s,t)=>{uh.init(s,t),Vc(s._zod,"values",()=>{const n=t.innerType._zod.values;return n?new Set([...n].filter(r=>r!==void 0)):void 0}),s._zod.parse=(n,r)=>{const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>iBe(i,s)):iBe(a,s)}});function iBe(s,t){return!s.issues.length&&s.value===void 0&&s.issues.push({code:"invalid_type",expected:"nonoptional",input:s.value,inst:t}),s}const SVt=mr("$ZodCatch",(s,t)=>{uh.init(s,t),s._zod.optin="optional",Vc(s._zod,"optout",()=>t.innerType._zod.optout),Vc(s._zod,"values",()=>t.innerType._zod.values),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(i=>(n.value=i.value,i.issues.length&&(n.value=t.catchValue({...n,error:{issues:i.issues.map(l=>pM(l,r,mM()))},input:n.value}),n.issues=[],n.fallback=!0),n)):(n.value=a.value,a.issues.length&&(n.value=t.catchValue({...n,error:{issues:a.issues.map(i=>pM(i,r,mM()))},input:n.value}),n.issues=[],n.fallback=!0),n)}}),CVt=mr("$ZodPipe",(s,t)=>{uh.init(s,t),Vc(s._zod,"values",()=>t.in._zod.values),Vc(s._zod,"optin",()=>t.in._zod.optin),Vc(s._zod,"optout",()=>t.out._zod.optout),Vc(s._zod,"propValues",()=>t.in._zod.propValues),s._zod.parse=(n,r)=>{if(r.direction==="backward"){const i=t.out._zod.run(n,r);return i instanceof Promise?i.then(l=>KV(l,t.in,r)):KV(i,t.in,r)}const a=t.in._zod.run(n,r);return a instanceof Promise?a.then(i=>KV(i,t.out,r)):KV(a,t.out,r)}});function KV(s,t,n){return s.issues.length?(s.aborted=!0,s):t._zod.run({value:s.value,issues:s.issues,fallback:s.fallback},n)}const TVt=mr("$ZodReadonly",(s,t)=>{uh.init(s,t),Vc(s._zod,"propValues",()=>t.innerType._zod.propValues),Vc(s._zod,"values",()=>t.innerType._zod.values),Vc(s._zod,"optin",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optin}),Vc(s._zod,"optout",()=>{var n,r;return(r=(n=t.innerType)==null?void 0:n._zod)==null?void 0:r.optout}),s._zod.parse=(n,r)=>{if(r.direction==="backward")return t.innerType._zod.run(n,r);const a=t.innerType._zod.run(n,r);return a instanceof Promise?a.then(oBe):oBe(a)}});function oBe(s){return s.value=Object.freeze(s.value),s}const EVt=mr("$ZodCustom",(s,t)=>{e0.init(s,t),uh.init(s,t),s._zod.parse=(n,r)=>n,s._zod.check=n=>{const r=n.value,a=t.fn(r);if(a instanceof Promise)return a.then(i=>lBe(i,n,r,s));lBe(a,n,r,s)}});function lBe(s,t,n,r){if(!s){const a={code:"custom",input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(a.params=r._zod.def.params),t.issues.push(sB(a))}}var cBe;class AVt{constructor(){this._map=new WeakMap,this._idmap=new Map}add(t,...n){const r=n[0];return this._map.set(t,r),r&&typeof r=="object"&&"id"in r&&this._idmap.set(r.id,t),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(t){const n=this._map.get(t);return n&&typeof n=="object"&&"id"in n&&this._idmap.delete(n.id),this._map.delete(t),this}get(t){const n=t._zod.parent;if(n){const r={...this.get(n)??{}};delete r.id;const a={...r,...this._map.get(t)};return Object.keys(a).length?a:void 0}return this._map.get(t)}has(t){return this._map.has(t)}}function MVt(){return new AVt}(cBe=globalThis).__zod_globalRegistry??(cBe.__zod_globalRegistry=MVt());const t7=globalThis.__zod_globalRegistry;function IVt(s,t){return new s({type:"string",...Mi(t)})}function PVt(s,t){return new s({type:"string",format:"email",check:"string_format",abort:!1,...Mi(t)})}function dBe(s,t){return new s({type:"string",format:"guid",check:"string_format",abort:!1,...Mi(t)})}function LVt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,...Mi(t)})}function DVt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v4",...Mi(t)})}function RVt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v6",...Mi(t)})}function OVt(s,t){return new s({type:"string",format:"uuid",check:"string_format",abort:!1,version:"v7",...Mi(t)})}function FVt(s,t){return new s({type:"string",format:"url",check:"string_format",abort:!1,...Mi(t)})}function zVt(s,t){return new s({type:"string",format:"emoji",check:"string_format",abort:!1,...Mi(t)})}function BVt(s,t){return new s({type:"string",format:"nanoid",check:"string_format",abort:!1,...Mi(t)})}function $Vt(s,t){return new s({type:"string",format:"cuid",check:"string_format",abort:!1,...Mi(t)})}function UVt(s,t){return new s({type:"string",format:"cuid2",check:"string_format",abort:!1,...Mi(t)})}function qVt(s,t){return new s({type:"string",format:"ulid",check:"string_format",abort:!1,...Mi(t)})}function VVt(s,t){return new s({type:"string",format:"xid",check:"string_format",abort:!1,...Mi(t)})}function HVt(s,t){return new s({type:"string",format:"ksuid",check:"string_format",abort:!1,...Mi(t)})}function GVt(s,t){return new s({type:"string",format:"ipv4",check:"string_format",abort:!1,...Mi(t)})}function WVt(s,t){return new s({type:"string",format:"ipv6",check:"string_format",abort:!1,...Mi(t)})}function KVt(s,t){return new s({type:"string",format:"cidrv4",check:"string_format",abort:!1,...Mi(t)})}function YVt(s,t){return new s({type:"string",format:"cidrv6",check:"string_format",abort:!1,...Mi(t)})}function ZVt(s,t){return new s({type:"string",format:"base64",check:"string_format",abort:!1,...Mi(t)})}function QVt(s,t){return new s({type:"string",format:"base64url",check:"string_format",abort:!1,...Mi(t)})}function XVt(s,t){return new s({type:"string",format:"e164",check:"string_format",abort:!1,...Mi(t)})}function JVt(s,t){return new s({type:"string",format:"jwt",check:"string_format",abort:!1,...Mi(t)})}function eHt(s,t){return new s({type:"string",format:"datetime",check:"string_format",offset:!1,local:!1,precision:null,...Mi(t)})}function tHt(s,t){return new s({type:"string",format:"date",check:"string_format",...Mi(t)})}function sHt(s,t){return new s({type:"string",format:"time",check:"string_format",precision:null,...Mi(t)})}function nHt(s,t){return new s({type:"string",format:"duration",check:"string_format",...Mi(t)})}function rHt(s,t){return new s({type:"number",checks:[],...Mi(t)})}function aHt(s,t){return new s({type:"number",check:"number_format",abort:!1,format:"safeint",...Mi(t)})}function iHt(s,t){return new s({type:"boolean",...Mi(t)})}function oHt(s){return new s({type:"unknown"})}function lHt(s,t){return new s({type:"never",...Mi(t)})}function uBe(s,t){return new Ect({check:"less_than",...Mi(t),value:s,inclusive:!1})}function Wwe(s,t){return new Ect({check:"less_than",...Mi(t),value:s,inclusive:!0})}function hBe(s,t){return new Act({check:"greater_than",...Mi(t),value:s,inclusive:!1})}function Kwe(s,t){return new Act({check:"greater_than",...Mi(t),value:s,inclusive:!0})}function mBe(s,t){return new Nqt({check:"multiple_of",...Mi(t),value:s})}function Rct(s,t){return new Sqt({check:"max_length",...Mi(t),maximum:s})}function Xpe(s,t){return new Cqt({check:"min_length",...Mi(t),minimum:s})}function Oct(s,t){return new Tqt({check:"length_equals",...Mi(t),length:s})}function cHt(s,t){return new Eqt({check:"string_format",format:"regex",...Mi(t),pattern:s})}function dHt(s){return new Aqt({check:"string_format",format:"lowercase",...Mi(s)})}function uHt(s){return new Mqt({check:"string_format",format:"uppercase",...Mi(s)})}function hHt(s,t){return new Iqt({check:"string_format",format:"includes",...Mi(t),includes:s})}function mHt(s,t){return new Pqt({check:"string_format",format:"starts_with",...Mi(t),prefix:s})}function pHt(s,t){return new Lqt({check:"string_format",format:"ends_with",...Mi(t),suffix:s})}function OD(s){return new Dqt({check:"overwrite",tx:s})}function fHt(s){return OD(t=>t.normalize(s))}function xHt(){return OD(s=>s.trim())}function gHt(){return OD(s=>s.toLowerCase())}function yHt(){return OD(s=>s.toUpperCase())}function vHt(){return OD(s=>SUt(s))}function bHt(s,t,n){return new s({type:"array",element:t,...Mi(n)})}function _Ht(s,t,n){return new s({type:"custom",check:"custom",fn:t,...Mi(n)})}function wHt(s,t){const n=jHt(r=>(r.addIssue=a=>{if(typeof a=="string")r.issues.push(sB(a,r.value,n._zod.def));else{const i=a;i.fatal&&(i.continue=!1),i.code??(i.code="custom"),i.input??(i.input=r.value),i.inst??(i.inst=n),i.continue??(i.continue=!n._zod.def.abort),r.issues.push(sB(i))}},s(r.value,r)),t);return n}function jHt(s,t){const n=new e0({check:"custom",...Mi(t)});return n._zod.check=s,n}function Fct(s){let t=(s==null?void 0:s.target)??"draft-2020-12";return t==="draft-4"&&(t="draft-04"),t==="draft-7"&&(t="draft-07"),{processors:s.processors??{},metadataRegistry:(s==null?void 0:s.metadata)??t7,target:t,unrepresentable:(s==null?void 0:s.unrepresentable)??"throw",override:(s==null?void 0:s.override)??(()=>{}),io:(s==null?void 0:s.io)??"output",counter:0,seen:new Map,cycles:(s==null?void 0:s.cycles)??"ref",reused:(s==null?void 0:s.reused)??"inline",external:(s==null?void 0:s.external)??void 0}}function jf(s,t,n={path:[],schemaPath:[]}){var u,h;var r;const a=s._zod.def,i=t.seen.get(s);if(i)return i.count++,n.schemaPath.includes(s)&&(i.cycle=n.path),i.schema;const l={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(s,l);const o=(h=(u=s._zod).toJSONSchema)==null?void 0:h.call(u);if(o)l.schema=o;else{const p={...n,schemaPath:[...n.schemaPath,s],path:n.path};if(s._zod.processJSONSchema)s._zod.processJSONSchema(t,l.schema,p);else{const y=l.schema,_=t.processors[a.type];if(!_)throw new Error(`[toJSONSchema]: Non-representable type encountered: ${a.type}`);_(s,t,y,p)}const f=s._zod.parent;f&&(l.ref||(l.ref=f),jf(f,t,p),t.seen.get(f).isParent=!0)}const c=t.metadataRegistry.get(s);return c&&Object.assign(l.schema,c),t.io==="input"&&Lx(s)&&(delete l.schema.examples,delete l.schema.default),t.io==="input"&&"_prefault"in l.schema&&((r=l.schema).default??(r.default=l.schema._prefault)),delete l.schema._prefault,t.seen.get(s).schema}function zct(s,t){var l,o,c,d;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=new Map;for(const u of s.seen.entries()){const h=(l=s.metadataRegistry.get(u[0]))==null?void 0:l.id;if(h){const p=r.get(h);if(p&&p!==u[0])throw new Error(`Duplicate schema id "${h}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(h,u[0])}}const a=u=>{var _;const h=s.target==="draft-2020-12"?"$defs":"definitions";if(s.external){const v=(_=s.external.registry.get(u[0]))==null?void 0:_.id,j=s.external.uri??(S=>S);if(v)return{ref:j(v)};const w=u[1].defId??u[1].schema.id??`schema${s.counter++}`;return u[1].defId=w,{defId:w,ref:`${j("__shared")}#/${h}/${w}`}}if(u[1]===n)return{ref:"#"};const f=`#/${h}/`,y=u[1].schema.id??`__schema${s.counter++}`;return{defId:y,ref:f+y}},i=u=>{if(u[1].schema.$ref)return;const h=u[1],{ref:p,defId:f}=a(u);h.def={...h.schema},f&&(h.defId=f);const y=h.schema;for(const _ in y)delete y[_];y.$ref=p};if(s.cycles==="throw")for(const u of s.seen.entries()){const h=u[1];if(h.cycle)throw new Error(`Cycle detected: #/${(o=h.cycle)==null?void 0:o.join("/")}/ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(const u of s.seen.entries()){const h=u[1];if(t===u[0]){i(u);continue}if(s.external){const f=(c=s.external.registry.get(u[0]))==null?void 0:c.id;if(t!==u[0]&&f){i(u);continue}}if((d=s.metadataRegistry.get(u[0]))==null?void 0:d.id){i(u);continue}if(h.cycle){i(u);continue}if(h.count>1&&s.reused==="ref"){i(u);continue}}}function Bct(s,t){var o,c,d,u;const n=s.seen.get(t);if(!n)throw new Error("Unprocessed schema. This is a bug in Zod.");const r=h=>{const p=s.seen.get(h);if(p.ref===null)return;const f=p.def??p.schema,y={...f},_=p.ref;if(p.ref=null,_){r(_);const j=s.seen.get(_),w=j.schema;if(w.$ref&&(s.target==="draft-07"||s.target==="draft-04"||s.target==="openapi-3.0")?(f.allOf=f.allOf??[],f.allOf.push(w)):Object.assign(f,w),Object.assign(f,y),h._zod.parent===_)for(const A in f)A==="$ref"||A==="allOf"||A in y||delete f[A];if(w.$ref&&j.def)for(const A in f)A==="$ref"||A==="allOf"||A in j.def&&JSON.stringify(f[A])===JSON.stringify(j.def[A])&&delete f[A]}const v=h._zod.parent;if(v&&v!==_){r(v);const j=s.seen.get(v);if(j!=null&&j.schema.$ref&&(f.$ref=j.schema.$ref,j.def))for(const w in f)w==="$ref"||w==="allOf"||w in j.def&&JSON.stringify(f[w])===JSON.stringify(j.def[w])&&delete f[w]}s.override({zodSchema:h,jsonSchema:f,path:p.path??[]})};for(const h of[...s.seen.entries()].reverse())r(h[0]);const a={};if(s.target==="draft-2020-12"?a.$schema="https://json-schema.org/draft/2020-12/schema":s.target==="draft-07"?a.$schema="http://json-schema.org/draft-07/schema#":s.target==="draft-04"?a.$schema="http://json-schema.org/draft-04/schema#":s.target,(o=s.external)!=null&&o.uri){const h=(c=s.external.registry.get(t))==null?void 0:c.id;if(!h)throw new Error("Schema is missing an `id` property");a.$id=s.external.uri(h)}Object.assign(a,n.def??n.schema);const i=(d=s.metadataRegistry.get(t))==null?void 0:d.id;i!==void 0&&a.id===i&&delete a.id;const l=((u=s.external)==null?void 0:u.defs)??{};for(const h of s.seen.entries()){const p=h[1];p.def&&p.defId&&(p.def.id===p.defId&&delete p.def.id,l[p.defId]=p.def)}s.external||Object.keys(l).length>0&&(s.target==="draft-2020-12"?a.$defs=l:a.definitions=l);try{const h=JSON.parse(JSON.stringify(a));return Object.defineProperty(h,"~standard",{value:{...t["~standard"],jsonSchema:{input:Jpe(t,"input",s.processors),output:Jpe(t,"output",s.processors)}},enumerable:!1,writable:!1}),h}catch{throw new Error("Error converting schema to JSON.")}}function Lx(s,t){const n=t??{seen:new Set};if(n.seen.has(s))return!1;n.seen.add(s);const r=s._zod.def;if(r.type==="transform")return!0;if(r.type==="array")return Lx(r.element,n);if(r.type==="set")return Lx(r.valueType,n);if(r.type==="lazy")return Lx(r.getter(),n);if(r.type==="promise"||r.type==="optional"||r.type==="nonoptional"||r.type==="nullable"||r.type==="readonly"||r.type==="default"||r.type==="prefault")return Lx(r.innerType,n);if(r.type==="intersection")return Lx(r.left,n)||Lx(r.right,n);if(r.type==="record"||r.type==="map")return Lx(r.keyType,n)||Lx(r.valueType,n);if(r.type==="pipe")return s._zod.traits.has("$ZodCodec")?!0:Lx(r.in,n)||Lx(r.out,n);if(r.type==="object"){for(const a in r.shape)if(Lx(r.shape[a],n))return!0;return!1}if(r.type==="union"){for(const a of r.options)if(Lx(a,n))return!0;return!1}if(r.type==="tuple"){for(const a of r.items)if(Lx(a,n))return!0;return!!(r.rest&&Lx(r.rest,n))}return!1}const NHt=(s,t={})=>n=>{const r=Fct({...n,processors:t});return jf(s,r),zct(r,s),Bct(r,s)},Jpe=(s,t,n={})=>r=>{const{libraryOptions:a,target:i}=r??{},l=Fct({...a??{},target:i,io:t,processors:n});return jf(s,l),zct(l,s),Bct(l,s)},kHt={guid:"uuid",url:"uri",datetime:"date-time",json_string:"json-string",regex:""},SHt=(s,t,n,r)=>{const a=n;a.type="string";const{minimum:i,maximum:l,format:o,patterns:c,contentEncoding:d}=s._zod.bag;if(typeof i=="number"&&(a.minLength=i),typeof l=="number"&&(a.maxLength=l),o&&(a.format=kHt[o]??o,a.format===""&&delete a.format,o==="time"&&delete a.format),d&&(a.contentEncoding=d),c&&c.size>0){const u=[...c];u.length===1?a.pattern=u[0].source:u.length>1&&(a.allOf=[...u.map(h=>({...t.target==="draft-07"||t.target==="draft-04"||t.target==="openapi-3.0"?{type:"string"}:{},pattern:h.source}))])}},CHt=(s,t,n,r)=>{const a=n,{minimum:i,maximum:l,format:o,multipleOf:c,exclusiveMaximum:d,exclusiveMinimum:u}=s._zod.bag;typeof o=="string"&&o.includes("int")?a.type="integer":a.type="number";const h=typeof u=="number"&&u>=(i??Number.NEGATIVE_INFINITY),p=typeof d=="number"&&d<=(l??Number.POSITIVE_INFINITY),f=t.target==="draft-04"||t.target==="openapi-3.0";h?f?(a.minimum=u,a.exclusiveMinimum=!0):a.exclusiveMinimum=u:typeof i=="number"&&(a.minimum=i),p?f?(a.maximum=d,a.exclusiveMaximum=!0):a.exclusiveMaximum=d:typeof l=="number"&&(a.maximum=l),typeof c=="number"&&(a.multipleOf=c)},THt=(s,t,n,r)=>{n.type="boolean"},EHt=(s,t,n,r)=>{n.not={}},AHt=(s,t,n,r)=>{},MHt=(s,t,n,r)=>{const a=s._zod.def,i=yct(a.entries);i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),n.enum=i},IHt=(s,t,n,r)=>{const a=s._zod.def,i=[];for(const l of a.values)if(l===void 0){if(t.unrepresentable==="throw")throw new Error("Literal `undefined` cannot be represented in JSON Schema")}else if(typeof l=="bigint"){if(t.unrepresentable==="throw")throw new Error("BigInt literals cannot be represented in JSON Schema");i.push(Number(l))}else i.push(l);if(i.length!==0)if(i.length===1){const l=i[0];n.type=l===null?"null":typeof l,t.target==="draft-04"||t.target==="openapi-3.0"?n.enum=[l]:n.const=l}else i.every(l=>typeof l=="number")&&(n.type="number"),i.every(l=>typeof l=="string")&&(n.type="string"),i.every(l=>typeof l=="boolean")&&(n.type="boolean"),i.every(l=>l===null)&&(n.type="null"),n.enum=i},PHt=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Custom types cannot be represented in JSON Schema")},LHt=(s,t,n,r)=>{if(t.unrepresentable==="throw")throw new Error("Transforms cannot be represented in JSON Schema")},DHt=(s,t,n,r)=>{const a=n,i=s._zod.def,{minimum:l,maximum:o}=s._zod.bag;typeof l=="number"&&(a.minItems=l),typeof o=="number"&&(a.maxItems=o),a.type="array",a.items=jf(i.element,t,{...r,path:[...r.path,"items"]})},RHt=(s,t,n,r)=>{var d;const a=n,i=s._zod.def;a.type="object",a.properties={};const l=i.shape;for(const u in l)a.properties[u]=jf(l[u],t,{...r,path:[...r.path,"properties",u]});const o=new Set(Object.keys(l)),c=new Set([...o].filter(u=>{const h=i.shape[u]._zod;return t.io==="input"?h.optin===void 0:h.optout===void 0}));c.size>0&&(a.required=Array.from(c)),((d=i.catchall)==null?void 0:d._zod.def.type)==="never"?a.additionalProperties=!1:i.catchall?i.catchall&&(a.additionalProperties=jf(i.catchall,t,{...r,path:[...r.path,"additionalProperties"]})):t.io==="output"&&(a.additionalProperties=!1)},OHt=(s,t,n,r)=>{const a=s._zod.def,i=a.inclusive===!1,l=a.options.map((o,c)=>jf(o,t,{...r,path:[...r.path,i?"oneOf":"anyOf",c]}));i?n.oneOf=l:n.anyOf=l},FHt=(s,t,n,r)=>{const a=s._zod.def,i=jf(a.left,t,{...r,path:[...r.path,"allOf",0]}),l=jf(a.right,t,{...r,path:[...r.path,"allOf",1]}),o=d=>"allOf"in d&&Object.keys(d).length===1,c=[...o(i)?i.allOf:[i],...o(l)?l.allOf:[l]];n.allOf=c},zHt=(s,t,n,r)=>{const a=s._zod.def,i=jf(a.innerType,t,r),l=t.seen.get(s);t.target==="openapi-3.0"?(l.ref=a.innerType,n.nullable=!0):n.anyOf=[i,{type:"null"}]},BHt=(s,t,n,r)=>{const a=s._zod.def;jf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},$Ht=(s,t,n,r)=>{const a=s._zod.def;jf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.default=JSON.parse(JSON.stringify(a.defaultValue))},UHt=(s,t,n,r)=>{const a=s._zod.def;jf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,t.io==="input"&&(n._prefault=JSON.parse(JSON.stringify(a.defaultValue)))},qHt=(s,t,n,r)=>{const a=s._zod.def;jf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType;let l;try{l=a.catchValue(void 0)}catch{throw new Error("Dynamic catch values are not supported in JSON Schema")}n.default=l},VHt=(s,t,n,r)=>{const a=s._zod.def,i=a.in._zod.traits.has("$ZodTransform"),l=t.io==="input"?i?a.out:a.in:a.out;jf(l,t,r);const o=t.seen.get(s);o.ref=l},HHt=(s,t,n,r)=>{const a=s._zod.def;jf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType,n.readOnly=!0},$ct=(s,t,n,r)=>{const a=s._zod.def;jf(a.innerType,t,r);const i=t.seen.get(s);i.ref=a.innerType},GHt=mr("ZodISODateTime",(s,t)=>{Yqt.init(s,t),Ou.init(s,t)});function WHt(s){return eHt(GHt,s)}const KHt=mr("ZodISODate",(s,t)=>{Zqt.init(s,t),Ou.init(s,t)});function YHt(s){return tHt(KHt,s)}const ZHt=mr("ZodISOTime",(s,t)=>{Qqt.init(s,t),Ou.init(s,t)});function QHt(s){return sHt(ZHt,s)}const XHt=mr("ZodISODuration",(s,t)=>{Xqt.init(s,t),Ou.init(s,t)});function JHt(s){return nHt(XHt,s)}const Uct=(s,t)=>{jct.init(s,t),s.name="ZodError",Object.defineProperties(s,{format:{value:n=>BUt(s,n)},flatten:{value:n=>zUt(s,n)},addIssue:{value:n=>{s.issues.push(n),s.message=JSON.stringify(s.issues,v4e,2)}},addIssues:{value:n=>{s.issues.push(...n),s.message=JSON.stringify(s.issues,v4e,2)}},isEmpty:{get(){return s.issues.length===0}}})},eGt=mr("ZodError",Uct),Kv=mr("ZodError",Uct,{Parent:Error}),tGt=YAe(Kv),sGt=ZAe(Kv),nGt=nye(Kv),rGt=rye(Kv),aGt=qUt(Kv),iGt=VUt(Kv),oGt=HUt(Kv),lGt=GUt(Kv),cGt=WUt(Kv),dGt=KUt(Kv),uGt=YUt(Kv),hGt=ZUt(Kv),pBe=new WeakMap;function K$(s,t,n){const r=Object.getPrototypeOf(s);let a=pBe.get(r);if(a||(a=new Set,pBe.set(r,a)),!a.has(t)){a.add(t);for(const i in n){const l=n[i];Object.defineProperty(r,i,{configurable:!0,enumerable:!1,get(){const o=l.bind(this);return Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:o}),o},set(o){Object.defineProperty(this,i,{configurable:!0,writable:!0,enumerable:!0,value:o})}})}}}const hh=mr("ZodType",(s,t)=>(uh.init(s,t),Object.assign(s["~standard"],{jsonSchema:{input:Jpe(s,"input"),output:Jpe(s,"output")}}),s.toJSONSchema=NHt(s,{}),s.def=t,s.type=t.type,Object.defineProperty(s,"_def",{value:t}),s.parse=(n,r)=>tGt(s,n,r,{callee:s.parse}),s.safeParse=(n,r)=>nGt(s,n,r),s.parseAsync=async(n,r)=>sGt(s,n,r,{callee:s.parseAsync}),s.safeParseAsync=async(n,r)=>rGt(s,n,r),s.spa=s.safeParseAsync,s.encode=(n,r)=>aGt(s,n,r),s.decode=(n,r)=>iGt(s,n,r),s.encodeAsync=async(n,r)=>oGt(s,n,r),s.decodeAsync=async(n,r)=>lGt(s,n,r),s.safeEncode=(n,r)=>cGt(s,n,r),s.safeDecode=(n,r)=>dGt(s,n,r),s.safeEncodeAsync=async(n,r)=>uGt(s,n,r),s.safeDecodeAsync=async(n,r)=>hGt(s,n,r),K$(s,"ZodType",{check(...n){const r=this.def;return this.clone(q4(r,{checks:[...r.checks??[],...n.map(a=>typeof a=="function"?{_zod:{check:a,def:{check:"custom"},onattach:[]}}:a)]}),{parent:!0})},with(...n){return this.check(...n)},clone(n,r){return V4(this,n,r)},brand(){return this},register(n,r){return n.add(this,r),this},refine(n,r){return this.check(oWt(n,r))},superRefine(n,r){return this.check(lWt(n,r))},overwrite(n){return this.check(OD(n))},optional(){return yBe(this)},exactOptional(){return KGt(this)},nullable(){return vBe(this)},nullish(){return yBe(vBe(this))},nonoptional(n){return eWt(this,n)},array(){return FGt(this)},or(n){return $Gt([this,n])},and(n){return qGt(this,n)},transform(n){return bBe(this,GGt(n))},default(n){return QGt(this,n)},prefault(n){return JGt(this,n)},catch(n){return sWt(this,n)},pipe(n){return bBe(this,n)},readonly(){return aWt(this)},describe(n){const r=this.clone();return t7.add(r,{description:n}),r},meta(...n){if(n.length===0)return t7.get(this);const r=this.clone();return t7.add(r,n[0]),r},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(n){return n(this)}}),Object.defineProperty(s,"description",{get(){var n;return(n=t7.get(s))==null?void 0:n.description},configurable:!0}),s)),qct=mr("_ZodString",(s,t)=>{QAe.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>SHt(s,r,a);const n=s._zod.bag;s.format=n.format??null,s.minLength=n.minimum??null,s.maxLength=n.maximum??null,K$(s,"_ZodString",{regex(...r){return this.check(cHt(...r))},includes(...r){return this.check(hHt(...r))},startsWith(...r){return this.check(mHt(...r))},endsWith(...r){return this.check(pHt(...r))},min(...r){return this.check(Xpe(...r))},max(...r){return this.check(Rct(...r))},length(...r){return this.check(Oct(...r))},nonempty(...r){return this.check(Xpe(1,...r))},lowercase(r){return this.check(dHt(r))},uppercase(r){return this.check(uHt(r))},trim(){return this.check(xHt())},normalize(...r){return this.check(fHt(...r))},toLowerCase(){return this.check(gHt())},toUpperCase(){return this.check(yHt())},slugify(){return this.check(vHt())}})}),mGt=mr("ZodString",(s,t)=>{QAe.init(s,t),qct.init(s,t),s.email=n=>s.check(PVt(pGt,n)),s.url=n=>s.check(FVt(fGt,n)),s.jwt=n=>s.check(JVt(AGt,n)),s.emoji=n=>s.check(zVt(xGt,n)),s.guid=n=>s.check(dBe(fBe,n)),s.uuid=n=>s.check(LVt(YV,n)),s.uuidv4=n=>s.check(DVt(YV,n)),s.uuidv6=n=>s.check(RVt(YV,n)),s.uuidv7=n=>s.check(OVt(YV,n)),s.nanoid=n=>s.check(BVt(gGt,n)),s.guid=n=>s.check(dBe(fBe,n)),s.cuid=n=>s.check($Vt(yGt,n)),s.cuid2=n=>s.check(UVt(vGt,n)),s.ulid=n=>s.check(qVt(bGt,n)),s.base64=n=>s.check(ZVt(CGt,n)),s.base64url=n=>s.check(QVt(TGt,n)),s.xid=n=>s.check(VVt(_Gt,n)),s.ksuid=n=>s.check(HVt(wGt,n)),s.ipv4=n=>s.check(GVt(jGt,n)),s.ipv6=n=>s.check(WVt(NGt,n)),s.cidrv4=n=>s.check(KVt(kGt,n)),s.cidrv6=n=>s.check(YVt(SGt,n)),s.e164=n=>s.check(XVt(EGt,n)),s.datetime=n=>s.check(WHt(n)),s.date=n=>s.check(YHt(n)),s.time=n=>s.check(QHt(n)),s.duration=n=>s.check(JHt(n))});function fo(s){return IVt(mGt,s)}const Ou=mr("ZodStringFormat",(s,t)=>{hu.init(s,t),qct.init(s,t)}),pGt=mr("ZodEmail",(s,t)=>{Bqt.init(s,t),Ou.init(s,t)}),fBe=mr("ZodGUID",(s,t)=>{Fqt.init(s,t),Ou.init(s,t)}),YV=mr("ZodUUID",(s,t)=>{zqt.init(s,t),Ou.init(s,t)}),fGt=mr("ZodURL",(s,t)=>{$qt.init(s,t),Ou.init(s,t)}),xGt=mr("ZodEmoji",(s,t)=>{Uqt.init(s,t),Ou.init(s,t)}),gGt=mr("ZodNanoID",(s,t)=>{qqt.init(s,t),Ou.init(s,t)}),yGt=mr("ZodCUID",(s,t)=>{Vqt.init(s,t),Ou.init(s,t)}),vGt=mr("ZodCUID2",(s,t)=>{Hqt.init(s,t),Ou.init(s,t)}),bGt=mr("ZodULID",(s,t)=>{Gqt.init(s,t),Ou.init(s,t)}),_Gt=mr("ZodXID",(s,t)=>{Wqt.init(s,t),Ou.init(s,t)}),wGt=mr("ZodKSUID",(s,t)=>{Kqt.init(s,t),Ou.init(s,t)}),jGt=mr("ZodIPv4",(s,t)=>{Jqt.init(s,t),Ou.init(s,t)}),NGt=mr("ZodIPv6",(s,t)=>{eVt.init(s,t),Ou.init(s,t)}),kGt=mr("ZodCIDRv4",(s,t)=>{tVt.init(s,t),Ou.init(s,t)}),SGt=mr("ZodCIDRv6",(s,t)=>{sVt.init(s,t),Ou.init(s,t)}),CGt=mr("ZodBase64",(s,t)=>{nVt.init(s,t),Ou.init(s,t)}),TGt=mr("ZodBase64URL",(s,t)=>{aVt.init(s,t),Ou.init(s,t)}),EGt=mr("ZodE164",(s,t)=>{iVt.init(s,t),Ou.init(s,t)}),AGt=mr("ZodJWT",(s,t)=>{lVt.init(s,t),Ou.init(s,t)}),Vct=mr("ZodNumber",(s,t)=>{Ict.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>CHt(s,r,a),K$(s,"ZodNumber",{gt(r,a){return this.check(hBe(r,a))},gte(r,a){return this.check(Kwe(r,a))},min(r,a){return this.check(Kwe(r,a))},lt(r,a){return this.check(uBe(r,a))},lte(r,a){return this.check(Wwe(r,a))},max(r,a){return this.check(Wwe(r,a))},int(r){return this.check(xBe(r))},safe(r){return this.check(xBe(r))},positive(r){return this.check(hBe(0,r))},nonnegative(r){return this.check(Kwe(0,r))},negative(r){return this.check(uBe(0,r))},nonpositive(r){return this.check(Wwe(0,r))},multipleOf(r,a){return this.check(mBe(r,a))},step(r,a){return this.check(mBe(r,a))},finite(){return this}});const n=s._zod.bag;s.minValue=Math.max(n.minimum??Number.NEGATIVE_INFINITY,n.exclusiveMinimum??Number.NEGATIVE_INFINITY)??null,s.maxValue=Math.min(n.maximum??Number.POSITIVE_INFINITY,n.exclusiveMaximum??Number.POSITIVE_INFINITY)??null,s.isInt=(n.format??"").includes("int")||Number.isSafeInteger(n.multipleOf??.5),s.isFinite=!0,s.format=n.format??null});function z9(s){return rHt(Vct,s)}const MGt=mr("ZodNumberFormat",(s,t)=>{cVt.init(s,t),Vct.init(s,t)});function xBe(s){return aHt(MGt,s)}const IGt=mr("ZodBoolean",(s,t)=>{dVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>THt(s,n,r)});function PGt(s){return iHt(IGt,s)}const LGt=mr("ZodUnknown",(s,t)=>{uVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>AHt()});function gBe(){return oHt(LGt)}const DGt=mr("ZodNever",(s,t)=>{hVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>EHt(s,n,r)});function RGt(s){return lHt(DGt,s)}const OGt=mr("ZodArray",(s,t)=>{mVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>DHt(s,n,r,a),s.element=t.element,K$(s,"ZodArray",{min(n,r){return this.check(Xpe(n,r))},nonempty(n){return this.check(Xpe(1,n))},max(n,r){return this.check(Rct(n,r))},length(n,r){return this.check(Oct(n,r))},unwrap(){return this.element}})});function FGt(s,t){return bHt(OGt,s,t)}const zGt=mr("ZodObject",(s,t)=>{fVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>RHt(s,n,r,a),Vc(s,"shape",()=>t.shape),K$(s,"ZodObject",{keyof(){return XAe(Object.keys(this._zod.def.shape))},catchall(n){return this.clone({...this._zod.def,catchall:n})},passthrough(){return this.clone({...this._zod.def,catchall:gBe()})},loose(){return this.clone({...this._zod.def,catchall:gBe()})},strict(){return this.clone({...this._zod.def,catchall:RGt()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(n){return PUt(this,n)},safeExtend(n){return LUt(this,n)},merge(n){return DUt(this,n)},pick(n){return MUt(this,n)},omit(n){return IUt(this,n)},partial(...n){return RUt(Hct,this,n[0])},required(...n){return OUt(Gct,this,n[0])}})});function Gw(s,t){const n={type:"object",shape:s??{},...Mi(t)};return new zGt(n)}const BGt=mr("ZodUnion",(s,t)=>{xVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>OHt(s,n,r,a),s.options=t.options});function $Gt(s,t){return new BGt({type:"union",options:s,...Mi(t)})}const UGt=mr("ZodIntersection",(s,t)=>{gVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>FHt(s,n,r,a)});function qGt(s,t){return new UGt({type:"intersection",left:s,right:t})}const _4e=mr("ZodEnum",(s,t)=>{yVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(r,a,i)=>MHt(s,r,a),s.enum=t.entries,s.options=Object.values(t.entries);const n=new Set(Object.keys(t.entries));s.extract=(r,a)=>{const i={};for(const l of r)if(n.has(l))i[l]=t.entries[l];else throw new Error(`Key ${l} not found in enum`);return new _4e({...t,checks:[],...Mi(a),entries:i})},s.exclude=(r,a)=>{const i={...t.entries};for(const l of r)if(n.has(l))delete i[l];else throw new Error(`Key ${l} not found in enum`);return new _4e({...t,checks:[],...Mi(a),entries:i})}});function XAe(s,t){const n=Array.isArray(s)?Object.fromEntries(s.map(r=>[r,r])):s;return new _4e({type:"enum",entries:n,...Mi(t)})}const VGt=mr("ZodLiteral",(s,t)=>{vVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>IHt(s,n,r),s.values=new Set(t.values),Object.defineProperty(s,"value",{get(){if(t.values.length>1)throw new Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function bp(s,t){return new VGt({type:"literal",values:Array.isArray(s)?s:[s],...Mi(t)})}const HGt=mr("ZodTransform",(s,t)=>{bVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>LHt(s,n),s._zod.parse=(n,r)=>{if(r.direction==="backward")throw new gct(s.constructor.name);n.addIssue=i=>{if(typeof i=="string")n.issues.push(sB(i,n.value,t));else{const l=i;l.fatal&&(l.continue=!1),l.code??(l.code="custom"),l.input??(l.input=n.value),l.inst??(l.inst=s),n.issues.push(sB(l))}};const a=t.transform(n.value,n);return a instanceof Promise?a.then(i=>(n.value=i,n.fallback=!0,n)):(n.value=a,n.fallback=!0,n)}});function GGt(s){return new HGt({type:"transform",transform:s})}const Hct=mr("ZodOptional",(s,t)=>{Dct.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>$ct(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function yBe(s){return new Hct({type:"optional",innerType:s})}const WGt=mr("ZodExactOptional",(s,t)=>{_Vt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>$ct(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function KGt(s){return new WGt({type:"optional",innerType:s})}const YGt=mr("ZodNullable",(s,t)=>{wVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>zHt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function vBe(s){return new YGt({type:"nullable",innerType:s})}const ZGt=mr("ZodDefault",(s,t)=>{jVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>$Ht(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeDefault=s.unwrap});function QGt(s,t){return new ZGt({type:"default",innerType:s,get defaultValue(){return typeof t=="function"?t():bct(t)}})}const XGt=mr("ZodPrefault",(s,t)=>{NVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>UHt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function JGt(s,t){return new XGt({type:"prefault",innerType:s,get defaultValue(){return typeof t=="function"?t():bct(t)}})}const Gct=mr("ZodNonOptional",(s,t)=>{kVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>BHt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function eWt(s,t){return new Gct({type:"nonoptional",innerType:s,...Mi(t)})}const tWt=mr("ZodCatch",(s,t)=>{SVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>qHt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType,s.removeCatch=s.unwrap});function sWt(s,t){return new tWt({type:"catch",innerType:s,catchValue:typeof t=="function"?t:()=>t})}const nWt=mr("ZodPipe",(s,t)=>{CVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>VHt(s,n,r,a),s.in=t.in,s.out=t.out});function bBe(s,t){return new nWt({type:"pipe",in:s,out:t})}const rWt=mr("ZodReadonly",(s,t)=>{TVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>HHt(s,n,r,a),s.unwrap=()=>s._zod.def.innerType});function aWt(s){return new rWt({type:"readonly",innerType:s})}const iWt=mr("ZodCustom",(s,t)=>{EVt.init(s,t),hh.init(s,t),s._zod.processJSONSchema=(n,r,a)=>PHt(s,n)});function oWt(s,t={}){return _Ht(iWt,s,t)}function lWt(s,t){return wHt(s,t)}const cWt=["Excellent","Good","Neutral","Bad","Very Bad"],dWt=[5,4,3,2,1];function uWt({questions:s,visitorId:t,onComplete:n,onSkip:r}){const a=Azt(),[i,l]=N.useState({}),o=s.filter(p=>p.question_type==="rating"),c=s.filter(p=>p.question_type!=="rating"),d=(p,f)=>{l(y=>({...y,[p]:{rating_value:f}}))},u=(p,f)=>{l(y=>({...y,[p]:{text_value:f}}))},h=async()=>{const p=Object.entries(i).filter(([,f])=>f.rating_value!=null||f.text_value&&f.text_value.trim()).map(([f,y])=>{var _;return{visitor_id:t,question_id:f,rating_value:y.rating_value??null,text_value:((_=y.text_value)==null?void 0:_.trim())||null}});if(p.length>0)try{await a.mutateAsync(p)}catch{}n()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h2",{className:"text-lg font-bold text-slate-900",children:"Quick Feedback"}),e.jsx("button",{onClick:r,className:"text-sm text-slate-400 hover:text-slate-600 underline",children:"Skip"})]}),e.jsx("p",{className:"text-sm text-slate-500 -mt-2",children:"Your feedback helps the agent — totally optional!"}),o.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("div",{className:"flex-1"}),cWt.map(p=>e.jsx("div",{className:"w-12 text-center",children:e.jsx("span",{className:"text-[10px] text-slate-400 leading-tight block",children:p})},p))]}),o.map(p=>e.jsxs("div",{className:"flex items-center gap-1 py-1.5 border-b border-slate-100 last:border-0",children:[e.jsx("span",{className:"flex-1 text-sm text-slate-700 pr-2",children:p.question_text}),dWt.map(f=>{var y;return e.jsx("div",{className:"w-12 flex justify-center",children:e.jsx("button",{type:"button",onClick:()=>d(p.id,f),className:`w-6 h-6 rounded-full border-2 transition-all ${((y=i[p.id])==null?void 0:y.rating_value)===f?"bg-slate-900 border-slate-900":"border-slate-300 hover:border-slate-500"}`})},f)})]},p.id))]}),c.map(p=>{var f;return e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium text-slate-700 block mb-1",children:p.question_text}),e.jsx(Ms,{value:((f=i[p.id])==null?void 0:f.text_value)||"",onChange:y=>u(p.id,y.target.value),placeholder:"Your thoughts...",className:"h-16 text-sm resize-none rounded-xl border-slate-200"})]},p.id)}),e.jsx(B,{onClick:h,disabled:a.isPending,className:"w-full h-12 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:a.isPending?e.jsx(rs,{className:"h-5 w-5 animate-spin"}):"Submit Feedback"})]})}var iye="Checkbox",[hWt,sfn]=uu(iye),[mWt,JAe]=hWt(iye);function pWt(s){const{__scopeCheckbox:t,checked:n,children:r,defaultChecked:a,disabled:i,form:l,name:o,onCheckedChange:c,required:d,value:u="on",internal_do_not_use_render:h}=s,[p,f]=cm({prop:n,defaultProp:a??!1,onChange:c,caller:iye}),[y,_]=N.useState(null),[v,j]=N.useState(null),w=N.useRef(!1),S=y?!!l||!!y.closest("form"):!0,A={checked:p,disabled:i,setChecked:f,control:y,setControl:_,name:o,form:l,value:u,hasConsumerStoppedPropagationRef:w,required:d,defaultChecked:l4(a)?!1:a,isFormControl:S,bubbleInput:v,setBubbleInput:j};return e.jsx(mWt,{scope:t,...A,children:fWt(h)?h(A):r})}var Wct="CheckboxTrigger",Kct=N.forwardRef(({__scopeCheckbox:s,onKeyDown:t,onClick:n,...r},a)=>{const{control:i,value:l,disabled:o,checked:c,required:d,setControl:u,setChecked:h,hasConsumerStoppedPropagationRef:p,isFormControl:f,bubbleInput:y}=JAe(Wct,s),_=ji(a,u),v=N.useRef(c);return N.useEffect(()=>{const j=i==null?void 0:i.form;if(j){const w=()=>h(v.current);return j.addEventListener("reset",w),()=>j.removeEventListener("reset",w)}},[i,h]),e.jsx(Yr.button,{type:"button",role:"checkbox","aria-checked":l4(c)?"mixed":c,"aria-required":d,"data-state":Jct(c),"data-disabled":o?"":void 0,disabled:o,value:l,...r,ref:_,onKeyDown:xr(t,j=>{j.key==="Enter"&&j.preventDefault()}),onClick:xr(n,j=>{h(w=>l4(w)?!0:!w),y&&f&&(p.current=j.isPropagationStopped(),p.current||j.stopPropagation())})})});Kct.displayName=Wct;var eMe=N.forwardRef((s,t)=>{const{__scopeCheckbox:n,name:r,checked:a,defaultChecked:i,required:l,disabled:o,value:c,onCheckedChange:d,form:u,...h}=s;return e.jsx(pWt,{__scopeCheckbox:n,checked:a,defaultChecked:i,disabled:o,required:l,onCheckedChange:d,name:r,form:u,value:c,internal_do_not_use_render:({isFormControl:p})=>e.jsxs(e.Fragment,{children:[e.jsx(Kct,{...h,ref:t,__scopeCheckbox:n}),p&&e.jsx(Xct,{__scopeCheckbox:n})]})})});eMe.displayName=iye;var Yct="CheckboxIndicator",Zct=N.forwardRef((s,t)=>{const{__scopeCheckbox:n,forceMount:r,...a}=s,i=JAe(Yct,n);return e.jsx(Lh,{present:r||l4(i.checked)||i.checked===!0,children:e.jsx(Yr.span,{"data-state":Jct(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t,style:{pointerEvents:"none",...s.style}})})});Zct.displayName=Yct;var Qct="CheckboxBubbleInput",Xct=N.forwardRef(({__scopeCheckbox:s,...t},n)=>{const{control:r,hasConsumerStoppedPropagationRef:a,checked:i,defaultChecked:l,required:o,disabled:c,name:d,value:u,form:h,bubbleInput:p,setBubbleInput:f}=JAe(Qct,s),y=ji(n,f),_=G$(i),v=M$(r);N.useEffect(()=>{const w=p;if(!w)return;const S=window.HTMLInputElement.prototype,E=Object.getOwnPropertyDescriptor(S,"checked").set,O=!a.current;if(_!==i&&E){const D=new Event("click",{bubbles:O});w.indeterminate=l4(i),E.call(w,l4(i)?!1:i),w.dispatchEvent(D)}},[p,_,i,a]);const j=N.useRef(l4(i)?!1:i);return e.jsx(Yr.input,{type:"checkbox","aria-hidden":!0,defaultChecked:l??j.current,required:o,disabled:c,name:d,value:u,form:h,...t,tabIndex:-1,ref:y,style:{...t.style,...v,position:"absolute",pointerEvents:"none",opacity:0,margin:0,transform:"translateX(-100%)"}})});Xct.displayName=Qct;function fWt(s){return typeof s=="function"}function l4(s){return s==="indeterminate"}function Jct(s){return l4(s)?"indeterminate":s?"checked":"unchecked"}const hi=N.forwardRef(({className:s,...t},n)=>e.jsx(eMe,{ref:n,className:Mt("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(Zct,{className:Mt("flex items-center justify-center text-current"),children:e.jsx(Lr,{className:"h-4 w-4"})})}));hi.displayName=eMe.displayName;const t0=B0e,Y$=SAe,xWt=$0e,edt=N.forwardRef(({className:s,...t},n)=>e.jsx(PD,{className:Mt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...t,ref:n}));edt.displayName=PD.displayName;const gWt=OM("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"}}),og=N.forwardRef(({side:s="right",className:t,children:n,...r},a)=>e.jsxs(xWt,{children:[e.jsx(edt,{}),e.jsxs(LD,{ref:a,className:Mt(gWt({side:s}),t),...r,children:[n,e.jsxs(V$,{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($n,{className:"h-4 w-4"}),e.jsx("span",{className:"sr-only",children:"Close"})]})]})]}));og.displayName=LD.displayName;const jy=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col space-y-2 text-center sm:text-left",s),...t});jy.displayName="SheetHeader";const tdt=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});tdt.displayName="SheetFooter";const Ny=N.forwardRef(({className:s,...t},n)=>e.jsx(U$,{ref:n,className:Mt("text-lg font-semibold text-foreground",s),...t}));Ny.displayName=U$.displayName;const Z$=N.forwardRef(({className:s,...t},n)=>e.jsx(q$,{ref:n,className:Mt("text-sm text-muted-foreground",s),...t}));Z$.displayName=q$.displayName;function w4e(s){return/iframe\.mediadelivery\.net\/embed\//.test(s)}function yWt({rooms:s}){var h;const[t,n]=N.useState(((h=s[0])==null?void 0:h.id)||""),[r,a]=N.useState(null),i=s.find(p=>p.id===t)||s[0],l=r!==null?i==null?void 0:i.media[r]:null,o=(i==null?void 0:i.media.length)??0,c=()=>a(null),d=()=>a(p=>p===null||o===0?p:(p-1+o)%o),u=()=>a(p=>p===null||o===0?p:(p+1)%o);return N.useEffect(()=>{if(r===null)return;const p=f=>{f.key==="Escape"?c():f.key==="ArrowLeft"?d():f.key==="ArrowRight"&&u()};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[r,o]),s.length?e.jsxs("div",{className:"hidden md:block",children:[e.jsx("div",{className:"sticky top-0 z-20 -mx-5 px-5 py-3 bg-slate-950/80 backdrop-blur-md border-b border-white/10 overflow-x-auto",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(p=>e.jsxs("button",{onClick:()=>n(p.id),className:Mt("px-4 py-2 rounded-full text-sm font-medium whitespace-nowrap transition",t===p.id?"bg-white text-slate-900":"bg-white/5 text-white/70 hover:bg-white/10"),children:[p.name,e.jsx("span",{className:"ml-1.5 text-xs opacity-60",children:p.media.length})]},p.id))})}),i&&e.jsxs("div",{className:"mt-6",children:[e.jsx("h3",{className:"text-2xl font-bold",children:i.name}),i.description&&e.jsx("p",{className:"text-white/60 mt-1.5 text-sm max-w-2xl",children:i.description}),i.media.length===0?e.jsx("p",{className:"text-white/40 text-sm mt-6 italic",children:"No media yet for this room."}):e.jsx("div",{className:"mt-5 grid grid-cols-2 lg:grid-cols-3 gap-3",children:i.media.map((p,f)=>e.jsx("button",{onClick:()=>a(f),className:"relative aspect-[4/3] rounded-xl overflow-hidden bg-white/5 group",children:p.kind==="video"?e.jsxs(e.Fragment,{children:[w4e(p.url)?e.jsx("div",{className:"absolute inset-0 bg-slate-900"}):e.jsx("video",{src:p.url,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 group-hover:bg-black/50 transition",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(fr,{className:"h-5 w-5 text-slate-900"})})})]}):e.jsx("img",{src:p.url,alt:i.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})},p.id))})]}),l&&i&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center p-6 cursor-zoom-out",onClick:c,children:[e.jsxs("div",{className:"absolute top-5 left-1/2 -translate-x-1/2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-xs font-medium",children:[i.name," — ",(r??0)+1," / ",o]}),e.jsx("button",{onClick:p=>{p.stopPropagation(),c()},className:"absolute top-5 right-5 h-10 w-10 rounded-full bg-white/10 hover:bg-white/20 text-white text-xl flex items-center justify-center transition","aria-label":"Close",children:"×"}),o>1&&e.jsx("button",{onClick:p=>{p.stopPropagation(),d()},className:"absolute left-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Previous",children:e.jsx(ml,{className:"h-6 w-6"})}),l.kind==="video"?w4e(l.url)?e.jsx("iframe",{src:`${l.url}?autoplay=true`,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full max-w-5xl aspect-video rounded-lg",onClick:p=>p.stopPropagation()},l.url):e.jsx("video",{src:l.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-full rounded-lg",onClick:p=>p.stopPropagation()},l.url):e.jsx("img",{src:l.url,alt:"",className:"max-w-full max-h-full rounded-lg cursor-default",onClick:p=>p.stopPropagation()}),o>1&&e.jsx("button",{onClick:p=>{p.stopPropagation(),u()},className:"absolute right-5 top-1/2 -translate-y-1/2 h-12 w-12 rounded-full bg-white/10 hover:bg-white/20 text-white flex items-center justify-center transition","aria-label":"Next",children:e.jsx(ga,{className:"h-6 w-6"})})]})]}):null}function vWt({rooms:s}){var o;const t=[];s.forEach(c=>{t.push({type:"cover",roomId:c.id,roomName:c.name,description:c.description,mediaCount:c.media.length}),c.media.forEach((d,u)=>{t.push({type:"media",roomId:c.id,roomName:c.name,url:d.url,kind:d.kind,index:u,total:c.media.length})})});const n=N.useRef(null),[r,a]=N.useState(0);N.useEffect(()=>{const c=n.current;if(!c)return;let d=0;const u=()=>{cancelAnimationFrame(d),d=requestAnimationFrame(()=>{const h=Math.round(c.scrollLeft/c.clientWidth);a(h)})};return c.addEventListener("scroll",u,{passive:!0}),()=>{c.removeEventListener("scroll",u),cancelAnimationFrame(d)}},[]);const i=c=>{const d=n.current;d&&d.scrollTo({left:c*d.clientWidth,behavior:"smooth"})};if(!t.length)return null;const l=(o=t[r])==null?void 0:o.roomId;return e.jsxs("div",{className:"md:hidden -mx-5",children:[e.jsx("div",{className:"px-5 py-3 overflow-x-auto sticky top-0 z-20 bg-slate-950/80 backdrop-blur-md border-b border-white/10",children:e.jsx("div",{className:"flex gap-2 min-w-max",children:s.map(c=>{const d=t.findIndex(h=>h.roomId===c.id),u=l===c.id;return e.jsx("button",{onClick:()=>i(d),className:Mt("px-3.5 py-1.5 rounded-full text-xs font-medium whitespace-nowrap transition",u?"bg-white text-slate-900":"bg-white/10 text-white/80"),children:c.name},c.id)})})}),e.jsx("div",{ref:n,className:"flex overflow-x-auto snap-x snap-mandatory scroll-smooth no-scrollbar",style:{scrollSnapType:"x mandatory"},children:t.map((c,d)=>e.jsx("div",{className:"shrink-0 w-screen snap-center",children:e.jsxs("div",{className:"w-full aspect-[9/16] max-h-[75vh] bg-slate-900 relative",children:[c.type==="cover"?e.jsxs("div",{className:"w-full h-full flex flex-col items-center justify-center p-8 text-center bg-gradient-to-br from-slate-800 to-slate-950",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-white/40 mb-2",children:"Next room"}),e.jsx("h3",{className:"text-3xl font-bold",children:c.roomName}),c.description&&e.jsx("p",{className:"text-white/70 text-sm mt-3 max-w-xs",children:c.description}),e.jsxs("p",{className:"text-white/40 text-xs mt-5",children:[c.mediaCount," ",c.mediaCount===1?"item":"items"," — swipe to view →"]})]}):c.kind==="video"?w4e(c.url)?e.jsx("iframe",{src:c.url,allow:"accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,className:"w-full h-full"}):e.jsx("video",{src:c.url,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):e.jsx("img",{src:c.url,alt:c.roomName,className:"w-full h-full object-cover"}),c.type==="media"&&e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-center justify-between pointer-events-none",children:[e.jsx("div",{className:"px-3 py-1 rounded-full bg-black/50 backdrop-blur-sm text-xs text-white font-medium",children:c.roomName}),e.jsxs("div",{className:"px-2.5 py-1 rounded-full bg-black/50 backdrop-blur-sm text-[10px] text-white/80",children:[c.index+1," / ",c.total]})]})]})},d))}),e.jsxs("div",{className:"flex items-center justify-between px-5 mt-3",children:[e.jsxs("button",{onClick:()=>i(Math.max(0,r-1)),disabled:r===0,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:[e.jsx(ml,{className:"h-4 w-4"})," Prev"]}),e.jsxs("span",{className:"text-xs text-white/50",children:[r+1," / ",t.length]}),e.jsxs("button",{onClick:()=>i(Math.min(t.length-1,r+1)),disabled:r===t.length-1,className:"flex items-center gap-1 text-sm text-white/70 disabled:opacity-30",children:["Next ",e.jsx(ga,{className:"h-4 w-4"})]})]})]})}const Ywe={question:{label:"Ask a Question",title:"Ask the agent",placeholder:"What would you like to know about the home?",icon:Ai},showing:{label:"Schedule a Showing",title:"Request a private showing",placeholder:"Anything specific to focus on during the showing? (optional)",icon:yr},disclosure:{label:"Request Disclosures",title:"Request seller disclosures",placeholder:"Any specific documents? (optional)",icon:br},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:Yl}},bWt=["Seller's Property Disclosure","HOA Documents & Bylaws","Inspection Reports","Title / CC&Rs","Utility & Tax History"];function _Wt(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 wWt({openHouse:s,visitorId:t,visitorName:n,visitorEmail:r,visitorPhone:a,previewMode:i=!1}){var Be;const l=s.profiles,o=((Be=l==null?void 0:l.name)==null?void 0:Be.split(" ").map(we=>we[0]).join("").slice(0,2))||"?",c=s.brand_color_override||null,[d,u]=N.useState(null),[h,p]=N.useState(""),[f,y]=N.useState(r||""),[_,v]=N.useState(a||""),[j,w]=N.useState(!1),[S,A]=N.useState(null),[E,O]=N.useState(""),[D,I]=N.useState(""),[F,z]=N.useState(""),[H,Z]=N.useState([]),[Y,W]=N.useState(""),[ee,se]=N.useState(""),[oe,he]=N.useState(""),[ce,me]=N.useState(""),le=_Wt(s.price),ve=s.tour_mode==="rooms",{data:ge=[]}=Bzt(ve?s.id:void 0),Te=[s.enable_question&&"question",s.enable_showing&&"showing",s.enable_disclosures&&"disclosure",s.enable_offer&&"offer"].filter(Boolean),Ie=we=>{u(we),p(""),O(""),I(""),z(""),Z([]),W(""),se(""),he(""),me("")},Ce=()=>{u(null)},Me=we=>{Z(Je=>Je.includes(we)?Je.filter(ke=>ke!==we):[...Je,we])},Pe=we=>we==="showing"?{preferred_date:E||null,preferred_time:D||null,alternate_date:F||null}:we==="disclosure"?{requested_documents:H}:we==="offer"?{offer_amount:Y||null,financing:ee||null,timeline:oe||null,pre_approved:ce||null}:{},Re=d?d==="showing"?!!E:d==="question"?h.trim().length>0:!0:!1,Ae=async()=>{if(d){if(i){Br({title:"Preview mode",description:"Lead not sent — this is just a preview."}),A(d),setTimeout(()=>{u(null),A(null)},1500);return}w(!0);try{const we=Pe(d),{error:Je}=await q.from("open_house_leads").insert({open_house_id:s.id,visitor_id:t,action_type:d,payload:{message:h.trim()||null,email:f.trim()||null,phone:_.trim()||null,visitor_name:n,...we}});if(Je)throw Je;q.functions.invoke("send-virtual-open-house-lead",{body:{open_house_id:s.id,visitor_id:t,action_type:d,message:h.trim()||null,visitor_name:n,visitor_email:f.trim()||null,visitor_phone:_.trim()||null,extras:we}}).catch(()=>{}),A(d),Br({title:"Sent!",description:"The agent has been notified."}),setTimeout(()=>{Ce(),A(null)},1400)}catch(we){Br({title:"Something went wrong",description:we.message,variant:"destructive"})}finally{w(!1)}}};return e.jsxs("div",{className:"min-h-screen bg-slate-950 text-white",children:[e.jsxs("div",{className:"relative w-full aspect-video bg-slate-900 md:max-h-[70vh]",children:[s.hero_video_url?e.jsx("video",{src:s.hero_video_url,poster:s.hero_video_thumbnail_url||s.photo_url||void 0,controls:!0,playsInline:!0,className:"w-full h-full object-cover"}):s.photo_url?e.jsx("img",{src:s.photo_url,alt:s.property_address,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-white/40",children:"No tour video yet"}),e.jsx("div",{className:"absolute inset-x-0 bottom-0 h-32 bg-gradient-to-t from-slate-950 to-transparent pointer-events-none"})]}),e.jsxs("div",{className:"max-w-3xl mx-auto px-5 pb-32 -mt-10 relative z-10",children:[e.jsxs("div",{className:"bg-slate-900/80 backdrop-blur-md border border-white/10 rounded-2xl p-6 shadow-2xl",children:[e.jsx("h1",{className:"text-2xl font-bold leading-tight",children:s.property_address}),s.city&&e.jsxs("p",{className:"text-sm text-white/60 mt-1 flex items-center gap-1",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),s.city,s.state?`, ${s.state}`:""," ",s.zip]}),le&&e.jsx("p",{className:"text-3xl font-bold text-white mt-3",children:le}),e.jsxs("div",{className:"flex flex-wrap gap-4 mt-4 text-sm text-white/80",children:[s.beds!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(J0,{className:"h-4 w-4"}),s.beds," bd"]}),s.baths!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(kp,{className:"h-4 w-4"}),s.baths," ba"]}),s.sqft!=null&&e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ay,{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(Jr,{className:"h-12 w-12 ring-2 ring-white/20",style:c?{boxShadow:`0 0 0 2px ${c}`}:void 0,children:[e.jsx(ti,{src:l.avatar_url||"",alt:l.name||""}),e.jsx(ea,{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(Cr,{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(Gs,{className:"h-4 w-4"})})]})]}),ve&&ge.length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx(yWt,{rooms:ge}),e.jsx(vWt,{rooms:ge})]}),Te.length>0&&e.jsx("div",{className:"mt-5 grid grid-cols-1 sm:grid-cols-2 gap-3",children:Te.map(we=>{const Je=Ywe[we],ke=Je.icon;return e.jsxs("button",{onClick:()=>Ie(we),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(ke,{className:"h-5 w-5"})}),e.jsx("span",{className:"font-medium text-sm",children:Je.label})]},we)})}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-8",children:"Powered by LevelUp Virtual Open House"})]}),e.jsx(t0,{open:!!d,onOpenChange:we=>!we&&Ce(),children:e.jsx(og,{side:"bottom",className:"rounded-t-2xl max-h-[92vh] overflow-y-auto",children:d&&e.jsxs(e.Fragment,{children:[e.jsxs(jy,{className:"text-left",children:[e.jsx(Ny,{children:Ywe[d].title}),e.jsxs(Z$,{children:[(l==null?void 0:l.name)||"The agent"," will be notified by email."]})]}),S===d?e.jsxs("div",{className:"py-10 flex flex-col items-center gap-3",children:[e.jsx("div",{className:"w-14 h-14 rounded-full bg-green-100 flex items-center justify-center",children:e.jsx(vr,{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(ne,{className:"text-xs",children:"Email"}),e.jsx(ye,{type:"email",value:f,onChange:we=>y(we.target.value),placeholder:"you@example.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Phone"}),e.jsx(ye,{type:"tel",value:_,onChange:we=>v(we.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(ne,{className:"text-xs",children:"Preferred date *"}),e.jsx(ye,{type:"date",value:E,onChange:we=>O(we.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Preferred time"}),e.jsx(ye,{type:"time",value:D,onChange:we=>I(we.target.value),className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Alternate date (optional)"}),e.jsx(ye,{type:"date",value:F,onChange:we=>z(we.target.value),className:"mt-1"})]})]}),d==="disclosure"&&e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Which documents? (select all that apply)"}),e.jsx("div",{className:"mt-2 space-y-2",children:bWt.map(we=>e.jsxs("label",{className:"flex items-center gap-2 text-sm cursor-pointer",children:[e.jsx(hi,{checked:H.includes(we),onCheckedChange:()=>Me(we)}),e.jsx("span",{children:we})]},we))})]}),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(ne,{className:"text-xs",children:"Estimated offer"}),e.jsx(ye,{value:Y,onChange:we=>W(we.target.value),placeholder:"$",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Financing"}),e.jsxs(us,{value:ee,onValueChange:se,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"Cash",children:"Cash"}),e.jsx(Ze,{value:"Conventional",children:"Conventional"}),e.jsx(Ze,{value:"FHA",children:"FHA"}),e.jsx(Ze,{value:"VA",children:"VA"}),e.jsx(Ze,{value:"Other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Timeline"}),e.jsxs(us,{value:oe,onValueChange:he,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"ASAP",children:"ASAP"}),e.jsx(Ze,{value:"30 days",children:"30 days"}),e.jsx(Ze,{value:"60 days",children:"60 days"}),e.jsx(Ze,{value:"90+ days",children:"90+ days"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Pre-approved?"}),e.jsxs(us,{value:ce,onValueChange:me,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"Yes",children:"Yes"}),e.jsx(Ze,{value:"No",children:"No"}),e.jsx(Ze,{value:"In progress",children:"In progress"})]})]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"text-xs",children:["Message",d==="question"?" *":" (optional)"]}),e.jsx(Ms,{value:h,onChange:we=>p(we.target.value),placeholder:Ywe[d].placeholder,rows:4,className:"mt-1"})]}),e.jsx(B,{onClick:Ae,disabled:j||!Re,className:"w-full h-12 text-white hover:opacity-90",style:c?{backgroundColor:c}:void 0,children:j?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):"Send to agent"})]})]})})})]})}const jWt=Gw({first_name:fo().trim().min(1,"First name is required").max(50),last_name:fo().trim().max(50).optional(),email:fo().trim().email("Please enter a valid email").max(255).optional().or(bp("")),phone:fo().trim().max(20).optional().or(bp(""))}),NWt=[{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 sdt({slug:s}={}){var $e;const t=bi(),n=s||t.slug,[r]=xl(),a=r.get("kiosk")==="1"||r.get("mode")==="kiosk",i=8,{data:l,isLoading:o,error:c}=Czt(n),d=Rzt(),u=Ozt(),h=Fzt(),p=N.useRef(!1),[f,y]=N.useState("welcome"),[_,v]=N.useState(null),[j,w]=N.useState({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),[S,A]=N.useState(""),[E,O]=N.useState(!1),[D,I]=N.useState(!1),[F,z]=N.useState(""),[H,Z]=N.useState(""),[Y,W]=N.useState(i),ee=N.useCallback(()=>{v(null),w({first_name:"",last_name:"",email:"",phone:"",visitor_address:""}),A(""),O(!1),I(!1),z(""),Z(""),W(i),y(a?"info":"welcome")},[a]),se=N.useCallback((Ke,Ge)=>{l!=null&&l.id&&q.functions.invoke("guestbook-lead-notify",{body:{open_house_id:l.id,visitor_id:Ke,first_name:Ge.first_name??j.first_name,last_name:Ge.last_name??j.last_name,email:Ge.email??j.email,phone:Ge.phone??j.phone,visitor_intent:Ge.visitor_intent??S,message:Ge.message,wants_market_updates:Ge.wants_market_updates??E,has_agent:Ge.has_agent??D,working_with_agent_name:Ge.working_with_agent_name??F,visitor_address:Ge.visitor_address??j.visitor_address}}).catch(rt=>console.error("Guest book lead notify failed:",rt))},[l==null?void 0:l.id,j,S,E,D,F]);N.useEffect(()=>{if(!a||f!=="done")return;W(i);const Ke=setInterval(()=>{W(Ge=>Ge<=1?(clearInterval(Ke),ee(),0):Ge-1)},1e3);return()=>clearInterval(Ke)},[a,f,ee]),N.useEffect(()=>{if(!a)return;y(Ge=>Ge==="welcome"?"info":Ge);let Ke=null;return(async()=>{var Ge,rt;try{Ke=await((rt=(Ge=navigator.wakeLock)==null?void 0:Ge.request)==null?void 0:rt.call(Ge,"screen"))}catch{}})(),()=>{var Ge;try{(Ge=Ke==null?void 0:Ke.release)==null||Ge.call(Ke)}catch{}}},[a]);const oe=N.useCallback(()=>{var Ge;const Ke=document.documentElement;document.fullscreenElement||(Ge=Ke.requestFullscreen||Ke.webkitRequestFullscreen)==null||Ge.call(Ke).catch(()=>{})},[]),{data:he,isLoading:ce}=Ezt(l==null?void 0:l.id),me=!!(l!=null&&l.enable_survey),le=(l==null?void 0:l.ask_visitor_intent)!==!1,ve=(l==null?void 0:l.ask_visitor_address)===!0;N.useEffect(()=>{if(!n||!(l!=null&&l.id)||p.current)return;const Ke=`oh_scan_${l.id}`;if(sessionStorage.getItem(Ke)){p.current=!0;return}p.current=!0,sessionStorage.setItem(Ke,"1"),h.mutate(n)},[n,l==null?void 0:l.id]),N.useEffect(()=>{f==="pending_survey"&&(ce||y(me&&((he==null?void 0:he.length)??0)>0?"survey":"done"))},[f,ce,me,he]);const ge=Ke=>{if(!Ke)return"";const[Ge,rt]=Ke.split(":"),tt=parseInt(Ge),at=tt>=12?"PM":"AM";return`${tt>12?tt-12:tt||12}:${rt} ${at}`},Te=async()=>{Z("");const Ke=jWt.safeParse(j);if(!Ke.success){Z(Ke.error.issues[0].message);return}if(!j.email&&!j.phone){Z("Please provide either an email or phone number");return}const Ge=(l==null?void 0:l.kind)==="virtual";let rt=null;if(!_&&(l!=null&&l.id))try{const tt=await d.mutateAsync({open_house_id:l.id,first_name:j.first_name.trim(),last_name:j.last_name.trim()||void 0,email:j.email.trim()||void 0,phone:j.phone.trim()||void 0,visitor_address:ve&&j.visitor_address.trim()?j.visitor_address.trim():void 0,wants_market_updates:E,has_agent:D,working_with_agent_name:D&&F.trim()?F.trim():void 0,partial_signin:Ge?!1:le});rt=tt.id,v(tt.id)}catch{if(Ge){Z("We could not start the virtual tour. Please try again.");return}}if(Ge){le?y("intent"):(rt&&se(rt,{}),y("done"));return}if(!le){rt&&se(rt,{}),me?!ce&&he&&he.length>0?y("survey"):y("pending_survey"):y("done");return}y("intent")},Ie=async Ke=>{A(Ke);try{let Ge=_;if(Ge?await u.mutateAsync({visitor_id:Ge,visitor_intent:Ke,wants_market_updates:E,has_agent:D,working_with_agent_name:D&&F.trim()?F.trim():null,partial_signin:!1}):(Ge=(await d.mutateAsync({open_house_id:l.id,first_name:j.first_name.trim(),last_name:j.last_name.trim()||void 0,email:j.email.trim()||void 0,phone:j.phone.trim()||void 0,visitor_address:ve&&j.visitor_address.trim()?j.visitor_address.trim():void 0,visitor_intent:Ke,wants_market_updates:E,has_agent:D,working_with_agent_name:D&&F.trim()?F.trim():void 0,partial_signin:!1})).id,v(Ge)),Ge&&se(Ge,{visitor_intent:Ke,wants_market_updates:E,has_agent:D,working_with_agent_name:D&&F.trim()?F.trim():null}),(l==null?void 0:l.kind)==="virtual"){y("done");return}me?!ce&&he&&he.length>0?y("survey"):y("pending_survey"):y("done")}catch{Z("Something went wrong. Please try again.")}};if(o)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center",children:e.jsx("div",{className:"w-10 h-10 border-4 border-white/20 border-t-white rounded-full animate-spin"})});if(c||!l)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(Or,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Open House Not Found"}),e.jsx("p",{className:"text-white/60",children:"This sign-in page doesn't exist or is no longer active."})]})});const Ce=l.profiles,Me=(($e=Ce==null?void 0:Ce.name)==null?void 0:$e.split(" ").map(Ke=>Ke[0]).join("").slice(0,2))||"?",Pe=l.event_type==="community",Re=l.kind==="virtual",Ae=typeof window<"u"&&new URLSearchParams(window.location.search).get("preview")==="1";if(Re&&(Ae||f==="done"))return!Ae&&!_?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(Zo,{children:[e.jsxs("title",{children:["Virtual Tour | ",l.property_address]}),e.jsx("meta",{name:"description",content:`Take a virtual tour of ${l.property_address}`}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),Ae&&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(wWt,{openHouse:l,visitorId:Ae?"preview":_,visitorName:Ae?"Preview Visitor":`${j.first_name} ${j.last_name}`.trim(),visitorEmail:Ae?"":j.email,visitorPhone:Ae?"":j.phone,previewMode:Ae})]});const we=`${Re?"Virtual Open House":Pe?"Community Event":"Open House"} — ${l.property_address}`,ke=[[l.city,l.state].filter(Boolean).join(", "),l.event_date?Ss(new Date(l.event_date+"T00:00:00"),"EEE, MMM d"):null,Ce!=null&&Ce.name?`Hosted by ${Ce.name}`:null].filter(Boolean).join(" · "),it=l.photo_url||"",je=it&&it.includes("/storage/v1/object/public/")?it.replace("/object/public/","/render/image/public/")+"?width=1200&height=630&resize=cover":it||"https://dashboard.relevelup.com/og-image.png",He=typeof window<"u"?window.location.href:`https://guestbook.relevelup.com/${n}`;return e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{children:[e.jsx("title",{children:we}),e.jsx("meta",{name:"description",content:ke||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:title",content:we}),e.jsx("meta",{property:"og:description",content:ke||`Sign in to ${l.property_address}`}),e.jsx("meta",{property:"og:image",content:je}),e.jsx("meta",{property:"og:image:width",content:"1200"}),e.jsx("meta",{property:"og:image:height",content:"630"}),e.jsx("meta",{property:"og:url",content: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:we}),e.jsx("meta",{name:"twitter:description",content:ke||`Sign in to ${l.property_address}`}),e.jsx("meta",{name:"twitter:image",content:je}),e.jsx("meta",{name:"robots",content:"noindex, nofollow"})]}),e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsxs("div",{className:"text-center mb-6",children:[e.jsxs(Jr,{className:"h-16 w-16 mx-auto mb-3 ring-2 ring-white/20",children:[e.jsx(ti,{src:(Ce==null?void 0:Ce.avatar_url)||"",alt:(Ce==null?void 0:Ce.name)||""}),e.jsx(ea,{className:"bg-white/10 text-white text-lg",children:Me})]}),e.jsx("p",{className:"text-white/60 text-sm",children:Ce==null?void 0:Ce.name}),(Ce==null?void 0:Ce.title)&&e.jsx("p",{className:"text-white/40 text-xs",children:Ce.title})]}),e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl overflow-hidden",children:[l.photo_url&&e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",children:[e.jsx("img",{src:l.photo_url,alt:l.property_address,className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-900/80 via-slate-900/20 to-transparent"}),e.jsxs("div",{className:"absolute bottom-0 left-0 right-0 px-6 pb-4",children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight drop-shadow-md",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-1.5 text-white/70 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Re&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),ge(l.start_time),l.end_time?` – ${ge(l.end_time)}`:""]})]})]})]})]}),!l.photo_url&&e.jsx("div",{className:"bg-gradient-to-r from-slate-800 to-slate-700 px-6 py-5",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/10 flex items-center justify-center shrink-0 mt-0.5",children:Pe?e.jsx(Ua,{className:"h-5 w-5 text-white"}):e.jsx(Or,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-white font-bold text-lg leading-tight",children:l.property_address}),e.jsxs("div",{className:"flex flex-wrap gap-3 mt-2 text-white/60 text-xs",children:[l.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),l.city,l.state?`, ${l.state}`:""," ",l.zip]}),!Re&&e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(l.event_date+"T00:00:00"),"MMM d, yyyy")]}),l.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),ge(l.start_time),l.end_time?` – ${ge(l.end_time)}`:""]})]})]})]})]})}),e.jsxs("div",{className:"p-6",children:[f==="welcome"&&e.jsxs("div",{className:"text-center space-y-6",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900 mb-2",children:"Welcome!"}),e.jsx("p",{className:"text-slate-500 text-sm",children:l.agent_greeting||"Please sign in below."})]}),e.jsxs(B,{onClick:()=>y("info"),className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Sign In ",e.jsx(Oa,{className:"h-5 w-5 ml-2"})]}),e.jsx("p",{className:"text-xs text-slate-400",children:"Quick & easy — takes 30 seconds"})]}),f==="info"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>y("welcome"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(qr,{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(ne,{className:"text-slate-600 text-xs",children:"First Name *"}),e.jsx(ye,{value:j.first_name,onChange:Ke=>w(Ge=>({...Ge,first_name:Ke.target.value})),placeholder:"First",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-slate-600 text-xs",children:"Last Name"}),e.jsx(ye,{value:j.last_name,onChange:Ke=>w(Ge=>({...Ge,last_name:Ke.target.value})),placeholder:"Last",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-slate-600 text-xs",children:"Email"}),e.jsx(ye,{type:"email",value:j.email,onChange:Ke=>w(Ge=>({...Ge,email:Ke.target.value})),placeholder:"your@email.com",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-slate-600 text-xs",children:"Phone"}),e.jsx(ye,{type:"tel",value:j.phone,onChange:Ke=>w(Ge=>({...Ge,phone:Ke.target.value})),placeholder:"(555) 123-4567",className:"mt-1 h-12 rounded-xl border-slate-200 text-base"})]}),ve&&e.jsxs("div",{children:[e.jsx(ne,{className:"text-slate-600 text-xs",children:"Your Home Address"}),e.jsx(ye,{value:j.visitor_address,onChange:Ke=>w(Ge=>({...Ge,visitor_address:Ke.target.value})),placeholder:"Street, City, State ZIP",className:"mt-1 h-12 rounded-xl border-slate-200 text-base",autoComplete:"street-address"})]}),e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer pt-1",children:[e.jsx("input",{type:"checkbox",checked:E,onChange:Ke=>O(Ke.target.checked),className:"rounded border-slate-300 text-slate-900 focus:ring-slate-500"}),e.jsx("span",{className:"text-sm text-slate-600",children:"Send me market updates for this area"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-slate-600",children:"Already working with an agent?"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs font-medium text-slate-400",children:D?"Yes":"No"}),e.jsx(jn,{checked:D,onCheckedChange:I})]})]}),D&&e.jsx(ye,{value:F,onChange:Ke=>z(Ke.target.value),placeholder:"Agent's name",className:"mt-1 h-10 rounded-xl border-slate-200 text-sm"})]}),H&&e.jsx("p",{className:"text-destructive text-sm",children:H}),e.jsxs(B,{onClick:Te,className:"w-full h-14 text-base bg-slate-900 hover:bg-slate-800 text-white rounded-xl",children:["Continue ",e.jsx(Oa,{className:"h-5 w-5 ml-2"})]})]}),f==="intent"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("button",{onClick:()=>y("info"),className:"text-slate-400 hover:text-slate-600",children:e.jsx(qr,{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:NWt.map(Ke=>e.jsxs("button",{onClick:()=>Ie(Ke.value),disabled:d.isPending,className:"flex flex-col items-center gap-2 p-5 rounded-xl border-2 border-slate-200 hover:border-slate-900 hover:bg-slate-50 transition-all text-center group",children:[e.jsx("span",{className:"text-2xl",children:Ke.emoji}),e.jsx("span",{className:"text-sm font-medium text-slate-700 group-hover:text-slate-900",children:Ke.label})]},Ke.value))}),H&&e.jsx("p",{className:"text-destructive text-sm text-center",children:H})]}),f==="pending_survey"&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 gap-3",children:[e.jsx("div",{className:"w-8 h-8 border-[3px] border-slate-200 border-t-slate-900 rounded-full animate-spin"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading survey..."})]}),f==="survey"&&_&&he&&e.jsx(uWt,{questions:he,visitorId:_,onComplete:()=>y("done"),onSkip:()=>y("done")}),f==="done"&&e.jsxs("div",{className:"text-center space-y-4 py-4",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-green-100 flex items-center justify-center mx-auto",children:e.jsx(vr,{className:"h-8 w-8 text-green-600"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold text-slate-900",children:"You're all set!"}),e.jsxs("p",{className:"text-slate-500 text-sm mt-1",children:["Thanks for signing in, ",j.first_name,". ",Pe?"Enjoy the event!":"Enjoy the open house!"]})]}),(l==null?void 0:l.disclosure_pdf_url)&&e.jsxs("a",{href:`https://docs.google.com/gview?url=${encodeURIComponent(l.disclosure_pdf_url)}&embedded=true`,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 px-5 py-3 rounded-xl bg-slate-100 hover:bg-slate-200 text-slate-800 font-medium text-sm transition-colors",children:[e.jsx(br,{className:"h-4 w-4"}),"View Seller's Disclosures"]}),(Ce==null?void 0:Ce.name)&&e.jsxs("p",{className:"text-sm text-slate-400",children:["Your host today: ",e.jsx("strong",{className:"text-slate-600",children:Ce.name})]}),a&&e.jsxs("div",{className:"pt-4 space-y-3",children:[e.jsx(B,{onClick:ee,className:"w-full h-14 text-base font-semibold rounded-xl",children:"Sign in next visitor"}),e.jsxs("p",{className:"text-xs text-slate-400",children:["Ready for the next visitor in ",Y,"s…"]})]})]})]})]}),e.jsx("p",{className:"text-center text-white/30 text-xs mt-6",children:"Powered by LevelUp Guest Book"}),a&&e.jsxs("div",{className:"fixed top-3 right-3 flex items-center gap-2 z-50",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10",children:[e.jsx(pL,{className:"h-3 w-3"})," Tablet Mode"]}),e.jsx("button",{onClick:oe,className:"inline-flex items-center gap-1 rounded-full bg-white/10 backdrop-blur-sm text-white/80 text-[11px] px-2.5 py-1 border border-white/10 hover:bg-white/20",title:"Enter full screen",children:e.jsx(t9,{className:"h-3 w-3"})})]})]})})]})}function nfn(s){const{user:t}=vs();return dt({queryKey:["cohost-tokens",s],queryFn:async()=>{const{data:n,error:r}=await q.from("open_house_cohost_tokens").select("*").eq("open_house_id",s).order("created_at",{ascending:!1});if(r)throw r;return n},enabled:!!t&&!!s})}function rfn(){const s=Kt(),{user:t}=vs();return yt({mutationFn:async({openHouseId:n,label:r})=>{const{data:a,error:i}=await q.from("open_house_cohost_tokens").insert({open_house_id:n,label:r||null,created_by:t.id,expires_at:new Date(Date.now()+864e5).toISOString()}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["cohost-tokens",r.openHouseId]})}})}function afn(){const s=Kt();return yt({mutationFn:async({id:t,openHouseId:n})=>{const{error:r}=await q.from("open_house_cohost_tokens").update({is_active:!1}).eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cohost-tokens",n.openHouseId]})}})}function kWt(s){return dt({queryKey:["cohost-validate",s],queryFn:async()=>{const{data:t,error:n}=await q.from("open_house_cohost_tokens").select("*, open_houses(*)").eq("token",s).eq("is_active",!0).single();if(n)throw n;if(t.expires_at&&new Date(t.expires_at)t[n][r]??n,s)}var tMe="ScrollArea",[ndt,ifn]=uu(tMe),[CWt,Yv]=ndt(tMe),rdt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,type:r="hover",dir:a,scrollHideDelay:i=600,...l}=s,[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,y]=N.useState(null),[_,v]=N.useState(null),[j,w]=N.useState(0),[S,A]=N.useState(0),[E,O]=N.useState(!1),[D,I]=N.useState(!1),F=ji(t,H=>c(H)),z=vN(a);return e.jsx(CWt,{scope:n,type:r,dir:z,scrollHideDelay:i,scrollArea:o,viewport:d,onViewportChange:u,content:h,onContentChange:p,scrollbarX:f,onScrollbarXChange:y,scrollbarXEnabled:E,onScrollbarXEnabledChange:O,scrollbarY:_,onScrollbarYChange:v,scrollbarYEnabled:D,onScrollbarYEnabledChange:I,onCornerWidthChange:w,onCornerHeightChange:A,children:e.jsx(Yr.div,{dir:z,...l,ref:F,style:{position:"relative","--radix-scroll-area-corner-width":j+"px","--radix-scroll-area-corner-height":S+"px",...s.style}})})});rdt.displayName=tMe;var adt="ScrollAreaViewport",idt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,children:r,nonce:a,...i}=s,l=Yv(adt,n),o=N.useRef(null),c=ji(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(Yr.div,{"data-radix-scroll-area-viewport":"",...i,ref:c,style:{overflowX:l.scrollbarXEnabled?"scroll":"hidden",overflowY:l.scrollbarYEnabled?"scroll":"hidden",...s.style},children:e.jsx("div",{ref:l.onContentChange,style:{minWidth:"100%",display:"table"},children:r})})]})});idt.displayName=adt;var Ww="ScrollAreaScrollbar",sMe=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Yv(Ww,s.__scopeScrollArea),{onScrollbarXEnabledChange:i,onScrollbarYEnabledChange:l}=a,o=s.orientation==="horizontal";return N.useEffect(()=>(o?i(!0):l(!0),()=>{o?i(!1):l(!1)}),[o,i,l]),a.type==="hover"?e.jsx(TWt,{...r,ref:t,forceMount:n}):a.type==="scroll"?e.jsx(EWt,{...r,ref:t,forceMount:n}):a.type==="auto"?e.jsx(odt,{...r,ref:t,forceMount:n}):a.type==="always"?e.jsx(nMe,{...r,ref:t}):null});sMe.displayName=Ww;var TWt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Yv(Ww,s.__scopeScrollArea),[i,l]=N.useState(!1);return N.useEffect(()=>{const o=a.scrollArea;let c=0;if(o){const d=()=>{window.clearTimeout(c),l(!0)},u=()=>{c=window.setTimeout(()=>l(!1),a.scrollHideDelay)};return o.addEventListener("pointerenter",d),o.addEventListener("pointerleave",u),()=>{window.clearTimeout(c),o.removeEventListener("pointerenter",d),o.removeEventListener("pointerleave",u)}}},[a.scrollArea,a.scrollHideDelay]),e.jsx(Lh,{present:n||i,children:e.jsx(odt,{"data-state":i?"visible":"hidden",...r,ref:t})})}),EWt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=Yv(Ww,s.__scopeScrollArea),i=s.orientation==="horizontal",l=lye(()=>c("SCROLL_END"),100),[o,c]=SWt("hidden",{hidden:{SCROLL:"scrolling"},scrolling:{SCROLL_END:"idle",POINTER_ENTER:"interacting"},interacting:{SCROLL:"interacting",POINTER_LEAVE:"idle"},idle:{HIDE:"hidden",SCROLL:"scrolling",POINTER_ENTER:"interacting"}});return N.useEffect(()=>{if(o==="idle"){const d=window.setTimeout(()=>c("HIDE"),a.scrollHideDelay);return()=>window.clearTimeout(d)}},[o,a.scrollHideDelay,c]),N.useEffect(()=>{const d=a.viewport,u=i?"scrollLeft":"scrollTop";if(d){let h=d[u];const p=()=>{const f=d[u];h!==f&&(c("SCROLL"),l()),h=f};return d.addEventListener("scroll",p),()=>d.removeEventListener("scroll",p)}},[a.viewport,i,c,l]),e.jsx(Lh,{present:n||o!=="hidden",children:e.jsx(nMe,{"data-state":o==="hidden"?"hidden":"visible",...r,ref:t,onPointerEnter:xr(s.onPointerEnter,()=>c("POINTER_ENTER")),onPointerLeave:xr(s.onPointerLeave,()=>c("POINTER_LEAVE"))})})}),odt=N.forwardRef((s,t)=>{const n=Yv(Ww,s.__scopeScrollArea),{forceMount:r,...a}=s,[i,l]=N.useState(!1),o=s.orientation==="horizontal",c=lye(()=>{if(n.viewport){const d=n.viewport.offsetWidth{const{orientation:n="vertical",...r}=s,a=Yv(Ww,s.__scopeScrollArea),i=N.useRef(null),l=N.useRef(0),[o,c]=N.useState({content:0,viewport:0,scrollbar:{size:0,paddingStart:0,paddingEnd:0}}),d=hdt(o.viewport,o.content),u={...r,sizes:o,onSizesChange:c,hasThumb:d>0&&d<1,onThumbChange:p=>i.current=p,onThumbPointerUp:()=>l.current=0,onThumbPointerDown:p=>l.current=p};function h(p,f){return DWt(p,l.current,o,f)}return n==="horizontal"?e.jsx(AWt,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const p=a.viewport.scrollLeft,f=_Be(p,o,a.dir);i.current.style.transform=`translate3d(${f}px, 0, 0)`}},onWheelScroll:p=>{a.viewport&&(a.viewport.scrollLeft=p)},onDragScroll:p=>{a.viewport&&(a.viewport.scrollLeft=h(p,a.dir))}}):n==="vertical"?e.jsx(MWt,{...u,ref:t,onThumbPositionChange:()=>{if(a.viewport&&i.current){const p=a.viewport.scrollTop,f=_Be(p,o);i.current.style.transform=`translate3d(0, ${f}px, 0)`}},onWheelScroll:p=>{a.viewport&&(a.viewport.scrollTop=p)},onDragScroll:p=>{a.viewport&&(a.viewport.scrollTop=h(p))}}):null}),AWt=N.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=Yv(Ww,s.__scopeScrollArea),[l,o]=N.useState(),c=N.useRef(null),d=ji(t,c,i.onScrollbarXChange);return N.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(cdt,{"data-orientation":"horizontal",...a,ref:d,sizes:n,style:{bottom:0,left:i.dir==="rtl"?"var(--radix-scroll-area-corner-width)":0,right:i.dir==="ltr"?"var(--radix-scroll-area-corner-width)":0,"--radix-scroll-area-thumb-width":oye(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.x),onDragScroll:u=>s.onDragScroll(u.x),onWheelScroll:(u,h)=>{if(i.viewport){const p=i.viewport.scrollLeft+u.deltaX;s.onWheelScroll(p),pdt(p,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollWidth,viewport:i.viewport.offsetWidth,scrollbar:{size:c.current.clientWidth,paddingStart:tfe(l.paddingLeft),paddingEnd:tfe(l.paddingRight)}})}})}),MWt=N.forwardRef((s,t)=>{const{sizes:n,onSizesChange:r,...a}=s,i=Yv(Ww,s.__scopeScrollArea),[l,o]=N.useState(),c=N.useRef(null),d=ji(t,c,i.onScrollbarYChange);return N.useEffect(()=>{c.current&&o(getComputedStyle(c.current))},[c]),e.jsx(cdt,{"data-orientation":"vertical",...a,ref:d,sizes:n,style:{top:0,right:i.dir==="ltr"?0:void 0,left:i.dir==="rtl"?0:void 0,bottom:"var(--radix-scroll-area-corner-height)","--radix-scroll-area-thumb-height":oye(n)+"px",...s.style},onThumbPointerDown:u=>s.onThumbPointerDown(u.y),onDragScroll:u=>s.onDragScroll(u.y),onWheelScroll:(u,h)=>{if(i.viewport){const p=i.viewport.scrollTop+u.deltaY;s.onWheelScroll(p),pdt(p,h)&&u.preventDefault()}},onResize:()=>{c.current&&i.viewport&&l&&r({content:i.viewport.scrollHeight,viewport:i.viewport.offsetHeight,scrollbar:{size:c.current.clientHeight,paddingStart:tfe(l.paddingTop),paddingEnd:tfe(l.paddingBottom)}})}})}),[IWt,ldt]=ndt(Ww),cdt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,sizes:r,hasThumb:a,onThumbChange:i,onThumbPointerUp:l,onThumbPointerDown:o,onThumbPositionChange:c,onDragScroll:d,onWheelScroll:u,onResize:h,...p}=s,f=Yv(Ww,n),[y,_]=N.useState(null),v=ji(t,F=>_(F)),j=N.useRef(null),w=N.useRef(""),S=f.viewport,A=r.content-r.viewport,E=rh(u),O=rh(c),D=lye(h,10);function I(F){if(j.current){const z=F.clientX-j.current.left,H=F.clientY-j.current.top;d({x:z,y:H})}}return N.useEffect(()=>{const F=z=>{const H=z.target;(y==null?void 0:y.contains(H))&&E(z,A)};return document.addEventListener("wheel",F,{passive:!1}),()=>document.removeEventListener("wheel",F,{passive:!1})},[S,y,A,E]),N.useEffect(O,[r,O]),y8(y,D),y8(f.content,D),e.jsx(IWt,{scope:n,scrollbar:y,hasThumb:a,onThumbChange:rh(i),onThumbPointerUp:rh(l),onThumbPositionChange:O,onThumbPointerDown:rh(o),children:e.jsx(Yr.div,{...p,ref:v,style:{position:"absolute",...p.style},onPointerDown:xr(s.onPointerDown,F=>{F.button===0&&(F.target.setPointerCapture(F.pointerId),j.current=y.getBoundingClientRect(),w.current=document.body.style.webkitUserSelect,document.body.style.webkitUserSelect="none",f.viewport&&(f.viewport.style.scrollBehavior="auto"),I(F))}),onPointerMove:xr(s.onPointerMove,I),onPointerUp:xr(s.onPointerUp,F=>{const z=F.target;z.hasPointerCapture(F.pointerId)&&z.releasePointerCapture(F.pointerId),document.body.style.webkitUserSelect=w.current,f.viewport&&(f.viewport.style.scrollBehavior=""),j.current=null})})})}),efe="ScrollAreaThumb",ddt=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=ldt(efe,s.__scopeScrollArea);return e.jsx(Lh,{present:n||a.hasThumb,children:e.jsx(PWt,{ref:t,...r})})}),PWt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,style:r,...a}=s,i=Yv(efe,n),l=ldt(efe,n),{onThumbPositionChange:o}=l,c=ji(t,h=>l.onThumbChange(h)),d=N.useRef(void 0),u=lye(()=>{d.current&&(d.current(),d.current=void 0)},100);return N.useEffect(()=>{const h=i.viewport;if(h){const p=()=>{if(u(),!d.current){const f=RWt(h,o);d.current=f,o()}};return o(),h.addEventListener("scroll",p),()=>h.removeEventListener("scroll",p)}},[i.viewport,u,o]),e.jsx(Yr.div,{"data-state":l.hasThumb?"visible":"hidden",...a,ref:c,style:{width:"var(--radix-scroll-area-thumb-width)",height:"var(--radix-scroll-area-thumb-height)",...r},onPointerDownCapture:xr(s.onPointerDownCapture,h=>{const f=h.target.getBoundingClientRect(),y=h.clientX-f.left,_=h.clientY-f.top;l.onThumbPointerDown({x:y,y:_})}),onPointerUp:xr(s.onPointerUp,l.onThumbPointerUp)})});ddt.displayName=efe;var rMe="ScrollAreaCorner",udt=N.forwardRef((s,t)=>{const n=Yv(rMe,s.__scopeScrollArea),r=!!(n.scrollbarX&&n.scrollbarY);return n.type!=="scroll"&&r?e.jsx(LWt,{...s,ref:t}):null});udt.displayName=rMe;var LWt=N.forwardRef((s,t)=>{const{__scopeScrollArea:n,...r}=s,a=Yv(rMe,n),[i,l]=N.useState(0),[o,c]=N.useState(0),d=!!(i&&o);return y8(a.scrollbarX,()=>{var h;const u=((h=a.scrollbarX)==null?void 0:h.offsetHeight)||0;a.onCornerHeightChange(u),c(u)}),y8(a.scrollbarY,()=>{var h;const u=((h=a.scrollbarY)==null?void 0:h.offsetWidth)||0;a.onCornerWidthChange(u),l(u)}),d?e.jsx(Yr.div,{...r,ref:t,style:{width:i,height:o,position:"absolute",right:a.dir==="ltr"?0:void 0,left:a.dir==="rtl"?0:void 0,bottom:0,...s.style}}):null});function tfe(s){return s?parseInt(s,10):0}function hdt(s,t){const n=s/t;return isNaN(n)?0:n}function oye(s){const t=hdt(s.viewport,s.content),n=s.scrollbar.paddingStart+s.scrollbar.paddingEnd,r=(s.scrollbar.size-n)*t;return Math.max(r,18)}function DWt(s,t,n,r="ltr"){const a=oye(n),i=a/2,l=t||i,o=a-l,c=n.scrollbar.paddingStart+l,d=n.scrollbar.size-n.scrollbar.paddingEnd-o,u=n.content-n.viewport,h=r==="ltr"?[0,u]:[u*-1,0];return mdt([c,d],h)(s)}function _Be(s,t,n="ltr"){const r=oye(t),a=t.scrollbar.paddingStart+t.scrollbar.paddingEnd,i=t.scrollbar.size-a,l=t.content-t.viewport,o=i-r,c=n==="ltr"?[0,l]:[l*-1,0],d=eB(s,c);return mdt([0,l],[0,o])(d)}function mdt(s,t){return n=>{if(s[0]===s[1]||t[0]===t[1])return t[0];const r=(t[1]-t[0])/(s[1]-s[0]);return t[0]+r*(n-s[0])}}function pdt(s,t){return s>0&&s{})=>{let n={left:s.scrollLeft,top:s.scrollTop},r=0;return function a(){const i={left:s.scrollLeft,top:s.scrollTop},l=n.left!==i.left,o=n.top!==i.top;(l||o)&&t(),n=i,r=window.requestAnimationFrame(a)}(),()=>window.cancelAnimationFrame(r)};function lye(s,t){const n=rh(s),r=N.useRef(0);return N.useEffect(()=>()=>window.clearTimeout(r.current),[]),N.useCallback(()=>{window.clearTimeout(r.current),r.current=window.setTimeout(n,t)},[n,t])}function y8(s,t){const n=rh(t);lh(()=>{let r=0;if(s){const a=new ResizeObserver(()=>{cancelAnimationFrame(r),r=window.requestAnimationFrame(n)});return a.observe(s),()=>{window.cancelAnimationFrame(r),a.unobserve(s)}}},[s,n])}var fdt=rdt,OWt=idt,FWt=udt;const di=N.forwardRef(({className:s,children:t,...n},r)=>e.jsxs(fdt,{ref:r,className:Mt("relative overflow-hidden",s),...n,children:[e.jsx(OWt,{className:"h-full w-full rounded-[inherit]",children:t}),e.jsx(Q$,{}),e.jsx(FWt,{})]}));di.displayName=fdt.displayName;const Q$=N.forwardRef(({className:s,orientation:t="vertical",...n},r)=>e.jsx(sMe,{ref:r,orientation:t,className:Mt("flex touch-none select-none transition-colors",t==="vertical"&&"h-full w-2.5 border-l border-l-transparent p-[1px]",t==="horizontal"&&"h-2.5 flex-col border-t border-t-transparent p-[1px]",s),...n,children:e.jsx(ddt,{className:"relative flex-1 rounded-full bg-border"})}));Q$.displayName=sMe.displayName;const aMe=N.createContext({});function iMe(s){const t=N.useRef(null);return t.current===null&&(t.current=s()),t.current}const zWt=typeof window<"u",xdt=zWt?N.useLayoutEffect:N.useEffect,cye=N.createContext(null);function oMe(s,t){s.indexOf(t)===-1&&s.push(t)}function sfe(s,t){const n=s.indexOf(t);n>-1&&s.splice(n,1)}const Ew=(s,t,n)=>n>t?t:n{},v8=()=>{};const k4={},gdt=s=>/^-?(?:\d+(?:\.\d+)?|\.\d+)$/u.test(s);function ydt(s){return typeof s=="object"&&s!==null}const vdt=s=>/^0[^.\s]+$/u.test(s);function bdt(s){let t;return()=>(t===void 0&&(t=s()),t)}const Fv=s=>s,BWt=(s,t)=>n=>t(s(n)),X$=(...s)=>s.reduce(BWt),nB=(s,t,n)=>{const r=t-s;return r===0?1:(n-s)/r};class lMe{constructor(){this.subscriptions=[]}add(t){return oMe(this.subscriptions,t),()=>sfe(this.subscriptions,t)}notify(t,n,r){const a=this.subscriptions.length;if(a)if(a===1)this.subscriptions[0](t,n,r);else for(let i=0;is*1e3,Ev=s=>s/1e3;function _dt(s,t){return t?s*(1e3/t):0}const wdt=(s,t,n)=>(((1-3*n+3*t)*s+(3*n-6*t))*s+3*t)*s,$Wt=1e-7,UWt=12;function qWt(s,t,n,r,a){let i,l,o=0;do l=t+(n-t)/2,i=wdt(l,r,a)-s,i>0?n=l:t=l;while(Math.abs(i)>$Wt&&++oqWt(i,0,1,s,n);return i=>i===0||i===1?i:wdt(a(i),t,r)}const jdt=s=>t=>t<=.5?s(2*t)/2:(2-s(2*(1-t)))/2,Ndt=s=>t=>1-s(1-t),kdt=J$(.33,1.53,.69,.99),cMe=Ndt(kdt),Sdt=jdt(cMe),Cdt=s=>s>=1?1:(s*=2)<1?.5*cMe(s):.5*(2-Math.pow(2,-10*(s-1))),dMe=s=>1-Math.sin(Math.acos(s)),Tdt=Ndt(dMe),Edt=jdt(dMe),VWt=J$(.42,0,1,1),HWt=J$(0,0,.58,1),Adt=J$(.42,0,.58,1),GWt=s=>Array.isArray(s)&&typeof s[0]!="number",Mdt=s=>Array.isArray(s)&&typeof s[0]=="number",wBe={linear:Fv,easeIn:VWt,easeInOut:Adt,easeOut:HWt,circIn:dMe,circInOut:Edt,circOut:Tdt,backIn:cMe,backInOut:Sdt,backOut:kdt,anticipate:Cdt},WWt=s=>typeof s=="string",jBe=s=>{if(Mdt(s)){v8(s.length===4,"Cubic bezier arrays must contain four numerical values.","cubic-bezier-length");const[t,n,r,a]=s;return J$(t,n,r,a)}else if(WWt(s))return v8(wBe[s]!==void 0,`Invalid easing type '${s}'`,"invalid-easing-type"),wBe[s];return s},ZV=["setup","read","resolveKeyframes","preUpdate","update","preRender","render","postRender"],NBe={value:null,addProjectionMetrics:null};function KWt(s,t){let n=new Set,r=new Set,a=!1,i=!1;const l=new WeakSet;let o={delta:0,timestamp:0,isProcessing:!1},c=0;function d(h){l.has(h)&&(u.schedule(h),s()),c++,h(o)}const u={schedule:(h,p=!1,f=!1)=>{const _=f&&a?n:r;return p&&l.add(h),_.add(h),h},cancel:h=>{r.delete(h),l.delete(h)},process:h=>{if(o=h,a){i=!0;return}a=!0;const p=n;n=r,r=p,n.forEach(d),t&&NBe.value&&NBe.value.frameloop[t].push(c),c=0,n.clear(),a=!1,i&&(i=!1,u.process(h))}};return u}const YWt=40;function Idt(s,t){let n=!1,r=!0;const a={delta:0,timestamp:0,isProcessing:!1},i=()=>n=!0,l=ZV.reduce((S,A)=>(S[A]=KWt(i,t?A:void 0),S),{}),{setup:o,read:c,resolveKeyframes:d,preUpdate:u,update:h,preRender:p,render:f,postRender:y}=l,_=()=>{const S=k4.useManualTiming,A=S?a.timestamp:performance.now();n=!1,S||(a.delta=r?1e3/60:Math.max(Math.min(A-a.timestamp,YWt),1)),a.timestamp=A,a.isProcessing=!0,o.process(a),c.process(a),d.process(a),u.process(a),h.process(a),p.process(a),f.process(a),y.process(a),a.isProcessing=!1,n&&t&&(r=!1,s(_))},v=()=>{n=!0,r=!0,a.isProcessing||s(_)};return{schedule:ZV.reduce((S,A)=>{const E=l[A];return S[A]=(O,D=!1,I=!1)=>(n||v(),E.schedule(O,D,I)),S},{}),cancel:S=>{for(let A=0;A(bme===void 0&&Hx.set(Jp.isProcessing||k4.useManualTiming?Jp.timestamp:performance.now()),bme),set:s=>{bme=s,queueMicrotask(ZWt)}},Pdt=s=>t=>typeof t=="string"&&t.startsWith(s),Ldt=Pdt("--"),QWt=Pdt("var(--"),uMe=s=>QWt(s)?XWt.test(s.split("/*")[0].trim()):!1,XWt=/var\(--(?:[\w-]+\s*|[\w-]+\s*,(?:\s*[^)(\s]|\s*\((?:[^)(]|\([^)(]*\))*\))+\s*)\)$/iu;function kBe(s){return typeof s!="string"?!1:s.split("/*")[0].includes("var(--")}const FD={test:s=>typeof s=="number",parse:parseFloat,transform:s=>s},rB={...FD,transform:s=>Ew(0,1,s)},QV={...FD,default:1},B9=s=>Math.round(s*1e5)/1e5,hMe=/-?(?:\d+(?:\.\d+)?|\.\d+)/gu;function JWt(s){return s==null}const eKt=/^(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))$/iu,mMe=(s,t)=>n=>!!(typeof n=="string"&&eKt.test(n)&&n.startsWith(s)||t&&!JWt(n)&&Object.prototype.hasOwnProperty.call(n,t)),Ddt=(s,t,n)=>r=>{if(typeof r!="string")return r;const[a,i,l,o]=r.match(hMe);return{[s]:parseFloat(a),[t]:parseFloat(i),[n]:parseFloat(l),alpha:o!==void 0?parseFloat(o):1}},tKt=s=>Ew(0,255,s),Qwe={...FD,transform:s=>Math.round(tKt(s))},$E={test:mMe("rgb","red"),parse:Ddt("red","green","blue"),transform:({red:s,green:t,blue:n,alpha:r=1})=>"rgba("+Qwe.transform(s)+", "+Qwe.transform(t)+", "+Qwe.transform(n)+", "+B9(rB.transform(r))+")"};function sKt(s){let t="",n="",r="",a="";return s.length>5?(t=s.substring(1,3),n=s.substring(3,5),r=s.substring(5,7),a=s.substring(7,9)):(t=s.substring(1,2),n=s.substring(2,3),r=s.substring(3,4),a=s.substring(4,5),t+=t,n+=n,r+=r,a+=a),{red:parseInt(t,16),green:parseInt(n,16),blue:parseInt(r,16),alpha:a?parseInt(a,16)/255:1}}const j4e={test:mMe("#"),parse:sKt,transform:$E.transform},eU=s=>({test:t=>typeof t=="string"&&t.endsWith(s)&&t.split(" ").length===1,parse:parseFloat,transform:t=>`${t}${s}`}),Dk=eU("deg"),bw=eU("%"),oi=eU("px"),nKt=eU("vh"),rKt=eU("vw"),SBe={...bw,parse:s=>bw.parse(s)/100,transform:s=>bw.transform(s*100)},wP={test:mMe("hsl","hue"),parse:Ddt("hue","saturation","lightness"),transform:({hue:s,saturation:t,lightness:n,alpha:r=1})=>"hsla("+Math.round(s)+", "+bw.transform(B9(t))+", "+bw.transform(B9(n))+", "+B9(rB.transform(r))+")"},Wh={test:s=>$E.test(s)||j4e.test(s)||wP.test(s),parse:s=>$E.test(s)?$E.parse(s):wP.test(s)?wP.parse(s):j4e.parse(s),transform:s=>typeof s=="string"?s:s.hasOwnProperty("red")?$E.transform(s):wP.transform(s),getAnimatableNone:s=>{const t=Wh.parse(s);return t.alpha=0,Wh.transform(t)}},aKt=/(?:#[\da-f]{3,8}|(?:rgb|hsl)a?\((?:-?[\d.]+%?[,\s]+){2}-?[\d.]+%?\s*(?:[,/]\s*)?(?:\b\d+(?:\.\d+)?|\.\d+)?%?\))/giu;function iKt(s){var t,n;return isNaN(s)&&typeof s=="string"&&(((t=s.match(hMe))==null?void 0:t.length)||0)+(((n=s.match(aKt))==null?void 0:n.length)||0)>0}const Rdt="number",Odt="color",oKt="var",lKt="var(",CBe="${}",cKt=/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 b8(s){const t=s.toString(),n=[],r={color:[],number:[],var:[]},a=[];let i=0;const o=t.replace(cKt,c=>(Wh.test(c)?(r.color.push(i),a.push(Odt),n.push(Wh.parse(c))):c.startsWith(lKt)?(r.var.push(i),a.push(oKt),n.push(c)):(r.number.push(i),a.push(Rdt),n.push(parseFloat(c))),++i,CBe)).split(CBe);return{values:n,split:o,indexes:r,types:a}}function dKt(s){return b8(s).values}function Fdt({split:s,types:t}){const n=s.length;return r=>{let a="";for(let i=0;itypeof s=="number"?0:Wh.test(s)?Wh.getAnimatableNone(s):s,mKt=(s,t)=>typeof s=="number"?t!=null&&t.trim().endsWith("/")?s:0:hKt(s);function pKt(s){const t=b8(s);return Fdt(t)(t.values.map((r,a)=>mKt(r,t.split[a])))}const vb={test:iKt,parse:dKt,createTransformer:uKt,getAnimatableNone:pKt};function Xwe(s,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?s+(t-s)*6*n:n<1/2?t:n<2/3?s+(t-s)*(2/3-n)*6:s}function fKt({hue:s,saturation:t,lightness:n,alpha:r}){s/=360,t/=100,n/=100;let a=0,i=0,l=0;if(!t)a=i=l=n;else{const o=n<.5?n*(1+t):n+t-n*t,c=2*n-o;a=Xwe(c,o,s+1/3),i=Xwe(c,o,s),l=Xwe(c,o,s-1/3)}return{red:Math.round(a*255),green:Math.round(i*255),blue:Math.round(l*255),alpha:r}}function nfe(s,t){return n=>n>0?t:s}const Od=(s,t,n)=>s+(t-s)*n,Jwe=(s,t,n)=>{const r=s*s,a=n*(t*t-r)+r;return a<0?0:Math.sqrt(a)},xKt=[j4e,$E,wP],gKt=s=>xKt.find(t=>t.test(s));function TBe(s){const t=gKt(s);if(dye(!!t,`'${s}' is not an animatable color. Use the equivalent color code instead.`,"color-not-animatable"),!t)return!1;let n=t.parse(s);return t===wP&&(n=fKt(n)),n}const EBe=(s,t)=>{const n=TBe(s),r=TBe(t);if(!n||!r)return nfe(s,t);const a={...n};return i=>(a.red=Jwe(n.red,r.red,i),a.green=Jwe(n.green,r.green,i),a.blue=Jwe(n.blue,r.blue,i),a.alpha=Od(n.alpha,r.alpha,i),$E.transform(a))},N4e=new Set(["none","hidden"]);function yKt(s,t){return N4e.has(s)?n=>n<=0?s:t:n=>n>=1?t:s}function vKt(s,t){return n=>Od(s,t,n)}function pMe(s){return typeof s=="number"?vKt:typeof s=="string"?uMe(s)?nfe:Wh.test(s)?EBe:wKt:Array.isArray(s)?zdt:typeof s=="object"?Wh.test(s)?EBe:bKt:nfe}function zdt(s,t){const n=[...s],r=n.length,a=s.map((i,l)=>pMe(i)(i,t[l]));return i=>{for(let l=0;l{for(const i in r)n[i]=r[i](a);return n}}function _Kt(s,t){const n=[],r={color:0,var:0,number:0};for(let a=0;a{const n=vb.createTransformer(t),r=b8(s),a=b8(t);return r.indexes.var.length===a.indexes.var.length&&r.indexes.color.length===a.indexes.color.length&&r.indexes.number.length>=a.indexes.number.length?N4e.has(s)&&!a.values.length||N4e.has(t)&&!r.values.length?yKt(s,t):X$(zdt(_Kt(r,a),a.values),n):(dye(!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"),nfe(s,t))};function Bdt(s,t,n){return typeof s=="number"&&typeof t=="number"&&typeof n=="number"?Od(s,t,n):pMe(s)(s,t)}const jKt=s=>{const t=({timestamp:n})=>s(n);return{start:(n=!0)=>sd.update(t,n),stop:()=>S4(t),now:()=>Jp.isProcessing?Jp.timestamp:Hx.now()}},$dt=(s,t,n=10)=>{let r="";const a=Math.max(Math.round(t/n),2);for(let i=0;i=rfe?1/0:t}function NKt(s,t=100,n){const r=n({...s,keyframes:[0,t]}),a=Math.min(fMe(r),rfe);return{type:"keyframes",ease:i=>r.next(a*i).value/t,duration:Ev(a)}}const ju={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 k4e(s,t){return s*Math.sqrt(1-t*t)}const kKt=12;function SKt(s,t,n){let r=n;for(let a=1;a{const u=d*l,h=u*s,p=u-n,f=k4e(d,l),y=Math.exp(-h);return eje-p/f*y},i=d=>{const h=d*l*s,p=h*n+n,f=Math.pow(l,2)*Math.pow(d,2)*s,y=Math.exp(-h),_=k4e(Math.pow(d,2),l);return(-a(d)+eje>0?-1:1)*((p-f)*y)/_}):(a=d=>{const u=Math.exp(-d*s),h=(d-n)*s+1;return-eje+u*h},i=d=>{const u=Math.exp(-d*s),h=(n-d)*(s*s);return u*h});const o=5/s,c=SKt(a,i,o);if(s=Vg(s),isNaN(c))return{stiffness:ju.stiffness,damping:ju.damping,duration:s};{const d=Math.pow(c,2)*r;return{stiffness:d,damping:l*2*Math.sqrt(r*d),duration:s}}}const TKt=["duration","bounce"],EKt=["stiffness","damping","mass"];function ABe(s,t){return t.some(n=>s[n]!==void 0)}function AKt(s){let t={velocity:ju.velocity,stiffness:ju.stiffness,damping:ju.damping,mass:ju.mass,isResolvedFromDuration:!1,...s};if(!ABe(s,EKt)&&ABe(s,TKt))if(t.velocity=0,s.visualDuration){const n=s.visualDuration,r=2*Math.PI/(n*1.2),a=r*r,i=2*Ew(.05,1,1-(s.bounce||0))*Math.sqrt(a);t={...t,mass:ju.mass,stiffness:a,damping:i}}else{const n=CKt({...s,velocity:0});t={...t,...n,mass:ju.mass},t.isResolvedFromDuration=!0}return t}function afe(s=ju.visualDuration,t=ju.bounce){const n=typeof s!="object"?{visualDuration:s,keyframes:[0,1],bounce:t}:s;let{restSpeed:r,restDelta:a}=n;const i=n.keyframes[0],l=n.keyframes[n.keyframes.length-1],o={done:!1,value:i},{stiffness:c,damping:d,mass:u,duration:h,velocity:p,isResolvedFromDuration:f}=AKt({...n,velocity:-Ev(n.velocity||0)}),y=p||0,_=d/(2*Math.sqrt(c*u)),v=l-i,j=Ev(Math.sqrt(c/u)),w=Math.abs(v)<5;r||(r=w?ju.restSpeed.granular:ju.restSpeed.default),a||(a=w?ju.restDelta.granular:ju.restDelta.default);let S,A,E,O,D,I;if(_<1)E=k4e(j,_),O=(y+_*j*v)/E,S=z=>{const H=Math.exp(-_*j*z);return l-H*(O*Math.sin(E*z)+v*Math.cos(E*z))},D=_*j*O+v*E,I=_*j*v-O*E,A=z=>Math.exp(-_*j*z)*(D*Math.sin(E*z)+I*Math.cos(E*z));else if(_===1){S=H=>l-Math.exp(-j*H)*(v+(y+j*v)*H);const z=y+j*v;A=H=>Math.exp(-j*H)*(j*z*H-y)}else{const z=j*Math.sqrt(_*_-1);S=W=>{const ee=Math.exp(-_*j*W),se=Math.min(z*W,300);return l-ee*((y+_*j*v)*Math.sinh(se)+z*v*Math.cosh(se))/z};const H=(y+_*j*v)/z,Z=_*j*H-v*z,Y=_*j*v-H*z;A=W=>{const ee=Math.exp(-_*j*W),se=Math.min(z*W,300);return ee*(Z*Math.sinh(se)+Y*Math.cosh(se))}}const F={calculatedDuration:f&&h||null,velocity:z=>Vg(A(z)),next:z=>{if(!f&&_<1){const Z=Math.exp(-_*j*z),Y=Math.sin(E*z),W=Math.cos(E*z),ee=l-Z*(O*Y+v*W),se=Vg(Z*(D*Y+I*W));return o.done=Math.abs(se)<=r&&Math.abs(l-ee)<=a,o.value=o.done?l:ee,o}const H=S(z);if(f)o.done=z>=h;else{const Z=Vg(A(z));o.done=Math.abs(Z)<=r&&Math.abs(l-H)<=a}return o.value=o.done?l:H,o},toString:()=>{const z=Math.min(fMe(F),rfe),H=$dt(Z=>F.next(z*Z).value,z,30);return z+"ms "+H},toTransition:()=>{}};return F}afe.applyToOptions=s=>{const t=NKt(s,100,afe);return s.ease=t.ease,s.duration=Vg(t.duration),s.type="keyframes",s};const MKt=5;function Udt(s,t,n){const r=Math.max(t-MKt,0);return _dt(n-s(r),t-r)}function S4e({keyframes:s,velocity:t=0,power:n=.8,timeConstant:r=325,bounceDamping:a=10,bounceStiffness:i=500,modifyTarget:l,min:o,max:c,restDelta:d=.5,restSpeed:u}){const h=s[0],p={done:!1,value:h},f=I=>o!==void 0&&Ic,y=I=>o===void 0?c:c===void 0||Math.abs(o-I)-_*Math.exp(-I/r),S=I=>j+w(I),A=I=>{const F=w(I),z=S(I);p.done=Math.abs(F)<=d,p.value=p.done?j:z};let E,O;const D=I=>{f(p.value)&&(E=I,O=afe({keyframes:[p.value,y(p.value)],velocity:Udt(S,I,p.value),damping:a,stiffness:i,restDelta:d,restSpeed:u}))};return D(0),{calculatedDuration:null,next:I=>{let F=!1;return!O&&E===void 0&&(F=!0,A(I),D(I)),E!==void 0&&I>=E?O.next(I-E):(!F&&A(I),p)}}}function IKt(s,t,n){const r=[],a=n||k4.mix||Bdt,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=IKt(t,r,a),c=o.length,d=u=>{if(l&&u1)for(;hd(Ew(s[0],s[i-1],u)):d}function LKt(s,t){const n=s[s.length-1];for(let r=1;r<=t;r++){const a=nB(0,t,r);s.push(Od(n,1,a))}}function DKt(s){const t=[0];return LKt(t,s.length-1),t}function RKt(s,t){return s.map(n=>n*t)}function OKt(s,t){return s.map(()=>t||Adt).splice(0,s.length-1)}function $9({duration:s=300,keyframes:t,times:n,ease:r="easeInOut"}){const a=GWt(r)?r.map(jBe):jBe(r),i={done:!1,value:t[0]},l=RKt(n&&n.length===t.length?n:DKt(t),s),o=PKt(l,t,{ease:Array.isArray(a)?a:OKt(t,a)});return{calculatedDuration:s,next:c=>(i.value=o(c),i.done=c>=s,i)}}const FKt=s=>s!==null;function uye(s,{repeat:t,repeatType:n="loop"},r,a=1){const i=s.filter(FKt),o=a<0||t&&n!=="loop"&&t%2===1?0:i.length-1;return!o||r===void 0?i[o]:r}const zKt={decay:S4e,inertia:S4e,tween:$9,keyframes:$9,spring:afe};function qdt(s){typeof s.type=="string"&&(s.type=zKt[s.type])}class xMe{constructor(){this.updateFinished()}get finished(){return this._finished}updateFinished(){this._finished=new Promise(t=>{this.resolve=t})}notifyFinished(){this.resolve()}then(t,n){return this.finished.then(t,n)}}const BKt=s=>s/100;class ife extends xMe{constructor(t){super(),this.state="idle",this.startTime=null,this.isStopped=!1,this.currentTime=0,this.holdTime=null,this.playbackSpeed=1,this.delayState={done:!1,value:void 0},this.stop=()=>{var r,a;const{motionValue:n}=this.options;n&&n.updatedAt!==Hx.now()&&this.tick(Hx.now()),this.isStopped=!0,this.state!=="idle"&&(this.teardown(),(a=(r=this.options).onStop)==null||a.call(r))},this.options=t,this.initAnimation(),this.play(),t.autoplay===!1&&this.pause()}initAnimation(){const{options:t}=this;qdt(t);const{type:n=$9,repeat:r=0,repeatDelay:a=0,repeatType:i,velocity:l=0}=t;let{keyframes:o}=t;const c=n||$9;c!==$9&&typeof o[0]!="number"&&(this.mixKeyframes=X$(BKt,Bdt(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=fMe(d));const{calculatedDuration:u}=d;this.calculatedDuration=u,this.resolvedDuration=u+a,this.totalDuration=this.resolvedDuration*(r+1)-a,this.generator=d}updateTime(t){const n=Math.round(t-this.startTime)*this.playbackSpeed;this.holdTime!==null?this.currentTime=this.holdTime:this.currentTime=n}tick(t,n=!1){const{generator:r,totalDuration:a,mixKeyframes:i,mirroredGenerator:l,resolvedDuration:o,calculatedDuration:c}=this;if(this.startTime===null)return r.next(0);const{delay:d=0,keyframes:u,repeat:h,repeatType:p,repeatDelay:f,type:y,onUpdate:_,finalKeyframe:v}=this.options;this.speed>0?this.startTime=Math.min(this.startTime,t):this.speed<0&&(this.startTime=Math.min(t-a/this.speed,this.startTime)),n?this.currentTime=t:this.updateTime(t);const j=this.currentTime-d*(this.playbackSpeed>=0?1:-1),w=this.playbackSpeed>=0?j<0:j>a;this.currentTime=Math.max(j,0),this.state==="finished"&&this.holdTime===null&&(this.currentTime=a);let S=this.currentTime,A=r;if(h){const I=Math.min(this.currentTime,a)/o;let F=Math.floor(I),z=I%1;!z&&I>=1&&(z=1),z===1&&F--,F=Math.min(F,h+1),!!(F%2)&&(p==="reverse"?(z=1-z,f&&(z-=f/o)):p==="mirror"&&(A=l)),S=Ew(0,1,z)*o}let E;w?(this.delayState.value=u[0],E=this.delayState):E=A.next(S),i&&!w&&(E.value=i(E.value));let{done:O}=E;!w&&c!==null&&(O=this.playbackSpeed>=0?this.currentTime>=a:this.currentTime<=0);const D=this.holdTime===null&&(this.state==="finished"||this.state==="running"&&O);return D&&y!==S4e&&(E.value=uye(u,this.options,v,this.speed)),_&&_(E.value),D&&this.finish(),E}then(t,n){return this.finished.then(t,n)}get duration(){return Ev(this.calculatedDuration)}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Ev(t)}get time(){return Ev(this.currentTime)}set time(t){t=Vg(t),this.currentTime=t,this.startTime===null||this.holdTime!==null||this.playbackSpeed===0?this.holdTime=t:this.driver&&(this.startTime=this.driver.now()-t/this.playbackSpeed),this.driver?this.driver.start(!1):(this.startTime=0,this.state="paused",this.holdTime=t,this.tick(t))}getGeneratorVelocity(){const t=this.currentTime;if(t<=0)return this.options.velocity||0;if(this.generator.velocity)return this.generator.velocity(t);const n=this.generator.next(t).value;return Udt(r=>this.generator.next(r).value,t,n)}get speed(){return this.playbackSpeed}set speed(t){const n=this.playbackSpeed!==t;n&&this.driver&&this.updateTime(Hx.now()),this.playbackSpeed=t,n&&this.driver&&(this.time=Ev(this.currentTime))}play(){var a,i;if(this.isStopped)return;const{driver:t=jKt,startTime:n}=this.options;this.driver||(this.driver=t(l=>this.tick(l))),(i=(a=this.options).onPlay)==null||i.call(a);const r=this.driver.now();this.state==="finished"?(this.updateFinished(),this.startTime=r):this.holdTime!==null?this.startTime=r-this.holdTime:this.startTime||(this.startTime=n??r),this.state==="finished"&&this.speed<0&&(this.startTime+=this.calculatedDuration),this.holdTime=null,this.state="running",this.driver.start()}pause(){this.state="paused",this.updateTime(Hx.now()),this.holdTime=this.currentTime}complete(){this.state!=="running"&&this.play(),this.state="finished",this.holdTime=null}finish(){var t,n;this.notifyFinished(),this.teardown(),this.state="finished",(n=(t=this.options).onComplete)==null||n.call(t)}cancel(){var t,n;this.holdTime=null,this.startTime=0,this.tick(0),this.teardown(),(n=(t=this.options).onCancel)==null||n.call(t)}teardown(){this.state="idle",this.stopDriver(),this.startTime=this.holdTime=null}stopDriver(){this.driver&&(this.driver.stop(),this.driver=void 0)}sample(t){return this.startTime=0,this.tick(t,!0)}attachTimeline(t){var n;return this.options.allowFlatten&&(this.options.type="keyframes",this.options.ease="linear",this.initAnimation()),(n=this.driver)==null||n.stop(),t.observe(this)}}function $Kt(s){for(let t=1;ts*180/Math.PI,C4e=s=>{const t=UE(Math.atan2(s[1],s[0]));return T4e(t)},UKt={x:4,y:5,translateX:4,translateY:5,scaleX:0,scaleY:3,scale:s=>(Math.abs(s[0])+Math.abs(s[3]))/2,rotate:C4e,rotateZ:C4e,skewX:s=>UE(Math.atan(s[1])),skewY:s=>UE(Math.atan(s[2])),skew:s=>(Math.abs(s[1])+Math.abs(s[2]))/2},T4e=s=>(s=s%360,s<0&&(s+=360),s),MBe=C4e,IBe=s=>Math.sqrt(s[0]*s[0]+s[1]*s[1]),PBe=s=>Math.sqrt(s[4]*s[4]+s[5]*s[5]),qKt={x:12,y:13,z:14,translateX:12,translateY:13,translateZ:14,scaleX:IBe,scaleY:PBe,scale:s=>(IBe(s)+PBe(s))/2,rotateX:s=>T4e(UE(Math.atan2(s[6],s[5]))),rotateY:s=>T4e(UE(Math.atan2(-s[2],s[0]))),rotateZ:MBe,rotate:MBe,skewX:s=>UE(Math.atan(s[4])),skewY:s=>UE(Math.atan(s[1])),skew:s=>(Math.abs(s[1])+Math.abs(s[4]))/2};function E4e(s){return s.includes("scale")?1:0}function A4e(s,t){if(!s||s==="none")return E4e(t);const n=s.match(/^matrix3d\(([-\d.e\s,]+)\)$/u);let r,a;if(n)r=qKt,a=n;else{const o=s.match(/^matrix\(([-\d.e\s,]+)\)$/u);r=UKt,a=o}if(!a)return E4e(t);const i=r[t],l=a[1].split(",").map(HKt);return typeof i=="function"?i(l):l[i]}const VKt=(s,t)=>{const{transform:n="none"}=getComputedStyle(s);return A4e(n,t)};function HKt(s){return parseFloat(s.trim())}const zD=["transformPerspective","x","y","z","translateX","translateY","translateZ","scale","scaleX","scaleY","rotate","rotateX","rotateY","rotateZ","skew","skewX","skewY"],BD=new Set(zD),LBe=s=>s===FD||s===oi,GKt=new Set(["x","y","z"]),WKt=zD.filter(s=>!GKt.has(s));function KKt(s){const t=[];return WKt.forEach(n=>{const r=s.getValue(n);r!==void 0&&(t.push([n,r.get()]),r.set(n.startsWith("scale")?1:0))}),t}const NS={width:({x:s},{paddingLeft:t="0",paddingRight:n="0",boxSizing:r})=>{const a=s.max-s.min;return r==="border-box"?a:a-parseFloat(t)-parseFloat(n)},height:({y:s},{paddingTop:t="0",paddingBottom:n="0",boxSizing:r})=>{const a=s.max-s.min;return r==="border-box"?a:a-parseFloat(t)-parseFloat(n)},top:(s,{top:t})=>parseFloat(t),left:(s,{left:t})=>parseFloat(t),bottom:({y:s},{top:t})=>parseFloat(t)+(s.max-s.min),right:({x:s},{left:t})=>parseFloat(t)+(s.max-s.min),x:(s,{transform:t})=>A4e(t,"x"),y:(s,{transform:t})=>A4e(t,"y")};NS.translateX=NS.x;NS.translateY=NS.y;const FA=new Set;let M4e=!1,I4e=!1,P4e=!1;function Vdt(){if(I4e){const s=Array.from(FA).filter(r=>r.needsMeasurement),t=new Set(s.map(r=>r.element)),n=new Map;t.forEach(r=>{const a=KKt(r);a.length&&(n.set(r,a),r.render())}),s.forEach(r=>r.measureInitialState()),t.forEach(r=>{r.render();const a=n.get(r);a&&a.forEach(([i,l])=>{var o;(o=r.getValue(i))==null||o.set(l)})}),s.forEach(r=>r.measureEndState()),s.forEach(r=>{r.suspendedScrollY!==void 0&&window.scrollTo(0,r.suspendedScrollY)})}I4e=!1,M4e=!1,FA.forEach(s=>s.complete(P4e)),FA.clear()}function Hdt(){FA.forEach(s=>{s.readKeyframes(),s.needsMeasurement&&(I4e=!0)})}function YKt(){P4e=!0,Hdt(),Vdt(),P4e=!1}class gMe{constructor(t,n,r,a,i,l=!1){this.state="pending",this.isAsync=!1,this.needsMeasurement=!1,this.unresolvedKeyframes=[...t],this.onComplete=n,this.name=r,this.motionValue=a,this.element=i,this.isAsync=l}scheduleResolve(){this.state="scheduled",this.isAsync?(FA.add(this),M4e||(M4e=!0,sd.read(Hdt),sd.resolveKeyframes(Vdt))):(this.readKeyframes(),this.complete())}readKeyframes(){const{unresolvedKeyframes:t,name:n,element:r,motionValue:a}=this;if(t[0]===null){const i=a==null?void 0:a.get(),l=t[t.length-1];if(i!==void 0)t[0]=i;else if(r&&n){const o=r.readValue(n,l);o!=null&&(t[0]=o)}t[0]===void 0&&(t[0]=l),a&&i===void 0&&a.set(t[0])}$Kt(t)}setFinalKeyframe(){}measureInitialState(){}renderEndStyles(){}measureEndState(){}complete(t=!1){this.state="complete",this.onComplete(this.unresolvedKeyframes,this.finalKeyframe,t),FA.delete(this)}cancel(){this.state==="scheduled"&&(FA.delete(this),this.state="pending")}resume(){this.state==="pending"&&this.scheduleResolve()}}const ZKt=s=>s.startsWith("--");function Gdt(s,t,n){ZKt(t)?s.style.setProperty(t,n):s.style[t]=n}const QKt={};function Wdt(s,t){const n=bdt(s);return()=>QKt[t]??n()}const XKt=Wdt(()=>window.ScrollTimeline!==void 0,"scrollTimeline"),Kdt=Wdt(()=>{try{document.createElement("div").animate({opacity:0},{easing:"linear(0, 1)"})}catch{return!1}return!0},"linearEasing"),s7=([s,t,n,r])=>`cubic-bezier(${s}, ${t}, ${n}, ${r})`,DBe={linear:"linear",ease:"ease",easeIn:"ease-in",easeOut:"ease-out",easeInOut:"ease-in-out",circIn:s7([0,.65,.55,1]),circOut:s7([.55,0,1,.45]),backIn:s7([.31,.01,.66,-.59]),backOut:s7([.33,1.53,.69,.99])};function Ydt(s,t){if(s)return typeof s=="function"?Kdt()?$dt(s,t):"ease-out":Mdt(s)?s7(s):Array.isArray(s)?s.map(n=>Ydt(n,t)||DBe.easeOut):DBe[s]}function JKt(s,t,n,{delay:r=0,duration:a=300,repeat:i=0,repeatType:l="loop",ease:o="easeOut",times:c}={},d=void 0){const u={[t]:n};c&&(u.offset=c);const h=Ydt(o,a);Array.isArray(h)&&(u.easing=h);const p={delay:r,duration:a,easing:Array.isArray(h)?"linear":h,fill:"both",iterations:i+1,direction:l==="reverse"?"alternate":"normal"};return d&&(p.pseudoElement=d),s.animate(u,p)}function Zdt(s){return typeof s=="function"&&"applyToOptions"in s}function eYt({type:s,...t}){return Zdt(s)&&Kdt()?s.applyToOptions(t):(t.duration??(t.duration=300),t.ease??(t.ease="easeOut"),t)}class Qdt extends xMe{constructor(t){if(super(),this.finishedTime=null,this.isStopped=!1,this.manualStartTime=null,!t)return;const{element:n,name:r,keyframes:a,pseudoElement:i,allowFlatten:l=!1,finalKeyframe:o,onComplete:c}=t;this.isPseudoElement=!!i,this.allowFlatten=l,this.options=t,v8(typeof t.type!="string",`Mini animate() doesn't support "type" as a string.`,"mini-spring");const d=eYt(t);this.animation=JKt(n,r,a,d,i),d.autoplay===!1&&this.animation.pause(),this.animation.onfinish=()=>{if(this.finishedTime=this.time,!i){const u=uye(a,this.options,o,this.speed);this.updateMotionValue&&this.updateMotionValue(u),Gdt(n,r,u),this.animation.cancel()}c==null||c(),this.notifyFinished()}}play(){this.isStopped||(this.manualStartTime=null,this.animation.play(),this.state==="finished"&&this.updateFinished())}pause(){this.animation.pause()}complete(){var t,n;(n=(t=this.animation).finish)==null||n.call(t)}cancel(){try{this.animation.cancel()}catch{}}stop(){if(this.isStopped)return;this.isStopped=!0;const{state:t}=this;t==="idle"||t==="finished"||(this.updateMotionValue?this.updateMotionValue():this.commitStyles(),this.isPseudoElement||this.cancel())}commitStyles(){var n,r,a;const t=(n=this.options)==null?void 0:n.element;!this.isPseudoElement&&(t!=null&&t.isConnected)&&((a=(r=this.animation).commitStyles)==null||a.call(r))}get duration(){var n,r;const t=((r=(n=this.animation.effect)==null?void 0:n.getComputedTiming)==null?void 0:r.call(n).duration)||0;return Ev(Number(t))}get iterationDuration(){const{delay:t=0}=this.options||{};return this.duration+Ev(t)}get time(){return Ev(Number(this.animation.currentTime)||0)}set time(t){const n=this.finishedTime!==null;this.manualStartTime=null,this.finishedTime=null,this.animation.currentTime=Vg(t),n&&this.animation.pause()}get speed(){return this.animation.playbackRate}set speed(t){t<0&&(this.finishedTime=null),this.animation.playbackRate=t}get state(){return this.finishedTime!==null?"finished":this.animation.playState}get startTime(){return this.manualStartTime??Number(this.animation.startTime)}set startTime(t){this.manualStartTime=this.animation.startTime=t}attachTimeline({timeline:t,rangeStart:n,rangeEnd:r,observe:a}){var i;return this.allowFlatten&&((i=this.animation.effect)==null||i.updateTiming({easing:"linear"})),this.animation.onfinish=null,t&&XKt()?(this.animation.timeline=t,n&&(this.animation.rangeStart=n),r&&(this.animation.rangeEnd=r),Fv):a(this)}}const Xdt={anticipate:Cdt,backInOut:Sdt,circInOut:Edt};function tYt(s){return s in Xdt}function sYt(s){typeof s.ease=="string"&&tYt(s.ease)&&(s.ease=Xdt[s.ease])}const tje=10;class nYt extends Qdt{constructor(t){sYt(t),qdt(t),super(t),t.startTime!==void 0&&t.autoplay!==!1&&(this.startTime=t.startTime),this.options=t}updateMotionValue(t){const{motionValue:n,onUpdate:r,onComplete:a,element:i,...l}=this.options;if(!n)return;if(t!==void 0){n.set(t);return}const o=new ife({...l,autoplay:!1}),c=Math.max(tje,Hx.now()-this.startTime),d=Ew(0,tje,c-tje),u=o.sample(c).value,{name:h}=this.options;i&&h&&Gdt(i,h,u),n.setWithVelocity(o.sample(Math.max(0,c-d)).value,u,d),o.stop()}}const RBe=(s,t)=>t==="zIndex"?!1:!!(typeof s=="number"||Array.isArray(s)||typeof s=="string"&&(vb.test(s)||s==="0")&&!s.startsWith("url("));function rYt(s){const t=s[0];if(s.length===1)return!0;for(let n=0;nObject.hasOwnProperty.call(Element.prototype,"animate"));function dYt(s){var h;const{motionValue:t,name:n,repeatDelay:r,repeatType:a,damping:i,type:l,keyframes:o}=s;if(!(((h=t==null?void 0:t.owner)==null?void 0:h.current)instanceof HTMLElement))return!1;const{onUpdate:d,transformTemplate:u}=t.owner.getProps();return cYt()&&n&&(Jdt.has(n)||lYt.has(n)&&oYt(o))&&(n!=="transform"||!u)&&!d&&!r&&a!=="mirror"&&i!==0&&l!=="inertia"}const uYt=40;class hYt extends xMe{constructor({autoplay:t=!0,delay:n=0,type:r="keyframes",repeat:a=0,repeatDelay:i=0,repeatType:l="loop",keyframes:o,name:c,motionValue:d,element:u,...h}){var y;super(),this.stop=()=>{var _,v;this._animation&&(this._animation.stop(),(_=this.stopTimeline)==null||_.call(this)),(v=this.keyframeResolver)==null||v.cancel()},this.createdAt=Hx.now();const p={autoplay:t,delay:n,type:r,repeat:a,repeatDelay:i,repeatType:l,name:c,motionValue:d,element:u,...h},f=(u==null?void 0:u.KeyframeResolver)||gMe;this.keyframeResolver=new f(o,(_,v,j)=>this.onKeyframesResolved(_,v,p,!j),c,d,u),(y=this.keyframeResolver)==null||y.scheduleResolve()}onKeyframesResolved(t,n,r,a){var j,w;this.keyframeResolver=void 0;const{name:i,type:l,velocity:o,delay:c,isHandoff:d,onUpdate:u}=r;this.resolvedAt=Hx.now();let h=!0;aYt(t,i,l,o)||(h=!1,(k4.instantAnimations||!c)&&(u==null||u(uye(t,r,n))),t[0]=t[t.length-1],L4e(r),r.repeat=0);const f={startTime:a?this.resolvedAt?this.resolvedAt-this.createdAt>uYt?this.resolvedAt:this.createdAt:this.createdAt:void 0,finalKeyframe:n,...r,keyframes:t},y=h&&!d&&dYt(f),_=(w=(j=f.motionValue)==null?void 0:j.owner)==null?void 0:w.current;let v;if(y)try{v=new nYt({...f,element:_})}catch{v=new ife(f)}else v=new ife(f);v.finished.then(()=>{this.notifyFinished()}).catch(Fv),this.pendingTimeline&&(this.stopTimeline=v.attachTimeline(this.pendingTimeline),this.pendingTimeline=void 0),this._animation=v}get finished(){return this._animation?this.animation.finished:this._finished}then(t,n){return this.finished.finally(t).then(()=>{})}get animation(){var t;return this._animation||((t=this.keyframeResolver)==null||t.resume(),YKt()),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 eut(s,t,n,r=0,a=1){const i=Array.from(s).sort((d,u)=>d.sortNodePosition(u)).indexOf(t),l=s.size,o=(l-1)*r;return typeof n=="function"?n(i,l):a===1?i*r:o-i*r}const mYt=/^var\(--(?:([\w-]+)|([\w-]+), ?([a-zA-Z\d ()%#.,-]+))\)/u;function pYt(s){const t=mYt.exec(s);if(!t)return[,];const[,n,r,a]=t;return[`--${n??r}`,a]}const fYt=4;function tut(s,t,n=1){v8(n<=fYt,`Max CSS variable fallback depth detected in property "${s}". This may indicate a circular fallback dependency.`,"max-css-var-depth");const[r,a]=pYt(s);if(!r)return;const i=window.getComputedStyle(t).getPropertyValue(r);if(i){const l=i.trim();return gdt(l)?parseFloat(l):l}return uMe(a)?tut(a,t,n+1):a}const xYt={type:"spring",stiffness:500,damping:25,restSpeed:10},gYt=s=>({type:"spring",stiffness:550,damping:s===0?2*Math.sqrt(550):30,restSpeed:10}),yYt={type:"keyframes",duration:.8},vYt={type:"keyframes",ease:[.25,.1,.35,1],duration:.3},bYt=(s,{keyframes:t})=>t.length>2?yYt:BD.has(s)?s.startsWith("scale")?gYt(t[1]):xYt:vYt;function sut(s,t){if(s!=null&&s.inherit&&t){const{inherit:n,...r}=s;return{...t,...r}}return s}function yMe(s,t){const n=(s==null?void 0:s[t])??(s==null?void 0:s.default)??s;return n!==s?sut(n,s):n}const _Yt=new Set(["when","delay","delayChildren","staggerChildren","staggerDirection","repeat","repeatType","repeatDelay","from","elapsed"]);function wYt(s){for(const t in s)if(!_Yt.has(t))return!0;return!1}const vMe=(s,t,n,r={},a,i)=>l=>{const o=yMe(r,s)||{},c=o.delay||r.delay||0;let{elapsed:d=0}=r;d=d-Vg(c);const u={keyframes:Array.isArray(n)?n:[null,n],ease:"easeOut",velocity:t.getVelocity(),...o,delay:-d,onUpdate:p=>{t.set(p),o.onUpdate&&o.onUpdate(p)},onComplete:()=>{l(),o.onComplete&&o.onComplete()},name:s,motionValue:t,element:i?void 0:a};wYt(o)||Object.assign(u,bYt(s,u)),u.duration&&(u.duration=Vg(u.duration)),u.repeatDelay&&(u.repeatDelay=Vg(u.repeatDelay)),u.from!==void 0&&(u.keyframes[0]=u.from);let h=!1;if((u.type===!1||u.duration===0&&!u.repeatDelay)&&(L4e(u),u.delay===0&&(h=!0)),(k4.instantAnimations||k4.skipAnimations||a!=null&&a.shouldSkipAnimations)&&(h=!0,L4e(u),u.delay=0),u.allowFlatten=!o.type&&!o.ease,h&&!i&&t.get()!==void 0){const p=uye(u.keyframes,o);if(p!==void 0){sd.update(()=>{u.onUpdate(p),u.onComplete()});return}}return o.isSync?new ife(u):new hYt(u)};function OBe(s){const t=[{},{}];return s==null||s.values.forEach((n,r)=>{t[0][r]=n.get(),t[1][r]=n.getVelocity()}),t}function bMe(s,t,n,r){if(typeof t=="function"){const[a,i]=OBe(r);t=t(n!==void 0?n:s.custom,a,i)}if(typeof t=="string"&&(t=s.variants&&s.variants[t]),typeof t=="function"){const[a,i]=OBe(r);t=t(n!==void 0?n:s.custom,a,i)}return t}function zA(s,t,n){const r=s.getProps();return bMe(r,t,n!==void 0?n:r.custom,s)}const nut=new Set(["width","height","top","left","right","bottom",...zD]),FBe=30,jYt=s=>!isNaN(parseFloat(s));class NYt{constructor(t,n={}){this.canTrackVelocity=null,this.events={},this.updateAndNotify=r=>{var i;const a=Hx.now();if(this.updatedAt!==a&&this.setPrevFrameValue(),this.prev=this.current,this.setCurrent(r),this.current!==this.prev&&((i=this.events.change)==null||i.notify(this.current),this.dependents))for(const l of this.dependents)l.dirty()},this.hasAnimated=!1,this.setCurrent(t),this.owner=n.owner}setCurrent(t){this.current=t,this.updatedAt=Hx.now(),this.canTrackVelocity===null&&t!==void 0&&(this.canTrackVelocity=jYt(this.current))}setPrevFrameValue(t=this.current){this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt}onChange(t){return this.on("change",t)}on(t,n){this.events[t]||(this.events[t]=new lMe);const r=this.events[t].add(n);return t==="change"?()=>{r(),sd.read(()=>{this.events.change.getSize()||this.stop()})}:r}clearListeners(){for(const t in this.events)this.events[t].clear()}attach(t,n){this.passiveEffect=t,this.stopPassiveEffect=n}set(t){this.passiveEffect?this.passiveEffect(t,this.updateAndNotify):this.updateAndNotify(t)}setWithVelocity(t,n,r){this.set(n),this.prev=void 0,this.prevFrameValue=t,this.prevUpdatedAt=this.updatedAt-r}jump(t,n=!0){this.updateAndNotify(t),this.prev=t,this.prevUpdatedAt=this.prevFrameValue=void 0,n&&this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}dirty(){var t;(t=this.events.change)==null||t.notify(this.current)}addDependent(t){this.dependents||(this.dependents=new Set),this.dependents.add(t)}removeDependent(t){this.dependents&&this.dependents.delete(t)}get(){return this.current}getPrevious(){return this.prev}getVelocity(){const t=Hx.now();if(!this.canTrackVelocity||this.prevFrameValue===void 0||t-this.updatedAt>FBe)return 0;const n=Math.min(this.updatedAt-this.prevUpdatedAt,FBe);return _dt(parseFloat(this.current)-parseFloat(this.prevFrameValue),n)}start(t){return this.stop(),new Promise(n=>{this.hasAnimated=!0,this.animation=t(n),this.events.animationStart&&this.events.animationStart.notify()}).then(()=>{this.events.animationComplete&&this.events.animationComplete.notify(),this.clearAnimation()})}stop(){this.animation&&(this.animation.stop(),this.events.animationCancel&&this.events.animationCancel.notify()),this.clearAnimation()}isAnimating(){return!!this.animation}clearAnimation(){delete this.animation}destroy(){var t,n;(t=this.dependents)==null||t.clear(),(n=this.events.destroy)==null||n.notify(),this.clearListeners(),this.stop(),this.stopPassiveEffect&&this.stopPassiveEffect()}}function _8(s,t){return new NYt(s,t)}const D4e=s=>Array.isArray(s);function kYt(s,t,n){s.hasValue(t)?s.getValue(t).set(n):s.addValue(t,_8(n))}function SYt(s){return D4e(s)?s[s.length-1]||0:s}function CYt(s,t){const n=zA(s,t);let{transitionEnd:r={},transition:a={},...i}=n||{};i={...i,...r};for(const l in i){const o=SYt(i[l]);kYt(s,l,o)}}const lf=s=>!!(s&&s.getVelocity);function TYt(s){return!!(lf(s)&&s.add)}function R4e(s,t){const n=s.getValue("willChange");if(TYt(n))return n.add(t);if(!n&&k4.WillChange){const r=new k4.WillChange("auto");s.addValue("willChange",r),r.add(t)}}function _Me(s){return s.replace(/([A-Z])/g,t=>`-${t.toLowerCase()}`)}const EYt="framerAppearId",rut="data-"+_Me(EYt);function aut(s){return s.props[rut]}function AYt({protectedKeys:s,needsAnimating:t},n){const r=s.hasOwnProperty(n)&&t[n]!==!0;return t[n]=!1,r}function iut(s,t,{delay:n=0,transitionOverride:r,type:a}={}){let{transition:i,transitionEnd:l,...o}=t;const c=s.getDefaultTransition();i=i?sut(i,c):c;const d=i==null?void 0:i.reduceMotion;r&&(i=r);const u=[],h=a&&s.animationState&&s.animationState.getState()[a];for(const p in o){const f=s.getValue(p,s.latestValues[p]??null),y=o[p];if(y===void 0||h&&AYt(h,p))continue;const _={delay:n,...yMe(i||{},p)},v=f.get();if(v!==void 0&&!f.isAnimating()&&!Array.isArray(y)&&y===v&&!_.velocity){sd.update(()=>f.set(y));continue}let j=!1;if(window.MotionHandoffAnimation){const A=aut(s);if(A){const E=window.MotionHandoffAnimation(A,p,sd);E!==null&&(_.startTime=E,j=!0)}}R4e(s,p);const w=d??s.shouldReduceMotion;f.start(vMe(p,f,y,w&&nut.has(p)?{type:!1}:_,s,j));const S=f.animation;S&&u.push(S)}if(l){const p=()=>sd.update(()=>{l&&CYt(s,l)});u.length?Promise.all(u).then(p):p()}return u}function O4e(s,t,n={}){var c;const r=zA(s,t,n.type==="exit"?(c=s.presenceContext)==null?void 0:c.custom:void 0);let{transition:a=s.getDefaultTransition()||{}}=r||{};n.transitionOverride&&(a=n.transitionOverride);const i=r?()=>Promise.all(iut(s,r,n)):()=>Promise.resolve(),l=s.variantChildren&&s.variantChildren.size?(d=0)=>{const{delayChildren:u=0,staggerChildren:h,staggerDirection:p}=a;return MYt(s,t,d,u,h,p,n)}:()=>Promise.resolve(),{when:o}=a;if(o){const[d,u]=o==="beforeChildren"?[i,l]:[l,i];return d().then(()=>u())}else return Promise.all([i(),l(n.delay)])}function MYt(s,t,n=0,r=0,a=0,i=1,l){const o=[];for(const c of s.variantChildren)c.notify("AnimationStart",t),o.push(O4e(c,t,{...l,delay:n+(typeof r=="function"?0:r)+eut(s.variantChildren,c,r,a,i)}).then(()=>c.notify("AnimationComplete",t)));return Promise.all(o)}function IYt(s,t,n={}){s.notify("AnimationStart",t);let r;if(Array.isArray(t)){const a=t.map(i=>O4e(s,i,n));r=Promise.all(a)}else if(typeof t=="string")r=O4e(s,t,n);else{const a=typeof t=="function"?zA(s,t,n.custom):t;r=Promise.all(iut(s,a,n))}return r.then(()=>{s.notify("AnimationComplete",t)})}const PYt={test:s=>s==="auto",parse:s=>s},out=s=>t=>t.test(s),lut=[FD,oi,bw,Dk,rKt,nKt,PYt],zBe=s=>lut.find(out(s));function LYt(s){return typeof s=="number"?s===0:s!==null?s==="none"||s==="0"||vdt(s):!0}const DYt=new Set(["brightness","contrast","saturate","opacity"]);function RYt(s){const[t,n]=s.slice(0,-1).split("(");if(t==="drop-shadow")return s;const[r]=n.match(hMe)||[];if(!r)return s;const a=n.replace(r,"");let i=DYt.has(t)?1:0;return r!==n&&(i*=100),t+"("+i+a+")"}const OYt=/\b([a-z-]*)\(.*?\)/gu,F4e={...vb,getAnimatableNone:s=>{const t=s.match(OYt);return t?t.map(RYt).join(" "):s}},z4e={...vb,getAnimatableNone:s=>{const t=vb.parse(s);return vb.createTransformer(s)(t.map(r=>typeof r=="number"?0:typeof r=="object"?{...r,alpha:1}:r))}},BBe={...FD,transform:Math.round},FYt={rotate:Dk,rotateX:Dk,rotateY:Dk,rotateZ:Dk,scale:QV,scaleX:QV,scaleY:QV,scaleZ:QV,skew:Dk,skewX:Dk,skewY:Dk,distance:oi,translateX:oi,translateY:oi,translateZ:oi,x:oi,y:oi,z:oi,perspective:oi,transformPerspective:oi,opacity:rB,originX:SBe,originY:SBe,originZ:oi},wMe={borderWidth:oi,borderTopWidth:oi,borderRightWidth:oi,borderBottomWidth:oi,borderLeftWidth:oi,borderRadius:oi,borderTopLeftRadius:oi,borderTopRightRadius:oi,borderBottomRightRadius:oi,borderBottomLeftRadius:oi,width:oi,maxWidth:oi,height:oi,maxHeight:oi,top:oi,right:oi,bottom:oi,left:oi,inset:oi,insetBlock:oi,insetBlockStart:oi,insetBlockEnd:oi,insetInline:oi,insetInlineStart:oi,insetInlineEnd:oi,padding:oi,paddingTop:oi,paddingRight:oi,paddingBottom:oi,paddingLeft:oi,paddingBlock:oi,paddingBlockStart:oi,paddingBlockEnd:oi,paddingInline:oi,paddingInlineStart:oi,paddingInlineEnd:oi,margin:oi,marginTop:oi,marginRight:oi,marginBottom:oi,marginLeft:oi,marginBlock:oi,marginBlockStart:oi,marginBlockEnd:oi,marginInline:oi,marginInlineStart:oi,marginInlineEnd:oi,fontSize:oi,backgroundPositionX:oi,backgroundPositionY:oi,...FYt,zIndex:BBe,fillOpacity:rB,strokeOpacity:rB,numOctaves:BBe},zYt={...wMe,color:Wh,backgroundColor:Wh,outlineColor:Wh,fill:Wh,stroke:Wh,borderColor:Wh,borderTopColor:Wh,borderRightColor:Wh,borderBottomColor:Wh,borderLeftColor:Wh,filter:F4e,WebkitFilter:F4e,mask:z4e,WebkitMask:z4e},cut=s=>zYt[s],BYt=new Set([F4e,z4e]);function dut(s,t){let n=cut(s);return BYt.has(n)||(n=vb),n.getAnimatableNone?n.getAnimatableNone(t):void 0}const $Yt=new Set(["auto","none","0"]);function UYt(s,t,n){let r=0,a;for(;r{t.getValue(c).set(d)}),this.resolveNoneKeyframes()}}function jMe(s,t,n){if(s==null)return[];if(s instanceof EventTarget)return[s];if(typeof s=="string"){const a=document.querySelectorAll(s);return a?Array.from(a):[]}return Array.from(s).filter(r=>r!=null)}const uut=(s,t)=>t&&typeof s=="number"?t.transform(s):s;function _me(s){return ydt(s)&&"offsetHeight"in s&&!("ownerSVGElement"in s)}const{schedule:NMe,cancel:ofn}=Idt(queueMicrotask,!1),B1={x:!1,y:!1};function hut(){return B1.x||B1.y}function VYt(s){return s==="x"||s==="y"?B1[s]?null:(B1[s]=!0,()=>{B1[s]=!1}):B1.x||B1.y?null:(B1.x=B1.y=!0,()=>{B1.x=B1.y=!1})}function mut(s,t){const n=jMe(s),r=new AbortController,a={passive:!0,...t,signal:r.signal};return[n,a,()=>r.abort()]}function HYt(s){return!(s.pointerType==="touch"||hut())}function GYt(s,t,n={}){const[r,a,i]=mut(s,n);return r.forEach(l=>{let o=!1,c=!1,d;const u=()=>{l.removeEventListener("pointerleave",y)},h=v=>{d&&(d(v),d=void 0),u()},p=v=>{o=!1,window.removeEventListener("pointerup",p),window.removeEventListener("pointercancel",p),c&&(c=!1,h(v))},f=()=>{o=!0,window.addEventListener("pointerup",p,a),window.addEventListener("pointercancel",p,a)},y=v=>{if(v.pointerType!=="touch"){if(o){c=!0;return}h(v)}},_=v=>{if(!HYt(v))return;c=!1;const j=t(l,v);typeof j=="function"&&(d=j,l.addEventListener("pointerleave",y,a))};l.addEventListener("pointerenter",_,a),l.addEventListener("pointerdown",f,a)}),i}const put=(s,t)=>t?s===t?!0:put(s,t.parentElement):!1,kMe=s=>s.pointerType==="mouse"?typeof s.button!="number"||s.button<=0:s.isPrimary!==!1,WYt=new Set(["BUTTON","INPUT","SELECT","TEXTAREA","A"]);function KYt(s){return WYt.has(s.tagName)||s.isContentEditable===!0}const YYt=new Set(["INPUT","SELECT","TEXTAREA"]);function ZYt(s){return YYt.has(s.tagName)||s.isContentEditable===!0}const wme=new WeakSet;function $Be(s){return t=>{t.key==="Enter"&&s(t)}}function sje(s,t){s.dispatchEvent(new PointerEvent("pointer"+t,{isPrimary:!0,bubbles:!0}))}const QYt=(s,t)=>{const n=s.currentTarget;if(!n)return;const r=$Be(()=>{if(wme.has(n))return;sje(n,"down");const a=$Be(()=>{sje(n,"up")}),i=()=>sje(n,"cancel");n.addEventListener("keyup",a,t),n.addEventListener("blur",i,t)});n.addEventListener("keydown",r,t),n.addEventListener("blur",()=>n.removeEventListener("keydown",r),t)};function UBe(s){return kMe(s)&&!hut()}const qBe=new WeakSet;function XYt(s,t,n={}){const[r,a,i]=mut(s,n),l=o=>{const c=o.currentTarget;if(!UBe(o)||qBe.has(o))return;wme.add(c),n.stopPropagation&&qBe.add(o);const d=t(c,o),u=(f,y)=>{window.removeEventListener("pointerup",h),window.removeEventListener("pointercancel",p),wme.has(c)&&wme.delete(c),UBe(f)&&typeof d=="function"&&d(f,{success:y})},h=f=>{u(f,c===window||c===document||n.useGlobalTarget||put(c,f.target))},p=f=>{u(f,!1)};window.addEventListener("pointerup",h,a),window.addEventListener("pointercancel",p,a)};return r.forEach(o=>{(n.useGlobalTarget?window:o).addEventListener("pointerdown",l,a),_me(o)&&(o.addEventListener("focus",d=>QYt(d,a)),!KYt(o)&&!o.hasAttribute("tabindex")&&(o.tabIndex=0))}),i}function SMe(s){return ydt(s)&&"ownerSVGElement"in s}const jme=new WeakMap;let Rk;const fut=(s,t,n)=>(r,a)=>a&&a[0]?a[0][s+"Size"]:SMe(r)&&"getBBox"in r?r.getBBox()[t]:r[n],JYt=fut("inline","width","offsetWidth"),eZt=fut("block","height","offsetHeight");function tZt({target:s,borderBoxSize:t}){var n;(n=jme.get(s))==null||n.forEach(r=>{r(s,{get width(){return JYt(s,t)},get height(){return eZt(s,t)}})})}function sZt(s){s.forEach(tZt)}function nZt(){typeof ResizeObserver>"u"||(Rk=new ResizeObserver(sZt))}function rZt(s,t){Rk||nZt();const n=jMe(s);return n.forEach(r=>{let a=jme.get(r);a||(a=new Set,jme.set(r,a)),a.add(t),Rk==null||Rk.observe(r)}),()=>{n.forEach(r=>{const a=jme.get(r);a==null||a.delete(t),a!=null&&a.size||Rk==null||Rk.unobserve(r)})}}const Nme=new Set;let jP;function aZt(){jP=()=>{const s={get width(){return window.innerWidth},get height(){return window.innerHeight}};Nme.forEach(t=>t(s))},window.addEventListener("resize",jP)}function iZt(s){return Nme.add(s),jP||aZt(),()=>{Nme.delete(s),!Nme.size&&typeof jP=="function"&&(window.removeEventListener("resize",jP),jP=void 0)}}function VBe(s,t){return typeof s=="function"?iZt(s):rZt(s,t)}function oZt(s){return SMe(s)&&s.tagName==="svg"}const lZt=[...lut,Wh,vb],cZt=s=>lZt.find(out(s)),HBe=()=>({translate:0,scale:1,origin:0,originPoint:0}),NP=()=>({x:HBe(),y:HBe()}),GBe=()=>({min:0,max:0}),Sm=()=>({x:GBe(),y:GBe()}),dZt=new WeakMap;function hye(s){return s!==null&&typeof s=="object"&&typeof s.start=="function"}function aB(s){return typeof s=="string"||Array.isArray(s)}const CMe=["animate","whileInView","whileFocus","whileHover","whileTap","whileDrag","exit"],TMe=["initial",...CMe];function mye(s){return hye(s.animate)||TMe.some(t=>aB(s[t]))}function xut(s){return!!(mye(s)||s.variants)}function uZt(s,t,n){for(const r in t){const a=t[r],i=n[r];if(lf(a))s.addValue(r,a);else if(lf(i))s.addValue(r,_8(a,{owner:s}));else if(i!==a)if(s.hasValue(r)){const l=s.getValue(r);l.liveStyle===!0?l.jump(a):l.hasAnimated||l.set(a)}else{const l=s.getStaticValue(r);s.addValue(r,_8(l!==void 0?l:a,{owner:s}))}}for(const r in n)t[r]===void 0&&s.removeValue(r);return t}const B4e={current:null},gut={current:!1},hZt=typeof window<"u";function mZt(){if(gut.current=!0,!!hZt)if(window.matchMedia){const s=window.matchMedia("(prefers-reduced-motion)"),t=()=>B4e.current=s.matches;s.addEventListener("change",t),t()}else B4e.current=!1}const WBe=["AnimationStart","AnimationComplete","Update","BeforeLayoutMeasure","LayoutMeasure","LayoutAnimationStart","LayoutAnimationComplete"];let ofe={};function yut(s){ofe=s}function pZt(){return ofe}class fZt{scrapeMotionValuesFromProps(t,n,r){return{}}constructor({parent:t,props:n,presenceContext:r,reducedMotionConfig:a,skipAnimations:i,blockInitialAnimation:l,visualState:o},c={}){this.current=null,this.children=new Set,this.isVariantNode=!1,this.isControllingVariants=!1,this.shouldReduceMotion=null,this.shouldSkipAnimations=!1,this.values=new Map,this.KeyframeResolver=gMe,this.features={},this.valueSubscriptions=new Map,this.prevMotionValues={},this.hasBeenMounted=!1,this.events={},this.propEventSubscriptions={},this.notifyUpdate=()=>this.notify("Update",this.latestValues),this.render=()=>{this.current&&(this.triggerBuild(),this.renderInstance(this.current,this.renderState,this.props.style,this.projection))},this.renderScheduledAt=0,this.scheduleRender=()=>{const f=Hx.now();this.renderScheduledAtthis.bindToMotionValue(i,a)),this.reducedMotionConfig==="never"?this.shouldReduceMotion=!1:this.reducedMotionConfig==="always"?this.shouldReduceMotion=!0:(gut.current||mZt(),this.shouldReduceMotion=B4e.current),this.shouldSkipAnimations=this.skipAnimationsConfig??!1,(r=this.parent)==null||r.addChild(this),this.update(this.props,this.presenceContext),this.hasBeenMounted=!0}unmount(){var t;this.projection&&this.projection.unmount(),S4(this.notifyUpdate),S4(this.render),this.valueSubscriptions.forEach(n=>n()),this.valueSubscriptions.clear(),this.removeFromVariantTree&&this.removeFromVariantTree(),(t=this.parent)==null||t.removeChild(this);for(const n in this.events)this.events[n].clear();for(const n in this.features){const r=this.features[n];r&&(r.unmount(),r.isMounted=!1)}this.current=null}addChild(t){this.children.add(t),this.enteringChildren??(this.enteringChildren=new Set),this.enteringChildren.add(t)}removeChild(t){this.children.delete(t),this.enteringChildren&&this.enteringChildren.delete(t)}bindToMotionValue(t,n){if(this.valueSubscriptions.has(t)&&this.valueSubscriptions.get(t)(),n.accelerate&&Jdt.has(t)&&this.current instanceof HTMLElement){const{factory:l,keyframes:o,times:c,ease:d,duration:u}=n.accelerate,h=new Qdt({element:this.current,name:t,keyframes:o,times:c,ease:d,duration:Vg(u)}),p=l(h);this.valueSubscriptions.set(t,()=>{p(),h.cancel()});return}const r=BD.has(t);r&&this.onBindTransform&&this.onBindTransform();const a=n.on("change",l=>{this.latestValues[t]=l,this.props.onUpdate&&sd.preRender(this.notifyUpdate),r&&this.projection&&(this.projection.isTransformDirty=!0),this.scheduleRender()});let i;typeof window<"u"&&window.MotionCheckAppearSync&&(i=window.MotionCheckAppearSync(this,t,n)),this.valueSubscriptions.set(t,()=>{a(),i&&i(),n.owner&&n.stop()})}sortNodePosition(t){return!this.current||!this.sortInstanceNodePosition||this.type!==t.type?0:this.sortInstanceNodePosition(this.current,t.current)}updateFeatures(){let t="animation";for(t in ofe){const n=ofe[t];if(!n)continue;const{isEnabled:r,Feature:a}=n;if(!this.features[t]&&a&&r(this.props)&&(this.features[t]=new a(this)),this.features[t]){const i=this.features[t];i.isMounted?i.update():(i.mount(),i.isMounted=!0)}}}triggerBuild(){this.build(this.renderState,this.latestValues,this.props)}measureViewportBox(){return this.current?this.measureInstanceViewportBox(this.current,this.props):Sm()}getStaticValue(t){return this.latestValues[t]}setStaticValue(t,n){this.latestValues[t]=n}update(t,n){(t.transformTemplate||this.props.transformTemplate)&&this.scheduleRender(),this.prevProps=this.props,this.props=t,this.prevPresenceContext=this.presenceContext,this.presenceContext=n;for(let r=0;rn.variantChildren.delete(t)}addValue(t,n){const r=this.values.get(t);n!==r&&(r&&this.removeValue(t),this.bindToMotionValue(t,n),this.values.set(t,n),this.latestValues[t]=n.get())}removeValue(t){this.values.delete(t);const n=this.valueSubscriptions.get(t);n&&(n(),this.valueSubscriptions.delete(t)),delete this.latestValues[t],this.removeValueFromRenderState(t,this.renderState)}hasValue(t){return this.values.has(t)}getValue(t,n){if(this.props.values&&this.props.values[t])return this.props.values[t];let r=this.values.get(t);return r===void 0&&n!==void 0&&(r=_8(n===null?void 0:n,{owner:this}),this.addValue(t,r)),r}readValue(t,n){let r=this.latestValues[t]!==void 0||!this.current?this.latestValues[t]:this.getBaseTargetFromProps(this.props,t)??this.readValueFromInstance(this.current,t,this.options);return r!=null&&(typeof r=="string"&&(gdt(r)||vdt(r))?r=parseFloat(r):!cZt(r)&&vb.test(n)&&(r=dut(t,n)),this.setBaseTarget(t,lf(r)?r.get():r)),lf(r)?r.get():r}setBaseTarget(t,n){this.baseTarget[t]=n}getBaseTarget(t){var i;const{initial:n}=this.props;let r;if(typeof n=="string"||typeof n=="object"){const l=bMe(this.props,n,(i=this.presenceContext)==null?void 0:i.custom);l&&(r=l[t])}if(n&&r!==void 0)return r;const a=this.getBaseTargetFromProps(this.props,t);return a!==void 0&&!lf(a)?a:this.initialValues[t]!==void 0&&r===void 0?void 0:this.baseTarget[t]}on(t,n){return this.events[t]||(this.events[t]=new lMe),this.events[t].add(n)}notify(t,...n){this.events[t]&&this.events[t].notify(...n)}scheduleRenderMicrotask(){NMe.render(this.render)}}class vut extends fZt{constructor(){super(...arguments),this.KeyframeResolver=qYt}sortInstanceNodePosition(t,n){return t.compareDocumentPosition(n)&2?1:-1}getBaseTargetFromProps(t,n){const r=t.style;return r?r[n]:void 0}removeValueFromRenderState(t,{vars:n,style:r}){delete n[t],delete r[t]}handleChildMotionValue(){this.childSubscription&&(this.childSubscription(),delete this.childSubscription);const{children:t}=this.props;lf(t)&&(this.childSubscription=t.on("change",n=>{this.current&&(this.current.textContent=`${n}`)}))}}class H4{constructor(t){this.isMounted=!1,this.node=t}update(){}}function but({top:s,left:t,right:n,bottom:r}){return{x:{min:t,max:n},y:{min:s,max:r}}}function xZt({x:s,y:t}){return{top:t.min,right:s.max,bottom:t.max,left:s.min}}function gZt(s,t){if(!t)return s;const n=t({x:s.left,y:s.top}),r=t({x:s.right,y:s.bottom});return{top:n.y,left:n.x,bottom:r.y,right:r.x}}function nje(s){return s===void 0||s===1}function $4e({scale:s,scaleX:t,scaleY:n}){return!nje(s)||!nje(t)||!nje(n)}function kE(s){return $4e(s)||_ut(s)||s.z||s.rotate||s.rotateX||s.rotateY||s.skewX||s.skewY}function _ut(s){return KBe(s.x)||KBe(s.y)}function KBe(s){return s&&s!=="0%"}function lfe(s,t,n){const r=s-n,a=t*r;return n+a}function YBe(s,t,n,r,a){return a!==void 0&&(s=lfe(s,a,r)),lfe(s,n,r)+t}function U4e(s,t=0,n=1,r,a){s.min=YBe(s.min,t,n,r,a),s.max=YBe(s.max,t,n,r,a)}function wut(s,{x:t,y:n}){U4e(s.x,t.translate,t.scale,t.originPoint),U4e(s.y,n.translate,n.scale,n.originPoint)}const ZBe=.999999999999,QBe=1.0000000000001;function yZt(s,t,n,r=!1){var o;const a=n.length;if(!a)return;t.x=t.y=1;let i,l;for(let c=0;cZBe&&(t.x=1),t.yZBe&&(t.y=1)}function H_(s,t){s.min+=t,s.max+=t}function XBe(s,t,n,r,a=.5){const i=Od(s.min,s.max,a);U4e(s,t,n,i,r)}function JBe(s,t){return typeof s=="string"?parseFloat(s)/100*(t.max-t.min):s}function kme(s,t,n){const r=n??s;XBe(s.x,JBe(t.x,r.x),t.scaleX,t.scale,t.originX),XBe(s.y,JBe(t.y,r.y),t.scaleY,t.scale,t.originY)}function jut(s,t){return but(gZt(s.getBoundingClientRect(),t))}function vZt(s,t,n){const r=jut(s,n),{scroll:a}=t;return a&&(H_(r.x,a.offset.x),H_(r.y,a.offset.y)),r}const bZt={x:"translateX",y:"translateY",z:"translateZ",transformPerspective:"perspective"},_Zt=zD.length;function wZt(s,t,n){let r="",a=!0;for(let i=0;i<_Zt;i++){const l=zD[i],o=s[l];if(o===void 0)continue;let c=!0;if(typeof o=="number")c=o===(l.startsWith("scale")?1:0);else{const d=parseFloat(o);c=l.startsWith("scale")?d===1:d===0}if(!c||n){const d=uut(o,wMe[l]);if(!c){a=!1;const u=bZt[l]||l;r+=`${u}(${d}) `}n&&(t[l]=d)}}return r=r.trim(),n?r=n(t,a?"":r):a&&(r="none"),r}function EMe(s,t,n){const{style:r,vars:a,transformOrigin:i}=s;let l=!1,o=!1;for(const c in t){const d=t[c];if(BD.has(c)){l=!0;continue}else if(Ldt(c)){a[c]=d;continue}else{const u=uut(d,wMe[c]);c.startsWith("origin")?(o=!0,i[c]=u):r[c]=u}}if(t.transform||(l||n?r.transform=wZt(t,s.transform,n):r.transform&&(r.transform="none")),o){const{originX:c="50%",originY:d="50%",originZ:u=0}=i;r.transformOrigin=`${c} ${d} ${u}`}}function Nut(s,{style:t,vars:n},r,a){const i=s.style;let l;for(l in t)i[l]=t[l];a==null||a.applyProjectionStyles(i,r);for(l in n)i.setProperty(l,n[l])}function e$e(s,t){return t.max===t.min?0:s/(t.max-t.min)*100}const eF={correct:(s,t)=>{if(!t.target)return s;if(typeof s=="string")if(oi.test(s))s=parseFloat(s);else return s;const n=e$e(s,t.target.x),r=e$e(s,t.target.y);return`${n}% ${r}%`}},jZt={correct:(s,{treeScale:t,projectionDelta:n})=>{const r=s,a=vb.parse(s);if(a.length>5)return r;const i=vb.createTransformer(s),l=typeof a[0]!="number"?1:0,o=n.x.scale*t.x,c=n.y.scale*t.y;a[0+l]/=o,a[1+l]/=c;const d=Od(o,c,.5);return typeof a[2+l]=="number"&&(a[2+l]/=d),typeof a[3+l]=="number"&&(a[3+l]/=d),i(a)}},q4e={borderRadius:{...eF,applyTo:["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"]},borderTopLeftRadius:eF,borderTopRightRadius:eF,borderBottomLeftRadius:eF,borderBottomRightRadius:eF,boxShadow:jZt};function kut(s,{layout:t,layoutId:n}){return BD.has(s)||s.startsWith("origin")||(t||n!==void 0)&&(!!q4e[s]||s==="opacity")}function AMe(s,t,n){var l;const r=s.style,a=t==null?void 0:t.style,i={};if(!r)return i;for(const o in r)(lf(r[o])||a&&lf(a[o])||kut(o,s)||((l=n==null?void 0:n.getValue(o))==null?void 0:l.liveStyle)!==void 0)&&(i[o]=r[o]);return i}function NZt(s){return window.getComputedStyle(s)}class kZt extends vut{constructor(){super(...arguments),this.type="html",this.renderInstance=Nut}readValueFromInstance(t,n){var r;if(BD.has(n))return(r=this.projection)!=null&&r.isProjecting?E4e(n):VKt(t,n);{const a=NZt(t),i=(Ldt(n)?a.getPropertyValue(n):a[n])||0;return typeof i=="string"?i.trim():i}}measureInstanceViewportBox(t,{transformPagePoint:n}){return jut(t,n)}build(t,n,r){EMe(t,n,r.transformTemplate)}scrapeMotionValuesFromProps(t,n,r){return AMe(t,n,r)}}const SZt={offset:"stroke-dashoffset",array:"stroke-dasharray"},CZt={offset:"strokeDashoffset",array:"strokeDasharray"};function TZt(s,t,n=1,r=0,a=!0){s.pathLength=1;const i=a?SZt:CZt;s[i.offset]=`${-r}`,s[i.array]=`${t} ${n}`}const EZt=["offsetDistance","offsetPath","offsetRotate","offsetAnchor"];function Sut(s,{attrX:t,attrY:n,attrScale:r,pathLength:a,pathSpacing:i=1,pathOffset:l=0,...o},c,d,u){if(EMe(s,o,d),c){s.style.viewBox&&(s.attrs.viewBox=s.style.viewBox);return}s.attrs=s.style,s.style={};const{attrs:h,style:p}=s;h.transform&&(p.transform=h.transform,delete h.transform),(p.transform||h.transformOrigin)&&(p.transformOrigin=h.transformOrigin??"50% 50%",delete h.transformOrigin),p.transform&&(p.transformBox=(u==null?void 0:u.transformBox)??"fill-box",delete h.transformBox);for(const f of EZt)h[f]!==void 0&&(p[f]=h[f],delete h[f]);t!==void 0&&(h.x=t),n!==void 0&&(h.y=n),r!==void 0&&(h.scale=r),a!==void 0&&TZt(h,a,i,l,!1)}const Cut=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"]),Tut=s=>typeof s=="string"&&s.toLowerCase()==="svg";function AZt(s,t,n,r){Nut(s,t,void 0,r);for(const a in t.attrs)s.setAttribute(Cut.has(a)?a:_Me(a),t.attrs[a])}function Eut(s,t,n){const r=AMe(s,t,n);for(const a in s)if(lf(s[a])||lf(t[a])){const i=zD.indexOf(a)!==-1?"attr"+a.charAt(0).toUpperCase()+a.substring(1):a;r[i]=s[a]}return r}class MZt extends vut{constructor(){super(...arguments),this.type="svg",this.isSVGTag=!1,this.measureInstanceViewportBox=Sm}getBaseTargetFromProps(t,n){return t[n]}readValueFromInstance(t,n){if(BD.has(n)){const r=cut(n);return r&&r.default||0}return n=Cut.has(n)?n:_Me(n),t.getAttribute(n)}scrapeMotionValuesFromProps(t,n,r){return Eut(t,n,r)}build(t,n,r){Sut(t,n,this.isSVGTag,r.transformTemplate,r.style)}renderInstance(t,n,r,a){AZt(t,n,r,a)}mount(t){this.isSVGTag=Tut(t.tagName),super.mount(t)}}const IZt=TMe.length;function Aut(s){if(!s)return;if(!s.isControllingVariants){const n=s.parent?Aut(s.parent)||{}:{};return s.props.initial!==void 0&&(n.initial=s.props.initial),n}const t={};for(let n=0;nPromise.all(t.map(({animation:n,options:r})=>IYt(s,n,r)))}function RZt(s){let t=DZt(s),n=t$e(),r=!0,a=!1;const i=d=>(u,h)=>{var f;const p=zA(s,h,d==="exit"?(f=s.presenceContext)==null?void 0:f.custom:void 0);if(p){const{transition:y,transitionEnd:_,...v}=p;u={...u,...v,..._}}return u};function l(d){t=d(s)}function o(d){const{props:u}=s,h=Aut(s.parent)||{},p=[],f=new Set;let y={},_=1/0;for(let j=0;j_&&E,z=!1;const H=Array.isArray(A)?A:[A];let Z=H.reduce(i(w),{});O===!1&&(Z={});const{prevResolvedValues:Y={}}=S,W={...Y,...Z},ee=he=>{F=!0,f.has(he)&&(z=!0,f.delete(he)),S.needsAnimating[he]=!0;const ce=s.getValue(he);ce&&(ce.liveStyle=!1)};for(const he in W){const ce=Z[he],me=Y[he];if(y.hasOwnProperty(he))continue;let le=!1;D4e(ce)&&D4e(me)?le=!Mut(ce,me):le=ce!==me,le?ce!=null?ee(he):f.add(he):ce!==void 0&&f.has(he)?ee(he):S.protectedKeys[he]=!0}S.prevProp=A,S.prevResolvedValues=Z,S.isActive&&(y={...y,...Z}),(r||a)&&s.blockInitialAnimation&&(F=!1);const se=D&&I;F&&(!se||z)&&p.push(...H.map(he=>{const ce={type:w};if(typeof he=="string"&&(r||a)&&!se&&s.manuallyAnimateOnMount&&s.parent){const{parent:me}=s,le=zA(me,he);if(me.enteringChildren&&le){const{delayChildren:ve}=le.transition||{};ce.delay=eut(me.enteringChildren,s,ve)}}return{animation:he,options:ce}}))}if(f.size){const j={};if(typeof u.initial!="boolean"){const w=zA(s,Array.isArray(u.initial)?u.initial[0]:u.initial);w&&w.transition&&(j.transition=w.transition)}f.forEach(w=>{const S=s.getBaseTarget(w),A=s.getValue(w);A&&(A.liveStyle=!0),j[w]=S??null}),p.push({animation:j})}let v=!!p.length;return r&&(u.initial===!1||u.initial===u.animate)&&!s.manuallyAnimateOnMount&&(v=!1),r=!1,a=!1,v?t(p):Promise.resolve()}function c(d,u){var p;if(n[d].isActive===u)return Promise.resolve();(p=s.variantChildren)==null||p.forEach(f=>{var y;return(y=f.animationState)==null?void 0:y.setActive(d,u)}),n[d].isActive=u;const h=o(d);for(const f in n)n[f].protectedKeys={};return h}return{animateChanges:o,setActive:c,setAnimateFunction:l,getState:()=>n,reset:()=>{n=t$e(),a=!0}}}function OZt(s,t){return typeof t=="string"?t!==s:Array.isArray(t)?!Mut(t,s):!1}function s3(s=!1){return{isActive:s,protectedKeys:{},needsAnimating:{},prevResolvedValues:{}}}function t$e(){return{animate:s3(!0),whileInView:s3(),whileHover:s3(),whileTap:s3(),whileDrag:s3(),whileFocus:s3(),exit:s3()}}function V4e(s,t){s.min=t.min,s.max=t.max}function D1(s,t){V4e(s.x,t.x),V4e(s.y,t.y)}function s$e(s,t){s.translate=t.translate,s.scale=t.scale,s.originPoint=t.originPoint,s.origin=t.origin}const Iut=1e-4,FZt=1-Iut,zZt=1+Iut,Put=.01,BZt=0-Put,$Zt=0+Put;function Gx(s){return s.max-s.min}function UZt(s,t,n){return Math.abs(s-t)<=n}function n$e(s,t,n,r=.5){s.origin=r,s.originPoint=Od(t.min,t.max,s.origin),s.scale=Gx(n)/Gx(t),s.translate=Od(n.min,n.max,s.origin)-s.originPoint,(s.scale>=FZt&&s.scale<=zZt||isNaN(s.scale))&&(s.scale=1),(s.translate>=BZt&&s.translate<=$Zt||isNaN(s.translate))&&(s.translate=0)}function U9(s,t,n,r){n$e(s.x,t.x,n.x,r?r.originX:void 0),n$e(s.y,t.y,n.y,r?r.originY:void 0)}function r$e(s,t,n,r=0){const a=r?Od(n.min,n.max,r):n.min;s.min=a+t.min,s.max=s.min+Gx(t)}function qZt(s,t,n,r){r$e(s.x,t.x,n.x,r==null?void 0:r.x),r$e(s.y,t.y,n.y,r==null?void 0:r.y)}function a$e(s,t,n,r=0){const a=r?Od(n.min,n.max,r):n.min;s.min=t.min-a,s.max=s.min+Gx(t)}function cfe(s,t,n,r){a$e(s.x,t.x,n.x,r==null?void 0:r.x),a$e(s.y,t.y,n.y,r==null?void 0:r.y)}function i$e(s,t,n,r,a){return s-=t,s=lfe(s,1/n,r),a!==void 0&&(s=lfe(s,1/a,r)),s}function VZt(s,t=0,n=1,r=.5,a,i=s,l=s){if(bw.test(t)&&(t=parseFloat(t),t=Od(l.min,l.max,t/100)-l.min),typeof t!="number")return;let o=Od(i.min,i.max,r);s===i&&(o-=t),s.min=i$e(s.min,t,n,o,a),s.max=i$e(s.max,t,n,o,a)}function o$e(s,t,[n,r,a],i,l){VZt(s,t[n],t[r],t[a],t.scale,i,l)}const HZt=["x","scaleX","originX"],GZt=["y","scaleY","originY"];function l$e(s,t,n,r){o$e(s.x,t,HZt,n?n.x:void 0,r?r.x:void 0),o$e(s.y,t,GZt,n?n.y:void 0,r?r.y:void 0)}function c$e(s){return s.translate===0&&s.scale===1}function Lut(s){return c$e(s.x)&&c$e(s.y)}function d$e(s,t){return s.min===t.min&&s.max===t.max}function WZt(s,t){return d$e(s.x,t.x)&&d$e(s.y,t.y)}function u$e(s,t){return Math.round(s.min)===Math.round(t.min)&&Math.round(s.max)===Math.round(t.max)}function Dut(s,t){return u$e(s.x,t.x)&&u$e(s.y,t.y)}function h$e(s){return Gx(s.x)/Gx(s.y)}function m$e(s,t){return s.translate===t.translate&&s.scale===t.scale&&s.originPoint===t.originPoint}function D_(s){return[s("x"),s("y")]}function KZt(s,t,n){let r="";const a=s.x.translate/t.x,i=s.y.translate/t.y,l=(n==null?void 0:n.z)||0;if((a||i||l)&&(r=`translate3d(${a}px, ${i}px, ${l}px) `),(t.x!==1||t.y!==1)&&(r+=`scale(${1/t.x}, ${1/t.y}) `),n){const{transformPerspective:d,rotate:u,rotateX:h,rotateY:p,skewX:f,skewY:y}=n;d&&(r=`perspective(${d}px) ${r}`),u&&(r+=`rotate(${u}deg) `),h&&(r+=`rotateX(${h}deg) `),p&&(r+=`rotateY(${p}deg) `),f&&(r+=`skewX(${f}deg) `),y&&(r+=`skewY(${y}deg) `)}const o=s.x.scale*t.x,c=s.y.scale*t.y;return(o!==1||c!==1)&&(r+=`scale(${o}, ${c})`),r||"none"}const Rut=["borderTopLeftRadius","borderTopRightRadius","borderBottomLeftRadius","borderBottomRightRadius"],YZt=Rut.length,p$e=s=>typeof s=="string"?parseFloat(s):s,f$e=s=>typeof s=="number"||oi.test(s);function ZZt(s,t,n,r,a,i){a?(s.opacity=Od(0,n.opacity??1,QZt(r)),s.opacityExit=Od(t.opacity??1,0,XZt(r))):i&&(s.opacity=Od(t.opacity??1,n.opacity??1,r));for(let l=0;lrt?1:n(nB(s,t,r))}function JZt(s,t,n){const r=lf(s)?s:_8(s);return r.start(vMe("",r,t,n)),r.animation}function iB(s,t,n,r={passive:!0}){return s.addEventListener(t,n,r),()=>s.removeEventListener(t,n)}const eQt=(s,t)=>s.depth-t.depth;class tQt{constructor(){this.children=[],this.isDirty=!1}add(t){oMe(this.children,t),this.isDirty=!0}remove(t){sfe(this.children,t),this.isDirty=!0}forEach(t){this.isDirty&&this.children.sort(eQt),this.isDirty=!1,this.children.forEach(t)}}function sQt(s,t){const n=Hx.now(),r=({timestamp:a})=>{const i=a-n;i>=t&&(S4(r),s(i-t))};return sd.setup(r,!0),()=>S4(r)}function Sme(s){return lf(s)?s.get():s}class nQt{constructor(){this.members=[]}add(t){oMe(this.members,t);for(let n=this.members.length-1;n>=0;n--){const r=this.members[n];if(r===t||r===this.lead||r===this.prevLead)continue;const a=r.instance;(!a||a.isConnected===!1)&&!r.snapshot&&(sfe(this.members,r),r.unmount())}t.scheduleRender()}remove(t){if(sfe(this.members,t),t===this.prevLead&&(this.prevLead=void 0),t===this.lead){const n=this.members[this.members.length-1];n&&this.promote(n)}}relegate(t){var n;for(let r=this.members.indexOf(t)-1;r>=0;r--){const a=this.members[r];if(a.isPresent!==!1&&((n=a.instance)==null?void 0:n.isConnected)!==!1)return this.promote(a),!0}return!1}promote(t,n){var a;const r=this.lead;if(t!==r&&(this.prevLead=r,this.lead=t,t.show(),r)){r.updateSnapshot(),t.scheduleRender();const{layoutDependency:i}=r.options,{layoutDependency:l}=t.options;(i===void 0||i!==l)&&(t.resumeFrom=r,n&&(r.preserveOpacity=!0),r.snapshot&&(t.snapshot=r.snapshot,t.snapshot.latestValues=r.animationValues||r.latestValues),(a=t.root)!=null&&a.isUpdating&&(t.isLayoutDirty=!0)),t.options.crossfade===!1&&r.hide()}}exitAnimationComplete(){this.members.forEach(t=>{var n,r,a,i,l;(r=(n=t.options).onExitComplete)==null||r.call(n),(l=(a=t.resumingFrom)==null?void 0:(i=a.options).onExitComplete)==null||l.call(i)})}scheduleRender(){this.members.forEach(t=>t.instance&&t.scheduleRender(!1))}removeLeadSnapshot(){var t;(t=this.lead)!=null&&t.snapshot&&(this.lead.snapshot=void 0)}}const Cme={hasAnimatedSinceResize:!0,hasEverUpdated:!1},rje=["","X","Y","Z"],rQt=1e3;let aQt=0;function aje(s,t,n,r){const{latestValues:a}=t;a[s]&&(n[s]=a[s],t.setStaticValue(s,0),r&&(r[s]=0))}function Fut(s){if(s.hasCheckedOptimisedAppear=!0,s.root===s)return;const{visualElement:t}=s.options;if(!t)return;const n=aut(t);if(window.MotionHasOptimisedAnimation(n,"transform")){const{layout:a,layoutId:i}=s.options;window.MotionCancelOptimisedAnimation(n,"transform",sd,!(a||i))}const{parent:r}=s;r&&!r.hasCheckedOptimisedAppear&&Fut(r)}function zut({attachResizeListener:s,defaultParent:t,measureScroll:n,checkIsScrollRoot:r,resetTransform:a}){return class{constructor(l={},o=t==null?void 0:t()){this.id=aQt++,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(lQt),this.nodes.forEach(pQt),this.nodes.forEach(fQt),this.nodes.forEach(cQt)},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;sd.read(()=>{h=window.innerWidth}),s(l,()=>{const f=window.innerWidth;f!==h&&(h=f,this.root.updateBlockedByResize=!0,u&&u(),u=sQt(p,250),Cme.hasAnimatedSinceResize&&(Cme.hasAnimatedSinceResize=!1,this.nodes.forEach(v$e)))})}o&&this.root.registerSharedNode(o,this),this.options.animate!==!1&&d&&(o||c)&&this.addEventListener("didUpdate",({delta:u,hasLayoutChanged:h,hasRelativeLayoutChanged:p,layout:f})=>{if(this.isTreeAnimationBlocked()){this.target=void 0,this.relativeTarget=void 0;return}const y=this.options.transition||d.getDefaultTransition()||bQt,{onLayoutAnimationStart:_,onLayoutAnimationComplete:v}=d.getProps(),j=!this.targetLayout||!Dut(this.targetLayout,f),w=!h&&p;if(this.options.layoutRoot||this.resumeFrom||w||h&&(j||!this.currentAnimation)){this.resumeFrom&&(this.resumingFrom=this.resumeFrom,this.resumingFrom.resumingFrom=void 0);const S={...yMe(y,"layout"),onPlay:_,onComplete:v};(d.shouldReduceMotion||this.options.layoutRoot)&&(S.delay=0,S.type=!1),this.startAnimation(S),this.setAnimationOrigin(u,w)}else h||v$e(this),this.isLead()&&this.options.onExitComplete&&this.options.onExitComplete();this.targetLayout=f})}unmount(){this.options.layoutId&&this.willUpdate(),this.root.nodes.remove(this);const l=this.getStack();l&&l.remove(this),this.parent&&this.parent.children.delete(this),this.instance=void 0,this.eventHandlers.clear(),S4(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(xQt),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&&Fut(this),!this.root.isUpdating&&this.root.startUpdate(),this.isLayoutDirty)return;this.isLayoutDirty=!0;for(let u=0;u{this.isLayoutDirty?this.root.didUpdate():this.root.checkUpdateFailed()})}updateSnapshot(){this.snapshot||!this.instance||(this.snapshot=this.measure(),this.snapshot&&!Gx(this.snapshot.measuredBox.x)&&!Gx(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 E=A/1e3;b$e(h.x,l.x,E),b$e(h.y,l.y,E),this.setTargetDelta(h),this.relativeTarget&&this.relativeTargetOrigin&&this.layout&&this.relativeParent&&this.relativeParent.layout&&(cfe(p,this.layout.layoutBox,this.relativeParent.layout.layoutBox,this.options.layoutAnchor||void 0),yQt(this.relativeTarget,this.relativeTargetOrigin,p,E),S&&WZt(this.relativeTarget,S)&&(this.isProjectionDirty=!1),S||(S=Sm()),D1(S,this.relativeTarget)),_&&(this.animationValues=u,ZZt(u,d,this.latestValues,E,w,j)),this.root.scheduleUpdateProjection(),this.scheduleRender(),this.animationProgress=E},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&&(S4(this.pendingAnimation),this.pendingAnimation=void 0),this.pendingAnimation=sd.update(()=>{Cme.hasAnimatedSinceResize=!0,this.motionValue||(this.motionValue=_8(0)),this.motionValue.jump(0,!1),this.currentAnimation=JZt(this.motionValue,[0,1e3],{...l,velocity:0,isSync:!0,onUpdate:u=>{this.mixTargetDelta(u),l.onUpdate&&l.onUpdate(u)},onStop:()=>{},onComplete:()=>{l.onComplete&&l.onComplete(),this.completeAnimation()}}),this.resumingFrom&&(this.resumingFrom.currentAnimation=this.currentAnimation),this.pendingAnimation=void 0})}completeAnimation(){this.resumingFrom&&(this.resumingFrom.currentAnimation=void 0,this.resumingFrom.preserveOpacity=void 0);const l=this.getStack();l&&l.exitAnimationComplete(),this.resumingFrom=this.currentAnimation=this.animationValues=void 0,this.notifyListeners("animationComplete")}finishAnimation(){this.currentAnimation&&(this.mixTargetDelta&&this.mixTargetDelta(rQt),this.currentAnimation.stop()),this.completeAnimation()}applyTransformsToTarget(){const l=this.getLead();let{targetWithTransforms:o,target:c,layout:d,latestValues:u}=l;if(!(!o||!c||!d)){if(this!==l&&this.layout&&d&&But(this.options.animationType,this.layout.layoutBox,d.layoutBox)){c=this.target||Sm();const h=Gx(this.layout.layoutBox.x);c.x.min=l.target.x.min,c.x.max=c.x.min+h;const p=Gx(this.layout.layoutBox.y);c.y.min=l.target.y.min,c.y.max=c.y.min+p}D1(o,c),kme(o,u),U9(this.projectionDeltaWithTransform,this.layoutCorrected,o,u)}}registerSharedNode(l,o){this.sharedNodes.has(l)||this.sharedNodes.set(l,new nQt),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&&aje("z",l,d,this.animationValues);for(let u=0;u{var o;return(o=l.currentAnimation)==null?void 0:o.stop()}),this.root.nodes.forEach(g$e),this.root.sharedNodes.clear()}}}function iQt(s){s.updateLayout()}function oQt(s){var n;const t=((n=s.resumeFrom)==null?void 0:n.snapshot)||s.snapshot;if(s.isLead()&&s.layout&&t&&s.hasListeners("didUpdate")){const{layoutBox:r,measuredBox:a}=s.layout,{animationType:i}=s.options,l=t.source!==s.layout.source;if(i==="size")D_(h=>{const p=l?t.measuredBox[h]:t.layoutBox[h],f=Gx(p);p.min=r[h].min,p.max=p.min+f});else if(i==="x"||i==="y"){const h=i==="x"?"y":"x";V4e(l?t.measuredBox[h]:t.layoutBox[h],r[h])}else But(i,t.layoutBox,r)&&D_(h=>{const p=l?t.measuredBox[h]:t.layoutBox[h],f=Gx(r[h]);p.max=p.min+f,s.relativeTarget&&!s.currentAnimation&&(s.isProjectionDirty=!0,s.relativeTarget[h].max=s.relativeTarget[h].min+f)});const o=NP();U9(o,r,t.layoutBox);const c=NP();l?U9(c,s.applyTransform(a,!0),t.measuredBox):U9(c,r,t.layoutBox);const d=!Lut(o);let u=!1;if(!s.resumeFrom){const h=s.getClosestProjectingParent();if(h&&!h.resumeFrom){const{snapshot:p,layout:f}=h;if(p&&f){const y=s.options.layoutAnchor||void 0,_=Sm();cfe(_,t.layoutBox,p.layoutBox,y);const v=Sm();cfe(v,r,f.layoutBox,y),Dut(_,v)||(u=!0),h.options.layoutRoot&&(s.relativeTarget=v,s.relativeTargetOrigin=_,s.relativeParent=h)}}}s.notifyListeners("didUpdate",{layout:r,snapshot:t,delta:c,layoutDelta:o,hasLayoutChanged:d,hasRelativeLayoutChanged:u})}else if(s.isLead()){const{onExitComplete:r}=s.options;r&&r()}s.options.transition=void 0}function lQt(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 cQt(s){s.isProjectionDirty=s.isSharedProjectionDirty=s.isTransformDirty=!1}function dQt(s){s.clearSnapshot()}function g$e(s){s.clearMeasurements()}function uQt(s){s.isLayoutDirty=!0,s.updateLayout()}function y$e(s){s.isLayoutDirty=!1}function hQt(s){s.isAnimationBlocked&&s.layout&&!s.isLayoutDirty&&(s.snapshot=s.layout,s.isLayoutDirty=!0)}function mQt(s){const{visualElement:t}=s.options;t&&t.getProps().onBeforeLayoutMeasure&&t.notify("BeforeLayoutMeasure"),s.resetTransform()}function v$e(s){s.finishAnimation(),s.targetDelta=s.relativeTarget=s.target=void 0,s.isProjectionDirty=!0}function pQt(s){s.resolveTargetDelta()}function fQt(s){s.calcProjection()}function xQt(s){s.resetSkewAndRotation()}function gQt(s){s.removeLeadSnapshot()}function b$e(s,t,n){s.translate=Od(t.translate,0,n),s.scale=Od(t.scale,1,n),s.origin=t.origin,s.originPoint=t.originPoint}function _$e(s,t,n,r){s.min=Od(t.min,n.min,r),s.max=Od(t.max,n.max,r)}function yQt(s,t,n,r){_$e(s.x,t.x,n.x,r),_$e(s.y,t.y,n.y,r)}function vQt(s){return s.animationValues&&s.animationValues.opacityExit!==void 0}const bQt={duration:.45,ease:[.4,0,.1,1]},w$e=s=>typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().includes(s),j$e=w$e("applewebkit/")&&!w$e("chrome/")?Math.round:Fv;function N$e(s){s.min=j$e(s.min),s.max=j$e(s.max)}function _Qt(s){N$e(s.x),N$e(s.y)}function But(s,t,n){return s==="position"||s==="preserve-aspect"&&!UZt(h$e(t),h$e(n),.2)}function wQt(s){var t;return s!==s.root&&((t=s.scroll)==null?void 0:t.wasRoot)}const jQt=zut({attachResizeListener:(s,t)=>iB(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}),ije={current:void 0},$ut=zut({measureScroll:s=>({x:s.scrollLeft,y:s.scrollTop}),defaultParent:()=>{if(!ije.current){const s=new jQt({});s.mount(window),s.setOptions({layoutScroll:!0}),ije.current=s}return ije.current},resetTransform:(s,t)=>{s.style.transform=t!==void 0?t:"none"},checkIsScrollRoot:s=>window.getComputedStyle(s).position==="fixed"}),MMe=N.createContext({transformPagePoint:s=>s,isStatic:!1,reducedMotion:"never"});function k$e(s,t){if(typeof s=="function")return s(t);s!=null&&(s.current=t)}function NQt(...s){return t=>{let n=!1;const r=s.map(a=>{const i=k$e(a,t);return!n&&typeof i=="function"&&(n=!0),i});if(n)return()=>{for(let a=0;a{const{width:f,height:y,top:_,left:v,right:j,bottom:w}=c.current;if(t||i===!1||!o.current||!f||!y)return;const S=n==="left"?`left: ${v}`:`right: ${j}`,A=r==="bottom"?`bottom: ${w}`:`top: ${_}`;o.current.dataset.motionPopId=l;const E=document.createElement("style");d&&(E.nonce=d);const O=a??document.head;return O.appendChild(E),E.sheet&&E.sheet.insertRule(` [data-motion-pop-id="${l}"] { position: absolute !important; width: ${f}px !important; height: ${y}px !important; ${S}px !important; ${A}px !important; } `),()=>{var D;(D=o.current)==null||D.removeAttribute("data-motion-pop-id"),O.contains(E)&&O.removeChild(E)}},[t]),e.jsx(SQt,{isPresent:t,childRef:o,sizeRef:c,pop:i,children:i===!1?s:N.cloneElement(s,{ref:h})})}const TQt=({children:s,initial:t,isPresent:n,onExitComplete:r,custom:a,presenceAffectsLayout:i,mode:l,anchorX:o,anchorY:c,root:d})=>{const u=iMe(EQt),h=N.useId();let p=!0,f=N.useMemo(()=>(p=!1,{id:h,initial:t,isPresent:n,custom:a,onExitComplete:y=>{u.set(y,!0);for(const _ of u.values())if(!_)return;r&&r()},register:y=>(u.set(y,!1),()=>u.delete(y))}),[n,u,r]);return i&&p&&(f={...f}),N.useMemo(()=>{u.forEach((y,_)=>u.set(_,!1))},[n]),N.useEffect(()=>{!n&&!u.size&&r&&r()},[n]),s=e.jsx(CQt,{pop:l==="popLayout",isPresent:n,anchorX:o,anchorY:c,root:d,children:s}),e.jsx(cye.Provider,{value:f,children:s})};function EQt(){return new Map}function Uut(s=!0){const t=N.useContext(cye);if(t===null)return[!0,null];const{isPresent:n,onExitComplete:r,register:a}=t,i=N.useId();N.useEffect(()=>{if(s)return a(i)},[s]);const l=N.useCallback(()=>s&&r&&r(i),[i,r,s]);return!n&&r?[!1,l]:[!0]}const XV=s=>s.key||"";function S$e(s){const t=[];return N.Children.forEach(s,n=>{N.isValidElement(n)&&t.push(n)}),t}const pye=({children:s,custom:t,initial:n=!0,onExitComplete:r,presenceAffectsLayout:a=!0,mode:i="sync",propagate:l=!1,anchorX:o="left",anchorY:c="top",root:d})=>{const[u,h]=Uut(l),p=N.useMemo(()=>S$e(s),[s]),f=l&&!u?[]:p.map(XV),y=N.useRef(!0),_=N.useRef(p),v=iMe(()=>new Map),j=N.useRef(new Set),[w,S]=N.useState(p),[A,E]=N.useState(p);xdt(()=>{y.current=!1,_.current=p;for(let I=0;I{const F=XV(I),z=l&&!u?!1:p===A||f.includes(F),H=()=>{if(j.current.has(F))return;if(v.has(F))j.current.add(F),v.set(F,!0);else return;let Z=!0;v.forEach(Y=>{Y||(Z=!1)}),Z&&(D==null||D(),E(_.current),l&&(h==null||h()),r&&r())};return e.jsx(TQt,{isPresent:z,initial:!y.current||n?void 0:!1,custom:t,presenceAffectsLayout:a,mode:i,root:d,onExitComplete:z?void 0:H,anchorX:o,anchorY:c,children:I},F)})})},qut=N.createContext({strict:!1}),C$e={animation:["animate","variants","whileHover","whileTap","exit","whileInView","whileFocus","whileDrag"],exit:["exit"],drag:["drag","dragControls"],focus:["whileFocus"],hover:["whileHover","onHoverStart","onHoverEnd"],tap:["whileTap","onTap","onTapStart","onTapCancel"],pan:["onPan","onPanStart","onPanSessionStart","onPanEnd"],inView:["whileInView","onViewportEnter","onViewportLeave"],layout:["layout","layoutId"]};let T$e=!1;function AQt(){if(T$e)return;const s={};for(const t in C$e)s[t]={isEnabled:n=>C$e[t].some(r=>!!n[r])};yut(s),T$e=!0}function Vut(){return AQt(),pZt()}function MQt(s){const t=Vut();for(const n in s)t[n]={...t[n],...s[n]};yut(t)}const IQt=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 dfe(s){return s.startsWith("while")||s.startsWith("drag")&&s!=="draggable"||s.startsWith("layout")||s.startsWith("onTap")||s.startsWith("onPan")||s.startsWith("onLayout")||IQt.has(s)}let Hut=s=>!dfe(s);function PQt(s){typeof s=="function"&&(Hut=t=>t.startsWith("on")?!dfe(t):s(t))}try{PQt(require("@emotion/is-prop-valid").default)}catch{}function LQt(s,t,n){const r={};for(const a in s)a==="values"&&typeof s.values=="object"||lf(s[a])||(Hut(a)||n===!0&&dfe(a)||!t&&!dfe(a)||s.draggable&&a.startsWith("onDrag"))&&(r[a]=s[a]);return r}const fye=N.createContext({});function DQt(s,t){if(mye(s)){const{initial:n,animate:r}=s;return{initial:n===!1||aB(n)?n:void 0,animate:aB(r)?r:void 0}}return s.inherit!==!1?t:{}}function RQt(s){const{initial:t,animate:n}=DQt(s,N.useContext(fye));return N.useMemo(()=>({initial:t,animate:n}),[E$e(t),E$e(n)])}function E$e(s){return Array.isArray(s)?s.join(" "):s}const IMe=()=>({style:{},transform:{},transformOrigin:{},vars:{}});function Gut(s,t,n){for(const r in t)!lf(t[r])&&!kut(r,n)&&(s[r]=t[r])}function OQt({transformTemplate:s},t){return N.useMemo(()=>{const n=IMe();return EMe(n,t,s),Object.assign({},n.vars,n.style)},[t])}function FQt(s,t){const n=s.style||{},r={};return Gut(r,n,s),Object.assign(r,OQt(s,t)),r}function zQt(s,t){const n={},r=FQt(s,t);return s.drag&&s.dragListener!==!1&&(n.draggable=!1,r.userSelect=r.WebkitUserSelect=r.WebkitTouchCallout="none",r.touchAction=s.drag===!0?"none":`pan-${s.drag==="x"?"y":"x"}`),s.tabIndex===void 0&&(s.onTap||s.onTapStart||s.whileTap)&&(n.tabIndex=0),n.style=r,n}const Wut=()=>({...IMe(),attrs:{}});function BQt(s,t,n,r){const a=N.useMemo(()=>{const i=Wut();return Sut(i,t,Tut(r),s.transformTemplate,s.style),{...i.attrs,style:{...i.style}}},[t]);if(s.style){const i={};Gut(i,s.style,s),a.style={...i,...a.style}}return a}const $Qt=["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 PMe(s){return typeof s!="string"||s.includes("-")?!1:!!($Qt.indexOf(s)>-1||/[A-Z]/u.test(s))}function UQt(s,t,n,{latestValues:r},a,i=!1,l){const c=(l??PMe(s)?BQt:zQt)(t,r,a,s),d=LQt(t,typeof s=="string",i),u=s!==N.Fragment?{...d,...c,ref:n}:{},{children:h}=t,p=N.useMemo(()=>lf(h)?h.get():h,[h]);return N.createElement(s,{...u,children:p})}function qQt({scrapeMotionValuesFromProps:s,createRenderState:t},n,r,a){return{latestValues:VQt(n,r,a,s),renderState:t()}}function VQt(s,t,n,r){const a={},i=r(s,{});for(const p in i)a[p]=Sme(i[p]);let{initial:l,animate:o}=s;const c=mye(s),d=xut(s);t&&d&&!c&&s.inherit!==!1&&(l===void 0&&(l=t.initial),o===void 0&&(o=t.animate));let u=n?n.initial===!1:!1;u=u||l===!1;const h=u?o:l;if(h&&typeof h!="boolean"&&!hye(h)){const p=Array.isArray(h)?h:[h];for(let f=0;f(t,n)=>{const r=N.useContext(fye),a=N.useContext(cye),i=()=>qQt(s,t,r,a);return n?i():iMe(i)},HQt=Kut({scrapeMotionValuesFromProps:AMe,createRenderState:IMe}),GQt=Kut({scrapeMotionValuesFromProps:Eut,createRenderState:Wut}),WQt=Symbol.for("motionComponentSymbol");function KQt(s,t,n){const r=N.useRef(n);N.useInsertionEffect(()=>{r.current=n});const a=N.useRef(null);return N.useCallback(i=>{var o;i&&((o=s.onMount)==null||o.call(s,i));const l=r.current;if(typeof l=="function")if(i){const c=l(i);typeof c=="function"&&(a.current=c)}else a.current?(a.current(),a.current=null):l(i);else l&&(l.current=i);t&&(i?t.mount(i):t.unmount())},[t])}const Yut=N.createContext({});function JI(s){return s&&typeof s=="object"&&Object.prototype.hasOwnProperty.call(s,"current")}function YQt(s,t,n,r,a,i){var S,A;const{visualElement:l}=N.useContext(fye),o=N.useContext(qut),c=N.useContext(cye),d=N.useContext(MMe),u=d.reducedMotion,h=d.skipAnimations,p=N.useRef(null),f=N.useRef(!1);r=r||o.renderer,!p.current&&r&&(p.current=r(s,{visualState:t,parent:l,props:n,presenceContext:c,blockInitialAnimation:c?c.initial===!1:!1,reducedMotionConfig:u,skipAnimations:h,isSVG:i}),f.current&&p.current&&(p.current.manuallyAnimateOnMount=!0));const y=p.current,_=N.useContext(Yut);y&&!y.projection&&a&&(y.type==="html"||y.type==="svg")&&ZQt(p.current,n,a,_);const v=N.useRef(!1);N.useInsertionEffect(()=>{y&&v.current&&y.update(n,c)});const j=n[rut],w=N.useRef(!!j&&typeof window<"u"&&!((S=window.MotionHandoffIsComplete)!=null&&S.call(window,j))&&((A=window.MotionHasOptimisedAnimation)==null?void 0:A.call(window,j)));return xdt(()=>{f.current=!0,y&&(v.current=!0,window.MotionIsMounted=!0,y.updateFeatures(),y.scheduleRenderMicrotask(),w.current&&y.animationState&&y.animationState.animateChanges())}),N.useEffect(()=>{y&&(!w.current&&y.animationState&&y.animationState.animateChanges(),w.current&&(queueMicrotask(()=>{var E;(E=window.MotionHandoffMarkAsComplete)==null||E.call(window,j)}),w.current=!1),y.enteringChildren=void 0)}),y}function ZQt(s,t,n,r){const{layoutId:a,layout:i,drag:l,dragConstraints:o,layoutScroll:c,layoutRoot:d,layoutAnchor:u,layoutCrossfade:h}=t;s.projection=new n(s.latestValues,t["data-framer-portal-id"]?void 0:Zut(s.parent)),s.projection.setOptions({layoutId:a,layout:i,alwaysMeasureLayout:!!l||o&&JI(o),visualElement:s,animationType:typeof i=="string"?i:"both",initialPromotionConfig:r,crossfade:h,layoutScroll:c,layoutRoot:d,layoutAnchor:u})}function Zut(s){if(s)return s.options.allowProjection!==!1?s.projection:Zut(s.parent)}function oje(s,{forwardMotionProps:t=!1,type:n}={},r,a){r&&MQt(r);const i=n?n==="svg":PMe(s),l=i?GQt:HQt;function o(d,u){let h;const p={...N.useContext(MMe),...d,layoutId:QQt(d)},{isStatic:f}=p,y=RQt(d),_=l(d,f);if(!f&&typeof window<"u"){XQt();const v=JQt(p);h=v.MeasureLayout,y.visualElement=YQt(s,_,p,a,v.ProjectionNode,i)}return e.jsxs(fye.Provider,{value:y,children:[h&&y.visualElement?e.jsx(h,{visualElement:y.visualElement,...p}):null,UQt(s,d,KQt(_,y.visualElement,u),_,f,t,i)]})}o.displayName=`motion.${typeof s=="string"?s:`create(${s.displayName??s.name??""})`}`;const c=N.forwardRef(o);return c[WQt]=s,c}function QQt({layoutId:s}){const t=N.useContext(aMe).id;return t&&s!==void 0?t+"-"+s:s}function XQt(s,t){N.useContext(qut).strict}function JQt(s){const t=Vut(),{drag:n,layout:r}=t;if(!n&&!r)return{};const a={...n,...r};return{MeasureLayout:n!=null&&n.isEnabled(s)||r!=null&&r.isEnabled(s)?a.MeasureLayout:void 0,ProjectionNode:a.ProjectionNode}}function eXt(s,t){if(typeof Proxy>"u")return oje;const n=new Map,r=(i,l)=>oje(i,l,s,t),a=(i,l)=>r(i,l);return new Proxy(a,{get:(i,l)=>l==="create"?r:(n.has(l)||n.set(l,oje(l,void 0,s,t)),n.get(l))})}const tXt=(s,t)=>t.isSVG??PMe(s)?new MZt(t):new kZt(t,{allowProjection:s!==N.Fragment});class sXt extends H4{constructor(t){super(t),t.animationState||(t.animationState=RZt(t))}updateAnimationControlsSubscription(){const{animate:t}=this.node.getProps();hye(t)&&(this.unmountControls=t.subscribe(this.node))}mount(){this.updateAnimationControlsSubscription()}update(){const{animate:t}=this.node.getProps(),{animate:n}=this.node.prevProps||{};t!==n&&this.updateAnimationControlsSubscription()}unmount(){var t;this.node.animationState.reset(),(t=this.unmountControls)==null||t.call(this)}}let nXt=0;class rXt extends H4{constructor(){super(...arguments),this.id=nXt++,this.isExitComplete=!1}update(){var i;if(!this.node.presenceContext)return;const{isPresent:t,onExitComplete:n}=this.node.presenceContext,{isPresent:r}=this.node.prevPresenceContext||{};if(!this.node.animationState||t===r)return;if(t&&r===!1){if(this.isExitComplete){const{initial:l,custom:o}=this.node.getProps();if(typeof l=="string"){const c=zA(this.node,l,o);if(c){const{transition:d,transitionEnd:u,...h}=c;for(const p in h)(i=this.node.getValue(p))==null||i.jump(h[p])}}this.node.animationState.reset(),this.node.animationState.animateChanges()}else this.node.animationState.setActive("exit",!1);this.isExitComplete=!1;return}const a=this.node.animationState.setActive("exit",!t);n&&!t&&a.then(()=>{this.isExitComplete=!0,n(this.id)})}mount(){const{register:t,onExitComplete:n}=this.node.presenceContext||{};n&&n(this.id),t&&(this.unmount=t(this.id))}unmount(){}}const aXt={animation:{Feature:sXt},exit:{Feature:rXt}};function tU(s){return{point:{x:s.pageX,y:s.pageY}}}const iXt=s=>t=>kMe(t)&&s(t,tU(t));function q9(s,t,n,r){return iB(s,t,iXt(n),r)}const Qut=({current:s})=>s?s.ownerDocument.defaultView:null,A$e=(s,t)=>Math.abs(s-t);function oXt(s,t){const n=A$e(s.x,t.x),r=A$e(s.y,t.y);return Math.sqrt(n**2+r**2)}const M$e=new Set(["auto","scroll"]);class Xut{constructor(t,n,{transformPagePoint:r,contextWindow:a=window,dragSnapToOrigin:i=!1,distanceThreshold:l=3,element:o}={}){if(this.startEvent=null,this.lastMoveEvent=null,this.lastMoveEventInfo=null,this.lastRawMoveEventInfo=null,this.handlers={},this.contextWindow=window,this.scrollPositions=new Map,this.removeScrollListeners=null,this.onElementScroll=f=>{this.handleScroll(f.target)},this.onWindowScroll=()=>{this.handleScroll(window)},this.updatePoint=()=>{if(!(this.lastMoveEvent&&this.lastMoveEventInfo))return;this.lastRawMoveEventInfo&&(this.lastMoveEventInfo=JV(this.lastRawMoveEventInfo,this.transformPagePoint));const f=lje(this.lastMoveEventInfo,this.history),y=this.startEvent!==null,_=oXt(f.offset,{x:0,y:0})>=this.distanceThreshold;if(!y&&!_)return;const{point:v}=f,{timestamp:j}=Jp;this.history.push({...v,timestamp:j});const{onStart:w,onMove:S}=this.handlers;y||(w&&w(this.lastMoveEvent,f),this.startEvent=this.lastMoveEvent),S&&S(this.lastMoveEvent,f)},this.handlePointerMove=(f,y)=>{this.lastMoveEvent=f,this.lastRawMoveEventInfo=y,this.lastMoveEventInfo=JV(y,this.transformPagePoint),sd.update(this.updatePoint,!0)},this.handlePointerUp=(f,y)=>{this.end();const{onEnd:_,onSessionEnd:v,resumeAnimation:j}=this.handlers;if((this.dragSnapToOrigin||!this.startEvent)&&j&&j(),!(this.lastMoveEvent&&this.lastMoveEventInfo))return;const w=lje(f.type==="pointercancel"?this.lastMoveEventInfo:JV(y,this.transformPagePoint),this.history);this.startEvent&&_&&_(f,w),v&&v(f,w)},!kMe(t))return;this.dragSnapToOrigin=i,this.handlers=n,this.transformPagePoint=r,this.distanceThreshold=l,this.contextWindow=a||window;const c=tU(t),d=JV(c,this.transformPagePoint),{point:u}=d,{timestamp:h}=Jp;this.history=[{...u,timestamp:h}];const{onSessionStart:p}=n;p&&p(t,lje(d,this.history)),this.removeListeners=X$(q9(this.contextWindow,"pointermove",this.handlePointerMove),q9(this.contextWindow,"pointerup",this.handlePointerUp),q9(this.contextWindow,"pointercancel",this.handlePointerUp)),o&&this.startScrollTracking(o)}startScrollTracking(t){let n=t.parentElement;for(;n;){const r=getComputedStyle(n);(M$e.has(r.overflowX)||M$e.has(r.overflowY))&&this.scrollPositions.set(n,{x:n.scrollLeft,y:n.scrollTop}),n=n.parentElement}this.scrollPositions.set(window,{x:window.scrollX,y:window.scrollY}),window.addEventListener("scroll",this.onElementScroll,{capture:!0}),window.addEventListener("scroll",this.onWindowScroll),this.removeScrollListeners=()=>{window.removeEventListener("scroll",this.onElementScroll,{capture:!0}),window.removeEventListener("scroll",this.onWindowScroll)}}handleScroll(t){const n=this.scrollPositions.get(t);if(!n)return;const r=t===window,a=r?{x:window.scrollX,y:window.scrollY}:{x:t.scrollLeft,y:t.scrollTop},i={x:a.x-n.x,y:a.y-n.y};i.x===0&&i.y===0||(r?this.lastMoveEventInfo&&(this.lastMoveEventInfo.point.x+=i.x,this.lastMoveEventInfo.point.y+=i.y):this.history.length>0&&(this.history[0].x-=i.x,this.history[0].y-=i.y),this.scrollPositions.set(t,a),sd.update(this.updatePoint,!0))}updateHandlers(t){this.handlers=t}end(){this.removeListeners&&this.removeListeners(),this.removeScrollListeners&&this.removeScrollListeners(),this.scrollPositions.clear(),S4(this.updatePoint)}}function JV(s,t){return t?{point:t(s.point)}:s}function I$e(s,t){return{x:s.x-t.x,y:s.y-t.y}}function lje({point:s},t){return{point:s,delta:I$e(s,Jut(t)),offset:I$e(s,lXt(t)),velocity:cXt(t,.1)}}function lXt(s){return s[0]}function Jut(s){return s[s.length-1]}function cXt(s,t){if(s.length<2)return{x:0,y:0};let n=s.length-1,r=null;const a=Jut(s);for(;n>=0&&(r=s[n],!(a.timestamp-r.timestamp>Vg(t)));)n--;if(!r)return{x:0,y:0};r===s[0]&&s.length>2&&a.timestamp-r.timestamp>Vg(t)*2&&(r=s[1]);const i=Ev(a.timestamp-r.timestamp);if(i===0)return{x:0,y:0};const l={x:(a.x-r.x)/i,y:(a.y-r.y)/i};return l.x===1/0&&(l.x=0),l.y===1/0&&(l.y=0),l}function dXt(s,{min:t,max:n},r){return t!==void 0&&sn&&(s=r?Od(n,s,r.max):Math.min(s,n)),s}function P$e(s,t,n){return{min:t!==void 0?s.min+t:void 0,max:n!==void 0?s.max+n-(s.max-s.min):void 0}}function uXt(s,{top:t,left:n,bottom:r,right:a}){return{x:P$e(s.x,n,a),y:P$e(s.y,t,r)}}function L$e(s,t){let n=t.min-s.min,r=t.max-s.max;return t.max-t.minr?n=nB(t.min,t.max-r,s.min):r>a&&(n=nB(s.min,s.max-a,t.min)),Ew(0,1,n)}function pXt(s,t){const n={};return t.min!==void 0&&(n.min=t.min-s.min),t.max!==void 0&&(n.max=t.max-s.min),n}const H4e=.35;function fXt(s=H4e){return s===!1?s=0:s===!0&&(s=H4e),{x:D$e(s,"left","right"),y:D$e(s,"top","bottom")}}function D$e(s,t,n){return{min:R$e(s,t),max:R$e(s,n)}}function R$e(s,t){return typeof s=="number"?s:s[t]||0}const xXt=new WeakMap;class gXt{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=Sm(),this.latestPointerEvent=null,this.latestPanInfo=null,this.visualElement=t}start(t,{snapToCursor:n=!1,distanceThreshold:r}={}){const{presenceContext:a}=this.visualElement;if(a&&a.isPresent===!1)return;const i=h=>{n&&this.snapToCursor(tU(h).point),this.stopAnimation()},l=(h,p)=>{const{drag:f,dragPropagation:y,onDragStart:_}=this.getProps();if(f&&!y&&(this.openDragLock&&this.openDragLock(),this.openDragLock=VYt(f),!this.openDragLock))return;this.latestPointerEvent=h,this.latestPanInfo=p,this.isDragging=!0,this.currentDirection=null,this.resolveConstraints(),this.visualElement.projection&&(this.visualElement.projection.isAnimationBlocked=!0,this.visualElement.projection.target=void 0),D_(j=>{let w=this.getAxisMotionValue(j).get()||0;if(bw.test(w)){const{projection:S}=this.visualElement;if(S&&S.layout){const A=S.layout.layoutBox[j];A&&(w=Gx(A)*(parseFloat(w)/100))}}this.originPoint[j]=w}),_&&sd.update(()=>_(h,p),!1,!0),R4e(this.visualElement,"transform");const{animationState:v}=this.visualElement;v&&v.setActive("whileDrag",!0)},o=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p;const{dragPropagation:f,dragDirectionLock:y,onDirectionLock:_,onDrag:v}=this.getProps();if(!f&&!this.openDragLock)return;const{offset:j}=p;if(y&&this.currentDirection===null){this.currentDirection=vXt(j),this.currentDirection!==null&&_&&_(this.currentDirection);return}this.updateAxis("x",p.point,j),this.updateAxis("y",p.point,j),this.visualElement.render(),v&&sd.update(()=>v(h,p),!1,!0)},c=(h,p)=>{this.latestPointerEvent=h,this.latestPanInfo=p,this.stop(h,p),this.latestPointerEvent=null,this.latestPanInfo=null},d=()=>{const{dragSnapToOrigin:h}=this.getProps();(h||this.constraints)&&this.startAnimation({x:0,y:0})},{dragSnapToOrigin:u}=this.getProps();this.panSession=new Xut(t,{onSessionStart:i,onStart:l,onMove:o,onSessionEnd:c,resumeAnimation:d},{transformPagePoint:this.visualElement.getTransformPagePoint(),dragSnapToOrigin:u,distanceThreshold:r,contextWindow:Qut(this.visualElement),element:this.visualElement.current})}stop(t,n){const r=t||this.latestPointerEvent,a=n||this.latestPanInfo,i=this.isDragging;if(this.cancel(),!i||!a||!r)return;const{velocity:l}=a;this.startAnimation(l);const{onDragEnd:o}=this.getProps();o&&sd.postRender(()=>o(r,a))}cancel(){this.isDragging=!1;const{projection:t,animationState:n}=this.visualElement;t&&(t.isAnimationBlocked=!1),this.endPanSession();const{dragPropagation:r}=this.getProps();!r&&this.openDragLock&&(this.openDragLock(),this.openDragLock=null),n&&n.setActive("whileDrag",!1)}endPanSession(){this.panSession&&this.panSession.end(),this.panSession=void 0}updateAxis(t,n,r){const{drag:a}=this.getProps();if(!r||!eH(t,a,this.currentDirection))return;const i=this.getAxisMotionValue(t);let l=this.originPoint[t]+r[t];this.constraints&&this.constraints[t]&&(l=dXt(l,this.constraints[t],this.elastic[t])),i.set(l)}resolveConstraints(){var i;const{dragConstraints:t,dragElastic:n}=this.getProps(),r=this.visualElement.projection&&!this.visualElement.projection.layout?this.visualElement.projection.measure(!1):(i=this.visualElement.projection)==null?void 0:i.layout,a=this.constraints;t&&JI(t)?this.constraints||(this.constraints=this.resolveRefConstraints()):t&&r?this.constraints=uXt(r.layoutBox,t):this.constraints=!1,this.elastic=fXt(n),a!==this.constraints&&!JI(t)&&r&&this.constraints&&!this.hasMutatedConstraints&&D_(l=>{this.constraints!==!1&&this.getAxisMotionValue(l)&&(this.constraints[l]=pXt(r.layoutBox[l],this.constraints[l]))})}resolveRefConstraints(){const{dragConstraints:t,onMeasureDragConstraints:n}=this.getProps();if(!t||!JI(t))return!1;const r=t.current;v8(r!==null,"If `dragConstraints` is set as a React ref, that ref must be passed to another component's `ref` prop.","drag-constraints-ref");const{projection:a}=this.visualElement;if(!a||!a.layout)return!1;const i=vZt(r,a.root,this.visualElement.getTransformPagePoint());let l=hXt(a.layout.layoutBox,i);if(n){const o=n(xZt(l));this.hasMutatedConstraints=!!o,o&&(l=but(o))}return l}startAnimation(t){const{drag:n,dragMomentum:r,dragElastic:a,dragTransition:i,dragSnapToOrigin:l,onDragTransitionEnd:o}=this.getProps(),c=this.constraints||{},d=D_(u=>{if(!eH(u,n,this.currentDirection))return;let h=c&&c[u]||{};(l===!0||l===u)&&(h={min:0,max:0});const p=a?200:1e6,f=a?40:1e7,y={type:"inertia",velocity:r?t[u]:0,bounceStiffness:p,bounceDamping:f,timeConstant:750,restDelta:1,restSpeed:10,...i,...h};return this.startAxisValueAnimation(u,y)});return Promise.all(d).then(o)}startAxisValueAnimation(t,n){const r=this.getAxisMotionValue(t);return R4e(this.visualElement,t),r.start(vMe(t,r,0,n,this.visualElement,!1))}stopAnimation(){D_(t=>this.getAxisMotionValue(t).stop())}getAxisMotionValue(t){const n=`_drag${t.toUpperCase()}`,r=this.visualElement.getProps(),a=r[n];return a||this.visualElement.getValue(t,(r.initial?r.initial[t]:void 0)||0)}snapToCursor(t){D_(n=>{const{drag:r}=this.getProps();if(!eH(n,r,this.currentDirection))return;const{projection:a}=this.visualElement,i=this.getAxisMotionValue(n);if(a&&a.layout){const{min:l,max:o}=a.layout.layoutBox[n],c=i.get()||0;i.set(t[n]-Od(l,o,.5)+c)}})}scalePositionWithinConstraints(){if(!this.visualElement.current)return;const{drag:t,dragConstraints:n}=this.getProps(),{projection:r}=this.visualElement;if(!JI(n)||!r||!this.constraints)return;this.stopAnimation();const a={x:0,y:0};D_(l=>{const o=this.getAxisMotionValue(l);if(o&&this.constraints!==!1){const c=o.get();a[l]=mXt({min:c,max:c},this.constraints[l])}});const{transformTemplate:i}=this.visualElement.getProps();this.visualElement.current.style.transform=i?i({},""):"none",r.root&&r.root.updateScroll(),r.updateLayout(),this.constraints=!1,this.resolveConstraints(),D_(l=>{if(!eH(l,t,null))return;const o=this.getAxisMotionValue(l),{min:c,max:d}=this.constraints[l];o.set(Od(c,d,a[l]))}),this.visualElement.render()}addListeners(){if(!this.visualElement.current)return;xXt.set(this.visualElement,this);const t=this.visualElement.current,n=q9(t,"pointerdown",d=>{const{drag:u,dragListener:h=!0}=this.getProps(),p=d.target,f=p!==t&&ZYt(p);u&&h&&!f&&this.start(d)});let r;const a=()=>{const{dragConstraints:d}=this.getProps();JI(d)&&d.current&&(this.constraints=this.resolveRefConstraints(),r||(r=yXt(t,d.current,()=>this.scalePositionWithinConstraints())))},{projection:i}=this.visualElement,l=i.addEventListener("measure",a);i&&!i.layout&&(i.root&&i.root.updateScroll(),i.updateLayout()),sd.read(a);const o=iB(window,"resize",()=>this.scalePositionWithinConstraints()),c=i.addEventListener("didUpdate",({delta:d,hasLayoutChanged:u})=>{this.isDragging&&u&&(D_(h=>{const p=this.getAxisMotionValue(h);p&&(this.originPoint[h]+=d[h].translate,p.set(p.get()+d[h].translate))}),this.visualElement.render())});return()=>{o(),n(),l(),c&&c(),r&&r()}}getProps(){const t=this.visualElement.getProps(),{drag:n=!1,dragDirectionLock:r=!1,dragPropagation:a=!1,dragConstraints:i=!1,dragElastic:l=H4e,dragMomentum:o=!0}=t;return{...t,drag:n,dragDirectionLock:r,dragPropagation:a,dragConstraints:i,dragElastic:l,dragMomentum:o}}}function O$e(s){let t=!0;return()=>{if(t){t=!1;return}s()}}function yXt(s,t,n){const r=VBe(s,O$e(n)),a=VBe(t,O$e(n));return()=>{r(),a()}}function eH(s,t,n){return(t===!0||t===s)&&(n===null||n===s)}function vXt(s,t=10){let n=null;return Math.abs(s.y)>t?n="y":Math.abs(s.x)>t&&(n="x"),n}class bXt extends H4{constructor(t){super(t),this.removeGroupControls=Fv,this.removeListeners=Fv,this.controls=new gXt(t)}mount(){const{dragControls:t}=this.node.getProps();t&&(this.removeGroupControls=t.subscribe(this.controls)),this.removeListeners=this.controls.addListeners()||Fv}update(){const{dragControls:t}=this.node.getProps(),{dragControls:n}=this.node.prevProps||{};t!==n&&(this.removeGroupControls(),t&&(this.removeGroupControls=t.subscribe(this.controls)))}unmount(){this.removeGroupControls(),this.removeListeners(),this.controls.isDragging||this.controls.endPanSession()}}const cje=s=>(t,n)=>{s&&sd.update(()=>s(t,n),!1,!0)};class _Xt extends H4{constructor(){super(...arguments),this.removePointerDownListener=Fv}onPointerDown(t){this.session=new Xut(t,this.createPanHandlers(),{transformPagePoint:this.node.getTransformPagePoint(),contextWindow:Qut(this.node)})}createPanHandlers(){const{onPanSessionStart:t,onPanStart:n,onPan:r,onPanEnd:a}=this.node.getProps();return{onSessionStart:cje(t),onStart:cje(n),onMove:cje(r),onEnd:(i,l)=>{delete this.session,a&&sd.postRender(()=>a(i,l))}}}mount(){this.removePointerDownListener=q9(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 dje=!1;class wXt extends N.Component{componentDidMount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r,layoutId:a}=this.props,{projection:i}=t;i&&(n.group&&n.group.add(i),r&&r.register&&a&&r.register(i),dje&&i.root.didUpdate(),i.addEventListener("animationComplete",()=>{this.safeToRemove()}),i.setOptions({...i.options,layoutDependency:this.props.layoutDependency,onExitComplete:()=>this.safeToRemove()})),Cme.hasEverUpdated=!0}getSnapshotBeforeUpdate(t){const{layoutDependency:n,visualElement:r,drag:a,isPresent:i}=this.props,{projection:l}=r;return l&&(l.isPresent=i,t.layoutDependency!==n&&l.setOptions({...l.options,layoutDependency:n}),dje=!0,a||t.layoutDependency!==n||n===void 0||t.isPresent!==i?l.willUpdate():this.safeToRemove(),t.isPresent!==i&&(i?l.promote():l.relegate()||sd.postRender(()=>{const o=l.getStack();(!o||!o.members.length)&&this.safeToRemove()}))),null}componentDidUpdate(){const{visualElement:t,layoutAnchor:n}=this.props,{projection:r}=t;r&&(r.options.layoutAnchor=n,r.root.didUpdate(),NMe.postRender(()=>{!r.currentAnimation&&r.isLead()&&this.safeToRemove()}))}componentWillUnmount(){const{visualElement:t,layoutGroup:n,switchLayoutGroup:r}=this.props,{projection:a}=t;dje=!0,a&&(a.scheduleCheckAfterUnmount(),n&&n.group&&n.group.remove(a),r&&r.deregister&&r.deregister(a))}safeToRemove(){const{safeToRemove:t}=this.props;t&&t()}render(){return null}}function eht(s){const[t,n]=Uut(),r=N.useContext(aMe);return e.jsx(wXt,{...s,layoutGroup:r,switchLayoutGroup:N.useContext(Yut),isPresent:t,safeToRemove:n})}const jXt={pan:{Feature:_Xt},drag:{Feature:bXt,ProjectionNode:$ut,MeasureLayout:eht}};function F$e(s,t,n){const{props:r}=s;s.animationState&&r.whileHover&&s.animationState.setActive("whileHover",n==="Start");const a="onHover"+n,i=r[a];i&&sd.postRender(()=>i(t,tU(t)))}class NXt extends H4{mount(){const{current:t}=this.node;t&&(this.unmount=GYt(t,(n,r)=>(F$e(this.node,r,"Start"),a=>F$e(this.node,a,"End"))))}unmount(){}}class kXt extends H4{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=X$(iB(this.node.current,"focus",()=>this.onFocus()),iB(this.node.current,"blur",()=>this.onBlur()))}unmount(){}}function z$e(s,t,n){const{props:r}=s;if(s.current instanceof HTMLButtonElement&&s.current.disabled)return;s.animationState&&r.whileTap&&s.animationState.setActive("whileTap",n==="Start");const a="onTap"+(n==="End"?"":n),i=r[a];i&&sd.postRender(()=>i(t,tU(t)))}class SXt extends H4{mount(){const{current:t}=this.node;if(!t)return;const{globalTapTarget:n,propagate:r}=this.node.props;this.unmount=XYt(t,(a,i)=>(z$e(this.node,i,"Start"),(l,{success:o})=>z$e(this.node,l,o?"End":"Cancel")),{useGlobalTarget:n,stopPropagation:(r==null?void 0:r.tap)===!1})}unmount(){}}const G4e=new WeakMap,uje=new WeakMap,CXt=s=>{const t=G4e.get(s.target);t&&t(s)},TXt=s=>{s.forEach(CXt)};function EXt({root:s,...t}){const n=s||document;uje.has(n)||uje.set(n,{});const r=uje.get(n),a=JSON.stringify(t);return r[a]||(r[a]=new IntersectionObserver(TXt,{root:s,...t})),r[a]}function AXt(s,t,n){const r=EXt(t);return G4e.set(s,n),r.observe(s),()=>{G4e.delete(s),r.unobserve(s)}}const MXt={some:0,all:1};class IXt extends H4{constructor(){super(...arguments),this.hasEnteredView=!1,this.isInView=!1}startObserver(){var c;(c=this.stopObserver)==null||c.call(this);const{viewport:t={}}=this.node.getProps(),{root:n,margin:r,amount:a="some",once:i}=t,l={root:n?n.current:void 0,rootMargin:r,threshold:typeof a=="number"?a:MXt[a]},o=d=>{const{isIntersecting:u}=d;if(this.isInView===u||(this.isInView=u,i&&!u&&this.hasEnteredView))return;u&&(this.hasEnteredView=!0),this.node.animationState&&this.node.animationState.setActive("whileInView",u);const{onViewportEnter:h,onViewportLeave:p}=this.node.getProps(),f=u?h:p;f&&f(d)};this.stopObserver=AXt(this.node.current,l,o)}mount(){this.startObserver()}update(){if(typeof IntersectionObserver>"u")return;const{props:t,prevProps:n}=this.node;["amount","margin","root"].some(PXt(t,n))&&this.startObserver()}unmount(){var t;(t=this.stopObserver)==null||t.call(this),this.hasEnteredView=!1,this.isInView=!1}}function PXt({viewport:s={}},{viewport:t={}}={}){return n=>s[n]!==t[n]}const LXt={inView:{Feature:IXt},tap:{Feature:SXt},focus:{Feature:kXt},hover:{Feature:NXt}},DXt={layout:{ProjectionNode:$ut,MeasureLayout:eht}},RXt={...aXt,...LXt,...jXt,...DXt},Zn=eXt(RXt,tXt),OXt={some:0,all:1};function FXt(s,t,{root:n,margin:r,amount:a="some"}={}){const i=jMe(s),l=new WeakMap,o=d=>{d.forEach(u=>{const h=l.get(u.target);if(u.isIntersecting!==!!h)if(u.isIntersecting){const p=t(u.target,u);typeof p=="function"?l.set(u.target,p):c.unobserve(u.target)}else typeof h=="function"&&(h(u),l.delete(u.target))})},c=new IntersectionObserver(o,{root:n,rootMargin:r,threshold:typeof a=="number"?a:OXt[a]});return i.forEach(d=>c.observe(d)),()=>c.disconnect()}function zXt(s,{root:t,margin:n,amount:r,once:a=!1,initial:i=!1}={}){const[l,o]=N.useState(i);return N.useEffect(()=>{if(!s.current||a&&l)return;const c=()=>(o(!0),a?void 0:()=>o(!1)),d={root:t&&t.current||void 0,margin:n,amount:r};return FXt(s.current,c,d)},[t,s,n,a,r]),l}function BXt(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 B$e(s){return s.visitor_intent==="buying"&&!s.has_agent}function $Xt({token:s}={}){var y;const t=bi(),n=s||t.token,{data:r,isLoading:a,isError:i}=kWt(n),l=Kt(),o=(y=r==null?void 0:r.open_houses)==null?void 0:y.id,{data:c}=dt({queryKey:["cohost-visitors",o],queryFn:async()=>{const{data:_,error:v}=await q.from("open_house_visitors").select("*").eq("open_house_id",o).order("created_at",{ascending:!1});if(v)throw v;return _},enabled:!!o});if(N.useEffect(()=>{if(!o)return;const _=q.channel(`cohost-visitors-${o}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"open_house_visitors",filter:`open_house_id=eq.${o}`},()=>{l.invalidateQueries({queryKey:["cohost-visitors",o]})}).subscribe();return()=>{q.removeChannel(_)}},[o,l]),a)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center",children:e.jsx("div",{className:"animate-pulse text-white/40",children:"Validating access..."})});if(i||!r)return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-950 via-slate-900 to-slate-950 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-xl font-bold mb-2",children:"Link Expired or Invalid"}),e.jsx("p",{className:"text-white/40 text-sm",children:"This co-host link is no longer active. Ask the host for a new one."})]})});const d=r.open_houses,u=(c==null?void 0:c.length)||0,h=(c==null?void 0:c.filter(_=>_.visitor_intent==="buying").length)||0,p=(c==null?void 0:c.filter(B$e).length)||0,f=_=>{if(!_)return"";const[v,j]=_.split(":"),w=parseInt(v);return`${w>12?w-12:w||12}:${j} ${w>=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(An,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:u})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-orange-400",children:[e.jsx(Hc,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:p})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Or,{className:"h-4 w-4"}),e.jsx("span",{className:"font-bold text-white",children:h})]})]})]}),e.jsxs("div",{className:"px-4 sm:px-6 py-2 flex items-center gap-4 text-xs text-white/40 border-b border-white/5",children:[e.jsx("span",{children:Ss(new Date(d.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy")}),d.start_time&&e.jsxs("span",{children:[f(d.start_time),d.end_time?` – ${f(d.end_time)}`:""]})]}),e.jsx(di,{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(pye,{children:c.map((_,v)=>{var S;const j=BXt(_.visitor_intent),w=B$e(_);return e.jsxs(Zn.div,{initial:{opacity:0,x:-40,scale:.95},animate:{opacity:1,x:0,scale:1},transition:{duration:.4,delay:v*.05},className:`flex items-center gap-4 p-4 rounded-xl border ${w?"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 ${w?"bg-gradient-to-br from-orange-500 to-amber-500 text-white":"bg-white/10 text-white/80"}`,children:(S=_.first_name[0])==null?void 0:S.toUpperCase()}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{className:"font-semibold text-white truncate",children:[_.first_name," ",_.last_name||""]}),w&&e.jsx(Ue,{className:"bg-orange-500/20 text-orange-300 border-orange-500/40 text-[10px] px-1.5 py-0",children:"🔥 HOT"}),_.has_agent&&e.jsx(Ue,{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(Ue,{variant:"outline",className:`text-[10px] px-1.5 py-0 ${j.color}`,children:[j.emoji," ",j.label]}),e.jsx("span",{className:"text-white/30 text-xs",children:Ss(new Date(_.created_at),"h:mm a")})]})]})]},_.id)})})}):e.jsxs("div",{className:"flex flex-col items-center justify-center h-full text-center py-20",children:[e.jsx("div",{className:"w-20 h-20 rounded-full bg-white/5 flex items-center justify-center mb-4",children:e.jsx(yf,{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 UXt(){const t=Xl().pathname.slice(1);if(N.useEffect(()=>(document.body.classList.add("guestbook-page"),()=>{document.body.classList.remove("guestbook-page")}),[]),t.startsWith("live/")){const n=t.slice(5);if(n)return e.jsx($Xt,{token:n})}return!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Guest Book"}),e.jsx("p",{className:"text-white/60",children:"The modern open house sign-in experience."}),e.jsx("p",{className:"text-white/40 text-sm mt-2",children:"Visit a specific open house link to sign in."})]})}):e.jsx(sdt,{slug:t})}function qXt({dealData:s,agentProfile:t,welcomeMessage:n,isWon:r,branding:a}){var d;const i=s!=null&&s.property_address?`${s.property_address}, ${s.city||""}, ${s.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,l=(a==null?void 0:a.logo_url)||null,o=(a==null?void 0:a.cover_photo_url)||null,c=(a==null?void 0:a.tagline)||"Your Real Estate Concierge";return e.jsxs("div",{className:"relative overflow-hidden",children:[e.jsxs("div",{className:"relative px-4 pt-10 pb-20",children:[o&&e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${o})`,backgroundSize:"cover",backgroundPosition:"center",filter:"grayscale(0.4) brightness(0.45)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:o?"linear-gradient(180deg, hsl(0 0% 3% / 0.85) 0%, hsl(0 0% 5% / 0.75) 50%, hsl(0 0% 5%) 100%)":"radial-gradient(ellipse 100% 70% at 50% 0%, hsl(var(--portal-gold) / 0.12), transparent 60%), linear-gradient(180deg, hsl(0 0% 7%), hsl(0 0% 4%))"}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.05]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, hsl(var(--portal-gold)) 1px, transparent 1px)",backgroundSize:"32px 32px"}}),e.jsxs("div",{className:"relative text-center max-w-lg mx-auto",children:[l&&e.jsx(Zn.div,{initial:{opacity:0,y:-8},animate:{opacity:1,y:0},transition:{duration:.5},className:"mb-6 flex justify-center",children:e.jsx("div",{className:"rounded-xl px-4 py-2.5",style:{background:"hsl(0 0% 100% / 0.06)",backdropFilter:"blur(8px)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:l,alt:"Brand",className:"h-9 max-w-[160px] object-contain"})})}),t&&e.jsxs(Zn.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.5,delay:.05},className:"mb-6",children:[t.avatar_url?e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:t.avatar_url,alt:t.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-20 h-20 mx-auto mb-3 rounded-full flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"hsl(var(--portal-gold))"},children:((d=t.name)==null?void 0:d.charAt(0))||"?"}),e.jsx("p",{className:"portal-serif text-lg",style:{color:"hsl(var(--portal-ink))"},children:t.name}),e.jsx("p",{className:"text-[10px] mt-1 tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:c})]}),e.jsxs(Zn.div,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6,delay:.1},children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.2em] uppercase mb-4",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.25)",color:"hsl(var(--portal-gold))"},children:[e.jsx(Or,{className:"w-3 h-3"}),(s==null?void 0:s.deal_type)==="listing"?"Sale":(s==null?void 0:s.deal_type)==="buy-side"?"Purchase":"Transaction",r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif text-[2.5rem] leading-[1.05] mb-3",style:{color:"hsl(var(--portal-ink))"},children:(s==null?void 0:s.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-24 mx-auto mb-4"}),i&&e.jsxs("div",{className:"flex items-center justify-center gap-1.5 text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:[e.jsx(ka,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}),e.jsx("span",{children:i})]}),n&&e.jsxs("p",{className:"mt-6 text-sm leading-relaxed max-w-md mx-auto italic portal-serif",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1.05rem"},children:["“",n,"”"]})]})]})]}),t&&e.jsx("div",{className:"max-w-lg mx-auto px-4 -mt-10 relative z-10",children:e.jsx("div",{className:"rounded-2xl p-3",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.2)",boxShadow:"var(--portal-shadow-tile)"},children:e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[t.phone&&e.jsxs("a",{href:`tel:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Cr,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Call"})]}),t.email&&e.jsxs("a",{href:`mailto:${t.email}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Gs,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Email"})]}),t.phone&&e.jsxs("a",{href:`sms:${t.phone}`,className:"flex-1 flex items-center justify-center gap-2 px-3 py-2.5 rounded-xl transition-colors",style:{background:"hsl(var(--portal-gold) / 0.06)",color:"hsl(var(--portal-gold))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx(Zl,{className:"w-4 h-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Text"})]})]})})})]})}function tht({targetCloseDate:s,actualCloseDate:t,clientName:n}){if(t||!s)return null;const r=s.split(/[-/T]/),a=new Date(Number(r[0]),Number(r[1])-1,Number(r[2])),l=Vv(a,new Date);if(vw(a)&&!of(a))return null;const o=of(a),c=o?"0":String(Math.max(0,l)),d=Math.max(4,Math.min(100,(60-Math.min(60,l))/60*100));return e.jsxs("div",{className:"portal-tile p-8 text-center",children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:o?"The Moment Has Arrived":"Countdown to Closing"}),o?e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"portal-serif text-5xl mb-2",style:{color:"hsl(var(--portal-gold))"},children:"Closing Day"}),e.jsxs("p",{className:"text-sm mt-3",style:{color:"hsl(var(--portal-ink-muted))"},children:["Congratulations",n?`, ${n.split(" ")[0]}`:"","."]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-baseline justify-center gap-3",children:[e.jsx(Zn.span,{initial:{opacity:0,y:8},animate:{opacity:1,y:0},transition:{duration:.6},className:"portal-serif tabular-nums leading-none",style:{fontSize:"5.5rem",color:"hsl(var(--portal-gold))",textShadow:"0 0 40px hsl(var(--portal-gold) / 0.4)"},children:c}),e.jsx("span",{className:"portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink-muted))"},children:l===1?"day":"days"})]}),e.jsx("div",{className:"portal-hairline w-16 mx-auto my-4"}),e.jsx("p",{className:"text-xs tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-muted))"},children:"Until you hold the keys"}),e.jsx("div",{className:"mt-6 mx-auto max-w-[260px]",children:e.jsx("div",{className:"h-[2px] rounded-full overflow-hidden",style:{background:"hsl(var(--portal-gold) / 0.15)"},children:e.jsx(Zn.div,{initial:{width:0},animate:{width:`${d}%`},transition:{duration:1.2,ease:"easeOut"},className:"h-full rounded-full",style:{background:"var(--portal-gradient-gold)",boxShadow:"0 0 12px hsl(var(--portal-gold) / 0.6)"}})})})]})]})}function sht({journeyStages:s,currentIndex:t}){return s.length===0?null:e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"The Journey"}),e.jsx("h2",{className:"portal-serif text-2xl mb-6",style:{color:"hsl(var(--portal-ink))"},children:"Your path to the keys"}),e.jsx("div",{className:"relative",children:s.map((n,r)=>{const a=rt;return e.jsxs(Zn.div,{initial:{opacity:0,x:-6},animate:{opacity:1,x:0},transition:{duration:.35,delay:r*.05},className:"flex items-start gap-4 relative",children:[r{var l,o;if(i.includes("youtube.com/watch")){const c=new URL(i).searchParams.get("v");return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("youtu.be/")){const c=(l=i.split("youtu.be/")[1])==null?void 0:l.split("?")[0];return c?`https://www.youtube.com/embed/${c}`:null}if(i.includes("loom.com/share/")){const c=(o=i.split("loom.com/share/")[1])==null?void 0:o.split("?")[0];return c?`https://www.loom.com/embed/${c}`:null}return i};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Right Now"}),e.jsx("h4",{className:"portal-serif text-3xl mb-2 portal-gold-underline",style:{color:"hsl(var(--portal-ink))"},children:s.label}),e.jsx("p",{className:"text-sm leading-relaxed mt-4",style:{color:"hsl(var(--portal-ink-muted))"},children:s.description}),t&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Note From Your Agent"}),e.jsxs("p",{className:"text-sm leading-relaxed portal-serif italic",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:["“",t,"”"]})]}),n&&e.jsxs("div",{className:"mt-5 rounded-xl p-4",style:{background:"linear-gradient(135deg, hsl(var(--portal-gold) / 0.08), hsl(var(--portal-gold) / 0.02))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"What’s Next"}),e.jsx("p",{className:"text-sm leading-relaxed",style:{color:"hsl(var(--portal-ink))"},children:n})]}),r&&e.jsx("div",{className:"mt-5 rounded-xl overflow-hidden aspect-video relative group",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("iframe",{src:a(r)||r,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Next step video"})})]})}function Ll(s){const t=s.split(/[-/T]/);if(t.length>=3){const n=Number(t[0]);return n>99?new Date(n,Number(t[1])-1,Number(t[2])):new Date(Number(t[2]),Number(t[0])-1,Number(t[1]))}return new Date(`${s}T12:00:00`)}function VXt(s,t){const n=Ss(t,"yyyyMMdd");return`https://calendar.google.com/calendar/render?${new URLSearchParams({action:"TEMPLATE",text:s,dates:`${n}/${n}`,details:"Added from your Client Portal"}).toString()}`}function HXt(s,t){const n=Ss(t,"yyyyMMdd");return`data:text/calendar;charset=utf-8,${encodeURIComponent(`BEGIN:VCALENDAR VERSION:2.0 BEGIN:VEVENT DTSTART;VALUE=DATE:${n} DTEND;VALUE=DATE:${n} SUMMARY:${s} DESCRIPTION:Added from your Client Portal END:VEVENT END:VCALENDAR`)}`}function rht({targetCloseDate:s,contractDate:t,inspectionDate:n,appraisalDate:r,actualCloseDate:a}){const i=[{label:"Contract",date:t,icon:KP},{label:"Inspection",date:n,icon:gr},{label:"Appraisal",date:r,icon:Or},{label:a?"Closed":"Target Close",date:a||s,icon:yr}].filter(o=>o.date);if(i.length===0)return null;const l=(o,c,d)=>{const u=Ll(c);if(d==="google")window.open(VXt(o,u),"_blank");else{const h=HXt(o,u),p=document.createElement("a");p.href=h,p.download=`${o.replace(/\s+/g,"-").toLowerCase()}.ics`,p.click()}};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Milestones"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Key dates"}),e.jsxs("div",{className:"space-y-4 relative",children:[e.jsx("div",{className:"absolute left-[7px] top-2 bottom-2 w-[1px]",style:{background:"hsl(var(--portal-gold) / 0.15)"}}),i.map(({label:o,date:c,icon:d})=>{const u=Ll(c),h=vw(u)&&!of(u),p=of(u),f=!h&&!p;return e.jsxs("div",{className:"flex items-start gap-3 relative",children:[e.jsx("div",{className:"w-[15px] h-[15px] rounded-full mt-1 flex-shrink-0 relative z-10",style:{background:h?"hsl(var(--portal-gold) / 0.4)":p?"hsl(var(--portal-gold))":"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold))",boxShadow:p?"0 0 12px hsl(var(--portal-gold) / 0.6)":"none"}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:o}),e.jsxs("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.15rem",color:h?"hsl(var(--portal-ink-muted))":"hsl(var(--portal-ink))"},children:[Ss(u,"MMM d, yyyy"),p&&e.jsx("span",{className:"ml-2 text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-gold))"},children:"Today"})]})]}),f&&e.jsxs("div",{className:"flex items-center gap-1 mt-1",children:[e.jsx("button",{onClick:()=>l(o,c,"google"),className:"p-1.5 rounded transition-colors",style:{color:"hsl(var(--portal-ink-dim))"},onMouseEnter:y=>{y.currentTarget.style.color="hsl(var(--portal-gold))"},onMouseLeave:y=>{y.currentTarget.style.color="hsl(var(--portal-ink-dim))"},title:"Add to Google Calendar",children:e.jsx(Lg,{className:"w-3.5 h-3.5"})}),e.jsx("button",{onClick:()=>l(o,c,"apple"),className:"text-[9px] tracking-widest px-1.5 py-1 rounded",style:{color:"hsl(var(--portal-ink-dim))"},title:"Download .ics",children:".ICS"})]})]},o)})]})]})}function aht({documents:s}){const t=r=>r<1024?`${r} B`:r<1048576?`${(r/1024).toFixed(0)} KB`:`${(r/1048576).toFixed(1)} MB`,n=async r=>{const{data:a}=await q.storage.from("deal-files").createSignedUrl(r.storage_path,300);a!=null&&a.signedUrl&&window.open(a.signedUrl,"_blank")};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Paperwork"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Documents"}),e.jsx("div",{className:"space-y-2",children:s.map(r=>e.jsxs("button",{onClick:()=>n(r),className:"w-full flex items-center gap-3 p-3 rounded-xl transition-all text-left group",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.08)"},onMouseEnter:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.35)"},onMouseLeave:a=>{a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.08)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center flex-shrink-0",style:{background:"hsl(var(--portal-gold) / 0.08)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx(br,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm portal-serif truncate",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:r.file_name}),e.jsx("p",{className:"text-[10px] tracking-widest uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:t(r.file_size)})]}),e.jsx(Ia,{className:"w-4 h-4 flex-shrink-0",style:{color:"hsl(var(--portal-gold) / 0.5)"}})]},r.id))})]})}function iht({updates:s}){const t=n=>{var r,a;if(n.includes("youtube.com/watch")){const i=new URL(n).searchParams.get("v");return i?`https://www.youtube.com/embed/${i}`:null}if(n.includes("youtu.be/")){const i=(r=n.split("youtu.be/")[1])==null?void 0:r.split("?")[0];return i?`https://www.youtube.com/embed/${i}`:null}if(n.includes("loom.com/share/")){const i=(a=n.split("loom.com/share/")[1])==null?void 0:a.split("?")[0];return i?`https://www.loom.com/embed/${i}`:null}return n};return e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow mb-2",children:"Dispatch"}),e.jsx("h2",{className:"portal-serif text-2xl mb-5",style:{color:"hsl(var(--portal-ink))"},children:"Updates from your agent"}),e.jsx("div",{className:"space-y-6",children:s.map((n,r)=>e.jsx("div",{className:r>0?"pt-6":"",style:r>0?{borderTop:"1px solid hsl(var(--portal-gold) / 0.1)"}:void 0,children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-full flex items-center justify-center flex-shrink-0 mt-0.5",style:{background:n.is_stage_change?"hsl(var(--portal-gold) / 0.15)":"hsl(var(--portal-surface-3))",border:"1px solid hsl(var(--portal-gold) / 0.25)"},children:n.is_stage_change?e.jsx(ah,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}}):e.jsx(nm,{className:"w-3.5 h-3.5",style:{color:"hsl(var(--portal-gold))"}})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-baseline justify-between gap-2",children:[e.jsx("h3",{className:"portal-serif",style:{fontSize:r===0?"1.4rem":"1.15rem",color:"hsl(var(--portal-ink))"},children:n.title}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase flex-shrink-0",style:{color:"hsl(var(--portal-ink-dim))"},children:Ss(new Date(n.created_at),"MMM d")})]}),n.content&&e.jsx("p",{className:`text-sm mt-2 leading-relaxed ${r===0?"italic portal-serif":""}`,style:{color:"hsl(var(--portal-ink-muted))",fontSize:r===0?"1rem":"0.875rem"},children:r===0?`“${n.content}”`:n.content}),n.video_url&&e.jsx("div",{className:"mt-3 rounded-xl overflow-hidden aspect-video",style:{background:"hsl(var(--portal-bg))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:e.jsx("iframe",{src:t(n.video_url)||n.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:n.title})})]})]})},n.id))})]})}const fe=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("rounded-lg border bg-card text-card-foreground shadow-sm",s),...t}));fe.displayName="Card";const It=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("flex flex-col space-y-1.5 p-6",s),...t}));It.displayName="CardHeader";const Rt=N.forwardRef(({className:s,...t},n)=>e.jsx("h3",{ref:n,className:Mt("text-2xl font-semibold leading-none tracking-tight",s),...t}));Rt.displayName="CardTitle";const Vn=N.forwardRef(({className:s,...t},n)=>e.jsx("p",{ref:n,className:Mt("text-sm text-muted-foreground",s),...t}));Vn.displayName="CardDescription";const Ee=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("p-6 pt-0",s),...t}));Ee.displayName="CardContent";const V9=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("flex items-center p-6 pt-0",s),...t}));V9.displayName="CardFooter";const $D=[{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"}],GXt=[{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 WXt(s){return dt({queryKey:["vendors","brokerage",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("vendors").select("*").eq("owner_type","brokerage").eq("owner_brokerage_id",s).order("sort_order",{ascending:!0}).order("name",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function KXt(){const s=wa(),{brokerageId:t}=vs();return dt({queryKey:["vendors","library",s,t],queryFn:async()=>{if(!s)return{vendors:[],selections:[]};let n=q.from("vendors").select("*");t?n=n.or(`and(owner_type.eq.agent,owner_user_id.eq.${s}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${t})`):n=n.eq("owner_type","agent").eq("owner_user_id",s);const[{data:r,error:a},{data:i,error:l}]=await Promise.all([n.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("*").eq("agent_user_id",s)]);if(a)throw a;if(l)throw l;return{vendors:r||[],selections:i||[]}},enabled:!!s})}function YXt(){const s=Kt();return yt({mutationFn:async t=>{if(t.id){const{id:n,created_at:r,...a}=t,{data:i,error:l}=await q.from("vendors").update(a).eq("id",n).select().single();if(l)throw l;return i}else{const{data:n,error:r}=await q.from("vendors").insert(t).select().single();if(r)throw r;return n}},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function oht(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("vendors").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["vendors"]})})}function ZXt(){const s=wa(),t=Kt();return yt({mutationFn:async({vendorId:n,isVisible:r})=>{if(!s)throw new Error("No user");const{data:a}=await q.from("agent_vendor_selections").select("id").eq("agent_user_id",s).eq("vendor_id",n).maybeSingle();if(a){const{error:i}=await q.from("agent_vendor_selections").update({is_visible:r}).eq("id",a.id);if(i)throw i}else{const{error:i}=await q.from("agent_vendor_selections").insert({agent_user_id:s,vendor_id:n,is_visible:r});if(i)throw i}},onSuccess:()=>t.invalidateQueries({queryKey:["vendors"]})})}function lht(s){return dt({queryKey:["portal-vendors",s==null?void 0:s.id,s==null?void 0:s.owner_user_id],queryFn:async()=>{if(!(s!=null&&s.id)||!(s!=null&&s.owner_user_id))return[];const t=s.owner_user_id,{data:n}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),r=n==null?void 0:n.brokerage_id,a=q.from("vendors").select("*").eq("is_active",!0),i=r?a.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${r})`):a.eq("owner_type","agent").eq("owner_user_id",t),[{data:l,error:o},{data:c},{data:d}]=await Promise.all([i.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, display_order, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s.id)]);if(o)throw o;const u=new Map;(c||[]).forEach(f=>u.set(f.vendor_id,{display_order:f.display_order,is_visible:f.is_visible}));const h=new Map;return(d||[]).forEach(f=>h.set(f.vendor_id,f.is_visible)),(l||[]).filter(f=>{if(h.get(f.id)===!1)return!1;const y=u.get(f.id);return!(y&&y.is_visible===!1&&!f.is_required)}).map(f=>{var y;return{...f,display_order:((y=u.get(f.id))==null?void 0:y.display_order)??f.sort_order??0}}).sort((f,y)=>(f.display_order||0)-(y.display_order||0))},enabled:!!(s!=null&&s.id)&&!!(s!=null&&s.owner_user_id)})}async function $$e(s){try{await q.from("vendor_clicks").insert({vendor_id:s.vendorId,portal_id:s.portalId||null,agent_user_id:s.agentUserId||null,action_taken:s.actionTaken||null,user_agent:typeof navigator<"u"?navigator.userAgent.slice(0,500):null})}catch(t){console.warn("vendor click track failed",t)}}function cht(s,t){return dt({queryKey:["vendor-clicks",s,t],queryFn:async()=>{if(!t)return{};const{data:n}=await q.from("vendors").select("id").eq(s==="agent"?"owner_user_id":"owner_brokerage_id",t).eq("owner_type",s),r=(n||[]).map(l=>l.id);if(r.length===0)return{};const{data:a}=await q.from("vendor_clicks").select("vendor_id").in("vendor_id",r),i={};return(a||[]).forEach(l=>{i[l.vendor_id]=(i[l.vendor_id]||0)+1}),i},enabled:!!t})}function dht({portalId:s,ownerUserId:t,currentStage:n,brandingColor:r,layout:a="list"}){const{data:i=[],isLoading:l}=lht({id:s,owner_user_id:t});if(l||i.length===0)return null;const o=i.filter(w=>!w.stage_filter||w.stage_filter.length===0||!n?!0:w.stage_filter.includes(n));if(o.length===0)return null;const c=r||"#406E71",d=(w,S)=>{switch(S){case"book":return w.booking_url;case"website":return w.website;case"call":return w.phone?`tel:${w.phone.replace(/[^\d+]/g,"")}`:null;case"email":case"quote":return w.email?`mailto:${w.email}`:null}},u=w=>{const S=d(w,w.action_type);$$e({vendorId:w.id,portalId:s,agentUserId:t,actionTaken:w.action_type}),S&&window.open(S,w.action_type==="call"||w.action_type==="email"||w.action_type==="quote"?"_self":"_blank")},h=w=>{const S=d(w,w.action_type);return[{action:"website",label:"Website",icon:e.jsx(lc,{className:"w-3.5 h-3.5"})},{action:"email",label:"Email",icon:e.jsx(Gs,{className:"w-3.5 h-3.5"})},{action:"call",label:"Call",icon:e.jsx(Cr,{className:"w-3.5 h-3.5"})},{action:"book",label:"Book",icon:e.jsx(yr,{className:"w-3.5 h-3.5"})}].filter(E=>E.action!==w.action_type).map(E=>{const O=d(w,E.action);return!O||O===S?null:e.jsxs("button",{onClick:()=>{$$e({vendorId:w.id,portalId:s,agentUserId:t,actionTaken:E.action}),window.open(O,E.action==="call"||E.action==="email"?"_self":"_blank")},className:"inline-flex items-center gap-1 text-slate-500 hover:text-slate-700 hover:underline",title:E.label,children:[E.icon,e.jsx("span",{className:"text-xs",children:E.label})]},E.action)}).filter(Boolean)},p=w=>{switch(w.action_type){case"book":return"Book Now";case"quote":return"Request Quote";case"call":return"Call";case"email":return"Email";case"website":return"Visit Site"}},f=w=>{switch(w.action_type){case"book":return e.jsx(yr,{className:"w-3.5 h-3.5"});case"call":return e.jsx(Cr,{className:"w-3.5 h-3.5"});case"email":case"quote":return e.jsx(Gs,{className:"w-3.5 h-3.5"});case"website":return e.jsx(lc,{className:"w-3.5 h-3.5"})}},y=w=>{var S;return((S=$D.find(A=>A.value===w))==null?void 0:S.label)||w},_=e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center",style:{backgroundColor:`${c}15`,color:c},children:e.jsx(un,{className:"w-4 h-4"})}),e.jsxs("div",{children:[e.jsx("h2",{className:"font-semibold text-slate-800",children:"Trusted Partners"}),e.jsx("p",{className:"text-xs text-slate-500",children:"My personally-vetted recommendations for you"})]})]}),v=o.some(w=>w.disclosure_text)&&e.jsx("div",{className:"mt-4 pt-3 border-t border-slate-100 space-y-1",children:o.filter(w=>w.disclosure_text).map(w=>e.jsxs("p",{className:"text-[10px] text-slate-400",children:[e.jsxs("span",{className:"font-medium",children:[w.company||w.name,":"]})," ",w.disclosure_text]},w.id))});if(a==="grid")return e.jsxs(fe,{className:"p-5 sm:p-6 rounded-2xl border-slate-200/80 shadow-sm bg-white/70 backdrop-blur",children:[_,e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3",children:o.map(w=>e.jsxs("div",{className:"group flex flex-col p-4 rounded-xl border border-slate-200/70 bg-white hover:shadow-md hover:-translate-y-0.5 transition-all",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-slate-50 border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:w.logo_url?e.jsx("img",{src:w.logo_url,alt:w.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-base font-semibold text-slate-500",children:(w.company||w.name).charAt(0)})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-semibold text-sm text-slate-800 truncate",children:w.company||w.name}),w.company&&w.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:w.name}),e.jsx("span",{className:"inline-block mt-1 text-[10px] font-medium px-1.5 py-0.5 rounded",style:{backgroundColor:`${c}12`,color:c},children:y(w.category)})]})]}),w.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-3 line-clamp-2",children:w.description}),e.jsxs("div",{className:"mt-auto pt-4 flex flex-col gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>u(w),style:{backgroundColor:c},className:"text-white hover:opacity-90 w-full",children:[f(w),e.jsx("span",{className:"ml-1.5 text-xs",children:p(w)})]}),h(w).length>0&&e.jsx("div",{className:"flex flex-wrap items-center justify-center gap-3",children:h(w)})]})]},w.id))}),v]});const j=o.reduce((w,S)=>((w[S.category]=w[S.category]||[]).push(S),w),{});return e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200/80 shadow-sm",children:[_,e.jsx("div",{className:"space-y-4",children:Object.entries(j).map(([w,S])=>e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-slate-400 font-medium mb-2",children:y(w)}),e.jsx("div",{className:"space-y-2",children:S.map(A=>e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-xl bg-slate-50 hover:bg-slate-100 transition-colors",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-white border border-slate-200 flex items-center justify-center overflow-hidden shrink-0",children:A.logo_url?e.jsx("img",{src:A.logo_url,alt:A.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-slate-500",children:A.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm text-slate-800 truncate",children:A.company||A.name}),A.company&&A.name&&e.jsx("p",{className:"text-xs text-slate-500 truncate",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-slate-500 truncate mt-0.5",children:A.description})]}),e.jsxs(B,{size:"sm",onClick:()=>u(A),style:{backgroundColor:c},className:"text-white hover:opacity-90 shrink-0",children:[f(A),e.jsx("span",{className:"ml-1.5 text-xs",children:p(A)})]})]},A.id))})]},w))}),v]})}function QXt(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 XXt(s){if(!s)return null;const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([\w-]+)/);if(t)return`https://www.youtube.com/embed/${t[1]}`;const n=s.match(/loom\.com\/share\/([\w-]+)/);return n?`https://www.loom.com/embed/${n[1]}`:(s.match(/\.(mp4|webm|mov)(\?|$)/i),s)}function uht({portalId:s,portalSlug:t,ownerUserId:n,rewardText:r,ctaHeadline:a,agentName:i,clientName:l,reviewUrl:o,hubVideoUrl:c}){const[d,u]=N.useState(!1),h=N.useRef(!1),p=QXt(t);N.useEffect(()=>{h.current||(h.current=!0,q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:"card_view",user_agent:navigator.userAgent.slice(0,500)}).then(()=>{}))},[s,n]);const f=async O=>{await q.from("portal_referral_clicks").insert({portal_id:s,owner_user_id:n,click_type:O,user_agent:navigator.userAgent.slice(0,500)})},y=()=>`${l?`Hey, it's ${l}!`:"Hey!"} I just had an amazing experience working with ${i||"my real estate agent"} on my home. If you or someone you know is thinking about buying or selling, here's their referral link: ${p}`,_=async()=>{await navigator.clipboard.writeText(p),u(!0),f("copy_link"),setTimeout(()=>u(!1),2e3)},v=()=>{f("share_sms");const O=encodeURIComponent(y());window.location.href=`sms:?&body=${O}`},j=()=>{f("share_email");const O=encodeURIComponent("A referral you'll thank me for"),D=encodeURIComponent(y());window.location.href=`mailto:?subject=${O}&body=${D}`},w=()=>{f("open_form"),window.open(p,"_blank")},S=a||"Know someone buying or selling?",A=c?XXt(c):null,E=A==null?void 0:A.match(/\.(mp4|webm|mov)(\?|$)/i);return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-gradient-to-br from-emerald-50 via-teal-50 to-cyan-50 rounded-2xl p-6 border border-emerald-100 text-center",children:[e.jsx("div",{className:"text-5xl mb-2",children:"🎉"}),e.jsxs("h3",{className:"text-xl font-bold text-emerald-900 mb-1 font-serif",children:["Welcome Home",l?`, ${l.split(" ")[0]}`:"","!"]}),e.jsx("p",{className:"text-sm text-emerald-700/80",children:"Your transaction is complete. We're so proud to have been part of your journey."})]}),A&&e.jsxs("div",{className:"bg-white rounded-2xl border border-slate-100 shadow-sm overflow-hidden",children:[e.jsx("div",{className:"px-4 pt-4 pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"w-4 h-4 text-[#406E71]"}),e.jsxs("p",{className:"text-sm font-medium text-slate-700",children:["A message from ",i||"your agent"]})]})}),e.jsx("div",{className:"aspect-video bg-slate-900",children:E?e.jsx("video",{src:A,controls:!0,className:"w-full h-full",playsInline:!0}):e.jsx("iframe",{src:A,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] via-[#345e7a] to-[#406E71] text-white shadow-xl",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.07]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px)",backgroundSize:"20px 20px"}}),e.jsxs("div",{className:"relative p-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/15 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium mb-3",children:[e.jsx(Oi,{className:"w-3 h-3"}),"Referral Program"]}),e.jsx("h3",{className:"text-xl font-bold leading-tight mb-2 font-serif",children:S}),r&&e.jsxs("p",{className:"text-sm text-white/85 mb-1",children:[e.jsx("span",{className:"font-semibold text-white",children:"Your reward:"})," ",r]}),e.jsxs("p",{className:"text-sm text-white/70 mb-5 leading-relaxed",children:["The biggest compliment you can give ",i||"us"," is sending a friend or family member."]}),e.jsxs("button",{onClick:w,className:"w-full bg-white text-[#2a4c64] font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 shadow-md hover:bg-white/95 active:scale-[0.99] transition-all",children:["Refer a Friend",e.jsx(Oa,{className:"w-4 h-4"})]}),e.jsxs("div",{className:"mt-4 grid grid-cols-3 gap-2",children:[e.jsxs("button",{onClick:v,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Zl,{className:"w-3.5 h-3.5"}),"Text"]}),e.jsxs("button",{onClick:j,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[e.jsx(Gs,{className:"w-3.5 h-3.5"}),"Email"]}),e.jsxs("button",{onClick:_,className:"flex items-center justify-center gap-1.5 bg-white/10 hover:bg-white/20 backdrop-blur-sm rounded-lg py-2.5 text-xs font-medium transition-colors",children:[d?e.jsx(Lr,{className:"w-3.5 h-3.5"}):e.jsx(Zr,{className:"w-3.5 h-3.5"}),d?"Copied":"Copy"]})]})]})]}),o&&e.jsx("a",{href:o,target:"_blank",rel:"noopener noreferrer",onClick:()=>f("review_click"),className:"block bg-white border border-slate-200 hover:border-amber-300 hover:bg-amber-50/30 rounded-2xl p-4 transition-colors",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"text-2xl",children:"⭐"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-800",children:"Loved working together?"}),e.jsx("p",{className:"text-xs text-slate-500",children:"Leave a quick review — it means the world."})]}),e.jsx(Oa,{className:"w-4 h-4 text-slate-400"})]})})]})}function JXt(s){return s==="buy-side"?"Home Search in Progress":s==="listing"?"Your Home Is On The Market":"Active Phase"}function eJt(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 tJt={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. 🎉"}},hht=["Lead","Consultation","Agreement Signed","Active","Under Contract","Closing","Closed Won"];function xye(s){return hht.map(t=>{if(t==="Active")return{key:"Active",label:JXt(s),description:eJt(s)};const n=tJt[t];return{key:t,label:n.label,description:n.description}})}function ufe(s){if(!s)return 0;const t=hht.indexOf(s);return t>=0?t:0}function sJt({portal:s,linkedPortal:t,activePortal:n,activeTab:r,onTabChange:a,agentProfile:i,branding:l,updates:o,documents:c}){var ee,se,oe;const d=(l==null?void 0:l.cover_photo_url)||null,u=(l==null?void 0:l.logo_url)||null,h=(l==null?void 0:l.tagline)||"Your Real Estate Concierge",p=n==null?void 0:n.deal_pipeline,f=p==null?void 0:p.deal_pipeline_stages,y=f==null?void 0:f.is_won_stage,_=p==null?void 0:p.deal_type,v=n==null?void 0:n.stage_mapping;let j=xye(_);v&&v.length>0&&(j=v.map((he,ce)=>{var me,le;return{key:`custom-${ce}`,label:he.label||((me=j[ce])==null?void 0:me.label)||`Stage ${ce+1}`,description:he.description||((le=j[ce])==null?void 0:le.description)||"",video_url:he.video_url||void 0}}));const w=v&&v.length>0?Math.min(ufe(f==null?void 0:f.name),j.length-1):ufe(f==null?void 0:f.name),S=j[w],A=S==null?void 0:S.video_url,E=y&&n.show_post_close_tips!==!1&&n.referral_enabled!==!1,O=p!=null&&p.property_address?`${p.property_address}, ${p.city||""}, ${p.state||""}`.replace(/,\s*,/g,",").replace(/,\s*$/,""):null,D=!!t,I=(ee=s==null?void 0:s.deal_pipeline)==null?void 0:ee.deal_type,F=(se=t==null?void 0:t.deal_pipeline)==null?void 0:se.deal_type,z=he=>he==="listing"?"Your Sale":he==="buy-side"?"Your Purchase":"Transaction",H=j.length>1?Math.round((w+1)/j.length*100):0,{data:Z=[]}=lht({id:n==null?void 0:n.id,owner_user_id:n==null?void 0:n.owner_user_id}),Y=Z.some(he=>!he.stage_filter||he.stage_filter.length===0||!(f!=null&&f.name)?!0:he.stage_filter.includes(f.name)),W=()=>{var he;(he=document.getElementById("trusted-vendors"))==null||he.scrollIntoView({behavior:"smooth",block:"start"})};return e.jsxs("div",{className:"min-h-screen relative",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx("div",{className:"pointer-events-none absolute inset-x-0 top-0 h-[600px] opacity-70",style:{background:"radial-gradient(ellipse 70% 100% at 50% 0%, hsl(var(--portal-gold) / 0.08), transparent 60%)"}}),e.jsxs("div",{className:"relative max-w-[1400px] mx-auto px-8 py-8",children:[e.jsxs(Zn.div,{initial:{opacity:0,y:-6},animate:{opacity:1,y:0},transition:{duration:.4},className:"flex items-center justify-between mb-8",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[u?e.jsx("div",{className:"rounded-lg px-3 py-1.5",style:{background:"hsl(0 0% 100% / 0.04)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},children:e.jsx("img",{src:u,alt:"Brand",className:"h-8 max-w-[140px] object-contain"})}):e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center portal-serif text-xl",style:{background:"var(--portal-gradient-gold)",color:"hsl(var(--portal-bg))"},children:"✦"}),e.jsxs("div",{children:[e.jsx("p",{className:"portal-eyebrow",children:"Private Client Portal"}),e.jsx("p",{className:"portal-serif mt-0.5",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:n!=null&&n.client_name?`Welcome, ${n.client_name.split(" ")[0]}`:"Your transaction"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(Ih,{className:"w-3 h-3",style:{color:"hsl(var(--portal-gold))"}}),"Secure & Encrypted"]})]}),e.jsxs(Zn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{duration:.6,ease:"easeOut"},className:"relative overflow-hidden rounded-3xl mb-8",style:{minHeight:380,border:"1px solid hsl(var(--portal-gold) / 0.25)",boxShadow:"var(--portal-shadow-luxe)"},children:[d?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute inset-0",style:{backgroundImage:`url(${d})`,backgroundSize:"cover",backgroundPosition:"center",filter:"grayscale(0.3) brightness(0.55)"}}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, hsl(0 0% 3% / 0.4) 0%, hsl(0 0% 3% / 0.7) 55%, hsl(0 0% 5%) 100%)"}})]}):e.jsx("div",{className:"absolute inset-0",style:{background:"radial-gradient(ellipse 80% 60% at 20% 20%, hsl(var(--portal-gold) / 0.15), transparent 60%), radial-gradient(ellipse 80% 60% at 80% 80%, hsl(var(--portal-gold) / 0.08), transparent 60%), hsl(var(--portal-surface))"}}),e.jsx("div",{className:"absolute top-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.6), transparent)"}}),e.jsxs("div",{className:"relative grid grid-cols-3 gap-8 p-12",children:[e.jsxs("div",{className:"col-span-2 flex flex-col justify-end",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 rounded-full px-3 py-1 text-[10px] tracking-[0.22em] uppercase mb-6 self-start",style:{background:"hsl(var(--portal-gold) / 0.1)",border:"1px solid hsl(var(--portal-gold) / 0.3)",color:"hsl(var(--portal-gold))"},children:[e.jsx(Or,{className:"w-3 h-3"}),_==="listing"?"Sale":_==="buy-side"?"Purchase":"Transaction",y&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"opacity-50 mx-1",children:"·"}),"Complete"]})]}),e.jsx("h1",{className:"portal-serif leading-[0.95] mb-4",style:{fontSize:"4.5rem",color:"hsl(var(--portal-ink))"},children:(p==null?void 0:p.deal_name)||"Your Transaction"}),e.jsx("div",{className:"portal-hairline w-32 mb-5"}),O&&e.jsxs("div",{className:"flex items-center gap-2",style:{color:"hsl(var(--portal-ink-muted))"},children:[e.jsx(ka,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}}),e.jsx("span",{className:"text-base",children:O})]}),(n==null?void 0:n.welcome_message)&&e.jsxs("p",{className:"mt-6 portal-serif italic leading-relaxed max-w-2xl",style:{color:"hsl(var(--portal-ink-muted))",fontSize:"1.15rem"},children:["“",n.welcome_message,"”"]})]}),e.jsxs("div",{className:"flex flex-col items-center justify-center",children:[e.jsx(nJt,{pct:H}),e.jsx("p",{className:"portal-eyebrow mt-4",children:"Journey Progress"}),e.jsxs("p",{className:"portal-serif mt-1",style:{fontSize:"1.1rem",color:"hsl(var(--portal-ink))"},children:["Stage ",w+1," of ",j.length]})]})]}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-[1px]",style:{background:"linear-gradient(90deg, transparent, hsl(var(--portal-gold) / 0.4), transparent)"}})]}),D&&e.jsx("div",{className:"inline-flex gap-1 rounded-xl p-1 mb-8",style:{background:"hsl(var(--portal-surface))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(he=>{const ce=he==="primary"?I:F,me=r===he;return e.jsx("button",{onClick:()=>a(he),className:"portal-serif px-5 py-2 rounded-lg transition-all",style:{fontSize:"1rem",background:me?"hsl(var(--portal-surface-3))":"transparent",color:me?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",borderBottom:me?"1px solid hsl(var(--portal-gold))":"1px solid transparent"},children:z(ce)},he)})}),e.jsxs(Zn.div,{initial:"hidden",animate:"show",variants:{hidden:{},show:{transition:{staggerChildren:.06}}},className:"grid grid-cols-12 gap-5",children:[e.jsx("aside",{className:"col-span-3 space-y-5",children:e.jsxs("div",{className:"sticky top-6 space-y-5",children:[e.jsxs(_k,{children:[e.jsxs("div",{className:"text-center pt-2 pb-1",children:[i!=null&&i.avatar_url?e.jsx("div",{className:"w-24 h-24 mx-auto relative",children:e.jsx("div",{className:"absolute inset-0 rounded-full",style:{background:"var(--portal-gradient-gold)",padding:"2px"},children:e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-full h-full rounded-full object-cover",style:{background:"hsl(var(--portal-surface))"}})})}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center portal-serif text-3xl",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.4)",color:"hsl(var(--portal-gold))"},children:((oe=i==null?void 0:i.name)==null?void 0:oe.charAt(0))||"?"}),e.jsx("h3",{className:"mt-4 portal-serif",style:{fontSize:"1.5rem",color:"hsl(var(--portal-ink))"},children:i==null?void 0:i.name}),e.jsx("div",{className:"portal-hairline w-12 mx-auto my-2"}),e.jsx("p",{className:"text-[10px] tracking-[0.22em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:h})]}),e.jsxs("div",{className:"mt-5 space-y-2",children:[(i==null?void 0:i.phone)&&e.jsx(hje,{href:`tel:${i.phone}`,icon:Cr,label:"Call",sub:i.phone}),(i==null?void 0:i.phone)&&e.jsx(hje,{href:`sms:${i.phone}`,icon:Zl,label:"Text message"}),(i==null?void 0:i.email)&&e.jsx(hje,{href:`mailto:${i.email}`,icon:Gs,label:"Email",sub:i.email})]})]}),e.jsxs(_k,{children:[e.jsx("p",{className:"portal-eyebrow mb-4",children:"At a Glance"}),e.jsxs("div",{className:"space-y-4",children:[(p==null?void 0:p.target_close_date)&&e.jsx(mje,{icon:yr,label:"Target close",value:U$e(p.target_close_date)}),(p==null?void 0:p.contract_date)&&e.jsx(mje,{icon:pr,label:"Under contract",value:U$e(p.contract_date)}),e.jsx(mje,{icon:ao,label:"Progress",value:`${H}%`})]})]})]})}),e.jsxs("main",{className:"col-span-6 space-y-5",children:[E&&e.jsx(uht,{portalId:n.id,portalSlug:n.slug,ownerUserId:n.owner_user_id,rewardText:n.referral_reward_text,ctaHeadline:n.referral_cta_headline,agentName:i==null?void 0:i.name,clientName:n.client_name,reviewUrl:n.review_url,hubVideoUrl:n.homeowner_hub_video_url}),e.jsx(tht,{targetCloseDate:p==null?void 0:p.target_close_date,actualCloseDate:p==null?void 0:p.actual_close_date,clientName:n.client_name}),S&&e.jsx(_k,{children:e.jsx(nht,{currentStage:S,nextStepText:n.next_step_text,nextStepVideoUrl:A||n.next_step_video_url})}),e.jsx(_k,{children:e.jsx(sht,{journeyStages:j,currentIndex:w})}),o&&o.length>0&&e.jsx(_k,{children:e.jsx(iht,{updates:o})})]}),e.jsxs("aside",{className:"col-span-3 space-y-5",children:[e.jsx(_k,{children:e.jsx(rht,{targetCloseDate:p==null?void 0:p.target_close_date,contractDate:p==null?void 0:p.contract_date,inspectionDate:n.inspection_date,appraisalDate:n.appraisal_date,actualCloseDate:p==null?void 0:p.actual_close_date})}),c&&c.length>0&&e.jsx(_k,{children:e.jsx(aht,{documents:c})}),Y&&e.jsx(_k,{children:e.jsxs("button",{onClick:W,className:"w-full flex items-center gap-3 rounded-xl px-3 py-3 transition-all text-left group",style:{background:"hsl(var(--portal-gold) / 0.06)",border:"1px solid hsl(var(--portal-gold) / 0.2)"},onMouseEnter:he=>{he.currentTarget.style.background="hsl(var(--portal-gold) / 0.12)"},onMouseLeave:he=>{he.currentTarget.style.background="hsl(var(--portal-gold) / 0.06)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:e.jsx(b9,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"portal-serif",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:"Trusted Vendors"}),e.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:"My hand-picked network"})]}),e.jsx(ao,{className:"w-4 h-4",style:{color:"hsl(var(--portal-gold))"}})]})}),e.jsxs("div",{className:"text-center pt-2 space-y-2",children:[e.jsx("div",{className:"portal-hairline w-12 mx-auto"}),e.jsx("p",{className:"text-[10px] tracking-[0.25em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:"Powered by ReLevelUp"})]})]})]}),(n==null?void 0:n.id)&&(n==null?void 0:n.owner_user_id)&&e.jsx("div",{id:"trusted-vendors",className:"mt-8 scroll-mt-10",children:e.jsx(dht,{portalId:n.id,ownerUserId:n.owner_user_id,currentStage:f==null?void 0:f.name,brandingColor:"#c9a84c",layout:"grid"})})]})]})}function _k({children:s}){return e.jsx(Zn.div,{variants:{hidden:{opacity:0,y:10},show:{opacity:1,y:0,transition:{duration:.45,ease:"easeOut"}}},className:"portal-tile p-6",children:s})}function hje({href:s,icon:t,label:n,sub:r}){return e.jsxs("a",{href:s,className:"flex items-center gap-3 rounded-xl px-3 py-2.5 transition-all",style:{background:"hsl(var(--portal-gold) / 0.05)",border:"1px solid hsl(var(--portal-gold) / 0.12)"},onMouseEnter:a=>{a.currentTarget.style.background="hsl(var(--portal-gold) / 0.1)",a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.3)"},onMouseLeave:a=>{a.currentTarget.style.background="hsl(var(--portal-gold) / 0.05)",a.currentTarget.style.borderColor="hsl(var(--portal-gold) / 0.12)"},children:[e.jsx("div",{className:"w-9 h-9 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.15)",color:"hsl(var(--portal-gold))"},children:e.jsx(t,{className:"w-4 h-4"})}),e.jsxs("div",{className:"min-w-0 text-left",children:[e.jsx("p",{className:"text-sm portal-serif",style:{color:"hsl(var(--portal-ink))",fontSize:"1rem"},children:n}),r&&e.jsx("p",{className:"text-[10px] tracking-[0.15em] uppercase truncate mt-0.5",style:{color:"hsl(var(--portal-ink-dim))"},children:r})]})]})}function mje({icon:s,label:t,value:n}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-8 h-8 rounded-lg flex items-center justify-center shrink-0",style:{background:"hsl(var(--portal-gold) / 0.1)",color:"hsl(var(--portal-gold))"},children:e.jsx(s,{className:"w-4 h-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-[10px] tracking-[0.2em] uppercase",style:{color:"hsl(var(--portal-ink-dim))"},children:t}),e.jsx("p",{className:"portal-serif truncate",style:{fontSize:"1.05rem",color:"hsl(var(--portal-ink))"},children:n})]})]})}function nJt({pct:s}){const a=2*Math.PI*78,i=a-s/100*a;return e.jsxs("div",{className:"relative",style:{width:170,height:170},children:[e.jsxs("svg",{width:170,height:170,className:"-rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"portal-progress-gold",x1:"0%",y1:"0%",x2:"100%",y2:"100%",children:[e.jsx("stop",{offset:"0%",stopColor:"hsl(44, 51%, 54%)"}),e.jsx("stop",{offset:"100%",stopColor:"hsl(44, 74%, 74%)"})]})}),e.jsx("circle",{cx:170/2,cy:170/2,r:78,stroke:"hsl(44, 40%, 55%, 0.15)",strokeWidth:2,fill:"none"}),e.jsx(Zn.circle,{cx:170/2,cy:170/2,r:78,stroke:"url(#portal-progress-gold)",strokeWidth:3,strokeLinecap:"round",fill:"none",initial:{strokeDashoffset:a},animate:{strokeDashoffset:i},transition:{duration:1.4,ease:"easeOut"},strokeDasharray:a,style:{filter:"drop-shadow(0 0 6px hsl(44, 74%, 74%, 0.6))"}})]}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center",children:[e.jsx("span",{className:"portal-serif tabular-nums leading-none",style:{fontSize:"3rem",color:"hsl(var(--portal-gold))"},children:s}),e.jsx("span",{className:"text-[10px] tracking-[0.25em] uppercase mt-1",style:{color:"hsl(var(--portal-ink-dim))"},children:"percent"})]})]})}function U$e(s){const t=s.split(/[-/T]/),n=new Date(Number(t[0]),Number(t[1])-1,Number(t[2]));return new Intl.DateTimeFormat("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:"America/New_York"}).format(n)}function rJt({portal:s,dealData:t,agentProfile:n,customQuestions:r,deviceFingerprint:a,onComplete:i}){var v,j;const[l,o]=N.useState({first_name:((v=s.client_name)==null?void 0:v.split(" ")[0])||"",last_name:((j=s.client_name)==null?void 0:j.split(" ").slice(1).join(" "))||"",email:s.client_email||"",phone:s.client_phone||"",preferred_contact_method:"email",client_role:"buyer",notes:"",spouse_first_name:"",spouse_last_name:"",spouse_email:"",spouse_phone:""}),[c,d]=N.useState({}),[u,h]=N.useState(!1),p=yt({mutationFn:async()=>{const{error:w}=await q.from("portal_onboarding_submissions").insert({portal_id:s.id,first_name:l.first_name,last_name:l.last_name||null,email:l.email||null,phone:l.phone||null,preferred_contact_method:l.preferred_contact_method,client_role:l.client_role,notes:l.notes||null,device_fingerprint:a,custom_answers:Object.keys(c).length>0?c:null,spouse_first_name:u&&l.spouse_first_name||null,spouse_last_name:u&&l.spouse_last_name||null,spouse_email:u&&l.spouse_email||null,spouse_phone:u&&l.spouse_phone||null});if(w)throw w},onSuccess:i,onError:w=>{console.error("[PortalOnboarding] Submit failed:",w),ae.error("Something went wrong. Please try again.")}}),f=t!=null&&t.property_address?`${t.property_address}, ${t.city||""}, ${t.state||""}`:null,y="mt-1 rounded-xl bg-white text-slate-900 placeholder:text-slate-400 border-slate-200 focus-visible:ring-slate-400",_="mt-1 w-full rounded-xl border border-slate-200 bg-white text-slate-900 placeholder:text-slate-400 px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-slate-400";return e.jsx("div",{className:"max-w-md mx-auto px-4 py-10",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl ring-1 ring-slate-200 p-6 sm:p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[(n==null?void 0:n.avatar_url)&&e.jsx("img",{src:n.avatar_url,alt:n.name,className:"w-16 h-16 rounded-full border-2 border-slate-200 mx-auto mb-3 object-cover"}),e.jsx("h1",{className:"text-2xl font-bold text-slate-900",children:"Welcome to Your Portal"}),f&&e.jsxs("div",{className:"flex items-center justify-center gap-1 text-slate-500 text-sm mt-1",children:[e.jsx(ka,{className:"w-3.5 h-3.5"}),e.jsx("span",{children:f.replace(/,\s*,/g,",").replace(/,\s*$/,"")})]}),e.jsx("p",{className:"text-sm text-slate-600 mt-2",children:"Please fill in your details to access your transaction portal."})]}),e.jsxs("form",{onSubmit:w=>{w.preventDefault(),p.mutate()},className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"First Name *"}),e.jsx(ye,{required:!0,value:l.first_name,onChange:w=>o(S=>({...S,first_name:w.target.value})),className:y,placeholder:"John"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(ye,{value:l.last_name,onChange:w=>o(S=>({...S,last_name:w.target.value})),className:y,placeholder:"Doe"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(ye,{type:"email",value:l.email,onChange:w=>o(S=>({...S,email:w.target.value})),className:y,placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(ye,{type:"tel",value:l.phone,onChange:w=>o(S=>({...S,phone:w.target.value})),className:y,placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Preferred Contact Method"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:[{value:"email",label:"Email"},{value:"call",label:"Phone"},{value:"text",label:"Text"}].map(w=>e.jsx("button",{type:"button",onClick:()=>o(S=>({...S,preferred_contact_method:w.value})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.preferred_contact_method===w.value?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:w.label},w.value))})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Your Role"}),e.jsx("div",{className:"flex gap-2 mt-1.5",children:["buyer","seller","both"].map(w=>e.jsx("button",{type:"button",onClick:()=>o(S=>({...S,client_role:w})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${l.client_role===w?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:w.charAt(0).toUpperCase()+w.slice(1)},w))})]}),r.map(w=>e.jsxs("div",{children:[e.jsxs(ne,{className:"text-xs font-medium text-slate-700",children:[w.question_text," ",w.is_required&&"*"]}),w.field_type==="text"&&e.jsx(ye,{required:w.is_required,value:c[w.id]||"",onChange:S=>d(A=>({...A,[w.id]:S.target.value})),className:y}),w.field_type==="textarea"&&e.jsx("textarea",{required:w.is_required,value:c[w.id]||"",onChange:S=>d(A=>({...A,[w.id]:S.target.value})),className:`${_} min-h-[80px]`}),w.field_type==="dropdown"&&e.jsxs("select",{required:w.is_required,value:c[w.id]||"",onChange:S=>d(A=>({...A,[w.id]:S.target.value})),className:`${_} h-10`,children:[e.jsx("option",{value:"",children:"Select..."}),(w.options||[]).map(S=>e.jsx("option",{value:S,children:S},S))]}),w.field_type==="toggle"&&e.jsx("div",{className:"mt-1.5 flex gap-2",children:["Yes","No"].map(S=>e.jsx("button",{type:"button",onClick:()=>d(A=>({...A,[w.id]:S})),className:`px-3.5 py-1.5 rounded-full text-xs font-medium border transition-colors ${c[w.id]===S?"bg-slate-800 text-white border-slate-800":"bg-white text-slate-600 border-slate-200"}`,children:S},S))})]},w.id)),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Notes for your agent"}),e.jsx("textarea",{value:l.notes,onChange:w=>o(S=>({...S,notes:w.target.value})),className:`${_} min-h-[60px]`,placeholder:"Anything you'd like your agent to know..."})]}),s.allow_spouse&&e.jsxs("div",{children:[e.jsx("button",{type:"button",onClick:()=>h(!u),className:"text-sm text-blue-600 hover:text-blue-700 font-medium",children:u?"− Remove spouse/partner":"+ Add spouse/partner"}),u&&e.jsxs("div",{className:"mt-3 p-4 bg-slate-50 rounded-xl border border-slate-200 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"First Name"}),e.jsx(ye,{value:l.spouse_first_name,onChange:w=>o(S=>({...S,spouse_first_name:w.target.value})),className:y})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Last Name"}),e.jsx(ye,{value:l.spouse_last_name,onChange:w=>o(S=>({...S,spouse_last_name:w.target.value})),className:y})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Email"}),e.jsx(ye,{type:"email",value:l.spouse_email,onChange:w=>o(S=>({...S,spouse_email:w.target.value})),className:y})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium text-slate-700",children:"Phone"}),e.jsx(ye,{type:"tel",value:l.spouse_phone,onChange:w=>o(S=>({...S,spouse_phone:w.target.value})),className:y})]})]})]}),e.jsx(B,{type:"submit",disabled:p.isPending||!l.first_name,className:"w-full h-12 rounded-full text-sm font-semibold bg-slate-900 hover:bg-slate-800",children:p.isPending?"Submitting...":"Access My Portal"})]})]})})}function aJt(s,t){const n=(r,a)=>a!=null&&a!==""?a:r!=null&&r!==""?r:null;return{logo_url:n(s==null?void 0:s.logo_url,t==null?void 0:t.logo_url),cover_photo_url:n(s==null?void 0:s.cover_photo_url,t==null?void 0:t.cover_photo_url),brand_color:n(s==null?void 0:s.brand_color,t==null?void 0:t.brand_color),accent_color:n(s==null?void 0:s.accent_color,t==null?void 0:t.accent_color),tagline:n(s==null?void 0:s.tagline,t==null?void 0:t.tagline),welcome_message:n(s==null?void 0:s.welcome_message,t==null?void 0:t.welcome_message)}}function mht(){const s=wa();return dt({queryKey:["agent-portal-branding",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function iJt(s){return dt({queryKey:["agent-portal-branding-public",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_portal_branding").select("logo_url, cover_photo_url, brand_color, accent_color, tagline, welcome_message").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function oJt(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_portal_branding").upsert({user_id:s,...n},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-portal-branding",s]}),t.invalidateQueries({queryKey:["agent-portal-branding-public",s]})}})}async function pht(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("portal-branding").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=q.storage.from("portal-branding").getPublicUrl(a);return l.publicUrl}function lJt(s,t){return dt({queryKey:["client-portal-public",s],queryFn:async()=>{if(!s)return null;const{data:n,error:r}=await q.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("slug",s).eq("is_enabled",!0).maybeSingle();if(r)throw r;return n},enabled:t})}function cJt(s){return dt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select(` *, deal_pipeline ( id, deal_name, property_address, city, state, deal_type, target_close_date, contract_date, expected_price, actual_close_date, stage_id, owner_user_id, deal_pipeline_stages (id, name, color, icon, sort_order, is_won_stage, is_lost_stage) ) `).eq("id",s).eq("is_enabled",!0).maybeSingle();if(n)throw n;return t},enabled:!!s})}function fht({slug:s}){var oe,he,ce,me,le,ve;const[t,n]=N.useState(!1),[r,a]=N.useState("primary"),[i]=N.useState(()=>{const ge=`portal_fp_${s}`;let Te=localStorage.getItem(ge);return Te||(Te=localStorage.getItem("portal_fp"),Te?localStorage.setItem(ge,Te):(Te=crypto.randomUUID(),localStorage.setItem(ge,Te),localStorage.setItem("portal_fp",Te))),Te});N.useEffect(()=>(document.body.classList.add("client-portal-page","portal-theme-noir"),()=>document.body.classList.remove("client-portal-page","portal-theme-noir")),[]);const{data:l,isLoading:o,error:c}=lJt(s,!0),d=l==null?void 0:l.linked_portal_id,{data:u}=cJt(d),h=(oe=l==null?void 0:l.deal_pipeline)==null?void 0:oe.owner_user_id;dt({queryKey:["portal-stages",h],queryFn:async()=>{const{data:ge,error:Te}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",h).order("sort_order",{ascending:!0});if(Te)throw Te;return ge},enabled:!!h});const{data:p}=dt({queryKey:["portal-agent",h],queryFn:async()=>{const{data:ge,error:Te}=await q.from("profiles").select("id, name, avatar_url, phone, email").eq("id",h).single();if(Te)throw Te;return ge},enabled:!!h}),{data:f}=iJt(h),y=r==="linked"&&u?u:l,_=y==null?void 0:y.id,v=aJt(f,y==null?void 0:y.branding_override),{data:j}=dt({queryKey:["portal-updates-public",_],queryFn:async()=>{const{data:ge,error:Te}=await q.from("portal_updates").select("*").eq("portal_id",_).order("created_at",{ascending:!1});if(Te)throw Te;return ge},enabled:!!_}),w=(he=y==null?void 0:y.deal_pipeline)==null?void 0:he.id,{data:S}=dt({queryKey:["portal-documents",w],queryFn:async()=>{const{data:ge,error:Te}=await q.from("deal_files").select("*").eq("deal_id",w).eq("visible_on_portal",!0).order("created_at",{ascending:!1});if(Te)throw Te;return ge},enabled:!!w}),A=l==null?void 0:l.id,E=A?`portal_onboarded_${A}_${i}`:null,O=E?localStorage.getItem(E)==="1":!1,{data:D,isLoading:I}=dt({queryKey:["portal-onboarding-check",A,i],queryFn:async()=>{const{data:ge,error:Te}=await q.from("portal_onboarding_submissions").select("id").eq("portal_id",A).eq("device_fingerprint",i).maybeSingle();if(Te)throw Te;return ge&&E&&localStorage.setItem(E,"1"),ge},enabled:!!A&&!!(l!=null&&l.require_onboarding)&&!O,staleTime:5*60*1e3}),F=!!(l!=null&&l.require_onboarding)&&!O&&!D&&!t,{data:z}=dt({queryKey:["portal-custom-questions-public",h],queryFn:async()=>{const{data:ge,error:Te}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",h).eq("is_active",!0).order("sort_order",{ascending:!0});if(Te)throw Te;return ge},enabled:!!h&&F}),H=O||!!D||t||!(l!=null&&l.require_onboarding);if(o||l!=null&&l.require_onboarding&&!O&&I)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:"hsl(var(--portal-bg))"},children:e.jsx(rs,{className:"w-6 h-6 animate-spin",style:{color:"hsl(var(--portal-gold))"}})});if(c||!l)return e.jsx("div",{className:"min-h-screen flex items-center justify-center p-6",style:{background:"var(--portal-gradient-noir)"},children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("div",{className:"w-16 h-16 rounded-full flex items-center justify-center mx-auto mb-6",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.3)"},children:e.jsx(Ih,{className:"w-6 h-6",style:{color:"hsl(var(--portal-gold))"}})}),e.jsx("h1",{className:"portal-serif text-4xl mb-3",style:{color:"hsl(var(--portal-ink))"},children:"Portal Not Available"}),e.jsx("div",{className:"portal-hairline mx-auto w-24 mb-4"}),e.jsx("p",{className:"text-sm",style:{color:"hsl(var(--portal-ink-muted))"},children:"This portal is no longer active or doesn't exist."})]})});if(!H){const ge=l==null?void 0:l.deal_pipeline;return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-slate-100",children:e.jsx(rJt,{portal:l,dealData:ge,agentProfile:p,customQuestions:z||[],deviceFingerprint:i,onComplete:()=>{E&&localStorage.setItem(E,"1"),n(!0)}})})}const Z=(ce=l==null?void 0:l.deal_pipeline)==null?void 0:ce.deal_type,Y=(me=u==null?void 0:u.deal_pipeline)==null?void 0:me.deal_type,W=!!u,ee=ge=>ge==="listing"?"Your Sale":ge==="buy-side"?"Your Purchase":"Transaction",se=ge=>ge==="listing"?e.jsx(Or,{className:"w-3.5 h-3.5"}):e.jsx(Ug,{className:"w-3.5 h-3.5"});return e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"hidden lg:block",children:e.jsx(sJt,{portal:l,linkedPortal:u,activePortal:y,activeTab:r,onTabChange:a,agentProfile:p,branding:v,updates:j,documents:S})}),e.jsxs("div",{className:"lg:hidden min-h-screen pb-16",style:{background:"var(--portal-gradient-noir)"},children:[e.jsx(qXt,{dealData:y==null?void 0:y.deal_pipeline,agentProfile:p,welcomeMessage:(y==null?void 0:y.welcome_message)||v.welcome_message,isWon:(ve=(le=y==null?void 0:y.deal_pipeline)==null?void 0:le.deal_pipeline_stages)==null?void 0:ve.is_won_stage,branding:v}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 space-y-5 mt-8",children:[W&&e.jsx("div",{className:"flex gap-1 rounded-xl p-1",style:{background:"hsl(var(--portal-surface-2))",border:"1px solid hsl(var(--portal-gold) / 0.15)"},children:["primary","linked"].map(ge=>{const Te=r===ge,Ie=ge==="primary"?Z:Y;return e.jsxs("button",{onClick:()=>a(ge),className:"flex-1 flex items-center justify-center gap-1.5 rounded-lg py-2.5 text-sm font-medium transition-all portal-serif",style:{background:Te?"hsl(var(--portal-surface-3))":"transparent",color:Te?"hsl(var(--portal-gold))":"hsl(var(--portal-ink-muted))",boxShadow:Te?"0 1px 0 hsl(var(--portal-gold) / 0.3) inset":"none"},children:[se(Ie),e.jsx("span",{style:{fontSize:"1rem"},children:ee(Ie)})]},ge)})}),e.jsx(dJt,{portal:y,updates:j,documents:S,agentProfile:p}),e.jsxs("div",{className:"text-center pt-8 pb-2 space-y-3",children:[e.jsx("div",{className:"portal-hairline w-16 mx-auto"}),e.jsxs("div",{className:"flex items-center justify-center gap-1.5",style:{color:"hsl(var(--portal-ink-dim))"},children:[e.jsx(Ih,{className:"w-3 h-3"}),e.jsx("span",{className:"text-[10px] tracking-[0.2em] uppercase",children:"Secure Client Portal"})]}),p&&e.jsxs("p",{className:"text-xs",style:{color:"hsl(var(--portal-ink-muted))"},children:["Curated by ",e.jsx("span",{className:"portal-serif",style:{color:"hsl(var(--portal-gold))",fontSize:"0.95rem"},children:p.name})]})]})]})]})]})}function dJt({portal:s,updates:t,documents:n,agentProfile:r}){const a=s,i=a==null?void 0:a.deal_pipeline,l=i==null?void 0:i.deal_pipeline_stages,o=l==null?void 0:l.is_won_stage,c=i==null?void 0:i.deal_type,d=s.stage_mapping;let u=xye(c);d&&d.length>0&&(u=d.map((_,v)=>{var j,w;return{key:`custom-${v}`,label:_.label||((j=u[v])==null?void 0:j.label)||`Stage ${v+1}`,description:_.description||((w=u[v])==null?void 0:w.description)||"",video_url:_.video_url||void 0}}));const h=d&&d.length>0?Math.min(ufe(l==null?void 0:l.name),u.length-1):ufe(l==null?void 0:l.name),p=u[h],f=p==null?void 0:p.video_url,y=o&&s.show_post_close_tips!==!1&&s.referral_enabled!==!1;return e.jsxs(e.Fragment,{children:[y&&e.jsx(uht,{portalId:s.id,portalSlug:s.slug,ownerUserId:s.owner_user_id,rewardText:s.referral_reward_text,ctaHeadline:s.referral_cta_headline,agentName:r==null?void 0:r.name,clientName:s.client_name,reviewUrl:s.review_url,hubVideoUrl:s.homeowner_hub_video_url}),e.jsx(tht,{targetCloseDate:i==null?void 0:i.target_close_date,actualCloseDate:i==null?void 0:i.actual_close_date,clientName:s.client_name}),e.jsx(sht,{journeyStages:u,currentIndex:h}),p&&e.jsx(nht,{currentStage:p,nextStepText:s.next_step_text,nextStepVideoUrl:f||s.next_step_video_url}),e.jsx(rht,{targetCloseDate:i==null?void 0:i.target_close_date,contractDate:i==null?void 0:i.contract_date,inspectionDate:s.inspection_date,appraisalDate:s.appraisal_date,actualCloseDate:i==null?void 0:i.actual_close_date}),n&&n.length>0&&e.jsx(aht,{documents:n}),(s==null?void 0:s.id)&&(s==null?void 0:s.owner_user_id)&&e.jsx(dht,{portalId:s.id,ownerUserId:s.owner_user_id,currentStage:l==null?void 0:l.name}),t&&t.length>0&&e.jsx(iht,{updates:t})]})}function xht({slug:s}){const t=bi(),n=s||t.slug,[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState("buying"),[S,A]=N.useState("");N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>document.body.classList.remove("client-portal-page")),[]);const{data:E,isLoading:O,error:D}=dt({queryKey:["portal-referral-target",n],queryFn:async()=>{if(!n)return null;const{data:z,error:H}=await q.from("client_portals").select(` id, slug, owner_user_id, client_name, referral_enabled, referral_reward_text, referral_cta_headline, is_enabled `).eq("slug",n).eq("is_enabled",!0).maybeSingle();if(H)throw H;return z},enabled:!!n}),{data:I}=dt({queryKey:["portal-referral-agent",E==null?void 0:E.owner_user_id],queryFn:async()=>{const{data:z}=await q.from("profiles").select("id, name, avatar_url").eq("id",E.owner_user_id).single();return z},enabled:!!(E!=null&&E.owner_user_id)}),F=async z=>{if(z.preventDefault(),!E||!h.trim()){ae.error("Please enter your friend's name");return}if(!f.trim()&&!_.trim()){ae.error("Please add at least an email or phone for your friend");return}a(!0);try{const{error:H}=await q.from("portal_referrals").insert({portal_id:E.id,owner_user_id:E.owner_user_id,referrer_name:o.trim()||E.client_name||null,referrer_email:d.trim()||null,friend_name:h.trim(),friend_email:f.trim()||null,friend_phone:_.trim()||null,friend_interest:j,friend_message:S.trim()||null});if(H)throw H;l(!0)}catch(H){ae.error(H.message||"Could not submit referral")}finally{a(!1)}};return O?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsx(Ws,{className:"h-96 w-full max-w-lg rounded-2xl mx-4"})}):D||!E||!E.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(Lr,{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 ",(I==null?void 0:I.name)||"your agent",". They'll reach out to"," ",e.jsx("span",{className:"font-semibold text-slate-800",children:h})," personally and treat them like family."]}),e.jsxs("button",{onClick:()=>window.history.back(),className:"inline-flex items-center gap-2 text-sm text-[#406E71] hover:text-[#2a4c64] font-medium",children:[e.jsx(qr,{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:[I!=null&&I.avatar_url?e.jsx("img",{src:I.avatar_url,alt:I.name||"Agent",className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 object-cover"}):e.jsx("div",{className:"w-16 h-16 rounded-full border-[3px] border-white/30 shadow-xl mx-auto mb-3 bg-white/10 flex items-center justify-center",children:e.jsx(Oi,{className:"w-7 h-7 text-white/70"})}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 bg-white/10 backdrop-blur-sm rounded-full px-3 py-1 text-xs font-medium text-white/90 mb-2",children:[e.jsx(Oi,{className:"w-3 h-3"})," Referral"]}),e.jsx("h1",{className:"text-2xl font-bold tracking-tight mb-1 font-serif",children:E.referral_cta_headline||"Refer a Friend"}),e.jsxs("p",{className:"text-sm text-white/70",children:["Send ",(I==null?void 0:I.name)||"your agent"," someone you trust."]}),E.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:E.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(ne,{htmlFor:"friend_name",className:"text-sm",children:["Their name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ye,{id:"friend_name",value:h,onChange:z=>p(z.target.value),placeholder:"Jane Smith",required:!0,className:"mt-1"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"friend_email",className:"text-sm",children:"Email"}),e.jsx(ye,{id:"friend_email",type:"email",value:f,onChange:z=>y(z.target.value),placeholder:"jane@email.com",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"friend_phone",className:"text-sm",children:"Phone"}),e.jsx(ye,{id:"friend_phone",type:"tel",value:_,onChange:z=>v(z.target.value),placeholder:"(555) 123-4567",className:"mt-1"})]})]}),e.jsx("p",{className:"text-[11px] text-slate-400",children:"Add at least an email or phone so we can reach them."}),e.jsxs("div",{children:[e.jsx(ne,{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:()=>w(z.v),className:`rounded-lg border px-3 py-2 text-sm font-medium transition-colors ${j===z.v?"bg-[#406E71] text-white border-[#406E71]":"bg-white text-slate-600 border-slate-200 hover:border-slate-300"}`,children:z.l},z.v))})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"friend_message",className:"text-sm",children:"A note (optional)"}),e.jsx("textarea",{id:"friend_message",value:S,onChange:z=>A(z.target.value),placeholder:"They're moving from Boston in the spring...",rows:3,className:"mt-1 w-full rounded-md border border-input bg-background px-3 py-2 text-sm focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wide text-slate-500 mb-3",children:"Your info"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"referrer_name",className:"text-sm",children:"Your name"}),e.jsx(ye,{id:"referrer_name",value:o,onChange:z=>c(z.target.value),placeholder:E.client_name||"Your name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"referrer_email",className:"text-sm",children:"Your email"}),e.jsx(ye,{id:"referrer_email",type:"email",value:d,onChange:z=>u(z.target.value),placeholder:"So we can thank you!",className:"mt-1"})]})]})]}),e.jsxs("button",{type:"submit",disabled:r,className:"w-full bg-[#406E71] hover:bg-[#345e7a] disabled:opacity-60 text-white font-semibold rounded-xl py-3.5 px-4 flex items-center justify-center gap-2 transition-colors",children:[r?e.jsx(rs,{className:"w-4 h-4 animate-spin"}):e.jsx(Oi,{className:"w-4 h-4"}),r?"Sending...":"Send Referral"]}),e.jsx("p",{className:"text-[11px] text-center text-slate-400",children:"By submitting, you confirm your friend has agreed to be contacted."})]})})]})}function uJt(){const t=Xl().pathname.slice(1).replace(/\/$/,"");if(N.useEffect(()=>(document.body.classList.add("client-portal-page"),()=>{document.body.classList.remove("client-portal-page")}),[]),!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Client Portal"}),e.jsx("p",{className:"text-slate-500",children:"Visit your personalized portal link to view your transaction details."})]})});const n=t.match(/^([^/]+)\/refer$/);return n?e.jsx(xht,{slug:n[1]}):t.includes("/")?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This portal link doesn't look right."})]})}):e.jsx(fht,{slug:t})}function hJt(s){const t=[],n=r=>{r&&!t.includes(r)&&t.push(r)};for(const r of s.filter(Boolean)){n(r);try{const a=new URL(r),i=a.searchParams.get("u");i&&/\/functions\/v1\/trestle-media/i.test(a.pathname)&&n(i)}catch{}}return t}function hfe({photos:s,alt:t="",className:n="w-full h-full",imgClassName:r="w-full h-full object-cover",iconClassName:a="w-8 h-8"}){const i=N.useMemo(()=>hJt(Array.isArray(s)?s:[]),[s]),[l,o]=N.useState(0);return N.useEffect(()=>{o(0)},[i.join("|")]),!i.length||l>=i.length?e.jsx("div",{className:`${n} bg-muted flex items-center justify-center text-muted-foreground`,children:e.jsx(Or,{className:`${a} opacity-40`})}):e.jsx("div",{className:`${n} overflow-hidden bg-muted`,children:e.jsx("img",{src:i[l],alt:t,className:r,onError:()=>o(c=>c+1)})})}function ght({comp:s,open:t,onClose:n}){var d;const[r,a]=N.useState(0);if(!s)return null;const i=Array.isArray(s.photos)?s.photos.filter(Boolean):[],l=s.soldPrice||s.price,o=s.sqft&&l?Math.round(l/s.sqft):null,c=u=>{if(!u)return null;const[h,p,f]=u.split(/[-/T]/);return h?`${p}/${f}/${h}`:null};return e.jsx(_s,{open:t,onOpenChange:u=>{u||n()},children:e.jsxs(bs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(js,{className:"px-6 pt-6 pb-2",children:[e.jsx(ws,{className:"text-xl",children:s.address}),e.jsxs("div",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ka,{className:"w-3.5 h-3.5"}),s.city,", ",s.state," ",s.zip]})]}),i.length>0?e.jsxs("div",{className:"px-6",children:[e.jsx(hfe,{photos:i.slice(r),className:"rounded-lg aspect-[16/10]"}),i.length>1&&e.jsx("div",{className:"flex gap-2 mt-2 overflow-x-auto pb-2",children:i.slice(0,24).map((u,h)=>e.jsx("button",{onClick:()=>a(h),className:`flex-none w-20 h-16 rounded overflow-hidden border-2 transition ${h===r?"border-primary":"border-transparent opacity-70 hover:opacity-100"}`,children:e.jsx(hfe,{photos:[u],iconClassName:"w-5 h-5"})},h))})]}):e.jsx("div",{className:"px-6",children:e.jsx("div",{className:"rounded-lg bg-muted aspect-[16/10] flex items-center justify-center text-muted-foreground",children:e.jsx(Or,{className:"w-12 h-12 opacity-40"})})}),e.jsxs("div",{className:"px-6 pt-4 flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-3xl font-bold flex items-center gap-1",children:[e.jsx(Yl,{className:"w-6 h-6 text-muted-foreground"}),(l||0).toLocaleString()]}),o&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",o,"/sqft"]})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1",children:[e.jsx(Ue,{variant:"outline",children:s.status}),s.daysOnMarket!=null&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[s.daysOnMarket," DOM"]})]})]}),(s.listDate||s.statusChangeDate||s.soldDate)&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-2",children:"Timeline"}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(pje,{label:"Active",date:c(s.listDate),active:!0}),e.jsx(pje,{label:"Pending",date:/Pending|Contingent|Under Contract|Backup/i.test(String(s.status||""))?c(s.statusChangeDate):null,active:/Pending|Contingent|Under Contract|Backup/i.test(String(s.status||""))}),e.jsx(pje,{label:"Closed",date:c(s.soldDate)||(/Closed|Sold/i.test(String(s.status||""))?c(s.statusChangeDate):null),active:/Closed|Sold/i.test(String(s.status||""))})]})]}),e.jsxs("div",{className:"px-6 pt-4 grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(tH,{icon:e.jsx(J0,{className:"w-4 h-4"}),label:"Beds",value:s.bedrooms??"—"}),e.jsx(tH,{icon:e.jsx(kp,{className:"w-4 h-4"}),label:"Baths",value:s.bathrooms??"—"}),e.jsx(tH,{icon:e.jsx(Z2,{className:"w-4 h-4"}),label:"SqFt",value:((d=s.sqft)==null?void 0:d.toLocaleString())??"—"}),e.jsx(tH,{icon:e.jsx(yr,{className:"w-4 h-4"}),label:"Year Built",value:s.yearBuilt??"—"})]}),e.jsxs("div",{className:"px-6 pt-4 grid sm:grid-cols-2 gap-x-6 gap-y-2 text-sm",children:[e.jsx(Px,{label:"MLS #",value:s.mlsNumber}),e.jsx(Px,{label:"Property Type",value:s.propertySubType||s.propertyType}),e.jsx(Px,{label:"Lot Size",value:s.lotSize}),e.jsx(Px,{label:"Garage",value:s.garageSpaces}),e.jsx(Px,{label:"Stories",value:s.stories}),e.jsx(Px,{label:"HOA",value:s.hoaFee?`$${s.hoaFee}/${(s.hoaFrequency||"mo").toLowerCase()}`:null}),e.jsx(Px,{label:"Tax (annual)",value:s.taxAmount?`$${s.taxAmount.toLocaleString()}`:null}),e.jsx(Px,{label:"Heating",value:s.heating}),e.jsx(Px,{label:"Cooling",value:s.cooling}),e.jsx(Px,{label:"Parking",value:s.parking}),e.jsx(Px,{label:"Elementary",value:s.elementarySchool}),e.jsx(Px,{label:"Middle",value:s.middleSchool}),e.jsx(Px,{label:"High",value:s.highSchool}),e.jsx(Px,{label:"Listed By",value:s.listAgentFullName}),e.jsx(Px,{label:"Office",value:s.listOfficeName})]}),s.description&&e.jsxs("div",{className:"px-6 pt-4",children:[e.jsx("div",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground mb-1",children:"Description"}),e.jsx("p",{className:"text-sm leading-relaxed whitespace-pre-wrap",children:s.description})]}),e.jsx("div",{className:"px-6 py-4"})]})})}function tH({icon:s,label:t,value:n}){return e.jsxs("div",{className:"rounded-lg border bg-card p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsx("div",{className:"text-lg font-semibold mt-0.5",children:n})]})}function Px({label:s,value:t}){return t==null||t===""||t===0?null:e.jsxs("div",{className:"flex justify-between border-b border-dashed py-1",children:[e.jsx("span",{className:"text-muted-foreground",children:s}),e.jsx("span",{className:"font-medium text-right ml-3 truncate",children:String(t)})]})}function pje({label:s,date:t,active:n}){return e.jsxs("div",{className:`rounded-lg border p-2 text-center ${n?"bg-primary/5 border-primary/30":"bg-muted/30"}`,children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:`text-sm font-medium mt-0.5 ${t?"":"text-muted-foreground/60"}`,children:t||"—"})]})}function sH({to:s,durationMs:t=1400,prefix:n="",suffix:r="",className:a,delayMs:i=0}){const[l,o]=N.useState(0),c=N.useRef(null);return N.useEffect(()=>{if(!Number.isFinite(s))return;let d=0;const u=0,h=f=>1-Math.pow(1-f,3),p=setTimeout(()=>{const f=y=>{d||(d=y);const _=y-d,v=Math.min(1,_/t);o(Math.round(u+(s-u)*h(v))),v<1&&(c.current=requestAnimationFrame(f))};c.current=requestAnimationFrame(f)},i);return()=>{clearTimeout(p),c.current&&cancelAnimationFrame(c.current)}},[s,t,i]),e.jsxs("span",{className:a,children:[n,l.toLocaleString(),r]})}function mJt({low:s,likely:t,high:n,defaultMortgage:r=0,defaultCommissionPct:a=6,defaultClosingPct:i=1}){const[l,o]=N.useState(t),[c,d]=N.useState(r),[u,h]=N.useState(a),[p,f]=N.useState(i),{commission:y,closing:_,net:v}=N.useMemo(()=>{const S=Math.round(l*u/100),A=Math.round(l*p/100);return{commission:S,closing:A,net:Math.max(0,l-S-A-(c||0))}},[l,u,p,c]),j=S=>`$${S.toLocaleString()}`,w=n>s?(l-s)/(n-s)*100:50;return e.jsxs(fe,{className:"overflow-hidden border-primary/20",children:[e.jsxs("div",{className:"bg-gradient-to-br from-primary/5 to-primary/10 px-6 pt-6 pb-4 border-b border-primary/10",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(go,{className:"w-4 h-4 text-primary"}),e.jsx("span",{className:"text-xs uppercase tracking-widest font-semibold text-primary",children:"Your Price Story"})]}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"What if you priced it at…"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Drag the price. Watch your estimated walk-away update in real-time."})]}),e.jsxs(Ee,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-end justify-between mb-3",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"List price"}),e.jsx("span",{className:"text-3xl font-bold tabular-nums",children:j(l)})]}),e.jsxs("div",{className:"relative",children:[e.jsx(jp,{value:[l],min:s,max:n,step:1e3,onValueChange:([S])=>o(S)}),e.jsxs("div",{className:"flex justify-between text-[10px] text-muted-foreground mt-2",children:[e.jsx("span",{children:j(s)}),e.jsxs("span",{children:["Suggested ",j(t)]}),e.jsx("span",{children:j(n)})]})]}),e.jsx("div",{className:"mt-2 h-1.5 rounded-full bg-muted overflow-hidden",children:e.jsx("div",{className:"h-full bg-gradient-to-r from-emerald-500 via-primary to-amber-500 transition-all",style:{width:`${Math.min(100,Math.max(0,w))}%`}})})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Mortgage payoff"}),e.jsx(ye,{type:"number",inputMode:"numeric",value:c||"",placeholder:"$0",onChange:S=>d(Number(S.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Commission %"}),e.jsx(ye,{type:"number",step:"0.25",value:u,onChange:S=>h(Number(S.target.value)||0)})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Closing costs %"}),e.jsx(ye,{type:"number",step:"0.25",value:p,onChange:S=>f(Number(S.target.value)||0)})]})]}),e.jsxs("div",{className:"rounded-xl border bg-card overflow-hidden",children:[e.jsxs("div",{className:"px-5 py-4 grid grid-cols-2 gap-y-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sale price"}),e.jsx("span",{className:"text-right tabular-nums font-medium",children:j(l)}),e.jsxs("span",{className:"text-muted-foreground",children:["Commission (",u,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",j(y)]}),e.jsxs("span",{className:"text-muted-foreground",children:["Closing (",p,"%)"]}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",j(_)]}),c>0&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-muted-foreground",children:"Mortgage payoff"}),e.jsxs("span",{className:"text-right tabular-nums text-rose-600",children:["−",j(c)]})]})]}),e.jsxs("div",{className:"bg-gradient-to-r from-emerald-500/10 to-primary/10 px-5 py-4 border-t flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gL,{className:"w-5 h-5 text-emerald-600"}),e.jsx("span",{className:"font-semibold",children:"Your estimated walk-away"})]}),e.jsx("span",{className:"text-2xl font-bold tabular-nums text-emerald-700",children:j(v)})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-relaxed",children:"This is a rough estimate to help you think through pricing. Actual proceeds depend on title fees, prorations, repairs, and other items your agent will walk through in detail."})]})]})}function yht({tokenOverride:s}={}){var Ae,Be,we,Je,ke,it,je,He,$e,Ke,Ge,rt;const t=bi(),n=s??t.token,[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState([]),[d,u]=N.useState(!0),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState(!1),[S,A]=N.useState(!1),[E,O]=N.useState(null),[D,I]=N.useState(null),[F,z]=N.useState(!1),{toast:H}=Fa();N.useEffect(()=>{n&&(async()=>{const{data:tt}=await q.from("cmas").select("*").eq("share_token",n).eq("status","shared").maybeSingle();if(!tt){u(!1);return}a(tt);const[{data:at},{data:Ye}]=await Promise.all([q.from("cma_comps").select("*").eq("cma_id",tt.id).order("position"),q.from("profiles").select("id,name,email,phone,avatar_url,brokerage_name,website_url,title,bio").eq("id",tt.agent_id).maybeSingle()]);c((at||[]).filter(_t=>_t.selected)),l(Ye);const ut=localStorage.getItem("cma_visitor_token")||crypto.randomUUID();localStorage.setItem("cma_visitor_token",ut),await q.from("cma_views").insert({cma_id:tt.id,visitor_token:ut,user_agent:navigator.userAgent}),u(!1)})()},[n]);const Z=async tt=>{if(!r)return;const at=localStorage.getItem("cma_visitor_token")||"";await q.from("cma_views").insert({cma_id:r.id,visitor_token:at,reactions:{[tt]:!0}}),q.functions.invoke("cma-reply-notify",{body:{shareToken:n,reaction:tt,visitorToken:at}}).catch(()=>{}),H({title:"Thanks — your agent just got notified ✨"})},Y=!(r!=null&&r.contact_id),W=async()=>{if(!r||!h.trim())return;if(Y&&(!f.trim()||!_.trim())){H({title:"Please add your name and email",variant:"destructive"});return}w(!0);const tt=localStorage.getItem("cma_visitor_token")||"",{data:at,error:Ye}=await q.functions.invoke("cma-reply-notify",{body:{shareToken:n,message:h,visitorToken:tt,viewerName:f.trim()||void 0,viewerEmail:_.trim()||void 0}});if(w(!1),Ye||!(at!=null&&at.success)){H({title:"Could not send",description:(Ye==null?void 0:Ye.message)||(at==null?void 0:at.error),variant:"destructive"});return}p(""),A(!0),H({title:"Message sent to your agent"})},ee=N.useMemo(()=>{const tt=o.map(at=>{const Ye=at.snapshot,ut=(Ye==null?void 0:Ye.soldPrice)||(Ye==null?void 0:Ye.price);return ut&&(Ye!=null&&Ye.sqft)?ut/Ye.sqft:null}).filter(at=>!!at).sort((at,Ye)=>at-Ye);return tt.length?Math.round(tt[Math.floor(tt.length/2)]):null},[o]);if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",children:e.jsx(rs,{className:"w-8 h-8 animate-spin"})});if(!r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center text-center p-6",children:e.jsxs("div",{children:[e.jsx(Or,{className:"w-12 h-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h1",{className:"text-xl font-semibold",children:"CMA not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This report may have been removed or unpublished."})]})});const se=r.subject||{},oe=(Ae=r.settings)==null?void 0:Ae.personalVideo,he=(Be=se.photos)==null?void 0:Be[0],ce=r.contact_first_name?r.contact_first_name:null,me=((i==null?void 0:i.name)||"A").split(" ").map(tt=>tt[0]).slice(0,2).join("").toUpperCase(),le=i!=null&&i.phone?`tel:${String(i.phone).replace(/[^\d+]/g,"")}`:null,ve=i!=null&&i.email?`mailto:${i.email}`:null,ge=i!=null&&i.phone?`sms:${String(i.phone).replace(/[^\d+]/g,"")}`:null,Te=r.price_low??null,Ie=r.price_likely??null,Ce=r.price_high??null,Me=Te&&Ie&&Ce,Pe=Ie&&se.sqft?Math.round(Ie/se.sqft):null,Re=Pe&&ee?Math.round((Pe-ee)/ee*100):null;return e.jsxs("div",{className:"min-h-screen bg-background pb-28 md:pb-0",children:[i&&e.jsx("div",{className:"border-b bg-card sticky top-0 z-40 backdrop-blur supports-[backdrop-filter]:bg-card/80",children:e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-6 py-3 flex items-center gap-3",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-10 h-10 rounded-full object-cover ring-2 ring-primary/20"}):e.jsx("div",{className:"w-10 h-10 rounded-full bg-primary/10 flex items-center justify-center font-semibold text-primary text-sm",children:me}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-semibold leading-tight truncate text-sm",children:i.name}),(i.title||i.brokerage_name)&&e.jsxs("div",{className:"text-[11px] text-muted-foreground flex items-center gap-1 truncate",children:[i.brokerage_name&&e.jsx(Ua,{className:"w-3 h-3 shrink-0"}),e.jsx("span",{className:"truncate",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")})]})]}),e.jsxs("div",{className:"hidden md:flex items-center gap-2",children:[le&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(Cr,{className:"w-4 h-4 mr-1"}),"Call"]})}),ve&&e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:ve,children:[e.jsx(Gs,{className:"w-4 h-4 mr-1"}),"Email"]})})]})]})}),e.jsxs("div",{className:"relative overflow-hidden",children:[he?e.jsxs("div",{className:"absolute inset-0",children:[e.jsx("img",{src:he,alt:se.address,className:"w-full h-full object-cover scale-110 animate-[kenburns_18s_ease-out_infinite_alternate]",style:{animation:"kenburns 22s ease-in-out infinite alternate"}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-slate-950/85 via-slate-900/75 to-primary/60"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-background via-background/20 to-transparent"})]}):e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-primary/30 via-primary/10 to-background"}),e.jsx("style",{children:` @keyframes kenburns { 0% { transform: scale(1.08) translate(0, 0); } 100% { transform: scale(1.18) translate(-1.5%, -1%); } } `}),e.jsx("div",{className:"relative container mx-auto max-w-6xl px-4 md:px-8 pt-12 md:pt-20 pb-16 md:pb-24",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-8 items-center",children:[e.jsxs("div",{className:`${oe!=null&&oe.url?"md:col-span-3":"md:col-span-5"} text-white animate-fade-in`,children:[e.jsxs(Ue,{className:"mb-4 bg-white/15 text-white border-white/20 backdrop-blur-sm hover:bg-white/20",children:[e.jsx(un,{className:"w-3 h-3 mr-1"}),ce?`Prepared for ${ce}`:r.buyer_mode?"Your Buyer Analysis":"Your Market Analysis"]}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold leading-[1.05] tracking-tight",children:se.address}),e.jsxs("p",{className:"text-white/70 mt-2 text-base md:text-lg flex items-center gap-2",children:[e.jsx(ka,{className:"w-4 h-4"}),se.city,", ",se.state," ",se.zip]}),Me&&e.jsxs("div",{className:"mt-8 md:mt-10",children:[e.jsx("p",{className:"text-xs uppercase tracking-[0.2em] text-white/60 mb-2",children:"Estimated Value"}),e.jsx("div",{className:"flex items-baseline gap-4 flex-wrap",children:e.jsx("div",{className:"text-5xl md:text-7xl font-bold tabular-nums",children:e.jsx(sH,{to:Ie,prefix:"$",durationMs:1600,delayMs:250})})}),e.jsxs("div",{className:"mt-4 flex items-center gap-3 md:gap-6 text-sm text-white/80",children:[e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Low"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(sH,{to:Te,prefix:"$",delayMs:500})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"Likely"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(sH,{to:Ie,prefix:"$",delayMs:650})})]}),e.jsx("div",{className:"h-8 w-px bg-white/20"}),e.jsxs("div",{children:[e.jsx("span",{className:"block text-[11px] uppercase tracking-wider text-white/50",children:"High"}),e.jsx("span",{className:"tabular-nums font-medium",children:e.jsx(sH,{to:Ce,prefix:"$",delayMs:800})})]})]})]})]}),(oe==null?void 0:oe.url)&&e.jsx("div",{className:"md:col-span-2 animate-scale-in",children:e.jsxs("button",{onClick:()=>z(!0),className:"group relative w-full aspect-[4/5] md:aspect-[4/5] rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/20 bg-black",children:[oe.thumb?e.jsx("img",{src:oe.thumb,alt:"",className:"w-full h-full object-cover"}):e.jsx("video",{src:oe.url,className:"w-full h-full object-cover",muted:!0,playsInline:!0,preload:"metadata"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/60 to-black/10 group-hover:from-black/40 transition-colors"}),e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center text-white",children:[e.jsx("div",{className:"w-16 h-16 md:w-20 md:h-20 rounded-full bg-white/95 text-primary flex items-center justify-center shadow-2xl group-hover:scale-110 transition-transform",children:e.jsx(El,{className:"w-7 h-7 md:w-8 md:h-8 ml-1",fill:"currentColor"})}),e.jsxs("p",{className:"mt-4 text-sm font-medium tracking-wide",children:["A message from ",((we=i==null?void 0:i.name)==null?void 0:we.split(" ")[0])||"your agent"]})]})]})})]})})]}),F&&(oe==null?void 0:oe.url)&&e.jsx("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 animate-fade-in",onClick:()=>z(!1),children:e.jsxs("div",{className:"relative w-full max-w-4xl",onClick:tt=>tt.stopPropagation(),children:[e.jsx("video",{src:oe.url,controls:!0,autoPlay:!0,className:"w-full rounded-xl"}),e.jsx(B,{variant:"ghost",className:"absolute -top-12 right-0 text-white hover:bg-white/10",onClick:()=>z(!1),children:"Close"})]})}),e.jsxs("div",{className:"container mx-auto max-w-6xl px-4 md:px-8 py-10 md:py-16 space-y-10 md:space-y-14",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 md:gap-4 -mt-20 md:-mt-24 relative z-10",children:[{label:"Beds",value:se.bedrooms??"—"},{label:"Baths",value:se.bathrooms??"—"},{label:"Sq Ft",value:((Je=se.sqft)==null?void 0:Je.toLocaleString())??"—"},{label:"Year Built",value:se.yearBuilt??"—"}].map((tt,at)=>e.jsx(fe,{className:"shadow-lg animate-fade-in",style:{animationDelay:`${at*80}ms`},children:e.jsxs(Ee,{className:"p-4 md:p-6 text-center",children:[e.jsx("div",{className:"text-2xl md:text-3xl font-bold",children:tt.value}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1 uppercase tracking-wider",children:tt.label})]})},at))}),((it=(ke=r.settings)==null?void 0:ke.priceOverride)==null?void 0:it.enabled)&&((He=(je=r.settings)==null?void 0:je.priceOverride)==null?void 0:He.note)&&e.jsx(fe,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:e.jsxs(Ee,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"A note from your agent"}),e.jsx("p",{className:"text-base md:text-lg leading-relaxed whitespace-pre-wrap text-foreground/90",children:r.settings.priceOverride.note})]})}),Me&&e.jsx(mJt,{low:Te,likely:Ie,high:Ce}),ee&&Pe&&e.jsxs("div",{className:"grid md:grid-cols-3 gap-4",children:[e.jsx(fe,{className:"md:col-span-2",children:e.jsxs(Ee,{className:"p-6 md:p-8",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-2",children:"Why this price"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mb-3",children:"The market is talking."}),e.jsxs("p",{className:"text-muted-foreground leading-relaxed",children:["Based on ",e.jsxs("strong",{className:"text-foreground",children:[o.length," comparable ",o.length===1?"home":"homes"]})," in ",se.city,", the median sale rate is ",e.jsxs("strong",{className:"text-foreground",children:["$",ee,"/sqft"]}),". Applied to your home's ",($e=se.sqft)==null?void 0:$e.toLocaleString()," sqft, the comps support a value near ",e.jsxs("strong",{className:"text-foreground",children:["$",(ee*(se.sqft||0)).toLocaleString()]}),". Your agent's suggested price reflects local nuance and condition."]})]})}),e.jsx(fe,{className:"bg-gradient-to-br from-primary/10 to-primary/5 border-primary/20",children:e.jsxs(Ee,{className:"p-6 md:p-8 h-full flex flex-col justify-center",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground mb-1",children:"Your home"}),e.jsxs("div",{className:"text-3xl font-bold tabular-nums",children:["$",Pe,e.jsx("span",{className:"text-base font-normal text-muted-foreground",children:"/sqft"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Neighborhood avg: ",e.jsxs("span",{className:"font-medium text-foreground",children:["$",ee,"/sqft"]})]}),Re!==null&&Re!==0&&e.jsxs("p",{className:`text-sm font-medium mt-1 ${Re>0?"text-emerald-600":"text-rose-600"}`,children:[Re>0?"▲":"▼"," ",Math.abs(Re),"% ",Re>0?"above":"below"," the median"]})]})})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-baseline justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold",children:"Homes like yours"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold",children:"The Comparables"})]}),e.jsxs(Ue,{variant:"outline",className:"text-xs",children:[o.length," comps"]})]}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-4",children:o.map((tt,at)=>{var _t;const Ye=tt.snapshot,ut=Ye.soldPrice||Ye.price;return e.jsxs(fe,{className:`overflow-hidden cursor-pointer transition-all duration-300 hover:shadow-xl hover:-translate-y-1 animate-fade-in ${D===at?"ring-2 ring-primary":""}`,style:{animationDelay:`${at*60}ms`},onClick:()=>O(at),onMouseEnter:()=>I(at),onMouseLeave:()=>I(null),children:[e.jsxs("div",{className:"relative",children:[e.jsx(hfe,{photos:Ye.photos,className:"w-full h-44"}),e.jsxs(Ue,{className:"absolute top-2 left-2 bg-black/70 text-white border-0 backdrop-blur-sm",children:["#",at+1]}),e.jsx(Ue,{variant:"outline",className:"absolute top-2 right-2 bg-white/95 border-0",children:Ye.status})]}),e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"font-semibold leading-tight truncate",children:Ye.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Ye.city,", ",Ye.state]}),e.jsx("div",{className:"flex justify-between items-center mt-3 text-sm",children:e.jsxs("span",{className:"text-muted-foreground",children:[Ye.bedrooms??"?","bd · ",Ye.bathrooms??"?","ba · ",((_t=Ye.sqft)==null?void 0:_t.toLocaleString())??"?"," sqft"]})}),e.jsxs("div",{className:"flex justify-between items-center mt-3 pt-3 border-t",children:[e.jsxs("span",{className:"text-xl font-bold tabular-nums",children:["$",ut==null?void 0:ut.toLocaleString()]}),Ye.sqft&&ut?e.jsxs("span",{className:"text-xs text-muted-foreground tabular-nums",children:["$",Math.round(ut/Ye.sqft),"/sqft"]}):null]})]})]},at)})})]}),e.jsx(ght,{comp:E!==null?(Ke=o[E])==null?void 0:Ke.snapshot:null,open:E!==null,onClose:()=>O(null)}),e.jsx(fe,{className:"border-primary/20 bg-gradient-to-br from-primary/5 via-background to-background overflow-hidden",children:e.jsxs(Ee,{className:"p-6 md:p-8 space-y-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-primary font-semibold mb-1",children:"Your turn"}),e.jsxs("h2",{className:"text-2xl md:text-3xl font-bold",children:["What do you think",ce?`, ${ce}`:"","?"]}),e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:["One tap. ",((Ge=i==null?void 0:i.name)==null?void 0:Ge.split(" ")[0])||"Your agent"," hears you instantly."]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:[{kind:"love",icon:gi,label:"I love this price"},{kind:"fair",icon:$m,label:"Seems fair"},{kind:"lower",icon:fb,label:"I'd price lower"},{kind:"higher",icon:go,label:"I'd price higher"},{kind:"ready_to_list",icon:pw,label:"Ready to list"},{kind:"want_walkthrough",icon:Sr,label:"Want a walkthrough"},{kind:"need_time",icon:yr,label:"Need more time"},{kind:"have_questions",icon:q_,label:"I have questions"}].map(({kind:tt,icon:at,label:Ye})=>e.jsxs(B,{variant:"outline",className:"bg-card hover:bg-primary hover:text-primary-foreground hover:scale-105 transition-all",onClick:()=>Z(tt),children:[e.jsx(at,{className:"w-4 h-4 mr-2"}),Ye]},tt))}),e.jsxs("div",{className:"pt-4 border-t",children:[e.jsxs("p",{className:"text-sm font-medium mb-2 flex items-center gap-1",children:[e.jsx(Zl,{className:"w-4 h-4"}),"Ask your agent a question"]}),S?e.jsxs("div",{className:"rounded-md bg-emerald-50 border border-emerald-200 p-4 text-sm text-emerald-800 animate-fade-in",children:["✓ Sent! ",((rt=i==null?void 0:i.name)==null?void 0:rt.split(" ")[0])||"Your agent"," was notified and will get back to you shortly."]}):e.jsxs(e.Fragment,{children:[Y&&e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2 mb-2",children:[e.jsx("input",{className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your name",value:f,onChange:tt=>y(tt.target.value)}),e.jsx("input",{type:"email",className:"border rounded-md p-2 text-sm bg-background",placeholder:"Your email",value:_,onChange:tt=>v(tt.target.value)})]}),e.jsx("textarea",{className:"w-full border rounded-md p-3 text-sm min-h-[100px] bg-background",placeholder:"What questions do you have about this analysis?",value:h,onChange:tt=>p(tt.target.value)}),e.jsx(B,{onClick:W,disabled:!h.trim()||j,className:"mt-2",children:j?"Sending…":"Send to agent"})]})]})]})}),i&&e.jsx(fe,{className:"overflow-hidden border-primary/20",children:e.jsx("div",{className:"bg-gradient-to-br from-primary/10 to-primary/5 p-6 md:p-10",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-6 items-start",children:[i.avatar_url?e.jsx("img",{src:i.avatar_url,alt:i.name,className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl object-cover ring-4 ring-background shadow-lg"}):e.jsx("div",{className:"w-24 h-24 md:w-32 md:h-32 rounded-2xl bg-primary/20 flex items-center justify-center text-3xl font-bold text-primary ring-4 ring-background shadow-lg",children:me}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-xs uppercase tracking-widest text-muted-foreground",children:"Prepared by"}),e.jsx("h2",{className:"text-2xl md:text-3xl font-bold mt-1",children:i.name}),(i.title||i.brokerage_name)&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:[i.title,i.brokerage_name].filter(Boolean).join(" · ")}),i.bio&&e.jsx("p",{className:"text-sm text-muted-foreground mt-3 leading-relaxed",children:i.bio}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[le&&e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(Cr,{className:"w-4 h-4 mr-2"}),i.phone]})}),ve&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:ve,children:[e.jsx(Gs,{className:"w-4 h-4 mr-2"}),"Email"]})}),i.website_url&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:i.website_url,target:"_blank",rel:"noreferrer",children:[e.jsx(lc,{className:"w-4 h-4 mr-2"}),"Website"]})})]})]})]})})})]}),i&&(le||ge||ve)&&e.jsxs("div",{className:"md:hidden fixed bottom-0 left-0 right-0 bg-card/95 backdrop-blur border-t shadow-2xl z-50 px-3 py-3 flex gap-2",style:{paddingBottom:"calc(0.75rem + env(safe-area-inset-bottom))"},children:[le&&e.jsx(B,{className:"flex-1",asChild:!0,children:e.jsxs("a",{href:le,children:[e.jsx(Cr,{className:"w-4 h-4 mr-1.5"}),"Call"]})}),ge&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ge,children:[e.jsx(Zl,{className:"w-4 h-4 mr-1.5"}),"Text"]})}),ve&&e.jsx(B,{variant:"outline",className:"flex-1",asChild:!0,children:e.jsxs("a",{href:ve,children:[e.jsx(Gs,{className:"w-4 h-4 mr-1.5"}),"Email"]})})]})]})}function pJt(){const t=Xl().pathname.slice(1).replace(/\/$/,"");return!t||t.includes("/")?e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"CMA Portal"}),e.jsx("p",{className:"text-slate-500",children:"Open your CMA link to view your personalized market analysis."})]})}):e.jsx(yht,{tokenOverride:t})}const W4e="levelup_affiliate_ref",fJt=30,xJt=()=>{const[s]=xl();N.useEffect(()=>{const t=s.get("ref");if(t){const n={code:t.toUpperCase(),timestamp:Date.now()};localStorage.setItem(W4e,JSON.stringify(n)),console.log("[Affiliate] Stored referral code:",t)}},[s])},gJt=()=>{try{const s=localStorage.getItem(W4e);if(!s)return null;const t=JSON.parse(s),n=fJt*24*60*60*1e3;return Date.now()-t.timestamp>n?(localStorage.removeItem(W4e),console.log("[Affiliate] Referral code expired"),null):t.code}catch{return null}},mfe="/assets/levelup-logo-header-_ZX7DvlA.png",yJt="/assets/scale-your-team-ku4MPatU.png";function vJt({open:s,onOpenChange:t}){return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(js,{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(Ua,{className:"h-5 w-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(ws,{children:"Schedule a Brokerage Interest Meeting"}),e.jsx(Jn,{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 up={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}},bJt=[{icon:jh,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:pl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:yr,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Zl,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:br,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Oi,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],_Jt=[{icon:An,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:un,title:"Smart Touchpoint Plans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Cr,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Ah,title:"Birthday & Anniversary Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ka,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:_o,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:gi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:im,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],wJt=[{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."}],jJt=()=>{const{user:s,loading:t}=vs(),n=Ln(),[r]=xl();N.useEffect(()=>{const D=window.location.host==="listings.relevelup.com",I=window.location.pathname==="/";if(D&&I){n("/public/listings",{replace:!0});return}},[n]);const[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),[y,_]=N.useState(""),[v,j]=N.useState(!1),[w,S]=N.useState(!1),A=(D,I=!1)=>{o({tier:D,skipTrial:I}),d(!0)};xJt(),N.useEffect(()=>{const D=window.location.host==="listings.relevelup.com",I=location.pathname.startsWith("/public/");!t&&s&&!D&&!I&&n("/dashboard")},[s,t,n,location.pathname]),N.useEffect(()=>{r.get("canceled")==="true"&&ae.error("Checkout was canceled. Feel free to try again when you're ready!")},[r]);const E=async(D,I=!1)=>{if(!u){ae.error("Please enter your email address");return}if(!p.trim()){ae.error("Please enter your full name");return}j(!0),i(D+(I?"_direct":""));const F=gJt();try{const{data:z,error:H}=await q.functions.invoke("create-checkout",{body:{tier:D,email:u,name:p.trim(),couponCode:y.trim()||void 0,skipTrial:I,referralCode:F}});if(H)throw H;if(z!=null&&z.url)window.open(z.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(z){console.error("Checkout error:",z),ae.error(z.message||"Failed to start checkout. Please try again.")}finally{j(!1),i(null),d(!1),o(null)}},O=()=>{l&&E(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:mfe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var D;return(D=document.getElementById("features"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},children:"Pricing"}),e.jsx(B,{onClick:()=>n("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-5xl mx-auto text-center space-y-8",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-[136px] md:h-[164px] drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("p",{className:"text-lg text-white/80 max-w-3xl mx-auto leading-relaxed font-sans font-bold md:text-4xl",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center items-center pt-4",children:[e.jsxs(B,{size:"lg",onClick:()=>{var D;return(D=document.getElementById("free-trial"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",children:["Start Your Free Trial",e.jsx(Oa,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]}),e.jsx(B,{size:"lg",variant:"outline",onClick:()=>{var D;return(D=document.getElementById("features"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"px-8 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#1e3a4c] rounded-full",children:"See What's Included"})]})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Learn how we support agents and empower brokerages to grow—together."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center pt-4",children:[e.jsxs(B,{size:"lg",variant:"outline",onClick:()=>{var D;return(D=document.getElementById("brokerage"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/5",children:[e.jsx(Ua,{className:"mr-2 h-5 w-5"}),"Brokerage Partnership"]}),e.jsxs(B,{size:"lg",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:[e.jsx(Wi,{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:bJt.map((D,I)=>e.jsxs(fe,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(It,{children:[e.jsx("div",{className:"w-14 h-14 rounded-2xl bg-[#4a6b6d]/10 flex items-center justify-center mb-4",children:e.jsx(D.icon,{className:"w-7 h-7 text-[#4a6b6d]"})}),e.jsx(Rt,{className:"text-xl font-sans",children:D.title})]}),e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:D.description})})]},I))})]})}),e.jsxs("section",{id:"agent-os",className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(un,{className:"w-4 h-4"}),"Included with Membership"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:_Jt.map((D,I)=>e.jsxs(fe,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(It,{className:"pb-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-xl bg-white/20 flex items-center justify-center mb-3",children:e.jsx(D.icon,{className:"w-6 h-6 text-white"})}),e.jsx(Rt,{className:"text-lg font-semibold text-white",children:D.title})]}),e.jsx(Ee,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:D.description})})]},I))}),e.jsx("div",{className:"text-center mt-12",children:e.jsxs(B,{size:"lg",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"bg-white text-[#4a6b6d] hover:bg-white/90 shadow-xl transition-all hover:scale-105",children:["Get Agent OS with Your Membership",e.jsx(Oa,{className:"ml-2 w-5 h-5"})]})})]})]}),e.jsx("section",{id:"brokerage",className:"py-20 bg-[#4a6b6d]/5",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsx("div",{className:"max-w-6xl mx-auto",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium",children:[e.jsx(Ua,{className:"w-4 h-4"}),"For Brokerages"]}),e.jsxs("h2",{className:"text-3xl font-sans font-bold md:text-6xl",children:["Empower Your"," ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Entire Team"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Give every agent on your team access to world-class training and resources. Track performance, streamline onboarding, and watch your brokerage thrive."}),e.jsx("ul",{className:"space-y-4",children:["Dedicated brokerage manager dashboard","Invite and manage agents with one click","Exclusive brokerage-only resources","Team analytics and performance tracking","Simplified agent onboarding","Share resources across your team"].map((D,I)=>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(Lr,{className:"w-4 h-4 text-[#4a6b6d]"})}),e.jsx("span",{className:"text-foreground",children:D})]},I))}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-4",children:[e.jsxs(B,{size:"lg",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["See Brokerage Plans",e.jsx(ga,{className:"ml-2 w-5 h-5"})]}),e.jsxs(B,{size:"lg",variant:"outline",onClick:()=>S(!0),className:"border-[#4a6b6d] text-[#4a6b6d] hover:bg-[#4a6b6d]/10",children:[e.jsx(yr,{className:"mr-2 w-5 h-5"}),"Schedule Info Session"]})]})]}),e.jsx("div",{className:"relative hidden md:block",children:e.jsx("img",{src:yJt,alt:"Scale Your Team from 5 to 500 Agents",className:"w-full rounded-3xl shadow-lg"})})]})})})}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Agents Love ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"LevelUp"})]}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what top producers are saying about the platform."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-8 max-w-6xl mx-auto",children:wJt.map((D,I)=>e.jsx(fe,{className:"bg-muted/30 border-0",children:e.jsxs(Ee,{className:"pt-8",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(F=>e.jsx(oa,{className:"w-5 h-5 fill-yellow-400 text-yellow-400"},F))}),e.jsxs("p",{className:"text-lg mb-6 italic text-muted-foreground",children:['"',D.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:D.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:D.role})]})]})},I))})]})}),e.jsxs("section",{id:"free-trial",className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center space-y-8",children:[e.jsxs("h2",{className:"text-3xl md:text-5xl font-bold text-white",children:["Start Your Free Trial ",e.jsx("span",{className:"italic",children:"Today"})]}),e.jsx("p",{className:"text-lg md:text-xl text-white/80 leading-relaxed",children:"Get instant access to 7 days of trainings, templates, and tools — designed to give you quick wins now and resources you'll keep forever."}),e.jsx("div",{className:"pt-4",children:e.jsxs(B,{size:"lg",className:"px-12 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 group rounded-full",onClick:()=>A("individual_agent"),children:["Start Free Trial",e.jsx(Oa,{className:"ml-2 w-5 h-5 group-hover:translate-x-1 transition-transform"})]})})]})})]}),e.jsx("section",{id:"pricing",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsxs("h2",{className:"text-3xl mb-6 font-sans md:text-5xl font-bold",children:["Simple, Transparent ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Pricing"})]}),e.jsx("p",{className:"text-lg text-muted-foreground max-w-2xl mx-auto",children:"Choose the plan that fits your needs. All plans include everything you need to succeed."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:[e.jsxs(fe,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(It,{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(Wi,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx(Rt,{className:"text-xl font-sans",children:up.individual_agent.name})]}),e.jsxs("div",{className:"flex items-baseline gap-1 mt-4",children:[e.jsx("span",{className:"text-5xl font-bold",children:up.individual_agent.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:up.individual_agent.period})]}),e.jsx(Vn,{className:"text-base mt-2",children:up.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(pr,{className:"w-4 h-4"}),up.individual_agent.trial]})]}),e.jsx(Ee,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:up.individual_agent.features.map((D,I)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Lr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:D})]},I))})}),e.jsxs(V9,{className:"flex flex-col gap-3 pt-4",children:[e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("individual_agent"),children:"Start Free Trial"}),e.jsx(B,{variant:"outline",className:"w-full rounded-full border-2 border-[#4a6b6d] text-[#4a6b6d] bg-white hover:bg-[#4a6b6d]/5 uppercase text-sm font-medium tracking-wide",onClick:()=>A("individual_agent",!0),children:"Skip Trial, Subscribe Now"})]})]}),e.jsxs(fe,{className:"relative flex flex-col border-2 border-[#4a6b6d] shadow-2xl scale-105 bg-background",children:[e.jsx("div",{className:"absolute -top-4 left-1/2 -translate-x-1/2 px-6 py-2 bg-[#4a6b6d] text-white text-sm font-semibold rounded-full shadow-lg",children:"Most Popular"}),e.jsxs(It,{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(Ua,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-xl font-sans",children:up.brokerage_under_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:up.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:up.brokerage_under_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:up.brokerage_under_25.period})]}),e.jsx(Vn,{className:"text-base mt-2",children:up.brokerage_under_25.description})]}),e.jsx(Ee,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:up.brokerage_under_25.features.map((D,I)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Lr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:D})]},I))})}),e.jsx(V9,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg shadow-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_under_25"),children:"Get Started"})})]}),e.jsxs(fe,{className:"relative flex flex-col border hover:border-[#4a6b6d]/50 transition-all hover:shadow-xl bg-background",children:[e.jsxs(It,{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(Ua,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-xl font-sans",children:up.brokerage_over_25.name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:up.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:up.brokerage_over_25.price}),e.jsx("span",{className:"text-muted-foreground text-lg",children:up.brokerage_over_25.period})]}),e.jsx(Vn,{className:"text-base mt-2",children:up.brokerage_over_25.description})]}),e.jsx(Ee,{className:"flex-1 pt-0",children:e.jsx("ul",{className:"space-y-3",children:up.brokerage_over_25.features.map((D,I)=>e.jsxs("li",{className:"flex items-center gap-3",children:[e.jsx(Lr,{className:"w-5 h-5 text-[#4a6b6d] flex-shrink-0"}),e.jsx("span",{children:D})]},I))})}),e.jsx(V9,{className:"pt-4",children:e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:()=>A("brokerage_over_25"),children:"Get Started"})})]})]})]})}),e.jsx("section",{id:"neutrality",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs("div",{className:"text-center mb-12",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-[#4a6b6d]/10 text-[#4a6b6d] text-sm font-medium mb-4",children:[e.jsx(Ih,{className:"w-4 h-4"}),"Our Commitment"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-sans font-bold",children:["LevelUp Brokerage ",e.jsx("span",{className:"italic text-[#4a6b6d]",children:"Neutrality Policy"})]}),e.jsx("p",{className:"text-lg text-muted-foreground mt-4 max-w-2xl mx-auto",children:"We are committed to being a trusted, independent partner for every agent and brokerage."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ee,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Ua,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp serves all brokerages."})]})}),e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ee,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(Gc,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not share member information with any brokerage."})]})}),e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ee,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(xb,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not recruit brokerage partners' agents."})]})}),e.jsx(fe,{className:"border-[#4a6b6d]/20 bg-[#4a6b6d]/[0.03]",children:e.jsxs(Ee,{className:"p-6 flex items-start gap-4",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-[#4a6b6d]/10 flex items-center justify-center shrink-0",children:e.jsx(br,{className:"w-5 h-5 text-[#4a6b6d]"})}),e.jsx("p",{className:"text-foreground font-medium leading-relaxed",children:"LevelUp does not use LevelUp events, trainings, webinars, CRM data, or member lists for recruiting purposes."})]})})]})]})})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl text-white font-sans md:text-5xl",children:"Ready to Level Up?"}),e.jsx("p",{className:"text-lg text-white/80 max-w-2xl mx-auto",children:"Join thousands of agents who are closing more deals, saving time, and growing their business with LevelUp."}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs(B,{size:"lg",onClick:()=>{var D;return(D=document.getElementById("pricing"))==null?void 0:D.scrollIntoView({behavior:"smooth"})},className:"px-10 py-7 text-lg font-semibold bg-white text-[#4a6b6d] hover:bg-white/90 shadow-2xl transition-all hover:scale-105",children:["Start Your Free Trial",e.jsx(Oa,{className:"ml-2 w-5 h-5"})]}),e.jsx(B,{size:"lg",onClick:()=>n("/auth"),className:"px-10 py-7 text-lg font-semibold border-2 border-white text-white bg-transparent hover:bg-white hover:text-[#4a6b6d]",children:"Sign In"})]})]})})]}),e.jsx("footer",{className:"py-12 bg-[#3d5a5c] text-white/80",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center justify-between gap-4",children:[e.jsx("img",{src:mfe,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(vJt,{open:w,onOpenChange:S}),e.jsx(_s,{open:c,onOpenChange:d,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{className:"text-xl font-sans font-semibold",children:"Enter your details to get started"}),e.jsx(Jn,{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(ne,{htmlFor:"dialog-name",children:["Full Name ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ye,{id:"dialog-name",type:"text",placeholder:"John Smith",value:p,onChange:D=>f(D.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ne,{htmlFor:"dialog-email",children:["Email Address ",e.jsx("span",{className:"text-red-500",children:"*"})]}),e.jsx(ye,{id:"dialog-email",type:"email",placeholder:"you@example.com",value:u,onChange:D=>h(D.target.value),className:"mt-1",required:!0})]}),e.jsxs("div",{children:[e.jsxs(ne,{htmlFor:"dialog-coupon",children:["Discount Code ",e.jsx("span",{className:"text-muted-foreground",children:"(Optional)"})]}),e.jsx(ye,{id:"dialog-coupon",type:"text",placeholder:"Enter discount code",value:y,onChange:D=>_(D.target.value),className:"mt-1"})]})]}),e.jsx(B,{className:"w-full py-6 text-lg bg-[#4a6b6d] hover:bg-[#3d5a5c]",onClick:O,disabled:v,children:v?"Loading...":"Continue to Checkout"})]})})]})},q$e=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{children:[e.jsx("title",{children:"Privacy Policy | LevelUp"}),e.jsx("meta",{name:"description",content:"Privacy Policy for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Privacy Policy"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Introduction"}),e.jsx("p",{children:'Welcome to LevelUp ("we," "our," or "us"). We are committed to protecting your personal information and your right to privacy. This Privacy Policy explains how we collect, use, disclose, and safeguard your information when you use our platform.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Information We Collect"}),e.jsx("p",{children:"We collect information that you provide directly to us, including:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Name and contact information (email address, phone number)"}),e.jsx("li",{children:"Account credentials"}),e.jsx("li",{children:"Profile information"}),e.jsx("li",{children:"Transaction and billing information"}),e.jsx("li",{children:"Communications you send to us"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. How We Use Your Information"}),e.jsx("p",{children:"We use the information we collect to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide, maintain, and improve our services"}),e.jsx("li",{children:"Process transactions and send related information"}),e.jsx("li",{children:"Send you technical notices and support messages"}),e.jsx("li",{children:"Respond to your comments and questions"}),e.jsx("li",{children:"Communicate with you about products, services, and events"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Information Sharing"}),e.jsx("p",{children:"We do not sell, trade, or otherwise transfer your personal information to third parties without your consent, except as described in this policy or as required by law."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Data Security"}),e.jsx("p",{children:"We implement appropriate technical and organizational measures to protect the security of your personal information. However, no method of transmission over the Internet is 100% secure."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Your Rights"}),e.jsx("p",{children:"You have the right to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Access your personal information"}),e.jsx("li",{children:"Correct inaccurate data"}),e.jsx("li",{children:"Request deletion of your data"}),e.jsx("li",{children:"Opt-out of marketing communications"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. SMS / Text Messaging Program & Mobile Information"}),e.jsx("p",{children:"Your privacy is important to us. This section outlines how we collect, use, and protect your information when you use our services, including our SMS/text messaging program."}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Information We Collect:"})," We collect personal information you provide, including your name, email address, phone number, and mobile number when you opt in to receive text messages from us."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"How We Use Your Information:"})," If you opt in, we use your mobile number to send SMS account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"No Sharing of Mobile Information:"})," No mobile information will be shared with third parties/affiliates for marketing/promotional purposes. All the above categories exclude text messaging originator opt-in data and consent; this information will not be shared with any third parties."]}),e.jsxs("p",{className:"mt-3",children:[e.jsx("strong",{className:"text-foreground",children:"Your Rights:"})," You have the right to access, modify, or delete your personal information at any time. You may opt out of text messages at any time by replying STOP to any message. Reply HELP for help. Message and data rates may apply. Message frequency varies."]}),e.jsxs("p",{className:"mt-3",children:["For questions about this policy, contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Third-Party Services"}),e.jsx("p",{children:"Our platform may integrate with third-party services such as Facebook and Instagram for social media posting features. When you connect these accounts, you are subject to their respective privacy policies."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. SMS Privacy Policy"}),e.jsx("p",{children:"We collect contact information you provide to us, including your name, email address, phone number, and business details, in order to provide our services, respond to inquiries, and deliver requested communications."}),e.jsx("p",{className:"mt-3",children:"If you choose to opt in to SMS communications from LevelUp, we may send you text messages including account notifications, real-time lead alerts, service updates, and customer support communications related to your LevelUp account."}),e.jsx("p",{className:"mt-3",children:"SMS consent is not shared with third parties or affiliates for marketing purposes. Mobile information will not be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties, except with vendors, aggregators, and providers that help us deliver these text messages."}),e.jsx("p",{className:"mt-3",children:"Message frequency may vary depending on your activity and use of our services. Message and data rates may apply."}),e.jsxs("p",{className:"mt-3",children:["You can opt out at any time by replying STOP. For help, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:hello@relevelup.com",className:"text-primary hover:underline",children:"hello@relevelup.com"}),"."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. Contact Us"}),e.jsxs("p",{children:["If you have questions about this Privacy Policy, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),V$e=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{children:[e.jsx("title",{children:"Terms of Service | LevelUp"}),e.jsx("meta",{name:"description",content:"Terms of Service for LevelUp platform"})]}),e.jsx("div",{className:"min-h-screen bg-background py-12 px-4 sm:px-6 lg:px-8",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground mb-8",children:"Terms of Service"}),e.jsxs("div",{className:"prose prose-sm max-w-none text-muted-foreground space-y-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last updated: January 17, 2026"}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"1. Acceptance of Terms"}),e.jsx("p",{children:'By accessing or using the LevelUp platform ("Service"), you agree to be bound by these Terms of Service. If you do not agree to these terms, please do not use our Service.'})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"2. Description of Service"}),e.jsx("p",{children:"LevelUp provides a platform for real estate professionals to access training, resources, marketing tools, and community features. We reserve the right to modify or discontinue the Service at any time."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"3. User Accounts"}),e.jsx("p",{children:"To use certain features, you must create an account. You agree to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Provide accurate and complete information"}),e.jsx("li",{children:"Maintain the security of your account credentials"}),e.jsx("li",{children:"Notify us immediately of any unauthorized access"}),e.jsx("li",{children:"Accept responsibility for all activities under your account"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"4. Acceptable Use"}),e.jsx("p",{children:"You agree not to:"}),e.jsxs("ul",{className:"list-disc pl-6 mt-2 space-y-1",children:[e.jsx("li",{children:"Violate any applicable laws or regulations"}),e.jsx("li",{children:"Infringe on the rights of others"}),e.jsx("li",{children:"Upload malicious code or interfere with the Service"}),e.jsx("li",{children:"Attempt to gain unauthorized access to any part of the Service"}),e.jsx("li",{children:"Use the Service for any unlawful purpose"})]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"5. Intellectual Property"}),e.jsx("p",{children:"The Service and its original content, features, and functionality are owned by LevelUp and are protected by international copyright, trademark, and other intellectual property laws."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"6. Third-Party Integrations"}),e.jsx("p",{children:"Our Service may integrate with third-party platforms such as Facebook and Instagram. Your use of these integrations is subject to the terms and policies of those third parties. We are not responsible for the content or practices of any third-party services."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"7. Payment Terms"}),e.jsx("p",{children:"Certain features may require payment. By subscribing to paid features, you agree to pay all applicable fees. All payments are non-refundable unless otherwise specified."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"8. Limitation of Liability"}),e.jsx("p",{children:"To the maximum extent permitted by law, LevelUp shall not be liable for any indirect, incidental, special, consequential, or punitive damages resulting from your use of the Service."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"9. Termination"}),e.jsx("p",{children:"We may terminate or suspend your account at any time, without prior notice, for conduct that we believe violates these Terms or is harmful to other users, us, or third parties."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"10. Changes to Terms"}),e.jsx("p",{children:"We reserve the right to modify these Terms at any time. We will notify you of significant changes by posting a notice on our platform. Continued use of the Service constitutes acceptance of the modified terms."})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"11. SMS / Text Messaging Terms"}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 mb-4 text-sm",children:[e.jsx("strong",{children:"To opt in:"})," Submit our public SMS opt-in form at"," ",e.jsx("a",{href:"/sms-opt-in",className:"text-primary hover:underline font-medium",children:"/sms-opt-in"})," ","— consent is captured with timestamp and the exact disclosure text shown below."]}),e.jsx("p",{children:"By opting in to receive text messages from LevelUp, you agree to the following terms:"}),e.jsx("p",{className:"mt-2",children:"You consent to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Consent is not a condition of purchase."}),e.jsxs("p",{className:"mt-2",children:["You may opt out at any time by replying STOP to any message. After opting out, you will receive a confirmation message and no further messages will be sent. For assistance, reply HELP or contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"}),"."]}),e.jsxs("p",{className:"mt-2",children:["No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties. See our"," ",e.jsx("a",{href:"/privacy-policy",className:"text-primary hover:underline",children:"Privacy Policy"})," ","for full details."]})]}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground mt-8 mb-4",children:"12. Contact Us"}),e.jsxs("p",{children:["If you have questions about these Terms, please contact us at"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})]})]})]})})]}),NJt=()=>e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{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"})]})]})]})]})})]}),H$e="I agree to receive recurring SMS/MMS messages from LevelUp, including account notifications, real-time lead alerts, service updates, and customer support communications. Message frequency varies. Message and data rates may apply. Reply STOP to opt out and HELP for help. Consent is not a condition of purchase.",kJt=Gw({name:fo().trim().min(1,"Name is required").max(200),phone:fo().trim().min(10,"Enter a valid mobile number").max(30).regex(/^[+\d\s()\-.]+$/,"Enter a valid mobile number"),email:fo().trim().email("Enter a valid email").max(320).optional().or(bp(""))});function SJt(){const[s,t]=N.useState(""),[n,r]=N.useState(""),[a,i]=N.useState(""),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),p=async f=>{var v;if(f.preventDefault(),!l){ae.error("Please check the consent box to opt in.");return}const y=kJt.safeParse({name:s,phone:n,email:a});if(!y.success){ae.error(((v=y.error.issues[0])==null?void 0:v.message)??"Please check your inputs.");return}d(!0);const{error:_}=await q.from("sms_opt_in_consents").insert({name:y.data.name,phone:y.data.phone,email:y.data.email||null,consent_text:H$e,source:"web_form",user_agent:navigator.userAgent.slice(0,500)});if(d(!1),_){ae.error("Something went wrong. Please try again.");return}h(!0)};return e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-background via-background to-muted/30 py-10 px-4",children:[e.jsxs(Zo,{children:[e.jsx("title",{children:"SMS Opt-In | LevelUp"}),e.jsx("meta",{name:"description",content:"Opt in to receive SMS account notifications and real-time lead alerts from LevelUp. Review consent terms, message frequency, and STOP/HELP instructions."}),e.jsx("link",{rel:"canonical",href:"https://dashboard.relevelup.com/sms-opt-in"})]}),e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs("header",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-14 h-14 rounded-2xl bg-primary/10 text-primary mb-4",children:e.jsx(Ai,{className:"w-7 h-7"})}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"LevelUp — SMS Opt-In"}),e.jsx("p",{className:"text-muted-foreground mt-3 max-w-xl mx-auto",children:"Sign up to receive SMS account notifications and real-time lead alerts from LevelUp. These messages help subscribed real estate agents review and respond to new consumer inquiries submitted through their websites."})]}),u?e.jsxs(fe,{className:"p-8 text-center",children:[e.jsx(vr,{className:"w-14 h-14 text-primary mx-auto mb-4"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're opted in!"}),e.jsxs("p",{className:"text-muted-foreground",children:["You'll now receive SMS account notifications and real-time lead alerts from LevelUp. Reply ",e.jsx("strong",{children:"STOP"})," at any time to opt out, or ",e.jsx("strong",{children:"HELP"})," for assistance."]})]}):e.jsx(fe,{className:"p-6 md:p-8",children:e.jsxs("form",{onSubmit:p,className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"name",children:"Full Name *"}),e.jsx(ye,{id:"name",value:s,onChange:f=>t(f.target.value),required:!0,maxLength:200,autoComplete:"name",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"phone",children:"Mobile Number *"}),e.jsx(ye,{id:"phone",type:"tel",value:n,onChange:f=>r(f.target.value),required:!0,maxLength:30,placeholder:"(555) 123-4567",autoComplete:"tel",className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"email",children:"Email (optional)"}),e.jsx(ye,{id:"email",type:"email",value:a,onChange:f=>i(f.target.value),maxLength:320,autoComplete:"email",className:"mt-1.5"})]}),e.jsx("div",{className:"rounded-lg border bg-muted/30 p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(hi,{id:"consent",checked:l,onCheckedChange:f=>o(f===!0),className:"mt-0.5"}),e.jsx(ne,{htmlFor:"consent",className:"text-sm leading-relaxed font-normal cursor-pointer",children:H$e})]})}),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(In,{to:"/terms-of-service",className:"text-primary underline underline-offset-2",children:"SMS Terms & Conditions"})," ","and"," ",e.jsx(In,{to:"/privacy-policy",className:"text-primary underline underline-offset-2",children:"Privacy Policy"}),"."]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Message types:"})," account notifications, real-time lead alerts, service updates, customer support."," ",e.jsx("strong",{children:"Frequency:"})," varies."," ",e.jsx("strong",{children:"Msg & data rates may apply."})," ","Reply ",e.jsx("strong",{children:"STOP"})," to opt out, ",e.jsx("strong",{children:"HELP"})," for help."]}),e.jsx("p",{children:"No mobile information will be shared with third parties or affiliates for marketing or promotional purposes. Text messaging originator opt-in data and consent will not be shared with any third parties."})]}),e.jsx(B,{type:"submit",disabled:!l||c,className:"w-full",size:"lg",children:c?"Submitting…":"Opt in to SMS"}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-muted-foreground pt-2",children:[e.jsx(eg,{className:"w-3.5 h-3.5"}),"Secure consent record stored for compliance."]})]})}),e.jsx("footer",{className:"text-center mt-8 text-xs text-muted-foreground",children:e.jsxs("p",{children:["LevelUp · Questions? Email"," ",e.jsx("a",{href:"mailto:support@relevelup.com",className:"text-primary hover:underline",children:"support@relevelup.com"})]})})]})]})}const vht="/assets/levelup-logo-horizontal-DEFNc0ms.png",CJt=Gw({email:fo().email("Invalid email address"),password:fo().min(6,"Password must be at least 6 characters")}),TJt="https://dashboard.relevelup.com",nH="/oauth-connect",Tme="levelupOAuthRouteHistory";function G$e(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function EJt(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(Tme)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(Tme,JSON.stringify([{route:s,at:t}])),!1}}function AJt(){sessionStorage.removeItem(Tme)}const MJt=()=>{const{signIn:s,user:t,loading:n}=vs(),r=(t==null?void 0:t.id)??null,a=Ln(),[i]=xl(),l=i.get("authorization_id")??"",o=i.get("next")??"",[c,d]=N.useState(!1),[u,h]=N.useState({}),[p,f]=N.useState(""),[y,_]=N.useState(!1),[v,j]=N.useState(!1),[w,S]=N.useState(null),A=N.useRef(!1);N.useEffect(()=>{if(l&&window.location.hostname==="tile-portal.lovable.app"){const D=new URL("/auth",TJt);D.searchParams.set("next",`${nH}?authorization_id=${encodeURIComponent(l)}`),window.location.replace(D.toString());return}if(l){const D=`${nH}?authorization_id=${encodeURIComponent(l)}`;sessionStorage.setItem("redirectAfterLogin",D);return}o&&G$e(o)&&sessionStorage.setItem("redirectAfterLogin",o)},[l,o]),N.useEffect(()=>{if(n||!r||A.current)return;const D=l?`${nH}?authorization_id=${encodeURIComponent(l)}`:sessionStorage.getItem("redirectAfterLogin")||"/dashboard";if(!G$e(D)){sessionStorage.removeItem("redirectAfterLogin"),A.current=!0,a("/dashboard",{replace:!0});return}const I=D.startsWith(nH)||D.startsWith("/oauth/consent")||D.startsWith("/.lovable/oauth/consent");if(I&&EJt("auth")){S("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}A.current=!0,I||(AJt(),sessionStorage.removeItem("redirectAfterLogin")),a(D,{replace:!0})},[l,n,a,r]);const E=async D=>{D.preventDefault(),h({}),d(!0);const I=new FormData(D.currentTarget),F=I.get("email"),z=I.get("password");try{CJt.parse({email:F,password:z}),await s(F,z)}catch(H){if(H instanceof eGt){const Z={};H.issues.forEach(Y=>{Y.path[0]&&(Z[Y.path[0]]=Y.message)}),h(Z)}}finally{d(!1)}},O=async()=>{if(!p){ae.error("Please enter your email address");return}_(!0);try{const{error:D}=await q.functions.invoke("send-password-reset",{body:{email:p,redirectTo:"https://dashboard.relevelup.com/profile?reset=true"}});if(D)throw D;ae.success("Password reset email sent! Check your inbox."),j(!1),f("")}catch(D){ae.error(D instanceof Error?D.message:"Failed to send reset email")}finally{_(!1)}};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]",children:e.jsxs("div",{className:"absolute inset-0 opacity-30",children:[e.jsx("div",{className:"absolute top-0 left-0 w-96 h-96 bg-white/10 rounded-full blur-3xl animate-pulse"}),e.jsx("div",{className:"absolute bottom-0 right-0 w-96 h-96 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl animate-pulse",style:{animationDelay:"2s"}})]})}),e.jsxs("div",{className:"relative z-10 flex flex-col min-h-screen",children:[e.jsx("header",{className:"p-6",children:e.jsxs(In,{to:"/",className:"inline-flex items-center gap-2 text-sm text-white/80 hover:text-white transition-colors",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back to Home"]})}),e.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:vht,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(fe,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(It,{className:"space-y-1 text-center pb-4",children:[e.jsx(Rt,{className:"text-3xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Welcome Back"}),e.jsx(Vn,{className:"text-gray-600",children:w||"Sign in to access your dashboard"})]}),e.jsx(Ee,{children:e.jsxs("form",{onSubmit:E,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"signin-email",className:"text-gray-700",children:"Email"}),e.jsx(ye,{id:"signin-email",name:"email",type:"email",placeholder:"your@email.com",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.email&&e.jsx("p",{className:"text-sm text-red-600",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"signin-password",className:"text-gray-700",children:"Password"}),e.jsx(ye,{id:"signin-password",name:"password",type:"password",required:!0,className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"}),u.password&&e.jsx("p",{className:"text-sm text-red-600",children:u.password})]}),e.jsx(B,{type:"submit",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg transition-all duration-200 shadow-lg hover:shadow-xl",disabled:c,children:c?"Signing in...":"Sign In"}),e.jsxs(_s,{open:v,onOpenChange:j,children:[e.jsx(ki,{asChild:!0,children:e.jsx(B,{variant:"link",className:"w-full text-sm text-[#4a6b6d] hover:text-[#3d5a5c]",children:"Forgot password?"})}),e.jsxs(bs,{className:"bg-white",children:[e.jsxs(js,{children:[e.jsx(ws,{className:"text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Password"}),e.jsx(Jn,{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(ne,{htmlFor:"reset-email",className:"text-gray-700",children:"Email"}),e.jsx(ye,{id:"reset-email",type:"email",placeholder:"your@email.com",value:p,onChange:D=>f(D.target.value),className:"border-gray-300 focus:border-[#4a6b6d] focus:ring-[#4a6b6d]"})]}),e.jsx(B,{onClick:O,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white",disabled:y,children:y?"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(In,{to:"/",className:"text-white hover:underline font-medium",children:"View Plans"})]})]})})]})]})},W$e=()=>q.auth.oauth,IJt="https://dashboard.relevelup.com",PJt="/oauth-connect",Eme="levelupOAuthRouteHistory",LJt="https://relzejiswnotikjgvjhz.supabase.co/auth/v1",DJt="eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM";function RJt(s){return s.startsWith("/")&&!s.startsWith("//")&&!s.includes("://")}function OJt(s){const t=Date.now(),n=15e3;try{const i=[...JSON.parse(sessionStorage.getItem(Eme)??"[]").filter(o=>t-o.ato.route));return i.length>=6&&l.has("auth")&&l.has("consent")}catch{return sessionStorage.setItem(Eme,JSON.stringify([{route:s,at:t}])),!1}}function FJt(){sessionStorage.removeItem(Eme)}async function K$e(s,t,n){const r=await fetch(`${LJt}${s}`,{...n,headers:{Authorization:`Bearer ${t}`,apikey:DJt,"Content-Type":"application/json",...(n==null?void 0:n.headers)??{}}}),a=await r.json().catch(()=>null);return r.ok?{data:a,error:null}:{data:null,error:{message:(a==null?void 0:a.msg)??(a==null?void 0:a.message)??(a==null?void 0:a.error_description)??(a==null?void 0:a.error)??"Authorization request failed."}}}function fje(){var _;const{user:s,session:t,loading:n}=vs(),r=(s==null?void 0:s.id)??null,a=(t==null?void 0:t.access_token)??null,[i]=xl(),l=i.get("authorization_id")??"",[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(!1);N.useEffect(()=>{let v=!0;return(async()=>{if(!l){u("Missing authorization_id");return}const j=`${PJt}?authorization_id=${encodeURIComponent(l)}`;if(window.location.hostname==="tile-portal.lovable.app"){window.location.href=`${IJt}${j}`;return}if(n)return;if(!r){if(OJt("consent")){u("We couldn't complete the OAuth sign-in handoff because the browser kept bouncing between sign-in and consent. Please refresh this page and try Connect again.");return}RJt(j)&&sessionStorage.setItem("redirectAfterLogin",j),window.location.replace(`/auth?next=${encodeURIComponent(j)}`);return}if(!a)return;FJt(),sessionStorage.removeItem("redirectAfterLogin");const w=W$e(),{data:S,error:A}=w?await w.getAuthorizationDetails(l):await K$e(`/oauth/authorizations/${encodeURIComponent(l)}`,a);if(!v)return;if(A){u(A.message);return}const E=(S==null?void 0:S.redirect_url)??(S==null?void 0:S.redirect_to);if(E&&!(S!=null&&S.client)){window.location.href=E;return}c(S)})(),()=>{v=!1}},[a,l,n,r]);async function f(v){if(!(t!=null&&t.access_token)){u("Your sign-in session is not ready yet. Please refresh and try again.");return}p(!0);const j=W$e(),{data:w,error:S}=j?v?await j.approveAuthorization(l,{skipBrowserRedirect:!0}):await j.denyAuthorization(l,{skipBrowserRedirect:!0}):await K$e(`/oauth/authorizations/${encodeURIComponent(l)}/consent`,t.access_token,{method:"POST",body:JSON.stringify({action:v?"approve":"deny"})});if(S){p(!1),u(S.message);return}const A=(w==null?void 0:w.redirect_url)??(w==null?void 0:w.redirect_to);if(!A){p(!1),u("No redirect returned by the authorization server.");return}window.location.href=A}if(d)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsx(fe,{className:"w-full max-w-md",children:e.jsxs(It,{children:[e.jsx(Rt,{children:"Authorization error"}),e.jsx(Vn,{children:d})]})})});if(!o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-primary"})});const y=((_=o.client)==null?void 0:_.name)??"An app";return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{children:[e.jsxs(Rt,{children:["Connect ",y," to LevelUp"]}),e.jsxs(Vn,{children:[y," is requesting access to use LevelUp tools on your behalf. You can revoke access at any time."]})]}),e.jsxs(Ee,{className:"flex gap-3 justify-end",children:[e.jsx(B,{variant:"outline",disabled:h,onClick:()=>f(!1),children:"Deny"}),e.jsx(B,{disabled:h,onClick:()=>f(!0),children:h?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):"Approve"})]})]})})}const bht=s=>{const[t,n]=N.useState(null),[r,a]=N.useState(!0);return N.useEffect(()=>{if(!s){a(!1);return}(async()=>{try{const{data:o}=await q.storage.from("avatars").list(`${s}`);if(o&&o.length>0){const{data:c}=q.storage.from("avatars").getPublicUrl(`${s}/${o[0].name}`);n(`${c.publicUrl}?t=${Date.now()}`)}else n(null)}catch(o){console.error("Error fetching avatar:",o),n(null)}finally{a(!1)}})()},[s]),{avatarUrl:t,loading:r,refreshAvatar:async()=>{if(s)try{const{data:l}=await q.storage.from("avatars").list(`${s}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s}/${l[0].name}`);n(`${o.publicUrl}?t=${Date.now()}`)}}catch(l){console.error("Error refreshing avatar:",l)}}}},_ht=async s=>{const t=new Map;return await Promise.all(s.map(async n=>{try{const{data:r}=await q.storage.from("avatars").list(`${n}`);if(r&&r.length>0){const{data:a}=q.storage.from("avatars").getPublicUrl(`${n}/${r[0].name}`);t.set(n,a.publicUrl)}}catch{}})),t},zJt=s=>{const[t,n]=N.useState({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!0});return N.useEffect(()=>{if(!s){n(a=>({...a,loading:!1}));return}(async()=>{try{const{data:a,error:i}=await q.from("profiles").select("is_trial, trial_expires_at, subscription_status, subscription_end_date").eq("id",s).single();if(i){console.error("Error fetching trial status:",i),n(h=>({...h,loading:!1}));return}const l=(a==null?void 0:a.subscription_status)==="trialing",o=!!(a!=null&&a.is_trial),c=!!(a!=null&&a.trial_expires_at)&&new Date(a.trial_expires_at).getTime()>Date.now()&&(a==null?void 0:a.subscription_status)!=="active",d=l&&(a==null?void 0:a.subscription_end_date)||(a==null?void 0:a.trial_expires_at)||(a==null?void 0:a.subscription_end_date)||null;if((l||o||c)&&!!d&&d){const h=new Date().getTime(),p=new Date(d).getTime(),f=Math.ceil((p-h)/(1e3*60*60*24)),y=f<=0;n({isTrial:!0,isExpired:y,expiresAt:d,daysLeft:y?0:f,loading:!1})}else n({isTrial:!1,isExpired:!1,expiresAt:null,daysLeft:null,loading:!1})}catch(a){console.error("Error in useTrialStatus:",a),n(i=>({...i,loading:!1}))}})()},[s]),t},wht=()=>{const{data:s,isLoading:t}=dt({queryKey:["feature-flags"],queryFn:async()=>{const{data:r,error:a}=await q.from("feature_flags").select("*");if(a)throw a;return r}}),n=r=>{if(!s)return!1;const a=s.find(i=>i.key===r);return(a==null?void 0:a.enabled)??!1};return{flags:s,isLoading:t,isFeatureEnabled:n,isAgentOSEnabled:n("agent_os_enabled"),isInnerCircleEnabled:n("innercircle_enabled"),isMarketplaceEnabled:n("marketplace")}},Y$e="community_last_seen_post_at";function BJt(){const{user:s}=vs(),t=Xl(),[n,r]=N.useState(0),[a,i]=N.useState(null);N.useEffect(()=>{if(!s)return;const o=localStorage.getItem(`${Y$e}_${s.id}`);i(o)},[s]),N.useEffect(()=>{if(!s)return;const o=`community_unread_count_${s.id}`,c=2*60*1e3;(async()=>{try{const f=sessionStorage.getItem(o);if(f){const y=JSON.parse(f);if(y.ts&&Date.now()-y.ts{if(!s)return;const o=q.channel("community-new-posts").on("postgres_changes",{event:"INSERT",schema:"public",table:"community_posts"},async c=>{const d=c.new;if(d.user_id===s.id)return;const u=t.pathname==="/community";u||r(_=>_+1);const{data:h}=await q.from("profiles").select("name").eq("id",d.user_id).single(),p=(h==null?void 0:h.name)||"Someone",f=d.content.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),y=f.length>50?f.substring(0,50)+"...":f;u||ae("New Community Post",{description:`${p}: ${y}`,action:{label:"View",onClick:()=>{window.location.href="/community"}}})}).subscribe();return()=>{q.removeChannel(o)}},[s,t.pathname]);const l=N.useCallback(()=>{if(!s)return;const o=new Date().toISOString();localStorage.setItem(`${Y$e}_${s.id}`,o),i(o),r(0)},[s]);return N.useEffect(()=>{t.pathname==="/community"&&n>0&&l()},[t.pathname,n,l]),{unreadCount:n,markAsRead:l}}function $Jt(){const{isAdmin:s}=vs(),{data:t=0}=dt({queryKey:["wishlist-open-count"],queryFn:async()=>{const{count:n,error:r}=await q.from("wishlist_items").select("*",{count:"exact",head:!0}).eq("status","open");if(r)throw r;return n||0},enabled:s,staleTime:6e4});return{openCount:s?t:0}}var gye="Collapsible",[UJt,jht]=uu(gye),[qJt,LMe]=UJt(gye),Nht=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,open:r,defaultOpen:a,disabled:i,onOpenChange:l,...o}=s,[c,d]=cm({prop:r,defaultProp:a??!1,onChange:l,caller:gye});return e.jsx(qJt,{scope:n,disabled:i,contentId:om(),open:c,onOpenToggle:N.useCallback(()=>d(u=>!u),[d]),children:e.jsx(Yr.div,{"data-state":FMe(c),"data-disabled":i?"":void 0,...o,ref:t})})});Nht.displayName=gye;var kht="CollapsibleTrigger",DMe=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,...r}=s,a=LMe(kht,n);return e.jsx(Yr.button,{type:"button","aria-controls":a.contentId,"aria-expanded":a.open||!1,"data-state":FMe(a.open),"data-disabled":a.disabled?"":void 0,disabled:a.disabled,...r,ref:t,onClick:xr(s.onClick,a.onOpenToggle)})});DMe.displayName=kht;var RMe="CollapsibleContent",OMe=N.forwardRef((s,t)=>{const{forceMount:n,...r}=s,a=LMe(RMe,s.__scopeCollapsible);return e.jsx(Lh,{present:n||a.open,children:({present:i})=>e.jsx(VJt,{...r,ref:t,present:i})})});OMe.displayName=RMe;var VJt=N.forwardRef((s,t)=>{const{__scopeCollapsible:n,present:r,children:a,...i}=s,l=LMe(RMe,n),[o,c]=N.useState(r),d=N.useRef(null),u=ji(t,d),h=N.useRef(0),p=h.current,f=N.useRef(0),y=f.current,_=l.open||o,v=N.useRef(_),j=N.useRef(void 0);return N.useEffect(()=>{const w=requestAnimationFrame(()=>v.current=!1);return()=>cancelAnimationFrame(w)},[]),lh(()=>{const w=d.current;if(w){j.current=j.current||{transitionDuration:w.style.transitionDuration,animationName:w.style.animationName},w.style.transitionDuration="0s",w.style.animationName="none";const S=w.getBoundingClientRect();h.current=S.height,f.current=S.width,v.current||(w.style.transitionDuration=j.current.transitionDuration,w.style.animationName=j.current.animationName),c(r)}},[l.open,r]),e.jsx(Yr.div,{"data-state":FMe(l.open),"data-disabled":l.disabled?"":void 0,id:l.contentId,hidden:!_,...i,ref:u,style:{"--radix-collapsible-content-height":p?`${p}px`:void 0,"--radix-collapsible-content-width":y?`${y}px`:void 0,...s.style},children:_&&a})});function FMe(s){return s?"open":"closed"}var Sht=Nht,HJt=DMe,GJt=OMe;const oy=Sht,ly=DMe,cy=OMe,WJt="/assets/levelup-logo-Eif24dqY.png",KJt="/assets/levelup-logo-icon-C-7iromj.png",YJt="/assets/levelup-logo-mobile-B9skSjUG.png";var sU=s=>s.type==="checkbox",qE=s=>s instanceof Date,Ux=s=>s==null;const Cht=s=>typeof s=="object";var Ph=s=>!Ux(s)&&!Array.isArray(s)&&Cht(s)&&!qE(s),Tht=s=>Ph(s)&&s.target?sU(s.target)?s.target.checked:s.target.value:s,ZJt=s=>s.substring(0,s.search(/\.\d+(\.|$)/))||s,Eht=(s,t)=>s.has(ZJt(t)),QJt=s=>{const t=s.constructor&&s.constructor.prototype;return Ph(t)&&t.hasOwnProperty("isPrototypeOf")},zMe=typeof window<"u"&&typeof window.HTMLElement<"u"&&typeof document<"u";function km(s){let t;const n=Array.isArray(s),r=typeof FileList<"u"?s instanceof FileList:!1;if(s instanceof Date)t=new Date(s);else if(!(zMe&&(s instanceof Blob||r))&&(n||Ph(s)))if(t=n?[]:{},!n&&!QJt(s))t=s;else for(const a in s)s.hasOwnProperty(a)&&(t[a]=km(s[a]));else return s;return t}var yye=s=>/^\w*$/.test(s),bh=s=>s===void 0,BMe=s=>Array.isArray(s)?s.filter(Boolean):[],$Me=s=>BMe(s.replace(/["|']|\]/g,"").split(/\.|\[/)),Ea=(s,t,n)=>{if(!t||!Ph(s))return n;const r=(yye(t)?[t]:$Me(t)).reduce((a,i)=>Ux(a)?a:a[i],s);return bh(r)||r===s?bh(s[t])?n:s[t]:r},U0=s=>typeof s=="boolean",bc=(s,t,n)=>{let r=-1;const a=yye(t)?[t]:$Me(t),i=a.length,l=i-1;for(;++rCt.useContext(UMe),XJt=s=>{const{children:t,...n}=s;return Ct.createElement(UMe.Provider,{value:n},t)};var Aht=(s,t,n,r=!0)=>{const a={defaultValues:t._defaultValues};for(const i in s)Object.defineProperty(a,i,{get:()=>{const l=i;return t._proxyFormState[l]!==eb.all&&(t._proxyFormState[l]=!r||eb.all),n&&(n[l]=!0),s[l]}});return a};const qMe=typeof window<"u"?Ct.useLayoutEffect:Ct.useEffect;function JJt(s){const t=vye(),{control:n=t.control,disabled:r,name:a,exact:i}=s||{},[l,o]=Ct.useState(n._formState),c=Ct.useRef({isDirty:!1,isLoading:!1,dirtyFields:!1,touchedFields:!1,validatingFields:!1,isValidating:!1,isValid:!1,errors:!1});return qMe(()=>n._subscribe({name:a,formState:c.current,exact:i,callback:d=>{!r&&o({...n._formState,...d})}}),[a,r,i]),Ct.useEffect(()=>{c.current.isValid&&n._setValid(!0)},[n]),Ct.useMemo(()=>Aht(l,n,c.current,!1),[l,n])}var J_=s=>typeof s=="string",Mht=(s,t,n,r,a)=>J_(s)?(r&&t.watch.add(s),Ea(n,s,a)):Array.isArray(s)?s.map(i=>(r&&t.watch.add(i),Ea(n,i))):(r&&(t.watchAll=!0),n),K4e=s=>Ux(s)||!Cht(s);function E2(s,t,n=new WeakSet){if(K4e(s)||K4e(t))return s===t;if(qE(s)&&qE(t))return s.getTime()===t.getTime();const r=Object.keys(s),a=Object.keys(t);if(r.length!==a.length)return!1;if(n.has(s)||n.has(t))return!0;n.add(s),n.add(t);for(const i of r){const l=s[i];if(!a.includes(i))return!1;if(i!=="ref"){const o=t[i];if(qE(l)&&qE(o)||Ph(l)&&Ph(o)||Array.isArray(l)&&Array.isArray(o)?!E2(l,o,n):l!==o)return!1}}return!0}function ees(s){const t=vye(),{control:n=t.control,name:r,defaultValue:a,disabled:i,exact:l,compute:o}=s||{},c=Ct.useRef(a),d=Ct.useRef(o),u=Ct.useRef(void 0);d.current=o;const h=Ct.useMemo(()=>n._getWatch(r,c.current),[n,r]),[p,f]=Ct.useState(d.current?d.current(h):h);return qMe(()=>n._subscribe({name:r,formState:{values:!0},exact:l,callback:y=>{if(!i){const _=Mht(r,n._names,y.values||n._formValues,!1,c.current);if(d.current){const v=d.current(_);E2(v,u.current)||(f(v),u.current=v)}else f(_)}}}),[n,i,r,l]),Ct.useEffect(()=>n._removeUnmounted()),p}function tes(s){const t=vye(),{name:n,disabled:r,control:a=t.control,shouldUnregister:i,defaultValue:l}=s,o=Eht(a._names.array,n),c=Ct.useMemo(()=>Ea(a._formValues,n,Ea(a._defaultValues,n,l)),[a,n,l]),d=ees({control:a,name:n,defaultValue:c,exact:!0}),u=JJt({control:a,name:n,exact:!0}),h=Ct.useRef(s),p=Ct.useRef(a.register(n,{...s.rules,value:d,...U0(s.disabled)?{disabled:s.disabled}:{}}));h.current=s;const f=Ct.useMemo(()=>Object.defineProperties({},{invalid:{enumerable:!0,get:()=>!!Ea(u.errors,n)},isDirty:{enumerable:!0,get:()=>!!Ea(u.dirtyFields,n)},isTouched:{enumerable:!0,get:()=>!!Ea(u.touchedFields,n)},isValidating:{enumerable:!0,get:()=>!!Ea(u.validatingFields,n)},error:{enumerable:!0,get:()=>Ea(u.errors,n)}}),[u,n]),y=Ct.useCallback(w=>p.current.onChange({target:{value:Tht(w),name:n},type:pfe.CHANGE}),[n]),_=Ct.useCallback(()=>p.current.onBlur({target:{value:Ea(a._formValues,n),name:n},type:pfe.BLUR}),[n,a._formValues]),v=Ct.useCallback(w=>{const S=Ea(a._fields,n);S&&w&&(S._f.ref={focus:()=>w.focus&&w.focus(),select:()=>w.select&&w.select(),setCustomValidity:A=>w.setCustomValidity(A),reportValidity:()=>w.reportValidity()})},[a._fields,n]),j=Ct.useMemo(()=>({name:n,value:d,...U0(r)||u.disabled?{disabled:u.disabled||r}:{},onChange:y,onBlur:_,ref:v}),[n,r,u.disabled,y,_,v,d]);return Ct.useEffect(()=>{const w=a._options.shouldUnregister||i;a.register(n,{...h.current.rules,...U0(h.current.disabled)?{disabled:h.current.disabled}:{}});const S=(A,E)=>{const O=Ea(a._fields,A);O&&O._f&&(O._f.mount=E)};if(S(n,!0),w){const A=km(Ea(a._options.defaultValues,n));bc(a._defaultValues,n,A),bh(Ea(a._formValues,n))&&bc(a._formValues,n,A)}return!o&&a.register(n),()=>{(o?w&&!a._state.action:w)?a.unregister(n):S(n,!1)}},[n,a,o,i]),Ct.useEffect(()=>{a._setDisabledField({disabled:r,name:n})},[r,n,a]),Ct.useMemo(()=>({field:j,formState:u,fieldState:f}),[j,u,f])}const ses=s=>s.render(tes(s));var Iht=(s,t,n,r,a)=>t?{...n[s],types:{...n[s]&&n[s].types?n[s].types:{},[r]:a||!0}}:{},H9=s=>Array.isArray(s)?s:[s],Z$e=()=>{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=[]}}},Cg=s=>Ph(s)&&!Object.keys(s).length,VMe=s=>s.type==="file",tb=s=>typeof s=="function",ffe=s=>{if(!zMe)return!1;const t=s?s.ownerDocument:0;return s instanceof(t&&t.defaultView?t.defaultView.HTMLElement:HTMLElement)},Pht=s=>s.type==="select-multiple",HMe=s=>s.type==="radio",nes=s=>HMe(s)||sU(s),xje=s=>ffe(s)&&s.isConnected;function res(s,t){const n=t.slice(0,-1).length;let r=0;for(;r{for(const t in s)if(tb(s[t]))return!0;return!1};function xfe(s,t={}){const n=Array.isArray(s);if(Ph(s)||n)for(const r in s)Array.isArray(s[r])||Ph(s[r])&&!Lht(s[r])?(t[r]=Array.isArray(s[r])?[]:{},xfe(s[r],t[r])):Ux(s[r])||(t[r]=!0);return t}function Dht(s,t,n){const r=Array.isArray(s);if(Ph(s)||r)for(const a in s)Array.isArray(s[a])||Ph(s[a])&&!Lht(s[a])?bh(t)||K4e(n[a])?n[a]=Array.isArray(s[a])?xfe(s[a],[]):{...xfe(s[a])}:Dht(s[a],Ux(t)?{}:t[a],n[a]):n[a]=!E2(s[a],t[a]);return n}var tF=(s,t)=>Dht(s,t,xfe(t));const Q$e={value:!1,isValid:!1},X$e={value:!0,isValid:!0};var Rht=s=>{if(Array.isArray(s)){if(s.length>1){const t=s.filter(n=>n&&n.checked&&!n.disabled).map(n=>n.value);return{value:t,isValid:!!t.length}}return s[0].checked&&!s[0].disabled?s[0].attributes&&!bh(s[0].attributes.value)?bh(s[0].value)||s[0].value===""?X$e:{value:s[0].value,isValid:!0}:X$e:Q$e}return Q$e},Oht=(s,{valueAsNumber:t,valueAsDate:n,setValueAs:r})=>bh(s)?s:t?s===""?NaN:s&&+s:n&&J_(s)?new Date(s):r?r(s):s;const J$e={isValid:!1,value:null};var Fht=s=>Array.isArray(s)?s.reduce((t,n)=>n&&n.checked&&!n.disabled?{isValid:!0,value:n.value}:t,J$e):J$e;function eUe(s){const t=s.ref;return VMe(t)?t.files:HMe(t)?Fht(s.refs).value:Pht(t)?[...t.selectedOptions].map(({value:n})=>n):sU(t)?Rht(s.refs).value:Oht(bh(t.value)?s.ref.value:t.value,s)}var ies=(s,t,n,r)=>{const a={};for(const i of s){const l=Ea(t,i);l&&bc(a,i,l._f)}return{criteriaMode:n,names:[...s],fields:a,shouldUseNativeValidation:r}},gfe=s=>s instanceof RegExp,sF=s=>bh(s)?s:gfe(s)?s.source:Ph(s)?gfe(s.value)?s.value.source:s.value:s,tUe=s=>({isOnSubmit:!s||s===eb.onSubmit,isOnBlur:s===eb.onBlur,isOnChange:s===eb.onChange,isOnAll:s===eb.all,isOnTouch:s===eb.onTouched});const sUe="AsyncFunction";var oes=s=>!!s&&!!s.validate&&!!(tb(s.validate)&&s.validate.constructor.name===sUe||Ph(s.validate)&&Object.values(s.validate).find(t=>t.constructor.name===sUe)),les=s=>s.mount&&(s.required||s.min||s.max||s.maxLength||s.minLength||s.pattern||s.validate),nUe=(s,t,n)=>!n&&(t.watchAll||t.watch.has(s)||[...t.watch].some(r=>s.startsWith(r)&&/^\.\w+/.test(s.slice(r.length))));const G9=(s,t,n,r)=>{for(const a of n||Object.keys(s)){const i=Ea(s,a);if(i){const{_f:l,...o}=i;if(l){if(l.refs&&l.refs[0]&&t(l.refs[0],a)&&!r)return!0;if(l.ref&&t(l.ref,l.name)&&!r)return!0;if(G9(o,t))break}else if(Ph(o)&&G9(o,t))break}}};function rUe(s,t,n){const r=Ea(s,n);if(r||yye(n))return{error:r,name:n};const a=n.split(".");for(;a.length;){const i=a.join("."),l=Ea(t,i),o=Ea(s,i);if(l&&!Array.isArray(l)&&n!==i)return{name:n};if(o&&o.type)return{name:i,error:o};if(o&&o.root&&o.root.type)return{name:`${i}.root`,error:o.root};a.pop()}return{name:n}}var ces=(s,t,n,r)=>{n(s);const{name:a,...i}=s;return Cg(i)||Object.keys(i).length>=Object.keys(t).length||Object.keys(i).find(l=>t[l]===(!r||eb.all))},des=(s,t,n)=>!s||!t||s===t||H9(s).some(r=>r&&(n?r===t:r.startsWith(t)||t.startsWith(r))),ues=(s,t,n,r,a)=>a.isOnAll?!1:!n&&a.isOnTouch?!(t||s):(n?r.isOnBlur:a.isOnBlur)?!s:(n?r.isOnChange:a.isOnChange)?s:!0,hes=(s,t)=>!BMe(Ea(s,t)).length&&Hh(s,t),mes=(s,t,n)=>{const r=H9(Ea(s,n));return bc(r,"root",t[n]),bc(s,n,r),s},Ame=s=>J_(s);function aUe(s,t,n="validate"){if(Ame(s)||Array.isArray(s)&&s.every(Ame)||U0(s)&&!s)return{type:n,message:Ame(s)?s:"",ref:t}}var xI=s=>Ph(s)&&!gfe(s)?s:{value:s,message:""},iUe=async(s,t,n,r,a,i)=>{const{ref:l,refs:o,required:c,maxLength:d,minLength:u,min:h,max:p,pattern:f,validate:y,name:_,valueAsNumber:v,mount:j}=s._f,w=Ea(n,_);if(!j||t.has(_))return{};const S=o?o[0]:l,A=Z=>{a&&S.reportValidity&&(S.setCustomValidity(U0(Z)?"":Z||""),S.reportValidity())},E={},O=HMe(l),D=sU(l),I=O||D,F=(v||VMe(l))&&bh(l.value)&&bh(w)||ffe(l)&&l.value===""||w===""||Array.isArray(w)&&!w.length,z=Iht.bind(null,_,r,E),H=(Z,Y,W,ee=e2.maxLength,se=e2.minLength)=>{const oe=Z?Y:W;E[_]={type:Z?ee:se,message:oe,ref:l,...z(Z?ee:se,oe)}};if(i?!Array.isArray(w)||!w.length:c&&(!I&&(F||Ux(w))||U0(w)&&!w||D&&!Rht(o).isValid||O&&!Fht(o).isValid)){const{value:Z,message:Y}=Ame(c)?{value:!!c,message:c}:xI(c);if(Z&&(E[_]={type:e2.required,message:Y,ref:S,...z(e2.required,Y)},!r))return A(Y),E}if(!F&&(!Ux(h)||!Ux(p))){let Z,Y;const W=xI(p),ee=xI(h);if(!Ux(w)&&!isNaN(w)){const se=l.valueAsNumber||w&&+w;Ux(W.value)||(Z=se>W.value),Ux(ee.value)||(Y=senew Date(new Date().toDateString()+" "+me),he=l.type=="time",ce=l.type=="week";J_(W.value)&&w&&(Z=he?oe(w)>oe(W.value):ce?w>W.value:se>new Date(W.value)),J_(ee.value)&&w&&(Y=he?oe(w)+Z.value,ee=!Ux(Y.value)&&w.length<+Y.value;if((W||ee)&&(H(W,Z.message,Y.message),!r))return A(E[_].message),E}if(f&&!F&&J_(w)){const{value:Z,message:Y}=xI(f);if(gfe(Z)&&!w.match(Z)&&(E[_]={type:e2.pattern,message:Y,ref:l,...z(e2.pattern,Y)},!r))return A(Y),E}if(y){if(tb(y)){const Z=await y(w,n),Y=aUe(Z,S);if(Y&&(E[_]={...Y,...z(e2.validate,Y.message)},!r))return A(Y.message),E}else if(Ph(y)){let Z={};for(const Y in y){if(!Cg(Z)&&!r)break;const W=aUe(await y[Y](w,n),S,Y);W&&(Z={...W,...z(Y,W.message)},A(W.message),r&&(E[_]=Z))}if(!Cg(Z)&&(E[_]={ref:S,...Z},!r))return E}}return A(!0),E};const pes={mode:eb.onSubmit,reValidateMode:eb.onChange,shouldFocusError:!0};function fes(s={}){let t={...pes,...s},n={submitCount:0,isDirty:!1,isReady:!1,isLoading:tb(t.defaultValues),isValidating:!1,isSubmitted:!1,isSubmitting:!1,isSubmitSuccessful:!1,isValid:!1,touchedFields:{},dirtyFields:{},validatingFields:{},errors:t.errors||{},disabled:t.disabled||!1},r={},a=Ph(t.defaultValues)||Ph(t.values)?km(t.defaultValues||t.values)||{}:{},i=t.shouldUnregister?{}:km(a),l={action:!1,mount:!1,watch:!1},o={mount:new Set,disabled:new Set,unMount:new Set,array:new Set,watch:new Set},c,d=0;const u={isDirty:!1,dirtyFields:!1,validatingFields:!1,touchedFields:!1,isValidating:!1,isValid:!1,errors:!1};let h={...u};const p={array:Z$e(),state:Z$e()},f=t.criteriaMode===eb.all,y=Ge=>rt=>{clearTimeout(d),d=setTimeout(Ge,rt)},_=async Ge=>{if(!t.disabled&&(u.isValid||h.isValid||Ge)){const rt=t.resolver?Cg((await D()).errors):await F(r,!0);rt!==n.isValid&&p.state.next({isValid:rt})}},v=(Ge,rt)=>{!t.disabled&&(u.isValidating||u.validatingFields||h.isValidating||h.validatingFields)&&((Ge||Array.from(o.mount)).forEach(tt=>{tt&&(rt?bc(n.validatingFields,tt,rt):Hh(n.validatingFields,tt))}),p.state.next({validatingFields:n.validatingFields,isValidating:!Cg(n.validatingFields)}))},j=(Ge,rt=[],tt,at,Ye=!0,ut=!0)=>{if(at&&tt&&!t.disabled){if(l.action=!0,ut&&Array.isArray(Ea(r,Ge))){const _t=tt(Ea(r,Ge),at.argA,at.argB);Ye&&bc(r,Ge,_t)}if(ut&&Array.isArray(Ea(n.errors,Ge))){const _t=tt(Ea(n.errors,Ge),at.argA,at.argB);Ye&&bc(n.errors,Ge,_t),hes(n.errors,Ge)}if((u.touchedFields||h.touchedFields)&&ut&&Array.isArray(Ea(n.touchedFields,Ge))){const _t=tt(Ea(n.touchedFields,Ge),at.argA,at.argB);Ye&&bc(n.touchedFields,Ge,_t)}(u.dirtyFields||h.dirtyFields)&&(n.dirtyFields=tF(a,i)),p.state.next({name:Ge,isDirty:H(Ge,rt),dirtyFields:n.dirtyFields,errors:n.errors,isValid:n.isValid})}else bc(i,Ge,rt)},w=(Ge,rt)=>{bc(n.errors,Ge,rt),p.state.next({errors:n.errors})},S=Ge=>{n.errors=Ge,p.state.next({errors:n.errors,isValid:!1})},A=(Ge,rt,tt,at)=>{const Ye=Ea(r,Ge);if(Ye){const ut=Ea(i,Ge,bh(tt)?Ea(a,Ge):tt);bh(ut)||at&&at.defaultChecked||rt?bc(i,Ge,rt?ut:eUe(Ye._f)):W(Ge,ut),l.mount&&_()}},E=(Ge,rt,tt,at,Ye)=>{let ut=!1,_t=!1;const bt={name:Ge};if(!t.disabled){if(!tt||at){(u.isDirty||h.isDirty)&&(_t=n.isDirty,n.isDirty=bt.isDirty=H(),ut=_t!==bt.isDirty);const $t=E2(Ea(a,Ge),rt);_t=!!Ea(n.dirtyFields,Ge),$t?Hh(n.dirtyFields,Ge):bc(n.dirtyFields,Ge,!0),bt.dirtyFields=n.dirtyFields,ut=ut||(u.dirtyFields||h.dirtyFields)&&_t!==!$t}if(tt){const $t=Ea(n.touchedFields,Ge);$t||(bc(n.touchedFields,Ge,tt),bt.touchedFields=n.touchedFields,ut=ut||(u.touchedFields||h.touchedFields)&&$t!==tt)}ut&&Ye&&p.state.next(bt)}return ut?bt:{}},O=(Ge,rt,tt,at)=>{const Ye=Ea(n.errors,Ge),ut=(u.isValid||h.isValid)&&U0(rt)&&n.isValid!==rt;if(t.delayError&&tt?(c=y(()=>w(Ge,tt)),c(t.delayError)):(clearTimeout(d),c=null,tt?bc(n.errors,Ge,tt):Hh(n.errors,Ge)),(tt?!E2(Ye,tt):Ye)||!Cg(at)||ut){const _t={...at,...ut&&U0(rt)?{isValid:rt}:{},errors:n.errors,name:Ge};n={...n,..._t},p.state.next(_t)}},D=async Ge=>{v(Ge,!0);const rt=await t.resolver(i,t.context,ies(Ge||o.mount,r,t.criteriaMode,t.shouldUseNativeValidation));return v(Ge),rt},I=async Ge=>{const{errors:rt}=await D(Ge);if(Ge)for(const tt of Ge){const at=Ea(rt,tt);at?bc(n.errors,tt,at):Hh(n.errors,tt)}else n.errors=rt;return rt},F=async(Ge,rt,tt={valid:!0})=>{for(const at in Ge){const Ye=Ge[at];if(Ye){const{_f:ut,..._t}=Ye;if(ut){const bt=o.array.has(ut.name),$t=Ye._f&&oes(Ye._f);$t&&u.validatingFields&&v([at],!0);const Yt=await iUe(Ye,o.disabled,i,f,t.shouldUseNativeValidation&&!rt,bt);if($t&&u.validatingFields&&v([at]),Yt[ut.name]&&(tt.valid=!1,rt))break;!rt&&(Ea(Yt,ut.name)?bt?mes(n.errors,Yt,ut.name):bc(n.errors,ut.name,Yt[ut.name]):Hh(n.errors,ut.name))}!Cg(_t)&&await F(_t,rt,tt)}}return tt.valid},z=()=>{for(const Ge of o.unMount){const rt=Ea(r,Ge);rt&&(rt._f.refs?rt._f.refs.every(tt=>!xje(tt)):!xje(rt._f.ref))&&Me(Ge)}o.unMount=new Set},H=(Ge,rt)=>!t.disabled&&(Ge&&rt&&bc(i,Ge,rt),!E2(me(),a)),Z=(Ge,rt,tt)=>Mht(Ge,o,{...l.mount?i:bh(rt)?a:J_(Ge)?{[Ge]:rt}:rt},tt,rt),Y=Ge=>BMe(Ea(l.mount?i:a,Ge,t.shouldUnregister?Ea(a,Ge,[]):[])),W=(Ge,rt,tt={})=>{const at=Ea(r,Ge);let Ye=rt;if(at){const ut=at._f;ut&&(!ut.disabled&&bc(i,Ge,Oht(rt,ut)),Ye=ffe(ut.ref)&&Ux(rt)?"":rt,Pht(ut.ref)?[...ut.ref.options].forEach(_t=>_t.selected=Ye.includes(_t.value)):ut.refs?sU(ut.ref)?ut.refs.forEach(_t=>{(!_t.defaultChecked||!_t.disabled)&&(Array.isArray(Ye)?_t.checked=!!Ye.find(bt=>bt===_t.value):_t.checked=Ye===_t.value||!!Ye)}):ut.refs.forEach(_t=>_t.checked=_t.value===Ye):VMe(ut.ref)?ut.ref.value="":(ut.ref.value=Ye,ut.ref.type||p.state.next({name:Ge,values:km(i)})))}(tt.shouldDirty||tt.shouldTouch)&&E(Ge,Ye,tt.shouldTouch,tt.shouldDirty,!0),tt.shouldValidate&&ce(Ge)},ee=(Ge,rt,tt)=>{for(const at in rt){if(!rt.hasOwnProperty(at))return;const Ye=rt[at],ut=Ge+"."+at,_t=Ea(r,ut);(o.array.has(Ge)||Ph(Ye)||_t&&!_t._f)&&!qE(Ye)?ee(ut,Ye,tt):W(ut,Ye,tt)}},se=(Ge,rt,tt={})=>{const at=Ea(r,Ge),Ye=o.array.has(Ge),ut=km(rt);bc(i,Ge,ut),Ye?(p.array.next({name:Ge,values:km(i)}),(u.isDirty||u.dirtyFields||h.isDirty||h.dirtyFields)&&tt.shouldDirty&&p.state.next({name:Ge,dirtyFields:tF(a,i),isDirty:H(Ge,ut)})):at&&!at._f&&!Ux(ut)?ee(Ge,ut,tt):W(Ge,ut,tt),nUe(Ge,o)&&p.state.next({...n,name:Ge}),p.state.next({name:l.mount?Ge:void 0,values:km(i)})},oe=async Ge=>{l.mount=!0;const rt=Ge.target;let tt=rt.name,at=!0;const Ye=Ea(r,tt),ut=$t=>{at=Number.isNaN($t)||qE($t)&&isNaN($t.getTime())||E2($t,Ea(i,tt,$t))},_t=tUe(t.mode),bt=tUe(t.reValidateMode);if(Ye){let $t,Yt;const Ds=rt.type?eUe(Ye._f):Tht(Ge),Ls=Ge.type===pfe.BLUR||Ge.type===pfe.FOCUS_OUT,xs=!les(Ye._f)&&!t.resolver&&!Ea(n.errors,tt)&&!Ye._f.deps||ues(Ls,Ea(n.touchedFields,tt),n.isSubmitted,bt,_t),Lt=nUe(tt,o,Ls);bc(i,tt,Ds),Ls?(Ye._f.onBlur&&Ye._f.onBlur(Ge),c&&c(0)):Ye._f.onChange&&Ye._f.onChange(Ge);const Jt=E(tt,Ds,Ls),gt=!Cg(Jt)||Lt;if(!Ls&&p.state.next({name:tt,type:Ge.type,values:km(i)}),xs)return(u.isValid||h.isValid)&&(t.mode==="onBlur"?Ls&&_():Ls||_()),gt&&p.state.next({name:tt,...Lt?{}:Jt});if(!Ls&&Lt&&p.state.next({...n}),t.resolver){const{errors:zt}=await D([tt]);if(ut(Ds),at){const As=rUe(n.errors,r,tt),Xt=rUe(zt,r,As.name||tt);$t=Xt.error,tt=Xt.name,Yt=Cg(zt)}}else v([tt],!0),$t=(await iUe(Ye,o.disabled,i,f,t.shouldUseNativeValidation))[tt],v([tt]),ut(Ds),at&&($t?Yt=!1:(u.isValid||h.isValid)&&(Yt=await F(r,!0)));at&&(Ye._f.deps&&ce(Ye._f.deps),O(tt,Yt,$t,Jt))}},he=(Ge,rt)=>{if(Ea(n.errors,rt)&&Ge.focus)return Ge.focus(),1},ce=async(Ge,rt={})=>{let tt,at;const Ye=H9(Ge);if(t.resolver){const ut=await I(bh(Ge)?Ge:Ye);tt=Cg(ut),at=Ge?!Ye.some(_t=>Ea(ut,_t)):tt}else Ge?(at=(await Promise.all(Ye.map(async ut=>{const _t=Ea(r,ut);return await F(_t&&_t._f?{[ut]:_t}:_t)}))).every(Boolean),!(!at&&!n.isValid)&&_()):at=tt=await F(r);return p.state.next({...!J_(Ge)||(u.isValid||h.isValid)&&tt!==n.isValid?{}:{name:Ge},...t.resolver||!Ge?{isValid:tt}:{},errors:n.errors}),rt.shouldFocus&&!at&&G9(r,he,Ge?Ye:o.mount),at},me=Ge=>{const rt={...l.mount?i:a};return bh(Ge)?rt:J_(Ge)?Ea(rt,Ge):Ge.map(tt=>Ea(rt,tt))},le=(Ge,rt)=>({invalid:!!Ea((rt||n).errors,Ge),isDirty:!!Ea((rt||n).dirtyFields,Ge),error:Ea((rt||n).errors,Ge),isValidating:!!Ea(n.validatingFields,Ge),isTouched:!!Ea((rt||n).touchedFields,Ge)}),ve=Ge=>{Ge&&H9(Ge).forEach(rt=>Hh(n.errors,rt)),p.state.next({errors:Ge?n.errors:{}})},ge=(Ge,rt,tt)=>{const at=(Ea(r,Ge,{_f:{}})._f||{}).ref,Ye=Ea(n.errors,Ge)||{},{ref:ut,message:_t,type:bt,...$t}=Ye;bc(n.errors,Ge,{...$t,...rt,ref:at}),p.state.next({name:Ge,errors:n.errors,isValid:!1}),tt&&tt.shouldFocus&&at&&at.focus&&at.focus()},Te=(Ge,rt)=>tb(Ge)?p.state.subscribe({next:tt=>"values"in tt&&Ge(Z(void 0,rt),tt)}):Z(Ge,rt,!0),Ie=Ge=>p.state.subscribe({next:rt=>{des(Ge.name,rt.name,Ge.exact)&&ces(rt,Ge.formState||u,He,Ge.reRenderRoot)&&Ge.callback({values:{...i},...n,...rt,defaultValues:a})}}).unsubscribe,Ce=Ge=>(l.mount=!0,h={...h,...Ge.formState},Ie({...Ge,formState:h})),Me=(Ge,rt={})=>{for(const tt of Ge?H9(Ge):o.mount)o.mount.delete(tt),o.array.delete(tt),rt.keepValue||(Hh(r,tt),Hh(i,tt)),!rt.keepError&&Hh(n.errors,tt),!rt.keepDirty&&Hh(n.dirtyFields,tt),!rt.keepTouched&&Hh(n.touchedFields,tt),!rt.keepIsValidating&&Hh(n.validatingFields,tt),!t.shouldUnregister&&!rt.keepDefaultValue&&Hh(a,tt);p.state.next({values:km(i)}),p.state.next({...n,...rt.keepDirty?{isDirty:H()}:{}}),!rt.keepIsValid&&_()},Pe=({disabled:Ge,name:rt})=>{(U0(Ge)&&l.mount||Ge||o.disabled.has(rt))&&(Ge?o.disabled.add(rt):o.disabled.delete(rt))},Re=(Ge,rt={})=>{let tt=Ea(r,Ge);const at=U0(rt.disabled)||U0(t.disabled);return bc(r,Ge,{...tt||{},_f:{...tt&&tt._f?tt._f:{ref:{name:Ge}},name:Ge,mount:!0,...rt}}),o.mount.add(Ge),tt?Pe({disabled:U0(rt.disabled)?rt.disabled:t.disabled,name:Ge}):A(Ge,!0,rt.value),{...at?{disabled:rt.disabled||t.disabled}:{},...t.progressive?{required:!!rt.required,min:sF(rt.min),max:sF(rt.max),minLength:sF(rt.minLength),maxLength:sF(rt.maxLength),pattern:sF(rt.pattern)}:{},name:Ge,onChange:oe,onBlur:oe,ref:Ye=>{if(Ye){Re(Ge,rt),tt=Ea(r,Ge);const ut=bh(Ye.value)&&Ye.querySelectorAll&&Ye.querySelectorAll("input,select,textarea")[0]||Ye,_t=nes(ut),bt=tt._f.refs||[];if(_t?bt.find($t=>$t===ut):ut===tt._f.ref)return;bc(r,Ge,{_f:{...tt._f,..._t?{refs:[...bt.filter(xje),ut,...Array.isArray(Ea(a,Ge))?[{}]:[]],ref:{type:ut.type,name:Ge}}:{ref:ut}}}),A(Ge,!1,void 0,ut)}else tt=Ea(r,Ge,{}),tt._f&&(tt._f.mount=!1),(t.shouldUnregister||rt.shouldUnregister)&&!(Eht(o.array,Ge)&&l.action)&&o.unMount.add(Ge)}}},Ae=()=>t.shouldFocusError&&G9(r,he,o.mount),Be=Ge=>{U0(Ge)&&(p.state.next({disabled:Ge}),G9(r,(rt,tt)=>{const at=Ea(r,tt);at&&(rt.disabled=at._f.disabled||Ge,Array.isArray(at._f.refs)&&at._f.refs.forEach(Ye=>{Ye.disabled=at._f.disabled||Ge}))},0,!1))},we=(Ge,rt)=>async tt=>{let at;tt&&(tt.preventDefault&&tt.preventDefault(),tt.persist&&tt.persist());let Ye=km(i);if(p.state.next({isSubmitting:!0}),t.resolver){const{errors:ut,values:_t}=await D();n.errors=ut,Ye=km(_t)}else await F(r);if(o.disabled.size)for(const ut of o.disabled)Hh(Ye,ut);if(Hh(n.errors,"root"),Cg(n.errors)){p.state.next({errors:{}});try{await Ge(Ye,tt)}catch(ut){at=ut}}else rt&&await rt({...n.errors},tt),Ae(),setTimeout(Ae);if(p.state.next({isSubmitted:!0,isSubmitting:!1,isSubmitSuccessful:Cg(n.errors)&&!at,submitCount:n.submitCount+1,errors:n.errors}),at)throw at},Je=(Ge,rt={})=>{Ea(r,Ge)&&(bh(rt.defaultValue)?se(Ge,km(Ea(a,Ge))):(se(Ge,rt.defaultValue),bc(a,Ge,km(rt.defaultValue))),rt.keepTouched||Hh(n.touchedFields,Ge),rt.keepDirty||(Hh(n.dirtyFields,Ge),n.isDirty=rt.defaultValue?H(Ge,km(Ea(a,Ge))):H()),rt.keepError||(Hh(n.errors,Ge),u.isValid&&_()),p.state.next({...n}))},ke=(Ge,rt={})=>{const tt=Ge?km(Ge):a,at=km(tt),Ye=Cg(Ge),ut=Ye?a:at;if(rt.keepDefaultValues||(a=tt),!rt.keepValues){if(rt.keepDirtyValues){const _t=new Set([...o.mount,...Object.keys(tF(a,i))]);for(const bt of Array.from(_t))Ea(n.dirtyFields,bt)?bc(ut,bt,Ea(i,bt)):se(bt,Ea(ut,bt))}else{if(zMe&&bh(Ge))for(const _t of o.mount){const bt=Ea(r,_t);if(bt&&bt._f){const $t=Array.isArray(bt._f.refs)?bt._f.refs[0]:bt._f.ref;if(ffe($t)){const Yt=$t.closest("form");if(Yt){Yt.reset();break}}}}if(rt.keepFieldsRef)for(const _t of o.mount)se(_t,Ea(ut,_t));else r={}}i=t.shouldUnregister?rt.keepDefaultValues?km(a):{}:km(ut),p.array.next({values:{...ut}}),p.state.next({values:{...ut}})}o={mount:rt.keepDirtyValues?o.mount:new Set,unMount:new Set,array:new Set,disabled:new Set,watch:new Set,watchAll:!1,focus:""},l.mount=!u.isValid||!!rt.keepIsValid||!!rt.keepDirtyValues,l.watch=!!t.shouldUnregister,p.state.next({submitCount:rt.keepSubmitCount?n.submitCount:0,isDirty:Ye?!1:rt.keepDirty?n.isDirty:!!(rt.keepDefaultValues&&!E2(Ge,a)),isSubmitted:rt.keepIsSubmitted?n.isSubmitted:!1,dirtyFields:Ye?{}:rt.keepDirtyValues?rt.keepDefaultValues&&i?tF(a,i):n.dirtyFields:rt.keepDefaultValues&&Ge?tF(a,Ge):rt.keepDirty?n.dirtyFields:{},touchedFields:rt.keepTouched?n.touchedFields:{},errors:rt.keepErrors?n.errors:{},isSubmitSuccessful:rt.keepIsSubmitSuccessful?n.isSubmitSuccessful:!1,isSubmitting:!1})},it=(Ge,rt)=>ke(tb(Ge)?Ge(i):Ge,rt),je=(Ge,rt={})=>{const tt=Ea(r,Ge),at=tt&&tt._f;if(at){const Ye=at.refs?at.refs[0]:at.ref;Ye.focus&&(Ye.focus(),rt.shouldSelect&&tb(Ye.select)&&Ye.select())}},He=Ge=>{n={...n,...Ge}},Ke={control:{register:Re,unregister:Me,getFieldState:le,handleSubmit:we,setError:ge,_subscribe:Ie,_runSchema:D,_focusError:Ae,_getWatch:Z,_getDirty:H,_setValid:_,_setFieldArray:j,_setDisabledField:Pe,_setErrors:S,_getFieldArray:Y,_reset:ke,_resetDefaultValues:()=>tb(t.defaultValues)&&t.defaultValues().then(Ge=>{it(Ge,t.resetOptions),p.state.next({isLoading:!1})}),_removeUnmounted:z,_disableForm:Be,_subjects:p,_proxyFormState:u,get _fields(){return r},get _formValues(){return i},get _state(){return l},set _state(Ge){l=Ge},get _defaultValues(){return a},get _names(){return o},set _names(Ge){o=Ge},get _formState(){return n},get _options(){return t},set _options(Ge){t={...t,...Ge}}},subscribe:Ce,trigger:ce,register:Re,handleSubmit:we,watch:Te,setValue:se,getValues:me,reset:it,resetField:Je,clearErrors:ve,unregister:Me,setError:ge,setFocus:je,getFieldState:le};return{...Ke,formControl:Ke}}function bye(s={}){const t=Ct.useRef(void 0),n=Ct.useRef(void 0),[r,a]=Ct.useState({isDirty:!1,isValidating:!1,isLoading:tb(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:tb(s.defaultValues)?void 0:s.defaultValues});if(!t.current)if(s.formControl)t.current={...s.formControl,formState:r},s.defaultValues&&!tb(s.defaultValues)&&s.formControl.reset(s.defaultValues,s.resetOptions);else{const{formControl:l,...o}=fes(s);t.current={...o,formState:r}}const i=t.current.control;return i._options=s,qMe(()=>{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]),Ct.useEffect(()=>i._disableForm(s.disabled),[i,s.disabled]),Ct.useEffect(()=>{s.mode&&(i._options.mode=s.mode),s.reValidateMode&&(i._options.reValidateMode=s.reValidateMode)},[i,s.mode,s.reValidateMode]),Ct.useEffect(()=>{s.errors&&(i._setErrors(s.errors),i._focusError())},[i,s.errors]),Ct.useEffect(()=>{s.shouldUnregister&&i._subjects.state.next({values:i._getWatch()})},[i,s.shouldUnregister]),Ct.useEffect(()=>{if(i._proxyFormState.isDirty){const l=i._getDirty();l!==r.isDirty&&i._subjects.state.next({isDirty:l})}},[i,r.isDirty]),Ct.useEffect(()=>{s.values&&!E2(s.values,n.current)?(i._reset(s.values,{keepFieldsRef:!0,...i._options.resetOptions}),n.current=s.values,a(l=>({...l}))):i._resetDefaultValues()},[i,s.values]),Ct.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=Aht(r,i),t.current}const oUe=(s,t,n)=>{if(s&&"reportValidity"in s){const r=Ea(n,t);s.setCustomValidity(r&&r.message||""),s.reportValidity()}},zht=(s,t)=>{for(const n in t.fields){const r=t.fields[n];r&&r.ref&&"reportValidity"in r.ref?oUe(r.ref,n,s):r.refs&&r.refs.forEach(a=>oUe(a,n,s))}},xes=(s,t)=>{t.shouldUseNativeValidation&&zht(s,t);const n={};for(const r in s){const a=Ea(t.fields,r),i=Object.assign(s[r]||{},{ref:a&&a.ref});if(ges(t.names||Object.keys(s),r)){const l=Object.assign({},Ea(n,r));bc(l,"root",i),bc(n,r,l)}else bc(n,r,i)}return n},ges=(s,t)=>s.some(n=>n.startsWith(t+"."));var yes=function(s,t){for(var n={};s.length;){var r=s[0],a=r.code,i=r.message,l=r.path.join(".");if(!n[l])if("unionErrors"in r){var o=r.unionErrors[0].errors[0];n[l]={message:o.message,type:o.code}}else n[l]={message:i,type:a};if("unionErrors"in r&&r.unionErrors.forEach(function(u){return u.errors.forEach(function(h){return s.push(h)})}),t){var c=n[l].types,d=c&&c[r.code];n[l]=Iht(l,t,n,a,d?[].concat(d,r.message):r.message)}s.shift()}return n},_ye=function(s,t,n){return n===void 0&&(n={}),function(r,a,i){try{return Promise.resolve(function(l,o){try{var c=Promise.resolve(s[n.mode==="sync"?"parse":"parseAsync"](r,t)).then(function(d){return i.shouldUseNativeValidation&&zht({},i),{errors:{},values:n.raw?r:d}})}catch(d){return o(d)}return c&&c.then?c.then(void 0,o):c}(0,function(l){if(function(o){return Array.isArray(o==null?void 0:o.errors)}(l))return{values:{},errors:xes(yes(l.errors,!i.shouldUseNativeValidation&&i.criteriaMode==="all"),i)};throw l}))}catch(l){return Promise.reject(l)}}};const wye=XJt,Bht=N.createContext({}),_u=({...s})=>e.jsx(Bht.Provider,{value:{name:s.name},children:e.jsx(ses,{...s})}),jye=()=>{const s=N.useContext(Bht),t=N.useContext($ht),{getFieldState:n,formState:r}=vye(),a=n(s.name,r);if(!s)throw new Error("useFormField should be used within ");const{id:i}=t;return{id:i,name:s.name,formItemId:`${i}-form-item`,formDescriptionId:`${i}-form-item-description`,formMessageId:`${i}-form-item-message`,...a}},$ht=N.createContext({}),tu=N.forwardRef(({className:s,...t},n)=>{const r=N.useId();return e.jsx($ht.Provider,{value:{id:r},children:e.jsx("div",{ref:n,className:Mt("space-y-2",s),...t})})});tu.displayName="FormItem";const su=N.forwardRef(({className:s,...t},n)=>{const{error:r,formItemId:a}=jye();return e.jsx(ne,{ref:n,className:Mt(r&&"text-destructive",s),htmlFor:a,...t})});su.displayName="FormLabel";const nu=N.forwardRef(({...s},t)=>{const{error:n,formItemId:r,formDescriptionId:a,formMessageId:i}=jye();return e.jsx(BEe,{ref:t,id:r,"aria-describedby":n?`${a} ${i}`:`${a}`,"aria-invalid":!!n,...s})});nu.displayName="FormControl";const Mme=N.forwardRef(({className:s,...t},n)=>{const{formDescriptionId:r}=jye();return e.jsx("p",{ref:n,id:r,className:Mt("text-sm text-muted-foreground",s),...t})});Mme.displayName="FormDescription";const Wx=N.forwardRef(({className:s,children:t,...n},r)=>{const{error:a,formMessageId:i}=jye(),l=a?String(a==null?void 0:a.message):t;return l?e.jsx("p",{ref:r,id:i,className:Mt("text-sm font-medium text-destructive",s),...n,children:l}):null});Wx.displayName="FormMessage";const ves=Gw({category:XAe(["general","technology","crm","marketing"]),subject:fo().min(5,"Subject must be at least 5 characters").max(200),description:fo().min(20,"Please provide more details (at least 20 characters)").max(2e3)}),bes={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function Y4e({trigger:s}){const[t,n]=N.useState(!1),[r,a]=N.useState(!1),{user:i}=vs(),l=bye({resolver:_ye(ves),defaultValues:{category:"general",subject:"",description:""}}),o=async c=>{if(!i){ae.error("You must be logged in to submit a ticket");return}a(!0);try{const{error:d}=await q.from("support_tickets").insert({user_id:i.id,category:c.category,subject:c.subject,description:c.description});if(d)throw d;try{await q.functions.invoke("support-ticket-notify",{body:{category:bes[c.category],subject:c.subject}})}catch(u){console.log("Notification send attempted:",u)}ae.success("Support ticket submitted successfully!"),l.reset(),n(!1)}catch(d){console.error("Error submitting ticket:",d),ae.error("Failed to submit ticket. Please try again.")}finally{a(!1)}};return e.jsxs(_s,{open:t,onOpenChange:n,children:[e.jsx(ki,{asChild:!0,children:s||e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(s9,{className:"h-5 w-5"}),e.jsx("span",{className:"sr-only",children:"Support"})]})}),e.jsxs(bs,{className:"sm:max-w-[500px]",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Need Help?"}),e.jsx(Jn,{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(Cr,{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(wye,{...l,children:e.jsxs("form",{onSubmit:l.handleSubmit(o),className:"space-y-4",children:[e.jsx(_u,{control:l.control,name:"category",render:({field:c})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Category"}),e.jsxs(us,{onValueChange:c.onChange,defaultValue:c.value,children:[e.jsx(nu,{children:e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a category"})})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"general",children:"General Support"}),e.jsx(Ze,{value:"technology",children:"Technology Support"}),e.jsx(Ze,{value:"crm",children:"CRM Support"}),e.jsx(Ze,{value:"marketing",children:"Marketing Support"})]})]}),e.jsx(Wx,{})]})}),e.jsx(_u,{control:l.control,name:"subject",render:({field:c})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Subject"}),e.jsx(nu,{children:e.jsx(ye,{placeholder:"Brief description of your issue",...c})}),e.jsx(Wx,{})]})}),e.jsx(_u,{control:l.control,name:"description",render:({field:c})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Description"}),e.jsx(nu,{children:e.jsx(Ms,{placeholder:"Please describe your issue in detail...",className:"min-h-[120px]",...c})}),e.jsx(Wx,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:r,children:r?"Submitting...":"Submit Ticket"})]})]})})]})]})}const _es=()=>{const{user:s}=vs(),t=Ln(),[n,r]=N.useState([]),[a,i]=N.useState(0),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null);N.useEffect(()=>{u.current=c},[c]),N.useEffect(()=>{if(!s)return;const _=`notification_last_read_${s.id}`,v=localStorage.getItem(_);v&&!u.current&&(u.current=v,d(v));const j=`nb_cache_${s.id}`,w=60*1e3,S=async()=>{try{const I=sessionStorage.getItem(j);if(I){const F=JSON.parse(I);if(F.ts&&Date.now()-F.ts{r(O);const D=u.current?new Date(u.current):null,I=O.filter(F=>D?new Date(F.created_at)>D:!0);i(I.length)};S();const E=q.channel("push-notifications").on("postgres_changes",{event:"INSERT",schema:"public",table:"push_notifications"},O=>{const D=O.new;r(F=>{const z=[D,...F].slice(0,20);try{sessionStorage.setItem(j,JSON.stringify({ts:Date.now(),data:z}))}catch{}return z});const I=u.current?new Date(u.current):null;(!I||new Date(D.created_at)>I)&&i(F=>F+1),Notification.permission==="granted"&&new Notification(D.title,{body:D.body,icon:"/favicon.ico"})}).subscribe();return()=>{q.removeChannel(E)}},[s]);const h=_=>{const v=_.toLowerCase();return v.includes("community")||v.includes("post")?Ai:v.includes("academy")||v.includes("video")?fr:v.includes("template")?pl:v.includes("event")?yr:v.includes("newsletter")?sy:v.includes("brokerage")?zm:v.includes("swag")||v.includes("social")?Oi:v.includes("toolbox")||v.includes("tool")?gb:v.includes("brief")?un:Ai},p=_=>{o(!1),_.url&&_.url!=="/"&&t(_.url)},f=()=>{if(!s)return;const _=new Date().toISOString(),v=`notification_last_read_${s.id}`;localStorage.setItem(v,_),d(_),i(0)},y=_=>{o(_),_&&a>0&&f()};return e.jsxs(Mc,{open:l,onOpenChange:y,children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",children:[e.jsx(nm,{className:"h-5 w-5"}),a>0&&e.jsx(Ue,{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(gc,{align:"end",className:"w-80",children:[e.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[e.jsx("span",{className:"font-semibold",children:"Notifications"}),n.length>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-xs h-6",onClick:f,children:"Mark all read"})]}),e.jsx(di,{className:"h-[300px]",children:n.length===0?e.jsx("div",{className:"p-4 text-center text-muted-foreground text-sm",children:"No notifications yet"}):n.map(_=>{const v=h(_.title);return e.jsxs(Kr,{className:"group flex items-start gap-3 p-3 cursor-pointer data-[highlighted]:bg-accent data-[highlighted]:text-accent-foreground",onClick:()=>p(_),children:[e.jsx("div",{className:"flex-shrink-0 mt-0.5",children:e.jsx(v,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex flex-col gap-1 min-w-0",children:[e.jsx("span",{className:"font-medium text-sm",children:_.title}),e.jsx("span",{className:"text-xs text-muted-foreground line-clamp-2 group-data-[highlighted]:text-accent-foreground/80",children:_.body}),e.jsx("span",{className:"text-xs text-muted-foreground group-data-[highlighted]:text-accent-foreground/80",children:Uo(new Date(_.created_at),{addSuffix:!0})})]})]},_.id)})})]})]})};var lUe=1,wes=.9,jes=.8,Nes=.17,gje=.1,yje=.999,kes=.9999,Ses=.99,Ces=/[\\\/_+.#"@\[\(\{&]/,Tes=/[\\\/_+.#"@\[\(\{&]/g,Ees=/[\s-]/,Uht=/[\s-]/g;function Z4e(s,t,n,r,a,i,l){if(i===t.length)return a===s.length?lUe:Ses;var o=`${a},${i}`;if(l[o]!==void 0)return l[o];for(var c=r.charAt(i),d=n.indexOf(c,a),u=0,h,p,f,y;d>=0;)h=Z4e(s,t,n,r,d+1,i+1,l),h>u&&(d===a?h*=lUe:Ces.test(s.charAt(d-1))?(h*=jes,f=s.slice(a,d-1).match(Tes),f&&a>0&&(h*=Math.pow(yje,f.length))):Ees.test(s.charAt(d-1))?(h*=wes,y=s.slice(a,d-1).match(Uht),y&&a>0&&(h*=Math.pow(yje,y.length))):(h*=Nes,a>0&&(h*=Math.pow(yje,d-a))),s.charAt(d)!==t.charAt(i)&&(h*=kes)),(hh&&(h=p*gje)),h>u&&(u=h),d=n.indexOf(c,d+1);return l[o]=u,u}function cUe(s){return s.toLowerCase().replace(Uht," ")}function Aes(s,t,n){return s=n&&n.length>0?`${s+" "+n.join(" ")}`:s,Z4e(s,t,cUe(s),cUe(t),0,0,{})}var nF='[cmdk-group=""]',vje='[cmdk-group-items=""]',Mes='[cmdk-group-heading=""]',qht='[cmdk-item=""]',dUe=`${qht}:not([aria-disabled="true"])`,Q4e="cmdk-item-select",eP="data-value",Ies=(s,t,n)=>Aes(s,t,n),Vht=N.createContext(void 0),nU=()=>N.useContext(Vht),Hht=N.createContext(void 0),GMe=()=>N.useContext(Hht),Ght=N.createContext(void 0),Wht=N.forwardRef((s,t)=>{let n=tP(()=>{var ve,ge;return{search:"",value:(ge=(ve=s.value)!=null?ve:s.defaultValue)!=null?ge:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=tP(()=>new Set),a=tP(()=>new Map),i=tP(()=>new Map),l=tP(()=>new Set),o=Kht(s),{label:c,children:d,value:u,onValueChange:h,filter:p,shouldFilter:f,loop:y,disablePointerSelection:_=!1,vimBindings:v=!0,...j}=s,w=om(),S=om(),A=om(),E=N.useRef(null),O=qes();fM(()=>{if(u!==void 0){let ve=u.trim();n.current.value=ve,D.emit()}},[u]),fM(()=>{O(6,Y)},[]);let D=N.useMemo(()=>({subscribe:ve=>(l.current.add(ve),()=>l.current.delete(ve)),snapshot:()=>n.current,setState:(ve,ge,Te)=>{var Ie,Ce,Me,Pe;if(!Object.is(n.current[ve],ge)){if(n.current[ve]=ge,ve==="search")Z(),z(),O(1,H);else if(ve==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let Re=document.getElementById(A);Re?Re.focus():(Ie=document.getElementById(w))==null||Ie.focus()}if(O(7,()=>{var Re;n.current.selectedItemId=(Re=W())==null?void 0:Re.id,D.emit()}),Te||O(5,Y),((Ce=o.current)==null?void 0:Ce.value)!==void 0){let Re=ge??"";(Pe=(Me=o.current).onValueChange)==null||Pe.call(Me,Re);return}}D.emit()}},emit:()=>{l.current.forEach(ve=>ve())}}),[]),I=N.useMemo(()=>({value:(ve,ge,Te)=>{var Ie;ge!==((Ie=i.current.get(ve))==null?void 0:Ie.value)&&(i.current.set(ve,{value:ge,keywords:Te}),n.current.filtered.items.set(ve,F(ge,Te)),O(2,()=>{z(),D.emit()}))},item:(ve,ge)=>(r.current.add(ve),ge&&(a.current.has(ge)?a.current.get(ge).add(ve):a.current.set(ge,new Set([ve]))),O(3,()=>{Z(),z(),n.current.value||H(),D.emit()}),()=>{i.current.delete(ve),r.current.delete(ve),n.current.filtered.items.delete(ve);let Te=W();O(4,()=>{Z(),(Te==null?void 0:Te.getAttribute("id"))===ve&&H(),D.emit()})}),group:ve=>(a.current.has(ve)||a.current.set(ve,new Set),()=>{i.current.delete(ve),a.current.delete(ve)}),filter:()=>o.current.shouldFilter,label:c||s["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:w,inputId:A,labelId:S,listInnerRef:E}),[]);function F(ve,ge){var Te,Ie;let Ce=(Ie=(Te=o.current)==null?void 0:Te.filter)!=null?Ie:Ies;return ve?Ce(ve,n.current.search,ge):0}function z(){if(!n.current.search||o.current.shouldFilter===!1)return;let ve=n.current.filtered.items,ge=[];n.current.filtered.groups.forEach(Ie=>{let Ce=a.current.get(Ie),Me=0;Ce.forEach(Pe=>{let Re=ve.get(Pe);Me=Math.max(Re,Me)}),ge.push([Ie,Me])});let Te=E.current;ee().sort((Ie,Ce)=>{var Me,Pe;let Re=Ie.getAttribute("id"),Ae=Ce.getAttribute("id");return((Me=ve.get(Ae))!=null?Me:0)-((Pe=ve.get(Re))!=null?Pe:0)}).forEach(Ie=>{let Ce=Ie.closest(vje);Ce?Ce.appendChild(Ie.parentElement===Ce?Ie:Ie.closest(`${vje} > *`)):Te.appendChild(Ie.parentElement===Te?Ie:Ie.closest(`${vje} > *`))}),ge.sort((Ie,Ce)=>Ce[1]-Ie[1]).forEach(Ie=>{var Ce;let Me=(Ce=E.current)==null?void 0:Ce.querySelector(`${nF}[${eP}="${encodeURIComponent(Ie[0])}"]`);Me==null||Me.parentElement.appendChild(Me)})}function H(){let ve=ee().find(Te=>Te.getAttribute("aria-disabled")!=="true"),ge=ve==null?void 0:ve.getAttribute(eP);D.setState("value",ge||void 0)}function Z(){var ve,ge,Te,Ie;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let Ce=0;for(let Me of r.current){let Pe=(ge=(ve=i.current.get(Me))==null?void 0:ve.value)!=null?ge:"",Re=(Ie=(Te=i.current.get(Me))==null?void 0:Te.keywords)!=null?Ie:[],Ae=F(Pe,Re);n.current.filtered.items.set(Me,Ae),Ae>0&&Ce++}for(let[Me,Pe]of a.current)for(let Re of Pe)if(n.current.filtered.items.get(Re)>0){n.current.filtered.groups.add(Me);break}n.current.filtered.count=Ce}function Y(){var ve,ge,Te;let Ie=W();Ie&&(((ve=Ie.parentElement)==null?void 0:ve.firstChild)===Ie&&((Te=(ge=Ie.closest(nF))==null?void 0:ge.querySelector(Mes))==null||Te.scrollIntoView({block:"nearest"})),Ie.scrollIntoView({block:"nearest"}))}function W(){var ve;return(ve=E.current)==null?void 0:ve.querySelector(`${qht}[aria-selected="true"]`)}function ee(){var ve;return Array.from(((ve=E.current)==null?void 0:ve.querySelectorAll(dUe))||[])}function se(ve){let ge=ee()[ve];ge&&D.setState("value",ge.getAttribute(eP))}function oe(ve){var ge;let Te=W(),Ie=ee(),Ce=Ie.findIndex(Pe=>Pe===Te),Me=Ie[Ce+ve];(ge=o.current)!=null&&ge.loop&&(Me=Ce+ve<0?Ie[Ie.length-1]:Ce+ve===Ie.length?Ie[0]:Ie[Ce+ve]),Me&&D.setState("value",Me.getAttribute(eP))}function he(ve){let ge=W(),Te=ge==null?void 0:ge.closest(nF),Ie;for(;Te&&!Ie;)Te=ve>0?$es(Te,nF):Ues(Te,nF),Ie=Te==null?void 0:Te.querySelector(dUe);Ie?D.setState("value",Ie.getAttribute(eP)):oe(ve)}let ce=()=>se(ee().length-1),me=ve=>{ve.preventDefault(),ve.metaKey?ce():ve.altKey?he(1):oe(1)},le=ve=>{ve.preventDefault(),ve.metaKey?se(0):ve.altKey?he(-1):oe(-1)};return N.createElement(Yr.div,{ref:t,tabIndex:-1,...j,"cmdk-root":"",onKeyDown:ve=>{var ge;(ge=j.onKeyDown)==null||ge.call(j,ve);let Te=ve.nativeEvent.isComposing||ve.keyCode===229;if(!(ve.defaultPrevented||Te))switch(ve.key){case"n":case"j":{v&&ve.ctrlKey&&me(ve);break}case"ArrowDown":{me(ve);break}case"p":case"k":{v&&ve.ctrlKey&&le(ve);break}case"ArrowUp":{le(ve);break}case"Home":{ve.preventDefault(),se(0);break}case"End":{ve.preventDefault(),ce();break}case"Enter":{ve.preventDefault();let Ie=W();if(Ie){let Ce=new Event(Q4e);Ie.dispatchEvent(Ce)}}}}},N.createElement("label",{"cmdk-label":"",htmlFor:I.inputId,id:I.labelId,style:Hes},c),Nye(s,ve=>N.createElement(Hht.Provider,{value:D},N.createElement(Vht.Provider,{value:I},ve))))}),Pes=N.forwardRef((s,t)=>{var n,r;let a=om(),i=N.useRef(null),l=N.useContext(Ght),o=nU(),c=Kht(s),d=(r=(n=c.current)==null?void 0:n.forceMount)!=null?r:l==null?void 0:l.forceMount;fM(()=>{if(!d)return o.item(a,l==null?void 0:l.id)},[d]);let u=Yht(a,i,[s.value,s.children,i],s.keywords),h=GMe(),p=C4(O=>O.value&&O.value===u.current),f=C4(O=>d||o.filter()===!1?!0:O.search?O.filtered.items.get(a)>0:!0);N.useEffect(()=>{let O=i.current;if(!(!O||s.disabled))return O.addEventListener(Q4e,y),()=>O.removeEventListener(Q4e,y)},[f,s.onSelect,s.disabled]);function y(){var O,D;_(),(D=(O=c.current).onSelect)==null||D.call(O,u.current)}function _(){h.setState("value",u.current,!0)}if(!f)return null;let{disabled:v,value:j,onSelect:w,forceMount:S,keywords:A,...E}=s;return N.createElement(Yr.div,{ref:iN(i,t),...E,id:a,"cmdk-item":"",role:"option","aria-disabled":!!v,"aria-selected":!!p,"data-disabled":!!v,"data-selected":!!p,onPointerMove:v||o.getDisablePointerSelection()?void 0:_,onClick:v?void 0:y},s.children)}),Les=N.forwardRef((s,t)=>{let{heading:n,children:r,forceMount:a,...i}=s,l=om(),o=N.useRef(null),c=N.useRef(null),d=om(),u=nU(),h=C4(f=>a||u.filter()===!1?!0:f.search?f.filtered.groups.has(l):!0);fM(()=>u.group(l),[]),Yht(l,o,[s.value,s.heading,c]);let p=N.useMemo(()=>({id:l,forceMount:a}),[a]);return N.createElement(Yr.div,{ref:iN(o,t),...i,"cmdk-group":"",role:"presentation",hidden:h?void 0:!0},n&&N.createElement("div",{ref:c,"cmdk-group-heading":"","aria-hidden":!0,id:d},n),Nye(s,f=>N.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?d:void 0},N.createElement(Ght.Provider,{value:p},f))))}),Des=N.forwardRef((s,t)=>{let{alwaysRender:n,...r}=s,a=N.useRef(null),i=C4(l=>!l.search);return!n&&!i?null:N.createElement(Yr.div,{ref:iN(a,t),...r,"cmdk-separator":"",role:"separator"})}),Res=N.forwardRef((s,t)=>{let{onValueChange:n,...r}=s,a=s.value!=null,i=GMe(),l=C4(d=>d.search),o=C4(d=>d.selectedItemId),c=nU();return N.useEffect(()=>{s.value!=null&&i.setState("search",s.value)},[s.value]),N.createElement(Yr.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":c.listId,"aria-labelledby":c.labelId,"aria-activedescendant":o,id:c.inputId,type:"text",value:a?s.value:l,onChange:d=>{a||i.setState("search",d.target.value),n==null||n(d.target.value)}})}),Oes=N.forwardRef((s,t)=>{let{children:n,label:r="Suggestions",...a}=s,i=N.useRef(null),l=N.useRef(null),o=C4(d=>d.selectedItemId),c=nU();return N.useEffect(()=>{if(l.current&&i.current){let d=l.current,u=i.current,h,p=new ResizeObserver(()=>{h=requestAnimationFrame(()=>{let f=d.offsetHeight;u.style.setProperty("--cmdk-list-height",f.toFixed(1)+"px")})});return p.observe(d),()=>{cancelAnimationFrame(h),p.unobserve(d)}}},[]),N.createElement(Yr.div,{ref:iN(i,t),...a,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:c.listId},Nye(s,d=>N.createElement("div",{ref:iN(l,c.listInnerRef),"cmdk-list-sizer":""},d)))}),Fes=N.forwardRef((s,t)=>{let{open:n,onOpenChange:r,overlayClassName:a,contentClassName:i,container:l,...o}=s;return N.createElement(B0e,{open:n,onOpenChange:r},N.createElement($0e,{container:l},N.createElement(PD,{"cmdk-overlay":"",className:a}),N.createElement(LD,{"aria-label":s.label,"cmdk-dialog":"",className:i},N.createElement(Wht,{ref:t,...o}))))}),zes=N.forwardRef((s,t)=>C4(n=>n.filtered.count===0)?N.createElement(Yr.div,{ref:t,...s,"cmdk-empty":"",role:"presentation"}):null),Bes=N.forwardRef((s,t)=>{let{progress:n,children:r,label:a="Loading...",...i}=s;return N.createElement(Yr.div,{ref:t,...i,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":a},Nye(s,l=>N.createElement("div",{"aria-hidden":!0},l)))}),s0=Object.assign(Wht,{List:Oes,Item:Pes,Input:Res,Group:Les,Separator:Des,Dialog:Fes,Empty:zes,Loading:Bes});function $es(s,t){let n=s.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function Ues(s,t){let n=s.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function Kht(s){let t=N.useRef(s);return fM(()=>{t.current=s}),t}var fM=typeof window>"u"?N.useEffect:N.useLayoutEffect;function tP(s){let t=N.useRef();return t.current===void 0&&(t.current=s()),t}function C4(s){let t=GMe(),n=()=>s(t.snapshot());return N.useSyncExternalStore(t.subscribe,n,n)}function Yht(s,t,n,r=[]){let a=N.useRef(),i=nU();return fM(()=>{var l;let o=(()=>{var d;for(let u of n){if(typeof u=="string")return u.trim();if(typeof u=="object"&&"current"in u)return u.current?(d=u.current.textContent)==null?void 0:d.trim():a.current}})(),c=r.map(d=>d.trim());i.value(s,o,c),(l=t.current)==null||l.setAttribute(eP,o),a.current=o}),a}var qes=()=>{let[s,t]=N.useState(),n=tP(()=>new Map);return fM(()=>{n.current.forEach(r=>r()),n.current=new Map},[s]),(r,a)=>{n.current.set(r,a),t({})}};function Ves(s){let t=s.type;return typeof t=="function"?t(s.props):"render"in t?t.render(s.props):s}function Nye({asChild:s,children:t},n){return s&&N.isValidElement(t)?N.cloneElement(Ves(t),{ref:t.ref},n(t.props.children)):n(t)}var Hes={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};const Yg=N.forwardRef(({className:s,...t},n)=>e.jsx(s0,{ref:n,className:Mt("flex h-full w-full flex-col overflow-hidden rounded-md bg-popover text-popover-foreground",s),...t}));Yg.displayName=s0.displayName;const Ges=({children:s,...t})=>e.jsx(_s,{...t,children:e.jsx(bs,{className:"overflow-hidden p-0 shadow-lg",children:e.jsx(Yg,{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})})}),Zg=N.forwardRef(({className:s,...t},n)=>e.jsxs("div",{className:"flex items-center border-b px-3","cmdk-input-wrapper":"",children:[e.jsx(gr,{className:"mr-2 h-4 w-4 shrink-0 opacity-50"}),e.jsx(s0.Input,{ref:n,className:Mt("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})]}));Zg.displayName=s0.Input.displayName;const Qg=N.forwardRef(({className:s,...t},n)=>e.jsx(s0.List,{ref:n,className:Mt("max-h-[300px] overflow-y-auto overflow-x-hidden",s),...t}));Qg.displayName=s0.List.displayName;const Xg=N.forwardRef((s,t)=>e.jsx(s0.Empty,{ref:t,className:"py-6 text-center text-sm",...s}));Xg.displayName=s0.Empty.displayName;const Jg=N.forwardRef(({className:s,...t},n)=>e.jsx(s0.Group,{ref:n,className:Mt("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}));Jg.displayName=s0.Group.displayName;const Wes=N.forwardRef(({className:s,...t},n)=>e.jsx(s0.Separator,{ref:n,className:Mt("-mx-1 h-px bg-border",s),...t}));Wes.displayName=s0.Separator.displayName;const Zf=N.forwardRef(({className:s,...t},n)=>e.jsx(s0.Item,{ref:n,className:Mt("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}));Zf.displayName=s0.Item.displayName;const Kes={event:{label:"Events",icon:Cl,color:"bg-blue-500/10 text-blue-600"},template:{label:"Templates",icon:pl,color:"bg-purple-500/10 text-purple-600"},academy:{label:"Academy",icon:yd,color:"bg-amber-500/10 text-amber-600"},toolbox:{label:"Toolbox",icon:gb,color:"bg-green-500/10 text-green-600"},"social-swag":{label:"Social Swag",icon:un,color:"bg-fuchsia-500/10 text-fuchsia-600"}},uUe=()=>{const[s,t]=N.useState(!1),[n,r]=N.useState(""),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=Ln();N.useEffect(()=>{const p=f=>{f.key==="k"&&(f.metaKey||f.ctrlKey)&&(f.preventDefault(),t(y=>!y))};return document.addEventListener("keydown",p),()=>document.removeEventListener("keydown",p)},[]);const d=N.useCallback(async p=>{if(!p.trim()){i([]);return}o(!0);const f=`%${p}%`;try{const[y,_,v,j,w]=await Promise.all([q.from("events").select("id, title, description, event_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5),q.from("canva_templates").select("id, name, description, publish_date").or(`name.ilike.${f},description.ilike.${f}`).limit(5),q.from("academy_videos").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5),q.from("resource_kits").select("id, name, description, publish_date").eq("is_published",!0).or(`name.ilike.${f},description.ilike.${f}`).limit(5),q.from("social_swag").select("id, title, description, publish_date").eq("is_published",!0).or(`title.ilike.${f},description.ilike.${f}`).limit(5)]),S=[];y.data&&y.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"event",date:A.event_date,path:`/event/${A.id}`})}),_.data&&_.data.forEach(A=>{S.push({id:A.id,title:A.name,description:A.description,type:"template",date:A.publish_date,path:`/templates/${A.id}`})}),v.data&&v.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"academy",date:A.publish_date,path:`/academy/${A.id}`})}),j.data&&j.data.forEach(A=>{S.push({id:A.id,title:A.name,description:A.description,type:"toolbox",date:A.publish_date,path:`/toolbox/${A.id}`})}),w.data&&w.data.forEach(A=>{S.push({id:A.id,title:A.title,description:A.description,type:"social-swag",date:A.publish_date,path:`/social-swag/${A.id}`})}),i(S)}catch(y){console.error("Search error:",y)}finally{o(!1)}},[]);N.useEffect(()=>{const p=setTimeout(()=>{d(n)},300);return()=>clearTimeout(p)},[n,d]);const u=p=>{t(!1),r(""),c(p)},h=a.reduce((p,f)=>(p[f.type]||(p[f.type]=[]),p[f.type].push(f),p),{});return e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"relative h-9 w-9 p-0 xl:h-9 xl:w-60 xl:justify-start xl:px-3 xl:py-2",onClick:()=>t(!0),children:[e.jsx(gr,{className:"h-4 w-4 xl:mr-2"}),e.jsx("span",{className:"hidden xl:inline-flex text-muted-foreground text-sm",children:"Search..."}),e.jsxs("kbd",{className:"pointer-events-none absolute right-1.5 top-1.5 hidden h-6 select-none items-center gap-1 rounded border bg-muted px-1.5 font-mono text-[10px] font-medium opacity-100 xl:flex",children:[e.jsx("span",{className:"text-xs",children:"⌘"}),"K"]})]}),e.jsxs(Ges,{open:s,onOpenChange:t,children:[e.jsx(Zg,{placeholder:"Search events, templates, academy, toolbox, social swag...",value:n,onValueChange:r}),e.jsxs(Qg,{children:[l&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Searching..."}),!l&&n&&a.length===0&&e.jsxs(Xg,{children:['No results found for "',n,'"']}),!l&&!n&&e.jsx("div",{className:"py-6 text-center text-sm text-muted-foreground",children:"Start typing to search across all content..."}),Object.entries(h).map(([p,f])=>{const y=Kes[p],_=y.icon;return e.jsx(Jg,{heading:y.label,children:f.map(v=>e.jsxs(Zf,{value:`${v.type}-${v.id}-${v.title}`,onSelect:()=>u(v.path),className:"flex items-start gap-3 py-3 cursor-pointer",children:[e.jsx("div",{className:`p-2 rounded-md ${y.color}`,children:e.jsx(_,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:v.title}),v.description&&e.jsx("div",{className:"text-sm text-muted-foreground truncate group-data-[selected=true]:text-primary-foreground/80",children:v.description})]}),e.jsxs("div",{className:"flex flex-col items-end gap-1 shrink-0",children:[e.jsx(Ue,{variant:"secondary",className:"text-xs",children:y.label}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Uo(new Date(v.date),{addSuffix:!0})})]})]},`${v.type}-${v.id}`))},p)})]})]})]})},Yes=({expiresAt:s,className:t,showUpgradeButton:n=!0})=>{const[r,a]=N.useState(null),i=Ln();if(N.useEffect(()=>{const d=()=>{const h=new Date().getTime(),f=new Date(s).getTime()-h;if(f<=0){a({days:0,hours:0,minutes:0});return}const y=Math.floor(f/(1e3*60*60*24)),_=Math.floor(f%(1e3*60*60*24)/(1e3*60*60)),v=Math.floor(f%(1e3*60*60)/(1e3*60));a({days:y,hours:_,minutes:v})};d();const u=setInterval(d,6e4);return()=>clearInterval(u)},[s]),!r)return null;const l=r.days===0&&r.hours===0&&r.minutes===0,o=r.days<=1,c=r.days<=3&&!o;return l?e.jsxs("div",{className:Mt("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(ic,{className:"h-4 w-4 text-destructive"}),e.jsx("span",{className:"text-sm font-medium text-destructive",children:"Your free trial has expired"})]}),n&&e.jsxs(B,{size:"sm",onClick:()=>i("/subscription"),className:"bg-primary hover:bg-primary/90 text-xs h-7 px-3",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Upgrade Now"]})]}):e.jsxs("div",{className:Mt("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(pr,{className:Mt("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:Mt("text-sm font-medium",o?"text-destructive":c?"text-amber-600":"text-primary"),children:"Free Trial:"}),e.jsxs("div",{className:"flex items-center gap-1",children:[r.days>0&&e.jsxs("span",{className:Mt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.days,"d"]}),e.jsxs("span",{className:Mt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.hours,"h"]}),e.jsxs("span",{className:Mt("text-sm font-bold",o?"text-destructive":c?"text-amber-600":"text-primary"),children:[r.minutes,"m"]}),e.jsx("span",{className:Mt("text-xs",o?"text-destructive/70":c?"text-amber-600/70":"text-primary/70"),children:"remaining"})]})]})]}),n&&e.jsxs(B,{size:"sm",onClick:()=>i("/subscription"),variant:o?"destructive":c?"default":"outline",className:Mt("text-xs h-7 px-3",c&&"bg-amber-500 hover:bg-amber-600 text-white"),children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Upgrade"]})]})},Zes=()=>{const s=Ln();return e.jsx("div",{className:"fixed inset-0 bg-background/95 backdrop-blur-sm z-50 flex items-center justify-center p-4 overflow-y-auto",children:e.jsxs(fe,{className:"w-full max-w-2xl shadow-2xl border-destructive/20 my-8",children:[e.jsxs(It,{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(ic,{className:"h-8 w-8 text-destructive"})}),e.jsx(Rt,{className:"text-2xl",children:"Your Free Trial Has Ended"}),e.jsx(Vn,{className:"text-base",children:"Your 7-day free trial has expired. Upgrade now to continue accessing all the powerful tools and resources LevelUp has to offer!"})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(fe,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ee,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(An,{className:"h-6 w-6 text-primary"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Individual Agent"}),e.jsxs("p",{className:"text-2xl font-bold text-primary mb-2",children:["$39",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Perfect for solo agents ready to level up"}),e.jsxs(B,{className:"w-full",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Choose Individual"]})]})}),e.jsx(fe,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors cursor-pointer",onClick:()=>s("/subscription"),children:e.jsxs(Ee,{className:"p-5 text-center",children:[e.jsx("div",{className:"mx-auto mb-3 h-12 w-12 rounded-full bg-amber-500/10 flex items-center justify-center",children:e.jsx(Ua,{className:"h-6 w-6 text-amber-600"})}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"Brokerage"}),e.jsxs("p",{className:"text-2xl font-bold text-amber-600 mb-2",children:["$299",e.jsx("span",{className:"text-sm font-normal text-muted-foreground",children:"/mo"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"For teams and brokerages"}),e.jsxs(B,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",onClick:t=>{t.stopPropagation(),s("/subscription")},children:[e.jsx(Ua,{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(Cr,{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(Gs,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})]})]})})},Qes=({hasUnseenBrief:s,onClick:t,className:n})=>e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"icon",onClick:t,className:Mt("relative transition-colors",s&&"text-primary hover:text-primary",n),children:[e.jsx(zd,{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(Nc,{children:e.jsx("p",{children:"The LevelUp Brief"})})]});var WMe="Radio",[Xes,Zht]=uu(WMe),[Jes,ets]=Xes(WMe),Qht=N.forwardRef((s,t)=>{const{__scopeRadio:n,name:r,checked:a=!1,required:i,disabled:l,value:o="on",onCheck:c,form:d,...u}=s,[h,p]=N.useState(null),f=ji(t,v=>p(v)),y=N.useRef(!1),_=h?d||!!h.closest("form"):!0;return e.jsxs(Jes,{scope:n,checked:a,disabled:l,children:[e.jsx(Yr.button,{type:"button",role:"radio","aria-checked":a,"data-state":tmt(a),"data-disabled":l?"":void 0,disabled:l,value:o,...u,ref:f,onClick:xr(s.onClick,v=>{a||c==null||c(),_&&(y.current=v.isPropagationStopped(),y.current||v.stopPropagation())})}),_&&e.jsx(emt,{control:h,bubbles:!y.current,name:r,value:o,checked:a,required:i,disabled:l,form:d,style:{transform:"translateX(-100%)"}})]})});Qht.displayName=WMe;var Xht="RadioIndicator",Jht=N.forwardRef((s,t)=>{const{__scopeRadio:n,forceMount:r,...a}=s,i=ets(Xht,n);return e.jsx(Lh,{present:r||i.checked,children:e.jsx(Yr.span,{"data-state":tmt(i.checked),"data-disabled":i.disabled?"":void 0,...a,ref:t})})});Jht.displayName=Xht;var tts="RadioBubbleInput",emt=N.forwardRef(({__scopeRadio:s,control:t,checked:n,bubbles:r=!0,...a},i)=>{const l=N.useRef(null),o=ji(l,i),c=G$(n),d=M$(t);return N.useEffect(()=>{const u=l.current;if(!u)return;const h=window.HTMLInputElement.prototype,f=Object.getOwnPropertyDescriptor(h,"checked").set;if(c!==n&&f){const y=new Event("click",{bubbles:r});f.call(u,n),u.dispatchEvent(y)}},[c,n,r]),e.jsx(Yr.input,{type:"radio","aria-hidden":!0,defaultChecked:n,...a,tabIndex:-1,ref:o,style:{...a.style,...d,position:"absolute",pointerEvents:"none",opacity:0,margin:0}})});emt.displayName=tts;function tmt(s){return s?"checked":"unchecked"}var sts=["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"],kye="RadioGroup",[nts,cfn]=uu(kye,[z4,Zht]),smt=z4(),nmt=Zht(),[rts,ats]=nts(kye),rmt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,name:r,defaultValue:a,value:i,required:l=!1,disabled:o=!1,orientation:c,dir:d,loop:u=!0,onValueChange:h,...p}=s,f=smt(n),y=vN(d),[_,v]=cm({prop:i,defaultProp:a??null,onChange:h,caller:kye});return e.jsx(rts,{scope:n,name:r,required:l,disabled:o,value:_,onValueChange:v,children:e.jsx(I0e,{asChild:!0,...f,orientation:c,dir:y,loop:u,children:e.jsx(Yr.div,{role:"radiogroup","aria-required":l,"aria-orientation":c,"data-disabled":o?"":void 0,dir:y,...p,ref:t})})})});rmt.displayName=kye;var amt="RadioGroupItem",imt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,disabled:r,...a}=s,i=ats(amt,n),l=i.disabled||r,o=smt(n),c=nmt(n),d=N.useRef(null),u=ji(t,d),h=i.value===a.value,p=N.useRef(!1);return N.useEffect(()=>{const f=_=>{sts.includes(_.key)&&(p.current=!0)},y=()=>p.current=!1;return document.addEventListener("keydown",f),document.addEventListener("keyup",y),()=>{document.removeEventListener("keydown",f),document.removeEventListener("keyup",y)}},[]),e.jsx(P0e,{asChild:!0,...o,focusable:!l,active:h,children:e.jsx(Qht,{disabled:l,required:i.required,checked:h,...c,...a,name:i.name,ref:u,onCheck:()=>i.onValueChange(a.value),onKeyDown:xr(f=>{f.key==="Enter"&&f.preventDefault()}),onFocus:xr(a.onFocus,()=>{var f;p.current&&((f=d.current)==null||f.click())})})})});imt.displayName=amt;var its="RadioGroupIndicator",omt=N.forwardRef((s,t)=>{const{__scopeRadioGroup:n,...r}=s,a=nmt(n);return e.jsx(Jht,{...a,...r,ref:t})});omt.displayName=its;var lmt=rmt,cmt=imt,ots=omt;const ib=N.forwardRef(({className:s,...t},n)=>e.jsx(lmt,{className:Mt("grid gap-2",s),...t,ref:n}));ib.displayName=lmt.displayName;const Ld=N.forwardRef(({className:s,...t},n)=>e.jsx(cmt,{ref:n,className:Mt("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(ots,{className:"flex items-center justify-center",children:e.jsx(am,{className:"h-2.5 w-2.5 fill-current text-current"})})}));Ld.displayName=cmt.displayName;const lts=({brief:s,open:t,onClose:n,onDismiss:r})=>{const{user:a}=vs(),[i,l]=N.useState({}),[o,c]=N.useState({}),[d,u]=N.useState([]);N.useEffect(()=>{t&&a&&s.polls.length>0&&h()},[t,a,s.polls]);const h=async()=>{if(!a)return;const v=s.polls.map(w=>w.id),{data:j}=await q.from("levelup_brief_poll_responses").select("poll_id, option_id").eq("user_id",a.id).in("poll_id",v);if(j){const w={};j.forEach(S=>{w[S.poll_id]||(w[S.poll_id]=[]),w[S.poll_id].push(S.option_id)}),c(w)}},p=(v,j)=>{l(w=>({...w,[v]:j}))},f=(v,j,w)=>{l(S=>{const A=S[v]||[];return w?{...S,[v]:[...A,j]}:{...S,[v]:A.filter(E=>E!==j)}})},y=async v=>{if(!a)return;const j=i[v];if(!j||Array.isArray(j)&&j.length===0){ae.error("Please select an option");return}u(w=>[...w,v]);try{await q.from("levelup_brief_poll_responses").delete().eq("poll_id",v).eq("user_id",a.id);const w=Array.isArray(j)?j:[j],S=w.map(E=>({poll_id:v,option_id:E,user_id:a.id})),{error:A}=await q.from("levelup_brief_poll_responses").insert(S);if(A)throw A;c(E=>({...E,[v]:w})),ae.success("Response submitted!")}catch(w){console.error("Error submitting poll response:",w),ae.error("Failed to submit response")}finally{u(w=>w.filter(S=>S!==v))}},_=v=>(v.includes("mediadelivery.net")||v.includes("bunny"),v);return e.jsx(_s,{open:t,onOpenChange:v=>!v&&n(),children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] p-0 overflow-hidden [&>button]:hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-primary to-primary/80 p-4 pr-12 text-primary-foreground relative",children:[e.jsx("button",{onClick:n,className:"absolute top-3 right-3 p-1.5 rounded-full bg-white/30 hover:bg-white/50 transition-colors","aria-label":"Close",children:e.jsx($n,{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(zd,{className:"h-6 w-6"})}),e.jsxs("div",{children:[e.jsx(Ue,{variant:"secondary",className:"mb-1 bg-white/20 text-white border-0",children:"The LevelUp Brief"}),e.jsx(ws,{className:"text-xl font-bold text-white",children:s.brief.title})]})]})]}),e.jsx(di,{className:"max-h-[calc(90vh-240px)]",children:e.jsxs("div",{className:"p-6 space-y-6",children:[s.brief.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:s.brief.description}}),s.brief.video_url&&e.jsx("div",{className:"relative w-full aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:_(s.brief.video_url),className:"absolute inset-0 w-full h-full",allow:"autoplay; fullscreen; picture-in-picture",allowFullScreen:!0})}),s.brief.graphic_url&&!s.brief.video_url&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted",children:s.brief.graphic_link_url?e.jsx("a",{href:s.brief.graphic_link_url,target:"_blank",rel:"noopener noreferrer",className:"block",children:e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain cursor-pointer hover:opacity-90 transition-opacity"})}):e.jsx("img",{src:s.brief.graphic_url,alt:"Brief graphic",className:"w-full object-contain"})}),s.links.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:"Quick Links"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:s.links.map(v=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(v.url,"_blank"),className:"gap-2",children:[e.jsx(tr,{className:"h-4 w-4"}),v.title]},v.id))})]}),s.polls.map(v=>{var S,A;const j=((S=o[v.id])==null?void 0:S.length)>0,w=d.includes(v.id);return e.jsxs("div",{className:"space-y-3 p-4 bg-muted/50 rounded-lg border",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h4",{className:"font-semibold text-foreground",children:v.question}),j&&e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(vr,{className:"h-3 w-3"}),"Responded"]})]}),v.poll_type==="single"?e.jsx(ib,{value:i[v.id]||((A=o[v.id])==null?void 0:A[0])||"",onValueChange:E=>p(v.id,E),className:"space-y-2",children:v.options.map(E=>e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:E.id,id:E.id}),e.jsx(ne,{htmlFor:E.id,className:"cursor-pointer",children:E.option_text})]},E.id))}):e.jsx("div",{className:"space-y-2",children:v.options.map(E=>{const D=(i[v.id]||o[v.id]||[]).includes(E.id);return e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(hi,{id:E.id,checked:D,onCheckedChange:I=>f(v.id,E.id,I)}),e.jsx(ne,{htmlFor:E.id,className:"cursor-pointer",children:E.option_text})]},E.id)})}),e.jsx(B,{size:"sm",onClick:()=>y(v.id),disabled:w,children:w?"Submitting...":j?"Update Response":"Submit"})]},v.id)})]})}),e.jsxs("div",{className:"p-4 pb-[calc(1rem+env(safe-area-inset-bottom))] border-t bg-muted/30 flex flex-col items-center gap-2 sticky bottom-0 z-10",children:[e.jsx(B,{onClick:n,className:"w-full max-w-xs",children:"Got it!"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Don't show again"})]})]})})},cts=()=>{const{user:s}=vs(),[t,n]=N.useState(null),[r,a]=N.useState(!1),[i,l]=N.useState(!0),[o,c]=N.useState(!1),d=N.useCallback(async()=>{if(!s){l(!1);return}try{const{data:y,error:_}=await q.from("levelup_briefs").select("*").eq("is_published",!0).lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(1).single();if(_||!y){l(!1);return}const{data:v}=await q.from("levelup_brief_views").select("*").eq("brief_id",y.id).eq("user_id",s.id).maybeSingle(),[j,w]=await Promise.all([q.from("levelup_brief_links").select("*").eq("brief_id",y.id).order("sort_order"),q.from("levelup_brief_polls").select("*").eq("brief_id",y.id).order("sort_order")]),S=[];if(w.data)for(const I of w.data){const{data:F}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",I.id).order("sort_order");S.push({...I,options:F||[]})}const A={brief:y,links:j.data||[],polls:S};n(A);const E=!!v,O=(v==null?void 0:v.dismissed_at)!=null,D=localStorage.getItem(`brief-dismissed-${y.id}`)==="true";if(O||D)c(!1),a(!1);else if(!E)a(!0),c(!0);else if(y.show_frequency==="every_login")a(!0),c(!0);else if(y.show_frequency==="daily"){const I=new Date(v.viewed_at);(new Date().getTime()-I.getTime())/(1e3*60*60)>=24&&(a(!0),c(!0))}else c(!1)}catch(y){console.error("Error fetching brief:",y)}finally{l(!1)}},[s]);N.useEffect(()=>{d()},[d]);const u=async()=>{if(!(!s||!t))try{const{data:y}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();y?await q.from("levelup_brief_views").update({viewed_at:new Date().toISOString()}).eq("id",y.id):await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id})}catch(y){console.error("Error marking brief as viewed:",y)}};return{currentBrief:t,shouldShowPopup:r,hasUnseenBrief:o,loading:i,openBrief:()=>{a(!0)},closeBrief:()=>{a(!1),u()},dismissBrief:async()=>{if(!(!s||!t)){a(!1),c(!1);try{const{data:y,error:_}=await q.from("levelup_brief_views").select("id").eq("brief_id",t.brief.id).eq("user_id",s.id).maybeSingle();if(_&&console.error("Error checking existing brief view:",_),y){const{error:v}=await q.from("levelup_brief_views").update({dismissed_at:new Date().toISOString()}).eq("id",y.id).eq("user_id",s.id);v&&console.error("Error updating brief dismiss:",v)}else{const{error:v}=await q.from("levelup_brief_views").insert({brief_id:t.brief.id,user_id:s.id,dismissed_at:new Date().toISOString()});v&&console.error("Error inserting brief dismiss:",v)}localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}catch(y){console.error("Error dismissing brief:",y),t&&localStorage.setItem(`brief-dismissed-${t.brief.id}`,"true")}}},refetch:d}};function dts(){const[s,t]=N.useState(!1),[n,r]=N.useState(!1),[a,i]=N.useState(null);N.useEffect(()=>{if(localStorage.getItem("install-banner-dismissed")||window.matchMedia("(display-mode: standalone)").matches||!/iPhone|iPad|iPod|Android/i.test(navigator.userAgent))return;const h=/iPhone|iPad|iPod/i.test(navigator.userAgent);r(h),t(!0);const p=f=>{f.preventDefault(),i(f)};return window.addEventListener("beforeinstallprompt",p),()=>{window.removeEventListener("beforeinstallprompt",p)}},[]);const l=()=>{localStorage.setItem("install-banner-dismissed","true"),t(!1)},o=async()=>{if(a){await a.prompt();const{outcome:c}=await a.userChoice;c==="accepted"&&l(),i(null)}};return s?e.jsx("div",{className:"fixed bottom-0 left-0 right-0 z-50 p-4 bg-primary text-primary-foreground shadow-lg animate-in slide-in-from-bottom duration-300",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1 min-w-0",children:[e.jsx("div",{className:"flex-shrink-0 p-2 bg-primary-foreground/10 rounded-full",children:e.jsx(Ia,{className:"h-5 w-5"})}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:"Add LevelUp to your home screen"}),n?e.jsxs("p",{className:"text-xs opacity-80 flex items-center gap-1",children:["Tap ",e.jsx(y9,{className:"h-3 w-3 inline"}),' then "Add to Home Screen"']}):e.jsx("p",{className:"text-xs opacity-80",children:"Quick access anytime"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-shrink-0",children:[!n&&a&&e.jsx(B,{size:"sm",variant:"secondary",onClick:o,className:"text-xs",children:"Install"}),e.jsx("button",{onClick:l,className:"p-1.5 hover:bg-primary-foreground/10 rounded-full transition-colors","aria-label":"Dismiss",children:e.jsx($n,{className:"h-4 w-4"})})]})]})}):null}const uts=({children:s,onRefresh:t})=>{const[n,r]=N.useState(!1),[a,i]=N.useState(0),[l,o]=N.useState(!1),c=N.useRef(null),d=N.useRef(0),u=Kt(),h=80,p=120,f=N.useCallback(w=>{const S=c.current;S&&S.scrollTop<=0&&(d.current=w.touches[0].clientY,r(!0))},[]),y=N.useCallback(w=>{if(!n||l)return;const S=c.current;if(!S||S.scrollTop>0){r(!1),i(0);return}const E=w.touches[0].clientY-d.current;if(E>0){const D=Math.min(E*.5,p);i(D),D>10&&w.preventDefault()}},[n,l]),_=N.useCallback(async()=>{if(n)if(r(!1),a>=h&&!l){o(!0),i(h);try{t?await t():await u.invalidateQueries()}catch(w){console.error("Refresh failed:",w)}finally{o(!1),i(0)}}else i(0)},[n,a,l,t,u]),v=Math.min(a/h,1),j=v*180;return e.jsxs("div",{ref:c,className:"h-full overflow-auto",onTouchStart:f,onTouchMove:y,onTouchEnd:_,children:[e.jsx("div",{className:"flex justify-center items-center overflow-hidden transition-all duration-200 ease-out",style:{height:a>0?a:0,opacity:v},children:e.jsx("div",{className:`p-2 rounded-full bg-primary/10 ${l?"animate-spin":""}`,style:{transform:l?void 0:`rotate(${j}deg)`,transition:l?void 0:"transform 0.1s ease-out"},children:e.jsx(Ei,{className:"h-5 w-5 text-primary"})})}),e.jsx("div",{style:{transform:a>0?`translateY(${Math.max(0,a-60)}px)`:void 0,transition:n?void 0:"transform 0.2s ease-out"},children:s})]})},dmt=()=>{const{user:s}=vs(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(!0);N.useEffect(()=>{(async()=>{if(!s){c(!1);return}try{const{data:f}=await q.from("membership_reviews").select("id").eq("user_id",s.id).maybeSingle();if(f){a(!0),n(!1),c(!1);return}const{data:y}=await q.from("profiles").select("login_count").eq("id",s.id).single(),_=(y==null?void 0:y.login_count)||0;l(_);const v=sessionStorage.getItem("review-prompt-dismissed");n(_>=4&&!v)}catch(f){console.error("Error checking review eligibility:",f)}finally{c(!1)}})()},[s]);const d=N.useCallback(()=>{sessionStorage.setItem("review-prompt-dismissed","true"),n(!1)},[]),u=N.useCallback(async(p,f)=>{if(!s)return{success:!1,error:"Not authenticated"};try{const{error:y}=await q.from("membership_reviews").insert({user_id:s.id,rating:p,review_text:f});if(y)throw y;return a(!0),n(!1),{success:!0,pointsAwarded:25}}catch(y){return console.error("Error submitting review:",y),{success:!1,error:y.message}}},[s]),h=N.useCallback(async()=>{if(s)try{await q.from("membership_reviews").update({posted_to_google:!0}).eq("user_id",s.id)}catch(p){console.error("Error updating Google review status:",p)}},[s]);return{shouldShowPrompt:t,hasSubmittedReview:r,loginCount:i,isLoading:o,dismissPrompt:d,submitReview:u,markPostedToGoogle:h}},hts="https://search.google.com/local/writereview?placeid=ChIJM73ERQD1QogRPxupMFObuck&source=g.page.m.ia._&laa=nmx-review-solicitation-ia2",mts=()=>{const{shouldShowPrompt:s,isLoading:t,dismissPrompt:n,submitReview:r,markPostedToGoogle:a}=dmt(),[i,l]=N.useState(!1),[o,c]=N.useState("review"),[d,u]=N.useState(0),[h,p]=N.useState(0),[f,y]=N.useState(""),[_,v]=N.useState(!1),[j,w]=N.useState(!1);if(t||!s&&!j)return null;const S=async()=>{if(d===0){Br({title:"Please select a rating",variant:"destructive"});return}v(!0);const O=await r(d,f);v(!1),O.success?(w(!0),Br({title:"Thank you for your feedback!",description:"Your review helps us improve."}),c("google")):Br({title:"Error submitting review",description:O.error,variant:"destructive"})},A=async O=>{O&&(await navigator.clipboard.writeText(f||`${d} star rating for LevelUp!`),Br({title:"Review copied!",description:"Paste it on Google Reviews."}),await a(),window.open(hts,"_blank")),l(!1),n()},E=()=>{l(!1),n()};return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>l(!0),className:"fixed bottom-20 left-1/2 -translate-x-1/2 z-40 flex items-center gap-2 rounded-full bg-primary/90 px-3 py-2 text-xs text-primary-foreground shadow-lg backdrop-blur-sm transition-all hover:bg-primary hover:scale-105 md:bottom-6",children:[e.jsx(oa,{className:"h-3.5 w-3.5 fill-current"}),e.jsx("span",{className:"hidden sm:inline",children:"Leave a Review"})]}),e.jsx(_s,{open:i,onOpenChange:E,children:e.jsx(bs,{className:"sm:max-w-md",children:o==="review"?e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsx(ws,{className:"text-center",children:"How are you enjoying LevelUp?"}),e.jsx(Jn,{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(O=>e.jsx("button",{type:"button",onClick:()=>u(O),onMouseEnter:()=>p(O),onMouseLeave:()=>p(0),className:"p-1 transition-transform hover:scale-110",children:e.jsx(oa,{className:Mt("h-8 w-8 transition-colors",(h||d)>=O?"fill-yellow-400 text-yellow-400":"text-muted-foreground")})},O))}),e.jsx(Ms,{placeholder:"Tell us about your experience (optional)",value:f,onChange:O=>y(O.target.value),rows:4,className:"resize-none"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:E,className:"flex-1",children:"Maybe Later"}),e.jsx(B,{onClick:S,disabled:_||d===0,className:"flex-1",children:_?"Submitting...":"Submit Review"})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsx(ws,{className:"text-center",children:"🎉 Thank you!"}),e.jsx(Jn,{className:"text-center",children:"Would you mind sharing your review on Google? It really helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-center text-sm text-muted-foreground",children:"We'll copy your review so you can easily paste it."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>A(!1),className:"flex-1",children:"No Thanks"}),e.jsx(B,{onClick:()=>A(!0),className:"flex-1",children:"Yes, Open Google"})]})]})]})})})]})};function pts(s){const t="=".repeat((4-s.length%4)%4),n=(s+t).replace(/-/g,"+").replace(/_/g,"/"),r=window.atob(n),a=new Uint8Array(r.length);for(let i=0;i{if(!h){l(!1);return}(async()=>{try{const _="vapid_public_key";let v=localStorage.getItem(_);if(!v){const{data:S,error:A}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(A)throw A;if(v=(S==null?void 0:S.vapidPublicKey)??null,!v)throw new Error("Missing VAPID public key");localStorage.setItem(_,v)}u(v);const j=await navigator.serviceWorker.register("/push-sw.js",{scope:"/push-notifications/"});c(j),n(Notification.permission);const w=await j.pushManager.getSubscription();a(!!w)}catch(_){console.error("Error initializing push notifications:",_)}finally{l(!1)}})()},[h]);const p=N.useCallback(async()=>{if(!h||!o||!s)return console.error("Push notifications not supported or user not logged in"),!1;if(!d)return ae.error("Push notifications are not ready yet. Please try again in a moment."),!1;try{l(!0);const y=await o.pushManager.getSubscription();if(y){try{await y.unsubscribe()}catch(A){console.warn("Failed to unsubscribe existing push subscription:",A)}const{error:S}=await q.from("push_subscriptions").delete().eq("user_id",s.id);S&&console.warn("Failed to cleanup push_subscriptions rows:",S)}if(Notification.permission!=="granted"){const S=await Notification.requestPermission();if(n(S),S!=="granted")return S==="denied"?ae.error("Notifications blocked. Please enable them in your browser settings (click the lock icon in the address bar)."):ae.error("Notification permission was dismissed. Please try again."),!1}const _=pts(d);let v;try{v=await o.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:_})}catch(S){console.error("PushManager.subscribe() failed:",S);const A=(S==null?void 0:S.message)||String(S);return A.includes("permission")?ae.error("Push permission denied. Check your browser notification settings."):A.includes("key")||A.includes("VAPID")?ae.error("Push configuration error. Please contact support."):A.includes("AbortError")?ae.error("Push subscription was cancelled. Please try again."):ae.error(`Failed to subscribe: ${A}`),!1}const j=v.toJSON(),{error:w}=await q.from("push_subscriptions").upsert({user_id:s.id,endpoint:j.endpoint,p256dh_key:j.keys.p256dh,auth_key:j.keys.auth},{onConflict:"user_id,endpoint"});if(w)throw console.error("Error saving subscription:",w),ae.error("Failed to save notification preferences. Please try again."),w;return a(!0),ae.success("Push notifications enabled!"),!0}catch(y){if(console.error("Error subscribing to push notifications:",y),!(y instanceof Error&&y.message.includes("toast"))){const _=y instanceof Error?y.message:"Unknown error";ae.error("Failed to enable push notifications: "+_)}return!1}finally{l(!1)}},[h,o,s,d]),f=N.useCallback(async()=>{if(!o||!s)return!1;try{l(!0);const y=await o.pushManager.getSubscription();return y&&await y.unsubscribe(),await q.from("push_subscriptions").delete().eq("user_id",s.id),a(!1),ae.success("Push notifications disabled"),!0}catch(y){console.error("Error unsubscribing:",y);const _=y instanceof Error?y.message:"Unknown error";return ae.error("Failed to disable push notifications: "+_),!1}finally{l(!1)}},[o,s]);return{isSupported:h,permission:t,isSubscribed:r,isLoading:i,vapidPublicKey:d,subscribe:p,unsubscribe:f}}const bje="push_notification_prompt_dismissed",fts=["/dashboard","/admin"],xts=()=>{const{user:s}=vs(),{isSupported:t,isSubscribed:n,isLoading:r,subscribe:a}=umt(),i=Xl(),[l,o]=N.useState(!1),[c,d]=N.useState(!1),u=fts.some(f=>i.pathname===f||i.pathname.startsWith(`${f}/`));N.useEffect(()=>{if(u){o(!1);return}if(!s||!t||n||r||localStorage.getItem(`${bje}_${s.id}`))return;const y=setTimeout(()=>{o(!0)},2e3);return()=>clearTimeout(y)},[s,t,n,r,u]);const h=async()=>{d(!0);const f=await a();d(!1),f&&(s&&localStorage.setItem(`${bje}_${s.id}`,"true"),o(!1))},p=()=>{s&&localStorage.setItem(`${bje}_${s.id}`,"true"),o(!1)};return!t||n||u?null:e.jsx(_s,{open:l,onOpenChange:f=>!f&&p(),children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{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(nm,{className:"h-6 w-6 text-primary"})}),e.jsx(ws,{className:"text-center",children:"Stay in the Loop!"}),e.jsx(Jn,{className:"text-center",children:"Enable push notifications to get alerted when:"})]}),e.jsxs("ul",{className:"my-4 space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New events go live"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Fresh templates are added"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New toolbox resources drop"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Social swag updates"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," New newsletters arrive"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-primary",children:"•"})," Posts in your community groups"]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsx(B,{onClick:h,disabled:c,className:"w-full",children:c?"Enabling...":"Enable Notifications"}),e.jsx(B,{variant:"ghost",onClick:p,className:"w-full",children:"Not Now"})]}),e.jsx("p",{className:"text-center text-xs text-muted-foreground",children:"You can always change this in your Profile settings."})]})})},hUe=s=>{let t;const n=new Set,r=(d,u)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=u??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(f=>f(t,p))}},a=()=>t,o={setState:r,getState:a,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d))},c=t=s(r,a,o);return o},gts=s=>s?hUe(s):hUe,yts=s=>s;function vts(s,t=yts){const n=Ct.useSyncExternalStore(s.subscribe,Ct.useCallback(()=>t(s.getState()),[s,t]),Ct.useCallback(()=>t(s.getInitialState()),[s,t]));return Ct.useDebugValue(n),n}const mUe=s=>{const t=gts(s),n=r=>vts(t,r);return Object.assign(n,t),n},bts=s=>s?mUe(s):mUe;function _ts(s,t){let n;try{n=s()}catch{return}return{getItem:a=>{var i;const l=c=>c===null?null:JSON.parse(c,void 0),o=(i=n.getItem(a))!=null?i:null;return o instanceof Promise?o.then(l):l(o)},setItem:(a,i)=>n.setItem(a,JSON.stringify(i,void 0)),removeItem:a=>n.removeItem(a)}}const X4e=s=>t=>{try{const n=s(t);return n instanceof Promise?n:{then(r){return X4e(r)(n)},catch(r){return this}}}catch(n){return{then(r){return this},catch(r){return X4e(r)(n)}}}},wts=(s,t)=>(n,r,a)=>{let i={storage:_ts(()=>window.localStorage),partialize:v=>v,version:0,merge:(v,j)=>({...j,...v}),...t},l=!1,o=0;const c=new Set,d=new Set;let u=i.storage;if(!u)return s((...v)=>{console.warn(`[zustand persist middleware] Unable to update item '${i.name}', the given storage is currently unavailable.`),n(...v)},r,a);const h=()=>{const v=i.partialize({...r()});return u.setItem(i.name,{state:v,version:i.version})},p=a.setState;a.setState=(v,j)=>(p(v,j),h());const f=s((...v)=>(n(...v),h()),r,a);a.getInitialState=()=>f;let y;const _=()=>{var v,j;if(!u)return;const w=++o;l=!1,c.forEach(A=>{var E;return A((E=r())!=null?E:f)});const S=((j=i.onRehydrateStorage)==null?void 0:j.call(i,(v=r())!=null?v:f))||void 0;return X4e(u.getItem.bind(u))(i.name).then(A=>{if(A)if(typeof A.version=="number"&&A.version!==i.version){if(i.migrate){const E=i.migrate(A.state,A.version);return E instanceof Promise?E.then(O=>[!0,O]):[!0,E]}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 E;if(w!==o)return;const[O,D]=A;if(y=i.merge(D,(E=r())!=null?E:f),n(y,!0),O)return h()}).then(()=>{w===o&&(S==null||S(r(),void 0),y=r(),l=!0,d.forEach(A=>A(y)))}).catch(A=>{w===o&&(S==null||S(void 0,A))})};return a.persist={setOptions:v=>{i={...i,...v},v.storage&&(u=v.storage)},clearStorage:()=>{u==null||u.removeItem(i.name)},getOptions:()=>i,rehydrate:()=>_(),hasHydrated:()=>l,onHydrate:v=>(c.add(v),()=>{c.delete(v)}),onFinishHydration:v=>(d.add(v),()=>{d.delete(v)})},i.skipHydration||_(),y||f},jts=wts,Sye=bts()(jts((s,t)=>({cartItems:[],addToCart:(n,r,a=1,i)=>{s(l=>{const o=l.cartItems.findIndex(c=>{var d;return c.product.id===n.id&&((d=c.variant)==null?void 0:d.id)===(r==null?void 0:r.id)});if(o>=0){const c=[...l.cartItems];return c[o].quantity+=a,i&&(c[o].artworkUrl=i),{cartItems:c}}return{cartItems:[...l.cartItems,{product:n,variant:r,quantity:a,artworkUrl:i}]}})},removeFromCart:(n,r)=>{s(a=>({cartItems:a.cartItems.filter(i=>{var l;return!(i.product.id===n&&((l=i.variant)==null?void 0:l.id)===r)})}))},updateQuantity:(n,r,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===n&&((o=l.variant)==null?void 0:o.id)===r?{...l,quantity:Math.max(1,a)}:l})}))},updateArtwork:(n,r,a)=>{s(i=>({cartItems:i.cartItems.map(l=>{var o;return l.product.id===n&&((o=l.variant)==null?void 0:o.id)===r?{...l,artworkUrl:a}:l})}))},clearCart:()=>s({cartItems:[]}),getItemPrice:n=>{const r=Number(n.product.base_price),a=n.variant?Number(n.variant.price_adjustment):0;return r+a},getSubtotal:()=>{const{cartItems:n,getItemPrice:r}=t();return n.reduce((a,i)=>a+r(i)*i.quantity,0)},getShippingTotal:()=>{const{cartItems:n}=t();return n.reduce((r,a)=>r+Number(a.product.shipping_fee)*a.quantity,0)},getTotal:()=>{const{getSubtotal:n,getShippingTotal:r}=t();return n()+r()}}),{name:"marketplace-cart",partialize:s=>({cartItems:s.cartItems})}));function Nts(s){return s!=null&&s.length?s.find(t=>t.is_active&&t.mls_provider_id&&!t.no_mls_mode)||s[0]:null}function Ap(){const{user:s}=vs(),{data:t,isLoading:n}=dt({queryKey:["agent-lead-site",s==null?void 0:s.id],queryFn:async()=>{const{data:r,error:a}=await q.from("lead_sites").select("id, subdomain_slug, site_title, is_active, mls_provider_id, no_mls_mode, mls_agent_id, mls_agent_key, mls_office_id").eq("agent_id",s.id).eq("is_active",!0).order("created_at",{ascending:!0}).limit(10);if(a)throw a;return Nts(r)},enabled:!!s,staleTime:5*60*1e3});return{leadSite:t??null,hasLeadSite:!!t,isLoading:n,siteUrl:t?`https://${t.subdomain_slug}.thelocalmove.com`:null}}const pUe="dashboard-sidebar-collapsed",Cs=({children:s,title:t})=>{var it;const{user:n,signOut:r,isAdmin:a,isBrokerageManager:i,isCoach:l,brokerageId:o}=vs(),{isAssistant:c,actingAsAgent:d,hasPermission:u}=mAe(),{isImpersonating:h}=A0e(),f=(c&&!!d?40:0)+(h?40:0),{avatarUrl:y}=bht(n==null?void 0:n.id),{isTrial:_,isExpired:v,expiresAt:j}=zJt(n==null?void 0:n.id),{isInnerCircleEnabled:w,isMarketplaceEnabled:S}=wht(),{currentBrief:A,shouldShowPopup:E,hasUnseenBrief:O,openBrief:D,closeBrief:I,dismissBrief:F}=cts(),{unreadCount:z}=BJt(),{openCount:H}=$Jt(),{data:Z}=Wv(),Y=!!Z,ee=Sye(je=>je.cartItems).reduce((je,He)=>je+He.quantity,0),{leadSite:se,hasLeadSite:oe,siteUrl:he}=Ap(),ce=Ln(),me=Xl(),[le,ve]=N.useState(null);N.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("name").eq("id",n.id).single().then(({data:je})=>{je!=null&&je.name&&ve(je.name)})},[n==null?void 0:n.id]);const ge=le||((it=n==null?void 0:n.user_metadata)==null?void 0:it.name)||(n==null?void 0:n.email)||"User",[Te,Ie]=N.useState(()=>typeof window<"u"?localStorage.getItem(pUe)==="true":!1);N.useEffect(()=>{localStorage.setItem(pUe,String(Te))},[Te]);const[Ce,Me]=N.useState({agentos:!0,tools:!0,marketing:!0,learning:!0,community:!0,contacts:!0,website:!0,help:!1}),Pe=je=>{Me(He=>({...He,[je]:!He[je]}))},Re=je=>je.split(" ").map(He=>He[0]).join("").toUpperCase().slice(0,2),Ae=je=>me.pathname===je,Be=je=>je.some(He=>me.pathname===He),we=({path:je,icon:He,label:$e,badgeCount:Ke})=>{const Ge=e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Ae(je)&&"bg-sidebar-accent text-sidebar-accent-foreground",Te?"w-10 h-10 p-0 justify-center":"w-full justify-start gap-2"),onClick:()=>ce(je),children:[e.jsxs("div",{className:"relative",children:[e.jsx(He,{className:"h-4 w-4 shrink-0"}),Te&&Ke!=null&&Ke>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]}),!Te&&$e,!Te&&Ke!=null&&Ke>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:Ke>9?"9+":Ke})]});return Te?e.jsxs(Bc,{delayDuration:0,children:[e.jsx($c,{asChild:!0,children:Ge}),e.jsxs(Nc,{side:"right",className:"flex items-center gap-2",children:[$e,Ke!=null&&Ke>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:Ke>9?"9+":Ke})]})]}):Ge},Je=({id:je,label:He,icon:$e,children:Ke,activePaths:Ge,showBetaBadge:rt,defaultPath:tt,badgeCount:at})=>{if(Te){const Ye=tt||Ge[0];return e.jsxs(Bc,{delayDuration:0,children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:Mt("w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground relative",Be(Ge)&&"text-primary"),onClick:()=>ce(Ye),children:e.jsxs("div",{className:"relative",children:[e.jsx($e,{className:"h-4 w-4"}),at!=null&&at>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-2 w-2 rounded-full bg-muted-foreground/40 border border-background"})]})})}),e.jsxs(Nc,{side:"right",className:"flex items-center gap-2",children:[He,rt&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600",children:"Beta"}),at!=null&&at>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:at>9?"9+":at})]})]})}return e.jsxs(oy,{open:Ce[je],onOpenChange:()=>Pe(je),children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be(Ge)&&"text-primary"),children:[e.jsxs("span",{className:"flex items-center gap-2 font-semibold text-[15px]",children:[e.jsx($e,{className:"h-4 w-4"}),He,rt&&e.jsx("span",{className:"text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("span",{className:"flex items-center gap-1",children:[at!=null&&at>0&&e.jsx("span",{className:"flex h-5 w-5 items-center justify-center rounded-full bg-muted text-muted-foreground text-xs font-medium border border-muted-foreground/20",children:at>9?"9+":at}),e.jsx(ao,{className:Mt("h-4 w-4 transition-transform duration-200",Ce[je]&&"rotate-180")})]})]})}),e.jsx(cy,{className:"pl-4 space-y-1 mt-1",children:Ke})]})},ke=({isMobile:je=!1})=>{const He=je?!1:Te;return e.jsxs("div",{className:"flex flex-col h-full",children:[e.jsxs("div",{className:Mt("p-3 border-b border-sidebar-border",He?"flex flex-col items-center gap-2":"flex items-center justify-between"),children:[He?e.jsx("img",{src:KJt,alt:"LevelUp",className:"h-8 w-auto"}):e.jsx("img",{src:WJt,alt:"LevelUp",className:"h-8 w-auto"}),!je&&e.jsxs(Bc,{delayDuration:0,children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 shrink-0",onClick:()=>Ie(!He),children:e.jsx(ml,{className:Mt("h-4 w-4 transition-transform duration-300",He&&"rotate-180")})})}),e.jsx(Nc,{side:"right",children:He?"Expand sidebar":"Collapse sidebar"})]})]}),e.jsx(di,{className:"flex-1 [&_[data-radix-scroll-area-scrollbar]]:w-1.5",children:e.jsxs("nav",{className:Mt("p-3 space-y-1",He&&"flex flex-col items-center"),children:[je&&_&&!v&&e.jsx("button",{type:"button",onClick:()=>ce("/subscription"),className:Mt("relative w-full overflow-hidden rounded-md p-[1.5px] mb-2","bg-[linear-gradient(120deg,#f59e0b,#ef4444,#a855f7,#f59e0b)] bg-[length:200%_200%]","animate-gradient-x shadow-lg shadow-amber-500/20"),children:e.jsxs("span",{className:"flex items-center gap-2 rounded-[5px] bg-sidebar px-3 py-2 text-sm font-semibold text-sidebar-foreground",children:[e.jsx(un,{className:"h-4 w-4 text-amber-500 animate-pulse"}),e.jsx("span",{className:"flex-1 text-left bg-[linear-gradient(90deg,#f59e0b,#ef4444,#a855f7)] bg-clip-text text-transparent",children:"Ready to Upgrade?"}),j&&e.jsxs("span",{className:"text-[10px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded bg-amber-500/15 text-amber-600 dark:text-amber-400 border border-amber-500/30",children:[Math.max(0,Math.ceil((new Date(j).getTime()-Date.now())/864e5)),"d left"]})]})}),e.jsx(we,{path:"/dashboard",icon:GS,label:"Dashboard"}),e.jsx(we,{path:"/apps",icon:mv,label:"Apps & Tools"}),Te?e.jsxs(Bc,{delayDuration:0,children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:Mt("w-10 h-10 p-0 justify-center relative bg-primary/10 text-primary hover:bg-primary/20 border border-primary/30",Ae("/programs")&&"bg-primary/25"),onClick:()=>ce("/programs"),children:e.jsx(tx,{className:"h-4 w-4 shrink-0"})})}),e.jsx(Nc,{side:"right",children:"Programs"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 bg-primary/10 text-primary border border-primary/30 hover:bg-primary/20 hover:text-primary font-semibold",Ae("/programs")&&"bg-primary/25"),onClick:()=>ce("/programs"),children:[e.jsx(tx,{className:"h-4 w-4 shrink-0"}),"Programs"]}),Te?e.jsxs(Bc,{delayDuration:0,children:[e.jsx($c,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/levelup-u"),children:[e.jsx(yd,{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(Nc,{side:"right",className:"flex items-center gap-2",children:["LevelUp U",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/levelup-u")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/levelup-u"),children:[e.jsx(yd,{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(we,{path:"/events",icon:Cl,label:"Events"}),e.jsxs(Je,{id:"agentos",label:"Agent OS",icon:US,activePaths:["/mission-control","/mission-control/contacts","/mission-control/plans","/mission-control/popbys","/mission-control/video-library","/mission-control/scorecard","/mission-control/listings","/mission-control/pipeline","/mission-control/tasks","/mission-control/smart-drips","/mission-control/relationship-scorecard","/mission-control/sphere-gaps","/mission-control/signals","/mission-control/connect-page","/mission-control/client-portals","/mission-control/vendors","/mission-control/portal-referrals","/email-campaigns/templates"],showBetaBadge:!0,defaultPath:"/mission-control",children:[u("contacts")&&e.jsx(we,{path:"/mission-control",icon:gi,label:"Mission Control"}),u("contacts")&&!He&&e.jsxs(oy,{open:Ce.contacts,onOpenChange:()=>Pe("contacts"),children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-between gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Be(["/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(An,{className:"h-4 w-4"}),"Contacts"]}),e.jsx(ao,{className:Mt("h-3.5 w-3.5 transition-transform duration-200",Ce.contacts&&"rotate-180")})]})}),e.jsxs(cy,{className:"pl-4 pr-1 space-y-0.5 mt-0.5",children:[e.jsx(we,{path:"/mission-control/contacts",icon:An,label:"All Contacts"}),e.jsx(we,{path:"/mission-control/relationship-scorecard",icon:em,label:"Relationship Report"}),e.jsx(we,{path:"/mission-control/sphere-gaps",icon:x9,label:"Sphere Gaps"}),e.jsx(we,{path:"/mission-control/sent-emails",icon:lr,label:"Sent Emails"}),e.jsx(we,{path:"/mission-control/connect-page",icon:Tl,label:"Connect Page"})]})]}),u("contacts")&&He&&e.jsx(we,{path:"/mission-control/contacts",icon:An,label:"Contacts"}),u("contacts")&&e.jsx(we,{path:"/mission-control/plans",icon:Cl,label:"TouchPlans"}),u("pipeline")&&e.jsx(we,{path:"/mission-control/pipeline",icon:G2,label:"Deal Pipeline"}),u("pipeline")&&e.jsx(we,{path:"/mission-control/tasks",icon:S2,label:"Tasks"}),u("popbys")&&e.jsx(we,{path:"/mission-control/popbys",icon:Oi,label:"Popbys"}),u("videos")&&e.jsx(we,{path:"/mission-control/video-library",icon:fr,label:"Video Library"}),u("scorecard")&&e.jsx(we,{path:"/mission-control/scorecard",icon:_o,label:"Scorecard"}),u("listings")&&e.jsx(we,{path:"/mission-control/listings",icon:Ua,label:"Listing Exchange"}),e.jsx(we,{path:"/mission-control/client-portals",icon:un,label:"Client Portals"}),e.jsx(we,{path:"/mission-control/signals",icon:IA,label:"Signals"}),!He&&e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/mission-control/smart-drips")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/mission-control/smart-drips"),children:[e.jsx(im,{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"})]}),He&&e.jsx(we,{path:"/mission-control/smart-drips",icon:im,label:"Smart Drips"}),e.jsx(we,{path:"/email-campaigns/templates",icon:Gs,label:"Email Templates"})]}),oe&&se&&e.jsxs(Je,{id:"website",label:"My Website",icon:lc,activePaths:[`/admin/lead-sites/${se.id}/edit`],defaultPath:`/admin/lead-sites/${se.id}/edit`,children:[He?e.jsxs(Bc,{delayDuration:0,children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"w-10 h-10 p-0 justify-center text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(he||"#","_blank"),children:e.jsx(Sr,{className:"h-4 w-4"})})}),e.jsx(Nc,{side:"right",children:"View Site"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open(he||"#","_blank"),children:[e.jsx(Sr,{className:"h-4 w-4"}),"View Site",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsx(we,{path:`/my-website/${se.id}/edit`,icon:ya,label:"Edit Website"}),e.jsx(we,{path:"/my-website/mls-listings",icon:Or,label:"MLS Listings"}),e.jsx(we,{path:"/my-website/market-report",icon:_o,label:"Market Reports"}),(se==null?void 0:se.mls_provider_id)&&e.jsx(we,{path:"/mission-control/cma",icon:dw,label:"CMA Reports"}),e.jsx(we,{path:"/mission-control/website-activity",icon:em,label:"Website Activity"}),e.jsx(we,{path:"/m",icon:tg,label:"Mobile Command"})]}),e.jsxs(Je,{id:"marketing",label:"Marketing",icon:zd,activePaths:["/templates","/social-swag-2","/newsletters","/website-apps","/marketing-studio"],defaultPath:"/templates",children:[e.jsx(we,{path:"/templates",icon:pl,label:"Templates"}),e.jsx(we,{path:"/marketing-studio",icon:Xo,label:"Marketing Studio"}),e.jsx(we,{path:"/social-swag-2",icon:tg,label:"Social Swag"}),Te?e.jsxs(Bc,{delayDuration:0,children:[e.jsx($c,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-10 h-10 p-0 justify-center relative text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/newsletters"),children:[e.jsx(sy,{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(Nc,{side:"right",className:"flex items-center gap-2",children:["Newsletter Pro",e.jsx("span",{className:"text-[10px] font-bold uppercase tracking-wider text-primary-foreground bg-primary rounded px-1 py-0.5",children:"New"})]})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/newsletters")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/newsletters"),children:[e.jsx(sy,{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(we,{path:"/website-apps",icon:un,label:"Website Apps"})]}),e.jsxs(Je,{id:"learning",label:"Learning",icon:rm,activePaths:["/academy","/toolbox","/programs"],defaultPath:"/academy",children:[e.jsx(we,{path:"/academy",icon:yd,label:"Academy"}),e.jsx(we,{path:"/toolbox",icon:gb,label:"Toolbox"})]}),e.jsxs(Je,{id:"community",label:"Community",icon:Ai,activePaths:["/community","/wishlist"],defaultPath:"/community",badgeCount:z,children:[e.jsx(we,{path:"/community",icon:An,label:"Community",badgeCount:z}),e.jsx(we,{path:"/wishlist",icon:W2,label:"Wishlist",badgeCount:H}),!He&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:()=>window.open("https://www.facebook.com/share/g/1CC6thti2V/","_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"Facebook Group"]})]}),e.jsxs(Je,{id:"goods",label:"The Goods",icon:Dg,activePaths:["/marketplace","/reward-store"],defaultPath:"/reward-store",children:[S&&!He&&e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",me.pathname.startsWith("/marketplace")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/marketplace"),children:[e.jsx(Dg,{className:"h-4 w-4"}),"Marketplace",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1.5 py-0.5 rounded-full bg-primary text-primary-foreground",children:"New"})]}),S&&He&&e.jsx(we,{path:"/marketplace",icon:Dg,label:"Marketplace"}),e.jsx(we,{path:"/reward-store",icon:xo,label:"Reward Store"}),e.jsx(we,{path:"/refer-friends",icon:Oi,label:"Refer & Earn"})]}),e.jsxs(Je,{id:"help",label:"Help & Services",icon:q_,activePaths:["/support","/additional-services"],defaultPath:"/support",children:[e.jsx(we,{path:"/support",icon:eL,label:"Support"}),e.jsx(we,{path:"/additional-services",icon:un,label:"Additional Services"})]}),l&&e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(we,{path:"/coaching",icon:yd,label:"Coaching"})}),e.jsx(kts,{}),(n==null?void 0:n.email)==="jeremy@relevelup.com"&&e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",me.pathname.startsWith("/attract")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/attract"),children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"}),!He&&e.jsx("span",{children:"LevelUp Attract"}),!He&&e.jsx("span",{className:"ml-auto text-[9px] font-semibold text-violet-600 uppercase tracking-wider",children:"Beta"})]}),a&&e.jsxs(e.Fragment,{children:[!He&&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"})}),He?e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsx(we,{path:"/admin",icon:Gc,label:"Admin Dashboard"})}):e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",me.pathname==="/admin"&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/admin"),children:[e.jsx(Gc,{className:"h-4 w-4"}),"Admin Dashboard"]})]}),(o||i)&&!a&&e.jsxs(e.Fragment,{children:[!He&&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"})}),He?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(we,{path:"/my-brokerage",icon:Ua,label:"My Brokerage"}),e.jsx(we,{path:"/brokerage/help-board",icon:X1,label:"Help Board"}),e.jsx(we,{path:"/brokerage-content",icon:rm,label:"Brokerage Content"})]}),Y&&!i&&e.jsx(we,{path:"/my-team",icon:An,label:"My Team"}),i&&e.jsxs(e.Fragment,{children:[e.jsx(we,{path:"/brokerage/dashboard",icon:Ko,label:"Manage Brokerages"}),e.jsx(we,{path:"/brokerage/teams",icon:An,label:"Teams"}),e.jsx(we,{path:"/brokerage/recruiting",icon:zd,label:"Recruiting"}),e.jsx(we,{path:"/brokerage/vendors",icon:pw,label:"Vendors"}),e.jsx(we,{path:"/brokerage-resources",icon:zm,label:"Brokerage Resources"})]})]}):e.jsxs(e.Fragment,{children:[o&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/my-brokerage")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/my-brokerage"),children:[e.jsx(Ua,{className:"h-4 w-4"}),"My Brokerage"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/brokerage/help-board")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/help-board"),children:[e.jsx(X1,{className:"h-4 w-4"}),"Help Board"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/brokerage-content")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage-content"),children:[e.jsx(rm,{className:"h-4 w-4"}),"Brokerage Content"]})]}),Y&&!i&&e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/my-team")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/my-team"),children:[e.jsx(An,{className:"h-4 w-4"}),"My Team"]}),i&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/brokerage/dashboard")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/dashboard"),children:[e.jsx(Ko,{className:"h-4 w-4"}),"Manage Brokerages"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/brokerage/teams")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/teams"),children:[e.jsx(An,{className:"h-4 w-4"}),"Teams",e.jsx("span",{className:"ml-auto text-[9px] font-bold uppercase tracking-wide px-1 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"New"})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/brokerage/recruiting")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/recruiting"),children:[e.jsx(zd,{className:"h-4 w-4"}),"Recruiting"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/brokerage/vendors")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage/vendors"),children:[e.jsx(pw,{className:"h-4 w-4"}),"Vendors"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/brokerage-resources")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/brokerage-resources"),children:[e.jsx(zm,{className:"h-4 w-4"}),"Brokerage Resources"]})]})]})]})]})}),e.jsxs("div",{className:"p-3 border-t border-sidebar-border md:hidden",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",Ae("/profile")&&"bg-sidebar-accent text-sidebar-accent-foreground"),onClick:()=>ce("/profile"),children:[e.jsx(Wi,{className:"h-4 w-4"}),"Profile"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground",onClick:r,children:[e.jsx(TA,{className:"h-4 w-4"}),"Sign Out"]})]})]})};return e.jsx(Vw,{children:e.jsxs("div",{className:"min-h-screen bg-background flex",children:[_&&v&&me.pathname!=="/subscription"&&e.jsx(Zes,{}),typeof document<"u"&&qx.createPortal(e.jsx("aside",{className:Mt("hidden md:flex flex-col bg-card border-r border-border fixed left-0 z-30 !pointer-events-auto transition-[width] duration-300",Te?"w-16":"w-56"),style:{top:`${f}px`,height:`calc(100vh - ${f}px)`},children:e.jsx(ke,{})}),document.body),e.jsxs("div",{className:Mt("flex-1 flex flex-col overflow-hidden transition-all duration-300",Te?"md:ml-16":"md:ml-56"),style:{height:`calc(100vh - ${f}px)`,marginTop:`${f}px`},children:[e.jsx("header",{className:"sticky top-0 z-40 bg-card border-b border-border flex-shrink-0",children:e.jsxs("div",{className:"flex items-center justify-between px-6 py-3",children:[e.jsxs(t0,{children:[e.jsx(Y$,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"md:hidden",children:e.jsx(KS,{className:"h-5 w-5"})})}),e.jsx(og,{side:"left",className:"w-56 p-0 bg-card",children:e.jsx(ke,{isMobile:!0})})]}),e.jsx("div",{className:"flex-1 md:hidden",children:e.jsx("img",{src:YJt,alt:"LevelUp",className:"h-8 w-auto"})}),e.jsx("div",{className:"hidden md:flex flex-1 justify-center",children:e.jsx(uUe,{})}),e.jsxs("div",{className:"flex items-center gap-3 ml-auto",children:[_&&!v&&j&&e.jsx(Yes,{expiresAt:j,className:"hidden lg:flex"}),e.jsx("div",{className:"md:hidden",children:e.jsx(uUe,{})}),A&&e.jsx(Qes,{hasUnseenBrief:O,onClick:D}),S&&e.jsxs(B,{variant:"ghost",size:"icon",className:"relative",onClick:()=>ce("/marketplace/cart"),children:[e.jsx(Dg,{className:"h-5 w-5"}),ee>0&&e.jsx("span",{className:"absolute -top-1 -right-1 h-5 w-5 rounded-full bg-primary text-primary-foreground text-xs font-medium flex items-center justify-center",children:ee>99?"99+":ee})]}),e.jsx(_es,{}),e.jsx(Y4e,{}),e.jsxs("span",{className:"hidden sm:block text-sm font-medium text-foreground",children:["Hello, ",ge.split(" ")[0],"!"]}),e.jsxs(Mc,{children:[e.jsx(Ic,{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(Jr,{className:"h-9 w-9 cursor-pointer hover:opacity-80 transition-opacity",children:[e.jsx(ti,{src:y||void 0}),e.jsx(ea,{className:"bg-primary text-primary-foreground font-medium text-sm",children:Re(ge)})]})})}),e.jsxs(gc,{align:"end",className:"w-48",children:[e.jsxs(Kr,{onClick:()=>ce("/profile"),className:"cursor-pointer",children:[e.jsx(Wi,{className:"h-4 w-4 mr-2"}),"Profile"]}),e.jsxs(Kr,{onClick:()=>ce("/mission-control/integrations"),className:"cursor-pointer",children:[e.jsx(Y2,{className:"h-4 w-4 mr-2"}),"Integrations"]}),e.jsxs(Kr,{onClick:()=>ce("/mission-control/browser-extension"),className:"cursor-pointer",children:[e.jsx(Y2,{className:"h-4 w-4 mr-2"}),"Browser Extension"]}),e.jsx(Kg,{}),e.jsxs(Kr,{onClick:r,className:"cursor-pointer text-destructive focus:text-destructive",children:[e.jsx(TA,{className:"h-4 w-4 mr-2"}),"Sign Out"]})]})]})]})]})}),e.jsx(uts,{children:e.jsx("main",{className:"p-4 sm:p-6 lg:p-8 overflow-x-hidden",children:s})}),A&&e.jsx(lts,{brief:A,open:E,onClose:I,onDismiss:F}),e.jsx(dts,{}),e.jsx(mts,{}),e.jsx(xts,{})]})]})})};function kts(){const{user:s}=vs(),t=Xl(),n=Ln(),{data:r}=dt({queryKey:["my-coach-nav",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i}=await q.from("coaching_assignments").select("id").eq("agent_id",s.id).eq("status","active").limit(1);return(i||[]).length>0}});if(!r)return null;const a=t.pathname==="/my-coach";return e.jsx("div",{className:"pt-3 border-t border-sidebar-border mt-3 space-y-1",children:e.jsxs(B,{variant:"ghost",size:"sm",className:`w-full justify-start gap-2 text-sidebar-foreground hover:bg-sidebar-accent hover:text-sidebar-accent-foreground ${a?"bg-sidebar-accent text-sidebar-accent-foreground":""}`,onClick:()=>n("/my-coach"),children:[e.jsx(yd,{className:"h-4 w-4"}),"My Coach"]})})}const fUe="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/mcp",Sts="https://tile-portal.lovable.app/mcp-oauth-bridge.html",Cts=[{label:"Open ChatGPT",description:"You need ChatGPT Plus, Pro, or Team to add custom MCP connectors."},{label:"Add a new connector",description:"Settings → Connectors → Add. Choose 'Custom / MCP Server'."},{label:"Fill in the basics",description:"Name it LevelUp and add a short description like 'Tools for the LevelUp real estate platform.'"},{label:"Paste the server URL",description:"Paste the MCP server URL below into the Server URL field. Do not paste the tile-portal bridge URL."},{label:"Confirm OAuth",description:"Authentication should be OAuth. Check the 'I understand' box, then tap Create."},{label:"Sign in to LevelUp",description:"ChatGPT will open a LevelUp consent page. Sign in with your LevelUp account and tap Approve."},{label:"Start chatting",description:"Ask ChatGPT to 'list my upcoming LevelUp trainings' or 'summarize my Inner Circle contacts'."}];function Tts(){const[s,t]=N.useState(!1),n=async()=>{try{await navigator.clipboard.writeText(fUe),t(!0),ae.success("MCP URL copied to clipboard"),setTimeout(()=>t(!1),2e3)}catch{ae.error("Could not copy URL")}};return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(US,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Connect ChatGPT to LevelUp"}),e.jsx("p",{className:"text-muted-foreground",children:"Let ChatGPT use LevelUp tools while you are signed in."})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Use this exact MCP server URL"}),e.jsx(Vn,{children:"Paste only this URL into ChatGPT's Server URL field."})]}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"flex-1 block rounded-md bg-muted px-3 py-2 text-sm break-all",children:fUe}),e.jsx(B,{variant:"outline",size:"icon",onClick:n,"aria-label":"Copy MCP URL",children:s?e.jsx(Pi,{className:"h-4 w-4 text-green-600"}):e.jsx(Zr,{className:"h-4 w-4"})})]})})]}),e.jsx(fe,{className:"border-destructive/30 bg-destructive/5",children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(ic,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsx("p",{className:"font-semibold text-destructive",children:"Do not use the bridge URL as the Server URL."}),e.jsx("p",{className:"text-muted-foreground",children:"If ChatGPT shows “does not implement OAuth,” it means this wrong URL was pasted:"}),e.jsx("code",{className:"block rounded-md bg-background px-3 py-2 break-all text-xs",children:Sts}),e.jsx("p",{className:"text-muted-foreground",children:"Delete that plugin attempt and create a new one with the MCP server URL above."})]})]})})}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Quick steps"}),e.jsx(Vn,{children:"ChatGPT adds MCP servers as a new plugin / custom tool. Share these steps with any agent who wants to connect."})]}),e.jsx(Ee,{children:e.jsx("ol",{className:"space-y-4",children:Cts.map((r,a)=>e.jsxs("li",{className:"flex gap-3",children:[e.jsx("span",{className:"flex h-6 w-6 shrink-0 items-center justify-center rounded-full bg-primary/10 text-xs font-medium text-primary",children:a+1}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:r.label}),e.jsx("p",{className:"text-sm text-muted-foreground",children:r.description})]})]},a))})})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(tr,{className:"h-4 w-4"}),e.jsx("span",{children:"Only basic tools are exposed today. More LevelUp actions will be added over time."})]})]})})}const Ets=()=>{const[s]=xl(),t=s.get("tier"),n=t==null?void 0:t.includes("brokerage");return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(fe,{className:"max-w-lg w-full",children:[e.jsxs(It,{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(Pi,{className:"w-10 h-10 text-green-500"})}),e.jsx(Rt,{className:"text-2xl",children:"Welcome to LevelUp!"}),e.jsx(Vn,{className:"text-lg",children:"Your subscription has been activated successfully."})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"p-4 rounded-lg bg-primary/10 border border-primary/20 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(Gs,{className:"w-5 h-5"}),e.jsx("span",{className:"font-semibold",children:"Check your email to sign in"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We've sent you an email with a secure link to access your account. Click the link in your email to get started."})]}),n?e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Create and name your brokerage"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"4."}),"Start inviting agents to join your team"]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"What's next?"}),e.jsxs("ul",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"1."}),"Click the link in your email to sign in"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"2."}),"Set your password and complete your profile"]}),e.jsxs("li",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"font-bold text-primary",children:"3."}),"Start exploring templates, training videos, and more!"]})]}),e.jsx("p",{className:"text-sm text-green-600 font-medium mt-4",children:"🎉 Your 7-day free trial has started!"})]}),e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"Didn't receive the email? Check your spam folder or contact support."})})]})]})})},Ats=()=>{const{user:s}=vs(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(""),o=async h=>{var p;if(!(s!=null&&s.email)){ae.error("Please sign in to upgrade");return}n(!0),a(h);try{const{data:f,error:y}=await q.functions.invoke("create-checkout",{body:{tier:h,email:s.email,name:((p=s.user_metadata)==null?void 0:p.full_name)||s.email,couponCode:i.trim()||void 0,skipTrial:!0}});if(y)throw y;if(f!=null&&f.url)window.open(f.url,"_blank","noopener,noreferrer"),ae.success("Checkout opened in a new tab");else throw new Error("No checkout URL returned")}catch(f){console.error("Checkout error:",f),ae.error(f.message||"Failed to start checkout. Please try again.")}finally{n(!1),a(null)}},c=["Unlimited access to all marketing templates","Complete Academy training library","AI-powered tools and resources","Community forums and support","Exclusive member events and workshops","Deal pipeline & scorecard tracking","Listing exchange access","Social media content library"],d=["Everything in Individual plan","Up to 25 agent seats","Brokerage admin dashboard","Team performance analytics","Custom branding options","Priority support","Agent onboarding tools","Brokerage-wide announcements"],u=["Everything in Brokerage plan","Unlimited agent seats","Dedicated account manager","Advanced analytics & reporting","White-label options","API access","Custom integrations","Enterprise-level support"];return e.jsx(Cs,{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(ne,{htmlFor:"coupon",className:"text-sm font-medium",children:"Have a discount code?"}),e.jsx(ye,{id:"coupon",placeholder:"Enter discount code",value:i,onChange:h=>l(h.target.value),className:"mt-1"})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6 mb-8",children:[e.jsxs(fe,{className:"border-2 border-primary/20 hover:border-primary/50 transition-colors relative overflow-hidden",children:[e.jsx("div",{className:"absolute top-0 right-0 bg-primary text-primary-foreground text-xs px-3 py-1 rounded-bl-lg font-medium",children:"Popular"}),e.jsxs(It,{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(An,{className:"h-7 w-7 text-primary"})}),e.jsx(Rt,{className:"text-xl",children:"Individual Agent"}),e.jsx(Vn,{children:"Perfect for solo agents ready to level up"})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-primary",children:"$39"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:c.map((h,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Lr,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),e.jsxs(B,{className:"w-full",size:"lg",onClick:()=>o("individual_agent"),disabled:t,children:[t&&r==="individual_agent"?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(fe,{className:"border-2 border-amber-500/20 hover:border-amber-500/50 transition-colors",children:[e.jsxs(It,{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(Ua,{className:"h-7 w-7 text-amber-600"})}),e.jsx(Rt,{className:"text-xl",children:"Brokerage"}),e.jsx(Vn,{children:"For teams and brokerages up to 25 agents"})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-amber-600",children:"$299"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:d.map((h,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Lr,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),e.jsxs(B,{variant:"outline",className:"w-full border-amber-500 text-amber-600 hover:bg-amber-50",size:"lg",onClick:()=>o("brokerage_under_25"),disabled:t,children:[t&&r==="brokerage_under_25"?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ua,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]}),e.jsxs(fe,{className:"border-2 border-purple-500/20 hover:border-purple-500/50 transition-colors",children:[e.jsxs(It,{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(Ua,{className:"h-7 w-7 text-purple-600"})}),e.jsx(Rt,{className:"text-xl",children:"Brokerage 25+"}),e.jsx(Vn,{children:"For larger brokerages with 25+ agents"})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"text-center",children:[e.jsx("span",{className:"text-4xl font-bold text-purple-600",children:"$499"}),e.jsx("span",{className:"text-muted-foreground",children:"/month"})]}),e.jsx("ul",{className:"space-y-2",children:u.map((h,p)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Lr,{className:"h-4 w-4 text-purple-600 mt-0.5 shrink-0"}),e.jsx("span",{children:h})]},p))}),e.jsxs(B,{variant:"outline",className:"w-full border-purple-500 text-purple-600 hover:bg-purple-50",size:"lg",onClick:()=>o("brokerage_over_25"),disabled:t,children:[t&&r==="brokerage_over_25"?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ua,{className:"h-4 w-4 mr-2"}),"Get Started"]})]})]})]}),e.jsx(fe,{className:"bg-muted/50",children:e.jsxs(Ee,{className:"py-6",children:[e.jsx("p",{className:"text-center font-medium mb-4",children:"Questions? We're here to help!"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center",children:[e.jsxs("a",{href:"tel:1-866-527-8668",className:"flex items-center justify-center gap-2 text-primary hover:underline",children:[e.jsx(Cr,{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(Gs,{className:"h-4 w-4"}),e.jsx("span",{children:"support@relevelup.com"})]})]})]})})]})})},Mts=()=>{const{user:s,loading:t,isBrokerageManager:n,brokerageId:r}=vs(),a=Ln(),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(!1);N.useEffect(()=>{!t&&!s&&a("/auth")},[s,t,a]),N.useEffect(()=>{!t&&s&&r&&a("/profile?setup=true")},[s,t,r,a]);const h=async()=>{if(!i.trim()){ae.error("Please enter a brokerage name");return}const{data:p}=await q.auth.getSession(),f=p.session;if(!s||!f){ae.error("Please sign in again to create your brokerage."),a("/auth");return}c(!0);try{console.log("[SetupBrokerage] Creating brokerage…",{hasUser:!!s,hasSession:!!f,userId:s==null?void 0:s.id});const{data:y,error:_}=await q.functions.invoke("create-brokerage",{body:{name:i.trim()}});if(console.log("[SetupBrokerage] create-brokerage response",{data:y,error:_}),_)throw _;if(!(y!=null&&y.ok))throw new Error((y==null?void 0:y.error)||"Failed to create brokerage");c(!1),u(!0),ae.success("Brokerage created! Setting up your account..."),setTimeout(()=>{a("/profile?setup=true")},2e3)}catch(y){console.error("Error creating brokerage:",y),ae.error(y.message||"Failed to create brokerage"),c(!1)}};return t?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(fe,{className:"max-w-lg w-full",children:[e.jsxs(It,{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(rs,{className:"w-10 h-10 text-primary animate-spin"})}),e.jsx(Rt,{className:"text-2xl",children:"Setting Up Your Brokerage"}),e.jsx(Vn,{className:"text-lg",children:"We're assigning you as the brokerage manager and preparing your dashboard..."})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-center gap-2 text-muted-foreground",children:[e.jsx(Pi,{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(rs,{className:"w-5 h-5 animate-spin text-primary"}),e.jsx("span",{children:"Assigning you as manager..."})]}),e.jsx("p",{className:"text-center text-sm text-muted-foreground mt-4",children:"You'll be redirected to complete your profile setup in a moment."})]})]})}):e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-background via-primary/5 to-secondary/10 flex items-center justify-center p-4",children:e.jsxs(fe,{className:"max-w-lg w-full",children:[e.jsxs(It,{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(Ua,{className:"w-10 h-10 text-primary"})}),e.jsx(Rt,{className:"text-2xl",children:"Set Up Your Brokerage"}),e.jsx(Vn,{className:"text-lg",children:"Create your brokerage to start managing your team"})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(ye,{id:"brokerage-name",placeholder:"Enter your brokerage name",value:i,onChange:p=>l(p.target.value),onKeyDown:p=>p.key==="Enter"&&h()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This is how your brokerage will appear to your agents"})]}),e.jsxs("div",{className:"p-4 rounded-lg bg-muted/50 space-y-3",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2",children:[e.jsx(An,{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(Pi,{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(Pi,{className:"w-4 h-4 text-green-500"}),"Access exclusive brokerage resources"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx(Pi,{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(Pi,{className:"w-4 h-4 text-green-500"}),"Share resources with your agents"]})]})]}),e.jsxs(B,{onClick:h,className:"w-full",disabled:o||!i.trim(),children:[o?"Creating...":"Create Brokerage",e.jsx(Oa,{className:"w-4 h-4 ml-2"})]})]})]})})},xUe=()=>{const s=Ln(),[t,n]=N.useState("verifying"),[r,a]=N.useState("");N.useEffect(()=>{(async()=>{try{const{data:{session:o},error:c}=await q.auth.getSession();if(c)throw c;if(o!=null&&o.user){const{data:d}=await q.from("profiles").select("login_count").eq("id",o.user.id).single();if(((d==null?void 0:d.login_count)||0)>1){console.log("Account already claimed, redirecting to dashboard"),n("already_claimed");return}console.log("User logged in successfully:",o.user.email),n("success");try{await q.functions.invoke("trial-claim-hook",{body:{userId:o.user.id}})}catch(u){console.log("Trial claim hook (non-critical):",u)}setTimeout(()=>{s("/profile?setup=true")},1500)}else setTimeout(()=>{n("already_claimed")},2e3)}catch(o){console.error("Claim error:",o),n("already_claimed")}})()},[s]);const i=()=>{window.location.href="https://dashboard.relevelup.com/auth"};return e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{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(Rt,{className:"text-2xl",children:[t==="verifying"&&"Claiming Your Account...",t==="success"&&"Account Claimed!",t==="already_claimed"&&"Account Already Claimed",t==="error"&&"Claim Failed"]}),e.jsxs(Vn,{children:[t==="verifying"&&"Please wait while we verify your account...",t==="success"&&"Redirecting you to complete your profile...",t==="already_claimed"&&"This account has already been set up. Please log in to access your dashboard.",t==="error"&&r]})]}),(t==="already_claimed"||t==="error")&&e.jsx(Ee,{children:e.jsx(B,{onClick:i,className:"w-full",children:"Go to Login"})})]})})},Its=()=>{const[s,t]=N.useState(!1),n=N.useMemo(()=>new URLSearchParams(window.location.search).get("link"),[]),r=N.useMemo(()=>{if(!n)return!1;try{const i=new URL(n);return i.hostname.endsWith(".supabase.co")&&i.pathname.startsWith("/auth/v1/verify")}catch{return!1}},[n]);N.useEffect(()=>{document.title="Reset Your Password"},[]);const a=()=>{!r||!n||(t(!0),window.location.href=n)};return e.jsxs("div",{className:"min-h-screen relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-[#4a6b6d] via-[#3d5a5c] to-[#2a4347]"}),e.jsx("div",{className:"relative z-10 flex flex-col min-h-screen items-center justify-center p-4",children:e.jsxs("div",{className:"w-full max-w-md",children:[e.jsx("div",{className:"flex justify-center mb-8",children:e.jsx("div",{className:"bg-white rounded-xl p-4 shadow-2xl",children:e.jsx("img",{src:vht,alt:"LevelUp",className:"h-12 w-auto"})})}),e.jsxs(fe,{className:"border-0 shadow-2xl bg-white/95 backdrop-blur-sm",children:[e.jsxs(It,{className:"text-center",children:[e.jsx(Rt,{className:"text-2xl font-bold text-[#2a4347]",style:{fontFamily:"'Libre Baskerville', serif"},children:"Reset Your Password"}),e.jsx(Vn,{className:"text-gray-600 pt-2",children:r?"Click the button below to continue resetting your password.":"This link is invalid or has expired. Please request a new password reset email."})]}),e.jsxs(Ee,{className:"space-y-4",children:[r?e.jsx(B,{onClick:a,disabled:s,className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg shadow-lg hover:shadow-xl",children:s?"Continuing…":"Continue to Reset Password"}):e.jsx(B,{onClick:()=>window.location.href="/auth",className:"w-full bg-[#4a6b6d] hover:bg-[#3d5a5c] text-white font-semibold py-6 text-lg",children:"Go to Sign In"}),e.jsx("p",{className:"text-xs text-center text-gray-500 pt-2",children:"For your security, password reset links expire and can only be used once."})]})]})]})})]})},Pts=()=>{const s=Ln(),[t]=xl(),[n,r]=N.useState(t.get("code")||""),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[y,_]=N.useState(!1),[v,j]=N.useState(!1),[w,S]=N.useState(null),[A,E]=N.useState(null),[O,D]=N.useState(null),[I,F]=N.useState(null);N.useEffect(()=>{const Y=t.get("code");Y&&(r(Y),z(Y))},[t]);const z=async Y=>{_(!0);const{data:W,error:ee}=await q.from("invite_codes").select("id, code, max_uses, uses_count, expires_at, is_active, brokerage_id, trial_days").eq("code",Y.toUpperCase().trim()).single();if(ee||!W){ae.error("Invalid invite code"),_(!1);return}if(!W.is_active){ae.error("This invite code is no longer active"),_(!1);return}if(W.max_uses&&W.uses_count>=W.max_uses){ae.error("This invite code has reached its maximum uses"),_(!1);return}if(W.expires_at&&new Date(W.expires_at){Y.preventDefault(),z(n)},Z=async Y=>{var W;if(Y.preventDefault(),!c.trim()){ae.error("Please enter your name");return}if(l.length<6){ae.error("Password must be at least 6 characters");return}f(!0);try{const ee=`${window.location.origin}/`,{data:se,error:oe}=await q.auth.signUp({email:a.trim(),password:l,options:{emailRedirectTo:ee,data:{name:c.trim()}}});if(oe){oe.message.includes("already registered")?ae.error("This email is already registered. Please sign in instead."):ae.error(oe.message);return}if(se.user){await q.rpc("add_default_signup_tag",{user_id:se.user.id});const he=n.toUpperCase().trim();A?await q.functions.invoke("assign-brokerage",{body:{userId:se.user.id,brokerageId:A,inviteCode:he}}):I?await q.functions.invoke("assign-brokerage",{body:{userId:se.user.id,trialDays:I,inviteCode:he}}):await q.functions.invoke("assign-brokerage",{body:{userId:se.user.id,grandfathered:!0,inviteCode:he}}),w&&await q.from("invite_codes").update({uses_count:((W=(await q.from("invite_codes").select("uses_count").eq("id",w).single()).data)==null?void 0:W.uses_count)+1}).eq("id",w),ae.success("Account created! You can now access the dashboard."),s("/dashboard")}}catch(ee){console.error("Signup error:",ee),ae.error("An unexpected error occurred")}finally{f(!1)}};return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{className:"text-center",children:[e.jsx(Rt,{className:"text-2xl font-bold text-primary",children:O?`Join ${O}`:"Join LevelUp"}),e.jsx(Vn,{children:v?O?`Create your account to join ${O}`:"Create your account to get started":"Enter your invite code to continue"})]}),e.jsx(Ee,{children:v?e.jsxs("form",{onSubmit:Z,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"name",children:"Full Name"}),e.jsx(ye,{id:"name",type:"text",placeholder:"John Doe",value:c,onChange:Y=>d(Y.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",placeholder:"you@example.com",value:a,onChange:Y=>i(Y.target.value),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"password",children:"Password"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{id:"password",type:u?"text":"password",placeholder:"••••••••",value:l,onChange:Y=>o(Y.target.value),required:!0,minLength:6}),e.jsx("button",{type:"button",className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",onClick:()=>h(!u),children:u?e.jsx(mf,{className:"h-4 w-4"}):e.jsx(Sr,{className:"h-4 w-4"})})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:p,children:p?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating Account..."]}):"Create Account"})]}):e.jsxs("form",{onSubmit:H,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"inviteCode",children:"Invite Code"}),e.jsx(ye,{id:"inviteCode",type:"text",placeholder:"Enter your invite code",value:n,onChange:Y=>r(Y.target.value),required:!0,autoFocus:!0})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:y,children:y?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}),"Verifying..."]}):"Verify Code"})]})})]})})},rU=()=>{const{user:s,isCoach:t}=vs();return dt({queryKey:["my-coach-profile",s==null?void 0:s.id],enabled:!!s&&t,queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("*").eq("user_id",s.id).maybeSingle();if(r)throw r;return n}})},Lts=()=>{const{data:s}=rU();return dt({queryKey:["coach-roster",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("coach_id",s.id).order("started_at",{ascending:!1});if(n)throw n;const r=t||[];if(r.length===0)return[];const a=r.map(o=>o.agent_id),{data:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>({...o,agent:l.get(o.agent_id)||null}))}})},Dts=()=>{const{user:s}=vs();return dt({queryKey:["my-coaching-assignment",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("agent_id",s.id).eq("status","active").order("started_at",{ascending:!1}).limit(1);if(n)throw n;const r=(t||[])[0];if(!r)return null;const{data:a}=await q.from("coaches").select("*").eq("id",r.coach_id).maybeSingle();let i=null;if(a!=null&&a.user_id){const{data:l}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",a.user_id).maybeSingle();i=l}return{...r,coach:a,coachProfile:i}}})},Rts=s=>dt({queryKey:["coaching-assignment",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_assignments").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return null;const{data:r}=await q.from("profiles").select("id, name, email, avatar_url").eq("id",t.agent_id).maybeSingle();return{...t,agent:r}}}),hmt=s=>dt({queryKey:["coaching-sessions",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_sessions").select("*").eq("assignment_id",s).order("scheduled_at",{ascending:!1});if(n)throw n;return t||[]}}),mmt=s=>dt({queryKey:["coaching-action-items",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("coaching_action_items").select("*").eq("assignment_id",s).order("due_date",{ascending:!0,nullsFirst:!1});if(n)throw n;return t||[]}}),Ots=[{key:"onboarding",label:"Onboarding"},{key:"active",label:"Active"},{key:"thriving",label:"Thriving"},{key:"at_risk",label:"At Risk"},{key:"graduated",label:"Graduated"}];function Fts(){const s=Ln(),{data:t,isLoading:n}=rU(),{data:r=[],isLoading:a}=Lts();if(n)return e.jsx(Cs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Cs,{title:"Coaching",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(yd,{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."})]})});Ots.map(l=>({...l,items:r.filter(o=>(o.pipeline_stage||"active")===l.key)}));const i=r.filter(l=>l.status==="active").length;return e.jsx(Cs,{title:"Coaching",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-8",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-white/80",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider font-medium",children:"Coaching Command Center"})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-2",children:"Welcome back, Coach"}),e.jsx("p",{className:"text-white/80 mb-6",children:"Lead your agents. Track momentum. Build champions."}),e.jsxs("div",{className:"flex flex-wrap gap-6",children:[e.jsx(_je,{icon:yd,label:"Active agents",value:i}),e.jsx(_je,{icon:Cl,label:"This month",value:"—"}),e.jsx(_je,{icon:Hc,label:"Momentum",value:"🔥"})]})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Your Roster"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>s("/coaching/waitlist"),children:"Waitlist"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>s("/coaching/settings"),children:"Profile Settings"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>s("/coaching/billing"),children:"Billing & Packages"})]})]}),a?e.jsx("div",{className:"text-muted-foreground",children:"Loading roster…"}):r.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No agents assigned yet. An admin or you can invite agents to get started."})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:r.map(l=>{var o,c,d,u;return e.jsx(fe,{className:"cursor-pointer hover:shadow-lg transition-all hover:-translate-y-0.5",onClick:()=>s(`/coaching/agent/${l.id}`),children:e.jsx(Ee,{className:"p-5",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs(Jr,{className:"h-14 w-14",children:[e.jsx(ti,{src:((o=l.agent)==null?void 0:o.avatar_url)||void 0}),e.jsx(ea,{children:(((c=l.agent)==null?void 0:c.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("h3",{className:"font-semibold truncate",children:((d=l.agent)==null?void 0:d.name)||"Unknown"}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:(u=l.agent)==null?void 0:u.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-3",children:[e.jsx(Ue,{variant:"secondary",className:"capitalize",children:(l.pipeline_stage||"active").replace("_"," ")}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["Started ",Uo(new Date(l.started_at),{addSuffix:!0})]})]})]})]})})},l.id)})})]})]})})}function _je({icon:s,label:t,value:n}){return e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-white/15 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-white/70 mt-1",children:t})]})]})}function pmt({assignmentId:s}){const{user:t}=vs(),n=Kt(),[r,a]=N.useState(""),[i,l]=N.useState(!1),o=N.useRef(null),{data:c=[]}=dt({queryKey:["coaching-messages",s],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await q.from("coaching_messages").select("*").eq("assignment_id",s).order("created_at",{ascending:!0});if(h)throw h;return u||[]}});N.useEffect(()=>{if(!s)return;const u=q.channel(`coaching-messages-${s}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"coaching_messages",filter:`assignment_id=eq.${s}`},()=>n.invalidateQueries({queryKey:["coaching-messages",s]})).subscribe();return()=>{q.removeChannel(u)}},[s,n]),N.useEffect(()=>{var u;(u=o.current)==null||u.scrollTo({top:o.current.scrollHeight,behavior:"smooth"})},[c]);const d=async()=>{const u=r.trim();if(!u||!t)return;l(!0);const{error:h}=await q.from("coaching_messages").insert({assignment_id:s,sender_id:t.id,body:u});l(!1),h||a("")};return e.jsxs(fe,{className:"flex flex-col h-[60vh] min-h-[400px]",children:[e.jsx("div",{ref:o,className:"flex-1 overflow-y-auto p-4 space-y-3",children:c.length===0?e.jsx("div",{className:"h-full flex items-center justify-center text-sm text-muted-foreground",children:"No messages yet. Say hi 👋"}):c.map(u=>{const h=u.sender_id===(t==null?void 0:t.id);return e.jsxs("div",{className:Mt("flex gap-2",h?"justify-end":"justify-start"),children:[!h&&e.jsx(Jr,{className:"h-8 w-8 mt-1",children:e.jsx(ea,{className:"text-xs",children:(u.sender_id||"?").charAt(0).toUpperCase()})}),e.jsxs("div",{className:Mt("max-w-[75%] rounded-2xl px-3 py-2 text-sm",h?"bg-[#406E71] text-white rounded-br-sm":"bg-muted rounded-bl-sm"),children:[e.jsx("p",{className:"whitespace-pre-wrap break-words",children:u.body}),e.jsx("p",{className:Mt("text-[10px] mt-1",h?"text-white/70":"text-muted-foreground"),children:Uo(new Date(u.created_at),{addSuffix:!0})})]})]},u.id)})}),e.jsx(Ee,{className:"border-t p-3",children:e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsx(Ms,{value:r,onChange:u=>a(u.target.value),onKeyDown:u=>{u.key==="Enter"&&!u.shiftKey&&(u.preventDefault(),d())},placeholder:"Type a message…",rows:1,className:"resize-none min-h-[40px]"}),e.jsx(B,{onClick:d,disabled:i||!r.trim(),size:"icon",className:"bg-[#406E71] hover:bg-[#2a4c64]",children:e.jsx(lr,{className:"h-4 w-4"})})]})})]})}var KMe="Progress",YMe=100,[zts,dfn]=uu(KMe),[Bts,$ts]=zts(KMe),fmt=N.forwardRef((s,t)=>{const{__scopeProgress:n,value:r=null,max:a,getValueLabel:i=Uts,...l}=s;(a||a===0)&&!gUe(a)&&console.error(qts(`${a}`,"Progress"));const o=gUe(a)?a:YMe;r!==null&&!yUe(r,o)&&console.error(Vts(`${r}`,"Progress"));const c=yUe(r,o)?r:null,d=yfe(c)?i(c,o):void 0;return e.jsx(Bts,{scope:n,value:c,max:o,children:e.jsx(Yr.div,{"aria-valuemax":o,"aria-valuemin":0,"aria-valuenow":yfe(c)?c:void 0,"aria-valuetext":d,role:"progressbar","data-state":ymt(c,o),"data-value":c??void 0,"data-max":o,...l,ref:t})})});fmt.displayName=KMe;var xmt="ProgressIndicator",gmt=N.forwardRef((s,t)=>{const{__scopeProgress:n,...r}=s,a=$ts(xmt,n);return e.jsx(Yr.div,{"data-state":ymt(a.value,a.max),"data-value":a.value??void 0,"data-max":a.max,...r,ref:t})});gmt.displayName=xmt;function Uts(s,t){return`${Math.round(s/t*100)}%`}function ymt(s,t){return s==null?"indeterminate":s===t?"complete":"loading"}function yfe(s){return typeof s=="number"}function gUe(s){return yfe(s)&&!isNaN(s)&&s>0}function yUe(s,t){return yfe(s)&&!isNaN(s)&&s<=t&&s>=0}function qts(s,t){return`Invalid prop \`max\` of value \`${s}\` supplied to \`${t}\`. Only numbers greater than 0 are valid max values. Defaulting to \`${YMe}\`.`}function Vts(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 ${YMe} if no \`max\` prop is set) - \`null\` or \`undefined\` if the progress is indeterminate. Defaulting to \`null\`.`}var vmt=fmt,Hts=gmt;const fi=N.forwardRef(({className:s,value:t,...n},r)=>e.jsx(vmt,{ref:r,className:Mt("relative h-4 w-full overflow-hidden rounded-full bg-secondary",s),...n,children:e.jsx(Hts,{className:"h-full w-full flex-1 bg-primary transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})}));fi.displayName=vmt.displayName;function bmt({agentUserId:s}){const t=new Date().getFullYear(),n=`${t}-01-01`,r=`${t}-12-31`,{data:a=[]}=dt({queryKey:["coaching-kpi-txns",s,t],enabled:!!s,queryFn:async()=>{const{data:_,error:v}=await q.from("scorecard_transactions").select("id, sale_price, commission_amount, close_date, is_win").eq("owner_user_id",s).gte("close_date",n).lte("close_date",r);if(v)throw v;return _||[]}}),{data:i}=dt({queryKey:["coaching-kpi-goal",s,t],enabled:!!s,queryFn:async()=>{const{data:_}=await q.from("scorecard_goals").select("*").eq("owner_user_id",s).eq("year",t).maybeSingle();return _}}),l=a.filter(_=>_.is_win),o=l.length,c=l.reduce((_,v)=>_+(Number(v.sale_price)||0),0),d=l.reduce((_,v)=>_+(Number(v.commission_amount)||0),0),u=i,h=(u==null?void 0:u.transactions_goal)||0,p=(u==null?void 0:u.volume_goal)||0,f=(u==null?void 0:u.gci_goal)||0,y=_=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(_);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(go,{className:"h-5 w-5"})," ",t," KPIs"]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsx(wje,{icon:fc,label:"Transactions",value:o.toString(),goal:h,current:o,suffix:h?`/ ${h}`:""}),e.jsx(wje,{icon:go,label:"Volume",value:y(c),goal:p,current:c,suffix:p?`of ${y(p)}`:""}),e.jsx(wje,{icon:Yl,label:"GCI",value:y(d),goal:f,current:d,suffix:f?`of ${y(f)}`:""})]}),o===0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-sm text-muted-foreground text-center",children:["No transactions logged for ",t," yet."]})})]})}function wje({icon:s,label:t,value:n,goal:r,current:a,suffix:i}){const l=r>0?Math.min(100,a/r*100):0;return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-2",children:[e.jsx(s,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs uppercase tracking-wider",children:t})]}),e.jsx("div",{className:"text-2xl font-bold",children:n}),r>0&&e.jsxs("div",{className:"mt-2 space-y-1",children:[e.jsx(fi,{value:l}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsx("span",{children:i}),e.jsxs("span",{children:[l.toFixed(0),"%"]})]})]})]})})}function _mt({assignmentId:s,canEdit:t}){const n=Kt(),[r,a]=N.useState(!1),[i,l]=N.useState(null),{data:o=[]}=dt({queryKey:["coaching-goals",s],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("coaching_goals").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(u)throw u;return d||[]}}),c=()=>n.invalidateQueries({queryKey:["coaching-goals",s]});return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Ac,{className:"h-5 w-5"})," Goals"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>{l(null),a(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),o.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-center text-muted-foreground",children:"No goals yet."})}):o.map(d=>{const u=Number(d.target_value||0),h=Number(d.current_value||0),p=u>0?Math.min(100,h/u*100):0;return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:d.title}),e.jsx(Ue,{variant:"outline",className:"capitalize",children:d.status||"active"})]}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:d.description})]}),t&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{l(d),a(!0)},children:e.jsx(ya,{className:"h-4 w-4"})})]}),u>0&&e.jsxs("div",{className:"mt-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[h.toLocaleString()," / ",u.toLocaleString()," ",d.target_metric||""]}),e.jsxs("span",{children:[p.toFixed(0),"%"]})]}),e.jsx(fi,{value:p})]}),d.due_date&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Due ",Ss(new Date(d.due_date),"PP")]})]})},d.id)}),t&&e.jsx(Gts,{open:r,onOpenChange:a,assignmentId:s,goal:i,onSaved:c})]})}function Gts({open:s,onOpenChange:t,assignmentId:n,goal:r,onSaved:a}){var A,E;const[i,l]=N.useState((r==null?void 0:r.title)||""),[o,c]=N.useState((r==null?void 0:r.description)||""),[d,u]=N.useState((r==null?void 0:r.target_metric)||""),[h,p]=N.useState(((A=r==null?void 0:r.target_value)==null?void 0:A.toString())||""),[f,y]=N.useState(((E=r==null?void 0:r.current_value)==null?void 0:E.toString())||"0"),[_,v]=N.useState((r==null?void 0:r.due_date)||""),[j,w]=N.useState(!1);N.useState(()=>{var O,D;l((r==null?void 0:r.title)||""),c((r==null?void 0:r.description)||""),u((r==null?void 0:r.target_metric)||""),p(((O=r==null?void 0:r.target_value)==null?void 0:O.toString())||""),y(((D=r==null?void 0:r.current_value)==null?void 0:D.toString())||"0"),v((r==null?void 0:r.due_date)||"")});const S=async()=>{if(!i.trim())return;w(!0);const O={assignment_id:n,title:i,description:o||null,target_metric:d||null,target_value:h?Number(h):null,current_value:f?Number(f):0,due_date:_||null},{error:D}=r!=null&&r.id?await q.from("coaching_goals").update(O).eq("id",r.id):await q.from("coaching_goals").insert(O);if(w(!1),D)return ae.error(D.message);ae.success(r!=null&&r.id?"Goal updated":"Goal created"),a==null||a(),t(!1)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:r!=null&&r.id?"Edit Goal":"New Goal"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ye,{placeholder:"Title",value:i,onChange:O=>l(O.target.value)}),e.jsx(Ms,{placeholder:"Description (optional)",rows:2,value:o,onChange:O=>c(O.target.value)}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Metric"}),e.jsx(ye,{placeholder:"transactions",value:d,onChange:O=>u(O.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Target"}),e.jsx(ye,{type:"number",value:h,onChange:O=>p(O.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Current"}),e.jsx(ye,{type:"number",value:f,onChange:O=>y(O.target.value)})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Due date"}),e.jsx(ye,{type:"date",value:_,onChange:O=>v(O.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:j,children:r!=null&&r.id?"Save":"Create"})]})]})})}function wmt({assignmentId:s}){const t=Kt(),{user:n}=vs(),r=N.useRef(null),[a,i]=N.useState(!1),{data:l=[]}=dt({queryKey:["coaching-files",s],enabled:!!s,queryFn:async()=>{const{data:h,error:p}=await q.from("coaching_shared_files").select("*").eq("assignment_id",s).order("created_at",{ascending:!1});if(p)throw p;return h||[]}}),o=()=>t.invalidateQueries({queryKey:["coaching-files",s]}),c=async h=>{var f;const p=(f=h.target.files)==null?void 0:f[0];if(!(!p||!n)){i(!0);try{const y=`${s}/${Date.now()}-${p.name}`,{error:_}=await q.storage.from("coaching-files").upload(y,p);if(_)throw _;const{error:v}=await q.from("coaching_shared_files").insert({assignment_id:s,uploaded_by:n.id,file_url:y,file_name:p.name,file_size_bytes:p.size,mime_type:p.type});if(v)throw v;ae.success("File uploaded"),o()}catch(y){ae.error(y.message||"Upload failed")}finally{i(!1),r.current&&(r.current.value="")}}},d=async h=>{const{data:p,error:f}=await q.storage.from("coaching-files").createSignedUrl(h.file_url,60);if(f||!p)return ae.error("Could not get download link");window.open(p.signedUrl,"_blank")},u=async h=>{confirm("Delete this file?")&&(await q.storage.from("coaching-files").remove([h.file_url]),await q.from("coaching_shared_files").delete().eq("id",h.id),o())};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Shared Files"}),e.jsxs(B,{size:"sm",onClick:()=>{var h;return(h=r.current)==null?void 0:h.click()},disabled:a,children:[e.jsx(_a,{className:"h-4 w-4 mr-1"})," ",a?"Uploading…":"Upload"]}),e.jsx("input",{ref:r,type:"file",hidden:!0,onChange:c})]}),l.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-center text-muted-foreground",children:"No files yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(h=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-muted flex items-center justify-center",children:e.jsx(br,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.file_name}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[h.file_size_bytes?`${(h.file_size_bytes/1024).toFixed(0)} KB · `:"",Ss(new Date(h.created_at),"PP")]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>d(h),children:e.jsx(Ia,{className:"h-4 w-4"})}),h.uploaded_by===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h),children:e.jsx(_n,{className:"h-4 w-4"})})]})},h.id))})]})}function Wts(){var p,f,y,_;const{id:s}=bi(),t=Ln(),n=Kt(),{data:r,isLoading:a}=Rts(s),{data:i=[]}=hmt(s),{data:l=[]}=mmt(s),[o,c]=N.useState(!1),[d,u]=N.useState(!1);if(a)return e.jsx(Cs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!r)return e.jsx(Cs,{title:"Coaching",children:e.jsx("div",{className:"p-8",children:"Assignment not found."})});const h=r;return e.jsxs(Cs,{title:"Coaching",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-6xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/coaching"),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"})," Back to roster"]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-24 bg-gradient-to-br from-[#2a4c64] to-[#406E71]"}),e.jsx(Ee,{className:"pt-0 -mt-12 pb-6",children:e.jsxs("div",{className:"flex flex-col md:flex-row gap-4 md:items-end",children:[e.jsxs(Jr,{className:"h-24 w-24 ring-4 ring-background",children:[e.jsx(ti,{src:((p=h.agent)==null?void 0:p.avatar_url)||void 0}),e.jsx(ea,{className:"text-2xl",children:(((f=h.agent)==null?void 0:f.name)||"?").charAt(0)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-2xl font-bold",children:((y=h.agent)==null?void 0:y.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(_=h.agent)==null?void 0:_.email}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Ue,{variant:"secondary",className:"capitalize",children:(h.pipeline_stage||"active").replace("_"," ")}),e.jsx(Ue,{variant:"outline",className:"capitalize",children:h.status})]})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Kts,{value:h.pipeline_stage||"active",onChange:async v=>{await q.from("coaching_assignments").update({pipeline_stage:v}).eq("id",h.id),n.invalidateQueries({queryKey:["coaching-assignment",h.id]}),n.invalidateQueries({queryKey:["coach-roster"]})}})})]})})]}),e.jsxs(Fr,{defaultValue:"sessions",children:[e.jsxs(Rr,{className:"w-full flex flex-wrap justify-start h-auto",children:[e.jsxs(Zt,{value:"sessions",children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Sessions"]}),e.jsxs(Zt,{value:"actions",children:[e.jsx(lu,{className:"h-4 w-4 mr-2"}),"Actions"]}),e.jsxs(Zt,{value:"goals",children:[e.jsx(Ac,{className:"h-4 w-4 mr-2"}),"Goals"]}),e.jsxs(Zt,{value:"kpis",children:[e.jsx(go,{className:"h-4 w-4 mr-2"}),"KPIs"]}),e.jsxs(Zt,{value:"messages",children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Messages"]}),e.jsxs(Zt,{value:"files",children:[e.jsx(pf,{className:"h-4 w-4 mr-2"}),"Files"]}),e.jsxs(Zt,{value:"notes",children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"Private Notes"]})]}),e.jsxs(is,{value:"sessions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sessions"}),e.jsxs(B,{size:"sm",onClick:()=>c(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," New Session"]})]}),i.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-muted-foreground text-center",children:"No sessions yet."})}):e.jsx("div",{className:"space-y-3",children:i.map(v=>e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:Ss(new Date(v.scheduled_at),"PPp")}),e.jsx(Ue,{variant:"outline",className:"capitalize",children:v.status}),v.template&&e.jsx(Ue,{variant:"secondary",children:v.template})]}),v.summary&&e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:v.summary}),v.private_notes&&e.jsxs("div",{className:"mt-2 p-2 rounded bg-muted/50 text-xs",children:[e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground mb-1",children:[e.jsx(Gc,{className:"h-3 w-3"})," Private"]}),e.jsx("p",{className:"whitespace-pre-wrap",children:v.private_notes})]})]})})})},v.id))})]}),e.jsxs(is,{value:"actions",className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Action Items"}),e.jsxs(B,{size:"sm",onClick:()=>u(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add"]})]}),l.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-muted-foreground text-center",children:"No action items yet."})}):e.jsx("div",{className:"space-y-2",children:l.map(v=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-3 flex items-center gap-3",children:[e.jsx(hi,{checked:v.status==="done",onCheckedChange:async j=>{await q.from("coaching_action_items").update({status:j?"done":"open",completed_at:j?new Date().toISOString():null}).eq("id",v.id),n.invalidateQueries({queryKey:["coaching-action-items",h.id]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:v.status==="done"?"line-through text-muted-foreground":"font-medium",children:v.title}),v.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:v.description})]}),v.due_date&&e.jsx(Ue,{variant:"outline",children:Ss(new Date(v.due_date),"MMM d")}),e.jsx(Ue,{variant:"secondary",className:"capitalize",children:v.priority})]})},v.id))})]}),e.jsx(is,{value:"goals",children:e.jsx(_mt,{assignmentId:h.id,canEdit:!0})}),e.jsx(is,{value:"kpis",children:h.agent_id&&e.jsx(bmt,{agentUserId:h.agent_id})}),e.jsx(is,{value:"messages",children:e.jsx(pmt,{assignmentId:h.id})}),e.jsx(is,{value:"files",children:e.jsx(wmt,{assignmentId:h.id})}),e.jsx(is,{value:"notes",className:"space-y-4",children:e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-muted-foreground",children:"Private notes per session live under the Sessions tab. General-relationship notes coming soon."})})})]})]}),e.jsx(Yts,{open:o,onOpenChange:c,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-sessions",h.id]})}),e.jsx(Zts,{open:d,onOpenChange:u,assignmentId:h.id,onSaved:()=>n.invalidateQueries({queryKey:["coaching-action-items",h.id]})})]})}function Kts({value:s,onChange:t}){return e.jsxs(us,{value:s,onValueChange:t,children:[e.jsx(ls,{className:"w-40",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"onboarding",children:"Onboarding"}),e.jsx(Ze,{value:"active",children:"Active"}),e.jsx(Ze,{value:"thriving",children:"Thriving"}),e.jsx(Ze,{value:"at_risk",children:"At Risk"}),e.jsx(Ze,{value:"graduated",children:"Graduated"})]})]})}function Yts({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=N.useState(()=>new Date().toISOString().slice(0,16)),[l,o]=N.useState(60),[c,d]=N.useState("weekly_1on1"),[u,h]=N.useState(""),[p,f]=N.useState(""),[y,_]=N.useState(!1),[v,j]=N.useState(!0),[w,S]=N.useState(null),[A,E]=N.useState(!1),O=async()=>{E(!0);const{data:I,error:F}=await q.functions.invoke("coaching-prep-brief",{body:{assignmentId:n}});if(E(!1),F||I!=null&&I.error)return ae.error((I==null?void 0:I.error)||(F==null?void 0:F.message)||"Failed to generate brief");S(I.brief||"No brief returned.")},D=async()=>{_(!0);const{data:I,error:F}=await q.from("coaching_sessions").insert({assignment_id:n,scheduled_at:new Date(a).toISOString(),duration_minutes:l,template:c,summary:u,private_notes:p,status:"completed"}).select("id").maybeSingle();if(F)return _(!1),ae.error(F.message);if(ae.success("Session saved"),v&&u.trim()&&(I!=null&&I.id)){const{error:z}=await q.functions.invoke("coaching-send-recap",{body:{sessionId:I.id}});z?ae.error("Saved, but recap email failed: "+z.message):ae.success("Recap emailed to agent")}_(!1),r==null||r(),t(!1),h(""),f(""),S(null)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ws,{children:"New Session"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:O,disabled:A,children:[A?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-1"}),"Pre-session brief"]})]})}),e.jsxs("div",{className:"space-y-3",children:[w&&e.jsxs("div",{className:"rounded-lg border bg-gradient-to-br from-[#406E71]/5 to-[#2a4c64]/5 p-3 text-sm whitespace-pre-wrap max-h-60 overflow-y-auto",children:[e.jsxs("div",{className:"flex items-center gap-1 text-xs font-medium text-[#406E71] mb-2",children:[e.jsx(un,{className:"h-3 w-3"})," AI Brief"]}),w]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"When"}),e.jsx(ye,{type:"datetime-local",value:a,onChange:I=>i(I.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Duration (min)"}),e.jsx(ye,{type:"number",value:l,onChange:I=>o(Number(I.target.value))})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Template"}),e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"weekly_1on1",children:"Weekly 1:1"}),e.jsx(Ze,{value:"grow",children:"GROW Model"}),e.jsx(Ze,{value:"goal_review",children:"Goal Review"}),e.jsx(Ze,{value:"breakthrough",children:"Breakthrough Session"})]})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Summary (agent sees this)"}),e.jsx(Ms,{rows:4,value:u,onChange:I=>h(I.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(Gc,{className:"h-3 w-3"})," Private notes (only you)"]}),e.jsx(Ms,{rows:3,value:p,onChange:I=>f(I.target.value),placeholder:"Your private observations…"})]}),e.jsxs("label",{className:"flex items-center gap-2 text-sm pt-1",children:[e.jsx(hi,{checked:v,onCheckedChange:I=>j(!!I)}),e.jsx(lr,{className:"h-3.5 w-3.5 text-muted-foreground"}),"Email recap to agent on save"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:D,disabled:y,children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save Session"]})]})]})})}function Zts({open:s,onOpenChange:t,assignmentId:n,onSaved:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState("medium"),[p,f]=N.useState(!1),y=async()=>{if(!a.trim())return;f(!0);const{error:_}=await q.from("coaching_action_items").insert({assignment_id:n,title:a,description:l||null,due_date:c||null,priority:u});if(f(!1),_)return ae.error(_.message);ae.success("Action item added"),r==null||r(),t(!1),i(""),o(""),d("")};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"New Action Item"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ye,{placeholder:"Title",value:a,onChange:_=>i(_.target.value)}),e.jsx(Ms,{rows:3,placeholder:"Description (optional)",value:l,onChange:_=>o(_.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Due date"}),e.jsx(ye,{type:"date",value:c,onChange:_=>d(_.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Priority"}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"low",children:"Low"}),e.jsx(Ze,{value:"medium",children:"Medium"}),e.jsx(Ze,{value:"high",children:"High"})]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:y,disabled:p,children:"Add"})]})]})})}function J4e({value:s,size:t=16,onChange:n}){return e.jsx("div",{className:"flex items-center gap-0.5",children:[1,2,3,4,5].map(r=>e.jsx("button",{type:"button",onClick:()=>n==null?void 0:n(r),disabled:!n,className:n?"cursor-pointer":"cursor-default",children:e.jsx(oa,{style:{width:t,height:t},className:r<=s?"fill-yellow-400 text-yellow-400":"text-muted-foreground/40"})},r))})}function Qts({coachId:s}){const[t,n]=N.useState([]),[r,a]=N.useState(!0);N.useEffect(()=>{(async()=>{const{data:l}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("is_published",!0).order("created_at",{ascending:!1}),o=l||[];if(o.length){const c=o.map(h=>h.agent_id),{data:d}=await q.from("profiles").select("id, name, avatar_url").in("id",c),u=new Map((d||[]).map(h=>[h.id,h]));o.forEach(h=>h.profile=u.get(h.agent_id))}n(o),a(!1)})()},[s]);const i=t.length?t.reduce((l,o)=>l+o.rating,0)/t.length:0;return r||!t.length?null:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Reviews"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(J4e,{value:Math.round(i)}),e.jsxs("span",{children:[i.toFixed(1)," · ",t.length," review",t.length===1?"":"s"]})]})]}),e.jsx("div",{className:"space-y-3",children:t.map(l=>{var o,c,d;return e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs(Jr,{className:"h-9 w-9",children:[e.jsx(ti,{src:((o=l.profile)==null?void 0:o.avatar_url)||void 0}),e.jsx(ea,{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(J4e,{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 Xts({coachId:s,assignmentId:t}){const{user:n}=vs(),[r,a]=N.useState(null),[i,l]=N.useState(0),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(!1);N.useEffect(()=>{n&&(async()=>{const{data:y}=await q.from("coaching_reviews").select("*").eq("coach_id",s).eq("agent_id",n.id).maybeSingle();y&&(a(y),l(y.rating),c(y.title||""),u(y.body||""))})()},[n,s]);const f=async()=>{if(!n)return;if(!i)return ae.error("Pick a rating");p(!0);const y={coach_id:s,agent_id:n.id,assignment_id:t||null,rating:i,title:o||null,body:d||null},{error:_}=r?await q.from("coaching_reviews").update(y).eq("id",r.id):await q.from("coaching_reviews").insert(y);if(p(!1),_)return ae.error(_.message);ae.success("Thanks for your review!"),a({...y,id:r==null?void 0:r.id})};return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:r?"Your review":"Leave a review"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Help other agents find a great coach."})]}),e.jsx(J4e,{value:i,size:28,onChange:l}),e.jsx(ye,{placeholder:"Title (optional)",value:o,onChange:y=>c(y.target.value)}),e.jsx(Ms,{rows:4,placeholder:"What was your experience like?",value:d,onChange:y=>u(y.target.value)}),e.jsx(B,{onClick:f,disabled:h,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:h?"Saving…":r?"Update review":"Submit review"})]})})}function Jts(){var h,p,f,y,_,v;const{user:s}=vs(),{data:t,isLoading:n,refetch:r}=Dts(),a=Kt(),i=t==null?void 0:t.id,{data:l=[]}=hmt(i),{data:o=[]}=mmt(i);if(N.useEffect(()=>{new URLSearchParams(window.location.search).get("subscribed")==="1"&&q.functions.invoke("coaching-verify-checkout").then(()=>{r(),a.invalidateQueries({queryKey:["my-coaching-assignment"]})})},[r,a]),n)return e.jsx(Cs,{title:"My Coach",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Cs,{title:"My Coach",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-8 text-center",children:[e.jsx(yd,{className:"h-12 w-12 mx-auto mb-4 text-muted-foreground"}),e.jsx("h2",{className:"text-2xl font-semibold mb-2",children:"You're not in a coaching program yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Browse LevelUp Certified Coaches to find a fit (coming soon)."})]})});const c=t,d=o.filter(j=>j.status!=="done"),u=o.length-d.length;return e.jsx(Cs,{title:"My Coach",children:e.jsxs("div",{className:"p-4 md:p-8 max-w-5xl mx-auto space-y-6",children:[e.jsx(fe,{className:"overflow-hidden",children:e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white p-8",children:[e.jsx("div",{className:"absolute -right-20 -top-20 h-64 w-64 rounded-full bg-white/10 blur-3xl"}),e.jsxs("div",{className:"relative flex flex-col md:flex-row items-start md:items-center gap-6",children:[e.jsxs(Jr,{className:"h-24 w-24 ring-4 ring-white/20",children:[e.jsx(ti,{src:((h=c.coachProfile)==null?void 0:h.avatar_url)||void 0}),e.jsx(ea,{className:"text-2xl bg-white/20 text-white",children:(((p=c.coachProfile)==null?void 0:p.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80 mb-1",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm uppercase tracking-wider",children:"Your Coach"})]}),e.jsx("h1",{className:"text-3xl font-bold",children:((f=c.coachProfile)==null?void 0:f.name)||"Your Coach"}),((y=c.coach)==null?void 0:y.headline)&&e.jsx("p",{className:"text-white/80 mt-1",children:c.coach.headline}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[((_=c.coach)==null?void 0:_.is_certified)&&e.jsx(Ue,{className:"bg-yellow-400/20 text-yellow-100 border-yellow-300/30",children:"LevelUp Certified"}),e.jsx(Ue,{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(jje,{icon:lu,label:"Open action items",value:d.length}),e.jsx(jje,{icon:Ac,label:"Completed",value:u}),e.jsx(jje,{icon:yr,label:"Sessions",value:l.length})]}),((v=c.coach)==null?void 0:v.id)&&e.jsx(Xts,{coachId:c.coach.id,assignmentId:i}),e.jsxs(Fr,{defaultValue:"actions",children:[e.jsxs(Rr,{className:"flex flex-wrap h-auto w-full justify-start",children:[e.jsxs(Zt,{value:"actions",children:[e.jsx(lu,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Zt,{value:"sessions",children:[e.jsx(yr,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Recaps"})]}),e.jsxs(Zt,{value:"goals",children:[e.jsx(Ac,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Goals"})]}),e.jsxs(Zt,{value:"kpis",children:[e.jsx(go,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"KPIs"})]}),e.jsxs(Zt,{value:"messages",children:[e.jsx(Ai,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Messages"})]}),e.jsxs(Zt,{value:"files",children:[e.jsx(pf,{className:"h-4 w-4 mr-1 md:mr-2"}),e.jsx("span",{className:"hidden sm:inline",children:"Files"})]})]}),e.jsx(is,{value:"actions",className:"space-y-2",children:o.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-center text-muted-foreground",children:"Your coach hasn't assigned any action items yet."})}):o.map(j=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-3 flex items-center gap-3",children:[e.jsx(hi,{checked:j.status==="done",onCheckedChange:async w=>{await q.from("coaching_action_items").update({status:w?"done":"open",completed_at:w?new Date().toISOString():null}).eq("id",j.id),a.invalidateQueries({queryKey:["coaching-action-items",i]})}}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:j.status==="done"?"line-through text-muted-foreground":"font-medium",children:j.title}),j.description&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j.description})]}),j.due_date&&e.jsx(Ue,{variant:"outline",children:Ss(new Date(j.due_date),"MMM d")}),e.jsx(Ue,{variant:"secondary",className:"capitalize",children:j.priority})]})},j.id))}),e.jsx(is,{value:"sessions",className:"space-y-3",children:l.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-center text-muted-foreground",children:"No sessions logged yet."})}):l.map(j=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"font-medium",children:Ss(new Date(j.scheduled_at),"PPp")}),e.jsx(Ue,{variant:"outline",className:"capitalize",children:j.status})]}),j.summary?e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.summary}):e.jsx("p",{className:"text-sm text-muted-foreground italic",children:"Recap coming soon."})]})},j.id))}),e.jsx(is,{value:"goals",children:e.jsx(_mt,{assignmentId:i,canEdit:!1})}),e.jsx(is,{value:"kpis",children:s&&e.jsx(bmt,{agentUserId:s.id})}),e.jsx(is,{value:"messages",children:e.jsx(pmt,{assignmentId:i})}),e.jsx(is,{value:"files",children:e.jsx(wmt,{assignmentId:i})})]})]})})}function jje({icon:s,label:t,value:n}){return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(s,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold leading-none",children:n}),e.jsx("div",{className:"text-xs text-muted-foreground mt-1",children:t})]})]})})}function ess(){const s=Kt(),[t,n]=N.useState(""),[r,a]=N.useState([]),[i,l]=N.useState(null),{data:o=[],isLoading:c}=dt({queryKey:["admin-coaches"],queryFn:async()=>{const{data:h,error:p}=await q.from("coaches").select("*").order("created_at",{ascending:!1});if(p)throw p;if(!(h!=null&&h.length))return[];const f=h.map(v=>v.user_id),{data:y}=await q.from("profiles").select("id, name, email, avatar_url").in("id",f),_=new Map((y||[]).map(v=>[v.id,v]));return h.map(v=>({...v,profile:_.get(v.user_id)}))}});N.useEffect(()=>{const h=t.trim();if(h.length<2){a([]);return}const p=setTimeout(async()=>{const{data:f}=await q.from("profiles").select("id, email, name, avatar_url").or(`email.ilike.%${h}%,name.ilike.%${h}%`).limit(10);a(f||[])},250);return()=>clearTimeout(p)},[t]);const d=async h=>{const{error:p}=await q.functions.invoke("manage-user-roles",{body:{userId:h.id,role:"coach",action:"add"}});if(p)return ae.error(p.message);const{error:f}=await q.from("coaches").insert({user_id:h.id});if(f&&!String(f.message).includes("duplicate"))return ae.error(f.message);ae.success(`${h.name||h.email} is now a coach`),n(""),a([]),s.invalidateQueries({queryKey:["admin-coaches"]})},u=async(h,p)=>{const{error:f}=await q.from("coaches").update({is_certified:p}).eq("id",h);if(f)return ae.error(f.message);ae.success(p?"Marked Certified":"Removed certification"),s.invalidateQueries({queryKey:["admin-coaches"]})};return e.jsxs(Cs,{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(yd,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"LevelUp Coaching"})]}),e.jsx(tss,{}),e.jsx(nss,{}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 space-y-3",children:[e.jsx(ye,{placeholder:"Search by user email or name…",value:t,onChange:h=>n(h.target.value)}),t.trim().length>=2&&e.jsx("div",{className:"border rounded-md divide-y max-h-72 overflow-auto",children:r.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No users found"}):r.map(h=>e.jsxs("div",{className:"flex items-center justify-between p-2 hover:bg-muted/40",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:h.name||h.email}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:h.email})]}),e.jsxs(B,{size:"sm",onClick:()=>d(h),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Make Coach"]})]},h.id))})]})}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold mb-3",children:"Coaches"}),c?e.jsx("div",{children:"Loading…"}):o.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-center text-muted-foreground",children:"No coaches yet. Search for a user above to promote them."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:o.map(h=>{var p,f,y;return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium",children:((p=h.profile)==null?void 0:p.name)||((f=h.profile)==null?void 0:f.email)||h.user_id}),e.jsx("div",{className:"text-xs text-muted-foreground",children:(y=h.profile)==null?void 0:y.email}),e.jsxs("div",{className:"flex gap-2 mt-2 flex-wrap",children:[h.is_certified&&e.jsxs(Ue,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Certified"]}),h.accepting_clients&&e.jsx(Ue,{variant:"outline",children:"Accepting clients"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>l(h.id),children:[e.jsx(Fo,{className:"h-4 w-4 mr-1"})," Assign"]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm pt-2 border-t",children:[e.jsx("span",{className:"text-muted-foreground",children:"LevelUp Certified"}),e.jsx(jn,{checked:h.is_certified,onCheckedChange:_=>u(h.id,_)})]})]})},h.id)})})]})]}),e.jsx(sss,{coachId:i,onClose:()=>l(null)})]})}function tss(){const[s,t]=N.useState("1500"),[n,r]=N.useState(!1),[a,i]=N.useState(!1);N.useEffect(()=>{(async()=>{const{data:c}=await q.from("settings").select("value").eq("key","coaching_platform_fee_bps").maybeSingle();c!=null&&c.value&&t(String(c.value)),i(!0)})()},[]);const l=async()=>{const c=parseInt(s,10);if(isNaN(c)||c<0||c>5e3)return ae.error("Enter a value between 0 and 5000 bps (0–50%)");r(!0);const{error:d}=await q.from("settings").upsert({key:"coaching_platform_fee_bps",value:String(c)});if(r(!1),d)return ae.error(d.message);ae.success("Platform fee updated")};if(!a)return null;const o=(parseInt(s,10)/100).toFixed(2);return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(QS,{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(ne,{children:"Fee (bps)"}),e.jsx(ye,{type:"number",value:s,onChange:c=>t(c.target.value),min:0,max:5e3}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["= ",o,"%"]})]}),e.jsx(B,{onClick:l,disabled:n,className:"bg-[#406E71] hover:bg-[#2a4c64] self-end",children:n?"Saving…":"Save"})]})]})})}function sss({coachId:s,onClose:t}){const[n,r]=N.useState(""),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=Kt();N.useEffect(()=>{if(!s){r(""),i([]);return}},[s]),N.useEffect(()=>{const u=n.trim();if(u.length<2){i([]);return}o(!0);const h=setTimeout(async()=>{const{data:p}=await q.from("profiles").select("id, name, email").or(`email.ilike.%${u}%,name.ilike.%${u}%`).limit(15);i(p||[]),o(!1)},250);return()=>clearTimeout(h)},[n]);const d=async u=>{const{error:h}=await q.from("coaching_assignments").insert({coach_id:s,agent_id:u,status:"active",source:"admin",pipeline_stage:"onboarding"});if(h)return ae.error(h.message);ae.success("Agent assigned"),c.invalidateQueries({queryKey:["coach-roster"]}),t()};return e.jsx(_s,{open:!!s,onOpenChange:u=>!u&&t(),children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Assign Agent"})}),e.jsx(ye,{placeholder:"Search agents by name or email…",value:n,onChange:u=>r(u.target.value),autoFocus:!0}),e.jsx("div",{className:"space-y-1 max-h-72 overflow-auto border rounded-md",children:n.trim().length<2?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Type at least 2 characters to search…"}):l?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"Searching…"}):a.length===0?e.jsx("div",{className:"p-3 text-sm text-muted-foreground",children:"No agents found"}):a.map(u=>e.jsxs("button",{onClick:()=>d(u.id),className:"w-full text-left p-2 hover:bg-muted",children:[e.jsx("div",{className:"font-medium",children:u.name||u.email}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.email})]},u.id))}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:t,children:"Close"})})]})})}function nss(){const s=Kt(),[t,n]=N.useState("pending"),[r,a]=N.useState(null),{data:i=[],isLoading:l}=dt({queryKey:["coach-applications",t],queryFn:async()=>{let u=q.from("coach_applications").select("*").order("created_at",{ascending:!1});t!=="all"&&(u=u.eq("status",t));const{data:h,error:p}=await u;if(p)throw p;return h||[]}}),{data:o=0}=dt({queryKey:["coach-applications-pending-count"],queryFn:async()=>{const{count:u}=await q.from("coach_applications").select("id",{count:"exact",head:!0}).eq("status","pending");return u||0}}),c=async(u,h)=>{const{error:p}=await q.from("coach_applications").update({status:h,reviewed_at:new Date().toISOString()}).eq("id",u);if(p)return ae.error(p.message);ae.success(`Marked ${h}`),s.invalidateQueries({queryKey:["coach-applications"]}),s.invalidateQueries({queryKey:["coach-applications-pending-count"]}),a(null)},d=u=>u==="approved"?e.jsxs(Ue,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),"Approved"]}):u==="rejected"?e.jsxs(Ue,{className:"bg-rose-500/15 text-rose-700 border-rose-300/40",children:[e.jsx($n,{className:"h-3 w-3 mr-1"}),"Rejected"]}):e.jsxs(Ue,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),"Pending"]});return e.jsxs(fe,{children:[e.jsxs(Ee,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(H2,{className:"h-5 w-5 text-primary"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Coach Applications"}),o>0&&e.jsxs(Ue,{className:"bg-yellow-500/15 text-yellow-700 border-yellow-300/40",children:[o," pending"]}),e.jsx("div",{className:"ml-auto flex gap-1 flex-wrap",children:["pending","approved","rejected","all"].map(u=>e.jsx(B,{size:"sm",variant:t===u?"default":"outline",onClick:()=>n(u),className:t===u?"bg-[#406E71] hover:bg-[#2a4c64]":"",children:u.charAt(0).toUpperCase()+u.slice(1)},u))})]}),l?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading…"}):i.length===0?e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center border rounded-md",children:["No applications ",t!=="all"?`with status "${t}"`:"yet","."]}):e.jsx("div",{className:"divide-y border rounded-md",children:i.map(u=>e.jsx("button",{onClick:()=>a(u),className:"w-full text-left p-3 hover:bg-muted/40 transition-colors",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium",children:u.full_name}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-3 mt-0.5",children:[e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Gs,{className:"h-3 w-3"}),u.email]}),u.brokerage&&e.jsxs("span",{children:["· ",u.brokerage]}),u.years_experience&&e.jsxs("span",{children:["· ",u.years_experience," yrs"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[d(u.status),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(u.created_at).toLocaleDateString()})]})]})},u.id))})]}),e.jsx(_s,{open:!!r,onOpenChange:u=>!u&&a(null),children:e.jsx(bs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:r&&e.jsxs(e.Fragment,{children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-3",children:[r.full_name,d(r.status)]})}),e.jsxs("div",{className:"space-y-4 text-sm",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(gI,{icon:Gs,label:"Email",value:r.email,link:`mailto:${r.email}`}),r.phone&&e.jsx(gI,{icon:Cr,label:"Phone",value:r.phone,link:`tel:${r.phone}`}),r.brokerage&&e.jsx(gI,{label:"Brokerage",value:r.brokerage}),r.years_experience&&e.jsx(gI,{label:"Years",value:r.years_experience}),r.website_url&&e.jsx(gI,{icon:tr,label:"Website",value:r.website_url,link:r.website_url}),r.linkedin_url&&e.jsx(gI,{icon:tr,label:"LinkedIn",value:r.linkedin_url,link:r.linkedin_url})]}),r.specialties&&e.jsx(Nje,{label:"Specialties",children:r.specialties}),e.jsx(Nje,{label:"Why they want to coach",children:r.why_coach}),r.results_story&&e.jsx(Nje,{label:"Results story",children:r.results_story}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-semibold uppercase text-muted-foreground",children:"Admin notes"}),e.jsx(Ms,{defaultValue:r.admin_notes||"",rows:3,onBlur:async u=>{const h=u.target.value;h!==(r.admin_notes||"")&&(await q.from("coach_applications").update({admin_notes:h}).eq("id",r.id),s.invalidateQueries({queryKey:["coach-applications"]}))},placeholder:"Internal notes (saved on blur)…"})]})]}),e.jsxs(Xn,{className:"gap-2 flex-wrap",children:[r.status!=="rejected"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"rejected"),className:"text-rose-600 border-rose-200 hover:bg-rose-50",children:[e.jsx($n,{className:"h-4 w-4 mr-1"})," Reject"]}),r.status!=="pending"&&e.jsxs(B,{variant:"outline",onClick:()=>c(r.id,"pending"),children:[e.jsx(pr,{className:"h-4 w-4 mr-1"})," Move to pending"]}),r.status!=="approved"&&e.jsxs(B,{onClick:()=>c(r.id,"approved"),className:"bg-emerald-600 hover:bg-emerald-700",children:[e.jsx(Lr,{className:"h-4 w-4 mr-1"})," Approve"]})]})]})})})]})}function gI({icon:s,label:t,value:n,link:r}){const a=e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[s&&e.jsx(s,{className:"h-3.5 w-3.5"}),n]});return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase text-muted-foreground tracking-wide",children:t}),e.jsx("div",{className:"text-sm",children:r?e.jsx("a",{href:r,target:"_blank",rel:"noreferrer",className:"text-[#406E71] hover:underline break-all",children:a}):a})]})}function Nje({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 rss(){const s=Ln(),{data:t}=rU(),n=Kt(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),{data:d,refetch:u}=dt({queryKey:["coach-stripe-status",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.functions.invoke("coach-stripe-status");return v}}),{data:h=[]}=dt({queryKey:["coach-packages",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:v}=await q.from("coaching_packages").select("*").eq("coach_id",t.id).order("sort_order");return v||[]}});N.useEffect(()=>{const v=new URLSearchParams(window.location.search);(v.get("onboarded")||v.get("refresh"))&&u()},[u]);const p=async()=>{var S,A;a(!0);const{data:v,error:j}=await q.functions.invoke("coach-stripe-connect");a(!1);let w=v==null?void 0:v.error;if(!w&&j)try{const E=await((A=(S=j==null?void 0:j.context)==null?void 0:S.json)==null?void 0:A.call(S));w=(E==null?void 0:E.error)||j.message}catch{w=j.message}if(w)return ae.error(w,{duration:1e4});v!=null&&v.url&&(window.location.href=v.url)},f=d||{},y=!!(t!=null&&t.use_platform_stripe),_=y||f.connected&&f.charges_enabled;return e.jsx(Cs,{title:"Coaching · Billing",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(qr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Billing & Packages"})]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(uf,{className:"h-5 w-5"})," Stripe Connect"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:y?"Your coaching sales are billed through the main LevelUp Stripe account.":"Payouts go directly to your bank. LevelUp takes a small platform fee from each charge."})]}),_?e.jsxs(Ue,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-300/40 flex items-center gap-1",children:[e.jsx(vr,{className:"h-3 w-3"})," ",y?"Using LevelUp billing":"Connected"]}):f.connected?e.jsxs(Ue,{variant:"secondary",className:"flex items-center gap-1",children:[e.jsx(Bi,{className:"h-3 w-3"})," Setup incomplete"]}):e.jsx(Ue,{variant:"outline",children:"Not connected"})]}),!y&&e.jsxs(B,{onClick:p,disabled:r,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[_?"Update Stripe details":f.connected?"Finish Stripe setup":"Connect Stripe",e.jsx(tr,{className:"h-4 w-4 ml-1"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages"}),e.jsxs(B,{size:"sm",onClick:()=>{c(null),l(!0)},disabled:!_,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," New Package"]})]}),!_&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect Stripe before creating packages."}),h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No packages yet."}):e.jsx("div",{className:"space-y-2",children:h.map(v=>e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium flex items-center gap-2",children:[v.name,v.is_active&&v.accepting_clients===!1&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full bg-amber-100 text-amber-800 font-semibold",children:"Booked full"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:["$",(v.price_cents/100).toFixed(0)," / ",v.billing_interval,!v.is_active&&" · Inactive"]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{c(v),l(!0)},children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:async()=>{confirm("Delete this package?")&&(await q.from("coaching_packages").delete().eq("id",v.id),n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]}))},children:e.jsx(_n,{className:"h-4 w-4"})})]},v.id))})]})}),e.jsx(ass,{open:i,onOpenChange:l,coachId:t==null?void 0:t.id,pkg:o,onSaved:()=>n.invalidateQueries({queryKey:["coach-packages",t==null?void 0:t.id]})})]})})}function ass({open:s,onOpenChange:t,coachId:n,pkg:r,onSaved:a}){const[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState("month"),[f,y]=N.useState(!0),[_,v]=N.useState(!0),[j,w]=N.useState(!1);N.useEffect(()=>{s&&(l((r==null?void 0:r.name)||""),c((r==null?void 0:r.description)||""),u(r?(r.price_cents/100).toString():""),p((r==null?void 0:r.billing_interval)||"month"),y((r==null?void 0:r.is_active)??!0),v((r==null?void 0:r.accepting_clients)??!0))},[s,r]);const S=async()=>{if(!i.trim()||!d)return ae.error("Name and price required");w(!0);const A={coach_id:n,name:i,description:o||null,price_cents:Math.round(Number(d)*100),billing_interval:h,is_active:f,accepting_clients:_},{error:E}=r!=null&&r.id?await q.from("coaching_packages").update(A).eq("id",r.id):await q.from("coaching_packages").insert(A);if(w(!1),E)return ae.error(E.message);ae.success("Saved"),a==null||a(),t(!1)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:r!=null&&r.id?"Edit Package":"New Package"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ye,{placeholder:"Name (e.g. Accelerator)",value:i,onChange:A=>l(A.target.value)}),e.jsx(Ms,{rows:3,placeholder:"What's included",value:o,onChange:A=>c(A.target.value)}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(ye,{type:"number",value:d,onChange:A=>u(A.target.value)})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-xs text-muted-foreground",children:"Interval"}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"month",children:"Monthly"}),e.jsx(Ze,{value:"year",children:"Yearly"}),e.jsx(Ze,{value:"one_time",children:"One-time"})]})]})]})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",checked:f,onChange:A=>y(A.target.checked)}),"Active (visible to agents)"]}),e.jsxs("label",{className:"flex items-start gap-2 text-sm",children:[e.jsx("input",{type:"checkbox",className:"mt-0.5",checked:_,onChange:A=>v(A.target.checked)}),e.jsxs("span",{children:[e.jsx("span",{className:"font-medium",children:"Accepting new clients"}),e.jsx("span",{className:"block text-xs text-muted-foreground",children:"Uncheck if you're booked full — visitors will still see the package but can't sign up."})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:j,children:r!=null&&r.id?"Save":"Create"})]})]})})}function vUe({kind:s,value:t,onChange:n}){const r=N.useRef(null),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null),h=N.useRef(null),p=N.useRef(null),f=N.useRef([]),[y,_]=N.useState(!1),v=s==="photo"?"image/*":"video/*",j=s==="photo"?10*1024*1024:200*1024*1024,w=async(I,F)=>{var ee;const{data:z}=await q.auth.getUser(),H=(ee=z.user)==null?void 0:ee.id;if(!H)return ae.error("Not signed in");if(I.size>j)return ae.error(`File too large. Max ${s==="photo"?"10MB":"200MB"}.`);i(!0);const Z=`${H}/${s}-${Date.now()}.${F}`,{error:Y}=await q.storage.from("coach-media").upload(Z,I,{upsert:!0,contentType:I.type||(s==="photo"?"image/jpeg":"video/webm")});if(Y)return i(!1),ae.error(Y.message);const{data:W}=await q.storage.from("coach-media").createSignedUrl(Z,60*60*24*365*10);i(!1),W!=null&&W.signedUrl&&(n(W.signedUrl),ae.success("Uploaded"),d(null))},S=async I=>{const F=I.name.split(".").pop()||(s==="photo"?"jpg":"webm");await w(I,F)},A=async()=>{try{const I=await navigator.mediaDevices.getUserMedia({video:!0,audio:!0});h.current=I,_(!0),setTimeout(()=>{u.current&&(u.current.srcObject=I,u.current.play())},50);const F=new MediaRecorder(I,{mimeType:"video/webm"});f.current=[],F.ondataavailable=z=>z.data.size>0&&f.current.push(z.data),F.onstop=()=>{const z=new Blob(f.current,{type:"video/webm"});d(z),I.getTracks().forEach(H=>H.stop())},p.current=F,F.start(),o(!0)}catch(I){ae.error(I.message||"Could not access camera")}},E=()=>{var I;(I=p.current)==null||I.stop(),o(!1)},O=()=>{var I;(I=h.current)==null||I.getTracks().forEach(F=>F.stop()),_(!1),o(!1),d(null)},D=async()=>{c&&(await w(c,"webm"),O())};return N.useEffect(()=>()=>{var I;return(I=h.current)==null?void 0:I.getTracks().forEach(F=>F.stop())},[]),e.jsxs("div",{className:"space-y-2",children:[t&&e.jsx("div",{className:"rounded-lg overflow-hidden border bg-muted/30",children:s==="photo"?e.jsx("img",{src:t,alt:"Profile",className:"w-32 h-32 object-cover"}):e.jsx("video",{src:t,controls:!0,className:"w-full max-h-64"})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx("input",{ref:r,type:"file",accept:v,className:"hidden",onChange:I=>{var z;const F=(z=I.target.files)==null?void 0:z[0];F&&S(F),I.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:a,onClick:()=>{var I;return(I=r.current)==null?void 0:I.click()},children:[a?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(_a,{className:"h-4 w-4 mr-1"}),s==="photo"?"Upload photo":"Upload video"]}),s==="video"&&e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:A,disabled:a||y,children:[e.jsx(Jf,{className:"h-4 w-4 mr-1"})," Record intro"]}),t&&e.jsxs(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>n(""),children:[e.jsx(_n,{className:"h-4 w-4 mr-1"})," Remove"]})]}),y&&e.jsxs("div",{className:"rounded-lg border p-3 space-y-3 bg-background",children:[c?e.jsx("video",{src:URL.createObjectURL(c),controls:!0,className:"w-full max-h-64 rounded bg-black"}):e.jsx("video",{ref:u,muted:!0,playsInline:!0,className:"w-full max-h-64 rounded bg-black"}),e.jsxs("div",{className:"flex gap-2",children:[!c&&l&&e.jsxs(B,{type:"button",size:"sm",onClick:E,className:"bg-red-600 hover:bg-red-700",children:[e.jsx(ay,{className:"h-4 w-4 mr-1"})," Stop"]}),!c&&!l&&e.jsxs(B,{type:"button",size:"sm",onClick:()=>{var I;return(I=p.current)==null?void 0:I.start()},children:[e.jsx(fr,{className:"h-4 w-4 mr-1"})," Start"]}),c&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{type:"button",size:"sm",onClick:D,disabled:a,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[a?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(_a,{className:"h-4 w-4 mr-1"}),"Use this recording"]}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:()=>{d(null),A()},children:"Re-record"})]}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:O,children:"Cancel"})]})]})]})}function iss(){const s=Ln(),{data:t,isLoading:n}=rU(),r=Kt(),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[y,_]=N.useState(!1),[v,j]=N.useState([]),[w,S]=N.useState(""),[A,E]=N.useState(!1);N.useEffect(()=>{if(!t)return;const z=t;i(z.slug||""),o(z.headline||""),d(z.bio||""),h(z.photo_url||""),f(z.intro_video_url||""),_(!!z.accepting_clients),j(z.specialties||[])},[t]);const O=async()=>{if(!t)return;E(!0);const{error:z}=await q.from("coaches").update({slug:a.trim()||null,headline:l||null,bio:c||null,photo_url:u||null,intro_video_url:p||null,accepting_clients:y,specialties:v}).eq("id",t.id);if(E(!1),z)return ae.error(z.message);ae.success("Profile saved"),r.invalidateQueries({queryKey:["my-coach-profile"]})},D=()=>{const z=w.trim();if(z){if(v.includes(z))return S("");j([...v,z]),S("")}};if(n)return e.jsx(Cs,{title:"Coach Settings",children:e.jsx("div",{className:"p-8",children:"Loading…"})});if(!t)return e.jsx(Cs,{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 I=t,F=I.slug?`${window.location.origin}/coaches/${I.slug}`:null;return e.jsx(Cs,{title:"Coach Settings",children:e.jsxs("div",{className:"max-w-3xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/coaching"),children:e.jsx(qr,{className:"h-5 w-5"})}),e.jsx("h1",{className:"text-2xl font-bold",children:"Coach Profile"})]}),e.jsxs("div",{className:"flex gap-2",children:[F&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(F,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4 mr-1"})," View public"]}),e.jsxs(B,{onClick:O,disabled:A,className:"bg-[#406E71] hover:bg-[#2a4c64]",children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," ",A?"Saving…":"Save"]})]})]}),I.is_certified&&e.jsxs("div",{className:"rounded-lg border border-yellow-300/50 bg-yellow-50 dark:bg-yellow-950/20 px-4 py-3 text-sm",children:["✨ ",e.jsx("strong",{children:"LevelUp Certified"})," — Your profile displays a verified badge."]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Accepting new clients"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When off, you're hidden from the public directory."})]}),e.jsx(jn,{checked:y,onCheckedChange:_})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Public URL slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:"/coaches/"}),e.jsx(ye,{value:a,onChange:z=>i(z.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"")),placeholder:"your-name"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Headline"}),e.jsx(ye,{value:l,onChange:z=>o(z.target.value),placeholder:"e.g. Helping new agents close their first 10 deals",maxLength:140})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Bio"}),e.jsx(Ms,{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(ne,{children:"Profile photo"}),e.jsx(vUe,{kind:"photo",value:u,onChange:h})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Intro video"}),e.jsx(vUe,{kind:"video",value:p,onChange:f})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-2",children:v.map(z=>e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[z,e.jsx("button",{onClick:()=>j(v.filter(H=>H!==z)),children:e.jsx($n,{className:"h-3 w-3"})})]},z))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:w,onChange:z=>S(z.target.value),placeholder:"Add a specialty…",onKeyDown:z=>{z.key==="Enter"&&(z.preventDefault(),D())}}),e.jsx(B,{type:"button",variant:"outline",onClick:D,children:e.jsx(Is,{className:"h-4 w-4"})})]})]})]})}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Packages & Stripe"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage your monetized packages on the Billing page."})]}),e.jsx(B,{variant:"outline",onClick:()=>s("/coaching/billing"),children:"Go to Billing"})]})})}),e.jsx(oss,{coachId:I.id})]})})}function oss({coachId:s}){const[t,n]=N.useState("");Kt();const{data:r=[],refetch:a}=dt({queryKey:["coach-invites",s],queryFn:async()=>{const{data:c}=await q.from("coaching_invites").select("*").eq("coach_id",s).order("created_at",{ascending:!1});return c||[]}}),i=async()=>{const c=t.trim().toLowerCase();if(!c)return ae.error("Email required");const{error:d}=await q.from("coaching_invites").insert({coach_id:s,email:c});if(d)return ae.error(d.message);n(""),ae.success("Invite created"),a()},l=c=>{const d=`${window.location.origin}/auth?coach_invite=${c}`;navigator.clipboard.writeText(d),ae.success("Link copied")},o=async c=>{confirm("Revoke this invite?")&&(await q.from("coaching_invites").delete().eq("id",c),a())};return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(Yo,{className:"h-5 w-5"})," Invite agents"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a magic link to onboard agents directly."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"agent@email.com",value:t,onChange:c=>n(c.target.value),onKeyDown:c=>c.key==="Enter"&&i()}),e.jsxs(B,{onClick:i,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Create"]})]}),e.jsxs("div",{className:"space-y-2",children:[r.map(c=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:c.email}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[c.status," · expires ",new Date(c.expires_at).toLocaleDateString()]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>l(c.token),children:e.jsx(Zr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>o(c.id),children:e.jsx(_n,{className:"h-4 w-4"})})]},c.id)),r.length===0&&e.jsx("div",{className:"text-sm text-muted-foreground text-center py-4",children:"No invites yet."})]})]})})}const rH=[{value:"pending",label:"Pending",tone:"bg-amber-100 text-amber-800"},{value:"invited",label:"Invited",tone:"bg-blue-100 text-blue-800"},{value:"converted",label:"Converted",tone:"bg-emerald-100 text-emerald-800"},{value:"declined",label:"Declined",tone:"bg-rose-100 text-rose-800"},{value:"archived",label:"Archived",tone:"bg-slate-100 text-slate-700"}];function lss(){const s=Ln(),t=Kt(),{data:n,isLoading:r}=rU(),[a,i]=N.useState("pending"),[l,o]=N.useState(""),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[y,_]=N.useState(!1),[v,j]=N.useState(""),{data:w=[],isLoading:S}=dt({queryKey:["coaching-waitlist",n==null?void 0:n.id],enabled:!!(n!=null&&n.id),queryFn:async()=>{const{data:z,error:H}=await q.from("coaching_waitlist").select("*").eq("coach_id",n.id).order("created_at",{ascending:!1});if(H)throw H;return z||[]}}),A=N.useMemo(()=>w.filter(z=>{if(a!=="all"&&z.status!==a)return!1;if(l){const H=l.toLowerCase();return(z.name||"").toLowerCase().includes(H)||(z.email||"").toLowerCase().includes(H)||(z.brokerage||"").toLowerCase().includes(H)}return!0}),[w,a,l]),E=N.useMemo(()=>{const z={all:w.length};for(const H of rH)z[H.value]=0;for(const H of w)z[H.status]=(z[H.status]||0)+1;return z},[w]),O=async(z,H)=>{const{error:Z}=await q.from("coaching_waitlist").update(H).eq("id",z);if(Z)return ae.error(Z.message);t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),(c==null?void 0:c.id)===z&&d(Y=>({...Y,...H}))},D=async z=>{if(!confirm("Remove this person from the waitlist?"))return;const{error:H}=await q.from("coaching_waitlist").delete().eq("id",z);if(H)return ae.error(H.message);ae.success("Removed"),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]}),d(null)},I=async()=>{if(!c)return;const{data:z,error:H}=await q.functions.invoke("coaching-waitlist-invite",{body:{waitlistId:c.id,message:p}});if(H||z!=null&&z.error)return ae.error((z==null?void 0:z.error)||(H==null?void 0:H.message)||"Could not send invite");ae.success(`Invite sent to ${c.name}`),h(!1),f(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})},F=async()=>{if(!n)return;const{data:z,error:H}=await q.functions.invoke("coaching-waitlist-invite",{body:{coachId:n.id,notifyAll:!0,message:v}});if(H||z!=null&&z.error)return ae.error((z==null?void 0:z.error)||(H==null?void 0:H.message)||"Could not notify");ae.success(`Notified ${(z==null?void 0:z.count)||0} agents`),_(!1),j(""),t.invalidateQueries({queryKey:["coaching-waitlist",n==null?void 0:n.id]})};return r?e.jsx(Cs,{title:"Waitlist",children:e.jsx("div",{className:"p-8",children:"Loading…"})}):n?e.jsxs(Cs,{title:"Coaching Waitlist",children:[e.jsxs("div",{className:"p-4 md:p-8 max-w-7xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"mb-2 -ml-2",onClick:()=>s("/coaching"),children:[e.jsx(qr,{className:"h-4 w-4 mr-1"})," Back to Coaching"]}),e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(cb,{className:"h-6 w-6 text-[#406E71]"}),"Waitlist"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Agents waiting for a spot to open up with you."})]}),e.jsxs(B,{variant:"outline",onClick:()=>_(!0),disabled:!E.pending,title:E.pending?"":"No pending applicants",children:[e.jsx(sL,{className:"h-4 w-4 mr-2"}),"Notify all pending (",E.pending||0,")"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs("button",{onClick:()=>i("all"),className:`px-3 py-1.5 rounded-full text-sm border ${a==="all"?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:["All (",E.all,")"]}),rH.map(z=>e.jsxs("button",{onClick:()=>i(z.value),className:`px-3 py-1.5 rounded-full text-sm border ${a===z.value?"bg-[#406E71] text-white border-[#406E71]":"bg-white hover:bg-muted"}`,children:[z.label," (",E[z.value]||0,")"]},z.value))]}),e.jsx(ye,{placeholder:"Search by name, email, brokerage…",value:l,onChange:z=>o(z.target.value),className:"max-w-md"}),S?e.jsx("div",{className:"text-muted-foreground",children:"Loading…"}):A.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-10 text-center text-muted-foreground",children:"No entries here yet."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:A.map(z=>{const H=rH.find(Z=>Z.value===z.status);return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>d(z),children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold truncate",children:z.name}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z.email}),z.brokerage&&e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:z.brokerage})]}),e.jsx(Ue,{className:(H==null?void 0:H.tone)||"",children:(H==null?void 0:H.label)||z.status})]}),e.jsxs("div",{className:"flex items-center justify-between mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Joined ",Uo(new Date(z.created_at),{addSuffix:!0})]}),z.preferred_package&&e.jsxs("span",{className:"truncate ml-2",children:["→ ",z.preferred_package]})]})]})},z.id)})})]}),e.jsx(_s,{open:!!c,onOpenChange:z=>!z&&d(null),children:e.jsx(bs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:c&&e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:c.name}),e.jsxs(Jn,{children:["Joined ",Uo(new Date(c.created_at),{addSuffix:!0})]})]}),e.jsxs("div",{className:"space-y-3 text-sm",children:[e.jsx(rF,{label:"Email",value:c.email}),e.jsx(rF,{label:"Phone",value:c.phone}),e.jsx(rF,{label:"Brokerage",value:c.brokerage}),e.jsx(rF,{label:"Years",value:c.years_in_business}),e.jsx(rF,{label:"Preferred package",value:c.preferred_package}),c.biggest_challenge&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Biggest challenge"}),e.jsx("p",{className:"whitespace-pre-wrap",children:c.biggest_challenge})]}),c.message&&e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Message"}),e.jsx("p",{className:"whitespace-pre-wrap",children:c.message})]}),c.invited_at&&e.jsxs("div",{className:"text-xs text-blue-700",children:["Invite sent ",Uo(new Date(c.invited_at),{addSuffix:!0})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Status"}),e.jsxs(us,{value:c.status,onValueChange:z=>O(c.id,{status:z}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:rH.map(z=>e.jsx(Ze,{value:z.value,children:z.label},z.value))})]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Private notes"}),e.jsx(Ms,{rows:3,defaultValue:c.coach_notes||"",onBlur:z=>{z.target.value!==(c.coach_notes||"")&&O(c.id,{coach_notes:z.target.value})}})]})]}),e.jsxs(Xn,{className:"flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"text-destructive",onClick:()=>D(c.id),children:[e.jsx(_n,{className:"h-4 w-4 mr-1"})," Remove"]}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:`mailto:${c.email}`,children:[e.jsx(Gs,{className:"h-4 w-4 mr-1"})," Email directly"]})}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>{f(""),h(!0)},children:[e.jsx(lr,{className:"h-4 w-4 mr-1"})," Invite to subscribe"]})]})]})})}),e.jsx(_s,{open:u,onOpenChange:h,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Invite to subscribe"}),e.jsxs(Jn,{children:["We'll email ",c==null?void 0:c.name," a link to your coaching page so they can pick a package."]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Personal note (optional)"}),e.jsx(Ms,{rows:4,placeholder:"Hey! A spot just opened up and I'd love to work with you…",value:p,onChange:z=>f(z.target.value)})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:I,children:[e.jsx(lr,{className:"h-4 w-4 mr-1"})," Send invite"]})]})]})}),e.jsx(_s,{open:y,onOpenChange:_,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Notify all pending applicants"}),e.jsx(Jn,{children:"Send everyone with status “Pending” an email letting them know spots are opening up. They'll each be marked “Invited”."})]}),e.jsx(Ms,{rows:4,placeholder:"Good news — I just opened up new coaching spots…",value:v,onChange:z=>j(z.target.value)}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsxs(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:F,children:[e.jsx(sL,{className:"h-4 w-4 mr-1"})," Send to ",E.pending||0," agents"]})]})]})})]}):e.jsx(Cs,{title:"Waitlist",children:e.jsx("div",{className:"p-8 text-center text-muted-foreground",children:"You need a coach profile to view this page."})})}function rF({label:s,value:t}){return t?e.jsxs("div",{className:"flex justify-between gap-3 border-b pb-1",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:s}),e.jsx("span",{className:"text-right",children:t})]}):null}function css(){const{data:s=[],isLoading:t}=dt({queryKey:["coaches-directory"],queryFn:async()=>{const{data:n,error:r}=await q.from("coaches").select("id, slug, headline, bio, specialties, photo_url, is_certified, accepting_clients, user_id").not("slug","is",null);if(r)throw r;const a=(n||[]).map(o=>o.user_id);if(a.length===0)return[];const{data:i}=await q.from("profiles").select("id, name, avatar_url").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return(n||[]).map(o=>({...o,profile:l.get(o.user_id)}))}});return e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 py-20 md:py-28 text-center",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"}),"LevelUp Certified Coaches"]}),e.jsxs("h1",{className:"text-5xl md:text-7xl font-bold tracking-tight leading-[1.05]",children:["Coaching that ",e.jsx("span",{className:"bg-gradient-to-r from-yellow-300 to-yellow-100 bg-clip-text text-transparent",children:"moves the needle."})]}),e.jsx("p",{className:"text-white/75 mt-6 max-w-2xl mx-auto text-lg leading-relaxed",children:"Hand-picked real-estate coaches ready to help you hit your next breakthrough — from lead gen to listings to luxury."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-6 mt-10 text-sm text-white/70",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-4 w-4 text-yellow-300"})," Vetted by LevelUp"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-4 w-4 text-yellow-300"})," Top-producer experience"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oa,{className:"h-4 w-4 text-yellow-300"})," Real, measurable results"]})]})]}),e.jsx("svg",{className:"block w-full text-white",viewBox:"0 0 1440 60",preserveAspectRatio:"none","aria-hidden":!0,children:e.jsx("path",{fill:"currentColor",d:"M0,40 C360,80 1080,0 1440,40 L1440,60 L0,60 Z"})})]}),e.jsxs("section",{className:"max-w-6xl mx-auto px-4 py-16 md:py-20",children:[t?e.jsx("div",{className:"text-center text-muted-foreground",children:"Loading coaches…"}):s.length===0?e.jsx("div",{className:"text-center text-muted-foreground",children:"No coaches available yet. Check back soon."}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:s.map(n=>{var i,l;const r=((i=n.profile)==null?void 0:i.name)||"Coach",a=n.photo_url||((l=n.profile)==null?void 0:l.avatar_url);return e.jsx(In,{to:`/coaches/${n.slug||n.id}`,className:"group",children:e.jsx("article",{className:"relative h-full rounded-2xl bg-[#1c3447] overflow-hidden transition-all duration-300 hover:-translate-y-1 hover:shadow-[0_24px_60px_-20px_rgba(42,76,100,0.5)]",children:e.jsxs("div",{className:"relative aspect-[3/4] w-full overflow-hidden",children:[a?e.jsx("img",{src:a,alt:r,className:"absolute inset-0 h-full w-full object-cover object-top group-hover:scale-105 transition-transform duration-700"}):e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white text-6xl font-bold",children:r.charAt(0)}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0d1f2d] via-[#0d1f2d]/70 to-transparent"}),e.jsxs("div",{className:"absolute top-3 left-3 right-3 flex items-start justify-between gap-2",children:[n.is_certified?e.jsxs("div",{className:"inline-flex items-center gap-1 px-2.5 py-1 rounded-full bg-gradient-to-r from-yellow-400 to-yellow-300 text-[#2a4c64] text-[11px] font-semibold shadow-md",children:[e.jsx(un,{className:"h-3 w-3"})," Certified"]}):e.jsx("span",{}),e.jsxs("div",{className:`inline-flex items-center gap-1 px-2.5 py-1 rounded-full text-[11px] font-medium backdrop-blur-md ${n.accepting_clients?"bg-emerald-500/90 text-white":"bg-white/85 text-[#2a4c64]"}`,children:[e.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${n.accepting_clients?"bg-white":"bg-amber-500"}`}),n.accepting_clients?"Accepting":"Waitlist"]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-5 text-white",children:[e.jsx("h3",{className:"text-xl font-bold leading-tight drop-shadow-sm",children:r}),n.headline&&e.jsx("p",{className:"text-sm text-yellow-200/90 font-medium mt-1 line-clamp-1",children:n.headline}),n.bio&&e.jsx("p",{className:"text-[13px] text-white/80 mt-2 line-clamp-2 leading-relaxed",children:n.bio}),n.specialties&&n.specialties.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-3",children:n.specialties.slice(0,2).map(o=>e.jsx("span",{className:"text-[10px] px-2 py-0.5 rounded-full bg-white/15 backdrop-blur-sm text-white border border-white/20",children:o},o))}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-3 border-t border-white/15",children:[e.jsx("span",{className:"text-sm font-semibold text-white",children:"View profile"}),e.jsx("span",{className:"inline-flex items-center justify-center h-8 w-8 rounded-full bg-white/15 backdrop-blur-sm text-white group-hover:bg-yellow-300 group-hover:text-[#1c3447] transition-colors",children:e.jsx(Oa,{className:"h-4 w-4"})})]})]})]})})},n.id)})}),e.jsxs("div",{className:"mt-20 rounded-3xl bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white p-10 md:p-14 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-[0.06]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"18px 18px"}}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-yellow-300/15 blur-3xl"}),e.jsxs("div",{className:"relative md:flex items-center gap-10",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 border border-white/15 text-[11px] uppercase tracking-[0.18em] font-semibold mb-5",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"})," Coach Applications Open"]}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold leading-tight",children:["Are you the kind of agent ",e.jsx("span",{className:"text-yellow-300",children:"other agents need?"})]}),e.jsx("p",{className:"text-white/80 mt-4 max-w-xl leading-relaxed",children:"LevelUp Coaches are the top 1% — top producers, proven mentors, and category leaders making a measurable difference in agents' businesses. If that's you, we want to meet you."}),e.jsxs("div",{className:"mt-6 flex flex-wrap gap-3 text-sm text-white/70",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(vr,{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(vr,{className:"h-4 w-4 text-yellow-300"})," Recurring revenue"]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(vr,{className:"h-4 w-4 text-yellow-300"})," Certified status"]})]})]}),e.jsxs("div",{className:"mt-8 md:mt-0",children:[e.jsxs(In,{to:"/coaches/apply",className:"inline-flex items-center gap-2 bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-bold px-7 py-4 rounded-xl shadow-lg shadow-yellow-300/20 transition-all hover:-translate-y-0.5",children:["Apply to coach ",e.jsx(Oa,{className:"h-5 w-5"})]}),e.jsx("p",{className:"text-xs text-white/60 mt-3 text-center md:text-left",children:"By application only."})]})]})]})]})]})}const dss=Gw({name:fo().trim().min(1,"Name required").max(120),email:fo().trim().email("Invalid email").max(255),phone:fo().trim().max(40).optional().or(bp("")),brokerage:fo().trim().max(160).optional().or(bp("")),years_in_business:fo().max(40).optional().or(bp("")),biggest_challenge:fo().trim().max(1e3).optional().or(bp("")),preferred_package:fo().max(120).optional().or(bp("")),message:fo().trim().max(1500).optional().or(bp(""))});function uss({open:s,onOpenChange:t,coachId:n,coachName:r,packages:a=[]}){const{user:i}=vs(),[l,o]=N.useState(!1),[c,d]=N.useState({name:"",email:(i==null?void 0:i.email)||"",phone:"",brokerage:"",years_in_business:"",biggest_challenge:"",preferred_package:"",message:""}),u=(p,f)=>d(y=>({...y,[p]:f})),h=async()=>{var y;const p=dss.safeParse(c);if(!p.success){ae.error(((y=p.error.issues[0])==null?void 0:y.message)||"Please check your entries");return}o(!0);const{error:f}=await q.from("coaching_waitlist").insert({coach_id:n,agent_user_id:(i==null?void 0:i.id)||null,name:c.name.trim(),email:c.email.trim().toLowerCase(),phone:c.phone||null,brokerage:c.brokerage||null,years_in_business:c.years_in_business||null,biggest_challenge:c.biggest_challenge||null,preferred_package:c.preferred_package||null,message:c.message||null,status:"pending"});if(o(!1),f){ae.error(f.message||"Could not join waitlist");return}ae.success(`You're on the waitlist${r?` for ${r}`:""}. We'll be in touch when a spot opens.`),t(!1),d({...c,biggest_challenge:"",message:""})};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{children:["Join the waitlist",r?` — ${r}`:""]}),e.jsx(Jn,{children:"Tell us a bit about you. The coach will reach out as soon as a spot opens."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Name *"}),e.jsx(ye,{value:c.name,onChange:p=>u("name",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Email *"}),e.jsx(ye,{type:"email",value:c.email,onChange:p=>u("email",p.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Phone"}),e.jsx(ye,{value:c.phone,onChange:p=>u("phone",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Brokerage"}),e.jsx(ye,{value:c.brokerage,onChange:p=>u("brokerage",p.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Years in business"}),e.jsxs(us,{value:c.years_in_business,onValueChange:p=>u("years_in_business",p),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select…"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"< 1 year",children:"Less than 1 year"}),e.jsx(Ze,{value:"1-3 years",children:"1-3 years"}),e.jsx(Ze,{value:"4-7 years",children:"4-7 years"}),e.jsx(Ze,{value:"8-15 years",children:"8-15 years"}),e.jsx(Ze,{value:"15+ years",children:"15+ years"})]})]})]}),a.length>0&&e.jsxs("div",{children:[e.jsx(ne,{children:"Preferred package"}),e.jsxs(us,{value:c.preferred_package,onValueChange:p=>u("preferred_package",p),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Any"})}),e.jsx(cs,{children:a.map(p=>e.jsx(Ze,{value:p.name,children:p.name},p.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Biggest challenge right now"}),e.jsx(Ms,{rows:2,value:c.biggest_challenge,onChange:p=>u("biggest_challenge",p.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Anything else?"}),e.jsx(Ms,{rows:2,value:c.message,onChange:p=>u("message",p.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:l,children:"Cancel"}),e.jsx(B,{className:"bg-[#406E71] hover:bg-[#2a4c64]",onClick:h,disabled:l,children:l?"Submitting…":"Join Waitlist"})]})]})})}function hss(){var _;const{slug:s}=bi(),t=Ln(),{user:n}=vs(),[r,a]=N.useState(null),[i,l]=N.useState(!1),{data:o,isLoading:c}=dt({queryKey:["coach-public",s],enabled:!!s,queryFn:async()=>{const v=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s||""),j=q.from("coaches").select("*"),{data:w}=v?await j.eq("id",s).maybeSingle():await j.eq("slug",s).maybeSingle();if(!w)return null;const[{data:S},{data:A}]=await Promise.all([q.from("profiles").select("id, name, avatar_url").eq("id",w.user_id).maybeSingle(),q.from("coaching_packages").select("*").eq("coach_id",w.id).eq("is_active",!0).order("sort_order")]);return{coach:w,profile:S,packages:A||[]}}}),d=async v=>{if(!n){ae.error("Please sign in to subscribe"),t(`/auth?redirect=/coaches/${s}`);return}a(v);const{data:j,error:w}=await q.functions.invoke("create-coaching-checkout",{body:{packageId:v}});if(a(null),w||j!=null&&j.error){ae.error((j==null?void 0:j.error)||(w==null?void 0:w.message)||"Checkout failed");return}j!=null&&j.url&&(window.location.href=j.url)};if(c)return e.jsx("div",{className:"p-12 text-center",children:"Loading…"});if(!(o!=null&&o.coach))return e.jsx("div",{className:"p-12 text-center",children:"Coach not found."});const{coach:u,profile:h,packages:p}=o,f=u,y=(v,j)=>{const w=(v/100).toLocaleString("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0});return j==="one_time"?w:`${w} / ${j}`};return e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("div",{className:"bg-gradient-to-br from-[#2a4c64] to-[#406E71] text-white",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 md:py-20",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-white/80 hover:text-white hover:bg-white/10 mb-6",onClick:()=>t("/coaches"),children:[e.jsx(qr,{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(Jr,{className:"h-28 w-28 ring-4 ring-white/20",children:[e.jsx(ti,{src:f.photo_url||(h==null?void 0:h.avatar_url)}),e.jsx(ea,{className:"text-3xl bg-white/20",children:((h==null?void 0:h.name)||"C").charAt(0)})]}),e.jsxs("div",{className:"flex-1",children:[f.is_certified&&e.jsxs("div",{className:"inline-flex items-center gap-1 bg-yellow-400/20 border border-yellow-300/30 text-yellow-100 px-2 py-1 rounded-full text-xs mb-2",children:[e.jsx(un,{className:"h-3 w-3"})," LevelUp Certified"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:(h==null?void 0:h.name)||"Coach"}),f.headline&&e.jsx("p",{className:"text-white/80 text-lg mt-2",children:f.headline}),((_=f.specialties)==null?void 0:_.length)>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-4",children:f.specialties.map(v=>e.jsx(Ue,{className:"bg-white/15 text-white border-white/20",children:v},v))})]})]})]})}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-12 grid grid-cols-1 md:grid-cols-3 gap-8",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[f.intro_video_url&&e.jsx("div",{className:"aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("video",{src:f.intro_video_url,controls:!0,className:"w-full h-full"})}),f.bio&&e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-3",children:"About"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap leading-relaxed",children:f.bio})]}),e.jsx(Qts,{coachId:f.id})]}),e.jsxs("div",{className:"space-y-4 md:sticky md:top-6 md:self-start",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Choose a plan"}),p.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 text-sm text-muted-foreground text-center",children:"No packages available yet."})}):p.map(v=>{const j=v.accepting_clients===!1;return e.jsx(fe,{className:`border-2 transition-colors ${j?"border-amber-200 bg-amber-50/30":"hover:border-[#406E71]"}`,children:e.jsxs(Ee,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("h3",{className:"font-semibold text-lg",children:v.name}),j&&e.jsx("span",{className:"text-[10px] uppercase tracking-wider font-bold px-2 py-1 rounded-full bg-amber-500 text-white shrink-0",children:"Booked Full"})]}),v.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:v.description}),e.jsx("div",{className:"text-2xl font-bold mt-3",children:y(v.price_cents,v.billing_interval)}),j?e.jsxs("div",{className:"mt-4 space-y-2",children:[e.jsx("div",{className:"rounded-md bg-amber-100 border border-amber-200 text-amber-900 px-3 py-2.5 text-sm text-center",children:"Currently not accepting new clients."}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>l(!0),children:[e.jsx(cb,{className:"h-4 w-4 mr-1"})," Join Waitlist"]})]}):e.jsxs(B,{className:"w-full mt-4 bg-[#406E71] hover:bg-[#2a4c64]",onClick:()=>d(v.id),disabled:r===v.id,children:[r===v.id?"Loading…":"Get Started",e.jsx(Lr,{className:"h-4 w-4 ml-1"})]})]})},v.id)}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Secure checkout powered by Stripe."}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-muted-foreground",onClick:()=>l(!0),children:[e.jsx(cb,{className:"h-4 w-4 mr-1"})," Join the waitlist instead"]})]})]}),e.jsx(uss,{open:i,onOpenChange:l,coachId:f.id,coachName:h==null?void 0:h.name,packages:p.map(v=>({id:v.id,name:v.name}))})]})}const mss=Gw({full_name:fo().trim().min(2,"Please enter your full name").max(100),email:fo().trim().email("Enter a valid email").max(255),phone:fo().trim().max(40).optional().or(bp("")),brokerage:fo().trim().max(150).optional().or(bp("")),years_experience:fo().trim().max(40).optional().or(bp("")),specialties:fo().trim().max(500).optional().or(bp("")),why_coach:fo().trim().min(20,"Tell us a bit more — at least 20 characters").max(2e3),results_story:fo().trim().max(2e3).optional().or(bp("")),website_url:fo().trim().max(300).optional().or(bp("")),linkedin_url:fo().trim().max(300).optional().or(bp(""))});function pss(){const s=Ln(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState({full_name:"",email:"",phone:"",brokerage:"",years_experience:"",specialties:"",why_coach:"",results_story:"",website_url:"",linkedin_url:""}),o=(d,u)=>l(h=>({...h,[d]:u})),c=async d=>{var p;d.preventDefault();const u=mss.safeParse(i);if(!u.success){const f=(p=Object.values(u.error.flatten().fieldErrors)[0])==null?void 0:p[0];return ae.error(f||"Please check the form and try again")}n(!0);const{error:h}=await q.from("coach_applications").insert(u.data);if(n(!1),h)return ae.error(h.message||"Could not submit application");a(!0),window.scrollTo({top:0,behavior:"smooth"})};return r?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"max-w-xl text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center h-20 w-20 rounded-full bg-gradient-to-br from-yellow-400 to-yellow-300 text-[#1c3447] mb-6 shadow-2xl",children:e.jsx(vr,{className:"h-10 w-10"})}),e.jsx("h1",{className:"text-4xl md:text-5xl font-bold mb-4",children:"Application received."}),e.jsx("p",{className:"text-white/80 text-lg leading-relaxed mb-8",children:"Thank you for applying to the LevelUp Coaching program. Our team personally reviews every application — we'll be in touch within 5 business days."}),e.jsx(B,{onClick:()=>s("/coaches"),className:"bg-yellow-300 text-[#1c3447] hover:bg-yellow-200 font-semibold",children:"Browse our coaches"})]})}):e.jsxs("div",{className:"min-h-screen bg-white",children:[e.jsxs("section",{className:"relative overflow-hidden bg-gradient-to-br from-[#1c3447] via-[#2a4c64] to-[#406E71] text-white",children:[e.jsx("div",{className:"absolute -top-32 -left-24 h-96 w-96 rounded-full bg-[#5a9ea2]/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-32 -right-24 h-96 w-96 rounded-full bg-yellow-400/10 blur-3xl"}),e.jsx("div",{className:"absolute inset-0 opacity-[0.04]",style:{backgroundImage:"radial-gradient(white 1px, transparent 1px)",backgroundSize:"22px 22px"}}),e.jsxs("div",{className:"relative max-w-5xl mx-auto px-4 py-16 md:py-20",children:[e.jsxs(In,{to:"/coaches",className:"inline-flex items-center gap-2 text-white/70 hover:text-white text-sm mb-8",children:[e.jsx(qr,{className:"h-4 w-4"})," Back to coaches"]}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1.5 rounded-full bg-white/10 backdrop-blur-sm border border-white/15 text-xs uppercase tracking-[0.18em] font-semibold mb-6",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-yellow-300"}),"Coach Application — By Invitation & Application Only"]}),e.jsx("h1",{className:"text-4xl md:text-6xl font-bold tracking-tight leading-[1.05] max-w-3xl",children:"Join the most respected coaching program in real estate."}),e.jsx("p",{className:"text-white/80 mt-6 max-w-2xl text-lg leading-relaxed",children:"LevelUp Coaches don't just teach — they transform careers. We hand-pick top-producing agents and proven mentors who are ready to multiply their impact, build a recurring revenue stream, and help thousands of agents finally break through."}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-4 mt-12",children:[e.jsxs("div",{className:"rounded-2xl bg-white/5 backdrop-blur-sm border border-white/10 p-5",children:[e.jsx(An,{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(go,{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(fc,{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(vr,{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(xo,{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(oa,{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(j_,{label:"Full name *",children:e.jsx(ye,{value:i.full_name,onChange:d=>o("full_name",d.target.value),required:!0,maxLength:100})}),e.jsx(j_,{label:"Email *",children:e.jsx(ye,{type:"email",value:i.email,onChange:d=>o("email",d.target.value),required:!0,maxLength:255})}),e.jsx(j_,{label:"Phone",children:e.jsx(ye,{value:i.phone,onChange:d=>o("phone",d.target.value),maxLength:40})}),e.jsx(j_,{label:"Current brokerage",children:e.jsx(ye,{value:i.brokerage,onChange:d=>o("brokerage",d.target.value),maxLength:150})}),e.jsx(j_,{label:"Years in real estate",children:e.jsx(ye,{value:i.years_experience,onChange:d=>o("years_experience",d.target.value),placeholder:"e.g. 8",maxLength:40})}),e.jsx(j_,{label:"Coaching specialties",children:e.jsx(ye,{value:i.specialties,onChange:d=>o("specialties",d.target.value),placeholder:"Lead gen, listings, luxury, teams…",maxLength:500})}),e.jsx(j_,{label:"Website",children:e.jsx(ye,{value:i.website_url,onChange:d=>o("website_url",d.target.value),placeholder:"https://",maxLength:300})}),e.jsx(j_,{label:"LinkedIn",children:e.jsx(ye,{value:i.linkedin_url,onChange:d=>o("linkedin_url",d.target.value),placeholder:"https://linkedin.com/in/",maxLength:300})})]}),e.jsx(j_,{label:"Why do you want to coach with LevelUp? *",children:e.jsx(Ms,{value:i.why_coach,onChange:d=>o("why_coach",d.target.value),required:!0,rows:5,maxLength:2e3,placeholder:"What drives you? Who do you want to help? What makes your approach different?"})}),e.jsx(j_,{label:"Tell us about results you've created — for yourself or other agents.",children:e.jsx(Ms,{value:i.results_story,onChange:d=>o("results_story",d.target.value),rows:5,maxLength:2e3,placeholder:"Production numbers, agent breakthroughs, testimonials — anything that shows the impact you've had."})}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-stretch sm:items-center gap-3 pt-2",children:[e.jsx(B,{type:"submit",disabled:t,className:"bg-gradient-to-r from-[#406E71] to-[#2a4c64] hover:opacity-95 text-white font-semibold px-8 py-6 text-base flex-1 sm:flex-none",children:t?"Submitting…":"Submit application"}),e.jsx("p",{className:"text-xs text-slate-500",children:"We review every application within 5 business days."})]})]})]})]})}function j_({label:s,children:t}){return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-semibold text-[#1c3447]",children:s}),t]})}const fss="/assets/testimonial-avatar-1-BsCQFauB.jpg",xss="/assets/testimonial-avatar-2-B6VPVc2t.jpg",gss="/assets/testimonial-avatar-3-GuEFwYUE.jpg",yss="/assets/testimonial-avatar-4-98iKMtkB.jpg",vss="/assets/testimonial-avatar-5-ZsZfyxMX.jpg",bss=[fss,xss,gss,yss,vss],_ss=Gw({name:fo().trim().min(2,"Name must be at least 2 characters").max(100),email:fo().trim().email("Please enter a valid email address").max(255),phone:fo().trim().min(10,"Please enter a valid phone number").max(20).optional().or(bp("")),brokerage:fo().trim().max(200).optional().or(bp(""))}),wss=[{icon:jh,title:"Academy Training",description:"Access a library of on-demand video training covering lead generation, marketing, technology, and more."},{icon:pl,title:"300+ Templates",description:"Professional Canva templates for social media, flyers, postcards, and marketing materials."},{icon:yr,title:"Live Events",description:"Weekly live training sessions, workshops, and Q&A events with industry experts."},{icon:Zl,title:"Agent Community",description:"Connect with fellow agents, share wins, ask questions, and network in our private community."},{icon:br,title:"Resource Kits",description:"Downloadable toolkits with scripts, checklists, guides, and everything you need to close more deals."},{icon:Oi,title:"Social Swag",description:"Fresh social media content and designs updated regularly to help you stand out online."}],jss=[{icon:An,title:"Contact Management",description:"Organize your sphere into relationship tiers—Top 25, Past Clients, Referral Partners, and more."},{icon:un,title:"Smart TouchPlans",description:"Automated action plans that tell you exactly who to contact and how, based on relationship type."},{icon:Cr,title:"One-Tap Actions",description:"Call, text, or email contacts directly with pre-written scripts tailored to each relationship."},{icon:Ah,title:"Birthday Alerts",description:"Never miss an important date—get reminders for birthdays and home anniversaries."},{icon:ka,title:"Pop-by Map",description:"See all your contacts on a map and plan efficient pop-by routes in your area."},{icon:_o,title:"Momentum Tracking",description:"Track your touch streaks, weekly goals, and relationship health scores."},{icon:gi,title:"Relationship Health",description:"Visual dashboard showing which contacts need attention based on last touch date."},{icon:im,title:"Daily Action Cards",description:"Wake up to a prioritized list of exactly who to reach out to today."}],Nss=[{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."}],kss=()=>{const s=Ln(),[t,n]=N.useState(!1),[r,a]=N.useState({name:"",email:"",phone:"",brokerage:""}),[i,l]=N.useState({}),o=async c=>{var u,h;c.preventDefault(),l({});const d=_ss.safeParse(r);if(!d.success){const p={};d.error.issues.forEach(f=>{f.path[0]&&(p[f.path[0]]=f.message)}),l(p);return}n(!0);try{const p=typeof window<"u"&&localStorage.getItem("levelup_referral_code")||void 0,{data:f,error:y}=await q.functions.invoke("create-trial-signup",{body:{name:r.name.trim(),email:r.email.trim().toLowerCase(),phone:((u=r.phone)==null?void 0:u.trim())||void 0,brokerage:((h=r.brokerage)==null?void 0:h.trim())||void 0,referral_code:p}});if(y){console.error("Trial signup error:",y),ae.error(y.message||"Something went wrong. Please try again.");return}if(f!=null&&f.error){ae.error(f.error);return}ae.success("🎉 Welcome aboard! Check your email to claim your account."),typeof window<"u"&&window.oaiq&&window.oaiq("measure","trial_started",{type:"plan_enrollment"}),typeof window<"u"&&window.fbq&&window.fbq("track","Lead",{content_name:"Trial Signup",value:0,currency:"USD"}),s("/trial/success")}catch(p){console.error("Trial signup error:",p),ae.error("Something went wrong. Please try again.")}finally{n(!1)}};return e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{children:[e.jsx("title",{children:"Start Your Free 7-Day Trial | LevelUp Dashboard"}),e.jsx("meta",{name:"description",content:"Take LevelUp for a free 7-day test drive. No credit card required. The all-in-one platform for real estate agents and brokerages."}),e.jsx("meta",{property:"og:title",content:"Start Your Free 7-Day Trial | LevelUp"}),e.jsx("meta",{property:"og:description",content:"Take LevelUp for a free 7-day test drive. No credit card required."}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("script",{children:"!function(f,b,e,v,n,t,s){if(f.fbq)return;n=f.fbq=function(){n.callMethod?n.callMethod.apply(n,arguments):n.queue.push(arguments)};if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';n.queue=[];t=b.createElement(e);t.async=!0;t.src=v;s=b.getElementsByTagName(e)[0];s.parentNode.insertBefore(t,s)}(window,document,'script','https://connect.facebook.net/en_US/fbevents.js'); fbq('init', '1388750291887997'); fbq('track', 'PageView');"})]}),e.jsx("noscript",{dangerouslySetInnerHTML:{__html:''}}),e.jsxs("div",{className:"min-h-screen bg-background overflow-hidden",children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-50 bg-[#4a6b6d] shadow-md",children:e.jsxs("div",{className:"container mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{className:"flex items-center",children:e.jsx("img",{src:mfe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsxs("div",{className:"flex items-center gap-2 md:gap-4",children:[e.jsx(B,{variant:"ghost",className:"text-white/90 hover:text-white hover:bg-white/10 hidden sm:inline-flex",onClick:()=>{var c;return(c=document.getElementById("features"))==null?void 0:c.scrollIntoView({behavior:"smooth"})},children:"Features"}),e.jsx(B,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})]})}),e.jsxs("section",{className:"relative pt-24 pb-20 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsxs("div",{className:"grid lg:grid-cols-2 gap-12 items-center",children:[e.jsxs("div",{className:"space-y-8 text-center lg:text-left",children:[e.jsx("div",{className:"flex justify-center lg:justify-start",children:e.jsx("img",{alt:"LevelUp Consulting Group",className:"h-24 md:h-32 drop-shadow-lg",src:"/lovable-uploads/3a0c7ef9-9e79-411f-a9af-6f2a99e8bd7b.webp"})}),e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium",children:[e.jsx(un,{className:"h-4 w-4 text-yellow-400"}),e.jsx("span",{children:"7-Day Free Trial • No Credit Card Required"})]}),e.jsxs("h1",{className:"text-3xl md:text-4xl lg:text-5xl font-bold text-white leading-tight font-sans",children:["Take LevelUp for a"," ",e.jsx("span",{className:"italic",children:"Free Test Drive"})]}),e.jsxs("p",{className:"text-lg md:text-xl text-white/80 max-w-xl mx-auto lg:mx-0 font-sans",children:["The tools you need to get it done.",e.jsx("br",{}),e.jsx("em",{children:"The platform you need to keep it going."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 justify-center lg:justify-start",children:[e.jsxs("div",{className:"flex items-center gap-2 text-white/80",children:[e.jsx(vr,{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(vr,{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:bss.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(oa,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},c))}),e.jsx("p",{className:"text-sm text-white/60",children:"Trusted by 3,000+ agents"})]})]})]}),e.jsx("div",{className:"lg:pl-8",children:e.jsx(fe,{className:"bg-white shadow-2xl border-0",children:e.jsxs(Ee,{className:"p-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-[#4a6b6d] mb-4",children:e.jsx(tx,{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(ne,{htmlFor:"name",children:"Full Name *"}),e.jsx(ye,{id:"name",type:"text",placeholder:"John Smith",value:r.name,onChange:c=>a({...r,name:c.target.value}),required:!0}),i.name&&e.jsx("p",{className:"text-sm text-destructive",children:i.name})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"email",children:"Email Address *"}),e.jsx(ye,{id:"email",type:"email",placeholder:"john@example.com",value:r.email,onChange:c=>a({...r,email:c.target.value}),required:!0}),i.email&&e.jsx("p",{className:"text-sm text-destructive",children:i.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ye,{id:"phone",type:"tel",placeholder:"(555) 123-4567",value:r.phone,onChange:c=>a({...r,phone:c.target.value})}),i.phone&&e.jsx("p",{className:"text-sm text-destructive",children:i.phone})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"brokerage",children:"Brokerage Name"}),e.jsx(ye,{id:"brokerage",type:"text",placeholder:"Your brokerage or team name",value:r.brokerage,onChange:c=>a({...r,brokerage:c.target.value})}),i.brokerage&&e.jsx("p",{className:"text-sm text-destructive",children:i.brokerage})]}),e.jsx(B,{type:"submit",className:"w-full h-12 text-lg font-semibold bg-[#4a6b6d] hover:bg-[#3d5a5c]",disabled:t,children:t?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"mr-2 h-5 w-5 animate-spin"}),"Creating Your Account..."]}):e.jsxs(e.Fragment,{children:["Start My Free Trial",e.jsx(Oa,{className:"ml-2 h-5 w-5"})]})}),e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["By signing up, you agree to our"," ",e.jsx("a",{href:"/terms-of-service",className:"text-[#4a6b6d] hover:underline",children:"Terms"})," ","and"," ",e.jsx("a",{href:"/privacy-policy",className:"text-[#4a6b6d] hover:underline",children:"Privacy Policy"})]})]})]})})})]})})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center space-y-8",children:[e.jsx("h2",{className:"text-3xl md:text-5xl leading-tight font-sans font-semibold text-secondary",children:"We help brokerages and agents grow with training, tools, and built-in execution."}),e.jsxs("div",{className:"space-y-2 text-lg text-muted-foreground",children:[e.jsx("p",{children:"Agents get weekly coaching + plug-and-play marketing."}),e.jsx("p",{children:"Brokerages get higher adoption, consistency, and real engagement."})]}),e.jsx("p",{className:"text-2xl md:text-4xl text-[#4a6b6d] pt-4 font-sans font-bold",children:"LEVELUP EQUIPS BOTH TO THRIVE."})]})})}),e.jsx("section",{id:"features",className:"py-20 bg-muted/30",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl mb-6 font-sans font-bold",children:"What's inside our members only portal?"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"Everything you need to grow your business, all in one place."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8 max-w-6xl mx-auto",children:wss.map((c,d)=>e.jsxs(fe,{className:"group relative overflow-hidden border hover:border-[#4a6b6d]/50 transition-all duration-300 hover:shadow-lg bg-background",children:[e.jsxs(It,{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(Rt,{className:"text-xl font-sans",children:c.title})]}),e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground leading-relaxed",children:c.description})})]},d))})]})}),e.jsxs("section",{className:"py-20 bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs("div",{className:"container mx-auto px-4 relative",children:[e.jsxs("div",{className:"text-center max-w-3xl mx-auto mb-16",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-2 rounded-full bg-white/10 text-white text-sm font-medium mb-6",children:[e.jsx(un,{className:"w-4 h-4"}),"Included with Your Trial"]}),e.jsxs("h2",{className:"text-3xl mb-6 text-white font-sans font-bold md:text-6xl",children:["Meet ",e.jsx("span",{className:"italic",children:"Agent OS"})]}),e.jsx("p",{className:"text-lg text-white/80",children:"Your relationship-first operating system. Never forget a follow-up, track every touchpoint, and turn your sphere into a referral machine."})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-6 max-w-6xl mx-auto",children:jss.map((c,d)=>e.jsxs(fe,{className:"group relative overflow-hidden border-0 bg-white/10 backdrop-blur-sm hover:bg-white/20 transition-all duration-300",children:[e.jsxs(It,{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(Rt,{className:"text-lg font-semibold text-white",children:c.title})]}),e.jsx(Ee,{children:e.jsx("p",{className:"text-white/70 text-sm leading-relaxed",children:c.description})})]},d))})]})]}),e.jsx("section",{className:"py-20 bg-background",children:e.jsxs("div",{className:"container mx-auto px-4",children:[e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold mb-4 font-sans",children:"Loved by Top Producers"}),e.jsx("p",{className:"text-lg text-muted-foreground",children:"See what agents are saying about LevelUp"})]}),e.jsx("div",{className:"grid md:grid-cols-3 gap-8 max-w-5xl mx-auto",children:Nss.map((c,d)=>e.jsx(fe,{className:"border hover:shadow-lg transition-shadow",children:e.jsxs(Ee,{className:"p-6",children:[e.jsx("div",{className:"flex gap-1 mb-4",children:[1,2,3,4,5].map(u=>e.jsx(oa,{className:"h-4 w-4 fill-yellow-400 text-yellow-400"},u))}),e.jsxs("p",{className:"text-muted-foreground mb-4 italic",children:['"',c.quote,'"']}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:c.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.role})]})]})},d))})]})}),e.jsx("section",{className:"py-16 bg-muted/30",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-wrap justify-center gap-8 md:gap-16",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-[#4a6b6d]/10 flex items-center justify-center",children:e.jsx(Ih,{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(im,{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(An,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Expert Support"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Real estate pros"})]})]})]})})}),e.jsx("section",{id:"free-trial",className:"py-20 bg-background",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs(fe,{className:"bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] border-0 shadow-2xl overflow-hidden relative",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsxs(Ee,{className:"p-12 text-center relative",children:[e.jsx("h2",{className:"text-3xl md:text-4xl font-bold text-white mb-4 font-sans",children:"Ready to Level Up Your Business?"}),e.jsx("p",{className:"text-xl text-white/80 mb-8 max-w-2xl mx-auto",children:"Join thousands of successful agents. Start your free 7-day trial today."}),e.jsxs(B,{onClick:()=>window.scrollTo({top:0,behavior:"smooth"}),size:"lg",className:"h-14 px-8 text-lg font-semibold bg-white text-[#1e3a4c] hover:bg-white/90 shadow-2xl transition-all hover:scale-105 rounded-full",children:["Start Your Free Trial Now",e.jsx(Oa,{className:"ml-2 h-5 w-5"})]})]})]})})}),e.jsx("footer",{className:"bg-[#1e3a4c] py-12",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center gap-6",children:[e.jsx("img",{src:Kpe,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."})]})})})]})]})},Sss=()=>{const s=Ln();return e.jsxs(e.Fragment,{children:[e.jsx(Zo,{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:mfe,alt:"LevelUp",className:"h-8 md:h-10"})}),e.jsx(B,{onClick:()=>s("/auth"),className:"bg-white text-[#4a6b6d] hover:bg-gray-100 font-medium shadow-md",children:"Sign In"})]})}),e.jsxs("section",{className:"relative pt-24 pb-12 bg-gradient-to-br from-[#1e3a4c] via-[#2a4f5f] to-[#3d6b6b] overflow-hidden flex-1 flex items-center",children:[e.jsx("div",{className:"absolute inset-0 opacity-10",children:e.jsx("div",{className:"absolute inset-0 bg-[url('data:image/svg+xml;base64,PHN2ZyB3aWR0aD0iNjAiIGhlaWdodD0iNjAiIHZpZXdCb3g9IjAgMCA2MCA2MCIgeG1sbnM9Imh0dHA6Ly93d3cudzMub3JnLzIwMDAvc3ZnIj48ZyBmaWxsPSJub25lIiBmaWxsLXJ1bGU9ImV2ZW5vZGQiPjxnIGZpbGw9IiNmZmZmZmYiIGZpbGwtb3BhY2l0eT0iMC40Ij48cGF0aCBkPSJNMzYgMzRoLTJ2LTRoMnY0em0wLTZ2LTRoLTJ2NGgyem0tNiA2aC0ydi00aDJ2NHptMC02di00aC0ydjRoMnoiLz48L2c+PC9nPjwvc3ZnPg==')]"})}),e.jsx("div",{className:"container mx-auto px-4 relative",children:e.jsx("div",{className:"flex justify-center",children:e.jsx(fe,{className:"max-w-lg w-full bg-white shadow-2xl border-0",children:e.jsxs(Ee,{className:"p-8 md:p-12 text-center",children:[e.jsxs("div",{className:"relative inline-block mb-8",children:[e.jsx("div",{className:"w-24 h-24 rounded-full bg-gradient-to-br from-[#4a6b6d] to-[#3d5a5c] flex items-center justify-center",children:e.jsx(vr,{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(ih,{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(Gs,{className:"h-6 w-6 text-[#4a6b6d]"})}),e.jsx("h2",{className:"text-lg font-semibold text-foreground",children:"Check Your Inbox"})]}),e.jsx("p",{className:"text-muted-foreground",children:"We just sent you a magic link to claim your account and set up your password. Click the link in your email to get started!"})]}),e.jsxs("div",{className:"text-left space-y-3 mb-8",children:[e.jsx("p",{className:"text-sm text-muted-foreground font-medium uppercase tracking-wide",children:"What happens next:"}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"1"})}),e.jsx("p",{className:"text-foreground",children:"Check your email for the welcome message"})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"2"})}),e.jsx("p",{className:"text-foreground",children:'Click "Claim Your Account" to set your password'})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-[#4a6b6d] flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-xs font-bold text-white",children:"3"})}),e.jsx("p",{className:"text-foreground",children:"Start exploring all the features!"})]})]}),e.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:["Didn't receive the email? Check your spam folder or"," ",e.jsx("button",{onClick:()=>s("/trial"),className:"text-[#4a6b6d] hover:underline font-medium",children:"try again"})]}),e.jsxs(B,{onClick:()=>s("/auth"),className:"bg-[#4a6b6d] hover:bg-[#3d5a5c]",children:["Go to Sign In",e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})]})})})})]}),e.jsx("footer",{className:"bg-[#1e3a4c] py-8",children:e.jsx("div",{className:"container mx-auto px-4",children:e.jsxs("div",{className:"flex flex-col md:flex-row justify-between items-center gap-4",children:[e.jsx("img",{src:Kpe,alt:"LevelUp",className:"h-8"}),e.jsxs("p",{className:"text-sm text-white/40",children:["© ",new Date().getFullYear()," LevelUp Consulting Group. All rights reserved."]})]})})})]})]})},Css=Gw({viewerName:fo().min(1,"Name is required").max(100,"Name must be less than 100 characters"),viewerEmail:fo().email("Please enter a valid email").max(255,"Email must be less than 255 characters"),viewerPhone:fo().max(20,"Phone must be less than 20 characters").optional(),message:fo().min(1,"Message is required").max(1e3,"Message must be less than 1000 characters")});function Tss({shareToken:s,agentName:t,hasContact:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),d=bye({resolver:_ye(Css),defaultValues:{viewerName:"",viewerEmail:"",viewerPhone:"",message:""}}),u=async h=>{a(!0),c(null);try{const{data:p,error:f}=await q.functions.invoke("video-reply-notify",{body:{shareToken:s,viewerName:h.viewerName,viewerEmail:h.viewerEmail,viewerPhone:h.viewerPhone||void 0,message:h.message}});if(f)throw new Error(f.message);if(!(p!=null&&p.success))throw new Error((p==null?void 0:p.error)||"Failed to send reply");l(!0)}catch(p){console.error("Failed to submit reply:",p),c(p.message||"Something went wrong. Please try again.")}finally{a(!1)}};return i?e.jsx(fe,{className:"border-2 border-primary/20 bg-gradient-to-br from-primary/5 to-primary/10",children:e.jsxs(Ee,{className:"py-8 text-center",children:[e.jsx("div",{className:"inline-flex items-center justify-center w-16 h-16 rounded-full bg-primary/20 mb-4",children:e.jsx(vr,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-xl font-semibold mb-2",children:"Message Sent!"}),e.jsxs("p",{className:"text-muted-foreground",children:[t?`${t} will`:"They'll"," get back to you soon."]})]})}):e.jsxs(fe,{children:[e.jsxs(It,{className:"pb-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(Zl,{className:"h-5 w-5 text-primary"}),e.jsx(Rt,{className:"text-lg",children:"Reply to this video"})]}),e.jsx(Vn,{children:n?`Have a question or want to connect? Send ${t||"them"} a message.`:`Interested? Share your info and ${t||"your agent"} will be in touch.`})]}),e.jsx(Ee,{children:e.jsx(wye,{...d,children:e.jsxs("form",{onSubmit:d.handleSubmit(u),className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(_u,{control:d.control,name:"viewerName",render:({field:h})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Your Name *"}),e.jsx(nu,{children:e.jsx(ye,{placeholder:"John Smith",...h})}),e.jsx(Wx,{})]})}),e.jsx(_u,{control:d.control,name:"viewerEmail",render:({field:h})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Email *"}),e.jsx(nu,{children:e.jsx(ye,{type:"email",placeholder:"john@example.com",...h})}),e.jsx(Wx,{})]})})]}),!n&&e.jsx(_u,{control:d.control,name:"viewerPhone",render:({field:h})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Phone (optional)"}),e.jsx(nu,{children:e.jsx(ye,{type:"tel",placeholder:"(555) 123-4567",...h})}),e.jsx(Wx,{})]})}),e.jsx(_u,{control:d.control,name:"message",render:({field:h})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Message *"}),e.jsx(nu,{children:e.jsx(Ms,{placeholder:n?"Thanks for the video! I had a question about...":"I'm interested in learning more about...",className:"min-h-[100px] resize-none",...h})}),e.jsx(Wx,{})]})}),o&&e.jsx("p",{className:"text-sm text-destructive",children:o}),e.jsx(B,{type:"submit",className:"w-full gap-2",disabled:r,children:r?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4"}),"Send Message"]})})]})})})]})}const Ess=()=>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(oa,{className:"absolute top-[5%] left-[8%] w-6 h-6 text-blue-600/30 fill-blue-600/20"}),e.jsx(oa,{className:"absolute top-[15%] left-[20%] w-4 h-4 text-blue-600/25 fill-blue-600/15"}),e.jsx(oa,{className:"absolute top-[8%] left-[28%] w-5 h-5 text-blue-600/30 fill-blue-600/20"}),e.jsx(oa,{className:"absolute top-[25%] left-[12%] w-4 h-4 text-blue-600/20 fill-blue-600/10"}),e.jsx(oa,{className:"absolute top-[20%] right-[15%] w-5 h-5 text-red-500/25 fill-red-500/15 animate-pulse"}),e.jsx(V2,{className:"absolute bottom-[20%] right-[10%] w-12 h-12 text-blue-600/15 rotate-12"})]}),Ass=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-red-500/5 via-transparent to-blue-500/5"}),e.jsxs("div",{className:"absolute top-[10%] left-[15%] w-32 h-32",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-red-400/20 animate-ping",style:{animationDuration:"3s"}}),e.jsx(un,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-8 h-8 text-red-400/40"})]}),e.jsxs("div",{className:"absolute top-[5%] right-[20%] w-24 h-24",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border-2 border-blue-400/20 animate-ping",style:{animationDuration:"4s",animationDelay:"1s"}}),e.jsx(oa,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-6 h-6 text-blue-400/40 fill-blue-400/20"})]}),e.jsxs("div",{className:"absolute top-[20%] left-[50%] w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full border border-white/10 animate-ping",style:{animationDuration:"3.5s",animationDelay:"0.5s"}}),e.jsx(un,{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-5 h-5 text-amber-400/40"})]}),e.jsx(oa,{className:"absolute bottom-[25%] left-[10%] w-6 h-6 text-blue-500/25 fill-blue-500/15 animate-pulse"}),e.jsx(oa,{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(V2,{className:"absolute top-[8%] left-[5%] w-10 h-10 text-red-500/20 rotate-12"})]}),Mss=()=>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(rb,{className:"w-20 h-20 text-pink-400 rotate-12"})}),e.jsx("div",{className:"absolute top-[2%] right-[8%] opacity-15",children:e.jsx(rb,{className:"w-16 h-16 text-rose-400 -rotate-12"})}),e.jsx("div",{className:"absolute bottom-[15%] left-[8%] opacity-15",children:e.jsx(rb,{className:"w-14 h-14 text-purple-400 rotate-45"})}),e.jsx("div",{className:"absolute bottom-[20%] right-[5%] opacity-20",children:e.jsx(rb,{className:"w-16 h-16 text-pink-300 -rotate-6"})}),e.jsx(gi,{className:"absolute top-[15%] left-[30%] w-5 h-5 text-rose-300/40 fill-rose-300/20 animate-pulse"}),e.jsx(gi,{className:"absolute top-[25%] right-[25%] w-4 h-4 text-pink-300/40 fill-pink-300/20 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(gi,{className:"absolute top-[10%] left-[60%] w-4 h-4 text-rose-400/30 fill-rose-400/15 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx("div",{className:"absolute top-[8%] left-[45%] w-8 h-8 rounded-full bg-pink-300/10 blur-sm"}),e.jsx("div",{className:"absolute bottom-[25%] right-[30%] w-6 h-6 rounded-full bg-rose-300/10 blur-sm"})]}),Iss=()=>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(fc,{className:"absolute top-[8%] left-[12%] w-12 h-12 text-blue-600/15"}),e.jsx(oa,{className:"absolute top-[15%] left-[22%] w-5 h-5 text-amber-500/25 fill-amber-500/15"}),e.jsx(fc,{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(oa,{className:"absolute bottom-[25%] left-[15%] w-6 h-6 text-blue-500/20 fill-blue-500/10 animate-pulse"}),e.jsx(oa,{className:"absolute top-[20%] right-[22%] w-5 h-5 text-indigo-400/20 fill-indigo-400/10 animate-pulse",style:{animationDelay:"0.5s"}})]}),Pss=()=>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(rb,{className:"absolute top-[20%] left-[32%] w-7 h-7 text-purple-400/30"}),e.jsx(rb,{className:"absolute top-[12%] right-[28%] w-6 h-6 text-pink-400/30"}),e.jsx(ZP,{className:"absolute top-[18%] left-[52%] w-5 h-5 text-sky-400/35"})]}),Lss=()=>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(wA,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-orange-400/25"}),e.jsx(wA,{className:"absolute top-[10%] right-[12%] w-12 h-12 text-purple-400/20 animate-pulse"}),e.jsxs("div",{className:"absolute bottom-[18%] left-[8%]",children:[e.jsx("div",{className:"w-14 h-12 rounded-full bg-orange-500/20"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-4 bg-green-600/25 rounded-t-full"})]}),e.jsxs("div",{className:"absolute bottom-[22%] right-[12%]",children:[e.jsx("div",{className:"w-12 h-10 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-1.5 left-1/2 -translate-x-1/2 w-1.5 h-3 bg-green-600/20 rounded-t-full"})]}),e.jsx("div",{className:"absolute top-[15%] left-[40%] opacity-20",children:e.jsx("svg",{viewBox:"0 0 24 12",className:"w-10 h-5 text-slate-800 fill-current",children:e.jsx("path",{d:"M12 6c-2-4-6-6-12-6 4 2 6 4 6 6s-2 4-6 6c6 0 10-2 12-6zm0 0c2-4 6-6 12-6-4 2-6 4-6 6s2 4 6 6c-6 0-10-2-12-6z"})})}),e.jsx(un,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-purple-400/35 animate-pulse"}),e.jsx(un,{className:"absolute bottom-[28%] right-[25%] w-5 h-5 text-orange-400/30 animate-pulse",style:{animationDelay:"0.5s"}})]}),Dss=()=>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(s4,{className:"absolute bottom-[8%] left-[5%] w-20 h-20 text-green-600/18"}),e.jsx(s4,{className:"absolute bottom-[12%] right-[8%] w-16 h-16 text-emerald-600/15"}),e.jsx(s4,{className:"absolute bottom-[10%] left-[28%] w-12 h-12 text-green-500/12"}),e.jsx(Tv,{className:"absolute top-[5%] left-[15%] w-10 h-10 text-sky-300/30 animate-pulse"}),e.jsx(Tv,{className:"absolute top-[10%] right-[20%] w-8 h-8 text-blue-300/25 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(Tv,{className:"absolute top-[18%] left-[45%] w-6 h-6 text-sky-200/25 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(Tv,{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(oa,{className:"absolute top-[3%] left-[50%] -translate-x-1/2 w-10 h-10 text-amber-400/35 fill-amber-400/25"})]}),Rss=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-orange-900/10 via-amber-800/6 to-red-900/10"}),e.jsx("div",{className:"absolute top-[5%] left-[10%] w-10 h-8 rounded-full bg-orange-500/25 rotate-45"}),e.jsx("div",{className:"absolute top-[10%] right-[15%] w-8 h-6 rounded-full bg-red-500/20 -rotate-12"}),e.jsx("div",{className:"absolute top-[15%] left-[35%] w-7 h-5 rounded-full bg-amber-500/22 rotate-30"}),e.jsx("div",{className:"absolute bottom-[18%] left-[12%] w-10 h-7 rounded-full bg-yellow-600/18 -rotate-45"}),e.jsx("div",{className:"absolute bottom-[22%] right-[10%] w-9 h-6 rounded-full bg-orange-600/15 rotate-12"}),e.jsxs("div",{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2",children:[e.jsx("div",{className:"w-16 h-14 rounded-full bg-orange-400/15"}),e.jsx("div",{className:"absolute -top-2 left-1/2 -translate-x-1/2 w-2 h-5 bg-green-600/18 rounded-t-full"})]}),e.jsx(gi,{className:"absolute top-[8%] left-[55%] w-6 h-6 text-red-400/22 fill-red-400/12"}),e.jsx(gi,{className:"absolute top-[20%] right-[25%] w-5 h-5 text-orange-400/22 fill-orange-400/12"})]}),Oss=()=>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(oa,{className:"absolute top-[5%] left-[15%] w-12 h-12 text-yellow-400/35 fill-yellow-400/25 animate-pulse"}),e.jsx(oa,{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(oa,{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(oa,{className:"absolute top-[12%] right-[35%] w-8 h-8 text-amber-300/28 fill-amber-300/18 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[20%] left-[25%] w-4 h-4 rounded-full bg-pink-400/30"}),e.jsx("div",{className:"absolute top-[18%] right-[30%] w-3 h-3 rounded-full bg-sky-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[60%] w-2.5 h-2.5 rounded-full bg-emerald-400/30"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-3 h-3 rounded-full bg-purple-400/30"}),e.jsx(un,{className:"absolute top-[3%] left-[50%] w-10 h-10 text-yellow-400/40"}),e.jsx(ih,{className:"absolute bottom-[18%] left-[10%] w-12 h-12 text-purple-400/18 rotate-12"}),e.jsx(ih,{className:"absolute bottom-[20%] right-[12%] w-10 h-10 text-amber-400/15 -rotate-12"})]}),Fss=()=>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(oa,{className:"absolute top-[8%] left-[50%] -translate-x-1/2 w-14 h-14 text-yellow-400/28 fill-yellow-400/18"}),e.jsx(un,{className:"absolute top-[5%] left-[20%] w-7 h-7 text-blue-400/35"}),e.jsx(un,{className:"absolute top-[10%] right-[18%] w-6 h-6 text-sky-400/30"})]}),zss=()=>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(P2,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-green-500/25"}),e.jsx(P2,{className:"absolute top-[8%] right-[12%] w-12 h-12 text-emerald-500/20"}),e.jsx(P2,{className:"absolute bottom-[18%] left-[12%] w-14 h-14 text-green-400/22"}),e.jsx(P2,{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"})]})]})]}),Bss=()=>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(oa,{className:"absolute top-[5%] left-[42%] w-10 h-10 text-amber-400/30 fill-amber-400/20"}),e.jsx(oa,{className:"absolute top-[15%] right-[25%] w-7 h-7 text-yellow-400/25 fill-yellow-400/15"}),e.jsx(fc,{className:"absolute bottom-[20%] right-[12%] w-12 h-12 text-blue-500/18"}),e.jsx(fc,{className:"absolute top-[18%] left-[28%] w-8 h-8 text-indigo-400/15"}),e.jsx(V2,{className:"absolute top-[8%] left-[60%] w-10 h-10 text-indigo-400/18"})]}),$ss=()=>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(Ah,{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(ih,{className:"absolute top-[8%] left-[45%] w-10 h-10 text-purple-400/22 rotate-12"}),e.jsx(Oi,{className:"absolute bottom-[18%] right-[15%] w-12 h-12 text-rose-400/18"})]}),Uss=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-rose-900/12 via-pink-900/8 to-red-900/12"}),e.jsx(gi,{className:"absolute top-[5%] left-[10%] w-16 h-16 text-rose-400/28 fill-rose-400/18"}),e.jsx(gi,{className:"absolute top-[8%] right-[12%] w-14 h-14 text-pink-400/25 fill-pink-400/15"}),e.jsx(gi,{className:"absolute bottom-[15%] left-[12%] w-12 h-12 text-red-400/22 fill-red-400/12"}),e.jsx(gi,{className:"absolute bottom-[18%] right-[10%] w-13 h-13 text-rose-300/25 fill-rose-300/15"}),e.jsx(gi,{className:"absolute top-[15%] left-[30%] w-6 h-6 text-pink-300/35 fill-pink-300/20 animate-pulse"}),e.jsx(gi,{className:"absolute top-[20%] right-[35%] w-5 h-5 text-rose-300/35 fill-rose-300/20 animate-pulse",style:{animationDelay:"0.3s"}}),e.jsx(gi,{className:"absolute top-[12%] left-[55%] w-5 h-5 text-red-300/30 fill-red-300/15 animate-pulse",style:{animationDelay:"0.6s"}}),e.jsx(gi,{className:"absolute top-[25%] right-[25%] w-4 h-4 text-pink-400/30 fill-pink-400/15 animate-pulse",style:{animationDelay:"0.9s"}}),e.jsx("div",{className:"absolute top-[18%] left-[45%] w-8 h-8 rounded-full bg-rose-300/18 blur-sm"}),e.jsx("div",{className:"absolute bottom-[25%] right-[40%] w-6 h-6 rounded-full bg-pink-300/15 blur-sm"})]}),qss=()=>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(pb,{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(pb,{className:"absolute top-[15%] left-[18%] w-10 h-10 text-yellow-400/30"}),e.jsx(un,{className:"absolute top-[10%] left-[42%] w-7 h-7 text-amber-400/35"}),e.jsx(pb,{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"})]}),Vss=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-teal-900/10 via-cyan-900/6 to-emerald-900/10"}),e.jsx(Or,{className:"absolute top-[8%] left-[10%] w-14 h-14 text-teal-500/22"}),e.jsx(Or,{className:"absolute bottom-[15%] right-[8%] w-16 h-16 text-emerald-500/18"}),e.jsx(Ug,{className:"absolute top-[12%] right-[18%] w-10 h-10 text-amber-400/25"}),e.jsx(Ug,{className:"absolute bottom-[22%] left-[22%] w-8 h-8 text-yellow-400/22"}),e.jsx(gi,{className:"absolute top-[18%] left-[40%] w-6 h-6 text-rose-400/22 fill-rose-400/12"}),e.jsx(gi,{className:"absolute top-[22%] right-[35%] w-5 h-5 text-teal-400/20 fill-teal-400/10"}),e.jsx(un,{className:"absolute top-[5%] left-[55%] w-8 h-8 text-teal-400/30"}),e.jsx(ih,{className:"absolute bottom-[20%] left-[48%] w-10 h-10 text-cyan-400/18 rotate-12"})]}),Hss=()=>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(ih,{className:"absolute top-[5%] left-[12%] w-14 h-14 text-emerald-400/25 rotate-12"}),e.jsx(ih,{className:"absolute top-[8%] right-[10%] w-12 h-12 text-teal-400/22 -rotate-12"}),e.jsx(Ug,{className:"absolute bottom-[18%] left-[18%] w-12 h-12 text-amber-400/25"}),e.jsx(Or,{className:"absolute bottom-[15%] right-[12%] w-14 h-14 text-teal-500/18"}),e.jsx(un,{className:"absolute top-[15%] left-[42%] w-10 h-10 text-emerald-400/35"}),e.jsx(un,{className:"absolute top-[20%] right-[32%] w-7 h-7 text-cyan-400/30"}),e.jsx("div",{className:"absolute top-[25%] left-[55%] w-3 h-3 bg-amber-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[22%] right-[42%] w-2.5 h-2.5 bg-teal-400/30 rounded-full"}),e.jsx("div",{className:"absolute top-[28%] left-[35%] w-2 h-2 bg-emerald-400/30 rounded-full"})]}),Gss=()=>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(Ug,{className:"absolute bottom-[12%] left-[50%] -translate-x-1/2 w-24 h-24 text-amber-400/25 rotate-45"}),e.jsx(Ug,{className:"absolute top-[10%] left-[12%] w-10 h-10 text-yellow-400/30"}),e.jsx(Ug,{className:"absolute top-[12%] right-[15%] w-9 h-9 text-amber-300/25"}),e.jsx(Or,{className:"absolute top-[8%] left-[42%] w-12 h-12 text-teal-500/18"}),e.jsx(ih,{className:"absolute bottom-[22%] right-[18%] w-12 h-12 text-orange-400/18 rotate-12"}),e.jsx(un,{className:"absolute top-[5%] right-[35%] w-8 h-8 text-yellow-400/35"}),e.jsx(oa,{className:"absolute top-[18%] left-[28%] w-6 h-6 text-amber-400/25 fill-amber-400/15"})]}),Wss=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx("div",{className:"absolute inset-0 bg-gradient-to-br from-teal-900/10 via-emerald-900/6 to-green-900/10"}),e.jsx(Or,{className:"absolute bottom-[10%] left-[50%] -translate-x-1/2 w-20 h-20 text-teal-500/22"}),e.jsx("div",{className:"absolute bottom-[18%] left-[12%] w-12 h-10 bg-amber-400/18 rounded-sm"}),e.jsx("div",{className:"absolute bottom-[20%] left-[20%] w-10 h-8 bg-orange-400/15 rounded-sm"}),e.jsx("div",{className:"absolute bottom-[16%] right-[15%] w-11 h-9 bg-amber-300/18 rounded-sm"}),e.jsx(Ug,{className:"absolute top-[10%] right-[12%] w-10 h-10 text-amber-400/28"}),e.jsx(gi,{className:"absolute top-[8%] left-[18%] w-8 h-8 text-rose-400/25 fill-rose-400/15"}),e.jsx(un,{className:"absolute top-[12%] left-[45%] w-8 h-8 text-teal-400/30"}),e.jsx(hw,{className:"absolute top-[15%] right-[28%] w-10 h-10 text-emerald-400/20"})]}),bUe=()=>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"})]}),Kss=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(gi,{className:"absolute top-6 left-[12%] w-4 h-4 text-rose-300/50 fill-rose-300/30 animate-pulse"}),e.jsx(gi,{className:"absolute top-10 right-[18%] w-3 h-3 text-pink-300/50 fill-pink-300/30 animate-pulse delay-150"}),e.jsx(gi,{className:"absolute top-4 left-[40%] w-2.5 h-2.5 text-rose-400/40 fill-rose-400/20 animate-pulse delay-300"}),e.jsx(gi,{className:"absolute top-14 right-[35%] w-3.5 h-3.5 text-pink-300/40 fill-pink-300/20 animate-pulse delay-200"})]}),Yss=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(hw,{className:"absolute top-5 left-[10%] w-4 h-4 text-blue-400/50 animate-pulse"}),e.jsx(un,{className:"absolute top-10 right-[15%] w-3 h-3 text-amber-400/50 animate-pulse delay-100"}),e.jsx(Or,{className:"absolute top-8 left-[38%] w-3 h-3 text-teal-300/40 animate-pulse delay-200"})]}),Zss=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(ey,{className:"absolute top-5 left-[12%] w-4 h-4 text-amber-500/50 animate-pulse"}),e.jsx(aL,{className:"absolute top-10 right-[15%] w-3 h-3 text-rose-400/50 animate-pulse delay-100"}),e.jsx(ey,{className:"absolute top-8 left-[40%] w-3 h-3 text-amber-400/40 animate-pulse delay-200"})]}),aF=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(un,{className:"absolute top-5 left-[10%] w-4 h-4 text-emerald-400/50 animate-pulse"}),e.jsx(ih,{className:"absolute top-10 right-[12%] w-5 h-5 text-amber-400/50 animate-pulse delay-150"}),e.jsx(un,{className:"absolute top-8 left-[45%] w-3 h-3 text-sky-400/40 animate-pulse delay-300"})]}),_Ue=()=>e.jsxs("div",{className:"absolute inset-0 overflow-hidden pointer-events-none",children:[e.jsx(Or,{className:"absolute top-6 left-[12%] w-4 h-4 text-teal-400/40 animate-pulse"}),e.jsx(un,{className:"absolute top-10 right-[15%] w-3 h-3 text-emerald-400/50 animate-pulse delay-100"}),e.jsx(Or,{className:"absolute top-4 right-[40%] w-3 h-3 text-cyan-400/30 animate-pulse delay-200"})]}),eCe=[{id:"default",name:"Classic",description:"Clean, professional look for any occasion",icon:e.jsx(un,{className:"h-5 w-5"}),category:"general",headerText:()=>"Video Message",subText:"A personal video just for you",gradientClasses:"from-background to-muted/30",accentColor:"primary"},{id:"thank_you",name:"Thank You",description:"Express your gratitude",icon:e.jsx(gi,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Thank You, ${s}!`:"Thank You!",subText:"Your support means the world to me",gradientClasses:"from-rose-50/70 via-pink-50/50 to-red-50/40 dark:from-rose-950/30 dark:via-pink-950/20 dark:to-red-950/20",accentColor:"rose",decorativeElement:e.jsx(Kss,{})},{id:"thinking_of_you",name:"Thinking of You",description:"Let them know they're on your mind",icon:e.jsx(R7,{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(aF,{})},{id:"check_in",name:"Check-in",description:"Touch base with your contacts",icon:e.jsx(ey,{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(Zss,{})},{id:"market_update",name:"Market Update",description:"Share real estate market insights",icon:e.jsx(_o,{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(An,{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(aF,{})},{id:"congratulations",name:"Congratulations",description:"Celebrate their achievements",icon:e.jsx(fc,{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(bUe,{})},{id:"welcome_neighborhood",name:"Welcome to the Neighborhood",description:"Greet new neighbors",icon:e.jsx(ka,{className:"h-5 w-5"}),category:"general",headerText:s=>s?`Welcome to the Neighborhood, ${s}!`:"Welcome to the Neighborhood!",subText:"So excited to have you as our new neighbor",gradientClasses:"from-teal-50/70 via-cyan-50/50 to-sky-50/40 dark:from-teal-950/30 dark:via-cyan-950/20 dark:to-sky-950/20",accentColor:"teal",decorativeElement:e.jsx(_Ue,{})},{id:"just_because",name:"Just Because",description:"No reason needed to connect",icon:e.jsx(aL,{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(aF,{})},{id:"birthday",name:"Birthday",description:"Celebrate their special day",icon:e.jsx(Ah,{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($ss,{})},{id:"valentines_day",name:"Valentine's Day",description:"Show appreciation on this special day",icon:e.jsx(gi,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Valentine's Day, ${s}!`:"Happy Valentine's Day!",subText:"A heartfelt message from your real estate professional",gradientClasses:"from-rose-50/80 via-pink-50/60 to-red-50/40 dark:from-rose-950/30 dark:via-pink-950/20 dark:to-red-950/20",accentColor:"rose",decorativeElement:e.jsx(Uss,{})},{id:"groundhog_day",name:"Groundhog Day",description:"A fun seasonal greeting",icon:e.jsx(pb,{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(qss,{})},{id:"new_years",name:"New Year's Day",description:"Ring in the new year",icon:e.jsx(oa,{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(Oss,{})},{id:"easter",name:"Easter",description:"Celebrate the spring season",icon:e.jsx(ZP,{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(Pss,{})},{id:"mothers_day",name:"Mother's Day",description:"Celebrate the amazing moms",icon:e.jsx(rb,{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(Mss,{})},{id:"fathers_day",name:"Father's Day",description:"Celebrate the amazing dads",icon:e.jsx(fc,{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(Iss,{})},{id:"memorial_day",name:"Memorial Day",description:"Honor those who served",icon:e.jsx(V2,{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(Ess,{})},{id:"independence_day",name:"4th of July",description:"Celebrate Independence Day",icon:e.jsx(Hc,{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(Ass,{})},{id:"labor_day",name:"Labor Day",description:"Celebrate the workers",icon:e.jsx(fc,{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(Bss,{})},{id:"halloween",name:"Halloween",description:"Spooky seasonal greetings",icon:e.jsx(wA,{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(Lss,{})},{id:"thanksgiving",name:"Thanksgiving",description:"Express gratitude this season",icon:e.jsx(gi,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Thanksgiving, ${s}!`:"Happy Thanksgiving!",subText:"Grateful for you and your friendship",gradientClasses:"from-orange-50/70 via-amber-50/50 to-red-50/40 dark:from-orange-950/30 dark:via-amber-950/20 dark:to-red-950/20",accentColor:"orange",decorativeElement:e.jsx(Rss,{})},{id:"christmas",name:"Christmas",description:"Spread holiday cheer",icon:e.jsx(s4,{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(Dss,{})},{id:"hanukkah",name:"Hanukkah",description:"Celebrate the Festival of Lights",icon:e.jsx(un,{className:"h-5 w-5"}),category:"holidays",headerText:s=>s?`Happy Hanukkah, ${s}!`:"Happy Hanukkah!",subText:"Wishing you eight nights of light and joy",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-sky-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-sky-950/20",accentColor:"blue",decorativeElement:e.jsx(Fss,{})},{id:"st_patricks_day",name:"St. Patrick's Day",description:"Celebrate the luck of the Irish",icon:e.jsx(P2,{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(zss,{})},{id:"home_anniversary",name:"Home Anniversary",description:"Celebrate their home ownership milestone",icon:e.jsx(Or,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Happy Home Anniversary, ${s}!`:"Happy Home Anniversary!",subText:"Celebrating another year in your beautiful home",gradientClasses:"from-teal-50/70 via-cyan-50/50 to-emerald-50/40 dark:from-teal-950/30 dark:via-cyan-950/20 dark:to-emerald-950/20",accentColor:"teal",decorativeElement:e.jsx(Vss,{})},{id:"under_contract",name:"Under Contract",description:"Celebrate this exciting milestone",icon:e.jsx(ih,{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(Hss,{})},{id:"just_listed",name:"Just Listed",description:"Announce a new listing",icon:e.jsx(yr,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Exciting News, ${s}!`:"Just Listed!",subText:"A new property is now on the market",gradientClasses:"from-blue-50/70 via-indigo-50/50 to-violet-50/40 dark:from-blue-950/30 dark:via-indigo-950/20 dark:to-violet-950/20",accentColor:"blue",decorativeElement:e.jsx(_Ue,{})},{id:"just_sold",name:"Just Sold",description:"Celebrate a successful sale",icon:e.jsx(Yl,{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(aF,{})},{id:"price_reduction",name:"Price Reduction",description:"Notify about a price change",icon:e.jsx(fb,{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(hw,{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(Yss,{})},{id:"closing_day",name:"Closing Day",description:"Celebrate their closing day",icon:e.jsx(Ug,{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(Gss,{})},{id:"move_in_day",name:"Move-in Day",description:"Welcome them to their new home",icon:e.jsx(Or,{className:"h-5 w-5"}),category:"transactional",headerText:s=>s?`Welcome Home, ${s}!`:"Welcome Home!",subText:"Wishing you all the best in your new home",gradientClasses:"from-teal-50/70 via-emerald-50/50 to-green-50/40 dark:from-teal-950/30 dark:via-emerald-950/20 dark:to-green-950/20",accentColor:"teal",decorativeElement:e.jsx(Wss,{})},{id:"offer_accepted",name:"Offer Accepted",description:"Celebrate their accepted offer",icon:e.jsx($m,{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(aF,{})},{id:"pre_approval",name:"Pre-Approval Congrats",description:"Congratulate on pre-approval",icon:e.jsx(fc,{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(bUe,{})}],Qss=[{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 Xss(s){return eCe.filter(t=>t.category===s)}function SL(s){return eCe.find(t=>t.id===s)||eCe[0]}function wUe(){const{shareToken:s,recipientToken:t}=bi(),[n,r]=N.useState(null),[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!0),[u,h]=N.useState(null),[p,f]=N.useState(!0),y=N.useRef(null),_=N.useRef(0),v=N.useRef(0),j=(()=>{const Z=new URLSearchParams(window.location.search);return t||Z.get("rt")||null})(),w=N.useCallback((Z,Y=!1)=>{if(!j||Z<=0)return;const W=Math.max(1,Math.round(Z));if(W<=v.current)return;const se=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${encodeURIComponent(j)}&e=watch&ws=${W}`;Y&&navigator.sendBeacon?navigator.sendBeacon(se):fetch(se,{method:"GET",keepalive:Y}).catch(()=>{}),v.current=Math.max(v.current,W)},[j]);N.useEffect(()=>{var he;if(!p||!(n!=null&&n.playback_url)||!j)return;let Z=!1;const Y=()=>{_.current>0&&w(_.current,!0)},W=()=>{document.visibilityState==="hidden"&&Y()},ee=()=>{Y()},se=()=>{var me;if(Z||!y.current||!((me=window.playerjs)!=null&&me.Player))return;const ce=new window.playerjs.Player(y.current);ce.on("timeupdate",le=>{const ve=Math.floor(Number((le==null?void 0:le.seconds)??0));!Number.isFinite(ve)||ve<=0||(_.current=Math.max(_.current,ve))}),ce.on("pause",()=>{_.current>0&&w(_.current)}),ce.on("ended",()=>{_.current>0&&w(_.current,!0)})},oe=document.querySelector('script[data-bunny-playerjs="true"]');if((he=window.playerjs)!=null&&he.Player)se();else if(oe)oe.addEventListener("load",se,{once:!0});else{const ce=document.createElement("script");ce.src="https://assets.mediadelivery.net/playerjs/playerjs-latest.min.js",ce.async=!0,ce.defer=!0,ce.dataset.bunnyPlayerjs="true",ce.onload=se,document.body.appendChild(ce)}return document.addEventListener("visibilitychange",W),window.addEventListener("beforeunload",ee),()=>{Z=!0,document.removeEventListener("visibilitychange",W),window.removeEventListener("beforeunload",ee),Y()}},[p,n==null?void 0:n.playback_url,j,w]),N.useEffect(()=>{_.current=0,v.current=0},[j,s]),N.useEffect(()=>{const Z=()=>{['[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(se=>{document.querySelectorAll(se).forEach(oe=>{oe.style.display="none"})})};Z();const Y=[setTimeout(Z,500),setTimeout(Z,1500),setTimeout(Z,3e3)],W=new MutationObserver(Z);return W.observe(document.body,{childList:!0,subtree:!0}),()=>{Y.forEach(clearTimeout),W.disconnect()}},[]),N.useEffect(()=>{(async()=>{if(!s){h("Invalid share link"),d(!1);return}const{data:Y,error:W}=await q.from("agent_videos").select("id, title, playback_url, thumbnail_url, preview_url, duration_seconds, share_token, owner_user_id, contact_id, page_template, recipient_name").eq("share_token",s).eq("is_deleted",!1).single();if(W||!Y){h("Video not found or has been removed"),d(!1);return}r(Y);try{await q.rpc("log_video_view",{p_video_id:Y.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch(ee){console.warn("Failed to log video view:",ee)}if(Y.owner_user_id){const{data:ee}=await q.from("profiles").select("id, name, email, phone").eq("id",Y.owner_user_id).single();if(ee){i(ee);try{const{data:se}=await q.storage.from("avatars").list(`${Y.owner_user_id}`);if(se&&se.length>0){const{data:oe}=q.storage.from("avatars").getPublicUrl(`${Y.owner_user_id}/${se[0].name}`);o(oe.publicUrl)}}catch{}}}d(!1)})()},[s]);const S=Z=>{if(!Z)return"0:00";const Y=Math.floor(Z/60),W=Z%60;return`${Y}:${W.toString().padStart(2,"0")}`},A=Z=>Z.includes("iframe.mediadelivery.net/play/")?Z.replace("/play/","/embed/")+"?autoplay=true&responsive=true":Z,E=Z=>{if(!Z)return"?";const Y=Z.split(" ");return Y.length>=2?`${Y[0][0]}${Y[1][0]}`.toUpperCase():Z.substring(0,2).toUpperCase()},O=SL((n==null?void 0:n.page_template)||"default"),D=(n==null?void 0:n.recipient_name)||null,I=O.headerText(D),z=`https://dashboard.relevelup.com/share/video/${s}`;if(c)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-primary"})});if(u||!n)return e.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center p-4",children:e.jsx(fe,{className:"max-w-md w-full",children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Video Not Found"}),e.jsx("p",{className:"text-muted-foreground",children:u||"This video is no longer available."})]})})});const H=O.id!=="default";return e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{children:[e.jsx("title",{children:I}),e.jsx("meta",{name:"description",content:O.subText}),e.jsx("meta",{property:"og:title",content:I}),e.jsx("meta",{property:"og:description",content:O.subText}),e.jsx("meta",{property:"og:type",content:"video.other"}),e.jsx("meta",{property:"og:url",content:z}),n.preview_url&&e.jsx("meta",{property:"og:image",content:n.preview_url}),!n.preview_url&&n.thumbnail_url&&e.jsx("meta",{property:"og:image",content:n.thumbnail_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{property:"og:video",content:n.playback_url}),e.jsx("meta",{property:"og:video:type",content:"text/html"}),e.jsx("meta",{property:"og:video:width",content:"1280"}),e.jsx("meta",{property:"og:video:height",content:"720"})]}),e.jsx("meta",{name:"twitter:card",content:"player"}),e.jsx("meta",{name:"twitter:title",content:I}),e.jsx("meta",{name:"twitter:description",content:O.subText}),n.preview_url&&e.jsx("meta",{name:"twitter:image",content:n.preview_url}),n.playback_url&&e.jsxs(e.Fragment,{children:[e.jsx("meta",{name:"twitter:player",content:n.playback_url}),e.jsx("meta",{name:"twitter:player:width",content:"1280"}),e.jsx("meta",{name:"twitter:player:height",content:"720"})]})]}),e.jsxs("div",{className:Mt("min-h-screen flex items-center justify-center p-4 bg-gradient-to-b relative",O.gradientClasses),children:[H&&O.decorativeElement,e.jsxs("div",{className:"max-w-2xl w-full space-y-6 relative z-10",children:[H&&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:Mt("w-14 h-14 rounded-full flex items-center justify-center shadow-sm",O.accentColor==="primary"&&"bg-primary/10 text-primary",O.accentColor==="amber"&&"bg-amber-100 text-amber-600 dark:bg-amber-900/50 dark:text-amber-400",O.accentColor==="teal"&&"bg-teal-100 text-teal-600 dark:bg-teal-900/50 dark:text-teal-400",O.accentColor==="rose"&&"bg-rose-100 text-rose-600 dark:bg-rose-900/50 dark:text-rose-400",O.accentColor==="emerald"&&"bg-emerald-100 text-emerald-600 dark:bg-emerald-900/50 dark:text-emerald-400",O.accentColor==="yellow"&&"bg-yellow-100 text-yellow-600 dark:bg-yellow-900/50 dark:text-yellow-400",O.accentColor==="pink"&&"bg-pink-100 text-pink-600 dark:bg-pink-900/50 dark:text-pink-400",O.accentColor==="blue"&&"bg-blue-100 text-blue-600 dark:bg-blue-900/50 dark:text-blue-400",O.accentColor==="red"&&"bg-red-100 text-red-600 dark:bg-red-900/50 dark:text-red-400",O.accentColor==="orange"&&"bg-orange-100 text-orange-600 dark:bg-orange-900/50 dark:text-orange-400",O.accentColor==="green"&&"bg-green-100 text-green-600 dark:bg-green-900/50 dark:text-green-400",O.accentColor==="violet"&&"bg-violet-100 text-violet-600 dark:bg-violet-900/50 dark:text-violet-400",O.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:O.icon})})}),e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold mb-2",children:I}),e.jsx("p",{className:"text-muted-foreground",children:O.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(Jr,{className:"h-14 w-14 border-2 border-primary/20",children:[e.jsx(ti,{src:l||void 0,alt:a.name||"Agent"}),e.jsx(ea,{className:"bg-primary/10 text-primary font-semibold",children:E(a.name)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:H?"A special video from":"A personal video from"}),e.jsx("h2",{className:"text-lg font-semibold truncate",children:a.name||"Your Agent"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your Real Estate Professional"})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[a.phone&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`tel:${a.phone}`,"aria-label":"Call agent",children:e.jsx(Cr,{className:"h-4 w-4"})})}),a.email&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,className:"h-10 w-10",children:e.jsx("a",{href:`mailto:${a.email}`,"aria-label":"Email agent",children:e.jsx(Gs,{className:"h-4 w-4"})})})]})]}),e.jsx(fe,{className:"overflow-hidden shadow-lg",children:p&&n.playback_url?e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:e.jsx("iframe",{ref:y,src:A(n.playback_url),title:n.title||"Video message",className:"absolute top-0 left-0 w-full h-full",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})}):e.jsxs("div",{className:"relative aspect-video bg-muted cursor-pointer group",onClick:()=>f(!0),children:[n.preview_url||n.thumbnail_url?e.jsx("img",{src:n.preview_url||n.thumbnail_url||"",alt:n.title?`${n.title} video preview`:"Video message preview",className:"w-full h-full object-cover",onError:Z=>{var W;Z.currentTarget.style.display="none";const Y=(W=Z.currentTarget.parentElement)==null?void 0:W.querySelector(".video-fallback");Y&&(Y.style.display="flex")}}):null,e.jsx("div",{className:"video-fallback w-full h-full items-center justify-center bg-gradient-to-br from-primary/20 to-primary/5",style:{display:n.preview_url||n.thumbnail_url?"none":"flex"},children:e.jsx(fr,{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(El,{className:"h-10 w-10 text-primary ml-1"})})}),n.duration_seconds&&e.jsx("div",{className:"absolute bottom-3 right-3 bg-black/70 text-white text-sm px-2 py-1 rounded",children:S(n.duration_seconds)})]})}),!H&&e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.title||"Video Message"}),e.jsx("p",{className:"text-muted-foreground mt-2",children:p?"Enjoy the video!":"Click to play the video"})]}),!p&&e.jsx("div",{className:"flex justify-center",children:e.jsxs(B,{size:"lg",onClick:()=>f(!0),className:"gap-2",children:[e.jsx(El,{className:"h-5 w-5"}),"Watch Video"]})}),e.jsx(Tss,{shareToken:s,agentName:(a==null?void 0:a.name)||null,hasContact:!!n.contact_id})]})]})]})}function Jss(){return N.useEffect(()=>(document.body.classList.add("video-landing-page"),()=>{document.body.classList.remove("video-landing-page")}),[]),e.jsx(lat,{})}function ens(){const{token:s}=bi();return N.useEffect(()=>{if(!s)return;const t=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/video-og-image?token=${s}`;window.location.replace(t)},[s]),e.jsx("main",{className:"min-h-screen bg-background flex items-center justify-center",children:e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsx(rs,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{children:"Loading video preview…"})]})})}const tns={office_exclusive:"Office Exclusive",coming_soon:"Coming Soon",pre_market:"Pre-Market",active:"Active"},sns=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s||0);function nns(){var ve;const[s]=xl(),t=s.get("r"),n=s.get("m"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!0),[d,u]=N.useState(0),[h,p]=N.useState(!1),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState(""),[E,O]=N.useState("tour"),[D,I]=N.useState(!1),[F,z]=N.useState(!1),H=async()=>{if(!f.trim()||!_.trim()){ae.error("Please enter your name and email");return}I(!0);try{const Te=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-lead",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({r:t,m:n,name:f.trim(),email:_.trim(),phone:j.trim()||null,message:S.trim()||null,intent:E})}),Ie=await Te.json();if(!Te.ok||!(Ie!=null&&Ie.success))throw new Error((Ie==null?void 0:Ie.error)||"Could not send");z(!0),ae.success("Sent! The agent will be in touch shortly.")}catch(ge){ae.error((ge==null?void 0:ge.message)||"Could not send")}finally{I(!1)}};if(N.useEffect(()=>{if(!t||!n){l("Invalid link"),c(!1);return}const ge=`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/private-listing-view?r=${encodeURIComponent(t)}&m=${encodeURIComponent(n)}`;fetch(ge).then(Te=>Te.json()).then(Te=>{Te.error?l("This private listing link is no longer valid."):a({listing:Te.listing,agent:Te.agent})}).catch(()=>l("Unable to load listing.")).finally(()=>c(!1))},[t,n]),o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50",children:e.jsx("div",{className:"text-slate-500",children:"Loading…"})});if(i||!r)return e.jsxs(e.Fragment,{children:[e.jsx(Zo,{children:e.jsx("meta",{name:"robots",content:"noindex,nofollow,noarchive"})}),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-slate-50 px-6 text-center",children:e.jsxs("div",{children:[e.jsx(Gc,{className:"h-10 w-10 text-slate-400 mx-auto mb-3"}),e.jsx("h1",{className:"text-xl font-semibold text-slate-900",children:"Private listing unavailable"}),e.jsx("p",{className:"text-slate-600 mt-2",children:i||"This link has expired or was not shared with you."})]})})]});const{listing:Z,agent:Y}=r,W=(ve=Z.photos)!=null&&ve.length?Z.photos:[],ee=W[0],se=tns[Z.status]||Z.status,oe=(Y==null?void 0:Y.sender_name)||(Y==null?void 0:Y.name)||"Your Agent",he=(Y==null?void 0:Y.sender_email)||null,ce=encodeURIComponent(`Interested in ${Z.address}`),me=encodeURIComponent(`Hi ${oe}, I'd love to learn more about ${Z.address}, ${Z.city}. Thanks!`),le=Y!=null&&Y.booking_slug?`https://dashboard.relevelup.com/book/${Y.booking_slug}`:null;return e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{children:[e.jsxs("title",{children:["Private Listing · ",Z.address]}),e.jsx("meta",{name:"robots",content:"noindex,nofollow,noarchive,nosnippet"}),e.jsx("meta",{name:"googlebot",content:"noindex,nofollow,noarchive,nosnippet"})]}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 text-white text-center text-xs sm:text-sm py-2 px-4 flex items-center justify-center gap-2",children:[e.jsx(Gc,{className:"h-3.5 w-3.5"}),e.jsxs("span",{className:"font-medium tracking-wide uppercase",children:["Private listing · Shared by ",oe]})]}),e.jsxs("div",{className:"relative",children:[ee?e.jsx("button",{type:"button",className:"block w-full",onClick:()=>{u(0),p(!0)},children:e.jsx("img",{src:ee,alt:Z.address,className:"w-full h-[42vh] md:h-[60vh] object-cover"})}):e.jsx("div",{className:"w-full h-[42vh] md:h-[60vh] bg-slate-200 flex items-center justify-center text-slate-400",children:"No photos available"}),e.jsx("div",{className:"absolute top-4 left-4",children:e.jsx(Ue,{className:"bg-indigo-600 text-white border-0 text-xs px-2.5 py-1 shadow",children:se})}),W.length>1&&e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white text-xs px-2.5 py-1 rounded-full",children:[W.length," photos"]})]}),e.jsxs("div",{className:"max-w-5xl mx-auto px-4 sm:px-6 -mt-10 relative z-10",children:[e.jsx(fe,{className:"shadow-xl border-slate-200",children:e.jsxs(Ee,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl sm:text-3xl font-bold text-slate-900",children:Z.address}),e.jsxs("p",{className:"text-slate-600 mt-1 flex items-center gap-1.5",children:[e.jsx(ka,{className:"h-4 w-4"}),Z.city,", ",Z.state," ",Z.zip]})]}),e.jsx("div",{className:"text-right",children:e.jsx("p",{className:"text-3xl sm:text-4xl font-bold text-indigo-600",children:sns(Z.price)})})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 mt-6",children:[Z.bedrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(J0,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:Z.bedrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Beds"})]}):null,Z.bathrooms?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(kp,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:Z.bathrooms}),e.jsx("p",{className:"text-xs text-slate-500",children:"Baths"})]}):null,Z.sqft?e.jsxs("div",{className:"bg-slate-50 rounded-lg p-3 text-center",children:[e.jsx(ay,{className:"h-5 w-5 mx-auto text-slate-500 mb-1"}),e.jsx("p",{className:"text-lg font-semibold text-slate-900",children:Z.sqft.toLocaleString()}),e.jsx("p",{className:"text-xs text-slate-500",children:"Sq Ft"})]}):null]}),Z.description&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-2",children:"About this property"}),e.jsx("p",{className:"text-slate-700 leading-relaxed whitespace-pre-line",children:Z.description})]}),W.length>1&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h2",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Photos"}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:W.slice(0,9).map((ge,Te)=>e.jsx("button",{type:"button",onClick:()=>{u(Te),p(!0)},className:"aspect-[4/3] overflow-hidden rounded-lg bg-slate-100",children:e.jsx("img",{src:ge,alt:"",className:"w-full h-full object-cover hover:scale-105 transition"})},Te))})]})]})}),e.jsxs(fe,{className:"mt-6 shadow-lg border-slate-200 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-indigo-600 to-indigo-500 px-6 py-4 text-white",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Request more info or a private tour"}),e.jsxs("p",{className:"text-indigo-100 text-sm",children:[oe," will get back to you personally."]})]}),e.jsx(Ee,{className:"p-6 sm:p-8",children:F?e.jsxs("div",{className:"flex flex-col items-center text-center py-6",children:[e.jsx(vr,{className:"h-12 w-12 text-emerald-500 mb-3"}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Message sent"}),e.jsxs("p",{className:"text-slate-600 mt-1",children:[oe," just got your request and will reach out shortly."]})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{id:"tour",label:"Private tour"},{id:"info",label:"More info"},{id:"offer",label:"Make an offer"}].map(ge=>e.jsx("button",{type:"button",onClick:()=>O(ge.id),className:`px-3 py-2 rounded-lg border text-sm font-medium transition ${E===ge.id?"bg-indigo-600 text-white border-indigo-600":"bg-white text-slate-700 border-slate-200 hover:border-indigo-300"}`,children:ge.label},ge.id))}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pl-name",children:"Your name *"}),e.jsx(ye,{id:"pl-name",value:f,onChange:ge=>y(ge.target.value),placeholder:"Jane Doe",maxLength:120})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pl-email",children:"Email *"}),e.jsx(ye,{id:"pl-email",type:"email",value:_,onChange:ge=>v(ge.target.value),placeholder:"you@email.com",maxLength:255})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pl-phone",children:"Phone (optional)"}),e.jsx(ye,{id:"pl-phone",value:j,onChange:ge=>w(ge.target.value),placeholder:"(555) 555-5555",maxLength:40})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"pl-msg",children:"Message (optional)"}),e.jsx(Ms,{id:"pl-msg",value:S,onChange:ge=>A(ge.target.value),placeholder:`I'd love to see ${Z.address}…`,rows:4,maxLength:2e3})]}),e.jsx(B,{onClick:H,disabled:D,className:"w-full bg-indigo-600 hover:bg-indigo-700 h-11 text-base",children:D?"Sending…":"Send to "+oe.split(" ")[0]}),e.jsx("p",{className:"text-xs text-slate-500 text-center",children:"By submitting, you agree to be contacted about this property."})]})})]}),e.jsx(fe,{className:"mt-6 mb-12 shadow-lg border-slate-200",children:e.jsxs(Ee,{className:"p-6 sm:p-8",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-center sm:items-start gap-5",children:[Y!=null&&Y.avatar_url?e.jsx("img",{src:Y.avatar_url,alt:oe,className:"h-20 w-20 rounded-full object-cover ring-2 ring-indigo-100"}):e.jsx("div",{className:"h-20 w-20 rounded-full bg-indigo-100 flex items-center justify-center text-indigo-600 text-2xl font-bold",children:oe.charAt(0)}),e.jsxs("div",{className:"flex-1 text-center sm:text-left",children:[e.jsx("p",{className:"text-xs uppercase tracking-wider text-slate-500",children:"Shared by"}),e.jsx("h3",{className:"text-xl font-bold text-slate-900",children:oe}),(Y==null?void 0:Y.brokerage_name)&&e.jsx("p",{className:"text-slate-600 text-sm",children:Y.brokerage_name}),e.jsx("p",{className:"text-slate-600 text-sm mt-2",children:"Want a private tour or more info? Reach out — I'm happy to help."})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2 mt-6",children:[he&&e.jsx(B,{asChild:!0,className:"bg-indigo-600 hover:bg-indigo-700",children:e.jsxs("a",{href:`mailto:${he}?subject=${ce}&body=${me}`,children:[e.jsx(Gs,{className:"h-4 w-4 mr-1.5"}),"Email"]})}),(Y==null?void 0:Y.phone)&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:`tel:${Y.phone}`,children:[e.jsx(Cr,{className:"h-4 w-4 mr-1.5"}),Y.phone]})}),le&&e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs("a",{href:le,target:"_blank",rel:"noreferrer",children:[e.jsx(Xf,{className:"h-4 w-4 mr-1.5"}),"Book a tour"]})})]})]})})]}),h&&W.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",children:[e.jsx("button",{className:"absolute top-4 right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>p(!1),"aria-label":"Close",children:e.jsx($n,{className:"h-6 w-6"})}),e.jsx("button",{className:"absolute left-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(ge=>(ge-1+W.length)%W.length),"aria-label":"Previous",children:e.jsx(ml,{className:"h-8 w-8"})}),e.jsx("img",{src:W[d],alt:"",className:"max-w-[90vw] max-h-[85vh] object-contain"}),e.jsx("button",{className:"absolute right-4 text-white p-2 hover:bg-white/10 rounded-full",onClick:()=>u(ge=>(ge+1)%W.length),"aria-label":"Next",children:e.jsx(ga,{className:"h-8 w-8"})}),e.jsxs("p",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 text-white/80 text-sm",children:[d+1," / ",W.length]})]})]})]})}function rns(){var i;const{slug:s}=bi(),{data:t,isLoading:n,error:r}=Hlt(s);if(N.useEffect(()=>(document.body.classList.add("agent-card-page"),()=>{document.body.classList.remove("agent-card-page")}),[]),N.useEffect(()=>{t!=null&&t.id&&hl(t.id,"card_view")},[t==null?void 0:t.id]),n)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center",children:e.jsxs("div",{className:"w-full max-w-md mx-auto p-6 space-y-6",children:[e.jsxs("div",{className:"flex flex-col items-center gap-4",children:[e.jsx(Ws,{className:"h-28 w-28 rounded-full"}),e.jsx(Ws,{className:"h-6 w-48"}),e.jsx(Ws,{className:"h-4 w-36"})]}),e.jsx(Ws,{className:"h-12 w-full"}),e.jsx(Ws,{className:"h-12 w-full"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Card Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This agent card doesn't exist or isn't published yet."})]})});const a=((i=t.profile)==null?void 0:i.name)||"Agent";return e.jsxs(e.Fragment,{children:[e.jsxs(Zo,{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(DAe,{card:t})]})}const ans="https://images.unsplash.com/photo-1507525428034-b723cf961d3e?w=1600&q=80",ins="https://images.unsplash.com/photo-1616486338812-3dadae4b4ace?w=1600&q=80",ons="https://images.unsplash.com/photo-1500534314209-a25ddb2bd429?w=1600&q=80",lns="https://images.unsplash.com/photo-1600585154340-be6161a56a0c?w=1600&q=80",cns="https://images.unsplash.com/photo-1519741497674-611481863552?w=1600&q=80",dns="https://images.unsplash.com/photo-1494526585095-c41746248156?w=1600&q=80",Ime={"minimal-mono":{key:"minimal-mono",label:"Minimal Mono",description:"Clean paper white, restrained.",bg:"#f7f7f5",surface:"#ffffff",border:"#e6e5e0",text:"#111111",textMuted:"#6b6b6b",accent:"#111111",accentText:"#ffffff",headingFont:'"Fraunces", ui-serif, Georgia, serif',bodyFont:'"Inter", system-ui, sans-serif',swatch:["#f7f7f5","#111111","#6b6b6b","#e6e5e0"],defaultCover:dns},"warm-coastal":{key:"warm-coastal",label:"Warm Coastal",description:"Sand and soft teal.",bg:"linear-gradient(180deg,#faf6ef 0%,#f2ece1 100%)",surface:"#ffffff",border:"#e6dfd1",text:"#2b2a26",textMuted:"#7a746a",accent:"#2f7a7d",accentText:"#ffffff",headingFont:'"Cormorant Garamond", ui-serif, Georgia, serif',bodyFont:'"Karla", system-ui, sans-serif',swatch:["#faf6ef","#2f7a7d","#c9b99a","#2b2a26"],defaultCover:ans},"deep-luxe":{key:"deep-luxe",label:"Deep Luxe",description:"Charcoal with gold.",bg:"linear-gradient(180deg,#161616 0%,#0d0d0d 100%)",surface:"#1e1e1e",border:"#2c2c2c",text:"#f5f0e0",textMuted:"#a49a80",accent:"#c9a84c",accentText:"#111111",headingFont:'"Instrument Serif", ui-serif, Georgia, serif',bodyFont:'"Work Sans", system-ui, sans-serif',swatch:["#0d0d0d","#c9a84c","#f5f0e0","#2c2c2c"],defaultCover:ins},sunset:{key:"sunset",label:"Sunset",description:"Peach into magenta.",bg:"linear-gradient(160deg,#ffe4d1 0%,#ffc9b0 40%,#f2a1c5 100%)",surface:"#ffffff",border:"#f6d5ce",text:"#2a1a2f",textMuted:"#7a5a70",accent:"#d84a7a",accentText:"#ffffff",headingFont:'"Sora", system-ui, sans-serif',bodyFont:'"Manrope", system-ui, sans-serif',swatch:["#ffe4d1","#ffc9b0","#f2a1c5","#d84a7a"],defaultCover:ons},editorial:{key:"editorial",label:"Editorial",description:"Ink black on paper white.",bg:"#f5f3ee",surface:"#ffffff",border:"#d9d6ce",text:"#0d0d0d",textMuted:"#5a564d",accent:"#0d0d0d",accentText:"#f5f3ee",headingFont:'"DM Serif Display", ui-serif, Georgia, serif',bodyFont:'"Fira Sans", system-ui, sans-serif',swatch:["#f5f3ee","#0d0d0d","#d9d6ce","#5a564d"],defaultCover:lns},playful:{key:"playful",label:"Playful",description:"Blush and lavender.",bg:"linear-gradient(180deg,#fdf3f7 0%,#efe5ff 100%)",surface:"#ffffff",border:"#ecd7e6",text:"#3a2450",textMuted:"#7c6a94",accent:"#9b72cf",accentText:"#ffffff",headingFont:'"Outfit", system-ui, sans-serif',bodyFont:'"Figtree", system-ui, sans-serif',swatch:["#fdf3f7","#efe5ff","#c9a0dc","#9b72cf"],defaultCover:cns}},uns=["#111111","#2f7a7d","#c9a84c","#d84a7a","#3b6fa0","#9b72cf","#e85d3a","#4a6741"];function jmt(s){return s&&s in Ime?Ime[s]:Ime["minimal-mono"]}function hns(s,t){const n=t||s.accent;return{background:s.bg,color:s.text,fontFamily:s.bodyFont,"--c-bg":s.bg,"--c-surface":s.surface,"--c-border":s.border,"--c-text":s.text,"--c-text-muted":s.textMuted,"--c-accent":n,"--c-accent-text":s.accentText,"--c-heading-font":s.headingFont,"--c-body-font":s.bodyFont}}function Nmt({slugOverride:s}={}){var Qs;const{slug:t}=bi(),n=s||t,[r]=xl(),a=r.get("t"),[i,l]=N.useState(!0),[o,c]=N.useState(null),[d,u]=N.useState(null),h=N.useRef(null),p=N.useRef(null),[f,y]=N.useState(null),[_,v]=N.useState(null),[j,w]=N.useState(!1),[S,A]=N.useState(!1),[E,O]=N.useState(0),[D,I]=N.useState(!1),[F,z]=N.useState(""),[H,Z]=N.useState(""),[Y,W]=N.useState(""),[ee,se]=N.useState(""),[oe,he]=N.useState(""),[ce,me]=N.useState(""),[le,ve]=N.useState(""),[ge,Te]=N.useState(""),[Ie,Ce]=N.useState(""),[Me,Pe]=N.useState(""),[Re,Ae]=N.useState(""),[Be,we]=N.useState(""),[Je,ke]=N.useState(""),[it,je]=N.useState([]),[He,$e]=N.useState([]),[Ke,Ge]=N.useState(""),[rt,tt]=N.useState(""),[at,Ye]=N.useState(""),[ut,_t]=N.useState([]);N.useEffect(()=>{bt()},[n,a]);const bt=async()=>{if(!n)return;l(!0);const{data:ks,error:$s}=await q.from("contact_intake_pages").select("*").eq("slug",n).eq("is_active",!0).maybeSingle();if($s||!ks){I(!0),l(!1);return}u(ks),p.current=ks;const{data:an}=await q.from("profiles").select("name, avatar_url, title, phone, email, brokerage_id").eq("id",ks.user_id).single();if(an){let tn;if(an.brokerage_id){const{data:Pn}=await q.from("brokerages").select("name").eq("id",an.brokerage_id).single();tn=(Pn==null?void 0:Pn.name)||void 0}let er=an.avatar_url||null;if(!er){const{data:Pn}=q.storage.from("avatars").getPublicUrl(`${ks.user_id}/avatar.jpg`);Pn!=null&&Pn.publicUrl&&(er=`${Pn.publicUrl}?t=${Date.now()}`)}const xn={...an,avatar_url:er,brokerage_name:tn};c(xn),h.current=xn}if(a)try{console.log("[ConnectPage] Resolving token:",a,"for page:",ks.id);const{data:tn,error:er}=await q.functions.invoke("process-intake-submissions",{body:{action:"resolve_token",token:a,page_id:ks.id}});if(console.log("[ConnectPage] Resolve result:",{resolved:tn,resolveErr:er}),!er&&(tn!=null&&tn.contact_id)){v(tn.contact_id);const xn=tn.contact;xn&&(y(xn),z(xn.first_name||""),Z(xn.last_name||""),W(xn.email||""),se(xn.phone||""),he(xn.address||""),me(xn.city||""),ve(xn.state||""),Te(xn.zip||""),Ce(xn.birthday||""),Pe(xn.home_anniversary||""))}}catch(tn){console.error("Failed to resolve token:",tn)}l(!1)},$t=async()=>{var ks,$s;if(!F.trim()){ae.error("Please enter your first name");return}if(!n){ae.error("Invalid page. Please refresh.");return}A(!0);try{let an=(ks=p.current)==null?void 0:ks.id,tn=($s=p.current)==null?void 0:$s.user_id;if(!an||!tn){const{data:Pn}=await q.from("contact_intake_pages").select("id, user_id").eq("slug",n).eq("is_active",!0).maybeSingle();if(!Pn){ae.error("This page is no longer active. Please contact the agent directly."),A(!1);return}an=Pn.id,tn=Pn.user_id}const er={intake_page_id:an,agent_user_id:tn,existing_contact_id:_,first_name:F.trim(),last_name:H.trim()||null,email:Y.trim()||null,phone:ee.trim()||null,address:oe.trim()||null,city:ce.trim()||null,state:le.trim()||null,zip:ge.trim()||null,birthday:Ie||null,home_anniversary:Me||null,real_estate_interest:Re||null,message:Be.trim()||null,life_events:{spouse_name:Je.trim()||null,kids:it.filter(Pn=>Pn.name.trim()),pets:He.filter(Pn=>Pn.name.trim()),favorite_spots:Ke.trim()||null,dream_neighborhood:rt.trim()||null,wedding_anniversary:at||null},referrals:ut.filter(Pn=>Pn.name.trim()&&Pn.contact.trim())},{error:xn}=await q.from("contact_intake_submissions").insert(er);if(console.log("[ConnectPage] Insert result:",{error:xn}),xn)throw xn;a&&await q.from("contact_intake_tokens").update({used_at:new Date().toISOString()}).eq("token",a);try{const Pn=[F.trim(),H.trim()].filter(Boolean).join(" ");await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/connect-page-notify",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentUserId:tn,contactName:Pn,contactEmail:Y.trim()||null,contactPhone:ee.trim()||null,slug:n})})}catch(Pn){console.warn("Connect page notification failed (non-blocking):",Pn)}w(!0)}catch(an){console.error(an),ae.error("Something went wrong. Please try again.")}finally{A(!1)}};if(i)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-slate-400"})});if(D)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50",children:e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("h1",{className:"text-2xl font-semibold text-slate-700",children:"Page Not Found"}),e.jsx("p",{className:"text-slate-500",children:"This connect page doesn't exist or is no longer active."})]})});if(j)return e.jsxs("div",{className:"min-h-screen flex items-center justify-center bg-gradient-to-br from-slate-50 via-white to-blue-50 p-4",children:[e.jsx(Zo,{children:e.jsxs("title",{children:["Thank You | ",o==null?void 0:o.name]})}),e.jsxs(Zn.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(Zn.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(vr,{className:"h-10 w-10 text-emerald-600"})}),e.jsx("h1",{className:"text-3xl font-bold text-slate-800",children:"Thank You!"}),e.jsxs("p",{className:"text-lg text-slate-600",children:[o==null?void 0:o.name," has received your info and will be in touch soon."]}),e.jsxs("div",{className:"flex items-center justify-center gap-1 text-sm text-slate-400 pt-4",children:[e.jsx(gi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})]})]});const Yt=!!a&&!!f,Ds=(d==null?void 0:d.show_little_things)??!0,Ls=[{title:Yt?"Confirm Your Info":"Let's Get Connected",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"First Name *"}),e.jsx("input",{type:"text",value:F,onChange:ks=>z(ks.target.value),placeholder:"Jane",className:"connect-input",required:!0})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Last Name"}),e.jsx("input",{type:"text",value:H,onChange:ks=>Z(ks.target.value),placeholder:"Smith",className:"connect-input"})]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Email"}),e.jsx("input",{type:"email",value:Y,onChange:ks=>W(ks.target.value),placeholder:"jane@email.com",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Phone"}),e.jsx("input",{type:"tel",value:ee,onChange:ks=>se(ks.target.value),placeholder:"(555) 123-4567",className:"connect-input"})]})]})},{title:"A Little More About You",fields:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Street Address"}),e.jsx("input",{type:"text",value:oe,onChange:ks=>he(ks.target.value),placeholder:"123 Main St",className:"connect-input"})]}),e.jsxs("div",{className:"grid grid-cols-5 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"City"}),e.jsx("input",{type:"text",value:ce,onChange:ks=>me(ks.target.value),placeholder:"Austin",className:"connect-input"})]}),e.jsxs("div",{className:"col-span-1",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"State"}),e.jsx("input",{type:"text",value:le,onChange:ks=>ve(ks.target.value),placeholder:"TX",maxLength:2,className:"connect-input"})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Zip"}),e.jsx("input",{type:"text",value:ge,onChange:ks=>Te(ks.target.value),placeholder:"78701",className:"connect-input"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Birthday"}),e.jsx("input",{type:"date",value:Ie,onChange:ks=>Ce(ks.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Home Anniversary"}),e.jsx("input",{type:"date",value:Me,onChange:ks=>Pe(ks.target.value),className:"connect-input"})]})]})]})},...Ds?[{title:"The Little Things",subtitle:"Optional — helps me remember what matters to you.",fields:e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Spouse / partner's name"}),e.jsx("input",{type:"text",value:Je,onChange:ks=>ke(ks.target.value),placeholder:"Alex",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Wedding anniversary"}),e.jsx("input",{type:"date",value:at,onChange:ks=>Ye(ks.target.value),className:"connect-input"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Kids"}),e.jsxs("button",{type:"button",onClick:()=>je(ks=>[...ks,{name:"",age:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(Is,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[it.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),it.map((ks,$s)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:ks.name,onChange:an=>je(tn=>tn.map((er,xn)=>xn===$s?{...er,name:an.target.value}:er)),placeholder:"Child's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:ks.age,onChange:an=>je(tn=>tn.map((er,xn)=>xn===$s?{...er,age:an.target.value}:er)),placeholder:"Age",className:"connect-input shrink-0",style:{width:"5rem"}}),e.jsx("button",{type:"button",onClick:()=>je(an=>an.filter((tn,er)=>er!==$s)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx($n,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},$s))]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx("label",{className:"block text-sm font-medium",style:{color:"var(--c-text-muted)"},children:"Pets"}),e.jsxs("button",{type:"button",onClick:()=>$e(ks=>[...ks,{name:"",kind:""}]),className:"text-xs inline-flex items-center gap-1",style:{color:"var(--c-accent)"},children:[e.jsx(Is,{className:"h-3 w-3"})," Add"]})]}),e.jsxs("div",{className:"space-y-2",children:[He.length===0&&e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"None to add? Skip this."}),He.map((ks,$s)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:ks.name,onChange:an=>$e(tn=>tn.map((er,xn)=>xn===$s?{...er,name:an.target.value}:er)),placeholder:"Pet's name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:ks.kind,onChange:an=>$e(tn=>tn.map((er,xn)=>xn===$s?{...er,kind:an.target.value}:er)),placeholder:"Dog, cat…",className:"connect-input shrink-0",style:{width:"7rem"}}),e.jsx("button",{type:"button",onClick:()=>$e(an=>an.filter((tn,er)=>er!==$s)),className:"p-2 rounded-md hover:bg-black/5 shrink-0","aria-label":"Remove",children:e.jsx($n,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},$s))]})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Favorite local spots"}),e.jsx("input",{type:"text",value:Ke,onChange:ks=>Ge(ks.target.value),placeholder:"That coffee shop on Main, Town Lake…",className:"connect-input"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:"Dream neighborhood"}),e.jsx("input",{type:"text",value:rt,onChange:ks=>tt(ks.target.value),placeholder:"Where you'd love to live someday",className:"connect-input"})]}),e.jsxs("div",{className:"rounded-xl p-4",style:{background:"color-mix(in srgb, var(--c-accent) 8%, transparent)"},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",style:{color:"var(--c-text)"},children:"Know someone who'd love an agent like me?"}),e.jsx("p",{className:"text-xs",style:{color:"var(--c-text-muted)"},children:"Refer a friend — up to 3."})]}),ut.length<3&&e.jsxs("button",{type:"button",onClick:()=>_t(ks=>[...ks,{name:"",contact:""}]),className:"text-xs inline-flex items-center gap-1 px-2 py-1 rounded-md",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:[e.jsx(Is,{className:"h-3 w-3"})," Add"]})]}),e.jsx("div",{className:"space-y-2",children:ut.map((ks,$s)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx("input",{type:"text",value:ks.name,onChange:an=>_t(tn=>tn.map((er,xn)=>xn===$s?{...er,name:an.target.value}:er)),placeholder:"Their name",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("input",{type:"text",value:ks.contact,onChange:an=>_t(tn=>tn.map((er,xn)=>xn===$s?{...er,contact:an.target.value}:er)),placeholder:"Phone or email",className:"connect-input min-w-0",style:{flex:"1 1 0%"}}),e.jsx("button",{type:"button",onClick:()=>_t(an=>an.filter((tn,er)=>er!==$s)),className:"p-2 rounded-md hover:bg-black/5","aria-label":"Remove",children:e.jsx($n,{className:"h-3.5 w-3.5",style:{color:"var(--c-text-muted)"}})})]},$s))})]})]})}]:[],{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(ks=>e.jsxs("button",{type:"button",onClick:()=>Ae(Re===ks.value?"":ks.value),className:`p-3.5 rounded-xl border-2 text-left transition-all ${Re===ks.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:ks.label}),e.jsx("span",{className:"block text-xs text-slate-500 mt-0.5",children:ks.desc})]},ks.value))})]}),e.jsxs("div",{children:[e.jsxs("label",{className:"block text-sm font-medium mb-1.5",style:{color:"var(--c-text-muted)"},children:["Anything else you'd like to share? ",e.jsx("span",{className:"text-slate-400 font-normal",children:"(optional)"})]}),e.jsx("textarea",{value:Be,onChange:ks=>we(ks.target.value),placeholder:"Feel free to drop a note...",rows:3,className:"connect-input resize-none"})]})]})}],xs=Ls.length,Lt=jmt(d==null?void 0:d.theme),Jt=hns(Lt,(d==null?void 0:d.accent_color)||null),gt=(d==null?void 0:d.cover_image_url)||Lt.defaultCover,zt=(d==null?void 0:d.headline)||"Let's stay connected",As=(d==null?void 0:d.subheadline)||(o!=null&&o.brokerage_name?`${o==null?void 0:o.name} · ${o.brokerage_name}`:(o==null?void 0:o.name)||""),Xt=["deep-luxe"].includes((d==null?void 0:d.theme)||"");return e.jsxs("div",{className:"min-h-screen connect-shell",style:Jt,children:[e.jsxs(Zo,{children:[e.jsxs("title",{children:["Connect with ",(o==null?void 0:o.name)||"Agent"]}),e.jsx("meta",{name:"description",content:`${zt} — ${(o==null?void 0:o.name)||"your agent"}`}),gt&&e.jsx("meta",{property:"og:image",content:gt}),e.jsx("meta",{property:"og:title",content:`Connect with ${(o==null?void 0:o.name)||"me"}`}),e.jsx("meta",{property:"og:description",content:zt}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"})]}),e.jsx("style",{children:` .connect-shell { font-family: var(--c-body-font); color: var(--c-text); } .connect-shell h1, .connect-shell h2 { font-family: var(--c-heading-font); } .connect-input { width: 100%; padding: 0.75rem 1rem; border-radius: 0.75rem; border: 1px solid var(--c-border); background: var(--c-surface); color: var(--c-text); font-family: var(--c-body-font); font-size: 0.95rem; transition: border-color 150ms, box-shadow 150ms; } .connect-input::placeholder { color: var(--c-text-muted); opacity: 0.7; } .connect-input:focus { outline: none; border-color: var(--c-accent); box-shadow: 0 0 0 3px color-mix(in srgb, var(--c-accent) 25%, transparent); } `}),e.jsxs("div",{className:"relative w-full overflow-hidden",style:{height:"clamp(200px, 30vh, 320px)"},children:[e.jsx(Zn.img,{src:gt,alt:"",initial:{scale:1.08},animate:{scale:1},transition:{duration:1.4,ease:"easeOut"},className:"absolute inset-0 w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0",style:{background:"linear-gradient(180deg, rgba(0,0,0,0) 20%, rgba(0,0,0,0.55) 100%)"}}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 p-6 pb-16 text-center",children:[e.jsx(Zn.h1,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.15,duration:.6},style:{color:"#fff",fontFamily:Lt.headingFont,fontWeight:500,letterSpacing:"-0.01em"},className:"text-3xl sm:text-4xl leading-tight",children:zt}),As&&e.jsx(Zn.p,{initial:{opacity:0},animate:{opacity:.9},transition:{delay:.35,duration:.6},style:{color:"#fff"},className:"text-sm mt-2",children:As})]})]}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 pb-12 -mt-12 relative",children:[e.jsxs(Zn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.25},className:"text-center mb-6",children:[o!=null&&o.avatar_url?e.jsx("img",{src:o.avatar_url,alt:o.name,className:"w-24 h-24 rounded-full object-cover mx-auto shadow-xl",style:{border:"4px solid var(--c-surface)"}}):e.jsx("div",{className:"w-24 h-24 rounded-full mx-auto flex items-center justify-center shadow-xl",style:{background:Lt.accent,color:Lt.accentText,border:"4px solid var(--c-surface)"},children:e.jsx("span",{className:"text-3xl font-bold",children:((Qs=o==null?void 0:o.name)==null?void 0:Qs.charAt(0))||"?"})}),(o==null?void 0:o.title)&&e.jsx("p",{className:"text-sm mt-3",style:{color:"var(--c-text-muted)"},children:o.title}),((o==null?void 0:o.phone)||(o==null?void 0:o.email))&&e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-3",children:[(o==null?void 0:o.phone)&&e.jsx("a",{href:`tel:${o.phone}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Call agent",children:e.jsx(Cr,{className:"h-4 w-4"})}),(o==null?void 0:o.email)&&e.jsx("a",{href:`mailto:${o.email}`,className:"flex items-center justify-center w-10 h-10 rounded-full transition-opacity hover:opacity-80",style:{background:"color-mix(in srgb, var(--c-accent) 12%, transparent)",color:"var(--c-accent)"},"aria-label":"Email agent",children:e.jsx(Gs,{className:"h-4 w-4"})})]})]}),e.jsx(Zn.p,{initial:{opacity:0},animate:{opacity:1},transition:{delay:.35},className:"text-center mb-6 px-2 leading-relaxed text-sm",style:{color:"var(--c-text-muted)"},children:(d==null?void 0:d.welcome_message)||"I'd love to stay in touch — just a few quick details."}),e.jsx("div",{className:"flex gap-1.5 mb-6 px-2",children:Array.from({length:xs}).map((ks,$s)=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-all duration-500",style:{background:$s<=E?"var(--c-accent)":"color-mix(in srgb, var(--c-text) 12%, transparent)"}},$s))}),e.jsxs(Zn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},transition:{delay:.4},className:"rounded-2xl p-6 sm:p-8",style:{background:"var(--c-surface)",border:"1px solid var(--c-border)",boxShadow:Xt?"0 20px 40px -20px rgba(0,0,0,0.5)":"0 20px 40px -20px rgba(0,0,0,0.15)"},children:[e.jsx(pye,{mode:"wait",children:e.jsxs(Zn.div,{initial:{opacity:0,x:20},animate:{opacity:1,x:0},exit:{opacity:0,x:-20},transition:{duration:.25},children:[e.jsxs("div",{className:"mb-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4",style:{color:"var(--c-accent)"}}),e.jsx("h2",{className:"text-lg font-semibold",style:{color:"var(--c-text)"},children:Ls[E].title})]}),Ls[E].subtitle&&e.jsx("p",{className:"text-xs mt-1 ml-6",style:{color:"var(--c-text-muted)"},children:Ls[E].subtitle})]}),Ls[E].fields]},E)}),e.jsxs("div",{className:"flex justify-between mt-8",children:[E>0?e.jsx("button",{type:"button",onClick:()=>O(ks=>ks-1),className:"px-5 py-2.5 text-sm font-medium transition-opacity hover:opacity-70",style:{color:"var(--c-text-muted)"},children:"Back"}):e.jsx("div",{}),E{if(E===0&&!F.trim()){ae.error("Please enter your first name");return}O(ks=>ks+1)},className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:"Continue"}):e.jsx("button",{type:"button",onClick:()=>$t(),disabled:S,className:"px-6 py-2.5 text-sm font-medium rounded-xl transition-transform hover:scale-[1.02] shadow-sm disabled:opacity-50 flex items-center gap-2",style:{background:"var(--c-accent)",color:"var(--c-accent-text)"},children:S?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Sending..."]}):"Submit"})]}),E>0&&EO(ks=>ks+1),className:"text-xs transition-opacity hover:opacity-80",style:{color:"var(--c-text-muted)"},children:"Skip this step"})})]}),e.jsx("div",{className:"text-center mt-8",children:e.jsxs("div",{className:"flex items-center justify-center gap-1 text-xs",style:{color:"var(--c-text-muted)"},children:[e.jsx(gi,{className:"h-3 w-3"}),e.jsx("span",{children:"Powered by ReLevelUp"})]})})]})]})}const UD=()=>({trackEngagement:N.useCallback(async(t,n,r,a="view")=>{try{const{data:{user:i}}=await q.auth.getUser();if(!i)return;await q.from("content_engagement_logs").insert({user_id:i.id,resource_type:t,resource_id:n,resource_title:r,action_type:a})}catch(i){console.error("Error tracking engagement:",i)}},[])});function iF({banners:s,autoPlayInterval:t=5e3,className:n}){const[r,a]=N.useState(0),[i,l]=N.useState(!1),{trackEngagement:o}=UD(),c=N.useCallback(f=>{o("newsletter",f.id,f.title,"click_link")},[o]),d=N.useCallback(()=>{a(f=>(f+1)%s.length)},[s.length]),u=N.useCallback(()=>{a(f=>(f-1+s.length)%s.length)},[s.length]),h=N.useCallback(f=>{a(f)},[]);if(N.useEffect(()=>{if(s.length<=1||i)return;const f=setInterval(d,t);return()=>clearInterval(f)},[s.length,i,t,d]),!s||s.length===0)return null;const p=s[r];return e.jsxs("div",{className:Mt("relative w-full overflow-hidden rounded-xl",n),onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),children:[e.jsxs("div",{className:"relative aspect-[21/9] md:aspect-[3/1] w-full",children:[e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-full object-cover rounded-t-xl"}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",className:Mt("absolute left-2 top-1/2 -translate-y-1/2 bg-black/30 hover:bg-black/50 text-white rounded-full","opacity-0 transition-opacity",i&&"opacity-100"),onClick:u,children:e.jsx(ml,{className:"h-6 w-6"})}),e.jsx(B,{variant:"ghost",size:"icon",className:Mt("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(ga,{className:"h-6 w-6"})})]}),s.length>1&&e.jsx("div",{className:"absolute bottom-3 left-1/2 -translate-x-1/2 flex gap-2",children:s.map((f,y)=>e.jsx("button",{onClick:()=>h(y),className:Mt("w-2 h-2 rounded-full transition-all duration-300",y===r?"bg-white w-6":"bg-white/50 hover:bg-white/70"),"aria-label":`Go to slide ${y+1}`},y))})]}),e.jsxs("div",{className:"bg-foreground rounded-b-xl px-5 py-3 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("h2",{className:"text-sm md:text-base font-semibold text-background truncate",children:p.title}),p.description&&e.jsx("p",{className:"text-xs text-background/70 truncate",children:p.description})]}),p.link_url&&e.jsx("a",{href:p.link_url,target:"_blank",rel:"noopener noreferrer",className:"shrink-0",onClick:()=>c(p),children:e.jsx(B,{size:"sm",className:"bg-primary text-primary-foreground font-semibold transition-colors hover:bg-background hover:text-foreground",children:p.link_text||"Learn More"})})]})]})}function mns(s){return"EST"}function oB(s){const n=new Intl.DateTimeFormat("en-US",{hour:"numeric",minute:"2-digit",hour12:!0,timeZone:"America/New_York"}).format(s),r=mns();return`${n} ${r}`}function CL(s){const t=new Date,n=new Date(s),r=bP(n,-15),a=bP(n,30);return t>a?"ended":W1(t,{start:n,end:a})?"live":W1(t,{start:r,end:n})?"starting_soon":"upcoming"}function ZMe(s){const t=CL(s);return t==="starting_soon"||t==="live"}const jUe=ZMe,pns=({events:s,registrations:t,onNavigateToEvents:n})=>{const[r,a]=N.useState(new Date);N.useEffect(()=>{const f=setInterval(()=>{a(new Date)},3e4);return()=>clearInterval(f)},[]);const i=s.filter(f=>ZMe(f.event_date));if(i.length===0)return null;const l=i[0],o=CL(l.event_date),c=t.find(f=>f.event_id===l.id),d=(c==null?void 0:c.zoom_join_url)||l.zoom_link,u=!!c,h=o==="live",p=h?{container:"from-red-500/10 via-red-500/5 to-primary/10 border-red-500/30",pulse:"from-red-500/5",indicator:"bg-red-500",text:"text-red-500",button:"bg-red-500 hover:bg-red-600",outlineButton:"border-red-500/50 text-red-500 hover:bg-red-500/10"}:{container:"from-amber-500/10 via-amber-500/5 to-primary/10 border-amber-500/30",pulse:"from-amber-500/5",indicator:"bg-amber-500",text:"text-amber-500",button:"bg-amber-500 hover:bg-amber-600",outlineButton:"border-amber-500/50 text-amber-500 hover:bg-amber-500/10"};return e.jsxs("div",{className:`relative mb-8 overflow-hidden rounded-xl bg-gradient-to-r ${p.container} border`,children:[e.jsx("div",{className:`absolute inset-0 bg-gradient-to-r ${p.pulse} to-transparent animate-pulse`}),e.jsx("div",{className:"relative p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative flex items-center justify-center",children:[e.jsx("span",{className:`absolute inline-flex h-full w-full animate-ping rounded-full ${p.indicator} opacity-75`}),e.jsx("span",{className:`relative flex h-3 w-3 rounded-full ${p.indicator}`})]}),e.jsx("div",{className:`flex items-center gap-2 ${p.text} font-bold text-sm uppercase tracking-wider`,children:h?e.jsxs(e.Fragment,{children:[e.jsx(yf,{className:"h-4 w-4"}),"Live Now"]}):e.jsxs(e.Fragment,{children:[e.jsx(pr,{className:"h-4 w-4"}),"Starting Soon"]})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg text-foreground line-clamp-1",children:l.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:h?`Started at ${oB(new Date(l.event_date))}`:`Starts at ${oB(new Date(l.event_date))}`})]}),e.jsx("div",{className:"flex items-center gap-2",children:u?e.jsxs(B,{onClick:()=>window.open(d,"_blank"),className:`${p.button} text-white gap-2`,children:[e.jsx(tr,{className:"h-4 w-4"}),h?"Join Now":"Join When Live"]}):e.jsxs(B,{variant:"outline",onClick:n,className:`${p.outlineButton} gap-2`,children:[e.jsx(An,{className:"h-4 w-4"}),"Register & Join"]})})]})})]})};function Dh(){const{user:s}=vs(),{data:t,isLoading:n}=dt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:h,error:p}=await q.from("gmail_integrations").select("*").maybeSingle();if(p)throw p;return h}}),{data:r,isLoading:a}=dt({queryKey:["user-verified-ses-sender",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{const{data:h}=await q.from("user_verified_senders").select("email, status").eq("user_id",s.id).eq("status","verified").order("verified_at",{ascending:!1}).limit(1).maybeSingle();return h}}),i=!!(t!=null&&t.is_active),l=(t==null?void 0:t.gmail_email)||null,o=!!(r!=null&&r.email),c=(r==null?void 0:r.email)||null;return{isGmailConnected:i,gmailEmail:l,hasVerifiedSes:o,sesEmail:c,canSendEmail:i||o,sendMethod:i?"gmail":o?"mass_email":"none",isLoading:n||a}}function fns(){const{user:s}=vs(),{isGmailConnected:t,hasVerifiedSes:n,isLoading:r}=Dh(),[a,i]=N.useState(!1),[l,o]=N.useState(!1);N.useEffect(()=>{s!=null&&s.id&&q.from("onboarding_checklist_dismissed").select("id").eq("user_id",s.id).maybeSingle().then(({data:j})=>{i(!!j),o(!0)})},[s==null?void 0:s.id]);const{data:c,isLoading:d}=dt({queryKey:["new-agent-onboarding",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),staleTime:3e4,queryFn:async()=>{const[j,w,S,A,E]=await Promise.all([q.from("profiles").select("avatar_url, phone, bio, name").eq("id",s.id).maybeSingle(),q.from("innercircle_contacts").select("id",{count:"exact",head:!0}).eq("owner_user_id",s.id),q.from("event_registrations").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("community_posts").select("id",{count:"exact",head:!0}).eq("user_id",s.id),q.from("events").select("id, title, event_date, image_url").eq("is_published",!0).gte("event_date",new Date().toISOString()).or("title.ilike.%onboarding%,title.ilike.%new member%,title.ilike.%welcome%,description.ilike.%new member onboarding%").order("event_date",{ascending:!0}).limit(1).maybeSingle()]),O=j.data,D=!!(O!=null&&O.avatar_url&&(O!=null&&O.phone)&&(O!=null&&O.bio)),I=w.count||0,F=(S.count||0)>0,z=A.count||0;return{profile:O,profileComplete:D,contactsCount:I,contactsComplete:I>=5,eventsRegistered:F,communityComplete:z>0,nextOnboardingEvent:E.data||null}}}),u=t||n,h=[{id:"profile",complete:!!(c!=null&&c.profileComplete)},{id:"email",complete:u},{id:"contacts",complete:!!(c!=null&&c.contactsComplete)},{id:"event",complete:!!(c!=null&&c.eventsRegistered)},{id:"community",complete:!!(c!=null&&c.communityComplete)}],p=h.filter(j=>j.complete).length,f=h.length;return{steps:h,completedCount:p,totalCount:f,allComplete:p===f,dismissed:a,dismiss:async()=>{s!=null&&s.id&&(i(!0),await q.from("onboarding_checklist_dismissed").insert({user_id:s.id}))},reopen:async()=>{s!=null&&s.id&&(i(!1),await q.from("onboarding_checklist_dismissed").delete().eq("user_id",s.id))},data:c,isGmailConnected:t,hasVerifiedSes:n,loading:d||r||!l}}const xns={profile:{title:"Complete Your Profile",description:"Add your headshot, phone, and short bio so contacts recognize you.",icon:Wi,accent:"from-[#2a4c64] to-[#406E71]",cta:"Edit Profile"},email:{title:"Set Up Email Sending",description:"Connect Gmail (recommended) or verify a Mass Email sender to send from your address.",icon:Gs,accent:"from-[#406E71] to-[#5b9ea1]",cta:"Connect Email"},contacts:{title:"Add Your First Contacts",description:"Import your database or add contacts one at a time to start building your Inner Circle.",icon:An,accent:"from-[#c9a84c] to-[#e8c76f]",cta:"Add Contacts"},event:{title:"Register for New Member Onboarding",description:"Join our live LevelUp onboarding session to hit the ground running.",icon:yr,accent:"from-[#8b5cf6] to-[#a78bfa]",cta:"Register"},community:{title:"Say Hi in the Community",description:"Introduce yourself and connect with other LevelUp agents.",icon:Ai,accent:"from-[#ec4899] to-[#f472b6]",cta:"Visit Community"}};function gns(){var _,v;const s=Ln(),{user:t}=vs(),{steps:n,completedCount:r,totalCount:a,allComplete:i,dismissed:l,dismiss:o,data:c,loading:d}=fns(),[u,h]=N.useState(!0);if(d||l||i)return null;const p=(((_=c==null?void 0:c.profile)==null?void 0:_.name)||((v=t==null?void 0:t.user_metadata)==null?void 0:v.name)||"there").split(" ")[0],f=r/a*100,y=async j=>{switch(j){case"profile":s("/profile");break;case"email":s("/mission-control/integrations");break;case"contacts":s("/mission-control/contacts");break;case"event":{const w=c==null?void 0:c.nextOnboardingEvent;if(!w){s("/events");return}if(!(t!=null&&t.id))return;const{error:S}=await q.from("event_registrations").insert({user_id:t.id,event_id:w.id});S&&!String(S.message).toLowerCase().includes("duplicate")?(ae.error("Could not register — opening events page."),s("/events")):ae.success(`You're registered for ${w.title}!`);break}case"community":s("/community");break}};return e.jsxs(fe,{className:"mb-6 overflow-hidden border-0 shadow-lg",children:[e.jsxs("div",{className:"relative bg-gradient-to-br from-[#2a4c64] via-[#345a75] to-[#406E71] p-6 md:p-8 text-white",children:[e.jsx("button",{onClick:o,className:"absolute top-4 right-4 p-1.5 rounded-full hover:bg-white/10 transition","aria-label":"Dismiss",children:e.jsx($n,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"hidden sm:flex h-12 w-12 rounded-xl bg-white/15 backdrop-blur items-center justify-center shrink-0",children:e.jsx(un,{className:"h-6 w-6 text-[#f5f0e0]"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h2",{className:"text-xl md:text-2xl font-bold",children:["Welcome to LevelUp, ",p,"! 👋"]}),e.jsx("p",{className:"text-white/80 mt-1 text-sm md:text-base",children:"Let's get you set up in under 10 minutes."}),e.jsxs("div",{className:"mt-4 max-w-md",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs mb-1.5 text-white/90",children:[e.jsxs("span",{className:"font-medium",children:[r," of ",a," complete"]}),e.jsxs("span",{children:[a-r," steps left"]})]}),e.jsx(fi,{value:f,className:"h-2 bg-white/20 [&>div]:bg-[#f5f0e0]"})]}),e.jsxs("div",{className:"mt-5 flex flex-wrap items-center gap-3",children:[e.jsxs(B,{onClick:()=>h(!0),className:"bg-[#f5f0e0] text-[#2a4c64] hover:bg-white font-semibold",children:["Continue Setup ",e.jsx(Oa,{className:"h-4 w-4 ml-1.5"})]}),e.jsx("button",{onClick:()=>h(j=>!j),className:"text-sm text-white/80 hover:text-white flex items-center gap-1",children:u?e.jsxs(e.Fragment,{children:["Hide steps ",e.jsx(ex,{className:"h-4 w-4"})]}):e.jsxs(e.Fragment,{children:["Show steps ",e.jsx(ao,{className:"h-4 w-4"})]})})]})]})]})]}),u&&e.jsx(Ee,{className:"p-4 md:p-6 bg-gradient-to-b from-background to-muted/30",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:n.map(j=>{const w=xns[j.id],S=w.icon;return e.jsx("div",{className:Mt("relative rounded-xl border p-4 transition-all group",j.complete?"bg-muted/40 border-muted":"bg-card hover:shadow-md hover:border-primary/40 cursor-pointer"),onClick:()=>!j.complete&&y(j.id),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:Mt("h-10 w-10 rounded-lg flex items-center justify-center shrink-0 bg-gradient-to-br text-white",j.complete?"from-emerald-500 to-emerald-600":w.accent),children:j.complete?e.jsx(vr,{className:"h-5 w-5"}):e.jsx(S,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h3",{className:Mt("font-semibold text-sm",j.complete&&"text-muted-foreground line-through"),children:w.title})}),e.jsx("p",{className:Mt("text-xs text-muted-foreground mt-1 leading-relaxed",j.complete&&"line-through"),children:w.description}),j.id==="event"&&!j.complete&&(c==null?void 0:c.nextOnboardingEvent)&&e.jsxs("div",{className:"mt-2 text-xs font-medium text-primary",children:[new Date(c.nextOnboardingEvent.event_date).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"})," ","ET"]}),!j.complete&&e.jsxs(B,{size:"sm",variant:"ghost",className:"mt-2 h-7 px-2 -ml-2 text-primary hover:text-primary hover:bg-primary/10",onClick:A=>{A.stopPropagation(),y(j.id)},children:[w.cta," ",e.jsx(Oa,{className:"h-3 w-3 ml-1"})]})]}),j.complete&&e.jsx("span",{className:"text-xs font-medium text-emerald-600 shrink-0",children:"✓ Done"})]})},j.id)})})})]})}const ky=()=>dt({queryKey:["relationship-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("relationship_types").select("*").order("sort_order");if(t)throw t;return s}}),ax=s=>{const t=wa(),n=1e3,r=async a=>{const i=[];let l=0;for(;;){const{data:o,error:c}=await a.range(l,l+n-1);if(c)throw c;const d=o??[];if(i.push(...d),d.length{let a=q.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("owner_user_id",t).order("created_at",{ascending:!1}).order("first_name");return await r(a)},enabled:!!t})},yns=s=>dt({queryKey:["innercircle-contact",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` *, lead_source_ref:lead_sources(id, name), tags:innercircle_contact_tags( id, contact_id, relationship_type_id, relationship_type:relationship_types(*) ) `).eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s}),kmt=()=>{const s=wa();return dt({queryKey:["innercircle-contact-counts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `);if(n)throw n;const r={};return t==null||t.forEach(a=>{var i;(i=a.tags)==null||i.forEach(l=>{r[l.relationship_type_id]=(r[l.relationship_type_id]||0)+1})}),r},enabled:!!s})},Cye=()=>{const s=Kt(),t=wa();return yt({mutationFn:async n=>{const{tagIds:r,...a}=n,i={...a,birthday:a.birthday||null,home_anniversary:a.home_anniversary||null,spouse_birthday:a.spouse_birthday||null,owner_user_id:t},{data:l,error:o}=await q.from("innercircle_contacts").insert(i).select().single();if(o)throw o;if(r&&r.length>0){const{error:c}=await q.from("innercircle_contact_tags").insert(r.map(d=>({contact_id:l.id,relationship_type_id:d})));if(c)throw c}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Br({title:"Contact created successfully"})},onError:n=>{Br({title:"Error creating contact",description:n.message,variant:"destructive"})}})},QMe=()=>{const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{tagIds:r,tags:a,...i}=n,l=["birthday","home_anniversary","spouse_birthday","wedding_anniversary","last_contacted_at","next_touch_date"],o={...i};for(const u of Object.keys(o)){const h=o[u];(h===""||typeof h=="string"&&l.includes(u)&&h.trim()==="")&&(o[u]=null)}const{data:c,error:d}=await q.from("innercircle_contacts").update(o).eq("id",t).select().single();if(d)throw d;if(r!==void 0&&(await q.from("innercircle_contact_tags").delete().eq("contact_id",t),r.length>0)){const{error:u}=await q.from("innercircle_contact_tags").insert(r.map(h=>({contact_id:t,relationship_type_id:h})));if(u)throw u}return c},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Br({title:"Contact updated successfully"})},onError:t=>{Br({title:"Error updating contact",description:t.message,variant:"destructive"})}})},Smt=()=>{const s=Kt();return yt({mutationFn:async({contactId:t,spouseContactId:n})=>{if(n){const{error:r}=await q.from("innercircle_contacts").update({spouse_contact_id:n}).eq("id",t);if(r)throw r;const{error:a}=await q.from("innercircle_contacts").update({spouse_contact_id:t}).eq("id",n);if(a)throw a}else{const{data:r}=await q.from("innercircle_contacts").select("spouse_contact_id").eq("id",t).single(),a=r==null?void 0:r.spouse_contact_id,{error:i}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",t);if(i)throw i;if(a){const{error:l}=await q.from("innercircle_contacts").update({spouse_contact_id:null}).eq("id",a);if(l)throw l}}},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact"]}),s.invalidateQueries({queryKey:["innercircle-contact-spouse"]}),Br({title:"Spouse link updated"})},onError:t=>{Br({title:"Error linking spouse",description:t.message,variant:"destructive"})}})},XMe=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("innercircle_contacts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Br({title:"Contact deleted successfully"})},onError:t=>{Br({title:"Error deleting contact",description:t.message,variant:"destructive"})}})},aU=()=>dt({queryKey:["action-types"],queryFn:async()=>{const{data:s,error:t}=await q.from("action_types").select("*").order("sort_order");if(t)throw t;return s}}),vns=s=>dt({queryKey:["action-scripts",s],queryFn:async()=>{let t=q.from("action_scripts").select("*, action_type:action_types(*)");const{data:n,error:r}=await t;if(r)throw r;return n}}),bns=()=>dt({queryKey:["touchpoint-plans"],queryFn:async()=>{const{data:s,error:t}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) `).order("name");if(t)throw t;return s}}),_ns=()=>{const s=Kt(),t=wa();return yt({mutationFn:async({name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").insert({name:n,description:r,owner_user_id:t,active:!0,is_template:!1}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Br({title:"Plan created successfully"})},onError:n=>{Br({title:"Error creating plan",description:n.message,variant:"destructive"})}})},wns=()=>{const s=Kt(),t=wa();return yt({mutationFn:async({sourcePlanId:n,newName:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").select(` *, items:touchpoint_plan_items(*) `).eq("id",n).single();if(i)throw i;if(!a)throw new Error("Source plan not found");const{data:l,error:o}=await q.from("touchpoint_plans").insert({name:r,description:a.description,owner_user_id:t,active:!0,is_template:!1}).select().single();if(o)throw o;if(a.items&&a.items.length>0){const c=a.items.map(u=>({plan_id:l.id,month_number:u.month_number,action_type_id:u.action_type_id,default_script_id:u.default_script_id,notes:u.notes})),{error:d}=await q.from("touchpoint_plan_items").insert(c);if(d)throw d}return l},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Br({title:"Plan duplicated successfully",description:"You can now edit your copy of this plan."})},onError:n=>{Br({title:"Error duplicating plan",description:n.message,variant:"destructive"})}})},jns=()=>{const s=Kt();return yt({mutationFn:async({id:t,name:n,description:r})=>{const{data:a,error:i}=await q.from("touchpoint_plans").update({name:n,description:r}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Br({title:"Plan updated successfully"})}})},Nns=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("touchpoint_plans").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Br({title:"Plan deleted successfully"})}})},kns=()=>{const s=Kt();return yt({mutationFn:async({planId:t,items:n})=>{if(await q.from("touchpoint_plan_items").delete().eq("plan_id",t),n.length>0){const{error:r}=await q.from("touchpoint_plan_items").insert(n.map(a=>({plan_id:t,month_number:a.month_number,action_type_id:a.action_type_id,default_script_id:a.default_script_id||null,notes:a.notes})));if(r)throw r}},onSuccess:()=>{s.invalidateQueries({queryKey:["touchpoint-plans"]}),Br({title:"Plan schedule updated"})}})},Sns=()=>{const s=Kt();return yt({mutationFn:async({actionTypeId:t,title:n,scriptBody:r,emailSubject:a,tone:i})=>{const{data:{user:l}}=await q.auth.getUser(),{data:o,error:c}=await q.from("action_scripts").insert({action_type_id:t,title:n,script_body:r,email_subject:a||null,tone:i||null,active:!0,user_id:l==null?void 0:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["action-scripts"]}),Br({title:"Script created successfully"})},onError:t=>{Br({title:"Error creating script",description:t.message,variant:"destructive"})}})},Cns=()=>{const s=wa();return dt({queryKey:["user-plan-enrollments",s],queryFn:async()=>{const{data:t,error:n}=await q.from("user_plan_enrollments").select(` *, plan:touchpoint_plans(*), relationship_type:relationship_types(*) `);if(n)throw n;return t},enabled:!!s})},Tns=()=>{const s=Kt(),t=wa();return yt({mutationFn:async({planId:n,relationshipTypeId:r,active:a})=>{const{data:i}=await q.from("user_plan_enrollments").select("id").eq("plan_id",n).eq("relationship_type_id",r).maybeSingle();if(i){const{error:l}=await q.from("user_plan_enrollments").update({active:a}).eq("id",i.id);if(l)throw l}else if(a){const{error:l}=await q.from("user_plan_enrollments").insert({owner_user_id:t,plan_id:n,relationship_type_id:r,active:!0,start_date:new Date().toISOString().split("T")[0]});if(l)throw l}},onSuccess:()=>{s.invalidateQueries({queryKey:["user-plan-enrollments"]}),Br({title:"Plan enrollment updated"})}})},iU=(s=7)=>{const t=wa();return dt({queryKey:["contact-touch-logs",t,s],queryFn:async()=>{const n=new Date;n.setDate(n.getDate()-s);const{data:r,error:a}=await q.from("contact_touch_logs").select(` *, contact:innercircle_contacts(*), action_type:action_types(*) `).eq("owner_user_id",t).gte("completed_at",n.toISOString()).order("completed_at",{ascending:!1});if(a)throw a;return r},enabled:!!t})},Cmt=()=>{const s=wa();return dt({queryKey:["contacts-last-touch",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("contact_id, completed_at").eq("owner_user_id",s).order("completed_at",{ascending:!1});if(n)throw n;const r={};return t==null||t.forEach(a=>{r[a.contact_id]||(r[a.contact_id]=a.completed_at)}),r},enabled:!!s})},Ens=(s=90)=>{const{data:t}=ax(),{data:n}=Cmt();if(!t||!n)return{contacts:[],count:0};const r=new Date;r.setDate(r.getDate()-s);const a=t.filter(i=>{const l=n[i.id];return l?new Date(l){const s=Kt(),t=wa();return yt({mutationFn:async({contactId:n,actionTypeId:r,scriptUsedId:a,notes:i,completedAt:l})=>{const{data:o,error:c}=await q.from("contact_touch_logs").insert({owner_user_id:t,contact_id:n,action_type_id:r,script_used_id:a,notes:i,completed_at:l||new Date().toISOString()}).select().single();if(c)throw c;return o},onSuccess:async(n,r)=>{var a,i;s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Br({title:"Action completed!"});try{const[l,o]=await Promise.all([q.from("innercircle_contacts").select("email").eq("id",r.contactId).single(),q.from("action_types").select("name").eq("id",r.actionTypeId).single()]),c=(a=l.data)==null?void 0:a.email,d=((i=o.data)==null?void 0:i.name)||"Touch";/pop[\s-]?by/i.test(d)&&q.from("popby_logs").insert({owner_user_id:t,contact_id:r.contactId,notes:r.notes??null,completed_at:r.completedAt||n.completed_at}).then(()=>{s.invalidateQueries({queryKey:["popby-logs"]})}),c&&q.functions.invoke("boldtrail-sync",{body:{action:"push_touch",contact_email:c,touch_type:d,touch_notes:r.notes||null,touch_date:r.completedAt||n.completed_at}}).catch(()=>{})}catch{}}})},Tmt="agentos_weekly_touch_goal",NUe=20,vfe=()=>{if(typeof window>"u")return NUe;const s=localStorage.getItem(Tmt);if(s){const t=parseInt(s,10);if(!isNaN(t)&&t>0)return t}return NUe},Emt=s=>{localStorage.setItem(Tmt,s.toString())},JMe=()=>{const{data:s}=iU(7),t=new Date;t.setHours(0,0,0,0);const n=new Date(t);n.setDate(t.getDate()-t.getDay());const r=(s==null?void 0:s.filter(l=>new Date(l.completed_at)>=n).length)||0;let a=0;if(s&&s.length>0){const l=new Set(s.map(c=>new Date(c.completed_at).toDateString()));let o=new Date(t);for(;l.has(o.toDateString());)a++,o.setDate(o.getDate()-1)}const i=vfe();return{actionsThisWeek:r,weeklyGoal:i,streak:a,progress:Math.min(r/i*100,100)}},Ans=()=>{const s=wa();return dt({queryKey:["contact-plan-cycles",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_plan_cycles").select(` *, contact:innercircle_contacts(*), plan:touchpoint_plans( *, items:touchpoint_plan_items( *, action_type:action_types(*), default_script:action_scripts(*) ) ) `);if(n)throw n;return t},enabled:!!s})},Mns=()=>{const s=Kt();return wa(),yt({mutationFn:async()=>{var c;const{data:t}=await q.from("user_plan_enrollments").select("*").eq("active",!0);if(!t||t.length===0)return;const{data:n}=await q.auth.getUser(),r=(c=n==null?void 0:n.user)==null?void 0:c.id;if(!r)return;const{data:a}=await q.from("innercircle_contacts").select(` id, tags:innercircle_contact_tags(relationship_type_id) `).eq("owner_user_id",r);if(!a)return;const{data:i}=await q.from("contact_plan_cycles").select("contact_id, plan_id"),l=new Set((i==null?void 0:i.map(d=>`${d.contact_id}-${d.plan_id}`))||[]),o=[];for(const d of a)for(const u of d.tags||[]){const h=t.find(p=>p.relationship_type_id===u.relationship_type_id);h&&!l.has(`${d.id}-${h.plan_id}`)&&o.push({contact_id:d.id,plan_id:h.plan_id,relationship_type_id:u.relationship_type_id})}if(o.length>0){const{error:d}=await q.from("contact_plan_cycles").insert(o);if(d)throw d}return o.length},onSuccess:t=>{s.invalidateQueries({queryKey:["contact-plan-cycles"]}),t&&t>0&&Br({title:`${t} contact(s) enrolled in plans`})}})},Amt=()=>{const s=wa(),{data:t}=Ans(),{data:n}=iU(30);return dt({queryKey:["today-actions",s,t==null?void 0:t.length,n==null?void 0:n.length],queryFn:async()=>{var y;if(!t||t.length===0)return[];const{data:r}=await q.from("contact_snoozes").select("contact_id").gte("snoozed_until",new Date().toISOString()),a=new Set((r==null?void 0:r.map(_=>_.contact_id))||[]),i=new Date,l=[],o=new Date(i.getFullYear(),i.getMonth(),1),c=new Set((n==null?void 0:n.filter(_=>new Date(_.completed_at)>=o).map(_=>`${_.contact_id}-${_.action_type_id}`))||[]);for(const _ of t){if(!((y=_.plan)!=null&&y.items)||_.plan.items.length===0||!_.contact||a.has(_.contact_id))continue;const v=new Date(_.cycle_start_date),w=Math.floor((i.getTime()-v.getTime())/(30.44*24*60*60*1e3))%12+1,S=_.plan.items.find(A=>A.month_number===w);if(S&&S.action_type){const A=`${_.contact_id}-${S.action_type_id}`;if(!c.has(A)){const{data:E}=await q.from("relationship_types").select("name").eq("id",_.relationship_type_id).single();l.push({contact:_.contact,actionType:S.action_type,script:S.default_script||void 0,planName:_.plan.name,relationshipTypeName:(E==null?void 0:E.name)||"",monthNumber:w})}}}const d=5,u=i.getDate(),h=l.sort((_,v)=>_.contact.first_name.localeCompare(v.contact.first_name)),p=(u-1)%Math.max(1,h.length);return[...h.slice(p),...h.slice(0,p)].slice(0,d)},enabled:!!s&&!!t})};function Ins(){const s=Ln(),{data:t,isLoading:n}=Amt(),{data:r}=ax(),a=JMe(),[i,l]=N.useState(vfe()),[o,c]=N.useState(""),[d,u]=N.useState(!1);N.useEffect(()=>{l(vfe())},[]);const h=()=>{const O=parseInt(o,10);if(isNaN(O)||O<1){Br({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}l(O),Emt(O),u(!1),Br({title:"Goal updated",description:`Weekly touch goal set to ${O}`})},p=()=>{c(i.toString()),u(!0)},f=wf(new Date),y=Bl(f,7),_=O=>{if(!O)return null;const D=O.split(/[-/T]/);if(D.length<3)return null;const I=parseInt(D[1],10)-1,F=parseInt(D[2],10);return isNaN(I)||isNaN(F)?null:new Date(f.getFullYear(),I,F)},v=(r==null?void 0:r.map(O=>{const D=_(O.birthday),I=_(O.home_anniversary),F=[];return D&&D>=f&&D<=y&&F.push({contact:O,type:"birthday",date:D,isToday:ql(D,f)}),I&&I>=f&&I<=y&&F.push({contact:O,type:"anniversary",date:I,isToday:ql(I,f)}),F}).flat().sort((O,D)=>O.date.getTime()-D.date.getTime()).slice(0,3))||[],j=(r==null?void 0:r.filter(O=>{const D=_(O.birthday),I=_(O.home_anniversary);return D&&ql(D,f)||I&&ql(I,f)}).length)||0,w=(t==null?void 0:t.length)||0,S=j+w,A=(a==null?void 0:a.actionsThisWeek)||0,E=(a==null?void 0:a.streak)||0;return n?e.jsx(fe,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-primary/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-primary/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-primary/10 rounded w-1/2"})]})]})})}):e.jsxs(fe,{className:"bg-gradient-to-br from-primary/5 via-primary/10 to-primary/5 border-primary/20",children:[e.jsxs(It,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5 text-primary"}),"Agent OS"]}),e.jsx("div",{className:"flex items-center gap-2",children:E>0&&e.jsxs(Ue,{variant:"secondary",className:"gap-1 bg-orange-500/10 text-orange-600 border-orange-200",children:[e.jsx(Hc,{className:"h-3 w-3"}),E," day streak"]})})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[S>0?e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"text-primary font-medium",children:[S," tasks"]})," for today"]}):"No tasks for today",A>0&&e.jsxs("span",{className:"ml-2",children:["• ",e.jsx("span",{className:"text-emerald-600 font-medium",children:A})," touches this week"]})]})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:O=>{O.stopPropagation(),s("/mission-control/contacts?new=true")},children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Add Contact"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:O=>{O.stopPropagation(),s("/mission-control")},children:[e.jsx(Cr,{className:"h-3.5 w-3.5"}),"Log Touch"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-emerald-200 text-emerald-700 hover:bg-emerald-50 hover:text-emerald-800",onClick:O=>{O.stopPropagation(),s("/mission-control/video/record")},children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),"Quick Video"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:O=>{O.stopPropagation(),s("/mission-control/popbys")},children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),"Pop-by Map"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-purple-200 text-purple-700 hover:bg-purple-50 hover:text-purple-800",onClick:O=>{O.stopPropagation(),s("/mission-control/pipeline")},children:[e.jsx(G2,{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(Ac,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm font-medium",children:"Weekly Goal"}),e.jsxs(_s,{open:d,onOpenChange:u,children:[e.jsx(ki,{asChild:!0,children:e.jsx("button",{onClick:p,className:"p-0.5 rounded hover:bg-muted transition-colors","aria-label":"Edit weekly goal",children:e.jsx(Ko,{className:"h-3.5 w-3.5 text-muted-foreground hover:text-primary"})})}),e.jsxs(bs,{className:"sm:max-w-[360px]",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Set Weekly Goal"}),e.jsx(Jn,{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(ne,{htmlFor:"weekly-goal",children:"Weekly touch goal"}),e.jsx(ye,{id:"weekly-goal",type:"number",min:"1",value:o,onChange:O=>c(O.target.value),placeholder:"20",onKeyDown:O=>{O.key==="Enter"&&h()}})]}),e.jsx(B,{onClick:h,className:"w-full",children:"Save Goal"})]})]})]})]}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium text-primary",children:A}),e.jsxs("span",{className:"text-muted-foreground",children:[" / ",i," touches"]})]})]}),e.jsx(fi,{value:Math.min(A/i*100,100),className:"h-2 bg-muted [&>div]:bg-primary"}),A>=i&&e.jsxs("p",{className:"text-xs text-emerald-600 mt-1.5 flex items-center gap-1",children:[e.jsx("span",{children:"🎉"})," Goal achieved! Keep the momentum going."]}),A0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1.5",children:[i-A," more to hit your weekly goal"]})]}),v.length>0&&e.jsxs("div",{className:"pt-3 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ah,{className:"h-4 w-4 text-pink-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Upcoming Milestones"})]}),e.jsx("div",{className:"space-y-2",children:v.map((O,D)=>e.jsxs("div",{className:`flex items-center justify-between p-2 rounded-lg cursor-pointer transition-colors ${O.isToday?"bg-pink-500/10 hover:bg-pink-500/15":"bg-muted/50 hover:bg-muted"}`,onClick:I=>{I.stopPropagation(),s(`/mission-control/contacts/${O.contact.id}`)},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[O.type==="birthday"?e.jsx(Ah,{className:"h-3.5 w-3.5 text-pink-500"}):e.jsx(Or,{className:"h-3.5 w-3.5 text-blue-500"}),e.jsxs("span",{className:"text-sm",children:[O.contact.first_name," ",O.contact.last_name]}),O.isToday&&e.jsx(Ue,{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:O.isToday?O.type==="birthday"?"🎂":"🏠":Ss(O.date,"EEE, MMM d")}),e.jsx(ga,{className:"h-3 w-3"})]})]},`${O.contact.id}-${O.type}-${D}`))})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full gap-1 text-muted-foreground hover:text-primary",onClick:()=>s("/mission-control"),children:["Open Agent OS",e.jsx(Oa,{className:"h-4 w-4"})]})]})]})}function Pns(s){return dt({queryKey:["brokerage-content-categories",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_content_categories").select("*").eq("brokerage_id",s).order("sort_order");if(n)throw n;return t},enabled:!!s})}function Lns(s,t){return dt({queryKey:["brokerage-content",s,t],queryFn:async()=>{if(!s)return[];let n=q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1});t&&(n=n.eq("category_id",t));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!s})}function Dns(s,t=4){return dt({queryKey:["brokerage-content-recent",s,t],queryFn:async()=>{if(!s)return[];const{data:n,error:r}=await q.from("brokerage_content").select("*, category:brokerage_content_categories(*)").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(t);if(r)throw r;return n},enabled:!!s})}function Rns(s){const t=Kt();return yt({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content").insert(n).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content"]}),t.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function Ons(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content"]}),s.invalidateQueries({queryKey:["brokerage-content-recent"]})}})}function Fns(s){const t=Kt();return yt({mutationFn:async n=>{const{data:r,error:a}=await q.from("brokerage_content_categories").insert({...n,brokerage_id:s}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function zns(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_content_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}function Bns(s){const t=Kt();return yt({mutationFn:async()=>{const n=[{name:"Events",icon:"📅",sort_order:0,is_default:!0,brokerage_id:s},{name:"Videos",icon:"🎥",sort_order:1,is_default:!0,brokerage_id:s},{name:"Documents",icon:"📄",sort_order:2,is_default:!0,brokerage_id:s},{name:"Resources",icon:"🔗",sort_order:3,is_default:!0,brokerage_id:s},{name:"Graphics",icon:"🎨",sort_order:4,is_default:!0,brokerage_id:s}],{error:r}=await q.from("brokerage_content_categories").upsert(n,{onConflict:"brokerage_id,name"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-content-categories"]})}})}const $ns={video:El,pdf:br,link:Tl,event:yr,graphic:pl},Uns={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 qns(s){if(!s)return null;try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}function Vns(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 Hns({item:s}){const t=Ln(),n=$ns[s.content_type]||Tl,r=Uns[s.content_type]||"",[a,i]=N.useState(null),l=s.thumbnail_url||(s.content_type==="graphic"&&s.file_url?s.file_url:null)||(s.content_type==="video"?qns(s.url):null);N.useEffect(()=>{l||!s.url||s.content_type!=="video"||!Vns(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(c=>c.ok?c.json():null).then(c=>{c!=null&&c.thumbnail_url&&i(c.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,l]);const o=l||a;return e.jsxs(fe,{className:"group cursor-pointer overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",onClick:()=>t(`/brokerage-content/${s.id}`),children:[o?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:o,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/20 flex items-center justify-center",children:e.jsx(n,{className:"h-8 w-8 text-muted-foreground/30"})}),e.jsxs(Ee,{className:"p-3",children:[e.jsx("div",{className:"flex items-center gap-1.5 mb-1.5",children:e.jsxs(Ue,{variant:"secondary",className:`text-[10px] px-1.5 py-0 ${r}`,children:[e.jsx(n,{className:"h-3 w-3 mr-0.5"}),s.content_type]})}),e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:s.title}),s.content_type==="event"&&s.event_date&&e.jsx("p",{className:"text-xs text-primary mt-1 font-medium",children:Ss(new Date(s.event_date),"MMM d · h:mm a")})]})]})}function Gns(){const{brokerageId:s}=vs(),t=Ln(),{data:n=[],isLoading:r}=Dns(s,4);return!s||r||n.length===0?null:e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Brokerage Content"})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage-content"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:n.map(a=>e.jsx(Hns,{item:a},a.id))})]})}const Mmt=()=>dt({queryKey:["listing-exchange-enabled"],queryFn:async()=>{const{data:s,error:t}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").maybeSingle();if(t)throw t;return(s==null?void 0:s.enabled)??!1}}),Imt=s=>{const{user:t,brokerageId:n}=vs();return dt({queryKey:["listings",s,n],queryFn:async()=>{let r=q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("is_public",!0);s!=null&&s.status&&(r=r.eq("status",s.status)),s!=null&&s.propertyType&&(r=r.eq("property_type",s.propertyType)),s!=null&&s.city&&(r=r.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(r=r.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(r=r.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(r=r.eq("open_to_referrals",!0));const{data:a,error:i}=await r;if(i)throw i;let l=a||[];if(n){const{data:o}=await q.from("profiles").select("id").eq("brokerage_id",n);if(o&&o.length>0){const c=o.map(h=>h.id);let d=q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).eq("is_approved",!0).eq("share_with_brokerage",!0).eq("is_public",!1).in("agent_id",c);s!=null&&s.status&&(d=d.eq("status",s.status)),s!=null&&s.propertyType&&(d=d.eq("property_type",s.propertyType)),s!=null&&s.city&&(d=d.ilike("city",`%${s.city}%`)),s!=null&&s.minPrice&&(d=d.gte("price",s.minPrice)),s!=null&&s.maxPrice&&(d=d.lte("price",s.maxPrice)),s!=null&&s.openToReferrals&&(d=d.eq("open_to_referrals",!0));const{data:u}=await d;if(u){const h=new Set(l.map(f=>f.id)),p=u.filter(f=>!h.has(f.id));l=[...l,...p]}}}switch(s==null?void 0:s.sortBy){case"updated":l.sort((o,c)=>new Date(c.updated_at).getTime()-new Date(o.updated_at).getTime());break;case"price_asc":l.sort((o,c)=>o.price-c.price);break;case"price_desc":l.sort((o,c)=>c.price-o.price);break;default:l.sort((o,c)=>new Date(c.created_at).getTime()-new Date(o.created_at).getTime())}return l}})},Pmt=()=>{const{user:s}=vs();return dt({queryKey:["my-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listings").select(` *, photos:listing_photos(*) `).eq("agent_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})},e6e=s=>{const{user:t}=vs();return dt({queryKey:["listing",s],queryFn:async()=>{const{data:n,error:r}=await q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)), video:agent_videos!listings_video_id_fkey(id, playback_url, thumbnail_url, title, duration_seconds) `).eq("id",s).single();if(r)throw r;return t&&await q.from("listing_views").insert({listing_id:s,viewer_id:t.id}),n},enabled:!!s})},Wns=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Kns=()=>{const s=Kt();return yt({mutationFn:async({agentId:t,...n})=>{const{data:r,error:a}=await q.from("listings").insert({...n,agent_id:t}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["brokerage-listings"]})}})},Yns=()=>{const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("listings").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]}),s.invalidateQueries({queryKey:["listing",t.id]})}})},Lmt=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("listings").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["listings"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Zns=()=>{const s=Kt();return yt({mutationFn:async({listingId:t,photoUrl:n,isPrimary:r=!1})=>{const{data:a,error:i}=await q.from("listing_photos").insert({listing_id:t,photo_url:n,is_primary:r}).select().single();if(i)throw i;return a},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t.listing_id]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Qns=()=>{const s=Kt();return yt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Xns=()=>{const s=Kt();return yt({mutationFn:async({photos:t})=>{var i;const n=t.map(l=>q.from("listing_photos").update({sort_order:l.sort_order,is_primary:l.is_primary}).eq("id",l.id)),a=(i=(await Promise.all(n)).find(l=>l.error))==null?void 0:i.error;if(a)throw a;return t},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["listing"]}),s.invalidateQueries({queryKey:["my-listings"]})}})},Jns=()=>{const s=Kt();return yt({mutationFn:async({photoId:t,listingId:n})=>{const{error:r}=await q.from("listing_photos").update({is_primary:!1}).eq("listing_id",n);if(r)throw r;const{error:a}=await q.from("listing_photos").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["listing",t]}),s.invalidateQueries({queryKey:["my-listings"]})}})},ers=()=>{const{user:s}=vs();return dt({queryKey:["saved-listings",s==null?void 0:s.id],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("listing_saves").select(` *, listing:listings( *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id) ) `).eq("agent_id",s.id);if(n)throw n;return t},enabled:!!s})},Dmt=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_saves").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_saves").delete().eq("id",r.id),{saved:!1}):(await q.from("listing_saves").insert({listing_id:n,agent_id:t.id}),{saved:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["saved-listings"]}),s.invalidateQueries({queryKey:["listings"]})}})},Rmt=s=>{const{user:t}=vs();return dt({queryKey:["listing-saved",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_saves").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},trs=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{if(!t)throw new Error("Not authenticated");const{data:r}=await q.from("listing_follows").select("id").eq("listing_id",n).eq("agent_id",t.id).maybeSingle();return r?(await q.from("listing_follows").delete().eq("id",r.id),{following:!1}):(await q.from("listing_follows").insert({listing_id:n,agent_id:t.id}),{following:!0})},onSuccess:()=>{s.invalidateQueries({queryKey:["listing-following"]})}})},srs=s=>{const{user:t}=vs();return dt({queryKey:["listing-following",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return!1;const{data:n}=await q.from("listing_follows").select("id").eq("listing_id",s).eq("agent_id",t.id).maybeSingle();return!!n},enabled:!!t&&!!s})},nrs=()=>{const{user:s}=vs();return yt({mutationFn:async({listingId:t,shareType:n})=>{if(!s)throw new Error("Not authenticated");const{error:r}=await q.from("listing_shares").insert({listing_id:t,sharing_agent_id:s.id,share_type:n});if(r)throw r}})},rrs=()=>{const{user:s}=vs();return dt({queryKey:["my-referrals",s==null?void 0:s.id],queryFn:async()=>{if(!s)return{sent:[],received:[]};const[t,n]=await Promise.all([q.from("listing_referrals").select(` *, listing:listings(*,photos:listing_photos(*)) `).eq("sender_agent_id",s.id).order("created_at",{ascending:!1}),q.from("listing_referrals").select(` *, sender:profiles!listing_referrals_sender_agent_id_fkey(id, name, email), listing:listings(*,photos:listing_photos(*)) `).eq("listing_agent_id",s.id).order("created_at",{ascending:!1})]);return{sent:t.data||[],received:n.data||[]}},enabled:!!s})},ars=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async({listingId:n,listingAgentId:r,buyerName:a,buyerType:i,notes:l})=>{if(!t)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("listing_referrals").insert({listing_id:n,sender_agent_id:t.id,listing_agent_id:r,buyer_name:a,buyer_type:i,notes:l}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["my-referrals"]})}})},irs=()=>dt({queryKey:["listing-leaderboard"],queryFn:async()=>{const{data:s}=await q.from("listing_shares").select("sharing_agent_id, profiles!listing_shares_agent_id_fkey(name)").order("created_at",{ascending:!1}),t=new Map;s==null||s.forEach(l=>{var d;const o=l.sharing_agent_id;if(!o)return;const c=t.get(o);c?c.count++:t.set(o,{name:((d=l.profiles)==null?void 0:d.name)||"Unknown",count:1})});const n=Array.from(t.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10),{data:r}=await q.from("listings").select("agent_id, agent:profiles!listings_agent_id_fkey(name)").eq("is_approved",!0),a=new Map;r==null||r.forEach(l=>{var c;const o=a.get(l.agent_id);o?o.count++:a.set(l.agent_id,{name:((c=l.agent)==null?void 0:c.name)||"Unknown",count:1})});const i=Array.from(a.entries()).map(([l,o])=>({agentId:l,...o})).sort((l,o)=>o.count-l.count).slice(0,10);return{topSharers:n,topListers:i}}}),ors=()=>{const{user:s,brokerageId:t}=vs();return dt({queryKey:["brokerage-listings",t],queryFn:async()=>{if(!s||!t)return[];const{data:n}=await q.from("profiles").select("id").eq("brokerage_id",t);if(!n||n.length===0)return[];const r=n.map(l=>l.id),{data:a,error:i}=await q.from("listings").select(` *, photos:listing_photos(*), agent:profiles!listings_agent_id_fkey(id, name, email, brokerage_id, brokerage:brokerages(name)) `).in("agent_id",r).eq("is_approved",!0).order("created_at",{ascending:!1});if(i)throw i;return a},enabled:!!s&&!!t})},Omt=({className:s,variant:t="default"})=>e.jsx(Ue,{variant:"outline",className:Mt("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"}),lrs={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"},crs={coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",active:"Active",under_contract:"Under Contract",sold:"Sold",withdrawn:"Withdrawn"};function drs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function urs(){const s=Ln(),{data:t,isLoading:n}=Mmt(),{data:r,isLoading:a}=Imt({status:void 0,propertyType:void 0,sortBy:"newest"}),i=(r==null?void 0:r.filter(u=>u.is_approved&&u.is_public))||[],l=i.filter(u=>u.is_featured),o=i.filter(u=>!u.is_featured),c=[...l,...o].slice(0,6),d=n||a;return!d&&!t?null:d?e.jsx(fe,{className:"bg-gradient-to-br from-emerald-500/5 via-emerald-500/10 to-emerald-500/5 border-emerald-500/20",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"animate-pulse flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 bg-emerald-500/20 rounded-lg"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx("div",{className:"h-4 bg-emerald-500/20 rounded w-1/3"}),e.jsx("div",{className:"h-3 bg-emerald-500/10 rounded w-1/2"})]})]})})}):e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Listing Exchange"}),e.jsx(Omt,{})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control/listings"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),c.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Or,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No listings available yet"}),e.jsx(B,{variant:"link",size:"sm",onClick:()=>s("/mission-control/listings/new"),className:"mt-2",children:"Add the first listing"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:c.map(u=>{var p,f;const h=((p=u.photos)==null?void 0:p.find(y=>y.is_primary))||((f=u.photos)==null?void 0:f[0]);return e.jsxs("div",{onClick:()=>s(`/mission-control/listings/${u.id}`),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsxs("div",{className:"aspect-[4/3] bg-muted/50 overflow-hidden relative",children:[h!=null&&h.photo_url?e.jsx("img",{src:h.photo_url,alt:`${u.city}, ${u.state}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Or,{className:"h-8 w-8 text-muted-foreground/50"})}),u.is_featured&&e.jsx("div",{className:"absolute top-1.5 left-1.5",children:e.jsxs(Ue,{className:"gap-1 bg-amber-500 text-white border-0 text-[10px] px-1.5 py-0.5",children:[e.jsx(oa,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]})}),e.jsx("div",{className:"absolute top-1.5 right-1.5",children:e.jsx(Ue,{className:`text-[10px] px-1.5 py-0.5 ${lrs[u.status]}`,children:crs[u.status]})})]}),e.jsxs("div",{className:"p-2",children:[e.jsx("p",{className:"font-bold text-sm text-foreground",children:drs(u.price)}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[u.city,", ",u.state]}),(u.bedrooms||u.bathrooms)&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-0.5",children:[u.bedrooms&&`${u.bedrooms} bed`,u.bedrooms&&u.bathrooms&&" · ",u.bathrooms&&`${u.bathrooms} bath`]})]})]},u.id)})})]})}function Fmt(s=10,t){return dt({queryKey:["event-leaderboard",s,t],queryFn:async()=>{const{data:n}=await q.from("user_roles").select("user_id").eq("role","admin"),r=new Set((n==null?void 0:n.map(p=>p.user_id))||[]);let a=null;if(t){const{data:p}=await q.from("profiles").select("id").eq("brokerage_id",t);a=new Set((p==null?void 0:p.map(f=>f.id))||[])}const{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points, total_events_attended, current_streak").order("total_points",{ascending:!1}).limit(s+r.size+50);if(l)throw l;if(!i||i.length===0)return[];let o=i.filter(p=>!r.has(p.user_id));a&&(o=o.filter(p=>a.has(p.user_id)));const c=o.slice(0,s),d=c.map(p=>p.user_id),{data:u}=await q.from("profiles").select("id, name").in("id",d),h=new Map((u==null?void 0:u.map(p=>[p.id,{name:p.name}]))||[]);return c.map(p=>({user_id:p.user_id,total_points:p.total_points,total_events_attended:p.total_events_attended,current_streak:p.current_streak,profile:h.get(p.user_id)||null}))}})}function zmt(s){return dt({queryKey:["user-attendance-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("agent_attendance_stats").select("*").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return t},enabled:!!s})}function Bmt(s){return dt({queryKey:["user-badges",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("agent_badges").select("*").eq("user_id",s).order("earned_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function $mt(s,t){return dt({queryKey:["user-rank",s,t],queryFn:async()=>{if(!s)return null;const{data:n}=await q.from("agent_attendance_stats").select("total_points").eq("user_id",s).single();if(!n)return null;const{data:r}=await q.from("user_roles").select("user_id").eq("role","admin"),a=new Set((r==null?void 0:r.map(c=>c.user_id))||[]),{data:i,error:l}=await q.from("agent_attendance_stats").select("user_id, total_points").gt("total_points",n.total_points);if(l)throw l;let o=(i==null?void 0:i.filter(c=>!a.has(c.user_id)))||[];if(t){const{data:c}=await q.from("profiles").select("id").eq("brokerage_id",t),d=new Set((c==null?void 0:c.map(u=>u.id))||[]);o=o.filter(u=>d.has(u.user_id))}return o.length+1},enabled:!!s})}function hrs(){const{user:s,brokerageId:t,isAdmin:n}=vs();Ln();const r=!!t,[a,i]=N.useState("brokerage"),l=()=>{if(n)return null;if(r)return a==="global"?null:t},{data:o,isLoading:c}=Fmt(5,l()),{data:d}=zmt(s==null?void 0:s.id),{data:u}=$mt(s==null?void 0:s.id,l()),{data:h}=Bmt(s==null?void 0:s.id),p=n||r,f=()=>n?"Agent Leaderboard":r?a==="global"?"All LevelUp":"My Brokerage":"My Points";if(c)return e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(xo,{className:"h-4 w-4 text-yellow-500"}),f()]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-2",children:[...Array(p?5:3)].map((_,v)=>e.jsx(Ws,{className:"h-10 w-full"},v))})})]});const y=_=>_===0?e.jsx(xo,{className:"h-4 w-4 text-yellow-500 mx-auto"}):_===1?e.jsx("span",{className:"text-sm font-medium text-gray-400",children:"2"}):_===2?e.jsx("span",{className:"text-sm font-medium text-amber-600",children:"3"}):e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:_+1});if(p){const _=(o==null?void 0:o.slice(0,5))||[];return e.jsxs(fe,{children:[e.jsxs(It,{className:"pb-2",children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(xo,{className:"h-4 w-4 text-yellow-500"}),f()]}),!n&&r&&e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsx(B,{variant:a==="brokerage"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("brokerage"),children:"My Brokerage"}),e.jsx(B,{variant:a==="global"?"default":"outline",size:"sm",className:"text-xs h-7 flex-1",onClick:()=>i("global"),children:"All LevelUp"})]})]}),e.jsxs(Ee,{children:[!n&&d&&e.jsx("div",{className:"mb-3 p-2 rounded-lg bg-primary/5 border border-primary/10",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Your Rank:"}),e.jsxs("span",{className:"font-bold text-primary",children:["#",u||"-"]})]}),e.jsxs("div",{className:"flex items-center gap-3 text-sm",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-primary",children:d.total_points})," pts"]}),e.jsxs("span",{children:[e.jsx("strong",{children:d.total_events_attended})," events"]})]})]})}),e.jsxs("div",{className:"space-y-2",children:[_.map((v,j)=>{var w,S,A;return e.jsxs("div",{className:`flex items-center gap-2 p-2 rounded-lg ${v.user_id===(s==null?void 0:s.id)?"bg-primary/10 border border-primary/20":j===0?"bg-yellow-500/10":""}`,children:[e.jsx("div",{className:"w-5 text-center",children:y(j)}),e.jsx(Jr,{className:"h-6 w-6",children:e.jsx(ea,{className:"text-xs",children:((S=(w=v.profile)==null?void 0:w.name)==null?void 0:S.charAt(0))||"?"})}),e.jsx("span",{className:"flex-1 text-sm font-medium truncate",children:((A=v.profile)==null?void 0:A.name)||"Unknown"}),e.jsx("span",{className:"text-sm font-bold text-primary",children:v.total_points})]},v.user_id)}),_.length===0&&e.jsx("div",{className:"text-center text-muted-foreground py-2 text-sm",children:"No data yet"})]}),e.jsxs(In,{to:"/reward-store",className:"mt-3 flex items-center justify-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(Oi,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(ga,{className:"h-4 w-4"})]})]})]})}return e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(xo,{className:"h-4 w-4 text-yellow-500"}),"My Points"]})}),e.jsx(Ee,{children:d?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"p-3 rounded-lg bg-primary/5 border border-primary/10 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-primary",children:d.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Points"})]}),e.jsxs("div",{className:"p-3 rounded-lg bg-muted/50 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:d.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Events Attended"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Hc,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm font-medium",children:"Current Streak"})]}),e.jsxs("span",{className:"font-bold text-orange-500",children:[d.current_streak," 🔥"]})]}),h&&h.length>0&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsxs("div",{className:"flex items-center gap-1 mb-2",children:[e.jsx(fc,{className:"h-3 w-3 text-muted-foreground"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Badges"})]}),e.jsxs("div",{className:"flex flex-wrap gap-1",children:[h.slice(0,4).map(_=>e.jsx("span",{className:"text-xs px-2 py-1 rounded-full bg-yellow-500/10 text-yellow-600 border border-yellow-500/20",children:_.badge_name},_.id)),h.length>4&&e.jsxs("span",{className:"text-xs text-muted-foreground px-2 py-1",children:["+",h.length-4," more"]})]})]}),e.jsxs(In,{to:"/reward-store",className:"mt-3 flex items-center justify-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(Oi,{className:"h-4 w-4"}),"Spend Points in Reward Store",e.jsx(ga,{className:"h-4 w-4"})]})]}):e.jsxs("div",{className:"text-center text-muted-foreground py-4 text-sm",children:[e.jsx(oa,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground/50"}),e.jsx("p",{children:"Attend events to earn points!"}),e.jsxs(In,{to:"/reward-store",className:"mt-3 inline-flex items-center gap-2 p-2 rounded-lg bg-primary/5 hover:bg-primary/10 transition-colors text-sm font-medium text-primary",children:[e.jsx(Oi,{className:"h-4 w-4"}),"Visit Reward Store",e.jsx(ga,{className:"h-4 w-4"})]})]})})]})}const qD=()=>dt({queryKey:["lead-sources"],queryFn:async()=>{const{data:s,error:t}=await q.from("lead_sources").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s}}),t6e=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{const{data:r}=await q.from("lead_sources").select("id, name").eq("is_active",!0).ilike("name",n.trim()),a=(r||[]).find(o=>o.name.toLowerCase()===n.trim().toLowerCase()&&!0);if(a)throw new Error(`Lead source "${a.name}" already exists`);const{data:i,error:l}=await q.from("lead_sources").insert({name:n,owner_user_id:t==null?void 0:t.id,sort_order:100}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source added")},onError:n=>{ae.error("Failed to add lead source"),console.error(n)}})},mrs=()=>{const s=Kt();return yt({mutationFn:async({id:t,name:n})=>{const{error:r}=await q.from("lead_sources").update({name:n}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source updated")},onError:t=>{ae.error(t.message||"Failed to update lead source")}})},prs=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("lead_sources").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lead-sources"]}),ae.success("Lead source removed")},onError:t=>{ae.error(t.message||"Failed to remove lead source")}})},s6e=(s,t)=>{const{user:n,isAdmin:r}=vs(),a=r&&t?t:n==null?void 0:n.id;return dt({queryKey:["scorecard-transactions",s,a],queryFn:async()=>{let i=q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",a).order("close_date",{ascending:!1});s&&(i=i.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:l,error:o}=await i;if(o)throw o;return l},enabled:!!a})},n6e=s=>{const{user:t,isAdmin:n}=vs(),r=n&&s?s:t==null?void 0:t.id;return dt({queryKey:["scorecard-transactions-all",r],queryFn:async()=>{const{data:a,error:i}=await q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).eq("owner_user_id",r).order("close_date",{ascending:!1});if(i)throw i;return a},enabled:!!r})},Eye=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_transactions").insert({...n,owner_user_id:t.id}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction added")},onError:n=>{ae.error("Failed to add transaction"),console.error(n)}})},frs=()=>{const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("scorecard_transactions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction updated")},onError:t=>{ae.error("Failed to update transaction"),console.error(t)}})},xrs=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("scorecard_transactions").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-transactions"]}),s.invalidateQueries({queryKey:["scorecard-transactions-all"]}),ae.success("Transaction deleted")},onError:t=>{ae.error("Failed to delete transaction"),console.error(t)}})},Umt=(s,t)=>{const{user:n,isAdmin:r}=vs(),a=r&&t?t:n==null?void 0:n.id;return dt({queryKey:["scorecard-goals",s,a],queryFn:async()=>{const{data:i,error:l}=await q.from("scorecard_goals").select("*").eq("owner_user_id",a).eq("year",s).maybeSingle();if(l)throw l;return i},enabled:!!a})},grs=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_goals").upsert({...n,owner_user_id:t.id},{onConflict:"owner_user_id,year"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["scorecard-goals",r.year]}),ae.success("Goals saved")},onError:n=>{ae.error("Failed to save goals"),console.error(n)}})},Aye=()=>{const{user:s}=vs();return dt({queryKey:["scorecard-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_settings").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t},enabled:!!(s!=null&&s.id)})},yrs=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{const{data:r,error:a}=await q.from("scorecard_settings").upsert({...n,user_id:t.id},{onConflict:"user_id"}).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["scorecard-settings"]}),ae.success("Settings saved")},onError:n=>{ae.error("Failed to save settings"),console.error(n)}})},qmt=(s,t)=>{const{data:n,isLoading:r}=s6e(s,t),{data:a,isLoading:i}=n6e(t),{data:l}=Aye(),o=(l==null?void 0:l.show_commission)??!0,c=d=>{if(!d||d.length===0)return{totalTransactions:0,buyerCount:0,sellerCount:0,totalVolume:0,averagePrice:0,totalCommission:0,totalNetToAgent:0,topLeadSource:null,transactionsByMonth:[],leadSourceBreakdown:[]};const u=d.filter(E=>E.transaction_type==="buyer").length,h=d.filter(E=>E.transaction_type==="seller").length,p=d.reduce((E,O)=>E+Number(O.sale_price),0),f=d.reduce((E,O)=>E+(Number(O.commission_amount)||0),0),y=d.reduce((E,O)=>{const D=Number(O.commission_amount)||0;if(!D)return E;let I=D;return O.brokerage_split_pct&&(I-=D*(O.brokerage_split_pct/100)),O.team_split_pct&&(I-=D*(O.team_split_pct/100)),O.franchise_fee_pct&&(I-=D*(O.franchise_fee_pct/100)),O.referral_fee_pct&&(I-=D*(O.referral_fee_pct/100)),O.transaction_fee&&(I-=O.transaction_fee),E+Math.max(0,I)},0),_={};d.forEach(E=>{var D;const O=((D=E.lead_source)==null?void 0:D.name)||"Unknown";_[O]=(_[O]||0)+1});const v=Object.entries(_).map(([E,O])=>({name:E,count:O})).sort((E,O)=>O.count-E.count),j=v[0]||null,w={};d.forEach(E=>{const O=Ll(E.close_date).toLocaleString("default",{month:"short"});w[O]=(w[O]||0)+1});const A=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(E=>({month:E,count:w[E]||0}));return{totalTransactions:d.length,buyerCount:u,sellerCount:h,totalVolume:p,averagePrice:d.length>0?p/d.length:0,totalCommission:o?f:0,totalNetToAgent:o?y:0,topLeadSource:j,transactionsByMonth:A,leadSourceBreakdown:v}};return{yearStats:c(n),lifetimeStats:c(a),isLoading:r||i,showCommission:o}},vrs=()=>{const{isAdmin:s}=vs();return dt({queryKey:["agents-with-transactions"],queryFn:async()=>{const{data:t,error:n}=await q.from("scorecard_transactions").select("owner_user_id").order("owner_user_id");if(n)throw n;const r=[...new Set(t.map(l=>l.owner_user_id))],{data:a,error:i}=await q.from("profiles").select("id, name, email").in("id",r);if(i)throw i;return a},enabled:s})},Vk={recency:40,touchpoints:30,transactions:20,referrals:10},kUe={warm:70,cooling:40};function brs(s){return s===null?0:s<=14?Vk.recency:s<=30?Vk.recency*.85:s<=60?Vk.recency*.65:s<=90?Vk.recency*.4:s<=180?Vk.recency*.2:Vk.recency*.05}function _rs(s){const t=Math.min(s/12,1);return Math.round(Vk.touchpoints*t)}function wrs(s){return s?Vk.transactions:0}function jrs(){return 0}function Nrs(s){return s>=kUe.warm?"warm":s>=kUe.cooling?"cooling":"at-risk"}function Mye(){const{data:s,isLoading:t}=ax(),{data:n}=Cmt(),{data:r}=iU(365),{data:a}=n6e(),i=N.useMemo(()=>{if(!s)return[];const o=new Date,c=BE(o,12),d={};r==null||r.forEach(h=>{new Date(h.completed_at)>=c&&(d[h.contact_id]=(d[h.contact_id]||0)+1)});const u=new Set((a==null?void 0:a.filter(h=>h.contact_id).map(h=>h.contact_id))||[]);return s.map(h=>{const p=(n==null?void 0:n[h.id])||null,f=p?Vv(o,new Date(p)):null,y=d[h.id]||0,_=u.has(h.id),v=brs(f),j=_rs(y),w=wrs(_),S=jrs(),A=Math.round(v+j+w+S),E={score:A,status:Nrs(A),breakdown:{recency:Math.round(v),touchpoints:Math.round(j),transactions:Math.round(w),referrals:Math.round(S)},lastTouchDate:p,daysSinceTouch:f,touchCountLast12Months:y,hasTransaction:_};return{...h,relationshipScore:E}})},[s,n,r,a]),l=N.useMemo(()=>{const o=i.filter(p=>p.relationshipScore.status==="warm").length,c=i.filter(p=>p.relationshipScore.status==="cooling").length,d=i.filter(p=>p.relationshipScore.status==="at-risk").length,u=i.length,h=u>0?Math.round(i.reduce((p,f)=>p+f.relationshipScore.score,0)/u):0;return{warm:o,cooling:c,atRisk:d,total:u,averageScore:h}},[i]);return{contactsWithScores:i,stats:l,isLoading:t}}function Vmt(){const s=Ln(),{stats:t,contactsWithScores:n,isLoading:r}=Mye();if(r)return e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Ws,{className:"h-5 w-40"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(Ws,{className:"h-20 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]})]});if(t.total===0)return e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"Relationship Health"]})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts to see your relationship health scores."}),e.jsx(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>s("/mission-control/contacts?new=true"),children:"Add Your First Contact"})]})]});const a=Math.round(t.warm/t.total*100),i=Math.round(t.cooling/t.total*100),l=Math.round(t.atRisk/t.total*100),o=n.filter(c=>c.relationshipScore.status==="at-risk").sort((c,d)=>c.relationshipScore.score-d.relationshipScore.score).slice(0,3);return e.jsxs(fe,{children:[e.jsxs(It,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:[e.jsx(go,{className:"h-5 w-5 text-emerald-500"}),"Relationship Health"]}),e.jsx("span",{className:"text-2xl font-bold",children:t.averageScore})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Average score across ",t.total," contacts"]})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-emerald-500"}),e.jsx("span",{children:"Warm"})]}),e.jsxs("span",{className:"font-medium",children:[t.warm," (",a,"%)"]})]}),e.jsx(fi,{value:a,className:"h-2 bg-muted [&>div]:bg-emerald-500"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-amber-500"}),e.jsx("span",{children:"Cooling Off"})]}),e.jsxs("span",{className:"font-medium",children:[t.cooling," (",i,"%)"]})]}),e.jsx(fi,{value:i,className:"h-2 bg-muted [&>div]:bg-amber-500"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full bg-red-500"}),e.jsx("span",{children:"At Risk"})]}),e.jsxs("span",{className:"font-medium",children:[t.atRisk," (",l,"%)"]})]}),e.jsx(fi,{value:l,className:"h-2 bg-muted [&>div]:bg-red-500"})]})]}),o.length>0&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(fb,{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(ga,{className:"h-3 w-3"})]})]},c.id))})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>s("/mission-control/contacts?filter=at-risk"),children:["View All At-Risk Contacts",e.jsx(ga,{className:"h-4 w-4 ml-1"})]})]})]})}const krs=()=>{var se;const{user:s,isAdmin:t}=vs(),n=Ln(),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState([]),[d,u]=N.useState([]),[h,p]=N.useState([]),[f,y]=N.useState([]),[_,v]=N.useState(new Set),[j,w]=N.useState([]),[S,A]=N.useState([]),[E,O]=N.useState([]),[D,I]=N.useState(null),[F,z]=N.useState(!0);N.useEffect(()=>{H()},[s]);const H=async()=>{var oe,he,ce,me,le;try{const[ve,ge,Te,Ie,Ce,Me,Pe,Re,Ae,Be,we]=await Promise.all([q.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),q.from("app_tiles").select("*").order("name"),q.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),q.from("events").select("*").order("event_date",{ascending:!0}),q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",s==null?void 0:s.id),q.from("canva_templates").select("id, name, preview_image_url, publish_date").order("publish_date",{ascending:!1}).limit(4),q.from("resource_kits").select("id, name, description, featured_image_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("academy_videos").select("id, title, description, thumbnail_url, duration, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("additional_services").select("id, name, description, preview_image_url, signup_link_url, publish_date").eq("is_published",!0).order("publish_date",{ascending:!1}).limit(4),q.from("dashboard_banners").select("id, title, description, image_url, link_url, link_text, placement, section_after").eq("is_active",!0).order("sort_order"),q.from("profiles").select("name").eq("id",s==null?void 0:s.id).single()]);(oe=we.data)!=null&&oe.name&&I(we.data.name);const Je=((he=ve.data)==null?void 0:he.map(Ke=>Ke.tag))||[],ke=new Set(((ce=Te.data)==null?void 0:ce.map(Ke=>Ke.app_id))||[]);v(ke);const je=(((me=ge.data)==null?void 0:me.filter(Ke=>!Ke.required_tags||Ke.required_tags.length===0?!0:Ke.required_tags.some(Ge=>Je.includes(Ge))))||[]).sort((Ke,Ge)=>Ke.name==="LevelUp Members Portal"?-1:Ge.name==="LevelUp Members Portal"?1:0);a(je.slice(0,6));const He=((le=Ie.data)==null?void 0:le.filter(Ke=>CL(Ke.event_date)!=="ended"))||[];l(He.slice(0,4)),w(Ce.data||[]),c(Me.data||[]),u(Pe.data||[]),p(Re.data||[]),y(Ae.data||[]);const $e=Be.data||[];A($e.filter(Ke=>Ke.placement==="top")),O($e.filter(Ke=>Ke.placement==="between"))}catch(ve){console.error("Error loading dashboard:",ve),ae.error("Failed to load dashboard data")}finally{z(!1)}},Z=async oe=>{var ce;const he=window.open("about:blank","_blank");try{await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:oe.app_id,app_name:oe.name,user_agent:navigator.userAgent});const{data:me,error:le}=await q.functions.invoke("sso-launch",{body:{app_id:oe.app_id}});if(le)throw le;me!=null&&me.redirect_url?he&&!he.closed?(he.location.href=me.redirect_url,(ce=he.focus)==null||ce.call(he)):window.location.assign(me.redirect_url):(he==null||he.close(),ae.error("Launch link unavailable"))}catch(me){he==null||he.close(),console.error("Error launching app:",me),ae.error("Failed to launch app")}},Y=oe=>j==null?void 0:j.some(he=>he.event_id===oe),W=oe=>{const he=j==null?void 0:j.find(ce=>ce.event_id===oe);return he==null?void 0:he.zoom_join_url};if(F)return e.jsx(Cs,{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 ee=oe=>E.filter(he=>he.section_after===oe);return e.jsxs(Cs,{title:"Dashboard",children:[e.jsx(pns,{events:i,registrations:j,onNavigateToEvents:()=>n("/events")}),S.length>0&&e.jsx("div",{className:"mb-8",children:e.jsx(iF,{banners:S})}),e.jsx(gns,{}),e.jsxs("div",{className:"mb-6",children:[e.jsxs("h2",{className:"text-2xl font-bold text-foreground",children:["Welcome back, ",(D||((se=s==null?void 0:s.user_metadata)==null?void 0:se.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(Ins,{}),e.jsx(Vmt,{}),e.jsx(hrs,{})]}),e.jsx(Gns,{}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Upcoming Events"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/events"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),i.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(yr,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No upcoming events"})]})})}):e.jsx("div",{className:"bg-card rounded-xl border border-border overflow-hidden divide-y divide-border max-w-full",children:i.map(oe=>{const he=Y(oe.id),ce=W(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 ${jUe(oe.event_date)?"bg-red-500/5 border-l-2 border-l-red-500":""}`,onClick:()=>n("/events"),children:[jUe(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(yf,{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 ",oB(new Date(oe.event_date))]})]}),e.jsx("div",{className:"hidden sm:flex flex-shrink-0",children:he?e.jsxs(B,{size:"sm",variant:"default",className:"gap-1",onClick:me=>{me.stopPropagation(),window.open(ce,"_blank")},children:[e.jsx(tr,{className:"h-3.5 w-3.5"}),"Join"]}):e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground group-hover:text-primary transition-colors",children:[e.jsx("span",{className:"text-sm",children:"Register"}),e.jsx(ga,{className:"h-4 w-4"})]})})]},oe.id)})})]}),ee("events").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(iF,{banners:ee("events")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Academy Videos"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/academy"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),h.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(jh,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No academy videos available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:h.map(oe=>e.jsxs("div",{onClick:()=>n(`/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(jh,{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))})]}),ee("academy").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(iF,{banners:ee("academy")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Resource Kits"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/toolbox"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),d.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(pf,{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:()=>n(`/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(pf,{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))})]}),ee("toolbox").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(iF,{banners:ee("toolbox")})}),e.jsxs("section",{className:"mb-10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"New Templates"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/templates"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),o.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(q2,{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:()=>n("/templates"),className:"group cursor-pointer bg-card rounded-xl border border-border overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30",children:[e.jsx("div",{className:"aspect-[3/2] bg-muted/50 overflow-hidden",children: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(q2,{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))})]}),ee("templates").length>0&&e.jsx("div",{className:"mb-10",children:e.jsx(iF,{banners:ee("templates")})}),e.jsx("div",{className:"mb-10",children:e.jsx(urs,{})}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Your Apps"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/apps"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),r.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-12",children:e.jsxs("div",{className:"text-center",children:[e.jsx(Pv,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No apps available"})]})})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:r.map(oe=>{const he=_.has(oe.id);return e.jsxs("div",{onClick:()=>Z(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})]}),he&&e.jsx(Pv,{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(B,{variant:"ghost",size:"sm",onClick:()=>n("/additional-services"),className:"gap-1 text-muted-foreground hover:text-foreground",children:["View All ",e.jsx(Oa,{className:"h-4 w-4"})]})]}),f.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsxs("div",{className:"text-center",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/50 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No additional services available"})]})})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:f.map(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(un,{className:"h-8 w-8 text-muted-foreground/50"})})}),e.jsxs("div",{className:"p-3",children:[e.jsx("h4",{className:"font-medium text-sm text-foreground truncate group-hover:text-primary transition-colors",children:oe.name}),oe.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:oe.description})]})]},oe.id))})]})]})};var Hmt="AlertDialog",[Srs,ufn]=uu(Hmt,[uot]),bN=uot(),Gmt=s=>{const{__scopeAlertDialog:t,...n}=s,r=bN(t);return e.jsx(B0e,{...r,...n,modal:!0})};Gmt.displayName=Hmt;var Crs="AlertDialogTrigger",Wmt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=bN(n);return e.jsx(SAe,{...a,...r,ref:t})});Wmt.displayName=Crs;var Trs="AlertDialogPortal",Kmt=s=>{const{__scopeAlertDialog:t,...n}=s,r=bN(t);return e.jsx($0e,{...r,...n})};Kmt.displayName=Trs;var Ers="AlertDialogOverlay",Ymt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=bN(n);return e.jsx(PD,{...a,...r,ref:t})});Ymt.displayName=Ers;var TL="AlertDialogContent",[Ars,Mrs]=Srs(TL),Irs=Tnt("AlertDialogContent"),Zmt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,children:r,...a}=s,i=bN(n),l=N.useRef(null),o=ji(t,l),c=N.useRef(null);return e.jsx(b7t,{contentName:TL,titleName:Qmt,docsSlug:"alert-dialog",children:e.jsx(Ars,{scope:n,cancelRef:c,children:e.jsxs(LD,{role:"alertdialog",...i,...a,ref:o,onOpenAutoFocus:xr(a.onOpenAutoFocus,d=>{var u;d.preventDefault(),(u=c.current)==null||u.focus({preventScroll:!0})}),onPointerDownOutside:d=>d.preventDefault(),onInteractOutside:d=>d.preventDefault(),children:[e.jsx(Irs,{children:r}),e.jsx(Lrs,{contentRef:l})]})})})});Zmt.displayName=TL;var Qmt="AlertDialogTitle",Xmt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=bN(n);return e.jsx(U$,{...a,...r,ref:t})});Xmt.displayName=Qmt;var Jmt="AlertDialogDescription",ept=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=bN(n);return e.jsx(q$,{...a,...r,ref:t})});ept.displayName=Jmt;var Prs="AlertDialogAction",tpt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,a=bN(n);return e.jsx(V$,{...a,...r,ref:t})});tpt.displayName=Prs;var spt="AlertDialogCancel",npt=N.forwardRef((s,t)=>{const{__scopeAlertDialog:n,...r}=s,{cancelRef:a}=Mrs(spt,n),i=bN(n),l=ji(t,a);return e.jsx(V$,{...i,...r,ref:l})});npt.displayName=spt;var Lrs=({contentRef:s})=>{const t=`\`${TL}\` requires a description for the component to be accessible for screen reader users. You can add a description to the \`${TL}\` by passing a \`${Jmt}\` 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 \`${TL}\`. If the description is confusing or duplicative for sighted users, you can use the \`@radix-ui/react-visually-hidden\` primitive as a wrapper around your description component. For more information, see https://radix-ui.com/primitives/docs/components/alert-dialog`;return N.useEffect(()=>{var r;document.getElementById((r=s.current)==null?void 0:r.getAttribute("aria-describedby"))||console.warn(t)},[t,s]),null},Drs=Gmt,Rrs=Wmt,Ors=Kmt,rpt=Ymt,apt=Zmt,ipt=tpt,opt=npt,lpt=Xmt,cpt=ept;const Oo=Drs,Eh=Rrs,Frs=Ors,dpt=N.forwardRef(({className:s,...t},n)=>e.jsx(rpt,{className:Mt("fixed inset-0 z-50 bg-black/80 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",s),...t,ref:n}));dpt.displayName=rpt.displayName;const Co=N.forwardRef(({className:s,...t},n)=>e.jsxs(Frs,{children:[e.jsx(dpt,{}),e.jsx(apt,{ref:n,className:Mt("fixed left-[50%] top-[50%] z-50 grid w-full max-w-lg translate-x-[-50%] translate-y-[-50%] gap-4 border bg-background p-6 shadow-lg duration-200 data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[state=closed]:slide-out-to-left-1/2 data-[state=closed]:slide-out-to-top-[48%] data-[state=open]:slide-in-from-left-1/2 data-[state=open]:slide-in-from-top-[48%] sm:rounded-lg",s),...t})]}));Co.displayName=apt.displayName;const To=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col space-y-2 text-center sm:text-left",s),...t});To.displayName="AlertDialogHeader";const Eo=({className:s,...t})=>e.jsx("div",{className:Mt("flex flex-col-reverse sm:flex-row sm:justify-end sm:space-x-2",s),...t});Eo.displayName="AlertDialogFooter";const Ao=N.forwardRef(({className:s,...t},n)=>e.jsx(lpt,{ref:n,className:Mt("text-lg font-semibold",s),...t}));Ao.displayName=lpt.displayName;const Mo=N.forwardRef(({className:s,...t},n)=>e.jsx(cpt,{ref:n,className:Mt("text-sm text-muted-foreground",s),...t}));Mo.displayName=cpt.displayName;const wo=N.forwardRef(({className:s,...t},n)=>e.jsx(ipt,{ref:n,className:Mt(m8(),s),...t}));wo.displayName=ipt.displayName;const Io=N.forwardRef(({className:s,...t},n)=>e.jsx(opt,{ref:n,className:Mt(m8({variant:"outline"}),"mt-2 sm:mt-0",s),...t}));Io.displayName=opt.displayName;const zrs=[{key:"contacts",label:"Contacts",icon:Cr,description:"View, add, and edit contacts"},{key:"pipeline",label:"Deal Pipeline",icon:GS,description:"View, add, and move deals"},{key:"client_portal",label:"Client Portals",icon:pf,description:"Manage client portals on deals"},{key:"videos",label:"Videos",icon:fr,description:"View and upload videos"},{key:"listings",label:"Listings",icon:Or,description:"View, create, and edit listings"},{key:"scorecard",label:"Scorecard",icon:cb,description:"View and add transactions"},{key:"popbys",label:"Pop-bys",icon:ka,description:"View and log pop-bys"},{key:"digital_card",label:"Digital Card",icon:uf,description:"Create and edit digital business card"},{key:"guest_book",label:"Guest Book",icon:rm,description:"Manage open house guest books"},{key:"presentations",label:"Presentations",icon:ny,description:"Create and manage smart presentations"}];function Brs(){var D;const{user:s}=vs(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState({email:"",name:"",password:""}),[f,y]=N.useState("create"),[_,v]=N.useState(!1),[j,w]=N.useState(null);N.useEffect(()=>{s&&S()},[s]);const S=async()=>{if(s){a(!0);try{const{data:I,error:F}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions, created_at").eq("agent_id",s.id);if(F)throw F;if(I&&I.length>0){const z=I.map(Y=>Y.assistant_id),{data:H}=await q.from("profiles").select("id, name, email").in("id",z),Z=I.map(Y=>{const W=H==null?void 0:H.find(ee=>ee.id===Y.assistant_id);return{...Y,permissions:Y.permissions,assistant_profile:W?{name:W.name||"",email:W.email||""}:void 0}});n(Z)}else n([])}catch(I){console.error("Error loading assistants:",I)}finally{a(!1)}}},A=async()=>{if(s){if(f==="link"){if(!h.email.trim()){ae.error("Please enter the assistant's email");return}v(!0);try{const{data:{session:I}}=await q.auth.getSession();if(!I)throw new Error("Not authenticated");const{data:F,error:z}=await q.from("profiles").select("id, name, email").eq("email",h.email.trim().toLowerCase()).single();if(z||!F){ae.error("No account found with that email. Try creating a new assistant instead.");return}const{data:H}=await q.from("agent_assistant_assignments").select("id").eq("agent_id",s.id).eq("assistant_id",F.id);if(H&&H.length>0){ae.error("This assistant is already assigned to you");return}const Z=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.access_token}`},body:JSON.stringify({userId:F.id,role:"assistant",action:"add",agentId:s.id})}),Y=await Z.json();if(!Z.ok)throw new Error(Y.error||"Failed to assign assistant role");const{error:W}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:F.id,permissions:{contacts:!0,pipeline:!0,videos:!1,listings:!1,scorecard:!1,popbys:!1,digital_card:!1,client_portal:!1,guest_book:!1,presentations:!1}});if(W)throw W;ae.success(`${F.name||F.email} linked as your assistant`),l(!1),p({email:"",name:"",password:""}),S()}catch(I){console.error("Error linking assistant:",I),ae.error(I.message||"Failed to link assistant")}finally{v(!1)}return}if(!h.email.trim()||!h.name.trim()||!h.password.trim()){ae.error("Please fill in all fields");return}if(h.password.length<6){ae.error("Password must be at least 6 characters");return}v(!0);try{const{data:{session:I}}=await q.auth.getSession();if(!I)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 ${I.access_token}`},body:JSON.stringify({email:h.email.trim(),password:h.password,name:h.name.trim(),purpose:"assistant"})}),z=await F.json();if(!F.ok)throw new Error(z.error||"Failed to create assistant account");const H=z.userId||z.id;if(!H)throw new Error("No user ID returned");const Z=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.access_token}`},body:JSON.stringify({userId:H,role:"assistant",action:"add",agentId:s.id})}),Y=await Z.json();if(!Z.ok)throw new Error(Y.error||"Failed to assign assistant role");const{error:W}=await q.from("agent_assistant_assignments").insert({agent_id:s.id,assistant_id:H,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(W)throw W;ae.success(`Assistant account created for ${h.name.trim()}`),l(!1),p({email:"",name:"",password:""}),S()}catch(I){console.error("Error adding assistant:",I),ae.error(I.message||"Failed to add assistant")}finally{v(!1)}}},E=async()=>{if(!(!d||!s))try{const{data:{session:I}}=await q.auth.getSession();if(!I)throw new Error("Not authenticated");const{error:F}=await q.from("agent_assistant_assignments").delete().eq("id",d.id);if(F)throw F;const{data:z}=await q.from("agent_assistant_assignments").select("id").eq("assistant_id",d.assistant_id);(!z||z.length===0)&&await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${I.access_token}`},body:JSON.stringify({userId:d.assistant_id,role:"assistant",action:"remove"})}),ae.success("Assistant removed"),c(!1),u(null),S()}catch(I){console.error("Error removing assistant:",I),ae.error(I.message||"Failed to remove assistant")}},O=async(I,F,z)=>{w(I);try{const H=t.find(W=>W.id===I);if(!H)return;const Z={...H.permissions,[F]:z},{error:Y}=await q.from("agent_assistant_assignments").update({permissions:Z}).eq("id",I);if(Y)throw Y;n(W=>W.map(ee=>ee.id===I?{...ee,permissions:Z}:ee))}catch(H){console.error("Error updating permissions:",H),ae.error("Failed to update permissions")}finally{w(null)}};return r?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"My Assistants"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"My Assistants"]}),e.jsx(Vn,{children:"Add assistants to help manage your Agent OS"})]}),e.jsxs(B,{size:"sm",onClick:()=>{y("create"),l(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Assistant"]})]})}),e.jsx(Ee,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No assistant assigned. Add one to help manage your contacts, deals, and more."}):e.jsx("div",{className:"space-y-4",children:t.map(I=>{var F,z,H,Z;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(Jr,{className:"h-10 w-10",children:e.jsx(ea,{children:((z=(F=I.assistant_profile)==null?void 0:F.name)==null?void 0:z.split(" ").map(Y=>Y[0]).join("").toUpperCase())||"A"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((H=I.assistant_profile)==null?void 0:H.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((Z=I.assistant_profile)==null?void 0:Z.email)||""})]}),e.jsxs(Ue,{variant:"secondary",className:"ml-2",children:[e.jsx(Ih,{className:"h-3 w-3 mr-1"}),"Assistant"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",onClick:()=>{u(I),c(!0)},children:e.jsx(_n,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Permissions"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:zrs.map(Y=>{const W=Y.icon;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md border",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(W,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:Y.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Y.description})]})]}),e.jsx(jn,{checked:I.permissions[Y.key]||!1,onCheckedChange:ee=>O(I.id,Y.key,ee),disabled:j===I.id})]},Y.key)})})]})]},I.id)})})})]}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Add Assistant"}),e.jsx(Jn,{children:f==="create"?"Create a new account for your assistant.":"Link an existing assistant account by their email."})]}),e.jsxs("div",{className:"flex gap-2 mb-2",children:[e.jsxs(B,{variant:f==="create"?"default":"outline",size:"sm",onClick:()=>y("create"),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"Create New"]}),e.jsxs(B,{variant:f==="link"?"default":"outline",size:"sm",onClick:()=>y("link"),children:[e.jsx(Yo,{className:"h-3 w-3 mr-1"}),"Link Existing"]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"assistant-name",children:"Name"}),e.jsx(ye,{id:"assistant-name",value:h.name,onChange:I=>p({...h,name:I.target.value}),placeholder:"Assistant's full name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"assistant-email",children:"Email"}),e.jsx(ye,{id:"assistant-email",type:"email",value:h.email,onChange:I=>p({...h,email:I.target.value}),placeholder:"assistant@email.com"})]}),f==="create"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"assistant-password",children:"Temporary Password"}),e.jsx(ye,{id:"assistant-password",type:"password",value:h.password,onChange:I=>p({...h,password:I.target.value}),placeholder:"Min 6 characters"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your assistant can change this after their first login."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:A,disabled:_,children:[_&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),f==="create"?"Create Assistant":"Link Assistant"]})]})]})}),e.jsx(Oo,{open:o,onOpenChange:c,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove Assistant?"}),e.jsxs(Mo,{children:["This will remove ",(D=d==null?void 0:d.assistant_profile)==null?void 0:D.name,"'s access to your Agent OS. Their account will remain active but they won't be able to manage your data."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:E,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function Xp(s){this.content=s}Xp.prototype={constructor:Xp,find:function(s){for(var t=0;t>1}};Xp.from=function(s){if(s instanceof Xp)return s;var t=[];if(s)for(var n in s)t.push(n,s[n]);return new Xp(t)};function upt(s,t,n){for(let r=0;;r++){if(r==s.childCount||r==t.childCount)return s.childCount==t.childCount?null:n;let a=s.child(r),i=t.child(r);if(a==i){n+=a.nodeSize;continue}if(!a.sameMarkup(i))return n;if(a.isText&&a.text!=i.text){for(let l=0;a.text[l]==i.text[l];l++)n++;return n}if(a.content.size||i.content.size){let l=upt(a.content,i.content,n+1);if(l!=null)return l}n+=a.nodeSize}}function hpt(s,t,n,r){for(let a=s.childCount,i=t.childCount;;){if(a==0||i==0)return a==i?null:{a:n,b:r};let l=s.child(--a),o=t.child(--i),c=l.nodeSize;if(l==o){n-=c,r-=c;continue}if(!l.sameMarkup(o))return{a:n,b:r};if(l.isText&&l.text!=o.text){let d=0,u=Math.min(l.text.length,o.text.length);for(;dt&&r(c,a+o,i||null,l)!==!1&&c.content.size){let u=o+1;c.nodesBetween(Math.max(0,t-u),Math.min(c.content.size,n-u),r,a+u)}o=d}}descendants(t){this.nodesBetween(0,this.size,t)}textBetween(t,n,r,a){let i="",l=!0;return this.nodesBetween(t,n,(o,c)=>{let d=o.isText?o.text.slice(Math.max(t,c)-c,n-c):o.isLeaf?a?typeof a=="function"?a(o):a:o.type.spec.leafText?o.type.spec.leafText(o):"":"";o.isBlock&&(o.isLeaf&&d||o.isTextblock)&&r&&(l?l=!1:i+=r),i+=d},0),i}append(t){if(!t.size)return this;if(!this.size)return t;let n=this.lastChild,r=t.firstChild,a=this.content.slice(),i=0;for(n.isText&&n.sameMarkup(r)&&(a[a.length-1]=n.withText(n.text+r.text),i=1);it)for(let i=0,l=0;lt&&((ln)&&(o.isText?o=o.cut(Math.max(0,t-l),Math.min(o.text.length,n-l)):o=o.cut(Math.max(0,t-l-1),Math.min(o.content.size,n-l-1))),r.push(o),a+=o.nodeSize),l=c}return new Dx(r,a)}cutByIndex(t,n){return t==n?Dx.empty:t==0&&n==this.content.length?this:new Dx(this.content.slice(t,n))}replaceChild(t,n){let r=this.content[t];if(r==n)return this;let a=this.content.slice(),i=this.size+n.nodeSize-r.nodeSize;return a[t]=n,new Dx(a,i)}addToStart(t){return new Dx([t].concat(this.content),this.size+t.nodeSize)}addToEnd(t){return new Dx(this.content.concat(t),this.size+t.nodeSize)}eq(t){if(this.content.length!=t.content.length)return!1;for(let n=0;nthis.size||t<0)throw new RangeError(`Position ${t} outside of fragment (${this})`);for(let n=0,r=0;;n++){let a=this.child(n),i=r+a.nodeSize;if(i>=t)return i==t?aH(n+1,i):aH(n,r);r=i}}toString(){return"<"+this.toStringInner()+">"}toStringInner(){return this.content.join(", ")}toJSON(){return this.content.length?this.content.map(t=>t.toJSON()):null}static fromJSON(t,n){if(!n)return Dx.empty;if(!Array.isArray(n))throw new RangeError("Invalid input for Fragment.fromJSON");return new Dx(n.map(t.nodeFromJSON))}static fromArray(t){if(!t.length)return Dx.empty;let n,r=0;for(let a=0;athis.type.rank&&(n||(n=t.slice(0,a)),n.push(this),r=!0),n&&n.push(i)}}return n||(n=t.slice()),r||n.push(this),n}removeFromSet(t){for(let n=0;nr.type.rank-a.type.rank),n}};td.none=[];class _fe extends Error{}class ba{constructor(t,n,r){this.content=t,this.openStart=n,this.openEnd=r}get size(){return this.content.size-this.openStart-this.openEnd}insertAt(t,n){let r=ppt(this.content,t+this.openStart,n);return r&&new ba(r,this.openStart,this.openEnd)}removeBetween(t,n){return new ba(mpt(this.content,t+this.openStart,n+this.openStart),this.openStart,this.openEnd)}eq(t){return this.content.eq(t.content)&&this.openStart==t.openStart&&this.openEnd==t.openEnd}toString(){return this.content+"("+this.openStart+","+this.openEnd+")"}toJSON(){if(!this.content.size)return null;let t={content:this.content.toJSON()};return this.openStart>0&&(t.openStart=this.openStart),this.openEnd>0&&(t.openEnd=this.openEnd),t}static fromJSON(t,n){if(!n)return ba.empty;let r=n.openStart||0,a=n.openEnd||0;if(typeof r!="number"||typeof a!="number")throw new RangeError("Invalid input for Slice.fromJSON");return new ba($r.fromJSON(t,n.content),r,a)}static maxOpen(t,n=!0){let r=0,a=0;for(let i=t.firstChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.firstChild)r++;for(let i=t.lastChild;i&&!i.isLeaf&&(n||!i.type.spec.isolating);i=i.lastChild)a++;return new ba(t,r,a)}}ba.empty=new ba($r.empty,0,0);function mpt(s,t,n){let{index:r,offset:a}=s.findIndex(t),i=s.maybeChild(r),{index:l,offset:o}=s.findIndex(n);if(a==t||i.isText){if(o!=n&&!s.child(l).isText)throw new RangeError("Removing non-flat range");return s.cut(0,t).append(s.cut(n))}if(r!=l)throw new RangeError("Removing non-flat range");return s.replaceChild(r,i.copy(mpt(i.content,t-a-1,n-a-1)))}function ppt(s,t,n,r){let{index:a,offset:i}=s.findIndex(t),l=s.maybeChild(a);if(i==t||l.isText)return r&&!r.canReplace(a,a,n)?null:s.cut(0,t).append(n).append(s.cut(t));let o=ppt(l.content,t-i-1,n,l);return o&&s.replaceChild(a,l.copy(o))}function $rs(s,t,n){if(n.openStart>s.depth)throw new _fe("Inserted content deeper than insertion position");if(s.depth-n.openStart!=t.depth-n.openEnd)throw new _fe("Inconsistent open depths");return fpt(s,t,n,0)}function fpt(s,t,n,r){let a=s.index(r),i=s.node(r);if(a==t.index(r)&&r=0&&s.isText&&s.sameMarkup(t[n])?t[n]=s.withText(t[n].text+s.text):t.push(s)}function W9(s,t,n,r){let a=(t||s).node(n),i=0,l=t?t.index(n):a.childCount;s&&(i=s.index(n),s.depth>n?i++:s.textOffset&&(BA(s.nodeAfter,r),i++));for(let o=i;oa&&sCe(s,t,a+1),l=r.depth>a&&sCe(n,r,a+1),o=[];return W9(null,s,a,o),i&&l&&t.index(a)==n.index(a)?(xpt(i,l),BA($A(i,gpt(s,t,n,r,a+1)),o)):(i&&BA($A(i,wfe(s,t,a+1)),o),W9(t,n,a,o),l&&BA($A(l,wfe(n,r,a+1)),o)),W9(r,null,a,o),new $r(o)}function wfe(s,t,n){let r=[];if(W9(null,s,n,r),s.depth>n){let a=sCe(s,t,n+1);BA($A(a,wfe(s,t,n+1)),r)}return W9(t,null,n,r),new $r(r)}function Urs(s,t){let n=t.depth-s.openStart,a=t.node(n).copy(s.content);for(let i=n-1;i>=0;i--)a=t.node(i).copy($r.from(a));return{start:a.resolveNoCache(s.openStart+n),end:a.resolveNoCache(a.content.size-s.openEnd-n)}}class lB{constructor(t,n,r){this.pos=t,this.path=n,this.parentOffset=r,this.depth=n.length/3-1}resolveDepth(t){return t==null?this.depth:t<0?this.depth+t:t}get parent(){return this.node(this.depth)}get doc(){return this.node(0)}node(t){return this.path[this.resolveDepth(t)*3]}index(t){return this.path[this.resolveDepth(t)*3+1]}indexAfter(t){return t=this.resolveDepth(t),this.index(t)+(t==this.depth&&!this.textOffset?0:1)}start(t){return t=this.resolveDepth(t),t==0?0:this.path[t*3-1]+1}end(t){return t=this.resolveDepth(t),this.start(t)+this.node(t).content.size}before(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position before the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]}after(t){if(t=this.resolveDepth(t),!t)throw new RangeError("There is no position after the top-level node");return t==this.depth+1?this.pos:this.path[t*3-1]+this.path[t*3].nodeSize}get textOffset(){return this.pos-this.path[this.path.length-1]}get nodeAfter(){let t=this.parent,n=this.index(this.depth);if(n==t.childCount)return null;let r=this.pos-this.path[this.path.length-1],a=t.child(n);return r?t.child(n).cut(r):a}get nodeBefore(){let t=this.index(this.depth),n=this.pos-this.path[this.path.length-1];return n?this.parent.child(t).cut(0,n):t==0?null:this.parent.child(t-1)}posAtIndex(t,n){n=this.resolveDepth(n);let r=this.path[n*3],a=n==0?0:this.path[n*3-1]+1;for(let i=0;i0;n--)if(this.start(n)<=t&&this.end(n)>=t)return n;return 0}blockRange(t=this,n){if(t.pos=0;r--)if(t.pos<=this.end(r)&&(!n||n(this.node(r))))return new jfe(this,t,r);return null}sameParent(t){return this.pos-this.parentOffset==t.pos-t.parentOffset}max(t){return t.pos>this.pos?t:this}min(t){return t.pos=0&&n<=t.content.size))throw new RangeError("Position "+n+" out of range");let r=[],a=0,i=n;for(let l=t;;){let{index:o,offset:c}=l.content.findIndex(i),d=i-c;if(r.push(l,o,a+c),!d||(l=l.child(o),l.isText))break;i=d-1,a+=c+1}return new lB(n,r,i)}static resolveCached(t,n){let r=SUe.get(t);if(r)for(let i=0;it&&this.nodesBetween(t,n,i=>(r.isInSet(i.marks)&&(a=!0),!a)),a}get isBlock(){return this.type.isBlock}get isTextblock(){return this.type.isTextblock}get inlineContent(){return this.type.inlineContent}get isInline(){return this.type.isInline}get isText(){return this.type.isText}get isLeaf(){return this.type.isLeaf}get isAtom(){return this.type.isAtom}toString(){if(this.type.spec.toDebugString)return this.type.spec.toDebugString(this);let t=this.type.name;return this.content.size&&(t+="("+this.content.toStringInner()+")"),ypt(this.marks,t)}contentMatchAt(t){let n=this.type.contentMatch.matchFragment(this.content,0,t);if(!n)throw new Error("Called contentMatchAt on a node with invalid content");return n}canReplace(t,n,r=$r.empty,a=0,i=r.childCount){let l=this.contentMatchAt(t).matchFragment(r,a,i),o=l&&l.matchFragment(this.content,n);if(!o||!o.validEnd)return!1;for(let c=a;cn.type.name)}`);this.content.forEach(n=>n.check())}toJSON(){let t={type:this.type.name};for(let n in this.attrs){t.attrs=this.attrs;break}return this.content.size&&(t.content=this.content.toJSON()),this.marks.length&&(t.marks=this.marks.map(n=>n.toJSON())),t}static fromJSON(t,n){if(!n)throw new RangeError("Invalid input for Node.fromJSON");let r;if(n.marks){if(!Array.isArray(n.marks))throw new RangeError("Invalid mark data for Node.fromJSON");r=n.marks.map(t.markFromJSON)}if(n.type=="text"){if(typeof n.text!="string")throw new RangeError("Invalid text node in JSON");return t.text(n.text,r)}let a=$r.fromJSON(t,n.content),i=t.nodeType(n.type).create(n.attrs,a,r);return i.type.checkAttrs(i.attrs),i}};c4.prototype.text=void 0;class Nfe extends c4{constructor(t,n,r,a){if(super(t,n,null,a),!r)throw new RangeError("Empty text nodes are not allowed");this.text=r}toString(){return this.type.spec.toDebugString?this.type.spec.toDebugString(this):ypt(this.marks,JSON.stringify(this.text))}get textContent(){return this.text}textBetween(t,n){return this.text.slice(t,n)}get nodeSize(){return this.text.length}mark(t){return t==this.marks?this:new Nfe(this.type,this.attrs,this.text,t)}withText(t){return t==this.text?this:new Nfe(this.type,this.attrs,t,this.marks)}cut(t=0,n=this.text.length){return t==0&&n==this.text.length?this:this.withText(this.text.slice(t,n))}eq(t){return this.sameMarkup(t)&&this.text==t.text}toJSON(){let t=super.toJSON();return t.text=this.text,t}}function ypt(s,t){for(let n=s.length-1;n>=0;n--)t=s[n].type.name+"("+t+")";return t}class xM{constructor(t){this.validEnd=t,this.next=[],this.wrapCache=[]}static parse(t,n){let r=new Grs(t,n);if(r.next==null)return xM.empty;let a=vpt(r);r.next&&r.err("Unexpected trailing text");let i=Jrs(Xrs(a));return eas(i,r),i}matchType(t){for(let n=0;nd.createAndFill()));for(let d=0;d=this.next.length)throw new RangeError(`There's no ${t}th edge in this content match`);return this.next[t]}toString(){let t=[];function n(r){t.push(r);for(let a=0;a{let i=a+(r.validEnd?"*":" ")+" ";for(let l=0;l"+t.indexOf(r.next[l].next);return i}).join(` `)}}xM.empty=new xM(!0);class Grs{constructor(t,n){this.string=t,this.nodeTypes=n,this.inline=null,this.pos=0,this.tokens=t.split(/\s*(?=\b|\W|$)/),this.tokens[this.tokens.length-1]==""&&this.tokens.pop(),this.tokens[0]==""&&this.tokens.shift()}get next(){return this.tokens[this.pos]}eat(t){return this.next==t&&(this.pos++||!0)}err(t){throw new SyntaxError(t+" (in content expression '"+this.string+"')")}}function vpt(s){let t=[];do t.push(Wrs(s));while(s.eat("|"));return t.length==1?t[0]:{type:"choice",exprs:t}}function Wrs(s){let t=[];do t.push(Krs(s));while(s.next&&s.next!=")"&&s.next!="|");return t.length==1?t[0]:{type:"seq",exprs:t}}function Krs(s){let t=Qrs(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=Yrs(s,t);else break;return t}function CUe(s){/\D/.test(s.next)&&s.err("Expected number, got '"+s.next+"'");let t=Number(s.next);return s.pos++,t}function Yrs(s,t){let n=CUe(s),r=n;return s.eat(",")&&(s.next!="}"?r=CUe(s):r=-1),s.eat("}")||s.err("Unclosed braced range"),{type:"range",min:n,max:r,expr:t}}function Zrs(s,t){let n=s.nodeTypes,r=n[t];if(r)return[r];let a=[];for(let i in n){let l=n[i];l.isInGroup(t)&&a.push(l)}return a.length==0&&s.err("No node type or group '"+t+"' found"),a}function Qrs(s){if(s.eat("(")){let t=vpt(s);return s.eat(")")||s.err("Missing closing paren"),t}else if(/\W/.test(s.next))s.err("Unexpected token '"+s.next+"'");else{let t=Zrs(s,s.next).map(n=>(s.inline==null?s.inline=n.isInline:s.inline!=n.isInline&&s.err("Mixing inline and block content"),{type:"name",value:n}));return s.pos++,t.length==1?t[0]:{type:"choice",exprs:t}}}function Xrs(s){let t=[[]];return a(i(s,0),n()),t;function n(){return t.push([])-1}function r(l,o,c){let d={term:c,to:o};return t[l].push(d),d}function a(l,o){l.forEach(c=>c.to=o)}function i(l,o){if(l.type=="choice")return l.exprs.reduce((c,d)=>c.concat(i(d,o)),[]);if(l.type=="seq")for(let c=0;;c++){let d=i(l.exprs[c],o);if(c==l.exprs.length-1)return d;a(d,o=n())}else if(l.type=="star"){let c=n();return r(o,c),a(i(l.expr,c),c),[r(c)]}else if(l.type=="plus"){let c=n();return a(i(l.expr,o),c),a(i(l.expr,c),c),[r(c)]}else{if(l.type=="opt")return[r(o)].concat(i(l.expr,o));if(l.type=="range"){let c=o;for(let d=0;d{s[l].forEach(({term:o,to:c})=>{if(!o)return;let d;for(let u=0;u{d||a.push([o,d=[]]),d.indexOf(u)==-1&&d.push(u)})})});let i=t[r.join(",")]=new xM(r.indexOf(s.length-1)>-1);for(let l=0;l-1}get whitespace(){return this.spec.whitespace||(this.spec.code?"pre":"normal")}hasRequiredAttrs(){for(let t in this.attrs)if(this.attrs[t].isRequired)return!0;return!1}compatibleContent(t){return this==t||this.contentMatch.compatible(t.contentMatch)}computeAttrs(t){return!t&&this.defaultAttrs?this.defaultAttrs:wpt(this.attrs,t)}create(t=null,n,r){if(this.isText)throw new Error("NodeType.create can't construct text nodes");return new c4(this,this.computeAttrs(t),$r.from(n),td.setFrom(r))}createChecked(t=null,n,r){return n=$r.from(n),this.checkContent(n),new c4(this,this.computeAttrs(t),n,td.setFrom(r))}createAndFill(t=null,n,r){if(t=this.computeAttrs(t),n=$r.from(n),n.size){let l=this.contentMatch.fillBefore(n);if(!l)return null;n=l.append(n)}let a=this.contentMatch.matchFragment(n),i=a&&a.fillBefore($r.empty,!0);return i?new c4(this,t,n.append(i),td.setFrom(r)):null}validContent(t){let n=this.contentMatch.matchFragment(t);if(!n||!n.validEnd)return!1;for(let r=0;r-1}allowsMarks(t){if(this.markSet==null)return!0;for(let n=0;nr[i]=new kpt(i,n,l));let a=n.spec.topNode||"doc";if(!r[a])throw new RangeError("Schema is missing its top node type ('"+a+"')");if(!r.text)throw new RangeError("Every schema needs a 'text' type");for(let i in r.text.attrs)throw new RangeError("The text node type should not have attributes");return r}};function tas(s,t,n){let r=n.split("|");return a=>{let i=a===null?"null":typeof a;if(r.indexOf(i)<0)throw new RangeError(`Expected value of type ${r} for attribute ${t} on type ${s}, got ${i}`)}}class sas{constructor(t,n,r){this.hasDefault=Object.prototype.hasOwnProperty.call(r,"default"),this.default=r.default,this.validate=typeof r.validate=="string"?tas(t,n,r.validate):r.validate}get isRequired(){return!this.hasDefault}}class Iye{constructor(t,n,r,a){this.name=t,this.rank=n,this.schema=r,this.spec=a,this.attrs=Npt(t,a.attrs),this.excluded=null;let i=_pt(this.attrs);this.instance=i?new td(this,i):null}create(t=null){return!t&&this.instance?this.instance:new td(this,wpt(this.attrs,t))}static compile(t,n){let r=Object.create(null),a=0;return t.forEach((i,l)=>r[i]=new Iye(i,a++,n,l)),r}removeFromSet(t){for(var n=0;n-1}}class Spt{constructor(t){this.linebreakReplacement=null,this.cached=Object.create(null);let n=this.spec={};for(let a in t)n[a]=t[a];n.nodes=Xp.from(t.nodes),n.marks=Xp.from(t.marks||{}),this.nodes=EUe.compile(this.spec.nodes,this),this.marks=Iye.compile(this.spec.marks,this);let r=Object.create(null);for(let a in this.nodes){if(a in this.marks)throw new RangeError(a+" can not be both a node and a mark");let i=this.nodes[a],l=i.spec.content||"",o=i.spec.marks;if(i.contentMatch=r[l]||(r[l]=xM.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?AUe(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==""?[]:AUe(this,l.split(" "))}this.nodeFromJSON=a=>c4.fromJSON(this,a),this.markFromJSON=a=>td.fromJSON(this,a),this.topNodeType=this.nodes[this.spec.topNode||"doc"],this.cached.wrappings=Object.create(null)}node(t,n=null,r,a){if(typeof t=="string")t=this.nodeType(t);else if(t instanceof EUe){if(t.schema!=this)throw new RangeError("Node type from different schema used ("+t.name+")")}else throw new RangeError("Invalid node type: "+t);return t.createChecked(n,r,a)}text(t,n){let r=this.nodes.text;return new Nfe(r,r.defaultAttrs,t,td.setFrom(n))}mark(t,n){return typeof t=="string"&&(t=this.marks[t]),t.create(n)}nodeType(t){let n=this.nodes[t];if(!n)throw new RangeError("Unknown node type: "+t);return n}}function AUe(s,t){let n=[];for(let r=0;r-1)&&n.push(l=c)}if(!l)throw new SyntaxError("Unknown mark type: '"+t[r]+"'")}return n}function nas(s){return s.tag!=null}function ras(s){return s.style!=null}let K9=class rCe{constructor(t,n){this.schema=t,this.rules=n,this.tags=[],this.styles=[];let r=this.matchedStyles=[];n.forEach(a=>{if(nas(a))this.tags.push(a);else if(ras(a)){let i=/[^=]*/.exec(a.style)[0];r.indexOf(i)<0&&r.push(i),this.styles.push(a)}}),this.normalizeLists=!this.tags.some(a=>{if(!/^(ul|ol)\b/.test(a.tag)||!a.node)return!1;let i=t.nodes[a.node];return i.contentMatch.matchType(i)})}parse(t,n={}){let r=new IUe(this,n,!1);return r.addAll(t,td.none,n.from,n.to),r.finish()}parseSlice(t,n={}){let r=new IUe(this,n,!0);return r.addAll(t,td.none,n.from,n.to),ba.maxOpen(r.finish())}matchTag(t,n,r){for(let a=r?this.tags.indexOf(r)+1:0;at.length&&(o.charCodeAt(t.length)!=61||o.slice(t.length+1)!=n))){if(l.getAttrs){let c=l.getAttrs(n);if(c===!1)continue;l.attrs=c||void 0}return l}}}static schemaRules(t){let n=[];function r(a){let i=a.priority==null?50:a.priority,l=0;for(;l{r(l=PUe(l)),l.mark||l.ignore||l.clearMark||(l.mark=a)})}for(let a in t.nodes){let i=t.nodes[a].spec.parseDOM;i&&i.forEach(l=>{r(l=PUe(l)),l.node||l.ignore||l.mark||(l.node=a)})}return n}static fromSchema(t){return t.cached.domParser||(t.cached.domParser=new rCe(t,rCe.schemaRules(t)))}};const Cpt={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},aas={head:!0,noscript:!0,object:!0,script:!0,style:!0,title:!0},Tpt={ol:!0,ul:!0},cB=1,aCe=2,Y9=4;function MUe(s,t,n){return t!=null?(t?cB:0)|(t==="full"?aCe:0):s&&s.whitespace=="pre"?cB|aCe:n&~Y9}class iH{constructor(t,n,r,a,i,l){this.type=t,this.attrs=n,this.marks=r,this.solid=a,this.options=l,this.content=[],this.activeMarks=td.none,this.match=i||(l&Y9?null:t.contentMatch)}findWrapping(t){if(!this.match){if(!this.type)return[];let n=this.type.contentMatch.fillBefore($r.from(t));if(n)this.match=this.type.contentMatch.matchFragment(n);else{let r=this.type.contentMatch,a;return(a=r.findWrapping(t.type))?(this.match=r,a):null}}return this.match.findWrapping(t.type)}finish(t){if(!(this.options&cB)){let r=this.content[this.content.length-1],a;if(r&&r.isText&&(a=/[ \t\r\n\u000c]+$/.exec(r.text))){let i=r;r.text.length==a[0].length?this.content.pop():this.content[this.content.length-1]=i.withText(i.text.slice(0,i.text.length-a[0].length))}}let n=$r.from(this.content);return!t&&this.match&&(n=n.append(this.match.fillBefore($r.empty,!0))),this.type?this.type.create(this.attrs,n,this.marks):n}inlineContext(t){return this.type?this.type.inlineContent:this.content.length?this.content[0].isInline:t.parentNode&&!Cpt.hasOwnProperty(t.parentNode.nodeName.toLowerCase())}}class IUe{constructor(t,n,r){this.parser=t,this.options=n,this.isOpen=r,this.open=0,this.localPreserveWS=!1;let a=n.topNode,i,l=MUe(null,n.preserveWhitespace,0)|(r?Y9:0);a?i=new iH(a.type,a.attrs,td.none,!0,n.topMatch||a.type.contentMatch,l):r?i=new iH(null,null,td.none,!0,null,l):i=new iH(t.schema.topNodeType,null,td.none,!0,null,l),this.nodes=[i],this.find=n.findPositions,this.needsBlock=!1}get top(){return this.nodes[this.open]}addDOM(t,n){t.nodeType==3?this.addTextNode(t,n):t.nodeType==1&&this.addElement(t,n)}addTextNode(t,n){let r=t.nodeValue,a=this.top,i=a.options&aCe?"full":this.localPreserveWS||(a.options&cB)>0,{schema:l}=this.parser;if(i==="full"||a.inlineContext(t)||/[^ \t\r\n\u000c]/.test(r)){if(i)if(i==="full")r=r.replace(/\r\n?/g,` `);else if(l.linebreakReplacement&&/[\r\n]/.test(r)&&this.top.findWrapping(l.linebreakReplacement.create())){let o=r.split(/\r?\n|\r/);for(let c=0;c!c.clearMark(d)):n=n.concat(this.parser.schema.marks[c.mark].create(c.attrs)),c.consuming===!1)o=c;else break}}return n}addElementByRule(t,n,r,a){let i,l;if(n.node)if(l=this.parser.schema.nodes[n.node],l.isLeaf)this.insertNode(l.create(n.attrs),r,t.nodeName=="BR")||this.leafFallback(t,r);else{let c=this.enter(l,n.attrs||null,r,n.preserveWhitespace);c&&(i=!0,r=c)}else{let c=this.parser.schema.marks[n.mark];r=r.concat(c.create(n.attrs))}let o=this.top;if(l&&l.isLeaf)this.findInside(t);else if(a)this.addElement(t,r,a);else if(n.getContent)this.findInside(t),n.getContent(t,this.parser.schema).forEach(c=>this.insertNode(c,r,!1));else{let c=t;typeof n.contentElement=="string"?c=t.querySelector(n.contentElement):typeof n.contentElement=="function"?c=n.contentElement(t):n.contentElement&&(c=n.contentElement),this.findAround(t,c,!0),this.addAll(c,r),this.findAround(t,c,!1)}i&&this.sync(o)&&this.open--}addAll(t,n,r,a){let i=r||0;for(let l=r?t.childNodes[r]:t.firstChild,o=a==null?null:t.childNodes[a];l!=o;l=l.nextSibling,++i)this.findAtPoint(t,i),this.addDOM(l,n);this.findAtPoint(t,i)}findPlace(t,n,r){let a,i;for(let l=this.open,o=0;l>=0;l--){let c=this.nodes[l],d=c.findWrapping(t);if(d&&(!a||a.length>d.length+o)&&(a=d,i=c,!d.length))break;if(c.solid){if(r)break;o+=2}}if(!a)return null;this.sync(i);for(let l=0;l(l.type?l.type.allowsMarkType(d.type):LUe(d.type,t))?(c=d.addToSet(c),!1):!0),this.nodes.push(new iH(t,n,c,a,null,o)),this.open++,r}closeExtra(t=!1){let n=this.nodes.length-1;if(n>this.open){for(;n>this.open;n--)this.nodes[n-1].content.push(this.nodes[n].finish(t));this.nodes.length=this.open+1}}finish(){return this.open=0,this.closeExtra(this.isOpen),this.nodes[0].finish(!!(this.isOpen||this.options.topOpen))}sync(t){for(let n=this.open;n>=0;n--){if(this.nodes[n]==t)return this.open=n,!0;this.localPreserveWS&&(this.nodes[n].options|=cB)}return!1}get currentPos(){this.closeExtra();let t=0;for(let n=this.open;n>=0;n--){let r=this.nodes[n].content;for(let a=r.length-1;a>=0;a--)t+=r[a].nodeSize;n&&t++}return t}findAtPoint(t,n){if(this.find)for(let r=0;r-1)return t.split(/\s*\|\s*/).some(this.matchesContext,this);let n=t.split("/"),r=this.options.context,a=!this.isOpen&&(!r||r.parent.type==this.nodes[0].type),i=-(r?r.depth+1:0)+(a?0:1),l=(o,c)=>{for(;o>=0;o--){let d=n[o];if(d==""){if(o==n.length-1||o==0)continue;for(;c>=i;c--)if(l(o-1,c))return!0;return!1}else{let u=c>0||c==0&&a?this.nodes[c].type:r&&c>=i?r.node(c-i).type:null;if(!u||u.name!=d&&!u.isInGroup(d))return!1;c--}}return!0};return l(n.length-1,this.open)}textblockFromContext(){let t=this.options.context;if(t)for(let n=t.depth;n>=0;n--){let r=t.node(n).contentMatchAt(t.indexAfter(n)).defaultType;if(r&&r.isTextblock&&r.defaultAttrs)return r}for(let n in this.parser.schema.nodes){let r=this.parser.schema.nodes[n];if(r.isTextblock&&r.defaultAttrs)return r}}}function ias(s){for(let t=s.firstChild,n=null;t;t=t.nextSibling){let r=t.nodeType==1?t.nodeName.toLowerCase():null;r&&Tpt.hasOwnProperty(r)&&n?(n.appendChild(t),t=n):r=="li"?n=t:r&&(n=null)}}function oas(s,t){return(s.matches||s.msMatchesSelector||s.webkitMatchesSelector||s.mozMatchesSelector).call(s,t)}function PUe(s){let t={};for(let n in s)t[n]=s[n];return t}function LUe(s,t){let n=t.schema.nodes;for(let r in n){let a=n[r];if(!a.allowsMarkType(s))continue;let i=[],l=o=>{i.push(o);for(let c=0;c{if(i.length||l.marks.length){let o=0,c=0;for(;o=0;a--){let i=this.serializeMark(t.marks[a],t.isInline,n);i&&((i.contentDOM||i.dom).appendChild(r),r=i.dom)}return r}serializeMark(t,n,r={}){let a=this.marks[t.type.name];return a&&Pme(Sje(r),a(t,n),null,t.attrs)}static renderSpec(t,n,r=null,a){return Pme(t,n,r,a)}static fromSchema(t){return t.cached.domSerializer||(t.cached.domSerializer=new UM(this.nodesFromSchema(t),this.marksFromSchema(t)))}static nodesFromSchema(t){let n=DUe(t.nodes);return n.text||(n.text=r=>r.text),n}static marksFromSchema(t){return DUe(t.marks)}}function DUe(s){let t={};for(let n in s){let r=s[n].spec.toDOM;r&&(t[n]=r)}return t}function Sje(s){return s.document||window.document}const RUe=new WeakMap;function las(s){let t=RUe.get(s);return t===void 0&&RUe.set(s,t=cas(s)),t}function cas(s){let t=null;function n(r){if(r&&typeof r=="object")if(Array.isArray(r))if(typeof r[0]=="string")t||(t=[]),t.push(r);else for(let a=0;a-1)throw new RangeError("Using an array from an attribute object as a DOM spec. This may be an attempted cross site scripting attack.");let l=a.indexOf(" ");l>0&&(n=a.slice(0,l),a=a.slice(l+1));let o,c=n?s.createElementNS(n,a):s.createElement(a),d=t[1],u=1;if(d&&typeof d=="object"&&d.nodeType==null&&!Array.isArray(d)){u=2;for(let h in d)if(d[h]!=null){let p=h.indexOf(" ");p>0?c.setAttributeNS(h.slice(0,p),h.slice(p+1),d[h]):h=="style"&&c.style?c.style.cssText=d[h]:c.setAttribute(h,d[h])}}for(let h=u;hu)throw new RangeError("Content hole must be the only child of its parent node");return{dom:c,contentDOM:c}}else{let{dom:f,contentDOM:y}=Pme(s,p,n,r);if(c.appendChild(f),y){if(o)throw new RangeError("Multiple content holes");o=y}}}return{dom:c,contentDOM:o}}const Ept=65535,Apt=Math.pow(2,16);function das(s,t){return s+t*Apt}function OUe(s){return s&Ept}function uas(s){return(s-(s&Ept))/Apt}const Mpt=1,Ipt=2,Lme=4,Ppt=8;class iCe{constructor(t,n,r){this.pos=t,this.delInfo=n,this.recover=r}get deleted(){return(this.delInfo&Ppt)>0}get deletedBefore(){return(this.delInfo&(Mpt|Lme))>0}get deletedAfter(){return(this.delInfo&(Ipt|Lme))>0}get deletedAcross(){return(this.delInfo&Lme)>0}}class W0{constructor(t,n=!1){if(this.ranges=t,this.inverted=n,!t.length&&W0.empty)return W0.empty}recover(t){let n=0,r=OUe(t);if(!this.inverted)for(let a=0;at)break;let d=this.ranges[o+i],u=this.ranges[o+l],h=c+d;if(t<=h){let p=d?t==c?-1:t==h?1:n:n,f=c+a+(p<0?0:u);if(r)return f;let y=t==(n<0?c:h)?null:das(o/3,t-c),_=t==c?Ipt:t==h?Mpt:Lme;return(n<0?t!=c:t!=h)&&(_|=Ppt),new iCe(f,_,y)}a+=u-d}return r?t+a:new iCe(t+a,0,null)}touches(t,n){let r=0,a=OUe(n),i=this.inverted?2:1,l=this.inverted?1:2;for(let o=0;ot)break;let d=this.ranges[o+i],u=c+d;if(t<=u&&o==a*3)return!0;r+=this.ranges[o+l]-d}return!1}forEach(t){let n=this.inverted?2:1,r=this.inverted?1:2;for(let a=0,i=0;a=0;n--){let a=t.getMirror(n);this.appendMap(t._maps[n].invert(),a!=null&&a>n?r-a-1:void 0)}}invert(){let t=new dB;return t.appendMappingInverted(this),t}map(t,n=1){if(this.mirror)return this._map(t,n,!0);for(let r=this.from;ri&&c!l.isAtom||!o.type.allowsMarkType(this.mark.type)?l:l.mark(this.mark.addToSet(l.marks)),a),n.openStart,n.openEnd);return Xh.fromReplace(t,this.from,this.to,i)}invert(){return new ew(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new kS(n.pos,r.pos,this.mark)}merge(t){return t instanceof kS&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new kS(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"addMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for AddMarkStep.fromJSON");return new kS(n.from,n.to,t.markFromJSON(n.mark))}}ix.jsonID("addMark",kS);class ew extends ix{constructor(t,n,r){super(),this.from=t,this.to=n,this.mark=r}apply(t){let n=t.slice(this.from,this.to),r=new ba(r6e(n.content,a=>a.mark(this.mark.removeFromSet(a.marks)),t),n.openStart,n.openEnd);return Xh.fromReplace(t,this.from,this.to,r)}invert(){return new kS(this.from,this.to,this.mark)}map(t){let n=t.mapResult(this.from,1),r=t.mapResult(this.to,-1);return n.deleted&&r.deleted||n.pos>=r.pos?null:new ew(n.pos,r.pos,this.mark)}merge(t){return t instanceof ew&&t.mark.eq(this.mark)&&this.from<=t.to&&this.to>=t.from?new ew(Math.min(this.from,t.from),Math.max(this.to,t.to),this.mark):null}toJSON(){return{stepType:"removeMark",mark:this.mark.toJSON(),from:this.from,to:this.to}}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number")throw new RangeError("Invalid input for RemoveMarkStep.fromJSON");return new ew(n.from,n.to,t.markFromJSON(n.mark))}}ix.jsonID("removeMark",ew);class SS extends ix{constructor(t,n){super(),this.pos=t,this.mark=n}apply(t){let n=t.nodeAt(this.pos);if(!n)return Xh.fail("No node at mark step's position");let r=n.type.create(n.attrs,null,this.mark.addToSet(n.marks));return Xh.fromReplace(t,this.pos,this.pos+1,new ba($r.from(r),0,n.isLeaf?0:1))}invert(t){let n=t.nodeAt(this.pos);if(n){let r=this.mark.addToSet(n.marks);if(r.length==n.marks.length){for(let a=0;ar.pos?null:new Cp(n.pos,r.pos,a,i,this.slice,this.insert,this.structure)}toJSON(){let t={stepType:"replaceAround",from:this.from,to:this.to,gapFrom:this.gapFrom,gapTo:this.gapTo,insert:this.insert};return this.slice.size&&(t.slice=this.slice.toJSON()),this.structure&&(t.structure=!0),t}static fromJSON(t,n){if(typeof n.from!="number"||typeof n.to!="number"||typeof n.gapFrom!="number"||typeof n.gapTo!="number"||typeof n.insert!="number")throw new RangeError("Invalid input for ReplaceAroundStep.fromJSON");return new Cp(n.from,n.to,n.gapFrom,n.gapTo,ba.fromJSON(t,n.slice),n.insert,!!n.structure)}}ix.jsonID("replaceAround",Cp);function oCe(s,t,n){let r=s.resolve(t),a=n-t,i=r.depth;for(;a>0&&i>0&&r.indexAfter(i)==r.node(i).childCount;)i--,a--;if(a>0){let l=r.node(i).maybeChild(r.indexAfter(i));for(;a>0;){if(!l||l.isLeaf)return!0;l=l.firstChild,a--}}return!1}function has(s,t,n,r){let a=[],i=[],l,o;s.doc.nodesBetween(t,n,(c,d,u)=>{if(!c.isInline)return;let h=c.marks;if(!r.isInSet(h)&&u.type.allowsMarkType(r.type)){let p=Math.max(d,t),f=Math.min(d+c.nodeSize,n),y=r.addToSet(h);for(let _=0;_s.step(c)),i.forEach(c=>s.step(c))}function mas(s,t,n,r){let a=[],i=0;s.doc.nodesBetween(t,n,(l,o)=>{if(!l.isInline)return;i++;let c=null;if(r instanceof Iye){let d=l.marks,u;for(;u=r.isInSet(d);)(c||(c=[])).push(u),d=u.removeFromSet(d)}else r?r.isInSet(l.marks)&&(c=[r]):c=l.marks;if(c&&c.length){let d=Math.min(o+l.nodeSize,n);for(let u=0;us.step(new ew(l.from,l.to,l.style)))}function a6e(s,t,n,r=n.contentMatch,a=!0){let i=s.doc.nodeAt(t),l=[],o=t+1;for(let c=0;c=0;c--)s.step(l[c])}function pas(s,t,n){return(t==0||s.canReplace(t,s.childCount))&&(n==s.childCount||s.canReplace(0,n))}function VD(s){let n=s.parent.content.cutByIndex(s.startIndex,s.endIndex);for(let r=s.depth,a=0,i=0;;--r){let l=s.$from.node(r),o=s.$from.index(r)+a,c=s.$to.indexAfter(r)-i;if(rn;y--)_||r.index(y)>0?(_=!0,u=$r.from(r.node(y).copy(u)),h++):c--;let p=$r.empty,f=0;for(let y=i,_=!1;y>n;y--)_||a.after(y+1)=0;l--){if(r.size){let o=n[l].type.contentMatch.matchFragment(r);if(!o||!o.validEnd)throw new RangeError("Wrapper type given to Transform.wrap does not form valid content of its parent wrapper")}r=$r.from(n[l].type.create(n[l].attrs,r))}let a=t.start,i=t.end;s.step(new Cp(a,i,a,i,new ba(r,0,0),n.length,!0))}function vas(s,t,n,r,a){if(!r.isTextblock)throw new RangeError("Type given to setBlockType should be a textblock");let i=s.steps.length;s.doc.nodesBetween(t,n,(l,o)=>{let c=typeof a=="function"?a(l):a;if(l.isTextblock&&!l.hasMarkup(r,c)&&bas(s.doc,s.mapping.slice(i).map(o),r)){let d=null;if(r.schema.linebreakReplacement){let f=r.whitespace=="pre",y=!!r.contentMatch.matchType(r.schema.linebreakReplacement);f&&!y?d=!1:!f&&y&&(d=!0)}d===!1&&Dpt(s,l,o,i),a6e(s,s.mapping.slice(i).map(o,1),r,void 0,d===null);let u=s.mapping.slice(i),h=u.map(o,1),p=u.map(o+l.nodeSize,1);return s.step(new Cp(h,p,h+1,p-1,new ba($r.from(r.create(c,null,l.marks)),0,0),1,!0)),d===!0&&Lpt(s,l,o,i),!1}})}function Lpt(s,t,n,r){t.forEach((a,i)=>{if(a.isText){let l,o=/\r?\n|\r/g;for(;l=o.exec(a.text);){let c=s.mapping.slice(r).map(n+1+i+l.index);s.replaceWith(c,c+1,t.type.schema.linebreakReplacement.create())}}})}function Dpt(s,t,n,r){t.forEach((a,i)=>{if(a.type==a.type.schema.linebreakReplacement){let l=s.mapping.slice(r).map(n+1+i);s.replaceWith(l,l+1,t.type.schema.text(` `))}})}function bas(s,t,n){let r=s.resolve(t),a=r.index();return r.parent.canReplaceWith(a,a+1,n)}function _as(s,t,n,r,a){let i=s.doc.nodeAt(t);if(!i)throw new RangeError("No node at given position");n||(n=i.type);let l=n.create(r,null,a||i.marks);if(i.isLeaf)return s.replaceWith(t,t+i.nodeSize,l);if(!n.validContent(i.content))throw new RangeError("Invalid content for node type "+n.name);s.step(new Cp(t,t+i.nodeSize,t+1,t+i.nodeSize-1,new ba($r.from(l),0,0),1,!0))}function EL(s,t,n=1,r){let a=s.resolve(t),i=a.depth-n,l=r&&r[r.length-1]||a.parent;if(i<0||a.parent.type.spec.isolating||!a.parent.canReplace(a.index(),a.parent.childCount)||!l.type.validContent(a.parent.content.cutByIndex(a.index(),a.parent.childCount)))return!1;for(let d=a.depth-1,u=n-2;d>i;d--,u--){let h=a.node(d),p=a.index(d);if(h.type.spec.isolating)return!1;let f=h.content.cutByIndex(p,h.childCount),y=r&&r[u+1];y&&(f=f.replaceChild(0,y.type.create(y.attrs)));let _=r&&r[u]||h;if(!h.canReplace(p+1,h.childCount)||!_.type.validContent(f))return!1}let o=a.indexAfter(i),c=r&&r[0];return a.node(i).canReplaceWith(o,o,c?c.type:a.node(i+1).type)}function was(s,t,n=1,r){let a=s.doc.resolve(t),i=$r.empty,l=$r.empty;for(let o=a.depth,c=a.depth-n,d=n-1;o>c;o--,d--){i=$r.from(a.node(o).copy(i));let u=r&&r[d];l=$r.from(u?u.type.create(u.attrs,l):a.node(o).copy(l))}s.step(new Kh(t,t,new ba(i.append(l),n,n),!0))}function G4(s,t){let n=s.resolve(t),r=n.index();return Rpt(n.nodeBefore,n.nodeAfter)&&n.parent.canReplace(r,r+1)}function jas(s,t){t.content.size||s.type.compatibleContent(t.type);let n=s.contentMatchAt(s.childCount),{linebreakReplacement:r}=s.type.schema;for(let a=0;a0?(i=r.node(a+1),o++,l=r.node(a).maybeChild(o)):(i=r.node(a).maybeChild(o-1),l=r.node(a+1)),i&&!i.isTextblock&&Rpt(i,l)&&r.node(a).canReplace(o,o+1))return t;if(a==0)break;t=n<0?r.before(a):r.after(a)}}function Nas(s,t,n){let r=null,{linebreakReplacement:a}=s.doc.type.schema,i=s.doc.resolve(t-n),l=i.node().type;if(a&&l.inlineContent){let u=l.whitespace=="pre",h=!!l.contentMatch.matchType(a);u&&!h?r=!1:!u&&h&&(r=!0)}let o=s.steps.length;if(r===!1){let u=s.doc.resolve(t+n);Dpt(s,u.node(),u.before(),o)}l.inlineContent&&a6e(s,t+n-1,l,i.node().contentMatchAt(i.index()),r==null);let c=s.mapping.slice(o),d=c.map(t-n);if(s.step(new Kh(d,c.map(t+n,-1),ba.empty,!0)),r===!0){let u=s.doc.resolve(d);Lpt(s,u.node(),u.before(),s.steps.length)}return s}function kas(s,t,n){let r=s.resolve(t);if(r.parent.canReplaceWith(r.index(),r.index(),n))return t;if(r.parentOffset==0)for(let a=r.depth-1;a>=0;a--){let i=r.index(a);if(r.node(a).canReplaceWith(i,i,n))return r.before(a+1);if(i>0)return null}if(r.parentOffset==r.parent.content.size)for(let a=r.depth-1;a>=0;a--){let i=r.indexAfter(a);if(r.node(a).canReplaceWith(i,i,n))return r.after(a+1);if(i=0;l--){let o=l==r.depth?0:r.pos<=(r.start(l+1)+r.end(l+1))/2?-1:1,c=r.index(l)+(o>0?1:0),d=r.node(l),u=!1;if(i==1)u=d.canReplace(c,c,a);else{let h=d.contentMatchAt(c).findWrapping(a.firstChild.type);u=h&&d.canReplaceWith(c,c,h[0])}if(u)return o==0?r.pos:o<0?r.before(l+1):r.after(l+1)}return null}function Lye(s,t,n=t,r=ba.empty){if(t==n&&!r.size)return null;let a=s.resolve(t),i=s.resolve(n);return Fpt(a,i,r)?new Kh(t,n,r):new Sas(a,i,r).fit()}function Fpt(s,t,n){return!n.openStart&&!n.openEnd&&s.start()==t.start()&&s.parent.canReplace(s.index(),t.index(),n.content)}class Sas{constructor(t,n,r){this.$from=t,this.$to=n,this.unplaced=r,this.frontier=[],this.placed=$r.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=$r.from(t.node(a).copy(this.placed))}get depth(){return this.frontier.length-1}fit(){for(;this.unplaced.size;){let d=this.findFittable();d?this.placeNodes(d):this.openMore()||this.dropNode()}let t=this.mustMoveInline(),n=this.placed.size-this.depth-this.$from.depth,r=this.$from,a=this.close(t<0?this.$to:r.doc.resolve(t));if(!a)return null;let i=this.placed,l=r.depth,o=a.depth;for(;l&&o&&i.childCount==1;)i=i.firstChild.content,l--,o--;let c=new ba(i,l,o);return t>-1?new Cp(r.pos,t,this.$to.pos,this.$to.end(),c,n):c.size||r.pos!=this.$to.pos?new Kh(r.pos,a.pos,c):null}findFittable(){let t=this.unplaced.openStart;for(let n=this.unplaced.content,r=0,a=this.unplaced.openEnd;r1&&(a=0),i.type.spec.isolating&&a<=r){t=r;break}n=i.content}for(let n=1;n<=2;n++)for(let r=n==1?t:this.unplaced.openStart;r>=0;r--){let a,i=null;r?(i=Tje(this.unplaced.content,r-1).firstChild,a=i.content):a=this.unplaced.content;let l=a.firstChild;for(let o=this.depth;o>=0;o--){let{type:c,match:d}=this.frontier[o],u,h=null;if(n==1&&(l?d.matchType(l.type)||(h=d.fillBefore($r.from(l),!1)):i&&c.compatibleContent(i.type)))return{sliceDepth:r,frontierDepth:o,parent:i,inject:h};if(n==2&&l&&(u=d.findWrapping(l.type)))return{sliceDepth:r,frontierDepth:o,parent:i,wrap:u};if(i&&d.matchType(i.type))break}}}openMore(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=Tje(t,n);return!a.childCount||a.firstChild.isLeaf?!1:(this.unplaced=new ba(t,n+1,Math.max(r,a.size+n>=t.size-r?n+1:0)),!0)}dropNode(){let{content:t,openStart:n,openEnd:r}=this.unplaced,a=Tje(t,n);if(a.childCount<=1&&n>0){let i=t.size-n<=n+a.size;this.unplaced=new ba(n7(t,n-1,1),n-1,i?n-1:r)}else this.unplaced=new ba(n7(t,n,1),n,r)}placeNodes({sliceDepth:t,frontierDepth:n,parent:r,inject:a,wrap:i}){for(;this.depth>n;)this.closeFrontierNode();if(i)for(let _=0;_1||c==0||_.content.size)&&(h=v,u.push(zpt(_.mark(p.allowedMarks(_.marks)),d==1?c:0,d==o.childCount?f:-1)))}let y=d==o.childCount;y||(f=-1),this.placed=r7(this.placed,n,$r.from(u)),this.frontier[n].match=h,y&&f<0&&r&&r.type==this.frontier[this.depth].type&&this.frontier.length>1&&this.closeFrontierNode();for(let _=0,v=o;_1&&a==this.$to.end(--r);)++a;return a}findCloseLevel(t){e:for(let n=Math.min(this.depth,t.depth);n>=0;n--){let{match:r,type:a}=this.frontier[n],i=n=0;o--){let{match:c,type:d}=this.frontier[o],u=Eje(t,o,d,c,!0);if(!u||u.childCount)continue e}return{depth:n,fit:l,move:i?t.doc.resolve(t.after(n+1)):t}}}}close(t){let n=this.findCloseLevel(t);if(!n)return null;for(;this.depth>n.depth;)this.closeFrontierNode();n.fit.childCount&&(this.placed=r7(this.placed,n.depth,n.fit)),t=n.move;for(let r=n.depth+1;r<=t.depth;r++){let a=t.node(r),i=a.type.contentMatch.fillBefore(a.content,!0,t.index(r));this.openFrontierNode(a.type,a.attrs,i)}return t}openFrontierNode(t,n=null,r){let a=this.frontier[this.depth];a.match=a.match.matchType(t),this.placed=r7(this.placed,this.depth,$r.from(t.create(n,r))),this.frontier.push({type:t,match:t.contentMatch})}closeFrontierNode(){let n=this.frontier.pop().match.fillBefore($r.empty,!0);n.childCount&&(this.placed=r7(this.placed,this.frontier.length,n))}}function n7(s,t,n){return t==0?s.cutByIndex(n,s.childCount):s.replaceChild(0,s.firstChild.copy(n7(s.firstChild.content,t-1,n)))}function r7(s,t,n){return t==0?s.append(n):s.replaceChild(s.childCount-1,s.lastChild.copy(r7(s.lastChild.content,t-1,n)))}function Tje(s,t){for(let n=0;n1&&(r=r.replaceChild(0,zpt(r.firstChild,t-1,r.childCount==1?n-1:0))),t>0&&(r=s.type.contentMatch.fillBefore(r).append(r),n<=0&&(r=r.append(s.type.contentMatch.matchFragment(r).fillBefore($r.empty,!0)))),s.copy(r)}function Eje(s,t,n,r,a){let i=s.node(t),l=a?s.indexAfter(t):s.index(t);if(l==i.childCount&&!n.compatibleContent(i.type))return null;let o=r.fillBefore(i.content,!0,l);return o&&!Cas(n,i.content,l)?o:null}function Cas(s,t,n){for(let r=n;r0;p--,f--){let y=a.node(p).type.spec;if(y.defining||y.definingAsContext||y.isolating)break;l.indexOf(p)>-1?o=p:a.before(p)==f&&l.splice(1,0,-p)}let c=l.indexOf(o),d=[],u=r.openStart;for(let p=r.content,f=0;;f++){let y=p.firstChild;if(d.push(y),f==r.openStart)break;p=y.content}for(let p=u-1;p>=0;p--){let f=d[p],y=Tas(f.type);if(y&&!f.sameMarkup(a.node(Math.abs(o)-1)))u=p;else if(y||!f.type.isTextblock)break}for(let p=r.openStart;p>=0;p--){let f=(p+u+1)%(r.openStart+1),y=d[f];if(y)for(let _=0;_=0&&(s.replace(t,n,r),!(s.steps.length>h));p--){let f=l[p];f<0||(t=a.before(f),n=i.after(f))}}function Bpt(s,t,n,r,a){if(tr){let i=a.contentMatchAt(0),l=i.fillBefore(s).append(s);s=l.append(i.matchFragment(l).fillBefore($r.empty,!0))}return s}function Aas(s,t,n,r){if(!r.isInline&&t==n&&s.doc.resolve(t).parent.content.size){let a=kas(s.doc,t,r.type);a!=null&&(t=n=a)}s.replaceRange(t,n,new ba($r.from(r),0,0))}function Mas(s,t,n){let r=s.doc.resolve(t),a=s.doc.resolve(n);if(r.parent.isTextblock&&a.parent.isTextblock&&r.start()!=a.start()&&r.parentOffset==0&&a.parentOffset==0){let l=r.sharedDepth(n),o=!1;for(let c=r.depth;c>l;c--)r.node(c).type.spec.isolating&&(o=!0);for(let c=a.depth;c>l;c--)a.node(c).type.spec.isolating&&(o=!0);if(!o){for(let c=r.depth;c>0&&t==r.start(c);c--)t=r.before(c);for(let c=a.depth;c>0&&n==a.start(c);c--)n=a.before(c);r=s.doc.resolve(t),a=s.doc.resolve(n)}}let i=$pt(r,a);for(let l=0;l0&&(c||r.node(o-1).canReplace(r.index(o-1),a.indexAfter(o-1))))return s.delete(r.before(o),a.after(o))}for(let l=1;l<=r.depth&&l<=a.depth;l++)if(t-r.start(l)==r.depth-l&&n>r.end(l)&&a.end(l)-n!=a.depth-l&&r.start(l-1)==a.start(l-1)&&r.node(l-1).canReplace(r.index(l-1),a.index(l-1)))return s.delete(r.before(l),n);s.delete(t,n)}function $pt(s,t){let n=[],r=Math.min(s.depth,t.depth);for(let a=r;a>=0;a--){let i=s.start(a);if(it.pos+(t.depth-a)||s.node(a).type.spec.isolating||t.node(a).type.spec.isolating)break;(i==t.start(a)||a==s.depth&&a==t.depth&&s.parent.inlineContent&&t.parent.inlineContent&&a&&t.start(a-1)==i-1)&&n.push(a)}return n}class AL extends ix{constructor(t,n,r){super(),this.pos=t,this.attr=n,this.value=r}apply(t){let n=t.nodeAt(this.pos);if(!n)return Xh.fail("No node at attribute step's position");let r=Object.create(null);for(let i in n.attrs)r[i]=n.attrs[i];r[this.attr]=this.value;let a=n.type.create(r,null,n.marks);return Xh.fromReplace(t,this.pos,this.pos+1,new ba($r.from(a),0,n.isLeaf?0:1))}getMap(){return W0.empty}invert(t){return new AL(this.pos,this.attr,t.nodeAt(this.pos).attrs[this.attr])}map(t){let n=t.mapResult(this.pos,1);return n.deletedAfter?null:new AL(n.pos,this.attr,this.value)}toJSON(){return{stepType:"attr",pos:this.pos,attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.pos!="number"||typeof n.attr!="string")throw new RangeError("Invalid input for AttrStep.fromJSON");return new AL(n.pos,n.attr,n.value)}}ix.jsonID("attr",AL);class uB extends ix{constructor(t,n){super(),this.attr=t,this.value=n}apply(t){let n=Object.create(null);for(let a in t.attrs)n[a]=t.attrs[a];n[this.attr]=this.value;let r=t.type.create(n,t.content,t.marks);return Xh.ok(r)}getMap(){return W0.empty}invert(t){return new uB(this.attr,t.attrs[this.attr])}map(t){return this}toJSON(){return{stepType:"docAttr",attr:this.attr,value:this.value}}static fromJSON(t,n){if(typeof n.attr!="string")throw new RangeError("Invalid input for DocAttrStep.fromJSON");return new uB(n.attr,n.value)}}ix.jsonID("docAttr",uB);let w8=class extends Error{};w8=function s(t){let n=Error.call(this,t);return n.__proto__=s.prototype,n};w8.prototype=Object.create(Error.prototype);w8.prototype.constructor=w8;w8.prototype.name="TransformError";let o6e=class{constructor(t){this.doc=t,this.steps=[],this.docs=[],this.mapping=new dB}get before(){return this.docs.length?this.docs[0]:this.doc}step(t){let n=this.maybeStep(t);if(n.failed)throw new w8(n.failed);return this}maybeStep(t){let n=t.apply(this.doc);return n.failed||this.addStep(t,n.doc),n}get docChanged(){return this.steps.length>0}changedRange(){let t=1e9,n=-1e9;for(let r=0;r{t=Math.min(t,o),n=Math.max(n,c)})}return t==1e9?null:{from:t,to:n}}addStep(t,n){this.docs.push(this.doc),this.steps.push(t),this.mapping.appendMap(t.getMap()),this.doc=n}replace(t,n=t,r=ba.empty){let a=Lye(this.doc,t,n,r);return a&&this.step(a),this}replaceWith(t,n,r){return this.replace(t,n,new ba($r.from(r),0,0))}delete(t,n){return this.replace(t,n,ba.empty)}insert(t,n){return this.replaceWith(t,t,n)}replaceRange(t,n,r){return Eas(this,t,n,r),this}replaceRangeWith(t,n,r){return Aas(this,t,n,r),this}deleteRange(t,n){return Mas(this,t,n),this}lift(t,n){return fas(this,t,n),this}join(t,n=1){return Nas(this,t,n),this}wrap(t,n){return yas(this,t,n),this}setBlockType(t,n=t,r,a=null){return vas(this,t,n,r,a),this}setNodeMarkup(t,n,r=null,a){return _as(this,t,n,r,a),this}setNodeAttribute(t,n,r){return this.step(new AL(t,n,r)),this}setDocAttribute(t,n){return this.step(new uB(t,n)),this}addNodeMark(t,n){return this.step(new SS(t,n)),this}removeNodeMark(t,n){let r=this.doc.nodeAt(t);if(!r)throw new RangeError("No node at position "+t);if(n instanceof td)n.isInSet(r.marks)&&this.step(new gM(t,n));else{let a=r.marks,i,l=[];for(;i=n.isInSet(a);)l.push(new gM(t,i)),a=i.removeFromSet(a);for(let o=l.length-1;o>=0;o--)this.step(l[o])}return this}split(t,n=1,r){return was(this,t,n,r),this}addMark(t,n,r){return has(this,t,n,r),this}removeMark(t,n,r){return mas(this,t,n,r),this}clearIncompatible(t,n,r){return a6e(this,t,n,r),this}};const Aje=Object.create(null);class to{constructor(t,n,r){this.$anchor=t,this.$head=n,this.ranges=r||[new Upt(t.min(n),t.max(n))]}get anchor(){return this.$anchor.pos}get head(){return this.$head.pos}get from(){return this.$from.pos}get to(){return this.$to.pos}get $from(){return this.ranges[0].$from}get $to(){return this.ranges[0].$to}get empty(){let t=this.ranges;for(let n=0;n=0;i--){let l=n<0?sP(t.node(0),t.node(i),t.before(i+1),t.index(i),n,r):sP(t.node(0),t.node(i),t.after(i+1),t.index(i)+1,n,r);if(l)return l}return null}static near(t,n=1){return this.findFrom(t,n)||this.findFrom(t,-n)||new zv(t.node(0))}static atStart(t){return sP(t,t,0,0,1)||new zv(t)}static atEnd(t){return sP(t,t,t.content.size,t.childCount,-1)||new zv(t)}static fromJSON(t,n){if(!n||!n.type)throw new RangeError("Invalid input for Selection.fromJSON");let r=Aje[n.type];if(!r)throw new RangeError(`No selection type ${n.type} defined`);return r.fromJSON(t,n)}static jsonID(t,n){if(t in Aje)throw new RangeError("Duplicate use of selection JSON ID "+t);return Aje[t]=n,n.prototype.jsonID=t,n}getBookmark(){return Ui.between(this.$anchor,this.$head).getBookmark()}}to.prototype.visible=!0;class Upt{constructor(t,n){this.$from=t,this.$to=n}}let zUe=!1;function BUe(s){!zUe&&!s.parent.inlineContent&&(zUe=!0,console.warn("TextSelection endpoint not pointing into a node with inline content ("+s.parent.type.name+")"))}class Ui extends to{constructor(t,n=t){BUe(t),BUe(n),super(t,n)}get $cursor(){return this.$anchor.pos==this.$head.pos?this.$head:null}map(t,n){let r=t.resolve(n.map(this.head));if(!r.parent.inlineContent)return to.near(r);let a=t.resolve(n.map(this.anchor));return new Ui(a.parent.inlineContent?a:r,r)}replace(t,n=ba.empty){if(super.replace(t,n),n==ba.empty){let r=this.$from.marksAcross(this.$to);r&&t.ensureMarks(r)}}eq(t){return t instanceof Ui&&t.anchor==this.anchor&&t.head==this.head}getBookmark(){return new Dye(this.anchor,this.head)}toJSON(){return{type:"text",anchor:this.anchor,head:this.head}}static fromJSON(t,n){if(typeof n.anchor!="number"||typeof n.head!="number")throw new RangeError("Invalid input for TextSelection.fromJSON");return new Ui(t.resolve(n.anchor),t.resolve(n.head))}static create(t,n,r=n){let a=t.resolve(n);return new this(a,r==n?a:t.resolve(r))}static between(t,n,r){let a=t.pos-n.pos;if((!r||a)&&(r=a>=0?1:-1),!n.parent.inlineContent){let i=to.findFrom(n,r,!0)||to.findFrom(n,-r,!0);if(i)n=i.$head;else return to.near(n,r)}return t.parent.inlineContent||(a==0?t=n:(t=(to.findFrom(t,-r,!0)||to.findFrom(t,r,!0)).$anchor,t.pos0?0:1);a>0?l=0;l+=a){let o=t.child(l);if(o.isAtom){if(!i&&Li.isSelectable(o))return Li.create(s,n-(a<0?o.nodeSize:0))}else{let c=sP(s,o,n+a,a<0?o.childCount:0,a,i);if(c)return c}n+=o.nodeSize*a}return null}function $Ue(s,t,n){let r=s.steps.length-1;if(r{l==null&&(l=u)}),s.setSelection(to.near(s.doc.resolve(l),n))}const UUe=1,oH=2,qUe=4;class Pas extends o6e{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|=oH,this}ensureMarks(t){return td.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&oH)>0}addStep(t,n){super.addStep(t,n),this.updated=this.updated&~oH,this.storedMarks=null}setTime(t){return this.time=t,this}replaceSelection(t){return this.selection.replace(this,t),this}replaceSelectionWith(t,n=!0){let r=this.selection;return n&&(t=t.mark(this.storedMarks||(r.empty?r.$from.marks():r.$from.marksAcross(r.$to)||td.none))),r.replaceWith(this,t),this}deleteSelection(){return this.selection.replace(this),this}insertText(t,n,r){let a=this.doc.type.schema;if(n==null)return t?this.replaceSelectionWith(a.text(t),!0):this.deleteSelection();{if(r==null&&(r=n),!t)return this.deleteRange(n,r);let i=this.storedMarks;if(!i){let l=this.doc.resolve(n);i=r==n?l.marks():l.marksAcross(this.doc.resolve(r))}return this.replaceRangeWith(n,r,a.text(t,i)),!this.selection.empty&&this.selection.to==n+t.length&&this.setSelection(to.near(this.selection.$to)),this}}setMeta(t,n){return this.meta[typeof t=="string"?t:t.key]=n,this}getMeta(t){return this.meta[typeof t=="string"?t:t.key]}get isGeneric(){for(let t in this.meta)return!1;return!0}scrollIntoView(){return this.updated|=qUe,this}get scrolledIntoView(){return(this.updated&qUe)>0}}function VUe(s,t){return!t||!s?s:s.bind(t)}class a7{constructor(t,n,r){this.name=t,this.init=VUe(n.init,r),this.apply=VUe(n.apply,r)}}const Las=[new a7("doc",{init(s){return s.doc||s.schema.topNodeType.createAndFill()},apply(s){return s.doc}}),new a7("selection",{init(s,t){return s.selection||to.atStart(t.doc)},apply(s){return s.selection}}),new a7("storedMarks",{init(s){return s.storedMarks||null},apply(s,t,n,r){return r.selection.$cursor?s.storedMarks:null}}),new a7("scrollToSelection",{init(){return 0},apply(s,t){return s.scrolledIntoView?t+1:t}})];class Mje{constructor(t,n){this.schema=t,this.plugins=[],this.pluginsByKey=Object.create(null),this.fields=Las.slice(),n&&n.forEach(r=>{if(this.pluginsByKey[r.key])throw new RangeError("Adding different instances of a keyed plugin ("+r.key+")");this.plugins.push(r),this.pluginsByKey[r.key]=r,r.spec.state&&this.fields.push(new a7(r.key,r.spec.state,r))})}}class kP{constructor(t){this.config=t}get schema(){return this.config.schema}get plugins(){return this.config.plugins}apply(t){return this.applyTransaction(t).state}filterTransaction(t,n=-1){for(let r=0;rr.toJSON())),t&&typeof t=="object")for(let r in t){if(r=="doc"||r=="selection")throw new RangeError("The JSON fields `doc` and `selection` are reserved");let a=t[r],i=a.spec.state;i&&i.toJSON&&(n[r]=i.toJSON.call(a,this[a.key]))}return n}static fromJSON(t,n,r){if(!n)throw new RangeError("Invalid input for EditorState.fromJSON");if(!t.schema)throw new RangeError("Required config field 'schema' missing");let a=new Mje(t.schema,t.plugins),i=new kP(a);return a.fields.forEach(l=>{if(l.name=="doc")i.doc=c4.fromJSON(t.schema,n.doc);else if(l.name=="selection")i.selection=to.fromJSON(i.doc,n.selection);else if(l.name=="storedMarks")n.storedMarks&&(i.storedMarks=n.storedMarks.map(t.schema.markFromJSON));else{if(r)for(let o in r){let c=r[o],d=c.spec.state;if(c.key==l.name&&d&&d.fromJSON&&Object.prototype.hasOwnProperty.call(n,o)){i[l.name]=d.fromJSON.call(c,t,n[o],i);return}}i[l.name]=l.init(t,i)}}),i}}function qpt(s,t,n){for(let r in s){let a=s[r];a instanceof Function?a=a.bind(t):r=="handleDOMEvents"&&(a=qpt(a,t,{})),n[r]=a}return n}class Gm{constructor(t){this.spec=t,this.props={},t.props&&qpt(t.props,this,this.props),this.key=t.key?t.key.key:Vpt("plugin")}getState(t){return t[this.key]}}const Ije=Object.create(null);function Vpt(s){return s in Ije?s+"$"+ ++Ije[s]:(Ije[s]=0,s+"$")}class ox{constructor(t="key"){this.key=Vpt(t)}get(t){return t.config.pluginsByKey[this.key]}getState(t){return t[this.key]}}const sf=function(s){for(var t=0;;t++)if(s=s.previousSibling,!s)return t},j8=function(s){let t=s.assignedSlot||s.parentNode;return t&&t.nodeType==11?t.host:t};let lCe=null;const v2=function(s,t,n){let r=lCe||(lCe=document.createRange());return r.setEnd(s,n??s.nodeValue.length),r.setStart(s,t||0),r},Das=function(){lCe=null},yM=function(s,t,n,r){return n&&(HUe(s,t,n,r,-1)||HUe(s,t,n,r,1))},Ras=/^(img|br|input|textarea|hr)$/i;function HUe(s,t,n,r,a){for(var i;;){if(s==n&&t==r)return!0;if(t==(a<0?0:wv(s))){let l=s.parentNode;if(!l||l.nodeType!=1||oU(s)||Ras.test(s.nodeName)||s.contentEditable=="false")return!1;t=sf(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?wv(s):0}else return!1}}function wv(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function Oas(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=wv(s)}else if(s.parentNode&&!oU(s))t=sf(s),s=s.parentNode;else return null}}function Fas(s,t){for(;;){if(s.nodeType==3&&t2),gv=N8||(Aw?/Mac/.test(Aw.platform):!1),Wpt=Aw?/Win/.test(Aw.platform):!1,D2=/Android \d/.test(W4),lU=!!GUe&&"webkitFontSmoothing"in GUe.documentElement.style,Uas=lU?+(/\bAppleWebKit\/(\d+)/.exec(navigator.userAgent)||[0,0])[1]:0;function qas(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 t2(s,t){return typeof s=="number"?s:s[t]}function Vas(s){let t=s.getBoundingClientRect(),n=t.width/s.offsetWidth||1,r=t.height/s.offsetHeight||1;return{left:t.left,right:t.left+s.clientWidth*n,top:t.top,bottom:t.top+s.clientHeight*r}}function WUe(s,t,n){let r=s.someProp("scrollThreshold")||0,a=s.someProp("scrollMargin")||5,i=s.dom.ownerDocument;for(let l=n||s.dom;l;){if(l.nodeType!=1){l=j8(l);continue}let o=l,c=o==i.body,d=c?qas(i):Vas(o),u=0,h=0;if(t.topd.bottom-t2(r,"bottom")&&(h=t.bottom-t.top>d.bottom-d.top?t.top+t2(a,"top")-d.top:t.bottom-d.bottom+t2(a,"bottom")),t.leftd.right-t2(r,"right")&&(u=t.right-d.right+t2(a,"right")),u||h)if(c)i.defaultView.scrollBy(u,h);else{let f=o.scrollLeft,y=o.scrollTop;h&&(o.scrollTop+=h),u&&(o.scrollLeft+=u);let _=o.scrollLeft-f,v=o.scrollTop-y;t={left:t.left-_,top:t.top-v,right:t.right-_,bottom:t.bottom-v}}let p=c?"fixed":getComputedStyle(l).position;if(/^(fixed|sticky)$/.test(p))break;l=p=="absolute"?l.offsetParent:j8(l)}}function Has(s){let t=s.dom.getBoundingClientRect(),n=Math.max(0,t.top),r,a;for(let i=(t.left+t.right)/2,l=n+1;l=n-20){r=o,a=c.top;break}}return{refDOM:r,refTop:a,stack:Kpt(s.dom)}}function Kpt(s){let t=[],n=s.ownerDocument;for(let r=s;r&&(t.push({dom:r,top:r.scrollTop,left:r.scrollLeft}),s!=n);r=j8(r));return t}function Gas({refDOM:s,refTop:t,stack:n}){let r=s?s.getBoundingClientRect().top:0;Ypt(n,r==0?0:r-t)}function Ypt(s,t){for(let n=0;n=o){l=Math.max(y.bottom,l),o=Math.min(y.top,o);let _=y.left>t.left?y.left-t.left:y.right=(y.left+y.right)/2?1:0));continue}}else y.top>t.top&&!c&&y.left<=t.left&&y.right>=t.left&&(c=u,d={left:Math.max(y.left,Math.min(y.right,t.left)),top:y.top});!n&&(t.left>=y.right&&t.top>=y.top||t.left>=y.left&&t.top>=y.bottom)&&(i=h+1)}}return!n&&c&&(n=c,a=d,r=0),n&&n.nodeType==3?Kas(n,a):!n||r&&n.nodeType==1?{node:s,offset:i}:Zpt(n,a)}function Kas(s,t){let n=s.nodeValue.length,r=document.createRange(),a;for(let i=0;i=(l.left+l.right)/2?1:0)};break}}return r.detach(),a||{node:s,offset:0}}function c6e(s,t){return s.left>=t.left-1&&s.left<=t.right+1&&s.top>=t.top-1&&s.top<=t.bottom+1}function Yas(s,t){let n=s.parentNode;return n&&/^li$/i.test(n.nodeName)&&t.left(l.left+l.right)/2?1:-1}return s.docView.posFromDOM(r,a,i)}function Qas(s,t,n,r){let a=-1;for(let i=t,l=!1;i!=s.dom;){let o=s.docView.nearestDesc(i,!0),c;if(!o)return null;if(o.dom.nodeType==1&&(o.node.isBlock&&o.parent||!o.contentDOM)&&((c=o.dom.getBoundingClientRect()).width||c.height)&&(o.node.isBlock&&o.parent&&!/^T(R|BODY|HEAD|FOOT)$/.test(o.dom.nodeName)&&(!l&&c.left>r.left||c.top>r.top?a=o.posBefore:(!l&&c.right-1?a:s.docView.posFromDOM(t,n,-1)}function Qpt(s,t,n){let r=s.childNodes.length;if(r&&n.topt.top&&a++}let d;lU&&a&&r.nodeType==1&&(d=r.childNodes[a-1]).nodeType==1&&d.contentEditable=="false"&&d.getBoundingClientRect().top>=t.top&&a--,r==s.dom&&a==r.childNodes.length-1&&r.lastChild.nodeType==1&&t.top>r.lastChild.getBoundingClientRect().bottom?o=s.state.doc.content.size:(a==0||r.nodeType!=1||r.childNodes[a-1].nodeName!="BR")&&(o=Qas(s,r,a,t))}o==null&&(o=Zas(s,l,t));let c=s.docView.nearestDesc(l,!0);return{pos:o,inside:c?c.posAtStart-c.border:-1}}function KUe(s){return s.top=0&&a==r.nodeValue.length?(c--,u=1):n<0?c--:d++,oF(Ok(v2(r,c,d),u),u<0)}if(!s.state.doc.resolve(t-(i||0)).parent.inlineContent){if(i==null&&a&&(n<0||a==wv(r))){let c=r.childNodes[a-1];if(c.nodeType==1)return Pje(c.getBoundingClientRect(),!1)}if(i==null&&a=0)}if(i==null&&a&&(n<0||a==wv(r))){let c=r.childNodes[a-1],d=c.nodeType==3?v2(c,wv(c)-(l?0:1)):c.nodeType==1&&(c.nodeName!="BR"||!c.nextSibling)?c:null;if(d)return oF(Ok(d,1),!1)}if(i==null&&a=0)}function oF(s,t){if(s.width==0)return s;let n=t?s.left:s.right;return{top:s.top,bottom:s.bottom,left:n,right:n}}function Pje(s,t){if(s.height==0)return s;let n=t?s.top:s.bottom;return{top:n,bottom:n,left:s.left,right:s.right}}function Jpt(s,t,n){let r=s.state,a=s.root.activeElement;r!=t&&s.updateState(t),a!=s.dom&&s.focus();try{return n()}finally{r!=t&&s.updateState(r),a!=s.dom&&a&&a.focus()}}function eis(s,t,n){let r=t.selection,a=n=="up"?r.$from:r.$to;return Jpt(s,t,()=>{let{node:i}=s.docView.domFromPos(a.pos,n=="up"?-1:1);for(;;){let o=s.docView.nearestDesc(i,!0);if(!o)break;if(o.node.isBlock){i=o.contentDOM||o.dom;break}i=o.dom.parentNode}let l=Xpt(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=v2(o,0,o.nodeValue.length).getClientRects();else continue;for(let d=0;du.top+1&&(n=="up"?l.top-u.top>(u.bottom-l.top)*2:u.bottom-l.bottom>(l.bottom-u.top)*2))return!1}}return!0})}const tis=/[\u0590-\u08ac]/;function sis(s,t,n){let{$head:r}=t.selection;if(!r.parent.isTextblock)return!1;let a=r.parentOffset,i=!a,l=a==r.parent.content.size,o=s.domSelection();return o?!tis.test(r.parent.textContent)||!o.modify?n=="left"||n=="backward"?i:l:Jpt(s,t,()=>{let{focusNode:c,focusOffset:d,anchorNode:u,anchorOffset:h}=s.domSelectionRange(),p=o.caretBidiLevel;o.modify("move",n,"character");let f=r.depth?s.docView.domAfterPos(r.before()):s.dom,{focusNode:y,focusOffset:_}=s.domSelectionRange(),v=y&&!f.contains(y.nodeType==1?y:y.parentNode)||c==y&&d==_;try{o.collapse(u,h),c&&(c!=u||d!=h)&&o.extend&&o.extend(c,d)}catch{}return p!=null&&(o.caretBidiLevel=p),v}):r.pos==r.start()||r.pos==r.end()}let YUe=null,ZUe=null,QUe=!1;function nis(s,t,n){return YUe==t&&ZUe==n?QUe:(YUe=t,ZUe=n,QUe=n=="up"||n=="down"?eis(s,t,n):sis(s,t,n))}const $v=0,XUe=1,VE=2,Mw=3;class cU{constructor(t,n,r,a){this.parent=t,this.children=n,this.dom=r,this.contentDOM=a,this.dirty=$v,r.pmViewDesc=this}matchesWidget(t){return!1}matchesMark(t){return!1}matchesNode(t,n,r){return!1}matchesHack(t){return!1}parseRule(){return null}stopEvent(t){return!1}get size(){let t=0;for(let n=0;nsf(this.contentDOM);else if(this.contentDOM&&this.contentDOM!=this.dom&&this.dom.contains(this.contentDOM))a=t.compareDocumentPosition(this.contentDOM)&2;else if(this.dom.firstChild){if(n==0)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!1;break}if(i.previousSibling)break}if(a==null&&n==t.childNodes.length)for(let i=t;;i=i.parentNode){if(i==this.dom){a=!0;break}if(i.nextSibling)break}}return a??r>0?this.posAtEnd:this.posAtStart}nearestDesc(t,n=!1){for(let r=!0,a=t;a;a=a.parentNode){let i=this.getDesc(a),l;if(i&&(!n||i.node))if(r&&(l=i.nodeDOM)&&!(l.nodeType==1?l.contains(t.nodeType==1?t:t.parentNode):l==t))r=!1;else return i}}getDesc(t){let n=t.pmViewDesc;for(let r=n;r;r=r.parent)if(r==this)return n}posFromDOM(t,n,r){for(let a=t;a;a=a.parentNode){let i=this.getDesc(a);if(i)return i.localPosFromDOM(t,n,r)}return-1}descAt(t){for(let n=0,r=0;nt||l instanceof tft){a=t-i;break}i=o}if(a)return this.children[r].domFromPos(a-this.children[r].border,n);for(let i;r&&!(i=this.children[r-1]).size&&i instanceof eft&&i.side>=0;r--);if(n<=0){let i,l=!0;for(;i=r?this.children[r-1]:null,!(!i||i.dom.parentNode==this.contentDOM);r--,l=!1);return i&&n&&l&&!i.border&&!i.domAtom?i.domFromPos(i.size,n):{node:this.contentDOM,offset:i?sf(i.dom)+1:0}}else{let i,l=!0;for(;i=r=u&&n<=d-c.border&&c.node&&c.contentDOM&&this.contentDOM.contains(c.contentDOM))return c.parseRange(t,n,u);t=l;for(let h=o;h>0;h--){let p=this.children[h-1];if(p.size&&p.dom.parentNode==this.contentDOM&&!p.emptyChildAt(1)){a=sf(p.dom)+1;break}t-=p.size}a==-1&&(a=0)}if(a>-1&&(d>n||o==this.children.length-1)){n=d;for(let u=o+1;uy&&ln){let y=o;o=c,c=y}let f=document.createRange();f.setEnd(c.node,c.offset),f.setStart(o.node,o.offset),d.removeAllRanges(),d.addRange(f)}}ignoreMutation(t){return!this.contentDOM&&t.type!="selection"}get contentLost(){return this.contentDOM&&this.contentDOM!=this.dom&&!this.dom.contains(this.contentDOM)}markDirty(t,n){for(let r=0,a=0;a=r:tr){let o=r+i.border,c=l-i.border;if(t>=o&&n<=c){this.dirty=t==r||n==l?VE:XUe,t==o&&n==c&&(i.contentLost||i.dom.parentNode!=this.contentDOM)?i.dirty=Mw:i.markDirty(t-o,n-o);return}else i.dirty=i.dom==i.contentDOM&&i.dom.parentNode==this.contentDOM&&!i.children.length?VE:Mw}r=l}this.dirty=VE}markParentsDirty(){let t=1;for(let n=this.parent;n;n=n.parent,t++){let r=t==1?VE:XUe;n.dirty{if(!i)return a;if(i.parent)return i.parent.posBeforeChild(i)})),!n.type.spec.raw){if(l.nodeType!=1){let o=document.createElement("span");o.appendChild(l),l=o}l.contentEditable="false",l.classList.add("ProseMirror-widget")}super(t,[],l,null),this.widget=n,this.widget=n,i=this}matchesWidget(t){return this.dirty==$v&&t.type.eq(this.widget.type)}parseRule(){return{ignore:!0}}stopEvent(t){let n=this.widget.spec.stopEvent;return n?n(t):!1}ignoreMutation(t){return t.type!="selection"||this.widget.spec.ignoreSelection}destroy(){this.widget.type.destroy(this.dom),super.destroy()}get domAtom(){return!0}get ignoreForSelection(){return!!this.widget.type.spec.relaxedSide}get side(){return this.widget.type.side}}class ris extends cU{constructor(t,n,r,a){super(t,[],n,null),this.textDOM=r,this.text=a}get size(){return this.text.length}localPosFromDOM(t,n){return t!=this.textDOM?this.posAtStart+(n?this.size:0):this.posAtStart+n}domFromPos(t){return{node:this.textDOM,offset:t}}ignoreMutation(t){return t.type==="characterData"&&t.target.nodeValue==t.oldValue}}class vM extends cU{constructor(t,n,r,a,i){super(t,[],r,a),this.mark=n,this.spec=i}static create(t,n,r,a){let i=a.nodeViews[n.type.name],l=i&&i(n,a,r);return(!l||!l.dom)&&(l=UM.renderSpec(document,n.type.spec.toDOM(n,r),null,n.attrs)),new vM(t,n,l.dom,l.contentDOM||l.dom,l)}parseRule(){return this.dirty&Mw||this.mark.type.spec.reparseInView?null:{mark:this.mark.type.name,attrs:this.mark.attrs,contentElement:this.contentDOM}}matchesMark(t){return this.dirty!=Mw&&this.mark.eq(t)}markDirty(t,n){if(super.markDirty(t,n),this.dirty!=$v){let r=this.parent;for(;!r.node;)r=r.parent;r.dirty0&&(i=mCe(i,0,t,r));for(let o=0;o{if(!c)return l;if(c.parent)return c.parent.posBeforeChild(c)},r,a),u=d&&d.dom,h=d&&d.contentDOM;if(n.isText){if(!u)u=document.createTextNode(n.text);else if(u.nodeType!=3)throw new RangeError("Text must be rendered as a DOM text node")}else u||({dom:u,contentDOM:h}=UM.renderSpec(document,n.type.spec.toDOM(n),null,n.attrs));!h&&!n.isText&&u.nodeName!="BR"&&(u.hasAttribute("contenteditable")||(u.contentEditable="false"),n.type.spec.draggable&&(u.draggable=!0));let p=u;return u=rft(u,r,n),d?c=new ais(t,n,r,a,u,h||null,p,d,i,l+1):n.isText?new Oye(t,n,r,a,u,p,i):new u4(t,n,r,a,u,h||null,p,i,l+1)}parseRule(){if(this.node.type.spec.reparseInView)return null;let t={node:this.node.type.name,attrs:this.node.attrs};if(this.node.type.whitespace=="pre"&&(t.preserveWhitespace="full"),!this.contentDOM)t.getContent=()=>this.node.content;else if(!this.contentLost)t.contentElement=this.contentDOM;else{for(let n=this.children.length-1;n>=0;n--){let r=this.children[n];if(this.dom.contains(r.dom.parentNode)){t.contentElement=r.dom.parentNode;break}}t.contentElement||(t.getContent=()=>$r.empty)}return t}matchesNode(t,n,r){return this.dirty==$v&&t.eq(this.node)&&kfe(n,this.outerDeco)&&r.eq(this.innerDeco)}get size(){return this.node.nodeSize}get border(){return this.node.isLeaf?0:1}updateChildren(t,n){let r=this.node.inlineContent,a=n,i=t.composing?this.localCompositionInfo(t,n):null,l=i&&i.pos>-1?i:null,o=i&&i.pos<0,c=new ois(this,l&&l.node,t);dis(this.node,this.innerDeco,(d,u,h)=>{d.spec.marks?c.syncToMarks(d.spec.marks,r,t,u):d.type.side>=0&&!h&&c.syncToMarks(u==this.node.childCount?td.none:this.node.child(u).marks,r,t,u),c.placeWidget(d,t,a)},(d,u,h,p)=>{c.syncToMarks(d.marks,r,t,p);let f;c.findNodeMatch(d,u,h,p)||o&&t.state.selection.from>a&&t.state.selection.to-1&&c.updateNodeAt(d,u,h,f,t)||c.updateNextNode(d,u,h,t,p,a)||c.addNode(d,u,h,t,a),a+=d.nodeSize}),c.syncToMarks([],r,t,0),this.node.isTextblock&&c.addTextblockHacks(),c.destroyRest(),(c.changed||this.dirty==VE)&&(l&&this.protectLocalComposition(t,l),sft(this.contentDOM,this.children,t),N8&&uis(this.dom))}localCompositionInfo(t,n){let{from:r,to:a}=t.state.selection;if(!(t.state.selection instanceof Ui)||rn+this.node.content.size)return null;let i=t.input.compositionNode;if(!i||!this.dom.contains(i.parentNode))return null;if(this.node.inlineContent){let l=i.nodeValue,o=his(this.node.content,l,r-n,a-n);return o<0?null:{node:i,pos:o,text:l}}else return{node:i,pos:-1,text:""}}protectLocalComposition(t,{node:n,pos:r,text:a}){if(this.getDesc(n))return;let i=n;for(;i.parentNode!=this.contentDOM;i=i.parentNode){for(;i.previousSibling;)i.parentNode.removeChild(i.previousSibling);for(;i.nextSibling;)i.parentNode.removeChild(i.nextSibling);i.pmViewDesc&&(i.pmViewDesc=void 0)}let l=new ris(this,i,n,a);t.input.compositionNodes.push(l),this.children=mCe(this.children,r,r+a.length,t,l)}update(t,n,r,a){return this.dirty==Mw||!t.sameMarkup(this.node)?!1:(this.updateInner(t,n,r,a),!0)}updateInner(t,n,r,a){this.updateOuterDeco(n),this.node=t,this.innerDeco=r,this.contentDOM&&this.updateChildren(a,this.posAtStart),this.dirty=$v}updateOuterDeco(t){if(kfe(t,this.outerDeco))return;let n=this.nodeDOM.nodeType!=1,r=this.dom;this.dom=nft(this.dom,this.nodeDOM,hCe(this.outerDeco,this.node,n),hCe(t,this.node,n)),this.dom!=r&&(r.pmViewDesc=void 0,this.dom.pmViewDesc=this),this.outerDeco=t}selectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.add("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&(this.nodeDOM.draggable=!0))}deselectNode(){this.nodeDOM.nodeType==1&&(this.nodeDOM.classList.remove("ProseMirror-selectednode"),(this.contentDOM||!this.node.type.spec.draggable)&&this.nodeDOM.removeAttribute("draggable"))}get domAtom(){return this.node.isAtom}}function JUe(s,t,n,r,a){rft(r,t,s);let i=new u4(void 0,s,t,n,r,r,r,a,0);return i.contentDOM&&i.updateChildren(a,0),i}class Oye extends u4{constructor(t,n,r,a,i,l,o){super(t,n,r,a,i,null,l,o,0)}parseRule(){let t=this.nodeDOM.parentNode;for(;t&&t!=this.dom&&!t.pmIsDeco;)t=t.parentNode;return{skip:t||!0}}update(t,n,r,a){return this.dirty==Mw||this.dirty!=$v&&!this.inParent()||!t.sameMarkup(this.node)?!1:(this.updateOuterDeco(n),(this.dirty!=$v||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=$v,!0)}inParent(){let t=this.parent.contentDOM;for(let n=this.nodeDOM;n;n=n.parentNode)if(n==t)return!0;return!1}domFromPos(t){return{node:this.nodeDOM,offset:t}}localPosFromDOM(t,n,r){return t==this.nodeDOM?this.posAtStart+Math.min(n,this.node.text.length):super.localPosFromDOM(t,n,r)}ignoreMutation(t){return t.type!="characterData"&&t.type!="selection"}slice(t,n,r){let a=this.node.cut(t,n),i=document.createTextNode(a.text);return new Oye(this.parent,a,this.outerDeco,this.innerDeco,i,i,r)}markDirty(t,n){super.markDirty(t,n),this.dom!=this.nodeDOM&&(t==0||n==this.nodeDOM.nodeValue.length)&&(this.dirty=Mw)}get domAtom(){return!1}isText(t){return this.node.text==t}}class tft extends cU{parseRule(){return{ignore:!0}}matchesHack(t){return this.dirty==$v&&this.dom.nodeName==t}get domAtom(){return!0}get ignoreForCoords(){return this.dom.nodeName=="IMG"}}class ais extends u4{constructor(t,n,r,a,i,l,o,c,d,u){super(t,n,r,a,i,l,o,d,u),this.spec=c}update(t,n,r,a){if(this.dirty==Mw)return!1;if(this.spec.update&&(this.node.type==t.type||this.spec.multiType)){let i=this.spec.update(t,n,r);return i&&this.updateInner(t,n,r,a),i}else return!this.contentDOM&&!t.isLeaf?!1:super.update(t,n,r,a)}selectNode(){this.spec.selectNode?this.spec.selectNode():super.selectNode()}deselectNode(){this.spec.deselectNode?this.spec.deselectNode():super.deselectNode()}setSelection(t,n,r,a){this.spec.setSelection?this.spec.setSelection(t,n,r.root):super.setSelection(t,n,r,a)}destroy(){this.spec.destroy&&this.spec.destroy(),super.destroy()}stopEvent(t){return this.spec.stopEvent?this.spec.stopEvent(t):!1}ignoreMutation(t){return this.spec.ignoreMutation?this.spec.ignoreMutation(t):super.ignoreMutation(t)}}function sft(s,t,n){let r=s.firstChild,a=!1;for(let i=0;i>1,o=Math.min(l,t.length);for(;i-1)c>this.index&&(this.changed=!0,this.destroyBetween(this.index,c)),this.top=this.top.children[this.index];else{let u=vM.create(this.top,t[l],n,r);this.top.children.splice(this.index,0,u),this.top=u,this.changed=!0}this.index=0,l++}}findNodeMatch(t,n,r,a){let i=-1,l;if(a>=this.preMatch.index&&(l=this.preMatch.matches[a-this.preMatch.index]).parent==this.top&&l.matchesNode(t,n,r))i=this.top.children.indexOf(l,this.index);else for(let o=this.index,c=Math.min(this.top.children.length,o+5);o0;){let o;for(;;)if(r){let d=n.children[r-1];if(d instanceof vM)n=d,r=d.children.length;else{o=d,r--;break}}else{if(n==t)break e;r=n.parent.children.indexOf(n),n=n.parent}let c=o.node;if(c){if(c!=s.child(a-1))break;--a,i.set(o,a),l.push(o)}}return{index:a,matched:i,matches:l.reverse()}}function cis(s,t){return s.type.side-t.type.side}function dis(s,t,n,r){let a=t.locals(s),i=0;if(a.length==0){for(let d=0;di;)o.push(a[l++]);let y=i+p.nodeSize;if(p.isText){let v=y;l!v.inline):o.slice();r(p,_,t.forChild(i,p),f),i=y}}function uis(s){if(s.nodeName=="UL"||s.nodeName=="OL"){let t=s.style.cssText;s.style.cssText=t+"; list-style: square !important",window.getComputedStyle(s).listStyle,s.style.cssText=t}}function his(s,t,n,r){for(let a=0,i=0;a=n){if(i>=r&&c.slice(r-t.length-o,r-o)==t)return r-t.length;let d=o=0&&d+t.length+o>=n)return o+d;if(n==r&&c.length>=r+t.length-o&&c.slice(r-o,r-o+t.length)==t)return r}}return-1}function mCe(s,t,n,r,a){let i=[];for(let l=0,o=0;l=n||u<=t?i.push(c):(dn&&i.push(c.slice(n-d,c.size,r)))}return i}function d6e(s,t=null){let n=s.domSelectionRange(),r=s.state.doc;if(!n.focusNode)return null;let a=s.docView.nearestDesc(n.focusNode),i=a&&a.size==0,l=s.docView.posFromDOM(n.focusNode,n.focusOffset,1);if(l<0)return null;let o=r.resolve(l),c,d;if(Rye(n)){for(c=l;a&&!a.node;)a=a.parent;let h=a.node;if(a&&h.isAtom&&Li.isSelectable(h)&&a.parent&&!(h.isInline&&zas(n.focusNode,n.focusOffset,a.dom))){let p=a.posBefore;d=new Li(l==p?o:r.resolve(p))}}else{if(n instanceof s.dom.ownerDocument.defaultView.Selection&&n.rangeCount>1){let h=l,p=l;for(let f=0;f{(n.anchorNode!=r||n.anchorOffset!=a)&&(t.removeEventListener("selectionchange",s.input.hideSelectionGuard),setTimeout(()=>{(!aft(s)||s.state.selection.visible)&&s.dom.classList.remove("ProseMirror-hideselection")},20))})}function pis(s){let t=s.domSelection();if(!t)return;let n=s.cursorWrapper.dom,r=n.nodeName=="IMG";r?t.collapse(n.parentNode,sf(n)+1):t.collapse(n,0),!r&&!s.state.selection.visible&&Hg&&d4<=11&&(n.disabled=!0,n.disabled=!1)}function ift(s,t){if(t instanceof Li){let n=s.docView.descAt(t.from);n!=s.lastSelectedViewDesc&&(rqe(s),n&&n.selectNode(),s.lastSelectedViewDesc=n)}else rqe(s)}function rqe(s){s.lastSelectedViewDesc&&(s.lastSelectedViewDesc.parent&&s.lastSelectedViewDesc.deselectNode(),s.lastSelectedViewDesc=void 0)}function u6e(s,t,n,r){return s.someProp("createSelectionBetween",a=>a(s,t,n))||Ui.between(t,n,r)}function aqe(s){return s.editable&&!s.hasFocus()?!1:oft(s)}function oft(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 fis(s){let t=s.docView.domFromPos(s.state.selection.anchor,0),n=s.domSelectionRange();return yM(t.node,t.offset,n.anchorNode,n.anchorOffset)}function pCe(s,t){let{$anchor:n,$head:r}=s.selection,a=t>0?n.max(r):n.min(r),i=a.parent.inlineContent?a.depth?s.doc.resolve(t>0?a.after():a.before()):null:a;return i&&to.findFrom(i,t)}function Hk(s,t){return s.dispatch(s.state.tr.setSelection(t).scrollIntoView()),!0}function iqe(s,t,n){let r=s.state.selection;if(r instanceof Ui)if(n.indexOf("s")>-1){let{$head:a}=r,i=a.textOffset?null:t<0?a.nodeBefore:a.nodeAfter;if(!i||i.isText||!i.isLeaf)return!1;let l=s.state.doc.resolve(a.pos+i.nodeSize*(t<0?-1:1));return Hk(s,new Ui(r.$anchor,l))}else if(r.empty){if(s.endOfTextblock(t>0?"forward":"backward")){let a=pCe(s.state,t);return a&&a instanceof Li?Hk(s,a):!1}else if(!(gv&&n.indexOf("m")>-1)){let a=r.$head,i=a.textOffset?null:t<0?a.nodeBefore:a.nodeAfter,l;if(!i||i.isText)return!1;let o=t<0?a.pos-i.nodeSize:a.pos;return i.isAtom||(l=s.docView.descAt(o))&&!l.contentDOM?Li.isSelectable(i)?Hk(s,new Li(t<0?s.state.doc.resolve(a.pos-i.nodeSize):a)):lU?Hk(s,new Ui(s.state.doc.resolve(t<0?o:o+i.nodeSize))):!1:!1}}else return!1;else{if(r instanceof Li&&r.node.isInline)return Hk(s,new Ui(t>0?r.$to:r.$from));{let a=pCe(s.state,t);return a?Hk(s,a):!1}}}function Sfe(s){return s.nodeType==3?s.nodeValue.length:s.childNodes.length}function Q9(s,t){let n=s.pmViewDesc;return n&&n.size==0&&(t<0||s.nextSibling||s.nodeName!="BR")}function vI(s,t){return t<0?xis(s):gis(s)}function xis(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a,i,l=!1;for(Bv&&n.nodeType==1&&r0){if(n.nodeType!=1)break;{let o=n.childNodes[r-1];if(Q9(o,-1))a=n,i=--r;else if(o.nodeType==3)n=o,r=n.nodeValue.length;else break}}else{if(lft(n))break;{let o=n.previousSibling;for(;o&&Q9(o,-1);)a=n.parentNode,i=sf(o),o=o.previousSibling;if(o)n=o,r=Sfe(n);else{if(n=n.parentNode,n==s.dom)break;r=0}}}l?fCe(s,n,r):a&&fCe(s,a,i)}function gis(s){let t=s.domSelectionRange(),n=t.focusNode,r=t.focusOffset;if(!n)return;let a=Sfe(n),i,l;for(;;)if(r{s.state==a&&Q2(s)},50)}function oqe(s,t){let n=s.state.doc.resolve(t);if(!(cf||Wpt)&&n.parent.inlineContent){let a=s.coordsAtPos(t);if(t>n.start()){let i=s.coordsAtPos(t-1),l=(i.top+i.bottom)/2;if(l>a.top&&l1)return i.lefta.top&&l1)return i.left>a.left?"ltr":"rtl"}}return getComputedStyle(s.dom).direction=="rtl"?"rtl":"ltr"}function lqe(s,t,n){let r=s.state.selection;if(r instanceof Ui&&!r.empty||n.indexOf("s")>-1||gv&&n.indexOf("m")>-1)return!1;let{$from:a,$to:i}=r;if(!a.parent.inlineContent||s.endOfTextblock(t<0?"up":"down")){let l=pCe(s.state,t);if(l&&l instanceof Li)return Hk(s,l)}if(!a.parent.inlineContent){let l=t<0?a:i,o=r instanceof zv?to.near(l,t):to.findFrom(l,t);return o?Hk(s,o):!1}return!1}function cqe(s,t){if(!(s.state.selection instanceof Ui))return!0;let{$head:n,$anchor:r,empty:a}=s.state.selection;if(!n.sameParent(r))return!0;if(!a)return!1;if(s.endOfTextblock(t>0?"forward":"backward"))return!0;let i=!n.textOffset&&(t<0?n.nodeBefore:n.nodeAfter);if(i&&!i.isText){let l=s.state.tr;return t<0?l.delete(n.pos-i.nodeSize,n.pos):l.delete(n.pos,n.pos+i.nodeSize),s.dispatch(l),!0}return!1}function dqe(s,t,n){s.domObserver.stop(),t.contentEditable=n,s.domObserver.start()}function bis(s){if(!nx||s.state.selection.$head.parentOffset>0)return!1;let{focusNode:t,focusOffset:n}=s.domSelectionRange();if(t&&t.nodeType==1&&n==0&&t.firstChild&&t.firstChild.contentEditable=="false"){let r=t.firstChild;dqe(s,r,"true"),setTimeout(()=>dqe(s,r,"false"),20)}return!1}function _is(s){let t="";return s.ctrlKey&&(t+="c"),s.metaKey&&(t+="m"),s.altKey&&(t+="a"),s.shiftKey&&(t+="s"),t}function wis(s,t){let n=t.keyCode,r=_is(t);if(n==8||gv&&n==72&&r=="c")return cqe(s,-1)||vI(s,-1);if(n==46&&!t.shiftKey||gv&&n==68&&r=="c")return cqe(s,1)||vI(s,1);if(n==13||n==27)return!0;if(n==37||gv&&n==66&&r=="c"){let a=n==37?oqe(s,s.state.selection.from)=="ltr"?-1:1:-1;return iqe(s,a,r)||vI(s,a)}else if(n==39||gv&&n==70&&r=="c"){let a=n==39?oqe(s,s.state.selection.from)=="ltr"?1:-1:1;return iqe(s,a,r)||vI(s,a)}else{if(n==38||gv&&n==80&&r=="c")return lqe(s,-1,r)||vI(s,-1);if(n==40||gv&&n==78&&r=="c")return bis(s)||lqe(s,1,r)||vI(s,1);if(r==(gv?"m":"c")&&(n==66||n==73||n==89||n==90))return!0}return!1}function h6e(s,t){s.someProp("transformCopied",f=>{t=f(t,s)});let n=[],{content:r,openStart:a,openEnd:i}=t;for(;a>1&&i>1&&r.childCount==1&&r.firstChild.childCount==1;){a--,i--;let f=r.firstChild;n.push(f.type.name,f.attrs!=f.type.defaultAttrs?f.attrs:null),r=f.content}let l=s.someProp("clipboardSerializer")||UM.fromSchema(s.state.schema),o=pft(),c=o.createElement("div");c.appendChild(l.serializeFragment(r,{document:o}));let d=c.firstChild,u,h=0;for(;d&&d.nodeType==1&&(u=mft[d.nodeName.toLowerCase()]);){for(let f=u.length-1;f>=0;f--){let y=o.createElement(u[f]);for(;c.firstChild;)y.appendChild(c.firstChild);c.appendChild(y),h++}d=c.firstChild}d&&d.nodeType==1&&d.setAttribute("data-pm-slice",`${a} ${i}${h?` -${h}`:""} ${JSON.stringify(n)}`);let p=s.someProp("clipboardTextSerializer",f=>f(t,s))||t.content.textBetween(0,t.content.size,` `);return{dom:c,text:p,slice:t}}function cft(s,t,n,r,a){let i=a.parent.type.spec.code,l,o;if(!n&&!t)return null;let c=!!t&&(r||i||!n);if(c){if(s.someProp("transformPastedText",p=>{t=p(t,i||r,s)}),i)return o=new ba($r.from(s.state.schema.text(t.replace(/\r\n?/g,` `))),0,0),s.someProp("transformPasted",p=>{o=p(o,s,!0)}),o;let h=s.someProp("clipboardTextParser",p=>p(t,a,r,s));if(h)o=h;else{let p=a.marks(),{schema:f}=s.state,y=UM.fromSchema(f);l=document.createElement("div"),t.split(/(?:\r\n?|\n)+/).forEach(_=>{let v=l.appendChild(document.createElement("p"));_&&v.appendChild(y.serializeNode(f.text(_,p)))})}}else s.someProp("transformPastedHTML",h=>{n=h(n,s)}),l=Sis(n),lU&&Cis(l);let d=l&&l.querySelector("[data-pm-slice]"),u=d&&/^(\d+) (\d+)(?: -(\d+))? (.*)/.exec(d.getAttribute("data-pm-slice")||"");if(u&&u[3])for(let h=+u[3];h>0;h--){let p=l.firstChild;for(;p&&p.nodeType!=1;)p=p.nextSibling;if(!p)break;l=p}if(o||(o=(s.someProp("clipboardParser")||s.someProp("domParser")||K9.fromSchema(s.state.schema)).parseSlice(l,{preserveWhitespace:!!(c||u),context:a,ruleFromNode(p){return p.nodeName=="BR"&&!p.nextSibling&&p.parentNode&&!jis.test(p.parentNode.nodeName)?{ignore:!0}:null}})),u)o=Tis(uqe(o,+u[1],+u[2]),u[4]);else if(o=ba.maxOpen(Nis(o.content,a),!0),o.openStart||o.openEnd){let h=0,p=0;for(let f=o.content.firstChild;h{o=h(o,s,c)}),o}const jis=/^(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 Nis(s,t){if(s.childCount<2)return s;for(let n=t.depth;n>=0;n--){let a=t.node(n).contentMatchAt(t.index(n)),i,l=[];if(s.forEach(o=>{if(!l)return;let c=a.findWrapping(o.type),d;if(!c)return l=null;if(d=l.length&&i.length&&uft(c,i,o,l[l.length-1],0))l[l.length-1]=d;else{l.length&&(l[l.length-1]=hft(l[l.length-1],i.length));let u=dft(o,c);l.push(u),a=a.matchType(u.type),i=c}}),l)return $r.from(l)}return s}function dft(s,t,n=0){for(let r=t.length-1;r>=n;r--)s=t[r].create(null,$r.from(s));return s}function uft(s,t,n,r,a){if(a1&&(i=0),a=n&&(o=t<0?l.contentMatchAt(0).fillBefore(o,i<=a).append(o):o.append(l.contentMatchAt(l.childCount).fillBefore($r.empty,!0))),s.replaceChild(t<0?0:s.childCount-1,l.copy(o))}function uqe(s,t,n){return tn})),Dje.createHTML(s)):s}function Sis(s){let t=/^(\s*]*>)*/.exec(s);t&&(s=s.slice(t[0].length));let n=pft().createElement("div"),r=/<([a-z][^>\s]+)/i.exec(s),a;if((a=r&&mft[r[1].toLowerCase()])&&(s=a.map(i=>"<"+i+">").join("")+s+a.map(i=>"").reverse().join("")),n.innerHTML=kis(s),a)for(let i=0;i=0;o-=2){let c=n.nodes[r[o]];if(!c||c.hasRequiredAttrs())break;a=$r.from(c.create(r[o+1],a)),i++,l++}return new ba(a,i,l)}const sg={},ng={},Eis={touchstart:!0,touchmove:!0};class Ais{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 Mis(s){for(let t in sg){let n=sg[t];s.dom.addEventListener(t,s.input.eventHandlers[t]=r=>{Pis(s,r)&&!m6e(s,r)&&(s.editable||!(r.type in ng))&&n(s,r)},Eis[t]?{passive:!0}:void 0)}nx&&s.dom.addEventListener("input",()=>null),gCe(s)}function CS(s,t){s.input.lastSelectionOrigin=t,s.input.lastSelectionTime=Date.now()}function Iis(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 gCe(s){s.someProp("handleDOMEvents",t=>{for(let n in t)s.input.eventHandlers[n]||s.dom.addEventListener(n,s.input.eventHandlers[n]=r=>m6e(s,r))})}function m6e(s,t){return s.someProp("handleDOMEvents",n=>{let r=n[t.type];return r?r(s,t)||t.defaultPrevented:!1})}function Pis(s,t){if(!t.bubbles)return!0;if(t.defaultPrevented)return!1;for(let n=t.target;n!=s.dom;n=n.parentNode)if(!n||n.nodeType==11||n.pmViewDesc&&n.pmViewDesc.stopEvent(t))return!1;return!0}function Lis(s,t){!m6e(s,t)&&sg[t.type]&&(s.editable||!(t.type in ng))&&sg[t.type](s,t)}ng.keydown=(s,t)=>{let n=t;if(s.input.shiftKey=n.keyCode==16||n.shiftKey,!xft(s,n)&&(s.input.lastKeyCode=n.keyCode,s.input.lastKeyCodeTime=Date.now(),!(D2&&cf&&n.keyCode==13)))if(n.keyCode!=229&&s.domObserver.forceFlush(),N8&&n.keyCode==13&&!n.ctrlKey&&!n.altKey&&!n.metaKey){let r=Date.now();s.input.lastIOSEnter=r,s.input.lastIOSEnterFallbackTimeout=setTimeout(()=>{s.input.lastIOSEnter==r&&(s.someProp("handleKeyDown",a=>a(s,LE(13,"Enter"))),s.input.lastIOSEnter=0)},200)}else s.someProp("handleKeyDown",r=>r(s,n))||wis(s,n)?n.preventDefault():CS(s,"key")};ng.keyup=(s,t)=>{t.keyCode==16&&(s.input.shiftKey=!1)};ng.keypress=(s,t)=>{let n=t;if(xft(s,n)||!n.charCode||n.ctrlKey&&!n.altKey||gv&&n.metaKey)return;if(s.someProp("handleKeyPress",a=>a(s,n))){n.preventDefault();return}let r=s.state.selection;if(!(r instanceof Ui)||!r.$from.sameParent(r.$to)){let a=String.fromCharCode(n.charCode),i=()=>s.state.tr.insertText(a).scrollIntoView();!/[\r\n]/.test(a)&&!s.someProp("handleTextInput",l=>l(s,r.$from.pos,r.$to.pos,a,i))&&s.dispatch(i()),n.preventDefault()}};function Fye(s){return{left:s.clientX,top:s.clientY}}function Dis(s,t){let n=t.x-s.clientX,r=t.y-s.clientY;return n*n+r*r<100}function p6e(s,t,n,r,a){if(r==-1)return!1;let i=s.state.doc.resolve(r);for(let l=i.depth+1;l>0;l--)if(s.someProp(t,o=>l>i.depth?o(s,n,i.nodeAfter,i.before(l),a,!0):o(s,n,i.node(l),i.before(l),a,!1)))return!0;return!1}function ML(s,t,n){if(s.focused||s.focus(),s.state.selection.eq(t))return;let r=s.state.tr.setSelection(t);r.setMeta("pointer",!0),s.dispatch(r)}function Ris(s,t){if(t==-1)return!1;let n=s.state.doc.resolve(t),r=n.nodeAfter;return r&&r.isAtom&&Li.isSelectable(r)?(ML(s,new Li(n)),!0):!1}function Ois(s,t){if(t==-1)return!1;let n=s.state.selection,r,a;n instanceof Li&&(r=n.node);let i=s.state.doc.resolve(t);for(let l=i.depth+1;l>0;l--){let o=l>i.depth?i.nodeAfter:i.node(l);if(Li.isSelectable(o)){r&&n.$from.depth>0&&l>=n.$from.depth&&i.before(n.$from.depth+1)==n.$from.pos?a=i.before(n.$from.depth):a=i.before(l);break}}return a!=null?(ML(s,Li.create(s.state.doc,a)),!0):!1}function Fis(s,t,n,r,a){return p6e(s,"handleClickOn",t,n,r)||s.someProp("handleClick",i=>i(s,t,r))||(a?Ois(s,n):Ris(s,n))}function zis(s,t,n,r){return p6e(s,"handleDoubleClickOn",t,n,r)||s.someProp("handleDoubleClick",a=>a(s,t,r))}function Bis(s,t,n,r){return p6e(s,"handleTripleClickOn",t,n,r)||s.someProp("handleTripleClick",a=>a(s,t,r))||$is(s,n,r)}function $is(s,t,n){if(n.button!=0)return!1;let r=s.state.doc;if(t==-1)return r.inlineContent?(ML(s,Ui.create(r,0,r.content.size)),!0):!1;let a=r.resolve(t);for(let i=a.depth+1;i>0;i--){let l=i>a.depth?a.nodeAfter:a.node(i),o=a.before(i);if(l.inlineContent)ML(s,Ui.create(r,o+1,o+1+l.content.size));else if(Li.isSelectable(l))ML(s,Li.create(r,o));else continue;return!0}}function f6e(s){return Cfe(s)}const fft=gv?"metaKey":"ctrlKey";sg.mousedown=(s,t)=>{let n=t;s.input.shiftKey=n.shiftKey;let r=f6e(s),a=Date.now(),i="singleClick";a-s.input.lastClick.time<500&&Dis(n,s.input.lastClick)&&!n[fft]&&s.input.lastClick.button==n.button&&(s.input.lastClick.type=="singleClick"?i="doubleClick":s.input.lastClick.type=="doubleClick"&&(i="tripleClick")),s.input.lastClick={time:a,x:n.clientX,y:n.clientY,type:i,button:n.button};let l=s.posAtCoords(Fye(n));l&&(i=="singleClick"?(s.input.mouseDown&&s.input.mouseDown.done(),s.input.mouseDown=new Uis(s,l,n,!!r)):(i=="doubleClick"?zis:Bis)(s,l.pos,l.inside,n)?n.preventDefault():CS(s,"pointer"))};class Uis{constructor(t,n,r,a){this.view=t,this.pos=n,this.event=r,this.flushed=a,this.delayedSelectionSync=!1,this.mightDrag=null,this.startDoc=t.state.doc,this.selectNode=!!r[fft],this.allowDefault=r.shiftKey;let i,l;if(n.inside>-1)i=t.state.doc.nodeAt(n.inside),l=n.inside;else{let u=t.state.doc.resolve(n.pos);i=u.parent,l=u.depth?u.before():0}const o=a?null:r.target,c=o?t.docView.nearestDesc(o,!0):null;this.target=c&&c.nodeDOM.nodeType==1?c.nodeDOM:null;let{selection:d}=t.state;r.button==0&&(i.type.spec.draggable&&i.type.spec.selectable!==!1||d instanceof Li&&d.from<=l&&d.to>l)&&(this.mightDrag={node:i,pos:l,addAttr:!!(this.target&&!this.target.draggable),setUneditable:!!(this.target&&Bv&&!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)),CS(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(()=>Q2(this.view)),this.view.input.mouseDown=null}up(t){if(this.done(),!this.view.dom.contains(t.target))return;let n=this.pos;this.view.state.doc!=this.startDoc&&(n=this.view.posAtCoords(Fye(t))),this.updateAllowDefault(t),this.allowDefault||!n?CS(this.view,"pointer"):Fis(this.view,n.pos,n.inside,t,this.selectNode)?t.preventDefault():t.button==0&&(this.flushed||nx&&this.mightDrag&&!this.mightDrag.node.isAtom||cf&&!this.view.state.selection.visible&&Math.min(Math.abs(n.pos-this.view.state.selection.from),Math.abs(n.pos-this.view.state.selection.to))<=2)?(ML(this.view,to.near(this.view.state.doc.resolve(n.pos))),t.preventDefault()):CS(this.view,"pointer")}move(t){this.updateAllowDefault(t),CS(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)}}sg.touchstart=s=>{s.input.lastTouch=Date.now(),f6e(s),CS(s,"pointer")};sg.touchmove=s=>{s.input.lastTouch=Date.now(),CS(s,"pointer")};sg.contextmenu=s=>f6e(s);function xft(s,t){return s.composing?!0:nx&&Math.abs(t.timeStamp-s.input.compositionEndedAt)<500?(s.input.compositionEndedAt=-2e8,!0):!1}const qis=D2?5e3:-1;ng.compositionstart=ng.compositionupdate=s=>{if(!s.composing){s.domObserver.flush();let{state:t}=s,n=t.selection.$to;if(t.selection instanceof Ui&&(t.storedMarks||!n.textOffset&&n.parentOffset&&n.nodeBefore.marks.some(r=>r.type.spec.inclusive===!1)||cf&&Wpt&&Vis(s)))s.markCursor=s.state.storedMarks||n.marks(),Cfe(s,!0),s.markCursor=null;else if(Cfe(s,!t.selection.empty),Bv&&t.selection.empty&&n.parentOffset&&!n.textOffset&&n.nodeBefore.marks.length){let r=s.domSelectionRange();for(let a=r.focusNode,i=r.focusOffset;a&&a.nodeType==1&&i!=0;){let l=i<0?a.lastChild:a.childNodes[i-1];if(!l)break;if(l.nodeType==3){let o=s.domSelection();o&&o.collapse(l,l.nodeValue.length);break}else a=l,i=-1}}s.input.composing=!0}gft(s,qis)};function Vis(s){let{focusNode:t,focusOffset:n}=s.domSelectionRange();if(!t||t.nodeType!=1||n>=t.childNodes.length)return!1;let r=t.childNodes[n];return r.nodeType==1&&r.contentEditable=="false"}ng.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++,gft(s,20))};function gft(s,t){clearTimeout(s.input.composingTimeout),t>-1&&(s.input.composingTimeout=setTimeout(()=>Cfe(s),t))}function yft(s){for(s.composing&&(s.input.composing=!1,s.input.compositionEndedAt=Gis());s.input.compositionNodes.length>0;)s.input.compositionNodes.pop().markParentsDirty()}function His(s){let t=s.domSelectionRange();if(!t.focusNode)return null;let n=Oas(t.focusNode,t.focusOffset),r=Fas(t.focusNode,t.focusOffset);if(n&&r&&n!=r){let a=r.pmViewDesc,i=s.domObserver.lastChangedTextNode;if(n==i||r==i)return i;if(!a||!a.isText(r.nodeValue))return r;if(s.input.compositionNode==r){let l=n.pmViewDesc;if(!(!l||!l.isText(n.nodeValue)))return r}}return n||r}function Gis(){let s=document.createEvent("Event");return s.initEvent("event",!0,!0),s.timeStamp}function Cfe(s,t=!1){if(!(D2&&s.domObserver.flushingSoon>=0)){if(s.domObserver.forceFlush(),yft(s),t||s.docView&&s.docView.dirty){let n=d6e(s),r=s.state.selection;return n&&!n.eq(r)?s.dispatch(s.state.tr.setSelection(n)):(s.markCursor||t)&&!r.$from.node(r.$from.sharedDepth(r.to)).inlineContent?s.dispatch(s.state.tr.deleteSelection()):s.updateState(s.state),!0}return!1}}function Wis(s,t){if(!s.dom.parentNode)return;let n=s.dom.parentNode.appendChild(document.createElement("div"));n.appendChild(t),n.style.cssText="position: fixed; left: -10000px; top: 10px";let r=getSelection(),a=document.createRange();a.selectNodeContents(t),s.dom.blur(),r.removeAllRanges(),r.addRange(a),setTimeout(()=>{n.parentNode&&n.parentNode.removeChild(n),s.focus()},50)}const hB=Hg&&d4<15||N8&&Uas<604;sg.copy=ng.cut=(s,t)=>{let n=t,r=s.state.selection,a=n.type=="cut";if(r.empty)return;let i=hB?null:n.clipboardData,l=r.content(),{dom:o,text:c}=h6e(s,l);i?(n.preventDefault(),i.clearData(),i.setData("text/html",o.innerHTML),i.setData("text/plain",c)):Wis(s,o),a&&s.dispatch(s.state.tr.deleteSelection().scrollIntoView().setMeta("uiEvent","cut"))};function Kis(s){return s.openStart==0&&s.openEnd==0&&s.content.childCount==1?s.content.firstChild:null}function Yis(s,t){if(!s.dom.parentNode)return;let n=s.input.shiftKey||s.state.selection.$from.parent.type.spec.code,r=s.dom.parentNode.appendChild(document.createElement(n?"textarea":"div"));n||(r.contentEditable="true"),r.style.cssText="position: fixed; left: -10000px; top: 10px",r.focus();let a=s.input.shiftKey&&s.input.lastKeyCode!=45;setTimeout(()=>{s.focus(),r.parentNode&&r.parentNode.removeChild(r),n?mB(s,r.value,null,a,t):mB(s,r.textContent,r.innerHTML,a,t)},50)}function mB(s,t,n,r,a){let i=cft(s,t,n,r,s.state.selection.$from);if(s.someProp("handlePaste",c=>c(s,a,i||ba.empty)))return!0;if(!i)return!1;let l=Kis(i),o=l?s.state.tr.replaceSelectionWith(l,r):s.state.tr.replaceSelection(i);return s.dispatch(o.scrollIntoView().setMeta("paste",!0).setMeta("uiEvent","paste")),!0}function vft(s){let t=s.getData("text/plain")||s.getData("Text");if(t)return t;let n=s.getData("text/uri-list");return n?n.replace(/\r?\n/g," "):""}ng.paste=(s,t)=>{let n=t;if(s.composing&&!D2)return;let r=hB?null:n.clipboardData,a=s.input.shiftKey&&s.input.lastKeyCode!=45;r&&mB(s,vft(r),r.getData("text/html"),a,n)?n.preventDefault():Yis(s,n)};class bft{constructor(t,n,r){this.slice=t,this.move=n,this.node=r}}const Zis=gv?"altKey":"ctrlKey";function _ft(s,t){let n;return s.someProp("dragCopies",r=>{n=n||r(t)}),n!=null?!n:!t[Zis]}sg.dragstart=(s,t)=>{let n=t,r=s.input.mouseDown;if(r&&r.done(),!n.dataTransfer)return;let a=s.state.selection,i=a.empty?null:s.posAtCoords(Fye(n)),l;if(!(i&&i.pos>=a.from&&i.pos<=(a instanceof Li?a.to-1:a.to))){if(r&&r.mightDrag)l=Li.create(s.state.doc,r.mightDrag.pos);else if(n.target&&n.target.nodeType==1){let h=s.docView.nearestDesc(n.target,!0);h&&h.node.type.spec.draggable&&h!=s.docView&&(l=Li.create(s.state.doc,h.posBefore))}}let o=(l||s.state.selection).content(),{dom:c,text:d,slice:u}=h6e(s,o);(!n.dataTransfer.files.length||!cf||Gpt>120)&&n.dataTransfer.clearData(),n.dataTransfer.setData(hB?"Text":"text/html",c.innerHTML),n.dataTransfer.effectAllowed="copyMove",hB||n.dataTransfer.setData("text/plain",d),s.dragging=new bft(u,_ft(s,n),l)};sg.dragend=s=>{let t=s.dragging;window.setTimeout(()=>{s.dragging==t&&(s.dragging=null)},50)};ng.dragover=ng.dragenter=(s,t)=>t.preventDefault();ng.drop=(s,t)=>{try{Qis(s,t,s.dragging)}finally{s.dragging=null}};function Qis(s,t,n){if(!t.dataTransfer)return;let r=s.posAtCoords(Fye(t));if(!r)return;let a=s.state.doc.resolve(r.pos),i=n&&n.slice;i?s.someProp("transformPasted",f=>{i=f(i,s,!1)}):i=cft(s,vft(t.dataTransfer),hB?null:t.dataTransfer.getData("text/html"),!1,a);let l=!!(n&&_ft(s,t));if(s.someProp("handleDrop",f=>f(s,t,i||ba.empty,l))){t.preventDefault();return}if(!i)return;t.preventDefault();let o=i?Opt(s.state.doc,a.pos,i):a.pos;o==null&&(o=a.pos);let c=s.state.tr;if(l){let{node:f}=n;f?f.replace(c):c.deleteSelection()}let d=c.mapping.map(o),u=i.openStart==0&&i.openEnd==0&&i.content.childCount==1,h=c.doc;if(u?c.replaceRangeWith(d,d,i.content.firstChild):c.replaceRange(d,d,i),c.doc.eq(h))return;let p=c.doc.resolve(d);if(u&&Li.isSelectable(i.content.firstChild)&&p.nodeAfter&&p.nodeAfter.sameMarkup(i.content.firstChild))c.setSelection(new Li(p));else{let f=c.mapping.map(o);c.mapping.maps[c.mapping.maps.length-1].forEach((y,_,v,j)=>f=j),c.setSelection(u6e(s,p,c.doc.resolve(f)))}s.focus(),s.dispatch(c.setMeta("uiEvent","drop"))}sg.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())&&Q2(s)},20))};sg.blur=(s,t)=>{let n=t;s.focused&&(s.domObserver.stop(),s.dom.classList.remove("ProseMirror-focused"),s.domObserver.start(),n.relatedTarget&&s.dom.contains(n.relatedTarget)&&s.domObserver.currentSelection.clear(),s.focused=!1)};sg.beforeinput=(s,t)=>{if(cf&&D2&&t.inputType=="deleteContentBackward"){s.domObserver.flushSoon();let{domChangeCount:r}=s.input;setTimeout(()=>{if(s.input.domChangeCount!=r||(s.dom.blur(),s.focus(),s.someProp("handleKeyDown",i=>i(s,LE(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 ng)sg[s]=ng[s];function pB(s,t){if(s==t)return!0;for(let n in s)if(s[n]!==t[n])return!1;for(let n in t)if(!(n in s))return!1;return!0}class Tfe{constructor(t,n){this.toDOM=t,this.spec=n||UA,this.side=this.spec.side||0}map(t,n,r,a){let{pos:i,deleted:l}=t.mapResult(n.from+a,this.side<0?-1:1);return l?null:new Kx(i-r,i-r,this)}valid(){return!0}eq(t){return this==t||t instanceof Tfe&&(this.spec.key&&this.spec.key==t.spec.key||this.toDOM==t.toDOM&&pB(this.spec,t.spec))}destroy(t){this.spec.destroy&&this.spec.destroy(t)}}class h4{constructor(t,n){this.attrs=t,this.spec=n||UA}map(t,n,r,a){let i=t.map(n.from+a,this.spec.inclusiveStart?-1:1)-r,l=t.map(n.to+a,this.spec.inclusiveEnd?1:-1)-r;return i>=l?null:new Kx(i,l,this)}valid(t,n){return n.from=t&&(!i||i(o.spec))&&r.push(o.copy(o.from+a,o.to+a))}for(let l=0;lt){let o=this.children[l]+1;this.children[l+2].findInner(t-o,n-o,r,a+o,i)}}map(t,n,r){return this==Vf||t.maps.length==0?this:this.mapInner(t,n,0,0,r||UA)}mapInner(t,n,r,a,i){let l;for(let o=0;o{let d=c+r,u;if(u=jft(n,o,d)){for(a||(a=this.children.slice());io&&h.to=t){this.children[o]==t&&(r=this.children[o+2]);break}let i=t+1,l=i+n.content.size;for(let o=0;oi&&c.type instanceof h4){let d=Math.max(i,c.from)-i,u=Math.min(l,c.to)-i;da.map(t,n,UA));return aS.from(r)}forChild(t,n){if(n.isLeaf)return th.empty;let r=[];for(let a=0;an instanceof th)?t:t.reduce((n,r)=>n.concat(r instanceof th?r:r.members),[]))}}forEachSet(t){for(let n=0;n{let v=_-y-(f-p);for(let j=0;jw+u-h)continue;let S=o[j]+u-h;f>=S?o[j+1]=p<=S?-2:-1:p>=u&&v&&(o[j]+=v,o[j+1]+=v)}h+=v}),u=n.maps[d].map(u,-1)}let c=!1;for(let d=0;d=r.content.size){c=!0;continue}let p=n.map(s[d+1]+i,-1),f=p-a,{index:y,offset:_}=r.content.findIndex(h),v=r.maybeChild(y);if(v&&_==h&&_+v.nodeSize==f){let j=o[d+2].mapInner(n,v,u+1,s[d]+i+1,l);j!=Vf?(o[d]=h,o[d+1]=f,o[d+2]=j):(o[d+1]=-2,c=!0)}else c=!0}if(c){let d=Jis(o,s,t,n,a,i,l),u=Efe(d,r,0,l);t=u.local;for(let h=0;hn&&l.to{let d=jft(s,o,c+n);if(d){i=!0;let u=Efe(d,o,n+c+1,r);u!=Vf&&a.push(c,c+o.nodeSize,u)}});let l=wft(i?Nft(s):s,-n).sort(qA);for(let o=0;o0;)t++;s.splice(t,0,n)}function Rje(s){let t=[];return s.someProp("decorations",n=>{let r=n(s.state);r&&r!=Vf&&t.push(r)}),s.cursorWrapper&&t.push(th.create(s.state.doc,[s.cursorWrapper.deco])),aS.from(t)}const eos={childList:!0,characterData:!0,characterDataOldValue:!0,attributes:!0,attributeOldValue:!0,subtree:!0},tos=Hg&&d4<=11;class sos{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 nos{constructor(t,n){this.view=t,this.handleDOMChange=n,this.queue=[],this.flushingSoon=-1,this.observer=null,this.currentSelection=new sos,this.onCharData=null,this.suppressingSelectionUpdates=!1,this.lastChangedTextNode=null,this.observer=window.MutationObserver&&new window.MutationObserver(r=>{for(let a=0;aa.type=="childList"&&a.removedNodes.length||a.type=="characterData"&&a.oldValue.length>a.target.nodeValue.length)?this.flushSoon():nx&&t.composing&&r.some(a=>a.type=="childList"&&a.target.nodeName=="TR")?(t.input.badSafariComposition=!0,this.flushSoon()):this.flush()}),tos&&(this.onCharData=r=>{this.queue.push({target:r.target,type:"characterData",oldValue:r.prevValue}),this.flushSoon()}),this.onSelectionChange=this.onSelectionChange.bind(this)}flushSoon(){this.flushingSoon<0&&(this.flushingSoon=window.setTimeout(()=>{this.flushingSoon=-1,this.flush()},20))}forceFlush(){this.flushingSoon>-1&&(window.clearTimeout(this.flushingSoon),this.flushingSoon=-1,this.flush())}start(){this.observer&&(this.observer.takeRecords(),this.observer.observe(this.view.dom,eos)),this.onCharData&&this.view.dom.addEventListener("DOMCharacterDataModified",this.onCharData),this.connectSelection()}stop(){if(this.observer){let t=this.observer.takeRecords();if(t.length){for(let n=0;nthis.flush(),20)}this.observer.disconnect()}this.onCharData&&this.view.dom.removeEventListener("DOMCharacterDataModified",this.onCharData),this.disconnectSelection()}connectSelection(){this.view.dom.ownerDocument.addEventListener("selectionchange",this.onSelectionChange)}disconnectSelection(){this.view.dom.ownerDocument.removeEventListener("selectionchange",this.onSelectionChange)}suppressSelectionUpdates(){this.suppressingSelectionUpdates=!0,setTimeout(()=>this.suppressingSelectionUpdates=!1,50)}onSelectionChange(){if(aqe(this.view)){if(this.suppressingSelectionUpdates)return Q2(this.view);if(Hg&&d4<=11&&!this.view.state.selection.empty){let t=this.view.domSelectionRange();if(t.focusNode&&yM(t.focusNode,t.focusOffset,t.anchorNode,t.anchorOffset))return this.flushSoon()}this.flush()}}setCurSelection(){this.currentSelection.set(this.view.domSelectionRange())}ignoreSelectionChange(t){if(!t.focusNode)return!0;let n=new Set,r;for(let i=t.focusNode;i;i=j8(i))n.add(i);for(let i=t.anchorNode;i;i=j8(i))if(n.has(i)){r=i;break}let a=r&&this.view.docView.nearestDesc(r);if(a&&a.ignoreMutation({type:"selection",target:r.nodeType==3?r.parentNode:r}))return this.setCurSelection(),!0}pendingRecords(){if(this.observer)for(let t of this.observer.takeRecords())this.queue.push(t);return this.queue}flush(){let{view:t}=this;if(!t.docView||this.flushingSoon>-1)return;let n=this.pendingRecords();n.length&&(this.queue=[]);let r=t.domSelectionRange(),a=!this.suppressingSelectionUpdates&&!this.currentSelection.eq(r)&&aqe(t)&&!this.ignoreSelectionChange(r),i=-1,l=-1,o=!1,c=[];if(t.editable)for(let u=0;uu.nodeName=="BR")&&(t.input.lastKeyCode==8||t.input.lastKeyCode==46)){for(let u of c)if(u.nodeName=="BR"&&u.parentNode){let h=u.nextSibling;for(;h&&h.nodeType==1;){if(h.contentEditable=="false"){u.parentNode.removeChild(u);break}h=h.firstChild}}}else if(Bv&&c.length){let u=c.filter(h=>h.nodeName=="BR");if(u.length==2){let[h,p]=u;h.parentNode&&h.parentNode.parentNode==p.parentNode?p.remove():h.remove()}else{let{focusNode:h}=this.currentSelection;for(let p of u){let f=p.parentNode;f&&f.nodeName=="LI"&&(!h||ios(t,h)!=f)&&p.remove()}}}let d=null;i<0&&a&&t.input.lastFocus>Date.now()-200&&Math.max(t.input.lastTouch,t.input.lastClick.time)-1||a)&&(i>-1&&(t.docView.markDirty(i,l),ros(t)),t.input.badSafariComposition&&(t.input.badSafariComposition=!1,oos(t,c)),this.handleDOMChange(i,l,o,c),t.docView&&t.docView.dirty?t.updateState(t.state):this.currentSelection.eq(r)||Q2(t),this.currentSelection.set(r))}registerMutation(t,n){if(n.indexOf(t.target)>-1)return null;let r=this.view.docView.nearestDesc(t.target);if(t.type=="attributes"&&(r==this.view.docView||t.attributeName=="contenteditable"||t.attributeName=="style"&&!t.oldValue&&!t.target.getAttribute("style"))||!r||r.ignoreMutation(t))return null;if(t.type=="childList"){for(let u=0;ua;v--){let j=r.childNodes[v-1],w=j.pmViewDesc;if(j.nodeName=="BR"&&!w){i=v;break}if(!w||w.size)break}let h=s.state.doc,p=s.someProp("domParser")||K9.fromSchema(s.state.schema),f=h.resolve(l),y=null,_=p.parse(r,{topNode:f.parent,topMatch:f.parent.contentMatchAt(f.index()),topOpen:!0,from:a,to:i,preserveWhitespace:f.parent.type.whitespace=="pre"?"full":!0,findPositions:d,ruleFromNode:cos,context:f});if(d&&d[0].pos!=null){let v=d[0].pos,j=d[1]&&d[1].pos;j==null&&(j=v),y={anchor:v+l,head:j+l}}return{doc:_,sel:y,from:l,to:o}}function cos(s){let t=s.pmViewDesc;if(t)return t.parseRule();if(s.nodeName=="BR"&&s.parentNode){if(nx&&/^(ul|ol)$/i.test(s.parentNode.nodeName)){let n=document.createElement("div");return n.appendChild(document.createElement("li")),{skip:n}}else if(s.parentNode.lastChild==s||nx&&/^(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 dos=/^(a|abbr|acronym|b|bd[io]|big|br|button|cite|code|data(list)?|del|dfn|em|i|img|ins|kbd|label|map|mark|meter|output|q|ruby|s|samp|small|span|strong|su[bp]|time|u|tt|var)$/i;function uos(s,t,n,r,a){let i=s.input.compositionPendingChanges||(s.composing?s.input.compositionID:0);if(s.input.compositionPendingChanges=0,t<0){let D=s.input.lastSelectionTime>Date.now()-50?s.input.lastSelectionOrigin:null,I=d6e(s,D);if(I&&!s.state.selection.eq(I)){if(cf&&D2&&s.input.lastKeyCode===13&&Date.now()-100z(s,LE(13,"Enter"))))return;let F=s.state.tr.setSelection(I);D=="pointer"?F.setMeta("pointer",!0):D=="key"&&F.scrollIntoView(),i&&F.setMeta("composition",i),s.dispatch(F)}return}let l=s.state.doc.resolve(t),o=l.sharedDepth(n);t=l.before(o+1),n=s.state.doc.resolve(n).after(o+1);let c=s.state.selection,d=los(s,t,n),u=s.state.doc,h=u.slice(d.from,d.to),p,f;s.input.lastKeyCode===8&&Date.now()-100Date.now()-225||D2)&&a.some(D=>D.nodeType==1&&!dos.test(D.nodeName))&&(!y||y.endA>=y.endB)&&s.someProp("handleKeyDown",D=>D(s,LE(13,"Enter")))){s.input.lastIOSEnter=0;return}if(!y)if(r&&c instanceof Ui&&!c.empty&&c.$head.sameParent(c.$anchor)&&!s.composing&&!(d.sel&&d.sel.anchor!=d.sel.head))y={start:c.from,endA:c.to,endB:c.to};else{if(d.sel){let D=gqe(s,s.state.doc,d.sel);if(D&&!D.eq(s.state.selection)){let I=s.state.tr.setSelection(D);i&&I.setMeta("composition",i),s.dispatch(I)}}return}s.state.selection.froms.state.selection.from&&y.start<=s.state.selection.from+2&&s.state.selection.from>=d.from?y.start=s.state.selection.from:y.endA=s.state.selection.to-2&&s.state.selection.to<=d.to&&(y.endB+=s.state.selection.to-y.endA,y.endA=s.state.selection.to)),Hg&&d4<=11&&y.endB==y.start+1&&y.endA==y.start&&y.start>d.from&&d.doc.textBetween(y.start-d.from-1,y.start-d.from+1)=="  "&&(y.start--,y.endA--,y.endB--);let _=d.doc.resolveNoCache(y.start-d.from),v=d.doc.resolveNoCache(y.endB-d.from),j=u.resolve(y.start),w=_.sameParent(v)&&_.parent.inlineContent&&j.end()>=y.endA;if((N8&&s.input.lastIOSEnter>Date.now()-225&&(!w||a.some(D=>D.nodeName=="DIV"||D.nodeName=="P"))||!w&&_.posD(s,LE(13,"Enter")))){s.input.lastIOSEnter=0;return}if(s.state.selection.anchor>y.start&&mos(u,y.start,y.endA,_,v)&&s.someProp("handleKeyDown",D=>D(s,LE(8,"Backspace")))){D2&&cf&&s.domObserver.suppressSelectionUpdates();return}cf&&y.endB==y.start&&(s.input.lastChromeDelete=Date.now()),D2&&!w&&_.start()!=v.start()&&v.parentOffset==0&&_.depth==v.depth&&d.sel&&d.sel.anchor==d.sel.head&&d.sel.head==y.endA&&(y.endB-=2,v=d.doc.resolveNoCache(y.endB-d.from),setTimeout(()=>{s.someProp("handleKeyDown",function(D){return D(s,LE(13,"Enter"))})},20));let S=y.start,A=y.endA,E=D=>{let I=D||s.state.tr.replace(S,A,d.doc.slice(y.start-d.from,y.endB-d.from));if(d.sel){let F=gqe(s,I.doc,d.sel);F&&!(cf&&s.composing&&F.empty&&(y.start!=y.endB||s.input.lastChromeDeleteQ2(s),20));let D=E(s.state.tr.delete(S,A)),I=u.resolve(y.start).marksAcross(u.resolve(y.endA));I&&D.ensureMarks(I),s.dispatch(D)}else if(y.endA==y.endB&&(O=hos(_.parent.content.cut(_.parentOffset,v.parentOffset),j.parent.content.cut(j.parentOffset,y.endA-j.start())))){let D=E(s.state.tr);O.type=="add"?D.addMark(S,A,O.mark):D.removeMark(S,A,O.mark),s.dispatch(D)}else if(_.parent.child(_.index()).isText&&_.index()==v.index()-(v.textOffset?0:1)){let D=_.parent.textBetween(_.parentOffset,v.parentOffset),I=()=>E(s.state.tr.insertText(D,S,A));s.someProp("handleTextInput",F=>F(s,S,A,D,I))||s.dispatch(I())}else s.dispatch(E());else s.dispatch(E())}function gqe(s,t,n){return Math.max(n.anchor,n.head)>t.content.size?null:u6e(s,t.resolve(n.anchor),t.resolve(n.head))}function hos(s,t){let n=s.firstChild.marks,r=t.firstChild.marks,a=n,i=r,l,o,c;for(let u=0;uu.mark(o.addToSet(u.marks));else if(a.length==0&&i.length==1)o=i[0],l="remove",c=u=>u.mark(o.removeFromSet(u.marks));else return null;let d=[];for(let u=0;un||Oje(l,!0,!1)0&&(t||s.indexAfter(r)==s.node(r).childCount);)r--,a++,t=!1;if(n){let i=s.node(r).maybeChild(s.indexAfter(r));for(;i&&!i.isLeaf;)i=i.firstChild,a++}return a}function pos(s,t,n,r,a){let i=s.findDiffStart(t,n);if(i==null)return null;let{a:l,b:o}=s.findDiffEnd(t,n+s.size,n+t.size);if(a=="end"){let c=Math.max(0,i-Math.min(l,o));r-=l+c-i}if(l=l?i-r:0;i-=c,i&&i=o?i-r:0;i-=c,i&&i=56320&&t<=57343&&n>=55296&&n<=56319}class kft{constructor(t,n){this._root=null,this.focused=!1,this.trackWrites=null,this.mounted=!1,this.markCursor=null,this.cursorWrapper=null,this.lastSelectedViewDesc=void 0,this.input=new Ais,this.prevDirectPlugins=[],this.pluginViews=[],this.requiresGeckoHackNode=!1,this.dragging=null,this._props=n,this.state=n.state,this.directPlugins=n.plugins||[],this.directPlugins.forEach(jqe),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=_qe(this),bqe(this),this.nodeViews=wqe(this),this.docView=JUe(this.state.doc,vqe(this),Rje(this),this.dom,this),this.domObserver=new nos(this,(r,a,i,l)=>uos(this,r,a,i,l)),this.domObserver.start(),Mis(this),this.updatePluginViews()}get composing(){return this.input.composing}get props(){if(this._props.state!=this.state){let t=this._props;this._props={};for(let n in t)this._props[n]=t[n];this._props.state=this.state}return this._props}update(t){t.handleDOMEvents!=this._props.handleDOMEvents&&gCe(this);let n=this._props;this._props=t,t.plugins&&(t.plugins.forEach(jqe),this.directPlugins=t.plugins),this.updateStateInner(t.state,n)}setProps(t){let n={};for(let r in this._props)n[r]=this._props[r];n.state=this.state;for(let r in t)n[r]=t[r];this.update(n)}updateState(t){this.updateStateInner(t,this._props)}updateStateInner(t,n){var r;let a=this.state,i=!1,l=!1;t.storedMarks&&this.composing&&(yft(this),l=!0),this.state=t;let o=a.plugins!=t.plugins||this._props.plugins!=n.plugins;if(o||this._props.plugins!=n.plugins||this._props.nodeViews!=n.nodeViews){let f=wqe(this);xos(f,this.nodeViews)&&(this.nodeViews=f,i=!0)}(o||n.handleDOMEvents!=this._props.handleDOMEvents)&&gCe(this),this.editable=_qe(this),bqe(this);let c=Rje(this),d=vqe(this),u=a.plugins!=t.plugins&&!a.doc.eq(t.doc)?"reset":t.scrollToSelection>a.scrollToSelection?"to selection":"preserve",h=i||!this.docView.matchesNode(t.doc,d,c);(h||!t.selection.eq(a.selection))&&(l=!0);let p=u=="preserve"&&l&&this.dom.style.overflowAnchor==null&&Has(this);if(l){this.domObserver.stop();let f=h&&(Hg||cf)&&!this.composing&&!a.selection.empty&&!t.selection.empty&&fos(a.selection,t.selection);if(h){let y=cf?this.trackWrites=this.domSelectionRange().focusNode:null;this.composing&&(this.input.compositionNode=His(this)),(i||!this.docView.update(t.doc,d,c,this))&&(this.docView.updateOuterDeco(d),this.docView.destroy(),this.docView=JUe(t.doc,d,c,this.dom,this)),y&&(!this.trackWrites||!this.dom.contains(this.trackWrites))&&(f=!0)}f||!(this.input.mouseDown&&this.domObserver.currentSelection.eq(this.domSelectionRange())&&fis(this))?Q2(this,f):(ift(this,t.selection),this.domObserver.setCurSelection()),this.domObserver.start()}this.updatePluginViews(a),!((r=this.dragging)===null||r===void 0)&&r.node&&!a.doc.eq(t.doc)&&this.updateDraggedNode(this.dragging,a),u=="reset"?this.dom.scrollTop=0:u=="to selection"?this.scrollToSelection():p&&Gas(p)}scrollToSelection(){let t=this.domSelectionRange().focusNode;if(!(!t||!this.dom.contains(t.nodeType==1?t:t.parentNode))){if(!this.someProp("handleScrollToSelection",n=>n(this)))if(this.state.selection instanceof Li){let n=this.docView.domAfterPos(this.state.selection.from);n.nodeType==1&&WUe(this,n.getBoundingClientRect(),t)}else WUe(this,this.coordsAtPos(this.state.selection.head,1),t)}}destroyPluginViews(){let t;for(;t=this.pluginViews.pop();)t.destroy&&t.destroy()}updatePluginViews(t){if(!t||t.plugins!=this.state.plugins||this.directPlugins!=this.prevDirectPlugins){this.prevDirectPlugins=this.directPlugins,this.destroyPluginViews();for(let n=0;n0&&in.ownerDocument.getSelection()),this._root=n}return t||document}updateRoot(){this._root=null}posAtCoords(t){return Xas(this,t)}coordsAtPos(t,n=1){return Xpt(this,t,n)}domAtPos(t,n=0){return this.docView.domFromPos(t,n)}nodeDOM(t){let n=this.docView.descAt(t);return n?n.nodeDOM:null}posAtDOM(t,n,r=-1){let a=this.docView.posFromDOM(t,n,r);if(a==null)throw new RangeError("DOM position not inside the editor");return a}endOfTextblock(t,n){return nis(this,n||this.state,t)}pasteHTML(t,n){return mB(this,"",t,!1,n||new ClipboardEvent("paste"))}pasteText(t,n){return mB(this,t,null,!0,n||new ClipboardEvent("paste"))}serializeForClipboard(t){return h6e(this,t)}destroy(){this.docView&&(Iis(this),this.destroyPluginViews(),this.mounted?(this.docView.update(this.state.doc,[],Rje(this),this),this.dom.textContent=""):this.dom.parentNode&&this.dom.parentNode.removeChild(this.dom),this.docView.destroy(),this.docView=null,Das())}get isDestroyed(){return this.docView==null}dispatchEvent(t){return Lis(this,t)}domSelectionRange(){let t=this.domSelection();return t?nx&&this.root.nodeType===11&&Bas(this.dom.ownerDocument)==this.dom&&aos(this,t)||t:{focusNode:null,focusOffset:0,anchorNode:null,anchorOffset:0}}domSelection(){return this.root.getSelection()}}kft.prototype.dispatch=function(s){let t=this._props.dispatchTransaction;t?t.call(this,s):this.updateState(this.state.apply(s))};function vqe(s){let t=Object.create(null);return t.class="ProseMirror",t.contenteditable=String(s.editable),s.someProp("attributes",n=>{if(typeof n=="function"&&(n=n(s.state)),n)for(let r in n)r=="class"?t.class+=" "+n[r]:r=="style"?t.style=(t.style?t.style+";":"")+n[r]:!t[r]&&r!="contenteditable"&&r!="nodeName"&&(t[r]=String(n[r]))}),t.translate||(t.translate="no"),[Kx.node(0,s.state.doc.content.size,t)]}function bqe(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:Kx.widget(s.state.selection.from,t,{raw:!0,marks:s.markCursor})}}else s.cursorWrapper=null}function _qe(s){return!s.someProp("editable",t=>t(s.state)===!1)}function fos(s,t){let n=Math.min(s.$anchor.sharedDepth(s.head),t.$anchor.sharedDepth(t.head));return s.$anchor.start(n)!=t.$anchor.start(n)}function wqe(s){let t=Object.create(null);function n(r){for(let a in r)Object.prototype.hasOwnProperty.call(t,a)||(t[a]=r[a])}return s.someProp("nodeViews",n),s.someProp("markViews",n),t}function xos(s,t){let n=0,r=0;for(let a in s){if(s[a]!=t[a])return!0;n++}for(let a in t)r++;return n!=r}function jqe(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 T4={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:"'"},Afe={48:")",49:"!",50:"@",51:"#",52:"$",53:"%",54:"^",55:"&",56:"*",57:"(",59:":",61:"+",173:"_",186:":",187:"+",188:"<",189:"_",190:">",191:"?",192:"~",219:"{",220:"|",221:"}",222:'"'},gos=typeof navigator<"u"&&/Mac/.test(navigator.platform),yos=typeof navigator<"u"&&/MSIE \d|Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent);for(var nf=0;nf<10;nf++)T4[48+nf]=T4[96+nf]=String(nf);for(var nf=1;nf<=24;nf++)T4[nf+111]="F"+nf;for(var nf=65;nf<=90;nf++)T4[nf]=String.fromCharCode(nf+32),Afe[nf]=String.fromCharCode(nf);for(var Fje in T4)Afe.hasOwnProperty(Fje)||(Afe[Fje]=T4[Fje]);function vos(s){var t=gos&&s.metaKey&&s.shiftKey&&!s.ctrlKey&&!s.altKey||yos&&s.shiftKey&&s.key&&s.key.length==1||s.key=="Unidentified",n=!t&&s.key||(s.shiftKey?Afe:T4)[s.keyCode]||s.key||"Unidentified";return n=="Esc"&&(n="Escape"),n=="Del"&&(n="Delete"),n=="Left"&&(n="ArrowLeft"),n=="Up"&&(n="ArrowUp"),n=="Right"&&(n="ArrowRight"),n=="Down"&&(n="ArrowDown"),n}const bos=typeof navigator<"u"&&/Mac|iP(hone|[oa]d)/.test(navigator.platform),_os=typeof navigator<"u"&&/Win/.test(navigator.platform);function wos(s){let t=s.split(/-(?!$)/),n=t[t.length-1];n=="Space"&&(n=" ");let r,a,i,l;for(let o=0;os.selection.empty?!1:(t&&t(s.tr.deleteSelection().scrollIntoView()),!0);function Sft(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("backward",s):n.parentOffset>0)?null:n}const Sos=(s,t,n)=>{let r=Sft(s,n);if(!r)return!1;let a=v6e(r);if(!a){let l=r.blockRange(),o=l&&VD(l);return o==null?!1:(t&&t(s.tr.lift(l,o).scrollIntoView()),!0)}let i=a.nodeBefore;if(Aft(s,a,t,-1))return!0;if(r.parent.content.size==0&&(k8(i,"end")||Li.isSelectable(i)))for(let l=r.depth;;l--){let o=Lye(s.doc,r.before(l),r.after(l),ba.empty);if(o&&o.slice.size1)break}return i.isAtom&&a.depth==r.depth-1?(t&&t(s.tr.delete(a.pos-i.nodeSize,a.pos).scrollIntoView()),!0):!1},Cos=(s,t,n)=>{let r=Sft(s,n);if(!r)return!1;let a=v6e(r);return a?Cft(s,a,t):!1},Tos=(s,t,n)=>{let r=Tft(s,n);if(!r)return!1;let a=b6e(r);return a?Cft(s,a,t):!1};function Cft(s,t,n){let r=t.nodeBefore,a=r,i=t.pos-1;for(;!a.isTextblock;i--){if(a.type.spec.isolating)return!1;let u=a.lastChild;if(!u)return!1;a=u}let l=t.nodeAfter,o=l,c=t.pos+1;for(;!o.isTextblock;c++){if(o.type.spec.isolating)return!1;let u=o.firstChild;if(!u)return!1;o=u}let d=Lye(s.doc,i,c,ba.empty);if(!d||d.from!=i||d instanceof Kh&&d.slice.size>=c-i)return!1;if(n){let u=s.tr.step(d);u.setSelection(Ui.create(u.doc,i)),n(u.scrollIntoView())}return!0}function k8(s,t,n=!1){for(let r=s;r;r=t=="start"?r.firstChild:r.lastChild){if(r.isTextblock)return!0;if(n&&r.childCount!=1)return!1}return!1}const Eos=(s,t,n)=>{let{$head:r,empty:a}=s.selection,i=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("backward",s):r.parentOffset>0)return!1;i=v6e(r)}let l=i&&i.nodeBefore;return!l||!Li.isSelectable(l)?!1:(t&&t(s.tr.setSelection(Li.create(s.doc,i.pos-l.nodeSize)).scrollIntoView()),!0)};function v6e(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 Tft(s,t){let{$cursor:n}=s.selection;return!n||(t?!t.endOfTextblock("forward",s):n.parentOffset{let r=Tft(s,n);if(!r)return!1;let a=b6e(r);if(!a)return!1;let i=a.nodeAfter;if(Aft(s,a,t,1))return!0;if(r.parent.content.size==0&&(k8(i,"start")||Li.isSelectable(i))){let l=Lye(s.doc,r.before(),r.after(),ba.empty);if(l&&l.slice.size{let{$head:r,empty:a}=s.selection,i=r;if(!a)return!1;if(r.parent.isTextblock){if(n?!n.endOfTextblock("forward",s):r.parentOffset=0;t--){let n=s.node(t);if(s.index(t)+1{let n=s.selection,r=n instanceof Li,a;if(r){if(n.node.isTextblock||!G4(s.doc,n.from))return!1;a=n.from}else if(a=Pye(s.doc,n.from,-1),a==null)return!1;if(t){let i=s.tr.join(a);r&&i.setSelection(Li.create(i.doc,a-s.doc.resolve(a).nodeBefore.nodeSize)),t(i.scrollIntoView())}return!0},Pos=(s,t)=>{let n=s.selection,r;if(n instanceof Li){if(n.node.isTextblock||!G4(s.doc,n.to))return!1;r=n.to}else if(r=Pye(s.doc,n.to,1),r==null)return!1;return t&&t(s.tr.join(r).scrollIntoView()),!0},Los=(s,t)=>{let{$from:n,$to:r}=s.selection,a=n.blockRange(r),i=a&&VD(a);return i==null?!1:(t&&t(s.tr.lift(a,i).scrollIntoView()),!0)},Dos=(s,t)=>{let{$head:n,$anchor:r}=s.selection;return!n.parent.type.spec.code||!n.sameParent(r)?!1:(t&&t(s.tr.insertText(` `).scrollIntoView()),!0)};function Eft(s){for(let t=0;t{let{$head:n,$anchor:r}=s.selection;if(!n.parent.type.spec.code||!n.sameParent(r))return!1;let a=n.node(-1),i=n.indexAfter(-1),l=Eft(a.contentMatchAt(i));if(!l||!a.canReplaceWith(i,i,l))return!1;if(t){let o=n.after(),c=s.tr.replaceWith(o,o,l.createAndFill());c.setSelection(to.near(c.doc.resolve(o),1)),t(c.scrollIntoView())}return!0},Oos=(s,t)=>{let n=s.selection,{$from:r,$to:a}=n;if(n instanceof zv||r.parent.inlineContent||a.parent.inlineContent)return!1;let i=Eft(a.parent.contentMatchAt(a.indexAfter()));if(!i||!i.isTextblock)return!1;if(t){let l=(!r.parentOffset&&a.index(){let{$cursor:n}=s.selection;if(!n||n.parent.content.size)return!1;if(n.depth>1&&n.after()!=n.end(-1)){let i=n.before();if(EL(s.doc,i))return t&&t(s.tr.split(i).scrollIntoView()),!0}let r=n.blockRange(),a=r&&VD(r);return a==null?!1:(t&&t(s.tr.lift(r,a).scrollIntoView()),!0)},zos=(s,t)=>{let{$from:n,to:r}=s.selection,a,i=n.sharedDepth(r);return i==0?!1:(a=n.before(i),t&&t(s.tr.setSelection(Li.create(s.doc,a))),!0)};function Bos(s,t,n){let r=t.nodeBefore,a=t.nodeAfter,i=t.index();return!r||!a||!r.type.compatibleContent(a.type)?!1:!r.content.size&&t.parent.canReplace(i-1,i)?(n&&n(s.tr.delete(t.pos-r.nodeSize,t.pos).scrollIntoView()),!0):!t.parent.canReplace(i,i+1)||!(a.isTextblock||G4(s.doc,t.pos))?!1:(n&&n(s.tr.join(t.pos).scrollIntoView()),!0)}function Aft(s,t,n,r){let a=t.nodeBefore,i=t.nodeAfter,l,o,c=a.type.spec.isolating||i.type.spec.isolating;if(!c&&Bos(s,t,n))return!0;let d=!c&&t.parent.canReplace(t.index(),t.index()+1);if(d&&(l=(o=a.contentMatchAt(a.childCount)).findWrapping(i.type))&&o.matchType(l[0]||i.type).validEnd){if(n){let f=t.pos+i.nodeSize,y=$r.empty;for(let j=l.length-1;j>=0;j--)y=$r.from(l[j].create(null,y));y=$r.from(a.copy(y));let _=s.tr.step(new Cp(t.pos-1,f,t.pos,f,new ba(y,1,0),l.length,!0)),v=_.doc.resolve(f+2*l.length);v.nodeAfter&&v.nodeAfter.type==a.type&&G4(_.doc,v.pos)&&_.join(v.pos),n(_.scrollIntoView())}return!0}let u=i.type.spec.isolating||r>0&&c?null:to.findFrom(t,1),h=u&&u.$from.blockRange(u.$to),p=h&&VD(h);if(p!=null&&p>=t.depth)return n&&n(s.tr.lift(h,p).scrollIntoView()),!0;if(d&&k8(i,"start",!0)&&k8(a,"end")){let f=a,y=[];for(;y.push(f),!f.isTextblock;)f=f.lastChild;let _=i,v=1;for(;!_.isTextblock;_=_.firstChild)v++;if(f.canReplace(f.childCount,f.childCount,_.content)){if(n){let j=$r.empty;for(let S=y.length-1;S>=0;S--)j=$r.from(y[S].copy(j));let w=s.tr.step(new Cp(t.pos-y.length,t.pos+i.nodeSize,t.pos+v,t.pos+i.nodeSize-v,new ba(j,y.length,0),0,!0));n(w.scrollIntoView())}return!0}}return!1}function Mft(s){return function(t,n){let r=t.selection,a=s<0?r.$from:r.$to,i=a.depth;for(;a.node(i).isInline;){if(!i)return!1;i--}return a.node(i).isTextblock?(n&&n(t.tr.setSelection(Ui.create(t.doc,s<0?a.start(i):a.end(i)))),!0):!1}}const $os=Mft(-1),Uos=Mft(1);function qos(s,t=null){return function(n,r){let{$from:a,$to:i}=n.selection,l=a.blockRange(i),o=l&&i6e(l,s,t);return o?(r&&r(n.tr.wrap(l,o).scrollIntoView()),!0):!1}}function Nqe(s,t=null){return function(n,r){let a=!1;for(let i=0;i{if(a)return!1;if(!(!c.isTextblock||c.hasMarkup(s,t)))if(c.type==s)a=!0;else{let u=n.doc.resolve(d),h=u.index();a=u.parent.canReplaceWith(h,h+1,s)}})}if(!a)return!1;if(r){let i=n.tr;for(let l=0;l=2&&t.$from.node(t.depth-1).type.compatibleContent(n)&&t.startIndex==0){if(t.$from.index(t.depth-1)==0)return!1;let c=l.resolve(t.start-2);i=new jfe(c,c,t.depth),t.endIndex=0;u--)i=$r.from(n[u].type.create(n[u].attrs,i));s.step(new Cp(t.start-(r?2:0),t.end,t.start,t.end,new ba(i,0,0),n.length,!0));let l=0;for(let u=0;ul.childCount>0&&l.firstChild.type==s);return i?n?r.node(i.depth-1).type==s?Kos(t,n,s,i):Yos(t,n,i):!0:!1}}function Kos(s,t,n,r){let a=s.tr,i=r.end,l=r.$to.end(r.depth);i_;y--)f-=a.child(y).nodeSize,r.delete(f-1,f+1);let i=r.doc.resolve(n.start),l=i.nodeAfter;if(r.mapping.map(n.end)!=n.start+i.nodeAfter.nodeSize)return!1;let o=n.startIndex==0,c=n.endIndex==a.childCount,d=i.node(-1),u=i.index(-1);if(!d.canReplace(u+(o?0:1),u+1,l.content.append(c?$r.empty:$r.from(a))))return!1;let h=i.pos,p=h+l.nodeSize;return r.step(new Cp(h-(o?1:0),p+(c?1:0),h+1,p-1,new ba((o?$r.empty:$r.from(a.copy($r.empty))).append(c?$r.empty:$r.from(a.copy($r.empty))),o?0:1,c?0:1),o?0:1)),t(r.scrollIntoView()),!0}function Zos(s){return function(t,n){let{$from:r,$to:a}=t.selection,i=r.blockRange(a,d=>d.childCount>0&&d.firstChild.type==s);if(!i)return!1;let l=i.startIndex;if(l==0)return!1;let o=i.parent,c=o.child(l-1);if(c.type!=s)return!1;if(n){let d=c.lastChild&&c.lastChild.type==o.type,u=$r.from(d?s.create():null),h=new ba($r.from(s.create(null,$r.from(o.type.create(null,u)))),d?3:1,0),p=i.start,f=i.end;n(t.tr.step(new Cp(p-(d?3:1),f,p,f,h,1,!0)).scrollIntoView())}return!0}}function zye(s){const{state:t,transaction:n}=s;let{selection:r}=n,{doc:a}=n,{storedMarks:i}=n;return{...t,apply:t.apply.bind(t),applyTransaction:t.applyTransaction.bind(t),plugins:t.plugins,schema:t.schema,reconfigure:t.reconfigure.bind(t),toJSON:t.toJSON.bind(t),get storedMarks(){return i},get selection(){return r},get doc(){return a},get tr(){return r=n.selection,a=n.doc,i=n.storedMarks,n}}}class Bye{constructor(t){this.editor=t.editor,this.rawCommands=this.editor.extensionManager.commands,this.customState=t.state}get hasCustomState(){return!!this.customState}get state(){return this.customState||this.editor.state}get commands(){const{rawCommands:t,editor:n,state:r}=this,{view:a}=n,{tr:i}=r,l=this.buildProps(i);return Object.fromEntries(Object.entries(t).map(([o,c])=>[o,(...u)=>{const h=c(...u)(l);return!i.getMeta("preventDispatch")&&!this.hasCustomState&&a.dispatch(i),h}]))}get chain(){return()=>this.createChain()}get can(){return()=>this.createCan()}createChain(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o=[],c=!!t,d=t||i.tr,u=()=>(!c&&n&&!d.getMeta("preventDispatch")&&!this.hasCustomState&&l.dispatch(d),o.every(p=>p===!0)),h={...Object.fromEntries(Object.entries(r).map(([p,f])=>[p,(..._)=>{const v=this.buildProps(d,n),j=f(..._)(v);return o.push(j),h}])),run:u};return h}createCan(t){const{rawCommands:n,state:r}=this,a=!1,i=t||r.tr,l=this.buildProps(i,a);return{...Object.fromEntries(Object.entries(n).map(([c,d])=>[c,(...u)=>d(...u)({...l,dispatch:void 0})])),chain:()=>this.createChain(i,a)}}buildProps(t,n=!0){const{rawCommands:r,editor:a,state:i}=this,{view:l}=a,o={tr:t,editor:a,view:l,state:zye({state:i,transaction:t}),dispatch:n?()=>{}:void 0,chain:()=>this.createChain(t,n),can:()=>this.createCan(t),get commands(){return Object.fromEntries(Object.entries(r).map(([c,d])=>[c,(...u)=>d(...u)(o)]))}};return o}}let Qos=class{constructor(){this.callbacks={}}on(t,n){return this.callbacks[t]||(this.callbacks[t]=[]),this.callbacks[t].push(n),this}emit(t,...n){const r=this.callbacks[t];return r&&r.forEach(a=>a.apply(this,n)),this}off(t,n){const r=this.callbacks[t];return r&&(n?this.callbacks[t]=r.filter(a=>a!==n):delete this.callbacks[t]),this}once(t,n){const r=(...a)=>{this.off(t,r),n.apply(this,a)};return this.on(t,r)}removeAllListeners(){this.callbacks={}}};function li(s,t,n){return s.config[t]===void 0&&s.parent?li(s.parent,t,n):typeof s.config[t]=="function"?s.config[t].bind({...n,parent:s.parent?li(s.parent,t,n):null}):s.config[t]}function $ye(s){const t=s.filter(a=>a.type==="extension"),n=s.filter(a=>a.type==="node"),r=s.filter(a=>a.type==="mark");return{baseExtensions:t,nodeExtensions:n,markExtensions:r}}function Ift(s){const t=[],{nodeExtensions:n,markExtensions:r}=$ye(s),a=[...n,...r],i={default:null,rendered:!0,renderHTML:null,parseHTML:null,keepOnSplit:!0,isRequired:!1};return s.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage,extensions:a},c=li(l,"addGlobalAttributes",o);if(!c)return;c().forEach(u=>{u.types.forEach(h=>{Object.entries(u.attributes).forEach(([p,f])=>{t.push({type:h,name:p,attribute:{...i,...f}})})})})}),a.forEach(l=>{const o={name:l.name,options:l.options,storage:l.storage},c=li(l,"addAttributes",o);if(!c)return;const d=c();Object.entries(d).forEach(([u,h])=>{const p={...i,...h};typeof(p==null?void 0:p.default)=="function"&&(p.default=p.default()),p!=null&&p.isRequired&&(p==null?void 0:p.default)===void 0&&delete p.default,t.push({type:l.name,name:u,attribute:p})})}),t}function Ep(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 du(...s){return s.filter(t=>!!t).reduce((t,n)=>{const r={...t};return Object.entries(n).forEach(([a,i])=>{if(!r[a]){r[a]=i;return}if(a==="class"){const o=i?String(i).split(" "):[],c=r[a]?r[a].split(" "):[],d=o.filter(u=>!c.includes(u));r[a]=[...c,...d].join(" ")}else if(a==="style"){const o=i?i.split(";").map(u=>u.trim()).filter(Boolean):[],c=r[a]?r[a].split(";").map(u=>u.trim()).filter(Boolean):[],d=new Map;c.forEach(u=>{const[h,p]=u.split(":").map(f=>f.trim());d.set(h,p)}),o.forEach(u=>{const[h,p]=u.split(":").map(f=>f.trim());d.set(h,p)}),r[a]=Array.from(d.entries()).map(([u,h])=>`${u}: ${h}`).join("; ")}else r[a]=i}),r},{})}function yCe(s,t){return t.filter(n=>n.type===s.type.name).filter(n=>n.attribute.rendered).map(n=>n.attribute.renderHTML?n.attribute.renderHTML(s.attrs)||{}:{[n.name]:s.attrs[n.name]}).reduce((n,r)=>du(n,r),{})}function Pft(s){return typeof s=="function"}function Wo(s,t=void 0,...n){return Pft(s)?t?s.bind(t)(...n):s(...n):s}function Xos(s={}){return Object.keys(s).length===0&&s.constructor===Object}function Jos(s){return typeof s!="string"?s:s.match(/^[+-]?(?:\d*\.)?\d+$/)?Number(s):s==="true"?!0:s==="false"?!1:s}function kqe(s,t){return"style"in s?s:{...s,getAttrs:n=>{const r=s.getAttrs?s.getAttrs(n):s.attrs;if(r===!1)return!1;const a=t.reduce((i,l)=>{const o=l.attribute.parseHTML?l.attribute.parseHTML(n):Jos(n.getAttribute(l.name));return o==null?i:{...i,[l.name]:o}},{});return{...r,...a}}}}function Sqe(s){return Object.fromEntries(Object.entries(s).filter(([t,n])=>t==="attrs"&&Xos(n)?!1:n!=null))}function els(s,t){var n;const r=Ift(s),{nodeExtensions:a,markExtensions:i}=$ye(s),l=(n=a.find(d=>li(d,"topNode")))===null||n===void 0?void 0:n.name,o=Object.fromEntries(a.map(d=>{const u=r.filter(j=>j.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},p=s.reduce((j,w)=>{const S=li(w,"extendNodeSchema",h);return{...j,...S?S(d):{}}},{}),f=Sqe({...p,content:Wo(li(d,"content",h)),marks:Wo(li(d,"marks",h)),group:Wo(li(d,"group",h)),inline:Wo(li(d,"inline",h)),atom:Wo(li(d,"atom",h)),selectable:Wo(li(d,"selectable",h)),draggable:Wo(li(d,"draggable",h)),code:Wo(li(d,"code",h)),whitespace:Wo(li(d,"whitespace",h)),linebreakReplacement:Wo(li(d,"linebreakReplacement",h)),defining:Wo(li(d,"defining",h)),isolating:Wo(li(d,"isolating",h)),attrs:Object.fromEntries(u.map(j=>{var w;return[j.name,{default:(w=j==null?void 0:j.attribute)===null||w===void 0?void 0:w.default}]}))}),y=Wo(li(d,"parseHTML",h));y&&(f.parseDOM=y.map(j=>kqe(j,u)));const _=li(d,"renderHTML",h);_&&(f.toDOM=j=>_({node:j,HTMLAttributes:yCe(j,u)}));const v=li(d,"renderText",h);return v&&(f.toText=v),[d.name,f]})),c=Object.fromEntries(i.map(d=>{const u=r.filter(v=>v.type===d.name),h={name:d.name,options:d.options,storage:d.storage,editor:t},p=s.reduce((v,j)=>{const w=li(j,"extendMarkSchema",h);return{...v,...w?w(d):{}}},{}),f=Sqe({...p,inclusive:Wo(li(d,"inclusive",h)),excludes:Wo(li(d,"excludes",h)),group:Wo(li(d,"group",h)),spanning:Wo(li(d,"spanning",h)),code:Wo(li(d,"code",h)),attrs:Object.fromEntries(u.map(v=>{var j;return[v.name,{default:(j=v==null?void 0:v.attribute)===null||j===void 0?void 0:j.default}]}))}),y=Wo(li(d,"parseHTML",h));y&&(f.parseDOM=y.map(v=>kqe(v,u)));const _=li(d,"renderHTML",h);return _&&(f.toDOM=v=>_({mark:v,HTMLAttributes:yCe(v,u)})),[d.name,f]}));return new Spt({topNode:l,nodes:o,marks:c})}function Bje(s,t){return t.nodes[s]||t.marks[s]||null}function Cqe(s,t){return Array.isArray(t)?t.some(n=>(typeof n=="string"?n:n.name)===s.name):t}function _6e(s,t){const n=UM.fromSchema(t).serializeFragment(s),a=document.implementation.createHTMLDocument().createElement("div");return a.appendChild(n),a.innerHTML}const tls=(s,t=500)=>{let n="";const r=s.parentOffset;return s.parent.nodesBetween(Math.max(0,r-t),r,(a,i,l,o)=>{var c,d;const u=((d=(c=a.type.spec).toText)===null||d===void 0?void 0:d.call(c,{node:a,pos:i,parent:l,index:o}))||a.textContent||"%leaf%";n+=a.isAtom&&!a.isText?u:u.slice(0,Math.max(0,r-i))}),n};function w6e(s){return Object.prototype.toString.call(s)==="[object RegExp]"}class Uye{constructor(t){this.find=t.find,this.handler=t.handler}}const sls=(s,t)=>{if(w6e(t))return t.exec(s);const n=t(s);if(!n)return null;const r=[n.text];return r.index=n.index,r.input=s,r.data=n.data,n.replaceWith&&(n.text.includes(n.replaceWith)||console.warn('[tiptap warn]: "inputRuleMatch.replaceWith" must be part of "inputRuleMatch.text".'),r.push(n.replaceWith)),r};function lH(s){var t;const{editor:n,from:r,to:a,text:i,rules:l,plugin:o}=s,{view:c}=n;if(c.composing)return!1;const d=c.state.doc.resolve(r);if(d.parent.type.spec.code||!((t=d.nodeBefore||d.nodeAfter)===null||t===void 0)&&t.marks.find(p=>p.type.spec.code))return!1;let u=!1;const h=tls(d)+i;return l.forEach(p=>{if(u)return;const f=sls(h,p.find);if(!f)return;const y=c.state.tr,_=zye({state:c.state,transaction:y}),v={from:r-(f[0].length-i.length),to:a},{commands:j,chain:w,can:S}=new Bye({editor:n,state:_});p.handler({state:_,range:v,match:f,commands:j,chain:w,can:S})===null||!y.steps.length||(y.setMeta(o,{transform:y,from:r,to:a,text:i}),c.dispatch(y),u=!0)}),u}function nls(s){const{editor:t,rules:n}=s,r=new Gm({state:{init(){return null},apply(a,i,l){const o=a.getMeta(r);if(o)return o;const c=a.getMeta("applyInputRules");return!!c&&setTimeout(()=>{let{text:u}=c;typeof u=="string"?u=u:u=_6e($r.from(u),l.schema);const{from:h}=c,p=h+u.length;lH({editor:t,from:h,to:p,text:u,rules:n,plugin:r})}),a.selectionSet||a.docChanged?null:i}},props:{handleTextInput(a,i,l,o){return lH({editor:t,from:i,to:l,text:o,rules:n,plugin:r})},handleDOMEvents:{compositionend:a=>(setTimeout(()=>{const{$cursor:i}=a.state.selection;i&&lH({editor:t,from:i.pos,to:i.pos,text:"",rules:n,plugin:r})}),!1)},handleKeyDown(a,i){if(i.key!=="Enter")return!1;const{$cursor:l}=a.state.selection;return l?lH({editor:t,from:l.pos,to:l.pos,text:` `,rules:n,plugin:r}):!1}},isInputRules:!0});return r}function rls(s){return Object.prototype.toString.call(s).slice(8,-1)}function cH(s){return rls(s)!=="Object"?!1:s.constructor===Object&&Object.getPrototypeOf(s)===Object.prototype}function qye(s,t){const n={...s};return cH(s)&&cH(t)&&Object.keys(t).forEach(r=>{cH(t[r])&&cH(s[r])?n[r]=qye(s[r],t[r]):n[r]=t[r]}),n}class kb{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=Wo(li(this,"addOptions",{name:this.name}))),this.storage=Wo(li(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new kb(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>qye(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new kb(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=Wo(li(n,"addOptions",{name:n.name})),n.storage=Wo(li(n,"addStorage",{name:n.name,options:n.options})),n}static handleExit({editor:t,mark:n}){const{tr:r}=t.state,a=t.state.selection.$from;if(a.pos===a.end()){const l=a.marks();if(!!!l.find(d=>(d==null?void 0:d.type.name)===n.name))return!1;const c=l.find(d=>(d==null?void 0:d.type.name)===n.name);return c&&r.removeStoredMark(c),r.insertText(" ",a.pos),t.view.dispatch(r),!0}return!1}}function als(s){return typeof s=="number"}class ils{constructor(t){this.find=t.find,this.handler=t.handler}}const ols=(s,t,n)=>{if(w6e(t))return[...s.matchAll(t)];const r=t(s,n);return r?r.map(a=>{const i=[a.text];return i.index=a.index,i.input=s,i.data=a.data,a.replaceWith&&(a.text.includes(a.replaceWith)||console.warn('[tiptap warn]: "pasteRuleMatch.replaceWith" must be part of "pasteRuleMatch.text".'),i.push(a.replaceWith)),i}):[]};function lls(s){const{editor:t,state:n,from:r,to:a,rule:i,pasteEvent:l,dropEvent:o}=s,{commands:c,chain:d,can:u}=new Bye({editor:t,state:n}),h=[];return n.doc.nodesBetween(r,a,(f,y)=>{if(!f.isTextblock||f.type.spec.code)return;const _=Math.max(r,y),v=Math.min(a,y+f.content.size),j=f.textBetween(_-y,v-y,void 0,"");ols(j,i.find,l).forEach(S=>{if(S.index===void 0)return;const A=_+S.index+1,E=A+S[0].length,O={from:n.tr.mapping.map(A),to:n.tr.mapping.map(E)},D=i.handler({state:n,range:O,match:S,commands:c,chain:d,can:u,pasteEvent:l,dropEvent:o});h.push(D)})}),h.every(f=>f!==null)}let dH=null;const cls=s=>{var t;const n=new ClipboardEvent("paste",{clipboardData:new DataTransfer});return(t=n.clipboardData)===null||t===void 0||t.setData("text/html",s),n};function dls(s){const{editor:t,rules:n}=s;let r=null,a=!1,i=!1,l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,o;try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}const c=({state:u,from:h,to:p,rule:f,pasteEvt:y})=>{const _=u.tr,v=zye({state:u,transaction:_});if(!(!lls({editor:t,state:v,from:Math.max(h-1,0),to:p.b-1,rule:f,pasteEvent:y,dropEvent:o})||!_.steps.length)){try{o=typeof DragEvent<"u"?new DragEvent("drop"):null}catch{o=null}return l=typeof ClipboardEvent<"u"?new ClipboardEvent("paste"):null,_}};return n.map(u=>new Gm({view(h){const p=y=>{var _;r=!((_=h.dom.parentElement)===null||_===void 0)&&_.contains(y.target)?h.dom.parentElement:null,r&&(dH=t)},f=()=>{dH&&(dH=null)};return window.addEventListener("dragstart",p),window.addEventListener("dragend",f),{destroy(){window.removeEventListener("dragstart",p),window.removeEventListener("dragend",f)}}},props:{handleDOMEvents:{drop:(h,p)=>{if(i=r===h.dom.parentElement,o=p,!i){const f=dH;f!=null&&f.isEditable&&setTimeout(()=>{const y=f.state.selection;y&&f.commands.deleteRange({from:y.from,to:y.to})},10)}return!1},paste:(h,p)=>{var f;const y=(f=p.clipboardData)===null||f===void 0?void 0:f.getData("text/html");return l=p,a=!!(y!=null&&y.includes("data-pm-slice")),!1}}},appendTransaction:(h,p,f)=>{const y=h[0],_=y.getMeta("uiEvent")==="paste"&&!a,v=y.getMeta("uiEvent")==="drop"&&!i,j=y.getMeta("applyPasteRules"),w=!!j;if(!_&&!v&&!w)return;if(w){let{text:E}=j;typeof E=="string"?E=E:E=_6e($r.from(E),f.schema);const{from:O}=j,D=O+E.length,I=cls(E);return c({rule:u,state:f,from:O,to:{b:D},pasteEvt:I})}const S=p.doc.content.findDiffStart(f.doc.content),A=p.doc.content.findDiffEnd(f.doc.content);if(!(!als(S)||!A||S===A.b))return c({rule:u,state:f,from:S,to:A,pasteEvt:l})}}))}function uls(s){const t=s.filter((n,r)=>s.indexOf(n)!==r);return Array.from(new Set(t))}class SP{constructor(t,n){this.splittableMarks=[],this.editor=n,this.extensions=SP.resolve(t),this.schema=els(this.extensions,n),this.setupExtensions()}static resolve(t){const n=SP.sort(SP.flatten(t)),r=uls(n.map(a=>a.name));return r.length&&console.warn(`[tiptap warn]: Duplicate extension names found: [${r.map(a=>`'${a}'`).join(", ")}]. This can lead to issues.`),n}static flatten(t){return t.map(n=>{const r={name:n.name,options:n.options,storage:n.storage},a=li(n,"addExtensions",r);return a?[n,...this.flatten(a())]:n}).flat(10)}static sort(t){return t.sort((r,a)=>{const i=li(r,"priority")||100,l=li(a,"priority")||100;return i>l?-1:i{const r={name:n.name,options:n.options,storage:n.storage,editor:this.editor,type:Bje(n.name,this.schema)},a=li(n,"addCommands",r);return a?{...t,...a()}:t},{})}get plugins(){const{editor:t}=this,n=SP.sort([...this.extensions].reverse()),r=[],a=[],i=n.map(l=>{const o={name:l.name,options:l.options,storage:l.storage,editor:t,type:Bje(l.name,this.schema)},c=[],d=li(l,"addKeyboardShortcuts",o);let u={};if(l.type==="mark"&&li(l,"exitable",o)&&(u.ArrowRight=()=>kb.handleExit({editor:t,mark:l})),d){const _=Object.fromEntries(Object.entries(d()).map(([v,j])=>[v,()=>j({editor:t})]));u={...u,..._}}const h=Nos(u);c.push(h);const p=li(l,"addInputRules",o);Cqe(l,t.options.enableInputRules)&&p&&r.push(...p());const f=li(l,"addPasteRules",o);Cqe(l,t.options.enablePasteRules)&&f&&a.push(...f());const y=li(l,"addProseMirrorPlugins",o);if(y){const _=y();c.push(..._)}return c}).flat();return[nls({editor:t,rules:r}),...dls({editor:t,rules:a}),...i]}get attributes(){return Ift(this.extensions)}get nodeViews(){const{editor:t}=this,{nodeExtensions:n}=$ye(this.extensions);return Object.fromEntries(n.filter(r=>!!li(r,"addNodeView")).map(r=>{const a=this.attributes.filter(c=>c.type===r.name),i={name:r.name,options:r.options,storage:r.storage,editor:t,type:Ep(r.name,this.schema)},l=li(r,"addNodeView",i);if(!l)return[];const o=(c,d,u,h,p)=>{const f=yCe(c,a);return l()({node:c,view:d,getPos:u,decorations:h,innerDecorations:p,editor:t,extension:r,HTMLAttributes:f})};return[r.name,o]}))}setupExtensions(){this.extensions.forEach(t=>{var n;this.editor.extensionStorage[t.name]=t.storage;const r={name:t.name,options:t.options,storage:t.storage,editor:this.editor,type:Bje(t.name,this.schema)};t.type==="mark"&&(!((n=Wo(li(t,"keepOnSplit",r)))!==null&&n!==void 0)||n)&&this.splittableMarks.push(t.name);const a=li(t,"onBeforeCreate",r),i=li(t,"onCreate",r),l=li(t,"onUpdate",r),o=li(t,"onSelectionUpdate",r),c=li(t,"onTransaction",r),d=li(t,"onFocus",r),u=li(t,"onBlur",r),h=li(t,"onDestroy",r);a&&this.editor.on("beforeCreate",a),i&&this.editor.on("create",i),l&&this.editor.on("update",l),o&&this.editor.on("selectionUpdate",o),c&&this.editor.on("transaction",c),d&&this.editor.on("focus",d),u&&this.editor.on("blur",u),h&&this.editor.on("destroy",h)})}}class Nf{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=Wo(li(this,"addOptions",{name:this.name}))),this.storage=Wo(li(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new Nf(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>qye(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new Nf({...this.config,...t});return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=Wo(li(n,"addOptions",{name:n.name})),n.storage=Wo(li(n,"addStorage",{name:n.name,options:n.options})),n}}function Lft(s,t,n){const{from:r,to:a}=t,{blockSeparator:i=` `,textSerializers:l={}}=n||{};let o="";return s.nodesBetween(r,a,(c,d,u,h)=>{var p;c.isBlock&&d>r&&(o+=i);const f=l==null?void 0:l[c.type.name];if(f)return u&&(o+=f({node:c,pos:d,parent:u,index:h,range:t})),!1;c.isText&&(o+=(p=c==null?void 0:c.text)===null||p===void 0?void 0:p.slice(Math.max(r,d)-d,a-d))}),o}function Dft(s){return Object.fromEntries(Object.entries(s.nodes).filter(([,t])=>t.spec.toText).map(([t,n])=>[t,n.spec.toText]))}const hls=Nf.create({name:"clipboardTextSerializer",addOptions(){return{blockSeparator:void 0}},addProseMirrorPlugins(){return[new Gm({key:new ox("clipboardTextSerializer"),props:{clipboardTextSerializer:()=>{const{editor:s}=this,{state:t,schema:n}=s,{doc:r,selection:a}=t,{ranges:i}=a,l=Math.min(...i.map(u=>u.$from.pos)),o=Math.max(...i.map(u=>u.$to.pos)),c=Dft(n);return Lft(r,{from:l,to:o},{...this.options.blockSeparator!==void 0?{blockSeparator:this.options.blockSeparator}:{},textSerializers:c})}}})]}}),mls=()=>({editor:s,view:t})=>(requestAnimationFrame(()=>{var n;s.isDestroyed||(t.dom.blur(),(n=window==null?void 0:window.getSelection())===null||n===void 0||n.removeAllRanges())}),!0),pls=(s=!1)=>({commands:t})=>t.setContent("",s),fls=()=>({state:s,tr:t,dispatch:n})=>{const{selection:r}=t,{ranges:a}=r;return n&&a.forEach(({$from:i,$to:l})=>{s.doc.nodesBetween(i.pos,l.pos,(o,c)=>{if(o.type.isText)return;const{doc:d,mapping:u}=t,h=d.resolve(u.map(c)),p=d.resolve(u.map(c+o.nodeSize)),f=h.blockRange(p);if(!f)return;const y=VD(f);if(o.type.isTextblock){const{defaultType:_}=h.parent.contentMatchAt(h.index());t.setNodeMarkup(f.start,_)}(y||y===0)&&t.lift(f,y)})}),!0},xls=s=>t=>s(t),gls=()=>({state:s,dispatch:t})=>Oos(s,t),yls=(s,t)=>({editor:n,tr:r})=>{const{state:a}=n,i=a.doc.slice(s.from,s.to);r.deleteRange(s.from,s.to);const l=r.mapping.map(t);return r.insert(l,i.content),r.setSelection(new Ui(r.doc.resolve(Math.max(l-1,0)))),!0},vls=()=>({tr:s,dispatch:t})=>{const{selection:n}=s,r=n.$anchor.node();if(r.content.size>0)return!1;const a=s.selection.$anchor;for(let i=a.depth;i>0;i-=1)if(a.node(i).type===r.type){if(t){const o=a.before(i),c=a.after(i);s.delete(o,c).scrollIntoView()}return!0}return!1},bls=s=>({tr:t,state:n,dispatch:r})=>{const a=Ep(s,n.schema),i=t.selection.$anchor;for(let l=i.depth;l>0;l-=1)if(i.node(l).type===a){if(r){const c=i.before(l),d=i.after(l);t.delete(c,d).scrollIntoView()}return!0}return!1},_ls=s=>({tr:t,dispatch:n})=>{const{from:r,to:a}=s;return n&&t.delete(r,a),!0},wls=()=>({state:s,dispatch:t})=>kos(s,t),jls=()=>({commands:s})=>s.keyboardShortcut("Enter"),Nls=()=>({state:s,dispatch:t})=>Ros(s,t);function Mfe(s,t,n={strict:!0}){const r=Object.keys(t);return r.length?r.every(a=>n.strict?t[a]===s[a]:w6e(t[a])?t[a].test(s[a]):t[a]===s[a]):!0}function Rft(s,t,n={}){return s.find(r=>r.type===t&&Mfe(Object.fromEntries(Object.keys(n).map(a=>[a,r.attrs[a]])),n))}function Tqe(s,t,n={}){return!!Rft(s,t,n)}function j6e(s,t,n){var r;if(!s||!t)return;let a=s.parent.childAfter(s.parentOffset);if((!a.node||!a.node.marks.some(u=>u.type===t))&&(a=s.parent.childBefore(s.parentOffset)),!a.node||!a.node.marks.some(u=>u.type===t)||(n=n||((r=a.node.marks[0])===null||r===void 0?void 0:r.attrs),!Rft([...a.node.marks],t,n)))return;let l=a.index,o=s.start()+a.offset,c=l+1,d=o+a.node.nodeSize;for(;l>0&&Tqe([...s.parent.child(l-1).marks],t,n);)l-=1,o-=s.parent.child(l).nodeSize;for(;c({tr:n,state:r,dispatch:a})=>{const i=K4(s,r.schema),{doc:l,selection:o}=n,{$from:c,from:d,to:u}=o;if(a){const h=j6e(c,i,t);if(h&&h.from<=d&&h.to>=u){const p=Ui.create(l,h.from,h.to);n.setSelection(p)}}return!0},Sls=s=>t=>{const n=typeof s=="function"?s(t):s;for(let r=0;r({editor:n,view:r,tr:a,dispatch:i})=>{t={scrollIntoView:!0,...t};const l=()=>{(Ife()||Eqe())&&r.dom.focus(),requestAnimationFrame(()=>{n.isDestroyed||(r.focus(),Cls()&&!Ife()&&!Eqe()&&r.dom.focus({preventScroll:!0}))})};if(r.hasFocus()&&s===null||s===!1)return!0;if(i&&s===null&&!Oft(n.state.selection))return l(),!0;const o=Fft(a.doc,s)||n.state.selection,c=n.state.selection.eq(o);return i&&(c||a.setSelection(o),c&&a.storedMarks&&a.setStoredMarks(a.storedMarks),l()),!0},Els=(s,t)=>n=>s.every((r,a)=>t(r,{...n,index:a})),Als=(s,t)=>({tr:n,commands:r})=>r.insertContentAt({from:n.selection.from,to:n.selection.to},s,t),zft=s=>{const t=s.childNodes;for(let n=t.length-1;n>=0;n-=1){const r=t[n];r.nodeType===3&&r.nodeValue&&/^(\n\s\s|\n)$/.test(r.nodeValue)?s.removeChild(r):r.nodeType===1&&zft(r)}return s};function uH(s){const t=`${s}`,n=new window.DOMParser().parseFromString(t,"text/html").body;return zft(n)}function fB(s,t,n){if(s instanceof c4||s instanceof $r)return s;n={slice:!0,parseOptions:{},...n};const r=typeof s=="object"&&s!==null,a=typeof s=="string";if(r)try{if(Array.isArray(s)&&s.length>0)return $r.fromArray(s.map(o=>t.nodeFromJSON(o)));const l=t.nodeFromJSON(s);return n.errorOnInvalidContent&&l.check(),l}catch(i){if(n.errorOnInvalidContent)throw new Error("[tiptap error]: Invalid JSON content",{cause:i});return console.warn("[tiptap warn]: Invalid content.","Passed value:",s,"Error:",i),fB("",t,n)}if(a){if(n.errorOnInvalidContent){let l=!1,o="";const c=new Spt({topNode:t.spec.topNode,marks:t.spec.marks,nodes:t.spec.nodes.append({__tiptap__private__unknown__catch__all__node:{content:"inline*",group:"block",parseDOM:[{tag:"*",getAttrs:d=>(l=!0,o=typeof d=="string"?d:d.outerHTML,null)}]}})});if(n.slice?K9.fromSchema(c).parseSlice(uH(s),n.parseOptions):K9.fromSchema(c).parse(uH(s),n.parseOptions),n.errorOnInvalidContent&&l)throw new Error("[tiptap error]: Invalid HTML content",{cause:new Error(`Invalid element found: ${o}`)})}const i=K9.fromSchema(t);return n.slice?i.parseSlice(uH(s),n.parseOptions).content:i.parse(uH(s),n.parseOptions)}return fB("",t,n)}function Mls(s,t,n){const r=s.steps.length-1;if(r{l===0&&(l=u)}),s.setSelection(to.near(s.doc.resolve(l),n))}const Ils=s=>!("type"in s),Pls=(s,t,n)=>({tr:r,dispatch:a,editor:i})=>{var l;if(a){n={parseOptions:i.options.parseOptions,updateSelection:!0,applyInputRules:!1,applyPasteRules:!1,...n};let o;const c=v=>{i.emit("contentError",{editor:i,error:v,disableCollaboration:()=>{i.storage.collaboration&&(i.storage.collaboration.isDisabled=!0)}})},d={preserveWhitespace:"full",...n.parseOptions};if(!n.errorOnInvalidContent&&!i.options.enableContentCheck&&i.options.emitContentError)try{fB(t,i.schema,{parseOptions:d,errorOnInvalidContent:!0})}catch(v){c(v)}try{o=fB(t,i.schema,{parseOptions:d,errorOnInvalidContent:(l=n.errorOnInvalidContent)!==null&&l!==void 0?l:i.options.enableContentCheck})}catch(v){return c(v),!1}let{from:u,to:h}=typeof s=="number"?{from:s,to:s}:{from:s.from,to:s.to},p=!0,f=!0;if((Ils(o)?o:[o]).forEach(v=>{v.check(),p=p?v.isText&&v.marks.length===0:!1,f=f?v.isBlock:!1}),u===h&&f){const{parent:v}=r.doc.resolve(u);v.isTextblock&&!v.type.spec.code&&!v.childCount&&(u-=1,h+=1)}let _;if(p){if(Array.isArray(t))_=t.map(v=>v.text||"").join("");else if(t instanceof $r){let v="";t.forEach(j=>{j.text&&(v+=j.text)}),_=v}else typeof t=="object"&&t&&t.text?_=t.text:_=t;r.insertText(_,u,h)}else _=o,r.replaceWith(u,h,_);n.updateSelection&&Mls(r,r.steps.length-1,-1),n.applyInputRules&&r.setMeta("applyInputRules",{from:u,text:_}),n.applyPasteRules&&r.setMeta("applyPasteRules",{from:u,text:_})}return!0},Lls=()=>({state:s,dispatch:t})=>Ios(s,t),Dls=()=>({state:s,dispatch:t})=>Pos(s,t),Rls=()=>({state:s,dispatch:t})=>Sos(s,t),Ols=()=>({state:s,dispatch:t})=>Aos(s,t),Fls=()=>({state:s,dispatch:t,tr:n})=>{try{const r=Pye(s.doc,s.selection.$from.pos,-1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},zls=()=>({state:s,dispatch:t,tr:n})=>{try{const r=Pye(s.doc,s.selection.$from.pos,1);return r==null?!1:(n.join(r,2),t&&t(n),!0)}catch{return!1}},Bls=()=>({state:s,dispatch:t})=>Cos(s,t),$ls=()=>({state:s,dispatch:t})=>Tos(s,t);function Bft(){return typeof navigator<"u"?/Mac/.test(navigator.platform):!1}function Uls(s){const t=s.split(/-(?!$)/);let n=t[t.length-1];n==="Space"&&(n=" ");let r,a,i,l;for(let o=0;o({editor:t,view:n,tr:r,dispatch:a})=>{const i=Uls(s).split(/-(?!$)/),l=i.find(d=>!["Alt","Ctrl","Meta","Shift"].includes(d)),o=new KeyboardEvent("keydown",{key:l==="Space"?" ":l,altKey:i.includes("Alt"),ctrlKey:i.includes("Ctrl"),metaKey:i.includes("Meta"),shiftKey:i.includes("Shift"),bubbles:!0,cancelable:!0}),c=t.captureTransaction(()=>{n.someProp("handleKeyDown",d=>d(n,o))});return c==null||c.steps.forEach(d=>{const u=d.map(r.mapping);u&&a&&r.maybeStep(u)}),!0};function xB(s,t,n={}){const{from:r,to:a,empty:i}=s.selection,l=t?Ep(t,s.schema):null,o=[];s.doc.nodesBetween(r,a,(h,p)=>{if(h.isText)return;const f=Math.max(r,p),y=Math.min(a,p+h.nodeSize);o.push({node:h,from:f,to:y})});const c=a-r,d=o.filter(h=>l?l.name===h.node.type.name:!0).filter(h=>Mfe(h.node.attrs,n,{strict:!1}));return i?!!d.length:d.reduce((h,p)=>h+p.to-p.from,0)>=c}const Vls=(s,t={})=>({state:n,dispatch:r})=>{const a=Ep(s,n.schema);return xB(n,a,t)?Los(n,r):!1},Hls=()=>({state:s,dispatch:t})=>Fos(s,t),Gls=s=>({state:t,dispatch:n})=>{const r=Ep(s,t.schema);return Wos(r)(t,n)},Wls=()=>({state:s,dispatch:t})=>Dos(s,t);function Vye(s,t){return t.nodes[s]?"node":t.marks[s]?"mark":null}function Aqe(s,t){const n=typeof t=="string"?[t]:t;return Object.keys(s).reduce((r,a)=>(n.includes(a)||(r[a]=s[a]),r),{})}const Kls=(s,t)=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=Vye(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Ep(s,r.schema)),o==="mark"&&(l=K4(s,r.schema)),a&&n.selection.ranges.forEach(c=>{r.doc.nodesBetween(c.$from.pos,c.$to.pos,(d,u)=>{i&&i===d.type&&n.setNodeMarkup(u,void 0,Aqe(d.attrs,t)),l&&d.marks.length&&d.marks.forEach(h=>{l===h.type&&n.addMark(u,u+d.nodeSize,l.create(Aqe(h.attrs,t)))})})}),!0):!1},Yls=()=>({tr:s,dispatch:t})=>(t&&s.scrollIntoView(),!0),Zls=()=>({tr:s,dispatch:t})=>{if(t){const n=new zv(s.doc);s.setSelection(n)}return!0},Qls=()=>({state:s,dispatch:t})=>Eos(s,t),Xls=()=>({state:s,dispatch:t})=>Mos(s,t),Jls=()=>({state:s,dispatch:t})=>zos(s,t),ecs=()=>({state:s,dispatch:t})=>Uos(s,t),tcs=()=>({state:s,dispatch:t})=>$os(s,t);function vCe(s,t,n={},r={}){return fB(s,t,{slice:!1,parseOptions:n,errorOnInvalidContent:r.errorOnInvalidContent})}const scs=(s,t=!1,n={},r={})=>({editor:a,tr:i,dispatch:l,commands:o})=>{var c,d;const{doc:u}=i;if(n.preserveWhitespace!=="full"){const h=vCe(s,a.schema,n,{errorOnInvalidContent:(c=r.errorOnInvalidContent)!==null&&c!==void 0?c:a.options.enableContentCheck});return l&&i.replaceWith(0,u.content.size,h).setMeta("preventUpdate",!t),!0}return l&&i.setMeta("preventUpdate",!t),o.insertContentAt({from:0,to:u.content.size},s,{parseOptions:n,errorOnInvalidContent:(d=r.errorOnInvalidContent)!==null&&d!==void 0?d:a.options.enableContentCheck})};function $ft(s,t){const n=K4(t,s.schema),{from:r,to:a,empty:i}=s.selection,l=[];i?(s.storedMarks&&l.push(...s.storedMarks),l.push(...s.selection.$head.marks())):s.doc.nodesBetween(r,a,c=>{l.push(...c.marks)});const o=l.find(c=>c.type.name===n.name);return o?{...o.attrs}:{}}function ncs(s,t){const n=new o6e(s);return t.forEach(r=>{r.steps.forEach(a=>{n.step(a)})}),n}function rcs(s){for(let t=0;t{n(a)&&r.push({node:a,pos:i})}),r}function Uft(s,t){for(let n=s.depth;n>0;n-=1){const r=s.node(n);if(t(r))return{pos:n>0?s.before(n):0,start:s.start(n),depth:n,node:r}}}function N6e(s){return t=>Uft(t.$from,s)}function ics(s,t){const n={from:0,to:s.content.size};return Lft(s,n,t)}function ocs(s,t){const n=Ep(t,s.schema),{from:r,to:a}=s.selection,i=[];s.doc.nodesBetween(r,a,o=>{i.push(o)});const l=i.reverse().find(o=>o.type.name===n.name);return l?{...l.attrs}:{}}function qft(s,t){const n=Vye(typeof t=="string"?t:t.name,s.schema);return n==="node"?ocs(s,t):n==="mark"?$ft(s,t):{}}function lcs(s,t=JSON.stringify){const n={};return s.filter(r=>{const a=t(r);return Object.prototype.hasOwnProperty.call(n,a)?!1:n[a]=!0})}function ccs(s){const t=lcs(s);return t.length===1?t:t.filter((n,r)=>!t.filter((i,l)=>l!==r).some(i=>n.oldRange.from>=i.oldRange.from&&n.oldRange.to<=i.oldRange.to&&n.newRange.from>=i.newRange.from&&n.newRange.to<=i.newRange.to))}function dcs(s){const{mapping:t,steps:n}=s,r=[];return t.maps.forEach((a,i)=>{const l=[];if(a.ranges.length)a.forEach((o,c)=>{l.push({from:o,to:c})});else{const{from:o,to:c}=n[i];if(o===void 0||c===void 0)return;l.push({from:o,to:c})}l.forEach(({from:o,to:c})=>{const d=t.slice(i).map(o,-1),u=t.slice(i).map(c),h=t.invert().map(d,-1),p=t.invert().map(u);r.push({oldRange:{from:h,to:p},newRange:{from:d,to:u}})})}),ccs(r)}function k6e(s,t,n){const r=[];return s===t?n.resolve(s).marks().forEach(a=>{const i=n.resolve(s),l=j6e(i,a.type);l&&r.push({mark:a,...l})}):n.nodesBetween(s,t,(a,i)=>{!a||(a==null?void 0:a.nodeSize)===void 0||r.push(...a.marks.map(l=>({from:i,to:i+a.nodeSize,mark:l})))}),r}function Dme(s,t,n){return Object.fromEntries(Object.entries(n).filter(([r])=>{const a=s.find(i=>i.type===t&&i.name===r);return a?a.attribute.keepOnSplit:!1}))}function bCe(s,t,n={}){const{empty:r,ranges:a}=s.selection,i=t?K4(t,s.schema):null;if(r)return!!(s.storedMarks||s.selection.$from.marks()).filter(h=>i?i.name===h.type.name:!0).find(h=>Mfe(h.attrs,n,{strict:!1}));let l=0;const o=[];if(a.forEach(({$from:h,$to:p})=>{const f=h.pos,y=p.pos;s.doc.nodesBetween(f,y,(_,v)=>{if(!_.isText&&!_.marks.length)return;const j=Math.max(f,v),w=Math.min(y,v+_.nodeSize),S=w-j;l+=S,o.push(..._.marks.map(A=>({mark:A,from:j,to:w})))})}),l===0)return!1;const c=o.filter(h=>i?i.name===h.mark.type.name:!0).filter(h=>Mfe(h.mark.attrs,n,{strict:!1})).reduce((h,p)=>h+p.to-p.from,0),d=o.filter(h=>i?h.mark.type!==i&&h.mark.type.excludes(i):!0).reduce((h,p)=>h+p.to-p.from,0);return(c>0?c+d:c)>=l}function ucs(s,t,n={}){if(!t)return xB(s,null,n)||bCe(s,null,n);const r=Vye(t,s.schema);return r==="node"?xB(s,t,n):r==="mark"?bCe(s,t,n):!1}function Mqe(s,t){const{nodeExtensions:n}=$ye(t),r=n.find(l=>l.name===s);if(!r)return!1;const a={name:r.name,options:r.options,storage:r.storage},i=Wo(li(r,"group",a));return typeof i!="string"?!1:i.split(" ").includes("list")}function S6e(s,{checkChildren:t=!0,ignoreWhitespace:n=!1}={}){var r;if(n){if(s.type.name==="hardBreak")return!0;if(s.isText)return/^\s*$/m.test((r=s.text)!==null&&r!==void 0?r:"")}if(s.isText)return!s.text;if(s.isAtom||s.isLeaf)return!1;if(s.content.childCount===0)return!0;if(t){let a=!0;return s.content.forEach(i=>{a!==!1&&(S6e(i,{ignoreWhitespace:n,checkChildren:t})||(a=!1))}),a}return!1}function hcs(s){return s instanceof Li}function mcs(s,t,n){var r;const{selection:a}=t;let i=null;if(Oft(a)&&(i=a.$cursor),i){const o=(r=s.storedMarks)!==null&&r!==void 0?r:i.marks();return!!n.isInSet(o)||!o.some(c=>c.type.excludes(n))}const{ranges:l}=a;return l.some(({$from:o,$to:c})=>{let d=o.depth===0?s.doc.inlineContent&&s.doc.type.allowsMarkType(n):!1;return s.doc.nodesBetween(o.pos,c.pos,(u,h,p)=>{if(d)return!1;if(u.isInline){const f=!p||p.type.allowsMarkType(n),y=!!n.isInSet(u.marks)||!u.marks.some(_=>_.type.excludes(n));d=f&&y}return!d}),d})}const pcs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{const{selection:i}=n,{empty:l,ranges:o}=i,c=K4(s,r.schema);if(a)if(l){const d=$ft(r,c);n.addStoredMark(c.create({...d,...t}))}else o.forEach(d=>{const u=d.$from.pos,h=d.$to.pos;r.doc.nodesBetween(u,h,(p,f)=>{const y=Math.max(f,u),_=Math.min(f+p.nodeSize,h);p.marks.find(j=>j.type===c)?p.marks.forEach(j=>{c===j.type&&n.addMark(y,_,c.create({...j.attrs,...t}))}):n.addMark(y,_,c.create(t))})});return mcs(r,n,c)},fcs=(s,t)=>({tr:n})=>(n.setMeta(s,t),!0),xcs=(s,t={})=>({state:n,dispatch:r,chain:a})=>{const i=Ep(s,n.schema);let l;return n.selection.$anchor.sameParent(n.selection.$head)&&(l=n.selection.$anchor.parent.attrs),i.isTextblock?a().command(({commands:o})=>Nqe(i,{...l,...t})(n)?!0:o.clearNodes()).command(({state:o})=>Nqe(i,{...l,...t})(o,r)).run():(console.warn('[tiptap warn]: Currently "setNode()" only supports text block nodes.'),!1)},gcs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,a=GE(s,0,r.content.size),i=Li.create(r,a);t.setSelection(i)}return!0},ycs=s=>({tr:t,dispatch:n})=>{if(n){const{doc:r}=t,{from:a,to:i}=typeof s=="number"?{from:s,to:s}:s,l=Ui.atStart(r).from,o=Ui.atEnd(r).to,c=GE(a,l,o),d=GE(i,l,o),u=Ui.create(r,c,d);t.setSelection(u)}return!0},vcs=s=>({state:t,dispatch:n})=>{const r=Ep(s,t.schema);return Zos(r)(t,n)};function Iqe(s,t){const n=s.storedMarks||s.selection.$to.parentOffset&&s.selection.$from.marks();if(n){const r=n.filter(a=>t==null?void 0:t.includes(a.type.name));s.tr.ensureMarks(r)}}const bcs=({keepMarks:s=!0}={})=>({tr:t,state:n,dispatch:r,editor:a})=>{const{selection:i,doc:l}=t,{$from:o,$to:c}=i,d=a.extensionManager.attributes,u=Dme(d,o.node().type.name,o.node().attrs);if(i instanceof Li&&i.node.isBlock)return!o.parentOffset||!EL(l,o.pos)?!1:(r&&(s&&Iqe(n,a.extensionManager.splittableMarks),t.split(o.pos).scrollIntoView()),!0);if(!o.parent.isBlock)return!1;const h=c.parentOffset===c.parent.content.size,p=o.depth===0?void 0:rcs(o.node(-1).contentMatchAt(o.indexAfter(-1)));let f=h&&p?[{type:p,attrs:u}]:void 0,y=EL(t.doc,t.mapping.map(o.pos),1,f);if(!f&&!y&&EL(t.doc,t.mapping.map(o.pos),1,p?[{type:p}]:void 0)&&(y=!0,f=p?[{type:p,attrs:u}]:void 0),r){if(y&&(i instanceof Ui&&t.deleteSelection(),t.split(t.mapping.map(o.pos),1,f),p&&!h&&!o.parentOffset&&o.parent.type!==p)){const _=t.mapping.map(o.before()),v=t.doc.resolve(_);o.node(-1).canReplaceWith(v.index(),v.index()+1,p)&&t.setNodeMarkup(t.mapping.map(o.before()),p)}s&&Iqe(n,a.extensionManager.splittableMarks),t.scrollIntoView()}return y},_cs=(s,t={})=>({tr:n,state:r,dispatch:a,editor:i})=>{var l;const o=Ep(s,r.schema),{$from:c,$to:d}=r.selection,u=r.selection.node;if(u&&u.isBlock||c.depth<2||!c.sameParent(d))return!1;const h=c.node(-1);if(h.type!==o)return!1;const p=i.extensionManager.attributes;if(c.parent.content.size===0&&c.node(-1).childCount===c.indexAfter(-1)){if(c.depth===2||c.node(-3).type!==o||c.index(-2)!==c.node(-2).childCount-1)return!1;if(a){let j=$r.empty;const w=c.index(-1)?1:c.index(-2)?2:3;for(let I=c.depth-w;I>=c.depth-3;I-=1)j=$r.from(c.node(I).copy(j));const S=c.indexAfter(-1){if(D>-1)return!1;I.isTextblock&&I.content.size===0&&(D=F+1)}),D>-1&&n.setSelection(Ui.near(n.doc.resolve(D))),n.scrollIntoView()}return!0}const f=d.pos===c.end()?h.contentMatchAt(0).defaultType:null,y={...Dme(p,h.type.name,h.attrs),...t},_={...Dme(p,c.node().type.name,c.node().attrs),...t};n.delete(c.pos,d.pos);const v=f?[{type:o,attrs:y},{type:f,attrs:_}]:[{type:o,attrs:y}];if(!EL(n.doc,c.pos,2))return!1;if(a){const{selection:j,storedMarks:w}=r,{splittableMarks:S}=i.extensionManager,A=w||j.$to.parentOffset&&j.$from.marks();if(n.split(c.pos,2,v).scrollIntoView(),!A||!a)return!0;const E=A.filter(O=>S.includes(O.type.name));n.ensureMarks(E)}return!0},$je=(s,t)=>{const n=N6e(l=>l.type===t)(s.selection);if(!n)return!0;const r=s.doc.resolve(Math.max(0,n.pos-1)).before(n.depth);if(r===void 0)return!0;const a=s.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&G4(s.doc,n.pos)&&s.join(n.pos),!0},Uje=(s,t)=>{const n=N6e(l=>l.type===t)(s.selection);if(!n)return!0;const r=s.doc.resolve(n.start).after(n.depth);if(r===void 0)return!0;const a=s.doc.nodeAt(r);return n.node.type===(a==null?void 0:a.type)&&G4(s.doc,r)&&s.join(r),!0},wcs=(s,t,n,r={})=>({editor:a,tr:i,state:l,dispatch:o,chain:c,commands:d,can:u})=>{const{extensions:h,splittableMarks:p}=a.extensionManager,f=Ep(s,l.schema),y=Ep(t,l.schema),{selection:_,storedMarks:v}=l,{$from:j,$to:w}=_,S=j.blockRange(w),A=v||_.$to.parentOffset&&_.$from.marks();if(!S)return!1;const E=N6e(O=>Mqe(O.type.name,h))(_);if(S.depth>=1&&E&&S.depth-E.depth<=1){if(E.node.type===f)return d.liftListItem(y);if(Mqe(E.node.type.name,h)&&f.validContent(E.node.content)&&o)return c().command(()=>(i.setNodeMarkup(E.pos,f),!0)).command(()=>$je(i,f)).command(()=>Uje(i,f)).run()}return!n||!A||!o?c().command(()=>u().wrapInList(f,r)?!0:d.clearNodes()).wrapInList(f,r).command(()=>$je(i,f)).command(()=>Uje(i,f)).run():c().command(()=>{const O=u().wrapInList(f,r),D=A.filter(I=>p.includes(I.type.name));return i.ensureMarks(D),O?!0:d.clearNodes()}).wrapInList(f,r).command(()=>$je(i,f)).command(()=>Uje(i,f)).run()},jcs=(s,t={},n={})=>({state:r,commands:a})=>{const{extendEmptyMarkRange:i=!1}=n,l=K4(s,r.schema);return bCe(r,l,t)?a.unsetMark(l,{extendEmptyMarkRange:i}):a.setMark(l,t)},Ncs=(s,t,n={})=>({state:r,commands:a})=>{const i=Ep(s,r.schema),l=Ep(t,r.schema),o=xB(r,i,n);let c;return r.selection.$anchor.sameParent(r.selection.$head)&&(c=r.selection.$anchor.parent.attrs),o?a.setNode(l,c):a.setNode(i,{...c,...n})},kcs=(s,t={})=>({state:n,commands:r})=>{const a=Ep(s,n.schema);return xB(n,a,t)?r.lift(a):r.wrapIn(a,t)},Scs=()=>({state:s,dispatch:t})=>{const n=s.plugins;for(let r=0;r=0;c-=1)l.step(o.steps[c].invert(o.docs[c]));if(i.text){const c=l.doc.resolve(i.from).marks();l.replaceWith(i.from,i.to,s.schema.text(i.text,c))}else l.delete(i.from,i.to)}return!0}}return!1},Ccs=()=>({tr:s,dispatch:t})=>{const{selection:n}=s,{empty:r,ranges:a}=n;return r||t&&a.forEach(i=>{s.removeMark(i.$from.pos,i.$to.pos)}),!0},Tcs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{var i;const{extendEmptyMarkRange:l=!1}=t,{selection:o}=n,c=K4(s,r.schema),{$from:d,empty:u,ranges:h}=o;if(!a)return!0;if(u&&l){let{from:p,to:f}=o;const y=(i=d.marks().find(v=>v.type===c))===null||i===void 0?void 0:i.attrs,_=j6e(d,c,y);_&&(p=_.from,f=_.to),n.removeMark(p,f,c)}else h.forEach(p=>{n.removeMark(p.$from.pos,p.$to.pos,c)});return n.removeStoredMark(c),!0},Ecs=(s,t={})=>({tr:n,state:r,dispatch:a})=>{let i=null,l=null;const o=Vye(typeof s=="string"?s:s.name,r.schema);return o?(o==="node"&&(i=Ep(s,r.schema)),o==="mark"&&(l=K4(s,r.schema)),a&&n.selection.ranges.forEach(c=>{const d=c.$from.pos,u=c.$to.pos;let h,p,f,y;n.selection.empty?r.doc.nodesBetween(d,u,(_,v)=>{i&&i===_.type&&(f=Math.max(v,d),y=Math.min(v+_.nodeSize,u),h=v,p=_)}):r.doc.nodesBetween(d,u,(_,v)=>{v=d&&v<=u&&(i&&i===_.type&&n.setNodeMarkup(v,void 0,{..._.attrs,...t}),l&&_.marks.length&&_.marks.forEach(j=>{if(l===j.type){const w=Math.max(v,d),S=Math.min(v+_.nodeSize,u);n.addMark(w,S,l.create({...j.attrs,...t}))}}))}),p&&(h!==void 0&&n.setNodeMarkup(h,void 0,{...p.attrs,...t}),l&&p.marks.length&&p.marks.forEach(_=>{l===_.type&&n.addMark(f,y,l.create({..._.attrs,...t}))}))}),!0):!1},Acs=(s,t={})=>({state:n,dispatch:r})=>{const a=Ep(s,n.schema);return qos(a,t)(n,r)},Mcs=(s,t={})=>({state:n,dispatch:r})=>{const a=Ep(s,n.schema);return Vos(a,t)(n,r)};var Ics=Object.freeze({__proto__:null,blur:mls,clearContent:pls,clearNodes:fls,command:xls,createParagraphNear:gls,cut:yls,deleteCurrentNode:vls,deleteNode:bls,deleteRange:_ls,deleteSelection:wls,enter:jls,exitCode:Nls,extendMarkRange:kls,first:Sls,focus:Tls,forEach:Els,insertContent:Als,insertContentAt:Pls,joinBackward:Rls,joinDown:Dls,joinForward:Ols,joinItemBackward:Fls,joinItemForward:zls,joinTextblockBackward:Bls,joinTextblockForward:$ls,joinUp:Lls,keyboardShortcut:qls,lift:Vls,liftEmptyBlock:Hls,liftListItem:Gls,newlineInCode:Wls,resetAttributes:Kls,scrollIntoView:Yls,selectAll:Zls,selectNodeBackward:Qls,selectNodeForward:Xls,selectParentNode:Jls,selectTextblockEnd:ecs,selectTextblockStart:tcs,setContent:scs,setMark:pcs,setMeta:fcs,setNode:xcs,setNodeSelection:gcs,setTextSelection:ycs,sinkListItem:vcs,splitBlock:bcs,splitListItem:_cs,toggleList:wcs,toggleMark:jcs,toggleNode:Ncs,toggleWrap:kcs,undoInputRule:Scs,unsetAllMarks:Ccs,unsetMark:Tcs,updateAttributes:Ecs,wrapIn:Acs,wrapInList:Mcs});const Pcs=Nf.create({name:"commands",addCommands(){return{...Ics}}}),Lcs=Nf.create({name:"drop",addProseMirrorPlugins(){return[new Gm({key:new ox("tiptapDrop"),props:{handleDrop:(s,t,n,r)=>{this.editor.emit("drop",{editor:this.editor,event:t,slice:n,moved:r})}}})]}}),Dcs=Nf.create({name:"editable",addProseMirrorPlugins(){return[new Gm({key:new ox("editable"),props:{editable:()=>this.editor.options.editable}})]}}),Rcs=new ox("focusEvents"),Ocs=Nf.create({name:"focusEvents",addProseMirrorPlugins(){const{editor:s}=this;return[new Gm({key:Rcs,props:{handleDOMEvents:{focus:(t,n)=>{s.isFocused=!0;const r=s.state.tr.setMeta("focus",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1},blur:(t,n)=>{s.isFocused=!1;const r=s.state.tr.setMeta("blur",{event:n}).setMeta("addToHistory",!1);return t.dispatch(r),!1}}}})]}}),Fcs=Nf.create({name:"keymap",addKeyboardShortcuts(){const s=()=>this.editor.commands.first(({commands:l})=>[()=>l.undoInputRule(),()=>l.command(({tr:o})=>{const{selection:c,doc:d}=o,{empty:u,$anchor:h}=c,{pos:p,parent:f}=h,y=h.parent.isTextblock&&p>0?o.doc.resolve(p-1):h,_=y.parent.type.spec.isolating,v=h.pos-h.parentOffset,j=_&&y.parent.childCount===1?v===h.pos:to.atStart(d).from===p;return!u||!f.type.isTextblock||f.textContent.length||!j||j&&h.parent.type.name==="paragraph"?!1:l.clearNodes()}),()=>l.deleteSelection(),()=>l.joinBackward(),()=>l.selectNodeBackward()]),t=()=>this.editor.commands.first(({commands:l})=>[()=>l.deleteSelection(),()=>l.deleteCurrentNode(),()=>l.joinForward(),()=>l.selectNodeForward()]),r={Enter:()=>this.editor.commands.first(({commands:l})=>[()=>l.newlineInCode(),()=>l.createParagraphNear(),()=>l.liftEmptyBlock(),()=>l.splitBlock()]),"Mod-Enter":()=>this.editor.commands.exitCode(),Backspace:s,"Mod-Backspace":s,"Shift-Backspace":s,Delete:t,"Mod-Delete":t,"Mod-a":()=>this.editor.commands.selectAll()},a={...r},i={...r,"Ctrl-h":s,"Alt-Backspace":s,"Ctrl-d":t,"Ctrl-Alt-Backspace":t,"Alt-Delete":t,"Alt-d":t,"Ctrl-a":()=>this.editor.commands.selectTextblockStart(),"Ctrl-e":()=>this.editor.commands.selectTextblockEnd()};return Ife()||Bft()?i:a},addProseMirrorPlugins(){return[new Gm({key:new ox("clearDocument"),appendTransaction:(s,t,n)=>{if(s.some(_=>_.getMeta("composition")))return;const r=s.some(_=>_.docChanged)&&!t.doc.eq(n.doc),a=s.some(_=>_.getMeta("preventClearDocument"));if(!r||a)return;const{empty:i,from:l,to:o}=t.selection,c=to.atStart(t.doc).from,d=to.atEnd(t.doc).to;if(i||!(l===c&&o===d)||!S6e(n.doc))return;const p=n.tr,f=zye({state:n,transaction:p}),{commands:y}=new Bye({editor:this.editor,state:f});if(y.clearNodes(),!!p.steps.length)return p}})]}}),zcs=Nf.create({name:"paste",addProseMirrorPlugins(){return[new Gm({key:new ox("tiptapPaste"),props:{handlePaste:(s,t,n)=>{this.editor.emit("paste",{editor:this.editor,event:t,slice:n})}}})]}}),Bcs=Nf.create({name:"tabindex",addProseMirrorPlugins(){return[new Gm({key:new ox("tabindex"),props:{attributes:()=>this.editor.isEditable?{tabindex:"0"}:{}}})]}});class DE{get name(){return this.node.type.name}constructor(t,n,r=!1,a=null){this.currentNode=null,this.actualDepth=null,this.isBlock=r,this.resolvedPos=t,this.editor=n,this.currentNode=a}get node(){return this.currentNode||this.resolvedPos.node()}get element(){return this.editor.view.domAtPos(this.pos).node}get depth(){var t;return(t=this.actualDepth)!==null&&t!==void 0?t:this.resolvedPos.depth}get pos(){return this.resolvedPos.pos}get content(){return this.node.content}set content(t){let n=this.from,r=this.to;if(this.isBlock){if(this.content.size===0){console.error(`You can’t set content on a block node. Tried to set content on ${this.name} at ${this.pos}`);return}n=this.from+1,r=this.to-1}this.editor.commands.insertContentAt({from:n,to:r},t)}get attributes(){return this.node.attrs}get textContent(){return this.node.textContent}get size(){return this.node.nodeSize}get from(){return this.isBlock?this.pos:this.resolvedPos.start(this.resolvedPos.depth)}get range(){return{from:this.from,to:this.to}}get to(){return this.isBlock?this.pos+this.size:this.resolvedPos.end(this.resolvedPos.depth)+(this.node.isText?0:1)}get parent(){if(this.depth===0)return null;const t=this.resolvedPos.start(this.resolvedPos.depth-1),n=this.resolvedPos.doc.resolve(t);return new DE(n,this.editor)}get before(){let t=this.resolvedPos.doc.resolve(this.from-(this.isBlock?1:2));return t.depth!==this.depth&&(t=this.resolvedPos.doc.resolve(this.from-3)),new DE(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 DE(t,this.editor)}get children(){const t=[];return this.node.content.forEach((n,r)=>{const a=n.isBlock&&!n.isTextblock,i=n.isAtom&&!n.isText,l=this.pos+r+(i?0:1);if(l<0||l>this.resolvedPos.doc.nodeSize-2)return;const o=this.resolvedPos.doc.resolve(l);if(!a&&o.depth<=this.depth)return;const c=new DE(o,this.editor,a,a?n:null);a&&(c.actualDepth=this.depth+1),t.push(new DE(o,this.editor,a,a?n:null))}),t}get firstChild(){return this.children[0]||null}get lastChild(){const t=this.children;return t[t.length-1]||null}closest(t,n={}){let r=null,a=this.parent;for(;a&&!r;){if(a.node.type.name===t)if(Object.keys(n).length>0){const i=a.node.attrs,l=Object.keys(n);for(let o=0;o{r&&a.length>0||(l.node.type.name===t&&i.every(c=>n[c]===l.node.attrs[c])&&a.push(l),!(r&&a.length>0)&&(a=a.concat(l.querySelectorAll(t,n,r))))}),a}setAttribute(t){const{tr:n}=this.editor.state;n.setNodeMarkup(this.from,void 0,{...this.node.attrs,...t}),this.editor.view.dispatch(n)}}const $cs=`.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 Ucs(s,t,n){const r=document.querySelector("style[data-tiptap-style]");if(r!==null)return r;const a=document.createElement("style");return t&&a.setAttribute("nonce",t),a.setAttribute("data-tiptap-style",""),a.innerHTML=s,document.getElementsByTagName("head")[0].appendChild(a),a}class qcs extends Qos{constructor(t={}){super(),this.isFocused=!1,this.isInitialized=!1,this.extensionStorage={},this.options={element:document.createElement("div"),content:"",injectCSS:!0,injectNonce:void 0,extensions:[],autofocus:!1,editable:!0,editorProps:{},parseOptions:{},coreExtensionOptions:{},enableInputRules:!0,enablePasteRules:!0,enableCoreExtensions:!0,enableContentCheck:!1,emitContentError:!1,onBeforeCreate:()=>null,onCreate:()=>null,onUpdate:()=>null,onSelectionUpdate:()=>null,onTransaction:()=>null,onFocus:()=>null,onBlur:()=>null,onDestroy:()=>null,onContentError:({error:n})=>{throw n},onPaste:()=>null,onDrop:()=>null},this.isCapturingTransaction=!1,this.capturedTransaction=null,this.setOptions(t),this.createExtensionManager(),this.createCommandManager(),this.createSchema(),this.on("beforeCreate",this.options.onBeforeCreate),this.emit("beforeCreate",{editor:this}),this.on("contentError",this.options.onContentError),this.createView(),this.injectCSS(),this.on("create",this.options.onCreate),this.on("update",this.options.onUpdate),this.on("selectionUpdate",this.options.onSelectionUpdate),this.on("transaction",this.options.onTransaction),this.on("focus",this.options.onFocus),this.on("blur",this.options.onBlur),this.on("destroy",this.options.onDestroy),this.on("drop",({event:n,slice:r,moved:a})=>this.options.onDrop(n,r,a)),this.on("paste",({event:n,slice:r})=>this.options.onPaste(n,r)),window.setTimeout(()=>{this.isDestroyed||(this.commands.focus(this.options.autofocus),this.emit("create",{editor:this}),this.isInitialized=!0)},0)}get storage(){return this.extensionStorage}get commands(){return this.commandManager.commands}chain(){return this.commandManager.chain()}can(){return this.commandManager.can()}injectCSS(){this.options.injectCSS&&document&&(this.css=Ucs($cs,this.options.injectNonce))}setOptions(t={}){this.options={...this.options,...t},!(!this.view||!this.state||this.isDestroyed)&&(this.options.editorProps&&this.view.setProps(this.options.editorProps),this.view.updateState(this.state))}setEditable(t,n=!0){this.setOptions({editable:t}),n&&this.emit("update",{editor:this,transaction:this.state.tr})}get isEditable(){return this.options.editable&&this.view&&this.view.editable}get state(){return this.view.state}registerPlugin(t,n){const r=Pft(n)?n(t,[...this.state.plugins]):[...this.state.plugins,t],a=this.state.reconfigure({plugins:r});return this.view.updateState(a),a}unregisterPlugin(t){if(this.isDestroyed)return;const n=this.state.plugins;let r=n;if([].concat(t).forEach(i=>{const l=typeof i=="string"?`${i}$`:i.key;r=r.filter(o=>!o.key.startsWith(l))}),n.length===r.length)return;const a=this.state.reconfigure({plugins:r});return this.view.updateState(a),a}createExtensionManager(){var t,n;const a=[...this.options.enableCoreExtensions?[Dcs,hls.configure({blockSeparator:(n=(t=this.options.coreExtensionOptions)===null||t===void 0?void 0:t.clipboardTextSerializer)===null||n===void 0?void 0:n.blockSeparator}),Pcs,Ocs,Fcs,Bcs,Lcs,zcs].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 SP(a,this)}createCommandManager(){this.commandManager=new Bye({editor:this})}createSchema(){this.schema=this.extensionManager.schema}createView(){var t;let n;try{n=vCe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:this.options.enableContentCheck})}catch(l){if(!(l instanceof Error)||!["[tiptap error]: Invalid JSON content","[tiptap error]: Invalid HTML content"].includes(l.message))throw l;this.emit("contentError",{editor:this,error:l,disableCollaboration:()=>{this.storage.collaboration&&(this.storage.collaboration.isDisabled=!0),this.options.extensions=this.options.extensions.filter(o=>o.name!=="collaboration"),this.createExtensionManager()}}),n=vCe(this.options.content,this.schema,this.options.parseOptions,{errorOnInvalidContent:!1})}const r=Fft(n,this.options.autofocus);this.view=new kft(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:kP.create({doc:n,selection:r||void 0})});const a=this.state.reconfigure({plugins:this.extensionManager.plugins});this.view.updateState(a),this.createNodeViews(),this.prependClass();const i=this.view.dom;i.editor=this}createNodeViews(){this.view.isDestroyed||this.view.setProps({nodeViews:this.extensionManager.nodeViews})}prependClass(){this.view.dom.className=`tiptap ${this.view.dom.className}`}captureTransaction(t){this.isCapturingTransaction=!0,t(),this.isCapturingTransaction=!1;const n=this.capturedTransaction;return this.capturedTransaction=null,n}dispatchTransaction(t){if(this.view.isDestroyed)return;if(this.isCapturingTransaction){if(!this.capturedTransaction){this.capturedTransaction=t;return}t.steps.forEach(l=>{var o;return(o=this.capturedTransaction)===null||o===void 0?void 0:o.step(l)});return}const n=this.state.apply(t),r=!this.state.selection.eq(n.selection);this.emit("beforeTransaction",{editor:this,transaction:t,nextState:n}),this.view.updateState(n),this.emit("transaction",{editor:this,transaction:t}),r&&this.emit("selectionUpdate",{editor:this,transaction:t});const a=t.getMeta("focus"),i=t.getMeta("blur");a&&this.emit("focus",{editor:this,event:a.event,transaction:t}),i&&this.emit("blur",{editor:this,event:i.event,transaction:t}),!(!t.docChanged||t.getMeta("preventUpdate"))&&this.emit("update",{editor:this,transaction:t})}getAttributes(t){return qft(this.state,t)}isActive(t,n){const r=typeof t=="string"?t:null,a=typeof t=="string"?n:t;return ucs(this.state,r,a)}getJSON(){return this.state.doc.toJSON()}getHTML(){return _6e(this.state.doc.content,this.schema)}getText(t){const{blockSeparator:n=` `,textSerializers:r={}}=t||{};return ics(this.state.doc,{blockSeparator:n,textSerializers:{...Dft(this.schema),...r}})}get isEmpty(){return S6e(this.state.doc)}getCharacterCount(){return console.warn('[tiptap warn]: "editor.getCharacterCount()" is deprecated. Please use "editor.storage.characterCount.characters()" instead.'),this.state.doc.content.size-2}destroy(){if(this.emit("destroy"),this.view){const t=this.view.dom;t&&t.editor&&delete t.editor,this.view.destroy()}this.removeAllListeners()}get isDestroyed(){var t;return!(!((t=this.view)===null||t===void 0)&&t.docView)}$node(t,n){var r;return((r=this.$doc)===null||r===void 0?void 0:r.querySelector(t,n))||null}$nodes(t,n){var r;return((r=this.$doc)===null||r===void 0?void 0:r.querySelectorAll(t,n))||null}$pos(t){const n=this.state.doc.resolve(t);return new DE(n,this)}get $doc(){return this.$pos(0)}}function S8(s){return new Uye({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Wo(s.getAttributes,void 0,r);if(a===!1||a===null)return null;const{tr:i}=t,l=r[r.length-1],o=r[0];if(l){const c=o.search(/\S/),d=n.from+o.indexOf(l),u=d+l.length;if(k6e(n.from,n.to,t.doc).filter(f=>f.mark.type.excluded.find(_=>_===s.type&&_!==f.mark.type)).filter(f=>f.to>d).length)return null;un.from&&i.delete(n.from+c,d);const p=n.from+c+l.length;i.addMark(n.from+c,p,s.type.create(a||{})),i.removeStoredMark(s.type)}}})}function Vft(s){return new Uye({find:s.find,handler:({state:t,range:n,match:r})=>{const a=Wo(s.getAttributes,void 0,r)||{},{tr:i}=t,l=n.from;let o=n.to;const c=s.type.create(a);if(r[1]){const d=r[0].lastIndexOf(r[1]);let u=l+d;u>o?u=o:o=u+r[1].length;const h=r[0][r[0].length-1];i.insertText(h,l+r[0].length-1),i.replaceWith(u,o,c)}else if(r[0]){const d=s.type.isInline?l:l-1;i.insert(d,s.type.create(a)).delete(i.mapping.map(l),i.mapping.map(o))}i.scrollIntoView()}})}function _Ce(s){return new Uye({find:s.find,handler:({state:t,range:n,match:r})=>{const a=t.doc.resolve(n.from),i=Wo(s.getAttributes,void 0,r)||{};if(!a.node(-1).canReplaceWith(a.index(-1),a.indexAfter(-1),s.type))return null;t.tr.delete(n.from,n.to).setBlockType(n.from,n.from,s.type,i)}})}function gB(s){return new Uye({find:s.find,handler:({state:t,range:n,match:r,chain:a})=>{const i=Wo(s.getAttributes,void 0,r)||{},l=t.tr.delete(n.from,n.to),c=l.doc.resolve(n.from).blockRange(),d=c&&i6e(c,s.type,i);if(!d)return null;if(l.wrap(c,d),s.keepMarks&&s.editor){const{selection:h,storedMarks:p}=t,{splittableMarks:f}=s.editor.extensionManager,y=p||h.$to.parentOffset&&h.$from.marks();if(y){const _=y.filter(v=>f.includes(v.type.name));l.ensureMarks(_)}}if(s.keepAttributes){const h=s.type.name==="bulletList"||s.type.name==="orderedList"?"listItem":"taskList";a().updateAttributes(h,i).run()}const u=l.doc.resolve(n.from-1).nodeBefore;u&&u.type===s.type&&G4(l.doc,n.from-1)&&(!s.joinPredicate||s.joinPredicate(r,u))&&l.join(n.from-1)}})}let lx=class wCe{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=Wo(li(this,"addOptions",{name:this.name}))),this.storage=Wo(li(this,"addStorage",{name:this.name,options:this.options}))||{}}static create(t={}){return new wCe(t)}configure(t={}){const n=this.extend({...this.config,addOptions:()=>qye(this.options,t)});return n.name=this.name,n.parent=this.parent,n}extend(t={}){const n=new wCe(t);return n.parent=this,this.child=n,n.name=t.name?t.name:n.parent.name,t.defaultOptions&&Object.keys(t.defaultOptions).length>0&&console.warn(`[tiptap warn]: BREAKING CHANGE: "defaultOptions" is deprecated. Please use "addOptions" instead. Found in extension: "${n.name}".`),n.options=Wo(li(n,"addOptions",{name:n.name})),n.storage=Wo(li(n,"addStorage",{name:n.name,options:n.options})),n}};function bM(s){return new ils({find:s.find,handler:({state:t,range:n,match:r,pasteEvent:a})=>{const i=Wo(s.getAttributes,void 0,r,a);if(i===!1||i===null)return null;const{tr:l}=t,o=r[r.length-1],c=r[0];let d=n.to;if(o){const u=c.search(/\S/),h=n.from+c.indexOf(o),p=h+o.length;if(k6e(n.from,n.to,t.doc).filter(y=>y.mark.type.excluded.find(v=>v===s.type&&v!==y.mark.type)).filter(y=>y.to>h).length)return null;pn.from&&l.delete(n.from+u,h),d=n.from+u+o.length,l.addMark(n.from+u,d,s.type.create(i||{})),l.removeStoredMark(s.type)}}})}function Vcs(s,t){const{selection:n}=s,{$from:r}=n;if(n instanceof Li){const i=r.index();return r.parent.canReplaceWith(i,i+1,t)}let a=r.depth;for(;a>=0;){const i=r.index(a);if(r.node(a).contentMatchAt(i).matchType(t))return!0;a-=1}return!1}function Hcs(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Hft={exports:{}},qje={};/** * @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 Pqe;function Gcs(){if(Pqe)return qje;Pqe=1;var s=Ct;function t(h,p){return h===p&&(h!==0||1/h===1/p)||h!==h&&p!==p}var n=typeof Object.is=="function"?Object.is:t,r=s.useState,a=s.useEffect,i=s.useLayoutEffect,l=s.useDebugValue;function o(h,p){var f=p(),y=r({inst:{value:f,getSnapshot:p}}),_=y[0].inst,v=y[1];return i(function(){_.value=f,_.getSnapshot=p,c(_)&&v({inst:_})},[h,f,p]),a(function(){return c(_)&&v({inst:_}),h(function(){c(_)&&v({inst:_})})},[h]),l(f),f}function c(h){var p=h.getSnapshot;h=h.value;try{var f=p();return!n(h,f)}catch{return!0}}function d(h,p){return p()}var u=typeof window>"u"||typeof window.document>"u"||typeof window.document.createElement>"u"?d:o;return qje.useSyncExternalStore=s.useSyncExternalStore!==void 0?s.useSyncExternalStore:u,qje}Hft.exports=Gcs();var C6e=Hft.exports;const Wcs=(...s)=>t=>{s.forEach(n=>{typeof n=="function"?n(t):n&&(n.current=t)})},Kcs=({contentComponent:s})=>{const t=C6e.useSyncExternalStore(s.subscribe,s.getSnapshot,s.getServerSnapshot);return Ct.createElement(Ct.Fragment,null,Object.values(t))};function Ycs(){const s=new Set;let t={};return{subscribe(n){return s.add(n),()=>{s.delete(n)}},getSnapshot(){return t},getServerSnapshot(){return t},setRenderer(n,r){t={...t,[n]:zEe.createPortal(r.reactElement,r.element,n)},s.forEach(a=>a())},removeRenderer(n){const r={...t};delete r[n],t=r,s.forEach(a=>a())}}}class Zcs extends Ct.Component{constructor(t){var n;super(t),this.editorContentRef=Ct.createRef(),this.initialized=!1,this.state={hasContentComponentInitialized:!!(!((n=t.editor)===null||n===void 0)&&n.contentComponent)}}componentDidMount(){this.init()}componentDidUpdate(){this.init()}init(){const t=this.props.editor;if(t&&!t.isDestroyed&&t.options.element){if(t.contentComponent)return;const n=this.editorContentRef.current;n.append(...t.options.element.childNodes),t.setOptions({element:n}),t.contentComponent=Ycs(),this.state.hasContentComponentInitialized||(this.unsubscribeToContentComponent=t.contentComponent.subscribe(()=>{this.setState(r=>r.hasContentComponentInitialized?r:{hasContentComponentInitialized:!0}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent()})),t.createNodeViews(),this.initialized=!0}}componentWillUnmount(){const t=this.props.editor;if(!t||(this.initialized=!1,t.isDestroyed||t.view.setProps({nodeViews:{}}),this.unsubscribeToContentComponent&&this.unsubscribeToContentComponent(),t.contentComponent=null,!t.options.element.firstChild))return;const n=document.createElement("div");n.append(...t.options.element.childNodes),t.setOptions({element:n})}render(){const{editor:t,innerRef:n,...r}=this.props;return Ct.createElement(Ct.Fragment,null,Ct.createElement("div",{ref:Wcs(n,this.editorContentRef),...r}),(t==null?void 0:t.contentComponent)&&Ct.createElement(Kcs,{contentComponent:t.contentComponent}))}}const Qcs=N.forwardRef((s,t)=>{const n=Ct.useMemo(()=>Math.floor(Math.random()*4294967295).toString(),[s.editor]);return Ct.createElement(Zcs,{key:n,innerRef:t,...s})}),T6e=Ct.memo(Qcs);var Xcs=function s(t,n){if(t===n)return!0;if(t&&n&&typeof t=="object"&&typeof n=="object"){if(t.constructor!==n.constructor)return!1;var r,a,i;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(a=r;a--!==0;)if(!s(t[a],n[a]))return!1;return!0}if(t instanceof Map&&n instanceof Map){if(t.size!==n.size)return!1;for(a of t.entries())if(!n.has(a[0]))return!1;for(a of t.entries())if(!s(a[1],n.get(a[0])))return!1;return!0}if(t instanceof Set&&n instanceof Set){if(t.size!==n.size)return!1;for(a of t.entries())if(!n.has(a[0]))return!1;return!0}if(ArrayBuffer.isView(t)&&ArrayBuffer.isView(n)){if(r=t.length,r!=n.length)return!1;for(a=r;a--!==0;)if(t[a]!==n[a])return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(i=Object.keys(t),r=i.length,r!==Object.keys(n).length)return!1;for(a=r;a--!==0;)if(!Object.prototype.hasOwnProperty.call(n,i[a]))return!1;for(a=r;a--!==0;){var l=i[a];if(!(l==="_owner"&&t.$$typeof)&&!s(t[l],n[l]))return!1}return!0}return t!==t&&n!==n},Jcs=Hcs(Xcs),Gft={exports:{}},Vje={};/** * @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 Lqe;function eds(){if(Lqe)return Vje;Lqe=1;var s=Ct,t=C6e;function n(d,u){return d===u&&(d!==0||1/d===1/u)||d!==d&&u!==u}var r=typeof Object.is=="function"?Object.is:n,a=t.useSyncExternalStore,i=s.useRef,l=s.useEffect,o=s.useMemo,c=s.useDebugValue;return Vje.useSyncExternalStoreWithSelector=function(d,u,h,p,f){var y=i(null);if(y.current===null){var _={hasValue:!1,value:null};y.current=_}else _=y.current;y=o(function(){function j(O){if(!w){if(w=!0,S=O,O=p(O),f!==void 0&&_.hasValue){var D=_.value;if(f(D,O))return A=D}return A=O}if(D=A,r(S,O))return D;var I=p(O);return f!==void 0&&f(D,I)?D:(S=O,A=I)}var w=!1,S,A,E=h===void 0?null:h;return[function(){return j(u())},E===null?void 0:function(){return j(E())}]},[u,h,p,f]);var v=a(d,y[0],y[1]);return l(function(){_.hasValue=!0,_.value=v},[v]),c(v),v},Vje}Gft.exports=eds();var tds=Gft.exports;const sds=typeof window<"u"?N.useLayoutEffect:N.useEffect;class nds{constructor(t){this.transactionNumber=0,this.lastTransactionNumber=0,this.subscribers=new Set,this.editor=t,this.lastSnapshot={editor:t,transactionNumber:0},this.getSnapshot=this.getSnapshot.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.watch=this.watch.bind(this),this.subscribe=this.subscribe.bind(this)}getSnapshot(){return this.transactionNumber===this.lastTransactionNumber?this.lastSnapshot:(this.lastTransactionNumber=this.transactionNumber,this.lastSnapshot={editor:this.editor,transactionNumber:this.transactionNumber},this.lastSnapshot)}getServerSnapshot(){return{editor:null,transactionNumber:0}}subscribe(t){return this.subscribers.add(t),()=>{this.subscribers.delete(t)}}watch(t){if(this.editor=t,this.editor){const n=()=>{this.transactionNumber+=1,this.subscribers.forEach(a=>a())},r=this.editor;return r.on("transaction",n),()=>{r.off("transaction",n)}}}}function rds(s){var t;const[n]=N.useState(()=>new nds(s.editor)),r=tds.useSyncExternalStoreWithSelector(n.subscribe,n.getSnapshot,n.getServerSnapshot,s.selector,(t=s.equalityFn)!==null&&t!==void 0?t:Jcs);return sds(()=>n.watch(s.editor),[s.editor,n]),N.useDebugValue(r),r}const ads=!1,jCe=typeof window>"u",ids=jCe||!!(typeof window<"u"&&window.next);class E6e{constructor(t){this.editor=null,this.subscriptions=new Set,this.isComponentMounted=!1,this.previousDeps=null,this.instanceId="",this.options=t,this.subscriptions=new Set,this.setEditor(this.getInitialEditor()),this.scheduleDestroy(),this.getEditor=this.getEditor.bind(this),this.getServerSnapshot=this.getServerSnapshot.bind(this),this.subscribe=this.subscribe.bind(this),this.refreshEditorInstance=this.refreshEditorInstance.bind(this),this.scheduleDestroy=this.scheduleDestroy.bind(this),this.onRender=this.onRender.bind(this),this.createEditor=this.createEditor.bind(this)}setEditor(t){this.editor=t,this.instanceId=Math.random().toString(36).slice(2,9),this.subscriptions.forEach(n=>n())}getInitialEditor(){if(this.options.current.immediatelyRender===void 0)return jCe||ids?null:this.createEditor();if(this.options.current.immediatelyRender&&jCe&&ads)throw new Error("Tiptap Error: SSR has been detected, and `immediatelyRender` has been set to `true` this is an unsupported configuration that may result in errors, explicitly set `immediatelyRender` to `false` to avoid hydration mismatches.");return this.options.current.immediatelyRender?this.createEditor():null}createEditor(){const t={...this.options.current,onBeforeCreate:(...r)=>{var a,i;return(i=(a=this.options.current).onBeforeCreate)===null||i===void 0?void 0:i.call(a,...r)},onBlur:(...r)=>{var a,i;return(i=(a=this.options.current).onBlur)===null||i===void 0?void 0:i.call(a,...r)},onCreate:(...r)=>{var a,i;return(i=(a=this.options.current).onCreate)===null||i===void 0?void 0:i.call(a,...r)},onDestroy:(...r)=>{var a,i;return(i=(a=this.options.current).onDestroy)===null||i===void 0?void 0:i.call(a,...r)},onFocus:(...r)=>{var a,i;return(i=(a=this.options.current).onFocus)===null||i===void 0?void 0:i.call(a,...r)},onSelectionUpdate:(...r)=>{var a,i;return(i=(a=this.options.current).onSelectionUpdate)===null||i===void 0?void 0:i.call(a,...r)},onTransaction:(...r)=>{var a,i;return(i=(a=this.options.current).onTransaction)===null||i===void 0?void 0:i.call(a,...r)},onUpdate:(...r)=>{var a,i;return(i=(a=this.options.current).onUpdate)===null||i===void 0?void 0:i.call(a,...r)},onContentError:(...r)=>{var a,i;return(i=(a=this.options.current).onContentError)===null||i===void 0?void 0:i.call(a,...r)},onDrop:(...r)=>{var a,i;return(i=(a=this.options.current).onDrop)===null||i===void 0?void 0:i.call(a,...r)},onPaste:(...r)=>{var a,i;return(i=(a=this.options.current).onPaste)===null||i===void 0?void 0:i.call(a,...r)}};return new qcs(t)}getEditor(){return this.editor}getServerSnapshot(){return null}subscribe(t){return this.subscriptions.add(t),()=>{this.subscriptions.delete(t)}}static compareOptions(t,n){return Object.keys(t).every(r=>["onCreate","onBeforeCreate","onDestroy","onUpdate","onTransaction","onFocus","onBlur","onSelectionUpdate","onContentError","onDrop","onPaste"].includes(r)?!0:r==="extensions"&&t.extensions&&n.extensions?t.extensions.length!==n.extensions.length?!1:t.extensions.every((a,i)=>{var l;return a===((l=n.extensions)===null||l===void 0?void 0:l[i])}):t[r]===n[r])}onRender(t){return()=>(this.isComponentMounted=!0,clearTimeout(this.scheduledDestructionTimeout),this.editor&&!this.editor.isDestroyed&&t.length===0?E6e.compareOptions(this.options.current,this.editor.options)||this.editor.setOptions({...this.options.current,editable:this.editor.isEditable}):this.refreshEditorInstance(t),()=>{this.isComponentMounted=!1,this.scheduleDestroy()})}refreshEditorInstance(t){if(this.editor&&!this.editor.isDestroyed){if(this.previousDeps===null){this.previousDeps=t;return}if(this.previousDeps.length===t.length&&this.previousDeps.every((r,a)=>r===t[a]))return}this.editor&&!this.editor.isDestroyed&&this.editor.destroy(),this.setEditor(this.createEditor()),this.previousDeps=t}scheduleDestroy(){const t=this.instanceId,n=this.editor;this.scheduledDestructionTimeout=setTimeout(()=>{if(this.isComponentMounted&&this.instanceId===t){n&&n.setOptions(this.options.current);return}n&&!n.isDestroyed&&(n.destroy(),this.instanceId===t&&this.setEditor(null))},1)}}function A6e(s={},t=[]){const n=N.useRef(s);n.current=s;const[r]=N.useState(()=>new E6e(n)),a=C6e.useSyncExternalStore(r.subscribe,r.getEditor,r.getServerSnapshot);return N.useDebugValue(a),N.useEffect(r.onRender(t)),rds({editor:a,selector:({transactionNumber:i})=>s.shouldRerenderOnTransaction===!1?null:s.immediatelyRender&&i===0?0:i+1}),a}const ods=N.createContext({editor:null});ods.Consumer;const lds=N.createContext({onDragStart:void 0}),cds=()=>N.useContext(lds);Ct.forwardRef((s,t)=>{const{onDragStart:n}=cds(),r=s.as||"div";return Ct.createElement(r,{...s,ref:t,"data-node-view-wrapper":"",onDragStart:n,style:{whiteSpace:"normal",...s.style}})});const dds=/^\s*>\s$/,uds=lx.create({name:"blockquote",addOptions(){return{HTMLAttributes:{}}},content:"block+",group:"block",defining:!0,parseHTML(){return[{tag:"blockquote"}]},renderHTML({HTMLAttributes:s}){return["blockquote",du(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[gB({find:dds,type:this.type})]}}),hds=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))$/,mds=/(?:^|\s)(\*\*(?!\s+\*\*)((?:[^*]+))\*\*(?!\s+\*\*))/g,pds=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))$/,fds=/(?:^|\s)(__(?!\s+__)((?:[^_]+))__(?!\s+__))/g,xds=kb.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",du(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[S8({find:hds,type:this.type}),S8({find:pds,type:this.type})]},addPasteRules(){return[bM({find:mds,type:this.type}),bM({find:fds,type:this.type})]}}),gds="listItem",Dqe="textStyle",Rqe=/^\s*([-+*])\s$/,yds=lx.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",du(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(gds,this.editor.getAttributes(Dqe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-8":()=>this.editor.commands.toggleBulletList()}},addInputRules(){let s=gB({find:Rqe,type:this.type});return(this.options.keepMarks||this.options.keepAttributes)&&(s=gB({find:Rqe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:()=>this.editor.getAttributes(Dqe),editor:this.editor})),[s]}}),vds=/(^|[^`])`([^`]+)`(?!`)/,bds=/(^|[^`])`([^`]+)`(?!`)/g,_ds=kb.create({name:"code",addOptions(){return{HTMLAttributes:{}}},excludes:"_",code:!0,exitable:!0,parseHTML(){return[{tag:"code"}]},renderHTML({HTMLAttributes:s}){return["code",du(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[S8({find:vds,type:this.type})]},addPasteRules(){return[bM({find:bds,type:this.type})]}}),wds=/^```([a-z]+)?[\s\n]$/,jds=/^~~~([a-z]+)?[\s\n]$/,Nds=lx.create({name:"codeBlock",addOptions(){return{languageClassPrefix:"language-",exitOnTripleEnter:!0,exitOnArrowDown:!0,defaultLanguage:null,HTMLAttributes:{}}},content:"text*",marks:"",group:"block",code:!0,defining:!0,addAttributes(){return{language:{default:this.options.defaultLanguage,parseHTML:s=>{var t;const{languageClassPrefix:n}=this.options,i=[...((t=s.firstElementChild)===null||t===void 0?void 0:t.classList)||[]].filter(l=>l.startsWith(n)).map(l=>l.replace(n,""))[0];return i||null},rendered:!1}}},parseHTML(){return[{tag:"pre",preserveWhitespace:"full"}]},renderHTML({node:s,HTMLAttributes:t}){return["pre",du(this.options.HTMLAttributes,t),["code",{class:s.attrs.language?this.options.languageClassPrefix+s.attrs.language:null},0]]},addCommands(){return{setCodeBlock:s=>({commands:t})=>t.setNode(this.name,s),toggleCodeBlock:s=>({commands:t})=>t.toggleNode(this.name,"paragraph",s)}},addKeyboardShortcuts(){return{"Mod-Alt-c":()=>this.editor.commands.toggleCodeBlock(),Backspace:()=>{const{empty:s,$anchor:t}=this.editor.state.selection,n=t.pos===1;return!s||t.parent.type.name!==this.name?!1:n||!t.parent.textContent.length?this.editor.commands.clearNodes():!1},Enter:({editor:s})=>{if(!this.options.exitOnTripleEnter)return!1;const{state:t}=s,{selection:n}=t,{$from:r,empty:a}=n;if(!a||r.parent.type!==this.type)return!1;const i=r.parentOffset===r.parent.nodeSize-2,l=r.parent.textContent.endsWith(` `);return!i||!l?!1:s.chain().command(({tr:o})=>(o.delete(r.pos-2,r.pos),!0)).exitCode().run()},ArrowDown:({editor:s})=>{if(!this.options.exitOnArrowDown)return!1;const{state:t}=s,{selection:n,doc:r}=t,{$from:a,empty:i}=n;if(!i||a.parent.type!==this.type||!(a.parentOffset===a.parent.nodeSize-2))return!1;const o=a.after();return o===void 0?!1:r.nodeAt(o)?s.commands.command(({tr:d})=>(d.setSelection(to.near(r.resolve(o))),!0)):s.commands.exitCode()}}},addInputRules(){return[_Ce({find:wds,type:this.type,getAttributes:s=>({language:s[1]})}),_Ce({find:jds,type:this.type,getAttributes:s=>({language:s[1]})})]},addProseMirrorPlugins(){return[new Gm({key:new ox("codeBlockVSCodeHandler"),props:{handlePaste:(s,t)=>{if(!t.clipboardData||this.editor.isActive(this.type.name))return!1;const n=t.clipboardData.getData("text/plain"),r=t.clipboardData.getData("vscode-editor-data"),a=r?JSON.parse(r):void 0,i=a==null?void 0:a.mode;if(!n||!i)return!1;const{tr:l,schema:o}=s.state,c=o.text(n.replace(/\r\n?/g,` `));return l.replaceSelectionWith(this.type.create({language:i},c)),l.selection.$from.parent.type!==this.type&&l.setSelection(Ui.near(l.doc.resolve(Math.max(0,l.selection.from-2)))),l.setMeta("paste",!0),s.dispatch(l),!0}}})]}}),kds=lx.create({name:"doc",topNode:!0,content:"block+"});function Sds(s={}){return new Gm({view(t){return new Cds(t,s)}})}class Cds{constructor(t,n){var r;this.editorView=t,this.cursorPos=null,this.element=null,this.timeout=-1,this.width=(r=n.width)!==null&&r!==void 0?r:1,this.color=n.color===!1?void 0:n.color||"black",this.class=n.class,this.handlers=["dragover","dragend","drop","dragleave"].map(a=>{let i=l=>{this[a](l)};return t.dom.addEventListener(a,i),{name:a,handler:i}})}destroy(){this.handlers.forEach(({name:t,handler:n})=>this.editorView.dom.removeEventListener(t,n))}update(t,n){this.cursorPos!=null&&n.doc!=t.state.doc&&(this.cursorPos>t.state.doc.content.size?this.setCursor(null):this.updateOverlay())}setCursor(t){t!=this.cursorPos&&(this.cursorPos=t,t==null?(this.element.parentNode.removeChild(this.element),this.element=null):this.updateOverlay())}updateOverlay(){let t=this.editorView.state.doc.resolve(this.cursorPos),n=!t.parent.inlineContent,r,a=this.editorView.dom,i=a.getBoundingClientRect(),l=i.width/a.offsetWidth,o=i.height/a.offsetHeight;if(n){let h=t.nodeBefore,p=t.nodeAfter;if(h||p){let f=this.editorView.nodeDOM(this.cursorPos-(h?h.nodeSize:0));if(f){let y=f.getBoundingClientRect(),_=h?y.bottom:y.top;h&&p&&(_=(_+this.editorView.nodeDOM(this.cursorPos).getBoundingClientRect().top)/2);let v=this.width/2*o;r={left:y.left,right:y.right,top:_-v,bottom:_+v}}}}if(!r){let h=this.editorView.coordsAtPos(this.cursorPos),p=this.width/2*l;r={left:h.left-p,right:h.left+p,top:h.top,bottom:h.bottom}}let c=this.editorView.dom.offsetParent;this.element||(this.element=c.appendChild(document.createElement("div")),this.class&&(this.element.className=this.class),this.element.style.cssText="position: absolute; z-index: 50; pointer-events: none;",this.color&&(this.element.style.backgroundColor=this.color)),this.element.classList.toggle("prosemirror-dropcursor-block",n),this.element.classList.toggle("prosemirror-dropcursor-inline",!n);let d,u;if(!c||c==document.body&&getComputedStyle(c).position=="static")d=-pageXOffset,u=-pageYOffset;else{let h=c.getBoundingClientRect(),p=h.width/c.offsetWidth,f=h.height/c.offsetHeight;d=h.left-c.scrollLeft*p,u=h.top-c.scrollTop*f}this.element.style.left=(r.left-d)/l+"px",this.element.style.top=(r.top-u)/o+"px",this.element.style.width=(r.right-r.left)/l+"px",this.element.style.height=(r.bottom-r.top)/o+"px"}scheduleRemoval(t){clearTimeout(this.timeout),this.timeout=setTimeout(()=>this.setCursor(null),t)}dragover(t){if(!this.editorView.editable)return;let n=this.editorView.posAtCoords({left:t.clientX,top:t.clientY}),r=n&&n.inside>=0&&this.editorView.state.doc.nodeAt(n.inside),a=r&&r.type.spec.disableDropCursor,i=typeof a=="function"?a(this.editorView,n,t):a;if(n&&!i){let l=n.pos;if(this.editorView.dragging&&this.editorView.dragging.slice){let o=Opt(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 Tds=Nf.create({name:"dropCursor",addOptions(){return{color:"currentColor",width:1,class:void 0}},addProseMirrorPlugins(){return[Sds(this.options)]}});class sh extends to{constructor(t){super(t,t)}map(t,n){let r=t.resolve(n.map(this.head));return sh.valid(r)?new sh(r):to.near(r)}content(){return ba.empty}eq(t){return t instanceof sh&&t.head==this.head}toJSON(){return{type:"gapcursor",pos:this.head}}static fromJSON(t,n){if(typeof n.pos!="number")throw new RangeError("Invalid input for GapCursor.fromJSON");return new sh(t.resolve(n.pos))}getBookmark(){return new M6e(this.anchor)}static valid(t){let n=t.parent;if(n.inlineContent||!Eds(t)||!Ads(t))return!1;let r=n.type.spec.allowGapCursor;if(r!=null)return r;let a=n.contentMatchAt(t.index()).defaultType;return a&&a.isTextblock}static findGapCursorFrom(t,n,r=!1){e:for(;;){if(!r&&sh.valid(t))return t;let a=t.pos,i=null;for(let l=t.depth;;l--){let o=t.node(l);if(n>0?t.indexAfter(l)0){i=o.child(n>0?t.indexAfter(l):t.index(l)-1);break}else if(l==0)return null;a+=n;let c=t.doc.resolve(a);if(sh.valid(c))return c}for(;;){let l=n>0?i.firstChild:i.lastChild;if(!l){if(i.isAtom&&!i.isText&&!Li.isSelectable(i)){t=t.doc.resolve(a+i.nodeSize*n),r=!1;continue e}break}i=l,a+=n;let o=t.doc.resolve(a);if(sh.valid(o))return o}return null}}}sh.prototype.visible=!1;sh.findFrom=sh.findGapCursorFrom;to.jsonID("gapcursor",sh);class M6e{constructor(t){this.pos=t}map(t){return new M6e(t.map(this.pos))}resolve(t){let n=t.resolve(this.pos);return sh.valid(n)?new sh(n):to.near(n)}}function Wft(s){return s.isAtom||s.spec.isolating||s.spec.createGapCursor}function Eds(s){for(let t=s.depth;t>=0;t--){let n=s.index(t),r=s.node(t);if(n==0){if(r.type.spec.isolating)return!0;continue}for(let a=r.child(n-1);;a=a.lastChild){if(a.childCount==0&&!a.inlineContent||Wft(a.type))return!0;if(a.inlineContent)return!1}}return!0}function Ads(s){for(let t=s.depth;t>=0;t--){let n=s.indexAfter(t),r=s.node(t);if(n==r.childCount){if(r.type.spec.isolating)return!0;continue}for(let a=r.child(n);;a=a.firstChild){if(a.childCount==0&&!a.inlineContent||Wft(a.type))return!0;if(a.inlineContent)return!1}}return!0}function Mds(){return new Gm({props:{decorations:Dds,createSelectionBetween(s,t,n){return t.pos==n.pos&&sh.valid(n)?new sh(n):null},handleClick:Pds,handleKeyDown:Ids,handleDOMEvents:{beforeinput:Lds}}})}const Ids=y6e({ArrowLeft:hH("horiz",-1),ArrowRight:hH("horiz",1),ArrowUp:hH("vert",-1),ArrowDown:hH("vert",1)});function hH(s,t){const n=s=="vert"?t>0?"down":"up":t>0?"right":"left";return function(r,a,i){let l=r.selection,o=t>0?l.$to:l.$from,c=l.empty;if(l instanceof Ui){if(!i.endOfTextblock(n)||o.depth==0)return!1;c=!1,o=r.doc.resolve(t>0?o.after():o.before())}let d=sh.findGapCursorFrom(o,t,c);return d?(a&&a(r.tr.setSelection(new sh(d))),!0):!1}}function Pds(s,t,n){if(!s||!s.editable)return!1;let r=s.state.doc.resolve(t);if(!sh.valid(r))return!1;let a=s.posAtCoords({left:n.clientX,top:n.clientY});return a&&a.inside>-1&&Li.isSelectable(s.state.doc.nodeAt(a.inside))?!1:(s.dispatch(s.state.tr.setSelection(new sh(r))),!0)}function Lds(s,t){if(t.inputType!="insertCompositionText"||!(s.state.selection instanceof sh))return!1;let{$from:n}=s.state.selection,r=n.parent.contentMatchAt(n.index()).findWrapping(s.state.schema.nodes.text);if(!r)return!1;let a=$r.empty;for(let l=r.length-1;l>=0;l--)a=$r.from(r[l].createAndFill(null,a));let i=s.state.tr.replace(n.pos,n.pos,new ba(a,0,0));return i.setSelection(Ui.near(i.doc.resolve(n.pos+1))),s.dispatch(i),!1}function Dds(s){if(!(s.selection instanceof sh))return null;let t=document.createElement("div");return t.className="ProseMirror-gapcursor",th.create(s.doc,[Kx.widget(s.selection.head,t,{key:"gapcursor"})])}const Rds=Nf.create({name:"gapCursor",addProseMirrorPlugins(){return[Mds()]},extendNodeSchema(s){var t;const n={name:s.name,options:s.options,storage:s.storage};return{allowGapCursor:(t=Wo(li(s,"allowGapCursor",n)))!==null&&t!==void 0?t:null}}}),Ods=lx.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",du(this.options.HTMLAttributes,s)]},renderText(){return` `},addCommands(){return{setHardBreak:()=>({commands:s,chain:t,state:n,editor:r})=>s.first([()=>s.exitCode(),()=>s.command(()=>{const{selection:a,storedMarks:i}=n;if(a.$from.parent.type.spec.isolating)return!1;const{keepMarks:l}=this.options,{splittableMarks:o}=r.extensionManager,c=i||a.$to.parentOffset&&a.$from.marks();return t().insertContent({type:this.name}).command(({tr:d,dispatch:u})=>{if(u&&c&&l){const h=c.filter(p=>o.includes(p.type.name));d.ensureMarks(h)}return!0}).run()})])}},addKeyboardShortcuts(){return{"Mod-Enter":()=>this.editor.commands.setHardBreak(),"Shift-Enter":()=>this.editor.commands.setHardBreak()}}}),Fds=lx.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]}`,du(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=>_Ce({find:new RegExp(`^(#{${Math.min(...this.options.levels)},${s}})\\s$`),type:this.type,getAttributes:{level:s}}))}});var Pfe=200,Tp=function(){};Tp.prototype.append=function(t){return t.length?(t=Tp.from(t),!this.length&&t||t.length=n?Tp.empty:this.sliceInner(Math.max(0,t),Math.min(this.length,n))};Tp.prototype.get=function(t){if(!(t<0||t>=this.length))return this.getInner(t)};Tp.prototype.forEach=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length),n<=r?this.forEachInner(t,n,r,0):this.forEachInvertedInner(t,n,r,0)};Tp.prototype.map=function(t,n,r){n===void 0&&(n=0),r===void 0&&(r=this.length);var a=[];return this.forEach(function(i,l){return a.push(t(i,l))},n,r),a};Tp.from=function(t){return t instanceof Tp?t:t&&t.length?new Kft(t):Tp.empty};var Kft=function(s){function t(r){s.call(this),this.values=r}s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t;var n={length:{configurable:!0},depth:{configurable:!0}};return t.prototype.flatten=function(){return this.values},t.prototype.sliceInner=function(a,i){return a==0&&i==this.length?this:new t(this.values.slice(a,i))},t.prototype.getInner=function(a){return this.values[a]},t.prototype.forEachInner=function(a,i,l,o){for(var c=i;c=l;c--)if(a(this.values[c],o+c)===!1)return!1},t.prototype.leafAppend=function(a){if(this.length+a.length<=Pfe)return new t(this.values.concat(a.flatten()))},t.prototype.leafPrepend=function(a){if(this.length+a.length<=Pfe)return new t(a.flatten().concat(this.values))},n.length.get=function(){return this.values.length},n.depth.get=function(){return 0},Object.defineProperties(t.prototype,n),t}(Tp);Tp.empty=new Kft([]);var zds=function(s){function t(n,r){s.call(this),this.left=n,this.right=r,this.length=n.length+r.length,this.depth=Math.max(n.depth,r.depth)+1}return s&&(t.__proto__=s),t.prototype=Object.create(s&&s.prototype),t.prototype.constructor=t,t.prototype.flatten=function(){return this.left.flatten().concat(this.right.flatten())},t.prototype.getInner=function(r){return ro&&this.right.forEachInner(r,Math.max(a-o,0),Math.min(this.length,i)-o,l+o)===!1)return!1},t.prototype.forEachInvertedInner=function(r,a,i,l){var o=this.left.length;if(a>o&&this.right.forEachInvertedInner(r,a-o,Math.max(i,o)-o,l+o)===!1||i=i?this.right.slice(r-i,a-i):this.left.slice(r,i).append(this.right.slice(0,a-i))},t.prototype.leafAppend=function(r){var a=this.right.leafAppend(r);if(a)return new t(this.left,a)},t.prototype.leafPrepend=function(r){var a=this.left.leafPrepend(r);if(a)return new t(a,this.right)},t.prototype.appendInner=function(r){return this.left.depth>=Math.max(this.right.depth,r.depth)+1?new t(this.left,new t(this.right,r)):new t(this,r)},t}(Tp);const Bds=500;class sb{constructor(t,n){this.items=t,this.eventCount=n}popEvent(t,n){if(this.eventCount==0)return null;let r=this.items.length;for(;;r--)if(this.items.get(r-1).selection){--r;break}let a,i;n&&(a=this.remapping(r,this.items.length),i=a.maps.length);let l=t.tr,o,c,d=[],u=[];return this.items.forEach((h,p)=>{if(!h.step){a||(a=this.remapping(r,p+1),i=a.maps.length),i--,u.push(h);return}if(a){u.push(new wk(h.map));let f=h.step.map(a.slice(i)),y;f&&l.maybeStep(f).doc&&(y=l.mapping.maps[l.mapping.maps.length-1],d.push(new wk(y,void 0,void 0,d.length+u.length))),i--,y&&a.appendMap(y,i)}else l.maybeStep(h.step);if(h.selection)return o=a?h.selection.map(a.slice(i)):h.selection,c=new sb(this.items.slice(0,r).append(u.reverse().concat(d)),this.eventCount-1),!1},this.items.length,0),{remaining:c,transform:l,selection:o}}addTransform(t,n,r,a){let i=[],l=this.eventCount,o=this.items,c=!a&&o.length?o.get(o.length-1):null;for(let u=0;uUds&&(o=$ds(o,d),l-=d),new sb(o.append(i),l)}remapping(t,n){let r=new dB;return this.items.forEach((a,i)=>{let l=a.mirrorOffset!=null&&i-a.mirrorOffset>=t?r.maps.length-a.mirrorOffset:void 0;r.appendMap(a.map,l)},t,n),r}addMaps(t){return this.eventCount==0?this:new sb(this.items.append(t.map(n=>new wk(n))),this.eventCount)}rebased(t,n){if(!this.eventCount)return this;let r=[],a=Math.max(0,this.items.length-n),i=t.mapping,l=t.steps.length,o=this.eventCount;this.items.forEach(p=>{p.selection&&o--},a);let c=n;this.items.forEach(p=>{let f=i.getMirror(--c);if(f==null)return;l=Math.min(l,f);let y=i.maps[f];if(p.step){let _=t.steps[f].invert(t.docs[f]),v=p.selection&&p.selection.map(i.slice(c+1,f));v&&o++,r.push(new wk(y,_,v))}else r.push(new wk(y))},a);let d=[];for(let p=n;pBds&&(h=h.compress(this.items.length-r.length)),h}emptyItemCount(){let t=0;return this.items.forEach(n=>{n.step||t++}),t}compress(t=this.items.length){let n=this.remapping(0,t),r=n.maps.length,a=[],i=0;return this.items.forEach((l,o)=>{if(o>=t)a.push(l),l.selection&&i++;else if(l.step){let c=l.step.map(n.slice(r)),d=c&&c.getMap();if(r--,d&&n.appendMap(d,r),c){let u=l.selection&&l.selection.map(n.slice(r));u&&i++;let h=new wk(d.invert(),c,u),p,f=a.length-1;(p=a.length&&a[f].merge(h))?a[f]=p:a.push(h)}}else l.map&&r--},this.items.length,0),new sb(Tp.from(a.reverse()),i)}}sb.empty=new sb(Tp.empty,0);function $ds(s,t){let n;return s.forEach((r,a)=>{if(r.selection&&t--==0)return n=a,!1}),s.slice(n)}let wk=class Yft{constructor(t,n,r,a){this.map=t,this.step=n,this.selection=r,this.mirrorOffset=a}merge(t){if(this.step&&t.step&&!t.selection){let n=t.step.merge(this.step);if(n)return new Yft(n.getMap().invert(),n,this.selection)}}};class Gk{constructor(t,n,r,a,i){this.done=t,this.undone=n,this.prevRanges=r,this.prevTime=a,this.prevComposition=i}}const Uds=20;function qds(s,t,n,r){let a=n.getMeta(VA),i;if(a)return a.historyState;n.getMeta(Gds)&&(s=new Gk(s.done,s.undone,null,0,-1));let l=n.getMeta("appendedTransaction");if(n.steps.length==0)return s;if(l&&l.getMeta(VA))return l.getMeta(VA).redo?new Gk(s.done.addTransform(n,void 0,r,Rme(t)),s.undone,Oqe(n.mapping.maps),s.prevTime,s.prevComposition):new Gk(s.done,s.undone.addTransform(n,void 0,r,Rme(t)),null,s.prevTime,s.prevComposition);if(n.getMeta("addToHistory")!==!1&&!(l&&l.getMeta("addToHistory")===!1)){let o=n.getMeta("composition"),c=s.prevTime==0||!l&&s.prevComposition!=o&&(s.prevTime<(n.time||0)-r.newGroupDelay||!Vds(n,s.prevRanges)),d=l?Hje(s.prevRanges,n.mapping):Oqe(n.mapping.maps);return new Gk(s.done.addTransform(n,c?t.selection.getBookmark():void 0,r,Rme(t)),sb.empty,d,n.time,o??s.prevComposition)}else return(i=n.getMeta("rebased"))?new Gk(s.done.rebased(n,i),s.undone.rebased(n,i),Hje(s.prevRanges,n.mapping),s.prevTime,s.prevComposition):new Gk(s.done.addMaps(n.mapping.maps),s.undone.addMaps(n.mapping.maps),Hje(s.prevRanges,n.mapping),s.prevTime,s.prevComposition)}function Vds(s,t){if(!t)return!1;if(!s.docChanged)return!0;let n=!1;return s.mapping.maps[0].forEach((r,a)=>{for(let i=0;i=t[i]&&(n=!0)}),n}function Oqe(s){let t=[];for(let n=s.length-1;n>=0&&t.length==0;n--)s[n].forEach((r,a,i,l)=>t.push(i,l));return t}function Hje(s,t){if(!s)return null;let n=[];for(let r=0;r{let a=VA.getState(n);if(!a||(s?a.undone:a.done).eventCount==0)return!1;if(r){let i=Hds(a,n,s);i&&r(t?i.scrollIntoView():i)}return!0}}const Qft=Zft(!1,!0),Xft=Zft(!0,!0),Kds=Nf.create({name:"history",addOptions(){return{depth:100,newGroupDelay:500}},addCommands(){return{undo:()=>({state:s,dispatch:t})=>Qft(s,t),redo:()=>({state:s,dispatch:t})=>Xft(s,t)}},addProseMirrorPlugins(){return[Wds(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()}}}),Yds=lx.create({name:"horizontalRule",addOptions(){return{HTMLAttributes:{}}},group:"block",parseHTML(){return[{tag:"hr"}]},renderHTML({HTMLAttributes:s}){return["hr",du(this.options.HTMLAttributes,s)]},addCommands(){return{setHorizontalRule:()=>({chain:s,state:t})=>{if(!Vcs(t,t.schema.nodes[this.name]))return!1;const{selection:n}=t,{$from:r,$to:a}=n,i=s();return r.parentOffset===0?i.insertContentAt({from:Math.max(r.pos-1,0),to:a.pos},{type:this.name}):hcs(n)?i.insertContentAt(a.pos,{type:this.name}):i.insertContent({type:this.name}),i.command(({tr:l,dispatch:o})=>{var c;if(o){const{$to:d}=l.selection,u=d.end();if(d.nodeAfter)d.nodeAfter.isTextblock?l.setSelection(Ui.create(l.doc,d.pos+1)):d.nodeAfter.isBlock?l.setSelection(Li.create(l.doc,d.pos)):l.setSelection(Ui.create(l.doc,d.pos));else{const h=(c=d.parent.type.contentMatch.defaultType)===null||c===void 0?void 0:c.create();h&&(l.insert(u,h),l.setSelection(Ui.create(l.doc,u+1)))}l.scrollIntoView()}return!0}).run()}}},addInputRules(){return[Vft({find:/^(?:---|—-|___\s|\*\*\*\s)$/,type:this.type})]}}),Zds=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))$/,Qds=/(?:^|\s)(\*(?!\s+\*)((?:[^*]+))\*(?!\s+\*))/g,Xds=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))$/,Jds=/(?:^|\s)(_(?!\s+_)((?:[^_]+))_(?!\s+_))/g,eus=kb.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",du(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[S8({find:Zds,type:this.type}),S8({find:Xds,type:this.type})]},addPasteRules(){return[bM({find:Qds,type:this.type}),bM({find:Jds,type:this.type})]}}),tus=lx.create({name:"listItem",addOptions(){return{HTMLAttributes:{},bulletListTypeName:"bulletList",orderedListTypeName:"orderedList"}},content:"paragraph block*",defining:!0,parseHTML(){return[{tag:"li"}]},renderHTML({HTMLAttributes:s}){return["li",du(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)}}}),sus="listItem",zqe="textStyle",Bqe=/^(\d+)\.\s$/,nus=lx.create({name:"orderedList",addOptions(){return{itemTypeName:"listItem",HTMLAttributes:{},keepMarks:!1,keepAttributes:!1}},group:"block list",content(){return`${this.options.itemTypeName}+`},addAttributes(){return{start:{default:1,parseHTML:s=>s.hasAttribute("start")?parseInt(s.getAttribute("start")||"",10):1},type:{default:null,parseHTML:s=>s.getAttribute("type")}}},parseHTML(){return[{tag:"ol"}]},renderHTML({HTMLAttributes:s}){const{start:t,...n}=s;return t===1?["ol",du(this.options.HTMLAttributes,n),0]:["ol",du(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(sus,this.editor.getAttributes(zqe)).run():s.toggleList(this.name,this.options.itemTypeName,this.options.keepMarks)}},addKeyboardShortcuts(){return{"Mod-Shift-7":()=>this.editor.commands.toggleOrderedList()}},addInputRules(){let s=gB({find:Bqe,type:this.type,getAttributes:t=>({start:+t[1]}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1]});return(this.options.keepMarks||this.options.keepAttributes)&&(s=gB({find:Bqe,type:this.type,keepMarks:this.options.keepMarks,keepAttributes:this.options.keepAttributes,getAttributes:t=>({start:+t[1],...this.editor.getAttributes(zqe)}),joinPredicate:(t,n)=>n.childCount+n.attrs.start===+t[1],editor:this.editor})),[s]}}),rus=lx.create({name:"paragraph",priority:1e3,addOptions(){return{HTMLAttributes:{}}},group:"block",content:"inline*",parseHTML(){return[{tag:"p"}]},renderHTML({HTMLAttributes:s}){return["p",du(this.options.HTMLAttributes,s),0]},addCommands(){return{setParagraph:()=>({commands:s})=>s.setNode(this.name)}},addKeyboardShortcuts(){return{"Mod-Alt-0":()=>this.editor.commands.setParagraph()}}}),aus=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))$/,ius=/(?:^|\s)(~~(?!\s+~~)((?:[^~]+))~~(?!\s+~~))/g,ous=kb.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",du(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[S8({find:aus,type:this.type})]},addPasteRules(){return[bM({find:ius,type:this.type})]}}),lus=lx.create({name:"text",group:"inline"}),I6e=Nf.create({name:"starterKit",addExtensions(){const s=[];return this.options.bold!==!1&&s.push(xds.configure(this.options.bold)),this.options.blockquote!==!1&&s.push(uds.configure(this.options.blockquote)),this.options.bulletList!==!1&&s.push(yds.configure(this.options.bulletList)),this.options.code!==!1&&s.push(_ds.configure(this.options.code)),this.options.codeBlock!==!1&&s.push(Nds.configure(this.options.codeBlock)),this.options.document!==!1&&s.push(kds.configure(this.options.document)),this.options.dropcursor!==!1&&s.push(Tds.configure(this.options.dropcursor)),this.options.gapcursor!==!1&&s.push(Rds.configure(this.options.gapcursor)),this.options.hardBreak!==!1&&s.push(Ods.configure(this.options.hardBreak)),this.options.heading!==!1&&s.push(Fds.configure(this.options.heading)),this.options.history!==!1&&s.push(Kds.configure(this.options.history)),this.options.horizontalRule!==!1&&s.push(Yds.configure(this.options.horizontalRule)),this.options.italic!==!1&&s.push(eus.configure(this.options.italic)),this.options.listItem!==!1&&s.push(tus.configure(this.options.listItem)),this.options.orderedList!==!1&&s.push(nus.configure(this.options.orderedList)),this.options.paragraph!==!1&&s.push(rus.configure(this.options.paragraph)),this.options.strike!==!1&&s.push(ous.configure(this.options.strike)),this.options.text!==!1&&s.push(lus.configure(this.options.text)),s}}),cus="aaa1rp3bb0ott3vie4c1le2ogado5udhabi7c0ademy5centure6ountant0s9o1tor4d0s1ult4e0g1ro2tna4f0l1rica5g0akhan5ency5i0g1rbus3force5tel5kdn3l0ibaba4pay4lfinanz6state5y2sace3tom5m0azon4ericanexpress7family11x2fam3ica3sterdam8nalytics7droid5quan4z2o0l2partments8p0le4q0uarelle8r0ab1mco4chi3my2pa2t0e3s0da2ia2sociates9t0hleta5torney7u0ction5di0ble3o3spost5thor3o0s4w0s2x0a2z0ure5ba0by2idu3namex4d1k2r0celona5laycard4s5efoot5gains6seball5ketball8uhaus5yern5b0c1t1va3cg1n2d1e0ats2uty4er2rlin4st0buy5t2f1g1h0arti5i0ble3d1ke2ng0o3o1z2j1lack0friday9ockbuster8g1omberg7ue3m0s1w2n0pparibas9o0ats3ehringer8fa2m1nd2o0k0ing5sch2tik2on4t1utique6x2r0adesco6idgestone9oadway5ker3ther5ussels7s1t1uild0ers6siness6y1zz3v1w1y1z0h3ca0b1fe2l0l1vinklein9m0era3p2non3petown5ital0one8r0avan4ds2e0er0s4s2sa1e1h1ino4t0ering5holic7ba1n1re3c1d1enter4o1rn3f0a1d2g1h0anel2nel4rity4se2t2eap3intai5ristmas6ome4urch5i0priani6rcle4sco3tadel4i0c2y3k1l0aims4eaning6ick2nic1que6othing5ud3ub0med6m1n1o0ach3des3ffee4llege4ogne5m0mbank4unity6pany2re3uter5sec4ndos3struction8ulting7tact3ractors9oking4l1p2rsica5untry4pon0s4rses6pa2r0edit0card4union9icket5own3s1uise0s6u0isinella9v1w1x1y0mru3ou3z2dad1nce3ta1e1ing3sun4y2clk3ds2e0al0er2s3gree4livery5l1oitte5ta3mocrat6ntal2ist5si0gn4v2hl2iamonds6et2gital5rect0ory7scount3ver5h2y2j1k1m1np2o0cs1tor4g1mains5t1wnload7rive4tv2ubai3nlop4pont4rban5vag2r2z2earth3t2c0o2deka3u0cation8e1g1mail3erck5nergy4gineer0ing9terprises10pson4quipment8r0icsson6ni3s0q1tate5t1u0rovision8s2vents5xchange6pert3osed4ress5traspace10fage2il1rwinds6th3mily4n0s2rm0ers5shion4t3edex3edback6rrari3ero6i0delity5o2lm2nal1nce1ial7re0stone6mdale6sh0ing5t0ness6j1k1lickr3ghts4r2orist4wers5y2m1o0o0d1tball6rd1ex2sale4um3undation8x2r0ee1senius7l1ogans4ntier7tr2ujitsu5n0d2rniture7tbol5yi3ga0l0lery3o1up4me0s3p1rden4y2b0iz3d0n2e0a1nt0ing5orge5f1g0ee3h1i0ft0s3ves2ing5l0ass3e1obal2o4m0ail3bh2o1x2n1odaddy5ld0point6f2o0dyear5g0le4p1t1v2p1q1r0ainger5phics5tis4een3ipe3ocery4up4s1t1u0cci3ge2ide2tars5ru3w1y2hair2mburg5ngout5us3bo2dfc0bank7ealth0care8lp1sinki6re1mes5iphop4samitsu7tachi5v2k0t2m1n1ockey4ldings5iday5medepot5goods5s0ense7nda3rse3spital5t0ing5t0els3mail5use3w2r1sbc3t1u0ghes5yatt3undai7ibm2cbc2e1u2d1e0ee3fm2kano4l1m0amat4db2mo0bilien9n0c1dustries8finiti5o2g1k1stitute6urance4e4t0ernational10uit4vestments10o1piranga7q1r0ish4s0maili5t0anbul7t0au2v3jaguar4va3cb2e0ep2tzt3welry6io2ll2m0p2nj2o0bs1urg4t1y2p0morgan6rs3uegos4niper7kaufen5ddi3e0rryhotels6properties14fh2g1h1i0a1ds2m1ndle4tchen5wi3m1n1oeln3matsu5sher5p0mg2n2r0d1ed3uokgroup8w1y0oto4z2la0caixa5mborghini8er3nd0rover6xess5salle5t0ino3robe5w0yer5b1c1ds2ease3clerc5frak4gal2o2xus4gbt3i0dl2fe0insurance9style7ghting6ke2lly3mited4o2ncoln4k2ve1ing5k1lc1p2oan0s3cker3us3l1ndon4tte1o3ve3pl0financial11r1s1t0d0a3u0ndbeck6xe1ury5v1y2ma0drid4if1son4keup4n0agement7go3p1rket0ing3s4riott5shalls7ttel5ba2c0kinsey7d1e0d0ia3et2lbourne7me1orial6n0u2rckmsd7g1h1iami3crosoft7l1ni1t2t0subishi9k1l0b1s2m0a2n1o0bi0le4da2e1i1m1nash3ey2ster5rmon3tgage6scow4to0rcycles9v0ie4p1q1r1s0d2t0n1r2u0seum3ic4v1w1x1y1z2na0b1goya4me2vy3ba2c1e0c1t0bank4flix4work5ustar5w0s2xt0direct7us4f0l2g0o2hk2i0co2ke1on3nja3ssan1y5l1o0kia3rton4w0ruz3tv4p1r0a1w2tt2u1yc2z2obi1server7ffice5kinawa6layan0group9lo3m0ega4ne1g1l0ine5oo2pen3racle3nge4g0anic5igins6saka4tsuka4t2vh3pa0ge2nasonic7ris2s1tners4s1y3y2ccw3e0t2f0izer5g1h0armacy6d1ilips5one2to0graphy6s4ysio5ics1tet2ures6d1n0g1k2oneer5zza4k1l0ace2y0station9umbing5s3m1n0c2ohl2ker3litie5rn2st3r0axi3ess3ime3o0d0uctions8f1gressive8mo2perties3y5tection8u0dential9s1t1ub2w0c2y2qa1pon3uebec3st5racing4dio4e0ad1lestate6tor2y4cipes5d0stone5umbrella9hab3ise0n3t2liance6n0t0als5pair3ort3ublican8st0aurant8view0s5xroth6ich0ardli6oh3l1o1p2o0cks3deo3gers4om3s0vp3u0gby3hr2n2w0e2yukyu6sa0arland6fe0ty4kura4le1on3msclub4ung5ndvik0coromant12ofi4p1rl2s1ve2xo3b0i1s2c0b1haeffler7midt4olarships8ol3ule3warz5ience5ot3d1e0arch3t2cure1ity6ek2lect4ner3rvices6ven3w1x0y3fr2g1h0angrila6rp3ell3ia1ksha5oes2p0ping5uji3w3i0lk2na1gles5te3j1k0i0n2y0pe4l0ing4m0art3ile4n0cf3o0ccer3ial4ftbank4ware6hu2lar2utions7ng1y2y2pa0ce3ort2t3r0l2s1t0ada2ples4r1tebank4farm7c0group6ockholm6rage3e3ream4udio2y3yle4u0cks3pplies3y2ort5rf1gery5zuki5v1watch4iss4x1y0dney4stems6z2tab1ipei4lk2obao4rget4tamotors6r2too4x0i3c0i2d0k2eam2ch0nology8l1masek5nnis4va3f1g1h0d1eater2re6iaa2ckets5enda4ps2res2ol4j0maxx4x2k0maxx5l1m0all4n1o0day3kyo3ols3p1ray3shiba5tal3urs3wn2yota3s3r0ade1ing4ining5vel0ers0insurance16ust3v2t1ube2i1nes3shu4v0s2w1z2ua1bank3s2g1k1nicom3versity8o2ol2ps2s1y1z2va0cations7na1guard7c1e0gas3ntures6risign5mögensberater2ung14sicherung10t2g1i0ajes4deo3g1king4llas4n1p1rgin4sa1ion4va1o3laanderen9n1odka3lvo3te1ing3o2yage5u2wales2mart4ter4ng0gou5tch0es6eather0channel12bcam3er2site5d0ding5ibo2r3f1hoswho6ien2ki2lliamhill9n0dows4e1ners6me2olterskluwer11odside6rk0s2ld3w2s1tc1f3xbox3erox4ihuan4n2xx2yz3yachts4hoo3maxun5ndex5e1odobashi7ga2kohama6u0tube6t1un3za0ppos4ra3ero3ip2m1one3uerich6w2",dus="ελ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",NCe="numeric",kCe="ascii",SCe="alpha",X9="asciinumeric",i7="alphanumeric",CCe="domain",Jft="emoji",uus="scheme",hus="slashscheme",Wje="whitespace";function mus(s,t){return s in t||(t[s]=[]),t[s]}function WE(s,t,n){t[NCe]&&(t[X9]=!0,t[i7]=!0),t[kCe]&&(t[X9]=!0,t[SCe]=!0),t[X9]&&(t[i7]=!0),t[SCe]&&(t[i7]=!0),t[i7]&&(t[CCe]=!0),t[Jft]&&(t[CCe]=!0);for(const r in t){const a=mus(r,n);a.indexOf(s)<0&&a.push(s)}}function pus(s,t){const n={};for(const r in t)t[r].indexOf(s)>=0&&(n[r]=!0);return n}function Ig(s=null){this.j={},this.jr=[],this.jd=null,this.t=s}Ig.groups={};Ig.prototype={accepts(){return!!this.t},go(s){const t=this,n=t.j[s];if(n)return n;for(let r=0;rs.ta(t,n,r,a),Wu=(s,t,n,r,a)=>s.tr(t,n,r,a),$qe=(s,t,n,r,a)=>s.ts(t,n,r,a),Hr=(s,t,n,r,a)=>s.tt(t,n,r,a),m2="WORD",TCe="UWORD",ext="ASCIINUMERICAL",txt="ALPHANUMERICAL",yB="LOCALHOST",ECe="TLD",ACe="UTLD",Ome="SCHEME",rP="SLASH_SCHEME",P6e="NUM",MCe="WS",L6e="NL",J9="OPENBRACE",ez="CLOSEBRACE",Lfe="OPENBRACKET",Dfe="CLOSEBRACKET",Rfe="OPENPAREN",Ofe="CLOSEPAREN",Ffe="OPENANGLEBRACKET",zfe="CLOSEANGLEBRACKET",Bfe="FULLWIDTHLEFTPAREN",$fe="FULLWIDTHRIGHTPAREN",Ufe="LEFTCORNERBRACKET",qfe="RIGHTCORNERBRACKET",Vfe="LEFTWHITECORNERBRACKET",Hfe="RIGHTWHITECORNERBRACKET",Gfe="FULLWIDTHLESSTHAN",Wfe="FULLWIDTHGREATERTHAN",Kfe="AMPERSAND",Yfe="APOSTROPHE",Zfe="ASTERISK",Wk="AT",Qfe="BACKSLASH",Xfe="BACKTICK",Jfe="CARET",iS="COLON",D6e="COMMA",exe="DOLLAR",R_="DOT",txe="EQUALS",R6e="EXCLAMATION",hv="HYPHEN",tz="PERCENT",sxe="PIPE",nxe="PLUS",rxe="POUND",sz="QUERY",O6e="QUOTE",sxt="FULLWIDTHMIDDLEDOT",F6e="SEMI",O_="SLASH",nz="TILDE",axe="UNDERSCORE",nxt="EMOJI",ixe="SYM";var rxt=Object.freeze({__proto__:null,ALPHANUMERICAL:txt,AMPERSAND:Kfe,APOSTROPHE:Yfe,ASCIINUMERICAL:ext,ASTERISK:Zfe,AT:Wk,BACKSLASH:Qfe,BACKTICK:Xfe,CARET:Jfe,CLOSEANGLEBRACKET:zfe,CLOSEBRACE:ez,CLOSEBRACKET:Dfe,CLOSEPAREN:Ofe,COLON:iS,COMMA:D6e,DOLLAR:exe,DOT:R_,EMOJI:nxt,EQUALS:txe,EXCLAMATION:R6e,FULLWIDTHGREATERTHAN:Wfe,FULLWIDTHLEFTPAREN:Bfe,FULLWIDTHLESSTHAN:Gfe,FULLWIDTHMIDDLEDOT:sxt,FULLWIDTHRIGHTPAREN:$fe,HYPHEN:hv,LEFTCORNERBRACKET:Ufe,LEFTWHITECORNERBRACKET:Vfe,LOCALHOST:yB,NL:L6e,NUM:P6e,OPENANGLEBRACKET:Ffe,OPENBRACE:J9,OPENBRACKET:Lfe,OPENPAREN:Rfe,PERCENT:tz,PIPE:sxe,PLUS:nxe,POUND:rxe,QUERY:sz,QUOTE:O6e,RIGHTCORNERBRACKET:qfe,RIGHTWHITECORNERBRACKET:Hfe,SCHEME:Ome,SEMI:F6e,SLASH:O_,SLASH_SCHEME:rP,SYM:ixe,TILDE:nz,TLD:ECe,UNDERSCORE:axe,UTLD:ACe,UWORD:TCe,WORD:m2,WS:MCe});const s2=/[a-z]/,lF=new RegExp("\\p{L}","u"),Kje=new RegExp("\\p{Emoji}","u"),n2=/\d/,Yje=/\s/,Uqe="\r",Zje=` `,fus="️",xus="‍",Qje="";let mH=null,pH=null;function gus(s=[]){const t={};Ig.groups=t;const n=new Ig;mH==null&&(mH=qqe(cus)),pH==null&&(pH=qqe(dus)),Hr(n,"'",Yfe),Hr(n,"{",J9),Hr(n,"}",ez),Hr(n,"[",Lfe),Hr(n,"]",Dfe),Hr(n,"(",Rfe),Hr(n,")",Ofe),Hr(n,"<",Ffe),Hr(n,">",zfe),Hr(n,"(",Bfe),Hr(n,")",$fe),Hr(n,"「",Ufe),Hr(n,"」",qfe),Hr(n,"『",Vfe),Hr(n,"』",Hfe),Hr(n,"<",Gfe),Hr(n,">",Wfe),Hr(n,"&",Kfe),Hr(n,"*",Zfe),Hr(n,"@",Wk),Hr(n,"`",Xfe),Hr(n,"^",Jfe),Hr(n,":",iS),Hr(n,",",D6e),Hr(n,"$",exe),Hr(n,".",R_),Hr(n,"=",txe),Hr(n,"!",R6e),Hr(n,"-",hv),Hr(n,"%",tz),Hr(n,"|",sxe),Hr(n,"+",nxe),Hr(n,"#",rxe),Hr(n,"?",sz),Hr(n,'"',O6e),Hr(n,"/",O_),Hr(n,";",F6e),Hr(n,"~",nz),Hr(n,"_",axe),Hr(n,"\\",Qfe),Hr(n,"・",sxt);const r=Wu(n,n2,P6e,{[NCe]:!0});Wu(r,n2,r);const a=Wu(r,s2,ext,{[X9]:!0}),i=Wu(r,lF,txt,{[i7]:!0}),l=Wu(n,s2,m2,{[kCe]:!0});Wu(l,n2,a),Wu(l,s2,l),Wu(a,n2,a),Wu(a,s2,a);const o=Wu(n,lF,TCe,{[SCe]:!0});Wu(o,s2),Wu(o,n2,i),Wu(o,lF,o),Wu(i,n2,i),Wu(i,s2),Wu(i,lF,i);const c=Hr(n,Zje,L6e,{[Wje]:!0}),d=Hr(n,Uqe,MCe,{[Wje]:!0}),u=Wu(n,Yje,MCe,{[Wje]:!0});Hr(n,Qje,u),Hr(d,Zje,c),Hr(d,Qje,u),Wu(d,Yje,u),Hr(u,Uqe),Hr(u,Zje),Wu(u,Yje,u),Hr(u,Qje,u);const h=Wu(n,Kje,nxt,{[Jft]:!0});Hr(h,"#"),Wu(h,Kje,h),Hr(h,fus,h);const p=Hr(h,xus);Hr(p,"#"),Wu(p,Kje,h);const f=[[s2,l],[n2,a]],y=[[s2,null],[lF,o],[n2,i]];for(let _=0;__[0]>v[0]?1:-1);for(let _=0;_=0?w[CCe]=!0:s2.test(v)?n2.test(v)?w[X9]=!0:w[kCe]=!0:w[NCe]=!0,$qe(n,v,v,w)}return $qe(n,"localhost",yB,{ascii:!0}),n.jd=new Ig(ixe),{start:n,tokens:Object.assign({groups:t},rxt)}}function axt(s,t){const n=yus(t.replace(/[A-Z]/g,o=>o.toLowerCase())),r=n.length,a=[];let i=0,l=0;for(;l=0&&(h+=n[l].length,p++),d+=n[l].length,i+=n[l].length,l++;i-=h,l-=p,d-=h,a.push({t:u.t,v:t.slice(i-d,i),s:i-d,e:i})}return a}function yus(s){const t=[],n=s.length;let r=0;for(;r56319||r+1===n||(i=s.charCodeAt(r+1))<56320||i>57343?s[r]:s.slice(r,r+2);t.push(l),r+=l.length}return t}function jk(s,t,n,r,a){let i;const l=t.length;for(let o=0;o=0;)i++;if(i>0){t.push(n.join(""));for(let l=parseInt(s.substring(r,r+i),10);l>0;l--)n.pop();r+=i}else n.push(s[r]),r++}return t}const vB={defaultProtocol:"http",events:null,format:Vqe,formatHref:Vqe,nl2br:!1,tagName:"a",target:null,rel:null,validate:!0,truncate:1/0,className:null,attributes:null,ignoreTags:[],render:null};function z6e(s,t=null){let n=Object.assign({},vB);s&&(n=Object.assign(n,s instanceof z6e?s.o:s));const r=n.ignoreTags,a=[];for(let i=0;in?r.substring(0,n)+"…":r},toFormattedHref(s){return s.get("formatHref",this.toHref(s.get("defaultProtocol")),this)},startIndex(){return this.tk[0].s},endIndex(){return this.tk[this.tk.length-1].e},toObject(s=vB.defaultProtocol){return{type:this.t,value:this.toString(),isLink:this.isLink,href:this.toHref(s),start:this.startIndex(),end:this.endIndex()}},toFormattedObject(s){return{type:this.t,value:this.toFormattedString(s),isLink:this.isLink,href:this.toFormattedHref(s),start:this.startIndex(),end:this.endIndex()}},validate(s){return s.get("validate",this.toString(),this)},render(s){const t=this,n=this.toHref(s.get("defaultProtocol")),r=s.get("formatHref",n,this),a=s.get("tagName",n,t),i=this.toFormattedString(s),l={},o=s.get("className",n,t),c=s.get("target",n,t),d=s.get("rel",n,t),u=s.getObj("attributes",n,t),h=s.getObj("events",n,t);return l.href=r,o&&(l.class=o),c&&(l.target=c),d&&(l.rel=d),u&&Object.assign(l,u),{tagName:a,attributes:l,content:i,eventListeners:h}}};function Hye(s,t){class n extends ixt{constructor(a,i){super(a,i),this.t=s}}for(const r in t)n.prototype[r]=t[r];return n.t=s,n}const Hqe=Hye("email",{isLink:!0,toHref(){return"mailto:"+this.toString()}}),Gqe=Hye("text"),vus=Hye("nl"),fH=Hye("url",{isLink:!0,toHref(s=vB.defaultProtocol){return this.hasProtocol()?this.v:`${s}://${this.v}`},hasProtocol(){const s=this.tk;return s.length>=2&&s[0].t!==yB&&s[1].t===iS}}),sv=s=>new Ig(s);function bus({groups:s}){const t=s.domain.concat([Kfe,Zfe,Wk,Qfe,Xfe,Jfe,exe,txe,hv,P6e,tz,sxe,nxe,rxe,O_,ixe,nz,axe]),n=[Yfe,iS,D6e,R_,R6e,tz,sz,O6e,F6e,Ffe,zfe,J9,ez,Dfe,Lfe,Rfe,Ofe,Bfe,$fe,Ufe,qfe,Vfe,Hfe,Gfe,Wfe],r=[Kfe,Yfe,Zfe,Qfe,Xfe,Jfe,exe,txe,hv,J9,ez,tz,sxe,nxe,rxe,sz,O_,ixe,nz,axe],a=sv(),i=Hr(a,nz);Go(i,r,i),Go(i,s.domain,i);const l=sv(),o=sv(),c=sv();Go(a,s.domain,l),Go(a,s.scheme,o),Go(a,s.slashscheme,c),Go(l,r,i),Go(l,s.domain,l);const d=Hr(l,Wk);Hr(i,Wk,d),Hr(o,Wk,d),Hr(c,Wk,d);const u=Hr(i,R_);Go(u,r,i),Go(u,s.domain,i);const h=sv();Go(d,s.domain,h),Go(h,s.domain,h);const p=Hr(h,R_);Go(p,s.domain,h);const f=sv(Hqe);Go(p,s.tld,f),Go(p,s.utld,f),Hr(d,yB,f);const y=Hr(h,hv);Hr(y,hv,y),Go(y,s.domain,h),Go(f,s.domain,h),Hr(f,R_,p),Hr(f,hv,y);const _=Hr(f,iS);Go(_,s.numeric,Hqe);const v=Hr(l,hv),j=Hr(l,R_);Hr(v,hv,v),Go(v,s.domain,l),Go(j,r,i),Go(j,s.domain,l);const w=sv(fH);Go(j,s.tld,w),Go(j,s.utld,w),Go(w,s.domain,l),Go(w,r,i),Hr(w,R_,j),Hr(w,hv,v),Hr(w,Wk,d);const S=Hr(w,iS),A=sv(fH);Go(S,s.numeric,A);const E=sv(fH),O=sv();Go(E,t,E),Go(E,n,O),Go(O,t,E),Go(O,n,O),Hr(w,O_,E),Hr(A,O_,E);const D=Hr(o,iS),I=Hr(c,iS),F=Hr(I,O_),z=Hr(F,O_);Go(o,s.domain,l),Hr(o,R_,j),Hr(o,hv,v),Go(c,s.domain,l),Hr(c,R_,j),Hr(c,hv,v),Go(D,s.domain,E),Hr(D,O_,E),Hr(D,sz,E),Go(z,s.domain,E),Go(z,t,E),Hr(z,O_,E);const H=[[J9,ez],[Lfe,Dfe],[Rfe,Ofe],[Ffe,zfe],[Bfe,$fe],[Ufe,qfe],[Vfe,Hfe],[Gfe,Wfe]];for(let Z=0;Z=0&&p++,a++,u++;if(p<0)a-=u,a0&&(i.push(Xje(Gqe,t,l)),l=[]),a-=p,u-=p;const f=h.t,y=n.slice(a-u,a);i.push(Xje(f,t,y))}}return l.length>0&&i.push(Xje(Gqe,t,l)),i}function Xje(s,t,n){const r=n[0].s,a=n[n.length-1].e,i=t.slice(r,a);return new s(i,n)}const wus=typeof console<"u"&&console&&console.warn||(()=>{}),jus="until manual call of linkify.init(). Register all schemes and plugins before invoking linkify the first time.",Pd={scanner:null,parser:null,tokenQueue:[],pluginQueue:[],customSchemes:[],initialized:!1};function Nus(){return Ig.groups={},Pd.scanner=null,Pd.parser=null,Pd.tokenQueue=[],Pd.pluginQueue=[],Pd.customSchemes=[],Pd.initialized=!1,Pd}function Wqe(s,t=!1){if(Pd.initialized&&wus(`linkifyjs: already initialized - will not register custom scheme "${s}" ${jus}`),!/^[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`);Pd.customSchemes.push([s,t])}function kus(){Pd.scanner=gus(Pd.customSchemes);for(let s=0;s{const a=t.some(d=>d.docChanged)&&!n.doc.eq(r.doc),i=t.some(d=>d.getMeta("preventAutolink"));if(!a||i)return;const{tr:l}=r,o=ncs(n.doc,[...t]);if(dcs(o).forEach(({newRange:d})=>{const u=acs(r.doc,d,f=>f.isTextblock);let h,p;if(u.length>1)h=u[0],p=r.doc.textBetween(h.pos,h.pos+h.node.nodeSize,void 0," ");else if(u.length){const f=r.doc.textBetween(d.from,d.to," "," ");if(!Cus.test(f))return;h=u[0],p=r.doc.textBetween(h.pos,d.to,void 0," ")}if(h&&p){const f=p.split(Sus).filter(Boolean);if(f.length<=0)return!1;const y=f[f.length-1],_=h.pos+p.lastIndexOf(y);if(!y)return!1;const v=B6e(y).map(j=>j.toObject(s.defaultProtocol));if(!Eus(v))return!1;v.filter(j=>j.isLink).map(j=>({...j,from:_+j.start+1,to:_+j.end+1})).filter(j=>r.schema.marks.code?!r.doc.rangeHasMark(j.from,j.to,r.schema.marks.code):!0).filter(j=>s.validate(j.value)).filter(j=>s.shouldAutoLink(j.value)).forEach(j=>{k6e(j.from,j.to,r.doc).some(w=>w.mark.type===s.type)||l.addMark(j.from,j.to,s.type.create({href:j.href}))})}}),!!l.steps.length)return l}})}function Mus(s){return new Gm({key:new ox("handleClickLink"),props:{handleClick:(t,n,r)=>{var a,i;if(r.button!==0||!t.editable)return!1;let l=r.target;const o=[];for(;l.nodeName!=="DIV";)o.push(l),l=l.parentNode;if(!o.find(p=>p.nodeName==="A"))return!1;const c=qft(t.state,s.type.name),d=r.target,u=(a=d==null?void 0:d.href)!==null&&a!==void 0?a:c.href,h=(i=d==null?void 0:d.target)!==null&&i!==void 0?i:c.target;return d&&u?(window.open(u,h),!0):!1}}})}function Ius(s){return new Gm({key:new ox("handlePasteLink"),props:{handlePaste:(t,n,r)=>{const{state:a}=t,{selection:i}=a,{empty:l}=i;if(l)return!1;let o="";r.content.forEach(d=>{o+=d.textContent});const c=oxt(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 n3(s,t){const n=["http","https","ftp","ftps","mailto","tel","callto","sms","cid","xmpp"];return t&&t.forEach(r=>{const a=typeof r=="string"?r:r.scheme;a&&n.push(a)}),!s||s.replace(Tus,"").match(new RegExp(`^(?:(?:${n.join("|")}):|[^a-z]|[a-z0-9+.-]+(?:[^a-z+.-:]|$))`,"i"))}const U6e=kb.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"){Wqe(s);return}Wqe(s.scheme,s.optionalSlashes)})},onDestroy(){Nus()},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)=>!!n3(s,t.protocols),validate:s=>!!s,shouldAutoLink:s=>!!s}},addAttributes(){return{href:{default:null,parseHTML(s){return s.getAttribute("href")}},target:{default:this.options.HTMLAttributes.target},rel:{default:this.options.HTMLAttributes.rel},class:{default:this.options.HTMLAttributes.class}}},parseHTML(){return[{tag:"a[href]",getAttrs:s=>{const t=s.getAttribute("href");return!t||!this.options.isAllowedUri(t,{defaultValidate:n=>!!n3(n,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?!1:null}}]},renderHTML({HTMLAttributes:s}){return this.options.isAllowedUri(s.href,{defaultValidate:t=>!!n3(t,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?["a",du(this.options.HTMLAttributes,s),0]:["a",du(this.options.HTMLAttributes,{...s,href:""}),0]},addCommands(){return{setLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!n3(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().setMark(this.name,s).setMeta("preventAutolink",!0).run():!1},toggleLink:s=>({chain:t})=>{const{href:n}=s;return this.options.isAllowedUri(n,{defaultValidate:r=>!!n3(r,this.options.protocols),protocols:this.options.protocols,defaultProtocol:this.options.defaultProtocol})?t().toggleMark(this.name,s,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run():!1},unsetLink:()=>({chain:s})=>s().unsetMark(this.name,{extendEmptyMarkRange:!0}).setMeta("preventAutolink",!0).run()}},addPasteRules(){return[bM({find:s=>{const t=[];if(s){const{protocols:n,defaultProtocol:r}=this.options,a=oxt(s).filter(i=>i.isLink&&this.options.isAllowedUri(i.value,{defaultValidate:l=>!!n3(l,n),protocols:n,defaultProtocol:r}));a.length&&a.forEach(i=>t.push({text:i.value,data:{href:i.href},index:i.start}))}return t},type:this.type,getAttributes:s=>{var t;return{href:(t=s.data)===null||t===void 0?void 0:t.href}}})]},addProseMirrorPlugins(){const s=[],{protocols:t,defaultProtocol:n}=this.options;return this.options.autolink&&s.push(Aus({type:this.type,defaultProtocol:this.options.defaultProtocol,validate:r=>this.options.isAllowedUri(r,{defaultValidate:a=>!!n3(a,t),protocols:t,defaultProtocol:n}),shouldAutoLink:this.options.shouldAutoLink})),this.options.openOnClick===!0&&s.push(Mus({type:this.type})),this.options.linkOnPaste&&s.push(Ius({editor:this.editor,defaultProtocol:this.options.defaultProtocol,type:this.type})),s}}),q6e=Nf.create({name:"textAlign",addOptions(){return{types:[],alignments:["left","center","right","justify"],defaultAlignment:null}},addGlobalAttributes(){return[{types:this.options.types,attributes:{textAlign:{default:this.options.defaultAlignment,parseHTML:s=>{const t=s.style.textAlign;return this.options.alignments.includes(t)?t:this.options.defaultAlignment},renderHTML:s=>s.textAlign?{style:`text-align: ${s.textAlign}`}:{}}}}]},addCommands(){return{setTextAlign:s=>({commands:t})=>this.options.alignments.includes(s)?this.options.types.map(n=>t.updateAttributes(n,{textAlign:s})).every(n=>n):!1,unsetTextAlign:()=>({commands:s})=>this.options.types.map(t=>s.resetAttributes(t,"textAlign")).every(t=>t),toggleTextAlign:s=>({editor:t,commands:n})=>this.options.alignments.includes(s)?t.isActive({textAlign:s})?n.unsetTextAlign():n.setTextAlign(s):!1}},addKeyboardShortcuts(){return{"Mod-Shift-l":()=>this.editor.commands.setTextAlign("left"),"Mod-Shift-e":()=>this.editor.commands.setTextAlign("center"),"Mod-Shift-r":()=>this.editor.commands.setTextAlign("right"),"Mod-Shift-j":()=>this.editor.commands.setTextAlign("justify")}}}),Pus=s=>{if(!s.children.length)return;const t=s.querySelectorAll("span");t&&t.forEach(n=>{var r,a;const i=n.getAttribute("style"),l=(a=(r=n.parentElement)===null||r===void 0?void 0:r.closest("span"))===null||a===void 0?void 0:a.getAttribute("style");n.setAttribute("style",`${l};${i}`)})},V6e=kb.create({name:"textStyle",priority:101,addOptions(){return{HTMLAttributes:{},mergeNestedSpanStyles:!1}},parseHTML(){return[{tag:"span",getAttrs:s=>s.hasAttribute("style")?(this.options.mergeNestedSpanStyles&&Pus(s),{}):!1}]},renderHTML({HTMLAttributes:s}){return["span",du(this.options.HTMLAttributes,s),0]},addCommands(){return{removeEmptyTextStyle:()=>({tr:s})=>{const{selection:t}=s;return s.doc.nodesBetween(t.from,t.to,(n,r)=>{if(n.isTextblock)return!0;n.marks.filter(a=>a.type===this.type).some(a=>Object.values(a.attrs).some(i=>!!i))||s.removeMark(r,r+n.nodeSize,this.type)}),!0}}}}),Lus=/(?:^|\s)(!\[(.+|:?)]\((\S+)(?:(?:\s+)["'](\S+)["'])?\))$/,Dus=lx.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",du(this.options.HTMLAttributes,s)]},addCommands(){return{setImage:s=>({commands:t})=>t.insertContent({type:this.name,attrs:s})}},addInputRules(){return[Vft({find:Lus,type:this.type,getAttributes:s=>{const[,,t,n,r]=s;return{src:n,alt:t,title:r}}})]}});let ICe,PCe;if(typeof WeakMap<"u"){let s=new WeakMap;ICe=t=>s.get(t),PCe=(t,n)=>(s.set(t,n),n)}else{const s=[];let n=0;ICe=r=>{for(let a=0;a(n==10&&(n=0),s[n++]=r,s[n++]=a)}var nh=class{constructor(s,t,n,r){this.width=s,this.height=t,this.map=n,this.problems=r}findCell(s){for(let t=0;t=n){(i||(i=[])).push({type:"overlong_rowspan",pos:u,n:j-S});break}const A=a+S*t;for(let E=0;Er&&(i+=d.attrs.colspan)}}for(let l=0;l1&&(n=!0)}t==-1?t=i:t!=i&&(t=Math.max(t,i))}return t}function Fus(s,t,n){s.problems||(s.problems=[]);const r={};for(let a=0;a0;t--)if(s.node(t).type.spec.tableRole=="row")return s.node(0).resolve(s.before(t+1));return null}function Bus(s){for(let t=s.depth;t>0;t--){const n=s.node(t).type.spec.tableRole;if(n==="cell"||n==="header_cell")return s.node(t)}return null}function Eb(s){const t=s.selection.$head;for(let n=t.depth;n>0;n--)if(t.node(n).type.spec.tableRole=="row")return!0;return!1}function Gye(s){const t=s.selection;if("$anchorCell"in t&&t.$anchorCell)return t.$anchorCell.pos>t.$headCell.pos?t.$anchorCell:t.$headCell;if("node"in t&&t.node&&t.node.type.spec.tableRole=="cell")return t.$anchor;const n=_M(t.$head)||$us(t.$head);if(n)return n;throw new RangeError(`No cell found around position ${t.head}`)}function $us(s){for(let t=s.nodeAfter,n=s.pos;t;t=t.firstChild,n++){const r=t.type.spec.tableRole;if(r=="cell"||r=="header_cell")return s.doc.resolve(n)}for(let t=s.nodeBefore,n=s.pos;t;t=t.lastChild,n--){const r=t.type.spec.tableRole;if(r=="cell"||r=="header_cell")return s.doc.resolve(n-t.nodeSize)}}function LCe(s){return s.parent.type.spec.tableRole=="row"&&!!s.nodeAfter}function Uus(s){return s.node(0).resolve(s.pos+s.nodeAfter.nodeSize)}function H6e(s,t){return s.depth==t.depth&&s.pos>=t.start(-1)&&s.pos<=t.end(-1)}function lxt(s,t,n){const r=s.node(-1),a=nh.get(r),i=s.start(-1),l=a.nextCell(s.pos-i,t,n);return l==null?null:s.node(0).resolve(i+l)}function wM(s,t,n=1){const r={...s,colspan:s.colspan-n};return r.colwidth&&(r.colwidth=r.colwidth.slice(),r.colwidth.splice(t,n),r.colwidth.some(a=>a>0)||(r.colwidth=null)),r}function cxt(s,t,n=1){const r={...s,colspan:s.colspan+n};if(r.colwidth){r.colwidth=r.colwidth.slice();for(let a=0;au!=n.pos-i);c.unshift(n.pos-i);const d=c.map(u=>{const h=r.nodeAt(u);if(!h)throw new RangeError(`No cell with offset ${u} found`);const p=i+u+1;return new Upt(o.resolve(p),o.resolve(p+h.content.size))});super(d[0].$from,d[0].$to,d),this.$anchorCell=t,this.$headCell=n}map(t,n){const r=t.resolve(n.map(this.$anchorCell.pos)),a=t.resolve(n.map(this.$headCell.pos));if(LCe(r)&&LCe(a)&&H6e(r,a)){const i=this.$anchorCell.node(-1)!=r.node(-1);return i&&this.isRowSelection()?p2.rowSelection(r,a):i&&this.isColSelection()?p2.colSelection(r,a):new p2(r,a)}return Ui.between(r,a)}content(){const t=this.$anchorCell.node(-1),n=nh.get(t),r=this.$anchorCell.start(-1),a=n.rectBetween(this.$anchorCell.pos-r,this.$headCell.pos-r),i={},l=[];for(let c=a.top;c0||v>0){let j=y.attrs;if(_>0&&(j=wM(j,0,_)),v>0&&(j=wM(j,j.colspan-v,v)),f.lefta.bottom){const j={...y.attrs,rowspan:Math.min(f.bottom,a.bottom)-Math.max(f.top,a.top)};f.top0)return!1;const r=t+this.$anchorCell.nodeAfter.attrs.rowspan,a=n+this.$headCell.nodeAfter.attrs.rowspan;return Math.max(r,a)==this.$headCell.node(-1).childCount}static colSelection(t,n=t){const r=t.node(-1),a=nh.get(r),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(n.pos-i),c=t.node(0);return l.top<=o.top?(l.top>0&&(t=c.resolve(i+a.map[l.left])),o.bottom0&&(n=c.resolve(i+a.map[o.left])),l.bottom0)return!1;const l=a+this.$anchorCell.nodeAfter.attrs.colspan,o=i+this.$headCell.nodeAfter.attrs.colspan;return Math.max(l,o)==n.width}eq(t){return t instanceof p2&&t.$anchorCell.pos==this.$anchorCell.pos&&t.$headCell.pos==this.$headCell.pos}static rowSelection(t,n=t){const r=t.node(-1),a=nh.get(r),i=t.start(-1),l=a.findCell(t.pos-i),o=a.findCell(n.pos-i),c=t.node(0);return l.left<=o.left?(l.left>0&&(t=c.resolve(i+a.map[l.top*a.width])),o.right0&&(n=c.resolve(i+a.map[o.top*a.width])),l.right{t.push(Kx.node(r,r+n.nodeSize,{class:"selectedCell"}))}),th.create(s.doc,t)}function Gus({$from:s,$to:t}){if(s.pos==t.pos||s.pos=0&&!(s.after(a+1)=0&&!(t.before(i+1)>t.start(i));i--,r--);return n==r&&/row|table/.test(s.node(a).type.spec.tableRole)}function Wus({$from:s,$to:t}){let n,r;for(let a=s.depth;a>0;a--){const i=s.node(a);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){n=i;break}}for(let a=t.depth;a>0;a--){const i=t.node(a);if(i.type.spec.tableRole==="cell"||i.type.spec.tableRole==="header_cell"){r=i;break}}return n!==r&&t.parentOffset===0}function Kus(s,t,n){const r=(t||s).selection,a=(t||s).doc;let i,l;if(r instanceof Li&&(l=r.node.type.spec.tableRole)){if(l=="cell"||l=="header_cell")i=bd.create(a,r.from);else if(l=="row"){const o=a.resolve(r.from+1);i=bd.rowSelection(o,o)}else if(!n){const o=nh.get(r.node),c=r.from+1,d=c+o.map[o.width*o.height-1];i=bd.create(a,c+1,d)}}else r instanceof Ui&&Gus(r)?i=Ui.create(a,r.from):r instanceof Ui&&Wus(r)&&(i=Ui.create(a,r.$from.start(),r.$from.end()));return i&&(t||(t=s.tr)).setSelection(i),t}const Yus=new ox("fix-tables");function uxt(s,t,n,r){const a=s.childCount,i=t.childCount;e:for(let l=0,o=0;l{a.type.spec.tableRole=="table"&&(n=Zus(s,a,i,n))};return t?t.doc!=s.doc&&uxt(t.doc,s.doc,0,r):s.doc.descendants(r),n}function Zus(s,t,n,r){const a=nh.get(t);if(!a.problems)return r;r||(r=s.tr);const i=[];for(let c=0;c0){let f="cell";u.firstChild&&(f=u.firstChild.type.spec.tableRole);const y=[];for(let v=0;v0?-1:0;qus(t,r,a+i)&&(i=a==0||a==t.width?null:0);for(let l=0;l0&&a0&&t.map[o-1]==c||a0?-1:0;ths(t,r,a+o)&&(o=a==0||a==t.height?null:0);for(let d=0,u=t.width*a;d0&&a0&&h==t.map[u-t.width]){const p=n.nodeAt(h).attrs;s.setNodeMarkup(s.mapping.slice(o).map(h+r),null,{...p,rowspan:p.rowspan-1}),d+=p.colspan-1}else if(a0&&n[i]==n[i-1]||r.right0&&n[a]==n[a-s]||r.bottom0){const u=c+1+d.content.size,h=Kqe(d)?c+1:u;i.replaceWith(h+r.tableStart,u+r.tableStart,o)}i.setSelection(new bd(i.doc.resolve(c+r.tableStart))),t(i)}return!0}function Zqe(s,t){const n=rx(s.schema);return ohs(({node:r})=>n[r.type.spec.tableRole])(s,t)}function ohs(s){return(t,n)=>{const r=t.selection;let a,i;if(r instanceof bd){if(r.$anchorCell.pos!=r.$headCell.pos)return!1;a=r.$anchorCell.nodeAfter,i=r.$anchorCell.pos}else{var l;if(a=Bus(r.$from),!a)return!1;i=(l=_M(r.$from))===null||l===void 0?void 0:l.pos}if(a==null||i==null||a.attrs.colspan==1&&a.attrs.rowspan==1)return!1;if(n){let o=a.attrs;const c=[],d=o.colwidth;o.rowspan>1&&(o={...o,rowspan:1}),o.colspan>1&&(o={...o,colspan:1});const u=Kw(t),h=t.tr;for(let f=0;f{l.attrs[s]!==t&&i.setNodeMarkup(o,null,{...l.attrs,[s]:t})}):i.setNodeMarkup(a.pos,null,{...a.nodeAfter.attrs,[s]:t}),r(i)}return!0}}function chs(s){return function(t,n){if(!Eb(t))return!1;if(n){const r=rx(t.schema),a=Kw(t),i=t.tr,l=a.map.cellsInRect(s=="column"?{left:a.left,top:0,right:a.right,bottom:a.map.height}:s=="row"?{left:0,top:a.top,right:a.map.width,bottom:a.bottom}:a),o=l.map(c=>a.table.nodeAt(c));for(let c=0;c{const f=p+i.tableStart,y=l.doc.nodeAt(f);y&&l.setNodeMarkup(f,h,y.attrs)}),r(l)}return!0}}bB("row",{useDeprecatedLogic:!0});bB("column",{useDeprecatedLogic:!0});const dhs=bB("cell",{useDeprecatedLogic:!0});function uhs(s,t){if(t<0){const n=s.nodeBefore;if(n)return s.pos-n.nodeSize;for(let r=s.index(-1)-1,a=s.before();r>=0;r--){const i=s.node(-1).child(r),l=i.lastChild;if(l)return a-1-l.nodeSize;a-=i.nodeSize}}else{if(s.index()0;r--)if(n.node(r).type.spec.tableRole=="table")return t&&t(s.tr.delete(n.before(r),n.after(r)).scrollIntoView()),!0;return!1}function xH(s,t){const n=s.selection;if(!(n instanceof bd))return!1;if(t){const r=s.tr,a=rx(s.schema).cell.createAndFill().content;n.forEachCell((i,l)=>{i.content.eq(a)||r.replace(r.mapping.map(l+1),r.mapping.map(l+i.nodeSize-1),new ba(a,0,0))}),r.docChanged&&t(r)}return!0}function mhs(s){if(s.size===0)return null;let{content:t,openStart:n,openEnd:r}=s;for(;t.childCount==1&&(n>0&&r>0||t.child(0).type.spec.tableRole=="table");)n--,r--,t=t.child(0).content;const a=t.child(0),i=a.type.spec.tableRole,l=a.type.schema,o=[];if(i=="row")for(let c=0;c=0;l--){const{rowspan:o,colspan:c}=i.child(l).attrs;for(let d=a;d=t.length&&t.push($r.empty),n[a]r&&(p=p.type.createChecked(wM(p.attrs,p.attrs.colspan,u+p.attrs.colspan-r),p.content)),d.push(p),u+=p.attrs.colspan;for(let f=1;fa&&(h=h.type.create({...h.attrs,rowspan:Math.max(1,a-h.attrs.rowspan)},h.content)),c.push(h)}i.push($r.from(c))}n=i,t=a}return{width:s,height:t,rows:n}}function xhs(s,t,n,r,a,i,l){const o=s.doc.type.schema,c=rx(o);let d,u;if(a>t.width)for(let h=0,p=0;ht.height){const h=[];for(let y=0,_=(t.height-1)*t.width;y=t.width?!1:n.nodeAt(t.map[_+y]).type==c.header_cell;h.push(v?u||(u=c.header_cell.createAndFill()):d||(d=c.cell.createAndFill()))}const p=c.row.create(null,$r.from(h)),f=[];for(let y=t.height;y{if(!a)return!1;const i=n.selection;if(i instanceof bd)return Fme(n,r,to.near(i.$headCell,t));if(s!="horiz"&&!i.empty)return!1;const l=fxt(a,s,t);if(l==null)return!1;if(s=="horiz")return Fme(n,r,to.near(n.doc.resolve(i.head+t),t));{const o=n.doc.resolve(l),c=lxt(o,s,t);let d;return c?d=to.near(c,1):t<0?d=to.near(n.doc.resolve(o.before(-1)),-1):d=to.near(n.doc.resolve(o.after(-1)),1),Fme(n,r,d)}}}function yH(s,t){return(n,r,a)=>{if(!a)return!1;const i=n.selection;let l;if(i instanceof bd)l=i;else{const c=fxt(a,s,t);if(c==null)return!1;l=new bd(n.doc.resolve(c))}const o=lxt(l.$headCell,s,t);return o?Fme(n,r,new bd(l.$anchorCell,o)):!1}}function yhs(s,t){const n=s.state.doc,r=_M(n.resolve(t));return r?(s.dispatch(s.state.tr.setSelection(new bd(r))),!0):!1}function vhs(s,t,n){if(!Eb(s.state))return!1;let r=mhs(n);const a=s.state.selection;if(a instanceof bd){r||(r={width:1,height:1,rows:[$r.from(DCe(rx(s.state.schema).cell,n))]});const i=a.$anchorCell.node(-1),l=a.$anchorCell.start(-1),o=nh.get(i).rectBetween(a.$anchorCell.pos-l,a.$headCell.pos-l);return r=fhs(r,o.right-o.left,o.bottom-o.top),tVe(s.state,s.dispatch,l,o,r),!0}else if(r){const i=Gye(s.state),l=i.start(-1);return tVe(s.state,s.dispatch,l,nh.get(i.node(-1)).findCell(i.pos-l),r),!0}else return!1}function bhs(s,t){var n;if(t.button!=0||t.ctrlKey||t.metaKey)return;const r=sVe(s,t.target);let a;if(t.shiftKey&&s.state.selection instanceof bd)i(s.state.selection.$anchorCell,t),t.preventDefault();else if(t.shiftKey&&r&&(a=_M(s.state.selection.$anchor))!=null&&((n=Jje(s,t))===null||n===void 0?void 0:n.pos)!=a.pos)i(a,t),t.preventDefault();else if(!r)return;function i(c,d){let u=Jje(s,d);const h=oS.getState(s.state)==null;if(!u||!H6e(c,u))if(h)u=c;else return;const p=new bd(c,u);if(h||!s.state.selection.eq(p)){const f=s.state.tr.setSelection(p);h&&f.setMeta(oS,c.pos),s.dispatch(f)}}function l(){s.root.removeEventListener("mouseup",l),s.root.removeEventListener("dragstart",l),s.root.removeEventListener("mousemove",o),oS.getState(s.state)!=null&&s.dispatch(s.state.tr.setMeta(oS,-1))}function o(c){const d=c,u=oS.getState(s.state);let h;if(u!=null)h=s.state.doc.resolve(u);else if(sVe(s,d.target)!=r&&(h=Jje(s,t),!h))return l();h&&i(h,d)}s.root.addEventListener("mouseup",l),s.root.addEventListener("dragstart",l),s.root.addEventListener("mousemove",o)}function fxt(s,t,n){if(!(s.state.selection instanceof Ui))return null;const{$head:r}=s.state.selection;for(let a=r.depth-1;a>=0;a--){const i=r.node(a);if((n<0?r.index(a):r.indexAfter(a))!=(n<0?0:i.childCount))return null;if(i.type.spec.tableRole=="cell"||i.type.spec.tableRole=="header_cell"){const l=r.before(a),o=t=="vert"?n>0?"down":"up":n>0?"right":"left";return s.endOfTextblock(o)?l:null}}return null}function sVe(s,t){for(;t&&t!=s.dom;t=t.parentNode)if(t.nodeName=="TD"||t.nodeName=="TH")return t;return null}function Jje(s,t){const n=s.posAtCoords({left:t.clientX,top:t.clientY});if(!n)return null;let{inside:r,pos:a}=n;return r>=0&&_M(s.state.doc.resolve(r))||_M(s.state.doc.resolve(a))}var _hs=class{constructor(t,n){this.node=t,this.defaultCellMinWidth=n,this.dom=document.createElement("div"),this.dom.className="tableWrapper",this.table=this.dom.appendChild(document.createElement("table")),this.table.style.setProperty("--default-cell-min-width",`${n}px`),this.colgroup=this.table.appendChild(document.createElement("colgroup")),RCe(t,this.colgroup,this.table,n),this.contentDOM=this.table.appendChild(document.createElement("tbody"))}update(t){return t.type!=this.node.type?!1:(this.node=t,RCe(t,this.colgroup,this.table,this.defaultCellMinWidth),!0)}ignoreMutation(t){return t.type=="attributes"&&(t.target==this.table||this.colgroup.contains(t.target))}};function RCe(s,t,n,r,a,i){let l=0,o=!0,c=t.firstChild;const d=s.firstChild;if(d){for(let h=0,p=0;hnew r(h,n,p)),new jhs(-1,!1)},apply(l,o){return o.apply(l)}},props:{attributes:l=>{const o=K0.getState(l);return o&&o.activeHandle>-1?{class:"resize-cursor"}:{}},handleDOMEvents:{mousemove:(l,o)=>{Nhs(l,o,s,a)},mouseleave:l=>{khs(l)},mousedown:(l,o)=>{Shs(l,o,t,n)}},decorations:l=>{const o=K0.getState(l);if(o&&o.activeHandle>-1)return Mhs(l,o.activeHandle)},nodeViews:{}}});return i}var jhs=class zme{constructor(t,n){this.activeHandle=t,this.dragging=n}apply(t){const n=this,r=t.getMeta(K0);if(r&&r.setHandle!=null)return new zme(r.setHandle,!1);if(r&&r.setDragging!==void 0)return new zme(n.activeHandle,r.setDragging);if(n.activeHandle>-1&&t.docChanged){let a=t.mapping.map(n.activeHandle,-1);return LCe(t.doc.resolve(a))||(a=-1),new zme(a,n.dragging)}return n}};function Nhs(s,t,n,r){if(!s.editable)return;const a=K0.getState(s.state);if(a&&!a.dragging){const i=Ths(t.target);let l=-1;if(i){const{left:o,right:c}=i.getBoundingClientRect();t.clientX-o<=n?l=nVe(s,t,"left",n):c-t.clientX<=n&&(l=nVe(s,t,"right",n))}if(l!=a.activeHandle){if(!r&&l!==-1){const o=s.state.doc.resolve(l),c=o.node(-1),d=nh.get(c),u=o.start(-1);if(d.colCount(o.pos-u)+o.nodeAfter.attrs.colspan-1==d.width-1)return}xxt(s,l)}}}function khs(s){if(!s.editable)return;const t=K0.getState(s.state);t&&t.activeHandle>-1&&!t.dragging&&xxt(s,-1)}function Shs(s,t,n,r){var a;if(!s.editable)return!1;const i=(a=s.dom.ownerDocument.defaultView)!==null&&a!==void 0?a:window,l=K0.getState(s.state);if(!l||l.activeHandle==-1||l.dragging)return!1;const o=s.state.doc.nodeAt(l.activeHandle),c=Chs(s,l.activeHandle,o.attrs);s.dispatch(s.state.tr.setMeta(K0,{setDragging:{startX:t.clientX,startWidth:c}}));function d(h){i.removeEventListener("mouseup",d),i.removeEventListener("mousemove",u);const p=K0.getState(s.state);p!=null&&p.dragging&&(Ehs(s,p.activeHandle,rVe(p.dragging,h,n)),s.dispatch(s.state.tr.setMeta(K0,{setDragging:null})))}function u(h){if(!h.which)return d(h);const p=K0.getState(s.state);if(p&&p.dragging){const f=rVe(p.dragging,h,n);aVe(s,p.activeHandle,f,r)}}return aVe(s,l.activeHandle,c,r),i.addEventListener("mouseup",d),i.addEventListener("mousemove",u),t.preventDefault(),!0}function Chs(s,t,{colspan:n,colwidth:r}){const a=r&&r[r.length-1];if(a)return a;const i=s.domAtPos(t);let l=i.node.childNodes[i.offset].offsetWidth,o=n;if(r)for(let c=0;c{const r=s.nodes[n];r.spec.tableRole&&(t[r.spec.tableRole]=r)}),s.cached.tableNodeTypes=t,t}function Rhs(s,t,n,r,a){const i=Dhs(s),l=[],o=[];for(let d=0;d{const{selection:t}=s.state;if(!Ohs(t))return!1;let n=0;const r=Uft(t.ranges[0].$from,i=>i.type.name==="table");return r==null||r.node.descendants(i=>{if(i.type.name==="table")return!1;["tableCell","tableHeader"].includes(i.type.name)&&(n+=1)}),n===t.ranges.length?(s.commands.deleteTable(),!0):!1},Fhs=lx.create({name:"table",addOptions(){return{HTMLAttributes:{},resizable:!1,renderWrapper:!1,handleWidth:5,cellMinWidth:25,View:Phs,lastColumnResizable:!0,allowTableNodeSelection:!1}},content:"tableRow+",tableRole:"table",isolating:!0,group:"block",parseHTML(){return[{tag:"table"}]},renderHTML({node:s,HTMLAttributes:t}){const{colgroup:n,tableWidth:r,tableMinWidth:a}=Lhs(s,this.options.cellMinWidth),i=["table",du(this.options.HTMLAttributes,t,{style:r?`width: ${r}`:`min-width: ${a}`}),n,["tbody",0]];return this.options.renderWrapper?["div",{class:"tableWrapper"},i]:i},addCommands(){return{insertTable:({rows:s=3,cols:t=3,withHeaderRow:n=!0}={})=>({tr:r,dispatch:a,editor:i})=>{const l=Rhs(i.schema,s,t,n);if(a){const o=r.selection.from+1;r.replaceSelectionWith(l).scrollIntoView().setSelection(Ui.near(r.doc.resolve(o)))}return!0},addColumnBefore:()=>({state:s,dispatch:t})=>Qus(s,t),addColumnAfter:()=>({state:s,dispatch:t})=>Xus(s,t),deleteColumn:()=>({state:s,dispatch:t})=>ehs(s,t),addRowBefore:()=>({state:s,dispatch:t})=>shs(s,t),addRowAfter:()=>({state:s,dispatch:t})=>nhs(s,t),deleteRow:()=>({state:s,dispatch:t})=>ahs(s,t),deleteTable:()=>({state:s,dispatch:t})=>hhs(s,t),mergeCells:()=>({state:s,dispatch:t})=>Yqe(s,t),splitCell:()=>({state:s,dispatch:t})=>Zqe(s,t),toggleHeaderColumn:()=>({state:s,dispatch:t})=>bB("column")(s,t),toggleHeaderRow:()=>({state:s,dispatch:t})=>bB("row")(s,t),toggleHeaderCell:()=>({state:s,dispatch:t})=>dhs(s,t),mergeOrSplit:()=>({state:s,dispatch:t})=>Yqe(s,t)?!0:Zqe(s,t),setCellAttribute:(s,t)=>({state:n,dispatch:r})=>lhs(s,t)(n,r),goToNextCell:()=>({state:s,dispatch:t})=>Xqe(1)(s,t),goToPreviousCell:()=>({state:s,dispatch:t})=>Xqe(-1)(s,t),fixTables:()=>({state:s,dispatch:t})=>(t&&hxt(s),!0),setCellSelection:s=>({tr:t,dispatch:n})=>{if(n){const r=bd.create(t.doc,s.anchorCell,s.headCell);t.setSelection(r)}return!0}}},addKeyboardShortcuts(){return{Tab:()=>this.editor.commands.goToNextCell()?!0:this.editor.can().addRowAfter()?this.editor.chain().addRowAfter().goToNextCell().run():!1,"Shift-Tab":()=>this.editor.commands.goToPreviousCell(),Backspace:vH,"Mod-Backspace":vH,Delete:vH,"Mod-Delete":vH}},addProseMirrorPlugins(){return[...this.options.resizable&&this.editor.isEditable?[whs({handleWidth:this.options.handleWidth,cellMinWidth:this.options.cellMinWidth,defaultCellMinWidth:this.options.cellMinWidth,View:this.options.View,lastColumnResizable:this.options.lastColumnResizable})]:[],Ihs({allowTableNodeSelection:this.options.allowTableNodeSelection})]},extendNodeSchema(s){const t={name:s.name,options:s.options,storage:s.storage};return{tableRole:Wo(li(s,"tableRole",t))}}}),zhs=lx.create({name:"tableRow",addOptions(){return{HTMLAttributes:{}}},content:"(tableCell | tableHeader)*",tableRole:"row",parseHTML(){return[{tag:"tr"}]},renderHTML({HTMLAttributes:s}){return["tr",du(this.options.HTMLAttributes,s),0]}}),Bhs=lx.create({name:"tableCell",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}}}},tableRole:"cell",isolating:!0,parseHTML(){return[{tag:"td"}]},renderHTML({HTMLAttributes:s}){return["td",du(this.options.HTMLAttributes,s),0]}}),$hs=lx.create({name:"tableHeader",addOptions(){return{HTMLAttributes:{}}},content:"block+",addAttributes(){return{colspan:{default:1},rowspan:{default:1},colwidth:{default:null,parseHTML:s=>{const t=s.getAttribute("colwidth");return t?t.split(",").map(r=>parseInt(r,10)):null}}}},tableRole:"header_cell",isolating:!0,parseHTML(){return[{tag:"th"}]},renderHTML({HTMLAttributes:s}){return["th",du(this.options.HTMLAttributes,s),0]}});function Ab({content:s,onChange:t,placeholder:n="Enter content...",minHeight:r="150px",compact:a=!1}){const[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState(!0),h=A6e({extensions:[I6e,U6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),q6e.configure({types:["heading","paragraph"]}),V6e,Dus.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),width:{default:null},height:{default:null},style:{default:null}}}}).configure({inline:!0,allowBase64:!0}),Fhs.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},cellpadding:{default:null},cellspacing:{default:null},border:{default:null}}}}).configure({resizable:!1}),zhs.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null}}}}),Bhs.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1},valign:{default:null}}}}),$hs.extend({addAttributes(){var _;return{...(_=this.parent)==null?void 0:_.call(this),style:{default:null},width:{default:null},colspan:{default:1},rowspan:{default:1}}}})],content:s,onUpdate:({editor:_})=>{t(_.getHTML())},editorProps:{attributes:{class:"outline-none","data-placeholder":n},handlePaste:(_,v)=>{var w;const j=(w=v.clipboardData)==null?void 0:w.items;if(!j)return!1;for(const S of Array.from(j))if(S.type.startsWith("image/")){v.preventDefault();const A=S.getAsFile();if(!A)continue;const E=new FileReader;return E.onload=O=>{var I;const D=(I=O.target)==null?void 0:I.result;_.dispatch(_.state.tr.replaceSelectionWith(_.state.schema.nodes.image.create({src:D})))},E.readAsDataURL(A),!0}return!1}}});N.useEffect(()=>{h&&s!==h.getHTML()&&h.commands.setContent(s)},[s,h]);const p=()=>{if(!h)return;const _=h.getAttributes("link").href||"",v=h.getAttributes("link").target;c(_),u(v==="_blank"),l(!0)},f=()=>{h&&(o===""?h.chain().focus().extendMarkRange("link").unsetLink().run():h.chain().focus().extendMarkRange("link").setLink({href:o,target:d?"_blank":null,rel:d?"noopener noreferrer nofollow":null}).run(),l(!1),c(""))},y=()=>{h&&h.chain().focus().extendMarkRange("link").unsetLink().run()};return h?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-0.5 p-2 border-b bg-muted/30",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:1}).run(),className:h.isActive("heading",{level:1})?"bg-muted":"",title:"Heading 1",children:e.jsx(XP,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleHeading({level:2}).run(),className:h.isActive("heading",{level:2})?"bg-muted":"",title:"Heading 2",children:e.jsx(JP,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBold().run(),className:h.isActive("bold")?"bg-muted":"",title:"Bold",children:e.jsx($S,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleItalic().run(),className:h.isActive("italic")?"bg-muted":"",title:"Italic",children:e.jsx(HS,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleBulletList().run(),className:h.isActive("bulletList")?"bg-muted":"",title:"Bullet List",children:e.jsx(Sp,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().toggleOrderedList().run(),className:h.isActive("orderedList")?"bg-muted":"",title:"Numbered List",children:e.jsx(ub,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("left").run(),className:h.isActive({textAlign:"left"})?"bg-muted":"",title:"Align Left",children:e.jsx(fA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("center").run(),className:h.isActive({textAlign:"center"})?"bg-muted":"",title:"Align Center",children:e.jsx(pA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().setTextAlign("right").run(),className:h.isActive({textAlign:"right"})?"bg-muted":"",title:"Align Right",children:e.jsx(xA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:p,className:h.isActive("link")?"bg-muted":"",title:"Add Link",children:e.jsx(Yo,{className:"h-4 w-4"})}),h.isActive("link")&&e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:y,title:"Remove Link",children:e.jsx(Yo,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().undo().run(),disabled:!h.can().undo(),title:"Undo",children:e.jsx(n4,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>h.chain().focus().redo().run(),disabled:!h.can().redo(),title:"Redo",children:e.jsx(JS,{className:"h-4 w-4"})})]}),e.jsx(T6e,{editor:h,className:"prose prose-sm max-w-none p-3 focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror_img]:max-w-none [&_.ProseMirror_table]:border-none [&_.ProseMirror_table]:border-collapse [&_.ProseMirror_td]:border-none [&_.ProseMirror_td]:p-0 [&_.ProseMirror_td]:align-top [&_.ProseMirror_th]:border-none [&_.ProseMirror_th]:p-0 [&_.ProseMirror_tr]:border-none",style:{minHeight:r}})]}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Insert Link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"link-url",children:"URL"}),e.jsx(ye,{id:"link-url",value:o,onChange:_=>c(_.target.value),placeholder:"https://example.com"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(jn,{id:"link-new-tab",checked:d,onCheckedChange:u}),e.jsx(ne,{htmlFor:"link-new-tab",children:"Open in new tab"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:f,children:o?"Apply Link":"Remove Link"})]})]})})]}):null}var Uhs=Object.defineProperty,qhs=(s,t,n)=>t in s?Uhs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,eu=(s,t,n)=>qhs(s,typeof t!="symbol"?t+"":t,n);const oxe={x:0,y:0,width:0,height:0,unit:"px"},bI=(s,t,n)=>Math.min(Math.max(s,t),n),Vhs=(...s)=>s.filter(t=>t&&typeof t=="string").join(" "),lVe=(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 Hhs(s,t,n,r){const a=F_(s,n,r);return s.width&&(a.height=a.width/t),s.height&&(a.width=a.height*t),a.y+a.height>r&&(a.height=r-a.y,a.width=a.height*t),a.x+a.width>n&&(a.width=n-a.x,a.height=a.width/t),s.unit==="%"?Kk(a,n,r):a}function Ghs(s,t,n){const r=F_(s,t,n);return r.x=(t-r.width)/2,r.y=(n-r.height)/2,s.unit==="%"?Kk(r,t,n):r}function Kk(s,t,n){return s.unit==="%"?{...oxe,...s,unit:"%"}:{unit:"%",x:s.x?s.x/t*100:0,y:s.y?s.y/n*100:0,width:s.width?s.width/t*100:0,height:s.height?s.height/n*100:0}}function F_(s,t,n){return s.unit?s.unit==="px"?{...oxe,...s,unit:"px"}:{unit:"px",x:s.x?s.x*t/100:0,y:s.y?s.y*n/100:0,width:s.width?s.width*t/100:0,height:s.height?s.height*n/100:0}:{...oxe,...s,unit:"px"}}function cVe(s,t,n,r,a,i=0,l=0,o=r,c=a){const d={...s};let u=Math.min(i,r),h=Math.min(l,a),p=Math.min(o,r),f=Math.min(c,a);t&&(t>1?(u=l?l*t:u,h=u/t,p=o*t):(h=i?i/t:h,u=h*t,f=c/t)),d.y<0&&(d.height=Math.max(d.height+d.y,h),d.y=0),d.x<0&&(d.width=Math.max(d.width+d.x,u),d.x=0);const y=r-(d.x+d.width);y<0&&(d.x=Math.min(d.x,r-u),d.width+=y);const _=a-(d.y+d.height);if(_<0&&(d.y=Math.min(d.y,a-h),d.height+=_),d.widthp&&((n==="sw"||n=="nw")&&(d.x-=p-d.width),d.width=p),d.height>f&&((n==="nw"||n=="ne")&&(d.y-=f-d.height),d.height=f),t){const v=d.width/d.height;if(vt){const j=Math.max(d.height*t,u);(n==="sw"||n=="nw")&&(d.x-=j-d.width),d.width=j}}return d}function Whs(s,t,n,r){const a={...s};return t==="ArrowLeft"?r==="nw"?(a.x-=n,a.y-=n,a.width+=n,a.height+=n):r==="w"?(a.x-=n,a.width+=n):r==="sw"?(a.x-=n,a.width+=n,a.height+=n):r==="ne"?(a.y+=n,a.width-=n,a.height-=n):r==="e"?a.width-=n:r==="se"&&(a.width-=n,a.height-=n):t==="ArrowRight"&&(r==="nw"?(a.x+=n,a.y+=n,a.width-=n,a.height-=n):r==="w"?(a.x+=n,a.width-=n):r==="sw"?(a.x+=n,a.width-=n,a.height-=n):r==="ne"?(a.y-=n,a.width+=n,a.height+=n):r==="e"?a.width+=n:r==="se"&&(a.width+=n,a.height+=n)),t==="ArrowUp"?r==="nw"?(a.x-=n,a.y-=n,a.width+=n,a.height+=n):r==="n"?(a.y-=n,a.height+=n):r==="ne"?(a.y-=n,a.width+=n,a.height+=n):r==="sw"?(a.x+=n,a.width-=n,a.height-=n):r==="s"?a.height-=n:r==="se"&&(a.width-=n,a.height-=n):t==="ArrowDown"&&(r==="nw"?(a.x+=n,a.y+=n,a.width-=n,a.height-=n):r==="n"?(a.y+=n,a.height-=n):r==="ne"?(a.y+=n,a.width-=n,a.height-=n):r==="sw"?(a.x-=n,a.width+=n,a.height+=n):r==="s"?a.height+=n:r==="se"&&(a.width+=n,a.height+=n)),a}const _I={capture:!0,passive:!1};let Khs=0;const Fk=class F1 extends N.PureComponent{constructor(){super(...arguments),eu(this,"docMoveBound",!1),eu(this,"mouseDownOnCrop",!1),eu(this,"dragStarted",!1),eu(this,"evData",{startClientX:0,startClientY:0,startCropX:0,startCropY:0,clientX:0,clientY:0,isResize:!0}),eu(this,"componentRef",N.createRef()),eu(this,"mediaRef",N.createRef()),eu(this,"resizeObserver"),eu(this,"initChangeCalled",!1),eu(this,"instanceId",`rc-${Khs++}`),eu(this,"state",{cropIsActive:!1,newCropIsBeingDrawn:!1}),eu(this,"onCropPointerDown",t=>{const{crop:n,disabled:r}=this.props,a=this.getBox();if(!n)return;const i=F_(n,a.width,a.height);if(r)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const l=t.target.dataset.ord,o=!!l;let c=t.clientX,d=t.clientY,u=i.x,h=i.y;if(l){const p=t.clientX-a.x,f=t.clientY-a.y;let y=0,_=0;l==="ne"||l=="e"?(y=p-(i.x+i.width),_=f-i.y,u=i.x,h=i.y+i.height):l==="se"||l==="s"?(y=p-(i.x+i.width),_=f-(i.y+i.height),u=i.x,h=i.y):l==="sw"||l=="w"?(y=p-i.x,_=f-(i.y+i.height),u=i.x+i.width,h=i.y):(l==="nw"||l=="n")&&(y=p-i.x,_=f-i.y,u=i.x+i.width,h=i.y+i.height),c=u+a.x+y,d=h+a.y+_}this.evData={startClientX:c,startClientY:d,startCropX:u,startCropY:h,clientX:t.clientX,clientY:t.clientY,isResize:o,ord:l},this.mouseDownOnCrop=!0,this.setState({cropIsActive:!0})}),eu(this,"onComponentPointerDown",t=>{const{crop:n,disabled:r,locked:a,keepSelection:i,onChange:l}=this.props,o=this.getBox();if(r||a||i&&n)return;t.cancelable&&t.preventDefault(),this.bindDocMove(),this.componentRef.current.focus({preventScroll:!0});const c=t.clientX-o.x,d=t.clientY-o.y,u={unit:"px",x:c,y:d,width:0,height:0};this.evData={startClientX:t.clientX,startClientY:t.clientY,startCropX:c,startCropY:d,clientX:t.clientX,clientY:t.clientY,isResize:!0},this.mouseDownOnCrop=!0,l(F_(u,o.width,o.height),Kk(u,o.width,o.height)),this.setState({cropIsActive:!0,newCropIsBeingDrawn:!0})}),eu(this,"onDocPointerMove",t=>{const{crop:n,disabled:r,onChange:a,onDragStart:i}=this.props,l=this.getBox();if(r||!n||!this.mouseDownOnCrop)return;t.cancelable&&t.preventDefault(),this.dragStarted||(this.dragStarted=!0,i&&i(t));const{evData:o}=this;o.clientX=t.clientX,o.clientY=t.clientY;let c;o.isResize?c=this.resizeCrop():c=this.dragCrop(),lVe(n,c)||a(F_(c,l.width,l.height),Kk(c,l.width,l.height))}),eu(this,"onComponentKeyDown",t=>{const{crop:n,disabled:r,onChange:a,onComplete:i}=this.props;if(r)return;const l=t.key;let o=!1;if(!n)return;const c=this.getBox(),d=this.makePixelCrop(c),u=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?F1.nudgeStepLarge:t.shiftKey?F1.nudgeStepMedium:F1.nudgeStep;if(l==="ArrowLeft"?(d.x-=u,o=!0):l==="ArrowRight"?(d.x+=u,o=!0):l==="ArrowUp"?(d.y-=u,o=!0):l==="ArrowDown"&&(d.y+=u,o=!0),o){t.cancelable&&t.preventDefault(),d.x=bI(d.x,0,c.width-d.width),d.y=bI(d.y,0,c.height-d.height);const h=F_(d,c.width,c.height),p=Kk(d,c.width,c.height);a(h,p),i&&i(h,p)}}),eu(this,"onHandlerKeyDown",(t,n)=>{const{aspect:r=0,crop:a,disabled:i,minWidth:l=0,minHeight:o=0,maxWidth:c,maxHeight:d,onChange:u,onComplete:h}=this.props,p=this.getBox();if(i||!a)return;if(t.key==="ArrowUp"||t.key==="ArrowDown"||t.key==="ArrowLeft"||t.key==="ArrowRight")t.stopPropagation(),t.preventDefault();else return;const f=(navigator.platform.match("Mac")?t.metaKey:t.ctrlKey)?F1.nudgeStepLarge:t.shiftKey?F1.nudgeStepMedium:F1.nudgeStep,y=F_(a,p.width,p.height),_=Whs(y,t.key,f,n),v=cVe(_,r,n,p.width,p.height,l,o,c,d);if(!lVe(a,v)){const j=Kk(v,p.width,p.height);u(v,j),h&&h(v,j)}}),eu(this,"onDocPointerDone",t=>{const{crop:n,disabled:r,onComplete:a,onDragEnd:i}=this.props,l=this.getBox();this.unbindDocMove(),!(r||!n)&&this.mouseDownOnCrop&&(this.mouseDownOnCrop=!1,this.dragStarted=!1,i&&i(t),a&&a(F_(n,l.width,l.height),Kk(n,l.width,l.height)),this.setState({cropIsActive:!1,newCropIsBeingDrawn:!1}))}),eu(this,"onDragFocus",()=>{var t;(t=this.componentRef.current)==null||t.scrollTo(0,0)})}get document(){return document}getBox(){const t=this.mediaRef.current;if(!t)return{x:0,y:0,width:0,height:0};const{x:n,y:r,width:a,height:i}=t.getBoundingClientRect();return{x:n,y:r,width:a,height:i}}componentDidUpdate(t){const{crop:n,onComplete:r}=this.props;if(r&&!t.crop&&n){const{width:a,height:i}=this.getBox();a&&i&&r(F_(n,a,i),Kk(n,a,i))}}componentWillUnmount(){this.resizeObserver&&this.resizeObserver.disconnect(),this.unbindDocMove()}bindDocMove(){this.docMoveBound||(this.document.addEventListener("pointermove",this.onDocPointerMove,_I),this.document.addEventListener("pointerup",this.onDocPointerDone,_I),this.document.addEventListener("pointercancel",this.onDocPointerDone,_I),this.docMoveBound=!0)}unbindDocMove(){this.docMoveBound&&(this.document.removeEventListener("pointermove",this.onDocPointerMove,_I),this.document.removeEventListener("pointerup",this.onDocPointerDone,_I),this.document.removeEventListener("pointercancel",this.onDocPointerDone,_I),this.docMoveBound=!1)}getCropStyle(){const{crop:t}=this.props;if(t)return{top:`${t.y}${t.unit}`,left:`${t.x}${t.unit}`,width:`${t.width}${t.unit}`,height:`${t.height}${t.unit}`}}dragCrop(){const{evData:t}=this,n=this.getBox(),r=this.makePixelCrop(n),a=t.clientX-t.startClientX,i=t.clientY-t.startClientY;return r.x=bI(t.startCropX+a,0,n.width-r.width),r.y=bI(t.startCropY+i,0,n.height-r.height),r}getPointRegion(t,n,r,a){const{evData:i}=this,l=i.clientX-t.x,o=i.clientY-t.y;let c;a&&n?c=n==="nw"||n==="n"||n==="ne":c=o1?i?[i,i/n]:[l*n,l]:l?[l*n,l]:[i,i/n]}resizeCrop(){const{evData:t}=this,{aspect:n=0,maxWidth:r,maxHeight:a}=this.props,i=this.getBox(),[l,o]=this.resolveMinDimensions(i,n,this.props.minWidth,this.props.minHeight);let c=this.makePixelCrop(i);const d=this.getPointRegion(i,t.ord,l,o),u=t.ord||d;let h=t.clientX-t.startClientX,p=t.clientY-t.startClientY;(l&&u==="nw"||u==="w"||u==="sw")&&(h=Math.min(h,-l)),(o&&u==="nw"||u==="n"||u==="ne")&&(p=Math.min(p,-o));const f={unit:"px",x:0,y:0,width:0,height:0};d==="ne"?(f.x=t.startCropX,f.width=h,n?(f.height=f.width/n,f.y=t.startCropY-f.height):(f.height=Math.abs(p),f.y=t.startCropY-f.height)):d==="se"?(f.x=t.startCropX,f.y=t.startCropY,f.width=h,n?f.height=f.width/n:f.height=p):d==="sw"?(f.x=t.startCropX+h,f.y=t.startCropY,f.width=Math.abs(h),n?f.height=f.width/n:f.height=p):d==="nw"&&(f.x=t.startCropX+h,f.width=Math.abs(h),n?(f.height=f.width/n,f.y=t.startCropY-f.height):(f.height=Math.abs(p),f.y=t.startCropY+p));const y=cVe(f,n,d,i.width,i.height,l,o,r,a);return n||F1.xyOrds.indexOf(u)>-1?c=y:F1.xOrds.indexOf(u)>-1?(c.x=y.x,c.width=y.width):F1.yOrds.indexOf(u)>-1&&(c.y=y.y,c.height=y.height),c.x=bI(c.x,0,i.width-c.width),c.y=bI(c.y,0,i.height-c.height),c}renderCropSelection(){const{ariaLabels:t=F1.defaultProps.ariaLabels,disabled:n,locked:r,renderSelectionAddon:a,ruleOfThirds:i,crop:l}=this.props,o=this.getCropStyle();if(l)return Ct.createElement("div",{style:o,className:"ReactCrop__crop-selection",onPointerDown:this.onCropPointerDown,"aria-label":t.cropArea,tabIndex:0,onKeyDown:this.onComponentKeyDown,role:"group"},!n&&!r&&Ct.createElement("div",{className:"ReactCrop__drag-elements",onFocus:this.onDragFocus},Ct.createElement("div",{className:"ReactCrop__drag-bar ord-n","data-ord":"n"}),Ct.createElement("div",{className:"ReactCrop__drag-bar ord-e","data-ord":"e"}),Ct.createElement("div",{className:"ReactCrop__drag-bar ord-s","data-ord":"s"}),Ct.createElement("div",{className:"ReactCrop__drag-bar ord-w","data-ord":"w"}),Ct.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"}),Ct.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"}),Ct.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"}),Ct.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"}),Ct.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"}),Ct.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"}),Ct.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"}),Ct.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&&Ct.createElement("div",{className:"ReactCrop__selection-addon",onPointerDown:c=>c.stopPropagation()},a(this.state)),i&&Ct.createElement(Ct.Fragment,null,Ct.createElement("div",{className:"ReactCrop__rule-of-thirds-hz"}),Ct.createElement("div",{className:"ReactCrop__rule-of-thirds-vt"})))}makePixelCrop(t){const n={...oxe,...this.props.crop||{}};return F_(n,t.width,t.height)}render(){const{aspect:t,children:n,circularCrop:r,className:a,crop:i,disabled:l,locked:o,style:c,ruleOfThirds:d}=this.props,{cropIsActive:u,newCropIsBeingDrawn:h}=this.state,p=i?this.renderCropSelection():null,f=Vhs("ReactCrop",a,u&&"ReactCrop--active",l&&"ReactCrop--disabled",o&&"ReactCrop--locked",h&&"ReactCrop--new-crop",i&&t&&"ReactCrop--fixed-aspect",i&&r&&"ReactCrop--circular-crop",i&&d&&"ReactCrop--rule-of-thirds",!this.dragStarted&&i&&!i.width&&!i.height&&"ReactCrop--invisible-crop",r&&"ReactCrop--no-animate");return Ct.createElement("div",{ref:this.componentRef,className:f,style:c},Ct.createElement("div",{ref:this.mediaRef,className:"ReactCrop__child-wrapper",onPointerDown:this.onComponentPointerDown},n),i?Ct.createElement("svg",{className:"ReactCrop__crop-mask",width:"100%",height:"100%"},Ct.createElement("defs",null,Ct.createElement("mask",{id:`hole-${this.instanceId}`},Ct.createElement("rect",{width:"100%",height:"100%",fill:"white"}),r?Ct.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"}):Ct.createElement("rect",{x:`${i.x}${i.unit}`,y:`${i.y}${i.unit}`,width:`${i.width}${i.unit}`,height:`${i.height}${i.unit}`,fill:"black"}))),Ct.createElement("rect",{fill:"black",fillOpacity:.5,width:"100%",height:"100%",mask:`url(#hole-${this.instanceId})`})):void 0,p)}};eu(Fk,"xOrds",["e","w"]),eu(Fk,"yOrds",["n","s"]),eu(Fk,"xyOrds",["nw","ne","se","sw"]),eu(Fk,"nudgeStep",1),eu(Fk,"nudgeStepMedium",10),eu(Fk,"nudgeStepLarge",100),eu(Fk,"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 Yhs=Fk;function Zhs(s,t,n){return Ghs(Hhs({unit:"%",width:90},n,s,t),s,t)}const G6e=({open:s,onClose:t,imageSrc:n,onCropComplete:r,aspectRatio:a=1})=>{const i=N.useRef(null),[l,o]=N.useState(),[c,d]=N.useState(),[u,h]=N.useState(1),[p,f]=N.useState(0),y=N.useCallback(j=>{const{width:w,height:S}=j.currentTarget;o(Zhs(w,S,a))},[a]),_=N.useCallback(async()=>{const j=i.current;if(!j||!c)return;const w=document.createElement("canvas"),S=w.getContext("2d");if(!S)return;const A=j.naturalWidth/j.width,E=j.naturalHeight/j.height,O=400;w.width=O,w.height=O,S.imageSmoothingQuality="high";const D=c.x*A,I=c.y*E,F=c.width*A,z=c.height*E,H=p*Math.PI/180,Z=w.width/2,Y=w.height/2;return S.save(),S.translate(Z,Y),S.rotate(H),S.scale(u,u),S.translate(-Z,-Y),S.drawImage(j,D,I,F,z,0,0,O,O),S.restore(),new Promise((W,ee)=>{w.toBlob(se=>{se?W(se):ee(new Error("Canvas is empty"))},"image/jpeg",.95)})},[c,u,p]),v=async()=>{try{const j=await _();j&&(r(j),t())}catch(j){console.error("Error cropping image:",j)}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(ws,{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(Yhs,{crop:l,onChange:(j,w)=>o(w),onComplete:j=>d(j),aspect:a,circularCrop:!0,className:"max-h-[400px]",children:e.jsx("img",{ref:i,src:n,alt:"Crop preview",style:{transform:`scale(${u}) rotate(${p}deg)`,maxHeight:"400px",width:"auto"},onLoad:y})})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(yL,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(jp,{value:[u],min:.5,max:3,step:.1,onValueChange:([j])=>h(j),className:"flex-1"}),e.jsx(r4,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(PA,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(jp,{value:[p],min:-180,max:180,step:1,onValueChange:([j])=>f(j),className:"flex-1"}),e.jsxs("span",{className:"text-sm text-muted-foreground w-12",children:[p,"°"]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:v,children:"Save Photo"})]})]})})},Qhs=()=>{const{user:s}=vs(),{toast:t}=Fa(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(null);N.useEffect(()=>{s&&c()},[s]);const c=async()=>{r(!0);try{const{data:h}=await q.from("profiles").select("subscription_status, subscription_product_id, subscription_end_date, is_grandfathered").eq("id",s==null?void 0:s.id).single();h&&o({status:h.subscription_status||"none",productId:h.subscription_product_id,endDate:h.subscription_end_date,isGrandfathered:h.is_grandfathered||!1})}catch(h){console.error("Error loading subscription:",h)}finally{r(!1)}},d=async()=>{i(!0);try{const{data:{session:h}}=await q.auth.getSession();if(!h)throw new Error("Not authenticated");const{data:p,error:f}=await q.functions.invoke("customer-portal",{headers:{Authorization:`Bearer ${h.access_token}`}});if(f)throw f;p!=null&&p.url&&window.open(p.url,"_blank")}catch(h){console.error("Error opening customer portal:",h),t({title:"Error",description:h.message||"Failed to open billing portal",variant:"destructive"})}finally{i(!1)}},u=()=>{if(l!=null&&l.isGrandfathered)return e.jsx(Ue,{className:"bg-amber-500",children:"Grandfathered"});switch(l==null?void 0:l.status){case"active":return e.jsx(Ue,{className:"bg-green-500",children:"Active"});case"trialing":return e.jsx(Ue,{className:"bg-blue-500",children:"Trial"});case"past_due":return e.jsx(Ue,{variant:"destructive",children:"Past Due"});case"canceled":return e.jsx(Ue,{variant:"secondary",children:"Canceled"});default:return e.jsx(Ue,{variant:"outline",children:"No Subscription"})}};return n?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(uf,{className:"h-5 w-5"}),"Subscription"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})})})]}):e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(uf,{className:"h-5 w-5"}),"Subscription"]}),e.jsx(Vn,{children:"Manage your subscription and billing"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Status"}),e.jsx("div",{className:"mt-1",children:u()})]}),(l==null?void 0:l.endDate)&&l.status==="active"&&e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Next billing date"}),e.jsx("p",{className:"font-medium",children:new Date(l.endDate).toLocaleDateString()})]})]}),l!=null&&l.isGrandfathered?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your account was upgraded from LevelUp 1.0. To update/manage your subscription please reach out to support."}):(l==null?void 0:l.status)==="active"||(l==null?void 0:l.status)==="trialing"?e.jsxs(e.Fragment,{children:[(l==null?void 0:l.status)==="trialing"&&(l==null?void 0:l.endDate)&&e.jsxs("p",{className:"text-sm text-muted-foreground mb-3",children:["Your trial ends on ",new Date(l.endDate).toLocaleDateString(),". After the trial, you'll be charged automatically."]}),e.jsxs(B,{onClick:d,variant:"outline",disabled:a,children:[a?e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(tr,{className:"mr-2 h-4 w-4"}),"Manage Billing"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"You don't have an active subscription."})]})]})},Xhs=()=>{const{user:s}=vs(),t=Ln(),{toast:n}=Fa(),[r]=xl(),a=r.get("setup")==="true",i=r.get("reset")==="true",{isSupported:l,isSubscribed:o,isLoading:c,subscribe:d,unsubscribe:u}=umt(),[h,p]=N.useState(!1),[f,y]=N.useState(""),[_,v]=N.useState(!1),[j,w]=N.useState(!1),[S,A]=N.useState(""),[E,O]=N.useState({name:"",email:"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1}),[D,I]=N.useState(!1),[F,z]=N.useState(!1),[H,Z]=N.useState(!1),[Y,W]=N.useState(!1),[ee,se]=N.useState(!1),[oe,he]=N.useState({newPassword:"",confirmPassword:""});N.useEffect(()=>{s&&ce()},[s]),N.useEffect(()=>{i&&s&&setTimeout(()=>{var Te;(Te=document.getElementById("change-password-section"))==null||Te.scrollIntoView({behavior:"smooth",block:"center"})},500)},[i,s]);const ce=async()=>{var Te,Ie,Ce,Me;if(!(s!=null&&s.id)){console.log("No user ID available yet");return}try{console.log("Loading profile for user:",s.id);const{data:Pe,error:Re}=await q.from("profiles").select("name, email, phone, digest_opt_out, event_invite_opt_out, title, bio, areas_served, years_experience, brokerage_id, brokerage_name, instagram_url, facebook_url, linkedin_url, email_signature, use_email_signature, brokerages(name)").eq("id",s.id).maybeSingle();if(Re)throw console.error("Profile query error:",Re),Re;if(Pe){console.log("Profile loaded successfully:",Pe);const Be=((Te=Pe.brokerages)==null?void 0:Te.name)||"";I(!!Pe.brokerage_id),O({name:Pe.name||"",email:Pe.email||"",phone:Pe.phone||"",title:Pe.title||"",bio:Pe.bio||"",areas_served:Pe.areas_served||"",years_experience:((Ie=Pe.years_experience)==null?void 0:Ie.toString())||"",brokerage_name:Pe.brokerage_id?Be:Pe.brokerage_name||"",instagram_url:Pe.instagram_url||"",facebook_url:Pe.facebook_url||"",linkedin_url:Pe.linkedin_url||"",email_signature:Pe.email_signature||"",use_email_signature:Pe.use_email_signature||!1}),z(Pe.digest_opt_out||!1),W(Pe.event_invite_opt_out||!1)}else console.warn("No profile found for user"),O({name:((Ce=s.user_metadata)==null?void 0:Ce.name)||((Me=s.email)==null?void 0:Me.split("@")[0])||"",email:s.email||"",phone:"",title:"",bio:"",areas_served:"",years_experience:"",brokerage_name:"",instagram_url:"",facebook_url:"",linkedin_url:"",email_signature:"",use_email_signature:!1});const{data:Ae}=await q.storage.from("avatars").list(`${s.id}`);if(Ae&&Ae.length>0){const{data:Be}=q.storage.from("avatars").getPublicUrl(`${s.id}/${Ae[0].name}`);y(Be.publicUrl)}}catch(Pe){console.error("Error loading profile:",Pe),n({title:"Error",description:Pe.message||"Failed to load profile",variant:"destructive"})}},me=Te=>{var Me;const Ie=(Me=Te.target.files)==null?void 0:Me[0];if(!Ie)return;const Ce=new FileReader;Ce.onloadend=()=>{A(Ce.result),w(!0)},Ce.readAsDataURL(Ie),Te.target.value=""},le=async Te=>{if(s){v(!0);try{const{data:Ie}=await q.storage.from("avatars").list(`${s.id}`);Ie&&Ie.length>0&&await q.storage.from("avatars").remove(Ie.map(Be=>`${s.id}/${Be.name}`));const Me=`${s.id}/avatar.jpg`,{error:Pe}=await q.storage.from("avatars").upload(Me,Te,{upsert:!0,contentType:"image/jpeg"});if(Pe)throw Pe;const{data:Re}=q.storage.from("avatars").getPublicUrl(Me),Ae=Re.publicUrl;y(`${Ae}?t=${Date.now()}`),await q.from("profiles").update({avatar_url:Ae}).eq("id",s.id),n({title:"Success",description:"Profile photo updated successfully"})}catch(Ie){console.error("Error uploading avatar:",Ie),n({title:"Error",description:Ie.message||"Failed to upload photo",variant:"destructive"})}finally{v(!1)}}},ve=async()=>{if(!E.name.trim()||!E.email.trim()){n({title:"Error",description:"Name and email are required",variant:"destructive"});return}p(!0);try{const{error:Te}=await q.from("profiles").update({name:E.name.trim(),email:E.email.trim(),phone:E.phone.trim()||null,title:E.title.trim()||null,bio:E.bio.trim()||null,areas_served:E.areas_served.trim()||null,years_experience:E.years_experience?parseInt(E.years_experience):null,...D?{}:{brokerage_name:E.brokerage_name.trim()||null},instagram_url:E.instagram_url.trim()||null,facebook_url:E.facebook_url.trim()||null,linkedin_url:E.linkedin_url.trim()||null,email_signature:E.email_signature||"",use_email_signature:E.use_email_signature}).eq("id",s==null?void 0:s.id);if(Te)throw Te;n({title:"Success",description:"Profile updated successfully"})}catch(Te){console.error("Error updating profile:",Te),n({title:"Error",description:Te.message||"Failed to update profile",variant:"destructive"})}finally{p(!1)}},ge=async()=>{if(!oe.newPassword){n({title:"Error",description:"Please enter a new password",variant:"destructive"});return}if(oe.newPassword.length<6){n({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}if(oe.newPassword!==oe.confirmPassword){n({title:"Error",description:"Passwords do not match",variant:"destructive"});return}p(!0);try{const{error:Te}=await q.auth.updateUser({password:oe.newPassword});if(Te)throw Te;n({title:"Success",description:"Password updated successfully"}),he({newPassword:"",confirmPassword:""}),a&&setTimeout(()=>t("/dashboard"),1e3)}catch(Te){console.error("Error updating password:",Te),n({title:"Error",description:Te.message||"Failed to update password",variant:"destructive"})}finally{p(!1)}};return e.jsx(Cs,{title:a?"Complete Your Profile":i?"Reset Your Password":"Profile Settings",description:a?"Welcome! Please complete your profile setup":i?"Please set a new password for your account":"Manage your account information and password",children:e.jsxs("div",{className:"mx-auto max-w-4xl",children:[!a&&!i&&e.jsx("div",{className:"mb-6",children:e.jsxs(B,{variant:"outline",onClick:()=>{var Te;(Te=document.getElementById("change-password-section"))==null||Te.scrollIntoView({behavior:"smooth",block:"center"})},className:"gap-2",children:[e.jsx(SA,{className:"h-4 w-4"}),"Change Password"]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Profile Photo"}),e.jsx(Vn,{children:"Upload a professional photo for your profile"})]}),e.jsxs(Ee,{className:"flex items-center gap-6",children:[e.jsxs(Jr,{className:"h-24 w-24",children:[e.jsx(ti,{src:f}),e.jsx(ea,{className:"text-2xl",children:E.name.split(" ").map(Te=>Te[0]).join("").toUpperCase()||"U"})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("input",{type:"file",id:"avatar-upload",accept:"image/*",className:"hidden",onChange:me,disabled:_}),e.jsxs(B,{variant:"outline",onClick:()=>{var Te;return(Te=document.getElementById("avatar-upload"))==null?void 0:Te.click()},disabled:_,children:[e.jsx(_a,{className:"mr-2 h-4 w-4"}),_?"Uploading...":"Upload Photo"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"Upload an image and crop it to your liking."})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Personal Information"}),e.jsx(Vn,{children:"Update your profile details"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",value:E.name,onChange:Te=>O({...E,name:Te.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:E.email,onChange:Te=>O({...E,email:Te.target.value}),maxLength:255})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"phone",children:"Phone Number"}),e.jsx(ye,{id:"phone",type:"tel",value:E.phone,onChange:Te=>O({...E,phone:Te.target.value}),placeholder:"e.g., +14155551234",maxLength:20}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used for SMS lead notifications from your website — if you have a local authority site"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Job Title"}),e.jsx(ye,{id:"title",value:E.title,onChange:Te=>O({...E,title:Te.target.value}),placeholder:"e.g., Broker Associate, Team Lead",maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"bio",children:"Bio"}),e.jsx(Ms,{id:"bio",value:E.bio,onChange:Te=>O({...E,bio:Te.target.value}),placeholder:"A short description about yourself",maxLength:500,className:"min-h-[120px] resize-y"})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"areas_served",children:"Areas Served"}),e.jsx(ye,{id:"areas_served",value:E.areas_served,onChange:Te=>O({...E,areas_served:Te.target.value}),placeholder:"e.g., Downtown, Suburbs"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"years_experience",children:"Years Experience"}),e.jsx(ye,{id:"years_experience",type:"number",min:"0",value:E.years_experience,onChange:Te=>O({...E,years_experience:Te.target.value}),placeholder:"e.g., 5"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"brokerage_name",children:["Brokerage ",D&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"(managed)"})]}),e.jsx(ye,{id:"brokerage_name",value:E.brokerage_name,onChange:Te=>O({...E,brokerage_name:Te.target.value}),placeholder:"e.g., Keller Williams Realty",disabled:D,maxLength:150}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D?"Your brokerage is managed by your office and can't be changed here.":"Used as your brokerage name across ReelFlow, branding, and email signatures."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Social Links"}),e.jsxs("div",{className:"grid grid-cols-1 gap-3",children:[e.jsx(ye,{value:E.linkedin_url,onChange:Te=>O({...E,linkedin_url:Te.target.value}),placeholder:"LinkedIn URL"}),e.jsx(ye,{value:E.instagram_url,onChange:Te=>O({...E,instagram_url:Te.target.value}),placeholder:"Instagram URL"}),e.jsx(ye,{value:E.facebook_url,onChange:Te=>O({...E,facebook_url:Te.target.value}),placeholder:"Facebook URL"})]})]}),e.jsxs(B,{onClick:ve,disabled:h,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save Changes"]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(J1,{className:"h-5 w-5"}),"Email Signature"]}),e.jsx(Vn,{children:"Add a signature that will be appended to emails sent via Gmail"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Use email signature in all emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:E.use_email_signature?"Your signature will be added to every email sent via Gmail":"Signature is currently disabled"})]}),e.jsx(jn,{checked:E.use_email_signature,onCheckedChange:Te=>O({...E,use_email_signature:Te})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Signature"}),e.jsx(Ab,{content:E.email_signature,onChange:Te=>O({...E,email_signature:Te}),placeholder:"Paste your Gmail signature here or create one...",minHeight:"120px",compact:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Tip: Copy your signature from Gmail Settings and paste it here — images and formatting will be preserved."})]}),e.jsxs(B,{onClick:ve,disabled:h,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),"Save Signature"]})]})]}),e.jsxs(fe,{id:"change-password-section",children:[e.jsxs(It,{children:[e.jsx(Rt,{children:a?"Set Your Password":"Change Password"}),e.jsx(Vn,{children:a?"Create a secure password for your account":"Update your password to keep your account secure"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"newPassword",children:"New Password"}),e.jsx(ye,{id:"newPassword",type:"password",value:oe.newPassword,onChange:Te=>he({...oe,newPassword:Te.target.value}),placeholder:"Min 6 characters"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"confirmPassword",children:"Confirm Password"}),e.jsx(ye,{id:"confirmPassword",type:"password",value:oe.confirmPassword,onChange:Te=>he({...oe,confirmPassword:Te.target.value}),placeholder:"Re-enter your new password"})]}),e.jsxs(B,{onClick:ge,disabled:h,children:[e.jsx(Jo,{className:"mr-2 h-4 w-4"}),a?"Complete Setup":"Update Password"]}),a&&e.jsx(B,{variant:"outline",onClick:()=>t("/dashboard"),className:"ml-2",children:"Skip for Now"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[o?e.jsx(nm,{className:"h-5 w-5"}):e.jsx(cw,{className:"h-5 w-5"}),"Push Notifications"]}),e.jsx(Vn,{children:"Receive browser notifications when new content is added"})]}),e.jsx(Ee,{children:l?e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:o?"Notifications enabled":"Notifications disabled"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:o?"You'll receive notifications about new templates, videos, and events":"Enable to get notified about new content"})]}),e.jsx(jn,{checked:o,onCheckedChange:Te=>{Te?d():u()},disabled:c})]}):e.jsxs("div",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"Push notifications are not available in this browser."}),e.jsxs("p",{className:"text-xs space-y-1",children:[e.jsx("strong",{children:"Desktop:"})," Use Chrome, Firefox, or Edge.",e.jsx("br",{}),e.jsx("strong",{children:"Android:"})," Use Chrome or Firefox.",e.jsx("br",{}),e.jsx("strong",{children:"iPhone/iPad:"})," Push notifications on iOS ",e.jsx("em",{children:"only"})," work when this site is installed as an app from ",e.jsx("strong",{children:"Safari"}),". Open this site in Safari → tap the ",e.jsx("strong",{children:"Share"})," button → ",e.jsx("strong",{children:"Add to Home Screen"}),". Other browsers (Chrome, Firefox, etc.) on iOS do not support push notifications due to Apple restrictions."]})]})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[F?e.jsx(rL,{className:"h-5 w-5"}):e.jsx(Gs,{className:"h-5 w-5"}),"Email Preferences"]}),e.jsx(Vn,{children:"Manage your email subscription settings"})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:F?"You won't receive weekly digest emails":"Receive a weekly summary of new content, events, and your progress"})]}),e.jsx(jn,{checked:!F,onCheckedChange:async Te=>{Z(!0);try{const{error:Ie}=await q.from("profiles").update({digest_opt_out:!Te}).eq("id",s==null?void 0:s.id);if(Ie)throw Ie;z(!Te),n({title:Te?"Subscribed":"Unsubscribed",description:Te?"You will now receive weekly digest emails":"You will no longer receive weekly digest emails"})}catch(Ie){n({title:"Error",description:Ie.message||"Failed to update preference",variant:"destructive"})}finally{Z(!1)}},disabled:H})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 mt-4 border-t",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Event Invite Emails"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Y?"You won't receive event invite emails (weekly digest is unaffected)":"Get invited to LevelUp live trainings and special events"})]}),e.jsx(jn,{checked:!Y,onCheckedChange:async Te=>{se(!0);try{const{error:Ie}=await q.from("profiles").update({event_invite_opt_out:!Te}).eq("id",s==null?void 0:s.id);if(Ie)throw Ie;W(!Te),n({title:Te?"Subscribed":"Unsubscribed",description:Te?"You will now receive event invite emails":"You will no longer receive event invite emails"})}catch(Ie){n({title:"Error",description:Ie.message||"Failed to update preference",variant:"destructive"})}finally{se(!1)}},disabled:ee})]})]})]}),e.jsx(Brs,{}),e.jsx(Qhs,{})]}),e.jsx(G6e,{open:j,onClose:()=>w(!1),imageSrc:S,onCropComplete:le,aspectRatio:1})]})})};var Jhs="AspectRatio",gxt=N.forwardRef((s,t)=>{const{ratio:n=1/1,style:r,...a}=s;return e.jsx("div",{style:{position:"relative",width:"100%",paddingBottom:`${100/n}%`},"data-radix-aspect-ratio-wrapper":"",children:e.jsx(Yr.div,{...a,ref:t,style:{...r,position:"absolute",top:0,right:0,bottom:0,left:0}})})});gxt.displayName=Jhs;var ems=gxt;const tms=ems;function sms(){const{user:s}=vs(),t=Kt(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),{data:l,isLoading:o}=dt({queryKey:["calendar-token",s==null?void 0:s.id],queryFn:async()=>{const{data:y,error:_}=await q.from("profiles").select("calendar_token").eq("id",s==null?void 0:s.id).single();if(_)throw _;return y},enabled:!!s&&a}),c=yt({mutationFn:async()=>{const y=new Uint8Array(12);crypto.getRandomValues(y);const _=btoa(String.fromCharCode(...y)).replace(/\+/g,"x").replace(/\//g,"y").replace(/=/g,"").substring(0,16),{error:v}=await q.from("profiles").update({calendar_token:_}).eq("id",s==null?void 0:s.id);if(v)throw v;return _},onSuccess:()=>{t.invalidateQueries({queryKey:["calendar-token",s==null?void 0:s.id]}),ae.success("Calendar subscription URL generated!")},onError:y=>{ae.error("Failed to generate calendar URL: "+y.message)}}),d=l!=null&&l.calendar_token?`https://dashboard.relevelup.com/api/calendar/${l.calendar_token}.ics`:null,u=async()=>{d&&(await navigator.clipboard.writeText(d),r(!0),ae.success("Calendar URL copied to clipboard!"),setTimeout(()=>r(!1),2e3))},h=()=>{d&&(window.location.href=d.replace("https://","webcal://"))},p=()=>{if(d){const y=d.replace("https://","webcal://"),_=`https://calendar.google.com/calendar/r?cid=${encodeURIComponent(y)}`;window.open(_,"_blank")}},f=()=>{if(d){const y=`https://outlook.live.com/calendar/0/addfromweb?url=${encodeURIComponent(d)}&name=Level%20Up%20Events`;window.open(y,"_blank")}};return e.jsxs(_s,{open:a,onOpenChange:i,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Subscribe to Calendar"]})}),e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-5 w-5 text-primary"}),"Subscribe to Events Calendar"]}),e.jsx(Jn,{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(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):d?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Your Calendar URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:d,readOnly:!0,className:"text-xs font-mono"}),e.jsx(B,{variant:"outline",size:"icon",onClick:u,children:n?e.jsx(Lr,{className:"h-4 w-4 text-green-500"}):e.jsx(Zr,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("label",{className:"text-sm font-medium",children:"Quick Add"}),e.jsxs("div",{className:"grid gap-2",children:[e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-2",onClick:h,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M18.71 19.5c-.83 1.24-1.71 2.45-3.05 2.47-1.34.03-1.77-.79-3.29-.79-1.53 0-2 .77-3.27.82-1.31.05-2.3-1.32-3.14-2.53C4.25 17 2.94 12.45 4.7 9.39c.87-1.52 2.43-2.48 4.12-2.51 1.28-.02 2.5.87 3.29.87.78 0 2.26-1.07 3.81-.91.65.03 2.47.26 3.64 1.98-.09.06-2.17 1.28-2.15 3.81.03 3.02 2.65 4.03 2.68 4.04-.03.07-.42 1.44-1.38 2.83M13 3.5c.73-.83 1.94-1.46 2.94-1.5.13 1.17-.34 2.35-1.04 3.19-.69.85-1.83 1.51-2.95 1.42-.15-1.15.41-2.35 1.05-3.11z"})}),"Add to Apple Calendar",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-2",onClick:p,children:[e.jsxs("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:[e.jsx("path",{d:"M19.5 22h-15A2.5 2.5 0 0 1 2 19.5v-15A2.5 2.5 0 0 1 4.5 2H9v2H4.5a.5.5 0 0 0-.5.5v15a.5.5 0 0 0 .5.5h15a.5.5 0 0 0 .5-.5V15h2v4.5a2.5 2.5 0 0 1-2.5 2.5z"}),e.jsx("path",{d:"M12 2v8.5a1.5 1.5 0 0 0 1.5 1.5H22V2h-10z",fill:"#4285F4"}),e.jsx("path",{d:"M12 12V2H4.5A2.5 2.5 0 0 0 2 4.5V12h10z",fill:"#34A853"}),e.jsx("path",{d:"M2 12v7.5A2.5 2.5 0 0 0 4.5 22H12v-10H2z",fill:"#FBBC05"}),e.jsx("path",{d:"M12 22h7.5a2.5 2.5 0 0 0 2.5-2.5V12h-10v10z",fill:"#EA4335"})]}),"Add to Google Calendar",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]}),e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-2",onClick:f,children:[e.jsx("svg",{className:"h-4 w-4",viewBox:"0 0 24 24",fill:"currentColor",children:e.jsx("path",{d:"M7.88 12.04q0 .45-.11.87-.1.41-.33.74-.22.33-.58.52-.37.2-.87.2t-.85-.2q-.35-.21-.57-.55-.22-.33-.33-.75-.1-.42-.1-.86t.1-.87q.1-.43.34-.76.22-.34.59-.54.36-.2.87-.2t.86.2q.35.21.57.55.22.34.31.77.1.43.1.88zM24 12v9.38q0 .46-.33.8-.33.32-.8.32H7.13q-.46 0-.8-.33-.32-.33-.32-.8V18H1q-.41 0-.7-.3-.3-.29-.3-.7V7q0-.41.3-.7Q.58 6 1 6h6.5V2.55q0-.44.3-.75.3-.3.75-.3h12.9q.44 0 .75.3.3.3.3.75V12zm-6-8.25v3h3v-3zm0 4.5v3h3v-3zm0 4.5v1.83l3.05-1.83zm-5.25-9v3h3.75v-3zm0 4.5v3h3.75v-3zm0 4.5v2.03l2.41 1.5 1.34-.81v-2.72zM9 3.75V6h2l.13.01.12.04v-2.3zM5.98 15.98q.9 0 1.6-.3.7-.32 1.19-.86.48-.55.73-1.28.25-.74.25-1.61 0-.83-.25-1.55-.24-.71-.71-1.24t-1.15-.83q-.68-.3-1.55-.3-.92 0-1.64.3-.71.3-1.2.85-.5.54-.75 1.3-.25.74-.25 1.63 0 .85.26 1.56.26.72.74 1.23.48.52 1.17.81.69.3 1.56.3zM7.5 21h12.39L12 16.08V17q0 .41-.3.7-.29.3-.7.3H7.5zm15-.13v-7.24l-5.9 3.54Z"})}),"Add to Outlook",e.jsx(tr,{className:"h-3 w-3 ml-auto opacity-50"})]})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center pt-2",children:"Events sync automatically. If your membership expires, the calendar will show as empty."})]}):e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate your personal calendar subscription URL to get started."}),e.jsx(B,{onClick:()=>c.mutate(),disabled:c.isPending,className:"w-full",children:c.isPending?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),"Generate Calendar URL"]})})]})})]})]})}const nms={first_timer:oa,regular:K2,dedicated:fc,veteran:xo,streak_master:Hc,century:xo},rms={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 dVe(s){return s===1?e.jsx(xo,{className:"h-5 w-5 text-yellow-500"}):s===2?e.jsx(K2,{className:"h-5 w-5 text-gray-400"}):s===3?e.jsx(fc,{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 yxt({showUserStats:s=!0,compact:t=!1,brokerageId:n,title:r="Event Leaderboard"}){const{user:a}=vs(),{data:i,isLoading:l}=Fmt(t?5:10,n),{data:o}=zmt(a==null?void 0:a.id),{data:c}=$mt(a==null?void 0:a.id),{data:d}=Bmt(a==null?void 0:a.id);return l?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((u,h)=>e.jsx(Ws,{className:"h-12 w-full"},h))})})]}):e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5 text-yellow-500"}),r]})}),e.jsxs(Ee,{children:[s&&o&&e.jsxs("div",{className:"mb-4 p-3 rounded-lg bg-primary/5 border border-primary/10",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("span",{className:"text-sm font-medium",children:"Your Stats"}),c&&e.jsxs(Ue,{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(Hc,{className:"h-4 w-4 text-orange-500"}),e.jsx("div",{className:"text-lg font-bold",children:o.current_streak}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Streak"})]})]}),d&&d.length>0&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[d.slice(0,4).map(u=>{const h=nms[u.badge_type]||oa;return e.jsxs(Ue,{variant:"outline",className:`text-xs ${rms[u.badge_type]||""}`,title:u.badge_description||"",children:[e.jsx(h,{className:"h-3 w-3 mr-1"}),u.badge_name]},u.id)}),d.length>4&&e.jsxs(Ue,{variant:"outline",className:"text-xs",children:["+",d.length-4," more"]})]})]}),e.jsxs(Fr,{defaultValue:"points",className:"w-full",children:[e.jsxs(Rr,{className:"w-full mb-3",children:[e.jsx(Zt,{value:"points",className:"flex-1",children:"By Points"}),e.jsx(Zt,{value:"events",className:"flex-1",children:"By Events"})]}),e.jsx(is,{value:"points",className:"mt-0",children:e.jsxs("div",{className:"space-y-2",children:[i==null?void 0:i.map((u,h)=>{var p,f,y;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:dVe(h+1)}),e.jsx(Jr,{className:"h-8 w-8",children:e.jsx(ea,{className:"text-xs",children:((f=(p=u.profile)==null?void 0:p.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((y=u.profile)==null?void 0:y.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_events_attended," events"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold text-primary",children:u.total_points}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"pts"})]})]},u.user_id)}),(!i||i.length===0)&&e.jsx("div",{className:"text-center text-muted-foreground py-4 text-sm",children:"No attendance data yet. Attend an event to get on the leaderboard!"})]})}),e.jsx(is,{value:"events",className:"mt-0",children:e.jsx("div",{className:"space-y-2",children:[...i||[]].sort((u,h)=>h.total_events_attended-u.total_events_attended).map((u,h)=>{var p,f,y;return e.jsxs("div",{className:`flex items-center gap-3 p-2 rounded-lg ${u.user_id===(a==null?void 0:a.id)?"bg-primary/5 border border-primary/10":""} ${h===0?"bg-yellow-500/5":""}`,children:[e.jsx("div",{className:"w-6 flex justify-center",children:dVe(h+1)}),e.jsx(Jr,{className:"h-8 w-8",children:e.jsx(ea,{className:"text-xs",children:((f=(p=u.profile)==null?void 0:p.name)==null?void 0:f.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium text-sm truncate",children:[((y=u.profile)==null?void 0:y.name)||"Unknown",u.user_id===(a==null?void 0:a.id)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(You)"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[u.total_points," points"]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"font-bold",children:u.total_events_attended}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"events"})]})]},u.user_id)})})})]})]})]})}function ams(){const s=Ln(),{user:t,isAdmin:n}=vs(),r=Kt(),{data:a,isLoading:i}=dt({queryKey:["public-events"],queryFn:async()=>{const{data:_,error:v}=await q.from("events").select("*").order("event_date",{ascending:!0});if(v)throw v;return _}}),{data:l}=dt({queryKey:["my-registrations"],queryFn:async()=>{if(!t)return[];const{data:_,error:v}=await q.from("event_registrations").select("event_id, zoom_join_url").eq("user_id",t.id);if(v)throw v;return _},enabled:!!t}),{data:o}=dt({queryKey:["event-registration-counts"],queryFn:async()=>{let _=[],v=0;const j=1e3;for(;;){const{data:S,error:A}=await q.from("event_registrations").select("event_id").range(v,v+j-1);if(A)throw A;if(!S||S.length===0||(_=_.concat(S),S.length{w[S.event_id]=(w[S.event_id]||0)+1}),w}}),c=yt({mutationFn:async _=>{await q.auth.refreshSession();const{data:v,error:j}=await q.functions.invoke("zoom-register",{body:{event_id:_}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:_=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),_!=null&&_.join_url?ae.success("Successfully registered! You'll receive a Zoom confirmation email."):ae.success("Successfully registered for the event!")},onError:_=>{ae.error("Failed to register: "+_.message)}}),d=yt({mutationFn:async _=>{const{data:v,error:j}=await q.functions.invoke("zoom-unregister",{body:{event_id:_}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{r.invalidateQueries({queryKey:["my-registrations"]}),r.invalidateQueries({queryKey:["event-registration-counts"]}),ae.success("Registration cancelled and removed from Zoom")},onError:_=>{ae.error("Failed to cancel: "+_.message)}}),u=_=>l==null?void 0:l.some(v=>v.event_id===_),h=_=>{const v=l==null?void 0:l.find(j=>j.event_id===_);return v==null?void 0:v.zoom_join_url},p=_=>_.capacity?((o==null?void 0:o[_.id])||0)>=_.capacity:!1,f=(a==null?void 0:a.filter(_=>CL(_.event_date)!=="ended"))||[],y=(a==null?void 0:a.filter(_=>CL(_.event_date)==="ended"))||[];return e.jsx(Cs,{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(sms,{}),n&&e.jsx(B,{variant:"outline",onClick:()=>s("/admin/events"),children:"Manage Events"})]})]}),e.jsxs("div",{className:`grid grid-cols-1 ${n?"lg:grid-cols-3":""} gap-6`,children:[e.jsxs("div",{className:n?"lg:col-span-2":"",children:[i?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading events..."}):f.length===0?e.jsx(fe,{className:"text-center py-12",children:e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground",children:"No upcoming events at the moment. Check back soon!"})})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2",children:f.map(_=>{const v=CL(_.event_date),j=ZMe(_.event_date),w=v==="live",S=v==="starting_soon";return e.jsxs(fe,{className:`flex flex-col overflow-hidden cursor-pointer hover:shadow-lg transition-all ${w?"border-red-500 ring-2 ring-red-500/20":S?"border-amber-500 ring-2 ring-amber-500/20":"hover:border-primary/50"}`,onClick:()=>s(`/events/${_.id}`),children:[j&&e.jsxs("div",{className:`${w?"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"})]}),w?e.jsxs(e.Fragment,{children:[e.jsx(yf,{className:"h-3.5 w-3.5"}),"LIVE NOW"]}):e.jsxs(e.Fragment,{children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),"STARTING SOON"]})]}),_.image_url&&e.jsxs(tms,{ratio:16/9,className:"overflow-hidden relative bg-neutral-900",children:[e.jsx("img",{src:_.image_url,alt:"","aria-hidden":"true",className:"absolute inset-0 w-full h-full object-cover blur-2xl scale-110 opacity-60"}),e.jsx("img",{src:_.image_url,alt:_.title,className:"relative w-full h-full object-contain group-hover:scale-[1.03] transition-transform"})]}),e.jsxs(It,{children:[e.jsx(Rt,{className:"line-clamp-2",children:_.title}),_.description&&e.jsx(Vn,{className:"line-clamp-2",children:_.description.replace(/<[^>]*>/g,"")})]}),e.jsxs(Ee,{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(yr,{className:"h-4 w-4"}),new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(_.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(pr,{className:"h-4 w-4"}),oB(new Date(_.event_date))]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(An,{className:"h-4 w-4"}),(o==null?void 0:o[_.id])||0," registered",_.capacity&&` / ${_.capacity} spots`]})]}),e.jsx(V9,{className:"flex gap-2",onClick:A=>A.stopPropagation(),children:u(_.id)?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>d.mutate(_.id),disabled:d.isPending,children:[e.jsx($n,{className:"h-4 w-4 mr-2"}),"Cancel"]}),e.jsxs(B,{className:"flex-1",onClick:()=>window.open(h(_.id)||_.zoom_link,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Join Zoom"]})]}):e.jsx(B,{className:"w-full",onClick:()=>c.mutate(_.id),disabled:c.isPending||p(_),children:p(_)?"Event Full":e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-4 w-4 mr-2"}),"Register"]})})})]},_.id)})}),y.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:y.map(_=>e.jsx(fe,{className:"opacity-60 cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>s(`/events/${_.id}`),children:e.jsxs(It,{children:[e.jsx(Rt,{className:"text-base line-clamp-1",children:_.title}),e.jsx(Vn,{children:new Intl.DateTimeFormat("en-US",{year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(_.event_date))})]})},_.id))})]})]}),n&&e.jsx("div",{className:"lg:col-span-1",children:e.jsx(yxt,{showUserStats:!0})})]})]})})}const e2e=[{value:"all",label:"All Roles",icon:An},{value:"newest",label:"Newest Members",icon:pr},{value:"brokerage_manager",label:"Brokerage Managers",icon:C9},{value:"admin",label:"Admins",icon:Ih}];function ims({open:s,onOpenChange:t,resourceType:n,resourceId:r,resourceTitle:a}){var Ae,Be;const{user:i,isAdmin:l,isBrokerageManager:o}=vs(),[c,d]=N.useState([]),[u,h]=N.useState([]),[p,f]=N.useState([]),[y,_]=N.useState([]),[v,j]=N.useState(""),[w,S]=N.useState(""),[A,E]=N.useState(""),[O,D]=N.useState(!1),[I,F]=N.useState(!1),[z,H]=N.useState("agents"),[Z,Y]=N.useState("all"),[W,ee]=N.useState({}),se=l||o;N.useEffect(()=>{s&&i&&(l?oe():he())},[s,i,l]),N.useEffect(()=>{s||(f([]),_([]),j(""),S(""),E(""),H("agents"),Y("all"))},[s]);const oe=async()=>{if(i){D(!0);try{const{data:we,error:Je}=await q.from("brokerages").select("id, name").order("name");if(Je)throw Je;const ke=1e3,it={};let je=0,He=!0;for(;He;){const{data:Ge,error:rt}=await q.from("profiles").select("brokerage_id").range(je*ke,(je+1)*ke-1);if(rt)throw rt;Ge==null||Ge.forEach(tt=>{tt.brokerage_id&&(it[tt.brokerage_id]=(it[tt.brokerage_id]||0)+1)}),He=(Ge==null?void 0:Ge.length)===ke,je++}h((we==null?void 0:we.map(Ge=>({...Ge,agent_count:it[Ge.id]||0})))||[]);const $e=[];for(je=0,He=!0;He;){const{data:Ge,error:rt}=await q.from("profiles").select("id, name, email, brokerage_id, created_at, brokerages(name)").neq("id",i.id).order("name").range(je*ke,(je+1)*ke-1);if(rt)throw rt;Ge&&$e.push(...Ge),He=(Ge==null?void 0:Ge.length)===ke,je++}const Ke={};for(je=0,He=!0;He;){const{data:Ge,error:rt}=await q.from("user_roles").select("user_id, role").range(je*ke,(je+1)*ke-1);if(rt)throw rt;Ge==null||Ge.forEach(tt=>{Ke[tt.user_id]||(Ke[tt.user_id]=[]),Ke[tt.user_id].push(tt.role)}),He=(Ge==null?void 0:Ge.length)===ke,je++}ee(Ke),d($e.map(Ge=>{var rt;return{id:Ge.id,name:Ge.name,email:Ge.email,brokerage_name:((rt=Ge.brokerages)==null?void 0:rt.name)||"No Brokerage",roles:Ke[Ge.id]||[],created_at:Ge.created_at}}))}catch(we){console.error("Error loading data:",we),ae.error("Failed to load agents and brokerages")}finally{D(!1)}}},he=async()=>{if(i){D(!0);try{const{data:we}=await q.from("profiles").select("brokerage_id").eq("id",i.id).single();if(!(we!=null&&we.brokerage_id)){ae.error("You must be part of a brokerage to share resources"),t(!1);return}const{data:Je,error:ke}=await q.from("profiles").select("id, name, email").eq("brokerage_id",we.brokerage_id).neq("id",i.id).order("name");if(ke)throw ke;d(Je||[])}catch(we){console.error("Error loading agents:",we),ae.error("Failed to load agents")}finally{D(!1)}}},ce=c.filter(we=>{var ke;const Je=we.name.toLowerCase().includes(v.toLowerCase())||we.email.toLowerCase().includes(v.toLowerCase())||((ke=we.brokerage_name)==null?void 0:ke.toLowerCase().includes(v.toLowerCase()));if(l&&Z!=="all"&&Z!=="newest"){const it=W[we.id]||[];return Je&&it.includes(Z)}return Je}).sort((we,Je)=>Z==="newest"?(Je.created_at||"").localeCompare(we.created_at||""):0),me=u.filter(we=>we.name.toLowerCase().includes(w.toLowerCase())),le=()=>{p.length===ce.length?f([]):f(ce.map(we=>we.id))},ve=()=>{y.length===me.length?_([]):_(me.map(we=>we.id))},ge=we=>{if(!se){f([we]);return}f(Je=>Je.includes(we)?Je.filter(ke=>ke!==we):[...Je,we])},Te=we=>{_(Je=>Je.includes(we)?Je.filter(ke=>ke!==we):[...Je,we])},Ie=async()=>{if(!(p.length>0||y.length>0)){ae.error("Please select at least one agent or brokerage to share with");return}F(!0);try{const{data:Je,error:ke}=await q.functions.invoke("send-share-notification",{body:{recipientIds:p,brokerageIds:y,resourceType:n,resourceId:r,resourceTitle:a,message:A.trim()||void 0}});if(ke)throw ke;const it=(Je==null?void 0:Je.sharesCreated)||p.length;ae.success(`Shared with ${it} agent${it!==1?"s":""}`),t(!1)}catch(Je){console.error("Error sharing resource:",Je),ae.error("Failed to share resource")}finally{F(!1)}},Ce=we=>we.split(" ").map(Je=>Je[0]).join("").toUpperCase().slice(0,2),Me=we=>{const Je=W[we]||[];return Je.includes("admin")?e.jsx(Ue,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:"Admin"}):Je.includes("brokerage_manager")?e.jsx(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:"Manager"}):null},Pe=p.length+y.length,Re=Z!=="all"&&Z!=="newest"?ce.length:null;return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{className:"flex-shrink-0",children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(lr,{className:"h-5 w-5 text-primary"}),"Share Resource"]}),e.jsxs(Jn,{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(Fr,{value:z,onValueChange:H,className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-2 flex-shrink-0",children:[e.jsxs(Zt,{value:"agents",className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4"}),e.jsx("span",{children:"Agents"}),p.length>0&&e.jsx(Ue,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:p.length})]}),e.jsxs(Zt,{value:"brokerages",className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4"}),e.jsx("span",{children:"Brokerages"}),y.length>0&&e.jsx(Ue,{variant:"default",className:"h-5 min-w-5 px-1.5 text-xs",children:y.length})]})]}),e.jsxs(is,{value:"agents",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"flex gap-2 flex-shrink-0",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or brokerage...",value:v,onChange:we=>j(we.target.value),className:"pl-9"})]}),e.jsxs(us,{value:Z,onValueChange:Y,children:[e.jsxs(ls,{className:"w-[180px]",children:[e.jsx(Lv,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(hs,{placeholder:"Filter by role"})]}),e.jsx(cs,{children:e2e.map(we=>e.jsx(Ze,{value:we.value,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(we.icon,{className:"h-4 w-4"}),e.jsx("span",{children:we.label})]})},we.value))})]})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:le,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(An,{className:"h-3.5 w-3.5 mr-1.5"}),p.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[Re!==null&&e.jsxs("span",{className:"text-primary font-medium",children:[Re," ",(Ae=e2e.find(we=>we.value===Z))==null?void 0:Ae.label]}),e.jsxs("span",{className:"font-medium",children:[p.length," selected"]})]})]}),e.jsx(di,{className:"h-[300px] border rounded-lg",children:O?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(An,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:Z!=="all"?`No ${(Be=e2e.find(we=>we.value===Z))==null?void 0:Be.label.toLowerCase()} found`:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ce.map(we=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${p.includes(we.id)?"bg-accent":""}`,onClick:()=>ge(we.id),children:[e.jsx(hi,{checked:p.includes(we.id),onCheckedChange:()=>ge(we.id),className:"flex-shrink-0"}),e.jsx(Jr,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(ea,{className:"text-xs bg-primary/10 text-primary",children:Ce(we.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:we.name}),Me(we.id)]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[we.email,we.brokerage_name&&e.jsxs("span",{className:"ml-1 opacity-75",children:["• ",we.brokerage_name]})]})]})]},we.id))})})]}),e.jsxs(is,{value:"brokerages",className:"flex-1 flex flex-col space-y-3 mt-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:w,onChange:we=>S(we.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:ve,className:"text-xs h-8",disabled:me.length===0,children:[e.jsx(Ua,{className:"h-3.5 w-3.5 mr-1.5"}),y.length===me.length&&me.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[y.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(di,{className:"h-[250px] border rounded-lg",children:O?e.jsx("div",{className:"flex items-center justify-center h-[180px]",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):me.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[180px] text-muted-foreground",children:[e.jsx(Ua,{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:me.map(we=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${y.includes(we.id)?"bg-accent":""}`,onClick:()=>Te(we.id),children:[e.jsx(hi,{checked:y.includes(we.id),onCheckedChange:()=>Te(we.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(Ua,{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:we.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[we.agent_count," agent",we.agent_count!==1?"s":""]})]})]},we.id))})})]})]}):e.jsxs("div",{className:"flex-1 flex flex-col space-y-3 overflow-hidden",children:[e.jsxs("div",{className:"relative flex-shrink-0",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:v,onChange:we=>j(we.target.value),className:"pl-9"})]}),se&&e.jsxs("div",{className:"flex items-center justify-between px-1 flex-shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:le,className:"text-xs h-8",disabled:ce.length===0,children:[e.jsx(An,{className:"h-3.5 w-3.5 mr-1.5"}),p.length===ce.length&&ce.length>0?"Deselect All":"Select All"]}),e.jsxs("span",{className:"text-xs text-muted-foreground font-medium",children:[p.length," selected"]})]}),e.jsx(di,{className:"h-[300px] border rounded-lg",children:O?e.jsx("div",{className:"flex items-center justify-center h-[200px]",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):ce.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center h-[200px] text-muted-foreground",children:[e.jsx(An,{className:"h-8 w-8 mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No agents found"})]}):e.jsx("div",{className:"p-2 space-y-1",children:ce.map(we=>e.jsxs("div",{className:`flex items-center gap-3 p-2.5 rounded-lg cursor-pointer hover:bg-accent/50 transition-colors ${p.includes(we.id)?"bg-accent":""}`,onClick:()=>ge(we.id),children:[e.jsx(hi,{checked:p.includes(we.id),onCheckedChange:()=>ge(we.id),className:"flex-shrink-0"}),e.jsx(Jr,{className:"h-9 w-9 flex-shrink-0",children:e.jsx(ea,{className:"text-xs bg-primary/10 text-primary",children:Ce(we.name)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:we.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:we.email})]})]},we.id))})})]}),e.jsxs("div",{className:"space-y-2 flex-shrink-0",children:[e.jsx(ne,{htmlFor:"message",className:"text-sm font-medium",children:"Add a message (optional)"}),e.jsx(Ms,{id:"message",placeholder:"I thought you might find this useful...",value:A,onChange:we=>E(we.target.value),rows:2,className:"resize-none"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 flex-shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:Ie,disabled:Pe===0||I,children:I?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Sharing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Share"]})})]})]})]})})}function HD({resourceType:s,resourceId:t,resourceTitle:n,variant:r="outline",size:a="sm",className:i=""}){const[l,o]=N.useState(!1),{user:c}=vs();return c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:r,size:a,onClick:()=>o(!0),className:i,children:[e.jsx(Vl,{className:"h-4 w-4 mr-2"}),"Share"]}),e.jsx(ims,{open:l,onOpenChange:o,resourceType:s,resourceId:t,resourceTitle:n})]}):null}function oms(){const{eventId:s}=bi(),t=Ln(),{user:n}=vs(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(0),[d,u]=N.useState(!0),[h,p]=N.useState(!1);N.useEffect(()=>{s&&f()},[s,n]);const f=async()=>{try{const{data:S,error:A}=await q.from("events").select("*").eq("id",s).single();if(A)throw A;a(S);const{count:E}=await q.from("event_registrations").select("*",{count:"exact",head:!0}).eq("event_id",s);if(c(E||0),n){const{data:O}=await q.from("event_registrations").select("id, zoom_join_url").eq("event_id",s).eq("user_id",n.id).maybeSingle();l(O)}}catch(S){console.error("Error loading event:",S),ae.error("Failed to load event"),t("/events")}finally{u(!1)}},y=async()=>{if(!(!n||!r)){p(!0);try{const{error:S}=await q.auth.refreshSession();if(S){console.error("Session refresh failed:",S),ae.error("Your session has expired. Please log in again.");return}if(i){const{error:A}=await q.functions.invoke("zoom-unregister",{body:{event_id:r.id}});if(A)throw A;ae.success("Successfully cancelled registration"),l(null),c(E=>E-1)}else{const{data:A,error:E}=await q.functions.invoke("zoom-register",{body:{event_id:r.id}});if(E)throw E;ae.success("Successfully registered for event!"),l({id:A.registration_id,zoom_join_url:A.zoom_join_url}),c(O=>O+1)}}catch(S){console.error("Registration error:",S),ae.error(i?"Failed to cancel registration":"Failed to register for event")}finally{p(!1)}}},_=S=>{var A,E,O;if(S.includes("iframe.mediadelivery.net")||S.includes("video.bunnycdn.com")){const D=S.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(D)return`https://iframe.mediadelivery.net/embed/${D[1]}/${D[2]}?autoplay=false&preload=true`}if(S.includes("youtube.com")||S.includes("youtu.be")){const D=S.includes("youtu.be")?(A=S.split("youtu.be/")[1])==null?void 0:A.split("?")[0]:(E=S.split("v=")[1])==null?void 0:E.split("&")[0];if(D)return`https://www.youtube.com/embed/${D}`}if(S.includes("vimeo.com")){const D=(O=S.split("vimeo.com/")[1])==null?void 0:O.split("?")[0];if(D)return`https://player.vimeo.com/video/${D}`}return S};if(d)return e.jsx(Cs,{title:"Event",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading event..."})]})})});if(!r)return e.jsx(Cs,{title:"Event Not Found",children:e.jsxs("div",{className:"text-center py-16",children:[e.jsx("p",{className:"text-muted-foreground",children:"Event not found"}),e.jsx(B,{onClick:()=>t("/events"),className:"mt-4",children:"Back to Events"})]})});const v=vw(new Date(r.event_date)),j=r.capacity&&o>=r.capacity,w=(i==null?void 0:i.zoom_join_url)||r.zoom_link;return e.jsx(Cs,{title:r.title,children:e.jsxs("div",{className:"max-w-4xl mx-auto",children:[e.jsxs(B,{variant:"ghost",className:"mb-6 gap-2",onClick:()=>t("/events"),children:[e.jsx(qr,{className:"h-4 w-4"}),"Back to Events"]}),r.image_url&&e.jsxs("div",{className:"relative aspect-video rounded-xl overflow-hidden mb-6",children:[e.jsx("img",{src:r.image_url,alt:r.title,className:"w-full h-full object-cover"}),v&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Ue,{variant:"secondary",className:"text-lg px-4 py-2",children:"Event Ended"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 mb-4",children:[e.jsx("h1",{className:"text-3xl font-bold text-foreground",children:r.title}),e.jsx(HD,{resourceType:"event",resourceId:r.id,resourceTitle:r.title})]}),r.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground dark:prose-invert",dangerouslySetInnerHTML:{__html:r.description}})]}),r.video_url&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(jh,{className:"h-5 w-5"}),"Event Preview"]}),e.jsx("div",{className:"relative w-full aspect-video rounded-xl overflow-hidden border bg-muted",children:e.jsx("iframe",{src:_(r.video_url),className:"absolute inset-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:"Event Preview Video"})})]})]}),e.jsx("div",{className:"space-y-4",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(yr,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:new Intl.DateTimeFormat("en-US",{weekday:"long",year:"numeric",month:"long",day:"numeric",timeZone:"America/New_York"}).format(new Date(r.event_date))}),e.jsx("p",{className:"text-sm text-muted-foreground",children:oB(new Date(r.event_date))})]})]}),r.capacity&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(An,{className:"h-5 w-5 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:[o," / ",r.capacity]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Registered"})]})]}),i&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-green-500/10 rounded-lg",children:[e.jsx(Pi,{className:"h-5 w-5 text-green-600"}),e.jsx("span",{className:"text-sm font-medium text-green-700",children:"You're registered!"})]}),e.jsxs("div",{className:"space-y-2 pt-2",children:[!v&&e.jsx(e.Fragment,{children:i?e.jsxs(e.Fragment,{children:[e.jsxs(B,{className:"w-full gap-2",onClick:()=>window.open(w,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"Join Event"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:y,disabled:h,children:[h?e.jsx(rs,{className:"h-4 w-4 animate-spin mr-2"}):null,"Cancel Registration"]})]}):e.jsx(B,{className:"w-full gap-2",onClick:y,disabled:h||(j??!1),children:h?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):j?"Event Full":"Register Now"})}),v&&i&&e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:()=>window.open(r.zoom_link,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"View Recording"]})]})]})})})]})]})})}const lms=[{id:"quickvid",name:"QuickVid",description:"Record, manage, and share personalized video messages",icon:e.jsx(fr,{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(uf,{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(ny,{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(br,{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(rm,{className:"h-6 w-6"}),path:"/mission-control/guest-book",category:"Open House",color:"bg-orange-500/15 text-orange-600"},{id:"card-studio",name:"Card Studio",description:"Send beautiful animated digital cards for birthdays, anniversaries & milestones",icon:e.jsx(un,{className:"h-6 w-6"}),path:"/mission-control/card-studio",category:"Marketing",color:"bg-pink-500/15 text-pink-600"},{id:"direct-mail",name:"Direct Mail",description:"Send professional postcards to your contacts via direct mail",icon:e.jsx(Gs,{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(Sh,{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(lr,{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(J1,{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(lL,{className:"h-6 w-6"}),path:"/website-apps",category:"Website",isNew:!0,color:"bg-cyan-500/15 text-cyan-600"},{id:"newsletter-pro",name:"Newsletter Pro",description:"Design and send beautiful branded newsletters to your database",icon:e.jsx(sy,{className:"h-6 w-6"}),path:"/newsletters",category:"Marketing",color:"bg-yellow-500/15 text-yellow-600"},{id:"cma",name:"CMA Reports",description:"Build interactive CMAs with live comps, share with clients, and auto-create deals",icon:e.jsx(_o,{className:"h-6 w-6"}),path:"/mission-control/cma",category:"Marketing",isNew:!0,requiresLeadSiteMLS:!0,color:"bg-blue-500/15 text-blue-600"}],cms=()=>{const{user:s,isAdmin:t}=vs(),n=Ln(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,y]=N.useState(new Set),[_,v]=N.useState(!1);N.useEffect(()=>{j()},[s]);const j=async()=>{try{const{data:H}=await q.from("user_tags").select("tag").eq("user_id",s==null?void 0:s.id),Z=(H==null?void 0:H.map(ge=>ge.tag))||[],{data:Y,error:W}=await q.from("app_tiles").select("*").order("name");if(W)throw W;const[{data:ee},{data:se},{data:oe}]=await Promise.all([q.from("user_favorites").select("app_id").eq("user_id",s==null?void 0:s.id),q.from("user_tool_favorites").select("tool_id").eq("user_id",s==null?void 0:s.id),q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",s==null?void 0:s.id)]),he=(oe||[]).some(ge=>ge.is_active&&ge.mls_provider_id&&!ge.no_mls_mode);v(he);const ce=new Set((ee==null?void 0:ee.map(ge=>ge.app_id))||[]);p(ce);const me=new Set((se||[]).map(ge=>ge.tool_id));y(me);const ve=((Y==null?void 0:Y.filter(ge=>ge.app_id==="newsletter_studio"?!1:!ge.required_tags||ge.required_tags.length===0?!0:ge.required_tags.some(Te=>Z.includes(Te))))||[]).sort((ge,Te)=>ge.name==="LevelUp Members Portal"?-1:Te.name==="LevelUp Members Portal"?1:0);a(ve)}catch(H){console.error("Error loading apps:",H),ae.error("Failed to load apps")}finally{l(!1)}},w=async H=>{var Y;try{const W=new URL(H.target_url);if(new Set([window.location.hostname,"dashboard.relevelup.com"]).has(W.hostname)){await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:H.app_id,app_name:H.name,user_agent:navigator.userAgent}),n(W.pathname+W.search+W.hash);return}}catch{}const Z=window.open("about:blank","_blank");try{const{data:W,error:ee}=await q.auth.getSession();if(ee||!W.session){Z==null||Z.close(),ae.error("Session expired. Please refresh the page and try again.");return}const se=W.session.access_token;await q.from("activity_logs").insert({user_id:s==null?void 0:s.id,app_id:H.app_id,app_name:H.name,user_agent:navigator.userAgent});const{data:oe,error:he}=await q.functions.invoke("sso-launch",{body:{app_id:H.app_id},headers:{Authorization:`Bearer ${se}`}});if(he)throw he;oe!=null&&oe.redirect_url?Z&&!Z.closed?(Z.location.href=oe.redirect_url,(Y=Z.focus)==null||Y.call(Z)):window.location.assign(oe.redirect_url):(Z==null||Z.close(),ae.error("Launch link unavailable"))}catch(W){Z==null||Z.close(),console.error("Error launching app:",W),ae.error("Failed to launch app. Please try again.")}},S=async(H,Z)=>{H.stopPropagation();const Y=h.has(Z);try{if(Y){const{error:W}=await q.from("user_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("app_id",Z);if(W)throw W;p(ee=>{const se=new Set(ee);return se.delete(Z),se}),ae.success("Removed from favorites")}else{const{error:W}=await q.from("user_favorites").insert({user_id:s==null?void 0:s.id,app_id:Z});if(W)throw W;p(ee=>new Set(ee).add(Z)),ae.success("Added to favorites")}}catch(W){console.error("Error toggling favorite:",W),ae.error("Failed to update favorites")}},A=async(H,Z)=>{H.stopPropagation();const Y=f.has(Z);try{if(Y){const{error:W}=await q.from("user_tool_favorites").delete().eq("user_id",s==null?void 0:s.id).eq("tool_id",Z);if(W)throw W;y(ee=>{const se=new Set(ee);return se.delete(Z),se}),ae.success("Removed from favorites")}else{const{error:W}=await q.from("user_tool_favorites").insert({user_id:s==null?void 0:s.id,tool_id:Z});if(W)throw W;y(ee=>new Set(ee).add(Z)),ae.success("Added to favorites")}}catch(W){console.error("Error toggling tool favorite:",W),ae.error("Failed to update favorites")}},E=r.filter(H=>{var Y;const Z=H.name.toLowerCase().includes(o.toLowerCase())||((Y=H.description)==null?void 0:Y.toLowerCase().includes(o.toLowerCase()));return d==="favorites"?Z&&h.has(H.id):Z}),O=lms.filter(H=>{if(H.adminOnly&&!t||H.requiresLeadSiteMLS&&!_&&!t)return!1;const Z=H.name.toLowerCase().includes(o.toLowerCase())||H.description.toLowerCase().includes(o.toLowerCase());return d==="favorites"?Z&&f.has(H.id):Z}),D=O.reduce((H,Z)=>(H[Z.category]||(H[Z.category]=[]),H[Z.category].push(Z),H),{}),I=[{id:"all",label:"All"},{id:"tools",label:"Built-in Tools"},{id:"apps",label:"Connected Apps"},{id:"favorites",label:"Favorites"}];if(i)return e.jsx(Cs,{title:"Apps & Tools",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"Loading apps & tools..."})]})})});const F=d==="all"||d==="tools"||d==="favorites",z=d==="all"||d==="apps"||d==="favorites";return e.jsxs(Cs,{title:"Apps & Tools",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 mb-6",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground",children:"Apps & Tools"}),e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search apps & tools...",className:"pl-10 bg-muted/50 border-0 focus-visible:ring-1",value:o,onChange:H=>c(H.target.value)})]})]}),e.jsx("div",{className:"flex gap-6 border-b border-border mb-8",children:I.map(H=>e.jsxs("button",{onClick:()=>u(H.id),className:Mt("pb-3 text-sm font-medium transition-colors relative",d===H.id?"text-primary":"text-muted-foreground hover:text-foreground"),children:[H.label,d===H.id&&e.jsx("span",{className:"absolute bottom-0 left-0 right-0 h-0.5 bg-primary"})]},H.id))}),F&&Object.keys(D).length>0&&e.jsxs("div",{className:"mb-10",children:[d==="all"&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(gb,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Built-in Tools"})]}),Object.entries(D).map(([H,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:H})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:Z.map(Y=>{const W=f.has(Y.id);return e.jsxs("div",{onClick:()=>n(Y.path),className:Mt("group flex items-start gap-4 p-5 bg-card rounded-xl border transition-all duration-200 hover:shadow-lg cursor-pointer relative overflow-hidden",Y.isNew?"border-primary/40 ring-1 ring-primary/20 hover:border-primary/60":"border-border hover:border-primary/30"),children:[Y.isNew&&e.jsx("div",{className:"absolute top-0 right-0 bg-gradient-to-r from-violet-500 to-indigo-500 text-white text-[10px] font-bold uppercase px-3 py-0.5 rounded-bl-lg tracking-wider shadow-sm",children:"✨ New"}),e.jsx("div",{className:Mt("flex-shrink-0 w-14 h-14 rounded-xl flex items-center justify-center transition-transform group-hover:scale-105",Y.color||"bg-primary/10 text-primary"),children:Y.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors truncate flex items-center gap-2",children:[Y.name,Y.beta&&e.jsx("span",{className:"text-[10px] font-semibold bg-amber-100 text-amber-700 px-1.5 py-0.5 rounded-full border border-amber-200",children:"Beta"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:Y.description})]}),e.jsx("button",{className:Mt("flex-shrink-0 p-1 transition-colors",W?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:ee=>A(ee,Y.id),children:e.jsx(Pv,{className:Mt("h-5 w-5",W&&"fill-current")})})]},Y.id)})})]},H))]}),z&&e.jsxs("div",{children:[d==="all"&&E.length>0&&e.jsxs("div",{className:"flex items-center gap-2 mb-5",children:[e.jsx(tr,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground",children:"Connected Apps"})]}),E.length===0&&d!=="all"&&!(d==="favorites"&&O.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(Pv,{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(Gc,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No apps available"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:t?"Get started by adding apps in the admin panel":"Contact your administrator to get access to apps"}),t&&e.jsx(B,{className:"mt-4",onClick:()=>n("/admin/apps"),children:"Add Apps"})]})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:E.map(H=>{const Z=h.has(H.id),Y=H.name.toLowerCase().includes("agent review")||H.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:()=>w(H),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:H.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:H.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:H.description})]}),e.jsx("button",{className:Mt("flex-shrink-0 p-1 transition-colors",Z?"text-primary":"text-muted-foreground/50 hover:text-primary"),onClick:W=>S(W,H.id),children:e.jsx(Pv,{className:Mt("h-5 w-5",Z&&"fill-current")})})]}),Y&&e.jsx("a",{href:"https://forms.gle/vXnrzgSnPbw7CKPV6",target:"_blank",rel:"noopener noreferrer",onClick:W=>W.stopPropagation(),className:"mt-3 text-sm text-primary hover:underline flex items-center gap-1",children:"Create your account with this link →"})]},H.id)})})]}),F&&z&&E.length===0&&O.length===0&&o&&e.jsxs("div",{className:"flex flex-col items-center justify-center py-16 bg-card rounded-xl border border-border",children:[e.jsx(gr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("p",{className:"text-lg font-medium mb-2 text-foreground",children:"No results found"}),e.jsx("p",{className:"text-sm text-muted-foreground text-center max-w-md",children:"Try a different search term"})]})]})},dms=()=>{var S;const s=Ln(),{isAdmin:t}=vs(),[n,r]=N.useState(""),[a,i]=N.useState("all"),[l,o]=N.useState("all"),[c,d]=N.useState("grid"),{data:u=[]}=dt({queryKey:["template-categories"],queryFn:async()=>{const{data:A,error:E}=await q.from("template_categories").select("*").order("name");if(E)throw E;return A}}),{data:h=[]}=dt({queryKey:["template-types"],queryFn:async()=>{const{data:A,error:E}=await q.from("template_types").select("*").order("name");if(E)throw E;return A}}),{data:p=[],isLoading:f}=dt({queryKey:["canva-templates",t],queryFn:async()=>{const{data:A,error:E}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(E)throw E;const{data:O,error:D}=await q.from("template_links").select("*").order("sort_order");if(D)throw D;const I=async ee=>{let oe=0;const he=[];for(;;){const{data:ce,error:me}=await ee().range(oe,oe+1e3-1);if(me)throw me;if(!ce||ce.length===0||(he.push(...ce),ce.length<1e3))break;oe+=1e3}return he},F=await I(()=>q.from("template_likes").select("template_id")),z=await I(()=>q.from("template_comments").select("template_id")),H=new Map;F.forEach(ee=>{H.set(ee.template_id,(H.get(ee.template_id)||0)+1)});const Z=new Map;z.forEach(ee=>{Z.set(ee.template_id,(Z.get(ee.template_id)||0)+1)});const Y=new Map;return t&&(await I(()=>q.from("content_engagement_logs").select("resource_id").eq("resource_type","template").eq("action_type","view"))).forEach(se=>{Y.set(se.resource_id,(Y.get(se.resource_id)||0)+1)}),(A||[]).map(ee=>({...ee,links:(O||[]).filter(se=>se.template_id===ee.id)||[],likesCount:H.get(ee.id)||0,commentsCount:Z.get(ee.id)||0,viewsCount:Y.get(ee.id)||0}))}}),y=p.filter(A=>{var I;const E=A.name.toLowerCase().includes(n.toLowerCase())||((I=A.description)==null?void 0:I.toLowerCase().includes(n.toLowerCase())),O=a==="all"||A.category_id===a,D=l==="all"||A.type_id===l;return E&&O&&D}),_=()=>{r(""),i("all"),o("all")},v=n||a!=="all"||l!=="all",j=(S=[...p].sort((A,E)=>new Date(E.publish_date||E.created_at).getTime()-new Date(A.publish_date||A.created_at).getTime())[0])==null?void 0:S.id,w=A=>{s(`/templates/${A}`)};return e.jsx(Cs,{title:"Canva Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"font-bold text-foreground text-5xl",children:"Canva Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse and use our collection of professionally designed templates"})]}),!f&&p.filter(A=>A.is_featured).length>0&&e.jsxs("div",{className:"rounded-xl p-5 space-y-3",style:{backgroundColor:"#9aa8b2"},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oa,{className:"h-5 w-5 fill-foreground text-foreground"}),e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Featured Templates"})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:p.filter(A=>A.is_featured).slice(0,4).map(A=>e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer relative",onClick:()=>w(A.id),children:[e.jsxs("div",{className:"aspect-[3/2] relative overflow-hidden bg-muted",children:[A.id===j&&e.jsx(Ue,{className:"absolute top-2 left-2 z-10 font-bold border-0 hover:opacity-90",style:{backgroundColor:"#e8c369",color:"#3d2f0a"},children:"NEW!"}),A.preview_image_url?e.jsx("img",{src:A.preview_image_url,alt:A.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})]}),e.jsxs(Ee,{className:"p-3",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 text-sm",children:A.name}),A.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:qz(A.description)})]})]},A.id))})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search templates...",value:n,onChange:A=>r(A.target.value),className:"pl-9"})]}),e.jsxs(us,{value:a,onValueChange:i,children:[e.jsx(ls,{className:"w-full sm:w-48",children:e.jsx(hs,{placeholder:"All Categories"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Categories"}),u.map(A=>e.jsx(Ze,{value:A.id,children:A.name},A.id))]})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-full sm:w-48",children:e.jsx(hs,{placeholder:"All Types"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),h.map(A=>e.jsx(Ze,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex gap-2",children:[v&&e.jsx(B,{variant:"outline",size:"sm",onClick:_,children:"Clear Filters"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:c==="grid"?"secondary":"outline",size:"icon",onClick:()=>d("grid"),className:"rounded-full",children:e.jsx(ff,{className:"h-4 w-4"})}),e.jsx(B,{variant:c==="list"?"secondary":"outline",size:"icon",onClick:()=>d("list"),className:"rounded-full",children:e.jsx(Sp,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[y.length," template",y.length!==1?"s":""," found"]}),f&&e.jsx("div",{className:c==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((A,E)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ws,{className:"h-5 w-16"}),e.jsx(Ws,{className:"h-5 w-20"})]})]})},E))}),!f&&y.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:v?"No templates match your filters":"No templates available yet"}),v&&e.jsx(B,{variant:"outline",onClick:_,children:"Clear Filters"})]}),!f&&y.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:y.map(A=>e.jsxs(fe,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${c==="list"?"flex flex-row":""}`,onClick:()=>w(A.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${c==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[A.id===j&&e.jsx(Ue,{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(Ue,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm !text-secondary",children:[e.jsx(Yo,{className:"h-3 w-3"}),A.links.length]})})]}),e.jsxs(Ee,{className:`p-4 flex flex-col ${c==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:A.name}),A.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:qz(A.description)}),e.jsxs("div",{className:"flex flex-wrap gap-2 mb-3",children:[A.category&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:A.category.name}),A.type&&e.jsx(Ue,{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($m,{className:"h-3.5 w-3.5"}),A.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zl,{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(Sr,{className:"h-3.5 w-3.5"}),A.viewsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:E=>{E.stopPropagation(),w(A.id)},children:[e.jsx(tr,{className:"h-4 w-4"}),"View Template"]})]})]},A.id))})]})})};var ums="Separator",uVe="horizontal",hms=["horizontal","vertical"],vxt=N.forwardRef((s,t)=>{const{decorative:n,orientation:r=uVe,...a}=s,i=mms(r)?r:uVe,o=n?{role:"none"}:{"aria-orientation":i==="vertical"?i:void 0,role:"separator"};return e.jsx(Yr.div,{"data-orientation":i,...o,...a,ref:t})});vxt.displayName=ums;function mms(s){return hms.includes(s)}var bxt=vxt;const al=N.forwardRef(({className:s,orientation:t="horizontal",decorative:n=!0,...r},a)=>e.jsx(bxt,{ref:a,decorative:n,orientation:t,className:Mt("shrink-0 bg-border",t==="horizontal"?"h-[1px] w-full":"h-full w-[1px]",s),...r}));al.displayName=bxt.displayName;const pms=()=>{const{templateId:s}=bi(),t=Ln(),{user:n,isAdmin:r}=vs(),{toast:a}=Fa(),i=Kt(),{trackEngagement:l}=UD(),[o,c]=N.useState(""),{data:d,isLoading:u}=dt({queryKey:["template-detail",s],queryFn:async()=>{const{data:A,error:E}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("id",s).single();if(E)throw E;const{data:O}=await q.from("template_links").select("*").eq("template_id",s).order("sort_order"),{data:D}=await q.from("template_guides").select("*").eq("template_id",s).order("sort_order");return{...A,links:O||[],guides:D||[]}},enabled:!!s}),{data:h=[]}=dt({queryKey:["template-linked-toolkits",s],queryFn:async()=>{const{data:A,error:E}=await q.from("resource_kit_templates").select("kit_id, resource_kits:kit_id(id, name, featured_image_url)").eq("template_id",s);if(E)throw E;return(A||[]).map(O=>O.resource_kits).filter(Boolean)},enabled:!!s});N.useEffect(()=>{d&&l("template",d.id,d.name,"view")},[d==null?void 0:d.id]);const{data:p=[]}=dt({queryKey:["template-likes",s],queryFn:async()=>{const{data:A,error:E}=await q.from("template_likes").select("*").eq("template_id",s);if(E)throw E;return A},enabled:!!s}),{data:f=[]}=dt({queryKey:["template-comments",s],queryFn:async()=>{const{data:A,error:E}=await q.from("template_comments").select("*").eq("template_id",s).order("created_at",{ascending:!1});if(E)throw E;const O=[...new Set(A.map(F=>F.user_id))],{data:D}=await q.from("profiles").select("id, name").in("id",O),I=new Map((D==null?void 0:D.map(F=>[F.id,F.name]))||[]);return A.map(F=>({...F,user_name:I.get(F.user_id)||"Unknown User"}))},enabled:!!s}),y=yt({mutationFn:async A=>{const{error:E}=await q.from("template_comments").insert({template_id:s,user_id:n.id,content:A});if(E)throw E},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),c(""),a({title:"Comment added!"})},onError:A=>{a({title:"Error adding comment",description:A.message,variant:"destructive"})}}),_=yt({mutationFn:async A=>{const{error:E}=await q.from("template_comments").delete().eq("id",A);if(E)throw E},onSuccess:()=>{i.invalidateQueries({queryKey:["template-comments",s]}),a({title:"Comment deleted"})}}),v=yt({mutationFn:async()=>{const A=p.find(E=>E.user_id===(n==null?void 0:n.id));if(A){const{error:E}=await q.from("template_likes").delete().eq("id",A.id);if(E)throw E}else{const{error:E}=await q.from("template_likes").insert({template_id:s,user_id:n.id});if(E)throw E}},onSuccess:()=>{i.invalidateQueries({queryKey:["template-likes",s]})}}),j=p.some(A=>A.user_id===(n==null?void 0:n.id)),w=A=>A.split(" ").map(E=>E[0]).join("").toUpperCase().slice(0,2),S=A=>{A.preventDefault(),!(!o.trim()||!n)&&y.mutate(o.trim())};return u?e.jsx(Cs,{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(Cs,{title:d.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(In,{to:"/templates",children:[e.jsx(qr,{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(Ue,{variant:"secondary",children:d.category.name}),d.type&&e.jsx(Ue,{variant:"outline",children:d.type.name})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r&&e.jsx(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(In,{to:`/admin/templates?edit=${d.id}`,children:[e.jsx(ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(HD,{resourceType:"template",resourceId:d.id,resourceTitle:d.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:j?"default":"outline",className:"gap-2 rounded-full",onClick:()=>v.mutate(),disabled:!n||v.isPending,children:[e.jsx($m,{className:`h-4 w-4 ${j?"fill-current":""}`}),p.length," ",p.length===1?"Like":"Likes"]})]})]}),d.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&>p]:mb-4 [&>p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:d.description}})]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Yo,{className:"h-4 w-4"}),d.links.length===1?"Template Link":"Template Links"]}),e.jsx("div",{className:"grid gap-2",children:d.links.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_canva"),window.open(A.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:A.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),d.video_url&&e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsx("div",{className:"aspect-video w-full rounded-lg overflow-hidden",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})})}),d.guides&&d.guides.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(br,{className:"h-4 w-4"}),"Guide Files"]}),e.jsx("div",{className:"grid gap-2",children:d.guides.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{l("template",d.id,d.name,"click_pdf"),window.open(A.file_url,"_blank")},children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{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(Ia,{className:"h-4 w-4 text-muted-foreground"})]},A.id))})]})}),h.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Ec,{className:"h-4 w-4"}),"Related Toolkits"]}),e.jsx("div",{className:"grid gap-2",children:h.map(A=>e.jsxs(B,{variant:"outline",className:"w-full justify-start gap-3 h-auto py-3",onClick:()=>t(`/toolbox/${A.id}`),children:[A.featured_image_url?e.jsx("img",{src:A.featured_image_url,alt:"",className:"w-10 h-10 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Ec,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"font-medium",children:A.name})]},A.id))})]})}),e.jsx(al,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Zl,{className:"h-5 w-5"}),"Comments (",f.length,")"]}),n?e.jsxs("form",{onSubmit:S,className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Add a comment...",value:o,onChange:A=>c(A.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!o.trim()||y.isPending,children:e.jsx(lr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:f.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):f.map(A=>e.jsx(fe,{children:e.jsx(Ee,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Jr,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(ea,{className:"text-sm",children:w(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:Uo(new Date(A.created_at),{addSuffix:!0})}),A.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>_.mutate(A.id),children:e.jsx(_n,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:A.content})]})]})})},A.id))})]})]})}):e.jsx(Cs,{title:"Templates",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yo,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Template not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This template may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(In,{to:"/templates",children:"Back to Templates"})})]})})},fms=["reserved","scheduled_for_charge","paid","payment_failed","completed"],_B=s=>!!s&&(s.access_override||fms.includes(s.status)),Su=(s,t="usd")=>new Intl.NumberFormat("en-US",{style:"currency",currency:t.toUpperCase(),maximumFractionDigits:s%100===0?0:2}).format(s/100),wB=s=>{if(!s||s<=0)return"full program";const t=Math.round(s/4.345);return t>=1?`full ${t}-month program`:`full ${s}-week program`},FCe=(s,t="usd",n)=>`One-time payment: ${Su(s,t)} for the ${wB(n)}`,_xt=[{key:"full_name",label:"Full name",step:0},{key:"phone",label:"Mobile number",step:0},{key:"instagram_handle",label:"Instagram handle",step:0},{key:"city",label:"Primary city / market",step:0},{key:"service_areas",label:"Neighborhoods or areas served",step:0},{key:"years_experience",label:"Years in real estate",step:0},{key:"specialty",label:"Specialty or niche",step:0},{key:"target_audience",label:"Who they want to reach",step:1},{key:"video_comfort",label:"Comfort on camera",step:1},{key:"posting_frequency",label:"Current posting frequency",step:1},{key:"content_style",label:"Content style",step:1},{key:"personal_interests",label:"Interests / hobbies",step:1},{key:"primary_goal",label:"#1 goal for the program",step:2},{key:"topics_to_avoid",label:"Topics to avoid",step:2},{key:"timezone",label:"Time zone",step:2},{key:"consent_public_profile",label:"Content-sharing consent",step:2}],lxe=s=>{var n;const t=((n=s==null?void 0:s.sales_copy)==null?void 0:n.intake)||{};return{intro:typeof t.intro=="string"?t.intro:"",hidden:Array.isArray(t.hidden)?t.hidden:[],required:Array.isArray(t.required)?t.required:[],custom:Array.isArray(t.custom)?t.custom:[]}},xms=(s,t)=>!s.hidden.includes(t),hVe=(s,t)=>s.required.includes(t)&&!s.hidden.includes(t),Ul=(s,t=!1)=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",...t?{hour:"numeric",minute:"2-digit",timeZoneName:"short"}:{}}).format(new Date(s)):null,Wye=s=>{const t=Date.now(),n=s!=null&&s.enrollment_open_at?new Date(s.enrollment_open_at).getTime():null,r=s!=null&&s.enrollment_close_at?new Date(s.enrollment_close_at).getTime():null;return{notOpenYet:!!n&&n>t,closed:!!r&&rdt({queryKey:["programs"],queryFn:async()=>{const{data:s,error:t}=await q.from("programs").select("*").eq("status","published").order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0});if(t)throw t;return s||[]}}),W6e=s=>dt({queryKey:["program",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("programs").select("*").eq("slug",s).maybeSingle();if(n)throw n;return t||null}}),wxt=s=>dt({queryKey:["program-seats",s],enabled:!!s,refetchInterval:6e4,queryFn:async()=>{const{data:t,error:n}=await q.rpc("program_seats_remaining",{_program_id:s});if(n)throw n;return t??0}}),jxt=()=>{const{user:s}=vs();return dt({queryKey:["program-enrollments",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:t,error:n}=await q.from("program_enrollments").select("*").eq("user_id",s.id);if(n)throw n;return t||[]}})},K6e=s=>{const{data:t=[],...n}=jxt();return{...n,data:s&&t.find(r=>r.program_id===s)||null}},yms=()=>{const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{const{data:r,error:a}=await q.from("program_intake_responses").upsert({...n,user_id:s.id},{onConflict:"program_id,user_id"}).select("*").single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["program-intake"]}),onError:n=>ae.error(n.message||"Could not save your answers")})},vms=s=>{const{user:t}=vs();return dt({queryKey:["program-intake",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_intake_responses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n}})},bms=()=>{const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("program_claim_seat",{_program_id:t});if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["program-enrollments"]}),s.invalidateQueries({queryKey:["program-seats"]})}})},_ms=s=>{const{user:t}=vs();return dt({queryKey:["program-workspace",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const[n,r,a,i,l,o,c,d,u,h]=await Promise.all([q.from("program_weeks").select("*").eq("program_id",s).order("week_number"),q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_resources").select("*").eq("program_id",s).order("sort_order"),q.from("program_events").select("*").eq("program_id",s).order("starts_at"),q.from("program_announcements").select("*").eq("program_id",s).order("published_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s).eq("user_id",t.id),q.from("program_weekly_progress").select("*").eq("program_id",s).eq("user_id",t.id).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s).eq("user_id",t.id).order("posted_at",{ascending:!1}),q.from("program_badge_awards").select("*").eq("program_id",s).eq("user_id",t.id),q.from("program_profile_analyses").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle()]);return{weeks:n.data||[],lessons:r.data||[],resources:a.data||[],events:i.data||[],announcements:l.data||[],completions:o.data||[],progress:c.data||[],videoLogs:d.data||[],badges:u.data||[],analysis:h.data||null}}})},wms=s=>{const{user:t}=vs(),n=Kt();return yt({mutationFn:async({lessonId:r,done:a})=>{if(a){const{error:i}=await q.from("program_lesson_completions").insert({lesson_id:r,program_id:s,user_id:t.id});if(i&&!i.message.includes("duplicate"))throw i}else{const{error:i}=await q.from("program_lesson_completions").delete().eq("lesson_id",r).eq("user_id",t.id);if(i)throw i}},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>ae.error(r.message||"Could not update progress")})},jms=s=>{const{user:t}=vs(),n=Kt();return yt({mutationFn:async r=>{const{error:a}=await q.from("program_video_logs").insert({...r,program_id:s,user_id:t.id});if(a)throw a},onSuccess:()=>{ae.success("Video logged — nice work"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not log the video")})},Nms=s=>{const{user:t}=vs(),n=Kt();return yt({mutationFn:async r=>{const{error:a}=await q.from("program_weekly_progress").upsert({...r,program_id:s,user_id:t.id},{onConflict:"program_id,user_id,week_number"});if(a)throw a},onSuccess:()=>{ae.success("Weekly check-in saved"),n.invalidateQueries({queryKey:["program-workspace"]})},onError:r=>ae.error(r.message||"Could not save your check-in")})},kms=s=>{const{user:t}=vs(),n=Kt();return yt({mutationFn:async({eventId:r,optIn:a})=>{const{error:i}=await q.from("program_event_attendance").upsert({event_id:r,program_id:s,user_id:t.id,reminder_opt_in:a},{onConflict:"event_id,user_id"});if(i)throw i},onSuccess:()=>n.invalidateQueries({queryKey:["program-workspace"]}),onError:r=>ae.error(r.message||"Could not update your RSVP")})},Sms=s=>dt({queryKey:["program-discount-codes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_discount_codes").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}}),Cms=s=>{const t=Kt();return yt({mutationFn:async n=>{const r={program_id:s,code:(n.code||"").trim().toUpperCase(),label:n.label||null,percent_off:n.percent_off??null,amount_off_cents:n.amount_off_cents??null,max_redemptions:n.max_redemptions??null,starts_at:n.starts_at||null,expires_at:n.expires_at||null,is_active:n.is_active??!0};if(n.id){const{error:a}=await q.from("program_discount_codes").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_discount_codes").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Discount code saved"),t.invalidateQueries({queryKey:["program-discount-codes"]})},onError:n=>{var r;return ae.error((r=n.message)!=null&&r.includes("duplicate")?"That code already exists for this program":n.message||"Could not save the code")}})},Tms=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("program_discount_codes").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Discount code deleted"),s.invalidateQueries({queryKey:["program-discount-codes"]})},onError:t=>ae.error(t.message||"Could not delete the code")})},Ems=()=>yt({mutationFn:async({enrollmentId:s,code:t})=>{const{data:n,error:r}=await q.rpc("program_apply_discount",{_enrollment_id:s,_code:t});if(r)throw r;const a=n;if(!(a!=null&&a.ok))throw new Error((a==null?void 0:a.error)||"That code could not be applied");return a}}),Ams=()=>yt({mutationFn:async s=>{const{error:t}=await q.rpc("program_clear_discount",{_enrollment_id:s});if(t)throw t}}),Mms=s=>dt({queryKey:["admin-program-events",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_events").select("*").eq("program_id",s).order("starts_at",{ascending:!0});if(n)throw n;return t||[]}}),Ims=s=>{const t=Kt();return yt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,event_kind:n.event_kind||"mastermind",starts_at:n.starts_at,duration_minutes:n.duration_minutes??60,speaker:n.speaker||null,meeting_link:n.meeting_link||null,replay_url:n.replay_url||null,is_published:n.is_published??!0};if(n.id){const{error:a}=await q.from("program_events").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_events").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Session saved"),t.invalidateQueries({queryKey:["admin-program-events"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the session")})},Pms=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("program_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Session removed"),s.invalidateQueries({queryKey:["admin-program-events"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the session")})},Lms=s=>dt({queryKey:["admin-program-lessons",s],enabled:!!s,queryFn:async()=>{const[t,n]=await Promise.all([q.from("program_lessons").select("*").eq("program_id",s).order("sort_order"),q.from("program_weeks").select("id, week_number, title").eq("program_id",s).order("week_number")]);if(t.error)throw t.error;return{lessons:t.data||[],weeks:n.data||[]}}}),Dms=s=>{const t=Kt();return yt({mutationFn:async n=>{const r={program_id:s,week_id:n.week_id||null,title:(n.title||"").trim(),summary:n.summary||null,duration_minutes:n.duration_minutes??null,video_url:n.video_url||null,worksheet_url:n.worksheet_url||null,action_assignment:n.action_assignment||null,status:n.status||"published",publish_at:n.publish_at||null,sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_lessons").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_lessons").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Video saved"),t.invalidateQueries({queryKey:["admin-program-lessons"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the video")})},Rms=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("program_lessons").delete().eq("id",t);if(n)throw n},onSuccess:()=>{ae.success("Video removed"),s.invalidateQueries({queryKey:["admin-program-lessons"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the video")})},Nxt=s=>{if(!s)return null;const t=s.match(/(?:youtu\.be\/|youtube\.com\/(?:watch\?v=|embed\/|live\/|shorts\/))([\w-]{6,})/);if(t)return`https://www.youtube.com/embed/${t[1]}`;const n=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}`;const r=s.match(/loom\.com\/(?:share|embed)\/([\w-]+)/);return r?`https://www.loom.com/embed/${r[1]}`:null},Oms=[{value:"pdf",label:"PDF"},{value:"document",label:"Document"},{value:"checklist",label:"Checklist"},{value:"template_link",label:"Template"},{value:"video",label:"Video"},{value:"external",label:"Link"}],Y6e="event-images",kxt=s=>{if(s.file_path){const{data:t}=q.storage.from(Y6e).getPublicUrl(s.file_path);return t.publicUrl}return s.url||null},Fms=s=>dt({queryKey:["admin-program-resources",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_resources").select("*").eq("program_id",s).order("sort_order");if(n)throw n;return t||[]}}),zms=s=>{const t=Kt();return yt({mutationFn:async n=>{const r={program_id:s,title:(n.title||"").trim(),description:n.description||null,category:(n.category||"Resources").trim()||"Resources",resource_kind:n.resource_kind||"pdf",url:n.url||null,file_path:n.file_path||null,status:n.status||"published",sort_order:n.sort_order??0};if(n.id){const{error:a}=await q.from("program_resources").update(r).eq("id",n.id);if(a)throw a}else{const{error:a}=await q.from("program_resources").insert(r);if(a)throw a}},onSuccess:()=>{ae.success("Resource saved"),t.invalidateQueries({queryKey:["admin-program-resources"]}),t.invalidateQueries({queryKey:["program-workspace"]})},onError:n=>ae.error(n.message||"Could not save the resource")})},Bms=()=>{const s=Kt();return yt({mutationFn:async t=>{t.file_path&&await q.storage.from(Y6e).remove([t.file_path]);const{error:n}=await q.from("program_resources").delete().eq("id",t.id);if(n)throw n},onSuccess:()=>{ae.success("Resource removed"),s.invalidateQueries({queryKey:["admin-program-resources"]}),s.invalidateQueries({queryKey:["program-workspace"]})},onError:t=>ae.error(t.message||"Could not remove the resource")})},$ms=s=>{const{user:t}=vs();return dt({queryKey:["program-interest",s,t==null?void 0:t.id],enabled:!!s&&!!(t!=null&&t.id),queryFn:async()=>{const{data:n,error:r}=await q.from("program_interest").select("*").eq("program_id",s).eq("user_id",t.id).maybeSingle();if(r)throw r;return n||null}})},Ums=s=>{const t=Kt(),{user:n}=vs();return yt({mutationFn:async r=>{if(!(n!=null&&n.id)||!s)throw new Error("You need to be signed in.");if(r){const{error:a}=await q.from("program_interest").upsert({program_id:s,user_id:n.id,source:"program_detail"},{onConflict:"program_id,user_id"});if(a)throw a}else{const{error:a}=await q.from("program_interest").delete().eq("program_id",s).eq("user_id",n.id);if(a)throw a}return r},onSuccess:r=>{ae.success(r?"You're on the list — we'll email you when enrollment opens.":"Removed from the notify list"),t.invalidateQueries({queryKey:["program-interest"]}),t.invalidateQueries({queryKey:["admin-program-interest"]})},onError:r=>ae.error(r.message||"Could not update your notify preference")})},qms=s=>dt({queryKey:["admin-program-interest",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("program_interest").select("*").eq("program_id",s).order("created_at",{ascending:!1});if(n)throw n;const r=t||[];if(!r.length)return[];const a=Array.from(new Set(r.map(o=>o.user_id))),{data:i}=await q.from("profiles").select("id, name, email, phone, brokerage_name").in("id",a),l=new Map((i||[]).map(o=>[o.id,o]));return r.map(o=>{const c=l.get(o.user_id)||{};return{...o,full_name:c.name??null,email:c.email??null,phone:c.phone??null,brokerage:c.brokerage_name??null}})}}),mVe=({program:s,enrolled:t})=>{const{notOpenYet:n,closed:r,opensLabel:a}=Wye(s);return e.jsxs(fe,{className:"group overflow-hidden border-border/60 transition-all hover:border-primary/40 hover:shadow-lg",children:[e.jsxs("div",{className:"relative aspect-[16/9] overflow-hidden bg-muted",children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:`${s.name} program cover`,loading:"lazy",className:"h-full w-full object-cover transition-transform duration-500 group-hover:scale-105"}):e.jsx("div",{className:"flex h-full w-full items-center justify-center bg-gradient-to-br from-primary/15 via-background to-accent/20",children:e.jsx(un,{className:"h-10 w-10 text-primary/60"})}),e.jsxs("div",{className:"absolute left-3 top-3 flex gap-2",children:[s.is_featured&&e.jsx(Ue,{className:"shadow-sm",children:"Featured"}),t&&e.jsxs(Ue,{variant:"secondary",className:"shadow-sm",children:[e.jsx(vr,{className:"mr-1 h-3 w-3"})," Enrolled"]})]})]}),e.jsxs(Ee,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("h2",{className:"text-lg font-semibold leading-tight",children:s.name}),s.subtitle&&e.jsx("p",{className:"text-sm text-muted-foreground",children:s.subtitle})]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1.5 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),s.duration_weeks," weeks"]}),s.kickoff_at&&e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(Cl,{className:"h-3.5 w-3.5"}),"Starts ",Ul(s.kickoff_at)]}),e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(An,{className:"h-3.5 w-3.5"}),s.capacity," seats"]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:s.payment_mode==="free"?"Included":Su(s.price_cents,s.currency)}),n?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Enrollment opens ",a]}):s.payment_mode!=="free"?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["One-time payment for the ",wB(s.duration_weeks)," — no subscription",s.charge_at?` · charged ${Ul(s.charge_at)}`:""]}):null]}),e.jsx(B,{asChild:!0,size:"sm",children:e.jsxs(In,{to:t?`/programs/${s.slug}/workspace`:`/programs/${s.slug}`,children:[t?"Open program":n?"Preview details":"View details",e.jsx(Oa,{className:"ml-1.5 h-4 w-4"})]})})]})]})]})},Vms=()=>{const{data:s=[],isLoading:t}=gms(),{data:n=[]}=jxt(),r=new Set(n.filter(l=>_B(l)).map(l=>l.program_id)),a=s.filter(l=>r.has(l.id)),i=s.filter(l=>!r.has(l.id));return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-10 p-4 md:p-8",children:[e.jsxs("header",{className:"space-y-3",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"LevelUp Programs"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:"Go deeper than the membership"}),e.jsx("p",{className:"max-w-2xl text-muted-foreground",children:"Time-bound coaching programs, masterminds and challenges built to move one specific part of your business forward — with a real cohort, a real roadmap and real accountability."})]}),t?e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[0,1,2].map(l=>e.jsx(Ws,{className:"h-80 rounded-xl"},l))}):e.jsxs(e.Fragment,{children:[a.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Your programs"}),e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:a.map(l=>e.jsx(mVe,{program:l,enrolled:!0},l.id))})]}),e.jsxs("section",{className:"space-y-4",children:[a.length>0&&e.jsx("h2",{className:"text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Open for enrollment"}),i.length===0&&a.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No programs are open right now"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"New cohorts are announced inside the Hub. Check back soon — seats are limited when they open."})]})}):e.jsx("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:i.map(l=>e.jsx(mVe,{program:l,enrolled:!1},l.id))})]})]})]})})};var Mb="Accordion",Hms=["Home","End","ArrowDown","ArrowUp","ArrowLeft","ArrowRight"],[Z6e,Gms,Wms]=wD(Mb),[Kye,xfn]=uu(Mb,[Wms,jht]),Q6e=jht(),Sxt=Ct.forwardRef((s,t)=>{const{type:n,...r}=s,a=r,i=r;return e.jsx(Z6e.Provider,{scope:s.__scopeAccordion,children:n==="multiple"?e.jsx(Qms,{...i,ref:t}):e.jsx(Zms,{...a,ref:t})})});Sxt.displayName=Mb;var[Cxt,Kms]=Kye(Mb),[Txt,Yms]=Kye(Mb,{collapsible:!1}),Zms=Ct.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},collapsible:i=!1,...l}=s,[o,c]=cm({prop:n,defaultProp:r??"",onChange:a,caller:Mb});return e.jsx(Cxt,{scope:s.__scopeAccordion,value:Ct.useMemo(()=>o?[o]:[],[o]),onItemOpen:c,onItemClose:Ct.useCallback(()=>i&&c(""),[i,c]),children:e.jsx(Txt,{scope:s.__scopeAccordion,collapsible:i,children:e.jsx(Ext,{...l,ref:t})})})}),Qms=Ct.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=cm({prop:n,defaultProp:r??[],onChange:a,caller:Mb}),c=Ct.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Ct.useCallback(u=>o((h=[])=>h.filter(p=>p!==u)),[o]);return e.jsx(Cxt,{scope:s.__scopeAccordion,value:l,onItemOpen:c,onItemClose:d,children:e.jsx(Txt,{scope:s.__scopeAccordion,collapsible:!0,children:e.jsx(Ext,{...i,ref:t})})})}),[Xms,Yye]=Kye(Mb),Ext=Ct.forwardRef((s,t)=>{const{__scopeAccordion:n,disabled:r,dir:a,orientation:i="vertical",...l}=s,o=Ct.useRef(null),c=ji(o,t),d=Gms(n),h=vN(a)==="ltr",p=xr(s.onKeyDown,f=>{var I;if(!Hms.includes(f.key))return;const y=f.target,_=d().filter(F=>{var z;return!((z=F.ref.current)!=null&&z.disabled)}),v=_.findIndex(F=>F.ref.current===y),j=_.length;if(v===-1)return;f.preventDefault();let w=v;const S=0,A=j-1,E=()=>{w=v+1,w>A&&(w=S)},O=()=>{w=v-1,w{const{__scopeAccordion:n,value:r,...a}=s,i=Yye(cxe,n),l=Kms(cxe,n),o=Q6e(n),c=om(),d=r&&l.value.includes(r)||!1,u=i.disabled||s.disabled;return e.jsx(Jms,{scope:n,open:d,disabled:u,triggerId:c,children:e.jsx(Sht,{"data-orientation":i.orientation,"data-state":Rxt(d),...o,...a,ref:t,disabled:u,open:d,onOpenChange:h=>{h?l.onItemOpen(r):l.onItemClose(r)}})})});Axt.displayName=cxe;var Mxt="AccordionHeader",Ixt=Ct.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=Yye(Mb,n),i=X6e(Mxt,n);return e.jsx(Yr.h3,{"data-orientation":a.orientation,"data-state":Rxt(i.open),"data-disabled":i.disabled?"":void 0,...r,ref:t})});Ixt.displayName=Mxt;var zCe="AccordionTrigger",Pxt=Ct.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=Yye(Mb,n),i=X6e(zCe,n),l=Yms(zCe,n),o=Q6e(n);return e.jsx(Z6e.ItemSlot,{scope:n,children:e.jsx(HJt,{"aria-disabled":i.open&&!l.collapsible||void 0,"data-orientation":a.orientation,id:i.triggerId,...o,...r,ref:t})})});Pxt.displayName=zCe;var Lxt="AccordionContent",Dxt=Ct.forwardRef((s,t)=>{const{__scopeAccordion:n,...r}=s,a=Yye(Mb,n),i=X6e(Lxt,n),l=Q6e(n);return e.jsx(GJt,{role:"region","aria-labelledby":i.triggerId,"data-orientation":a.orientation,...l,...r,ref:t,style:{"--radix-accordion-content-height":"var(--radix-collapsible-content-height)","--radix-accordion-content-width":"var(--radix-collapsible-content-width)",...s.style}})});Dxt.displayName=Lxt;function Rxt(s){return s?"open":"closed"}var eps=Sxt,tps=Axt,sps=Ixt,Oxt=Pxt,Fxt=Dxt;const nps=eps,zxt=N.forwardRef(({className:s,...t},n)=>e.jsx(tps,{ref:n,className:Mt("border-b",s),...t}));zxt.displayName="AccordionItem";const Bxt=N.forwardRef(({className:s,children:t,...n},r)=>e.jsx(sps,{className:"flex",children:e.jsxs(Oxt,{ref:r,className:Mt("flex flex-1 items-center justify-between py-4 font-medium transition-all hover:underline [&[data-state=open]>svg]:rotate-180",s),...n,children:[t,e.jsx(ao,{className:"h-4 w-4 shrink-0 transition-transform duration-200"})]})}));Bxt.displayName=Oxt.displayName;const $xt=N.forwardRef(({className:s,children:t,...n},r)=>e.jsx(Fxt,{ref:r,className:"overflow-hidden text-sm transition-all data-[state=closed]:animate-accordion-up data-[state=open]:animate-accordion-down",...n,children:e.jsx("div",{className:Mt("pb-4 pt-0",s),children:t})}));$xt.displayName=Fxt.displayName;const rps=({programId:s,opensLabel:t})=>{const{data:n,isLoading:r}=$ms(s),a=Ums(s),i=!!n;return e.jsxs("div",{className:"flex flex-col gap-3 rounded-xl border border-primary/30 bg-primary/5 p-4 sm:flex-row sm:items-center sm:justify-between",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(BS,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"space-y-0.5 text-sm",children:[e.jsx("p",{className:"font-semibold",children:i?"You're on the notify list":"Want a heads-up when enrollment opens?"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:i?`We'll email you the moment seats go live${t?` (${t})`:""}.`:`Seats are limited — we'll email you the moment enrollment opens${t?` ${t}`:""}.`})]})]}),e.jsxs(B,{variant:i?"outline":"default",size:"sm",disabled:r||a.isPending,onClick:()=>a.mutate(!i),className:"shrink-0",children:[a.isPending?e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}):i?e.jsx(Lr,{className:"mr-2 h-4 w-4"}):e.jsx(BS,{className:"mr-2 h-4 w-4"}),i?"You're on the list":"Notify me"]})]})},aps=()=>{const{slug:s}=bi(),{data:t,isLoading:n}=W6e(s),{data:r}=wxt(t==null?void 0:t.id),{data:a}=K6e(t==null?void 0:t.id),i=_B(a),l=(t==null?void 0:t.sales_copy)||{},o=l.outcomes||[],c=l.included||[],d=l.for_who||[],u=l.not_for||[],h=l.faqs||[],p=l.phases||[];if(n)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-5xl space-y-6 p-8",children:[e.jsx(Ws,{className:"h-64 w-full rounded-xl"}),e.jsx(Ws,{className:"h-40 w-full rounded-xl"})]})});if(!t)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx("p",{className:"mt-2 text-muted-foreground",children:"This program may have been closed or unpublished."}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(In,{to:"/programs",children:"Back to Programs"})})]})});const f=typeof r=="number"&&r<=0&&!i,{notOpenYet:y,closed:_,opensLabel:v}=Wye(t),j=!i&&(f||_||y),w=i?"Open your program":y?`Enrollment opens ${Ul(t.enrollment_open_at)}`:f?"Cohort is full":_?"Enrollment closed":t.payment_mode==="delayed"?"Reserve my seat":"Enroll now",S=i?`/programs/${t.slug}/workspace`:`/programs/${t.slug}/enroll`;return e.jsxs(Cs,{children:[e.jsxs(Zo,{children:[e.jsx("title",{children:`${t.name} | LevelUp Programs`}),e.jsx("meta",{name:"description",content:(t.short_description||t.subtitle||t.name).slice(0,155)})]}),e.jsxs("div",{className:"mx-auto w-full max-w-5xl space-y-12 p-4 md:p-8",children:[e.jsxs("section",{className:"overflow-hidden rounded-2xl border border-border/60 bg-card",children:[e.jsx("div",{className:"relative",children:t.hero_image_url||t.cover_image_url?e.jsx("img",{src:t.hero_image_url||t.cover_image_url,alt:`${t.name} hero`,className:"h-56 w-full object-cover md:h-72"}):e.jsx("div",{className:"h-40 w-full bg-gradient-to-br from-primary/20 via-background to-accent/20 md:h-56"})}),e.jsxs("div",{className:"space-y-6 p-6 md:p-8",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ue,{variant:"secondary",children:[t.duration_weeks,"-week program"]}),typeof r=="number"&&!i&&e.jsx(Ue,{variant:r<=10?"destructive":"outline",children:r>0?`${r} of ${t.capacity} seats left`:"Full"}),i&&e.jsxs(Ue,{children:[e.jsx(vr,{className:"mr-1 h-3 w-3"})," You're enrolled"]})]}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight md:text-4xl",children:t.name}),t.subtitle&&e.jsx("p",{className:"text-lg text-muted-foreground",children:t.subtitle}),t.tagline&&e.jsx("p",{className:"text-sm font-medium text-primary",children:t.tagline})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Investment"}),e.jsx("p",{className:"mt-1 font-semibold",children:t.payment_mode==="free"?"Included":Su(t.price_cents,t.currency)}),t.payment_mode!=="free"&&e.jsxs("p",{className:"mt-1 text-xs text-muted-foreground",children:["One-time payment for the ",wB(t.duration_weeks)," — not a subscription"]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"mt-1 font-semibold",children:Ul(t.kickoff_at,!0)||"To be announced"})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Weekly commitment"}),e.jsxs("p",{className:"mt-1 font-semibold",children:[t.weekly_video_goal," videos / week"]})]}),e.jsxs("div",{className:"rounded-lg border border-border/60 p-3",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Cohort size"}),e.jsxs("p",{className:"mt-1 font-semibold",children:[t.capacity," agents"]})]})]}),t.payment_mode==="delayed"&&t.charge_at&&!i&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-primary/30 bg-primary/5 p-4",children:[e.jsx(uf,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{className:"space-y-1 text-sm",children:[e.jsxs("p",{children:[e.jsxs("span",{className:"font-semibold",children:[FCe(t.price_cents,t.currency,t.duration_weeks),"."]})," ","We save your card today and charge it once on"," ",e.jsx("span",{className:"font-semibold",children:Ul(t.charge_at)}),". Cancel any time before then and you won't be billed."]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No recurring billing, no monthly installments, and no automatic renewal."})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsx(B,{asChild:!j,size:"lg",disabled:j,children:j?e.jsx("span",{children:w}):e.jsxs(In,{to:S,children:[w,e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})}),e.jsx(B,{asChild:!0,variant:"ghost",size:"lg",children:e.jsx(In,{to:"/programs",children:"All programs"})})]}),y&&!i&&e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Cl,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}),e.jsx(rps,{programId:t.id,opensLabel:v})]})]})]}),t.description&&e.jsxs("section",{className:"space-y-3",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What this program is"}),e.jsx("div",{className:"whitespace-pre-line text-muted-foreground",children:t.description})]}),o.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What you'll walk away with"}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:o.map((A,E)=>e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(vr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsx("p",{className:"text-sm",children:A})]},E))})]}),p.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsxs("h2",{className:"text-xl font-semibold",children:["How the ",t.duration_weeks," weeks flow"]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-3",children:p.map((A,E)=>e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"space-y-2 p-5",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-primary",children:["Phase ",E+1]}),e.jsx("h3",{className:"font-semibold",children:A.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:A.detail})]})},E))})]}),c.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"What's included"}),e.jsx("ul",{className:"grid gap-2 sm:grid-cols-2",children:c.map((A,E)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-sm",children:[e.jsx(un,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),A]},E))})]}),(d.length>0||u.length>0)&&e.jsxs("section",{className:"grid gap-6 md:grid-cols-2",children:[d.length>0&&e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This is for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:d.map((A,E)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(vr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),A]},E))})]})}),u.length>0&&e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"space-y-3 p-5",children:[e.jsx("h3",{className:"font-semibold",children:"This isn't for you if…"}),e.jsx("ul",{className:"space-y-2 text-sm text-muted-foreground",children:u.map((A,E)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx(pr,{className:"mt-0.5 h-4 w-4 shrink-0"}),A]},E))})]})})]}),h.length>0&&e.jsxs("section",{className:"space-y-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Questions"}),e.jsx(nps,{type:"single",collapsible:!0,className:"rounded-xl border border-border/60 px-4",children:h.map((A,E)=>e.jsxs(zxt,{value:`faq-${E}`,children:[e.jsx(Bxt,{className:"text-left text-sm font-medium",children:A.q}),e.jsx($xt,{className:"text-sm text-muted-foreground",children:A.a})]},E))})]}),e.jsxs("section",{className:"rounded-2xl border border-border/60 bg-muted/40 p-6 text-center md:p-10",children:[e.jsx(fr,{className:"mx-auto h-8 w-8 text-primary"}),e.jsx("h2",{className:"mt-4 text-2xl font-bold",children:l.closing_headline||"Ready to commit?"}),e.jsx("p",{className:"mx-auto mt-2 max-w-xl text-muted-foreground",children:l.closing_body||`Seats are capped at ${t.capacity} so every member gets attention. Reserve yours and we'll take it from there.`}),e.jsxs("div",{className:"mt-6 flex flex-wrap items-center justify-center gap-3",children:[e.jsx(B,{asChild:!j,size:"lg",disabled:j,children:j?e.jsx("span",{children:w}):e.jsxs(In,{to:S,children:[w,e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})}),typeof r=="number"&&r>0&&!i&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 text-sm text-muted-foreground",children:[e.jsx(An,{className:"h-4 w-4"}),r," seats remaining"]})]}),!i&&(y?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Cl,{className:"h-3.5 w-3.5"}),"Enrollment opens ",v]}):t.enrollment_close_at?e.jsxs("p",{className:"mt-3 inline-flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Cl,{className:"h-3.5 w-3.5"}),"Enrollment closes ",Ul(t.enrollment_close_at)]}):null)]})]})]})},bH=["Your business","Your content","Your goals","Reserve your seat"],ips=()=>{const{slug:s}=bi(),t=Ln(),[n,r]=xl(),{user:a}=vs(),{data:i,isLoading:l}=W6e(s),{data:o}=wxt(i==null?void 0:i.id),{data:c,refetch:d}=K6e(i==null?void 0:i.id),{data:u}=vms(i==null?void 0:i.id),h=yms(),p=bms(),f=Ems(),y=Ams(),[_,v]=N.useState(0),[j,w]=N.useState(!1),[S,A]=N.useState(!1),[E,O]=N.useState(!1),[D,I]=N.useState(!1),[F,z]=N.useState(""),[H,Z]=N.useState(null),Y=N.useRef({}),[W,ee]=N.useState({}),se=N.useRef(!1),oe=($e,Ke)=>{Y.current={...Y.current,[$e]:Ke},ee(Y.current)};N.useEffect(()=>{se.current||(u?(Y.current={...u},ee(Y.current),se.current=!0):a&&(Y.current={email:a.email,...Y.current},ee(Y.current)))},[u,a]),N.useEffect(()=>{const $e=c;!i||!($e!=null&&$e.discount_code)||H||Z({code:$e.discount_code,discount_cents:$e.discount_cents||0,amount_cents:$e.amount_cents??i.price_cents,original_cents:i.price_cents})},[c,i,H]);const he=H?H.amount_cents:(i==null?void 0:i.price_cents)??0,ce=N.useMemo(()=>lxe(i),[i]),me=$e=>xms(ce,$e),le=$e=>hVe(ce,$e)?e.jsx("span",{className:"text-destructive",children:" *"}):null,ve=($e,Ke)=>{const Ge={...Y.current.extra||{},[$e]:Ke};oe("extra",Ge)},ge=$e=>ce.custom.filter((Ke,Ge)=>Ge%3===$e),Te=$e=>{const Ke=ge($e);if(!Ke.length)return null;const Ge=W.extra||{};return e.jsx("div",{className:"space-y-4",children:Ke.map(rt=>e.jsxs("div",{className:"space-y-2",children:[rt.type==="checkbox"?e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(hi,{id:rt.id,checked:!!Ge[rt.id],onCheckedChange:tt=>ve(rt.id,!!tt)}),e.jsxs(ne,{htmlFor:rt.id,className:"text-sm font-normal leading-relaxed",children:[rt.label,rt.required&&e.jsx("span",{className:"text-destructive",children:" *"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(ne,{htmlFor:rt.id,children:[rt.label,rt.required&&e.jsx("span",{className:"text-destructive",children:" *"})]}),rt.type==="long_text"?e.jsx(Ms,{id:rt.id,rows:3,value:Ge[rt.id]||"",onChange:tt=>ve(rt.id,tt.target.value)}):rt.type==="select"?e.jsxs(us,{value:Ge[rt.id]||"",onValueChange:tt=>ve(rt.id,tt),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(cs,{children:(rt.options||[]).map(tt=>e.jsx(Ze,{value:tt,children:tt},tt))})]}):e.jsx(ye,{id:rt.id,value:Ge[rt.id]||"",onChange:tt=>ve(rt.id,tt.target.value)})]}),rt.help&&e.jsx("p",{className:"text-xs text-muted-foreground",children:rt.help})]},rt.id))})},Ie=$e=>{const Ke=Y.current,Ge=Ye=>Ye==null||Ye===""||Ye===!1,rt=_xt.find(Ye=>Ye.step===$e&&hVe(ce,Ye.key)&&Ge(Ye.key==="timezone"?Ke.timezone||(i==null?void 0:i.timezone):Ke[Ye.key]));if(rt)return rt.label;const tt=Ke.extra||{},at=ge($e).find(Ye=>Ye.required&&Ge(tt[Ye.id]));return at?at.label:null},Ce=()=>{if(_<=2){const $e=Ie(_);if($e)return ae.error(`Please answer: ${$e}`)}v($e=>$e+1)},Me=async()=>{if(!(!i||!F.trim()))try{let $e=c==null?void 0:c.id;(!$e||(c==null?void 0:c.status)==="canceled")&&($e=await p.mutateAsync(i.id));const Ke=await f.mutateAsync({enrollmentId:$e,code:F});Z(Ke),z(""),await d(),ae.success(`Code applied — you save ${Su(Ke.discount_cents,i.currency)}`)}catch($e){ae.error($e.message||"That code could not be applied")}},Pe=async()=>{if(!(c!=null&&c.id))return Z(null);try{await y.mutateAsync(c.id),Z(null),await d()}catch($e){ae.error($e.message||"Could not remove the code")}},Re=n.get("setup"),Ae=n.get("session_id"),Be=N.useRef(!1);N.useEffect(()=>{Re!=="success"||!Ae||!(c!=null&&c.id)||Be.current||(Be.current=!0,A(!0),(async()=>{const{data:$e,error:Ke}=await q.functions.invoke("program-enroll",{body:{action:"verify",enrollment_id:c.id,session_id:Ae}});if(A(!1),Ke||$e!=null&&$e.error||($e==null?void 0:$e.success)===!1){ae.error(($e==null?void 0:$e.error)||(Ke==null?void 0:Ke.message)||"We could not confirm your card");return}await d(),n.delete("setup"),n.delete("session_id"),r(n,{replace:!0}),ae.success("Your seat is confirmed")})())},[Re,Ae,c==null?void 0:c.id]),N.useEffect(()=>{Re==="cancelled"&&ae.info("Checkout cancelled — your seat is held for a short while.")},[Re]);const we=N.useMemo(()=>c&&["reserved","scheduled_for_charge","paid","completed"].includes(c.status),[c]),Je=async()=>{if(i){if(!E||i.payment_mode!=="free"&&!D){ae.error("Please confirm the checkboxes to continue");return}w(!0);try{let $e=c==null?void 0:c.id;(!$e||(c==null?void 0:c.status)==="canceled")&&($e=await p.mutateAsync(i.id)),await h.mutateAsync({...Y.current,id:void 0,program_id:i.id,enrollment_id:$e,created_at:void 0,updated_at:void 0,user_id:void 0});const{data:Ke,error:Ge}=await q.functions.invoke("program-enroll",{body:{action:"setup",enrollment_id:$e}});if(Ge||Ke!=null&&Ke.error)throw new Error((Ke==null?void 0:Ke.error)||(Ge==null?void 0:Ge.message));if(Ke!=null&&Ke.free){await d(),ae.success("You're in"),t(`/programs/${i.slug}/workspace`);return}Ke!=null&&Ke.url&&(window.location.href=Ke.url)}catch($e){ae.error($e.message||"Could not start enrollment")}finally{w(!1)}}};if(l)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-2xl space-y-4 p-8",children:[e.jsx(Ws,{className:"h-10 w-1/2"}),e.jsx(Ws,{className:"h-64 w-full rounded-xl"})]})});if(!i)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(In,{to:"/programs",children:"Back to Programs"})})]})});if(_B(c)&&we&&Re!=="success")return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx(vr,{className:"mx-auto h-10 w-10 text-primary"}),e.jsxs("h1",{className:"text-2xl font-bold",children:["You're enrolled in ",i.name]}),e.jsx("p",{className:"text-muted-foreground",children:(c==null?void 0:c.status)==="paid"?"Your payment is complete.":`Your card is saved. Nothing is charged until ${Ul(c==null?void 0:c.charge_scheduled_at)||"the program start date"}.`}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(In,{to:`/programs/${i.slug}/workspace`,children:"Open your program workspace"})})]})});const ke=typeof o=="number"&&o<=0,{notOpenYet:it,closed:je,opensLabel:He}=Wye(i);return it||je?e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-xl space-y-4 p-8 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:it?"Enrollment is not open yet":"Enrollment is closed"}),e.jsx("p",{className:"text-muted-foreground",children:it?`Enrollment for ${i.name} opens ${He}. Come back then to reserve your seat.`:`Enrollment for ${i.name} has closed. Watch the Hub for the next cohort.`}),e.jsx(B,{asChild:!0,children:e.jsx(In,{to:`/programs/${i.slug}`,children:"Back to program details"})})]})}):e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-3xl space-y-6 p-4 md:p-8",children:[e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2",children:e.jsxs(In,{to:`/programs/${i.slug}`,children:[e.jsx(qr,{className:"mr-1.5 h-4 w-4"})," Back to program"]})}),e.jsxs("header",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-[0.2em] text-primary",children:"Enrollment"}),e.jsx("h1",{className:"text-2xl font-bold md:text-3xl",children:i.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:i.payment_mode==="delayed"&&i.charge_at?`${FCe(i.price_cents,i.currency,i.duration_weeks)}. Your card is saved today and charged once on ${Ul(i.charge_at)} — no recurring billing.`:"Complete the short intake and checkout to secure your seat."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium text-foreground",children:bH[_]}),e.jsxs("span",{children:["Step ",_+1," of ",bH.length]})]}),e.jsx(fi,{value:(_+1)/bH.length*100})]}),S&&e.jsx(fe,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4 text-sm",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin text-primary"}),"Confirming your card with Stripe…"]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[_===0&&ce.intro&&e.jsx("p",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm text-muted-foreground",children:ce.intro}),_===0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[me("full_name")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"full_name",children:["Full name",le("full_name")]}),e.jsx(ye,{id:"full_name",value:W.full_name||"",onChange:$e=>oe("full_name",$e.target.value)})]}),me("phone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"phone",children:["Mobile number",le("phone")]}),e.jsx(ye,{id:"phone",value:W.phone||"",onChange:$e=>oe("phone",$e.target.value)})]}),me("instagram_handle")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"instagram_handle",children:["Instagram handle",le("instagram_handle")]}),e.jsx(ye,{id:"instagram_handle",placeholder:"@yourhandle",value:W.instagram_handle||"",onChange:$e=>oe("instagram_handle",$e.target.value)})]}),me("city")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"city",children:["Primary city / market",le("city")]}),e.jsx(ye,{id:"city",value:W.city||"",onChange:$e=>oe("city",$e.target.value)})]})]}),me("service_areas")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"service_areas",children:["Neighborhoods or areas you serve",le("service_areas")]}),e.jsx(Ms,{id:"service_areas",rows:2,value:W.service_areas||"",onChange:$e=>oe("service_areas",$e.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[me("years_experience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{children:["Years in real estate",le("years_experience")]}),e.jsxs(us,{value:W.years_experience||"",onValueChange:$e=>oe("years_experience",$e),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(cs,{children:["Less than 1","1-3","4-7","8-15","15+"].map($e=>e.jsx(Ze,{value:$e,children:$e},$e))})]})]}),me("specialty")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"specialty",children:["Specialty or niche",le("specialty")]}),e.jsx(ye,{id:"specialty",value:W.specialty||"",onChange:$e=>oe("specialty",$e.target.value)})]})]}),Te(0)]}),_===1&&e.jsxs(e.Fragment,{children:[me("target_audience")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"target_audience",children:["Who are you trying to reach?",le("target_audience")]}),e.jsx(Ms,{id:"target_audience",rows:2,placeholder:"First-time buyers, move-up sellers, investors…",value:W.target_audience||"",onChange:$e=>oe("target_audience",$e.target.value)})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[me("video_comfort")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{children:["How comfortable are you on camera?",le("video_comfort")]}),e.jsxs(us,{value:W.video_comfort||"",onValueChange:$e=>oe("video_comfort",$e),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(cs,{children:["Terrified","Nervous but willing","Getting comfortable","Very comfortable"].map($e=>e.jsx(Ze,{value:$e,children:$e},$e))})]})]}),me("posting_frequency")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{children:["How often do you post today?",le("posting_frequency")]}),e.jsxs(us,{value:W.posting_frequency||"",onValueChange:$e=>oe("posting_frequency",$e),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(cs,{children:["Never","Rarely","Weekly","A few times a week","Daily"].map($e=>e.jsx(Ze,{value:$e,children:$e},$e))})]})]})]}),me("content_style")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"content_style",children:["What content style feels like you?",le("content_style")]}),e.jsx(Ms,{id:"content_style",rows:2,placeholder:"Educational, funny, behind-the-scenes, luxury-polished…",value:W.content_style||"",onChange:$e=>oe("content_style",$e.target.value)})]}),me("personal_interests")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"personal_interests",children:["Interests or hobbies we can weave in",le("personal_interests")]}),e.jsx(Ms,{id:"personal_interests",rows:2,value:W.personal_interests||"",onChange:$e=>oe("personal_interests",$e.target.value)})]}),Te(1)]}),_===2&&e.jsxs(e.Fragment,{children:[me("primary_goal")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"primary_goal",children:["Your #1 goal for this program",le("primary_goal")]}),e.jsx(Ms,{id:"primary_goal",rows:3,value:W.primary_goal||"",onChange:$e=>oe("primary_goal",$e.target.value)})]}),me("topics_to_avoid")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"topics_to_avoid",children:["Anything you don't want to talk about",le("topics_to_avoid")]}),e.jsx(Ms,{id:"topics_to_avoid",rows:2,value:W.topics_to_avoid||"",onChange:$e=>oe("topics_to_avoid",$e.target.value)})]}),me("timezone")&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{children:["Your time zone",le("timezone")]}),e.jsxs(us,{value:W.timezone||i.timezone,onValueChange:$e=>oe("timezone",$e),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(cs,{children:["America/New_York","America/Chicago","America/Denver","America/Phoenix","America/Los_Angeles","Pacific/Honolulu"].map($e=>e.jsx(Ze,{value:$e,children:$e.replace("America/","").replace("_"," ")},$e))})]})]}),Te(2),me("consent_public_profile")&&e.jsxs("div",{className:"flex items-start gap-3 rounded-lg border border-border/60 p-4",children:[e.jsx(hi,{id:"consent_public_profile",checked:!!W.consent_public_profile,onCheckedChange:$e=>oe("consent_public_profile",!!$e)}),e.jsx(ne,{htmlFor:"consent_public_profile",className:"text-sm font-normal leading-relaxed",children:"I'm okay with my content being reviewed and shared as an example inside the cohort."})]})]}),_===3&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:i.name}),e.jsx("span",{className:"font-semibold",children:i.payment_mode==="free"?"Included":H?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm font-normal text-muted-foreground line-through",children:Su(H.original_cents,i.currency)}),Su(he,i.currency)]}):Su(i.price_cents,i.currency)})]}),i.payment_mode!=="free"&&e.jsx("p",{className:"mt-1 text-xs text-muted-foreground",children:FCe(he,i.currency,i.duration_weeks)}),i.payment_mode!=="free"&&e.jsx("div",{className:"mt-3 border-t border-border/60 pt-3",children:H?e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-2 rounded-md bg-primary/5 px-3 py-2 text-sm",children:[e.jsxs("span",{className:"inline-flex items-center gap-2",children:[e.jsx(oh,{className:"h-3.5 w-3.5 text-primary"}),"Code ",e.jsx("span",{className:"font-mono font-semibold",children:H.code})," applied — you save ",Su(H.discount_cents,i.currency)]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:Pe,disabled:y.isPending,children:[e.jsx($n,{className:"mr-1 h-3.5 w-3.5"})," Remove"]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"discount_code",className:"text-xs text-muted-foreground",children:"Have a discount code?"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{id:"discount_code",placeholder:"Enter code",className:"font-mono uppercase",value:F,onChange:$e=>z($e.target.value.toUpperCase()),onKeyDown:$e=>{$e.key==="Enter"&&($e.preventDefault(),Me())}}),e.jsx(B,{variant:"outline",onClick:Me,disabled:!F.trim()||f.isPending||p.isPending,children:f.isPending||p.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):"Apply"})]})]})}),i.payment_mode==="delayed"&&e.jsxs("div",{className:"mt-3 flex items-start gap-2.5 border-t border-border/60 pt-3 text-sm",children:[e.jsx(uf,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("span",{children:["Charged once on"," ",e.jsx("span",{className:"font-semibold",children:Ul(i.charge_at||i.kickoff_at)||"the program start date"}),". No recurring billing, installments, or renewal. Cancel any time before then at no cost."]})]}),typeof o=="number"&&e.jsx("p",{className:"mt-3 text-xs text-muted-foreground",children:o>0?`${o} of ${i.capacity} seats left`:"This cohort is full"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(hi,{id:"terms",checked:E,onCheckedChange:$e=>O(!!$e)}),e.jsx(ne,{htmlFor:"terms",className:"text-sm font-normal leading-relaxed",children:"I agree to the program terms, including the attendance and participation expectations, and understand seats are limited."})]}),i.payment_mode!=="free"&&e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(hi,{id:"charge",checked:D,onCheckedChange:$e=>I(!!$e)}),e.jsx(ne,{htmlFor:"charge",className:"text-sm font-normal leading-relaxed",children:i.payment_mode==="delayed"?`I authorize LevelUp to charge my saved card one time — ${Su(he,i.currency)} for the ${wB(i.duration_weeks)} — on ${Ul(i.charge_at||i.kickoff_at)||"the program start date"} unless I cancel before then. I understand this is not a subscription and will not renew.`:`I authorize LevelUp to charge my card one time — ${Su(he,i.currency)} for the ${wB(i.duration_weeks)} — today. This is not a subscription and will not renew.`})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(eg,{className:"h-3.5 w-3.5"}),"Card details are handled by Stripe — LevelUp never sees or stores them."]})]}),e.jsxs("div",{className:"flex items-center justify-between border-t border-border/60 pt-5",children:[e.jsxs(B,{variant:"ghost",onClick:()=>v($e=>Math.max(0,$e-1)),disabled:_===0||j,children:[e.jsx(qr,{className:"mr-1.5 h-4 w-4"})," Back"]}),_s.toISOString().replace(/[-:]/g,"").split(".")[0]+"Z",ops=(s,t)=>{const n=new Date(s.starts_at),r=new Date(n.getTime()+(s.duration_minutes||60)*6e4),a=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp//Programs//EN","BEGIN:VEVENT",`UID:${s.id}@levelup`,`DTSTAMP:${t2e(new Date)}`,`DTSTART:${t2e(n)}`,`DTEND:${t2e(r)}`,`SUMMARY:${t} — ${s.title}`,`DESCRIPTION:${(s.description||"").replace(/\n/g,"\\n")}${s.meeting_link?`\\n\\nJoin: ${s.meeting_link}`:""}`,...s.meeting_link?[`LOCATION:${s.meeting_link}`]:[],"END:VEVENT","END:VCALENDAR"].join(`\r `),i=URL.createObjectURL(new Blob([a],{type:"text/calendar"})),l=document.createElement("a");l.href=i,l.download=`${s.title.replace(/[^a-z0-9]+/gi,"-").toLowerCase()}.ics`,l.click(),URL.revokeObjectURL(i)},lps={pdf:br,document:mw,checklist:lu,template_link:WS,video:Sh,external:Tl},cps=()=>{var he;const{slug:s}=bi(),[t]=xl(),{isAdmin:n}=vs(),r=n&&t.get("preview")==="1",{data:a,isLoading:i}=W6e(s),{data:l}=K6e(a==null?void 0:a.id),{data:o,isLoading:c}=_ms(a==null?void 0:a.id),d=wms(a==null?void 0:a.id),u=jms(a==null?void 0:a.id),h=Nms(a==null?void 0:a.id),p=kms(a==null?void 0:a.id),[f,y]=N.useState(!1),[_,v]=N.useState({title:"",instagram_url:""}),[j,w]=N.useState({}),[S,A]=N.useState(null),E=N.useMemo(()=>{if(!(a!=null&&a.kickoff_at))return 1;const ce=Math.floor((Date.now()-new Date(a.kickoff_at).getTime())/864e5);return Math.min(Math.max(Math.floor(ce/7)+1,1),a.duration_weeks)},[a]),O=new Set(((o==null?void 0:o.completions)||[]).map(ce=>ce.lesson_id)),D=(o==null?void 0:o.lessons)||[],I=D.length?Math.round(O.size/D.length*100):0,F=((o==null?void 0:o.videoLogs)||[]).filter(ce=>ce.week_number===E).length,z=((o==null?void 0:o.videoLogs)||[]).length,H=(a==null?void 0:a.weekly_video_goal)||3,Z=N.useMemo(()=>{const ce=new Map;((o==null?void 0:o.videoLogs)||[]).forEach(le=>ce.set(le.week_number,(ce.get(le.week_number)||0)+1));let me=0;for(let le=E;le>=1;le--)if((ce.get(le)||0)>=H)me++;else if(le!==E)break;return me},[o==null?void 0:o.videoLogs,E,H]);if(i||c)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-6xl space-y-6 p-8",children:[e.jsx(Ws,{className:"h-28 w-full rounded-xl"}),e.jsx(Ws,{className:"h-64 w-full rounded-xl"})]})});if(!a)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-xl p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Program not found"}),e.jsx(B,{asChild:!0,className:"mt-6",children:e.jsx(In,{to:"/programs",children:"Back to Programs"})})]})});if(!_B(l)&&!r)return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto max-w-xl space-y-4 p-12 text-center",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"You're not enrolled yet"}),e.jsxs("p",{className:"text-muted-foreground",children:["Reserve your seat in ",a.name," to unlock the roadmap, lessons and mastermind sessions."]}),e.jsx(B,{asChild:!0,size:"lg",children:e.jsx(In,{to:`/programs/${a.slug}`,children:"View the program"})})]})});const Y=((o==null?void 0:o.events)||[]).filter(ce=>new Date(ce.starts_at)>=new Date),W=((o==null?void 0:o.events)||[]).filter(ce=>new Date(ce.starts_at)ce.is_pinned),se=((o==null?void 0:o.resources)||[]).reduce((ce,me)=>{var le;return(ce[le=me.category]||(ce[le]=[])).push(me),ce},{}),oe=((o==null?void 0:o.progress)||[]).find(ce=>ce.week_number===E)||{};return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-6xl space-y-8 p-4 md:p-8",children:[r&&!_B(l)&&e.jsx(fe,{className:"border-primary/40 bg-primary/5",children:e.jsxs(Ee,{className:"flex flex-wrap items-center justify-between gap-3 p-4 text-sm",children:[e.jsxs("span",{children:[e.jsx("strong",{children:"Admin preview"})," — this is exactly what an enrollee sees. Your own progress, check-ins and video logs are empty because you're not enrolled."]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(In,{to:"/admin/programs",children:"Back to Programs admin"})})]})}),e.jsxs("header",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ue,{variant:"secondary",children:["Week ",E," of ",a.duration_weeks]}),(l==null?void 0:l.status)==="scheduled_for_charge"&&l.charge_scheduled_at&&e.jsxs(Ue,{variant:"outline",children:["Billing ",Ul(l.charge_scheduled_at)]}),(l==null?void 0:l.status)==="payment_failed"&&e.jsx(Ue,{variant:"destructive",children:"Payment issue"})]}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:a.name}),a.subtitle&&e.jsx("p",{className:"text-muted-foreground",children:a.subtitle})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(Ac,{className:"h-3.5 w-3.5"})," This week"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[F,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",H]})]}),e.jsx(fi,{value:Math.min(F/H*100,100),className:"h-1.5"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(Sh,{className:"h-3.5 w-3.5"})," Videos posted"]}),e.jsx("p",{className:"text-2xl font-bold",children:z}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"since kickoff"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(Hc,{className:"h-3.5 w-3.5"})," Streak"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[Z," wk"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"hitting your goal"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1.5 p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs uppercase tracking-wide text-muted-foreground",children:[e.jsx(go,{className:"h-3.5 w-3.5"})," Curriculum"]}),e.jsxs("p",{className:"text-2xl font-bold",children:[I,"%"]}),e.jsx(fi,{value:I,className:"h-1.5"})]})})]}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[e.jsxs(_s,{open:f,onOpenChange:y,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," Log a video"]})}),e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Log a posted video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"v-title",children:"What was it about?"}),e.jsx(ye,{id:"v-title",value:_.title,onChange:ce=>v(me=>({...me,title:ce.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"v-url",children:"Instagram link (optional)"}),e.jsx(ye,{id:"v-url",placeholder:"https://instagram.com/reel/…",value:_.instagram_url,onChange:ce=>v(me=>({...me,instagram_url:ce.target.value}))})]})]}),e.jsx(Xn,{children:e.jsx(B,{onClick:async()=>{await u.mutateAsync({week_number:E,..._}),v({title:"",instagram_url:""}),y(!1)},children:"Log video"})})]})]}),((he=Y[0])==null?void 0:he.meeting_link)&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:Y[0].meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(jh,{className:"mr-1.5 h-4 w-4"})," Join next session"]})})]}),ee.length>0&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsx(Ee,{className:"space-y-3 p-5",children:ee.map(ce=>e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(zd,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:ce.title}),ce.body&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.body})]})]},ce.id))})}),e.jsxs(Fr,{defaultValue:"roadmap",children:[e.jsxs(Rr,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"roadmap",children:"Roadmap"}),e.jsx(Zt,{value:"lessons",children:"Lessons"}),e.jsx(Zt,{value:"checkin",children:"Weekly check-in"}),e.jsx(Zt,{value:"events",children:"Sessions"}),e.jsx(Zt,{value:"resources",children:"Resources"}),e.jsx(Zt,{value:"profile",children:"Profile review"})]}),e.jsxs(is,{value:"roadmap",className:"mt-6 space-y-4",children:[((o==null?void 0:o.weeks)||[]).length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"The roadmap will appear here before kickoff."}),((o==null?void 0:o.weeks)||[]).map(ce=>{const me=ce.release_at&&new Date(ce.release_at)>new Date;return e.jsx(fe,{className:me?"opacity-60":ce.week_number===E?"border-primary/50":"",children:e.jsxs(Ee,{className:"space-y-2 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(Ue,{variant:"outline",children:["Week ",ce.week_number]}),e.jsx("span",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:ce.phase}),ce.week_number===E&&e.jsx(Ue,{children:"Current"}),me&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(pr,{className:"h-3 w-3"})," Unlocks ",Ul(ce.release_at)]})]}),e.jsx("h3",{className:"font-semibold",children:ce.title}),ce.learning_goal&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.learning_goal}),!me&&Array.isArray(ce.tasks)&&ce.tasks.length>0&&e.jsx("ul",{className:"mt-2 space-y-1.5",children:ce.tasks.map((le,ve)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(vr,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof le=="string"?le:le.label]},ve))})]})},ce.id)})]}),e.jsxs(is,{value:"lessons",className:"mt-6 space-y-3",children:[D.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Lessons unlock as the program progresses."}),D.map(ce=>{const me=Nxt(ce.video_url),le=S===ce.id;return e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-4 p-5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[e.jsx(hi,{checked:O.has(ce.id),onCheckedChange:ve=>d.mutate({lessonId:ce.id,done:!!ve}),"aria-label":`Mark ${ce.title} complete`}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ce.title}),ce.summary&&e.jsx("p",{className:"text-sm text-muted-foreground",children:ce.summary}),ce.action_assignment&&e.jsxs("p",{className:"mt-1 text-xs text-primary",children:["Action: ",ce.action_assignment]})]}),ce.duration_minutes&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(pr,{className:"h-3 w-3"})," ",ce.duration_minutes," min"]}),e.jsxs("div",{className:"flex gap-2",children:[ce.video_url&&me&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>A(le?null:ce.id),children:[e.jsx(jh,{className:"mr-1.5 h-3.5 w-3.5"})," ",le?"Close":"Watch"]}),ce.video_url&&!me&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ce.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(jh,{className:"mr-1.5 h-3.5 w-3.5"})," Watch"]})}),ce.worksheet_url&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs("a",{href:ce.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ia,{className:"mr-1.5 h-3.5 w-3.5"})," Worksheet"]})})]})]}),le&&me&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:me,title:ce.title,className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})})]})},ce.id)})]}),e.jsx(is,{value:"checkin",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold",children:["Week ",E," check-in"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Two minutes of honesty here is what makes the next week better."})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-3",children:[["videos_planned","Videos planned"],["videos_recorded","Videos recorded"],["videos_posted","Videos posted"]].map(([ce,me])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:ce,children:me}),e.jsx(ye,{id:ce,type:"number",min:0,defaultValue:oe[ce]??"",onChange:le=>w(ve=>({...ve,[ce]:Number(le.target.value)}))})]},ce))}),[["biggest_win","Biggest win"],["biggest_challenge","Biggest challenge"],["what_to_improve","What you’ll change next week"]].map(([ce,me])=>e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:ce,children:me}),e.jsx(Ms,{id:ce,rows:2,defaultValue:oe[ce]??"",onChange:le=>w(ve=>({...ve,[ce]:le.target.value}))})]},ce)),e.jsx(B,{onClick:()=>h.mutate({week_number:E,goal_videos:H,...j}),children:"Save check-in"})]})})}),e.jsxs(is,{value:"events",className:"mt-6 space-y-4",children:[Y.length===0&&W.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Sessions will be scheduled before kickoff."}),Y.map(ce=>e.jsx(fe,{className:"border-primary/30",children:e.jsxs(Ee,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(Ue,{variant:"secondary",className:"capitalize",children:String(ce.event_kind).replace("_"," ")}),e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Cl,{className:"h-3 w-3"})," ",Ul(ce.starts_at,!0)]})]}),e.jsx("p",{className:"mt-1.5 font-medium",children:ce.title}),ce.speaker&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["with ",ce.speaker]}),ce.description&&e.jsx("p",{className:"mt-1 text-sm text-muted-foreground",children:ce.description})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p.mutate({eventId:ce.id,optIn:!0}),children:"Remind me"}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>ops(ce,a.name),children:[e.jsx(Cl,{className:"mr-1.5 h-3.5 w-3.5"})," Add to calendar"]}),ce.meeting_link&&e.jsx(B,{size:"sm",asChild:!0,children:e.jsxs("a",{href:ce.meeting_link,target:"_blank",rel:"noreferrer",children:["Join ",e.jsx(tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})},ce.id)),W.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("h3",{className:"pt-2 text-sm font-semibold uppercase tracking-wider text-muted-foreground",children:"Replays"}),W.map(ce=>e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-wrap items-center gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium",children:ce.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ul(ce.starts_at,!0)})]}),ce.replay_url?e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:ce.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(jh,{className:"mr-1.5 h-3.5 w-3.5"})," Watch replay"]})}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Replay coming soon"})]})},ce.id))]})]}),e.jsxs(is,{value:"resources",className:"mt-6 space-y-8",children:[Object.keys(se).length===0&&e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-2 p-12 text-center",children:[e.jsx(br,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"Your resource library is being built"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Worksheets, scripts and swipe files will appear here as the program unlocks."})]})}),Object.entries(se).map(([ce,me])=>e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-[0.18em] text-muted-foreground",children:ce}),e.jsx("span",{className:"h-px flex-1 bg-border"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[me.length," item",me.length===1?"":"s"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 xl:grid-cols-3",children:me.map(le=>{const ve=kxt(le),ge=lps[le.resource_kind]||br;return e.jsxs("a",{href:ve||"#",target:"_blank",rel:"noreferrer",onClick:Te=>{ve||Te.preventDefault()},className:"group relative flex flex-col gap-3 overflow-hidden rounded-2xl border border-border/60 bg-card p-5 transition-all hover:-translate-y-0.5 hover:border-primary/50 hover:shadow-lg",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"flex h-11 w-11 items-center justify-center rounded-xl bg-primary/10 text-primary",children:e.jsx(ge,{className:"h-5 w-5"})}),e.jsx(Ue,{variant:"secondary",className:"capitalize",children:String(le.resource_kind).replace("_"," ")})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"font-semibold leading-snug",children:le.title}),le.description&&e.jsx("p",{className:"line-clamp-3 text-sm text-muted-foreground",children:le.description})]}),e.jsx("span",{className:"mt-auto inline-flex items-center gap-1.5 text-sm font-medium text-primary",children:le.file_path?e.jsxs(e.Fragment,{children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-3.5 w-3.5"})," Open"]})})]},le.id)})})]},ce))]}),e.jsx(is,{value:"profile",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-4 p-6",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ou,{className:"h-5 w-5 text-primary"}),e.jsx("h3",{className:"font-semibold",children:"Your profile review"})]}),!(o!=null&&o.analysis)||o.analysis.status==="not_submitted"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your Instagram review hasn't been submitted yet. Your coach will request screenshots during onboarding week."}):o.analysis.status==="in_review"?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your profile is in review — you'll get a notification when the report is ready."}):e.jsxs("div",{className:"space-y-4",children:[o.analysis.scores&&Object.keys(o.analysis.scores).length>0&&e.jsx("div",{className:"grid gap-3 sm:grid-cols-2",children:Object.entries(o.analysis.scores).map(([ce,me])=>e.jsxs("div",{className:"space-y-1 rounded-lg border border-border/60 p-3",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{className:"capitalize",children:ce.replace(/_/g," ")}),e.jsxs("span",{className:"font-semibold",children:[me,"/10"]})]}),e.jsx(fi,{value:Number(me)*10,className:"h-1.5"})]},ce))}),Array.isArray(o.analysis.top_priorities)&&o.analysis.top_priorities.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:"Top priorities"}),e.jsx("ul",{className:"space-y-1.5",children:o.analysis.top_priorities.map((ce,me)=>e.jsxs("li",{className:"flex items-start gap-2 text-sm",children:[e.jsx(fc,{className:"mt-0.5 h-3.5 w-3.5 shrink-0 text-primary"}),typeof ce=="string"?ce:ce.label]},me))})]}),o.analysis.member_notes&&e.jsx("div",{className:"rounded-lg border border-border/60 bg-muted/30 p-4 text-sm leading-relaxed whitespace-pre-line",children:o.analysis.member_notes}),o.analysis.report_url&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:o.analysis.report_url,target:"_blank",rel:"noreferrer",children:[e.jsx(Ia,{className:"mr-1.5 h-4 w-4"})," Download full report"]})})]})]})})})]})]})})},la=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{className:"relative w-full overflow-auto",children:e.jsx("table",{ref:n,className:Mt("w-full caption-bottom text-sm",s),...t})}));la.displayName="Table";const ca=N.forwardRef(({className:s,...t},n)=>e.jsx("thead",{ref:n,className:Mt("[&_tr]:border-b",s),...t}));ca.displayName="TableHeader";const da=N.forwardRef(({className:s,...t},n)=>e.jsx("tbody",{ref:n,className:Mt("[&_tr:last-child]:border-0",s),...t}));da.displayName="TableBody";const dps=N.forwardRef(({className:s,...t},n)=>e.jsx("tfoot",{ref:n,className:Mt("border-t bg-muted/50 font-medium [&>tr]:last:border-b-0",s),...t}));dps.displayName="TableFooter";const Hs=N.forwardRef(({className:s,...t},n)=>e.jsx("tr",{ref:n,className:Mt("border-b transition-colors data-[state=selected]:bg-muted hover:bg-muted/50",s),...t}));Hs.displayName="TableRow";const Tt=N.forwardRef(({className:s,...t},n)=>e.jsx("th",{ref:n,className:Mt("h-12 px-4 text-left align-middle font-medium text-muted-foreground [&:has([role=checkbox])]:pr-0",s),...t}));Tt.displayName="TableHead";const ht=N.forwardRef(({className:s,...t},n)=>e.jsx("td",{ref:n,className:Mt("p-4 align-middle [&:has([role=checkbox])]:pr-0",s),...t}));ht.displayName="TableCell";const ups=N.forwardRef(({className:s,...t},n)=>e.jsx("caption",{ref:n,className:Mt("mt-4 text-sm text-muted-foreground",s),...t}));ups.displayName="TableCaption";const _H=s=>{if(!s)return"";const t=new Date(s),n=r=>String(r).padStart(2,"0");return`${t.getFullYear()}-${n(t.getMonth()+1)}-${n(t.getDate())}T${n(t.getHours())}:${n(t.getMinutes())}`},wH=s=>s?new Date(s).toISOString():null,s2e=s=>({name:s.name||"",slug:s.slug||"",subtitle:s.subtitle||"",tagline:s.tagline||"",short_description:s.short_description||"",description:s.description||"",price_cents:s.price_cents??0,currency:s.currency||"usd",capacity:s.capacity??0,duration_weeks:s.duration_weeks??13,weekly_video_goal:s.weekly_video_goal??3,payment_mode:s.payment_mode||"delayed",payment_grace_days:s.payment_grace_days??3,timezone:s.timezone||"America/New_York",accent_color:s.accent_color||"",cover_image_url:s.cover_image_url||"",hero_image_url:s.hero_image_url||"",enrollment_open_at:_H(s.enrollment_open_at),enrollment_close_at:_H(s.enrollment_close_at),kickoff_at:_H(s.kickoff_at),charge_at:_H(s.charge_at),status:s.status||"draft",is_public:!!s.is_public,is_featured:!!s.is_featured,sort_order:s.sort_order??0}),hps=({program:s,onSaved:t})=>{const[n,r]=N.useState(()=>s2e(s)),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useRef(null),h=N.useRef(null);N.useEffect(()=>{r(s2e(s)),i(!1)},[s.id,s.updated_at]);const p=(v,j)=>{r(w=>({...w,[v]:j})),i(!0)},f=async(v,j)=>{if(!v.type.startsWith("image/")){ae.error("Please choose an image file");return}if(v.size>8*1024*1024){ae.error("Image must be under 8MB");return}d(j);try{const w=v.name.split(".").pop()||"jpg",S=`programs/${s.id}/${j}-${Date.now()}.${w}`,{error:A}=await q.storage.from("event-images").upload(S,v,{cacheControl:"31536000",upsert:!0});if(A)throw A;const{data:E}=q.storage.from("event-images").getPublicUrl(S);p(j==="cover"?"cover_image_url":"hero_image_url",E.publicUrl),ae.success(`${j==="cover"?"Cover":"Hero"} image uploaded — remember to save`)}catch(w){ae.error(w.message||"Upload failed")}finally{d(null)}},y=async()=>{if(!n.name.trim())return ae.error("Program name is required");if(!n.slug.trim())return ae.error("Slug is required");o(!0);try{const v={name:n.name.trim(),slug:n.slug.trim().toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),subtitle:n.subtitle||null,tagline:n.tagline||null,short_description:n.short_description||null,description:n.description||null,price_cents:Math.max(0,Math.round(n.price_cents)),currency:n.currency||"usd",capacity:Math.max(0,Math.round(n.capacity)),duration_weeks:Math.max(1,Math.round(n.duration_weeks)),weekly_video_goal:Math.max(0,Math.round(n.weekly_video_goal)),payment_mode:n.payment_mode,payment_grace_days:Math.max(0,Math.round(n.payment_grace_days)),timezone:n.timezone||"America/New_York",accent_color:n.accent_color||null,cover_image_url:n.cover_image_url||null,hero_image_url:n.hero_image_url||null,enrollment_open_at:wH(n.enrollment_open_at),enrollment_close_at:wH(n.enrollment_close_at),kickoff_at:wH(n.kickoff_at),charge_at:wH(n.charge_at),status:n.status,is_public:n.is_public,is_featured:n.is_featured,sort_order:Math.round(n.sort_order)},{error:j}=await q.from("programs").update(v).eq("id",s.id);if(j)throw j;ae.success("Program saved"),i(!1),t()}catch(v){ae.error(v.message||"Could not save the program")}finally{o(!1)}},_=({kind:v,label:j,hint:w})=>{const S=v==="cover"?n.cover_image_url:n.hero_image_url,A=v==="cover"?u:h;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:j}),e.jsxs("div",{className:"flex flex-wrap items-start gap-4",children:[e.jsx("div",{className:"relative h-28 w-48 shrink-0 overflow-hidden rounded-lg border border-border bg-muted/40",children:S?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:S,alt:`${j} preview`,className:"h-full w-full object-cover"}),e.jsx("button",{type:"button",onClick:()=>p(v==="cover"?"cover_image_url":"hero_image_url",""),className:"absolute right-1.5 top-1.5 rounded-full bg-background/90 p-1 text-foreground shadow","aria-label":`Remove ${j}`,children:e.jsx($n,{className:"h-3.5 w-3.5"})})]}):e.jsxs("div",{className:"flex h-full w-full flex-col items-center justify-center gap-1 text-muted-foreground",children:[e.jsx(ty,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"No image"})]})}),e.jsxs("div",{className:"min-w-[220px] flex-1 space-y-2",children:[e.jsx("input",{ref:A,type:"file",accept:"image/*",className:"hidden",onChange:E=>{var D;const O=(D=E.target.files)==null?void 0:D[0];O&&f(O,v),E.target.value=""}}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var E;return(E=A.current)==null?void 0:E.click()},disabled:c===v,children:[c===v?e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(_a,{className:"mr-1.5 h-4 w-4"}),"Upload image"]}),e.jsx(ye,{placeholder:"…or paste an image URL",value:S,onChange:E=>p(v==="cover"?"cover_image_url":"hero_image_url",E.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:w})]})]})]})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"sticky top-0 z-10 -mx-1 flex flex-wrap items-center justify-between gap-3 rounded-lg border border-border bg-background/95 px-4 py-3 backdrop-blur",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:a?"You have unsaved changes.":"All changes saved."}),e.jsxs("div",{className:"flex gap-2",children:[a&&e.jsx(B,{variant:"ghost",onClick:()=>{r(s2e(s)),i(!1)},children:"Discard"}),e.jsxs(B,{onClick:y,disabled:l||!a,children:[l?e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})]})]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Basics"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Program name"}),e.jsx(ye,{value:n.name,onChange:v=>p("name",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Slug (public URL)"}),e.jsx(ye,{value:n.slug,onChange:v=>p("slug",v.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["/programs/",n.slug||"slug"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Subtitle"}),e.jsx(ye,{value:n.subtitle,onChange:v=>p("subtitle",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Tagline"}),e.jsx(ye,{value:n.tagline,onChange:v=>p("tagline",v.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Short description (cards & previews)"}),e.jsx(Ms,{rows:2,value:n.short_description,onChange:v=>p("short_description",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Full program description (sales page)"}),e.jsx(Ms,{rows:8,value:n.description,onChange:v=>p("description",v.target.value)})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-6 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Imagery & branding"}),e.jsx(_,{kind:"cover",label:"Program cover image",hint:"Shown on the Programs list and enrollment cards. 1200×630 works great."}),e.jsx(_,{kind:"hero",label:"Hero banner (optional)",hint:"Wide banner used at the top of the program sales page."}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Accent color"}),e.jsx(ye,{placeholder:"#406E71",value:n.accent_color,onChange:v=>p("accent_color",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Sort order"}),e.jsx(ye,{type:"number",value:n.sort_order,onChange:v=>p("sort_order",Number(v.target.value))})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Pricing & seats"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"One-time price (USD)"}),e.jsx(ye,{type:"number",min:0,step:"1",value:n.price_cents/100,onChange:v=>p("price_cents",Math.round(Number(v.target.value)*100))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Seats (capacity)"}),e.jsx(ye,{type:"number",min:0,value:n.capacity,onChange:v=>p("capacity",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Billing mode"}),e.jsxs(us,{value:n.payment_mode,onValueChange:v=>p("payment_mode",v),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"delayed",children:"Save card, charge once later"}),e.jsx(Ze,{value:"immediate",children:"Charge once at checkout"}),e.jsx(Ze,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Charge date (one-time)"}),e.jsx(ye,{type:"datetime-local",value:n.charge_at,onChange:v=>p("charge_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Payment grace days"}),e.jsx(ye,{type:"number",min:0,value:n.payment_grace_days,onChange:v=>p("payment_grace_days",Number(v.target.value))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Days of access kept after a failed charge before access is paused."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Currency"}),e.jsx(ye,{value:n.currency,onChange:v=>p("currency",v.target.value)})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Schedule & structure"}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Enrollment opens"}),e.jsx(ye,{type:"datetime-local",value:n.enrollment_open_at,onChange:v=>p("enrollment_open_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Enrollment closes"}),e.jsx(ye,{type:"datetime-local",value:n.enrollment_close_at,onChange:v=>p("enrollment_close_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Kickoff"}),e.jsx(ye,{type:"datetime-local",value:n.kickoff_at,onChange:v=>p("kickoff_at",v.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Length (weeks)"}),e.jsx(ye,{type:"number",min:1,value:n.duration_weeks,onChange:v=>p("duration_weeks",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Videos per week goal"}),e.jsx(ye,{type:"number",min:0,value:n.weekly_video_goal,onChange:v=>p("weekly_video_goal",Number(v.target.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Timezone"}),e.jsx(ye,{value:n.timezone,onChange:v=>p("timezone",v.target.value)})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[e.jsx("h3",{className:"text-sm font-semibold uppercase tracking-wide text-muted-foreground",children:"Visibility"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Status"}),e.jsxs(us,{value:n.status,onValueChange:v=>p("status",v),children:[e.jsx(ls,{className:"sm:max-w-xs",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ze,{value:"published",children:"Published (members can enroll)"}),e.jsx(Ze,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pin this program to the top."})]}),e.jsx(jn,{checked:n.is_featured,onCheckedChange:v=>p("is_featured",v)})]}),e.jsxs("div",{className:"flex items-center justify-between gap-4 border-t border-border/60 pt-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Visible to all members"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Turn off to keep it invite-only via a direct link."})]}),e.jsx(jn,{checked:n.is_public,onCheckedChange:v=>p("is_public",v)})]})]})}),e.jsx("div",{className:"flex justify-end pb-4",children:e.jsxs(B,{onClick:y,disabled:l||!a,size:"lg",children:[l?e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(Jo,{className:"mr-1.5 h-4 w-4"}),"Save changes"]})})]})},mps=({program:s,enrollment:t,open:n,onOpenChange:r,onUpdated:a})=>{var ee,se,oe,he,ce,me,le;const i=t==null?void 0:t.user_id,[l,o]=N.useState((t==null?void 0:t.admin_notes)||""),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(!1),[y,_]=N.useState(!1),v=N.useRef(null),{data:j,isLoading:w,refetch:S}=dt({queryKey:["admin-program-agent",s.id,i],enabled:n&&!!i,queryFn:async()=>{const[ve,ge,Te,Ie,Ce,Me,Pe,Re]=await Promise.all([q.from("program_weekly_progress").select("*").eq("program_id",s.id).eq("user_id",i).order("week_number"),q.from("program_video_logs").select("*").eq("program_id",s.id).eq("user_id",i).order("posted_at",{ascending:!1}),q.from("program_lesson_completions").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_badge_awards").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_intake_responses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle(),q.from("program_event_attendance").select("*").eq("program_id",s.id).eq("user_id",i),q.from("program_lessons").select("id").eq("program_id",s.id),q.from("program_profile_analyses").select("*").eq("program_id",s.id).eq("user_id",i).maybeSingle()]);return{weekly:ve.data||[],videos:ge.data||[],completions:Te.data||[],badges:Ie.data||[],intake:Ce.data,attendance:Me.data||[],lessonCount:(Pe.data||[]).length,analysis:Re.data}}});N.useEffect(()=>{var ve;h(((ve=j==null?void 0:j.analysis)==null?void 0:ve.member_notes)||"")},[(ee=j==null?void 0:j.analysis)==null?void 0:ee.id]);const A=N.useMemo(()=>{var Te;const ve=lxe(s),ge=((Te=j==null?void 0:j.intake)==null?void 0:Te.extra)||{};return ve.custom.map(Ie=>({label:Ie.label,value:typeof ge[Ie.id]=="boolean"?ge[Ie.id]?"Yes":"No":ge[Ie.id]||""})).filter(Ie=>!!Ie.value)},[s,j==null?void 0:j.intake]),E=async ve=>i?q.from("program_profile_analyses").upsert({program_id:s.id,user_id:i,enrollment_id:(t==null?void 0:t.id)||null,...ve},{onConflict:"program_id,user_id"}):{error:{message:"Missing agent"}},O=async ve=>{if(ve.type!=="application/pdf")return ae.error("Please choose a PDF file");if(ve.size>25*1024*1024)return ae.error("PDF must be under 25MB");_(!0);try{const ge=`programs/${s.id}/reviews/${i}-${Date.now()}.pdf`,{error:Te}=await q.storage.from("event-images").upload(ge,ve,{contentType:"application/pdf",upsert:!0});if(Te)throw Te;const{data:Ie}=q.storage.from("event-images").getPublicUrl(ge),{error:Ce}=await E({report_url:Ie.publicUrl,status:"ready",reviewed_at:new Date().toISOString()});if(Ce)throw Ce;ae.success("Profile review uploaded"),await S()}catch(ge){ae.error(ge.message||"Upload failed")}finally{_(!1)}},D=async()=>{const{error:ve}=await E({report_url:null,status:"in_review"});if(ve)return ae.error(ve.message);ae.success("Review removed"),await S()},I=async()=>{f(!0);const{error:ve}=await E({member_notes:u});if(f(!1),ve)return ae.error(ve.message);ae.success("Review notes saved"),await S()},F=async()=>{if(!t)return;d(!0);const{error:ve}=await q.from("program_enrollments").update({admin_notes:l}).eq("id",t.id);if(d(!1),ve)return ae.error(ve.message);ae.success("Notes saved"),a()},z=((j==null?void 0:j.videos)||[]).filter(ve=>ve.posted).length,H=(s.weekly_video_goal||0)*(s.duration_weeks||0),Z=j!=null&&j.lessonCount?Math.round(((j==null?void 0:j.completions.length)||0)/j.lessonCount*100):0,Y=H?Math.min(100,Math.round(z/H*100)):0,W=((j==null?void 0:j.attendance)||[]).filter(ve=>ve.attended).length;return e.jsx(t0,{open:n,onOpenChange:r,children:e.jsxs(og,{className:"w-full overflow-y-auto sm:max-w-2xl",children:[e.jsxs(jy,{className:"mb-4",children:[e.jsxs(Ny,{children:[((se=t==null?void 0:t.profile)==null?void 0:se.name)||"Agent"," · ",s.name]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(oe=t==null?void 0:t.profile)==null?void 0:oe.email})]}),t?w?e.jsx(Ws,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4 pb-8",children:[e.jsxs("div",{className:"grid gap-3 sm:grid-cols-2",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsx(Ue,{className:"mt-1 capitalize",children:String(t.status).replace(/_/g," ")}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:[Su(t.amount_cents,t.currency)," ·"," ",t.charged_at?`Charged ${Ul(t.charged_at)}`:`Charge ${Ul(t.charge_scheduled_at)||"not set"}`]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Last activity"}),e.jsx("p",{className:"mt-1 text-sm font-medium",children:Ul(t.last_activity_at,!0)||"No activity yet"}),e.jsxs("p",{className:"mt-2 text-xs text-muted-foreground",children:["Enrolled ",Ul(t.created_at)]})]})})]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-4 p-5",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Videos posted"}),e.jsxs("span",{className:"text-muted-foreground",children:[z," / ",H||"—"]})]}),e.jsx(fi,{value:Y})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"mb-1 flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-medium",children:"Curriculum completed"}),e.jsxs("span",{className:"text-muted-foreground",children:[(j==null?void 0:j.completions.length)||0," / ",(j==null?void 0:j.lessonCount)||0]})]}),e.jsx(fi,{value:Z})]}),e.jsxs("div",{className:"flex flex-wrap gap-4 border-t border-border/60 pt-4 text-sm",children:[e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Live sessions attended: "}),W]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Badges: "}),(j==null?void 0:j.badges.length)||0]}),e.jsxs("span",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Weeks reported: "}),(j==null?void 0:j.weekly.length)||0]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Weekly progress"}),((j==null?void 0:j.weekly.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No weekly check-ins yet."}):e.jsx("div",{className:"space-y-3",children:j.weekly.map(ve=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-3 text-sm",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-medium",children:["Week ",ve.week_number]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[ve.videos_posted,"/",ve.goal_videos||s.weekly_video_goal," posted ·"," ",ve.stories_posted," stories"]})]}),ve.biggest_win&&e.jsxs("p",{className:"mt-1 text-muted-foreground",children:["Win: ",ve.biggest_win]}),ve.biggest_challenge&&e.jsxs("p",{className:"text-muted-foreground",children:["Challenge: ",ve.biggest_challenge]})]},ve.id))})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"mb-3 text-sm font-semibold",children:"Video log"}),((j==null?void 0:j.videos.length)||0)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No videos logged yet."}):e.jsx("div",{className:"space-y-2",children:j.videos.slice(0,25).map(ve=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(fr,{className:"h-3.5 w-3.5 shrink-0 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:ve.title||"Untitled video"}),e.jsxs("span",{className:"ml-auto shrink-0 text-xs text-muted-foreground",children:["Wk ",ve.week_number," · ",Ul(ve.posted_at)]}),ve.instagram_url&&e.jsx("a",{href:ve.instagram_url,target:"_blank",rel:"noreferrer",className:"shrink-0 text-muted-foreground hover:text-foreground","aria-label":"Open post",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})]},ve.id))})]})}),(j==null?void 0:j.intake)&&e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-1 p-5 text-sm",children:[e.jsx("p",{className:"mb-2 text-sm font-semibold",children:"Intake answers"}),[["Full name",j.intake.full_name],["Email",j.intake.email],["Phone",j.intake.phone],["Instagram",j.intake.instagram_handle],["City / market",j.intake.city],["Areas served",j.intake.service_areas],["Years in real estate",j.intake.years_experience],["Specialty",j.intake.specialty],["Target audience",j.intake.target_audience],["On camera",j.intake.video_comfort],["Posts today",j.intake.posting_frequency],["Content style",j.intake.content_style],["Interests",j.intake.personal_interests],["#1 goal",j.intake.primary_goal],["Topics to avoid",j.intake.topics_to_avoid],["Time zone",j.intake.timezone]].filter(([,ve])=>!!ve).map(([ve,ge])=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ve,": "]}),ge]},ve)),A.map(({label:ve,value:ge})=>e.jsxs("p",{children:[e.jsxs("span",{className:"text-muted-foreground",children:[ve,": "]}),ge]},ve)),e.jsxs("p",{className:"pt-1 text-xs text-muted-foreground",children:["Content-sharing consent: ",j.intake.consent_public_profile?"Yes":"No"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-3 p-5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Profile review PDF"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Upload this agent's personalized profile review. They see it in their workspace."})]}),((he=j==null?void 0:j.analysis)==null?void 0:he.status)&&e.jsx(Ue,{variant:"secondary",className:"capitalize",children:String(j.analysis.status).replace(/_/g," ")})]}),(ce=j==null?void 0:j.analysis)!=null&&ce.report_url?e.jsxs("div",{className:"flex flex-wrap items-center gap-2 rounded-lg border border-border/60 p-3 text-sm",children:[e.jsx(br,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:"Review uploaded"}),e.jsxs("a",{href:j.analysis.report_url,target:"_blank",rel:"noreferrer",className:"ml-auto inline-flex items-center gap-1 text-primary hover:underline",children:["View ",e.jsx(tr,{className:"h-3.5 w-3.5"})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No review uploaded yet."}),e.jsx("input",{ref:v,type:"file",accept:"application/pdf",className:"hidden",onChange:ve=>{var Te;const ge=(Te=ve.target.files)==null?void 0:Te[0];ge&&O(ge),ve.target.value=""}}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{var ve;return(ve=v.current)==null?void 0:ve.click()},disabled:y,children:[e.jsx(_a,{className:"mr-1.5 h-3.5 w-3.5"}),y?"Uploading…":(me=j==null?void 0:j.analysis)!=null&&me.report_url?"Replace PDF":"Upload PDF"]}),((le=j==null?void 0:j.analysis)==null?void 0:le.report_url)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:D,children:"Remove"})]}),e.jsxs("div",{className:"space-y-2 pt-1",children:[e.jsx(ne,{children:"Review summary shown to the agent (optional)"}),e.jsx(Ms,{rows:3,value:u,onChange:ve=>h(ve.target.value),placeholder:"Top 3 priorities, quick wins, what to fix first…"}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",variant:"outline",onClick:I,disabled:p,children:"Save review notes"})})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-3 p-5",children:[e.jsx(ne,{children:"Coach notes (internal)"}),e.jsx(Ms,{rows:4,value:l,onChange:ve=>o(ve.target.value)}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{size:"sm",onClick:F,disabled:c,children:"Save notes"})})]})})]}):null]})})},pVe={code:"",label:"",kind:"percent",percent_off:"20",amount_off:"",max_redemptions:"",starts_at:"",expires_at:"",is_active:!0},fVe=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},pps=({program:s})=>{const{data:t=[],isLoading:n}=Sms(s.id),r=Cms(s.id),a=Tms(),[i,l]=N.useState(!1),[o,c]=N.useState({...pVe}),d=()=>{c({...pVe}),l(!0)},u=y=>{c({id:y.id,code:y.code,label:y.label||"",kind:y.percent_off!=null?"percent":"amount",percent_off:y.percent_off!=null?String(y.percent_off):"",amount_off:y.amount_off_cents!=null?String(y.amount_off_cents/100):"",max_redemptions:y.max_redemptions!=null?String(y.max_redemptions):"",starts_at:fVe(y.starts_at),expires_at:fVe(y.expires_at),is_active:y.is_active}),l(!0)},h=N.useMemo(()=>{const y=o.kind==="percent"?Math.floor(s.price_cents*Number(o.percent_off||0)/100):Math.round(Number(o.amount_off||0)*100),_=Math.min(Math.max(y,0),s.price_cents);return{discount:_,final:s.price_cents-_}},[o,s.price_cents]),p=async()=>{if(!o.code.trim())return ae.error("Give the code a name, e.g. FOUNDER50");await r.mutateAsync({id:o.id,code:o.code,label:o.label||null,percent_off:o.kind==="percent"?Number(o.percent_off)||0:null,amount_off_cents:o.kind==="amount"?Math.round(Number(o.amount_off||0)*100):null,max_redemptions:o.max_redemptions?Number(o.max_redemptions):null,starts_at:o.starts_at?new Date(o.starts_at).toISOString():null,expires_at:o.expires_at?new Date(o.expires_at).toISOString():null,is_active:o.is_active}),l(!1)},f=y=>{const _=y.percent_off!=null?Math.floor(s.price_cents*Number(y.percent_off)/100):y.amount_off_cents||0,v=Math.max(s.price_cents-Math.min(_,s.price_cents),0);return{off:y.percent_off!=null?`${Number(y.percent_off)}% off`:`${Su(y.amount_off_cents||0,s.currency)} off`,final:Su(v,s.currency)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Discount codes"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Enrollees can enter a code on the final enrollment step. The discount is applied to the one-time ",Su(s.price_cents,s.currency)," charge."]})]}),e.jsxs(_s,{open:i,onOpenChange:l,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{onClick:d,children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," New code"]})}),e.jsxs(bs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:o.id?"Edit discount code":"Create a discount code"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Code"}),e.jsx(ye,{placeholder:"FOUNDER50",value:o.code,onChange:y=>c({...o,code:y.target.value.toUpperCase()})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Internal label (optional)"}),e.jsx(ye,{placeholder:"Founding cohort",value:o.label,onChange:y=>c({...o,label:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Discount type"}),e.jsxs(us,{value:o.kind,onValueChange:y=>c({...o,kind:y}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"percent",children:"Percent off"}),e.jsx(Ze,{value:"amount",children:"Dollar amount off"})]})]})]}),o.kind==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Percent off"}),e.jsx(ye,{type:"number",min:1,max:100,value:o.percent_off,onChange:y=>c({...o,percent_off:y.target.value})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Amount off (USD)"}),e.jsx(ye,{type:"number",min:0,value:o.amount_off,onChange:y=>c({...o,amount_off:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Max redemptions (blank = unlimited)"}),e.jsx(ye,{type:"number",min:1,value:o.max_redemptions,onChange:y=>c({...o,max_redemptions:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Active from (optional)"}),e.jsx(ye,{type:"datetime-local",value:o.starts_at,onChange:y=>c({...o,starts_at:y.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Expires (optional)"}),e.jsx(ye,{type:"datetime-local",value:o.expires_at,onChange:y=>c({...o,expires_at:y.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Code is active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to stop new redemptions instantly."})]}),e.jsx(jn,{checked:o.is_active,onCheckedChange:y=>c({...o,is_active:y})})]}),e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-4 text-sm",children:[e.jsx("p",{className:"font-medium",children:"Enrollee sees"}),e.jsxs("p",{className:"mt-1 text-muted-foreground",children:[Su(s.price_cents,s.currency)," →"," ",e.jsx("span",{className:"font-semibold text-foreground",children:Su(h.final,s.currency)})," ","(",Su(h.discount,s.currency)," off) — charged one time."]})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:p,disabled:r.isPending,children:[r.isPending&&e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save changes":"Create code"]})})]})]})]})}),n?e.jsx(Ws,{className:"h-40 w-full rounded-xl"}):t.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(oh,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No discount codes yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Create a code for early birds, brokerage partners or a founding cohort. Codes are entered by the enrollee at checkout and change the one-time price."})]})}):e.jsx(fe,{children:e.jsx(Ee,{className:"overflow-x-auto p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Code"}),e.jsx(Tt,{children:"Discount"}),e.jsx(Tt,{children:"Price after"}),e.jsx(Tt,{children:"Used"}),e.jsx(Tt,{children:"Window"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:t.map(y=>{const _=f(y);return e.jsxs(Hs,{children:[e.jsxs(ht,{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-mono font-semibold",children:y.code}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{navigator.clipboard.writeText(y.code),ae.success("Code copied")},children:e.jsx(Zr,{className:"h-3.5 w-3.5"})})]}),y.label&&e.jsx("p",{className:"text-xs text-muted-foreground",children:y.label})]}),e.jsx(ht,{className:"whitespace-nowrap",children:e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(QS,{className:"h-3.5 w-3.5 text-muted-foreground"}),_.off]})}),e.jsx(ht,{className:"font-medium",children:_.final}),e.jsxs(ht,{children:[y.times_redeemed,y.max_redemptions?` / ${y.max_redemptions}`:""]}),e.jsxs(ht,{className:"text-xs text-muted-foreground",children:[y.starts_at?`From ${Ul(y.starts_at)}`:"Anytime",y.expires_at?` · until ${Ul(y.expires_at)}`:""]}),e.jsx(ht,{children:e.jsx(Ue,{variant:y.is_active?"default":"secondary",children:y.is_active?"Active":"Paused"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(y),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${y.code}?`)&&a.mutate(y.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},y.id)})})]})})})]})},N_=({ok:s,label:t,detail:n})=>e.jsxs("div",{className:"flex items-start gap-3 border-b border-border/50 py-3 last:border-0",children:[s?e.jsx(vr,{className:"mt-0.5 h-4 w-4 shrink-0 text-primary"}):e.jsx(ic,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:t}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})]}),fps=({program:s})=>{var c,d;const{data:t,isLoading:n}=dt({queryKey:["admin-program-content-counts",s.id],queryFn:async()=>{const[u,h,p,f,y]=await Promise.all([q.from("program_weeks").select("id, week_number, title").eq("program_id",s.id),q.from("program_lessons").select("id, title").eq("program_id",s.id),q.from("program_resources").select("id, title").eq("program_id",s.id),q.from("program_events").select("id, title, starts_at").eq("program_id",s.id),q.from("program_announcements").select("id, title").eq("program_id",s.id)]);return{weeks:u.data||[],lessons:h.data||[],resources:p.data||[],events:f.data||[],announcements:y.data||[]}}}),{notOpenYet:r,closed:a,opensLabel:i}=Wye(s),l=`/programs/${s.slug}`,o=[{icon:un,title:"1 · Sales page",body:`${s.name} — hero image, ${s.subtitle?"subtitle":"no subtitle"}, description, price, dates, seats left and FAQ.`,href:l,cta:"Preview sales page"},{icon:m9,title:"2 · Enrollment intake",body:"4 steps: business profile, content style, goals, then the seat + payment summary with the discount-code field.",href:`${l}/enroll`,cta:"Preview enrollment flow"},{icon:uf,title:"3 · Checkout",body:s.payment_mode==="free"?"Free program — seat is confirmed instantly, no card collected.":s.payment_mode==="delayed"?`Stripe collects and saves the card today. The single ${Su(s.price_cents,s.currency)} charge runs on ${Ul(s.charge_at||s.kickoff_at)||"the charge date (not set)"}.`:`Stripe charges ${Su(s.price_cents,s.currency)} once at checkout.`},{icon:Gs,title:"4 · Emails",body:"Confirmation right after enrollment, then payment receipt (or a payment-failed action email) when the one-time charge runs."},{icon:lL,title:"5 · Program workspace",body:`Their home base: progress dashboard, ${s.duration_weeks}-week roadmap, lessons, resources, events, weekly check-ins and video logging (${s.weekly_video_goal}/week goal).`,href:`${l}/workspace?preview=1`,cta:"Preview workspace as an enrollee"}];return e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-wrap items-center justify-between gap-4 p-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"What enrollees see"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Walk the exact member journey end to end. Workspace preview opens in read-only admin mode — it does not create an enrollment."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:l,target:"_blank",rel:"noreferrer",children:["Sales page ",e.jsx(tr,{className:"ml-1.5 h-3.5 w-3.5"})]})}),e.jsx(B,{asChild:!0,children:e.jsxs("a",{href:`${l}/workspace?preview=1`,target:"_blank",rel:"noreferrer",children:["Workspace preview ",e.jsx(tr,{className:"ml-1.5 h-3.5 w-3.5"})]})})]})]})}),(s.status!=="published"||r||a)&&e.jsx(fe,{className:"border-amber-500/40 bg-amber-500/5",children:e.jsxs(Ee,{className:"flex items-start gap-3 p-5 text-sm",children:[e.jsx(ic,{className:"mt-0.5 h-4 w-4 shrink-0 text-amber-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Members can't enroll right now"}),e.jsx("p",{className:"text-muted-foreground",children:s.status!=="published"?`This program is ${s.status} — it isn't listed on the member Programs page yet.`:r?`Enrollment opens ${i}. CTAs are disabled until then.`:"Enrollment has closed for this cohort."})]})]})}),e.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-3 p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"The enrollee journey"}),e.jsx("div",{className:"space-y-4",children:o.map(u=>e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg bg-primary/10",children:e.jsx(u.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 space-y-1",children:[e.jsx("p",{className:"text-sm font-medium",children:u.title}),e.jsx("p",{className:"text-sm text-muted-foreground",children:u.body}),u.href&&e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:u.href,target:"_blank",rel:"noreferrer",children:[u.cta," ",e.jsx(tr,{className:"ml-1 h-3 w-3"})]})})]})]},u.title))})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Premium-experience checklist"}),n?e.jsx(Ws,{className:"mt-4 h-64 w-full rounded-lg"}):e.jsxs("div",{className:"mt-2",children:[e.jsx(N_,{ok:!!s.cover_image_url,label:"Cover image",detail:s.cover_image_url?"Set":"Missing — cards look empty on the Programs page"}),e.jsx(N_,{ok:!!s.hero_image_url,label:"Hero image on the sales page",detail:s.hero_image_url?"Set":"Missing — sales page falls back to a gradient"}),e.jsx(N_,{ok:!!s.short_description&&!!s.description,label:"Short + full description",detail:s.short_description&&s.description?"Both written":"Fill both in Details & pricing so the sales page reads well"}),e.jsx(N_,{ok:s.payment_mode==="free"||s.price_cents>0,label:"One-time price",detail:s.payment_mode==="free"?"Free / included":Su(s.price_cents,s.currency)}),e.jsx(N_,{ok:!!s.kickoff_at&&(s.payment_mode==="free"||!!s.charge_at),label:"Kickoff and charge dates",detail:`Kickoff ${Ul(s.kickoff_at)||"not set"} · charge ${Ul(s.charge_at)||"not set"}`}),e.jsx(N_,{ok:((t==null?void 0:t.weeks.length)||0)>0,label:"Weekly roadmap",detail:`${(t==null?void 0:t.weeks.length)||0} of ${s.duration_weeks} weeks built`}),e.jsx(N_,{ok:((t==null?void 0:t.lessons.length)||0)>0,label:"Lessons",detail:`${(t==null?void 0:t.lessons.length)||0} lessons — the workspace Curriculum tab is empty without these`}),e.jsx(N_,{ok:((t==null?void 0:t.resources.length)||0)>0,label:"Resources / downloads",detail:`${(t==null?void 0:t.resources.length)||0} resources`}),e.jsx(N_,{ok:((t==null?void 0:t.events.length)||0)>0,label:"Live calls on the calendar",detail:`${(t==null?void 0:t.events.length)||0} events${(d=(c=t==null?void 0:t.events)==null?void 0:c[0])!=null&&d.starts_at?` · next ${Ul(t.events[0].starts_at)}`:""}`}),e.jsx(N_,{ok:((t==null?void 0:t.announcements.length)||0)>0,label:"Welcome announcement",detail:`${(t==null?void 0:t.announcements.length)||0} announcements — a day-one welcome post makes the workspace feel alive`})]})]})})]}),t&&e.jsx(fe,{children:e.jsx(Ee,{className:"grid gap-4 p-5 sm:grid-cols-2 lg:grid-cols-5",children:[{icon:Cl,label:"Weeks",value:t.weeks.length},{icon:br,label:"Lessons",value:t.lessons.length},{icon:br,label:"Resources",value:t.resources.length},{icon:Cl,label:"Events",value:t.events.length},{icon:zd,label:"Announcements",value:t.announcements.length}].map((u,h)=>e.jsxs("div",{className:"rounded-lg border border-border/60 p-4",children:[e.jsx(u.icon,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("p",{className:"mt-2 text-2xl font-bold",children:u.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:u.label})]},h))})}),e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Tip: preview in an incognito window as a test member to see the real enrollment flow end to end."})]})},xps=["Step 1 · Your business","Step 2 · Your content","Step 3 · Your goals"],gps={short_text:"Short answer",long_text:"Paragraph",select:"Dropdown",checkbox:"Yes / no checkbox"},yps=({program:s,onSaved:t})=>{const[n,r]=N.useState(()=>lxe(s)),[a,i]=N.useState(!1),[l,o]=N.useState(!1);N.useEffect(()=>{r(lxe(s)),i(!1)},[s.id,s.updated_at]);const c=v=>{r(j=>({...j,...v})),i(!0)},d=(v,j)=>{const w=j?n.hidden.filter(A=>A!==v):[...new Set([...n.hidden,v])],S=j?n.required:n.required.filter(A=>A!==v);c({hidden:w,required:S})},u=(v,j)=>{c({required:j?[...new Set([...n.required,v])]:n.required.filter(w=>w!==v)})},h=()=>{const v={id:`q_${Date.now().toString(36)}`,label:"",type:"short_text",required:!1,options:[]};c({custom:[...n.custom,v]})},p=(v,j)=>c({custom:n.custom.map(w=>w.id===v?{...w,...j}:w)}),f=v=>c({custom:n.custom.filter(j=>j.id!==v)}),y=(v,j)=>{const w=[...n.custom],S=v+j;S<0||S>=w.length||([w[v],w[S]]=[w[S],w[v]],c({custom:w}))},_=async()=>{if(n.custom.find(S=>!S.label.trim()))return ae.error("Every custom question needs a label");o(!0);const j={...s.sales_copy||{},intake:n},{error:w}=await q.from("programs").update({sales_copy:j}).eq("id",s.id);if(o(!1),w)return ae.error(w.message);i(!1),ae.success("Intake form saved"),t==null||t()};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-semibold",children:"Intake form"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Controls the questions each agent answers during enrollment."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:`/programs/${s.slug}/enroll`,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"mr-1.5 h-3.5 w-3.5"})," Preview form"]})}),e.jsxs(B,{size:"sm",onClick:_,disabled:!a||l,children:[e.jsx(Jo,{className:"mr-1.5 h-3.5 w-3.5"}),l?"Saving…":"Save intake form"]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsx(Rt,{className:"text-sm",children:"Intro message"})}),e.jsx(Ee,{children:e.jsx(Ms,{rows:3,placeholder:"Shown at the top of the intake — e.g. “Answer a few questions so we can personalize your 90 days.”",value:n.intro||"",onChange:v=>c({intro:v.target.value})})})]}),[0,1,2].map(v=>e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsx(Rt,{className:"text-sm",children:xps[v]})}),e.jsxs(Ee,{className:"space-y-2",children:[e.jsxs("div",{className:"hidden grid-cols-[1fr,auto,auto] gap-4 pb-1 text-xs uppercase tracking-wide text-muted-foreground sm:grid",children:[e.jsx("span",{children:"Question"}),e.jsx("span",{className:"w-16 text-center",children:"Show"}),e.jsx("span",{className:"w-16 text-center",children:"Required"})]}),_xt.filter(j=>j.step===v).map(j=>{const w=!n.hidden.includes(j.key);return e.jsxs("div",{className:"grid grid-cols-[1fr,auto,auto] items-center gap-4 rounded-lg border border-border/60 px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:j.label}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(jn,{checked:w,onCheckedChange:S=>d(j.key,S),"aria-label":`Show ${j.label}`})}),e.jsx("div",{className:"flex w-16 justify-center",children:e.jsx(jn,{checked:n.required.includes(j.key),disabled:!w,onCheckedChange:S=>u(j.key,S),"aria-label":`Require ${j.label}`})})]},j.key)})]})]},v)),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex-row items-center justify-between space-y-0 pb-3",children:[e.jsxs(Rt,{className:"text-sm",children:["Custom questions"," ",e.jsx(Ue,{variant:"secondary",className:"ml-1",children:n.custom.length})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:h,children:[e.jsx(Is,{className:"mr-1.5 h-3.5 w-3.5"})," Add question"]})]}),e.jsxs(Ee,{className:"space-y-3",children:[n.custom.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No custom questions yet. Add program-specific questions here — answers appear on each agent's dashboard."}),n.custom.map((v,j)=>e.jsxs("div",{className:"space-y-3 rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("div",{className:"flex flex-col pt-1.5",children:e.jsx("button",{type:"button",className:"text-muted-foreground hover:text-foreground",onClick:()=>y(j,-1),"aria-label":"Move up",children:e.jsx(Pu,{className:"h-4 w-4"})})}),e.jsxs("div",{className:"grid flex-1 gap-3 sm:grid-cols-[2fr,1fr]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Question"}),e.jsx(ye,{value:v.label,placeholder:"What is your biggest content roadblock?",onChange:w=>p(v.id,{label:w.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Answer type"}),e.jsxs(us,{value:v.type,onValueChange:w=>p(v.id,{type:w}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Object.entries(gps).map(([w,S])=>e.jsx(Ze,{value:w,children:S},w))})]})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>f(v.id),"aria-label":"Delete question",children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]}),v.type==="select"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Options (one per line)"}),e.jsx(Ms,{rows:3,value:(v.options||[]).join(` `),onChange:w=>p(v.id,{options:w.target.value.split(` `).map(S=>S.trim()).filter(Boolean)})})]}),e.jsxs("div",{className:"grid gap-3 sm:grid-cols-[1fr,auto]",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Helper text (optional)"}),e.jsx(ye,{value:v.help||"",onChange:w=>p(v.id,{help:w.target.value})})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(jn,{checked:!!v.required,onCheckedChange:w=>p(v.id,{required:w}),"aria-label":"Required"}),e.jsx("span",{className:"text-sm",children:"Required"})]})]})]},v.id))]})]})]})},vps=[{value:"kickoff",label:"Kickoff call"},{value:"mastermind",label:"Mastermind"},{value:"workshop",label:"Workshop / training"},{value:"office_hours",label:"Office hours / Q&A"},{value:"other",label:"Other"}],bps=s=>{if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)},xVe={title:"",description:"",event_kind:"mastermind",starts_at:"",duration_minutes:60,speaker:"",meeting_link:"",replay_url:"",is_published:!0},_ps=({programId:s})=>{const{data:t=[],isLoading:n}=Mms(s),r=Ims(s),a=Pms(),[i,l]=N.useState(!1),[o,c]=N.useState({...xVe}),d=()=>{c({...xVe}),l(!0)},u=v=>{c({id:v.id,title:v.title,description:v.description||"",event_kind:v.event_kind,starts_at:bps(v.starts_at),duration_minutes:v.duration_minutes,speaker:v.speaker||"",meeting_link:v.meeting_link||"",replay_url:v.replay_url||"",is_published:v.is_published}),l(!0)},h=async()=>{if(!o.title.trim())return ae.error("Give the session a title");if(!o.starts_at)return ae.error("Pick a date and time");await r.mutateAsync({...o,starts_at:new Date(o.starts_at).toISOString(),duration_minutes:Number(o.duration_minutes)||60}),l(!1)},p=Date.now(),f=t.filter(v=>new Date(v.starts_at).getTime()>=p),y=t.filter(v=>new Date(v.starts_at).getTime()e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(Ue,{variant:"secondary",className:"capitalize",children:v.event_kind.replace("_"," ")}),!v.is_published&&e.jsx(Ue,{variant:"outline",children:"Hidden"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ul(v.starts_at,!0)," · ",v.duration_minutes," min",v.speaker?` · ${v.speaker}`:""]}),v.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.description}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[v.meeting_link?e.jsxs(e.Fragment,{children:[e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.meeting_link,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3 w-3"})," Join link"]}),e.jsxs("button",{className:"inline-flex items-center gap-1 text-muted-foreground hover:text-foreground",onClick:()=>{navigator.clipboard.writeText(v.meeting_link),ae.success("Join link copied")},children:[e.jsx(Zr,{className:"h-3 w-3"})," Copy"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"No meeting link yet"}),v.replay_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.replay_url,target:"_blank",rel:"noreferrer",children:[e.jsx(fr,{className:"h-3 w-3"})," Replay"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>u(v),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{confirm(`Remove "${v.title}"?`)&&a.mutate(v.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Live sessions"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add your Zoom (or Meet / Teams) sessions here. Enrolled members see them in the Sessions tab with the join button, RSVP reminders and an add-to-calendar link."})]}),e.jsxs(B,{onClick:d,children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," Add session"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading sessions…"}):t.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Xf,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No live sessions scheduled"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Paste your recurring Zoom link once for each call — kickoff, weekly masterminds, workshops and office hours."})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Upcoming (",f.length,")"]}),f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Nothing upcoming."}):f.map(v=>e.jsx(_,{e:v},v.id))]}),y.length>0&&e.jsxs("section",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Past (",y.length,") — add replay links so members can catch up"]}),y.map(v=>e.jsx(_,{e:v},v.id))]})]}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:o.id?"Edit session":"Add a live session"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{placeholder:"Week 1 Mastermind — Content that converts",value:o.title,onChange:v=>c({...o,title:v.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Type"}),e.jsxs(us,{value:o.event_kind,onValueChange:v=>c({...o,event_kind:v}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:vps.map(v=>e.jsx(Ze,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Host / speaker"}),e.jsx(ye,{value:o.speaker,onChange:v=>c({...o,speaker:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Starts (your local time)"}),e.jsx(ye,{type:"datetime-local",value:o.starts_at,onChange:v=>c({...o,starts_at:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Length (minutes)"}),e.jsx(ye,{type:"number",value:o.duration_minutes,onChange:v=>c({...o,duration_minutes:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Zoom / meeting link"}),e.jsx(ye,{placeholder:"https://us02web.zoom.us/j/1234567890?pwd=…",value:o.meeting_link,onChange:v=>c({...o,meeting_link:v.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Members only see this after they're enrolled. A recurring Zoom link can be reused on every session."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Replay link (after the call)"}),e.jsx(ye,{placeholder:"YouTube, Vimeo, Loom or Zoom cloud recording URL",value:o.replay_url,onChange:v=>c({...o,replay_url:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"What we'll cover"}),e.jsx(Ms,{rows:3,value:o.description,onChange:v=>c({...o,description:v.target.value})})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border border-border/60 p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Visible to members"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Turn off to draft a session privately."})]}),e.jsx(jn,{checked:o.is_published,onCheckedChange:v=>c({...o,is_published:v})})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:h,disabled:r.isPending,children:[r.isPending&&e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"}),o.id?"Save session":"Add session"]})})]})})]})},gVe={title:"",summary:"",week_id:"none",duration_minutes:"",video_url:"",worksheet_url:"",action_assignment:"",status:"published",sort_order:0},wps=({programId:s})=>{const{data:t,isLoading:n}=Lms(s),r=(t==null?void 0:t.lessons)||[],a=(t==null?void 0:t.weeks)||[],i=Dms(s),l=Rms(),[o,c]=N.useState(!1),[d,u]=N.useState({...gVe}),h=()=>{u({...gVe,sort_order:r.length}),c(!0)},p=v=>{u({id:v.id,title:v.title,summary:v.summary||"",week_id:v.week_id||"none",duration_minutes:v.duration_minutes??"",video_url:v.video_url||"",worksheet_url:v.worksheet_url||"",action_assignment:v.action_assignment||"",status:v.status,sort_order:v.sort_order}),c(!0)},f=async()=>{if(!d.title.trim())return ae.error("Give the video a title");await i.mutateAsync({...d,week_id:d.week_id==="none"?null:d.week_id,duration_minutes:d.duration_minutes===""?null:Number(d.duration_minutes),sort_order:Number(d.sort_order)||0}),c(!1)},y=v=>{const j=a.find(w=>w.id===v);return j?`Week ${j.week_number}`:"Unassigned"},_=Nxt(d.video_url);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"On-demand videos"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Your program's video library. Paste a YouTube, Vimeo or Loom link and it plays inline in the member workspace, grouped by week, with completion tracking."})]}),e.jsxs(B,{onClick:h,children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," Add video"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading library…"}):r.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(Sh,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No on-demand videos yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add training videos members can watch any time — assign each one to a week to build the roadmap."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(v=>e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:v.title}),e.jsx(Ue,{variant:"secondary",children:y(v.week_id)}),v.status!=="published"&&e.jsx(Ue,{variant:"outline",className:"capitalize",children:v.status}),v.duration_minutes?e.jsxs("span",{className:"text-xs text-muted-foreground",children:[v.duration_minutes," min"]}):null]}),v.summary&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:v.summary}),e.jsxs("div",{className:"flex flex-wrap gap-3 pt-1 text-xs",children:[v.video_url?e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.video_url,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3 w-3"})," Video"]}):e.jsx("span",{className:"text-muted-foreground",children:"No video link"}),v.worksheet_url&&e.jsxs("a",{className:"inline-flex items-center gap-1 text-primary hover:underline",href:v.worksheet_url,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3 w-3"})," Worksheet"]})]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>p(v),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{confirm(`Remove "${v.title}"?`)&&l.mutate(v.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})},v.id))}),e.jsx(_s,{open:o,onOpenChange:c,children:e.jsxs(bs,{className:"max-h-[85vh] max-w-2xl overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:d.id?"Edit video":"Add an on-demand video"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{placeholder:"How to script a 30-second listing reel",value:d.title,onChange:v=>u({...d,title:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Video link"}),e.jsx(ye,{placeholder:"https://youtu.be/… , Vimeo or Loom URL",value:d.video_url,onChange:v=>u({...d,video_url:v.target.value})}),d.video_url&&!_&&e.jsx("p",{className:"text-xs text-muted-foreground",children:`We can't embed this link — members will get an "Open video" button instead.`})]}),_&&e.jsx("div",{className:"overflow-hidden rounded-lg border border-border/60",children:e.jsx("iframe",{src:_,title:"Video preview",className:"aspect-video w-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; picture-in-picture",allowFullScreen:!0})}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Week"}),e.jsxs(us,{value:d.week_id,onValueChange:v=>u({...d,week_id:v}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"Unassigned (library)"}),a.map(v=>e.jsxs(Ze,{value:v.id,children:["Week ",v.week_number," — ",v.title]},v.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Length (minutes)"}),e.jsx(ye,{type:"number",value:d.duration_minutes,onChange:v=>u({...d,duration_minutes:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Status"}),e.jsxs(us,{value:d.status,onValueChange:v=>u({...d,status:v}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"published",children:"Published (visible)"}),e.jsx(Ze,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ze,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Order"}),e.jsx(ye,{type:"number",value:d.sort_order,onChange:v=>u({...d,sort_order:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Summary"}),e.jsx(Ms,{rows:3,value:d.summary,onChange:v=>u({...d,summary:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Worksheet / download link"}),e.jsx(ye,{value:d.worksheet_url,onChange:v=>u({...d,worksheet_url:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Action assignment"}),e.jsx(Ms,{rows:2,placeholder:"Post one reel using this hook before your next mastermind.",value:d.action_assignment,onChange:v=>u({...d,action_assignment:v.target.value})})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:f,disabled:i.isPending,children:[i.isPending&&e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"}),d.id?"Save video":"Add video"]})})]})})]})},yVe={title:"",description:"",category:"Resources",resource_kind:"pdf",url:"",file_path:"",status:"published",sort_order:0},jps=({programId:s})=>{const{data:t=[],isLoading:n}=Fms(s),r=zms(s),a=Bms(),[i,l]=N.useState(!1),[o,c]=N.useState({...yVe}),[d,u]=N.useState(!1),h=N.useRef(null),p=Array.from(new Set(t.map(j=>j.category))).filter(Boolean),f=()=>{c({...yVe,sort_order:t.length}),l(!0)},y=j=>{c({id:j.id,title:j.title,description:j.description||"",category:j.category||"Resources",resource_kind:j.resource_kind,url:j.url||"",file_path:j.file_path||"",status:j.status,sort_order:j.sort_order}),l(!0)},_=async j=>{if(!(!j||!s)){if(j.size>50*1024*1024)return ae.error("File must be under 50MB");u(!0);try{const w=j.name.split(".").pop()||"pdf",S=`programs/${s}/resources/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${w}`,{error:A}=await q.storage.from(Y6e).upload(S,j,{contentType:j.type||"application/pdf",upsert:!1});if(A)throw A;c(E=>({...E,file_path:S,url:"",title:E.title||j.name.replace(/\.[^.]+$/,""),resource_kind:j.type==="application/pdf"?"pdf":E.resource_kind})),ae.success("File uploaded")}catch(w){ae.error(w.message||"Upload failed")}finally{u(!1),h.current&&(h.current.value="")}}},v=async()=>{if(!o.title.trim())return ae.error("Give the resource a title");if(!o.file_path&&!o.url.trim())return ae.error("Upload a file or paste a link");await r.mutateAsync({...o,sort_order:Number(o.sort_order)||0}),l(!1)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Resources"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload PDFs, worksheets and checklists — or link to Canva/Google templates. Enrollees see them grouped by category in their program dashboard."})]}),e.jsxs(B,{onClick:f,children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," Add resource"]})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading resources…"}):t.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center gap-3 p-12 text-center",children:[e.jsx(br,{className:"h-8 w-8 text-muted-foreground"}),e.jsx("p",{className:"font-medium",children:"No resources yet"}),e.jsx("p",{className:"max-w-md text-sm text-muted-foreground",children:"Add the swipe files, scripts and worksheets that make this program feel premium."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(j=>{const w=kxt(j);return e.jsx(fe,{className:"border-border/60",children:e.jsxs(Ee,{className:"flex flex-wrap items-start justify-between gap-4 p-5",children:[e.jsxs("div",{className:"min-w-0 space-y-1.5",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:j.title}),e.jsx(Ue,{variant:"secondary",children:j.category}),e.jsx(Ue,{variant:"outline",className:"capitalize",children:j.resource_kind.replace("_"," ")}),j.status!=="published"&&e.jsx(Ue,{variant:"outline",className:"capitalize",children:j.status})]}),j.description&&e.jsx("p",{className:"max-w-2xl text-sm text-muted-foreground",children:j.description}),w&&e.jsxs("a",{href:w,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(tr,{className:"h-3 w-3"})," Open"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>y(j),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm(`Remove "${j.title}"?`)&&a.mutate(j)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})]})},j.id)})}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(ws,{children:o.id?"Edit resource":"Add resource"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:o.title,onChange:j=>c({...o,title:j.target.value}),placeholder:"90-Day Content Calendar"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{rows:2,value:o.description,onChange:j=>c({...o,description:j.target.value}),placeholder:"What this is and how to use it"})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Category"}),e.jsx(ye,{value:o.category,onChange:j=>c({...o,category:j.target.value}),placeholder:"Getting started",list:"program-resource-categories"}),e.jsx("datalist",{id:"program-resource-categories",children:p.map(j=>e.jsx("option",{value:j},j))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Type"}),e.jsxs(us,{value:o.resource_kind,onValueChange:j=>c({...o,resource_kind:j}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Oms.map(j=>e.jsx(Ze,{value:j.value,children:j.label},j.value))})]})]})]}),e.jsxs("div",{className:"space-y-2 rounded-lg border p-3",children:[e.jsx(ne,{children:"File"}),e.jsx("input",{ref:h,type:"file",className:"hidden",accept:".pdf,.doc,.docx,.xls,.xlsx,.ppt,.pptx,.csv,.zip,image/*",onChange:j=>{var w;return _((w=j.target.files)==null?void 0:w[0])}}),o.file_path?e.jsxs("div",{className:"flex items-center justify-between gap-2 text-sm",children:[e.jsx("span",{className:"truncate",children:o.file_path.split("/").pop()}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c({...o,file_path:""}),children:"Remove"})]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{var j;return(j=h.current)==null?void 0:j.click()},disabled:d,children:[d?e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(_a,{className:"mr-1.5 h-4 w-4"}),"Upload PDF or document"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Or paste an external link instead (Canva, Google Doc, Notion…)."}),e.jsx(ye,{value:o.url,onChange:j=>c({...o,url:j.target.value,file_path:""}),placeholder:"https://…",disabled:!!o.file_path})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Status"}),e.jsxs(us,{value:o.status,onValueChange:j=>c({...o,status:j}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"published",children:"Published (visible)"}),e.jsx(Ze,{value:"draft",children:"Draft (hidden)"}),e.jsx(Ze,{value:"archived",children:"Archived"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Sort order"}),e.jsx(ye,{type:"number",value:o.sort_order,onChange:j=>c({...o,sort_order:j.target.value})})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:r.isPending||d,children:[r.isPending&&e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"})," Save resource"]})]})]})})]})},Nps=({programId:s})=>{const{data:t=[],isLoading:n}=qms(s),r=N.useMemo(()=>{const l=Date.now()-6048e5;return t.filter(o=>new Date(o.created_at).getTime()>=l).length},[t]),a=t.map(l=>l.email).filter(Boolean).join(", "),i=()=>{const l=`Name,Email,Phone,Brokerage,Joined `,o=t.map(u=>[u.full_name,u.email,u.phone,u.brokerage,u.created_at].map(h=>`"${(h??"").toString().replace(/"/g,'""')}"`).join(",")).join(` `),c=URL.createObjectURL(new Blob([l+o],{type:"text/csv"})),d=document.createElement("a");d.href=c,d.download="program-interest.csv",d.click(),URL.revokeObjectURL(c)};return n?e.jsx(Ws,{className:"h-64 w-full rounded-xl"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(BS,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:t.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"On the notify list"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(An,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:r}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Signed up in last 7 days"})]})]})}),e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center gap-3 p-4",children:e.jsxs(Ue,{variant:"secondary",children:[t.filter(l=>l.notified_at).length," notified"]})})})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:!a,onClick:()=>{navigator.clipboard.writeText(a),ae.success("Emails copied")},children:[e.jsx(Zr,{className:"mr-2 h-4 w-4"})," Copy emails"]}),e.jsxs(B,{variant:"outline",size:"sm",disabled:!t.length,onClick:i,children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"})," Export CSV"]})]}),t.length===0?e.jsx("p",{className:"rounded-lg border border-dashed p-8 text-center text-sm text-muted-foreground",children:"Nobody has asked to be notified yet."}):e.jsx("div",{className:"rounded-lg border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Joined"})]})}),e.jsx(da,{children:t.map(l=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:l.full_name||"—"}),e.jsx(ht,{children:l.email||"—"}),e.jsx(ht,{children:l.phone||"—"}),e.jsx(ht,{children:l.brokerage||"—"}),e.jsx(ht,{className:"text-muted-foreground",children:Ul(l.created_at)})]},l.id))})]})})]})},vVe={name:"",slug:"",subtitle:"",short_description:"",description:"",price_cents:0,capacity:50,duration_weeks:13,weekly_video_goal:3,payment_mode:"delayed",status:"draft",kickoff_at:"",charge_at:"",enrollment_close_at:"",cover_image_url:""},kps=()=>{const s=Kt(),[t,n]=N.useState(null),[r,a]=N.useState(!1),[i,l]=N.useState({...vVe}),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(null),{data:f=[],isLoading:y}=dt({queryKey:["admin-programs"],queryFn:async()=>{const{data:I,error:F}=await q.from("programs").select("*").order("created_at",{ascending:!1});if(F)throw F;return I||[]}}),_=f.find(I=>I.id===t)||f[0]||null,{data:v=[]}=dt({queryKey:["admin-program-enrollments",_==null?void 0:_.id],enabled:!!(_!=null&&_.id),queryFn:async()=>{const{data:I,error:F}=await q.from("program_enrollments").select("*").eq("program_id",_.id).order("created_at",{ascending:!1});if(F)throw F;const z=(I||[]).map(Y=>Y.user_id),{data:H}=z.length?await q.from("profiles").select("id, name, email").in("id",z):{data:[]},Z=new Map((H||[]).map(Y=>[Y.id,Y]));return(I||[]).map(Y=>({...Y,profile:Z.get(Y.user_id)}))}}),{data:j=[]}=dt({queryKey:["admin-program-intakes",_==null?void 0:_.id],enabled:!!(_!=null&&_.id),queryFn:async()=>{const{data:I,error:F}=await q.from("program_intake_responses").select("*").eq("program_id",_.id);if(F)throw F;return I||[]}}),{data:w=[]}=dt({queryKey:["admin-program-audit",_==null?void 0:_.id],enabled:!!(_!=null&&_.id),queryFn:async()=>{const{data:I,error:F}=await q.from("program_audit_logs").select("*").eq("program_id",_.id).order("created_at",{ascending:!1}).limit(100);if(F)throw F;return I||[]}}),S=async()=>{c(!0);try{const I={...i,slug:i.slug||i.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,""),kickoff_at:i.kickoff_at||null,charge_at:i.charge_at||null,enrollment_close_at:i.enrollment_close_at||null},{error:F}=await q.from("programs").insert(I);if(F)throw F;ae.success("Program created"),a(!1),l({...vVe}),s.invalidateQueries({queryKey:["admin-programs"]})}catch(I){ae.error(I.message||"Could not create the program")}finally{c(!1)}},A=async I=>{if(!_)return;const{error:F}=await q.from("programs").update(I).eq("id",_.id);if(F)return ae.error(F.message);s.invalidateQueries({queryKey:["admin-programs"]})},E=async(I,F)=>{const{error:z}=await q.from("program_enrollments").update(F).eq("id",I);if(z)return ae.error(z.message);ae.success("Enrollment updated"),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},O=async I=>{u(!0);const{data:F,error:z}=await q.functions.invoke("program-charge-due",{body:I?{enrollment_id:I}:{}});if(u(!1),z||F!=null&&F.error)return ae.error((F==null?void 0:F.error)||(z==null?void 0:z.message));ae.success(`Processed ${(F==null?void 0:F.processed)??0} charge(s)`),s.invalidateQueries({queryKey:["admin-program-enrollments"]})},D=I=>I==="paid"||I==="completed"?"default":I==="payment_failed"?"destructive":"secondary";return e.jsx(Cs,{children:e.jsxs("div",{className:"mx-auto w-full max-w-7xl space-y-6 p-4 md:p-8",children:[e.jsxs("header",{className:"flex flex-wrap items-end justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Programs"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage cohorts, enrollments, delayed billing and program content."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>O(),disabled:d,children:[d?e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"}):e.jsx(uf,{className:"mr-1.5 h-4 w-4"}),"Run due charges"]}),e.jsxs(_s,{open:r,onOpenChange:a,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"mr-1.5 h-4 w-4"})," New program"]})}),e.jsxs(bs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Create a program"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Name"}),e.jsx(ye,{value:i.name,onChange:I=>l({...i,name:I.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Slug (URL)"}),e.jsx(ye,{placeholder:"reel-estate-90",value:i.slug,onChange:I=>l({...i,slug:I.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Subtitle"}),e.jsx(ye,{value:i.subtitle,onChange:I=>l({...i,subtitle:I.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{rows:4,value:i.description,onChange:I=>l({...i,description:I.target.value})})]}),e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"One-time price (USD)"}),e.jsx(ye,{type:"number",value:i.price_cents/100,onChange:I=>l({...i,price_cents:Math.round(Number(I.target.value)*100)})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Charged one time for the full program — never recurring."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Seats"}),e.jsx(ye,{type:"number",value:i.capacity,onChange:I=>l({...i,capacity:Number(I.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Weeks"}),e.jsx(ye,{type:"number",value:i.duration_weeks,onChange:I=>l({...i,duration_weeks:Number(I.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Videos per week"}),e.jsx(ye,{type:"number",value:i.weekly_video_goal,onChange:I=>l({...i,weekly_video_goal:Number(I.target.value)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Billing"}),e.jsxs(us,{value:i.payment_mode,onValueChange:I=>l({...i,payment_mode:I}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"delayed",children:"Save card, charge later"}),e.jsx(Ze,{value:"immediate",children:"Charge at checkout"}),e.jsx(Ze,{value:"free",children:"Free / included"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Kickoff"}),e.jsx(ye,{type:"datetime-local",value:i.kickoff_at,onChange:I=>l({...i,kickoff_at:I.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Charge date"}),e.jsx(ye,{type:"datetime-local",value:i.charge_at,onChange:I=>l({...i,charge_at:I.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Enrollment closes"}),e.jsx(ye,{type:"datetime-local",value:i.enrollment_close_at,onChange:I=>l({...i,enrollment_close_at:I.target.value})})]})]})]}),e.jsx(Xn,{children:e.jsxs(B,{onClick:S,disabled:o||!i.name,children:[o&&e.jsx(rs,{className:"mr-1.5 h-4 w-4 animate-spin"})," Create"]})})]})]})]})]}),y?e.jsx(Ws,{className:"h-40 w-full rounded-xl"}):f.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsx(Ee,{className:"p-12 text-center text-sm text-muted-foreground",children:"No programs yet. Create your first cohort to get started."})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-2",children:f.map(I=>e.jsxs(B,{variant:(_==null?void 0:_.id)===I.id?"default":"outline",size:"sm",onClick:()=>n(I.id),children:[I.name,e.jsx(Ue,{variant:"secondary",className:"ml-2 capitalize",children:I.status})]},I.id))}),_&&e.jsxs(Fr,{defaultValue:"overview",children:[e.jsxs(Rr,{className:"flex w-full flex-wrap justify-start",children:[e.jsx(Zt,{value:"overview",children:"Overview"}),e.jsx(Zt,{value:"details",children:"Details & pricing"}),e.jsx(Zt,{value:"sessions",children:"Live sessions"}),e.jsx(Zt,{value:"videos",children:"On-demand videos"}),e.jsx(Zt,{value:"resources",children:"Resources"}),e.jsx(Zt,{value:"intake-form",children:"Intake form"}),e.jsx(Zt,{value:"discounts",children:"Discount codes"}),e.jsx(Zt,{value:"experience",children:"Enrollee experience"}),e.jsx(Zt,{value:"interest",children:"Interest list"}),e.jsxs(Zt,{value:"enrollments",children:["Enrollments (",v.length,")"]}),e.jsxs(Zt,{value:"intake",children:["Intake (",j.length,")"]}),e.jsx(Zt,{value:"audit",children:"Audit"})]}),e.jsxs(is,{value:"overview",className:"mt-6 space-y-4",children:[e.jsxs("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Seats filled"}),e.jsxs("p",{className:"mt-1 text-2xl font-bold",children:[v.filter(I=>["reserved","scheduled_for_charge","paid","completed"].includes(I.status)).length,e.jsxs("span",{className:"text-base font-normal text-muted-foreground",children:[" / ",_.capacity]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Paid"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:v.filter(I=>I.status==="paid").length})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Failed payments"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:v.filter(I=>I.status==="payment_failed").length})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5",children:[e.jsx("p",{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Projected revenue (one-time)"}),e.jsx("p",{className:"mt-1 text-2xl font-bold",children:Su(v.filter(I=>["scheduled_for_charge","paid","completed"].includes(I.status)).reduce((I,F)=>I+(F.amount_cents||0),0),_.currency)})]})})]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-5 p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Publish this program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Published programs appear on the member Programs page."})]}),e.jsx(jn,{checked:_.status==="published",onCheckedChange:I=>A({status:I?"published":"draft"})})]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-4 border-t border-border/60 pt-5",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Feature it"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pins the program to the top."})]}),e.jsx(jn,{checked:_.is_featured,onCheckedChange:I=>A({is_featured:I})})]}),e.jsxs("div",{className:"grid gap-4 border-t border-border/60 pt-5 sm:grid-cols-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"One-time price"}),e.jsx("p",{className:"font-medium",children:Su(_.price_cents,_.currency)})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Kickoff"}),e.jsx("p",{className:"font-medium",children:Ul(_.kickoff_at)||"Not set"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Charge date"}),e.jsx("p",{className:"font-medium",children:Ul(_.charge_at)||"Not set"})]})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Edit pricing, seats, description, dates and images in the"," ",e.jsx("strong",{children:"Details"})," tab."]})]})})]}),e.jsx(is,{value:"details",className:"mt-6",children:e.jsx(hps,{program:_,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(is,{value:"sessions",className:"mt-6",children:e.jsx(_ps,{programId:_.id})}),e.jsx(is,{value:"videos",className:"mt-6",children:e.jsx(wps,{programId:_.id})}),e.jsx(is,{value:"resources",className:"mt-6",children:e.jsx(jps,{programId:_.id})}),e.jsx(is,{value:"discounts",className:"mt-6",children:e.jsx(pps,{program:_})}),e.jsx(is,{value:"intake-form",className:"mt-6",children:e.jsx(yps,{program:_,onSaved:()=>s.invalidateQueries({queryKey:["admin-programs"]})})}),e.jsx(is,{value:"experience",className:"mt-6",children:e.jsx(fps,{program:_})}),e.jsx(is,{value:"interest",className:"mt-6",children:e.jsx(Nps,{programId:_.id})}),e.jsx(is,{value:"enrollments",className:"mt-6",children:e.jsx(fe,{children:e.jsx(Ee,{className:"overflow-x-auto p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Charge date"}),e.jsx(Tt,{children:"Amount"}),e.jsx(Tt,{children:"Access"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsxs(da,{children:[v.length===0&&e.jsx(Hs,{children:e.jsxs(ht,{colSpan:6,className:"py-10 text-center text-sm text-muted-foreground",children:[e.jsx(An,{className:"mx-auto mb-2 h-5 w-5"}),"No enrollments yet"]})}),v.map(I=>{var F,z;return e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("button",{type:"button",className:"text-left hover:underline",onClick:()=>p(I),children:[e.jsx("p",{className:"font-medium",children:((F=I.profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(z=I.profile)==null?void 0:z.email})]})}),e.jsxs(ht,{children:[e.jsx(Ue,{variant:D(I.status),className:"capitalize",children:String(I.status).replace(/_/g," ")}),I.last_payment_error&&e.jsx("p",{className:"mt-1 max-w-[200px] truncate text-xs text-destructive",children:I.last_payment_error})]}),e.jsx(ht,{className:"text-sm",children:Ul(I.charge_scheduled_at)||"—"}),e.jsx(ht,{className:"text-sm",children:Su(I.amount_cents,I.currency)}),e.jsx(ht,{children:e.jsx(jn,{checked:I.access_override,onCheckedChange:H=>E(I.id,{access_override:H})})}),e.jsxs(ht,{className:"space-x-2 text-right",children:[["scheduled_for_charge","payment_failed"].includes(I.status)&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>O(I.id),disabled:d,children:[e.jsx(Ei,{className:"mr-1.5 h-3.5 w-3.5"})," Charge now"]}),!["canceled","refunded"].includes(I.status)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>E(I.id,{status:"canceled",canceled_at:new Date().toISOString()}),children:"Cancel"})]})]},I.id)})]})]})})})}),e.jsxs(is,{value:"intake",className:"mt-6 space-y-3",children:[j.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No intake responses yet."}),j.map(I=>e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-2 p-5 text-sm",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("p",{className:"font-semibold",children:I.full_name||I.email||"Member"}),I.instagram_handle&&e.jsx(Ue,{variant:"outline",children:I.instagram_handle}),I.city&&e.jsx("span",{className:"text-xs text-muted-foreground",children:I.city})]}),I.primary_goal&&e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Goal: "}),I.primary_goal]}),e.jsxs("div",{className:"flex flex-wrap gap-x-5 gap-y-1 text-xs text-muted-foreground",children:[I.years_experience&&e.jsxs("span",{children:["Experience: ",I.years_experience]}),I.video_comfort&&e.jsxs("span",{children:["On camera: ",I.video_comfort]}),I.posting_frequency&&e.jsxs("span",{children:["Posts: ",I.posting_frequency]})]})]})},I.id))]}),e.jsx(is,{value:"audit",className:"mt-6",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"space-y-2 p-5 text-sm",children:[w.length===0&&e.jsx("p",{className:"text-muted-foreground",children:"No activity yet."}),w.map(I=>e.jsxs("div",{className:"flex flex-wrap items-center gap-2 border-b border-border/40 py-2 last:border-0",children:[e.jsx(Ue,{variant:"outline",className:"capitalize",children:String(I.action).replace(/_/g," ")}),e.jsx("span",{className:"text-muted-foreground",children:I.actor_label||"system"}),e.jsx("span",{className:"ml-auto text-xs text-muted-foreground",children:Ul(I.created_at,!0)})]},I.id))]})})})]}),_&&e.jsx(mps,{program:_,enrollment:h,open:!!h,onOpenChange:I=>!I&&p(null),onUpdated:()=>s.invalidateQueries({queryKey:["admin-program-enrollments"]})})]})]})})},Sps=()=>{const{user:s}=vs(),[t,n]=N.useState(""),[r,a]=N.useState("all"),{data:i=[]}=dt({queryKey:["academy-categories"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(f)throw f;return p}}),{data:l=[],isLoading:o}=dt({queryKey:["academy-videos"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("is_published",!0).order("publish_date",{ascending:!1});if(f)throw f;const{data:y,error:_}=await q.from("academy_resources").select("*").order("sort_order");if(_)throw _;return p.map(j=>({...j,resources:(y==null?void 0:y.filter(w=>w.video_id===j.id))||[]}))}}),{data:c=[]}=dt({queryKey:["academy-video-likes"],queryFn:async()=>{const{data:p,error:f}=await q.from("academy_video_likes").select("video_id, user_id");if(f)throw f;return p}}),d=l.filter(p=>{var _;const f=t===""||p.title.toLowerCase().includes(t.toLowerCase())||((_=p.description)==null?void 0:_.toLowerCase().includes(t.toLowerCase())),y=r==="all"||p.category_id===r;return f&&y}),u=p=>c.filter(f=>f.video_id===p).length,h=p=>c.some(f=>f.video_id===p&&f.user_id===(s==null?void 0:s.id));return e.jsx(Cs,{title:"Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Academy"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"On-demand training videos and resources"})]}),e.jsx("div",{className:"flex flex-col sm:flex-row gap-4",children:e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos...",value:t,onChange:p=>n(p.target.value),className:"pl-10"})]})}),e.jsx(Fr,{value:r,onValueChange:a,children:e.jsxs(Rr,{className:"w-full justify-start flex-wrap h-auto gap-2 bg-transparent p-0",children:[e.jsx(Zt,{value:"all",className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:"All Videos"}),i.map(p=>e.jsx(Zt,{value:p.id,className:"data-[state=active]:bg-primary data-[state=active]:text-primary-foreground",children:p.name},p.id))]})}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):d.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No videos found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:t?"Try adjusting your search terms":"Check back soon for new content"})]})}):e.jsx("div",{className:"grid gap-6 sm:grid-cols-2 lg:grid-cols-3",children:d.map(p=>e.jsx(In,{to:`/academy/${p.id}`,children:e.jsxs(fe,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow group h-full",children:[e.jsxs("div",{className:"relative aspect-video bg-muted",children:[p.thumbnail_url?e.jsx("img",{src:p.thumbnail_url,alt:p.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(fr,{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(El,{className:"h-8 w-8 text-primary-foreground ml-1"})})}),p.duration&&e.jsxs("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-2 py-1 rounded flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),p.duration]})]}),e.jsxs(It,{className:"pb-2",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsx(Rt,{className:"text-lg line-clamp-2",children:p.title})}),p.category&&e.jsx(Ue,{variant:"secondary",className:"w-fit",children:p.category.name})]}),e.jsxs(Ee,{className:"pt-0",children:[p.description&&e.jsx(Vn,{className:"line-clamp-2",children:p.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($m,{className:`h-4 w-4 ${h(p.id)?"fill-primary text-primary":""}`}),u(p.id)]}),p.resources&&p.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-4 w-4"}),p.resources.length]})]})]})]})},p.id))})]})})};function Uxt({resourceType:s,resourceId:t}){const{data:n=[]}=dt({queryKey:["linked-templates",s,t],queryFn:async()=>{if(s==="academy_video"){const{data:r,error:a}=await q.from("academy_video_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("video_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}else{const{data:r,error:a}=await q.from("resource_kit_templates").select("template_id, canva_templates:template_id(id, name, preview_image_url)").eq("kit_id",t);if(a)throw a;return(r||[]).map(i=>i.canva_templates).filter(Boolean)}},enabled:!!t});return n.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-sm",children:[e.jsx(pl,{className:"h-4 w-4"}),"Related Templates"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(r=>e.jsx(In,{to:`/templates/${r.id}`,children:e.jsxs(Ue,{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(pl,{className:"h-3 w-3"}),r.name]})},r.id))})]})}const Cps=(s,t)=>{if(t==="bunny_stream"){let n=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return n.includes("?")||(n+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),n}if(t==="youtube"){const n=/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/,r=s.match(n);if(r)return`https://www.youtube.com/embed/${r[1]}`}if(t==="vimeo"){const n=/vimeo\.com\/(?:video\/)?(\d+)/,r=s.match(n);if(r)return`https://player.vimeo.com/video/${r[1]}`}if(t==="loom"){const n=/loom\.com\/share\/([a-zA-Z0-9]+)/,r=s.match(n);if(r)return`https://www.loom.com/embed/${r[1]}`}return s},Tps=()=>{const{videoId:s}=bi();Ln();const{user:t,isAdmin:n}=vs(),{toast:r}=Fa(),a=Kt(),{trackEngagement:i}=UD(),[l,o]=N.useState(""),{data:c,isLoading:d}=dt({queryKey:["academy-video",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:E}=await q.from("academy_resources").select("*").eq("video_id",s).order("sort_order");return{...S,resources:E||[]}},enabled:!!s});N.useEffect(()=>{c&&i("academy_video",c.id,c.title,"view")},[c==null?void 0:c.id]);const{data:u=[]}=dt({queryKey:["academy-video-likes",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_video_likes").select("*").eq("video_id",s);if(A)throw A;return S},enabled:!!s}),{data:h=[]}=dt({queryKey:["academy-video-comments",s],queryFn:async()=>{const{data:S,error:A}=await q.from("academy_video_comments").select("*").eq("video_id",s).order("created_at",{ascending:!1});if(A)throw A;const E=[...new Set(S.map(I=>I.user_id))],{data:O}=await q.from("profiles").select("id, name").in("id",E),D=new Map((O==null?void 0:O.map(I=>[I.id,I.name]))||[]);return S.map(I=>({...I,user_name:D.get(I.user_id)||"Unknown User"}))},enabled:!!s}),p=yt({mutationFn:async S=>{const{error:A}=await q.from("academy_video_comments").insert({video_id:s,user_id:t.id,content:S});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),o(""),r({title:"Comment added!"})},onError:S=>{r({title:"Error adding comment",description:S.message,variant:"destructive"})}}),f=yt({mutationFn:async S=>{const{error:A}=await q.from("academy_video_comments").delete().eq("id",S);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-comments",s]}),r({title:"Comment deleted"})}}),y=yt({mutationFn:async()=>{const S=u.find(A=>A.user_id===(t==null?void 0:t.id));if(S){const{error:A}=await q.from("academy_video_likes").delete().eq("id",S.id);if(A)throw A}else{const{error:A}=await q.from("academy_video_likes").insert({video_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-video-likes",s]})}}),_=u.some(S=>S.user_id===(t==null?void 0:t.id)),v=S=>{switch(S==null?void 0:S.toLowerCase()){case"pdf":return"📄";case"pptx":case"ppt":return"📊";case"xlsx":case"xls":return"📈";case"docx":case"doc":return"📝";case"zip":return"📦";default:return"📁"}},j=S=>S.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),w=S=>{S.preventDefault(),!(!l.trim()||!t)&&p.mutate(l.trim())};return d?e.jsx(Cs,{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(Cs,{title:c.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(In,{to:"/academy",children:[e.jsx(qr,{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:Cps(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(fr,{className:"h-16 w-16 opacity-50"}),e.jsx(B,{variant:"secondary",asChild:!0,children:e.jsxs("a",{href:c.video_url,target:"_blank",rel:"noopener noreferrer",className:"gap-2",children:[e.jsx(tr,{className:"h-4 w-4"}),"Open Video"]})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.title}),c.category&&e.jsx(Ue,{variant:"secondary",children:c.category.name})]}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(In,{to:`/admin/academy?edit=${c.id}`,children:[e.jsx(ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(HD,{resourceType:"academy_video",resourceId:c.id,resourceTitle:c.title}),e.jsxs(B,{variant:_?"default":"outline",className:"gap-2 w-fit",onClick:()=>y.mutate(),disabled:!t||y.isPending,children:[e.jsx($m,{className:`h-4 w-4 ${_?"fill-current":""}`}),u.length," ",u.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.resources&&c.resources.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(br,{className:"h-4 w-4"}),"Resources"]}),e.jsx("div",{className:"grid gap-2",children:c.resources.map(S=>e.jsxs("a",{href:S.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors",children:[e.jsx("span",{className:"text-2xl",children:v(S.file_type)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:S.title}),e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:S.file_type})]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"})]},S.id))})]})}),e.jsx(Uxt,{resourceType:"academy_video",resourceId:c.id}),e.jsx(al,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Zl,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:w,className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Add a comment...",value:l,onChange:S=>o(S.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||p.isPending,children:e.jsx(lr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:h.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(S=>e.jsx(fe,{children:e.jsx(Ee,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Jr,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(ea,{className:"text-sm",children:j(S.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Uo(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(S.id),children:e.jsx(_n,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(Cs,{title:"Academy",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Video not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This video may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(In,{to:"/academy",children:"Back to Academy"})})]})})},wI="https://dashboard.relevelup.com",Eps=(s,t)=>{if(t==="bunny_stream"){let n=s.replace("iframe.mediadelivery.net","player.mediadelivery.net");return n.includes("?")||(n+="?autoplay=false&loop=false&muted=false&preload=true&responsive=true"),n}if(t==="youtube"){const n=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(n)return`https://www.youtube.com/embed/${n[1]}`}if(t==="vimeo"){const n=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);if(n)return`https://player.vimeo.com/video/${n[1]}`}if(t==="loom"){const n=s.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(n)return`https://www.loom.com/embed/${n[1]}`}return s},Aps=[{icon:jh,title:"100+ Training Videos",desc:"On-demand LevelUp Academy content covering lead gen, listings, buyer conversion, marketing, and more."},{icon:im,title:"Marketing Studio & Tools",desc:"AI-powered marketing tools, listing videos, landing pages, and social content — done for you."},{icon:An,title:"Coaching & Community",desc:"Live coaching sessions, private community, and a network of top-performing agents."},{icon:xo,title:"Business Scorecard",desc:"Track your deals, GCI, and pipeline in one dashboard built for real estate."}];function Mps(){var i;const{slug:s}=bi(),{data:t,isLoading:n,error:r}=dt({queryKey:["public-academy-video",s],queryFn:async()=>{if(!s)return null;const{data:l,error:o}=await q.from("academy_videos").select("id, title, description, video_url, video_type, thumbnail_url, duration, category:academy_categories(name)").eq("public_slug",s).eq("is_public",!0).maybeSingle();if(o)throw o;return l},enabled:!!s});N.useEffect(()=>{if(t&&s){q.rpc("increment_academy_public_view",{_slug:s}),document.title=`${t.title} | LevelUp Academy`;const l=(t.description||"").replace(/<[^>]+>/g,"").slice(0,155),o=document.querySelector('meta[name="description"]');if(o&&o.setAttribute("content",l||"Free training preview from LevelUp Academy."),t.thumbnail_url){let c=document.querySelector('meta[property="og:image"]');c||(c=document.createElement("meta"),c.setAttribute("property","og:image"),document.head.appendChild(c)),c.setAttribute("content",t.thumbnail_url)}}},[t,s]);const a=N.useMemo(()=>t?Eps(t.video_url,t.video_type):"",[t]);return n?e.jsx("div",{className:"min-h-screen bg-[#0d1b26] flex items-center justify-center",children:e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-[#5a9ea1] border-t-transparent"})}):r||!t?e.jsxs("div",{className:"min-h-screen bg-[#0d1b26] flex flex-col items-center justify-center text-center px-6",children:[e.jsx("div",{className:"text-[#e8ecf1] text-2xl font-semibold mb-2",children:"This preview isn't available"}),e.jsx("p",{className:"text-[#8ba1b3] mb-6",children:"The link may have expired or is no longer public."}),e.jsx("a",{href:wI,children:e.jsx(B,{className:"bg-[#406E71] hover:bg-[#4d8285] text-white",children:"Go to LevelUp"})})]}):e.jsxs("div",{className:"min-h-screen bg-[#0a1520] text-[#e8ecf1] overflow-x-hidden",children:[e.jsxs("div",{className:"pointer-events-none fixed inset-0 z-0",children:[e.jsx("div",{className:"absolute -top-40 -left-40 w-[600px] h-[600px] rounded-full bg-[#406E71]/20 blur-3xl"}),e.jsx("div",{className:"absolute top-1/2 -right-40 w-[500px] h-[500px] rounded-full bg-[#2a4c64]/30 blur-3xl"}),e.jsx("div",{className:"absolute bottom-0 left-1/3 w-[400px] h-[400px] rounded-full bg-[#406E71]/10 blur-3xl"})]}),e.jsx("header",{className:"relative z-10 border-b border-white/5 backdrop-blur-sm bg-[#0a1520]/70",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-5 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-9 h-9 rounded-lg bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(un,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-bold text-lg tracking-tight",children:"LevelUp"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-[#5a9ea1] -mt-1",children:"Academy"})]})]}),e.jsx("a",{href:wI,children:e.jsx(B,{variant:"ghost",className:"text-[#e8ecf1] hover:bg-white/5 hover:text-white",children:"Sign In"})})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pt-12 pb-16",children:[e.jsxs("div",{className:"text-center mb-8 space-y-4",children:[e.jsxs(Ue,{className:"bg-[#406E71]/20 text-[#7ec0c3] border-[#406E71]/40 hover:bg-[#406E71]/30",children:[e.jsx(jh,{className:"w-3 h-3 mr-1.5"}),"Free Training Preview"]}),((i=t.category)==null?void 0:i.name)&&e.jsx("div",{className:"text-xs uppercase tracking-[0.2em] text-[#5a9ea1]",children:t.category.name}),e.jsx("h1",{className:"text-3xl md:text-5xl lg:text-6xl font-bold tracking-tight leading-[1.1] max-w-4xl mx-auto",children:t.title}),t.duration&&e.jsx("div",{className:"text-[#8ba1b3] text-sm",children:t.duration})]}),e.jsxs("div",{className:"relative rounded-2xl overflow-hidden shadow-2xl ring-1 ring-white/10 bg-black",children:[e.jsx("div",{className:"absolute -inset-px rounded-2xl bg-gradient-to-r from-[#406E71]/50 via-transparent to-[#2a4c64]/50 blur-xl -z-10"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:a,title:t.title,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}),t.description&&e.jsx("div",{className:"mt-10 max-w-3xl mx-auto text-[#c5d3de] text-lg leading-relaxed prose prose-invert prose-headings:text-white prose-a:text-[#7ec0c3]",dangerouslySetInnerHTML:{__html:t.description}})]}),e.jsx("section",{className:"relative z-10 max-w-4xl mx-auto px-6 pb-16",children:e.jsxs("div",{className:"relative rounded-3xl overflow-hidden p-10 md:p-14 text-center bg-gradient-to-br from-[#2a4c64] via-[#1d3a4f] to-[#0d1b26] ring-1 ring-white/10",children:[e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-[#406E71]/30 rounded-full blur-3xl"}),e.jsxs("div",{className:"relative",children:[e.jsx(tx,{className:"w-10 h-10 mx-auto mb-4 text-[#7ec0c3]"}),e.jsxs("h2",{className:"text-3xl md:text-4xl font-bold mb-3",children:["This is just ",e.jsx("span",{className:"text-[#7ec0c3]",children:"one"})," of hundreds."]}),e.jsx("p",{className:"text-[#c5d3de] text-lg mb-8 max-w-2xl mx-auto",children:"LevelUp members get unlimited access to the full Academy, AI marketing tools, coaching, and everything you need to grow your real estate business."}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-center justify-center gap-3",children:[e.jsx("a",{href:wI,className:"w-full sm:w-auto",children:e.jsxs(B,{size:"lg",className:"w-full sm:w-auto bg-[#f5f0e0] hover:bg-white text-[#0d1b26] font-semibold text-base h-12 px-8 shadow-xl",children:["Start Free Trial",e.jsx(Oa,{className:"w-4 h-4 ml-2"})]})}),e.jsx("a",{href:wI,className:"w-full sm:w-auto",children:e.jsx(B,{size:"lg",variant:"outline",className:"w-full sm:w-auto bg-transparent border-white/20 text-white hover:bg-white/10 hover:text-white h-12 px-8",children:"Join LevelUp"})})]}),e.jsx("p",{className:"text-xs text-[#7a8a99] mt-5",children:"No credit card required to preview the platform"})]})]})}),e.jsxs("section",{className:"relative z-10 max-w-6xl mx-auto px-6 pb-20",children:[e.jsxs("div",{className:"text-center mb-10",children:[e.jsx("div",{className:"text-xs uppercase tracking-[0.25em] text-[#5a9ea1] mb-2",children:"What's inside"}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold",children:"Built for agents who want more"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:Aps.map(l=>e.jsx("div",{className:"group relative rounded-2xl p-6 bg-white/[0.03] hover:bg-white/[0.06] ring-1 ring-white/5 hover:ring-[#406E71]/40 transition-all",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"shrink-0 w-11 h-11 rounded-xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] flex items-center justify-center",children:e.jsx(l.icon,{className:"w-5 h-5 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-white mb-1",children:l.title}),e.jsx("div",{className:"text-[#8ba1b3] text-sm leading-relaxed",children:l.desc})]})]})},l.title))})]}),e.jsx("section",{className:"relative z-10 max-w-4xl mx-auto px-6 pb-24",children:e.jsxs("div",{className:"rounded-2xl border border-white/10 p-8 md:p-10 bg-[#0d1b26]/60 backdrop-blur",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-8 gap-y-3 text-sm text-[#c5d3de] mb-6",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"w-4 h-4 text-[#7ec0c3]"})," Trusted by top producers"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"w-4 h-4 text-[#7ec0c3]"})," New training weekly"]}),e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"w-4 h-4 text-[#7ec0c3]"})," Cancel anytime"]})]}),e.jsx("div",{className:"text-center",children:e.jsx("a",{href:wI,children:e.jsxs(B,{size:"lg",className:"bg-[#406E71] hover:bg-[#4d8285] text-white h-12 px-10 shadow-lg",children:["Get Started at LevelUp",e.jsx(Oa,{className:"w-4 h-4 ml-2"})]})})})]})}),e.jsxs("footer",{className:"relative z-10 border-t border-white/5 py-6 text-center text-xs text-[#5a6a7a]",children:["© ",new Date().getFullYear()," LevelUp · ",e.jsx("a",{href:wI,className:"hover:text-[#7ec0c3]",children:"dashboard.relevelup.com"})]})]})}function Ips(){const s=Ln(),[t,n]=N.useState(""),{data:r,isLoading:a}=dt({queryKey:["resource-kits-published"],queryFn:async()=>{const{data:f,error:y}=await q.from("resource_kits").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(y)throw y;return f}}),{data:i}=dt({queryKey:["resource-kit-files-all"],queryFn:async()=>{const{data:f,error:y}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(y)throw y;return f}}),{data:l}=dt({queryKey:["resource-kit-likes-all"],queryFn:async()=>{const{data:f,error:y}=await q.from("resource_kit_likes").select("kit_id");if(y)throw y;return f}}),{data:o}=dt({queryKey:["resource-kit-comments-all"],queryFn:async()=>{const{data:f,error:y}=await q.from("resource_kit_comments").select("kit_id");if(y)throw y;return f}}),c=r==null?void 0:r.filter(f=>{var y;return f.name.toLowerCase().includes(t.toLowerCase())||((y=f.description)==null?void 0:y.toLowerCase().includes(t.toLowerCase()))}),d=f=>(i==null?void 0:i.filter(y=>y.kit_id===f))||[],u=f=>(l==null?void 0:l.filter(y=>y.kit_id===f).length)||0,h=f=>(o==null?void 0:o.filter(y=>y.kit_id===f).length)||0,p=f=>{s(`/toolbox/${f}`)};return e.jsx(Cs,{title:"Toolbox",description:"Download resource kits and tools to help grow your business",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Toolbox"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Download resource kits and tools to help grow your business"})]}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search resource kits...",value:t,onChange:f=>n(f.target.value),className:"pl-10"})]}),!a&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(c==null?void 0:c.length)||0," resource kit",(c==null?void 0:c.length)!==1?"s":""," available"]}),a?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((f,y)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsx(Ws,{className:"h-4 w-2/3"})]})},y))}):(c==null?void 0:c.length)===0?e.jsxs(fe,{className:"p-12 text-center",children:[e.jsx(Ec,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resource kits found"}),e.jsx("p",{className:"text-muted-foreground",children:t?"Try adjusting your search terms":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:c==null?void 0:c.map(f=>{const y=d(f.id).length,_=u(f.id),v=h(f.id);return e.jsxs(fe,{className:"group overflow-hidden cursor-pointer hover:shadow-lg transition-all duration-200",onClick:()=>p(f.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:f.featured_image_url?e.jsx("img",{src:f.featured_image_url,alt:f.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Ec,{className:"h-16 w-16 text-muted-foreground"})})}),e.jsxs(Ee,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:f.name}),f.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:qz(f.description)}),e.jsxs("div",{className:"flex items-center justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-4 w-4"}),y," file",y!==1?"s":""]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($m,{className:"h-3.5 w-3.5"}),_]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zl,{className:"h-3.5 w-3.5"}),v]})]})]})]})]},f.id)})})]})})}const Pps=()=>{const{kitId:s}=bi(),{user:t,isAdmin:n}=vs(),{toast:r}=Fa(),a=Kt(),{trackEngagement:i}=UD(),[l,o]=N.useState(""),{data:c,isLoading:d}=dt({queryKey:["resource-kit-detail",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kits").select("*").eq("id",s).eq("is_published",!0).single();if(A)throw A;const{data:E}=await q.from("resource_kit_files").select("*").eq("kit_id",s).order("sort_order"),{data:O}=await q.from("resource_kit_links").select("*").eq("kit_id",s).order("sort_order");return{...S,files:E||[],links:O||[]}},enabled:!!s});N.useEffect(()=>{c&&i("toolbox",c.id,c.name,"view")},[c==null?void 0:c.id]);const{data:u=[]}=dt({queryKey:["resource-kit-likes",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kit_likes").select("*").eq("kit_id",s);if(A)throw A;return S},enabled:!!s}),{data:h=[]}=dt({queryKey:["resource-kit-comments",s],queryFn:async()=>{const{data:S,error:A}=await q.from("resource_kit_comments").select("*").eq("kit_id",s).order("created_at",{ascending:!1});if(A)throw A;const E=[...new Set(S.map(I=>I.user_id))],{data:O}=await q.from("profiles").select("id, name").in("id",E),D=new Map((O==null?void 0:O.map(I=>[I.id,I.name]))||[]);return S.map(I=>({...I,user_name:D.get(I.user_id)||"Unknown User"}))},enabled:!!s}),p=yt({mutationFn:async S=>{const{error:A}=await q.from("resource_kit_comments").insert({kit_id:s,user_id:t.id,content:S});if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),o(""),r({title:"Comment added!"})},onError:S=>{r({title:"Error adding comment",description:S.message,variant:"destructive"})}}),f=yt({mutationFn:async S=>{const{error:A}=await q.from("resource_kit_comments").delete().eq("id",S);if(A)throw A},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-comments",s]}),r({title:"Comment deleted"})}}),y=yt({mutationFn:async()=>{const S=u.find(A=>A.user_id===(t==null?void 0:t.id));if(S){const{error:A}=await q.from("resource_kit_likes").delete().eq("id",S.id);if(A)throw A}else{const{error:A}=await q.from("resource_kit_likes").insert({kit_id:s,user_id:t.id});if(A)throw A}},onSuccess:()=>{a.invalidateQueries({queryKey:["resource-kit-likes",s]})}}),_=u.some(S=>S.user_id===(t==null?void 0:t.id)),v=S=>S.split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),j=S=>S?S<1024?S+" B":S<1024*1024?(S/1024).toFixed(1)+" KB":(S/(1024*1024)).toFixed(1)+" MB":"",w=S=>{S.preventDefault(),!(!l.trim()||!t)&&p.mutate(l.trim())};return d?e.jsx(Cs,{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(Cs,{title:c.name,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(In,{to:"/toolbox",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back to Toolbox"]})}),c.featured_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.featured_image_url,alt:c.name,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-4",children:[e.jsx("div",{className:"space-y-2",children:e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:c.name})}),e.jsxs("div",{className:"flex items-center gap-2",children:[n&&e.jsx(B,{variant:"outline",className:"gap-2 rounded-full",asChild:!0,children:e.jsxs(In,{to:`/admin/toolbox?edit=${c.id}`,children:[e.jsx(ya,{className:"h-4 w-4"}),e.jsx("span",{children:"Edit"})]})}),e.jsx(HD,{resourceType:"resource_kit",resourceId:c.id,resourceTitle:c.name,size:"default",className:"rounded-full"}),e.jsxs(B,{variant:_?"default":"outline",className:"gap-2 rounded-full",onClick:()=>y.mutate(),disabled:!t||y.isPending,children:[e.jsx($m,{className:`h-4 w-4 ${_?"fill-current":""}`}),u.length," ",u.length===1?"Like":"Likes"]})]})]}),c.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:c.description}})]}),c.files&&c.files.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(br,{className:"h-4 w-4"}),"Included Resources (",c.files.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.files.map(S=>e.jsxs("a",{href:S.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_pdf"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(br,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:S.name}),S.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:j(S.file_size)})]})]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},S.id))})]})}),c.links&&c.links.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(tr,{className:"h-4 w-4"}),"Canva Templates (",c.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:c.links.map(S=>e.jsxs("a",{href:S.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("toolbox",c.id,c.name,"click_canva"),className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-purple-500/10",children:e.jsx(tr,{className:"h-4 w-4 text-purple-600"})}),e.jsx("div",{className:"font-medium text-sm",children:S.title})]}),e.jsx("span",{className:"text-xs text-muted-foreground group-hover:text-primary transition-colors",children:"Open in Canva"})]},S.id))})]})}),e.jsx(Uxt,{resourceType:"resource_kit",resourceId:c.id}),e.jsx(al,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Zl,{className:"h-5 w-5"}),"Comments (",h.length,")"]}),t?e.jsxs("form",{onSubmit:w,className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Add a comment...",value:l,onChange:S=>o(S.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!l.trim()||p.isPending,children:e.jsx(lr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:h.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):h.map(S=>e.jsx(fe,{children:e.jsx(Ee,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Jr,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(ea,{className:"text-sm",children:v(S.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:S.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Uo(new Date(S.created_at),{addSuffix:!0})}),S.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>f.mutate(S.id),children:e.jsx(_n,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:S.content})]})]})})},S.id))})]})]})}):e.jsx(Cs,{title:"Toolbox",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ec,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource kit not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource kit may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(In,{to:"/toolbox",children:"Back to Toolbox"})})]})})},Lps=()=>{const s=Ln(),[t,n]=N.useState(""),[r,a]=N.useState("grid"),{data:i=[],isLoading:l}=dt({queryKey:["social-swag"],queryFn:async()=>{const{data:d,error:u}=await q.from("social_swag").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(u)throw u;const{data:h,error:p}=await q.from("social_swag_links").select("*").order("sort_order");if(p)throw p;const{data:f}=await q.from("social_swag_likes").select("swag_id"),{data:y}=await q.from("social_swag_comments").select("swag_id"),_=new Map;f==null||f.forEach(w=>{_.set(w.swag_id,(_.get(w.swag_id)||0)+1)});const v=new Map;return y==null||y.forEach(w=>{v.set(w.swag_id,(v.get(w.swag_id)||0)+1)}),(d||[]).map(w=>({...w,links:(h||[]).filter(S=>S.swag_id===w.id)||[],likesCount:_.get(w.id)||0,commentsCount:v.get(w.id)||0}))}}),o=i.filter(d=>{var h;return d.title.toLowerCase().includes(t.toLowerCase())||((h=d.description)==null?void 0:h.toLowerCase().includes(t.toLowerCase()))}),c=d=>{s(`/social-swag/${d}`)};return e.jsx(Cs,{title:"Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Social Swag"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Browse our collection of social media content and graphics"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search social swag...",value:t,onChange:d=>n(d.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(ff,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Sp,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," item",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(8)].map((d,u)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[4/3] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"})]})},u))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No items match your search":"No social swag available yet"}),t&&e.jsx(B,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(d=>e.jsxs(fe,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${r==="list"?"flex flex-row":""}`,onClick:()=>c(d.id),children:[e.jsxs("div",{className:`relative overflow-hidden bg-muted ${r==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:[d.preview_image_url?e.jsx("img",{src:d.preview_image_url,alt:d.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"}),d.links.length>1&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ue,{variant:"secondary",className:"gap-1 bg-background/90 backdrop-blur-sm",children:[e.jsx(Yo,{className:"h-3 w-3"}),d.links.length]})})]}),e.jsxs(Ee,{className:`p-4 flex flex-col ${r==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:d.title}),d.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:d.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground mb-3",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($m,{className:"h-3.5 w-3.5"}),d.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zl,{className:"h-3.5 w-3.5"}),d.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:u=>{u.stopPropagation(),c(d.id)},children:[e.jsx(tr,{className:"h-4 w-4"}),"View Details"]})]})]},d.id))})]})})};var ro=function(){return ro=Object.assign||function(t){for(var n,r=1,a=arguments.length;r1&&(c||!d),h=t>1&&(d||!c),p=function(){r&&i(r)},f=function(){a&&i(a)};return e.jsx(mfs,{displayMonth:s.displayMonth,hideNext:u,hidePrevious:h,nextMonth:a,previousMonth:r,onPreviousClick:p,onNextClick:f})}function pfs(s){var t,n=wd(),r=n.classNames,a=n.disableNavigation,i=n.styles,l=n.captionLayout,o=n.components,c=(t=o==null?void 0:o.CaptionLabel)!==null&&t!==void 0?t:Hxt,d;return a?d=e.jsx(c,{id:s.id,displayMonth:s.displayMonth}):l==="dropdown"?d=e.jsx(bVe,{displayMonth:s.displayMonth,id:s.id}):l==="dropdown-buttons"?d=e.jsxs(e.Fragment,{children:[e.jsx(bVe,{displayMonth:s.displayMonth,displayIndex:s.displayIndex,id:s.id}),e.jsx(_Ve,{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(_Ve,{displayMonth:s.displayMonth,id:s.id})]}),e.jsx("div",{className:r.caption,style:i.caption,children:d})}function ffs(s){var t=wd(),n=t.footer,r=t.styles,a=t.classNames.tfoot;return n?e.jsx("tfoot",{className:a,style:r.tfoot,children:e.jsx("tr",{children:e.jsx("td",{colSpan:8,children:n})})}):e.jsx(e.Fragment,{})}function xfs(s,t,n){for(var r=n?cN(new Date):Vm(new Date,{locale:s,weekStartsOn:t}),a=[],i=0;i<7;i++){var l=Bl(r,i);a.push(l)}return a}function gfs(){var s=wd(),t=s.classNames,n=s.styles,r=s.showWeekNumber,a=s.locale,i=s.weekStartsOn,l=s.ISOWeek,o=s.formatters.formatWeekdayName,c=s.labels.labelWeekday,d=xfs(a,i,l);return e.jsxs("tr",{style:n.head_row,className:t.head_row,children:[r&&e.jsx("td",{style:n.head_cell,className:t.head_cell}),d.map(function(u,h){return e.jsx("th",{scope:"col",className:t.head_cell,style:n.head_cell,"aria-label":c(u,{locale:a}),children:o(u,{locale:a})},h)})]})}function yfs(){var s,t=wd(),n=t.classNames,r=t.styles,a=t.components,i=(s=a==null?void 0:a.HeadRow)!==null&&s!==void 0?s:gfs;return e.jsx("thead",{style:r.head,className:n.head,children:e.jsx(i,{})})}function vfs(s){var t=wd(),n=t.locale,r=t.formatters.formatDay;return e.jsx(e.Fragment,{children:r(s.date,{locale:n})})}var J6e=N.createContext(void 0);function bfs(s){if(!dU(s.initialProps)){var t={selected:void 0,modifiers:{disabled:[]}};return e.jsx(J6e.Provider,{value:t,children:s.children})}return e.jsx(_fs,{initialProps:s.initialProps,children:s.children})}function _fs(s){var t=s.initialProps,n=s.children,r=t.selected,a=t.min,i=t.max,l=function(d,u,h){var p,f;(p=t.onDayClick)===null||p===void 0||p.call(t,d,u,h);var y=!!(u.selected&&a&&(r==null?void 0:r.length)===a);if(!y){var _=!!(!u.selected&&i&&(r==null?void 0:r.length)===i);if(!_){var v=r?qxt([],r):[];if(u.selected){var j=v.findIndex(function(w){return ql(d,w)});v.splice(j,1)}else v.push(d);(f=t.onSelect)===null||f===void 0||f.call(t,v,d,u,h)}}},o={disabled:[]};r&&o.disabled.push(function(d){var u=i&&r.length>i-1,h=r.some(function(p){return ql(p,d)});return!!(u&&!h)});var c={selected:r,onDayClick:l,modifiers:o};return e.jsx(J6e.Provider,{value:c,children:n})}function eIe(){var s=N.useContext(J6e);if(!s)throw new Error("useSelectMultiple must be used within a SelectMultipleProvider");return s}function wfs(s,t){var n=t||{},r=n.from,a=n.to;return r&&a?ql(a,s)&&ql(r,s)?void 0:ql(a,s)?{from:a,to:void 0}:ql(r,s)?void 0:Ov(r,s)?{from:s,to:a}:{from:r,to:s}:a?Ov(s,a)?{from:a,to:s}:{from:s,to:a}:r?yb(s,r)?{from:s,to:r}:{from:r,to:s}:{from:s,to:void 0}}var tIe=N.createContext(void 0);function jfs(s){if(!uU(s.initialProps)){var t={selected:void 0,modifiers:{range_start:[],range_end:[],range_middle:[],disabled:[]}};return e.jsx(tIe.Provider,{value:t,children:s.children})}return e.jsx(Nfs,{initialProps:s.initialProps,children:s.children})}function Nfs(s){var t=s.initialProps,n=s.children,r=t.selected,a=r||{},i=a.from,l=a.to,o=t.min,c=t.max,d=function(f,y,_){var v,j;(v=t.onDayClick)===null||v===void 0||v.call(t,f,y,_);var w=wfs(f,r);(j=t.onSelect)===null||j===void 0||j.call(t,w,f,y,_)},u={range_start:[],range_end:[],range_middle:[],disabled:[]};if(i?(u.range_start=[i],l?(u.range_end=[l],ql(i,l)||(u.range_middle=[{after:i,before:l}])):u.range_end=[i]):l&&(u.range_start=[l],u.range_end=[l]),o&&(i&&!l&&u.disabled.push({after:R9(i,o-1),before:Bl(i,o-1)}),i&&l&&u.disabled.push({after:i,before:Bl(i,o-1)}),!i&&l&&u.disabled.push({after:R9(l,o-1),before:Bl(l,o-1)})),c){if(i&&!l&&(u.disabled.push({before:Bl(i,-c+1)}),u.disabled.push({after:Bl(i,c-1)})),i&&l){var h=Vx(l,i)+1,p=c-h;u.disabled.push({before:R9(i,p)}),u.disabled.push({after:Bl(l,p)})}!i&&l&&(u.disabled.push({before:Bl(l,-c+1)}),u.disabled.push({after:Bl(l,c-1)}))}return e.jsx(tIe.Provider,{value:{selected:r,onDayClick:d,modifiers:u},children:n})}function sIe(){var s=N.useContext(tIe);if(!s)throw new Error("useSelectRange must be used within a SelectRangeProvider");return s}function Bme(s){return Array.isArray(s)?qxt([],s):s!==void 0?[s]:[]}function kfs(s){var t={};return Object.entries(s).forEach(function(n){var r=n[0],a=n[1];t[r]=Bme(a)}),t}var Sb;(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"})(Sb||(Sb={}));var Sfs=Sb.Selected,r2=Sb.Disabled,Cfs=Sb.Hidden,Tfs=Sb.Today,n2e=Sb.RangeEnd,r2e=Sb.RangeMiddle,a2e=Sb.RangeStart,Efs=Sb.Outside;function Afs(s,t,n){var r,a=(r={},r[Sfs]=Bme(s.selected),r[r2]=Bme(s.disabled),r[Cfs]=Bme(s.hidden),r[Tfs]=[s.today],r[n2e]=[],r[r2e]=[],r[a2e]=[],r[Efs]=[],r);return s.fromDate&&a[r2].push({before:s.fromDate}),s.toDate&&a[r2].push({after:s.toDate}),dU(s)?a[r2]=a[r2].concat(t.modifiers[r2]):uU(s)&&(a[r2]=a[r2].concat(n.modifiers[r2]),a[a2e]=n.modifiers[a2e],a[r2e]=n.modifiers[r2e],a[n2e]=n.modifiers[n2e]),a}var Kxt=N.createContext(void 0);function Mfs(s){var t=wd(),n=eIe(),r=sIe(),a=Afs(t,n,r),i=kfs(t.modifiers),l=ro(ro({},a),i);return e.jsx(Kxt.Provider,{value:l,children:s.children})}function Yxt(){var s=N.useContext(Kxt);if(!s)throw new Error("useModifiers must be used within a ModifiersProvider");return s}function Ifs(s){return!!(s&&typeof s=="object"&&"before"in s&&"after"in s)}function Pfs(s){return!!(s&&typeof s=="object"&&"from"in s)}function Lfs(s){return!!(s&&typeof s=="object"&&"after"in s)}function Dfs(s){return!!(s&&typeof s=="object"&&"before"in s)}function Rfs(s){return!!(s&&typeof s=="object"&&"dayOfWeek"in s)}function Ofs(s,t){var n,r=t.from,a=t.to;if(r&&a){var i=Vx(a,r)<0;i&&(n=[a,r],r=n[0],a=n[1]);var l=Vx(s,r)>=0&&Vx(a,s)>=0;return l}return a?ql(a,s):r?ql(r,s):!1}function Ffs(s){return OAe(s)}function zfs(s){return Array.isArray(s)&&s.every(OAe)}function Bfs(s,t){return t.some(function(n){if(typeof n=="boolean")return n;if(Ffs(n))return ql(s,n);if(zfs(n))return n.includes(s);if(Pfs(n))return Ofs(s,n);if(Rfs(n))return n.dayOfWeek.includes(s.getDay());if(Ifs(n)){var r=Vx(n.before,s),a=Vx(n.after,s),i=r>0,l=a<0,o=Ov(n.before,n.after);return o?l&&i:i||l}return Lfs(n)?Vx(s,n.after)>0:Dfs(n)?Vx(n.before,s)>0:typeof n=="function"?n(s):!1})}function nIe(s,t,n){var r=Object.keys(t).reduce(function(i,l){var o=t[l];return Bfs(s,o)&&i.push(l),i},[]),a={};return r.forEach(function(i){return a[i]=!0}),n&&!W$(s,n)&&(a.outside=!0),a}function $fs(s,t){for(var n=Rd(s[0]),r=$0(s[s.length-1]),a,i,l=n;l<=r;){var o=nIe(l,t),c=!o.disabled&&!o.hidden;if(!c){l=Bl(l,1);continue}if(o.selected)return l;o.today&&!i&&(i=l),a||(a=l),l=Bl(l,1)}return i||a}var Ufs=365;function Zxt(s,t){var n=t.moveBy,r=t.direction,a=t.context,i=t.modifiers,l=t.retry,o=l===void 0?{count:0,lastFocused:s}:l,c=a.weekStartsOn,d=a.fromDate,u=a.toDate,h=a.locale,p={day:Bl,week:L2,month:_f,year:nBt,startOfWeek:function(v){return a.ISOWeek?cN(v):Vm(v,{locale:h,weekStartsOn:c})},endOfWeek:function(v){return a.ISOWeek?lct(v):x8(v,{locale:h,weekStartsOn:c})}},f=p[n](s,r==="after"?1:-1);r==="before"&&d?f=rBt([d,f]):r==="after"&&u&&(f=aBt([u,f]));var y=!0;if(i){var _=nIe(f,i);y=!_.disabled&&!_.hidden}return y?f:o.count>Ufs?o.lastFocused:Zxt(f,{moveBy:n,direction:r,context:a,modifiers:i,retry:ro(ro({},o),{count:o.count+1})})}var Qxt=N.createContext(void 0);function qfs(s){var t=hU(),n=Yxt(),r=N.useState(),a=r[0],i=r[1],l=N.useState(),o=l[0],c=l[1],d=$fs(t.displayMonths,n),u=a??(o&&t.isDateDisplayed(o))?o:d,h=function(){c(a),i(void 0)},p=function(v){i(v)},f=wd(),y=function(v,j){if(a){var w=Zxt(a,{moveBy:v,direction:j,context:f,modifiers:n});ql(a,w)||(t.goToDate(w,a),p(w))}},_={focusedDay:a,focusTarget:u,blur:h,focus:p,focusDayAfter:function(){return y("day","after")},focusDayBefore:function(){return y("day","before")},focusWeekAfter:function(){return y("week","after")},focusWeekBefore:function(){return y("week","before")},focusMonthBefore:function(){return y("month","before")},focusMonthAfter:function(){return y("month","after")},focusYearBefore:function(){return y("year","before")},focusYearAfter:function(){return y("year","after")},focusStartOfWeek:function(){return y("startOfWeek","before")},focusEndOfWeek:function(){return y("endOfWeek","after")}};return e.jsx(Qxt.Provider,{value:_,children:s.children})}function rIe(){var s=N.useContext(Qxt);if(!s)throw new Error("useFocusContext must be used within a FocusProvider");return s}function Vfs(s,t){var n=Yxt(),r=nIe(s,n,t);return r}var aIe=N.createContext(void 0);function Hfs(s){if(!Zye(s.initialProps)){var t={selected:void 0};return e.jsx(aIe.Provider,{value:t,children:s.children})}return e.jsx(Gfs,{initialProps:s.initialProps,children:s.children})}function Gfs(s){var t=s.initialProps,n=s.children,r=function(i,l,o){var c,d,u;if((c=t.onDayClick)===null||c===void 0||c.call(t,i,l,o),l.selected&&!t.required){(d=t.onSelect)===null||d===void 0||d.call(t,void 0,i,l,o);return}(u=t.onSelect)===null||u===void 0||u.call(t,i,i,l,o)},a={selected:t.selected,onDayClick:r};return e.jsx(aIe.Provider,{value:a,children:n})}function Xxt(){var s=N.useContext(aIe);if(!s)throw new Error("useSelectSingle must be used within a SelectSingleProvider");return s}function Wfs(s,t){var n=wd(),r=Xxt(),a=eIe(),i=sIe(),l=rIe(),o=l.focusDayAfter,c=l.focusDayBefore,d=l.focusWeekAfter,u=l.focusWeekBefore,h=l.blur,p=l.focus,f=l.focusMonthBefore,y=l.focusMonthAfter,_=l.focusYearBefore,v=l.focusYearAfter,j=l.focusStartOfWeek,w=l.focusEndOfWeek,S=function(oe){var he,ce,me,le;Zye(n)?(he=r.onDayClick)===null||he===void 0||he.call(r,s,t,oe):dU(n)?(ce=a.onDayClick)===null||ce===void 0||ce.call(a,s,t,oe):uU(n)?(me=i.onDayClick)===null||me===void 0||me.call(i,s,t,oe):(le=n.onDayClick)===null||le===void 0||le.call(n,s,t,oe)},A=function(oe){var he;p(s),(he=n.onDayFocus)===null||he===void 0||he.call(n,s,t,oe)},E=function(oe){var he;h(),(he=n.onDayBlur)===null||he===void 0||he.call(n,s,t,oe)},O=function(oe){var he;(he=n.onDayMouseEnter)===null||he===void 0||he.call(n,s,t,oe)},D=function(oe){var he;(he=n.onDayMouseLeave)===null||he===void 0||he.call(n,s,t,oe)},I=function(oe){var he;(he=n.onDayPointerEnter)===null||he===void 0||he.call(n,s,t,oe)},F=function(oe){var he;(he=n.onDayPointerLeave)===null||he===void 0||he.call(n,s,t,oe)},z=function(oe){var he;(he=n.onDayTouchCancel)===null||he===void 0||he.call(n,s,t,oe)},H=function(oe){var he;(he=n.onDayTouchEnd)===null||he===void 0||he.call(n,s,t,oe)},Z=function(oe){var he;(he=n.onDayTouchMove)===null||he===void 0||he.call(n,s,t,oe)},Y=function(oe){var he;(he=n.onDayTouchStart)===null||he===void 0||he.call(n,s,t,oe)},W=function(oe){var he;(he=n.onDayKeyUp)===null||he===void 0||he.call(n,s,t,oe)},ee=function(oe){var he;switch(oe.key){case"ArrowLeft":oe.preventDefault(),oe.stopPropagation(),n.dir==="rtl"?o():c();break;case"ArrowRight":oe.preventDefault(),oe.stopPropagation(),n.dir==="rtl"?c():o();break;case"ArrowDown":oe.preventDefault(),oe.stopPropagation(),d();break;case"ArrowUp":oe.preventDefault(),oe.stopPropagation(),u();break;case"PageUp":oe.preventDefault(),oe.stopPropagation(),oe.shiftKey?_():f();break;case"PageDown":oe.preventDefault(),oe.stopPropagation(),oe.shiftKey?v():y();break;case"Home":oe.preventDefault(),oe.stopPropagation(),j();break;case"End":oe.preventDefault(),oe.stopPropagation(),w();break}(he=n.onDayKeyDown)===null||he===void 0||he.call(n,s,t,oe)},se={onClick:S,onFocus:A,onBlur:E,onKeyDown:ee,onKeyUp:W,onMouseEnter:O,onMouseLeave:D,onPointerEnter:I,onPointerLeave:F,onTouchCancel:z,onTouchEnd:H,onTouchMove:Z,onTouchStart:Y};return se}function Kfs(){var s=wd(),t=Xxt(),n=eIe(),r=sIe(),a=Zye(s)?t.selected:dU(s)?n.selected:uU(s)?r.selected:void 0;return a}function Yfs(s){return Object.values(Sb).includes(s)}function Zfs(s,t){var n=[s.classNames.day];return Object.keys(t).forEach(function(r){var a=s.modifiersClassNames[r];if(a)n.push(a);else if(Yfs(r)){var i=s.classNames["day_".concat(r)];i&&n.push(i)}}),n}function Qfs(s,t){var n=ro({},s.styles.day);return Object.keys(t).forEach(function(r){var a;n=ro(ro({},n),(a=s.modifiersStyles)===null||a===void 0?void 0:a[r])}),n}function Xfs(s,t,n){var r,a,i,l=wd(),o=rIe(),c=Vfs(s,t),d=Wfs(s,c),u=Kfs(),h=!!(l.onDayClick||l.mode!=="default");N.useEffect(function(){var O;c.outside||o.focusedDay&&h&&ql(o.focusedDay,s)&&((O=n.current)===null||O===void 0||O.focus())},[o.focusedDay,s,n,h,c.outside]);var p=Zfs(l,c).join(" "),f=Qfs(l,c),y=!!(c.outside&&!l.showOutsideDays||c.hidden),_=(i=(a=l.components)===null||a===void 0?void 0:a.DayContent)!==null&&i!==void 0?i:vfs,v=e.jsx(_,{date:s,displayMonth:t,activeModifiers:c}),j={style:f,className:p,children:v,role:"gridcell"},w=o.focusTarget&&ql(o.focusTarget,s)&&!c.outside,S=o.focusedDay&&ql(o.focusedDay,s),A=ro(ro(ro({},j),(r={disabled:c.disabled,role:"gridcell"},r["aria-selected"]=c.selected,r.tabIndex=S||w?0:-1,r)),d),E={isButton:h,isHidden:y,activeModifiers:c,selectedDays:u,buttonProps:A,divProps:j};return E}function Jfs(s){var t=N.useRef(null),n=Xfs(s.date,s.displayMonth,t);return n.isHidden?e.jsx("div",{role:"gridcell"}):n.isButton?e.jsx(dxe,ro({name:"day",ref:t},n.buttonProps)):e.jsx("div",ro({},n.divProps))}function exs(s){var t=s.number,n=s.dates,r=wd(),a=r.onWeekNumberClick,i=r.styles,l=r.classNames,o=r.locale,c=r.labels.labelWeekNumber,d=r.formatters.formatWeekNumber,u=d(Number(t),{locale:o});if(!a)return e.jsx("span",{className:l.weeknumber,style:i.weeknumber,children:u});var h=c(Number(t),{locale:o}),p=function(f){a(t,n,f)};return e.jsx(dxe,{name:"week-number","aria-label":h,className:l.weeknumber,style:i.weeknumber,onClick:p,children:u})}function txs(s){var t,n,r=wd(),a=r.styles,i=r.classNames,l=r.showWeekNumber,o=r.components,c=(t=o==null?void 0:o.Day)!==null&&t!==void 0?t:Jfs,d=(n=o==null?void 0:o.WeekNumber)!==null&&n!==void 0?n:exs,u;return l&&(u=e.jsx("td",{className:i.cell,style:a.cell,children:e.jsx(d,{number:s.weekNumber,dates:s.dates})})),e.jsxs("tr",{className:i.row,style:a.row,children:[u,s.dates.map(function(h){return e.jsx("td",{className:i.cell,style:a.cell,role:"presentation",children:e.jsx(c,{displayMonth:s.displayMonth,date:h})},l$t(h))})]})}function wVe(s,t,n){for(var r=n!=null&&n.ISOWeek?lct(t):x8(t,n),a=n!=null&&n.ISOWeek?cN(s):Vm(s,n),i=Vx(r,a),l=[],o=0;o<=i;o++)l.push(Bl(a,o));var c=l.reduce(function(d,u){var h=n!=null&&n.ISOWeek?FAe(u):BAe(u,n),p=d.find(function(f){return f.weekNumber===h});return p?(p.dates.push(u),d):(d.push({weekNumber:h,dates:[u]}),d)},[]);return c}function sxs(s,t){var n=wVe(Rd(s),$0(s),t);if(t!=null&&t.useFixedWeeks){var r=d$t(s,t);if(r<6){var a=n[n.length-1],i=a.dates[a.dates.length-1],l=L2(i,6-r),o=wVe(L2(i,1),l,t);n.push.apply(n,o)}}return n}function nxs(s){var t,n,r,a=wd(),i=a.locale,l=a.classNames,o=a.styles,c=a.hideHead,d=a.fixedWeeks,u=a.components,h=a.weekStartsOn,p=a.firstWeekContainsDate,f=a.ISOWeek,y=sxs(s.displayMonth,{useFixedWeeks:!!d,ISOWeek:f,locale:i,weekStartsOn:h,firstWeekContainsDate:p}),_=(t=u==null?void 0:u.Head)!==null&&t!==void 0?t:yfs,v=(n=u==null?void 0:u.Row)!==null&&n!==void 0?n:txs,j=(r=u==null?void 0:u.Footer)!==null&&r!==void 0?r:ffs;return e.jsxs("table",{id:s.id,className:l.table,style:o.table,role:"grid","aria-labelledby":s["aria-labelledby"],children:[!c&&e.jsx(_,{}),e.jsx("tbody",{className:l.tbody,style:o.tbody,children:y.map(function(w){return e.jsx(v,{displayMonth:s.displayMonth,dates:w.dates,weekNumber:w.weekNumber},w.weekNumber)})}),e.jsx(j,{displayMonth:s.displayMonth})]})}function rxs(){return!!(typeof window<"u"&&window.document&&window.document.createElement)}var axs=rxs()?N.useLayoutEffect:N.useEffect,i2e=!1,ixs=0;function jVe(){return"react-day-picker-".concat(++ixs)}function oxs(s){var t,n=s??(i2e?jVe():null),r=N.useState(n),a=r[0],i=r[1];return axs(function(){a===null&&i(jVe())},[]),N.useEffect(function(){i2e===!1&&(i2e=!0)},[]),(t=s??a)!==null&&t!==void 0?t:void 0}function lxs(s){var t,n,r=wd(),a=r.dir,i=r.classNames,l=r.styles,o=r.components,c=hU().displayMonths,d=oxs(r.id?"".concat(r.id,"-").concat(s.displayIndex):void 0),u=r.id?"".concat(r.id,"-grid-").concat(s.displayIndex):void 0,h=[i.month],p=l.month,f=s.displayIndex===0,y=s.displayIndex===c.length-1,_=!f&&!y;a==="rtl"&&(t=[f,y],y=t[0],f=t[1]),f&&(h.push(i.caption_start),p=ro(ro({},p),l.caption_start)),y&&(h.push(i.caption_end),p=ro(ro({},p),l.caption_end)),_&&(h.push(i.caption_between),p=ro(ro({},p),l.caption_between));var v=(n=o==null?void 0:o.Caption)!==null&&n!==void 0?n:pfs;return e.jsxs("div",{className:h.join(" "),style:p,children:[e.jsx(v,{id:d,displayMonth:s.displayMonth,displayIndex:s.displayIndex}),e.jsx(nxs,{id:u,"aria-labelledby":d,displayMonth:s.displayMonth})]},s.displayIndex)}function cxs(s){var t=wd(),n=t.classNames,r=t.styles;return e.jsx("div",{className:n.months,style:r.months,children:s.children})}function dxs(s){var t,n,r=s.initialProps,a=wd(),i=rIe(),l=hU(),o=N.useState(!1),c=o[0],d=o[1];N.useEffect(function(){a.initialFocus&&i.focusTarget&&(c||(i.focus(i.focusTarget),d(!0)))},[a.initialFocus,c,i.focus,i.focusTarget,i]);var u=[a.classNames.root,a.className];a.numberOfMonths>1&&u.push(a.classNames.multiple_months),a.showWeekNumber&&u.push(a.classNames.with_weeknumber);var h=ro(ro({},a.styles.root),a.style),p=Object.keys(r).filter(function(y){return y.startsWith("data-")}).reduce(function(y,_){var v;return ro(ro({},y),(v={},v[_]=r[_],v))},{}),f=(n=(t=r.components)===null||t===void 0?void 0:t.Months)!==null&&n!==void 0?n:cxs;return e.jsx("div",ro({className:u.join(" "),style:h,dir:a.dir,id:a.id,nonce:r.nonce,title:r.title,lang:r.lang},p,{children:e.jsx(f,{children:l.displayMonths.map(function(y,_){return e.jsx(lxs,{displayIndex:_,displayMonth:y},_)})})}))}function uxs(s){var t=s.children,n=Dps(s,["children"]);return e.jsx(efs,{initialProps:n,children:e.jsx(dfs,{children:e.jsx(Hfs,{initialProps:n,children:e.jsx(bfs,{initialProps:n,children:e.jsx(jfs,{initialProps:n,children:e.jsx(Mfs,{children:e.jsx(qfs,{children:t})})})})})})})}function hxs(s){return e.jsx(uxs,ro({},s,{children:e.jsx(dxs,{initialProps:s})}))}function Gg({className:s,classNames:t,showOutsideDays:n=!0,...r}){return e.jsx(hxs,{showOutsideDays:n,className:Mt("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:Mt(m8({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:Mt(m8({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(ml,{className:"h-4 w-4"}),IconRight:({...a})=>e.jsx(ga,{className:"h-4 w-4"})},...r})}Gg.displayName="Calendar";var Qye="Popover",[Jxt,gfn]=uu(Qye,[qw]),mU=qw(),[mxs,Y4]=Jxt(Qye),egt=s=>{const{__scopePopover:t,children:n,open:r,defaultOpen:a,onOpenChange:i,modal:l=!1}=s,o=mU(t),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=cm({prop:r,defaultProp:a??!1,onChange:i,caller:Qye});return e.jsx(I$,{...o,children:e.jsx(mxs,{scope:t,contentId:om(),triggerRef:c,open:h,onOpenChange:p,onOpenToggle:N.useCallback(()=>p(f=>!f),[p]),hasCustomAnchor:d,onCustomAnchorAdd:N.useCallback(()=>u(!0),[]),onCustomAnchorRemove:N.useCallback(()=>u(!1),[]),modal:l,children:n})})};egt.displayName=Qye;var tgt="PopoverAnchor",pxs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=Y4(tgt,n),i=mU(n),{onCustomAnchorAdd:l,onCustomAnchorRemove:o}=a;return N.useEffect(()=>(l(),()=>o()),[l,o]),e.jsx(CD,{...i,...r,ref:t})});pxs.displayName=tgt;var sgt="PopoverTrigger",ngt=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=Y4(sgt,n),i=mU(n),l=ji(t,a.triggerRef),o=e.jsx(Yr.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":lgt(a.open),...r,ref:l,onClick:xr(s.onClick,a.onOpenToggle)});return a.hasCustomAnchor?o:e.jsx(CD,{asChild:!0,...i,children:o})});ngt.displayName=sgt;var iIe="PopoverPortal",[fxs,xxs]=Jxt(iIe,{forceMount:void 0}),rgt=s=>{const{__scopePopover:t,forceMount:n,children:r,container:a}=s,i=Y4(iIe,t);return e.jsx(fxs,{scope:t,forceMount:n,children:e.jsx(Lh,{present:n||i.open,children:e.jsx(jD,{asChild:!0,container:a,children:r})})})};rgt.displayName=iIe;var C8="PopoverContent",agt=N.forwardRef((s,t)=>{const n=xxs(C8,s.__scopePopover),{forceMount:r=n.forceMount,...a}=s,i=Y4(C8,s.__scopePopover);return e.jsx(Lh,{present:r||i.open,children:i.modal?e.jsx(yxs,{...a,ref:t}):e.jsx(vxs,{...a,ref:t})})});agt.displayName=C8;var gxs=v4("PopoverContent.RemoveScroll"),yxs=N.forwardRef((s,t)=>{const n=Y4(C8,s.__scopePopover),r=N.useRef(null),a=ji(t,r),i=N.useRef(!1);return N.useEffect(()=>{const l=r.current;if(l)return L0e(l)},[]),e.jsx(z$,{as:gxs,allowPinchZoom:!0,children:e.jsx(igt,{...s,ref:a,trapFocus:n.open,disableOutsidePointerEvents:!0,onCloseAutoFocus:xr(s.onCloseAutoFocus,l=>{var o;l.preventDefault(),i.current||(o=n.triggerRef.current)==null||o.focus()}),onPointerDownOutside:xr(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:xr(s.onFocusOutside,l=>l.preventDefault(),{checkForDefaultPrevented:!1})})})}),vxs=N.forwardRef((s,t)=>{const n=Y4(C8,s.__scopePopover),r=N.useRef(!1),a=N.useRef(!1);return e.jsx(igt,{...s,ref:t,trapFocus:!1,disableOutsidePointerEvents:!1,onCloseAutoFocus:i=>{var l,o;(l=s.onCloseAutoFocus)==null||l.call(s,i),i.defaultPrevented||(r.current||(o=n.triggerRef.current)==null||o.focus(),i.preventDefault()),r.current=!1,a.current=!1},onInteractOutside:i=>{var c,d;(c=s.onInteractOutside)==null||c.call(s,i),i.defaultPrevented||(r.current=!0,i.detail.originalEvent.type==="pointerdown"&&(a.current=!0));const l=i.target;((d=n.triggerRef.current)==null?void 0:d.contains(l))&&i.preventDefault(),i.detail.originalEvent.type==="focusin"&&a.current&&i.preventDefault()}})}),igt=N.forwardRef((s,t)=>{const{__scopePopover:n,trapFocus:r,onOpenAutoFocus:a,onCloseAutoFocus:i,disableOutsidePointerEvents:l,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onInteractOutside:u,...h}=s,p=Y4(C8,n),f=mU(n);return M0e(),e.jsx(O$,{asChild:!0,loop:!0,trapped:r,onMountAutoFocus:a,onUnmountAutoFocus:i,children:e.jsx(O4,{asChild:!0,disableOutsidePointerEvents:l,onInteractOutside:u,onEscapeKeyDown:o,onPointerDownOutside:c,onFocusOutside:d,onDismiss:()=>p.onOpenChange(!1),children:e.jsx(P$,{"data-state":lgt(p.open),role:"dialog",id:p.contentId,...f,...h,ref:t,style:{...h.style,"--radix-popover-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-popover-content-available-width":"var(--radix-popper-available-width)","--radix-popover-content-available-height":"var(--radix-popper-available-height)","--radix-popover-trigger-width":"var(--radix-popper-anchor-width)","--radix-popover-trigger-height":"var(--radix-popper-anchor-height)"}})})})}),ogt="PopoverClose",bxs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=Y4(ogt,n);return e.jsx(Yr.button,{type:"button",...r,ref:t,onClick:xr(s.onClick,()=>a.onOpenChange(!1))})});bxs.displayName=ogt;var _xs="PopoverArrow",wxs=N.forwardRef((s,t)=>{const{__scopePopover:n,...r}=s,a=mU(n);return e.jsx(L$,{...a,...r,ref:t})});wxs.displayName=_xs;function lgt(s){return s?"open":"closed"}var jxs=egt,Nxs=ngt,kxs=rgt,cgt=agt;const il=jxs,ol=Nxs,el=N.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(kxs,{children:e.jsx(cgt,{ref:a,align:t,sideOffset:n,className:Mt("z-50 w-72 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r})}));el.displayName=cgt.displayName;const Sxs=OM("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"}}),oIe=N.forwardRef(({className:s,variant:t,...n},r)=>e.jsx("div",{ref:r,role:"alert",className:Mt(Sxs({variant:t}),s),...n}));oIe.displayName="Alert";const Cxs=N.forwardRef(({className:s,...t},n)=>e.jsx("h5",{ref:n,className:Mt("mb-1 font-medium leading-none tracking-tight",s),...t}));Cxs.displayName="AlertTitle";const lIe=N.forwardRef(({className:s,...t},n)=>e.jsx("div",{ref:n,className:Mt("text-sm [&_p]:leading-relaxed",s),...t}));lIe.displayName="AlertDescription";function Txs({open:s,onOpenChange:t,imageUrl:n,imageId:r,defaultCaption:a="",swagItemId:i,reelId:l}){const o=Kt(),[c,d]=N.useState(a),[u,h]=N.useState([]),[p,f]=N.useState(null),[y,_]=N.useState("now"),[v,j]=N.useState(qze(Yze(new Date),1)),[w,S]=N.useState("12"),[A,E]=N.useState("00"),[O,D]=N.useState("PM");N.useEffect(()=>{if(s){d(a),_("now"),h([]);const ge=qze(Yze(new Date),1);j(ge);const Te=ge.getHours();S(String(Te>12?Te-12:Te===0?12:Te)),E("00"),D(Te>=12?"PM":"AM")}},[s,a]);const I=()=>{if(!v)return null;let ge=parseInt(w);const Te=parseInt(A);return O==="PM"&&ge!==12&&(ge+=12),O==="AM"&&ge===12&&(ge=0),F9(O9(v,ge),Te)},{data:F,isLoading:z}=dt({queryKey:["social-accounts-for-post"],queryFn:async()=>{const{data:{user:ge}}=await q.auth.getUser();if(!ge)return[];const{data:Te,error:Ie}=await q.from("social_accounts").select("*").eq("user_id",ge.id).eq("is_active",!0).order("platform",{ascending:!0});if(Ie)throw Ie;return console.log("Fetched social accounts for posting:",Te),Te},enabled:s,staleTime:0}),H=yt({mutationFn:async({accountId:ge,platform:Te})=>{f(ge);const{data:Ie,error:Ce}=await q.functions.invoke("social-post",{body:{platform:Te,accountId:ge,imageUrl:n,caption:c}});if(Ce)throw Ce;if(Ie!=null&&Ie.error)throw new Error(Ie.error);return Ie},onSuccess:ge=>{const Te=ge.platform==="facebook"?"Facebook":ge.platform==="instagram"?"Instagram":ge.platform==="linkedin"?"LinkedIn":"Google Business";ae.success(`Posted to ${Te}!`)},onError:ge=>{ae.error(`Failed to post: ${ge.message}`)},onSettled:()=>{f(null)}}),Z=yt({mutationFn:async({accountId:ge,platform:Te,scheduledFor:Ie})=>{const{data:{user:Ce}}=await q.auth.getUser();if(!Ce)throw new Error("Not authenticated");const{error:Me}=await q.from("scheduled_posts").insert({user_id:Ce.id,social_account_id:ge,platform:Te,image_url:n,caption:c,swag_item_id:i||null,reel_id:l||null,scheduled_for:Ie.toISOString(),status:"scheduled"});if(Me)throw Me;return{platform:Te}},onSuccess:ge=>{const Te=ge.platform==="facebook"?"Facebook":ge.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Post scheduled for ${Te}!`)},onError:ge=>{ae.error(`Failed to schedule: ${ge.message}`)}}),Y=async()=>{if(u.length===0){ae.error("Please select at least one account");return}if(y==="schedule"){const ge=I();if(!ge||ge<=new Date){ae.error("Please select a future date and time");return}for(const Te of u){const Ie=F==null?void 0:F.find(Ce=>Ce.id===Te);Ie&&await Z.mutateAsync({accountId:Te,platform:Ie.platform,scheduledFor:ge})}o.invalidateQueries({queryKey:["scheduled-posts"]}),ae.success(`${u.length} post(s) scheduled for ${Ss(ge,"PPp")}`)}else for(const ge of u){const Te=F==null?void 0:F.find(Ie=>Ie.id===ge);Te&&await H.mutateAsync({accountId:ge,platform:Te.platform})}o.invalidateQueries({queryKey:["scheduled-posts"]}),d(""),h([]),t(!1)},W=ge=>{h(Te=>Te.includes(ge)?Te.filter(Ie=>Ie!==ge):[...Te,ge])},ee=(F==null?void 0:F.filter(ge=>ge.platform==="facebook"))||[],se=(F==null?void 0:F.filter(ge=>ge.platform==="instagram"))||[],oe=(F==null?void 0:F.filter(ge=>ge.platform==="linkedin"))||[],he=(F==null?void 0:F.filter(ge=>ge.platform==="google_business"))||[],ce=((F==null?void 0:F.length)||0)>0,me=H.isPending||Z.isPending,le=Array.from({length:12},(ge,Te)=>String(Te+1)),ve=["00","15","30","45"];return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create Social Post"}),e.jsx(Jn,{children:"Share this image to your connected social accounts"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("div",{className:"aspect-square w-full max-w-[200px] mx-auto overflow-hidden rounded-lg border",children:e.jsx("img",{src:n,alt:"Post preview",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"caption",children:"Caption"}),e.jsx(Ms,{id:"caption",placeholder:"Write a caption for your post...",value:c,onChange:ge=>d(ge.target.value),rows:3}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.length,"/2200 characters"]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{children:"Publish Time"}),e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsx("button",{type:"button",onClick:()=>_("now"),className:Mt("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",y==="now"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Post Now"}),e.jsx("button",{type:"button",onClick:()=>_("schedule"),className:Mt("flex-1 px-4 py-2 rounded-md text-sm font-medium transition-all",y==="schedule"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Schedule"})]})]}),y==="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(pr,{className:"h-4 w-4"}),"Schedule for"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("justify-start text-left font-normal flex-1",!v&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),v?Ss(v,"PPP"):e.jsx("span",{children:"Pick a date"})]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:v,onSelect:j,disabled:ge=>gee.jsx(Ze,{value:ge,children:ge},ge))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(us,{value:A,onValueChange:E,children:[e.jsx(ls,{className:"w-[70px]",children:e.jsx(hs,{})}),e.jsx(cs,{children:ve.map(ge=>e.jsx(Ze,{value:ge,children:ge},ge))})]}),e.jsxs(us,{value:O,onValueChange:ge=>D(ge),children:[e.jsx(ls,{className:"w-[70px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"AM",children:"AM"}),e.jsx(Ze,{value:"PM",children:"PM"})]})]})]})]}),v&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Post will be published on ",Ss(I()||new Date,"PPP 'at' p")]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{children:"Post to"}),z&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(rs,{className:"h-6 w-6 animate-spin"})}),!z&&!ce&&e.jsxs(oIe,{children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsxs(lIe,{className:"flex flex-col gap-2",children:[e.jsx("span",{children:"No social accounts connected yet."}),e.jsxs(In,{to:"/social-connections",className:"inline-flex items-center gap-1.5 text-primary hover:underline font-medium",children:[e.jsx(Ko,{className:"h-3.5 w-3.5"}),"Connect your Facebook, Instagram & LinkedIn"]})]})]}),ee.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(Mh,{className:"h-4 w-4 text-blue-600"})," Facebook"]}),ee.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(hi,{checked:u.includes(ge.id),onCheckedChange:()=>W(ge.id),disabled:p===ge.id}),e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:ge.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(Mh,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.page_name||ge.platform_username}),p===ge.id&&e.jsx(rs,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),se.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(ou,{className:"h-4 w-4 text-pink-600"})," Instagram"]}),se.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(hi,{checked:u.includes(ge.id),onCheckedChange:()=>W(ge.id),disabled:p===ge.id}),e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:ge.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(ou,{className:"h-4 w-4"})})]}),e.jsxs("span",{className:"flex-1 text-sm font-medium",children:["@",ge.platform_username]}),p===ge.id&&e.jsx(rs,{className:"h-4 w-4 animate-spin"})]},ge.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(xf,{className:"h-4 w-4 text-blue-700"})," LinkedIn"]}),oe.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(hi,{checked:u.includes(ge.id),onCheckedChange:()=>W(ge.id),disabled:p===ge.id}),e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:ge.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(xf,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.platform_username}),p===ge.id&&e.jsx(rs,{className:"h-4 w-4 animate-spin"})]},ge.id))]}),he.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(ka,{className:"h-4 w-4 text-red-600"})," Google Business"]}),he.map(ge=>e.jsxs("label",{className:"flex items-center gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/50 transition-colors",children:[e.jsx(hi,{checked:u.includes(ge.id),onCheckedChange:()=>W(ge.id),disabled:p===ge.id}),e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:ge.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(ka,{className:"h-4 w-4"})})]}),e.jsx("span",{className:"flex-1 text-sm font-medium",children:ge.page_name||ge.platform_username}),p===ge.id&&e.jsx(rs,{className:"h-4 w-4 animate-spin"})]},ge.id))]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:Y,disabled:u.length===0||me,className:"gap-2",children:[me?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):y==="schedule"?e.jsx(yr,{className:"h-4 w-4"}):e.jsx(lr,{className:"h-4 w-4"}),y==="schedule"?`Schedule ${u.length} post${u.length!==1?"s":""}`:`Post to ${u.length} account${u.length!==1?"s":""}`]})]})]})})}function Exs(){const s=Kt(),[t,n]=N.useState(void 0),[r,a]=N.useState("all"),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(void 0),[h,p]=N.useState("12"),[f,y]=N.useState("00"),[_,v]=N.useState("PM"),{data:j=[],isLoading:w}=dt({queryKey:["scheduled-posts"],queryFn:async()=>{const{data:he,error:ce}=await q.from("scheduled_posts").select(` *, social_accounts ( page_name, platform_username, profile_picture_url ) `).order("scheduled_for",{ascending:!1});if(ce)throw ce;return he}}),S=j.filter(he=>{if(r!=="all"&&he.status!==r)return!1;if(t&&he.scheduled_for){const ce=new Date(he.scheduled_for);if(!ql(ce,t))return!1}return!0}),A=j.filter(he=>he.scheduled_for).map(he=>wf(new Date(he.scheduled_for))),E=yt({mutationFn:async he=>{const{error:ce}=await q.from("scheduled_posts").update({caption:he.caption,scheduled_for:he.scheduled_for}).eq("id",he.id);if(ce)throw ce},onSuccess:()=>{ae.success("Post updated!"),s.invalidateQueries({queryKey:["scheduled-posts"]}),l(null)},onError:he=>{ae.error(`Failed to update: ${he.message}`)}}),O=yt({mutationFn:async he=>{const{error:ce}=await q.from("scheduled_posts").update({status:"cancelled"}).eq("id",he);if(ce)throw ce},onSuccess:()=>{ae.success("Post cancelled"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:he=>{ae.error(`Failed to cancel: ${he.message}`)}}),D=yt({mutationFn:async he=>{const{error:ce}=await q.from("scheduled_posts").delete().eq("id",he);if(ce)throw ce},onSuccess:()=>{ae.success("Post deleted"),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:he=>{ae.error(`Failed to delete: ${he.message}`)}}),I=yt({mutationFn:async he=>{const{data:ce,error:me}=await q.functions.invoke("social-post",{body:{platform:he.platform,accountId:he.social_account_id,imageUrl:he.image_url,caption:he.caption}});if(me)throw me;if(ce!=null&&ce.error)throw new Error(ce.error);return await q.from("scheduled_posts").update({status:"posted",posted_at:new Date().toISOString(),post_id:ce.postId}).eq("id",he.id),ce},onSuccess:he=>{const ce=he.platform==="facebook"?"Facebook":he.platform==="instagram"?"Instagram":"LinkedIn";ae.success(`Posted to ${ce}!`),s.invalidateQueries({queryKey:["scheduled-posts"]})},onError:he=>{ae.error(`Failed to post: ${he.message}`)}}),F=he=>{if(l(he),c(he.caption||""),he.scheduled_for){const ce=new Date(he.scheduled_for);u(ce);const me=ce.getHours();p(String(me>12?me-12:me===0?12:me)),y(String(ce.getMinutes()).padStart(2,"0")),v(me>=12?"PM":"AM")}},z=()=>{if(!i||!d)return;let he=parseInt(h);const ce=parseInt(f);_==="PM"&&he!==12&&(he+=12),_==="AM"&&he===12&&(he=0);const me=F9(O9(d,he),ce);E.mutate({id:i.id,caption:o,scheduled_for:me.toISOString()})},H=he=>{switch(he){case"facebook":return e.jsx(Mh,{className:"h-4 w-4 text-blue-600"});case"instagram":return e.jsx(ou,{className:"h-4 w-4 text-pink-600"});case"linkedin":return e.jsx(xf,{className:"h-4 w-4 text-blue-700"});default:return null}},Z=he=>{switch(he){case"scheduled":return e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),"Scheduled"]});case"posted":return e.jsxs(Ue,{variant:"default",className:"gap-1 bg-green-600",children:[e.jsx(Pi,{className:"h-3 w-3"}),"Posted"]});case"failed":return e.jsxs(Ue,{variant:"destructive",className:"gap-1",children:[e.jsx(Uc,{className:"h-3 w-3"}),"Failed"]});case"cancelled":return e.jsxs(Ue,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Bi,{className:"h-3 w-3"}),"Cancelled"]});default:return e.jsx(Ue,{variant:"outline",children:he})}},Y=Array.from({length:12},(he,ce)=>String(ce+1)),W=["00","15","30","45"],ee=j.filter(he=>he.status==="scheduled").length,se=j.filter(he=>he.status==="posted").length,oe=j.filter(he=>he.status==="scheduled"&&he.scheduled_for&&u$t(new Date(he.scheduled_for))).length;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:ee}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Scheduled"})]}),e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:oe}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Upcoming"})]}),e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:se}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Posted"})]}),e.jsxs(fe,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:j.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"})]})]}),e.jsxs("div",{className:"flex flex-col lg:flex-row gap-6",children:[e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx(Cl,{className:"h-5 w-5"}),e.jsx("h3",{className:"font-semibold",children:"Calendar"})]}),e.jsx(Gg,{mode:"single",selected:t,onSelect:n,className:Mt("pointer-events-auto"),modifiers:{hasPost:A},modifiersStyles:{hasPost:{fontWeight:"bold",backgroundColor:"hsl(var(--primary) / 0.1)",borderRadius:"50%"}}}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>n(void 0),className:"w-full mt-2",children:"Clear date filter"})]}),e.jsxs("div",{className:"flex-1 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Lv,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("div",{className:"flex flex-wrap gap-1",children:["all","scheduled","posted","failed","cancelled"].map(he=>e.jsx(B,{variant:r===he?"default":"outline",size:"sm",onClick:()=>a(he),className:"capitalize",children:he},he))})]}),w&&e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}),!w&&S.length===0&&e.jsxs(fe,{className:"p-8 text-center",children:[e.jsx(yr,{className:"h-12 w-12 mx-auto text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"font-medium mb-2",children:"No posts found"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:t?`No posts scheduled for ${Ss(t,"PPP")}`:"Schedule a post from Social Swag to get started!"})]}),e.jsx("div",{className:"space-y-4",children:S.map(he=>{var ce,me;return e.jsx(fe,{className:"overflow-hidden",children:e.jsxs("div",{className:"flex flex-col sm:flex-row",children:[e.jsx("div",{className:"sm:w-32 h-32 sm:h-auto bg-muted flex-shrink-0",children:e.jsx("img",{src:he.image_url,alt:"Post preview",className:"w-full h-full object-cover"})}),e.jsxs(Ee,{className:"flex-1 p-4",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-2 mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[H(he.platform),e.jsx("span",{className:"font-medium",children:((ce=he.social_accounts)==null?void 0:ce.page_name)||((me=he.social_accounts)==null?void 0:me.platform_username)||"Unknown"}),Z(he.status)]}),e.jsxs("div",{className:"flex items-center gap-1",children:[he.status==="scheduled"&&e.jsxs(Vw,{children:[e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>F(he),children:e.jsx(ya,{className:"h-4 w-4"})})}),e.jsx(Nc,{children:"Edit post"})]}),e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>I.mutate(he),disabled:I.isPending,children:I.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"})})}),e.jsx(Nc,{children:"Post now"})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Cancel this scheduled post?"}),e.jsx(Mo,{children:"This will cancel the post. You can delete it entirely or keep it in your history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep"}),e.jsx(wo,{onClick:()=>O.mutate(he.id),className:"bg-amber-600 hover:bg-amber-700",children:"Cancel Post"}),e.jsx(wo,{onClick:()=>D.mutate(he.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]}),(he.status==="posted"||he.status==="cancelled"||he.status==="failed")&&e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this post?"}),e.jsx(Mo,{children:"This will permanently remove this post from your history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>D.mutate(he.id),className:"bg-destructive hover:bg-destructive/90",children:"Delete"})]})]})]})]})]}),he.caption&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-2",children:he.caption}),e.jsxs("div",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),he.status==="posted"&&he.posted_at?`Posted ${Ss(new Date(he.posted_at),"PPp")}`:he.scheduled_for?`Scheduled for ${Ss(new Date(he.scheduled_for),"PPp")}`:"Not scheduled"]}),he.status==="failed"&&he.error_message&&e.jsxs("p",{className:"text-xs text-destructive mt-2",children:["Error: ",he.error_message]})]})]})},he.id)})})]})]}),e.jsx(_s,{open:!!i,onOpenChange:he=>!he&&l(null),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Edit Scheduled Post"}),e.jsx(Jn,{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(ne,{children:"Caption"}),e.jsx(Ms,{value:o,onChange:he=>c(he.target.value),rows:3})]}),e.jsxs("div",{className:"space-y-3 p-4 border rounded-lg",children:[e.jsx(ne,{children:"Schedule for"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("justify-start text-left font-normal flex-1",!d&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),d?Ss(d,"PPP"):"Pick a date"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:d,onSelect:u,disabled:he=>hee.jsx(Ze,{value:he,children:he},he))})]}),e.jsx("span",{className:"text-muted-foreground",children:":"}),e.jsxs(us,{value:f,onValueChange:y,children:[e.jsx(ls,{className:"w-[70px]",children:e.jsx(hs,{})}),e.jsx(cs,{children:W.map(he=>e.jsx(Ze,{value:he,children:he},he))})]}),e.jsxs(us,{value:_,onValueChange:he=>v(he),children:[e.jsx(ls,{className:"w-[70px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"AM",children:"AM"}),e.jsx(Ze,{value:"PM",children:"PM"})]})]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(null),children:"Cancel"}),e.jsxs(B,{onClick:z,disabled:E.isPending,children:[E.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin mr-2"}):null,"Save Changes"]})]})]})})]})}function jH(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 dgt={exports:{}};/*! JSZip v3.10.1 - A JavaScript class for generating and reading zip files (c) 2009-2016 Stuart Knightley Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown. JSZip uses the library pako released under the MIT license : https://github.com/nodeca/pako/blob/main/LICENSE */(function(s,t){(function(n){s.exports=n()})(function(){return function n(r,a,i){function l(d,u){if(!a[d]){if(!r[d]){var h=typeof jH=="function"&&jH;if(!u&&h)return h(d,!0);if(o)return o(d,!0);var p=new Error("Cannot find module '"+d+"'");throw p.code="MODULE_NOT_FOUND",p}var f=a[d]={exports:{}};r[d][0].call(f.exports,function(y){var _=r[d][1][y];return l(_||y)},f,f.exports,n,r,a,i)}return a[d].exports}for(var o=typeof jH=="function"&&jH,c=0;c>2,f=(3&d)<<4|u>>4,y=1>6:64,_=2>4,u=(15&p)<<4|(f=o.indexOf(c.charAt(_++)))>>2,h=(3&f)<<6|(y=o.indexOf(c.charAt(_++))),w[v++]=d,f!==64&&(w[v++]=u),y!==64&&(w[v++]=h);return w}},{"./support":30,"./utils":32}],2:[function(n,r,a){var i=n("./external"),l=n("./stream/DataWorker"),o=n("./stream/Crc32Probe"),c=n("./stream/DataLengthProbe");function d(u,h,p,f,y){this.compressedSize=u,this.uncompressedSize=h,this.crc32=p,this.compression=f,this.compressedContent=y}d.prototype={getContentWorker:function(){var u=new l(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new c("data_length")),h=this;return u.on("end",function(){if(this.streamInfo.data_length!==h.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),u},getCompressedWorker:function(){return new l(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},d.createWorkerFrom=function(u,h,p){return u.pipe(new o).pipe(new c("uncompressedSize")).pipe(h.compressWorker(p)).pipe(new c("compressedSize")).withStreamInfo("compression",h)},r.exports=d},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(n,r,a){var i=n("./stream/GenericWorker");a.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},a.DEFLATE=n("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(n,r,a){var i=n("./utils"),l=function(){for(var o,c=[],d=0;d<256;d++){o=d;for(var u=0;u<8;u++)o=1&o?3988292384^o>>>1:o>>>1;c[d]=o}return c}();r.exports=function(o,c){return o!==void 0&&o.length?i.getTypeOf(o)!=="string"?function(d,u,h,p){var f=l,y=p+h;d^=-1;for(var _=p;_>>8^f[255&(d^u[_])];return-1^d}(0|c,o,o.length,0):function(d,u,h,p){var f=l,y=p+h;d^=-1;for(var _=p;_>>8^f[255&(d^u.charCodeAt(_))];return-1^d}(0|c,o,o.length,0):0}},{"./utils":32}],5:[function(n,r,a){a.base64=!1,a.binary=!1,a.dir=!1,a.createFolders=!0,a.date=null,a.compression=null,a.compressionOptions=null,a.comment=null,a.unixPermissions=null,a.dosPermissions=null},{}],6:[function(n,r,a){var i=null;i=typeof Promise<"u"?Promise:n("lie"),r.exports={Promise:i}},{lie:37}],7:[function(n,r,a){var i=typeof Uint8Array<"u"&&typeof Uint16Array<"u"&&typeof Uint32Array<"u",l=n("pako"),o=n("./utils"),c=n("./stream/GenericWorker"),d=i?"uint8array":"array";function u(h,p){c.call(this,"FlateWorker/"+h),this._pako=null,this._pakoAction=h,this._pakoOptions=p,this.meta={}}a.magic="\b\0",o.inherits(u,c),u.prototype.processChunk=function(h){this.meta=h.meta,this._pako===null&&this._createPako(),this._pako.push(o.transformTo(d,h.data),!1)},u.prototype.flush=function(){c.prototype.flush.call(this),this._pako===null&&this._createPako(),this._pako.push([],!0)},u.prototype.cleanUp=function(){c.prototype.cleanUp.call(this),this._pako=null},u.prototype._createPako=function(){this._pako=new l[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var h=this;this._pako.onData=function(p){h.push({data:p,meta:h.meta})}},a.compressWorker=function(h){return new u("Deflate",h)},a.uncompressWorker=function(){return new u("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(n,r,a){function i(f,y){var _,v="";for(_=0;_>>=8;return v}function l(f,y,_,v,j,w){var S,A,E=f.file,O=f.compression,D=w!==d.utf8encode,I=o.transformTo("string",w(E.name)),F=o.transformTo("string",d.utf8encode(E.name)),z=E.comment,H=o.transformTo("string",w(z)),Z=o.transformTo("string",d.utf8encode(z)),Y=F.length!==E.name.length,W=Z.length!==z.length,ee="",se="",oe="",he=E.dir,ce=E.date,me={crc32:0,compressedSize:0,uncompressedSize:0};y&&!_||(me.crc32=f.crc32,me.compressedSize=f.compressedSize,me.uncompressedSize=f.uncompressedSize);var le=0;y&&(le|=8),D||!Y&&!W||(le|=2048);var ve=0,ge=0;he&&(ve|=16),j==="UNIX"?(ge=798,ve|=function(Ie,Ce){var Me=Ie;return Ie||(Me=Ce?16893:33204),(65535&Me)<<16}(E.unixPermissions,he)):(ge=20,ve|=function(Ie){return 63&(Ie||0)}(E.dosPermissions)),S=ce.getUTCHours(),S<<=6,S|=ce.getUTCMinutes(),S<<=5,S|=ce.getUTCSeconds()/2,A=ce.getUTCFullYear()-1980,A<<=4,A|=ce.getUTCMonth()+1,A<<=5,A|=ce.getUTCDate(),Y&&(se=i(1,1)+i(u(I),4)+F,ee+="up"+i(se.length,2)+se),W&&(oe=i(1,1)+i(u(H),4)+Z,ee+="uc"+i(oe.length,2)+oe);var Te="";return Te+=` \0`,Te+=i(le,2),Te+=O.magic,Te+=i(S,2),Te+=i(A,2),Te+=i(me.crc32,4),Te+=i(me.compressedSize,4),Te+=i(me.uncompressedSize,4),Te+=i(I.length,2),Te+=i(ee.length,2),{fileRecord:h.LOCAL_FILE_HEADER+Te+I+ee,dirRecord:h.CENTRAL_FILE_HEADER+i(ge,2)+Te+i(H.length,2)+"\0\0\0\0"+i(ve,4)+i(v,4)+I+ee+H}}var o=n("../utils"),c=n("../stream/GenericWorker"),d=n("../utf8"),u=n("../crc32"),h=n("../signature");function p(f,y,_,v){c.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=y,this.zipPlatform=_,this.encodeFileName=v,this.streamFiles=f,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}o.inherits(p,c),p.prototype.push=function(f){var y=f.meta.percent||0,_=this.entriesCount,v=this._sources.length;this.accumulate?this.contentBuffer.push(f):(this.bytesWritten+=f.data.length,c.prototype.push.call(this,{data:f.data,meta:{currentFile:this.currentFile,percent:_?(y+100*(_-v-1))/_:100}}))},p.prototype.openedSource=function(f){this.currentSourceOffset=this.bytesWritten,this.currentFile=f.file.name;var y=this.streamFiles&&!f.file.dir;if(y){var _=l(f,y,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:_.fileRecord,meta:{percent:0}})}else this.accumulate=!0},p.prototype.closedSource=function(f){this.accumulate=!1;var y=this.streamFiles&&!f.file.dir,_=l(f,y,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(_.dirRecord),y)this.push({data:function(v){return h.DATA_DESCRIPTOR+i(v.crc32,4)+i(v.compressedSize,4)+i(v.uncompressedSize,4)}(f),meta:{percent:100}});else for(this.push({data:_.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},p.prototype.flush=function(){for(var f=this.bytesWritten,y=0;y=this.index;c--)d=(d<<8)+this.byteAt(c);return this.index+=o,d},readString:function(o){return i.transformTo("string",this.readData(o))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var o=this.readInt(4);return new Date(Date.UTC(1980+(o>>25&127),(o>>21&15)-1,o>>16&31,o>>11&31,o>>5&63,(31&o)<<1))}},r.exports=l},{"../utils":32}],19:[function(n,r,a){var i=n("./Uint8ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(n,r,a){var i=n("./DataReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.byteAt=function(o){return this.data.charCodeAt(this.zero+o)},l.prototype.lastIndexOfSignature=function(o){return this.data.lastIndexOf(o)-this.zero},l.prototype.readAndCheckSignature=function(o){return o===this.readData(4)},l.prototype.readData=function(o){this.checkOffset(o);var c=this.data.slice(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./DataReader":18}],21:[function(n,r,a){var i=n("./ArrayReader");function l(o){i.call(this,o)}n("../utils").inherits(l,i),l.prototype.readData=function(o){if(this.checkOffset(o),o===0)return new Uint8Array(0);var c=this.data.subarray(this.zero+this.index,this.zero+this.index+o);return this.index+=o,c},r.exports=l},{"../utils":32,"./ArrayReader":17}],22:[function(n,r,a){var i=n("../utils"),l=n("../support"),o=n("./ArrayReader"),c=n("./StringReader"),d=n("./NodeBufferReader"),u=n("./Uint8ArrayReader");r.exports=function(h){var p=i.getTypeOf(h);return i.checkSupport(p),p!=="string"||l.uint8array?p==="nodebuffer"?new d(h):l.uint8array?new u(i.transformTo("uint8array",h)):new o(i.transformTo("array",h)):new c(h)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(n,r,a){a.LOCAL_FILE_HEADER="PK",a.CENTRAL_FILE_HEADER="PK",a.CENTRAL_DIRECTORY_END="PK",a.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK\x07",a.ZIP64_CENTRAL_DIRECTORY_END="PK",a.DATA_DESCRIPTOR="PK\x07\b"},{}],24:[function(n,r,a){var i=n("./GenericWorker"),l=n("../utils");function o(c){i.call(this,"ConvertWorker to "+c),this.destType=c}l.inherits(o,i),o.prototype.processChunk=function(c){this.push({data:l.transformTo(this.destType,c.data),meta:c.meta})},r.exports=o},{"../utils":32,"./GenericWorker":28}],25:[function(n,r,a){var i=n("./GenericWorker"),l=n("../crc32");function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n("../utils").inherits(o,i),o.prototype.processChunk=function(c){this.streamInfo.crc32=l(c.data,this.streamInfo.crc32||0),this.push(c)},r.exports=o},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataLengthProbe for "+c),this.propName=c,this.withStreamInfo(c,0)}i.inherits(o,l),o.prototype.processChunk=function(c){if(c){var d=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=d+c.data.length}l.prototype.processChunk.call(this,c)},r.exports=o},{"../utils":32,"./GenericWorker":28}],27:[function(n,r,a){var i=n("../utils"),l=n("./GenericWorker");function o(c){l.call(this,"DataWorker");var d=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,c.then(function(u){d.dataIsReady=!0,d.data=u,d.max=u&&u.length||0,d.type=i.getTypeOf(u),d.isPaused||d._tickAndRepeat()},function(u){d.error(u)})}i.inherits(o,l),o.prototype.cleanUp=function(){l.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!l.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var c=null,d=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":c=this.data.substring(this.index,d);break;case"uint8array":c=this.data.subarray(this.index,d);break;case"array":case"nodebuffer":c=this.data.slice(this.index,d)}return this.index=d,this.push({data:c,meta:{percent:this.max?this.index/this.max*100:0}})},r.exports=o},{"../utils":32,"./GenericWorker":28}],28:[function(n,r,a){function i(l){this.name=l||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(l){this.emit("data",l)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(l){this.emit("error",l)}return!0},error:function(l){return!this.isFinished&&(this.isPaused?this.generatedError=l:(this.isFinished=!0,this.emit("error",l),this.previous&&this.previous.error(l),this.cleanUp()),!0)},on:function(l,o){return this._listeners[l].push(o),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(l,o){if(this._listeners[l])for(var c=0;c "+l:l}},r.exports=i},{}],29:[function(n,r,a){var i=n("../utils"),l=n("./ConvertWorker"),o=n("./GenericWorker"),c=n("../base64"),d=n("../support"),u=n("../external"),h=null;if(d.nodestream)try{h=n("../nodejs/NodejsStreamOutputAdapter")}catch{}function p(y,_){return new u.Promise(function(v,j){var w=[],S=y._internalType,A=y._outputType,E=y._mimeType;y.on("data",function(O,D){w.push(O),_&&_(D)}).on("error",function(O){w=[],j(O)}).on("end",function(){try{var O=function(D,I,F){switch(D){case"blob":return i.newBlob(i.transformTo("arraybuffer",I),F);case"base64":return c.encode(I);default:return i.transformTo(D,I)}}(A,function(D,I){var F,z=0,H=null,Z=0;for(F=0;F"u")a.blob=!1;else{var i=new ArrayBuffer(0);try{a.blob=new Blob([i],{type:"application/zip"}).size===0}catch{try{var l=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);l.append(i),a.blob=l.getBlob("application/zip").size===0}catch{a.blob=!1}}}try{a.nodestream=!!n("readable-stream").Readable}catch{a.nodestream=!1}},{"readable-stream":16}],31:[function(n,r,a){for(var i=n("./utils"),l=n("./support"),o=n("./nodejsUtils"),c=n("./stream/GenericWorker"),d=new Array(256),u=0;u<256;u++)d[u]=252<=u?6:248<=u?5:240<=u?4:224<=u?3:192<=u?2:1;d[254]=d[254]=1;function h(){c.call(this,"utf-8 decode"),this.leftOver=null}function p(){c.call(this,"utf-8 encode")}a.utf8encode=function(f){return l.nodebuffer?o.newBufferFrom(f,"utf-8"):function(y){var _,v,j,w,S,A=y.length,E=0;for(w=0;w>>6:(v<65536?_[S++]=224|v>>>12:(_[S++]=240|v>>>18,_[S++]=128|v>>>12&63),_[S++]=128|v>>>6&63),_[S++]=128|63&v);return _}(f)},a.utf8decode=function(f){return l.nodebuffer?i.transformTo("nodebuffer",f).toString("utf-8"):function(y){var _,v,j,w,S=y.length,A=new Array(2*S);for(_=v=0;_>10&1023,A[v++]=56320|1023&j)}return A.length!==v&&(A.subarray?A=A.subarray(0,v):A.length=v),i.applyFromCharCode(A)}(f=i.transformTo(l.uint8array?"uint8array":"array",f))},i.inherits(h,c),h.prototype.processChunk=function(f){var y=i.transformTo(l.uint8array?"uint8array":"array",f.data);if(this.leftOver&&this.leftOver.length){if(l.uint8array){var _=y;(y=new Uint8Array(_.length+this.leftOver.length)).set(this.leftOver,0),y.set(_,this.leftOver.length)}else y=this.leftOver.concat(y);this.leftOver=null}var v=function(w,S){var A;for((S=S||w.length)>w.length&&(S=w.length),A=S-1;0<=A&&(192&w[A])==128;)A--;return A<0||A===0?S:A+d[w[A]]>S?A:S}(y),j=y;v!==y.length&&(l.uint8array?(j=y.subarray(0,v),this.leftOver=y.subarray(v,y.length)):(j=y.slice(0,v),this.leftOver=y.slice(v,y.length))),this.push({data:a.utf8decode(j),meta:f.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:a.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},a.Utf8DecodeWorker=h,i.inherits(p,c),p.prototype.processChunk=function(f){this.push({data:a.utf8encode(f.data),meta:f.meta})},a.Utf8EncodeWorker=p},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(n,r,a){var i=n("./support"),l=n("./base64"),o=n("./nodejsUtils"),c=n("./external");function d(_){return _}function u(_,v){for(var j=0;j<_.length;++j)v[j]=255&_.charCodeAt(j);return v}n("setimmediate"),a.newBlob=function(_,v){a.checkSupport("blob");try{return new Blob([_],{type:v})}catch{try{var j=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return j.append(_),j.getBlob(v)}catch{throw new Error("Bug : can't construct the Blob.")}}};var h={stringifyByChunk:function(_,v,j){var w=[],S=0,A=_.length;if(A<=j)return String.fromCharCode.apply(null,_);for(;S>8;this.dir=!!(16&this.externalFileAttributes),f==0&&(this.dosPermissions=63&this.externalFileAttributes),f==3&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||this.fileNameStr.slice(-1)!=="/"||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var f=i(this.extraFields[1].value);this.uncompressedSize===l.MAX_VALUE_32BITS&&(this.uncompressedSize=f.readInt(8)),this.compressedSize===l.MAX_VALUE_32BITS&&(this.compressedSize=f.readInt(8)),this.localHeaderOffset===l.MAX_VALUE_32BITS&&(this.localHeaderOffset=f.readInt(8)),this.diskNumberStart===l.MAX_VALUE_32BITS&&(this.diskNumberStart=f.readInt(4))}},readExtraFields:function(f){var y,_,v,j=f.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});f.index+4>>6:(f<65536?p[v++]=224|f>>>12:(p[v++]=240|f>>>18,p[v++]=128|f>>>12&63),p[v++]=128|f>>>6&63),p[v++]=128|63&f);return p},a.buf2binstring=function(h){return u(h,h.length)},a.binstring2buf=function(h){for(var p=new i.Buf8(h.length),f=0,y=p.length;f>10&1023,w[y++]=56320|1023&_)}return u(w,y)},a.utf8border=function(h,p){var f;for((p=p||h.length)>h.length&&(p=h.length),f=p-1;0<=f&&(192&h[f])==128;)f--;return f<0||f===0?p:f+c[h[f]]>p?f:p}},{"./common":41}],43:[function(n,r,a){r.exports=function(i,l,o,c){for(var d=65535&i|0,u=i>>>16&65535|0,h=0;o!==0;){for(o-=h=2e3>>1:l>>>1;o[c]=l}return o}();r.exports=function(l,o,c,d){var u=i,h=d+c;l^=-1;for(var p=d;p>>8^u[255&(l^o[p])];return-1^l}},{}],46:[function(n,r,a){var i,l=n("../utils/common"),o=n("./trees"),c=n("./adler32"),d=n("./crc32"),u=n("./messages"),h=0,p=4,f=0,y=-2,_=-1,v=4,j=2,w=8,S=9,A=286,E=30,O=19,D=2*A+1,I=15,F=3,z=258,H=z+F+1,Z=42,Y=113,W=1,ee=2,se=3,oe=4;function he(ke,it){return ke.msg=u[it],it}function ce(ke){return(ke<<1)-(4ke.avail_out&&(je=ke.avail_out),je!==0&&(l.arraySet(ke.output,it.pending_buf,it.pending_out,je,ke.next_out),ke.next_out+=je,it.pending_out+=je,ke.total_out+=je,ke.avail_out-=je,it.pending-=je,it.pending===0&&(it.pending_out=0))}function ve(ke,it){o._tr_flush_block(ke,0<=ke.block_start?ke.block_start:-1,ke.strstart-ke.block_start,it),ke.block_start=ke.strstart,le(ke.strm)}function ge(ke,it){ke.pending_buf[ke.pending++]=it}function Te(ke,it){ke.pending_buf[ke.pending++]=it>>>8&255,ke.pending_buf[ke.pending++]=255&it}function Ie(ke,it){var je,He,$e=ke.max_chain_length,Ke=ke.strstart,Ge=ke.prev_length,rt=ke.nice_match,tt=ke.strstart>ke.w_size-H?ke.strstart-(ke.w_size-H):0,at=ke.window,Ye=ke.w_mask,ut=ke.prev,_t=ke.strstart+z,bt=at[Ke+Ge-1],$t=at[Ke+Ge];ke.prev_length>=ke.good_match&&($e>>=2),rt>ke.lookahead&&(rt=ke.lookahead);do if(at[(je=it)+Ge]===$t&&at[je+Ge-1]===bt&&at[je]===at[Ke]&&at[++je]===at[Ke+1]){Ke+=2,je++;do;while(at[++Ke]===at[++je]&&at[++Ke]===at[++je]&&at[++Ke]===at[++je]&&at[++Ke]===at[++je]&&at[++Ke]===at[++je]&&at[++Ke]===at[++je]&&at[++Ke]===at[++je]&&at[++Ke]===at[++je]&&Ke<_t);if(He=z-(_t-Ke),Ke=_t-z,Gett&&--$e!=0);return Ge<=ke.lookahead?Ge:ke.lookahead}function Ce(ke){var it,je,He,$e,Ke,Ge,rt,tt,at,Ye,ut=ke.w_size;do{if($e=ke.window_size-ke.lookahead-ke.strstart,ke.strstart>=ut+(ut-H)){for(l.arraySet(ke.window,ke.window,ut,ut,0),ke.match_start-=ut,ke.strstart-=ut,ke.block_start-=ut,it=je=ke.hash_size;He=ke.head[--it],ke.head[it]=ut<=He?He-ut:0,--je;);for(it=je=ut;He=ke.prev[--it],ke.prev[it]=ut<=He?He-ut:0,--je;);$e+=ut}if(ke.strm.avail_in===0)break;if(Ge=ke.strm,rt=ke.window,tt=ke.strstart+ke.lookahead,at=$e,Ye=void 0,Ye=Ge.avail_in,at=F)for(Ke=ke.strstart-ke.insert,ke.ins_h=ke.window[Ke],ke.ins_h=(ke.ins_h<=F&&(ke.ins_h=(ke.ins_h<=F)if(He=o._tr_tally(ke,ke.strstart-ke.match_start,ke.match_length-F),ke.lookahead-=ke.match_length,ke.match_length<=ke.max_lazy_match&&ke.lookahead>=F){for(ke.match_length--;ke.strstart++,ke.ins_h=(ke.ins_h<=F&&(ke.ins_h=(ke.ins_h<=F&&ke.match_length<=ke.prev_length){for($e=ke.strstart+ke.lookahead-F,He=o._tr_tally(ke,ke.strstart-1-ke.prev_match,ke.prev_length-F),ke.lookahead-=ke.prev_length-1,ke.prev_length-=2;++ke.strstart<=$e&&(ke.ins_h=(ke.ins_h<ke.pending_buf_size-5&&(je=ke.pending_buf_size-5);;){if(ke.lookahead<=1){if(Ce(ke),ke.lookahead===0&&it===h)return W;if(ke.lookahead===0)break}ke.strstart+=ke.lookahead,ke.lookahead=0;var He=ke.block_start+je;if((ke.strstart===0||ke.strstart>=He)&&(ke.lookahead=ke.strstart-He,ke.strstart=He,ve(ke,!1),ke.strm.avail_out===0)||ke.strstart-ke.block_start>=ke.w_size-H&&(ve(ke,!1),ke.strm.avail_out===0))return W}return ke.insert=0,it===p?(ve(ke,!0),ke.strm.avail_out===0?se:oe):(ke.strstart>ke.block_start&&(ve(ke,!1),ke.strm.avail_out),W)}),new Re(4,4,8,4,Me),new Re(4,5,16,8,Me),new Re(4,6,32,32,Me),new Re(4,4,16,16,Pe),new Re(8,16,32,32,Pe),new Re(8,16,128,128,Pe),new Re(8,32,128,256,Pe),new Re(32,128,258,1024,Pe),new Re(32,258,258,4096,Pe)],a.deflateInit=function(ke,it){return Je(ke,it,w,15,8,0)},a.deflateInit2=Je,a.deflateReset=we,a.deflateResetKeep=Be,a.deflateSetHeader=function(ke,it){return ke&&ke.state?ke.state.wrap!==2?y:(ke.state.gzhead=it,f):y},a.deflate=function(ke,it){var je,He,$e,Ke;if(!ke||!ke.state||5>8&255),ge(He,He.gzhead.time>>16&255),ge(He,He.gzhead.time>>24&255),ge(He,He.level===9?2:2<=He.strategy||He.level<2?4:0),ge(He,255&He.gzhead.os),He.gzhead.extra&&He.gzhead.extra.length&&(ge(He,255&He.gzhead.extra.length),ge(He,He.gzhead.extra.length>>8&255)),He.gzhead.hcrc&&(ke.adler=d(ke.adler,He.pending_buf,He.pending,0)),He.gzindex=0,He.status=69):(ge(He,0),ge(He,0),ge(He,0),ge(He,0),ge(He,0),ge(He,He.level===9?2:2<=He.strategy||He.level<2?4:0),ge(He,3),He.status=Y);else{var Ge=w+(He.w_bits-8<<4)<<8;Ge|=(2<=He.strategy||He.level<2?0:He.level<6?1:He.level===6?2:3)<<6,He.strstart!==0&&(Ge|=32),Ge+=31-Ge%31,He.status=Y,Te(He,Ge),He.strstart!==0&&(Te(He,ke.adler>>>16),Te(He,65535&ke.adler)),ke.adler=1}if(He.status===69)if(He.gzhead.extra){for($e=He.pending;He.gzindex<(65535&He.gzhead.extra.length)&&(He.pending!==He.pending_buf_size||(He.gzhead.hcrc&&He.pending>$e&&(ke.adler=d(ke.adler,He.pending_buf,He.pending-$e,$e)),le(ke),$e=He.pending,He.pending!==He.pending_buf_size));)ge(He,255&He.gzhead.extra[He.gzindex]),He.gzindex++;He.gzhead.hcrc&&He.pending>$e&&(ke.adler=d(ke.adler,He.pending_buf,He.pending-$e,$e)),He.gzindex===He.gzhead.extra.length&&(He.gzindex=0,He.status=73)}else He.status=73;if(He.status===73)if(He.gzhead.name){$e=He.pending;do{if(He.pending===He.pending_buf_size&&(He.gzhead.hcrc&&He.pending>$e&&(ke.adler=d(ke.adler,He.pending_buf,He.pending-$e,$e)),le(ke),$e=He.pending,He.pending===He.pending_buf_size)){Ke=1;break}Ke=He.gzindex$e&&(ke.adler=d(ke.adler,He.pending_buf,He.pending-$e,$e)),Ke===0&&(He.gzindex=0,He.status=91)}else He.status=91;if(He.status===91)if(He.gzhead.comment){$e=He.pending;do{if(He.pending===He.pending_buf_size&&(He.gzhead.hcrc&&He.pending>$e&&(ke.adler=d(ke.adler,He.pending_buf,He.pending-$e,$e)),le(ke),$e=He.pending,He.pending===He.pending_buf_size)){Ke=1;break}Ke=He.gzindex$e&&(ke.adler=d(ke.adler,He.pending_buf,He.pending-$e,$e)),Ke===0&&(He.status=103)}else He.status=103;if(He.status===103&&(He.gzhead.hcrc?(He.pending+2>He.pending_buf_size&&le(ke),He.pending+2<=He.pending_buf_size&&(ge(He,255&ke.adler),ge(He,ke.adler>>8&255),ke.adler=0,He.status=Y)):He.status=Y),He.pending!==0){if(le(ke),ke.avail_out===0)return He.last_flush=-1,f}else if(ke.avail_in===0&&ce(it)<=ce(je)&&it!==p)return he(ke,-5);if(He.status===666&&ke.avail_in!==0)return he(ke,-5);if(ke.avail_in!==0||He.lookahead!==0||it!==h&&He.status!==666){var rt=He.strategy===2?function(tt,at){for(var Ye;;){if(tt.lookahead===0&&(Ce(tt),tt.lookahead===0)){if(at===h)return W;break}if(tt.match_length=0,Ye=o._tr_tally(tt,0,tt.window[tt.strstart]),tt.lookahead--,tt.strstart++,Ye&&(ve(tt,!1),tt.strm.avail_out===0))return W}return tt.insert=0,at===p?(ve(tt,!0),tt.strm.avail_out===0?se:oe):tt.last_lit&&(ve(tt,!1),tt.strm.avail_out===0)?W:ee}(He,it):He.strategy===3?function(tt,at){for(var Ye,ut,_t,bt,$t=tt.window;;){if(tt.lookahead<=z){if(Ce(tt),tt.lookahead<=z&&at===h)return W;if(tt.lookahead===0)break}if(tt.match_length=0,tt.lookahead>=F&&0tt.lookahead&&(tt.match_length=tt.lookahead)}if(tt.match_length>=F?(Ye=o._tr_tally(tt,1,tt.match_length-F),tt.lookahead-=tt.match_length,tt.strstart+=tt.match_length,tt.match_length=0):(Ye=o._tr_tally(tt,0,tt.window[tt.strstart]),tt.lookahead--,tt.strstart++),Ye&&(ve(tt,!1),tt.strm.avail_out===0))return W}return tt.insert=0,at===p?(ve(tt,!0),tt.strm.avail_out===0?se:oe):tt.last_lit&&(ve(tt,!1),tt.strm.avail_out===0)?W:ee}(He,it):i[He.level].func(He,it);if(rt!==se&&rt!==oe||(He.status=666),rt===W||rt===se)return ke.avail_out===0&&(He.last_flush=-1),f;if(rt===ee&&(it===1?o._tr_align(He):it!==5&&(o._tr_stored_block(He,0,0,!1),it===3&&(me(He.head),He.lookahead===0&&(He.strstart=0,He.block_start=0,He.insert=0))),le(ke),ke.avail_out===0))return He.last_flush=-1,f}return it!==p?f:He.wrap<=0?1:(He.wrap===2?(ge(He,255&ke.adler),ge(He,ke.adler>>8&255),ge(He,ke.adler>>16&255),ge(He,ke.adler>>24&255),ge(He,255&ke.total_in),ge(He,ke.total_in>>8&255),ge(He,ke.total_in>>16&255),ge(He,ke.total_in>>24&255)):(Te(He,ke.adler>>>16),Te(He,65535&ke.adler)),le(ke),0=je.w_size&&(Ke===0&&(me(je.head),je.strstart=0,je.block_start=0,je.insert=0),at=new l.Buf8(je.w_size),l.arraySet(at,it,Ye-je.w_size,je.w_size,0),it=at,Ye=je.w_size),Ge=ke.avail_in,rt=ke.next_in,tt=ke.input,ke.avail_in=Ye,ke.next_in=0,ke.input=it,Ce(je);je.lookahead>=F;){for(He=je.strstart,$e=je.lookahead-(F-1);je.ins_h=(je.ins_h<>>=F=I>>>24,S-=F,(F=I>>>16&255)===0)ee[u++]=65535&I;else{if(!(16&F)){if(!(64&F)){I=A[(65535&I)+(w&(1<>>=F,S-=F),S<15&&(w+=W[c++]<>>=F=I>>>24,S-=F,!(16&(F=I>>>16&255))){if(!(64&F)){I=E[(65535&I)+(w&(1<>>=F,S-=F,(F=u-h)>3,w&=(1<<(S-=z<<3))-1,i.next_in=c,i.next_out=u,i.avail_in=c>>24&255)+(Z>>>8&65280)+((65280&Z)<<8)+((255&Z)<<24)}function w(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function S(Z){var Y;return Z&&Z.state?(Y=Z.state,Z.total_in=Z.total_out=Y.total=0,Z.msg="",Y.wrap&&(Z.adler=1&Y.wrap),Y.mode=y,Y.last=0,Y.havedict=0,Y.dmax=32768,Y.head=null,Y.hold=0,Y.bits=0,Y.lencode=Y.lendyn=new i.Buf32(_),Y.distcode=Y.distdyn=new i.Buf32(v),Y.sane=1,Y.back=-1,p):f}function A(Z){var Y;return Z&&Z.state?((Y=Z.state).wsize=0,Y.whave=0,Y.wnext=0,S(Z)):f}function E(Z,Y){var W,ee;return Z&&Z.state?(ee=Z.state,Y<0?(W=0,Y=-Y):(W=1+(Y>>4),Y<48&&(Y&=15)),Y&&(Y<8||15=oe.wsize?(i.arraySet(oe.window,Y,W-oe.wsize,oe.wsize,0),oe.wnext=0,oe.whave=oe.wsize):(ee<(se=oe.wsize-oe.wnext)&&(se=ee),i.arraySet(oe.window,Y,W-ee,se,oe.wnext),(ee-=se)?(i.arraySet(oe.window,Y,W-ee,ee,0),oe.wnext=ee,oe.whave=oe.wsize):(oe.wnext+=se,oe.wnext===oe.wsize&&(oe.wnext=0),oe.whave>>8&255,W.check=o(W.check,Ke,2,0),ve=le=0,W.mode=2;break}if(W.flags=0,W.head&&(W.head.done=!1),!(1&W.wrap)||(((255&le)<<8)+(le>>8))%31){Z.msg="incorrect header check",W.mode=30;break}if((15&le)!=8){Z.msg="unknown compression method",W.mode=30;break}if(ve-=4,ke=8+(15&(le>>>=4)),W.wbits===0)W.wbits=ke;else if(ke>W.wbits){Z.msg="invalid window size",W.mode=30;break}W.dmax=1<>8&1),512&W.flags&&(Ke[0]=255&le,Ke[1]=le>>>8&255,W.check=o(W.check,Ke,2,0)),ve=le=0,W.mode=3;case 3:for(;ve<32;){if(ce===0)break e;ce--,le+=ee[oe++]<>>8&255,Ke[2]=le>>>16&255,Ke[3]=le>>>24&255,W.check=o(W.check,Ke,4,0)),ve=le=0,W.mode=4;case 4:for(;ve<16;){if(ce===0)break e;ce--,le+=ee[oe++]<>8),512&W.flags&&(Ke[0]=255&le,Ke[1]=le>>>8&255,W.check=o(W.check,Ke,2,0)),ve=le=0,W.mode=5;case 5:if(1024&W.flags){for(;ve<16;){if(ce===0)break e;ce--,le+=ee[oe++]<>>8&255,W.check=o(W.check,Ke,2,0)),ve=le=0}else W.head&&(W.head.extra=null);W.mode=6;case 6:if(1024&W.flags&&(ce<(Ie=W.length)&&(Ie=ce),Ie&&(W.head&&(ke=W.head.extra_len-W.length,W.head.extra||(W.head.extra=new Array(W.head.extra_len)),i.arraySet(W.head.extra,ee,oe,Ie,ke)),512&W.flags&&(W.check=o(W.check,ee,Ie,oe)),ce-=Ie,oe+=Ie,W.length-=Ie),W.length))break e;W.length=0,W.mode=7;case 7:if(2048&W.flags){if(ce===0)break e;for(Ie=0;ke=ee[oe+Ie++],W.head&&ke&&W.length<65536&&(W.head.name+=String.fromCharCode(ke)),ke&&Ie>9&1,W.head.done=!0),Z.adler=W.check=0,W.mode=12;break;case 10:for(;ve<32;){if(ce===0)break e;ce--,le+=ee[oe++]<>>=7&ve,ve-=7&ve,W.mode=27;break}for(;ve<3;){if(ce===0)break e;ce--,le+=ee[oe++]<>>=1)){case 0:W.mode=14;break;case 1:if(z(W),W.mode=20,Y!==6)break;le>>>=2,ve-=2;break e;case 2:W.mode=17;break;case 3:Z.msg="invalid block type",W.mode=30}le>>>=2,ve-=2;break;case 14:for(le>>>=7&ve,ve-=7&ve;ve<32;){if(ce===0)break e;ce--,le+=ee[oe++]<>>16^65535)){Z.msg="invalid stored block lengths",W.mode=30;break}if(W.length=65535&le,ve=le=0,W.mode=15,Y===6)break e;case 15:W.mode=16;case 16:if(Ie=W.length){if(ce>>=5,ve-=5,W.ndist=1+(31&le),le>>>=5,ve-=5,W.ncode=4+(15&le),le>>>=4,ve-=4,286>>=3,ve-=3}for(;W.have<19;)W.lens[Ge[W.have++]]=0;if(W.lencode=W.lendyn,W.lenbits=7,je={bits:W.lenbits},it=d(0,W.lens,0,19,W.lencode,0,W.work,je),W.lenbits=je.bits,it){Z.msg="invalid code lengths set",W.mode=30;break}W.have=0,W.mode=19;case 19:for(;W.have>>16&255,Ae=65535&$e,!((Pe=$e>>>24)<=ve);){if(ce===0)break e;ce--,le+=ee[oe++]<>>=Pe,ve-=Pe,W.lens[W.have++]=Ae;else{if(Ae===16){for(He=Pe+2;ve>>=Pe,ve-=Pe,W.have===0){Z.msg="invalid bit length repeat",W.mode=30;break}ke=W.lens[W.have-1],Ie=3+(3&le),le>>>=2,ve-=2}else if(Ae===17){for(He=Pe+3;ve>>=Pe)),le>>>=3,ve-=3}else{for(He=Pe+7;ve>>=Pe)),le>>>=7,ve-=7}if(W.have+Ie>W.nlen+W.ndist){Z.msg="invalid bit length repeat",W.mode=30;break}for(;Ie--;)W.lens[W.have++]=ke}}if(W.mode===30)break;if(W.lens[256]===0){Z.msg="invalid code -- missing end-of-block",W.mode=30;break}if(W.lenbits=9,je={bits:W.lenbits},it=d(u,W.lens,0,W.nlen,W.lencode,0,W.work,je),W.lenbits=je.bits,it){Z.msg="invalid literal/lengths set",W.mode=30;break}if(W.distbits=6,W.distcode=W.distdyn,je={bits:W.distbits},it=d(h,W.lens,W.nlen,W.ndist,W.distcode,0,W.work,je),W.distbits=je.bits,it){Z.msg="invalid distances set",W.mode=30;break}if(W.mode=20,Y===6)break e;case 20:W.mode=21;case 21:if(6<=ce&&258<=me){Z.next_out=he,Z.avail_out=me,Z.next_in=oe,Z.avail_in=ce,W.hold=le,W.bits=ve,c(Z,Te),he=Z.next_out,se=Z.output,me=Z.avail_out,oe=Z.next_in,ee=Z.input,ce=Z.avail_in,le=W.hold,ve=W.bits,W.mode===12&&(W.back=-1);break}for(W.back=0;Re=($e=W.lencode[le&(1<>>16&255,Ae=65535&$e,!((Pe=$e>>>24)<=ve);){if(ce===0)break e;ce--,le+=ee[oe++]<>Be)])>>>16&255,Ae=65535&$e,!(Be+(Pe=$e>>>24)<=ve);){if(ce===0)break e;ce--,le+=ee[oe++]<>>=Be,ve-=Be,W.back+=Be}if(le>>>=Pe,ve-=Pe,W.back+=Pe,W.length=Ae,Re===0){W.mode=26;break}if(32&Re){W.back=-1,W.mode=12;break}if(64&Re){Z.msg="invalid literal/length code",W.mode=30;break}W.extra=15&Re,W.mode=22;case 22:if(W.extra){for(He=W.extra;ve>>=W.extra,ve-=W.extra,W.back+=W.extra}W.was=W.length,W.mode=23;case 23:for(;Re=($e=W.distcode[le&(1<>>16&255,Ae=65535&$e,!((Pe=$e>>>24)<=ve);){if(ce===0)break e;ce--,le+=ee[oe++]<>Be)])>>>16&255,Ae=65535&$e,!(Be+(Pe=$e>>>24)<=ve);){if(ce===0)break e;ce--,le+=ee[oe++]<>>=Be,ve-=Be,W.back+=Be}if(le>>>=Pe,ve-=Pe,W.back+=Pe,64&Re){Z.msg="invalid distance code",W.mode=30;break}W.offset=Ae,W.extra=15&Re,W.mode=24;case 24:if(W.extra){for(He=W.extra;ve>>=W.extra,ve-=W.extra,W.back+=W.extra}if(W.offset>W.dmax){Z.msg="invalid distance too far back",W.mode=30;break}W.mode=25;case 25:if(me===0)break e;if(Ie=Te-me,W.offset>Ie){if((Ie=W.offset-Ie)>W.whave&&W.sane){Z.msg="invalid distance too far back",W.mode=30;break}Ce=Ie>W.wnext?(Ie-=W.wnext,W.wsize-Ie):W.wnext-Ie,Ie>W.length&&(Ie=W.length),Me=W.window}else Me=se,Ce=he-W.offset,Ie=W.length;for(meD?(F=Ce[Me+v[Y]],ve[ge+v[Y]]):(F=96,0),w=1<>he)+(S-=w)]=I<<24|F<<16|z|0,S!==0;);for(w=1<>=1;if(w!==0?(le&=w-1,le+=w):le=0,Y++,--Te[Z]==0){if(Z===ee)break;Z=h[p+v[Y]]}if(se>>7)]}function ge($e,Ke){$e.pending_buf[$e.pending++]=255&Ke,$e.pending_buf[$e.pending++]=Ke>>>8&255}function Te($e,Ke,Ge){$e.bi_valid>j-Ge?($e.bi_buf|=Ke<<$e.bi_valid&65535,ge($e,$e.bi_buf),$e.bi_buf=Ke>>j-$e.bi_valid,$e.bi_valid+=Ge-j):($e.bi_buf|=Ke<<$e.bi_valid&65535,$e.bi_valid+=Ge)}function Ie($e,Ke,Ge){Te($e,Ge[2*Ke],Ge[2*Ke+1])}function Ce($e,Ke){for(var Ge=0;Ge|=1&$e,$e>>>=1,Ge<<=1,0<--Ke;);return Ge>>>1}function Me($e,Ke,Ge){var rt,tt,at=new Array(v+1),Ye=0;for(rt=1;rt<=v;rt++)at[rt]=Ye=Ye+Ge[rt-1]<<1;for(tt=0;tt<=Ke;tt++){var ut=$e[2*tt+1];ut!==0&&($e[2*tt]=Ce(at[ut]++,ut))}}function Pe($e){var Ke;for(Ke=0;Ke>1;1<=Ge;Ge--)Be($e,at,Ge);for(tt=_t;Ge=$e.heap[1],$e.heap[1]=$e.heap[$e.heap_len--],Be($e,at,1),rt=$e.heap[1],$e.heap[--$e.heap_max]=Ge,$e.heap[--$e.heap_max]=rt,at[2*tt]=at[2*Ge]+at[2*rt],$e.depth[tt]=($e.depth[Ge]>=$e.depth[rt]?$e.depth[Ge]:$e.depth[rt])+1,at[2*Ge+1]=at[2*rt+1]=tt,$e.heap[1]=tt++,Be($e,at,1),2<=$e.heap_len;);$e.heap[--$e.heap_max]=$e.heap[1],function($t,Yt){var Ds,Ls,xs,Lt,Jt,gt,zt=Yt.dyn_tree,As=Yt.max_code,Xt=Yt.stat_desc.static_tree,Qs=Yt.stat_desc.has_stree,ks=Yt.stat_desc.extra_bits,$s=Yt.stat_desc.extra_base,an=Yt.stat_desc.max_length,tn=0;for(Lt=0;Lt<=v;Lt++)$t.bl_count[Lt]=0;for(zt[2*$t.heap[$t.heap_max]+1]=0,Ds=$t.heap_max+1;Ds<_;Ds++)an<(Lt=zt[2*zt[2*(Ls=$t.heap[Ds])+1]+1]+1)&&(Lt=an,tn++),zt[2*Ls+1]=Lt,As>=7;tt>>=1)if(1&bt&&ut.dyn_ltree[2*_t]!==0)return l;if(ut.dyn_ltree[18]!==0||ut.dyn_ltree[20]!==0||ut.dyn_ltree[26]!==0)return o;for(_t=32;_t>>3,(at=$e.static_len+3+7>>>3)<=tt&&(tt=at)):tt=at=Ge+5,Ge+4<=tt&&Ke!==-1?He($e,Ke,Ge,rt):$e.strategy===4||at===tt?(Te($e,2+(rt?1:0),3),we($e,H,Z)):(Te($e,4+(rt?1:0),3),function(ut,_t,bt,$t){var Yt;for(Te(ut,_t-257,5),Te(ut,bt-1,5),Te(ut,$t-4,4),Yt=0;Yt<$t;Yt++)Te(ut,ut.bl_tree[2*z[Yt]+1],3);it(ut,ut.dyn_ltree,_t-1),it(ut,ut.dyn_dtree,bt-1)}($e,$e.l_desc.max_code+1,$e.d_desc.max_code+1,Ye+1),we($e,$e.dyn_ltree,$e.dyn_dtree)),Pe($e),rt&&Re($e)},a._tr_tally=function($e,Ke,Ge){return $e.pending_buf[$e.d_buf+2*$e.last_lit]=Ke>>>8&255,$e.pending_buf[$e.d_buf+2*$e.last_lit+1]=255&Ke,$e.pending_buf[$e.l_buf+$e.last_lit]=255&Ge,$e.last_lit++,Ke===0?$e.dyn_ltree[2*Ge]++:($e.matches++,Ke--,$e.dyn_ltree[2*(W[Ge]+h+1)]++,$e.dyn_dtree[2*ve(Ke)]++),$e.last_lit===$e.lit_bufsize-1},a._tr_align=function($e){Te($e,2,3),Ie($e,S,H),function(Ke){Ke.bi_valid===16?(ge(Ke,Ke.bi_buf),Ke.bi_buf=0,Ke.bi_valid=0):8<=Ke.bi_valid&&(Ke.pending_buf[Ke.pending++]=255&Ke.bi_buf,Ke.bi_buf>>=8,Ke.bi_valid-=8)}($e)}},{"../utils/common":41}],53:[function(n,r,a){r.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(n,r,a){(function(i){(function(l,o){if(!l.setImmediate){var c,d,u,h,p=1,f={},y=!1,_=l.document,v=Object.getPrototypeOf&&Object.getPrototypeOf(l);v=v&&v.setTimeout?v:l,c={}.toString.call(l.process)==="[object process]"?function(A){process.nextTick(function(){w(A)})}:function(){if(l.postMessage&&!l.importScripts){var A=!0,E=l.onmessage;return l.onmessage=function(){A=!1},l.postMessage("","*"),l.onmessage=E,A}}()?(h="setImmediate$"+Math.random()+"$",l.addEventListener?l.addEventListener("message",S,!1):l.attachEvent("onmessage",S),function(A){l.postMessage(h+A,"*")}):l.MessageChannel?((u=new MessageChannel).port1.onmessage=function(A){w(A.data)},function(A){u.port2.postMessage(A)}):_&&"onreadystatechange"in _.createElement("script")?(d=_.documentElement,function(A){var E=_.createElement("script");E.onreadystatechange=function(){w(A),E.onreadystatechange=null,d.removeChild(E),E=null},d.appendChild(E)}):function(A){setTimeout(w,0,A)},v.setImmediate=function(A){typeof A!="function"&&(A=new Function(""+A));for(var E=new Array(arguments.length-1),O=0;O"u"?i===void 0?this:i:self)}).call(this,typeof kh<"u"?kh:typeof self<"u"?self:typeof window<"u"?window:{})},{}]},{},[10])(10)})})(dgt);var Axs=dgt.exports;const ugt=_l(Axs);function o2e(s,t=400,n=75){return s&&`${s.replace("/storage/v1/object/public/","/storage/v1/render/image/public/")}?width=${t}&quality=${n}&resize=contain`}const Mxs=()=>{vs();const[s,t]=N.useState(null),[n,r]=N.useState(null),[a,i]=N.useState("all"),[l,o]=N.useState(new Set),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState("images"),[y,_]=N.useState(null),{data:v=[],isLoading:j}=dt({queryKey:["social-swag-2"],queryFn:async()=>{const{data:he,error:ce}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(ce)throw ce;return he}}),{data:w=[]}=dt({queryKey:["social-swag-2-months"],queryFn:async()=>{const{data:he,error:ce}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(ce)throw ce;return he}}),{data:S=[]}=dt({queryKey:["social-swag-2-reels"],queryFn:async()=>{const{data:he,error:ce}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(ce)throw ce;return he}}),{data:A=[]}=dt({queryKey:["my-social-accounts-count"],queryFn:async()=>{const{data:he,error:ce}=await q.from("social_accounts").select("id, platform").eq("is_active",!0);if(ce)throw ce;return he||[]}}),E=A.length>0,O=N.useMemo(()=>a==="all"?null:S.find(he=>he.month===a)||null,[a,S]),D=N.useMemo(()=>[...new Set(v.map(ce=>ce.month))].sort((ce,me)=>me.localeCompare(ce)),[v]);N.useEffect(()=>{D.length>0&&a==="all"&&i(D[0])},[D,a]);const I=he=>{try{const ce=qAe(he,"yyyy-MM",new Date);return Ss(ce,"MMMM yyyy")}catch{return he}},F=N.useMemo(()=>a==="all"?v:v.filter(he=>he.month===a),[a,v]),z=N.useMemo(()=>{var he;return a==="all"?null:((he=w.find(ce=>ce.month===a))==null?void 0:he.canva_link)||null},[a,w]),H=async he=>{try{await navigator.clipboard.writeText(he),ae.success("Caption copied to clipboard!")}catch{ae.error("Failed to copy caption")}},Z=async(he,ce)=>{try{const le=await(await fetch(he)).blob(),ve=/iPhone|iPad|iPod|Android/i.test(navigator.userAgent),ge=navigator.canShare&&navigator.canShare({files:[new File([le],"test.jpg",{type:"image/jpeg"})]});if(ve&&ge){const Te=new File([le],`social-swag-${ce}.jpg`,{type:"image/jpeg"});await navigator.share({files:[Te],title:"Social Swag Image"}),ae.success("Image ready to save!")}else{const Te=window.URL.createObjectURL(le),Ie=document.createElement("a");Ie.href=Te,Ie.download=`social-swag-${ce}.jpg`,document.body.appendChild(Ie),Ie.click(),document.body.removeChild(Ie),window.URL.revokeObjectURL(Te),ae.success("Image downloaded!")}}catch(me){me.name!=="AbortError"&&ae.error("Failed to download image")}},Y=he=>{o(ce=>{const me=new Set(ce);return me.has(he)?me.delete(he):me.add(he),me})},W=()=>{o(new Set(F.map(he=>he.id)))},ee=()=>{o(new Set),d(!1)},se=async()=>{const he=F.filter(ce=>l.has(ce.id));if(he.length===0){ae.error("No images selected");return}h(!0),ae.info(`Preparing ${he.length} images for download...`);try{const ce=new ugt,me=[...he].sort((Ie,Ce)=>Ie.sort_order-Ce.sort_order);for(let Ie=0;Ie{c?Y(he.id):t(he)};return e.jsx(Cs,{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(Ue,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"New content monthly"]}),e.jsxs(Ue,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"}),v.length," images"]})]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3",children:"Social Swag 📸"}),e.jsx("p",{className:"text-lg text-primary-foreground/90 max-w-2xl",children:"Ready-to-post social media images delivered to you monthly. Just download, copy the caption, and share with your audience!"})]})]}),e.jsxs(Fr,{defaultValue:"gallery",className:"space-y-6",children:[e.jsxs(Rr,{className:"grid w-full max-w-md grid-cols-2",children:[e.jsxs(Zt,{value:"gallery",className:"gap-2",children:[e.jsx(Xo,{className:"h-4 w-4"}),"Gallery"]}),e.jsxs(Zt,{value:"scheduled",className:"gap-2",children:[e.jsx(Cl,{className:"h-4 w-4"}),"Scheduled"]})]}),e.jsxs(is,{value:"gallery",className:"space-y-6",children:[E?e.jsx(fe,{className:"border rounded-xl",children:e.jsx(Ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-muted text-2xl",children:"📸"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Ready to post!"}),e.jsx("p",{className:"text-muted-foreground",children:'Click any image and use "Create Post" to share directly to your connected accounts.'})]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"gap-2",children:e.jsx(In,{to:"/mission-control/integrations",children:"Manage Accounts"})})]})})}):e.jsx(fe,{className:"border-2 border-dashed border-primary/30 bg-gradient-to-r from-pink-500/5 via-purple-500/5 to-blue-500/5 rounded-xl",children:e.jsx(Ee,{className:"p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-2 rounded-full bg-blue-500/10",children:e.jsx(Mh,{className:"h-5 w-5 text-blue-600"})}),e.jsx("div",{className:"p-2 rounded-full bg-pink-500/10",children:e.jsx(ou,{className:"h-5 w-5 text-pink-600"})})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-foreground mb-1",children:"Post directly to social media"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Connect your Facebook & Instagram accounts to post images with one click!"})]}),e.jsx(B,{asChild:!0,className:"gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600",children:e.jsxs(In,{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:D.map(he=>e.jsx("button",{onClick:()=>i(he),className:Mt("px-4 py-2 rounded-full text-sm font-medium transition-all",a===he?"bg-primary text-primary-foreground shadow-sm":"bg-muted text-muted-foreground hover:text-foreground"),children:I(he)},he))}),a!=="all"&&(z?e.jsxs("a",{href:z,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("span",{className:"text-base",children:"🎨"}),"Edit ",I(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 ",I(a)," Images in Canva"]}))]}),e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-1 p-1 bg-muted rounded-full",children:[e.jsxs("button",{onClick:()=>{f("images"),ee()},className:Mt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",p==="images"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Xo,{className:"h-4 w-4"}),"Images"]}),e.jsxs("button",{onClick:()=>{f("reels"),ee()},className:Mt("flex items-center gap-2 px-4 py-2 rounded-full text-sm font-medium transition-all",p==="reels"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:[e.jsx(Sh,{className:"h-4 w-4"}),"Reels"]})]}),p==="images"&&e.jsx("div",{className:"flex flex-wrap items-center gap-3",children:c?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:W,className:"gap-2",children:["Select All (",F.length,")"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ee,className:"gap-2",children:[e.jsx($n,{className:"h-4 w-4"}),"Cancel"]}),l.size>0&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{size:"sm",onClick:se,disabled:u,className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),u?"Downloading...":`Download ${l.size} Selected`]}),e.jsx("span",{className:"text-xs text-muted-foreground hidden sm:inline",children:"Please ensure your browser allows downloads from the LevelUp Dashboard."})]})]}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>d(!0),className:"gap-2",children:[e.jsx(Lr,{className:"h-4 w-4"}),"Select Images"]})})]}),j&&e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}),!j&&p==="images"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:F.map(he=>{const ce=l.has(he.id);return e.jsx(fe,{className:Mt("group cursor-pointer overflow-hidden border-0 shadow-md hover:shadow-xl transition-all duration-300 rounded-2xl",c&&ce&&"ring-2 ring-primary ring-offset-2"),onClick:()=>oe(he),children:e.jsxs("div",{className:"relative aspect-[4/5] overflow-hidden",children:[e.jsx("img",{src:o2e(he.image_url,400,75),alt:"Social swag",className:"w-full h-full object-cover transition-transform duration-300 group-hover:scale-110",loading:"lazy",decoding:"async"}),he.post_date&&!c&&e.jsx("div",{className:"absolute top-0 left-0 w-24 h-24 overflow-hidden pointer-events-none",children:e.jsx("div",{className:"absolute flex items-center justify-center text-white font-bold text-[10px] tracking-wider uppercase",style:{top:"20px",left:"-34px",width:"136px",transform:"rotate(-45deg)",backgroundColor:"#2d5052",padding:"5px 0",boxShadow:"0 2px 4px rgba(0,0,0,0.25)"},children:Ss(new Date(he.post_date+"T00:00:00"),"MMM d")})}),c&&e.jsx("div",{className:Mt("absolute top-2 right-2 w-6 h-6 rounded-full border-2 flex items-center justify-center transition-all",ce?"bg-primary border-primary text-primary-foreground":"bg-white/80 border-muted-foreground/50"),children:ce&&e.jsx(Lr,{className:"h-4 w-4"})}),!c&&e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/40 transition-colors duration-300 flex items-center justify-center",children:e.jsx("span",{className:"text-white font-medium opacity-0 group-hover:opacity-100 transition-opacity duration-300 bg-primary px-4 py-2 rounded-full text-sm",children:"View Details"})})]})},he.id)})}),F.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Xo,{className:"h-12 w-12 text-muted-foreground/50 mx-auto mb-4"}),e.jsx("p",{className:"text-muted-foreground",children:"No images available for this month yet."})]})]}),!j&&p==="reels"&&e.jsx(e.Fragment,{children:O?e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5 xl:grid-cols-6 gap-4",children:e.jsx(fe,{className:"group overflow-hidden rounded-2xl cursor-pointer transition-all duration-300 hover:shadow-xl hover:scale-[1.02]",onClick:()=>r(O),children:e.jsxs("div",{className:"relative aspect-[9/16] overflow-hidden",children:[e.jsx("img",{src:o2e(O.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(Ue,{variant:"secondary",className:"bg-black/50 text-white border-0 backdrop-blur-sm text-xs",children:[e.jsx(Sh,{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(Sh,{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(_s,{open:!!s,onOpenChange:()=>t(null),children:e.jsx(bs,{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:o2e(s.image_url,900,85),alt:"Social swag",className:"w-full h-full object-cover",decoding:"async"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm text-muted-foreground mb-4",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-4 w-4"}),Ss(new Date(s.created_at),"MMMM d, yyyy")]}),s.post_date&&e.jsxs("span",{className:"inline-flex items-center gap-1.5 font-medium rounded-full px-3 py-1 text-xs text-white",style:{background:"#406E71"},children:[e.jsx(yr,{className:"h-3.5 w-3.5"}),"Post on ",Ss(new Date(s.post_date+"T00:00:00"),"MMMM d, yyyy")]})]}),e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:s.caption})})]}),e.jsxs("div",{className:"flex flex-col gap-3 mt-6",children:[e.jsxs(B,{onClick:()=>{_({imageUrl:s.image_url,imageId:s.id,caption:s.caption})},className:"w-full gap-2 bg-gradient-to-r from-pink-500 via-purple-500 to-blue-500 hover:from-pink-600 hover:via-purple-600 hover:to-blue-600 text-white",children:[e.jsx(lr,{className:"h-4 w-4"}),"Create Post"]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(B,{variant:"outline",onClick:()=>H(s.caption),className:"flex-1 gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Copy Caption"]}),e.jsxs(B,{variant:"outline",onClick:()=>Z(s.image_url,s.id),className:"flex-1 gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Download"]})]})]})]})]})})})}),e.jsx(_s,{open:!!n,onOpenChange:()=>r(null),children:e.jsx(bs,{className:"max-w-4xl max-h-[90vh] overflow-hidden p-0",children:e.jsx("div",{className:"max-h-[90vh] overflow-y-auto touch-pan-y",style:{WebkitOverflowScrolling:"touch"},children:n&&e.jsxs("div",{className:"flex flex-col md:flex-row",children:[e.jsx("div",{className:"md:w-1/2 bg-black flex items-center justify-center",children:e.jsx("div",{className:"aspect-[9/16] max-h-[70vh]",children:e.jsx("img",{src:n.image_url,alt:"Reel preview",className:"w-full h-full object-contain"})})}),e.jsxs("div",{className:"md:w-1/2 p-6 flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-4",children:[e.jsx(Sh,{className:"h-4 w-4"}),"Monthly Reel"]}),n.caption&&e.jsxs("div",{className:"flex-1 min-h-0",children:[e.jsx("h4",{className:"text-sm font-medium text-foreground mb-2",children:"Caption"}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-4 max-h-64 overflow-y-auto",children:e.jsx("p",{className:"text-sm text-foreground whitespace-pre-wrap",children:n.caption})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3 mt-6",children:[n.caption&&e.jsxs(B,{onClick:()=>H(n.caption||""),className:"flex-1 gap-2",children:[e.jsx(Zr,{className:"h-4 w-4"}),"Copy Caption"]}),n.canva_link&&e.jsxs(B,{variant:"outline",onClick:()=>window.open(n.canva_link,"_blank"),className:"flex-1 gap-2",children:[e.jsx(tr,{className:"h-4 w-4"}),"Open in Canva"]})]})]})]})})})}),e.jsx(Txs,{open:!!y,onOpenChange:he=>!he&&_(null),imageUrl:(y==null?void 0:y.imageUrl)||"",imageId:(y==null?void 0:y.imageId)||"",defaultCaption:(y==null?void 0:y.caption)||"",swagItemId:y==null?void 0:y.imageId})]}),e.jsx(is,{value:"scheduled",children:e.jsx(Exs,{})})]})]})})},Ixs=[{id:"branding-bar",title:"Branding Bar Studio",description:"Drop in any image — get a branded version with your headshot, logo, and contact info.",icon:Xo,to:"/marketing-studio/branding-bar",color:"from-violet-500 to-fuchsia-500"},{id:"listing-templates",title:"Listing Templates",description:"Just Listed, Just Sold, Open House, Price Drop — pulled from your MLS in one click.",icon:Or,to:"/marketing-studio/listing-templates",color:"from-blue-500 to-cyan-500"},{id:"personal-branding",title:"Personal Branding",description:'"Meet your agent", testimonials, milestones, pro tips — four editorial styles.',icon:Wi,to:"/marketing-studio/personal-branding",color:"from-emerald-500 to-teal-500"},{id:"market-updates",title:"Market Updates",description:"Auto-built from your MLS data — median price, days on market, year-over-year.",icon:_o,comingSoon:!0,color:"from-orange-500 to-red-500"},{id:"milestones",title:"Client Milestones",description:"Closing day, home anniversaries, birthdays, referral thank-yous.",icon:Ah,comingSoon:!0,color:"from-pink-500 to-rose-500"},{id:"holiday",title:"Holiday & Seasonal",description:"Pre-designed templates for every holiday, restyled to your brand.",icon:Tv,comingSoon:!0,color:"from-sky-500 to-indigo-500"},{id:"testimonial",title:"Testimonial Generator",description:"Paste a Zillow or Google review → branded testimonial graphic.",icon:xw,comingSoon:!0,color:"from-amber-500 to-yellow-500"}];function Pxs(){return e.jsx(Cs,{title:"Marketing Studio",children:e.jsxs("div",{className:"container max-w-6xl py-8 space-y-6",children:[e.jsxs(Zo,{children:[e.jsx("title",{children:"Marketing Studio | LevelUp"}),e.jsx("meta",{name:"description",content:"Brand any image, video, listing, or milestone in seconds — no AI credits used."})]}),e.jsxs("div",{className:"flex flex-col md:flex-row md:items-end md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsxs(Ue,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," New"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold tracking-tight",children:"Marketing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-2xl mt-1",children:"Your one-stop creative hub. Drop in any photo or video, and walk away with a fully branded export — no design skills, no AI credits."})]}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs(In,{to:"/marketing-studio/brand-kit",children:[e.jsx(pl,{className:"h-4 w-4 mr-1"})," Manage Brand Kit"]})})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:Ixs.map(s=>{const t=s.icon,n=e.jsxs(fe,{className:`group relative overflow-hidden transition-all h-full ${s.comingSoon?"opacity-70":"hover:shadow-xl hover:-translate-y-0.5 cursor-pointer"}`,children:[e.jsx("div",{className:`absolute inset-x-0 top-0 h-1 bg-gradient-to-r ${s.color}`}),e.jsxs(Ee,{className:"p-5 space-y-3",children:[e.jsx("div",{className:`inline-flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br ${s.color} text-white shadow-md`,children:e.jsx(t,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold",children:s.title}),s.comingSoon&&e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:"Coming soon"})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:s.description})]})]})]});return s.to&&!s.comingSoon?e.jsx(In,{to:s.to,className:"block",children:n},s.id):e.jsx("div",{children:n},s.id)})})]})})}function pU(){const s=wa();return dt({queryKey:["marketing-brand-presets",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("marketing_brand_presets").select("*").eq("user_id",s).order("is_default",{ascending:!1}).order("created_at",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function Lxs(){const{data:s,...t}=pU();return{data:(s==null?void 0:s.find(n=>n.is_default))??(s==null?void 0:s[0])??null,...t}}function Dxs(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not signed in");if(n.is_default&&await q.from("marketing_brand_presets").update({is_default:!1}).eq("user_id",s),n.id){const{id:r,...a}=n,{data:i,error:l}=await q.from("marketing_brand_presets").update(a).eq("id",r).eq("user_id",s).select().single();if(l)throw l;return i}else{const{data:r,error:a}=await q.from("marketing_brand_presets").insert({...n,user_id:s}).select().single();if(a)throw a;return r}},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}function Rxs(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{const{error:r}=await q.from("marketing_brand_presets").delete().eq("id",n);if(r)throw r},onSuccess:()=>t.invalidateQueries({queryKey:["marketing-brand-presets",s]})})}async function Oxs(s,t,n){var o;const r=((o=t.name.split(".").pop())==null?void 0:o.toLowerCase())||"png",a=`${s}/${n}-${Date.now()}.${r}`,{error:i}=await q.storage.from("marketing-studio-uploads").upload(a,t,{upsert:!0,cacheControl:"3600"});if(i)throw i;const{data:l}=await q.storage.from("marketing-studio-uploads").createSignedUrl(a,60*60*24*365*5);return(l==null?void 0:l.signedUrl)??""}function Fxs({preset:s,onSaved:t,onCancel:n}){var _;const r=wa(),a=Dxs(),i=Rxs(),l=N.useRef(null),o=N.useRef(null),[c,d]=N.useState(null),[u,h]=N.useState({name:(s==null?void 0:s.name)??"My Brand",is_default:(s==null?void 0:s.is_default)??!0,display_name:(s==null?void 0:s.display_name)??"",phone:(s==null?void 0:s.phone)??"",email:(s==null?void 0:s.email)??"",license_number:(s==null?void 0:s.license_number)??"",tagline:(s==null?void 0:s.tagline)??"",website_url:(s==null?void 0:s.website_url)??"",headshot_url:(s==null?void 0:s.headshot_url)??"",brokerage_logo_url:(s==null?void 0:s.brokerage_logo_url)??"",brand_color:(s==null?void 0:s.brand_color)??"#0f172a",accent_color:(s==null?void 0:s.accent_color)??"#3b82f6"});N.useEffect(()=>{s||(async()=>{if(!r)return;const{supabase:v}=await xi(async()=>{const{supabase:w}=await Promise.resolve().then(()=>kRt);return{supabase:w}},void 0),{data:j}=await v.from("profiles").select("name, email, phone, avatar_url, website_url, title, brokerage_id").eq("id",r).maybeSingle();j&&h(w=>({...w,display_name:w.display_name||(j.name??""),email:w.email||(j.email??""),phone:w.phone||(j.phone??""),headshot_url:w.headshot_url||(j.avatar_url??""),website_url:w.website_url||(j.website_url??""),tagline:w.tagline||(j.title??"")}))})()},[r]);const p=async(v,j)=>{if(r){d(v);try{const w=await Oxs(r,j,v);h(S=>({...S,[v==="headshot"?"headshot_url":"brokerage_logo_url"]:w}))}catch(w){ae.error(w.message||"Upload failed")}finally{d(null)}}},f=async()=>{try{const v=await a.mutateAsync({id:s==null?void 0:s.id,...u});ae.success("Brand preset saved"),t==null||t(v)}catch(v){ae.error(v.message||"Save failed")}},y=async()=>{s!=null&&s.id&&confirm("Delete this brand preset?")&&(await i.mutateAsync(s.id),ae.success("Preset deleted"),n==null||n())};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Preset name"}),e.jsx(ye,{value:u.name,onChange:v=>h({...u,name:v.target.value}),placeholder:"Personal, Team, Luxury..."})]}),e.jsxs("div",{className:"flex items-end gap-3 pb-1",children:[e.jsx(jn,{checked:u.is_default,onCheckedChange:v=>h({...u,is_default:v})}),e.jsx(ne,{children:"Use as default"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Display name"}),e.jsx(ye,{value:u.display_name,onChange:v=>h({...u,display_name:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Phone"}),e.jsx(ye,{value:u.phone,onChange:v=>h({...u,phone:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Email"}),e.jsx(ye,{value:u.email,onChange:v=>h({...u,email:v.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"License #"}),e.jsx(ye,{value:u.license_number,onChange:v=>h({...u,license_number:v.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Tagline"}),e.jsx(ye,{value:u.tagline,onChange:v=>h({...u,tagline:v.target.value}),placeholder:"Helping families find home"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Website"}),e.jsx(ye,{value:u.website_url,onChange:v=>h({...u,website_url:v.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Headshot"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Jr,{className:"h-16 w-16",children:[e.jsx(ti,{src:u.headshot_url||void 0}),e.jsx(ea,{children:((_=u.display_name)==null?void 0:_[0])??"A"})]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=l.current)==null?void 0:v.click()},disabled:c==="headshot",children:[c==="headshot"?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(_a,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var j;return((j=v.target.files)==null?void 0:j[0])&&p("headshot",v.target.files[0])}})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Brokerage logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-16 w-24 bg-muted rounded flex items-center justify-center overflow-hidden border",children:u.brokerage_logo_url?e.jsx("img",{src:u.brokerage_logo_url,alt:"logo",className:"max-h-full max-w-full object-contain"}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"No logo"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=o.current)==null?void 0:v.click()},disabled:c==="logo",children:[c==="logo"?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(_a,{className:"h-4 w-4 mr-1"}),"Upload"]}),e.jsx("input",{ref:o,type:"file",accept:"image/*",hidden:!0,onChange:v=>{var j;return((j=v.target.files)==null?void 0:j[0])&&p("logo",v.target.files[0])}})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Brand color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.brand_color,onChange:v=>h({...u,brand_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(ye,{value:u.brand_color,onChange:v=>h({...u,brand_color:v.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Accent color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:u.accent_color,onChange:v=>h({...u,accent_color:v.target.value}),className:"h-10 w-14 rounded cursor-pointer border"}),e.jsx(ye,{value:u.accent_color,onChange:v=>h({...u,accent_color:v.target.value})})]})]})]}),e.jsxs("div",{className:"flex justify-between pt-2",children:[e.jsx("div",{children:(s==null?void 0:s.id)&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:y,className:"text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-1"})," Delete"]})}),e.jsxs("div",{className:"flex gap-2",children:[n&&e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:a.isPending,children:[a.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}),"Save preset"]})]})]})]})}function zxs(){const{data:s,isLoading:t}=pU(),[n,r]=N.useState(null);return e.jsx(Cs,{title:"Brand Kit",children:e.jsxs("div",{className:"container max-w-5xl py-6 md:py-8 space-y-6 px-4",children:[e.jsx(Zo,{children:e.jsx("title",{children:"Brand Kit | Marketing Studio"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(In,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(qr,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Brand Kit"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Save your branding once — apply it across every Marketing Studio module."})]}),e.jsxs(B,{onClick:()=>r("new"),className:"w-full sm:w-auto",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," New preset"]})]}),t&&e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading..."}),!t&&s&&s.length===0&&e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"py-12 text-center space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Create your first brand preset"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"We'll pre-fill from your profile. You can have multiple presets — Personal, Team, Luxury division — and switch between them."}),e.jsxs(B,{onClick:()=>r("new"),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Create preset"]})]})}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:s==null?void 0:s.map(a=>e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"h-3",style:{background:`linear-gradient(90deg, ${a.brand_color}, ${a.accent_color})`}}),e.jsxs(It,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:[a.name,a.is_default&&e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(oa,{className:"h-3 w-3"})," Default"]})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>r(a),children:e.jsx(ya,{className:"h-4 w-4"})})]}),e.jsx(Vn,{children:a.display_name})]}),e.jsxs(Ee,{className:"text-sm text-muted-foreground space-y-1",children:[a.tagline&&e.jsxs("div",{className:"italic",children:['"',a.tagline,'"']}),a.phone&&e.jsx("div",{children:a.phone}),a.email&&e.jsx("div",{children:a.email})]})]},a.id))}),e.jsx(_s,{open:n!==null,onOpenChange:a=>!a&&r(null),children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto w-[calc(100vw-2rem)] sm:w-full",children:[e.jsx(js,{children:e.jsx(ws,{children:n==="new"?"New brand preset":"Edit brand preset"})}),e.jsx(Fxs,{preset:n==="new"?null:n,onSaved:()=>r(null),onCancel:()=>r(null)})]})})]})})}const BCe=[{id:"minimal-stripe",name:"Minimal Stripe",description:"Thin bottom strip with name + phone",appliesTo:["image","video"],position:"bottom",heightRatio:.085,background:"brand",fields:["headshot","name","phone"],circularHeadshot:!0,textColor:"auto"},{id:"full-footer",name:"Full Footer",description:"Generous footer with logo, tagline, and full contact",appliesTo:["image","video"],position:"bottom",heightRatio:.16,background:"brand",fields:["headshot","name","tagline","phone","email","logo"],circularHeadshot:!0,textColor:"auto"},{id:"corner-badge",name:"Corner Badge",description:"Subtle headshot + name in the bottom-right corner",appliesTo:["image","video"],position:"corner-br",heightRatio:.18,background:"gradient",fields:["headshot","name","phone"],circularHeadshot:!0,textColor:"light"},{id:"side-rail",name:"Side Rail",description:"Vertical strip on the right — great for stories",appliesTo:["image","video"],position:"side-right",heightRatio:.18,background:"brand",fields:["headshot","name","phone","logo"],circularHeadshot:!0,textColor:"auto"},{id:"letterbox",name:"Letterbox",description:"Cinematic top + bottom bars with logo and name",appliesTo:["image","video"],position:"letterbox",heightRatio:.09,background:"dark",fields:["headshot","name","phone","logo"],circularHeadshot:!0,textColor:"light"},{id:"top-banner",name:"Top Banner",description:"Bold banner across the top with logo and contact",appliesTo:["image","video"],position:"top",heightRatio:.1,background:"brand",fields:["logo","name","phone"],textColor:"auto"}],Bxs=s=>BCe.find(t=>t.id===s)??BCe[0];function $xs(s){if(!s)return"#ffffff";const t=s.replace("#","");if(t.length!==6)return"#ffffff";const n=parseInt(t.slice(0,2),16),r=parseInt(t.slice(2,4),16),a=parseInt(t.slice(4,6),16);return(n*299+r*587+a*114)/1e3>=150?"#0f172a":"#ffffff"}function Uxs({value:s,onChange:t,mediaType:n}){const r=BCe.filter(a=>a.appliesTo.includes(n));return e.jsx("div",{className:"grid grid-cols-2 gap-2",children:r.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.id),className:Mt("text-left rounded-lg border p-3 transition-all hover:border-primary/50",s===a.id&&"border-primary ring-2 ring-primary/20 bg-primary/5"),children:[e.jsx(qxs,{style:a}),e.jsx("div",{className:"mt-2 text-sm font-medium",children:a.name}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:a.description})]},a.id))})}function qxs({style:s}){const t="#cbd5e1",n="#0f172a";return e.jsxs("div",{className:"aspect-video w-full rounded relative overflow-hidden",style:{background:t},children:[s.position==="bottom"&&e.jsx("div",{className:"absolute left-0 right-0 bottom-0",style:{height:`${s.heightRatio*100}%`,background:n}}),s.position==="top"&&e.jsx("div",{className:"absolute left-0 right-0 top-0",style:{height:`${s.heightRatio*100}%`,background:n}}),s.position==="corner-br"&&e.jsx("div",{className:"absolute bottom-2 right-2 w-1/3 h-1/3 rounded",style:{background:n,opacity:.85}}),s.position==="side-right"&&e.jsx("div",{className:"absolute top-0 bottom-0 right-0",style:{width:`${s.heightRatio*100}%`,background:n}}),s.position==="letterbox"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute left-0 right-0 top-0",style:{height:`${s.heightRatio*100}%`,background:n}}),e.jsx("div",{className:"absolute left-0 right-0 bottom-0",style:{height:`${s.heightRatio*100}%`,background:n}})]})]})}const Vxs=Math.PI/180;function Hxs(){return typeof window<"u"&&({}.toString.call(window)==="[object Window]"||{}.toString.call(window)==="[object global]")}const KE=typeof global<"u"?global:typeof window<"u"?window:typeof WorkerGlobalScope<"u"?self:{},ua={_global:KE,version:"10.2.5",isBrowser:Hxs(),isUnminified:/param/.test((function(s){}).toString()),dblClickWindow:400,getAngle(s){return ua.angleDeg?s*Vxs:s},enableTrace:!1,pointerEventsEnabled:!0,autoDrawEnabled:!0,hitOnDragEnabled:!1,capturePointerEventsEnabled:!1,_mouseListenClick:!1,_touchListenClick:!1,_pointerListenClick:!1,_mouseInDblClickWindow:!1,_touchInDblClickWindow:!1,_pointerInDblClickWindow:!1,_mouseDblClickPointerId:null,_touchDblClickPointerId:null,_pointerDblClickPointerId:null,_renderBackend:"web",legacyTextRendering:!1,pixelRatio:typeof window<"u"&&window.devicePixelRatio||1,dragDistance:3,angleDeg:!0,showWarnings:!0,dragButtons:[0,1],isDragging(){return ua.DD.isDragging},isTransforming(){var s,t;return(t=(s=ua.Transformer)===null||s===void 0?void 0:s.isTransforming())!==null&&t!==void 0?t:!1},isDragReady(){return!!ua.DD.node},releaseCanvasOnDestroy:!0,document:KE.document,_injectGlobal(s){typeof KE.Konva<"u"&&console.error("Several Konva instances detected. It is not recommended to use multiple Konva instances in the same environment."),KE.Konva=s}},Fu=s=>{ua[s.prototype.getClassName()]=s};ua._injectGlobal(ua);const Gxs=`Konva.js unsupported environment. Looks like you are trying to use Konva.js in Node.js environment. because "document" object is undefined. To use Konva.js in Node.js environment, you need to use the "canvas-backend" or "skia-backend" module. bash: npm install canvas js: import "konva/canvas-backend"; or bash: npm install skia-canvas js: import "konva/skia-backend"; `,NVe=()=>{if(typeof document>"u")throw new Error(Gxs)};class Y0{constructor(t=[1,0,0,1,0,0]){this.dirty=!1,this.m=t&&t.slice()||[1,0,0,1,0,0]}reset(){this.m[0]=1,this.m[1]=0,this.m[2]=0,this.m[3]=1,this.m[4]=0,this.m[5]=0}copy(){return new Y0(this.m)}copyInto(t){t.m[0]=this.m[0],t.m[1]=this.m[1],t.m[2]=this.m[2],t.m[3]=this.m[3],t.m[4]=this.m[4],t.m[5]=this.m[5]}point(t){const n=this.m;return{x:n[0]*t.x+n[2]*t.y+n[4],y:n[1]*t.x+n[3]*t.y+n[5]}}translate(t,n){return this.m[4]+=this.m[0]*t+this.m[2]*n,this.m[5]+=this.m[1]*t+this.m[3]*n,this}scale(t,n){return this.m[0]*=t,this.m[1]*=t,this.m[2]*=n,this.m[3]*=n,this}rotate(t){const n=Math.cos(t),r=Math.sin(t),a=this.m[0]*n+this.m[2]*r,i=this.m[1]*n+this.m[3]*r,l=this.m[0]*-r+this.m[2]*n,o=this.m[1]*-r+this.m[3]*n;return this.m[0]=a,this.m[1]=i,this.m[2]=l,this.m[3]=o,this}getTranslation(){return{x:this.m[4],y:this.m[5]}}skew(t,n){const r=this.m[0]+this.m[2]*n,a=this.m[1]+this.m[3]*n,i=this.m[2]+this.m[0]*t,l=this.m[3]+this.m[1]*t;return this.m[0]=r,this.m[1]=a,this.m[2]=i,this.m[3]=l,this}multiply(t){const n=this.m[0]*t.m[0]+this.m[2]*t.m[1],r=this.m[1]*t.m[0]+this.m[3]*t.m[1],a=this.m[0]*t.m[2]+this.m[2]*t.m[3],i=this.m[1]*t.m[2]+this.m[3]*t.m[3],l=this.m[0]*t.m[4]+this.m[2]*t.m[5]+this.m[4],o=this.m[1]*t.m[4]+this.m[3]*t.m[5]+this.m[5];return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}invert(){const t=1/(this.m[0]*this.m[3]-this.m[1]*this.m[2]),n=this.m[3]*t,r=-this.m[1]*t,a=-this.m[2]*t,i=this.m[0]*t,l=t*(this.m[2]*this.m[5]-this.m[3]*this.m[4]),o=t*(this.m[1]*this.m[4]-this.m[0]*this.m[5]);return this.m[0]=n,this.m[1]=r,this.m[2]=a,this.m[3]=i,this.m[4]=l,this.m[5]=o,this}getMatrix(){return this.m}decompose(){const t=this.m[0],n=this.m[1],r=this.m[2],a=this.m[3],i=this.m[4],l=this.m[5],o=t*a-n*r,c={x:i,y:l,rotation:0,scaleX:0,scaleY:0,skewX:0,skewY:0};if(t!=0||n!=0){const d=Math.sqrt(t*t+n*n);c.rotation=n>0?Math.acos(t/d):-Math.acos(t/d),c.scaleX=d,c.scaleY=o/d,c.skewX=(t*r+n*a)/o,c.skewY=0}else if(r!=0||a!=0){const d=Math.sqrt(r*r+a*a);c.rotation=Math.PI/2-(a>0?Math.acos(-r/d):-Math.acos(r/d)),c.scaleX=o/d,c.scaleY=d,c.skewX=0,c.skewY=(t*r+n*a)/o}return c.rotation=yn._getRotation(c.rotation),c}}const Wxs="[object Array]",Kxs="[object Number]",Yxs="[object String]",Zxs="[object Boolean]",Qxs=Math.PI/180,Xxs=180/Math.PI,cF="#",Jxs="",egs="0",tgs="Konva warning: ",kVe="Konva error: ",sgs="rgb(",l2e={aliceblue:[240,248,255],antiquewhite:[250,235,215],aqua:[0,255,255],aquamarine:[127,255,212],azure:[240,255,255],beige:[245,245,220],bisque:[255,228,196],black:[0,0,0],blanchedalmond:[255,235,205],blue:[0,0,255],blueviolet:[138,43,226],brown:[165,42,42],burlywood:[222,184,135],cadetblue:[95,158,160],chartreuse:[127,255,0],chocolate:[210,105,30],coral:[255,127,80],cornflowerblue:[100,149,237],cornsilk:[255,248,220],crimson:[220,20,60],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgoldenrod:[184,132,11],darkgray:[169,169,169],darkgreen:[0,100,0],darkgrey:[169,169,169],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkseagreen:[143,188,143],darkslateblue:[72,61,139],darkslategray:[47,79,79],darkslategrey:[47,79,79],darkturquoise:[0,206,209],darkviolet:[148,0,211],deeppink:[255,20,147],deepskyblue:[0,191,255],dimgray:[105,105,105],dimgrey:[105,105,105],dodgerblue:[30,144,255],firebrick:[178,34,34],floralwhite:[255,255,240],forestgreen:[34,139,34],fuchsia:[255,0,255],gainsboro:[220,220,220],ghostwhite:[248,248,255],gold:[255,215,0],goldenrod:[218,165,32],gray:[128,128,128],green:[0,128,0],greenyellow:[173,255,47],grey:[128,128,128],honeydew:[240,255,240],hotpink:[255,105,180],indianred:[205,92,92],indigo:[75,0,130],ivory:[255,255,240],khaki:[240,230,140],lavender:[230,230,250],lavenderblush:[255,240,245],lawngreen:[124,252,0],lemonchiffon:[255,250,205],lightblue:[173,216,230],lightcoral:[240,128,128],lightcyan:[224,255,255],lightgoldenrodyellow:[250,250,210],lightgray:[211,211,211],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightsalmon:[255,160,122],lightseagreen:[32,178,170],lightskyblue:[135,206,250],lightslategray:[119,136,153],lightslategrey:[119,136,153],lightsteelblue:[176,196,222],lightyellow:[255,255,224],lime:[0,255,0],limegreen:[50,205,50],linen:[250,240,230],magenta:[255,0,255],maroon:[128,0,0],mediumaquamarine:[102,205,170],mediumblue:[0,0,205],mediumorchid:[186,85,211],mediumpurple:[147,112,219],mediumseagreen:[60,179,113],mediumslateblue:[123,104,238],mediumspringgreen:[0,250,154],mediumturquoise:[72,209,204],mediumvioletred:[199,21,133],midnightblue:[25,25,112],mintcream:[245,255,250],mistyrose:[255,228,225],moccasin:[255,228,181],navajowhite:[255,222,173],navy:[0,0,128],oldlace:[253,245,230],olive:[128,128,0],olivedrab:[107,142,35],orange:[255,165,0],orangered:[255,69,0],orchid:[218,112,214],palegoldenrod:[238,232,170],palegreen:[152,251,152],paleturquoise:[175,238,238],palevioletred:[219,112,147],papayawhip:[255,239,213],peachpuff:[255,218,185],peru:[205,133,63],pink:[255,192,203],plum:[221,160,203],powderblue:[176,224,230],purple:[128,0,128],rebeccapurple:[102,51,153],red:[255,0,0],rosybrown:[188,143,143],royalblue:[65,105,225],saddlebrown:[139,69,19],salmon:[250,128,114],sandybrown:[244,164,96],seagreen:[46,139,87],seashell:[255,245,238],sienna:[160,82,45],silver:[192,192,192],skyblue:[135,206,235],slateblue:[106,90,205],slategray:[119,128,144],slategrey:[119,128,144],snow:[255,255,250],springgreen:[0,255,127],steelblue:[70,130,180],tan:[210,180,140],teal:[0,128,128],thistle:[216,191,216],transparent:[255,255,255,0],tomato:[255,99,71],turquoise:[64,224,208],violet:[238,130,238],wheat:[245,222,179],white:[255,255,255],whitesmoke:[245,245,245],yellow:[255,255,0],yellowgreen:[154,205,5]},ngs=/rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)/;let NH=[],dF=null;const rgs=typeof requestAnimationFrame<"u"&&requestAnimationFrame||function(s){setTimeout(s,16)},yn={_isElement(s){return!!(s&&s.nodeType==1)},_isFunction(s){return!!(s&&s.constructor&&s.call&&s.apply)},_isPlainObject(s){return!!s&&s.constructor===Object},_isArray(s){return Object.prototype.toString.call(s)===Wxs},_isNumber(s){return Object.prototype.toString.call(s)===Kxs&&!isNaN(s)&&isFinite(s)},_isString(s){return Object.prototype.toString.call(s)===Yxs},_isBoolean(s){return Object.prototype.toString.call(s)===Zxs},isObject(s){return s instanceof Object},isValidSelector(s){if(typeof s!="string")return!1;const t=s[0];return t==="#"||t==="."||t===t.toUpperCase()},_sign(s){return s===0||s>0?1:-1},requestAnimFrame(s){NH.push(s),NH.length===1&&rgs(function(){const t=NH;NH=[],t.forEach(function(n){n()})})},createCanvasElement(){NVe();const s=document.createElement("canvas");try{s.style=s.style||{}}catch{}return s},createImageElement(){return NVe(),document.createElement("img")},_isInDocument(s){for(;s=s.parentNode;)if(s==document)return!0;return!1},_urlToImage(s,t){const n=yn.createImageElement();n.onload=function(){t(n)},n.src=s},_rgbToHex(s,t,n){return((1<<24)+(s<<16)+(t<<8)+n).toString(16).slice(1)},_hexToRgb(s){s=s.replace(cF,Jxs);const t=parseInt(s,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},getRandomColor(){let s=(Math.random()*16777215<<0).toString(16);for(;s.length<6;)s=egs+s;return cF+s},isCanvasFarblingActive(){if(dF!==null)return dF;if(typeof document>"u")return dF=!1,!1;const s=this.createCanvasElement();s.width=10,s.height=10;const t=s.getContext("2d",{willReadFrequently:!0});t.clearRect(0,0,10,10),t.fillStyle="#282828",t.fillRect(0,0,10,10);const n=t.getImageData(0,0,10,10).data;let r=!1;for(let a=0;a<100;a++)if(n[a*4]!==40||n[a*4+1]!==40||n[a*4+2]!==40||n[a*4+3]!==255){r=!0;break}return dF=r,this.releaseCanvas(s),dF},getHitColor(){const s=this.getRandomColor();return this.isCanvasFarblingActive()?this.getSnappedHexColor(s):s},getHitColorKey(s,t,n){return this.isCanvasFarblingActive()&&(s=Math.round(s/5)*5,t=Math.round(t/5)*5,n=Math.round(n/5)*5),cF+this._rgbToHex(s,t,n)},getSnappedHexColor(s){const t=this._hexToRgb(s);return cF+this._rgbToHex(Math.round(t.r/5)*5,Math.round(t.g/5)*5,Math.round(t.b/5)*5)},getRGB(s){let t;return s in l2e?(t=l2e[s],{r:t[0],g:t[1],b:t[2]}):s[0]===cF?this._hexToRgb(s.substring(1)):s.substr(0,4)===sgs?(t=ngs.exec(s.replace(/ /g,"")),{r:parseInt(t[1],10),g:parseInt(t[2],10),b:parseInt(t[3],10)}):{r:0,g:0,b:0}},colorToRGBA(s){return s=s||"black",yn._namedColorToRBA(s)||yn._hex3ColorToRGBA(s)||yn._hex4ColorToRGBA(s)||yn._hex6ColorToRGBA(s)||yn._hex8ColorToRGBA(s)||yn._rgbColorToRGBA(s)||yn._rgbaColorToRGBA(s)||yn._hslColorToRGBA(s)},_namedColorToRBA(s){const t=l2e[s.toLowerCase()];return t?{r:t[0],g:t[1],b:t[2],a:1}:null},_rgbColorToRGBA(s){if(s.indexOf("rgb(")===0){s=s.match(/rgb\(([^)]+)\)/)[1];const t=s.split(/ *, */).map(Number);return{r:t[0],g:t[1],b:t[2],a:1}}},_rgbaColorToRGBA(s){if(s.indexOf("rgba(")===0){s=s.match(/rgba\(([^)]+)\)/)[1];const t=s.split(/ *, */).map((n,r)=>n.slice(-1)==="%"?r===3?parseInt(n)/100:parseInt(n)/100*255:Number(n));return{r:t[0],g:t[1],b:t[2],a:t[3]}}},_hex8ColorToRGBA(s){if(s[0]==="#"&&s.length===9)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:parseInt(s.slice(7,9),16)/255}},_hex6ColorToRGBA(s){if(s[0]==="#"&&s.length===7)return{r:parseInt(s.slice(1,3),16),g:parseInt(s.slice(3,5),16),b:parseInt(s.slice(5,7),16),a:1}},_hex4ColorToRGBA(s){if(s[0]==="#"&&s.length===5)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:parseInt(s[4]+s[4],16)/255}},_hex3ColorToRGBA(s){if(s[0]==="#"&&s.length===4)return{r:parseInt(s[1]+s[1],16),g:parseInt(s[2]+s[2],16),b:parseInt(s[3]+s[3],16),a:1}},_hslColorToRGBA(s){if(/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.test(s)){const[t,...n]=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(s),r=Number(n[0])/360,a=Number(n[1])/100,i=Number(n[2])/100;let l,o,c;if(a===0)return c=i*255,{r:Math.round(c),g:Math.round(c),b:Math.round(c),a:1};i<.5?l=i*(1+a):l=i+a-i*a;const d=2*i-l,u=[0,0,0];for(let h=0;h<3;h++)o=r+1/3*-(h-1),o<0&&o++,o>1&&o--,6*o<1?c=d+(l-d)*6*o:2*o<1?c=l:3*o<2?c=d+(l-d)*(2/3-o)*6:c=d,u[h]=c*255;return{r:Math.round(u[0]),g:Math.round(u[1]),b:Math.round(u[2]),a:1}}},haveIntersection(s,t){return!(t.x>s.x+s.width||t.x+t.widths.y+s.height||t.y+t.height1?(l=n,o=r,c=(n-a)*(n-a)+(r-i)*(r-i)):(l=s+u*(n-s),o=t+u*(r-t),c=(l-a)*(l-a)+(o-i)*(o-i))}return[l,o,c]},_getProjectionToLine(s,t,n){const r=yn.cloneObject(s);let a=Number.MAX_VALUE;return t.forEach(function(i,l){if(!n&&l===t.length-1)return;const o=t[(l+1)%t.length],c=yn._getProjectionToSegment(i.x,i.y,o.x,o.y,s.x,s.y),d=c[0],u=c[1],h=c[2];ht.length){const l=t;t=s,s=l}for(let l=0;l{t.width=0,t.height=0})},drawRoundedRectPath(s,t,n,r){let a=t<0?t:0,i=n<0?n:0;t=Math.abs(t),n=Math.abs(n);let l=0,o=0,c=0,d=0;typeof r=="number"?l=o=c=d=Math.min(r,t/2,n/2):(l=Math.min(r[0]||0,t/2,n/2),o=Math.min(r[1]||0,t/2,n/2),d=Math.min(r[2]||0,t/2,n/2),c=Math.min(r[3]||0,t/2,n/2)),s.moveTo(a+l,i),s.lineTo(a+t-o,i),s.arc(a+t-o,i+o,o,Math.PI*3/2,0,!1),s.lineTo(a+t,i+n-d),s.arc(a+t-d,i+n-d,d,0,Math.PI/2,!1),s.lineTo(a+c,i+n),s.arc(a+c,i+n-c,c,Math.PI/2,Math.PI,!1),s.lineTo(a,i+l),s.arc(a+l,i+l,l,Math.PI,Math.PI*3/2,!1)},drawRoundedPolygonPath(s,t,n,r,a){r=Math.abs(r);for(let i=0;itypeof u=="number"?Math.floor(u):u)),i+=igs+d.join(SVe)+ogs)):(i+=o.property,t||(i+=hgs+o.val)),i+=dgs;return i}clearTrace(){this.traceArr=[]}_trace(t){let n=this.traceArr,r;n.push(t),r=n.length,r>=pgs&&n.shift()}reset(){const t=this.getCanvas().getPixelRatio();this.setTransform(1*t,0,0,1*t,0,0)}getCanvas(){return this.canvas}clear(t){const n=this.getCanvas();t?this.clearRect(t.x||0,t.y||0,t.width||0,t.height||0):this.clearRect(0,0,n.getWidth()/n.pixelRatio,n.getHeight()/n.pixelRatio)}_applyLineCap(t){const n=t.attrs.lineCap;n&&this.setAttr("lineCap",n)}_applyOpacity(t){const n=t.getAbsoluteOpacity();n!==1&&this.setAttr("globalAlpha",n)}_applyLineJoin(t){const n=t.attrs.lineJoin;n&&this.setAttr("lineJoin",n)}_applyMiterLimit(t){const n=t.attrs.miterLimit;n!=null&&this.setAttr("miterLimit",n)}setAttr(t,n){this._context[t]=n}arc(t,n,r,a,i,l){this._context.arc(t,n,r,a,i,l)}arcTo(t,n,r,a,i){this._context.arcTo(t,n,r,a,i)}beginPath(){this._context.beginPath()}bezierCurveTo(t,n,r,a,i,l){this._context.bezierCurveTo(t,n,r,a,i,l)}clearRect(t,n,r,a){this._context.clearRect(t,n,r,a)}clip(...t){this._context.clip.apply(this._context,t)}closePath(){this._context.closePath()}createImageData(t,n){const r=arguments;if(r.length===2)return this._context.createImageData(t,n);if(r.length===1)return this._context.createImageData(t)}createLinearGradient(t,n,r,a){return this._context.createLinearGradient(t,n,r,a)}createPattern(t,n){return this._context.createPattern(t,n)}createRadialGradient(t,n,r,a,i,l){return this._context.createRadialGradient(t,n,r,a,i,l)}drawImage(t,n,r,a,i,l,o,c,d){const u=arguments,h=this._context;u.length===3?h.drawImage(t,n,r):u.length===5?h.drawImage(t,n,r,a,i):u.length===9&&h.drawImage(t,n,r,a,i,l,o,c,d)}ellipse(t,n,r,a,i,l,o,c){this._context.ellipse(t,n,r,a,i,l,o,c)}isPointInPath(t,n,r,a){return r?this._context.isPointInPath(r,t,n,a):this._context.isPointInPath(t,n,a)}fill(...t){this._context.fill.apply(this._context,t)}fillRect(t,n,r,a){this._context.fillRect(t,n,r,a)}strokeRect(t,n,r,a){this._context.strokeRect(t,n,r,a)}fillText(t,n,r,a){a?this._context.fillText(t,n,r,a):this._context.fillText(t,n,r)}measureText(t){return this._context.measureText(t)}getImageData(t,n,r,a){return this._context.getImageData(t,n,r,a)}lineTo(t,n){this._context.lineTo(t,n)}moveTo(t,n){this._context.moveTo(t,n)}rect(t,n,r,a){this._context.rect(t,n,r,a)}roundRect(t,n,r,a,i){this._context.roundRect(t,n,r,a,i)}putImageData(t,n,r){this._context.putImageData(t,n,r)}quadraticCurveTo(t,n,r,a){this._context.quadraticCurveTo(t,n,r,a)}restore(){this._context.restore()}rotate(t){this._context.rotate(t)}save(){this._context.save()}scale(t,n){this._context.scale(t,n)}setLineDash(t){this._context.setLineDash?this._context.setLineDash(t):"mozDash"in this._context?this._context.mozDash=t:"webkitLineDash"in this._context&&(this._context.webkitLineDash=t)}getLineDash(){return this._context.getLineDash()}setTransform(t,n,r,a,i,l){this._context.setTransform(t,n,r,a,i,l)}stroke(t){t?this._context.stroke(t):this._context.stroke()}strokeText(t,n,r,a){this._context.strokeText(t,n,r,a)}transform(t,n,r,a,i,l){this._context.transform(t,n,r,a,i,l)}translate(t,n){this._context.translate(t,n)}_enableTrace(){let t=this,n=CVe.length,r=this.setAttr,a,i;const l=function(o){let c=t[o],d;t[o]=function(){return i=ags(Array.prototype.slice.call(arguments,0)),d=c.apply(t,arguments),t._trace({method:o,args:i}),d}};for(a=0;a{t.dragStatus==="dragging"&&(s=!0)}),s},justDragged:!1,get node(){let s;return zl._dragElements.forEach(t=>{s=t.node}),s},_dragElements:new Map,_drag(s){const t=[];zl._dragElements.forEach((n,r)=>{const{node:a}=n,i=a.getStage();i.setPointersPositions(s),n.pointerId===void 0&&(n.pointerId=yn._getFirstPointerId(s));const l=i._changedPointerPositions.find(o=>o.id===n.pointerId);if(l){if(n.dragStatus!=="dragging"){const o=a.dragDistance();if(Math.max(Math.abs(l.x-n.startPointerPos.x),Math.abs(l.y-n.startPointerPos.y)){n.getStage()&&n.fire("dragmove",{type:"dragmove",target:n,evt:s},!0)})},_endDragBefore(s){const t=[];zl._dragElements.forEach(n=>{const{node:r}=n,a=r.getStage();if(s&&a.setPointersPositions(s),!a._changedPointerPositions.find(o=>o.id===n.pointerId))return;(n.dragStatus==="dragging"||n.dragStatus==="stopped")&&(zl.justDragged=!0,ua._mouseListenClick=!1,ua._touchListenClick=!1,ua._pointerListenClick=!1,n.dragStatus="stopped");const l=n.node.getLayer()||n.node instanceof ua.Stage&&n.node;l&&t.indexOf(l)===-1&&t.push(l)}),t.forEach(n=>{n.draw()})},_endDragAfter(s){zl._dragElements.forEach((t,n)=>{t.dragStatus==="stopped"&&t.node.fire("dragend",{type:"dragend",target:t.node,evt:s},!0),t.dragStatus!=="dragging"&&zl._dragElements.delete(n)})}};ua.isBrowser&&(window.addEventListener("mouseup",zl._endDragBefore,!0),window.addEventListener("touchend",zl._endDragBefore,!0),window.addEventListener("touchcancel",zl._endDragBefore,!0),window.addEventListener("mousemove",zl._drag),window.addEventListener("touchmove",zl._drag),window.addEventListener("mouseup",zl._endDragAfter,!1),window.addEventListener("touchend",zl._endDragAfter,!1),window.addEventListener("touchcancel",zl._endDragAfter,!1));function Z4(s){return yn._isString(s)?'"'+s+'"':Object.prototype.toString.call(s)==="[object Number]"||yn._isBoolean(s)?s:Object.prototype.toString.call(s)}function hgt(s){return s>255?255:s<0?0:Math.round(s)}function ta(){if(ua.isUnminified)return function(s,t){return yn._isNumber(s)||yn.warn(Z4(s)+' is a not valid value for "'+t+'" attribute. The value should be a number.'),s}}function Jye(s){if(ua.isUnminified)return function(t,n){let r=yn._isNumber(t),a=yn._isArray(t)&&t.length==s;return!r&&!a&&yn.warn(Z4(t)+' is a not valid value for "'+n+'" attribute. The value should be a number or Array('+s+")"),t}}function uIe(){if(ua.isUnminified)return function(s,t){return yn._isNumber(s)||s==="auto"||yn.warn(Z4(s)+' is a not valid value for "'+t+'" attribute. The value should be a number or "auto".'),s}}function qM(){if(ua.isUnminified)return function(s,t){return yn._isString(s)||yn.warn(Z4(s)+' is a not valid value for "'+t+'" attribute. The value should be a string.'),s}}function mgt(){if(ua.isUnminified)return function(s,t){const n=yn._isString(s),r=Object.prototype.toString.call(s)==="[object CanvasGradient]"||s&&s.addColorStop;return n||r||yn.warn(Z4(s)+' is a not valid value for "'+t+'" attribute. The value should be a string or a native gradient.'),s}}function ygs(){if(ua.isUnminified)return function(s,t){const n=Int8Array?Object.getPrototypeOf(Int8Array):null;return n&&s instanceof n||(yn._isArray(s)?s.forEach(function(r){yn._isNumber(r)||yn.warn('"'+t+'" attribute has non numeric element '+r+". Make sure that all elements are numbers.")}):yn.warn(Z4(s)+' is a not valid value for "'+t+'" attribute. The value should be a array of numbers.')),s}}function Ib(){if(ua.isUnminified)return function(s,t){return s===!0||s===!1||yn.warn(Z4(s)+' is a not valid value for "'+t+'" attribute. The value should be a boolean.'),s}}function vgs(s){if(ua.isUnminified)return function(t,n){return t==null||yn.isObject(t)||yn.warn(Z4(t)+' is a not valid value for "'+n+'" attribute. The value should be an object with properties '+s),t}}const uF="get",hF="set",Rs={addGetterSetter(s,t,n,r,a){Rs.addGetter(s,t,n),Rs.addSetter(s,t,r,a),Rs.addOverloadedGetterSetter(s,t)},addGetter(s,t,n){const r=uF+yn._capitalize(t);s.prototype[r]=s.prototype[r]||function(){const a=this.attrs[t];return a===void 0?n:a}},addSetter(s,t,n,r){const a=hF+yn._capitalize(t);s.prototype[a]||Rs.overWriteSetter(s,t,n,r)},overWriteSetter(s,t,n,r){const a=hF+yn._capitalize(t);s.prototype[a]=function(i){return n&&i!==void 0&&i!==null&&(i=n.call(this,i,t)),this._setAttr(t,i),r&&r.call(this),this}},addComponentsGetterSetter(s,t,n,r,a){const i=n.length,l=yn._capitalize,o=uF+l(t),c=hF+l(t);s.prototype[o]=function(){const u={};for(let h=0;h{this._setAttr(t+l(p),void 0)}),this._fireChangeEvent(t,h,u),a&&a.call(this),this},Rs.addOverloadedGetterSetter(s,t)},addOverloadedGetterSetter(s,t){const n=yn._capitalize(t),r=hF+n,a=uF+n;s.prototype[t]=function(){return arguments.length?(this[r](arguments[0]),this):this[a]()}},addDeprecatedGetterSetter(s,t,n,r){yn.error("Adding deprecated "+t);const a=uF+yn._capitalize(t),i=t+" property is deprecated and will be removed soon. Look at Konva change log for more information.";s.prototype[a]=function(){yn.error(i);const l=this.attrs[t];return l===void 0?n:l},Rs.addSetter(s,t,r,function(){yn.error(i)}),Rs.addOverloadedGetterSetter(s,t)},backCompat(s,t){yn.each(t,function(n,r){const a=s.prototype[r],i=uF+yn._capitalize(n),l=hF+yn._capitalize(n);function o(){a.apply(this,arguments),yn.error('"'+n+'" method is deprecated and will be removed soon. Use ""'+r+'" instead.')}s.prototype[n]=o,s.prototype[i]=o,s.prototype[l]=o})},afterSetFilter(){this._filterUpToDate=!1}};function bgs(s){const t=/(\w+)\(([^)]+)\)/g;let n;for(;(n=t.exec(s))!==null;){const[,r,a]=n;switch(r){case"blur":{const i=parseFloat(a.replace("px",""));return function(l){this.blurRadius(i*.5);const o=ua.Filters;o&&o.Blur&&o.Blur.call(this,l)}}case"brightness":{const i=a.includes("%")?parseFloat(a)/100:parseFloat(a);return function(l){this.brightness(i);const o=ua.Filters;o&&o.Brightness&&o.Brightness.call(this,l)}}case"contrast":{const i=parseFloat(a);return function(l){const o=100*(Math.sqrt(i)-1);this.contrast(o);const c=ua.Filters;c&&c.Contrast&&c.Contrast.call(this,l)}}case"grayscale":return function(i){const l=ua.Filters;l&&l.Grayscale&&l.Grayscale.call(this,i)};case"sepia":return function(i){const l=ua.Filters;l&&l.Sepia&&l.Sepia.call(this,i)};case"invert":return function(i){const l=ua.Filters;l&&l.Invert&&l.Invert.call(this,i)};default:yn.warn(`CSS filter "${r}" is not supported in fallback mode. Consider using function filters for better compatibility.`);break}}return()=>{}}const $me="absoluteOpacity",EVe="allEventListeners",f2="absoluteTransform",AVe="absoluteScale",r3="canvas",_gs="Change",wgs="children",jgs="konva",$Ce="listening",Ngs="mouseenter",kgs="mouseleave",Sgs="pointerenter",Cgs="pointerleave",Tgs="touchenter",Egs="touchleave",MVe="set",IVe="Shape",Ume=" ",PVe="stage",zk="transform",Ags="Stage",UCe="visible",Mgs=["xChange.konva","yChange.konva","scaleXChange.konva","scaleYChange.konva","skewXChange.konva","skewYChange.konva","rotationChange.konva","offsetXChange.konva","offsetYChange.konva","transformsEnabledChange.konva"].join(Ume);let Igs=1,fa=class o7{constructor(t){this._id=Igs++,this.eventListeners={},this.attrs={},this.index=0,this._allEventListeners=null,this.parent=null,this._cache=new Map,this._attachedDepsListeners=new Map,this._lastPos=null,this._batchingTransformChange=!1,this._needClearTransformCache=!1,this._filterUpToDate=!1,this._isUnderCache=!1,this._dragEventId=null,this._shouldFireChangeEvents=!1,this.setAttrs(t),this._shouldFireChangeEvents=!0}hasChildren(){return!1}_clearCache(t){(t===zk||t===f2)&&this._cache.get(t)?this._cache.get(t).dirty=!0:t?this._cache.delete(t):this._cache.clear()}_getCache(t,n){let r=this._cache.get(t);return(r===void 0||(t===zk||t===f2)&&r.dirty===!0)&&(r=n.call(this),this._cache.set(t,r)),r}_calculate(t,n,r){if(!this._attachedDepsListeners.get(t)){const a=n.map(i=>i+"Change.konva").join(Ume);this.on(a,()=>{this._clearCache(t)}),this._attachedDepsListeners.set(t,!0)}return this._getCache(t,r)}_getCanvasCache(){return this._cache.get(r3)}_clearSelfAndDescendantCache(t){this._clearCache(t),t===f2&&this.fire("absoluteTransformChange")}clearCache(){if(this._cache.has(r3)){const{scene:t,filter:n,hit:r}=this._cache.get(r3);yn.releaseCanvas(t._canvas,n._canvas,r._canvas),this._cache.delete(r3)}return this._clearSelfAndDescendantCache(),this._requestDraw(),this}cache(t){const n=t||{};let r={};(n.x===void 0||n.y===void 0||n.width===void 0||n.height===void 0)&&(r=this.getClientRect({skipTransform:!0,relativeTo:this.getParent()||void 0}));let a=Math.ceil(n.width||r.width),i=Math.ceil(n.height||r.height),l=n.pixelRatio,o=n.x===void 0?Math.floor(r.x):n.x,c=n.y===void 0?Math.floor(r.y):n.y,d=n.offset||0,u=n.drawBorder||!1,h=n.hitCanvasPixelRatio||1;if(!a||!i){yn.error("Can not cache the node. Width or height of the node equals 0. Caching is skipped.");return}const p=Math.abs(Math.round(r.x)-o)>.5?1:0,f=Math.abs(Math.round(r.y)-c)>.5?1:0;a+=d*2+p,i+=d*2+f,o-=d,c-=d;const y=new lS({pixelRatio:l,width:a,height:i}),_=new lS({pixelRatio:l,width:0,height:0,willReadFrequently:!0}),v=new dIe({pixelRatio:h,width:a,height:i}),j=y.getContext(),w=v.getContext(),S=new lS({width:y.width/y.pixelRatio+Math.abs(o),height:y.height/y.pixelRatio+Math.abs(c),pixelRatio:y.pixelRatio}),A=S.getContext();return v.isCache=!0,y.isCache=!0,this._cache.delete(r3),this._filterUpToDate=!1,n.imageSmoothingEnabled===!1&&(y.getContext()._context.imageSmoothingEnabled=!1,_.getContext()._context.imageSmoothingEnabled=!1),j.save(),w.save(),A.save(),j.translate(-o,-c),w.translate(-o,-c),A.translate(-o,-c),S.x=o,S.y=c,this._isUnderCache=!0,this._clearSelfAndDescendantCache($me),this._clearSelfAndDescendantCache(AVe),this.drawScene(y,this,S),this.drawHit(v,this),this._isUnderCache=!1,j.restore(),w.restore(),u&&(j.save(),j.beginPath(),j.rect(0,0,a,i),j.closePath(),j.setAttr("strokeStyle","red"),j.setAttr("lineWidth",5),j.stroke(),j.restore()),yn.releaseCanvas(S._canvas),this._cache.set(r3,{scene:y,filter:_,hit:v,x:o,y:c}),this._requestDraw(),this}isCached(){return this._cache.has(r3)}getClientRect(t){throw new Error('abstract "getClientRect" method call')}_transformedRect(t,n){const r=[{x:t.x,y:t.y},{x:t.x+t.width,y:t.y},{x:t.x+t.width,y:t.y+t.height},{x:t.x,y:t.y+t.height}];let a=1/0,i=1/0,l=-1/0,o=-1/0;const c=this.getAbsoluteTransform(n);return r.forEach(function(d){const u=c.point(d);a===void 0&&(a=l=u.x,i=o=u.y),a=Math.min(a,u.x),i=Math.min(i,u.y),l=Math.max(l,u.x),o=Math.max(o,u.y)}),{x:a,y:i,width:l-a,height:o-i}}_drawCachedSceneCanvas(t){t.save(),t._applyOpacity(this),t._applyGlobalCompositeOperation(this);const n=this._getCanvasCache();t.translate(n.x,n.y);const r=this._getCachedSceneCanvas(),a=r.pixelRatio;t.drawImage(r._canvas,0,0,r.width/a,r.height/a),t.restore()}_drawCachedHitCanvas(t){const n=this._getCanvasCache(),r=n.hit;t.save(),t.translate(n.x,n.y),t.drawImage(r._canvas,0,0,r.width/r.pixelRatio,r.height/r.pixelRatio),t.restore()}_getCachedSceneCanvas(){let t=this.filters(),n=this._getCanvasCache(),r=n.scene,a=n.filter,i=a.getContext(),l,o,c,d;if(!t||t.length===0)return r;if(this._filterUpToDate)return a;let u=!0;for(let p=0;p{this.isAncestorOf(t.node)&&zl._dragElements.delete(n)}),this._remove(),this}_clearCaches(){this._clearSelfAndDescendantCache(f2),this._clearSelfAndDescendantCache($me),this._clearSelfAndDescendantCache(AVe),this._clearSelfAndDescendantCache(PVe),this._clearSelfAndDescendantCache(UCe),this._clearSelfAndDescendantCache($Ce)}_remove(){this._clearCaches();const t=this.getParent();t&&t.children&&(t.children.splice(this.index,1),t._setChildrenIndices(),this.parent=null)}destroy(){return this.remove(),this.clearCache(),this}getAttr(t){const n="get"+yn._capitalize(t);return yn._isFunction(this[n])?this[n]():this.attrs[t]}getAncestors(){let t=this.getParent(),n=[];for(;t;)n.push(t),t=t.getParent();return n}getAttrs(){return this.attrs||{}}setAttrs(t){return this._batchTransformChanges(()=>{let n,r;if(!t)return this;for(n in t)n!==wgs&&(r=MVe+yn._capitalize(n),yn._isFunction(this[r])?this[r](t[n]):this._setAttr(n,t[n]))}),this}isListening(){return this._getCache($Ce,this._isListening)}_isListening(t){if(!this.listening())return!1;const r=this.getParent();return r&&r!==t&&this!==t?r._isListening(t):!0}isVisible(){return this._getCache(UCe,this._isVisible)}_isVisible(t){if(!this.visible())return!1;const r=this.getParent();return r&&r!==t&&this!==t?r._isVisible(t):!0}shouldDrawHit(t,n=!1){if(t)return this._isVisible(t)&&this._isListening(t);const r=this.getLayer();let a=!1;zl._dragElements.forEach(l=>{l.dragStatus==="dragging"&&(l.node.nodeType==="Stage"||l.node.getLayer()===r)&&(a=!0)});const i=!n&&!ua.hitOnDragEnabled&&(a||ua.isTransforming());return this.isListening()&&this.isVisible()&&!i}show(){return this.visible(!0),this}hide(){return this.visible(!1),this}getZIndex(){return this.index||0}getAbsoluteZIndex(){let t=this.getDepth(),n=this,r=0,a,i,l,o;function c(u){for(a=[],i=u.length,l=0;l0&&a[0].getDepth()<=t&&c(a)}const d=this.getStage();return n.nodeType!==Ags&&d&&c(d.getChildren()),r}getDepth(){let t=0,n=this.parent;for(;n;)t++,n=n.parent;return t}_batchTransformChanges(t){this._batchingTransformChange=!0,t(),this._batchingTransformChange=!1,this._needClearTransformCache&&(this._clearCache(zk),this._clearSelfAndDescendantCache(f2)),this._needClearTransformCache=!1}setPosition(t){return this._batchTransformChanges(()=>{this.x(t.x),this.y(t.y)}),this}getPosition(){return{x:this.x(),y:this.y()}}getRelativePointerPosition(){const t=this.getStage();if(!t)return null;const n=t.getPointerPosition();if(!n)return null;const r=this.getAbsoluteTransform().copy();return r.invert(),r.point(n)}getAbsolutePosition(t){let n=!1,r=this.parent;for(;r;){if(r.isCached()){n=!0;break}r=r.parent}n&&!t&&(t=!0);const a=this.getAbsoluteTransform(t).getMatrix(),i=new Y0,l=this.offset();return i.m=a.slice(),i.translate(l.x,l.y),i.getTranslation()}setAbsolutePosition(t){const{x:n,y:r,...a}=this._clearTransform();this.attrs.x=n,this.attrs.y=r,this._clearCache(zk);const i=this._getAbsoluteTransform().copy();return i.invert(),i.translate(t.x,t.y),t={x:this.attrs.x+i.getTranslation().x,y:this.attrs.y+i.getTranslation().y},this._setTransform(a),this.setPosition({x:t.x,y:t.y}),this._clearCache(zk),this._clearSelfAndDescendantCache(f2),this}_setTransform(t){let n;for(n in t)this.attrs[n]=t[n]}_clearTransform(){const t={x:this.x(),y:this.y(),rotation:this.rotation(),scaleX:this.scaleX(),scaleY:this.scaleY(),offsetX:this.offsetX(),offsetY:this.offsetY(),skewX:this.skewX(),skewY:this.skewY()};return this.attrs.x=0,this.attrs.y=0,this.attrs.rotation=0,this.attrs.scaleX=1,this.attrs.scaleY=1,this.attrs.offsetX=0,this.attrs.offsetY=0,this.attrs.skewX=0,this.attrs.skewY=0,t}move(t){let n=t.x,r=t.y,a=this.x(),i=this.y();return n!==void 0&&(a+=n),r!==void 0&&(i+=r),this.setPosition({x:a,y:i}),this}_eachAncestorReverse(t,n){let r=[],a=this.getParent(),i,l;if(!(n&&n._id===this._id)){for(r.unshift(this);a&&(!n||a._id!==n._id);)r.unshift(a),a=a.parent;for(i=r.length,l=0;l0?(this.parent.children.splice(t,1),this.parent.children.splice(t-1,0,this),this.parent._setChildrenIndices(),!0):!1}moveToBottom(){if(!this.parent)return yn.warn("Node has no parent. moveToBottom function is ignored."),!1;const t=this.index;return t>0?(this.parent.children.splice(t,1),this.parent.children.unshift(this),this.parent._setChildrenIndices(),!0):!1}setZIndex(t){if(!this.parent)return yn.warn("Node has no parent. zIndex parameter is ignored."),this;(t<0||t>=this.parent.children.length)&&yn.warn("Unexpected value "+t+" for zIndex property. zIndex is just index of a node in children of its parent. Expected value is from 0 to "+(this.parent.children.length-1)+".");const n=this.index;return this.parent.children.splice(n,1),this.parent.children.splice(t,0,this),this.parent._setChildrenIndices(),this}getAbsoluteOpacity(){return this._getCache($me,this._getAbsoluteOpacity)}_getAbsoluteOpacity(){let t=this.opacity();const n=this.getParent();return n&&!n._isUnderCache&&(t*=n.getAbsoluteOpacity()),t}moveTo(t){return this.getParent()!==t&&(this._remove(),t.add(this)),this}toObject(){let t=this.getAttrs(),n,r,a,i,l;const o={attrs:{},className:this.getClassName()};for(n in t)r=t[n],l=yn.isObject(r)&&!yn._isPlainObject(r)&&!yn._isArray(r),!l&&(a=typeof this[n]=="function"&&this[n],delete t[n],i=a?a.call(this):null,t[n]=r,i!==r&&(o.attrs[n]=r));return yn._prepareToStringify(o)}toJSON(){return JSON.stringify(this.toObject())}getParent(){return this.parent}findAncestors(t,n,r){const a=[];n&&this._isMatch(t)&&a.push(this);let i=this.parent;for(;i;){if(i===r)return a;i._isMatch(t)&&a.push(i),i=i.parent}return a}isAncestorOf(t){return!1}findAncestor(t,n,r){return this.findAncestors(t,n,r)[0]}_isMatch(t){if(!t)return!1;if(typeof t=="function")return t(this);let n=t.replace(/ /g,"").split(","),r=n.length,a,i;for(a=0;a{try{const a=t==null?void 0:t.callback;a&&delete t.callback,yn._urlToImage(this.toDataURL(t),function(i){n(i),a==null||a(i)})}catch(a){r(a)}})}toBlob(t){return new Promise((n,r)=>{try{const a=t==null?void 0:t.callback;a&&delete t.callback,this.toCanvas(t).toBlob(i=>{n(i),a==null||a(i)},t==null?void 0:t.mimeType,t==null?void 0:t.quality)}catch(a){r(a)}})}setSize(t){return this.width(t.width),this.height(t.height),this}getSize(){return{width:this.width(),height:this.height()}}getClassName(){return this.className||this.nodeType}getType(){return this.nodeType}getDragDistance(){return this.attrs.dragDistance!==void 0?this.attrs.dragDistance:this.parent?this.parent.getDragDistance():ua.dragDistance}_off(t,n,r){let a=this.eventListeners[t],i,l,o;for(i=0;i=0)||this.isDragging())return;let a=!1;zl._dragElements.forEach(i=>{this.isAncestorOf(i.node)&&(a=!0)}),a||this._createDragElement(t)})}_dragChange(){if(this.attrs.draggable)this._listenDrag();else{if(this._dragCleanup(),!this.getStage())return;const n=zl._dragElements.get(this._id),r=n&&n.dragStatus==="dragging",a=n&&n.dragStatus==="ready";r?this.stopDrag():a&&zl._dragElements.delete(this._id)}}_dragCleanup(){this.off("mousedown.konva"),this.off("touchstart.konva")}isClientRectOnScreen(t={x:0,y:0}){const n=this.getStage();if(!n)return!1;const r={x:-t.x,y:-t.y,width:n.width()+2*t.x,height:n.height()+2*t.y};return yn.haveIntersection(r,this.getClientRect())}static create(t,n){return yn._isString(t)&&(t=JSON.parse(t)),this._createNode(t,n)}static _createNode(t,n){let r=o7.prototype.getClassName.call(t),a=t.children,i,l,o;n&&(t.attrs.container=n),ua[r]||(yn.warn('Can not find a node with class name "'+r+'". Fallback to "Shape".'),r="Shape");const c=ua[r];if(i=new c(t.attrs),a)for(l=a.length,o=0;o0}removeChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.remove()}),this.children=[],this._requestDraw(),this}destroyChildren(){return this.getChildren().forEach(t=>{t.parent=null,t.index=0,t.destroy()}),this.children=[],this._requestDraw(),this}add(...t){if(t.length===0)return this;if(t.length>1){for(let r=0;r0?n[0]:void 0}_generalFind(t,n){const r=[];return this._descendants(a=>{const i=a._isMatch(t);return i&&r.push(a),!!(i&&n)}),r}_descendants(t){let n=!1;const r=this.getChildren();for(const a of r){if(n=t(a),n)return!0;if(a.hasChildren()&&(n=a._descendants(t),n))return!0}return!1}toObject(){const t=fa.prototype.toObject.call(this);return t.children=[],this.getChildren().forEach(n=>{t.children.push(n.toObject())}),t}isAncestorOf(t){let n=t.getParent();for(;n;){if(n._id===this._id)return!0;n=n.getParent()}return!1}clone(t){const n=fa.prototype.clone.call(this,t);return this.getChildren().forEach(function(r){n.add(r.clone())}),n}getAllIntersections(t){const n=[];return this.find("Shape").forEach(r=>{r.isVisible()&&r.intersects(t)&&n.push(r)}),n}_clearSelfAndDescendantCache(t){var n;super._clearSelfAndDescendantCache(t),!this.isCached()&&((n=this.children)===null||n===void 0||n.forEach(function(r){r._clearSelfAndDescendantCache(t)}))}_setChildrenIndices(){var t;(t=this.children)===null||t===void 0||t.forEach(function(n,r){n.index=r}),this._requestDraw()}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas(),l=i&&i.getContext(),o=this._getCanvasCache(),c=o&&o.scene,d=i&&i.isCache;if(!this.isVisible()&&!d)return this;if(c){l.save();const u=this.getAbsoluteTransform(n).getMatrix();l.transform(u[0],u[1],u[2],u[3],u[4],u[5]),this._drawCachedSceneCanvas(l),l.restore()}else this._drawChildren("drawScene",i,n,r);return this}drawHit(t,n){if(!this.shouldDrawHit(n))return this;const r=this.getLayer(),a=t||r&&r.hitCanvas,i=a&&a.getContext(),l=this._getCanvasCache();if(l&&l.hit){i.save();const c=this.getAbsoluteTransform(n).getMatrix();i.transform(c[0],c[1],c[2],c[3],c[4],c[5]),this._drawCachedHitCanvas(i),i.restore()}else this._drawChildren("drawHit",a,n);return this}_drawChildren(t,n,r,a){var i;const l=n&&n.getContext(),o=this.clipWidth(),c=this.clipHeight(),d=this.clipFunc(),u=typeof o=="number"&&typeof c=="number"||d,h=r===this;if(u){l.save();const f=this.getAbsoluteTransform(r);let y=f.getMatrix();l.transform(y[0],y[1],y[2],y[3],y[4],y[5]),l.beginPath();let _;if(d)_=d.call(this,l,this);else{const v=this.clipX(),j=this.clipY();l.rect(v||0,j||0,o,c)}l.clip.apply(l,_),y=f.copy().invert().getMatrix(),l.transform(y[0],y[1],y[2],y[3],y[4],y[5])}const p=!h&&this.globalCompositeOperation()!=="source-over"&&t==="drawScene";p&&(l.save(),l._applyGlobalCompositeOperation(this)),(i=this.children)===null||i===void 0||i.forEach(function(f){f[t](n,r,a)}),p&&l.restore(),u&&l.restore()}getClientRect(t={}){var n;const r=t.skipTransform,a=t.relativeTo;let i,l,o,c,d={x:1/0,y:1/0,width:0,height:0};const u=this;(n=this.children)===null||n===void 0||n.forEach(function(f){if(!f.visible())return;const y=f.getClientRect({relativeTo:u,skipShadow:t.skipShadow,skipStroke:t.skipStroke});y.width===0&&y.height===0||(i===void 0?(i=y.x,l=y.y,o=y.x+y.width,c=y.y+y.height):(i=Math.min(i,y.x),l=Math.min(l,y.y),o=Math.max(o,y.x+y.width),c=Math.max(c,y.y+y.height)))});const h=this.find("Shape");let p=!1;for(let f=0;fs.indexOf("pointer")>=0?"pointer":s.indexOf("touch")>=0?"touch":"mouse",jI=s=>{const t=h7(s);if(t==="pointer")return ua.pointerEventsEnabled&&d2e.pointer;if(t==="touch")return d2e.touch;if(t==="mouse")return d2e.mouse};function DVe(s={}){return(s.clipFunc||s.clipWidth||s.clipHeight)&&yn.warn("Stage does not support clipping. Please use clip for Layers or Groups."),s}const zgs="Pointer position is missing and not registered by the stage. Looks like it is outside of the stage container. You can set it manually from event: stage.setPointersPositions(event);",az=[];let eve=class extends dy{constructor(t){super(DVe(t)),this._pointerPositions=[],this._changedPointerPositions=[],this._buildDOM(),this._bindContentEvents(),az.push(this),this.on("widthChange.konva heightChange.konva",this._resizeDOM),this.on("visibleChange.konva",this._checkVisibility),this.on("clipWidthChange.konva clipHeightChange.konva clipFuncChange.konva",()=>{DVe(this.attrs)}),this._checkVisibility()}_validateAdd(t){const n=t.getType()==="Layer",r=t.getType()==="FastLayer";n||r||yn.throw("You may only add layers to the stage.")}_checkVisibility(){if(!this.content)return;const t=this.visible()?"":"none";this.content.style.display=t}setContainer(t){if(typeof t===Lgs){let n;if(t.charAt(0)==="."){const r=t.slice(1);t=document.getElementsByClassName(r)[0]}else t.charAt(0)!=="#"?n=t:n=t.slice(1),t=document.getElementById(n);if(!t)throw"Can not find container in document with id "+n}return this._setAttr("container",t),this.content&&(this.content.parentElement&&this.content.parentElement.removeChild(this.content),t.appendChild(this.content)),this}shouldDrawHit(){return!0}clear(){const t=this.children,n=t.length;for(let r=0;r-1&&az.splice(n,1),yn.releaseCanvas(this.bufferCanvas._canvas,this.bufferHitCanvas._canvas),this}getPointerPosition(){const t=this._pointerPositions[0]||this._changedPointerPositions[0];return t?{x:t.x,y:t.y}:(yn.warn(zgs),null)}_getPointerById(t){return this._pointerPositions.find(n=>n.id===t)}getPointersPositions(){return this._pointerPositions}getStage(){return this}getContent(){return this.content}_toKonvaCanvas(t){t={...t},t.x=t.x||0,t.y=t.y||0,t.width=t.width||this.width(),t.height=t.height||this.height();const n=new lS({width:t.width,height:t.height,pixelRatio:t.pixelRatio||1}),r=n.getContext()._context,a=this.children;return(t.x||t.y)&&r.translate(-1*t.x,-1*t.y),a.forEach(function(i){if(!i.isVisible())return;const l=i._toKonvaCanvas(t);r.drawImage(l._canvas,t.x,t.y,l.getWidth()/l.getPixelRatio(),l.getHeight()/l.getPixelRatio())}),n}getIntersection(t){if(!t)return null;const n=this.children,r=n.length,a=r-1;for(let i=a;i>=0;i--){const l=n[i].getIntersection(t);if(l)return l}return null}_resizeDOM(){const t=this.width(),n=this.height();this.content&&(this.content.style.width=t+LVe,this.content.style.height=n+LVe),this.bufferCanvas.setSize(t,n),this.bufferHitCanvas.setSize(t,n),this.children.forEach(r=>{r.setSize({width:t,height:n}),r.draw()})}add(t,...n){if(arguments.length>1){for(let a=0;aOgs&&yn.warn("The stage has "+r+" layers. Recommended maximum number of layers is 3-5. Adding more layers into the stage may drop the performance. Rethink your tree structure, you can use Konva.Group."),t.setSize({width:this.width(),height:this.height()}),t.draw(),ua.isBrowser&&this.content.appendChild(t.canvas._canvas),this}getParent(){return null}getLayer(){return null}hasPointerCapture(t){return fgt(t,this)}setPointerCapture(t){xgt(t,this)}releaseCapture(t){rz(t)}getLayers(){return this.children}_bindContentEvents(){ua.isBrowser&&Fgs.forEach(([t,n])=>{this.content.addEventListener(t,r=>{this[n](r)},{passive:!1})})}_pointerenter(t){this.setPointersPositions(t);const n=jI(t.type);n&&this._fire(n.pointerenter,{evt:t,target:this,currentTarget:this})}_pointerover(t){this.setPointersPositions(t);const n=jI(t.type);n&&this._fire(n.pointerover,{evt:t,target:this,currentTarget:this})}_getTargetShape(t){let n=this[t+"targetShape"];return n&&!n.getStage()&&(n=null),n}_pointerleave(t){const n=jI(t.type),r=h7(t.type);if(!n)return;this.setPointersPositions(t);const a=this._getTargetShape(r),i=!(ua.isDragging()||ua.isTransforming())||ua.hitOnDragEnabled;a&&i?(a._fireAndBubble(n.pointerout,{evt:t}),a._fireAndBubble(n.pointerleave,{evt:t}),this._fire(n.pointerleave,{evt:t,target:this,currentTarget:this}),this[r+"targetShape"]=null):i&&(this._fire(n.pointerleave,{evt:t,target:this,currentTarget:this}),this._fire(n.pointerout,{evt:t,target:this,currentTarget:this})),this.pointerPos=null,this._pointerPositions=[]}_pointerdown(t){const n=jI(t.type),r=h7(t.type);if(!n)return;this.setPointersPositions(t);let a=!1;this._changedPointerPositions.forEach(i=>{const l=this.getIntersection(i);if(zl.justDragged=!1,ua["_"+r+"ListenClick"]=!0,!l||!l.isListening()){this[r+"ClickStartShape"]=void 0;return}ua.capturePointerEventsEnabled&&l.setPointerCapture(i.id),this[r+"ClickStartShape"]=l,l._fireAndBubble(n.pointerdown,{evt:t,pointerId:i.id}),a=!0;const o=t.type.indexOf("touch")>=0;l.preventDefault()&&t.cancelable&&o&&t.preventDefault()}),a||this._fire(n.pointerdown,{evt:t,target:this,currentTarget:this,pointerId:this._pointerPositions[0].id})}_pointermove(t){const n=jI(t.type),r=h7(t.type);if(!n)return;const a=t.type.indexOf("touch")>=0||t.pointerType==="touch";if(ua.isDragging()&&zl.node.preventDefault()&&t.cancelable&&a&&t.preventDefault(),this.setPointersPositions(t),!(!(ua.isDragging()||ua.isTransforming())||ua.hitOnDragEnabled))return;const l={};let o=!1;const c=this._getTargetShape(r);this._changedPointerPositions.forEach(d=>{const u=c2e(d.id)||this.getIntersection(d),h=d.id,p={evt:t,pointerId:h},f=c!==u;if(f&&c&&(c._fireAndBubble(n.pointerout,{...p},u),c._fireAndBubble(n.pointerleave,{...p},u)),u){if(l[u._id])return;l[u._id]=!0}u&&u.isListening()?(o=!0,f&&(u._fireAndBubble(n.pointerover,{...p},c),u._fireAndBubble(n.pointerenter,{...p},c),this[r+"targetShape"]=u),u._fireAndBubble(n.pointermove,{...p})):c&&(this._fire(n.pointerover,{evt:t,target:this,currentTarget:this,pointerId:h}),this[r+"targetShape"]=null)}),o||this._fire(n.pointermove,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id})}_pointerup(t){const n=jI(t.type),r=h7(t.type);if(!n)return;this.setPointersPositions(t);const a=this[r+"ClickStartShape"],i=this[r+"ClickEndShape"],l={};let o=!1;this._changedPointerPositions.forEach(c=>{const d=c2e(c.id)||this.getIntersection(c);if(d){if(d.releaseCapture(c.id),l[d._id])return;l[d._id]=!0}const u=c.id,h={evt:t,pointerId:u};let p=!1;ua["_"+r+"InDblClickWindow"]?(p=!0,clearTimeout(this[r+"DblTimeout"])):zl.justDragged||(ua["_"+r+"InDblClickWindow"]=!0,clearTimeout(this[r+"DblTimeout"])),this[r+"DblTimeout"]=setTimeout(function(){ua["_"+r+"InDblClickWindow"]=!1},ua.dblClickWindow),d&&d.isListening()?(o=!0,this[r+"ClickEndShape"]=d,d._fireAndBubble(n.pointerup,{...h}),ua["_"+r+"ListenClick"]&&a&&a===d&&(d._fireAndBubble(n.pointerclick,{...h}),p&&i&&i===d&&d._fireAndBubble(n.pointerdblclick,{...h}))):(this[r+"ClickEndShape"]=null,o||(this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),o=!0),ua["_"+r+"ListenClick"]&&this._fire(n.pointerclick,{evt:t,target:this,currentTarget:this,pointerId:u}),p&&this._fire(n.pointerdblclick,{evt:t,target:this,currentTarget:this,pointerId:u}))}),o||this._fire(n.pointerup,{evt:t,target:this,currentTarget:this,pointerId:this._changedPointerPositions[0].id}),ua["_"+r+"ListenClick"]=!1,t.cancelable&&r!=="touch"&&r!=="pointer"&&t.preventDefault()}_contextmenu(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(qCe,{evt:t}):this._fire(qCe,{evt:t,target:this,currentTarget:this})}_wheel(t){this.setPointersPositions(t);const n=this.getIntersection(this.getPointerPosition());n&&n.isListening()?n._fireAndBubble(VCe,{evt:t}):this._fire(VCe,{evt:t,target:this,currentTarget:this})}_pointercancel(t){this.setPointersPositions(t);const n=c2e(t.pointerId)||this.getIntersection(this.getPointerPosition());n&&n._fireAndBubble(CP,hIe(t)),rz(t.pointerId)}_lostpointercapture(t){rz(t.pointerId)}setPointersPositions(t){const n=this._getContentPosition();let r=null,a=null;t=t||window.event,t.touches!==void 0?(this._pointerPositions=[],this._changedPointerPositions=[],Array.prototype.forEach.call(t.touches,i=>{this._pointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})}),Array.prototype.forEach.call(t.changedTouches||t.touches,i=>{this._changedPointerPositions.push({id:i.identifier,x:(i.clientX-n.left)/n.scaleX,y:(i.clientY-n.top)/n.scaleY})})):(r=(t.clientX-n.left)/n.scaleX,a=(t.clientY-n.top)/n.scaleY,this.pointerPos={x:r,y:a},this._pointerPositions=[{x:r,y:a,id:yn._getFirstPointerId(t)}],this._changedPointerPositions=[{x:r,y:a,id:yn._getFirstPointerId(t)}])}_setPointerPosition(t){yn.warn('Method _setPointerPosition is deprecated. Use "stage.setPointersPositions(event)" instead.'),this.setPointersPositions(t)}_getContentPosition(){if(!this.content||!this.content.getBoundingClientRect)return{top:0,left:0,scaleX:1,scaleY:1};const t=this.content.getBoundingClientRect();return{top:t.top,left:t.left,scaleX:t.width/this.content.clientWidth||1,scaleY:t.height/this.content.clientHeight||1}}_buildDOM(){if(this.bufferCanvas=new lS({width:this.width(),height:this.height()}),this.bufferHitCanvas=new dIe({pixelRatio:1,width:this.width(),height:this.height()}),!ua.isBrowser)return;const t=this.container();if(!t)throw"Stage has no container. A container is required.";t.innerHTML="",this.content=document.createElement("div"),this.content.style.position="relative",this.content.style.userSelect="none",this.content.className="konvajs-content",this.content.setAttribute("role","presentation"),t.appendChild(this.content),this._resizeDOM()}cache(){return yn.warn("Cache function is not allowed for stage. You may use cache only for layers, groups and shapes."),this}clearCache(){return this}batchDraw(){return this.getChildren().forEach(function(t){t.batchDraw()}),this}};eve.prototype.nodeType=Pgs;Fu(eve);Rs.addGetterSetter(eve,"container");ua.isBrowser&&document.addEventListener("visibilitychange",()=>{az.forEach(s=>{s.batchDraw()})});const Cgt="hasShadow",Tgt="shadowRGBA",Egt="patternImage",Agt="linearGradient",Mgt="radialGradient";let AH;function u2e(){return AH||(AH=yn.createCanvasElement().getContext("2d"),AH)}const iz={};function Bgs(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function $gs(s){s.stroke()}function Ugs(s){const t=this.attrs.fillRule;t?s.fill(t):s.fill()}function qgs(s){s.stroke()}function Vgs(){this._clearCache(Cgt)}function Hgs(){this._clearCache(Tgt)}function Ggs(){this._clearCache(Egt)}function Wgs(){this._clearCache(Agt)}function Kgs(){this._clearCache(Mgt)}let Wr=class extends fa{constructor(t){super(t);let n,r=0;for(;n=yn.getHitColor(),!(n&&!(n in iz));)if(r++,r>=1e4){yn.warn("Failed to find a unique color key for a shape. Konva may work incorrectly. Most likely your browser is using canvas farbling. Consider disabling it."),n=yn.getRandomColor();break}this.colorKey=n,iz[n]=this}getContext(){return yn.warn("shape.getContext() method is deprecated. Please do not use it."),this.getLayer().getContext()}getCanvas(){return yn.warn("shape.getCanvas() method is deprecated. Please do not use it."),this.getLayer().getCanvas()}getSceneFunc(){return this.attrs.sceneFunc||this._sceneFunc}getHitFunc(){return this.attrs.hitFunc||this._hitFunc}hasShadow(){return this._getCache(Cgt,this._hasShadow)}_hasShadow(){return this.shadowEnabled()&&this.shadowOpacity()!==0&&!!(this.shadowColor()||this.shadowBlur()||this.shadowOffsetX()||this.shadowOffsetY())}_getFillPattern(){return this._getCache(Egt,this.__getFillPattern)}__getFillPattern(){if(this.fillPatternImage()){const n=u2e().createPattern(this.fillPatternImage(),this.fillPatternRepeat()||"repeat");if(n&&n.setTransform){const r=new Y0;r.translate(this.fillPatternX(),this.fillPatternY()),r.rotate(ua.getAngle(this.fillPatternRotation())),r.scale(this.fillPatternScaleX(),this.fillPatternScaleY()),r.translate(-1*this.fillPatternOffsetX(),-1*this.fillPatternOffsetY());const a=r.getMatrix(),i=typeof DOMMatrix>"u"?{a:a[0],b:a[1],c:a[2],d:a[3],e:a[4],f:a[5]}:new DOMMatrix(a);n.setTransform(i)}return n}}_getLinearGradient(){return this._getCache(Agt,this.__getLinearGradient)}__getLinearGradient(){const t=this.fillLinearGradientColorStops();if(t){const n=u2e(),r=this.fillLinearGradientStartPoint(),a=this.fillLinearGradientEndPoint(),i=n.createLinearGradient(r.x,r.y,a.x,a.y);for(let l=0;lthis.fillEnabled()&&!!(this.fill()||this.fillPatternImage()||this.fillLinearGradientColorStops()||this.fillRadialGradientColorStops()))}hasStroke(){return this._calculate("hasStroke",["strokeEnabled","strokeWidth","stroke","strokeLinearGradientColorStops"],()=>this.strokeEnabled()&&this.strokeWidth()&&!!(this.stroke()||this.strokeLinearGradientColorStops()))}hasHitStroke(){const t=this.hitStrokeWidth();return t==="auto"?this.hasStroke():this.strokeEnabled()&&!!t}intersects(t){const n=this.getStage();if(!n)return!1;const r=n.bufferHitCanvas;return r.getContext().clear(),this.drawHit(r,void 0,!0),r.context.getImageData(Math.round(t.x),Math.round(t.y),1,1).data[3]>0}destroy(){return fa.prototype.destroy.call(this),delete iz[this.colorKey],delete this.colorKey,this}_useBufferCanvas(t){var n;if(!((n=this.attrs.perfectDrawEnabled)!==null&&n!==void 0?n:!0))return!1;const a=t||this.hasFill(),i=this.hasStroke(),l=this.getAbsoluteOpacity()!==1;if(a&&i&&l)return!0;const o=this.hasShadow(),c=this.shadowForStrokeEnabled();return!!(a&&i&&o&&c)}setStrokeHitEnabled(t){yn.warn("strokeHitEnabled property is deprecated. Please use hitStrokeWidth instead."),t?this.hitStrokeWidth("auto"):this.hitStrokeWidth(0)}getStrokeHitEnabled(){return this.hitStrokeWidth()!==0}getSelfRect(){const t=this.size();return{x:this._centroid?-t.width/2:0,y:this._centroid?-t.height/2:0,width:t.width,height:t.height}}getClientRect(t={}){let n=!1,r=this.getParent();for(;r;){if(r.isCached()){n=!0;break}r=r.getParent()}const a=t.skipTransform,i=t.relativeTo||n&&this.getStage()||void 0,l=this.getSelfRect(),c=!t.skipStroke&&this.hasStroke()&&this.strokeWidth()||0,d=l.width+c,u=l.height+c,h=!t.skipShadow&&this.hasShadow(),p=h?this.shadowOffsetX():0,f=h?this.shadowOffsetY():0,y=d+Math.abs(p),_=u+Math.abs(f),v=h&&this.shadowBlur()||0,j=y+v*2,w=_+v*2,S={width:j,height:w,x:-(c/2+v)+Math.min(p,0)+l.x,y:-(c/2+v)+Math.min(f,0)+l.y};return a?S:this._transformedRect(S,i)}drawScene(t,n,r){const a=this.getLayer(),i=t||a.getCanvas(),l=i.getContext(),o=this._getCanvasCache(),c=this.getSceneFunc(),d=this.hasShadow();let u;const h=!1,p=n===this;if(!this.isVisible()&&!p)return this;if(o){l.save();const f=this.getAbsoluteTransform(n).getMatrix();return l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),this._drawCachedSceneCanvas(l),l.restore(),this}if(!c)return this;if(l.save(),this._useBufferCanvas()&&!h){u=this.getStage();const f=r||u.bufferCanvas,y=f.getContext();r?(y.save(),y.setTransform(1,0,0,1,0,0),y.clearRect(0,0,f.width,f.height),y.restore()):y.clear(),y.save(),y._applyLineJoin(this),y._applyMiterLimit(this);const _=this.getAbsoluteTransform(n).getMatrix();y.transform(_[0],_[1],_[2],_[3],_[4],_[5]),c.call(this,y,this),y.restore();const v=f.pixelRatio;d&&l._applyShadow(this),p||(l._applyOpacity(this),l._applyGlobalCompositeOperation(this)),l.drawImage(f._canvas,f.x||0,f.y||0,f.width/v,f.height/v)}else{if(l._applyLineJoin(this),l._applyMiterLimit(this),!p){const f=this.getAbsoluteTransform(n).getMatrix();l.transform(f[0],f[1],f[2],f[3],f[4],f[5]),l._applyOpacity(this),l._applyGlobalCompositeOperation(this)}d&&l._applyShadow(this),c.call(this,l,this)}return l.restore(),this}drawHit(t,n,r=!1){if(!this.shouldDrawHit(n,r))return this;const a=this.getLayer(),i=t||a.hitCanvas,l=i&&i.getContext(),o=this.hitFunc()||this.sceneFunc(),c=this._getCanvasCache(),d=c&&c.hit;if(this.colorKey||yn.warn("Looks like your canvas has a destroyed shape in it. Do not reuse shape after you destroyed it. If you want to reuse shape you should call remove() instead of destroy()"),d){l.save();const h=this.getAbsoluteTransform(n).getMatrix();return l.transform(h[0],h[1],h[2],h[3],h[4],h[5]),this._drawCachedHitCanvas(l),l.restore(),this}if(!o)return this;if(l.save(),l._applyLineJoin(this),l._applyMiterLimit(this),!(this===n)){const h=this.getAbsoluteTransform(n).getMatrix();l.transform(h[0],h[1],h[2],h[3],h[4],h[5])}return o.call(this,l,this),l.restore(),this}drawHitFromCache(t=0){const n=this._getCanvasCache(),r=this._getCachedSceneCanvas(),a=n.hit,i=a.getContext(),l=a.getWidth(),o=a.getHeight();i.clear(),i.drawImage(r._canvas,0,0,l,o);try{const c=i.getImageData(0,0,l,o),d=c.data,u=d.length,h=yn._hexToRgb(this.colorKey);for(let p=0;pt?(d[p]=h.r,d[p+1]=h.g,d[p+2]=h.b,d[p+3]=255):d[p+3]=0;i.putImageData(c,0,0)}catch(c){yn.error("Unable to draw hit graph from cached scene canvas. "+c.message)}return this}hasPointerCapture(t){return fgt(t,this)}setPointerCapture(t){xgt(t,this)}releaseCapture(t){rz(t)}};Wr.prototype._fillFunc=Bgs;Wr.prototype._strokeFunc=$gs;Wr.prototype._fillFuncHit=Ugs;Wr.prototype._strokeFuncHit=qgs;Wr.prototype._centroid=!1;Wr.prototype.nodeType="Shape";Fu(Wr);Wr.prototype.eventListeners={};Wr.prototype.on("shadowColorChange.konva shadowBlurChange.konva shadowOffsetChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Vgs);Wr.prototype.on("shadowColorChange.konva shadowOpacityChange.konva shadowEnabledChange.konva",Hgs);Wr.prototype.on("fillPriorityChange.konva fillPatternImageChange.konva fillPatternRepeatChange.konva fillPatternScaleXChange.konva fillPatternScaleYChange.konva fillPatternOffsetXChange.konva fillPatternOffsetYChange.konva fillPatternXChange.konva fillPatternYChange.konva fillPatternRotationChange.konva",Ggs);Wr.prototype.on("fillPriorityChange.konva fillLinearGradientColorStopsChange.konva fillLinearGradientStartPointXChange.konva fillLinearGradientStartPointYChange.konva fillLinearGradientEndPointXChange.konva fillLinearGradientEndPointYChange.konva",Wgs);Wr.prototype.on("fillPriorityChange.konva fillRadialGradientColorStopsChange.konva fillRadialGradientStartPointXChange.konva fillRadialGradientStartPointYChange.konva fillRadialGradientEndPointXChange.konva fillRadialGradientEndPointYChange.konva fillRadialGradientStartRadiusChange.konva fillRadialGradientEndRadiusChange.konva",Kgs);Rs.addGetterSetter(Wr,"stroke",void 0,mgt());Rs.addGetterSetter(Wr,"strokeWidth",2,ta());Rs.addGetterSetter(Wr,"fillAfterStrokeEnabled",!1);Rs.addGetterSetter(Wr,"hitStrokeWidth","auto",uIe());Rs.addGetterSetter(Wr,"strokeHitEnabled",!0,Ib());Rs.addGetterSetter(Wr,"perfectDrawEnabled",!0,Ib());Rs.addGetterSetter(Wr,"shadowForStrokeEnabled",!0,Ib());Rs.addGetterSetter(Wr,"lineJoin");Rs.addGetterSetter(Wr,"lineCap");Rs.addGetterSetter(Wr,"miterLimit");Rs.addGetterSetter(Wr,"sceneFunc");Rs.addGetterSetter(Wr,"hitFunc");Rs.addGetterSetter(Wr,"dash");Rs.addGetterSetter(Wr,"dashOffset",0,ta());Rs.addGetterSetter(Wr,"shadowColor",void 0,qM());Rs.addGetterSetter(Wr,"shadowBlur",0,ta());Rs.addGetterSetter(Wr,"shadowOpacity",1,ta());Rs.addComponentsGetterSetter(Wr,"shadowOffset",["x","y"]);Rs.addGetterSetter(Wr,"shadowOffsetX",0,ta());Rs.addGetterSetter(Wr,"shadowOffsetY",0,ta());Rs.addGetterSetter(Wr,"fillPatternImage");Rs.addGetterSetter(Wr,"fill",void 0,mgt());Rs.addGetterSetter(Wr,"fillPatternX",0,ta());Rs.addGetterSetter(Wr,"fillPatternY",0,ta());Rs.addGetterSetter(Wr,"fillLinearGradientColorStops");Rs.addGetterSetter(Wr,"strokeLinearGradientColorStops");Rs.addGetterSetter(Wr,"fillRadialGradientStartRadius",0);Rs.addGetterSetter(Wr,"fillRadialGradientEndRadius",0);Rs.addGetterSetter(Wr,"fillRadialGradientColorStops");Rs.addGetterSetter(Wr,"fillPatternRepeat","repeat");Rs.addGetterSetter(Wr,"fillEnabled",!0);Rs.addGetterSetter(Wr,"strokeEnabled",!0);Rs.addGetterSetter(Wr,"shadowEnabled",!0);Rs.addGetterSetter(Wr,"dashEnabled",!0);Rs.addGetterSetter(Wr,"strokeScaleEnabled",!0);Rs.addGetterSetter(Wr,"fillPriority","color");Rs.addComponentsGetterSetter(Wr,"fillPatternOffset",["x","y"]);Rs.addGetterSetter(Wr,"fillPatternOffsetX",0,ta());Rs.addGetterSetter(Wr,"fillPatternOffsetY",0,ta());Rs.addComponentsGetterSetter(Wr,"fillPatternScale",["x","y"]);Rs.addGetterSetter(Wr,"fillPatternScaleX",1,ta());Rs.addGetterSetter(Wr,"fillPatternScaleY",1,ta());Rs.addComponentsGetterSetter(Wr,"fillLinearGradientStartPoint",["x","y"]);Rs.addComponentsGetterSetter(Wr,"strokeLinearGradientStartPoint",["x","y"]);Rs.addGetterSetter(Wr,"fillLinearGradientStartPointX",0);Rs.addGetterSetter(Wr,"strokeLinearGradientStartPointX",0);Rs.addGetterSetter(Wr,"fillLinearGradientStartPointY",0);Rs.addGetterSetter(Wr,"strokeLinearGradientStartPointY",0);Rs.addComponentsGetterSetter(Wr,"fillLinearGradientEndPoint",["x","y"]);Rs.addComponentsGetterSetter(Wr,"strokeLinearGradientEndPoint",["x","y"]);Rs.addGetterSetter(Wr,"fillLinearGradientEndPointX",0);Rs.addGetterSetter(Wr,"strokeLinearGradientEndPointX",0);Rs.addGetterSetter(Wr,"fillLinearGradientEndPointY",0);Rs.addGetterSetter(Wr,"strokeLinearGradientEndPointY",0);Rs.addComponentsGetterSetter(Wr,"fillRadialGradientStartPoint",["x","y"]);Rs.addGetterSetter(Wr,"fillRadialGradientStartPointX",0);Rs.addGetterSetter(Wr,"fillRadialGradientStartPointY",0);Rs.addComponentsGetterSetter(Wr,"fillRadialGradientEndPoint",["x","y"]);Rs.addGetterSetter(Wr,"fillRadialGradientEndPointX",0);Rs.addGetterSetter(Wr,"fillRadialGradientEndPointY",0);Rs.addGetterSetter(Wr,"fillPatternRotation",0);Rs.addGetterSetter(Wr,"fillRule",void 0,qM());Rs.backCompat(Wr,{dashArray:"dash",getDashArray:"getDash",setDashArray:"getDash",drawFunc:"sceneFunc",getDrawFunc:"getSceneFunc",setDrawFunc:"setSceneFunc",drawHitFunc:"hitFunc",getDrawHitFunc:"getHitFunc",setDrawHitFunc:"setHitFunc"});const Ygs="beforeDraw",Zgs="draw",Igt=[{x:0,y:0},{x:-1,y:-1},{x:1,y:-1},{x:1,y:1},{x:-1,y:1}],Qgs=Igt.length;let VM=class extends dy{constructor(t){super(t),this.canvas=new lS,this.hitCanvas=new dIe({pixelRatio:1}),this._waitingForDraw=!1,this.on("visibleChange.konva",this._checkVisibility),this._checkVisibility(),this.on("imageSmoothingEnabledChange.konva",this._setSmoothEnabled),this._setSmoothEnabled()}createPNGStream(){return this.canvas._canvas.createPNGStream()}getCanvas(){return this.canvas}getNativeCanvasElement(){return this.canvas._canvas}getHitCanvas(){return this.hitCanvas}getContext(){return this.getCanvas().getContext()}clear(t){return this.getContext().clear(t),this.getHitCanvas().getContext().clear(t),this}setZIndex(t){super.setZIndex(t);const n=this.getStage();return n&&n.content&&(n.content.removeChild(this.getNativeCanvasElement()),t{this.draw(),this._waitingForDraw=!1})),this}getIntersection(t){if(!this.isListening()||!this.isVisible())return null;let n=1,r=!1;for(;;){for(let a=0;a0)return{antialiased:!0};return{}}drawScene(t,n,r){const a=this.getLayer(),i=t||a&&a.getCanvas();return this._fire(Ygs,{node:this}),this.clearBeforeDraw()&&i.getContext().clear(),dy.prototype.drawScene.call(this,i,n,r),this._fire(Zgs,{node:this}),this}drawHit(t,n){const r=this.getLayer(),a=t||r&&r.hitCanvas;return r&&r.clearBeforeDraw()&&r.getHitCanvas().getContext().clear(),dy.prototype.drawHit.call(this,a,n),this}enableHitGraph(){return this.hitGraphEnabled(!0),this}disableHitGraph(){return this.hitGraphEnabled(!1),this}setHitGraphEnabled(t){yn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening(t)}getHitGraphEnabled(t){return yn.warn("hitGraphEnabled method is deprecated. Please use layer.listening() instead."),this.listening()}toggleHitCanvas(){if(!this.parent||!this.parent.content)return;const t=this.parent;!!this.hitCanvas._canvas.parentNode?t.content.removeChild(this.hitCanvas._canvas):t.content.appendChild(this.hitCanvas._canvas)}destroy(){return yn.releaseCanvas(this.getNativeCanvasElement(),this.getHitCanvas()._canvas),super.destroy()}};VM.prototype.nodeType="Layer";Fu(VM);Rs.addGetterSetter(VM,"imageSmoothingEnabled",!0);Rs.addGetterSetter(VM,"clearBeforeDraw",!0);Rs.addGetterSetter(VM,"hitGraphEnabled",!0,Ib());class mIe extends VM{constructor(t){super(t),this.listening(!1),yn.warn('Konva.Fast layer is deprecated. Please use "new Konva.Layer({ listening: false })" instead.')}}mIe.prototype.nodeType="FastLayer";Fu(mIe);let T8=class extends dy{_validateAdd(t){const n=t.getType();n!=="Group"&&n!=="Shape"&&yn.throw("You may only add groups and shapes to groups.")}};T8.prototype.nodeType="Group";Fu(T8);const h2e=function(){return KE.performance&&KE.performance.now?function(){return KE.performance.now()}:function(){return new Date().getTime()}}();class jv{constructor(t,n){this.id=jv.animIdCounter++,this.frame={time:0,timeDiff:0,lastTime:h2e(),frameRate:0},this.func=t,this.setLayers(n)}setLayers(t){let n=[];return t&&(n=Array.isArray(t)?t:[t]),this.layers=n,this}getLayers(){return this.layers}addLayer(t){const n=this.layers,r=n.length;for(let a=0;athis.duration?this.yoyo?(this._time=this.duration,this.reverse()):this.finish():t<0?this.yoyo?(this._time=0,this.play()):this.reset():(this._time=t,this.update())}getTime(){return this._time}setPosition(t){this.prevPos=this._pos,this.propFunc(t),this._pos=t}getPosition(t){return t===void 0&&(t=this._time),this.func(t,this.begin,this._change,this.duration)}play(){this.state=RVe,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onPlay")}reverse(){this.state=OVe,this._time=this.duration-this._time,this._startTime=this.getTimer()-this._time,this.onEnterFrame(),this.fire("onReverse")}seek(t){this.pause(),this._time=t,this.update(),this.fire("onSeek")}reset(){this.pause(),this._time=0,this.update(),this.fire("onReset")}finish(){this.pause(),this._time=this.duration,this.update(),this.fire("onFinish")}update(){this.setPosition(this.getPosition(this._time)),this.fire("onUpdate")}onEnterFrame(){const t=this.getTimer()-this._startTime;this.state===RVe?this.setTime(t):this.state===OVe&&this.setTime(this.duration-t)}pause(){this.state=Jgs,this.fire("onPause")}getTimer(){return new Date().getTime()}}class pd{constructor(t){const n=this,r=t.node,a=r._id,i=t.easing||oz.Linear,l=!!t.yoyo;let o,c;typeof t.duration>"u"?o=.3:t.duration===0?o=.001:o=t.duration,this.node=r,this._id=e0s++;const d=r.getLayer()||(r instanceof ua.Stage?r.getLayers():null);d||yn.error("Tween constructor have `node` that is not in a layer. Please add node into layer first."),this.anim=new jv(function(){n.tween.onEnterFrame()},d),this.tween=new t0s(c,function(u){n._tweenFunc(u)},i,0,1,o*1e3,l),this._addListeners(),pd.attrs[a]||(pd.attrs[a]={}),pd.attrs[a][this._id]||(pd.attrs[a][this._id]={}),pd.tweens[a]||(pd.tweens[a]={});for(c in t)Xgs[c]===void 0&&this._addAttr(c,t[c]);this.reset(),this.onFinish=t.onFinish,this.onReset=t.onReset,this.onUpdate=t.onUpdate}_addAttr(t,n){const r=this.node,a=r._id;let i,l,o,c,d;const u=pd.tweens[a][t];u&&delete pd.attrs[a][u][t];let h=r.getAttr(t);if(yn._isArray(n))if(i=[],l=Math.max(n.length,h.length),t==="points"&&n.length!==h.length&&(n.length>h.length?(c=h,h=yn._prepareArrayForTween(h,n,r.closed())):(o=n,n=yn._prepareArrayForTween(n,h,r.closed()))),t.indexOf("fill")===0)for(let p=0;p{this.anim.start()},this.tween.onReverse=()=>{this.anim.start()},this.tween.onPause=()=>{this.anim.stop()},this.tween.onFinish=()=>{const t=this.node,n=pd.attrs[t._id][this._id];n.points&&n.points.trueEnd&&t.setAttr("points",n.points.trueEnd),this.onFinish&&this.onFinish.call(this)},this.tween.onReset=()=>{const t=this.node,n=pd.attrs[t._id][this._id];n.points&&n.points.trueStart&&t.points(n.points.trueStart),this.onReset&&this.onReset()},this.tween.onUpdate=()=>{this.onUpdate&&this.onUpdate.call(this)}}play(){return this.tween.play(),this}reverse(){return this.tween.reverse(),this}reset(){return this.tween.reset(),this}seek(t){return this.tween.seek(t*1e3),this}pause(){return this.tween.pause(),this}finish(){return this.tween.finish(),this}destroy(){const t=this.node._id,n=this._id,r=pd.tweens[t];this.pause(),this.anim&&this.anim.stop();for(const a in r)delete pd.tweens[t][a];delete pd.attrs[t][n],pd.tweens[t]&&(Object.keys(pd.tweens[t]).length===0&&delete pd.tweens[t],Object.keys(pd.attrs[t]).length===0&&delete pd.attrs[t])}}pd.attrs={};pd.tweens={};fa.prototype.to=function(s){const t=s.onFinish;s.node=this,s.onFinish=function(){this.destroy(),t&&t()},new pd(s).play()};const oz={BackEaseIn(s,t,n,r){return n*(s/=r)*s*((1.70158+1)*s-1.70158)+t},BackEaseOut(s,t,n,r){return n*((s=s/r-1)*s*((1.70158+1)*s+1.70158)+1)+t},BackEaseInOut(s,t,n,r){let a=1.70158;return(s/=r/2)<1?n/2*(s*s*(((a*=1.525)+1)*s-a))+t:n/2*((s-=2)*s*(((a*=1.525)+1)*s+a)+2)+t},ElasticEaseIn(s,t,n,r,a,i){let l=0;return s===0?t:(s/=r)===1?t+n:(i||(i=r*.3),!a||a0?t:n),u=l*n,h=o*(o>0?t:n),p=c*(c>0?n:t);return{x:d,y:r?-1*p:h,width:u-d,height:p-h}}}_N.prototype._centroid=!0;_N.prototype.className="Arc";_N.prototype._attrsAffectingSize=["innerRadius","outerRadius","angle","clockwise"];Fu(_N);Rs.addGetterSetter(_N,"innerRadius",0,ta());Rs.addGetterSetter(_N,"outerRadius",0,ta());Rs.addGetterSetter(_N,"angle",0,ta());Rs.addGetterSetter(_N,"clockwise",!1,Ib());function HCe(s,t,n,r,a,i,l){const o=Math.sqrt(Math.pow(n-s,2)+Math.pow(r-t,2)),c=Math.sqrt(Math.pow(a-n,2)+Math.pow(i-r,2)),d=l*o/(o+c),u=l*c/(o+c),h=n-d*(a-s),p=r-d*(i-t),f=n+u*(a-s),y=r+u*(i-t);return[h,p,f,y]}function zVe(s,t){const n=s.length,r=[];for(let a=2;a=0){const c=Math.sqrt(o);n.push((-i+c)/(2*a)),n.push((-i-c)/(2*a))}}}return n.filter(r=>r>0&&r<1).flatMap(r=>t.map(a=>{const i=1-r;return i*i*i*a[0]+3*i*i*r*a[1]+3*i*r*r*a[2]+r*r*r*a[3]}))}let wN=class extends Wr{constructor(t){super(t),this.on("pointsChange.konva tensionChange.konva closedChange.konva bezierChange.konva",function(){this._clearCache("tensionPoints")})}_sceneFunc(t){const n=this.points(),r=n.length,a=this.tension(),i=this.closed(),l=this.bezier();if(!r)return;let o=0;if(t.beginPath(),t.moveTo(n[0],n[1]),a!==0&&r>4){const c=this.getTensionPoints(),d=c.length;for(o=i?0:4,i||t.quadraticCurveTo(c[0],c[1],c[2],c[3]);o{let r,a;const l=n/2;r=0;for(let o=0;o<20;o++)a=l*n0s[20][o]+l,r+=r0s[20][o]*i0s(s,t,a);return l*r},$Ve=(s,t,n)=>{n===void 0&&(n=1);const r=s[0]-2*s[1]+s[2],a=t[0]-2*t[1]+t[2],i=2*s[1]-2*s[0],l=2*t[1]-2*t[0],o=4*(r*r+a*a),c=4*(r*i+a*l),d=i*i+l*l;if(o===0)return n*Math.sqrt(Math.pow(s[2]-s[0],2)+Math.pow(t[2]-t[0],2));const u=c/(2*o),h=d/o,p=n+u,f=h-u*u,y=p*p+f>0?Math.sqrt(p*p+f):0,_=u*u+f>0?Math.sqrt(u*u+f):0,v=u+Math.sqrt(u*u+f)!==0?f*Math.log(Math.abs((p+y)/(u+_))):0;return Math.sqrt(o)/2*(p*y-u*_+v)};function i0s(s,t,n){const r=GCe(1,n,s),a=GCe(1,n,t),i=r*r+a*a;return Math.sqrt(i)}const GCe=(s,t,n)=>{const r=n.length-1;let a,i;if(r===0)return 0;if(s===0){i=0;for(let l=0;l<=r;l++)i+=a0s[r][l]*Math.pow(1-t,r-l)*Math.pow(t,l)*n[l];return i}else{a=new Array(r);for(let l=0;l{let r=1,a=s/t,i=(s-n(a))/t,l=0;for(;r>.001;){const o=n(a+i),c=Math.abs(s-o)/t;if(c500)break}return a};let Nv=class Ng extends Wr{constructor(t){super(t),this.dataArray=[],this.pathLength=0,this._readDataAttribute(),this.on("dataChange.konva",function(){this._readDataAttribute()})}_readDataAttribute(){this.dataArray=Ng.parsePathData(this.data()),this.pathLength=Ng.getPathLength(this.dataArray)}_sceneFunc(t){const n=this.dataArray;t.beginPath();let r=!1;for(let a=0;au?d:u,v=d>u?1:d/u,j=d>u?u/d:1;t.translate(o,c),t.rotate(f),t.scale(v,j),t.arc(0,0,_,h,h+p,1-y),t.scale(1/v,1/j),t.rotate(-f),t.translate(-o,-c);break;case"z":r=!0,t.closePath();break}}!r&&!this.hasFill()?t.strokeShape(this):t.fillStrokeShape(this)}getSelfRect(){let t=[];this.dataArray.forEach(function(c){if(c.command==="A"){const d=c.points[4],u=c.points[5],h=c.points[4]+u;let p=Math.PI/180;if(Math.abs(d-h)h;f-=p){const y=Ng.getPointOnEllipticalArc(c.points[0],c.points[1],c.points[2],c.points[3],f,0);t.push(y.x,y.y)}else for(let f=d+p;fn[a].pathLength;)t-=n[a].pathLength,++a;if(a===i)return r=n[a-1].points.slice(-2),{x:r[0],y:r[1]};if(t<.01)return n[a].command==="M"?(r=n[a].points.slice(0,2),{x:r[0],y:r[1]}):{x:n[a].start.x,y:n[a].start.y};const l=n[a],o=l.points;switch(l.command){case"L":return Ng.getPointOnLine(t,l.start.x,l.start.y,o[0],o[1]);case"C":return Ng.getPointOnCubicBezier(UVe(t,Ng.getPathLength(n),_=>BVe([l.start.x,o[0],o[2],o[4]],[l.start.y,o[1],o[3],o[5]],_)),l.start.x,l.start.y,o[0],o[1],o[2],o[3],o[4],o[5]);case"Q":return Ng.getPointOnQuadraticBezier(UVe(t,Ng.getPathLength(n),_=>$Ve([l.start.x,o[0],o[2]],[l.start.y,o[1],o[3]],_)),l.start.x,l.start.y,o[0],o[1],o[2],o[3]);case"A":const c=o[0],d=o[1],u=o[2],h=o[3],p=o[5],f=o[6];let y=o[4];return y+=p*t/l.pathLength,Ng.getPointOnEllipticalArc(c,d,u,h,y,f)}return null}static getPointOnLine(t,n,r,a,i,l,o){l=l??n,o=o??r;const c=this.getLineLength(n,r,a,i);if(c<1e-10)return{x:n,y:r};if(a===n)return{x:l,y:o+(i>r?t:-t)};const d=(i-r)/(a-n),u=Math.sqrt(t*t/(1+d*d))*(a=0&&(_+=2,_>=7&&(_-=7));continue}if(_>=0){if(_===3){if(/^[01]{2}\d+(?:\.\d+)?$/.test(w)){y.push(parseInt(w[0],10)),y.push(parseInt(w[1],10)),y.push(parseFloat(w.slice(2))),_+=3,_>=7&&(_-=7);continue}if(w==="11"||w==="10"||w==="01"){y.push(parseInt(w[0],10)),y.push(parseInt(w[1],10)),_+=2,_>=7&&(_-=7);continue}if(w==="0"||w==="1"){y.push(parseInt(w,10)),_+=1,_>=7&&(_-=7);continue}}else if(_===4){if(/^[01]\d+(?:\.\d+)?$/.test(w)){y.push(parseInt(w[0],10)),y.push(parseFloat(w.slice(1))),_+=2,_>=7&&(_-=7);continue}if(w==="0"||w==="1"){y.push(parseInt(w,10)),_+=1,_>=7&&(_-=7);continue}}const S=parseFloat(w);isNaN(S)?y.push(0):y.push(S),_+=1,_>=7&&(_-=7)}else{const S=parseFloat(w);isNaN(S)?y.push(0):y.push(S)}}for(;y.length>0&&!isNaN(y[0]);){let v="",j=[];const w=o,S=c;let A,E,O,D,I,F,z,H,Z,Y;switch(f){case"l":o+=y.shift(),c+=y.shift(),v="L",j.push(o,c);break;case"L":o=y.shift(),c=y.shift(),j.push(o,c);break;case"m":const W=y.shift(),ee=y.shift();if(o+=W,c+=ee,v="M",i.length>2&&i[i.length-1].command==="z"){for(let se=i.length-2;se>=0;se--)if(i[se].command==="M"){o=i[se].points[0]+W,c=i[se].points[1]+ee;break}}j.push(o,c),f="l";break;case"M":o=y.shift(),c=y.shift(),v="M",j.push(o,c),f="L";break;case"h":o+=y.shift(),v="L",j.push(o,c);break;case"H":o=y.shift(),v="L",j.push(o,c);break;case"v":c+=y.shift(),v="L",j.push(o,c);break;case"V":c=y.shift(),v="L",j.push(o,c);break;case"C":j.push(y.shift(),y.shift(),y.shift(),y.shift()),o=y.shift(),c=y.shift(),j.push(o,c);break;case"c":j.push(o+y.shift(),c+y.shift(),o+y.shift(),c+y.shift()),o+=y.shift(),c+=y.shift(),v="C",j.push(o,c);break;case"S":E=o,O=c,A=i[i.length-1],A.command==="C"&&(E=o+(o-A.points[2]),O=c+(c-A.points[3])),j.push(E,O,y.shift(),y.shift()),o=y.shift(),c=y.shift(),v="C",j.push(o,c);break;case"s":E=o,O=c,A=i[i.length-1],A.command==="C"&&(E=o+(o-A.points[2]),O=c+(c-A.points[3])),j.push(E,O,o+y.shift(),c+y.shift()),o+=y.shift(),c+=y.shift(),v="C",j.push(o,c);break;case"Q":j.push(y.shift(),y.shift()),o=y.shift(),c=y.shift(),j.push(o,c);break;case"q":j.push(o+y.shift(),c+y.shift()),o+=y.shift(),c+=y.shift(),v="Q",j.push(o,c);break;case"T":E=o,O=c,A=i[i.length-1],A.command==="Q"&&(E=o+(o-A.points[0]),O=c+(c-A.points[1])),o=y.shift(),c=y.shift(),v="Q",j.push(E,O,o,c);break;case"t":E=o,O=c,A=i[i.length-1],A.command==="Q"&&(E=o+(o-A.points[0]),O=c+(c-A.points[1])),o+=y.shift(),c+=y.shift(),v="Q",j.push(E,O,o,c);break;case"A":D=y.shift(),I=y.shift(),F=y.shift(),z=y.shift(),H=y.shift(),Z=o,Y=c,o=y.shift(),c=y.shift(),v="A",j=this.convertEndpointToCenterParameterization(Z,Y,o,c,z,H,D,I,F);break;case"a":D=y.shift(),I=y.shift(),F=y.shift(),z=y.shift(),H=y.shift(),Z=o,Y=c,o+=y.shift(),c+=y.shift(),v="A",j=this.convertEndpointToCenterParameterization(Z,Y,o,c,z,H,D,I,F);break}i.push({command:v||f,points:j,start:{x:w,y:S},pathLength:this.calcLength(w,S,v||f,j)})}(f==="z"||f==="Z")&&i.push({command:"z",points:[],start:void 0,pathLength:0})}return i}static calcLength(t,n,r,a){let i,l,o,c;const d=Ng;switch(r){case"L":return d.getLineLength(t,n,a[0],a[1]);case"C":return BVe([t,a[0],a[2],a[4]],[n,a[1],a[3],a[5]],1);case"Q":return $Ve([t,a[0],a[2]],[n,a[1],a[3]],1);case"A":i=0;const u=a[4],h=a[5],p=a[4]+h;let f=Math.PI/180;if(Math.abs(u-p)p;c-=f)o=d.getPointOnEllipticalArc(a[0],a[1],a[2],a[3],c,0),i+=d.getLineLength(l.x,l.y,o.x,o.y),l=o;else for(c=u+f;c1&&(o*=Math.sqrt(f),c*=Math.sqrt(f));let y=Math.sqrt((o*o*(c*c)-o*o*(p*p)-c*c*(h*h))/(o*o*(p*p)+c*c*(h*h)));i===l&&(y*=-1),isNaN(y)&&(y=0);const _=y*o*p/c,v=y*-c*h/o,j=(t+r)/2+Math.cos(u)*_-Math.sin(u)*v,w=(n+a)/2+Math.sin(u)*_+Math.cos(u)*v,S=function(z){return Math.sqrt(z[0]*z[0]+z[1]*z[1])},A=function(z,H){return(z[0]*H[0]+z[1]*H[1])/(S(z)*S(H))},E=function(z,H){return(z[0]*H[1]=1&&(F=0),l===0&&F>0&&(F=F-2*Math.PI),l===1&&F<0&&(F=F+2*Math.PI),[j,w,o,c,O,F,u,l]}};Nv.prototype.className="Path";Nv.prototype._attrsAffectingSize=["data"];Fu(Nv);Rs.addGetterSetter(Nv,"data");class HM extends wN{_sceneFunc(t){super._sceneFunc(t);const n=Math.PI*2,r=this.points();let a=r;const i=this.tension()!==0&&r.length>4;i&&(a=this.getTensionPoints());const l=this.pointerLength(),o=r.length;let c,d;if(i){const p=[a[a.length-4],a[a.length-3],a[a.length-2],a[a.length-1],r[o-2],r[o-1]],f=Nv.calcLength(a[a.length-4],a[a.length-3],"C",p),y=Nv.getPointOnQuadraticBezier(Math.min(1,1-l/f),p[0],p[1],p[2],p[3],p[4],p[5]);c=r[o-2]-y.x,d=r[o-1]-y.y}else c=r[o-2]-r[o-4],d=r[o-1]-r[o-3];const u=(Math.atan2(d,c)+n)%n,h=this.pointerWidth();this.pointerAtEnding()&&(t.save(),t.beginPath(),t.translate(r[o-2],r[o-1]),t.rotate(u),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t)),this.pointerAtBeginning()&&(t.save(),t.beginPath(),t.translate(r[0],r[1]),i?(c=(a[0]+a[2])/2-r[0],d=(a[1]+a[3])/2-r[1]):(c=r[2]-r[0],d=r[3]-r[1]),t.rotate((Math.atan2(-d,-c)+n)%n),t.moveTo(0,0),t.lineTo(-l,h/2),t.lineTo(-l,-h/2),t.closePath(),t.restore(),this.__fillStroke(t))}__fillStroke(t){const n=this.dashEnabled();n&&(this.attrs.dashEnabled=!1,t.setLineDash([])),t.fillStrokeShape(this),n&&(this.attrs.dashEnabled=!0)}getSelfRect(){const t=super.getSelfRect(),n=this.pointerWidth()/2;return{x:t.x,y:t.y-n,width:t.width,height:t.height+n*2}}}HM.prototype.className="Arrow";Fu(HM);Rs.addGetterSetter(HM,"pointerLength",10,ta());Rs.addGetterSetter(HM,"pointerWidth",10,ta());Rs.addGetterSetter(HM,"pointerAtBeginning",!1);Rs.addGetterSetter(HM,"pointerAtEnding",!0);class GD extends Wr{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.attrs.radius||0,0,Math.PI*2,!1),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius()!==t/2&&this.radius(t/2)}setHeight(t){this.radius()!==t/2&&this.radius(t/2)}}GD.prototype._centroid=!0;GD.prototype.className="Circle";GD.prototype._attrsAffectingSize=["radius"];Fu(GD);Rs.addGetterSetter(GD,"radius",0,ta());class Q4 extends Wr{_sceneFunc(t){const n=this.radiusX(),r=this.radiusY();t.beginPath(),t.save(),n!==r&&t.scale(1,r/n),t.arc(0,0,n,0,Math.PI*2,!1),t.restore(),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radiusX()*2}getHeight(){return this.radiusY()*2}setWidth(t){this.radiusX(t/2)}setHeight(t){this.radiusY(t/2)}}Q4.prototype.className="Ellipse";Q4.prototype._centroid=!0;Q4.prototype._attrsAffectingSize=["radiusX","radiusY"];Fu(Q4);Rs.addComponentsGetterSetter(Q4,"radius",["x","y"]);Rs.addGetterSetter(Q4,"radiusX",0,ta());Rs.addGetterSetter(Q4,"radiusY",0,ta());let Pb=class Pgt extends Wr{constructor(t){super(t),this._loadListener=()=>{this._requestDraw()},this.on("imageChange.konva",n=>{this._removeImageLoad(n.oldVal),this._setImageLoad()}),this._setImageLoad()}_setImageLoad(){const t=this.image();t&&t.complete||t&&t.readyState===4||t&&t.addEventListener&&t.addEventListener("load",this._loadListener)}_removeImageLoad(t){t&&t.removeEventListener&&t.removeEventListener("load",this._loadListener)}destroy(){return this._removeImageLoad(this.image()),super.destroy(),this}_useBufferCanvas(){const t=!!this.cornerRadius(),n=this.hasShadow();return t&&n?!0:super._useBufferCanvas(!0)}_sceneFunc(t){const n=this.getWidth(),r=this.getHeight(),a=this.cornerRadius(),i=this.attrs.image;let l;if(i){const o=this.attrs.cropWidth,c=this.attrs.cropHeight;o&&c?l=[i,this.cropX(),this.cropY(),o,c,0,0,n,r]:l=[i,0,0,n,r]}(this.hasFill()||this.hasStroke()||a)&&(t.beginPath(),a?yn.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)),i&&(a&&t.clip(),t.drawImage.apply(t,l))}_hitFunc(t){const n=this.width(),r=this.height(),a=this.cornerRadius();t.beginPath(),a?yn.drawRoundedRectPath(t,n,r,a):t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}getWidth(){var t,n,r;return(r=(t=this.attrs.width)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.width)!==null&&r!==void 0?r:0}getHeight(){var t,n,r;return(r=(t=this.attrs.height)!==null&&t!==void 0?t:(n=this.image())===null||n===void 0?void 0:n.height)!==null&&r!==void 0?r:0}static fromURL(t,n,r=null){const a=yn.createImageElement();a.onload=function(){const i=new Pgt({image:a});n(i)},a.onerror=r,a.crossOrigin="Anonymous",a.src=t}};Pb.prototype.className="Image";Pb.prototype._attrsAffectingSize=["image"];Fu(Pb);Rs.addGetterSetter(Pb,"cornerRadius",0,Jye(4));Rs.addGetterSetter(Pb,"image");Rs.addComponentsGetterSetter(Pb,"crop",["x","y","width","height"]);Rs.addGetterSetter(Pb,"cropX",0,ta());Rs.addGetterSetter(Pb,"cropY",0,ta());Rs.addGetterSetter(Pb,"cropWidth",0,ta());Rs.addGetterSetter(Pb,"cropHeight",0,ta());const Lgt=["fontFamily","fontSize","fontStyle","padding","lineHeight","text","width","height","pointerDirection","pointerWidth","pointerHeight"],o0s="Change.konva",l0s="none",WCe="up",KCe="right",YCe="down",ZCe="left",c0s=Lgt.length;let pIe=class extends T8{constructor(t){super(t),this.on("add.konva",function(n){this._addListeners(n.child),this._sync()})}getText(){return this.find("Text")[0]}getTag(){return this.find("Tag")[0]}_addListeners(t){let n=this,r;const a=function(){n._sync()};for(r=0;r{n=Math.min(n,l.x),r=Math.max(r,l.x),a=Math.min(a,l.y),i=Math.max(i,l.y)}),{x:n,y:a,width:r-n,height:i-a}}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}X4.prototype.className="RegularPolygon";X4.prototype._centroid=!0;X4.prototype._attrsAffectingSize=["radius"];Fu(X4);Rs.addGetterSetter(X4,"radius",0,ta());Rs.addGetterSetter(X4,"sides",0,ta());Rs.addGetterSetter(X4,"cornerRadius",0,Jye(4));const qVe=Math.PI*2;let WM=class extends Wr{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.innerRadius(),0,qVe,!1),t.moveTo(this.outerRadius(),0),t.arc(0,0,this.outerRadius(),qVe,0,!0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.outerRadius()*2}getHeight(){return this.outerRadius()*2}setWidth(t){this.outerRadius(t/2)}setHeight(t){this.outerRadius(t/2)}};WM.prototype.className="Ring";WM.prototype._centroid=!0;WM.prototype._attrsAffectingSize=["innerRadius","outerRadius"];Fu(WM);Rs.addGetterSetter(WM,"innerRadius",0,ta());Rs.addGetterSetter(WM,"outerRadius",0,ta());class Yw extends Wr{constructor(t){super(t),this._updated=!0,this.anim=new jv(()=>{const n=this._updated;return this._updated=!1,n}),this.on("animationChange.konva",function(){this.frameIndex(0)}),this.on("frameIndexChange.konva",function(){this._updated=!0}),this.on("frameRateChange.konva",function(){this.anim.isRunning()&&(clearInterval(this.interval),this._setInterval())})}_sceneFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+0],c=i[a+1],d=i[a+2],u=i[a+3],h=this.image();if((this.hasFill()||this.hasStroke())&&(t.beginPath(),t.rect(0,0,d,u),t.closePath(),t.fillStrokeShape(this)),h)if(l){const p=l[n],f=r*2;t.drawImage(h,o,c,d,u,p[f+0],p[f+1],d,u)}else t.drawImage(h,o,c,d,u,0,0,d,u)}_hitFunc(t){const n=this.animation(),r=this.frameIndex(),a=r*4,i=this.animations()[n],l=this.frameOffsets(),o=i[a+2],c=i[a+3];if(t.beginPath(),l){const d=l[n],u=r*2;t.rect(d[u+0],d[u+1],o,c)}else t.rect(0,0,o,c);t.closePath(),t.fillShape(this)}_useBufferCanvas(){return super._useBufferCanvas(!0)}_setInterval(){const t=this;this.interval=setInterval(function(){t._updateIndex()},1e3/this.frameRate())}start(){if(this.isRunning())return;const t=this.getLayer();this.anim.setLayers(t),this._setInterval(),this.anim.start()}stop(){this.anim.stop(),clearInterval(this.interval)}isRunning(){return this.anim.isRunning()}_updateIndex(){const t=this.frameIndex(),n=this.animation(),r=this.animations(),a=r[n],i=a.length/4;t{if(new RegExp("\\p{Emoji}","u").test(n)){const i=a[r+1];i&&new RegExp("\\p{Emoji_Modifier}|\\u200D","u").test(i)?(t.push(n+i),a[r+1]=""):t.push(n)}else new RegExp("\\p{Regional_Indicator}{2}","u").test(n+(a[r+1]||""))?t.push(n+a[r+1]):r>0&&new RegExp("\\p{Mn}|\\p{Me}|\\p{Mc}","u").test(n)?t[t.length-1]+=n:n&&t.push(n);return t},[])}const NI="auto",d0s="center",Dgt="inherit",mF="justify",u0s="Change.konva",Rgt="2d",VVe="-",Ogt="left",h0s="text",m0s="Text",p0s="top",f0s="bottom",HVe="middle",Fgt="normal",x0s="px ",MH=" ",g0s="right",GVe="rtl",y0s="word",v0s="char",WVe="none",m2e="…",zgt=["direction","fontFamily","fontSize","fontStyle","fontVariant","padding","align","verticalAlign","lineHeight","text","width","height","wrap","ellipsis","letterSpacing"],b0s=zgt.length;let pF=null;function _0s(){if(pF!==null)return pF;pF=!1;try{const s=document.createElement("canvas");s.width=10,s.height=10;const t=s.getContext(Rgt);if(t){t.globalAlpha=0,t.shadowColor="black",t.shadowBlur=5,t.shadowOffsetX=5,t.shadowOffsetY=5,t.fillStyle="black",t.font="10px Arial",t.fillText("X",0,10);const n=t.getImageData(0,0,10,10).data;for(let r=3;r0){pF=!0;break}}}catch{}return pF}function w0s(s){return s.split(",").map(t=>{t=t.trim();const n=t.indexOf(" ")>=0,r=t.indexOf('"')>=0||t.indexOf("'")>=0;return n&&!r&&(t=`"${t}"`),t}).join(", ")}let IH;function p2e(){return IH||(IH=yn.createCanvasElement().getContext(Rgt),IH)}function j0s(s){s.fillText(this._partialText,this._partialTextX,this._partialTextY)}function N0s(s){s.setAttr("miterLimit",2),s.strokeText(this._partialText,this._partialTextX,this._partialTextY)}function k0s(s){return s=s||{},!s.fillLinearGradientColorStops&&!s.fillRadialGradientColorStops&&!s.fillPatternImage&&(s.fill=s.fill||"black"),s}let _d=class extends Wr{constructor(t){super(k0s(t)),this._partialTextX=0,this._partialTextY=0;for(let n=0;nve+Bk(ge.text).length,0),le=oe+me;_({char:he,index:le,x:I,y:O+F,lineIndex:E,column:oe,isLastInLine:Y,width:this.measureSize(he).width,context:t})}t.fillStrokeShape(this),_&&t.restore(),I+=this.measureSize(he).width+y}}else y!==0&&t.setAttr("letterSpacing",`${y}px`),this._partialTextX=I,this._partialTextY=O+F,this._partialText=H,t.fillStrokeShape(this);if(A){t.save(),t.beginPath();const ee=ua.legacyTextRendering?0:-Math.round(o/4),se=W;t.moveTo(se,O+F+ee);const oe=p===mF&&!Y?f-l*2:Z;t.lineTo(se+Math.round(oe),O+F+ee),t.lineWidth=o/15;const he=this._getLinearGradient();t.strokeStyle=he||v,t.stroke(),t.restore()}t.restore(),i>1&&(O+=c)}}_hitFunc(t){const n=this.getWidth(),r=this.getHeight();t.beginPath(),t.rect(0,0,n,r),t.closePath(),t.fillStrokeShape(this)}setText(t){const n=yn._isString(t)?t:t==null?"":t+"";return this._setAttr(h0s,n),this}getWidth(){return this.attrs.width===NI||this.attrs.width===void 0?this.getTextWidth()+this.padding()*2:this.attrs.width}getHeight(){return this.attrs.height===NI||this.attrs.height===void 0?this.fontSize()*this.textArr.length*this.lineHeight()+this.padding()*2:this.attrs.height}getTextWidth(){return this.textWidth}getTextHeight(){return yn.warn("text.getTextHeight() method is deprecated. Use text.height() - for full height and text.fontSize() - for one line height."),this.textHeight}measureSize(t){var n,r,a,i,l,o,c,d,u,h,p;let f=p2e(),y=this.fontSize(),_;f.save(),f.font=this._getContextFont(),_=f.measureText(t),f.restore();const v=y/100;return{actualBoundingBoxAscent:(n=_.actualBoundingBoxAscent)!==null&&n!==void 0?n:71.58203125*v,actualBoundingBoxDescent:(r=_.actualBoundingBoxDescent)!==null&&r!==void 0?r:0,actualBoundingBoxLeft:(a=_.actualBoundingBoxLeft)!==null&&a!==void 0?a:-7.421875*v,actualBoundingBoxRight:(i=_.actualBoundingBoxRight)!==null&&i!==void 0?i:75.732421875*v,alphabeticBaseline:(l=_.alphabeticBaseline)!==null&&l!==void 0?l:0,emHeightAscent:(o=_.emHeightAscent)!==null&&o!==void 0?o:100*v,emHeightDescent:(c=_.emHeightDescent)!==null&&c!==void 0?c:-20*v,fontBoundingBoxAscent:(d=_.fontBoundingBoxAscent)!==null&&d!==void 0?d:91*v,fontBoundingBoxDescent:(u=_.fontBoundingBoxDescent)!==null&&u!==void 0?u:21*v,hangingBaseline:(h=_.hangingBaseline)!==null&&h!==void 0?h:72.80000305175781*v,ideographicBaseline:(p=_.ideographicBaseline)!==null&&p!==void 0?p:-21*v,width:_.width,height:y}}_getContextFont(){return this.fontStyle()+MH+this.fontVariant()+MH+(this.fontSize()+x0s)+w0s(this.fontFamily())}_addTextLine(t){this.align()===mF&&(t=t.trim());const r=this._getTextWidth(t);return this.textArr.push({text:t,width:r,lastInParagraph:!1})}_getTextWidth(t){const n=this.letterSpacing(),r=t.length;return p2e().measureText(t).width+n*r}_setTextData(){let t=this.text().split(` `),n=+this.fontSize(),r=0,a=this.lineHeight()*n,i=this.attrs.width,l=this.attrs.height,o=i!==NI&&i!==void 0,c=l!==NI&&l!==void 0,d=this.padding(),u=i-d*2,h=l-d*2,p=0,f=this.wrap(),y=f!==WVe,_=f!==v0s&&y,v=this.ellipsis();this.textArr=[],p2e().font=this._getContextFont();const j=v?this._getTextWidth(m2e):0;for(let w=0,S=t.length;wu)for(;A.length>0;){let O=0,D=Bk(A).length,I="",F=0;for(;O>>1,H=Bk(A),Z=H.slice(0,z+1).join(""),Y=this._getTextWidth(Z);(v&&c&&p+a>h?Y+j:Y)<=u?(O=z+1,I=Z,F=Y):D=z}if(I){if(_){const Z=Bk(A),Y=Bk(I),W=Z[Y.length],ee=W===MH||W===VVe;let se;if(ee&&F<=u)se=Y.length;else{const oe=Y.lastIndexOf(MH),he=Y.lastIndexOf(VVe);se=Math.max(oe,he)+1}se>0&&(O=se,I=Z.slice(0,O).join(""),F=this._getTextWidth(I))}if(I=I.trimRight(),this._addTextLine(I),r=Math.max(r,F),p+=a,this._shouldHandleEllipsis(p)){this._tryToAddEllipsisToLastLine();break}if(A=Bk(A).slice(O).join("").trimLeft(),A.length>0&&(E=this._getTextWidth(A),E<=u)){this._addTextLine(A),p+=a,r=Math.max(r,E);break}}else break}else this._addTextLine(A),p+=a,r=Math.max(r,E),this._shouldHandleEllipsis(p)&&wh)break}this.textHeight=n,this.textWidth=r}_shouldHandleEllipsis(t){const n=+this.fontSize(),r=this.lineHeight()*n,a=this.attrs.height,i=a!==NI&&a!==void 0,l=this.padding(),o=a-l*2;return!(this.wrap()!==WVe)||i&&t+r>o}_tryToAddEllipsisToLastLine(){const t=this.attrs.width,n=t!==NI&&t!==void 0,r=this.padding(),a=t-r*2,i=this.ellipsis(),l=this.textArr[this.textArr.length-1];!l||!i||(n&&(this._getTextWidth(l.text+m2e)n?null:Nv.getPointAtLengthOfDataArray(t,this.dataArray)}_readDataAttribute(){this.dataArray=Nv.parsePathData(this.attrs.data),this.pathLength=this._getTextPathLength()}_sceneFunc(t){t.setAttr("font",this._getContextFont()),t.setAttr("textBaseline",this.textBaseline()),t.setAttr("textAlign","left"),t.save();const n=this.textDecoration(),r=this.fill(),a=this.fontSize(),i=this.glyphInfo,l=n.indexOf("underline")!==-1,o=n.indexOf("line-through")!==-1;l&&t.beginPath();for(let c=0;c=1){const r=n[0].p0;t.moveTo(r.x,r.y)}for(let r=0;rthis.pathLength&&j-this.pathLength<=d?this.pathLength:j);if(!w)return;const S=Nv.getLineLength(y.x,y.y,w.x,w.y);let A=0;if(c)try{A=c(n[f-1].char,_)*this.fontSize()}catch{A=0}y.x+=A,w.x+=A,this.textWidth+=A;const E=Nv.getPointOnLine(A+S/2,y.x,y.y,w.x,w.y),O=Math.atan2(w.y-y.y,w.x-y.x);this.glyphInfo.push({transposeX:E.x,transposeY:E.y,text:t[f],rotation:O,p0:y,p1:w,width:S}),p+=v}}getSelfRect(){if(!this.glyphInfo.length)return{x:0,y:0,width:0,height:0};const t=[];this.glyphInfo.forEach(function(d){t.push(d.p0.x),t.push(d.p0.y),t.push(d.p1.x),t.push(d.p1.y)});let n=t[0]||0,r=t[0]||0,a=t[1]||0,i=t[1]||0,l,o;for(let d=0;ds+`.${qgt}`).join(" "),KVe="nodesRect",T0s=["widthChange","heightChange","scaleXChange","scaleYChange","skewXChange","skewYChange","rotationChange","offsetXChange","offsetYChange","transformsEnabledChange","strokeWidthChange","draggableChange"],E0s={"top-left":-45,"top-center":0,"top-right":45,"middle-right":-90,"middle-left":90,"bottom-left":-135,"bottom-center":180,"bottom-right":135},A0s="ontouchstart"in ua._global;function M0s(s,t,n){if(s==="rotater")return n;t+=yn.degToRad(E0s[s]||0);const r=(yn.radToDeg(t)%360+360)%360;return yn._inRange(r,315+22.5,360)||yn._inRange(r,0,22.5)?"ns-resize":yn._inRange(r,45-22.5,45+22.5)?"nesw-resize":yn._inRange(r,90-22.5,90+22.5)?"ew-resize":yn._inRange(r,135-22.5,135+22.5)?"nwse-resize":yn._inRange(r,180-22.5,180+22.5)?"ns-resize":yn._inRange(r,225-22.5,225+22.5)?"nesw-resize":yn._inRange(r,270-22.5,270+22.5)?"ew-resize":yn._inRange(r,315-22.5,315+22.5)?"nwse-resize":(yn.error("Transformer has unknown angle for cursor detection: "+r),"pointer")}const uxe=["top-left","top-center","top-right","middle-right","middle-left","bottom-left","bottom-center","bottom-right"],YVe=1e8;function I0s(s){return{x:s.x+s.width/2*Math.cos(s.rotation)+s.height/2*Math.sin(-s.rotation),y:s.y+s.height/2*Math.cos(s.rotation)+s.width/2*Math.sin(s.rotation)}}function Vgt(s,t,n){const r=n.x+(s.x-n.x)*Math.cos(t)-(s.y-n.y)*Math.sin(t),a=n.y+(s.x-n.x)*Math.sin(t)+(s.y-n.y)*Math.cos(t);return{...s,rotation:s.rotation+t,x:r,y:a}}function P0s(s,t){const n=I0s(s);return Vgt(s,t,n)}function L0s(s,t,n){let r=t;for(let a=0;aa.isAncestorOf(this)?(yn.error("Konva.Transformer cannot be an a child of the node you are trying to attach"),!1):!0);return this._nodes=t=n,t.length===1&&this.useSingleNodeRotation()?this.rotation(t[0].getAbsoluteRotation()):this.rotation(0),this._nodes.forEach(a=>{const i=()=>{this.nodes().length===1&&this.useSingleNodeRotation()&&this.rotation(this.nodes()[0].getAbsoluteRotation()),this._resetTransformCache(),!this._transforming&&!this.isDragging()&&this.update()};if(a._attrsAffectingSize.length){const l=a._attrsAffectingSize.map(o=>o+"Change."+this._getEventNamespace()).join(" ");a.on(l,i)}a.on(T0s.map(l=>l+`.${this._getEventNamespace()}`).join(" "),i),a.on(`absoluteTransformChange.${this._getEventNamespace()}`,i),this._proxyDrag(a)}),this._resetTransformCache(),!!this.findOne(".top-left")&&this.update(),this}_proxyDrag(t){let n;t.on(`dragstart.${this._getEventNamespace()}`,r=>{n=t.getAbsolutePosition(),!this.isDragging()&&t!==this.findOne(".back")&&this.startDrag(r,!1)}),t.on(`dragmove.${this._getEventNamespace()}`,r=>{if(!n)return;const a=t.getAbsolutePosition(),i=a.x-n.x,l=a.y-n.y;this.nodes().forEach(o=>{if(o===t||o.isDragging())return;const c=o.getAbsolutePosition();o.setAbsolutePosition({x:c.x+i,y:c.y+l}),o.startDrag(r)}),n=null})}getNodes(){return this._nodes||[]}getActiveAnchor(){return this._movingAnchorName}detach(){this._nodes&&this._nodes.forEach(t=>{t.off("."+this._getEventNamespace())}),this._nodes=[],this._resetTransformCache()}_resetTransformCache(){this._clearCache(KVe),this._clearCache("transform"),this._clearSelfAndDescendantCache("absoluteTransform")}_getNodeRect(){return this._getCache(KVe,this.__getNodeRect)}__getNodeShape(t,n=this.rotation(),r){const a=t.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),i=t.getAbsoluteScale(r),l=t.getAbsolutePosition(r),o=a.x*i.x-t.offsetX()*i.x,c=a.y*i.y-t.offsetY()*i.y,d=(ua.getAngle(t.getAbsoluteRotation())+Math.PI*2)%(Math.PI*2),u={x:l.x+o*Math.cos(d)+c*Math.sin(-d),y:l.y+c*Math.cos(d)+o*Math.sin(d),width:a.width*i.x,height:a.height*i.y,rotation:d};return Vgt(u,-ua.getAngle(n),{x:0,y:0})}__getNodeRect(){if(!this.getNode())return{x:-YVe,y:-YVe,width:0,height:0,rotation:0};const n=[];this.nodes().map(d=>{const u=d.getClientRect({skipTransform:!0,skipShadow:!0,skipStroke:this.ignoreStroke()}),h=[{x:u.x,y:u.y},{x:u.x+u.width,y:u.y},{x:u.x+u.width,y:u.y+u.height},{x:u.x,y:u.y+u.height}],p=d.getAbsoluteTransform();h.forEach(function(f){const y=p.point(f);n.push(y)})});const r=new Y0;r.rotate(-ua.getAngle(this.rotation()));let a=1/0,i=1/0,l=-1/0,o=-1/0;n.forEach(function(d){const u=r.point(d);a===void 0&&(a=l=u.x,i=o=u.y),a=Math.min(a,u.x),i=Math.min(i,u.y),l=Math.max(l,u.x),o=Math.max(o,u.y)}),r.invert();const c=r.point({x:a,y:i});return{x:c.x,y:c.y,width:l-a,height:o-i,rotation:ua.getAngle(this.rotation())}}getX(){return this._getNodeRect().x}getY(){return this._getNodeRect().y}getWidth(){return this._getNodeRect().width}getHeight(){return this._getNodeRect().height}_createElements(){this._createBack(),uxe.forEach(t=>{this._createAnchor(t)}),this._createAnchor("rotater"),this._elementsCreated=!0}_createAnchor(t){const n=new fU({stroke:"rgb(0, 161, 255)",fill:"white",strokeWidth:1,name:t+" _anchor",dragDistance:0,draggable:!0,hitStrokeWidth:A0s?10:"auto"}),r=this;n.on("mousedown touchstart",function(a){r._handleMouseDown(a)}),n.on("dragstart",a=>{n.stopDrag(),a.cancelBubble=!0}),n.on("dragend",a=>{a.cancelBubble=!0}),n.on("mouseenter",()=>{const a=ua.getAngle(this.rotation()),i=this.rotateAnchorCursor(),l=M0s(t,a,i);n.getStage().content&&(n.getStage().content.style.cursor=l),this._cursorChange=!0}),n.on("mouseout",()=>{n.getStage().content&&(n.getStage().content.style.cursor=""),this._cursorChange=!1}),this.add(n)}_createBack(){const t=new Wr({name:"back",width:0,height:0,sceneFunc(n,r){const a=r.getParent(),i=a.padding(),l=r.width(),o=r.height();if(n.beginPath(),n.rect(-i,-i,l+i*2,o+i*2),a.rotateEnabled()&&a.rotateLineVisible()){const c=a.rotateAnchorAngle(),d=a.rotateAnchorOffset(),u=yn.degToRad(c),h=Math.sin(u),p=-Math.cos(u),f=l/2,y=o/2;let _=1/0;p<0?_=Math.min(_,-y/p):p>0&&(_=Math.min(_,(o-y)/p)),h<0?_=Math.min(_,-f/h):h>0&&(_=Math.min(_,(l-f)/h));const v=f+h*_,j=y+p*_,w=yn._sign(o),S=v+h*d*w,A=j+p*d*w;n.moveTo(v,j),n.lineTo(S,A)}n.fillStrokeShape(r)},hitFunc:(n,r)=>{if(!this.shouldOverdrawWholeArea())return;const a=this.padding();n.beginPath(),n.rect(-a,-a,r.width()+a*2,r.height()+a*2),n.fillStrokeShape(r)}});this.add(t),this._proxyDrag(t),t.on("dragstart",n=>{n.cancelBubble=!0}),t.on("dragmove",n=>{n.cancelBubble=!0}),t.on("dragend",n=>{n.cancelBubble=!0}),this.on("dragmove",n=>{this.update()})}_handleMouseDown(t){if(this._transforming)return;this._movingAnchorName=t.target.name().split(" ")[0];const n=this._getNodeRect(),r=n.width,a=n.height,i=Math.sqrt(Math.pow(r,2)+Math.pow(a,2));this.sin=Math.abs(a/i),this.cos=Math.abs(r/i),typeof window<"u"&&(window.addEventListener("mousemove",this._handleMouseMove),window.addEventListener("touchmove",this._handleMouseMove),window.addEventListener("mouseup",this._handleMouseUp,!0),window.addEventListener("touchend",this._handleMouseUp,!0)),this._transforming=!0;const l=t.target.getAbsolutePosition(),o=t.target.getStage().getPointerPosition();this._anchorDragOffset={x:o.x-l.x,y:o.y-l.y},QCe++,this._fire("transformstart",{evt:t.evt,target:this.getNode()}),this._nodes.forEach(c=>{c._fire("transformstart",{evt:t.evt,target:c})})}_handleMouseMove(t){let n,r,a;const i=this.findOne("."+this._movingAnchorName),l=i.getStage();l.setPointersPositions(t);const o=l.getPointerPosition();let c={x:o.x-this._anchorDragOffset.x,y:o.y-this._anchorDragOffset.y};const d=i.getAbsolutePosition();this.anchorDragBoundFunc()&&(c=this.anchorDragBoundFunc()(d,c,t)),i.setAbsolutePosition(c);const u=i.getAbsolutePosition();if(d.x===u.x&&d.y===u.y)return;if(this._movingAnchorName==="rotater"){const w=this._getNodeRect();n=i.x()-w.width/2,r=-i.y()+w.height/2;const S=ua.getAngle(this.rotateAnchorAngle());let A=Math.atan2(-r,n)+Math.PI/2-S;w.height<0&&(A-=Math.PI);const O=ua.getAngle(this.rotation())+A,D=ua.getAngle(this.rotationSnapTolerance()),F=L0s(this.rotationSnaps(),O,D)-w.rotation,z=P0s(w,F);this._fitNodesInto(z,t);return}const h=this.shiftBehavior();let p;h==="inverted"?p=this.keepRatio()&&!t.shiftKey:h==="none"?p=this.keepRatio():p=this.keepRatio()||t.shiftKey;let f=this.centeredScaling()||t.altKey;if(this._movingAnchorName==="top-left"){if(p){const w=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-right").x(),y:this.findOne(".bottom-right").y()};a=Math.sqrt(Math.pow(w.x-i.x(),2)+Math.pow(w.y-i.y(),2));const S=this.findOne(".top-left").x()>w.x?-1:1,A=this.findOne(".top-left").y()>w.y?-1:1;n=a*this.cos*S,r=a*this.sin*A,this.findOne(".top-left").x(w.x-n),this.findOne(".top-left").y(w.y-r)}}else if(this._movingAnchorName==="top-center")this.findOne(".top-left").y(i.y());else if(this._movingAnchorName==="top-right"){if(p){const w=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".bottom-left").x(),y:this.findOne(".bottom-left").y()};a=Math.sqrt(Math.pow(i.x()-w.x,2)+Math.pow(w.y-i.y(),2));const S=this.findOne(".top-right").x()w.y?-1:1;n=a*this.cos*S,r=a*this.sin*A,this.findOne(".top-right").x(w.x+n),this.findOne(".top-right").y(w.y-r)}var y=i.position();this.findOne(".top-left").y(y.y),this.findOne(".bottom-right").x(y.x)}else if(this._movingAnchorName==="middle-left")this.findOne(".top-left").x(i.x());else if(this._movingAnchorName==="middle-right")this.findOne(".bottom-right").x(i.x());else if(this._movingAnchorName==="bottom-left"){if(p){const w=f?{x:this.width()/2,y:this.height()/2}:{x:this.findOne(".top-right").x(),y:this.findOne(".top-right").y()};a=Math.sqrt(Math.pow(w.x-i.x(),2)+Math.pow(i.y()-w.y,2));const S=w.x{var i;a._fire("transformend",{evt:t,target:a}),(i=a.getLayer())===null||i===void 0||i.batchDraw()}),this._movingAnchorName=null}}_fitNodesInto(t,n){const r=this._getNodeRect(),a=1;if(yn._inRange(t.width,-this.padding()*2-a,a)){this.update();return}if(yn._inRange(t.height,-this.padding()*2-a,a)){this.update();return}const i=new Y0;if(i.rotate(ua.getAngle(this.rotation())),this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("left")>=0){const p=i.point({x:-this.padding()*2,y:0});t.x+=p.x,t.y+=p.y,t.width+=this.padding()*2,this._movingAnchorName=this._movingAnchorName.replace("left","right"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y}else if(this._movingAnchorName&&t.width<0&&this._movingAnchorName.indexOf("right")>=0){const p=i.point({x:this.padding()*2,y:0});this._movingAnchorName=this._movingAnchorName.replace("right","left"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.width+=this.padding()*2}if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("top")>=0){const p=i.point({x:0,y:-this.padding()*2});t.x+=p.x,t.y+=p.y,this._movingAnchorName=this._movingAnchorName.replace("top","bottom"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}else if(this._movingAnchorName&&t.height<0&&this._movingAnchorName.indexOf("bottom")>=0){const p=i.point({x:0,y:this.padding()*2});this._movingAnchorName=this._movingAnchorName.replace("bottom","top"),this._anchorDragOffset.x-=p.x,this._anchorDragOffset.y-=p.y,t.height+=this.padding()*2}if(this.boundBoxFunc()){const p=this.boundBoxFunc()(r,t);p?t=p:yn.warn("boundBoxFunc returned falsy. You should return new bound rect from it!")}const l=1e7,o=new Y0;o.translate(r.x,r.y),o.rotate(r.rotation),o.scale(r.width/l,r.height/l);const c=new Y0,d=t.width/l,u=t.height/l;this.flipEnabled()===!1?(c.translate(t.x,t.y),c.rotate(t.rotation),c.translate(t.width<0?t.width:0,t.height<0?t.height:0),c.scale(Math.abs(d),Math.abs(u))):(c.translate(t.x,t.y),c.rotate(t.rotation),c.scale(d,u));const h=c.multiply(o.invert());this._nodes.forEach(p=>{var f;if(!p.getStage())return;const y=p.getParent().getAbsoluteTransform(),_=p.getTransform().copy();_.translate(p.offsetX(),p.offsetY());const v=new Y0;v.multiply(y.copy().invert()).multiply(h).multiply(y).multiply(_);const j=v.decompose();p.setAttrs(j),(f=p.getLayer())===null||f===void 0||f.batchDraw()}),this.rotation(yn._getRotation(t.rotation)),this._nodes.forEach(p=>{this._fire("transform",{evt:n,target:p}),p._fire("transform",{evt:n,target:p})}),this._resetTransformCache(),this.update(),this.getLayer().batchDraw()}forceUpdate(){this._resetTransformCache(),this.update()}_batchChangeChild(t,n){this.findOne(t).setAttrs(n)}update(){var t;const n=this._getNodeRect();this.rotation(yn._getRotation(n.rotation));const r=n.width,a=n.height,i=this.enabledAnchors(),l=this.resizeEnabled(),o=this.padding(),c=this.anchorSize(),d=this.find("._anchor");d.forEach(O=>{O.setAttrs({width:c,height:c,offsetX:c/2,offsetY:c/2,stroke:this.anchorStroke(),strokeWidth:this.anchorStrokeWidth(),fill:this.anchorFill(),cornerRadius:this.anchorCornerRadius()})}),this._batchChangeChild(".top-left",{x:0,y:0,offsetX:c/2+o,offsetY:c/2+o,visible:l&&i.indexOf("top-left")>=0}),this._batchChangeChild(".top-center",{x:r/2,y:0,offsetY:c/2+o,visible:l&&i.indexOf("top-center")>=0}),this._batchChangeChild(".top-right",{x:r,y:0,offsetX:c/2-o,offsetY:c/2+o,visible:l&&i.indexOf("top-right")>=0}),this._batchChangeChild(".middle-left",{x:0,y:a/2,offsetX:c/2+o,visible:l&&i.indexOf("middle-left")>=0}),this._batchChangeChild(".middle-right",{x:r,y:a/2,offsetX:c/2-o,visible:l&&i.indexOf("middle-right")>=0}),this._batchChangeChild(".bottom-left",{x:0,y:a,offsetX:c/2+o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-left")>=0}),this._batchChangeChild(".bottom-center",{x:r/2,y:a,offsetY:c/2-o,visible:l&&i.indexOf("bottom-center")>=0}),this._batchChangeChild(".bottom-right",{x:r,y:a,offsetX:c/2-o,offsetY:c/2-o,visible:l&&i.indexOf("bottom-right")>=0});const u=this.rotateAnchorAngle(),h=this.rotateAnchorOffset(),p=yn.degToRad(u),f=Math.sin(p),y=-Math.cos(p),_=r/2,v=a/2;let j=1/0;y<0?j=Math.min(j,-v/y):y>0&&(j=Math.min(j,(a-v)/y)),f<0?j=Math.min(j,-_/f):f>0&&(j=Math.min(j,(r-_)/f));const w=_+f*j,S=v+y*j,A=yn._sign(a);this._batchChangeChild(".rotater",{x:w+f*h*A,y:S+y*h*A-o*y,visible:this.rotateEnabled()}),this._batchChangeChild(".back",{width:r,height:a,visible:this.borderEnabled(),stroke:this.borderStroke(),strokeWidth:this.borderStrokeWidth(),dash:this.borderDash(),draggable:this.nodes().some(O=>O.draggable()),x:0,y:0});const E=this.anchorStyleFunc();E&&d.forEach(O=>{E(O)}),(t=this.getLayer())===null||t===void 0||t.batchDraw()}isTransforming(){return this._transforming}stopTransform(){if(this._transforming){this._removeEvents();const t=this.findOne("."+this._movingAnchorName);t&&t.stopDrag()}}destroy(){return this.getStage()&&this._cursorChange&&this.getStage().content&&(this.getStage().content.style.cursor=""),T8.prototype.destroy.call(this),this.detach(),this._removeEvents(),this}add(...t){return this._elementsCreated?(yn.error("You cannot add external nodes to the Transformer. Use tr.nodes([node]) instead."),this):super.add(...t)}toObject(){return fa.prototype.toObject.call(this)}clone(t){return fa.prototype.clone.call(this,t)}getClientRect(){return this.nodes().length>0?super.getClientRect():{x:0,y:0,width:0,height:0}}};wl.isTransforming=()=>QCe>0;function D0s(s){return s instanceof Array||yn.warn("enabledAnchors value should be an array"),s instanceof Array&&s.forEach(function(t){uxe.indexOf(t)===-1&&yn.warn("Unknown anchor name: "+t+". Available names are: "+uxe.join(", "))}),s||[]}wl.prototype.className="Transformer";Fu(wl);Rs.addGetterSetter(wl,"enabledAnchors",uxe,D0s);Rs.addGetterSetter(wl,"flipEnabled",!0,Ib());Rs.addGetterSetter(wl,"resizeEnabled",!0);Rs.addGetterSetter(wl,"anchorSize",10,ta());Rs.addGetterSetter(wl,"rotateEnabled",!0);Rs.addGetterSetter(wl,"rotateLineVisible",!0);Rs.addGetterSetter(wl,"rotationSnaps",[]);Rs.addGetterSetter(wl,"rotateAnchorOffset",50,ta());Rs.addGetterSetter(wl,"rotateAnchorAngle",0,ta());Rs.addGetterSetter(wl,"rotateAnchorCursor","crosshair");Rs.addGetterSetter(wl,"rotationSnapTolerance",5,ta());Rs.addGetterSetter(wl,"borderEnabled",!0);Rs.addGetterSetter(wl,"anchorStroke","rgb(0, 161, 255)");Rs.addGetterSetter(wl,"anchorStrokeWidth",1,ta());Rs.addGetterSetter(wl,"anchorFill","white");Rs.addGetterSetter(wl,"anchorCornerRadius",0,ta());Rs.addGetterSetter(wl,"borderStroke","rgb(0, 161, 255)");Rs.addGetterSetter(wl,"borderStrokeWidth",1,ta());Rs.addGetterSetter(wl,"borderDash");Rs.addGetterSetter(wl,"keepRatio",!0);Rs.addGetterSetter(wl,"shiftBehavior","default");Rs.addGetterSetter(wl,"centeredScaling",!1);Rs.addGetterSetter(wl,"ignoreStroke",!1);Rs.addGetterSetter(wl,"padding",0,ta());Rs.addGetterSetter(wl,"nodes");Rs.addGetterSetter(wl,"node");Rs.addGetterSetter(wl,"boundBoxFunc");Rs.addGetterSetter(wl,"anchorDragBoundFunc");Rs.addGetterSetter(wl,"anchorStyleFunc");Rs.addGetterSetter(wl,"shouldOverdrawWholeArea",!1);Rs.addGetterSetter(wl,"useSingleNodeRotation",!0);Rs.backCompat(wl,{lineEnabled:"borderEnabled",rotateHandlerOffset:"rotateAnchorOffset",enabledHandlers:"enabledAnchors"});class jN extends Wr{_sceneFunc(t){t.beginPath(),t.arc(0,0,this.radius(),0,ua.getAngle(this.angle()),this.clockwise()),t.lineTo(0,0),t.closePath(),t.fillStrokeShape(this)}getWidth(){return this.radius()*2}getHeight(){return this.radius()*2}setWidth(t){this.radius(t/2)}setHeight(t){this.radius(t/2)}}jN.prototype.className="Wedge";jN.prototype._centroid=!0;jN.prototype._attrsAffectingSize=["radius"];Fu(jN);Rs.addGetterSetter(jN,"radius",0,ta());Rs.addGetterSetter(jN,"angle",0,ta());Rs.addGetterSetter(jN,"clockwise",!1);Rs.backCompat(jN,{angleDeg:"angle",getAngleDeg:"getAngle",setAngleDeg:"setAngle"});function ZVe(){this.r=0,this.g=0,this.b=0,this.a=0,this.next=null}const R0s=[512,512,456,512,328,456,335,512,405,328,271,456,388,335,292,512,454,405,364,328,298,271,496,456,420,388,360,335,312,292,273,512,482,454,428,405,383,364,345,328,312,298,284,271,259,496,475,456,437,420,404,388,374,360,347,335,323,312,302,292,282,273,265,512,497,482,468,454,441,428,417,405,394,383,373,364,354,345,337,328,320,312,305,298,291,284,278,271,265,259,507,496,485,475,465,456,446,437,428,420,412,404,396,388,381,374,367,360,354,347,341,335,329,323,318,312,307,302,297,292,287,282,278,273,269,265,261,512,505,497,489,482,475,468,461,454,447,441,435,428,422,417,411,405,399,394,389,383,378,373,368,364,359,354,350,345,341,337,332,328,324,320,316,312,309,305,301,298,294,291,287,284,281,278,274,271,268,265,262,259,257,507,501,496,491,485,480,475,470,465,460,456,451,446,442,437,433,428,424,420,416,412,408,404,400,396,392,388,385,381,377,374,370,367,363,360,357,354,350,347,344,341,338,335,332,329,326,323,320,318,315,312,310,307,304,302,299,297,294,292,289,287,285,282,280,278,275,273,271,269,267,265,263,261,259],O0s=[9,11,12,13,13,14,14,15,15,15,15,16,16,16,16,17,17,17,17,17,17,17,18,18,18,18,18,18,18,18,18,19,19,19,19,19,19,19,19,19,19,19,19,19,19,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,20,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,21,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,22,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,23,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24,24];function F0s(s,t){const n=s.data,r=s.width,a=s.height;let i,l,o,c,d,u,h,p,f,y,_,v,j,w,S,A,E,O,D,I;const F=t+t+1,z=r-1,H=a-1,Z=t+1,Y=Z*(Z+1)/2,W=new ZVe,ee=R0s[t],se=O0s[t];let oe=null,he=W,ce=null,me=null;for(let le=1;le>se,D!==0?(D=255/D,n[l]=(c*ee>>se)*D,n[l+1]=(d*ee>>se)*D,n[l+2]=(u*ee>>se)*D):n[l]=n[l+1]=n[l+2]=0,c-=p,d-=f,u-=y,h-=_,p-=ce.r,f-=ce.g,y-=ce.b,_-=ce.a,i=o+((i=ve+t+1)>se,D>0?(D=255/D,n[i]=(c*ee>>se)*D,n[i+1]=(d*ee>>se)*D,n[i+2]=(u*ee>>se)*D):n[i]=n[i+1]=n[i+2]=0,c-=p,d-=f,u-=y,h-=_,p-=ce.r,f-=ce.g,y-=ce.b,_-=ce.a,i=le+((i=ge+Z)0&&F0s(t,n)};Rs.addGetterSetter(fa,"blurRadius",0,ta(),Rs.afterSetFilter);const B0s=function(s){const t=this.brightness()*255,n=s.data,r=n.length;for(let a=0;a255?255:a,i=i<0?0:i>255?255:i,l=l<0?0:l>255?255:l,n[o]=a,n[o+1]=i,n[o+2]=l};Rs.addGetterSetter(fa,"contrast",0,ta(),Rs.afterSetFilter);const q0s=function(s){var t,n,r,a,i,l,o,c,d;const u=s.data,h=s.width,p=s.height,f=Math.min(1,Math.max(0,(n=(t=this.embossStrength)===null||t===void 0?void 0:t.call(this))!==null&&n!==void 0?n:.5)),y=Math.min(1,Math.max(0,(a=(r=this.embossWhiteLevel)===null||r===void 0?void 0:r.call(this))!==null&&a!==void 0?a:.5)),v=(o={"top-left":315,top:270,"top-right":225,right:180,"bottom-right":135,bottom:90,"bottom-left":45,left:0}[(l=(i=this.embossDirection)===null||i===void 0?void 0:i.call(this))!==null&&l!==void 0?l:"top-left"])!==null&&o!==void 0?o:315,j=!!((d=(c=this.embossBlend)===null||c===void 0?void 0:c.call(this))!==null&&d!==void 0&&d),w=f*10,S=y*255,A=v*Math.PI/180,E=Math.cos(A),O=Math.sin(A),D=128/1020*w,I=new Uint8ClampedArray(u),F=new Float32Array(h*p);for(let W=0,ee=0;eeW<0?0:W>255?255:W;for(let W=1;Wa&&(a=i),c=t[S+1],co&&(o=c),h=t[S+2],hu&&(u=h);a===r&&(a=255,r=0),o===l&&(o=255,l=0),u===d&&(u=255,d=0);let f,y,_,v,j,w;if(p>0)f=a+p*(255-a),y=r-p*(r-0),_=o+p*(255-o),v=l-p*(l-0),j=u+p*(255-u),w=d-p*(d-0);else{const S=(a+r)*.5;f=a+p*(a-S),y=r+p*(r-S);const A=(o+l)*.5;_=o+p*(o-A),v=l+p*(l-A);const E=(u+d)*.5;j=u+p*(u-E),w=d+p*(d-E)}for(let S=0;Sd?p:d;const f=l,y=i,_=360/y*Math.PI/180;for(let v=0;vd?p:d;const f=l,y=i,_=0;let v,j;for(u=0;ut&&(A=S,E=0,O=-1),a=0;a=0&&f=0&&y=0&&f=0&&y=255*4?255:0}return l}function nys(s,t,n){const r=[.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111,.1111111111111111],a=Math.round(Math.sqrt(r.length)),i=Math.floor(a/2),l=[];for(let o=0;o=0&&f=0&&y=n))for(let S=_;S=r)continue;const A=(n*S+w)*4;d+=l[A+0],u+=l[A+1],h+=l[A+2],p+=l[A+3],j+=1}d=d/j,u=u/j,h=h/j,p=p/j;for(let w=f;w=n))for(let S=_;S=r)continue;const A=(n*S+w)*4;l[A+0]=d,l[A+1]=u,l[A+2]=h,l[A+3]=p}}};Rs.addGetterSetter(fa,"pixelSize",8,ta(),Rs.afterSetFilter);const oys=function(s){const t=Math.round(this.levels()*254)+1,n=s.data,r=n.length,a=255/t;for(let i=0;i255?255:s<0?0:Math.round(s)});Rs.addGetterSetter(fa,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});Rs.addGetterSetter(fa,"blue",0,hgt,Rs.afterSetFilter);const cys=function(s){const t=s.data,n=t.length,r=this.red(),a=this.green(),i=this.blue(),l=this.alpha();for(let o=0;o255?255:s<0?0:Math.round(s)});Rs.addGetterSetter(fa,"green",0,function(s){return this._filterUpToDate=!1,s>255?255:s<0?0:Math.round(s)});Rs.addGetterSetter(fa,"blue",0,hgt,Rs.afterSetFilter);Rs.addGetterSetter(fa,"alpha",1,function(s){return this._filterUpToDate=!1,s>1?1:s<0?0:s});const dys=function(s){const t=s.data,n=t.length;for(let r=0;r=128&&(n[r]=255-a,n[r+1]=255-i,n[r+2]=255-l)}return s},hys=function(s){const t=this.threshold()*255,n=s.data,r=n.length;for(let a=0;apn||et[ms]!==vt[pn]){var Wn=` `+et[ms].replace(" at new "," at ");return Q.displayName&&Wn.includes("")&&(Wn=Wn.replace("",Q.displayName)),Wn}while(1<=ms&&0<=pn);break}}}finally{_r=!1,Error.prepareStackTrace=Ne}return(Q=Q?Q.displayName||Q.name:"")?Yn(Q):""}var Er=Object.prototype.hasOwnProperty,xa=[],Ki=-1;function io(Q){return{current:Q}}function Xa(Q){0>Ki||(Q.current=xa[Ki],xa[Ki]=null,Ki--)}function Mr(Q,J){Ki++,xa[Ki]=Q.current,Q.current=J}var qi={},Vi=io(qi),si=io(!1),Yi=qi;function Zi(Q,J){var Ne=Q.type.contextTypes;if(!Ne)return qi;var Ve=Q.stateNode;if(Ve&&Ve.__reactInternalMemoizedUnmaskedChildContext===J)return Ve.__reactInternalMemoizedMaskedChildContext;var et={},vt;for(vt in Ne)et[vt]=J[vt];return Ve&&(Q=Q.stateNode,Q.__reactInternalMemoizedUnmaskedChildContext=J,Q.__reactInternalMemoizedMaskedChildContext=et),et}function aa(Q){return Q=Q.childContextTypes,Q!=null}function Nn(){Xa(si),Xa(Vi)}function La(Q,J,Ne){if(Vi.current!==qi)throw Error(l(168));Mr(Vi,J),Mr(si,Ne)}function so(Q,J,Ne){var Ve=Q.stateNode;if(J=J.childContextTypes,typeof Ve.getChildContext!="function")return Ne;Ve=Ve.getChildContext();for(var et in Ve)if(!(et in J))throw Error(l(108,I(Q)||"Unknown",et));return i({},Ne,Ve)}function tl(Q){return Q=(Q=Q.stateNode)&&Q.__reactInternalMemoizedMergedChildContext||qi,Yi=Vi.current,Mr(Vi,Q),Mr(si,si.current),!0}function jl(Q,J,Ne){var Ve=Q.stateNode;if(!Ve)throw Error(l(169));Ne?(Q=so(Q,J,Yi),Ve.__reactInternalMemoizedMergedChildContext=Q,Xa(si),Xa(Vi),Mr(Vi,Q)):Xa(si),Mr(si,Ne)}var No=Math.clz32?Math.clz32:kf,jd=Math.log,Bu=Math.LN2;function kf(Q){return Q>>>=0,Q===0?32:31-(jd(Q)/Bu|0)|0}var $u=64,um=4194304;function Uu(Q){switch(Q&-Q){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return Q&4194240;case 4194304:case 8388608:case 16777216:case 33554432:case 67108864:return Q&130023424;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 1073741824;default:return Q}}function $d(Q,J){var Ne=Q.pendingLanes;if(Ne===0)return 0;var Ve=0,et=Q.suspendedLanes,vt=Q.pingedLanes,ms=Ne&268435455;if(ms!==0){var pn=ms&~et;pn!==0?Ve=Uu(pn):(vt&=ms,vt!==0&&(Ve=Uu(vt)))}else ms=Ne&~et,ms!==0?Ve=Uu(ms):vt!==0&&(Ve=Uu(vt));if(Ve===0)return 0;if(J!==0&&J!==Ve&&!(J&et)&&(et=Ve&-Ve,vt=J&-J,et>=vt||et===16&&(vt&4194240)!==0))return J;if(Ve&4&&(Ve|=Ne&16),J=Q.entangledLanes,J!==0)for(Q=Q.entanglements,J&=Ve;0Ne;Ne++)J.push(Q);return J}function Sf(Q,J,Ne){Q.pendingLanes|=J,J!==536870912&&(Q.suspendedLanes=0,Q.pingedLanes=0),Q=Q.eventTimes,J=31-No(J),Q[J]=Ne}function mh(Q,J){var Ne=Q.pendingLanes&~J;Q.pendingLanes=J,Q.suspendedLanes=0,Q.pingedLanes=0,Q.expiredLanes&=J,Q.mutableReadLanes&=J,Q.entangledLanes&=J,J=Q.entanglements;var Ve=Q.eventTimes;for(Q=Q.expirationTimes;0>=ms,et-=ms,Kc=1<<32-No(J)+et|Ne<no?(Wd=ni,ni=null):Wd=ni.sibling;var nl=ja(qn,ni,ln[no],Ma);if(nl===null){ni===null&&(ni=Wd);break}Q&&ni&&nl.alternate===null&&J(qn,ni),Ks=vt(nl,Ks,no),Di===null?qa=nl:Di.sibling=nl,Di=nl,ni=Wd}if(no===ln.length)return Ne(qn,ni),ha&&Lp(qn,no),qa;if(ni===null){for(;nono?(Wd=ni,ni=null):Wd=ni.sibling;var xg=ja(qn,ni,nl.value,Ma);if(xg===null){ni===null&&(ni=Wd);break}Q&&ni&&xg.alternate===null&&J(qn,ni),Ks=vt(xg,Ks,no),Di===null?qa=xg:Di.sibling=xg,Di=xg,ni=Wd}if(nl.done)return Ne(qn,ni),ha&&Lp(qn,no),qa;if(ni===null){for(;!nl.done;no++,nl=ln.next())nl=oo(qn,nl.value,Ma),nl!==null&&(Ks=vt(nl,Ks,no),Di===null?qa=nl:Di.sibling=nl,Di=nl);return ha&&Lp(qn,no),qa}for(ni=Ve(qn,ni);!nl.done;no++,nl=ln.next())nl=yc(ni,qn,no,nl.value,Ma),nl!==null&&(Q&&nl.alternate!==null&&ni.delete(nl.key===null?no:nl.key),Ks=vt(nl,Ks,no),Di===null?qa=nl:Di.sibling=nl,Di=nl);return Q&&ni.forEach(function(AC){return J(qn,AC)}),ha&&Lp(qn,no),qa}function Hp(qn,Ks,ln,Ma){if(typeof ln=="object"&&ln!==null&&ln.type===u&&ln.key===null&&(ln=ln.props.children),typeof ln=="object"&&ln!==null){switch(ln.$$typeof){case c:e:{for(var qa=ln.key,Di=Ks;Di!==null;){if(Di.key===qa){if(qa=ln.type,qa===u){if(Di.tag===7){Ne(qn,Di.sibling),Ks=et(Di,ln.props.children),Ks.return=qn,qn=Ks;break e}}else if(Di.elementType===qa||typeof qa=="object"&&qa!==null&&qa.$$typeof===S&&Ub(qa)===Di.type){Ne(qn,Di.sibling),Ks=et(Di,ln.props),Ks.ref=fx(qn,Di,ln),Ks.return=qn,qn=Ks;break e}Ne(qn,Di);break}else J(qn,Di);Di=Di.sibling}ln.type===u?(Ks=ps(ln.props.children,qn.mode,Ma,ln.key),Ks.return=qn,qn=Ks):(Ma=qo(ln.type,ln.key,ln.props,null,qn.mode,Ma),Ma.ref=fx(qn,Ks,ln),Ma.return=qn,qn=Ma)}return ms(qn);case d:e:{for(Di=ln.key;Ks!==null;){if(Ks.key===Di)if(Ks.tag===4&&Ks.stateNode.containerInfo===ln.containerInfo&&Ks.stateNode.implementation===ln.implementation){Ne(qn,Ks.sibling),Ks=et(Ks,ln.children||[]),Ks.return=qn,qn=Ks;break e}else{Ne(qn,Ks);break}else J(qn,Ks);Ks=Ks.sibling}Ks=zj(ln,qn.mode,Ma),Ks.return=qn,qn=Ks}return ms(qn);case S:return Di=ln._init,Hp(qn,Ks,Di(ln._payload),Ma)}if(ee(ln))return lo(qn,Ks,ln,Ma);if(O(ln))return xh(qn,Ks,ln,Ma);Ly(qn,ln)}return typeof ln=="string"&&ln!==""||typeof ln=="number"?(ln=""+ln,Ks!==null&&Ks.tag===6?(Ne(qn,Ks.sibling),Ks=et(Ks,ln),Ks.return=qn,qn=Ks):(Ne(qn,Ks),Ks=u_(ln,qn.mode,Ma),Ks.return=qn,qn=Ks),ms(qn)):Ne(qn,Ks)}return Hp}var Dl=Hu(!0),c6=Hu(!1),Dy=io(null),qb=null,xx=null,gx=null;function ij(){gx=xx=qb=null}function Vb(Q,J,Ne){Ae?(Mr(Dy,J._currentValue),J._currentValue=Ne):(Mr(Dy,J._currentValue2),J._currentValue2=Ne)}function Ud(Q){var J=Dy.current;Xa(Dy),Ae?Q._currentValue=J:Q._currentValue2=J}function ep(Q,J,Ne){for(;Q!==null;){var Ve=Q.alternate;if((Q.childLanes&J)!==J?(Q.childLanes|=J,Ve!==null&&(Ve.childLanes|=J)):Ve!==null&&(Ve.childLanes&J)!==J&&(Ve.childLanes|=J),Q===Ne)break;Q=Q.return}}function qd(Q,J){qb=Q,gx=xx=null,Q=Q.dependencies,Q!==null&&Q.firstContext!==null&&(Q.lanes&J&&(ym=!0),Q.firstContext=null)}function Dp(Q){var J=Ae?Q._currentValue:Q._currentValue2;if(gx!==Q)if(Q={context:Q,memoizedValue:J,next:null},xx===null){if(qb===null)throw Error(l(308));xx=Q,qb.dependencies={lanes:0,firstContext:Q}}else xx=xx.next=Q;return J}var Af=null;function Al(Q){Af===null?Af=[Q]:Af.push(Q)}function Qr(Q,J,Ne,Ve){var et=J.interleaved;return et===null?(Ne.next=Ne,Al(J)):(Ne.next=et.next,et.next=Ne),J.interleaved=Ne,nr(Q,Ve)}function nr(Q,J){Q.lanes|=J;var Ne=Q.alternate;for(Ne!==null&&(Ne.lanes|=J),Ne=Q,Q=Q.return;Q!==null;)Q.childLanes|=J,Ne=Q.alternate,Ne!==null&&(Ne.childLanes|=J),Ne=Q,Q=Q.return;return Ne.tag===3?Ne.stateNode:null}var gl=!1;function ra(Q){Q.updateQueue={baseState:Q.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,interleaved:null,lanes:0},effects:null}}function tp(Q,J){Q=Q.updateQueue,J.updateQueue===Q&&(J.updateQueue={baseState:Q.baseState,firstBaseUpdate:Q.firstBaseUpdate,lastBaseUpdate:Q.lastBaseUpdate,shared:Q.shared,effects:Q.effects})}function fm(Q,J){return{eventTime:Q,lane:J,tag:0,payload:null,callback:null,next:null}}function Pr(Q,J,Ne){var Ve=Q.updateQueue;if(Ve===null)return null;if(Ve=Ve.shared,po&2){var et=Ve.pending;return et===null?J.next=J:(J.next=et.next,et.next=J),Ve.pending=J,nr(Q,Ne)}return et=Ve.interleaved,et===null?(J.next=J,Al(Ve)):(J.next=et.next,et.next=J),Ve.interleaved=J,nr(Q,Ne)}function Ry(Q,J,Ne){if(J=J.updateQueue,J!==null&&(J=J.shared,(Ne&4194240)!==0)){var Ve=J.lanes;Ve&=Q.pendingLanes,Ne|=Ve,J.lanes=Ne,ux(Q,Ne)}}function oj(Q,J){var Ne=Q.updateQueue,Ve=Q.alternate;if(Ve!==null&&(Ve=Ve.updateQueue,Ne===Ve)){var et=null,vt=null;if(Ne=Ne.firstBaseUpdate,Ne!==null){do{var ms={eventTime:Ne.eventTime,lane:Ne.lane,tag:Ne.tag,payload:Ne.payload,callback:Ne.callback,next:null};vt===null?et=vt=ms:vt=vt.next=ms,Ne=Ne.next}while(Ne!==null);vt===null?et=vt=J:vt=vt.next=J}else et=vt=J;Ne={baseState:Ve.baseState,firstBaseUpdate:et,lastBaseUpdate:vt,shared:Ve.shared,effects:Ve.effects},Q.updateQueue=Ne;return}Q=Ne.lastBaseUpdate,Q===null?Ne.firstBaseUpdate=J:Q.next=J,Ne.lastBaseUpdate=J}function n1(Q,J,Ne,Ve){var et=Q.updateQueue;gl=!1;var vt=et.firstBaseUpdate,ms=et.lastBaseUpdate,pn=et.shared.pending;if(pn!==null){et.shared.pending=null;var Wn=pn,zr=Wn.next;Wn.next=null,ms===null?vt=zr:ms.next=zr,ms=Wn;var Ba=Q.alternate;Ba!==null&&(Ba=Ba.updateQueue,pn=Ba.lastBaseUpdate,pn!==ms&&(pn===null?Ba.firstBaseUpdate=zr:pn.next=zr,Ba.lastBaseUpdate=Wn))}if(vt!==null){var oo=et.baseState;ms=0,Ba=zr=Wn=null,pn=vt;do{var ja=pn.lane,yc=pn.eventTime;if((Ve&ja)===ja){Ba!==null&&(Ba=Ba.next={eventTime:yc,lane:0,tag:pn.tag,payload:pn.payload,callback:pn.callback,next:null});e:{var lo=Q,xh=pn;switch(ja=J,yc=Ne,xh.tag){case 1:if(lo=xh.payload,typeof lo=="function"){oo=lo.call(yc,oo,ja);break e}oo=lo;break e;case 3:lo.flags=lo.flags&-65537|128;case 0:if(lo=xh.payload,ja=typeof lo=="function"?lo.call(yc,oo,ja):lo,ja==null)break e;oo=i({},oo,ja);break e;case 2:gl=!0}}pn.callback!==null&&pn.lane!==0&&(Q.flags|=64,ja=et.effects,ja===null?et.effects=[pn]:ja.push(pn))}else yc={eventTime:yc,lane:ja,tag:pn.tag,payload:pn.payload,callback:pn.callback,next:null},Ba===null?(zr=Ba=yc,Wn=oo):Ba=Ba.next=yc,ms|=ja;if(pn=pn.next,pn===null){if(pn=et.shared.pending,pn===null)break;ja=pn,pn=ja.next,ja.next=null,et.lastBaseUpdate=ja,et.shared.pending=null}}while(!0);if(Ba===null&&(Wn=oo),et.baseState=Wn,et.firstBaseUpdate=zr,et.lastBaseUpdate=Ba,J=et.shared.interleaved,J!==null){et=J;do ms|=et.lane,et=et.next;while(et!==J)}else vt===null&&(et.shared.lanes=0);b0|=ms,Q.lanes=ms,Q.memoizedState=oo}}function Hb(Q,J,Ne){if(Q=J.effects,J.effects=null,Q!==null)for(J=0;JNe?Ne:4,Q(!0);var Ve=lC.transition;lC.transition={};try{Q(!1),J()}finally{mo=Ne,lC.transition=Ve}}function hC(){return Yc().memoizedState}function mC(Q,J,Ne){var Ve=pg(Q);if(Ne={lane:Ve,action:Ne,hasEagerState:!1,eagerState:null,next:null},pC(Q))d6(J,Ne);else if(Ne=Qr(Q,J,Ne,Ve),Ne!==null){var et=fh();ip(Ne,Q,Ve,et),ll(Ne,J,Ve)}}function MR(Q,J,Ne){var Ve=pg(Q),et={lane:Ve,action:Ne,hasEagerState:!1,eagerState:null,next:null};if(pC(Q))d6(J,et);else{var vt=Q.alternate;if(Q.lanes===0&&(vt===null||vt.lanes===0)&&(vt=J.lastRenderedReducer,vt!==null))try{var ms=J.lastRenderedState,pn=vt(ms,Ne);if(et.hasEagerState=!0,et.eagerState=pn,Ym(pn,ms)){var Wn=J.interleaved;Wn===null?(et.next=et,Al(J)):(et.next=Wn.next,Wn.next=et),J.interleaved=et;return}}catch{}finally{}Ne=Qr(Q,J,et,Ve),Ne!==null&&(et=fh(),ip(Ne,Q,Ve,et),ll(Ne,J,Ve))}}function pC(Q){var J=Q.alternate;return Q===Gl||J!==null&&J===Gl}function d6(Q,J){Pf=Gb=!0;var Ne=Q.pending;Ne===null?J.next=J:(J.next=Ne.next,Ne.next=J),Q.pending=J}function ll(Q,J,Ne){if(Ne&4194240){var Ve=J.lanes;Ve&=Q.pendingLanes,Ne|=Ve,J.lanes=Ne,ux(Q,Ne)}}var fj={readContext:Dp,useCallback:Fh,useContext:Fh,useEffect:Fh,useImperativeHandle:Fh,useInsertionEffect:Fh,useLayoutEffect:Fh,useMemo:Fh,useReducer:Fh,useRef:Fh,useState:Fh,useDebugValue:Fh,useDeferredValue:Fh,useTransition:Fh,useMutableSource:Fh,useSyncExternalStore:Fh,useId:Fh,unstable_isNewReconciler:!1},IR={readContext:Dp,useCallback:function(Q,J){return Lf().memoizedState=[Q,J===void 0?null:J],Q},useContext:Dp,useEffect:Fy,useImperativeHandle:function(Q,J,Ne){return Ne=Ne!=null?Ne.concat([Q]):null,mj(4194308,4,Yb.bind(null,J,Q),Ne)},useLayoutEffect:function(Q,J){return mj(4194308,4,Q,J)},useInsertionEffect:function(Q,J){return mj(4,2,Q,J)},useMemo:function(Q,J){var Ne=Lf();return J=J===void 0?null:J,Q=Q(),Ne.memoizedState=[Q,J],Q},useReducer:function(Q,J,Ne){var Ve=Lf();return J=Ne!==void 0?Ne(J):J,Ve.memoizedState=Ve.baseState=J,Q={pending:null,interleaved:null,lanes:0,dispatch:null,lastRenderedReducer:Q,lastRenderedState:J},Ve.queue=Q,Q=Q.dispatch=mC.bind(null,Gl,Q),[Ve.memoizedState,Q]},useRef:function(Q){var J=Lf();return Q={current:Q},J.memoizedState=Q},useState:np,useDebugValue:cC,useDeferredValue:function(Q){return Lf().memoizedState=Q},useTransition:function(){var Q=np(!1),J=Q[0];return Q=pi.bind(null,Q[1]),Lf().memoizedState=Q,[J,Q]},useMutableSource:function(){},useSyncExternalStore:function(Q,J,Ne){var Ve=Gl,et=Lf();if(ha){if(Ne===void 0)throw Error(l(407));Ne=Ne()}else{if(Ne=J(),dc===null)throw Error(l(349));d0&30||IN(Ve,J,Ne)}et.memoizedState=Ne;var vt={value:Ne,getSnapshot:J};return et.queue=vt,Fy(l1.bind(null,Ve,vt,Q),[Q]),Ve.flags|=2048,u0(9,o1.bind(null,Ve,vt,Ne,J),void 0,null),Ne},useId:function(){var Q=Lf(),J=dc.identifierPrefix;if(ha){var Ne=Jm,Ve=Kc;Ne=(Ve&~(1<<32-No(Ve)-1)).toString(32)+Ne,J=":"+J+"R"+Ne,Ne=cj++,0Rf&&(J.flags|=128,Ve=!0,e_(et,!1),J.lanes=4194304)}else{if(!Ve)if(Q=r1(vt),Q!==null){if(J.flags|=128,Ve=!0,Q=Q.updateQueue,Q!==null&&(J.updateQueue=Q,J.flags|=4),e_(et,!0),et.tail===null&&et.tailMode==="hidden"&&!vt.alternate&&!ha)return od(J),null}else 2*sl()-et.renderingStartTime>Rf&&Ne!==1073741824&&(J.flags|=128,Ve=!0,e_(et,!1),J.lanes=4194304);et.isBackwards?(vt.sibling=J.child,J.child=vt):(Q=et.last,Q!==null?Q.sibling=vt:J.child=vt,et.last=vt)}return et.tail!==null?(J=et.tail,et.rendering=J,et.tail=J.sibling,et.renderingStartTime=sl(),J.sibling=null,Q=Jl.current,Mr(Jl,Ve?Q&1|2:Q&1),J):(od(J),null);case 22:case 23:return Rj(),Ne=J.memoizedState!==null,Q!==null&&Q.memoizedState!==null!==Ne&&(J.flags|=8192),Ne&&J.mode&1?Bh&1073741824&&(od(J),Be&&J.subtreeFlags&6&&(J.flags|=8192)):od(J),null;case 24:return null;case 25:return null}throw Error(l(156,J.tag))}function BN(Q,J){switch(zn(J),J.tag){case 1:return aa(J.type)&&Nn(),Q=J.flags,Q&65536?(J.flags=Q&-65537|128,J):null;case 3:return Rp(),Xa(si),Xa(Vi),Op(),Q=J.flags,Q&65536&&!(Q&128)?(J.flags=Q&-65537|128,J):null;case 5:return TN(J),null;case 13:if(Xa(Jl),Q=J.memoizedState,Q!==null&&Q.dehydrated!==null){if(J.alternate===null)throw Error(l(340));Si()}return Q=J.flags,Q&65536?(J.flags=Q&-65537|128,J):null;case 19:return Xa(Jl),null;case 4:return Rp(),null;case 10:return Ud(J.type._context),null;case 22:case 23:return Rj(),null;case 24:return null;default:return null}}var $N=!1,ph=!1,LR=typeof WeakSet=="function"?WeakSet:Set,za=null;function p0(Q,J){var Ne=Q.ref;if(Ne!==null)if(typeof Ne=="function")try{Ne(null)}catch(Ve){Aa(Q,J,Ve)}else Ne.current=null}function t_(Q,J,Ne){try{Ne()}catch(Ve){Aa(Q,J,Ve)}}var bC=!1;function s_(Q,J){for(ce(Q.containerInfo),za=J;za!==null;)if(Q=za,J=Q.child,(Q.subtreeFlags&1028)!==0&&J!==null)J.return=Q,za=J;else for(;za!==null;){Q=za;try{var Ne=Q.alternate;if(Q.flags&1024)switch(Q.tag){case 0:case 11:case 15:break;case 1:if(Ne!==null){var Ve=Ne.memoizedProps,et=Ne.memoizedState,vt=Q.stateNode,ms=vt.getSnapshotBeforeUpdate(Q.elementType===Q.type?Ve:Df(Q.type,Ve),et);vt.__reactInternalSnapshotBeforeUpdate=ms}break;case 3:Be&&an(Q.stateNode.containerInfo);break;case 5:case 6:case 4:case 17:break;default:throw Error(l(163))}}catch(pn){Aa(Q,Q.return,pn)}if(J=Q.sibling,J!==null){J.return=Q.return,za=J;break}za=Q.return}return Ne=bC,bC=!1,Ne}function n_(Q,J,Ne){var Ve=J.updateQueue;if(Ve=Ve!==null?Ve.lastEffect:null,Ve!==null){var et=Ve=Ve.next;do{if((et.tag&Q)===Q){var vt=et.destroy;et.destroy=void 0,vt!==void 0&&t_(J,Ne,vt)}et=et.next}while(et!==Ve)}}function Sj(Q,J){if(J=J.updateQueue,J=J!==null?J.lastEffect:null,J!==null){var Ne=J=J.next;do{if((Ne.tag&Q)===Q){var Ve=Ne.create;Ne.destroy=Ve()}Ne=Ne.next}while(Ne!==J)}}function y1(Q){var J=Q.ref;if(J!==null){var Ne=Q.stateNode;switch(Q.tag){case 5:Q=se(Ne);break;default:Q=Ne}typeof J=="function"?J(Q):J.current=Q}}function Cj(Q){var J=Q.alternate;J!==null&&(Q.alternate=null,Cj(J)),Q.child=null,Q.deletions=null,Q.sibling=null,Q.tag===5&&(J=Q.stateNode,J!==null&&He(J)),Q.stateNode=null,Q.return=null,Q.dependencies=null,Q.memoizedProps=null,Q.memoizedState=null,Q.pendingProps=null,Q.stateNode=null,Q.updateQueue=null}function f0(Q){return Q.tag===5||Q.tag===3||Q.tag===4}function Tj(Q){e:for(;;){for(;Q.sibling===null;){if(Q.return===null||f0(Q.return))return null;Q=Q.return}for(Q.sibling.return=Q.return,Q=Q.sibling;Q.tag!==5&&Q.tag!==6&&Q.tag!==18;){if(Q.flags&2||Q.child===null||Q.tag===4)continue e;Q.child.return=Q,Q=Q.child}if(!(Q.flags&2))return Q.stateNode}}function r_(Q,J,Ne){var Ve=Q.tag;if(Ve===5||Ve===6)Q=Q.stateNode,J?Jt(Ne,Q,J):Yt(Ne,Q);else if(Ve!==4&&(Q=Q.child,Q!==null))for(r_(Q,J,Ne),Q=Q.sibling;Q!==null;)r_(Q,J,Ne),Q=Q.sibling}function UN(Q,J,Ne){var Ve=Q.tag;if(Ve===5||Ve===6)Q=Q.stateNode,J?Lt(Ne,Q,J):$t(Ne,Q);else if(Ve!==4&&(Q=Q.child,Q!==null))for(UN(Q,J,Ne),Q=Q.sibling;Q!==null;)UN(Q,J,Ne),Q=Q.sibling}var Rc=null,vm=!1;function Bp(Q,J,Ne){for(Ne=Ne.child;Ne!==null;)qN(Q,J,Ne),Ne=Ne.sibling}function qN(Q,J,Ne){if(Ka&&typeof Ka.onCommitFiberUnmount=="function")try{Ka.onCommitFiberUnmount(Cf,Ne)}catch{}switch(Ne.tag){case 5:ph||p0(Ne,J);case 6:if(Be){var Ve=Rc,et=vm;Rc=null,Bp(Q,J,Ne),Rc=Ve,vm=et,Rc!==null&&(vm?zt(Rc,Ne.stateNode):gt(Rc,Ne.stateNode))}else Bp(Q,J,Ne);break;case 18:Be&&Rc!==null&&(vm?Vs(Rc,Ne.stateNode):ns(Rc,Ne.stateNode));break;case 4:Be?(Ve=Rc,et=vm,Rc=Ne.stateNode.containerInfo,vm=!0,Bp(Q,J,Ne),Rc=Ve,vm=et):(we&&(Ve=Ne.stateNode.containerInfo,et=er(Ve),Qn(Ve,et)),Bp(Q,J,Ne));break;case 0:case 11:case 14:case 15:if(!ph&&(Ve=Ne.updateQueue,Ve!==null&&(Ve=Ve.lastEffect,Ve!==null))){et=Ve=Ve.next;do{var vt=et,ms=vt.destroy;vt=vt.tag,ms!==void 0&&(vt&2||vt&4)&&t_(Ne,J,ms),et=et.next}while(et!==Ve)}Bp(Q,J,Ne);break;case 1:if(!ph&&(p0(Ne,J),Ve=Ne.stateNode,typeof Ve.componentWillUnmount=="function"))try{Ve.props=Ne.memoizedProps,Ve.state=Ne.memoizedState,Ve.componentWillUnmount()}catch(pn){Aa(Ne,J,pn)}Bp(Q,J,Ne);break;case 21:Bp(Q,J,Ne);break;case 22:Ne.mode&1?(ph=(Ve=ph)||Ne.memoizedState!==null,Bp(Q,J,Ne),ph=Ve):Bp(Q,J,Ne);break;default:Bp(Q,J,Ne)}}function VN(Q){var J=Q.updateQueue;if(J!==null){Q.updateQueue=null;var Ne=Q.stateNode;Ne===null&&(Ne=Q.stateNode=new LR),J.forEach(function(Ve){var et=d_.bind(null,Q,Ve);Ne.has(Ve)||(Ne.add(Ve),Ve.then(et,et))})}}function ap(Q,J){var Ne=J.deletions;if(Ne!==null)for(var Ve=0;Ve";case v1:return":has("+($p(Q)||"")+")";case Vy:return'[role="'+Q.value+'"]';case x0:return'"'+Q.value+'"';case bx:return'[data-testname="'+Q.value+'"]';default:throw Error(l(365))}}function GN(Q,J){var Ne=[];Q=[Q,0];for(var Ve=0;Veet&&(et=ms),Ve&=~vt}if(Ve=et,Ve=sl()-Ve,Ve=(120>Ve?120:480>Ve?480:1080>Ve?1080:1920>Ve?1920:3e3>Ve?3e3:4320>Ve?4320:1960*Mj(Ve/1960))-Ve,10Q?16:Q,mg===null)var Ve=!1;else{if(Q=mg,mg=null,o_=0,po&6)throw Error(l(331));var et=po;for(po|=4,za=Q.current;za!==null;){var vt=za,ms=vt.child;if(za.flags&16){var pn=vt.deletions;if(pn!==null){for(var Wn=0;Wnsl()-i_?fg(Q,0):b1|=Ne),Uh(Q,J)}function Oj(Q,J){J===0&&(Q.mode&1?(J=um,um<<=1,!(um&130023424)&&(um=4194304)):J=1);var Ne=fh();Q=nr(Q,J),Q!==null&&(Sf(Q,J,Ne),Uh(Q,Ne))}function ZN(Q){var J=Q.memoizedState,Ne=0;J!==null&&(Ne=J.retryLane),Oj(Q,Ne)}function d_(Q,J){var Ne=0;switch(Q.tag){case 13:var Ve=Q.stateNode,et=Q.memoizedState;et!==null&&(Ne=et.retryLane);break;case 19:Ve=Q.stateNode;break;default:throw Error(l(314))}Ve!==null&&Ve.delete(J),Oj(Q,Ne)}var QN;QN=function(Q,J,Ne){if(Q!==null)if(Q.memoizedProps!==J.pendingProps||si.current)ym=!0;else{if(!(Q.lanes&Ne)&&!(J.flags&128))return ym=!1,Nj(Q,J,Ne);ym=!!(Q.flags&131072)}else ym=!1,ha&&J.flags&1048576&&Pt(J,$b,J.index);switch(J.lanes=0,J.tag){case 2:var Ve=J.type;x1(Q,J),Q=J.pendingProps;var et=Zi(J,Vi.current);qd(J,Ne),et=dj(null,J,Ve,Q,et,Ne);var vt=Wb();return J.flags|=1,typeof et=="object"&&et!==null&&typeof et.render=="function"&&et.$$typeof===void 0?(J.tag=1,J.memoizedState=null,J.updateQueue=null,aa(Ve)?(vt=!0,tl(J)):vt=!1,J.memoizedState=et.state!==null&&et.state!==void 0?et.state:null,ra(J),et.updater=u1,J.stateNode=et,et._reactInternals=J,$y(J,Ve,Q,Ne),J=wj(null,J,Ve,!0,vt,Ne)):(J.tag=0,ha&&vt&&dn(J),zh(null,J,et,Ne),J=J.child),J;case 16:Ve=J.elementType;e:{switch(x1(Q,J),Q=J.pendingProps,et=Ve._init,Ve=et(Ve._payload),J.type=Ve,et=J.tag=bn(Ve),Q=Df(Ve,Q),et){case 0:J=gC(null,J,Ve,Q,Ne);break e;case 1:J=FN(null,J,Ve,Q,Ne);break e;case 11:J=fC(null,J,Ve,Q,Ne);break e;case 14:J=m1(null,J,Ve,Df(Ve.type,Q),Ne);break e}throw Error(l(306,Ve,""))}return J;case 0:return Ve=J.type,et=J.pendingProps,et=J.elementType===Ve?et:Df(Ve,et),gC(Q,J,Ve,et,Ne);case 1:return Ve=J.type,et=J.pendingProps,et=J.elementType===Ve?et:Df(Ve,et),FN(Q,J,Ve,et,Ne);case 3:e:{if(Zb(J),Q===null)throw Error(l(387));Ve=J.pendingProps,vt=J.memoizedState,et=vt.element,tp(Q,J),n1(J,Ve,null,Ne);var ms=J.memoizedState;if(Ve=ms.element,Je&&vt.isDehydrated)if(vt={element:Ve,isDehydrated:!1,cache:ms.cache,pendingSuspenseBoundaries:ms.pendingSuspenseBoundaries,transitions:ms.transitions},J.updateQueue.baseState=vt,J.memoizedState=vt,J.flags&256){et=gm(Error(l(423)),J),J=p1(Q,J,Ve,Ne,et);break e}else if(Ve!==et){et=gm(Error(l(424)),J),J=p1(Q,J,Ve,Ne,et);break e}else for(Je&&(Gn=Fe(J.stateNode.containerInfo),Ir=J,ha=!0,ai=null,Ya=!1),Ne=c6(J,null,Ve,Ne),J.child=Ne;Ne;)Ne.flags=Ne.flags&-3|4096,Ne=Ne.sibling;else{if(Si(),Ve===et){J=zp(Q,J,Ne);break e}zh(Q,J,Ve,Ne)}J=J.child}return J;case 5:return lj(J),Q===null&&Vu(J),Ve=J.type,et=J.pendingProps,vt=Q!==null?Q.memoizedProps:null,ms=et.children,Ie(Ve,et)?ms=null:vt!==null&&Ie(Ve,vt)&&(J.flags|=32),m6(Q,J),zh(Q,J,ms,Ne),J.child;case 6:return Q===null&&Vu(J),null;case 13:return p6(Q,J,Ne);case 4:return Dc(J,J.stateNode.containerInfo),Ve=J.pendingProps,Q===null?J.child=Dl(J,null,Ve,Ne):zh(Q,J,Ve,Ne),J.child;case 11:return Ve=J.type,et=J.pendingProps,et=J.elementType===Ve?et:Df(Ve,et),fC(Q,J,Ve,et,Ne);case 7:return zh(Q,J,J.pendingProps,Ne),J.child;case 8:return zh(Q,J,J.pendingProps.children,Ne),J.child;case 12:return zh(Q,J,J.pendingProps.children,Ne),J.child;case 10:e:{if(Ve=J.type._context,et=J.pendingProps,vt=J.memoizedProps,ms=et.value,Vb(J,Ve,ms),vt!==null)if(Ym(vt.value,ms)){if(vt.children===et.children&&!si.current){J=zp(Q,J,Ne);break e}}else for(vt=J.child,vt!==null&&(vt.return=J);vt!==null;){var pn=vt.dependencies;if(pn!==null){ms=vt.child;for(var Wn=pn.firstContext;Wn!==null;){if(Wn.context===Ve){if(vt.tag===1){Wn=fm(-1,Ne&-Ne),Wn.tag=2;var zr=vt.updateQueue;if(zr!==null){zr=zr.shared;var Ba=zr.pending;Ba===null?Wn.next=Wn:(Wn.next=Ba.next,Ba.next=Wn),zr.pending=Wn}}vt.lanes|=Ne,Wn=vt.alternate,Wn!==null&&(Wn.lanes|=Ne),ep(vt.return,Ne,J),pn.lanes|=Ne;break}Wn=Wn.next}}else if(vt.tag===10)ms=vt.type===J.type?null:vt.child;else if(vt.tag===18){if(ms=vt.return,ms===null)throw Error(l(341));ms.lanes|=Ne,pn=ms.alternate,pn!==null&&(pn.lanes|=Ne),ep(ms,Ne,J),ms=vt.sibling}else ms=vt.child;if(ms!==null)ms.return=vt;else for(ms=vt;ms!==null;){if(ms===J){ms=null;break}if(vt=ms.sibling,vt!==null){vt.return=ms.return,ms=vt;break}ms=ms.return}vt=ms}zh(Q,J,et.children,Ne),J=J.child}return J;case 9:return et=J.type,Ve=J.pendingProps.children,qd(J,Ne),et=Dp(et),Ve=Ve(et),J.flags|=1,zh(Q,J,Ve,Ne),J.child;case 14:return Ve=J.type,et=Df(Ve,J.pendingProps),et=Df(Ve.type,et),m1(Q,J,Ve,et,Ne);case 15:return xC(Q,J,J.type,J.pendingProps,Ne);case 17:return Ve=J.type,et=J.pendingProps,et=J.elementType===Ve?et:Df(Ve,et),x1(Q,J),J.tag=1,aa(Ve)?(Q=!0,tl(J)):Q=!1,qd(J,Ne),zy(J,Ve,et),$y(J,Ve,et,Ne),wj(null,J,Ve,!0,Q,Ne);case 19:return Xb(Q,J,Ne);case 22:return h6(Q,J,Ne)}throw Error(l(156,J.tag))};function XN(Q,J){return mm(Q,J)}function w1(Q,J,Ne,Ve){this.tag=Q,this.key=Ne,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.ref=null,this.pendingProps=J,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=Ve,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function Gd(Q,J,Ne,Ve){return new w1(Q,J,Ne,Ve)}function wn(Q){return Q=Q.prototype,!(!Q||!Q.isReactComponent)}function bn(Q){if(typeof Q=="function")return wn(Q)?1:0;if(Q!=null){if(Q=Q.$$typeof,Q===_)return 11;if(Q===w)return 14}return 2}function Vp(Q,J){var Ne=Q.alternate;return Ne===null?(Ne=Gd(Q.tag,J,Q.key,Q.mode),Ne.elementType=Q.elementType,Ne.type=Q.type,Ne.stateNode=Q.stateNode,Ne.alternate=Q,Q.alternate=Ne):(Ne.pendingProps=J,Ne.type=Q.type,Ne.flags=0,Ne.subtreeFlags=0,Ne.deletions=null),Ne.flags=Q.flags&14680064,Ne.childLanes=Q.childLanes,Ne.lanes=Q.lanes,Ne.child=Q.child,Ne.memoizedProps=Q.memoizedProps,Ne.memoizedState=Q.memoizedState,Ne.updateQueue=Q.updateQueue,J=Q.dependencies,Ne.dependencies=J===null?null:{lanes:J.lanes,firstContext:J.firstContext},Ne.sibling=Q.sibling,Ne.index=Q.index,Ne.ref=Q.ref,Ne}function qo(Q,J,Ne,Ve,et,vt){var ms=2;if(Ve=Q,typeof Q=="function")wn(Q)&&(ms=1);else if(typeof Q=="string")ms=5;else e:switch(Q){case u:return ps(Ne.children,et,vt,J);case h:ms=8,et|=8;break;case p:return Q=Gd(12,Ne,J,et|2),Q.elementType=p,Q.lanes=vt,Q;case v:return Q=Gd(13,Ne,J,et),Q.elementType=v,Q.lanes=vt,Q;case j:return Q=Gd(19,Ne,J,et),Q.elementType=j,Q.lanes=vt,Q;case A:return Fj(Ne,et,vt,J);default:if(typeof Q=="object"&&Q!==null)switch(Q.$$typeof){case f:ms=10;break e;case y:ms=9;break e;case _:ms=11;break e;case w:ms=14;break e;case S:ms=16,Ve=null;break e}throw Error(l(130,Q==null?Q:typeof Q,""))}return J=Gd(ms,Ne,J,et),J.elementType=Q,J.type=Ve,J.lanes=vt,J}function ps(Q,J,Ne,Ve){return Q=Gd(7,Q,Ve,J),Q.lanes=Ne,Q}function Fj(Q,J,Ne,Ve){return Q=Gd(22,Q,Ve,J),Q.elementType=A,Q.lanes=Ne,Q.stateNode={isHidden:!1},Q}function u_(Q,J,Ne){return Q=Gd(6,Q,null,J),Q.lanes=Ne,Q}function zj(Q,J,Ne){return J=Gd(4,Q.children!==null?Q.children:[],Q.key,J),J.lanes=Ne,J.stateNode={containerInfo:Q.containerInfo,pendingChildren:null,implementation:Q.implementation},J}function JN(Q,J,Ne,Ve,et){this.tag=J,this.containerInfo=Q,this.finishedWork=this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=Re,this.callbackNode=this.pendingContext=this.context=null,this.callbackPriority=0,this.eventTimes=Ay(0),this.expirationTimes=Ay(-1),this.entangledLanes=this.finishedLanes=this.mutableReadLanes=this.expiredLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=Ay(0),this.identifierPrefix=Ve,this.onRecoverableError=et,Je&&(this.mutableSourceEagerHydrationData=null)}function CC(Q,J,Ne,Ve,et,vt,ms,pn,Wn){return Q=new JN(Q,J,Ne,pn,Wn),J===1?(J=1,vt===!0&&(J|=8)):J=0,vt=Gd(3,null,null,J),Q.current=vt,vt.stateNode=Q,vt.memoizedState={element:Ve,isDehydrated:Ne,cache:null,transitions:null,pendingSuspenseBoundaries:null},ra(vt),Q}function TC(Q){if(!Q)return qi;Q=Q._reactInternals;e:{if(F(Q)!==Q||Q.tag!==1)throw Error(l(170));var J=Q;do{switch(J.tag){case 3:J=J.stateNode.context;break e;case 1:if(aa(J.type)){J=J.stateNode.__reactInternalMemoizedMergedChildContext;break e}}J=J.return}while(J!==null);throw Error(l(171))}if(Q.tag===1){var Ne=Q.type;if(aa(Ne))return so(Q,Ne,J)}return J}function j1(Q){var J=Q._reactInternals;if(J===void 0)throw typeof Q.render=="function"?Error(l(188)):(Q=Object.keys(Q).join(","),Error(l(268,Q)));return Q=Z(J),Q===null?null:Q.stateNode}function EC(Q,J){if(Q=Q.memoizedState,Q!==null&&Q.dehydrated!==null){var Ne=Q.retryLane;Q.retryLane=Ne!==0&&Ne=zr&&vt>=oo&&et<=Ba&&ms<=ja){Q.splice(J,1);break}else if(Ve!==zr||Ne.width!==Wn.width||jams){if(!(vt!==oo||Ne.height!==Wn.height||Baet)){zr>Ve&&(Wn.width+=zr-Ve,Wn.x=Ve),Bavt&&(Wn.height+=oo-vt,Wn.y=vt),jaNe&&(Ne=ms)),ms ")+` No matching component was found for: `)+Q.join(" > ")}return null},n.getPublicRootInstance=function(Q){if(Q=Q.current,!Q.child)return null;switch(Q.child.tag){case 5:return se(Q.child.stateNode);default:return Q.child.stateNode}},n.injectIntoDevTools=function(Q){if(Q={bundleType:Q.bundleType,version:Q.version,rendererPackageName:Q.rendererPackageName,rendererConfig:Q.rendererConfig,overrideHookState:null,overrideHookStateDeletePath:null,overrideHookStateRenamePath:null,overrideProps:null,overridePropsDeletePath:null,overridePropsRenamePath:null,setErrorHandler:null,setSuspenseHandler:null,scheduleUpdate:null,currentDispatcherRef:o.ReactCurrentDispatcher,findHostInstanceByFiber:j6,findFiberByHostInstance:Q.findFiberByHostInstance||tk,findHostInstancesForRefresh:null,scheduleRefresh:null,scheduleRoot:null,setRefreshHandler:null,getCurrentFiber:null,reconcilerVersion:"18.3.1"},typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u")Q=!1;else{var J=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(J.isDisabled||!J.supportsFiber)Q=!0;else{try{Cf=J.inject(Q),Ka=J}catch{}Q=!!J.checkDCE}}return Q},n.isAlreadyRendering=function(){return!1},n.observeVisibleRects=function(Q,J,Ne,Ve){if(!Ge)throw Error(l(363));Q=WN(Q,J);var et=bt(Q,Ne,Ve).disconnect;return{disconnect:function(){et()}}},n.registerMutableSourceForHydration=function(Q,J){var Ne=J._getVersion;Ne=Ne(J._source),Q.mutableSourceEagerHydrationData==null?Q.mutableSourceEagerHydrationData=[J,Ne]:Q.mutableSourceEagerHydrationData.push(J,Ne)},n.runWithPriority=function(Q,J){var Ne=mo;try{return mo=Q,J()}finally{mo=Ne}},n.shouldError=function(){return null},n.shouldSuspend=function(){return!1},n.updateContainer=function(Q,J,Ne,Ve){var et=J.current,vt=fh(),ms=pg(et);return Ne=TC(Ne),J.context===null?J.context=Ne:J.pendingContext=Ne,J=fm(vt,ms),J.payload={element:Q},Ve=Ve===void 0?null:Ve,Ve!==null&&(J.callback=Ve),Q=Pr(et,J,ms),Q!==null&&(ip(Q,et,ms,vt),Ry(Q,et,ms)),ms},n};Hgt.exports=mys;var pys=Hgt.exports;const fys=_l(pys);var Ggt={exports:{}},KM={};/** * @license React * react-reconciler-constants.production.min.js * * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */KM.ConcurrentRoot=1;KM.ContinuousEventPriority=4;KM.DefaultEventPriority=16;KM.DiscreteEventPriority=1;KM.IdleEventPriority=536870912;KM.LegacyRoot=0;Ggt.exports=KM;var Wgt=Ggt.exports;const QVe={children:!0,ref:!0,key:!0,style:!0,forwardedRef:!0,unstable_applyCache:!0,unstable_applyDrawHitFromCache:!0};let XVe=!1,JVe=!1;const fIe=".react-konva-event",xys=`ReactKonva: You have a Konva node with draggable = true and position defined but no onDragMove or onDragEnd events are handled. Position of a node will be changed during drag&drop, so you should update state of the react app as well. Consider to add onDragMove or onDragEnd events. For more info see: https://github.com/konvajs/react-konva/issues/256 `,gys=`ReactKonva: You are using "zIndex" attribute for a Konva node. react-konva may get confused with ordering. Just define correct order of elements in your render function of a component. For more info see: https://github.com/konvajs/react-konva/issues/194 `,yys={};function tve(s,t,n=yys){if(!XVe&&"zIndex"in t&&(console.warn(gys),XVe=!0),!JVe&&t.draggable){var r=t.x!==void 0||t.y!==void 0,a=t.onDragEnd||t.onDragMove;r&&!a&&(console.warn(xys),JVe=!0)}for(var i in n)if(!QVe[i]){var l=i.slice(0,2)==="on",o=n[i]!==t[i];if(l&&o){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),s.off(c,n[i])}var d=!t.hasOwnProperty(i);d&&s.setAttr(i,void 0)}var u=t._useStrictMode,h={},p=!1;const f={};for(var i in t)if(!QVe[i]){var l=i.slice(0,2)==="on",y=n[i]!==t[i];if(l&&y){var c=i.substr(2).toLowerCase();c.substr(0,7)==="content"&&(c="content"+c.substr(7,1).toUpperCase()+c.substr(8)),t[i]&&(f[c]=t[i])}!l&&(t[i]!==n[i]||u&&t[i]!==s.getAttr(i))&&(p=!0,h[i]=t[i])}p&&(s.setAttrs(h),eC(s));for(var c in f)s.on(c+fIe,f[c])}function eC(s){if(!ua.autoDrawEnabled){var t=s.getLayer()||s.getStage();t&&t.batchDraw()}}const Kgt={},vys={};jM.Node.prototype._applyProps=tve;function bys(s,t){if(typeof t=="string"){console.error(`Do not use plain text as child of Konva.Node. You are using text: ${t}`);return}s.add(t),eC(s)}function _ys(s,t,n){let r=jM[s];r||(console.error(`Konva has no node with the type ${s}. Group will be used instead. If you use minimal version of react-konva, just import required nodes into Konva: "import "konva/lib/shapes/${s}" If you want to render DOM elements as part of canvas tree take a look into this demo: https://konvajs.github.io/docs/react/DOM_Portal.html`),r=jM.Group);const a={},i={};for(var l in t){var o=l.slice(0,2)==="on";o?i[l]=t[l]:a[l]=t[l]}const c=new r(a);return tve(c,i),c}function wys(s,t,n){console.error(`Text components are not supported for now in ReactKonva. Your text is: "${s}"`)}function jys(s,t,n){return!1}function Nys(s){return s}function kys(){return null}function Sys(){return null}function Cys(s,t,n,r){return vys}function Tys(){}function Eys(s){}function Ays(s,t){return!1}function Mys(){return Kgt}function Iys(){return Kgt}const Pys=setTimeout,Lys=clearTimeout,Dys=-1;function Rys(s,t){return!1}const Oys=!1,Fys=!0,zys=!0;function Bys(s,t){t.parent===s?t.moveToTop():s.add(t),eC(s)}function $ys(s,t){t.parent===s?t.moveToTop():s.add(t),eC(s)}function Ygt(s,t,n){t._remove(),s.add(t),t.setZIndex(n.getZIndex()),eC(s)}function Uys(s,t,n){Ygt(s,t,n)}function qys(s,t){t.destroy(),t.off(fIe),eC(s)}function Vys(s,t){t.destroy(),t.off(fIe),eC(s)}function Hys(s,t,n){console.error(`Text components are not yet supported in ReactKonva. You text is: "${n}"`)}function Gys(s,t,n){}function Wys(s,t,n,r,a){tve(s,a,r)}function Kys(s){s.hide(),eC(s)}function Yys(s){}function Zys(s,t){(t.visible==null||t.visible)&&s.show()}function Qys(s,t){}function Xys(s){}function Jys(){}const evs=()=>Wgt.DefaultEventPriority,tvs=Object.freeze(Object.defineProperty({__proto__:null,appendChild:Bys,appendChildToContainer:$ys,appendInitialChild:bys,cancelTimeout:Lys,clearContainer:Xys,commitMount:Gys,commitTextUpdate:Hys,commitUpdate:Wys,createInstance:_ys,createTextInstance:wys,detachDeletedInstance:Jys,finalizeInitialChildren:jys,getChildHostContext:Iys,getCurrentEventPriority:evs,getPublicInstance:Nys,getRootHostContext:Mys,hideInstance:Kys,hideTextInstance:Yys,idlePriority:_7.unstable_IdlePriority,insertBefore:Ygt,insertInContainerBefore:Uys,isPrimaryRenderer:Oys,noTimeout:Dys,now:_7.unstable_now,prepareForCommit:kys,preparePortalMount:Sys,prepareUpdate:Cys,removeChild:qys,removeChildFromContainer:Vys,resetAfterCommit:Tys,resetTextContent:Eys,run:_7.unstable_runWithPriority,scheduleTimeout:Pys,shouldDeprioritizeSubtree:Ays,shouldSetTextContent:Rys,supportsMutation:zys,unhideInstance:Zys,unhideTextInstance:Qys,warnsIfNotActing:Fys},Symbol.toStringTag,{value:"Module"}));var svs=Object.defineProperty,nvs=Object.defineProperties,rvs=Object.getOwnPropertyDescriptors,eHe=Object.getOwnPropertySymbols,avs=Object.prototype.hasOwnProperty,ivs=Object.prototype.propertyIsEnumerable,tHe=(s,t,n)=>t in s?svs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,sHe=(s,t)=>{for(var n in t||(t={}))avs.call(t,n)&&tHe(s,n,t[n]);if(eHe)for(var n of eHe(t))ivs.call(t,n)&&tHe(s,n,t[n]);return s},ovs=(s,t)=>nvs(s,rvs(t)),nHe,rHe;typeof window<"u"&&((nHe=window.document)!=null&&nHe.createElement||((rHe=window.navigator)==null?void 0:rHe.product)==="ReactNative")?N.useLayoutEffect:N.useEffect;function Zgt(s,t,n){if(!s)return;if(n(s)===!0)return s;let r=s.child;for(;r;){const a=Zgt(r,t,n);if(a)return a;r=r.sibling}}function Qgt(s){try{return Object.defineProperties(s,{_currentRenderer:{get(){return null},set(){}},_currentRenderer2:{get(){return null},set(){}}})}catch{return s}}const aHe=console.error;console.error=function(){const s=[...arguments].join("");if(s!=null&&s.startsWith("Warning:")&&s.includes("useContext")){console.error=aHe;return}return aHe.apply(this,arguments)};const xIe=Qgt(N.createContext(null));class Xgt extends N.Component{render(){return N.createElement(xIe.Provider,{value:this._reactInternals},this.props.children)}}function lvs(){const s=N.useContext(xIe);if(s===null)throw new Error("its-fine: useFiber must be called within a !");const t=N.useId();return N.useMemo(()=>{for(const r of[s,s==null?void 0:s.alternate]){if(!r)continue;const a=Zgt(r,!1,i=>{let l=i.memoizedState;for(;l;){if(l.memoizedState===t)return!0;l=l.next}});if(a)return a}},[s,t])}function cvs(){const s=lvs(),[t]=N.useState(()=>new Map);t.clear();let n=s;for(;n;){if(n.type&&typeof n.type=="object"){const a=n.type._context===void 0&&n.type.Provider===n.type?n.type:n.type._context;a&&a!==xIe&&!t.has(a)&&t.set(a,N.useContext(Qgt(a)))}n=n.return}return t}function dvs(){const s=cvs();return N.useMemo(()=>Array.from(s.keys()).reduce((t,n)=>r=>N.createElement(t,null,N.createElement(n.Provider,ovs(sHe({},r),{value:s.get(n)}))),t=>N.createElement(Xgt,sHe({},t))),[s])}function uvs(s){const t=Ct.useRef({});return Ct.useLayoutEffect(()=>{t.current=s}),Ct.useLayoutEffect(()=>()=>{t.current={}},[]),t.current}const hvs=s=>{const t=Ct.useRef(null),n=Ct.useRef(null),r=Ct.useRef(null),a=uvs(s),i=dvs(),l=o=>{const{forwardedRef:c}=s;c&&(typeof c=="function"?c(o):c.current=o)};return Ct.useLayoutEffect(()=>(n.current=new jM.Stage({width:s.width,height:s.height,container:t.current}),l(n.current),r.current=m7.createContainer(n.current,Wgt.LegacyRoot,!1,null),m7.updateContainer(Ct.createElement(i,{},s.children),r.current),()=>{jM.isBrowser&&(l(null),m7.updateContainer(null,r.current,null),n.current.destroy())}),[]),Ct.useLayoutEffect(()=>{l(n.current),tve(n.current,s,a),m7.updateContainer(Ct.createElement(i,{},s.children),r.current,null)}),Ct.createElement("div",{ref:t,id:s.id,accessKey:s.accessKey,className:s.className,role:s.role,style:s.style,tabIndex:s.tabIndex,title:s.title})},mvs="Layer",TS="Group",I_="Rect",TP="Image",kI="Text",Efn="Transformer",m7=fys(tvs);m7.injectIntoDevTools({findHostInstanceByFiber:()=>null,bundleType:0,version:Ct.version,rendererPackageName:"react-konva"});const pvs=Ct.forwardRef((s,t)=>Ct.createElement(Xgt,{},Ct.createElement(hvs,{...s,forwardedRef:t})));function fvs({imageUrl:s,preset:t,barStyleId:n,overrides:r,maxDisplayWidth:a=720,stageRef:i}){const l=N.useRef(null),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(null),f=(t==null?void 0:t.headshot_url)??"",y=(t==null?void 0:t.brokerage_logo_url)??"";N.useEffect(()=>{if(!s){c(null);return}const Y=new window.Image;Y.crossOrigin="anonymous",Y.onload=()=>c(Y),Y.onerror=()=>c(null),Y.src=s},[s]),N.useEffect(()=>{if(!f){u(null);return}const Y=new window.Image;Y.crossOrigin="anonymous",Y.onload=()=>u(Y),Y.onerror=()=>u(null),Y.src=f},[f]),N.useEffect(()=>{if(!y){p(null);return}const Y=new window.Image;Y.crossOrigin="anonymous",Y.onload=()=>p(Y),Y.onerror=()=>p(null),Y.src=y},[y]);const _=Bxs(n),v=(o==null?void 0:o.naturalWidth)??1080,j=(o==null?void 0:o.naturalHeight)??1080,w=N.useMemo(()=>Math.min(1,a/v),[v,a]),S=v*w,A=j*w,E=(r==null?void 0:r.brand_color)??(t==null?void 0:t.brand_color)??"#0f172a",O=(r==null?void 0:r.accent_color)??(t==null?void 0:t.accent_color)??"#3b82f6",D=(r==null?void 0:r.display_name)??(t==null?void 0:t.display_name)??"",I=(r==null?void 0:r.phone)??(t==null?void 0:t.phone)??"",F=(r==null?void 0:r.email)??(t==null?void 0:t.email)??"",z=(r==null?void 0:r.tagline)??(t==null?void 0:t.tagline)??"",H=new Set((r==null?void 0:r.hidden_fields)??(t==null?void 0:t.hidden_fields)??[]),Z=Y=>_.fields.includes(Y)&&!H.has(Y);return e.jsx("div",{className:"border rounded-lg overflow-hidden bg-muted/40 inline-block",children:e.jsx(pvs,{ref:Y=>{l.current=Y,i&&(i.current=Y)},width:S,height:A,scaleX:w,scaleY:w,children:e.jsxs(mvs,{children:[o&&e.jsx(TP,{image:o,width:v,height:j,listening:!1}),!o&&e.jsx(I_,{x:0,y:0,width:v,height:j,fill:"#e2e8f0"}),e.jsx(xvs,{style:_,canvasW:v,canvasH:j,brandColor:E,accentColor:O,name:D,phone:I,email:F,tagline:z,headshot:d,logo:h,hidden:H,has:Z})]})})})}function xvs({style:s,canvasW:t,canvasH:n,brandColor:r,accentColor:a,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h}){const p=n*s.heightRatio,f=p*.18,y=s.textColor==="light"?"#ffffff":s.textColor==="dark"?"#0f172a":s.background==="dark"||s.background==="gradient"?"#ffffff":$xs(r),_=y==="#ffffff"?"rgba(255,255,255,0.78)":"rgba(15,23,42,0.7)";if(s.position==="bottom"||s.position==="top"){const v=s.position==="bottom"?n-p:0;return e.jsxs(TS,{children:[e.jsx(I_,{x:0,y:v,width:t,height:p,fill:r}),e.jsx(I_,{x:0,y:s.position==="bottom"?v:p-4,width:t,height:4,fill:a}),e.jsx(LH,{x:f,y:v+f,width:t-f*2,height:p-f*2,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="corner-br"){const v=t*.42,j=p,w=t-v-n*.025,S=n-j-n*.025;return e.jsxs(TS,{children:[e.jsx(I_,{x:w,y:S,width:v,height:j,fill:r,cornerRadius:j*.12,opacity:.92}),e.jsx(I_,{x:w,y:S+j-4,width:v,height:4,fill:a,cornerRadius:2}),e.jsx(LH,{x:w+f,y:S+f,width:v-f*2,height:j-f*2,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot})]})}if(s.position==="side-right"){const v=Math.max(t*.22,Math.min(t*.3,260)),j=v*.12;return e.jsxs(TS,{children:[e.jsx(I_,{x:t-v,y:0,width:v,height:n,fill:r}),e.jsx(I_,{x:t-v,y:0,width:4,height:n,fill:a}),e.jsx(LH,{x:t-v+j,y:n*.08,width:v-j*2,height:n*.84,textColor:y,subTextColor:_,name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot,vertical:!0,railWidth:v})]})}return s.position==="letterbox"?e.jsxs(TS,{children:[e.jsx(I_,{x:0,y:0,width:t,height:p,fill:"#0a0a0a"}),e.jsx(I_,{x:0,y:n-p,width:t,height:p,fill:"#0a0a0a"}),e.jsx(I_,{x:0,y:n-p,width:t,height:3,fill:a}),e.jsx(LH,{x:f,y:n-p+f,width:t-f*2,height:p-f*2,textColor:"#ffffff",subTextColor:"rgba(255,255,255,0.75)",name:i,phone:l,email:o,tagline:c,headshot:d,logo:u,has:h,circular:s.circularHeadshot}),u&&h("logo")&&e.jsx(TP,{image:u,x:t-f-p*.7,y:f,height:p-f*2,width:p*.7})]}):null}function LH({x:s,y:t,width:n,height:r,textColor:a,subTextColor:i,name:l,phone:o,email:c,tagline:d,headshot:u,logo:h,has:p,circular:f,vertical:y,railWidth:_}){if(y){const Y=_??n,W=Math.min(n,Y*.7),ee=Math.max(14,Y*.13),se=Math.max(11,Y*.085),oe=Y*.08,he=Y*.35;let ce=t;const me=ce;ce+=W+oe;const le=ce,ve=l.length>12?2:1;ce+=ee*1.15*ve+oe*.5;const ge=ce;p("phone")&&o&&(ce+=se*1.3+oe*.4);const Te=ce;p("email")&&c&&(ce+=se*1.3+oe*.4);const Ie=ce+oe*.5;return e.jsxs(TS,{children:[p("headshot")&&u&&e.jsx(TS,{clipFunc:f?Ce=>{Ce.beginPath(),Ce.arc(s+n/2,me+W/2,W/2,0,Math.PI*2),Ce.closePath()}:void 0,children:e.jsx(TP,{image:u,x:s+(n-W)/2,y:me,width:W,height:W})}),p("name")&&l&&e.jsx(kI,{text:l,x:s,y:le,width:n,align:"center",fontSize:ee,fontStyle:"bold",fill:a}),p("phone")&&o&&e.jsx(kI,{text:o,x:s,y:ge,width:n,align:"center",fontSize:se,fill:i}),p("email")&&c&&e.jsx(kI,{text:c,x:s,y:Te,width:n,align:"center",fontSize:se,fill:i,ellipsis:!0,wrap:"none"}),p("logo")&&h&&e.jsx(TP,{image:h,x:s,y:Ie,width:n,height:he})]})}const v=r*.95,j=u&&p("headshot")?s+v+r*.18:s,w=n-(j-s)-(h&&p("logo")?r*1.6:0),S=Math.max(20,r*.34),A=Math.max(13,r*.22),E=r*.06,O=p("tagline")&&d?1:0,D=p("phone")&&o?1:0,I=p("email")&&c?1:0,F=1+O+(D||I?1:0),z=F*S+(F-1)*E;let Z=t+(r-z)/2;return e.jsxs(TS,{children:[p("headshot")&&u&&e.jsx(TS,{clipFunc:f?Y=>{Y.beginPath(),Y.arc(s+v/2,t+v/2,v/2,0,Math.PI*2),Y.closePath()}:void 0,children:e.jsx(TP,{image:u,x:s,y:t+(r-v)/2,width:v,height:v})}),p("name")&&l&&e.jsx(kI,{text:l,x:j,y:Z,width:w,fontSize:S,fontStyle:"bold",fill:a,ellipsis:!0,wrap:"none"}),(Z+=S+E,null),p("tagline")&&d&&e.jsxs(e.Fragment,{children:[e.jsx(kI,{text:d,x:j,y:Z,width:w,fontSize:A*1.1,fontStyle:"italic",fill:i,ellipsis:!0,wrap:"none"}),(Z+=A*1.1+E,null)]}),D||I?e.jsx(kI,{text:[o,c].filter(Boolean).join(" • "),x:j,y:Z,width:w,fontSize:A,fill:i,ellipsis:!0,wrap:"none"}):null,p("logo")&&h&&e.jsx(TP,{image:h,x:s+n-r*1.4,y:t+(r-r*.8)/2,width:r*1.4,height:r*.8})]})}function gvs(){const{data:s}=pU(),t=(s==null?void 0:s.find(Z=>Z.is_default))??(s==null?void 0:s[0])??null,[n,r]=N.useState(void 0),a=(s==null?void 0:s.find(Z=>Z.id===n))??t,[i,l]=N.useState([]),[o,c]=N.useState(0),[d,u]=N.useState("minimal-stripe"),[h,p]=N.useState({}),[f,y]=N.useState(!1),_=N.useRef(null),[v,j]=N.useState(780),w=N.useRef(null),S=Z=>{if(w.current&&(w.current.disconnect(),w.current=null),!Z)return;const Y=()=>{const ee=Z.clientWidth;ee>0&&j(Math.min(780,ee-16))};Y();const W=new ResizeObserver(Y);W.observe(Z),w.current=W};N.useEffect(()=>()=>{var Z;(Z=w.current)==null||Z.disconnect()},[]);const A=N.useRef(null),E=Z=>{if(!Z)return;const Y=[];Array.from(Z).forEach(W=>{W.type.startsWith("image/")&&Y.push({id:crypto.randomUUID(),url:URL.createObjectURL(W),file:W,name:W.name})}),l(W=>[...W,...Y])},O=Z=>{l(Y=>{const W=Y.find(ee=>ee.id===Z);return W&&URL.revokeObjectURL(W.url),Y.filter(ee=>ee.id!==Z)}),c(0)},D=typeof navigator<"u"&&/iPad|iPhone|iPod/.test(navigator.userAgent),I=Z=>{var he;const[Y,W]=Z.split(","),ee=((he=Y.match(/:(.*?);/))==null?void 0:he[1])??"image/jpeg",se=atob(W),oe=new Uint8Array(se.length);for(let ce=0;ce{var Z;if(A.current){y(!0);try{const Y=A.current,W=Y.toDataURL({pixelRatio:1/(Y.scaleX()||1),mimeType:"image/jpeg",quality:.95}),se=`${((Z=i[o])==null?void 0:Z.name.replace(/\.[^.]+$/,""))||"branded"}-branded.jpg`,oe=I(W),he=URL.createObjectURL(oe);if(D)window.open(he,"_blank")||(window.location.href=he),ae.success('Long-press the image and tap "Save to Photos"');else{const ce=document.createElement("a");ce.href=he,ce.download=se,document.body.appendChild(ce),ce.click(),ce.remove(),ae.success("Image exported")}setTimeout(()=>URL.revokeObjectURL(he),6e4)}catch(Y){ae.error(Y.message||"Export failed")}finally{y(!1)}}},z=async()=>{if(i.length){y(!0);try{const Z=new ugt,Y=i.length,W=o;for(let oe=0;oesetTimeout(ve,600)),!A.current)continue;const he=A.current,me=he.toDataURL({pixelRatio:1/(he.scaleX()||1),mimeType:"image/jpeg",quality:.95}).split(",")[1],le=i[oe].name.replace(/\.[^.]+$/,"")||`image-${oe+1}`;Z.file(`${le}-branded.jpg`,me,{base64:!0})}c(W);const ee=await Z.generateAsync({type:"blob"}),se=document.createElement("a");se.href=URL.createObjectURL(ee),se.download=`branded-images-${Date.now()}.zip`,se.click(),URL.revokeObjectURL(se.href),ae.success(`${Y} images exported`)}catch(Z){ae.error(Z.message||"Batch export failed")}finally{y(!1)}}},H=i[o];return e.jsx(Cs,{title:"Branding Bar Studio",children:e.jsxs("div",{className:"container max-w-7xl py-4 md:py-6 space-y-4 px-3 md:px-6",children:[e.jsx(Zo,{children:e.jsx("title",{children:"Branding Bar Studio | Marketing Studio"})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(In,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(qr,{className:"h-3 w-3"})," Marketing Studio"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Branding Bar Studio"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground",children:"Drop in any image, get a branded export. No AI credits used."})]}),e.jsx(B,{variant:"outline",asChild:!0,className:"w-full sm:w-auto",children:e.jsxs(In,{to:"/marketing-studio/brand-kit",children:[e.jsx(pl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})})]}),!a&&e.jsx(fe,{className:"border-dashed border-amber-500/50 bg-amber-500/5",children:e.jsxs(Ee,{className:"py-5 flex flex-col sm:flex-row sm:items-center sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"Create your brand kit first"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"We'll pre-fill it from your profile so you can be exporting in seconds."})]}),e.jsx(B,{asChild:!0,className:"w-full sm:w-auto",children:e.jsx(In,{to:"/marketing-studio/brand-kit",children:"Set up brand"})})]})}),e.jsxs("div",{className:"grid gap-6 lg:grid-cols-[1fr_360px]",children:[e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsx(fe,{className:"overflow-hidden",children:e.jsxs(Ee,{className:"p-4",children:[H?e.jsx("div",{ref:S,className:"flex justify-center bg-muted/30 rounded p-2 overflow-hidden",children:e.jsx(fvs,{imageUrl:H.url,preset:a,barStyleId:d,overrides:h,maxDisplayWidth:v,stageRef:A})}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-12 text-center space-y-3 cursor-pointer hover:bg-muted/30 transition-colors",onClick:()=>{var Z;return(Z=_.current)==null?void 0:Z.click()},onDragOver:Z=>Z.preventDefault(),onDrop:Z=>{Z.preventDefault(),E(Z.dataTransfer.files)},children:[e.jsx(Xo,{className:"h-12 w-12 mx-auto text-muted-foreground/60"}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium",children:"Drop images here or click to browse"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add up to 50 photos at once. We'll batch-brand them all."})]}),e.jsxs(B,{type:"button",children:[e.jsx(_a,{className:"h-4 w-4 mr-1"})," Choose images"]})]}),e.jsx("input",{ref:_,type:"file",accept:"image/*",multiple:!0,hidden:!0,onChange:Z=>E(Z.target.files)})]})}),i.length>0&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ee,{className:"p-3",children:e.jsxs("div",{className:"flex gap-2 overflow-x-auto py-1",children:[i.map((Z,Y)=>e.jsxs("div",{className:"relative group flex-shrink-0",children:[e.jsx("button",{onClick:()=>c(Y),className:`block h-16 w-16 rounded overflow-hidden border-2 transition-all ${Y===o?"border-primary":"border-transparent hover:border-muted-foreground/30"}`,children:e.jsx("img",{src:Z.url,alt:"",className:"h-full w-full object-cover"})}),e.jsx("button",{onClick:()=>O(Z.id),className:"absolute -top-1 -right-1 bg-destructive text-destructive-foreground rounded-full p-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx($n,{className:"h-3 w-3"})})]},Z.id)),e.jsx("button",{onClick:()=>{var Z;return(Z=_.current)==null?void 0:Z.click()},className:"flex-shrink-0 h-16 w-16 rounded border-2 border-dashed flex items-center justify-center hover:bg-muted/40",children:e.jsx(Is,{className:"h-5 w-5 text-muted-foreground"})})]})})}),i.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 justify-end",children:[e.jsx(B,{variant:"outline",onClick:()=>{i.forEach(Z=>URL.revokeObjectURL(Z.url)),l([])},children:"Clear all"}),e.jsxs(B,{onClick:F,disabled:f||!H,children:[f?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Download this image"]}),i.length>1&&e.jsxs(B,{onClick:z,disabled:f,children:[f?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Download all (",i.length,") as ZIP"]})]})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-base",children:"Brand preset"})}),e.jsx(Ee,{children:e.jsxs(us,{value:(a==null?void 0:a.id)??"",onValueChange:r,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Choose preset"})}),e.jsx(cs,{children:s==null?void 0:s.map(Z=>e.jsxs(Ze,{value:Z.id,children:[Z.name," ",Z.is_default?"(default)":""]},Z.id))})]})})]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-base",children:"Bar style"})}),e.jsx(Ee,{children:e.jsx(Uxs,{value:d,onChange:u,mediaType:"image"})})]}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-base",children:"Tweak this design"})}),e.jsx(Ee,{children:e.jsxs(Fr,{defaultValue:"text",children:[e.jsxs(Rr,{className:"grid grid-cols-2 w-full",children:[e.jsx(Zt,{value:"text",children:"Text"}),e.jsx(Zt,{value:"colors",children:"Colors"})]}),e.jsxs(is,{value:"text",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Display name"}),e.jsx(ye,{value:h.display_name??(a==null?void 0:a.display_name)??"",onChange:Z=>p({...h,display_name:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Phone"}),e.jsx(ye,{value:h.phone??(a==null?void 0:a.phone)??"",onChange:Z=>p({...h,phone:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Email"}),e.jsx(ye,{value:h.email??(a==null?void 0:a.email)??"",onChange:Z=>p({...h,email:Z.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Tagline"}),e.jsx(ye,{value:h.tagline??(a==null?void 0:a.tagline)??"",onChange:Z=>p({...h,tagline:Z.target.value})})]})]}),e.jsxs(is,{value:"colors",className:"space-y-3 pt-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Bar color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:Z=>p({...h,brand_color:Z.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(ye,{value:h.brand_color??(a==null?void 0:a.brand_color)??"#0f172a",onChange:Z=>p({...h,brand_color:Z.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Accent line"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:Z=>p({...h,accent_color:Z.target.value}),className:"h-10 w-14 rounded border cursor-pointer"}),e.jsx(ye,{value:h.accent_color??(a==null?void 0:a.accent_color)??"#3b82f6",onChange:Z=>p({...h,accent_color:Z.target.value})})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>p({}),children:"Reset to preset"})]})]})})]})]})]})]})})}function yvs(s,t){if(s.match(/^[a-z]+:\/\//i))return s;if(s.match(/^\/\//))return window.location.protocol+s;if(s.match(/^[a-z]+:/i))return s;const n=document.implementation.createHTMLDocument(),r=n.createElement("base"),a=n.createElement("a");return n.head.appendChild(r),n.body.appendChild(a),t&&(r.href=t),a.href=s,a.href}const vvs=(()=>{let s=0;const t=()=>`0000${(Math.random()*36**4<<0).toString(36)}`.slice(-4);return()=>(s+=1,`u${t()}${s}`)})();function m4(s){const t=[];for(let n=0,r=s.length;nC0||s.height>C0)&&(s.width>C0&&s.height>C0?s.width>s.height?(s.height*=C0/s.width,s.width=C0):(s.width*=C0/s.height,s.height=C0):s.width>C0?(s.height*=C0/s.width,s.width=C0):(s.width*=C0/s.height,s.height=C0))}function mxe(s){return new Promise((t,n)=>{const r=new Image;r.onload=()=>{r.decode().then(()=>{requestAnimationFrame(()=>t(r))})},r.onerror=n,r.crossOrigin="anonymous",r.decoding="async",r.src=s})}async function Nvs(s){return Promise.resolve().then(()=>new XMLSerializer().serializeToString(s)).then(encodeURIComponent).then(t=>`data:image/svg+xml;charset=utf-8,${t}`)}async function kvs(s,t,n){const r="http://www.w3.org/2000/svg",a=document.createElementNS(r,"svg"),i=document.createElementNS(r,"foreignObject");return a.setAttribute("width",`${t}`),a.setAttribute("height",`${n}`),a.setAttribute("viewBox",`0 0 ${t} ${n}`),i.setAttribute("width","100%"),i.setAttribute("height","100%"),i.setAttribute("x","0"),i.setAttribute("y","0"),i.setAttribute("externalResourcesRequired","true"),a.appendChild(i),i.appendChild(s),Nvs(a)}const Wg=(s,t)=>{if(s instanceof t)return!0;const n=Object.getPrototypeOf(s);return n===null?!1:n.constructor.name===t.name||Wg(n,t)};function Svs(s){const t=s.getPropertyValue("content");return`${s.cssText} content: '${t.replace(/'|"/g,"")}';`}function Cvs(s,t){return Jgt(t).map(n=>{const r=s.getPropertyValue(n),a=s.getPropertyPriority(n);return`${n}: ${r}${a?" !important":""};`}).join(" ")}function Tvs(s,t,n,r){const a=`.${s}:${t}`,i=n.cssText?Svs(n):Cvs(n,r);return document.createTextNode(`${a}{${i}}`)}function iHe(s,t,n,r){const a=window.getComputedStyle(s,n),i=a.getPropertyValue("content");if(i===""||i==="none")return;const l=vvs();try{t.className=`${t.className} ${l}`}catch{return}const o=document.createElement("style");o.appendChild(Tvs(l,n,a,r)),t.appendChild(o)}function Evs(s,t,n){iHe(s,t,":before",n),iHe(s,t,":after",n)}const oHe="application/font-woff",lHe="image/jpeg",Avs={woff:oHe,woff2:oHe,ttf:"application/font-truetype",eot:"application/vnd.ms-fontobject",png:"image/png",jpg:lHe,jpeg:lHe,gif:"image/gif",tiff:"image/tiff",svg:"image/svg+xml",webp:"image/webp"};function Mvs(s){const t=/\.([^./]*?)$/g.exec(s);return t?t[1]:""}function gIe(s){const t=Mvs(s).toLowerCase();return Avs[t]||""}function Ivs(s){return s.split(/,/)[1]}function XCe(s){return s.search(/^(data:)/)!==-1}function Pvs(s,t){return`data:${t};base64,${s}`}async function t0t(s,t,n){const r=await fetch(s,t);if(r.status===404)throw new Error(`Resource "${r.url}" not found`);const a=await r.blob();return new Promise((i,l)=>{const o=new FileReader;o.onerror=l,o.onloadend=()=>{try{i(n({res:r,result:o.result}))}catch(c){l(c)}},o.readAsDataURL(a)})}const x2e={};function Lvs(s,t,n){let r=s.replace(/\?.*/,"");return n&&(r=s),/ttf|otf|eot|woff2?/i.test(r)&&(r=r.replace(/.*\//,"")),t?`[${t}]${r}`:r}async function yIe(s,t,n){const r=Lvs(s,t,n.includeQueryParams);if(x2e[r]!=null)return x2e[r];n.cacheBust&&(s+=(/\?/.test(s)?"&":"?")+new Date().getTime());let a;try{const i=await t0t(s,n.fetchRequestInit,({res:l,result:o})=>(t||(t=l.headers.get("Content-Type")||""),Ivs(o)));a=Pvs(i,t)}catch(i){a=n.imagePlaceholder||"";let l=`Failed to fetch resource: ${s}`;i&&(l=typeof i=="string"?i:i.message),l&&console.warn(l)}return x2e[r]=a,a}async function Dvs(s){const t=s.toDataURL();return t==="data:,"?s.cloneNode(!1):mxe(t)}async function Rvs(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 mxe(o)}const n=s.poster,r=gIe(n),a=await yIe(n,r,t);return mxe(a)}async function Ovs(s,t){var n;try{if(!((n=s==null?void 0:s.contentDocument)===null||n===void 0)&&n.body)return await sve(s.contentDocument.body,t,!0)}catch{}return s.cloneNode(!1)}async function Fvs(s,t){return Wg(s,HTMLCanvasElement)?Dvs(s):Wg(s,HTMLVideoElement)?Rvs(s,t):Wg(s,HTMLIFrameElement)?Ovs(s,t):s.cloneNode(s0t(s))}const zvs=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SLOT",s0t=s=>s.tagName!=null&&s.tagName.toUpperCase()==="SVG";async function Bvs(s,t,n){var r,a;if(s0t(t))return t;let i=[];return zvs(s)&&s.assignedNodes?i=m4(s.assignedNodes()):Wg(s,HTMLIFrameElement)&&(!((r=s.contentDocument)===null||r===void 0)&&r.body)?i=m4(s.contentDocument.body.childNodes):i=m4(((a=s.shadowRoot)!==null&&a!==void 0?a:s).childNodes),i.length===0||Wg(s,HTMLVideoElement)||await i.reduce((l,o)=>l.then(()=>sve(o,n)).then(c=>{c&&t.appendChild(c)}),Promise.resolve()),t}function $vs(s,t,n){const r=t.style;if(!r)return;const a=window.getComputedStyle(s);a.cssText?(r.cssText=a.cssText,r.transformOrigin=a.transformOrigin):Jgt(n).forEach(i=>{let l=a.getPropertyValue(i);i==="font-size"&&l.endsWith("px")&&(l=`${Math.floor(parseFloat(l.substring(0,l.length-2)))-.1}px`),Wg(s,HTMLIFrameElement)&&i==="display"&&l==="inline"&&(l="block"),i==="d"&&t.getAttribute("d")&&(l=`path(${t.getAttribute("d")})`),r.setProperty(i,l,a.getPropertyPriority(i))})}function Uvs(s,t){Wg(s,HTMLTextAreaElement)&&(t.innerHTML=s.value),Wg(s,HTMLInputElement)&&t.setAttribute("value",s.value)}function qvs(s,t){if(Wg(s,HTMLSelectElement)){const n=t,r=Array.from(n.children).find(a=>s.value===a.getAttribute("value"));r&&r.setAttribute("selected","")}}function Vvs(s,t,n){return Wg(t,Element)&&($vs(s,t,n),Evs(s,t,n),Uvs(s,t),qvs(s,t)),t}async function Hvs(s,t){const n=s.querySelectorAll?s.querySelectorAll("use"):[];if(n.length===0)return s;const r={};for(let i=0;iFvs(r,t)).then(r=>Bvs(s,r,t)).then(r=>Vvs(s,r,t)).then(r=>Hvs(r,t))}const n0t=/url\((['"]?)([^'"]+?)\1\)/g,Gvs=/url\([^)]+\)\s*format\((["']?)([^"']+)\1\)/g,Wvs=/src:\s*(?:url\([^)]+\)\s*format\([^)]+\)[,;]\s*)+/g;function Kvs(s){const t=s.replace(/([.*+?^${}()|\[\]\/\\])/g,"\\$1");return new RegExp(`(url\\(['"]?)(${t})(['"]?\\))`,"g")}function Yvs(s){const t=[];return s.replace(n0t,(n,r,a)=>(t.push(a),n)),t.filter(n=>!XCe(n))}async function Zvs(s,t,n,r,a){try{const i=n?yvs(t,n):t,l=gIe(t);let o;return a||(o=await yIe(i,l,r)),s.replace(Kvs(t),`$1${o}$3`)}catch{}return s}function Qvs(s,{preferredFontFormat:t}){return t?s.replace(Wvs,n=>{for(;;){const[r,,a]=Gvs.exec(n)||[];if(!a)return"";if(a===t)return`src: ${r};`}}):s}function r0t(s){return s.search(n0t)!==-1}async function a0t(s,t,n){if(!r0t(s))return s;const r=Qvs(s,n);return Yvs(r).reduce((i,l)=>i.then(o=>Zvs(o,l,t,n)),Promise.resolve(r))}async function CI(s,t,n){var r;const a=(r=t.style)===null||r===void 0?void 0:r.getPropertyValue(s);if(a){const i=await a0t(a,null,n);return t.style.setProperty(s,i,t.style.getPropertyPriority(s)),!0}return!1}async function Xvs(s,t){await CI("background",s,t)||await CI("background-image",s,t),await CI("mask",s,t)||await CI("-webkit-mask",s,t)||await CI("mask-image",s,t)||await CI("-webkit-mask-image",s,t)}async function Jvs(s,t){const n=Wg(s,HTMLImageElement);if(!(n&&!XCe(s.src))&&!(Wg(s,SVGImageElement)&&!XCe(s.href.baseVal)))return;const r=n?s.src:s.href.baseVal,a=await yIe(r,gIe(r),t);await new Promise((i,l)=>{s.onload=i,s.onerror=t.onImageErrorHandler?(...c)=>{try{i(t.onImageErrorHandler(...c))}catch(d){l(d)}}:l;const o=s;o.decode&&(o.decode=i),o.loading==="lazy"&&(o.loading="eager"),n?(s.srcset="",s.src=a):s.href.baseVal=a})}async function e1s(s,t){const r=m4(s.childNodes).map(a=>i0t(a,t));await Promise.all(r).then(()=>s)}async function i0t(s,t){Wg(s,Element)&&(await Xvs(s,t),await Jvs(s,t),await e1s(s,t))}function t1s(s,t){const{style:n}=s;t.backgroundColor&&(n.backgroundColor=t.backgroundColor),t.width&&(n.width=`${t.width}px`),t.height&&(n.height=`${t.height}px`);const r=t.style;return r!=null&&Object.keys(r).forEach(a=>{n[a]=r[a]}),s}const cHe={};async function dHe(s){let t=cHe[s];if(t!=null)return t;const r=await(await fetch(s)).text();return t={url:s,cssText:r},cHe[s]=t,t}async function uHe(s,t){let n=s.cssText;const r=/url\(["']?([^"')]+)["']?\)/g,i=(n.match(/url\([^)]+\)/g)||[]).map(async l=>{let o=l.replace(r,"$1");return o.startsWith("https://")||(o=new URL(o,s.url).href),t0t(o,t.fetchRequestInit,({result:c})=>(n=n.replace(l,`url(${c})`),[l,c]))});return Promise.all(i).then(()=>n)}function hHe(s){if(s==null)return[];const t=[],n=/(\/\*[\s\S]*?\*\/)/gi;let r=s.replace(n,"");const a=new RegExp("((@.*?keyframes [\\s\\S]*?){([\\s\\S]*?}\\s*?)})","gi");for(;;){const c=a.exec(r);if(c===null)break;t.push(c[0])}r=r.replace(a,"");const i=/@import[\s\S]*?url\([^)]*\)[\s\S]*?;/gi,l="((\\s*?(?:\\/\\*[\\s\\S]*?\\*\\/)?\\s*?@media[\\s\\S]*?){([\\s\\S]*?)}\\s*?})|(([\\s\\S]*?){([\\s\\S]*?)})",o=new RegExp(l,"gi");for(;;){let c=i.exec(r);if(c===null){if(c=o.exec(r),c===null)break;i.lastIndex=o.lastIndex}else o.lastIndex=i.lastIndex;t.push(c[0])}return t}async function s1s(s,t){const n=[],r=[];return s.forEach(a=>{if("cssRules"in a)try{m4(a.cssRules||[]).forEach((i,l)=>{if(i.type===CSSRule.IMPORT_RULE){let o=l+1;const c=i.href,d=dHe(c).then(u=>uHe(u,t)).then(u=>hHe(u).forEach(h=>{try{a.insertRule(h,h.startsWith("@import")?o+=1:a.cssRules.length)}catch(p){console.error("Error inserting rule from remote css",{rule:h,error:p})}})).catch(u=>{console.error("Error loading remote css",u.toString())});r.push(d)}})}catch(i){const l=s.find(o=>o.href==null)||document.styleSheets[0];a.href!=null&&r.push(dHe(a.href).then(o=>uHe(o,t)).then(o=>hHe(o).forEach(c=>{l.insertRule(c,l.cssRules.length)})).catch(o=>{console.error("Error loading remote stylesheet",o)})),console.error("Error inlining remote css file",i)}}),Promise.all(r).then(()=>(s.forEach(a=>{if("cssRules"in a)try{m4(a.cssRules||[]).forEach(i=>{n.push(i)})}catch(i){console.error(`Error while reading CSS rules from ${a.href}`,i)}}),n))}function n1s(s){return s.filter(t=>t.type===CSSRule.FONT_FACE_RULE).filter(t=>r0t(t.style.getPropertyValue("src")))}async function r1s(s,t){if(s.ownerDocument==null)throw new Error("Provided element is not within a Document");const n=m4(s.ownerDocument.styleSheets),r=await s1s(n,t);return n1s(r)}function o0t(s){return s.trim().replace(/["']/g,"")}function a1s(s){const t=new Set;function n(r){(r.style.fontFamily||getComputedStyle(r).fontFamily).split(",").forEach(i=>{t.add(o0t(i))}),Array.from(r.children).forEach(i=>{i instanceof HTMLElement&&n(i)})}return n(s),t}async function i1s(s,t){const n=await r1s(s,t),r=a1s(s);return(await Promise.all(n.filter(i=>r.has(o0t(i.style.fontFamily))).map(i=>{const l=i.parentStyleSheet?i.parentStyleSheet.href:null;return a0t(i.cssText,l,t)}))).join(` `)}async function o1s(s,t){const n=t.fontEmbedCSS!=null?t.fontEmbedCSS:t.skipFonts?null:await i1s(s,t);if(n){const r=document.createElement("style"),a=document.createTextNode(n);r.appendChild(a),s.firstChild?s.insertBefore(r,s.firstChild):s.appendChild(r)}}async function l1s(s,t={}){const{width:n,height:r}=e0t(s,t),a=await sve(s,t,!0);return await o1s(a,t),await i0t(a,t),t1s(a,t),await kvs(a,n,r)}async function c1s(s,t={}){const{width:n,height:r}=e0t(s,t),a=await l1s(s,t),i=await mxe(a),l=document.createElement("canvas"),o=l.getContext("2d"),c=t.pixelRatio||wvs(),d=t.canvasWidth||n,u=t.canvasHeight||r;return l.width=d*c,l.height=u*c,t.skipAutoScale||jvs(l),l.style.width=`${d}`,l.style.height=`${u}`,t.backgroundColor&&(o.fillStyle=t.backgroundColor,o.fillRect(0,0,l.width,l.height)),o.drawImage(i,0,0,l.width,l.height),l}async function vIe(s,t={}){return(await c1s(s,t)).toDataURL()}const E8=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),nve={"just-listed":"JUST LISTED","just-sold":"JUST SOLD","open-house":"OPEN HOUSE","price-drop":"PRICE DROP"},ES={"instagram-square":{width:1080,height:1080},"instagram-story":{width:1080,height:1920},"facebook-post":{width:1200,height:630}},d1s=({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})]})]}),bIe=Ct.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=nve[t],u=[s.bedrooms?`${s.bedrooms} Bed`:null,s.bathrooms?`${s.bathrooms} Bath`:null,s.sqft?`${s.sqft.toLocaleString()} Sq Ft`:null].filter(Boolean).join(" • ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"linear-gradient(180deg, rgba(10,10,30,0.3) 0%, rgba(10,10,30,0.85) 100%)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",justifyContent:"space-between",padding:l.w*.06},children:[e.jsx("div",{children:e.jsx("div",{style:{display:"inline-block",background:"linear-gradient(135deg, #C9A84C, #E8D48B)",color:"#1A1A2E",padding:`${l.w*.012}px ${l.w*.035}px`,fontSize:l.w*.032,fontWeight:700,letterSpacing:"0.25em",textTransform:"uppercase"},children:d})}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:l.w*.07,fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,textShadow:"0 2px 12px rgba(0,0,0,0.5)"},children:E8(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.028,color:"#C9A84C",marginBottom:l.w*.01},children:["Sold for ",E8(s.soldPrice)]}),e.jsx("div",{style:{fontSize:l.w*.028,opacity:.9,marginBottom:l.w*.008},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.7,marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"flex",gap:l.w*.015,fontSize:l.w*.022,letterSpacing:"0.05em",borderTop:"1px solid rgba(201,168,76,0.4)",paddingTop:l.w*.02},children:e.jsx("span",{children:u})}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.02,background:"rgba(201,168,76,0.15)",border:"1px solid rgba(201,168,76,0.4)",padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.024,letterSpacing:"0.1em",display:"inline-block"},children:"SAT & SUN • 1–4 PM"}),e.jsx(d1s,{branding:r,dim:l})]})]})]})});bIe.displayName="LuxuryDarkTemplate";const u1s=({branding:s,dim:t,accentColor:n})=>!(s!=null&&s.enabled)||!s.agentName?null:e.jsxs("div",{style:{borderTop:"2px solid #E5E7EB",paddingTop:t.w*.025,display:"flex",alignItems:"center",justifyContent:"center",gap:t.w*.025},children:[s.agentPhotoUrl&&e.jsx("img",{src:s.agentPhotoUrl,alt:"",crossOrigin:"anonymous",style:{width:t.w*.14,height:t.w*.14,borderRadius:"50%",objectFit:"cover",border:`3px solid ${n}`,flexShrink:0}}),e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:t.w*.042,fontWeight:800,color:"#1A1A1A"},children:s.agentName}),s.brokerage&&e.jsx("div",{style:{fontSize:t.w*.028,color:"#6B7280",marginTop:t.w*.005},children:s.brokerage})]})]}),_Ie=Ct.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var f;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(f=s.photos)==null?void 0:f[a],d=nve[t],u=n==="instagram-story",h=n==="facebook-post",p=t==="just-sold"?"#7C3AED":t==="open-house"?"#2563EB":t==="price-drop"?"#DC2626":"#059669";return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Helvetica Neue', Arial, sans-serif",color:"#1A1A1A",background:"#FFFFFF",display:"flex",flexDirection:h?"row":"column"},children:[e.jsxs("div",{style:{width:h?"55%":"100%",height:h?"100%":u?"50%":"52%",position:"relative",overflow:"hidden",flexShrink:0},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",top:l.w*.04,left:0,background:p,color:"#FFFFFF",padding:`${l.w*.012}px ${l.w*.04}px`,fontSize:l.w*.026,fontWeight:800,letterSpacing:"0.15em"},children:d})]}),e.jsxs("div",{style:{flex:1,display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05},children:[e.jsx("div",{style:{fontSize:l.w*(h?.055:.065),fontWeight:800,lineHeight:1.1,color:p,marginBottom:l.w*.012},children:E8(s.price)}),e.jsx("div",{style:{fontSize:l.w*.026,fontWeight:600,marginBottom:l.w*.006},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.02,color:"#6B7280",marginBottom:l.w*.02},children:[s.city,", ",s.state," ",s.zip]}),e.jsxs("div",{style:{display:"flex",gap:l.w*.03,marginBottom:l.w*.02},children:[s.bedrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bedrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Beds"})]}),s.bathrooms>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.bathrooms}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Baths"})]}),s.sqft>0&&e.jsxs("div",{style:{textAlign:"center"},children:[e.jsx("div",{style:{fontSize:l.w*.035,fontWeight:700},children:s.sqft.toLocaleString()}),e.jsx("div",{style:{fontSize:l.w*.016,color:"#9CA3AF",textTransform:"uppercase",letterSpacing:"0.1em"},children:"Sq Ft"})]})]}),t==="open-house"&&e.jsx("div",{style:{background:`${p}10`,border:`2px solid ${p}`,borderRadius:l.w*.01,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,color:p,display:"inline-block",marginBottom:l.w*.015},children:"SAT & SUN • 1–4 PM"}),e.jsx(u1s,{branding:r,dim:l,accentColor:p})]})]})});_Ie.displayName="ModernCleanTemplate";const h1s=({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})]})]}),wIe=Ct.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var p;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(p=s.photos)==null?void 0:p[a],d=nve[t],u={"just-listed":"linear-gradient(135deg, #059669, #10B981)","just-sold":"linear-gradient(135deg, #7C3AED, #A855F7)","open-house":"linear-gradient(135deg, #2563EB, #3B82F6)","price-drop":"linear-gradient(135deg, #DC2626, #F43F5E)"},h=[s.bedrooms?`${s.bedrooms} BD`:null,s.bathrooms?`${s.bathrooms} BA`:null,s.sqft?`${s.sqft.toLocaleString()} SF`:null].filter(Boolean).join(" | ");return e.jsxs("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Arial Black', 'Helvetica Neue', sans-serif",color:"#FFFFFF"},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{position:"absolute",inset:0,width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:0,background:"rgba(0,0,0,0.4)"}}),e.jsxs("div",{style:{position:"relative",height:"100%",display:"flex",flexDirection:"column",padding:l.w*.05},children:[e.jsx("div",{style:{background:u[t],padding:`${l.w*.025}px ${l.w*.04}px`,fontSize:l.w*.055,fontWeight:900,letterSpacing:"0.08em",alignSelf:"flex-start",borderRadius:l.w*.01,boxShadow:"0 8px 32px rgba(0,0,0,0.3)",transform:"rotate(-2deg)",marginBottom:l.w*.03},children:d}),e.jsx("div",{style:{flex:1}}),e.jsxs("div",{style:{background:"rgba(0,0,0,0.65)",backdropFilter:"blur(10px)",borderRadius:l.w*.015,padding:l.w*.04},children:[e.jsx("div",{style:{fontSize:l.w*.08,fontWeight:900,lineHeight:1,marginBottom:l.w*.01},children:E8(s.price)}),e.jsx("div",{style:{fontSize:l.w*.028,fontWeight:700,marginBottom:l.w*.005},children:s.address}),e.jsxs("div",{style:{fontSize:l.w*.022,opacity:.8,marginBottom:l.w*.015},children:[s.city,", ",s.state," ",s.zip]}),e.jsx("div",{style:{display:"inline-block",background:"rgba(255,255,255,0.15)",borderRadius:l.w*.008,padding:`${l.w*.01}px ${l.w*.02}px`,fontSize:l.w*.022,fontWeight:700,letterSpacing:"0.08em"},children:h}),t==="open-house"&&e.jsx("div",{style:{marginTop:l.w*.015,background:u["open-house"],borderRadius:l.w*.008,padding:`${l.w*.012}px ${l.w*.025}px`,fontSize:l.w*.024,fontWeight:800,display:"inline-block",marginLeft:l.w*.01},children:"SAT & SUN 1–4 PM"}),e.jsx(h1s,{branding:r,dim:l})]})]})]})});wIe.displayName="BoldColorfulTemplate";const m1s=({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})]})]}),jIe=Ct.forwardRef(({listing:s,postType:t,format:n,branding:r,selectedPhotoIndex:a},i)=>{var h;const l=n==="instagram-story"?{w:1080,h:1920}:n==="facebook-post"?{w:1200,h:630}:{w:1080,h:1080},o=400/l.w,c=(h=s.photos)==null?void 0:h[a],d=nve[t],u=n==="instagram-story";return e.jsx("div",{ref:i,style:{width:l.w,height:l.h,transform:`scale(${o})`,transformOrigin:"top left",position:"relative",overflow:"hidden",fontFamily:"'Georgia', 'Times New Roman', serif",color:"#1A1A1A",background:"#F5F0EB"},children:e.jsxs("div",{style:{display:"flex",flexDirection:u?"column":"row",height:"100%"},children:[e.jsxs("div",{style:{width:u?"100%":"42%",height:u?"40%":"100%",display:"flex",flexDirection:"column",justifyContent:"center",padding:l.w*.05,order:u?2:1},children:[e.jsx("div",{style:{fontSize:l.w*.016,letterSpacing:"0.3em",textTransform:"uppercase",color:"#8B7355",borderBottom:"2px solid #8B7355",paddingBottom:l.w*.01,marginBottom:l.w*.025,display:"inline-block",alignSelf:"flex-start"},children:d}),e.jsx("div",{style:{fontSize:l.w*(u?.06:.055),fontWeight:700,lineHeight:1.1,marginBottom:l.w*.015,fontStyle:"italic"},children:E8(s.price)}),t==="just-sold"&&s.soldPrice&&e.jsxs("div",{style:{fontSize:l.w*.02,color:"#8B7355",marginBottom:l.w*.01},children:["Sold: ",E8(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(m1s,{branding:r,dim:l})]}),e.jsxs("div",{style:{width:u?"100%":"58%",height:u?"60%":"100%",position:"relative",overflow:"hidden",order:u?1:2},children:[c&&e.jsx("img",{src:c,alt:"",crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover"}}),e.jsx("div",{style:{position:"absolute",inset:l.w*.02,border:"1px solid rgba(255,255,255,0.4)",pointerEvents:"none"}})]})]})})});jIe.displayName="EditorialTemplate";const p1s=[{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:"📉"}],mHe=[{value:"instagram-square",label:"IG Post",dimensions:"1080×1080",icon:e.jsx(ou,{className:"h-4 w-4"})},{value:"instagram-story",label:"IG Story",dimensions:"1080×1920",icon:e.jsx(ou,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook",dimensions:"1200×630",icon:e.jsx(Mh,{className:"h-4 w-4"})}],f1s=[{value:"luxury-dark",label:"Luxury Dark",description:"Black & gold, high-end",preview:"🌙"},{value:"modern-clean",label:"Modern Clean",description:"White, bold, contemporary",preview:"✨"},{value:"bold-colorful",label:"Bold & Vibrant",description:"Energetic gradients",preview:"🔥"},{value:"editorial",label:"Editorial",description:"Magazine-style",preview:"📰"}],pHe={"luxury-dark":bIe,"modern-clean":_Ie,"bold-colorful":wIe,editorial:jIe},g2e=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s);function x1s(s){var l;const[t,n]=s.split(","),r=((l=t.match(/:(.*?);/))==null?void 0:l[1])||"image/png",a=atob(n),i=new Uint8Array(a.length);for(let o=0;oPe.is_default))??(s==null?void 0:s[0])??null,[n,r]=N.useState(void 0),a=(s==null?void 0:s.find(Pe=>Pe.id===n))??t,i=wa(),[l,o]=N.useState("mine"),[c,d]=N.useState(""),[u,h]=N.useState("address"),[p,f]=N.useState(!1),[y,_]=N.useState([]),[v,j]=N.useState(null),[w,S]=N.useState(0),[A,E]=N.useState("just-listed"),[O,D]=N.useState(["instagram-square"]),[I,F]=N.useState("luxury-dark"),[z,H]=N.useState(!0),[Z,Y]=N.useState(!1),[W,ee]=N.useState([]),[se,oe]=N.useState("search"),he=N.useRef({}),{data:ce=[],isLoading:me}=dt({queryKey:["marketing-studio-my-listings",i],enabled:!!i,queryFn:async()=>{const{data:Pe,error:Re}=await q.from("listings").select("id, property_address, city, state, price, status, bedrooms, bathrooms, square_footage, year_built, property_type, description, created_at, listing_photos(photo_url, sort_order, is_primary)").eq("agent_id",i).order("created_at",{ascending:!1}).limit(60);if(Re)throw Re;return(Pe||[]).map(Ae=>{const Be=(Ae.listing_photos||[]).slice().sort((Je,ke)=>(ke.is_primary?1:0)-(Je.is_primary?1:0)||(Je.sort_order??0)-(ke.sort_order??0)).map(Je=>Je.photo_url).filter(Boolean),we=String(Ae.status||"");return{mlsNumber:Ae.id,address:Ae.property_address||"",city:Ae.city||"",state:Ae.state||"",zip:"",price:Number(Ae.price||0),status:we,bedrooms:Number(Ae.bedrooms||0),bathrooms:Number(Ae.bathrooms||0),sqft:Number(Ae.square_footage||0),lotSize:"",yearBuilt:Ae.year_built??null,propertyType:Ae.property_type||"",description:Ae.description||"",photos:Be,listDate:Ae.created_at,soldDate:we.toLowerCase().includes("sold")?Ae.created_at:null,soldPrice:null,agent:{name:"",office:""}}})}}),le=N.useMemo(()=>!z||!a?{enabled:!1}:{enabled:!0,agentName:a.display_name||"",brokerage:a.tagline||"",agentPhotoUrl:a.headshot_url||void 0},[z,a]),ve=async()=>{if(c.trim()){f(!0),_([]);try{const{data:Pe,error:Re}=await q.functions.invoke("repliers-mls-search",{body:{searchType:u,query:c.trim()}});if(Re)throw Re;if(Pe!=null&&Pe.error)throw new Error(Pe.error);_((Pe==null?void 0:Pe.listings)||[]),((Pe==null?void 0:Pe.listings)||[]).length===0&&ae.info("No listings found. Try a different search.")}catch(Pe){ae.error(Pe.message||"Search failed")}finally{f(!1)}}},ge=Pe=>{var Re;j(Pe),S(0),oe("customize"),Pe.soldDate||(Re=Pe.status)!=null&&Re.toLowerCase().includes("sold")?E("just-sold"):E("just-listed")},Te=Pe=>D(Re=>Re.includes(Pe)?Re.filter(Ae=>Ae!==Pe):[...Re,Pe]),Ie=v?{listing:v,postType:A,format:"instagram-square",branding:le,selectedPhotoIndex:w}:null,Ce=N.useCallback(async()=>{if(!(!v||O.length===0)){Y(!0),ee([]),oe("generate");try{await new Promise(Re=>setTimeout(Re,600));const Pe=[];for(const Re of O){const Ae=`${I}-${Re}`,Be=he.current[Ae];if(!Be)continue;const we=ES[Re],Je=await vIe(Be,{width:we.width,height:we.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Pe.push({format:Re,url:Je})}ee(Pe),ae.success(`Generated ${Pe.length} design${Pe.length>1?"s":""}!`)}catch(Pe){ae.error(Pe.message||"Generation failed")}finally{Y(!1)}}},[v,O,I]),Me=(Pe,Re)=>{const Ae=`${((v==null?void 0:v.address)||"listing").replace(/\s+/g,"-")}-${A}-${Re}.png`;try{const Be=x1s(Pe),we=URL.createObjectURL(Be);if(g1s)window.open(we,"_blank"),ae.message("Long-press the image to save to Photos");else{const Je=document.createElement("a");Je.href=we,Je.download=Ae,document.body.appendChild(Je),Je.click(),document.body.removeChild(Je)}setTimeout(()=>URL.revokeObjectURL(we),6e4)}catch{const Be=document.createElement("a");Be.href=Pe,Be.download=Ae,Be.click()}};return N.useEffect(()=>{!n&&t&&r(t.id)},[t,n]),e.jsx(Cs,{title:"Listing Templates",children:e.jsxs("div",{className:"container max-w-6xl py-4 md:py-8 px-3 md:px-6 space-y-5",children:[e.jsxs(Zo,{children:[e.jsx("title",{children:"Listing Templates | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Just Listed, Just Sold, Open House and Price Drop templates pulled directly from your MLS."})]}),e.jsx("div",{className:"flex items-center gap-2",children:e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs(In,{to:"/marketing-studio",children:[e.jsx(qr,{className:"h-4 w-4 mr-1"})," Marketing Studio"]})})}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Ue,{variant:"secondary",className:"mb-2 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," Listing Templates"]}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight",children:"Just Listed. Just Stunning."}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl mt-1",children:"Search any MLS listing and get pixel-perfect, on-brand graphics for Instagram, Stories and Facebook in one click."})]}),s&&s.length>0&&e.jsxs("div",{className:"min-w-0 sm:min-w-[220px]",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Brand preset"}),e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Default"})}),e.jsx(cs,{children:s.map(Pe=>e.jsxs(Ze,{value:Pe.id,children:[Pe.name,Pe.is_default?" (default)":""]},Pe.id))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs sm:text-sm overflow-x-auto -mx-1 px-1 pb-1",children:[e.jsxs("button",{onClick:()=>oe("search"),className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${se==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:[e.jsx(gr,{className:"h-3.5 w-3.5"})," 1. Find listing"]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("button",{onClick:()=>v&&oe("customize"),disabled:!v,className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${se==="customize"?"bg-primary text-primary-foreground":v?"bg-muted text-muted-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(un,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:`flex items-center gap-1.5 px-3 py-1.5 rounded-full whitespace-nowrap ${se==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," 3. Download"]})]}),se==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fr,{value:l,onValueChange:Pe=>o(Pe),children:e.jsxs(Rr,{className:"grid grid-cols-2 w-full sm:w-auto",children:[e.jsxs(Zt,{value:"mine",children:[e.jsx(Or,{className:"h-4 w-4 mr-1.5"})," My Listings"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(gr,{className:"h-4 w-4 mr-1.5"})," MLS Search"]})]})}),l==="mine"&&e.jsx("div",{className:"space-y-3",children:me?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 flex items-center justify-center",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):ce.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-10 text-center space-y-2",children:[e.jsx(Or,{className:"h-10 w-10 mx-auto text-muted-foreground/40"}),e.jsx("p",{className:"text-sm font-medium",children:"No listings yet"}),e.jsx("p",{className:"text-xs text-muted-foreground max-w-sm mx-auto",children:"Add a listing to your Listing Exchange first, and it'll show up here ready to brand."}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"mt-2",children:e.jsx(In,{to:"/mission-control/listings",children:"Go to Listings"})})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[ce.length," listing",ce.length!==1?"s":""," from your Listing Exchange"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:ce.map((Pe,Re)=>{var Ae;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ge(Pe),children:e.jsx(Ee,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Ae=Pe.photos)!=null&&Ae[0]?e.jsx("img",{src:Pe.photos[0],alt:Pe.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Or,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:Pe.price>0?g2e(Pe.price):"—"}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Pe.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Pe.city,Pe.state?`, ${Pe.state}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Pe.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(U2,{className:"h-3 w-3"})," ",Pe.bedrooms]}),Pe.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(kp,{className:"h-3 w-3"})," ",Pe.bathrooms]}),Pe.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(AA,{className:"h-3 w-3"})," ",Pe.sqft.toLocaleString()]})]}),Pe.status&&e.jsx("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:Pe.status})})]})]})})},Pe.mlsNumber||Re)})})]})}),l==="mls"&&e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2 text-base md:text-lg",children:[e.jsx(gr,{className:"h-5 w-5 text-primary"})," Search MLS"]}),e.jsxs(Vn,{children:["Search by address or MLS number. Requires an MLS data connection — if your account doesn't have one, use ",e.jsx("button",{type:"button",className:"underline",onClick:()=>o("mine"),children:"My Listings"})," instead."]})]}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsx(Fr,{value:u,onValueChange:Pe=>h(Pe),children:e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"address",children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(oh,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(ye,{value:c,onChange:Pe=>d(Pe.target.value),placeholder:u==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Pe=>Pe.key==="Enter"&&ve()}),e.jsxs(B,{onClick:ve,disabled:p||!c.trim(),className:"sm:w-auto w-full",children:[p?e.jsx(rs,{className:"h-4 w-4 animate-spin mr-1.5"}):e.jsx(gr,{className:"h-4 w-4 mr-1.5"})," Search"]})]})]})]}),y.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[y.length," listing",y.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:y.map((Pe,Re)=>{var Ae;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group overflow-hidden",onClick:()=>ge(Pe),children:e.jsx(Ee,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-28 h-28 sm:w-32 sm:h-28 flex-shrink-0 bg-muted overflow-hidden",children:(Ae=Pe.photos)!=null&&Ae[0]?e.jsx("img",{src:Pe.photos[0],alt:Pe.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Or,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold",children:g2e(Pe.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Pe.address}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[Pe.city,", ",Pe.state," ",Pe.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Pe.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(U2,{className:"h-3 w-3"})," ",Pe.bedrooms]}),Pe.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(kp,{className:"h-3 w-3"})," ",Pe.bathrooms]}),Pe.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(AA,{className:"h-3 w-3"})," ",Pe.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[Pe.mlsNumber&&e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:Pe.mlsNumber}),Pe.status&&e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:Pe.status})]})]})]})})},Pe.mlsNumber||Re)})})]})]})]}),se==="customize"&&v&&Ie&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-4 md:gap-6",children:[e.jsxs(fe,{className:"lg:col-span-1 overflow-hidden min-w-0",children:[e.jsx(It,{className:"pb-3",children:e.jsx(Rt,{className:"text-base",children:"Selected listing"})}),e.jsxs(Ee,{className:"space-y-3",children:[v.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:v.photos[w],alt:"",className:"w-full h-full object-cover"})}),v.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>S(Pe=>Math.max(0,Pe-1)),disabled:w===0,children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[w+1," of ",v.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>S(Pe=>Math.min(v.photos.length-1,Pe+1)),disabled:w===v.photos.length-1,children:e.jsx(ga,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:g2e(v.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:v.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.city,", ",v.state," ",v.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[v.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),v.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),v.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:v.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{oe("search"),j(null)},children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Choose different listing"]})]})]}),e.jsxs(fe,{className:"lg:col-span-2 overflow-hidden min-w-0",children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2 text-base",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize"]}),e.jsx(Vn,{children:"Pick a template, post type, and output format."})]}),e.jsxs(Ee,{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4"})," Template style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:f1s.map(Pe=>e.jsxs("button",{onClick:()=>F(Pe.value),className:`flex flex-col items-center gap-1 px-2 py-3 rounded-lg border-2 transition-all text-center ${I===Pe.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Pe.preview}),e.jsx("span",{className:"text-sm font-medium",children:Pe.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Pe.description})]},Pe.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Post type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:p1s.map(Pe=>e.jsxs("button",{onClick:()=>E(Pe.value),className:`flex items-center justify-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${A===Pe.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Pe.icon})," ",e.jsx("span",{className:"truncate",children:Pe.label})]},Pe.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Output formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:mHe.map(Pe=>e.jsxs("button",{onClick:()=>Te(Pe.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${O.includes(Pe.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Pe.icon,e.jsxs("div",{className:"text-left min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Pe.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Pe.dimensions})]})]},Pe.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ne,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Wi,{className:"h-4 w-4"})," Show my branding"]}),e.jsx(jn,{checked:z,onCheckedChange:H})]}),z&&!a&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["No brand preset yet. ",e.jsx(In,{to:"/marketing-studio/brand-kit",className:"underline",children:"Create one"})," to add your headshot and name."]}),z&&a&&e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-muted/30",children:[a.headshot_url&&e.jsx("img",{src:a.headshot_url,alt:"",className:"w-10 h-10 rounded-full object-cover border"}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:a.display_name||"Unnamed agent"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.tagline||a.email||""})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Preview"}),e.jsx("div",{className:"bg-muted/30 rounded-lg p-3 md:p-4 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:360,maxWidth:"100%",height:360*(ES[O[0]||"instagram-square"].height/ES[O[0]||"instagram-square"].width)},children:(()=>{const Pe=pHe[I],Re=O[0]||"instagram-square";return e.jsx(Pe,{...Ie,format:Re})})()})})]}),e.jsx(B,{onClick:Ce,disabled:O.length===0||Z,size:"lg",className:"w-full gap-2",children:Z?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-5 w-5 animate-spin"})," Generating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-5 w-5"})," Generate ",O.length," design",O.length>1?"s":""]})})]})]})]}),se==="generate"&&e.jsxs("div",{className:"space-y-4",children:[Z&&e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(rs,{className:"h-12 w-12 animate-spin text-primary mb-3"}),e.jsx("p",{className:"text-base font-medium",children:"Rendering your designs..."}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"High-resolution PNGs, no AI credits used."})]})}),W.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Your designs"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>oe("customize"),children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Tweak & regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:W.map((Pe,Re)=>{const Ae=mHe.find(Be=>Be.value===Pe.format);return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Pe.url,alt:"",className:"w-full rounded"})}),e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Ae==null?void 0:Ae.icon,e.jsx("span",{className:"text-sm font-medium",children:Ae==null?void 0:Ae.label})]}),e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:Ae==null?void 0:Ae.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>Me(Pe.url,Pe.format),children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Download"]})]})]},Re)})})]})]}),se==="generate"&&v&&Ie&&e.jsx("div",{style:{position:"fixed",left:"-99999px",top:0,pointerEvents:"none"},"aria-hidden":!0,children:O.map(Pe=>{const Re=pHe[I],Ae=ES[Pe];return e.jsx("div",{style:{width:Ae.width,height:Ae.height},children:e.jsx(Re,{ref:Be=>{he.current[`${I}-${Pe}`]=Be},...Ie,format:Pe})},`${I}-${Pe}`)})})]})})}var l0t="Toggle",NIe=N.forwardRef((s,t)=>{const{pressed:n,defaultPressed:r,onPressedChange:a,...i}=s,[l,o]=cm({prop:n,onChange:a,defaultProp:r??!1,caller:l0t});return e.jsx(Yr.button,{type:"button","aria-pressed":l,"data-state":l?"on":"off","data-disabled":s.disabled?"":void 0,...i,ref:t,onClick:xr(s.onClick,()=>{s.disabled||o(!l)})})});NIe.displayName=l0t;var c0t=NIe,tC="ToggleGroup",[d0t,Afn]=uu(tC,[z4]),u0t=z4(),kIe=Ct.forwardRef((s,t)=>{const{type:n,...r}=s;if(n==="single"){const a=r;return e.jsx(v1s,{...a,ref:t})}if(n==="multiple"){const a=r;return e.jsx(b1s,{...a,ref:t})}throw new Error(`Missing prop \`type\` expected on \`${tC}\``)});kIe.displayName=tC;var[h0t,m0t]=d0t(tC),v1s=Ct.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=cm({prop:n,defaultProp:r??"",onChange:a,caller:tC});return e.jsx(h0t,{scope:s.__scopeToggleGroup,type:"single",value:Ct.useMemo(()=>l?[l]:[],[l]),onItemActivate:o,onItemDeactivate:Ct.useCallback(()=>o(""),[o]),children:e.jsx(p0t,{...i,ref:t})})}),b1s=Ct.forwardRef((s,t)=>{const{value:n,defaultValue:r,onValueChange:a=()=>{},...i}=s,[l,o]=cm({prop:n,defaultProp:r??[],onChange:a,caller:tC}),c=Ct.useCallback(u=>o((h=[])=>[...h,u]),[o]),d=Ct.useCallback(u=>o((h=[])=>h.filter(p=>p!==u)),[o]);return e.jsx(h0t,{scope:s.__scopeToggleGroup,type:"multiple",value:l,onItemActivate:c,onItemDeactivate:d,children:e.jsx(p0t,{...i,ref:t})})});kIe.displayName=tC;var[_1s,w1s]=d0t(tC),p0t=Ct.forwardRef((s,t)=>{const{__scopeToggleGroup:n,disabled:r=!1,rovingFocus:a=!0,orientation:i,dir:l,loop:o=!0,...c}=s,d=u0t(n),u=vN(l),h={role:"group",dir:u,...c};return e.jsx(_1s,{scope:n,rovingFocus:a,disabled:r,children:a?e.jsx(I0e,{asChild:!0,...d,orientation:i,dir:u,loop:o,children:e.jsx(Yr.div,{...h,ref:t})}):e.jsx(Yr.div,{...h,ref:t})})}),pxe="ToggleGroupItem",f0t=Ct.forwardRef((s,t)=>{const n=m0t(pxe,s.__scopeToggleGroup),r=w1s(pxe,s.__scopeToggleGroup),a=u0t(s.__scopeToggleGroup),i=n.value.includes(s.value),l=r.disabled||s.disabled,o={...s,pressed:i,disabled:l},c=Ct.useRef(null);return r.rovingFocus?e.jsx(P0e,{asChild:!0,...a,focusable:!l,active:i,ref:c,children:e.jsx(fHe,{...o,ref:t})}):e.jsx(fHe,{...o,ref:t})});f0t.displayName=pxe;var fHe=Ct.forwardRef((s,t)=>{const{__scopeToggleGroup:n,value:r,...a}=s,i=m0t(pxe,n),l={role:"radio","aria-checked":s.pressed,"aria-pressed":void 0},o=i.type==="single"?l:void 0;return e.jsx(NIe,{...o,...a,ref:t,onPressedChange:c=>{c?i.onItemActivate(r):i.onItemDeactivate(r)}})}),x0t=kIe,g0t=f0t;const y0t=OM("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"}}),j1s=N.forwardRef(({className:s,variant:t,size:n,...r},a)=>e.jsx(c0t,{ref:a,className:Mt(y0t({variant:t,size:n,className:s})),...r}));j1s.displayName=c0t.displayName;const v0t=N.createContext({size:"default",variant:"default"}),IL=N.forwardRef(({className:s,variant:t,size:n,children:r,...a},i)=>e.jsx(x0t,{ref:i,className:Mt("flex items-center justify-center gap-1",s),...a,children:e.jsx(v0t.Provider,{value:{variant:t,size:n},children:r})}));IL.displayName=x0t.displayName;const HA=N.forwardRef(({className:s,children:t,variant:n,size:r,...a},i)=>{const l=N.useContext(v0t);return e.jsx(g0t,{ref:i,className:Mt(y0t({variant:l.variant||n,size:l.size||r}),s),...a,children:t})});HA.displayName=g0t.displayName;const N1s=[{id:"meet",label:"Meet Your Agent",icon:Wi,description:"Polished intro card with your headshot, story, and contact."},{id:"testimonial",label:"Testimonial",icon:gw,description:"Turn a Zillow / Google review into a branded graphic."},{id:"milestone",label:"Milestone",icon:xo,description:"Celebrate homes sold, awards, anniversaries, achievements."},{id:"tip",label:"Pro Tip",icon:W2,description:"Drop a value-bomb tip — buyer/seller advice, market insight."},{id:"quote",label:"Quote / Mantra",icon:zd,description:"Personal philosophy, mantra, or rallying call."}],y2e={square:{w:1080,h:1080,label:"1:1 Feed"},portrait:{w:1080,h:1350,label:"4:5 Portrait"},story:{w:1080,h:1920,label:"9:16 Story"}},k1s=[{id:"editorial",label:"Editorial",description:"Magazine-style with serif accents."},{id:"bold",label:"Bold",description:"Big type, high contrast, gradient."},{id:"minimal",label:"Minimal",description:"Clean white space, hairline rules."},{id:"luxury",label:"Luxury",description:"Dark, gold accents, refined."}],xHe={meet:{headline:"Meet your agent",subline:"Helping families find home, one keys-in-hand moment at a time.",body:"15 years of negotiating wins, 200+ families moved, and a love for this city that runs deep.",attribution:"",badgeText:"REALTOR®"},testimonial:{headline:"What our clients say",subline:"",body:"She made the entire process feel effortless. From first showing to closing day, every detail was handled with care and expertise. We could not have asked for a better experience.",attribution:"The Bennett Family",rating:5,badgeText:"CLIENT REVIEW"},milestone:{headline:"100 homes sold",subline:"and counting…",body:"Thank you to every client, partner, and friend who trusted me with the biggest move of their life. Here is to the next 100.",attribution:"",badgeText:"MILESTONE"},tip:{headline:`Stop guessing. Start pricing.`,subline:"Pro tip · #03",body:"Homes priced within 3% of market value sell 2.4× faster than those priced higher. Pricing strategy is leverage — not a guess.",attribution:"",badgeText:"PRO TIP"},quote:{headline:`"Real estate is not about houses. It is about people."`,subline:"",body:"",attribution:"",badgeText:"PHILOSOPHY"}};function S1s(){const{data:s}=Lxs(),{data:t}=pU(),[n,r]=N.useState(void 0),a=N.useMemo(()=>(t==null?void 0:t.find(y=>y.id===n))??s??null,[t,n,s]),[i,l]=N.useState({template:"meet",style:"editorial",aspect:"portrait",rating:5,...xHe.meet}),o=y=>l(_=>({..._,...y})),c=y=>l(_=>({..._,template:y,...xHe[y]})),d=N.useRef(null),[u,h]=N.useState(!1),p=async()=>{if(!d.current)return;h(!0);const y=d.current,_=y.style.transform;try{y.style.transform="none",await new Promise(w=>requestAnimationFrame(()=>w(null)));const v=await vIe(y,{cacheBust:!0,pixelRatio:2,width:y.offsetWidth,height:y.offsetHeight,backgroundColor:"#ffffff"}),j=document.createElement("a");j.href=v,j.download=`personal-branding-${i.template}-${Date.now()}.png`,document.body.appendChild(j),j.click(),j.remove(),ae.success("Downloaded to your device")}catch(v){ae.error((v==null?void 0:v.message)||"Export failed")}finally{y.style.transform=_,h(!1)}},f=y2e[i.aspect];return e.jsx(Cs,{title:"Personal Branding",children:e.jsxs("div",{className:"container max-w-7xl py-6 md:py-8 space-y-6 px-4",children:[e.jsxs(Zo,{children:[e.jsx("title",{children:"Personal Branding | Marketing Studio"}),e.jsx("meta",{name:"description",content:"Editorial-grade personal branding graphics — meet your agent, testimonials, milestones, and pro tips."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-end sm:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(In,{to:"/marketing-studio",className:"text-sm text-muted-foreground inline-flex items-center gap-1 hover:underline",children:[e.jsx(qr,{className:"h-3 w-3"})," Back to Marketing Studio"]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," New"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold tracking-tight mt-1",children:"Personal Branding"}),e.jsx("p",{className:"text-sm md:text-base text-muted-foreground max-w-2xl",children:"Five editorial-grade templates, four distinct aesthetics. Pick one, drop in your story, export in seconds."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs(In,{to:"/marketing-studio/brand-kit",children:[e.jsx(pl,{className:"h-4 w-4 mr-1"})," Brand Kit"]})}),e.jsxs(B,{onClick:p,disabled:u,children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," ",u?"Exporting…":"Download"]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[380px_1fr] gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Template"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:N1s.map(y=>{const _=y.icon,v=i.template===y.id;return e.jsxs("button",{onClick:()=>c(y.id),className:`text-left rounded-lg border p-3 transition-all ${v?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[e.jsx(_,{className:"h-4 w-4 mb-1"}),e.jsx("div",{className:"text-xs font-semibold",children:y.label})]},y.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Style"}),e.jsx(IL,{type:"single",value:i.style,onValueChange:y=>y&&o({style:y}),className:"grid grid-cols-2 gap-1",children:k1s.map(y=>e.jsx(HA,{value:y.id,className:"text-xs h-9",children:y.label},y.id))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Format"}),e.jsx(IL,{type:"single",value:i.aspect,onValueChange:y=>y&&o({aspect:y}),className:"grid grid-cols-3 gap-1",children:Object.keys(y2e).map(y=>e.jsx(HA,{value:y,className:"text-xs h-9",children:y2e[y].label},y))})]}),t&&t.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Brand preset"}),e.jsxs(us,{value:n??(s==null?void 0:s.id)??"",onValueChange:r,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Choose preset"})}),e.jsx(cs,{children:t.map(y=>e.jsx(Ze,{value:y.id,children:y.name},y.id))})]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 space-y-3",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wider text-muted-foreground",children:"Content"}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"headline",className:"text-xs",children:"Headline"}),e.jsx(Ms,{id:"headline",value:i.headline,onChange:y=>o({headline:y.target.value}),rows:2})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"subline",className:"text-xs",children:"Subline"}),e.jsx(ye,{id:"subline",value:i.subline,onChange:y=>o({subline:y.target.value})})]}),i.template!=="quote"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"body",className:"text-xs",children:"Body"}),e.jsx(Ms,{id:"body",value:i.body,onChange:y=>o({body:y.target.value}),rows:4})]}),(i.template==="testimonial"||i.template==="quote")&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"attribution",className:"text-xs",children:"Attribution"}),e.jsx(ye,{id:"attribution",value:i.attribution,onChange:y=>o({attribution:y.target.value}),placeholder:"— Client name / Source"})]}),i.template==="testimonial"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Rating"}),e.jsx(IL,{type:"single",value:String(i.rating),onValueChange:y=>y&&o({rating:Number(y)}),className:"grid grid-cols-5 gap-1",children:[1,2,3,4,5].map(y=>e.jsxs(HA,{value:String(y),className:"text-xs h-9",children:[y,"★"]},y))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"badge",className:"text-xs",children:"Eyebrow tag"}),e.jsx(ye,{id:"badge",value:i.badgeText,onChange:y=>o({badgeText:y.target.value})})]})]})})]}),e.jsx(C1s,{aspect:f,canvasRef:d,children:e.jsx(T1s,{form:i,preset:a,width:f.w,height:f.h})})]})]})})}function C1s({aspect:s,canvasRef:t,children:n}){const r=N.useRef(null),[a,i]=N.useState(.5);return N.useEffect(()=>{const l=r.current;if(!l)return;const o=()=>{const d=l.clientWidth-32;i(Math.min(1,d/s.w))};o();const c=new ResizeObserver(o);return c.observe(l),()=>c.disconnect()},[s.w]),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{ref:r,className:"rounded-xl bg-muted/40 p-4 md:p-6 flex justify-center overflow-hidden",children:e.jsx("div",{style:{width:s.w*a,height:s.h*a,position:"relative"},className:"shadow-2xl",children:e.jsx("div",{ref:t,style:{width:s.w,height:s.h,transform:`scale(${a})`,transformOrigin:"top left",position:"absolute",top:0,left:0},children:n})})}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2 text-center",children:["Preview scaled. Export is ",s.w,"×",s.h,"px @ 2× retina."]})]})}function T1s({form:s,preset:t,width:n,height:r}){const a=(t==null?void 0:t.brand_color)||"#0F172A",i=(t==null?void 0:t.accent_color)||"#D4AF37",l=t==null?void 0:t.headshot_url,o=t==null?void 0:t.brokerage_logo_url,c=(t==null?void 0:t.display_name)||"Your Name",d=(t==null?void 0:t.phone)||"",u=(t==null?void 0:t.email)||"",h=(t==null?void 0:t.tagline)||"",p=(t==null?void 0:t.website_url)||"",f={form:s,brandColor:a,accentColor:i,headshot:l,logo:o,name:c,phone:d,email:u,tagline:h,website:p,width:n,height:r};return s.style==="editorial"?e.jsx(E1s,{...f}):s.style==="bold"?e.jsx(A1s,{...f}):s.style==="luxury"?e.jsx(I1s,{...f}):e.jsx(M1s,{...f})}function b0t({name:s,phone:t,email:n,website:r,color:a}){const i=[t,n,r].filter(Boolean);return e.jsxs("div",{style:{color:a,fontFamily:"Inter, system-ui, sans-serif"},children:[e.jsx("div",{style:{fontSize:22,fontWeight:700,letterSpacing:"0.02em"},children:s}),e.jsx("div",{style:{fontSize:16,opacity:.85,marginTop:4},children:i.join(" · ")})]})}function rve({rating:s,color:t}){return e.jsx("div",{style:{display:"flex",gap:4},children:Array.from({length:5}).map((n,r)=>e.jsx(oa,{size:28,fill:r1.5;return e.jsxs("div",{style:{width:h,height:p,background:"#FAF7F2",position:"relative",fontFamily:"Georgia, serif",color:"#1a1a1a",overflow:"hidden"},children:[e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:14,letterSpacing:"0.3em",color:n},children:t.badgeText}),e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:12,letterSpacing:"0.2em",color:"#888"},children:["EST. ",new Date().getFullYear()]})]}),e.jsx("div",{style:{position:"absolute",top:100,left:64,right:64,height:1,background:"#1a1a1a",opacity:.15}}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:140,left:64,width:h-128,height:f?700:480,overflow:"hidden",borderRadius:4},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"grayscale(0.15)"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:220,textAlign:t.template==="quote"?"center":"left"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:120,lineHeight:.7,color:r,fontFamily:"Georgia, serif"},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?76:92,lineHeight:1.05,fontWeight:400,margin:0,letterSpacing:"-0.02em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:22,marginTop:16,color:"#555",fontStyle:"italic"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:22,lineHeight:1.5,color:"#333",marginTop:28,maxWidth:820},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(rve,{rating:t.rating,color:r}),t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,color:"#555"},children:["— ",t.attribution]})]}),t.template==="quote"&&t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,marginTop:24,color:"#555",letterSpacing:"0.1em"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:64},children:[e.jsx("div",{style:{height:1,background:"#1a1a1a",opacity:.15,marginBottom:24}}),e.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx(b0t,{name:l,phone:o,email:c,website:d,color:"#1a1a1a"}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:56,objectFit:"contain"}})]}),u&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,color:"#888",marginTop:12,fontStyle:"italic"},children:u})]})]})}function A1s(s){const{form:t,brandColor:n,accentColor:r,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:u,height:h}=s;return e.jsxs("div",{style:{width:u,height:h,position:"relative",overflow:"hidden",fontFamily:"Inter, system-ui, sans-serif",background:`linear-gradient(135deg, ${n} 0%, ${P1s(n,-20)} 100%)`,color:"#fff"},children:[e.jsx("div",{style:{position:"absolute",top:-200,right:-200,width:700,height:700,borderRadius:"50%",background:r,opacity:.25,filter:"blur(40px)"}}),e.jsxs("div",{style:{position:"absolute",top:64,left:64,right:64,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontSize:14,letterSpacing:"0.4em",fontWeight:700,background:r,color:"#000",padding:"8px 16px",display:"inline-block"},children:t.badgeText}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:48,objectFit:"contain",filter:"brightness(0) invert(1)"}})]}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",right:64,top:180,width:380,height:380,borderRadius:"50%",overflow:"hidden",border:`6px solid ${r}`},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top"}})}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:240},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:180,lineHeight:.6,color:r},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?110:128,lineHeight:.95,fontWeight:900,margin:0,letterSpacing:"-0.04em",textTransform:t.template==="milestone"?"uppercase":"none",whiteSpace:"pre-wrap",maxWidth:u-128},children:t.headline}),t.subline&&e.jsx("div",{style:{fontSize:28,marginTop:16,color:r,fontWeight:700,letterSpacing:"0.04em"},children:t.subline}),t.body&&e.jsx("p",{style:{fontSize:24,lineHeight:1.45,marginTop:28,maxWidth:820,opacity:.92},children:t.body}),t.template==="testimonial"&&e.jsxs("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16},children:[e.jsx(rve,{rating:t.rating,color:r}),t.attribution&&e.jsxs("div",{style:{fontSize:20,opacity:.9},children:["— ",t.attribution]})]})]}),e.jsxs("div",{style:{position:"absolute",left:64,right:64,bottom:64},children:[e.jsx("div",{style:{height:2,background:r,marginBottom:20,width:80}}),e.jsx(b0t,{name:l,phone:o,email:c,website:d,color:"#fff"})]})]})}function M1s(s){const{form:t,brandColor:n,accentColor:r,headshot:a,logo:i,name:l,phone:o,email:c,website:d,width:u,height:h}=s;return e.jsxs("div",{style:{width:u,height:h,background:"#fff",position:"relative",fontFamily:"Inter, system-ui, sans-serif",color:"#0a0a0a",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",top:0,left:0,right:0,height:8,background:r}}),e.jsxs("div",{style:{position:"absolute",top:80,left:80,right:80,display:"flex",justifyContent:"space-between",alignItems:"center"},children:[e.jsx("div",{style:{fontSize:13,letterSpacing:"0.3em",color:n,fontWeight:600},children:t.badgeText}),i&&e.jsx("img",{src:i,crossOrigin:"anonymous",style:{height:44,objectFit:"contain"}})]}),a&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:160,left:"50%",transform:"translateX(-50%)",width:260,height:260,borderRadius:"50%",overflow:"hidden"},children:e.jsx("img",{src:a,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top"}})}),e.jsxs("div",{style:{position:"absolute",left:80,right:80,top:a&&(t.template==="meet"||t.template==="milestone")?460:220,textAlign:"center"},children:[e.jsx("h1",{style:{fontSize:84,lineHeight:1.05,fontWeight:300,margin:0,letterSpacing:"-0.03em",whiteSpace:"pre-wrap"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontSize:22,marginTop:16,color:"#666"},children:t.subline}),t.body&&e.jsx("p",{style:{fontSize:22,lineHeight:1.55,color:"#444",marginTop:32,maxWidth:760,marginLeft:"auto",marginRight:"auto"},children:t.body}),t.template==="testimonial"&&e.jsx("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16,justifyContent:"center"},children:e.jsx(rve,{rating:t.rating,color:r})}),t.attribution&&e.jsxs("div",{style:{fontSize:18,marginTop:16,color:"#666",letterSpacing:"0.1em"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:80,right:80,bottom:80,textAlign:"center"},children:[e.jsx("div",{style:{width:60,height:1,background:"#0a0a0a",opacity:.3,margin:"0 auto 20px"}}),e.jsx("div",{style:{fontSize:20,fontWeight:600},children:l}),e.jsx("div",{style:{fontSize:14,color:"#666",marginTop:4},children:[o,c,d].filter(Boolean).join(" · ")})]})]})}function I1s(s){const{form:t,accentColor:n,headshot:r,logo:a,name:i,phone:l,email:o,website:c,width:d,height:u}=s,h=n||"#D4AF37";return e.jsxs("div",{style:{width:d,height:u,background:"#0B0B0E",position:"relative",fontFamily:"Georgia, serif",color:"#EAE6DC",overflow:"hidden"},children:[e.jsx("div",{style:{position:"absolute",inset:40,border:`1px solid ${h}`,opacity:.6}}),e.jsx("div",{style:{position:"absolute",inset:50,border:`1px solid ${h}`,opacity:.25}}),e.jsxs("div",{style:{position:"absolute",top:96,left:96,right:96,textAlign:"center"},children:[e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,letterSpacing:"0.5em",color:h},children:t.badgeText}),e.jsx("div",{style:{width:40,height:1,background:h,margin:"20px auto 0"}})]}),r&&(t.template==="meet"||t.template==="milestone")&&e.jsx("div",{style:{position:"absolute",top:200,left:"50%",transform:"translateX(-50%)",width:340,height:420,overflow:"hidden",border:`1px solid ${h}`},children:e.jsx("img",{src:r,crossOrigin:"anonymous",style:{width:"100%",height:"100%",objectFit:"cover",objectPosition:"center top",filter:"sepia(0.15) brightness(0.95)"}})}),e.jsxs("div",{style:{position:"absolute",left:96,right:96,top:r&&(t.template==="meet"||t.template==="milestone")?680:280,textAlign:"center"},children:[t.template==="testimonial"&&e.jsx("div",{style:{fontSize:100,lineHeight:.6,color:h},children:'"'}),e.jsx("h1",{style:{fontSize:t.template==="quote"?68:80,lineHeight:1.1,fontWeight:400,margin:0,letterSpacing:"-0.01em",whiteSpace:"pre-wrap",fontStyle:t.template==="quote"?"italic":"normal"},children:t.headline}),t.subline&&e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:18,marginTop:16,color:h,letterSpacing:"0.3em",textTransform:"uppercase"},children:t.subline}),t.body&&e.jsx("p",{style:{fontFamily:"Inter, sans-serif",fontSize:20,lineHeight:1.65,color:"#C9C2B3",marginTop:28,maxWidth:760,marginLeft:"auto",marginRight:"auto",fontWeight:300},children:t.body}),t.template==="testimonial"&&e.jsx("div",{style:{marginTop:24,display:"flex",alignItems:"center",gap:16,justifyContent:"center"},children:e.jsx(rve,{rating:t.rating,color:h})}),t.attribution&&e.jsxs("div",{style:{fontFamily:"Inter, sans-serif",fontSize:16,marginTop:16,color:h,letterSpacing:"0.2em",textTransform:"uppercase"},children:["— ",t.attribution]})]}),e.jsxs("div",{style:{position:"absolute",left:96,right:96,bottom:96,textAlign:"center"},children:[e.jsx("div",{style:{width:40,height:1,background:h,margin:"0 auto 20px"}}),e.jsx("div",{style:{fontFamily:"Georgia, serif",fontSize:24,letterSpacing:"0.15em",color:"#EAE6DC"},children:i.toUpperCase()}),e.jsx("div",{style:{fontFamily:"Inter, sans-serif",fontSize:13,color:"#9A9285",marginTop:8,letterSpacing:"0.2em"},children:[l,o,c].filter(Boolean).join(" · ")}),a&&e.jsx("img",{src:a,crossOrigin:"anonymous",style:{height:40,objectFit:"contain",marginTop:20,filter:"brightness(0) invert(1) opacity(0.7)"}})]})]})}function P1s(s,t){const n=s.replace("#",""),r=parseInt(n.length===3?n.split("").map(o=>o+o).join(""):n,16);let a=(r>>16)+Math.round(t/100*255),i=(r>>8&255)+Math.round(t/100*255),l=(r&255)+Math.round(t/100*255);return a=Math.max(0,Math.min(255,a)),i=Math.max(0,Math.min(255,i)),l=Math.max(0,Math.min(255,l)),`#${(a<<16|i<<8|l).toString(16).padStart(6,"0")}`}const L1s=()=>{const{swagId:s}=bi(),{user:t}=vs(),{toast:n}=Fa(),r=Kt(),{trackEngagement:a}=UD(),[i,l]=N.useState(""),{data:o,isLoading:c}=dt({queryKey:["social-swag-detail",s],queryFn:async()=>{const{data:j,error:w}=await q.from("social_swag").select("*").eq("id",s).single();if(w)throw w;const{data:S}=await q.from("social_swag_links").select("*").eq("swag_id",s).order("sort_order");return{...j,links:S||[]}},enabled:!!s});N.useEffect(()=>{o&&a("social_swag",o.id,o.title,"view")},[o==null?void 0:o.id]);const{data:d=[]}=dt({queryKey:["social-swag-likes",s],queryFn:async()=>{const{data:j,error:w}=await q.from("social_swag_likes").select("*").eq("swag_id",s);if(w)throw w;return j},enabled:!!s}),{data:u=[]}=dt({queryKey:["social-swag-comments",s],queryFn:async()=>{const{data:j,error:w}=await q.from("social_swag_comments").select("*").eq("swag_id",s).order("created_at",{ascending:!1});if(w)throw w;const S=[...new Set(j.map(O=>O.user_id))],{data:A}=await q.from("profiles").select("id, name").in("id",S),E=new Map((A==null?void 0:A.map(O=>[O.id,O.name]))||[]);return j.map(O=>({...O,user_name:E.get(O.user_id)||"Unknown User"}))},enabled:!!s}),h=yt({mutationFn:async j=>{const{error:w}=await q.from("social_swag_comments").insert({swag_id:s,user_id:t.id,content:j});if(w)throw w},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),l(""),n({title:"Comment added!"})},onError:j=>{n({title:"Error adding comment",description:j.message,variant:"destructive"})}}),p=yt({mutationFn:async j=>{const{error:w}=await q.from("social_swag_comments").delete().eq("id",j);if(w)throw w},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-comments",s]}),n({title:"Comment deleted"})}}),f=yt({mutationFn:async()=>{const j=d.find(w=>w.user_id===(t==null?void 0:t.id));if(j){const{error:w}=await q.from("social_swag_likes").delete().eq("id",j.id);if(w)throw w}else{const{error:w}=await q.from("social_swag_likes").insert({swag_id:s,user_id:t.id});if(w)throw w}},onSuccess:()=>{r.invalidateQueries({queryKey:["social-swag-likes",s]})}}),y=d.some(j=>j.user_id===(t==null?void 0:t.id)),_=j=>j.split(" ").map(w=>w[0]).join("").toUpperCase().slice(0,2),v=j=>{j.preventDefault(),!(!i.trim()||!t)&&h.mutate(i.trim())};return c?e.jsx(Cs,{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(Cs,{title:o.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(In,{to:"/social-swag",children:[e.jsx(qr,{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(HD,{resourceType:"social_swag",resourceId:o.id,resourceTitle:o.title}),e.jsxs(B,{variant:y?"default":"outline",className:"gap-2 w-fit",onClick:()=>f.mutate(),disabled:!t||f.isPending,children:[e.jsx($m,{className:`h-4 w-4 ${y?"fill-current":""}`}),d.length," ",d.length===1?"Like":"Likes"]})]})]}),o.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:o.description}})]}),o.links.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(Yo,{className:"h-4 w-4"}),o.links.length===1?"Canva Link":"Canva Links"]}),e.jsx("div",{className:"grid gap-2",children:o.links.map(j=>e.jsxs(B,{variant:"outline",className:"w-full justify-between gap-2 h-auto py-3",onClick:()=>{a("social_swag",o.id,o.title,"click_canva"),window.open(j.canva_share_link,"_blank")},children:[e.jsx("span",{className:"font-medium",children:j.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground"})]},j.id))})]})}),e.jsx(al,{}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 text-lg",children:[e.jsx(Zl,{className:"h-5 w-5"}),"Comments (",u.length,")"]}),t?e.jsxs("form",{onSubmit:v,className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Add a comment...",value:i,onChange:j=>l(j.target.value),className:"min-h-[80px] resize-none flex-1"}),e.jsx(B,{type:"submit",size:"icon",className:"h-10 w-10",disabled:!i.trim()||h.isPending,children:e.jsx(lr,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Log in to add a comment"}),e.jsx("div",{className:"space-y-4",children:u.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center",children:e.jsx("p",{className:"text-muted-foreground",children:"No comments yet. Be the first to share your thoughts!"})})}):u.map(j=>e.jsx(fe,{children:e.jsx(Ee,{className:"pt-4 pb-4",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Jr,{className:"h-10 w-10 flex-shrink-0",children:e.jsx(ea,{className:"text-sm",children:_(j.user_name||"U")})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium",children:j.user_name}),e.jsx("span",{className:"text-sm text-muted-foreground",children:Uo(new Date(j.created_at),{addSuffix:!0})}),j.user_id===(t==null?void 0:t.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>p.mutate(j.id),children:e.jsx(_n,{className:"h-3 w-3 text-muted-foreground"})})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:j.content})]})]})})},j.id))})]})]})}):e.jsx(Cs,{title:"Social Swag",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Yo,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Item not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This item may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(In,{to:"/social-swag",children:"Back to Social Swag"})})]})})},D1s=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=N.useState(!0),[o,c]=N.useState(!0),[d,u]=N.useState(!0),h=p=>p.split(" ").map(f=>f[0]).join("").toUpperCase().slice(0,2);return e.jsx("aside",{className:"w-64 shrink-0 hidden lg:block relative z-0",children:e.jsx("div",{className:"sticky top-4 space-y-4 max-h-[calc(100vh-8rem)] overflow-y-auto overscroll-contain",children:e.jsxs("div",{className:"space-y-2 pr-4",children:[e.jsxs(B,{variant:n==="all"?"secondary":"ghost",className:"w-full justify-start",onClick:()=>r("all"),children:[e.jsx(VS,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsxs(oy,{open:i,onOpenChange:l,children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsx("span",{className:"text-xs font-semibold uppercase tracking-wider",children:"Categories"}),i?e.jsx(ao,{className:"h-4 w-4"}):e.jsx(ga,{className:"h-4 w-4"})]})}),e.jsx(cy,{className:"space-y-1 pl-2",children:s.map(p=>e.jsxs(B,{variant:n===p.id?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(p.id),children:[e.jsx("span",{className:"mr-2",children:p.icon||"📂"}),e.jsx("span",{className:"truncate",children:p.name})]},p.id))})]}),t.length>0&&e.jsxs(oy,{open:o,onOpenChange:c,children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(Gc,{className:"h-3 w-3"}),"Your Groups"]}),o?e.jsx(ao,{className:"h-4 w-4"}):e.jsx(ga,{className:"h-4 w-4"})]})}),e.jsx(cy,{className:"space-y-1 pl-2",children:t.map(p=>e.jsxs(B,{variant:n===`group:${p.id}`?"secondary":"ghost",size:"sm",className:"w-full justify-start h-9",onClick:()=>r(`group:${p.id}`),children:[e.jsx("span",{className:"mr-2",children:p.icon||"🔒"}),e.jsx("span",{className:"truncate",children:p.name})]},p.id))})]}),e.jsxs(oy,{open:d,onOpenChange:u,children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"w-full justify-between text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"text-xs font-semibold uppercase tracking-wider flex items-center gap-1",children:[e.jsx(An,{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(ao,{className:"h-4 w-4"}):e.jsx(ga,{className:"h-4 w-4"})]})}),e.jsx(cy,{className:"pl-2 space-y-1",children:a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-2 px-2",children:"No one else online right now"}):a.map(p=>e.jsxs("div",{className:"flex items-center gap-2 py-1.5 px-2 rounded-md hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Jr,{className:"h-7 w-7",children:[e.jsx(ti,{src:p.avatarUrl}),e.jsx(ea,{className:"text-xs",children:h(p.name)})]}),e.jsx(am,{className:"h-2.5 w-2.5 fill-green-500 text-green-500 absolute -bottom-0.5 -right-0.5"})]}),e.jsx("span",{className:"text-sm truncate",children:p.name})]},p.id))})]})]})})})},R1s=({categories:s,privateGroups:t,selectedFilter:n,onFilterChange:r,onlineUsers:a})=>{const[i,l]=N.useState(!1),o=d=>d.split(" ").map(u=>u[0]).join("").toUpperCase().slice(0,2),c=()=>{if(n==="all")return"All Posts";if(n.startsWith("group:")){const u=n.replace("group:",""),h=t.find(p=>p.id===u);return h?`🔒 ${h.name}`:"Private Group"}const d=s.find(u=>u.id===n);return d?`${d.icon||"📂"} ${d.name}`:"Category"};return e.jsxs("div",{className:"lg:hidden flex items-center gap-2 mb-4",children:[e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"flex-1 justify-between",children:[e.jsx("span",{className:"truncate",children:c()}),e.jsx(ao,{className:"h-4 w-4 ml-2 shrink-0"})]})}),e.jsxs(gc,{className:"w-56 bg-background border",children:[e.jsxs(Kr,{onClick:()=>r("all"),children:[e.jsx(VS,{className:"h-4 w-4 mr-2"}),"All Posts"]}),e.jsx(Kg,{}),e.jsx(cM,{className:"text-xs text-muted-foreground",children:"Categories"}),s.map(d=>e.jsxs(Kr,{onClick:()=>r(d.id),children:[e.jsx("span",{className:"mr-2",children:d.icon||"📂"}),d.name]},d.id)),t.length>0&&e.jsxs(e.Fragment,{children:[e.jsx(Kg,{}),e.jsxs(cM,{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Gc,{className:"h-3 w-3"}),"Your Groups"]}),t.map(d=>e.jsxs(Kr,{onClick:()=>r(`group:${d.id}`),children:[e.jsx("span",{className:"mr-2",children:d.icon||"🔒"}),d.name]},d.id))]})]})]}),e.jsxs(t0,{open:i,onOpenChange:l,children:[e.jsx(Y$,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"relative",children:[e.jsx(An,{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(og,{children:[e.jsx(jy,{children:e.jsxs(Ny,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"Online Now (",a.length,")"]})}),e.jsx(di,{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(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:d.avatarUrl}),e.jsx(ea,{children:o(d.name)})]}),e.jsx(am,{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 v2e,ave="HoverCard",[_0t,Mfn]=uu(ave,[qw]),ive=qw(),[O1s,SIe]=_0t(ave),w0t=s=>{const{__scopeHoverCard:t,children:n,open:r,defaultOpen:a,onOpenChange:i,openDelay:l=700,closeDelay:o=300}=s,c=ive(t),d=N.useRef(0),u=N.useRef(0),h=N.useRef(!1),p=N.useRef(!1),[f,y]=cm({prop:r,defaultProp:a??!1,onChange:i,caller:ave}),_=N.useCallback(()=>{clearTimeout(u.current),d.current=window.setTimeout(()=>y(!0),l)},[l,y]),v=N.useCallback(()=>{clearTimeout(d.current),!h.current&&!p.current&&(u.current=window.setTimeout(()=>y(!1),o))},[o,y]),j=N.useCallback(()=>y(!1),[y]);return N.useEffect(()=>()=>{clearTimeout(d.current),clearTimeout(u.current)},[]),e.jsx(O1s,{scope:t,open:f,onOpenChange:y,onOpen:_,onClose:v,onDismiss:j,hasSelectionRef:h,isPointerDownOnContentRef:p,children:e.jsx(I$,{...c,children:n})})};w0t.displayName=ave;var j0t="HoverCardTrigger",N0t=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=SIe(j0t,n),i=ive(n);return e.jsx(CD,{asChild:!0,...i,children:e.jsx(Yr.a,{"data-state":a.open?"open":"closed",...r,ref:t,onPointerEnter:xr(s.onPointerEnter,xxe(a.onOpen)),onPointerLeave:xr(s.onPointerLeave,xxe(a.onClose)),onFocus:xr(s.onFocus,a.onOpen),onBlur:xr(s.onBlur,a.onClose),onTouchStart:xr(s.onTouchStart,l=>l.preventDefault())})})});N0t.displayName=j0t;var F1s="HoverCardPortal",[Ifn,z1s]=_0t(F1s,{forceMount:void 0}),fxe="HoverCardContent",k0t=N.forwardRef((s,t)=>{const n=z1s(fxe,s.__scopeHoverCard),{forceMount:r=n.forceMount,...a}=s,i=SIe(fxe,s.__scopeHoverCard);return e.jsx(Lh,{present:r||i.open,children:e.jsx(B1s,{"data-state":i.open?"open":"closed",...a,onPointerEnter:xr(s.onPointerEnter,xxe(i.onOpen)),onPointerLeave:xr(s.onPointerLeave,xxe(i.onClose)),ref:t})})});k0t.displayName=fxe;var B1s=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:i,onInteractOutside:l,...o}=s,c=SIe(fxe,n),d=ive(n),u=N.useRef(null),h=ji(t,u),[p,f]=N.useState(!1);return N.useEffect(()=>{if(p){const y=document.body;return v2e=y.style.userSelect||y.style.webkitUserSelect,y.style.userSelect="none",y.style.webkitUserSelect="none",()=>{y.style.userSelect=v2e,y.style.webkitUserSelect=v2e}}},[p]),N.useEffect(()=>{if(u.current){const y=()=>{f(!1),c.isPointerDownOnContentRef.current=!1,setTimeout(()=>{var v;((v=document.getSelection())==null?void 0:v.toString())!==""&&(c.hasSelectionRef.current=!0)})};return document.addEventListener("pointerup",y),()=>{document.removeEventListener("pointerup",y),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!1}}},[c.isPointerDownOnContentRef,c.hasSelectionRef]),N.useEffect(()=>{u.current&&q1s(u.current).forEach(_=>_.setAttribute("tabindex","-1"))}),e.jsx(O4,{asChild:!0,disableOutsidePointerEvents:!1,onInteractOutside:l,onEscapeKeyDown:r,onPointerDownOutside:a,onFocusOutside:xr(i,y=>{y.preventDefault()}),onDismiss:c.onDismiss,children:e.jsx(P$,{...d,...o,onPointerDown:xr(o.onPointerDown,y=>{y.currentTarget.contains(y.target)&&f(!0),c.hasSelectionRef.current=!1,c.isPointerDownOnContentRef.current=!0}),ref:h,style:{...o.style,userSelect:p?"text":void 0,WebkitUserSelect:p?"text":void 0,"--radix-hover-card-content-transform-origin":"var(--radix-popper-transform-origin)","--radix-hover-card-content-available-width":"var(--radix-popper-available-width)","--radix-hover-card-content-available-height":"var(--radix-popper-available-height)","--radix-hover-card-trigger-width":"var(--radix-popper-anchor-width)","--radix-hover-card-trigger-height":"var(--radix-popper-anchor-height)"}})})}),$1s="HoverCardArrow",U1s=N.forwardRef((s,t)=>{const{__scopeHoverCard:n,...r}=s,a=ive(n);return e.jsx(L$,{...a,...r,ref:t})});U1s.displayName=$1s;function xxe(s){return t=>t.pointerType==="touch"?void 0:s()}function q1s(s){const t=[],n=document.createTreeWalker(s,NodeFilter.SHOW_ELEMENT,{acceptNode:r=>r.tabIndex>=0?NodeFilter.FILTER_ACCEPT:NodeFilter.FILTER_SKIP});for(;n.nextNode();)t.push(n.currentNode);return t}var V1s=w0t,H1s=N0t,S0t=k0t;const G1s=V1s,W1s=H1s,C0t=N.forwardRef(({className:s,align:t="center",sideOffset:n=4,...r},a)=>e.jsx(S0t,{ref:a,align:t,sideOffset:n,className:Mt("z-50 w-64 rounded-md border bg-popover p-4 text-popover-foreground shadow-md outline-none data-[state=open]:animate-in data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0 data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2",s),...r}));C0t.displayName=S0t.displayName;const K1s=[{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"}],Y1s=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2),T0t=({reactions:s,children:t})=>{if(s.length===0)return e.jsx(e.Fragment,{children:t});const n={};return s.forEach(r=>{n[r.reaction_type]||(n[r.reaction_type]=[]),n[r.reaction_type].push(r)}),e.jsxs(G1s,{openDelay:200,closeDelay:100,children:[e.jsx(W1s,{asChild:!0,children:e.jsx("div",{className:"cursor-pointer",children:t})}),e.jsx(C0t,{className:"w-64 p-3 bg-popover border shadow-lg z-50",side:"top",align:"start",children:e.jsx("div",{className:"space-y-3",children:Object.entries(n).map(([r,a])=>{const i=K1s.find(l=>l.type===r);return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("span",{className:"text-lg",children:i==null?void 0:i.emoji}),e.jsxs("span",{className:"text-sm font-medium text-foreground",children:[i==null?void 0:i.label," (",a.length,")"]})]}),e.jsxs("div",{className:"space-y-1.5",children:[a.slice(0,10).map(l=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Jr,{className:"h-6 w-6",children:[e.jsx(ti,{src:l.user_avatar||void 0}),e.jsx(ea,{className:"text-[10px]",children:Y1s(l.user_name||"U")})]}),e.jsx("span",{className:"text-sm text-foreground truncate",children:l.user_name||"Unknown User"})]},l.id)),a.length>10&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["+",a.length-10," more"]})]})]},r)})})})]})};function Z1s({images:s,initialIndex:t=0,open:n,onOpenChange:r}){const[a,i]=N.useState(t),[l,o]=N.useState(!1);N.useEffect(()=>{n&&(i(t),o(!1))},[n,t]);const c=()=>{i(p=>p>0?p-1:s.length-1),o(!1)},d=()=>{i(p=>p{n&&(p.key==="ArrowLeft"&&c(),p.key==="ArrowRight"&&d(),p.key==="Escape"&&r(!1))},[n,s.length]);N.useEffect(()=>(window.addEventListener("keydown",u),()=>window.removeEventListener("keydown",u)),[u]);const h=s[a];return e.jsx(_s,{open:n,onOpenChange:r,children:e.jsxs(bs,{className:"max-w-[95vw] max-h-[95vh] w-auto h-auto p-0 border-none bg-black/95 overflow-hidden",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"absolute top-2 right-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>r(!1),children:e.jsx($n,{className:"h-6 w-6"})}),s.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:c,children:e.jsx(ml,{className:"h-8 w-8"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 z-50 text-white hover:bg-white/20 h-12 w-12",onClick:d,children:e.jsx(ga,{className:"h-8 w-8"})})]}),s.length>1&&e.jsxs("div",{className:"absolute bottom-4 left-1/2 -translate-x-1/2 z-50 text-white text-sm bg-black/50 px-3 py-1 rounded-full",children:[a+1," / ",s.length]}),(h==null?void 0:h.type)==="image"&&e.jsx(B,{variant:"ghost",size:"icon",className:"absolute top-2 left-2 z-50 text-white hover:bg-white/20 h-10 w-10",onClick:()=>o(!l),children:l?e.jsx(yL,{className:"h-5 w-5"}):e.jsx(r4,{className:"h-5 w-5"})}),e.jsx("div",{className:Mt("flex items-center justify-center w-full h-full min-h-[50vh] p-4",l?"cursor-zoom-out overflow-auto":"cursor-zoom-in"),onClick:()=>(h==null?void 0:h.type)==="image"&&o(!l),children:(h==null?void 0:h.type)==="video"?e.jsx("video",{src:h.url,controls:!0,autoPlay:!0,className:"max-w-full max-h-[85vh] object-contain",onClick:p=>p.stopPropagation()}):e.jsx("img",{src:h==null?void 0:h.url,alt:"",className:Mt("object-contain transition-transform duration-200",l?"max-w-none max-h-none scale-150":"max-w-full max-h-[85vh]")})}),s.length>1&&e.jsx("div",{className:"absolute bottom-12 left-1/2 -translate-x-1/2 z-50 flex gap-2 bg-black/50 p-2 rounded-lg max-w-[90vw] overflow-x-auto",children:s.map((p,f)=>e.jsx("button",{onClick:()=>{i(f),o(!1)},className:Mt("w-12 h-12 rounded overflow-hidden flex-shrink-0 border-2 transition-all",a===f?"border-white":"border-transparent opacity-60 hover:opacity-100"),children:p.type==="video"?e.jsx("video",{src:p.url,className:"w-full h-full object-cover"}):e.jsx("img",{src:p.url,alt:"",className:"w-full h-full object-cover"})},f))})]})})}const DH=[{type:"like",emoji:"👍",label:"Like"},{type:"love",emoji:"❤️",label:"Love"}],Q1s=({commentId:s,reactions:t,currentUserId:n})=>{var d,u;const r=Kt(),[a,i]=N.useState(!1),l=t.find(h=>h.user_id===n),o=yt({mutationFn:async h=>{l?l.reaction_type===h?await q.from("community_comment_reactions").delete().eq("id",l.id):await q.from("community_comment_reactions").update({reaction_type:h}).eq("id",l.id):await q.from("community_comment_reactions").insert({comment_id:s,user_id:n,reaction_type:h})},onSuccess:()=>{r.invalidateQueries({queryKey:["community-posts"]}),i(!1)}}),c={};return t.forEach(h=>{c[h.reaction_type]=(c[h.reaction_type]||0)+1}),e.jsxs("div",{className:"flex items-center gap-2",children:[t.length>0&&e.jsx(T0t,{reactions:t,children:e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx("div",{className:"flex -space-x-0.5",children:Object.keys(c).slice(0,2).map(h=>{var p;return e.jsx("span",{className:"text-sm",children:(p=DH.find(f=>f.type===h))==null?void 0:p.emoji},h)})}),e.jsx("span",{children:t.length})]})}),n&&e.jsxs(il,{open:a,onOpenChange:i,children:[e.jsx(ol,{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=DH.find(h=>h.type===l.reaction_type))==null?void 0:d.emoji," ",(u=DH.find(h=>h.type===l.reaction_type))==null?void 0:u.label]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gi,{className:"h-3 w-3"}),"Like"]})})}),e.jsx(el,{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:DH.map(h=>e.jsx("button",{onClick:()=>o.mutate(h.type),className:"text-xl hover:scale-125 transition-transform p-1",title:h.label,children:h.emoji},h.type))})})]})]})};function CIe({content:s,className:t}){const n=/([@#])\[([^\]]+)\]\(([^)]+)\)|(https?:\/\/[^\s<>]+)/g,r=[];let a=0,i,l=0;for(;(i=n.exec(s))!==null;){if(i.index>a&&r.push(s.substring(a,i.index)),i[1]){const o=i[1],c=i[2],d=i[3],u=o==="#";r.push(e.jsx(In,{to:u?`/templates/${d}`:`/profile?user=${d}`,className:Mt("font-medium hover:underline",u?"text-white bg-[#2a4c64] px-1.5 py-0.5 rounded":"text-primary"),onClick:h=>h.stopPropagation(),children:u?c:`@${c}`},`mention-${l++}`))}else if(i[4]){const o=i[4],c=o.replace(/[.,;:!?)]+$/,""),d=o.slice(c.length);let u;try{const h=new URL(c);u=h.hostname+(h.pathname!=="/"?h.pathname.slice(0,20)+(h.pathname.length>20?"...":""):"")}catch{u=c.length>40?c.slice(0,40)+"...":c}r.push(e.jsx("a",{href:c,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline break-all",onClick:h=>h.stopPropagation(),children:u},`url-${l++}`)),d&&r.push(d)}a=i.index+i[0].length}return ae.jsx(N.Fragment,{children:o},c))})}function gxe({value:s,onChange:t,placeholder:n="What's on your mind? Use @ to mention someone",className:r,minHeight:a="80px",onMentionsChange:i,onTemplatesChange:l,onKeyDown:o,mentionFormat:c="encoded",enableTemplateMentions:d=!1}){const u=N.useRef(null),h=N.useRef(null),[p,f]=N.useState(!1),[y,_]=N.useState("user"),[v,j]=N.useState(""),[w,S]=N.useState(null),[A,E]=N.useState(0),[O,D]=N.useState({top:0,left:0,width:0}),I=N.useRef(new Map),F=N.useRef(new Map),z=ve=>{if(c==="plain"){const Ce=[];return I.current.forEach((Pe,Re)=>{ve.includes(`@${Re}`)&&Ce.push(Pe)}),[...new Set(Ce)]}const ge=/@\[([^\]]+)\]\(([^)]+)\)/g,Te=[];let Ie;for(;(Ie=ge.exec(ve))!==null;)Te.push(Ie[2]);return[...new Set(Te)]},H=ve=>{if(c==="plain"){const Ce=[];return F.current.forEach((Pe,Re)=>{ve.includes(`#${Re}`)&&Ce.push(Pe)}),[...new Set(Ce)]}const ge=/#\[([^\]]+)\]\(([^)]+)\)/g,Te=[];let Ie;for(;(Ie=ge.exec(ve))!==null;)Te.push(Ie[2]);return[...new Set(Te)]};N.useEffect(()=>{if(i){const ve=z(s);i(ve)}if(l){const ve=H(s);l(ve)}},[s,i,l,c]);const{data:Z=[],isLoading:Y}=dt({queryKey:["mention-users",v],queryFn:async()=>{const ve=q.from("profiles").select("id, name").limit(8),ge=v.length>=1?ve.ilike("name",`%${v}%`):ve.order("name"),{data:Te,error:Ie}=await ge;if(Ie)throw Ie;const Ce=Te.map(Pe=>Pe.id),Me=await _ht(Ce);return Te.map(Pe=>({id:Pe.id,name:Pe.name||"Unknown",avatar_url:Me.get(Pe.id)}))},enabled:p&&y==="user",staleTime:3e4}),{data:W=[],isLoading:ee}=dt({queryKey:["mention-templates",v],queryFn:async()=>{let ve=q.from("canva_templates").select("id, name, preview_image_url").lte("publish_date",new Date().toISOString()).order("publish_date",{ascending:!1}).limit(8);v.length>=1&&(ve=ve.ilike("name",`%${v}%`));const{data:ge,error:Te}=await ve;if(Te)throw Te;return ge||[]},enabled:p&&y==="template"&&d,staleTime:3e4}),se=y==="user"?Y:ee,oe=y==="user"?Z:W,he=ve=>ve.split(" ").map(ge=>ge[0]).join("").toUpperCase().slice(0,2),ce=ve=>{const ge=ve.target.value,Te=ve.target.selectionStart;t(ge);const Ie=ge.substring(0,Te),Ce=Ie.lastIndexOf("@"),Me=d?Ie.lastIndexOf("#"):-1;let Pe=-1,Re="user";if(Ce>Me?(Pe=Ce,Re="user"):Me>Ce&&d&&(Pe=Me,Re="template"),Pe!==-1){const Ae=Ie.substring(Pe+1),Be=Ae.includes(" "),we=Ae.includes(` `);if(!Be&&!we&&Ae.length<=30){S(Pe),j(Ae),_(Re),f(!0),E(0);return}}f(!1),S(null)},me=ve=>{if(w===null)return;const ge=s.substring(0,w),Te=s.substring(w+v.length+1),Ie=y==="user"?"@":"#",Ce=c==="plain"?`${Ie}${ve.name} `:`${Ie}[${ve.name}](${ve.id}) `;c==="plain"&&(y==="user"?I.current.set(ve.name,ve.id):F.current.set(ve.name,ve.id));const Me=ge+Ce+Te;t(Me),f(!1),S(null),j(""),setTimeout(()=>{if(u.current){const Pe=ge.length+Ce.length;u.current.focus(),u.current.setSelectionRange(Pe,Pe)}},0)},le=ve=>{if(!(!p||oe.length===0))switch(ve.key){case"ArrowDown":ve.preventDefault(),E(ge=>(ge+1)%oe.length);break;case"ArrowUp":ve.preventDefault(),E(ge=>(ge-1+oe.length)%oe.length);break;case"Enter":oe[A]&&(ve.preventDefault(),me(oe[A]));break;case"Escape":ve.preventDefault(),f(!1);break;case"Tab":oe[A]&&(ve.preventDefault(),me(oe[A]));break}};return N.useEffect(()=>{const ve=ge=>{h.current&&!h.current.contains(ge.target)&&u.current&&!u.current.contains(ge.target)&&f(!1)};return document.addEventListener("mousedown",ve),()=>document.removeEventListener("mousedown",ve)},[]),N.useEffect(()=>{if(!p)return;const ve=()=>{const ge=u.current;if(!ge)return;const Te=ge.getBoundingClientRect();D({top:Te.bottom+4,left:Te.left,width:Te.width})};return ve(),window.addEventListener("resize",ve),window.addEventListener("scroll",ve,!0),()=>{window.removeEventListener("resize",ve),window.removeEventListener("scroll",ve,!0)}},[p,s]),e.jsxs("div",{className:"relative flex-1",children:[e.jsx(Ms,{ref:u,value:s,onChange:ce,onKeyDown:ve=>{le(ve),ve.defaultPrevented||o==null||o(ve)},placeholder:n,className:Mt("resize-none",r),style:{minHeight:a}}),p&&qx.createPortal(e.jsxs("div",{ref:h,className:"fixed z-[1000] max-h-[220px] overflow-hidden rounded-lg border bg-popover shadow-lg",style:{top:O.top,left:O.left,width:O.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:y==="user"?"👤 Mention a person":"📋 Link a template"}),se?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:v.length<1?`Type to search ${y==="user"?"people":"templates"}...`:`No ${y==="user"?"users":"templates"} found`}):e.jsx("ul",{className:"py-1 max-h-[180px] overflow-y-auto",children:oe.map((ve,ge)=>e.jsx("li",{className:Mt("flex items-center gap-2 px-3 py-2 cursor-pointer transition-colors",ge===A?"bg-accent":"hover:bg-accent/50"),onClick:()=>me(ve),onMouseEnter:()=>E(ge),children:y==="user"?e.jsxs(e.Fragment,{children:[e.jsxs(Jr,{className:"h-6 w-6",children:[e.jsx(ti,{src:ve.avatar_url}),e.jsx(ea,{className:"text-xs",children:he(ve.name)})]}),e.jsx("span",{className:"text-sm font-medium truncate",children:ve.name})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center overflow-hidden flex-shrink-0",children:ve.preview_image_url?e.jsx("img",{src:ve.preview_image_url,alt:"",className:"w-full h-full object-cover"}):e.jsx(pl,{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 X1s(s){const t=/#\[([^\]]+)\]\(([^)]+)\)/g,n=[];let r;for(;(r=t.exec(s))!==null;)n.push(r[2]);return[...new Set(n)]}const gHe=s=>s.split(" ").map(t=>t[0]).join("").toUpperCase().slice(0,2);function E0t({comment:s,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l=0}){const o=Kt(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState([]),y=yt({mutationFn:async({content:w,parentCommentId:S})=>{const{data:A,error:E}=await q.from("community_comments").insert({post_id:t,user_id:n,content:w,parent_comment_id:S}).select("id").single();if(E)throw E;const O=p;if(O.length>0&&A){const D=O.filter(I=>I!==n).map(I=>({comment_id:A.id,mentioned_user_id:I,mentioned_by_user_id:n}));D.length>0&&await q.from("community_comment_mentions").insert(D)}},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),h(""),f([]),d(!1)}}),_=yt({mutationFn:async w=>{const{error:S}=await q.from("community_comments").delete().eq("id",w);if(S)throw S},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),v=()=>{u.trim()&&y.mutate({content:u,parentCommentId:s.id})};return e.jsxs("div",{className:l>0?"ml-8 border-l-2 border-muted pl-3":"",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Jr,{className:"h-8 w-8 shrink-0",children:[e.jsx(ti,{src:s.user_avatar||void 0}),e.jsx(ea,{className:"text-xs",children:gHe(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(CIe,{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:Uo(new Date(s.created_at),{addSuffix:!0})}),e.jsx(Q1s,{commentId:s.id,reactions:s.reactions,currentUserId:n}),n&&l<2&&e.jsxs("button",{onClick:()=>d(!c),className:"hover:text-primary flex items-center gap-1",children:[e.jsx(h9,{className:"h-3 w-3"}),"Reply"]}),(s.user_id===n||i)&&e.jsx("button",{onClick:()=>_.mutate(s.id),className:"hover:text-destructive",children:s.user_id!==n?"Remove":"Delete"})]}),c&&n&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(Jr,{className:"h-6 w-6 shrink-0 mt-1",children:[e.jsx(ti,{src:r||void 0}),e.jsx(ea,{className:"text-xs",children:gHe((a==null?void 0:a.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2 items-start",children:[e.jsx(gxe,{placeholder:`Reply to ${s.user_name}...`,value:u,onChange:h,onMentionsChange:f,mentionFormat:"plain",className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:v,disabled:!u.trim()||y.isPending,className:"h-8 px-2 mt-0.5",children:e.jsx(lr,{className:"h-3 w-3"})})]})]})]})]}),s.replies&&s.replies.length>0&&e.jsx("div",{className:"mt-2 space-y-2",children:s.replies.map(w=>e.jsx(E0t,{comment:w,postId:t,currentUserId:n,currentUserAvatar:r,currentUserEmail:a,canModerate:i,depth:l+1},w.id))})]})}const RH=[{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"}],J1s=()=>{const{user:s,isBrokerageManager:t,managedBrokerages:n,isAdmin:r}=vs(),{avatarUrl:a}=bht(s==null?void 0:s.id),{onlineUsers:i}=qat(),{toast:l}=Fa(),o=Kt(),c=N.useRef(null),[d,u]=N.useState("all"),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState([]),[S,A]=N.useState([]),[E,O]=N.useState(""),[D,I]=N.useState(!1),[F,z]=N.useState(null),[H,Z]=N.useState(""),[Y,W]=N.useState(new Set),[ee,se]=N.useState({}),[oe,he]=N.useState({}),[ce,me]=N.useState([]),[le,ve]=N.useState([]),[ge,Te]=N.useState({open:!1,images:[],index:0});N.useEffect(()=>{if(d.startsWith("group:")){const bt=d.replace("group:","");v(bt),y("")}else d!=="all"?(y(d),v("")):(y(""),v(""))},[d]);const{data:Ie=[]}=dt({queryKey:["community-categories"],queryFn:async()=>{const{data:bt,error:$t}=await q.from("community_categories").select("*").order("sort_order");if($t)throw $t;return bt}}),{data:Ce=[]}=dt({queryKey:["community-private-groups"],queryFn:async()=>{const{data:bt,error:$t}=await q.from("community_private_groups").select("id, name, description, icon, brokerage_id, sort_order").order("sort_order");if($t)throw $t;return bt}}),Me=20,{data:Pe,isLoading:Re,hasNextPage:Ae,fetchNextPage:Be,isFetchingNextPage:we}=PPt({queryKey:["community-posts",d],initialPageParam:0,queryFn:async({pageParam:bt})=>{var Qe;const $t=bt*Me,Yt=$t+Me;let Ds=q.from("community_posts").select("*").order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1}).range($t,Yt);if(d.startsWith("group:")){const ot=d.replace("group:","");Ds=Ds.eq("private_group_id",ot)}else d==="all"||(Ds=Ds.eq("category_id",d).is("private_group_id",null));const{data:Ls,error:xs}=await Ds;if(xs)throw xs;const Lt=((Ls==null?void 0:Ls.length)||0)>Me,Jt=(Ls||[]).slice(0,Me);if(Jt.length===0)return{posts:[],hasMore:!1,nextPage:bt+1};const gt=Jt.map(ot=>ot.id),zt=[...new Set(Jt.filter(ot=>ot.category_id).map(ot=>ot.category_id))].filter(Boolean),[As,Xt,Qs,ks,$s]=await Promise.all([zt.length?q.from("community_categories").select("*").in("id",zt):Promise.resolve({data:[]}),q.from("community_post_media").select("*").in("post_id",gt).order("sort_order"),q.from("community_reactions").select("*").in("post_id",gt),q.from("community_comments").select("*").in("post_id",gt).order("created_at",{ascending:!0}),q.from("community_post_resources").select("*").in("post_id",gt)]),an=As==null?void 0:As.data,tn=Xt==null?void 0:Xt.data,er=Qs==null?void 0:Qs.data,xn=ks==null?void 0:ks.data,Pn=$s==null?void 0:$s.data,Qn=(xn||[]).map(ot=>ot.id),[sa,na]=await Promise.all([Qn.length?q.from("community_comment_reactions").select("*").in("comment_id",Qn):Promise.resolve({data:[]}),(()=>{const ot=(Pn||[]).filter(St=>St.resource_type==="template").map(St=>St.resource_id);return ot.length===0?Promise.resolve({data:[]}):q.from("canva_templates").select("id, name, preview_image_url").in("id",ot)})()]),Es=(sa==null?void 0:sa.data)||[],mi=(na==null?void 0:na.data)||[],Ar=new Map(mi.map(ot=>[ot.id,{name:ot.name,preview_image_url:ot.preview_image_url}])),Hn=Array.from(new Set([...Jt.map(ot=>ot.user_id),...(er||[]).map(ot=>ot.user_id),...(xn||[]).map(ot=>ot.user_id),...Es.map(ot=>ot.user_id)])),[Ts,Un]=await Promise.all([Hn.length?q.from("profiles").select("id, name").in("id",Hn):Promise.resolve({data:[]}),_ht(Hn)]),ir=new Map(((Qe=Ts==null?void 0:Ts.data)==null?void 0:Qe.map(ot=>[ot.id,ot.name]))||[]),Tr=new Map((an||[]).map(ot=>[ot.id,ot])),ts=ot=>{const St=new Map,Bt=[];return ot.forEach(Vt=>{St.set(Vt.id,{...Vt,user_name:ir.get(Vt.user_id)||"Unknown User",user_avatar:Un.get(Vt.user_id),reactions:Es.filter(fs=>fs.comment_id===Vt.id).map(fs=>({...fs,user_name:ir.get(fs.user_id)||"Unknown User",user_avatar:Un.get(fs.user_id)})),replies:[]})}),ot.forEach(Vt=>{const fs=St.get(Vt.id);if(Vt.parent_comment_id&&St.has(Vt.parent_comment_id)){const lt=St.get(Vt.parent_comment_id);lt.replies=lt.replies||[],lt.replies.push(fs)}else Bt.push(fs)}),Bt};return{posts:Jt.map(ot=>{const St=(Pn||[]).filter(Bt=>Bt.post_id===ot.id).map(Bt=>{let Vt="",fs=null;if(Bt.resource_type==="template"){const lt=Ar.get(Bt.resource_id);Vt=(lt==null?void 0:lt.name)||"Unknown Template",fs=(lt==null?void 0:lt.preview_image_url)||null}return{id:Bt.id,resource_type:Bt.resource_type,resource_id:Bt.resource_id,resource_name:Vt,resource_preview_url:fs}});return{...ot,user_name:ir.get(ot.user_id)||"Unknown User",user_avatar:Un.get(ot.user_id),category:ot.category_id?Tr.get(ot.category_id):null,media:(tn||[]).filter(Bt=>Bt.post_id===ot.id),reactions:((er||[]).filter(Bt=>Bt.post_id===ot.id)||[]).map(Bt=>({...Bt,user_name:ir.get(Bt.user_id)||"Unknown User",user_avatar:Un.get(Bt.user_id)})),comments:ts((xn||[]).filter(Bt=>Bt.post_id===ot.id)),resources:St}}),hasMore:Lt,nextPage:bt+1}},getNextPageParam:bt=>bt.hasMore?bt.nextPage:void 0}),Je=N.useMemo(()=>(Pe==null?void 0:Pe.pages.flatMap(bt=>bt.posts))??[],[Pe]),ke=yt({mutationFn:async()=>{I(!0);const{data:bt,error:$t}=await q.from("community_posts").insert({user_id:s.id,category_id:_?null:f||null,private_group_id:_||null,content:h,link_url:E||null}).select().single();if($t)throw $t;for(let Ds=0;Ds0){const Ds=ce.filter(Ls=>Ls!==s.id).map(Ls=>({post_id:bt.id,mentioned_user_id:Ls,mentioned_by_user_id:s.id}));Ds.length>0&&await q.from("community_post_mentions").insert(Ds)}const Yt=X1s(h);if(Yt.length>0){const Ds=Yt.map(Ls=>({post_id:bt.id,resource_type:"template",resource_id:Ls}));await q.from("community_post_resources").insert(Ds)}return bt},onSuccess:async bt=>{var $t;o.invalidateQueries({queryKey:["community-posts"]}),p(""),me([]),ve([]),y(""),v(""),w([]),A([]),O(""),l({title:"Post created!"});try{const Yt=(($t=s==null?void 0:s.user_metadata)==null?void 0:$t.name)||"Someone",Ds=h.replace(/@\[([^\]]+)\]\([^)]+\)/g,"@$1"),Ls=Ds.length>50?Ds.substring(0,50)+"...":Ds;await q.functions.invoke("send-push-notification",{body:{title:"New Community Post",body:`${Yt}: ${Ls}`,url:"/community"}})}catch(Yt){console.error("Failed to send push notification:",Yt)}},onError:bt=>{l({title:"Error creating post",description:bt.message,variant:"destructive"})},onSettled:()=>I(!1)}),it=yt({mutationFn:async({postId:bt,content:$t})=>{const{error:Yt}=await q.from("community_posts").update({content:$t}).eq("id",bt);if(Yt)throw Yt},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),z(null),Z(""),l({title:"Post updated!"})}}),je=yt({mutationFn:async bt=>{const{error:$t}=await q.from("community_posts").delete().eq("id",bt);if($t)throw $t},onSuccess:()=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:"Post deleted"})}}),He=yt({mutationFn:async({postId:bt,isPinned:$t})=>{const{error:Yt}=await q.from("community_posts").update({is_pinned:!$t,pinned_at:$t?null:new Date().toISOString(),pinned_by:$t?null:s==null?void 0:s.id}).eq("id",bt);if(Yt)throw Yt},onSuccess:(bt,{isPinned:$t})=>{o.invalidateQueries({queryKey:["community-posts"]}),l({title:$t?"Post unpinned":"Post pinned to top"})}}),$e=yt({mutationFn:async({postId:bt,reactionType:$t})=>{var Ds;const Yt=(Ds=Je.find(Ls=>Ls.id===bt))==null?void 0:Ds.reactions.find(Ls=>Ls.user_id===(s==null?void 0:s.id));Yt?Yt.reaction_type===$t?await q.from("community_reactions").delete().eq("id",Yt.id):await q.from("community_reactions").update({reaction_type:$t}).eq("id",Yt.id):await q.from("community_reactions").insert({post_id:bt,user_id:s.id,reaction_type:$t})},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})}),Ke=yt({mutationFn:async({postId:bt,content:$t})=>{const{data:Yt,error:Ds}=await q.from("community_comments").insert({post_id:bt,user_id:s.id,content:$t}).select("id").single();if(Ds)throw Ds;const Ls=oe[bt]||[];if(Ls.length>0&&Yt){const xs=Ls.filter(Lt=>Lt!==s.id).map(Lt=>({comment_id:Yt.id,mentioned_user_id:Lt,mentioned_by_user_id:s.id}));xs.length>0&&await q.from("community_comment_mentions").insert(xs)}},onSuccess:(bt,{postId:$t})=>{o.invalidateQueries({queryKey:["community-posts"]}),se(Yt=>({...Yt,[$t]:""})),he(Yt=>({...Yt,[$t]:[]}))}});yt({mutationFn:async bt=>{const{error:$t}=await q.from("community_comments").delete().eq("id",bt);if($t)throw $t},onSuccess:()=>o.invalidateQueries({queryKey:["community-posts"]})});const Ge=bt=>{const $t=Array.from(bt.target.files||[]);if($t.length+j.length>10){l({title:"Maximum 10 files allowed",variant:"destructive"});return}w(Yt=>[...Yt,...$t]),$t.forEach(Yt=>{const Ds=new FileReader;Ds.onloadend=()=>{A(Ls=>[...Ls,Ds.result])},Ds.readAsDataURL(Yt)})},rt=bt=>{w($t=>$t.filter((Yt,Ds)=>Ds!==bt)),A($t=>$t.filter((Yt,Ds)=>Ds!==bt))},tt=bt=>bt.split(" ").map($t=>$t[0]).join("").toUpperCase().slice(0,2),at=bt=>{const $t={};return bt.forEach(Yt=>{$t[Yt.reaction_type]=($t[Yt.reaction_type]||0)+1}),$t},Ye=bt=>{var $t;return($t=bt.find(Yt=>Yt.user_id===(s==null?void 0:s.id)))==null?void 0:$t.reaction_type},ut=bt=>bt.reduce(($t,Yt)=>$t+1+(Yt.replies?ut(Yt.replies):0),0),_t=bt=>{if(r)return!0;if(!t||!bt.private_group_id)return!1;const $t=Ce.find(Yt=>Yt.id===bt.private_group_id);return $t!=null&&$t.brokerage_id?n.some(Yt=>Yt.id===$t.brokerage_id):!1};return e.jsx(Cs,{title:"Community",children:e.jsxs("div",{className:"flex gap-6 w-full isolate z-0",children:[e.jsx(D1s,{categories:Ie,privateGroups:Ce,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsxs("div",{className:"flex-1 min-w-0 max-w-2xl mx-auto lg:mx-0 space-y-6",children:[e.jsxs("div",{className:"px-1",children:[e.jsx("h1",{className:"text-4xl lg:text-5xl font-bold text-foreground",children:"Community"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Connect and share with fellow agents"})]}),e.jsx(R1s,{categories:Ie,privateGroups:Ce,selectedFilter:d,onFilterChange:u,onlineUsers:i}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsxs(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:a||void 0}),e.jsx(ea,{children:s!=null&&s.email?tt(s.email.split("@")[0]):"U"})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsx(gxe,{placeholder:r?"What's on your mind? Use @ to mention someone, # to link a template":"What's on your mind? Use @ to mention someone",value:h,onChange:p,onMentionsChange:me,onTemplatesChange:ve,mentionFormat:"encoded",minHeight:"80px",enableTemplateMentions:r}),S.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:S.map((bt,$t)=>{var Yt;return e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden bg-muted",children:[(Yt=j[$t])!=null&&Yt.type.startsWith("video/")?e.jsx("video",{src:bt,className:"w-full h-full object-cover"}):e.jsx("img",{src:bt,alt:"",className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>rt($t),children:e.jsx($n,{className:"h-3 w-3"})})]},$t)})}),E&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:E,onChange:bt=>O(bt.target.value),placeholder:"https://...",className:"flex-1"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>O(""),children:e.jsx($n,{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:Ge,accept:"image/*,video/*",multiple:!0,className:"hidden"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var bt;return(bt=c.current)==null?void 0:bt.click()},children:[e.jsx(Xo,{className:"h-4 w-4 mr-1"}),"Photo"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{var bt;return(bt=c.current)==null?void 0:bt.click()},children:[e.jsx(fr,{className:"h-4 w-4 mr-1"}),"Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>O("https://"),children:[e.jsx(Yo,{className:"h-4 w-4 mr-1"}),"Link"]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end",children:[Ce.length>0?e.jsxs(us,{value:_||f||"none",onValueChange:bt=>{bt==="none"?(y(""),v("")):bt.startsWith("group:")?(v(bt.replace("group:","")),y("")):(y(bt),v(""))},children:[e.jsx(ls,{className:"w-[130px] sm:w-[160px] h-8 text-xs sm:text-sm",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No category"}),Ie.map(bt=>e.jsxs(Ze,{value:bt.id,children:[bt.icon," ",bt.name]},bt.id)),Ce.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-2 py-1 text-xs font-semibold text-muted-foreground border-t mt-1 pt-1",children:"🔒 Private Groups"}),Ce.map(bt=>e.jsxs(Ze,{value:`group:${bt.id}`,children:[bt.icon||"🔒"," ",bt.name]},bt.id))]})]})]}):e.jsxs(us,{value:f,onValueChange:y,children:[e.jsx(ls,{className:"w-[110px] sm:w-[140px] h-8 text-xs sm:text-sm",children:e.jsx(hs,{placeholder:"Category"})}),e.jsx(cs,{children:Ie.map(bt=>e.jsxs(Ze,{value:bt.id,children:[bt.icon," ",bt.name]},bt.id))})]}),e.jsxs(B,{size:"sm",onClick:()=>ke.mutate(),disabled:!h.trim()||D,children:[e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Post"]})]})]})]})]})})}),Re?e.jsx("div",{className:"space-y-4",children:[...Array(3)].map((bt,$t)=>e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ws,{className:"h-10 w-10 rounded-full"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(Ws,{className:"h-4 w-32"}),e.jsx(Ws,{className:"h-4 w-full"}),e.jsx(Ws,{className:"h-4 w-3/4"})]})]})})},$t))}):Je.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Zl,{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:[Je.map(bt=>{var $t,Yt,Ds,Ls;return e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsxs("div",{className:"flex gap-3 min-w-0",children:[e.jsxs(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:bt.user_avatar||void 0}),e.jsx(ea,{children:tt(bt.user_name||"U")})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-semibold break-words",children:bt.user_name}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("span",{children:Uo(new Date(bt.created_at),{addSuffix:!0})}),bt.category&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs(Ue,{variant:"secondary",className:"text-xs",children:[bt.category.icon," ",bt.category.name]})]})]})]})]}),(bt.user_id===(s==null?void 0:s.id)||_t(bt))&&e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Kf,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",children:[_t(bt)&&bt.private_group_id&&e.jsx(Kr,{onClick:()=>He.mutate({postId:bt.id,isPinned:bt.is_pinned}),children:bt.is_pinned?e.jsxs(e.Fragment,{children:[e.jsx(o9,{className:"h-4 w-4 mr-2"}),"Unpin Post"]}):e.jsxs(e.Fragment,{children:[e.jsx(XS,{className:"h-4 w-4 mr-2"}),"Pin to Top"]})}),bt.user_id===(s==null?void 0:s.id)&&e.jsxs(Kr,{onClick:()=>{z(bt),Z(bt.content)},children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Kr,{className:"text-destructive",onClick:()=>je.mutate(bt.id),children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),bt.user_id!==(s==null?void 0:s.id)?"Remove (Moderate)":"Delete"]})]})]})]}),bt.is_pinned&&e.jsxs("div",{className:"flex items-center gap-2 mb-2 text-sm text-primary",children:[e.jsx(XS,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium",children:"Pinned"})]}),e.jsx("div",{className:"mb-3",children:e.jsx(CIe,{content:bt.content})}),bt.media.length>0&&e.jsx("div",{className:`grid gap-2 mb-3 ${bt.media.length===1?"grid-cols-1":bt.media.length===2?"grid-cols-2":bt.media.length===3?"grid-cols-3":"grid-cols-2"}`,children:bt.media.slice(0,4).map((xs,Lt)=>{const Jt=Lt===3&&bt.media.length>4,gt=bt.media.length-4;return e.jsxs("div",{className:`relative rounded-lg overflow-hidden bg-muted cursor-pointer group ${bt.media.length===1?"max-h-[500px]":bt.media.length===2?"aspect-[4/3]":"aspect-square"}`,onClick:()=>Te({open:!0,images:bt.media.map(zt=>({url:zt.media_url,type:zt.media_type==="video"?"video":"image"})),index:Lt}),children:[xs.media_type==="video"?e.jsx("video",{src:xs.media_url,className:"w-full h-full object-cover transition-transform group-hover:scale-105"}):e.jsx("img",{src:xs.media_url,alt:"",className:"w-full h-full object-cover transition-transform group-hover:scale-105"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-colors flex items-center justify-center",children:e.jsx("div",{className:"opacity-0 group-hover:opacity-100 transition-opacity text-white",children:e.jsx("svg",{xmlns:"http://www.w3.org/2000/svg",className:"h-8 w-8",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,d:"M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0zM10 7v3m0 0v3m0-3h3m-3 0H7"})})})}),Jt&&e.jsx("div",{className:"absolute inset-0 bg-black/60 flex items-center justify-center",children:e.jsxs("span",{className:"text-white text-2xl font-bold",children:["+",gt]})})]},xs.id)})}),bt.link_url&&e.jsxs("a",{href:bt.link_url,target:"_blank",rel:"noopener noreferrer",className:"block rounded-lg border hover:bg-muted transition-colors mb-3 overflow-hidden",children:[bt.link_image&&e.jsx("div",{className:"aspect-video bg-muted",children:e.jsx("img",{src:bt.link_image,alt:bt.link_title||"Link preview",className:"w-full h-full object-cover",onError:xs=>{xs.currentTarget.style.display="none"}})}),e.jsx("div",{className:"p-3",children:bt.link_title?e.jsxs(e.Fragment,{children:[e.jsx("p",{className:"font-medium text-foreground line-clamp-2",children:bt.link_title}),bt.link_description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mt-1",children:bt.link_description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 truncate",children:new URL(bt.link_url).hostname})]}):e.jsxs("div",{className:"flex items-center gap-2 text-sm text-primary",children:[e.jsx(Yo,{className:"h-4 w-4 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:bt.link_url})]})})]}),bt.reactions.length>0&&e.jsx(T0t,{reactions:bt.reactions,children:e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-sm text-muted-foreground hover:text-foreground transition-colors cursor-pointer",children:[e.jsx("div",{className:"flex -space-x-1",children:Object.entries(at(bt.reactions)).slice(0,3).map(([xs])=>{var Lt;return e.jsx("span",{className:"text-base",children:(Lt=RH.find(Jt=>Jt.type===xs))==null?void 0:Lt.emoji},xs)})}),e.jsx("span",{children:bt.reactions.length})]})}),e.jsxs("div",{className:"flex items-center gap-1 border-t border-b py-1 my-2",children:[e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",children:[Ye(bt.reactions)?e.jsx("span",{className:"mr-1",children:($t=RH.find(xs=>xs.type===Ye(bt.reactions)))==null?void 0:$t.emoji}):e.jsx($m,{className:"h-4 w-4 mr-1"}),Ye(bt.reactions)?(Yt=RH.find(xs=>xs.type===Ye(bt.reactions)))==null?void 0:Yt.label:"Like"]})}),e.jsx(el,{className:"w-auto p-2",side:"top",children:e.jsx("div",{className:"flex gap-1",children:RH.map(xs=>e.jsx("button",{onClick:()=>$e.mutate({postId:bt.id,reactionType:xs.type}),className:"text-2xl hover:scale-125 transition-transform p-1",title:xs.label,children:xs.emoji},xs.type))})})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"flex-1",onClick:()=>W(xs=>{const Lt=new Set(xs);return Lt.has(bt.id)?Lt.delete(bt.id):Lt.add(bt.id),Lt}),children:[e.jsx(Zl,{className:"h-4 w-4 mr-1"}),(()=>{const xs=ut(bt.comments);return xs>0?`Comment (${xs})`:"Comment"})()]})]}),Y.has(bt.id)&&e.jsxs("div",{className:"space-y-3 mt-3",children:[bt.comments.map(xs=>e.jsx(E0t,{comment:xs,postId:bt.id,currentUserId:s==null?void 0:s.id,currentUserAvatar:a,currentUserEmail:s==null?void 0:s.email,canModerate:_t(bt)},xs.id)),s&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:a||void 0}),e.jsx(ea,{className:"text-xs",children:tt(((Ds=s.email)==null?void 0:Ds.split("@")[0])||"U")})]}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsx(gxe,{placeholder:"Write a comment... (use @ to mention)",value:ee[bt.id]||"",onChange:xs=>se(Lt=>({...Lt,[bt.id]:xs})),onMentionsChange:xs=>he(Lt=>({...Lt,[bt.id]:xs})),mentionFormat:"plain",onKeyDown:xs=>{var Lt;xs.defaultPrevented||xs.key==="Enter"&&!xs.shiftKey&&((Lt=ee[bt.id])!=null&&Lt.trim())&&(xs.preventDefault(),Ke.mutate({postId:bt.id,content:ee[bt.id]}))},className:"text-sm min-h-0 py-1.5",minHeight:"32px"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var xs;(xs=ee[bt.id])!=null&&xs.trim()&&Ke.mutate({postId:bt.id,content:ee[bt.id]})},disabled:!((Ls=ee[bt.id])!=null&&Ls.trim()),className:"h-8 px-2 mt-0.5",children:e.jsx(lr,{className:"h-4 w-4"})})]})]})]})]})},bt.id)}),Ae&&e.jsx("div",{className:"flex justify-center pt-2",children:e.jsx(B,{variant:"outline",onClick:()=>Be(),disabled:we,children:we?"Loading…":"Load more posts"})})]}),e.jsx(_s,{open:!!F,onOpenChange:()=>z(null),children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Edit Post"})}),e.jsx(Ms,{value:H,onChange:bt=>Z(bt.target.value),className:"min-h-[120px]"}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>z(null),children:"Cancel"}),e.jsx(B,{onClick:()=>{F&&it.mutate({postId:F.id,content:H})},disabled:!H.trim(),children:"Save Changes"})]})]})}),e.jsx(Z1s,{images:ge.images,initialIndex:ge.index,open:ge.open,onOpenChange:bt=>Te($t=>({...$t,open:bt}))})]})]})})},ebs=50*1024*1024;function A0t({value:s,onChange:t,disabled:n}){const{user:r}=vs(),a=N.useRef(null),[i,l]=N.useState(!1),o=async d=>{if(!d||!r)return;const u=[];l(!0);try{for(const h of Array.from(d)){if(!h.type.startsWith("image/")&&!h.type.startsWith("video/")){ae.error(`${h.name}: only images and videos allowed`);continue}if(h.size>ebs){ae.error(`${h.name}: must be under 50MB`);continue}const p=h.name.split(".").pop()||"bin",f=`${r.id}/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${p}`,{error:y}=await q.storage.from("support-attachments").upload(f,h,{contentType:h.type,upsert:!1});if(y){ae.error(`${h.name}: ${y.message}`);continue}u.push({path:f,type:h.type,name:h.name,size:h.size})}u.length&&t([...s,...u])}finally{l(!1),a.current&&(a.current.value="")}},c=async d=>{const u=s[d];t(s.filter((h,p)=>p!==d)),await q.storage.from("support-attachments").remove([u.path])};return e.jsxs("div",{className:"space-y-2",children:[s.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2 px-2 py-1 rounded-md border bg-muted/40 text-xs",children:[d.type.startsWith("video/")?e.jsx(G7,{className:"h-3.5 w-3.5 text-muted-foreground"}):e.jsx(q2,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"max-w-[160px] truncate",children:d.name}),e.jsx("button",{type:"button",onClick:()=>c(u),className:"text-muted-foreground hover:text-foreground",children:e.jsx($n,{className:"h-3 w-3"})})]},d.path))}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var d;return(d=a.current)==null?void 0:d.click()},disabled:n||i,className:"gap-1.5",children:[i?e.jsx(rs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(YS,{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 M0t({attachments:s}){const[t,n]=N.useState({}),[r,a]=N.useState(!0);return N.useEffect(()=>{if(!(s!=null&&s.length)){a(!1);return}let i=!1;return(async()=>{const l=s.map(d=>d.path),{data:o}=await q.storage.from("support-attachments").createSignedUrls(l,60*60*24);if(i||!o)return;const c={};o.forEach((d,u)=>{d.signedUrl&&(c[l[u]]=d.signedUrl)}),n(c),a(!1)})(),()=>{i=!0}},[s]),s!=null&&s.length?r?e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-2",children:[e.jsx(rs,{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 TI={open:{label:"Open",icon:pr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Zl,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Pi,color:"bg-green-500"},closed:{label:"Closed",icon:Uc,color:"bg-muted-foreground"}},yHe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function tbs(){const{user:s}=vs(),t=Kt(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState([]),{data:c=[],isLoading:d}=dt({queryKey:["support-tickets"],queryFn:async()=>{const{data:f,error:y}=await q.from("support_tickets").select("*").eq("user_id",s==null?void 0:s.id).order("created_at",{ascending:!1});if(y)throw y;return f},enabled:!!s}),{data:u=[]}=dt({queryKey:["ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:f,error:y}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(y)throw y;return f},enabled:!!n}),h=yt({mutationFn:async({content:f,attachments:y})=>{if(!n||!s)throw new Error("Missing data");const{error:_}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:f,is_admin_reply:!1,attachments:y});if(_)throw _},onSuccess:()=>{t.invalidateQueries({queryKey:["ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),p=()=>{!a.trim()&&l.length===0||h.mutate({content:a,attachments:l})};if(n){const f=TI[n.status].icon;return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(qr,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ue,{variant:"secondary",children:yHe[n.category]}),e.jsxs(Ue,{className:TI[n.status].color,children:[e.jsx(f,{className:"h-3 w-3 mr-1"}),TI[n.status].label]})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Vn,{children:["Created on ",Ss(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ee,{children:[e.jsx(di,{className:"h-[300px] pr-4",children:u.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:u.map(y=>{var _;return e.jsxs("div",{className:`p-4 rounded-lg ${y.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:y.is_admin_reply?"Support Team":((_=y.profiles)==null?void 0:_.name)||"You"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(y.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:y.content}),y.attachments&&y.attachments.length>0&&e.jsx(M0t,{attachments:y.attachments})]},y.id)})})}),n.status!=="closed"&&e.jsxs(e.Fragment,{children:[e.jsx(al,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Type your reply...",value:a,onChange:y=>i(y.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:p,disabled:!a.trim()&&l.length===0||h.isPending,className:"self-end",children:e.jsx(lr,{className:"h-4 w-4"})})]}),e.jsx(A0t,{value:l,onChange:o,disabled:h.isPending})]})]})]})]})]})})}return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{className:"bg-gradient-to-br from-primary/10 via-primary/5 to-background border-primary/20",children:e.jsx(Ee,{className:"p-6 sm:p-8",children:e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center gap-6",children:[e.jsx("div",{className:"p-4 bg-primary/20 rounded-full",children:e.jsx(q_,{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(Y4e,{trigger:e.jsxs(B,{size:"lg",className:"gap-2",children:[e.jsx(Is,{className:"h-5 w-5"}),"Submit a Ticket"]})}),e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2 bg-muted rounded-lg",children:[e.jsx(Cr,{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(Y4e,{trigger:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"New Ticket"]})})]}),d?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):c.length===0?e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"text-center py-12",children:[e.jsx(Zl,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No tickets yet"}),e.jsx("p",{className:"text-muted-foreground",children:"You haven't submitted any support tickets. Use the button above to get started!"})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{const y=TI[f.status].icon;return e.jsx(fe,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(f),children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:f.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ue,{variant:"outline",className:"text-xs",children:yHe[f.category]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(f.created_at),"MMM d, yyyy")})]})]}),e.jsxs(Ue,{className:TI[f.status].color,children:[e.jsx(y,{className:"h-3 w-3 mr-1"}),TI[f.status].label]})]})})},f.id)})})]})})}function sbs({open:s,onOpenChange:t}){return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(js,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(yr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(ws,{children:"Schedule Agent Onboarding"}),e.jsx(Jn,{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 nbs({open:s,onOpenChange:t}){const{brokerageId:n}=vs(),[r,a]=N.useState(""),[i,l]=N.useState([]),[o,c]=N.useState(!1),{data:d,isLoading:u}=dt({queryKey:["brokerage-agents-for-onboarding",n],queryFn:async()=>{if(!n)return[];const{data:_,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name",{ascending:!0});if(v)throw v;return _},enabled:s&&!!n}),h=d==null?void 0:d.filter(_=>_.name.toLowerCase().includes(r.toLowerCase())||_.email.toLowerCase().includes(r.toLowerCase())),p=_=>{l(v=>v.includes(_)?v.filter(j=>j!==_):[...v,_])},f=async()=>{if(i.length===0){ae.error("Please select at least one agent");return}c(!0);try{const{data:_,error:v}=await q.functions.invoke("send-onboarding-link",{body:{agentIds:i}});if(v)throw v;ae.success(`Onboarding link sent to ${i.length} agent${i.length>1?"s":""}`),l([]),t(!1)}catch(_){console.error("Error sending onboarding link:",_),ae.error(_.message||"Failed to send onboarding link")}finally{c(!1)}},y=_=>{_||(l([]),a("")),t(_)};return e.jsx(_s,{open:s,onOpenChange:y,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{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(lr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(ws,{children:"Send Onboarding Link"}),e.jsx(Jn,{children:"Select agents to receive the onboarding booking link"})]})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:r,onChange:_=>a(_.target.value),className:"pl-10"})]}),u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):(h==null?void 0:h.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(An,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No agents found"})]}):e.jsx(di,{className:"h-[300px] border rounded-lg",children:e.jsx("div",{className:"p-2 space-y-1",children:h==null?void 0:h.map(_=>e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted cursor-pointer",onClick:()=>p(_.id),children:[e.jsx(hi,{checked:i.includes(_.id),onCheckedChange:()=>p(_.id)}),e.jsx(Jr,{className:"h-8 w-8",children:e.jsx(ea,{className:"text-xs",children:_.name.split(" ").map(v=>v[0]).join("").toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:_.name}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:_.email})]})]},_.id))})}),i.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[i.length," agent",i.length>1?"s":""," selected"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(B,{onClick:f,disabled:i.length===0||o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Send Link"]})})]})]})})}function rbs(){const[s,t]=N.useState(!1),[n,r]=N.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"mb-8",children:[e.jsx(It,{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(An,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rt,{children:"Agent Onboarding"}),e.jsx(Vn,{children:"Schedule onboarding sessions for yourself or your agents"})]})]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex flex-wrap gap-4",children:[e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Schedule Agent Onboarding"]}),e.jsxs(B,{variant:"outline",onClick:()=>r(!0),className:"flex items-center gap-2",children:[e.jsx(lr,{className:"h-4 w-4"}),"Send New Agent Onboarding Link"]})]})})]}),e.jsx(sbs,{open:s,onOpenChange:t}),e.jsx(nbs,{open:n,onOpenChange:r})]})}function abs({open:s,onOpenChange:t}){return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-hidden",children:[e.jsx(js,{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(tx,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(ws,{children:"Schedule Launch Meeting"}),e.jsx(Jn,{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 ibs(){const[s,t]=N.useState(!1);return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"mb-8",children:[e.jsx(It,{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(tx,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rt,{children:"Launch or ReLaunch Meeting"}),e.jsx(Vn,{children:"Schedule a private LevelUp information session for your brokerage. Have one of our staff host a meeting to help your team get the most out of all our trainings, tools, and resources."})]})]})}),e.jsx(Ee,{children:e.jsxs(B,{onClick:()=>t(!0),className:"flex items-center gap-2",children:[e.jsx(tx,{className:"h-4 w-4"}),"Schedule Launch Meeting"]})})]}),e.jsx(abs,{open:s,onOpenChange:t})]})}function obs(){const s=Ln(),[t,n]=N.useState(""),[r,a]=N.useState(null),{data:i,isLoading:l}=dt({queryKey:["brokerage-resources-published"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resources").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(v)throw v;return _}}),{data:o}=dt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(v)throw v;return _}}),{data:c}=dt({queryKey:["brokerage-resource-pdfs-all"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resource_pdfs").select("resource_id");if(v)throw v;return _}}),{data:d}=dt({queryKey:["brokerage-resource-videos-all"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resource_videos").select("resource_id");if(v)throw v;return _}}),{data:u}=dt({queryKey:["brokerage-resource-links-all"],queryFn:async()=>{const{data:_,error:v}=await q.from("brokerage_resource_links").select("resource_id");if(v)throw v;return _}}),h=i==null?void 0:i.filter(_=>{var w;const v=_.title.toLowerCase().includes(t.toLowerCase())||((w=_.description)==null?void 0:w.toLowerCase().includes(t.toLowerCase())),j=!r||_.category_id===r;return v&&j}),p=o==null?void 0:o.filter(_=>i==null?void 0:i.some(v=>v.category_id===_.id)),f=_=>{const v=(c==null?void 0:c.filter(S=>S.resource_id===_).length)||0,j=(d==null?void 0:d.filter(S=>S.resource_id===_).length)||0,w=(u==null?void 0:u.filter(S=>S.resource_id===_).length)||0;return{pdfCount:v,videoCount:j,linkCount:w}},y=_=>{s(`/brokerage-resources/${_}`)};return e.jsx(Cs,{title:"Brokerage Resources",description:"Access exclusive resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(rbs,{}),e.jsx(ibs,{}),e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search resources...",value:t,onChange:_=>n(_.target.value),className:"pl-10"})]}),p&&p.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(Ue,{variant:r===null?"default":"outline",className:"cursor-pointer",onClick:()=>a(null),children:"All"}),p.map(_=>e.jsx(Ue,{variant:r===_.id?"default":"outline",className:"cursor-pointer",onClick:()=>a(_.id),children:_.name},_.id))]}),!l&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(h==null?void 0:h.length)||0," resource",(h==null?void 0:h.length)!==1?"s":""," available"]}),l?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:[...Array(6)].map((_,v)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-40 w-full"}),e.jsx(It,{children:e.jsx(Ws,{className:"h-5 w-3/4"})}),e.jsxs(Ee,{children:[e.jsx(Ws,{className:"h-4 w-full mb-2"}),e.jsx(Ws,{className:"h-4 w-2/3"})]})]},v))}):(h==null?void 0:h.length)===0?e.jsxs(fe,{className:"p-12 text-center",children:[e.jsx(zm,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No resources found"}),e.jsx("p",{className:"text-muted-foreground",children:t||r?"Try adjusting your filters":"Check back later for new resources"})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6",children:h==null?void 0:h.map(_=>{const{pdfCount:v,videoCount:j,linkCount:w}=f(_.id),S=o==null?void 0:o.find(A=>A.id===_.category_id);return e.jsxs(fe,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>y(_.id),children:[_.preview_image_url?e.jsx("img",{src:_.preview_image_url,alt:_.title,className:"w-full h-40 object-cover"}):e.jsx("div",{className:"w-full h-40 bg-muted flex items-center justify-center",children:e.jsx(zm,{className:"h-16 w-16 text-muted-foreground"})}),e.jsx(It,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Rt,{className:"text-lg line-clamp-1",children:_.title}),S&&e.jsx(Ue,{variant:"secondary",className:"shrink-0 text-xs",children:S.name})]})}),e.jsxs(Ee,{children:[_.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3",children:_.description}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[v>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-4 w-4"}),v]}),j>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fr,{className:"h-4 w-4"}),j]}),w>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yo,{className:"h-4 w-4"}),w]})]})]})]},_.id)})})]})})}const lbs=()=>{const{resourceId:s}=bi(),{data:t,isLoading:n}=dt({queryKey:["brokerage-resource-detail",s],queryFn:async()=>{const{data:a,error:i}=await q.from("brokerage_resources").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;const{data:l}=await q.from("brokerage_resource_pdfs").select("*").eq("resource_id",s).order("sort_order"),{data:o}=await q.from("brokerage_resource_videos").select("*").eq("resource_id",s).order("sort_order"),{data:c}=await q.from("brokerage_resource_links").select("*").eq("resource_id",s).order("sort_order");return{...a,pdfs:l||[],videos:o||[],links:c||[]}},enabled:!!s}),r=a=>a?a<1024?a+" B":a<1024*1024?(a/1024).toFixed(1)+" KB":(a/(1024*1024)).toFixed(1)+" MB":"";return n?e.jsx(Cs,{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(Cs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(In,{to:"/brokerage-resources",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back to Resources"]})}),t.preview_image_url&&e.jsx("div",{className:"relative w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:t.preview_image_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),t.description&&e.jsx("div",{className:"text-muted-foreground prose prose-sm max-w-none dark:prose-invert",dangerouslySetInnerHTML:{__html:t.description}})]}),t.videos&&t.videos.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(fr,{className:"h-4 w-4"}),"Videos (",t.videos.length,")"]}),e.jsx("div",{className:"space-y-4",children:t.videos.map(a=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:a.title}),e.jsx("div",{className:"relative w-full",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:a.video_url,className:"absolute top-0 left-0 w-full h-full rounded-lg border",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})]},a.id))})]})}),t.pdfs&&t.pdfs.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(br,{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(br,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:a.name}),a.file_size&&e.jsx("div",{className:"text-xs text-muted-foreground",children:r(a.file_size)})]})]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})}),t.links&&t.links.length>0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("h3",{className:"font-semibold flex items-center gap-2 mb-4",children:[e.jsx(tr,{className:"h-4 w-4"}),"Canva Templates (",t.links.length,")"]}),e.jsx("div",{className:"grid gap-2",children:t.links.map(a=>e.jsxs("a",{href:a.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted transition-colors group",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(tr,{className:"h-4 w-4 text-primary"})}),e.jsx("div",{className:"font-medium text-sm",children:a.title})]}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors"})]},a.id))})]})})]})}):e.jsx(Cs,{title:"Brokerage Resources",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(zm,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Resource not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This resource may have been removed or is not available."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(In,{to:"/brokerage-resources",children:"Back to Resources"})})]})})};function cbs(){const{onlineUsers:s,totalOnline:t}=qat();return e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4"}),"Online Now"]}),e.jsxs(Ue,{variant:"secondary",className:"bg-green-100 text-green-700",children:[e.jsx(am,{className:"h-2 w-2 fill-green-500 text-green-500 mr-1"}),t," online"]})]})}),e.jsx(Ee,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No other users online right now"}):e.jsx(di,{className:"h-[300px] pr-4",children:e.jsx("div",{className:"space-y-3",children:s.map(n=>{var r;return e.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-lg hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"relative",children:[e.jsxs(Jr,{className:"h-9 w-9",children:[e.jsx(ti,{src:n.avatarUrl,alt:n.name}),e.jsx(ea,{className:"text-xs",children:(r=n.name)==null?void 0:r.split(" ").map(a=>a[0]).join("").slice(0,2).toUpperCase()})]}),e.jsx("span",{className:"absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full bg-green-500 ring-2 ring-background"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:n.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Online ",Uo(new Date(n.onlineSince),{addSuffix:!1})]})]})]},n.id)})})})})]})}const vHe={users:{label:"Users & Access",sections:[{title:"Members",description:"Manage users, roles, and brokerage assignments",icon:An,path:"/admin/members",color:"bg-blue-500/10 text-blue-600"},{title:"Invite Codes",description:"Create and manage signup invite codes",icon:k9,path:"/admin/invite-codes",color:"bg-amber-500/10 text-amber-600"},{title:"Subscriptions",description:"Track and manage user subscriptions",icon:uf,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:U7,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:oh,path:"/admin/discounts",color:"bg-red-500/10 text-red-600"},{title:"Referral Program",description:"Track brokerage referrals and discounts",icon:Vl,path:"/admin/referrals",color:"bg-teal-500/10 text-teal-600"},{title:"Teams",description:"Manage agent teams across all brokerages",icon:An,path:"/admin/members?tab=teams",color:"bg-violet-500/10 text-violet-600"},{title:"Prospector",description:"Send free trial invites and track conversions",icon:Ac,path:"/admin/prospector",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Recruiting",description:"Manage agent recruit pipeline and outreach",icon:Fo,path:"/admin/recruiting",color:"bg-gradient-to-br from-emerald-500/20 to-green-500/10 text-emerald-600"},{title:"Coaching",description:"Promote coaches and manage agent coaching assignments",icon:xo,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:pl,path:"/admin/templates",color:"bg-pink-500/10 text-pink-600"},{title:"Manage Programs",description:"Cohorts, enrollments and delayed billing",icon:yd,path:"/admin/programs",color:"bg-emerald-500/10 text-emerald-600"},{title:"Manage Academy",description:"Upload videos and training content",icon:yd,path:"/admin/academy",color:"bg-indigo-500/10 text-indigo-600"},{title:"Manage Toolbox",description:"Create and manage resource kits",icon:gb,path:"/admin/toolbox",color:"bg-orange-500/10 text-orange-600"},{title:"Social Swag",description:"Manage social media content and links",icon:un,path:"/admin/social-swag",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Social Swag 2.0",description:"New monthly social media images",icon:un,path:"/admin/social-swag-2",color:"bg-cyan-500/10 text-cyan-600"},{title:"Newsletters",description:"Manage monthly newsletter templates",icon:sy,path:"/admin/newsletters",color:"bg-violet-500/10 text-violet-600"},{title:"Newsletter Graphics",description:"Upload branded graphics agents drop into newsletters & emails",icon:sy,path:"/admin/newsletter-graphics",color:"bg-fuchsia-500/10 text-fuchsia-600"},{title:"Manage Events",description:"Create and publish events with Zoom integration",icon:Cl,path:"/admin/events",color:"bg-green-500/10 text-green-600"},{title:"LevelUp Live",description:"Public streaming pages, invite links, and live leads",icon:yf,path:"/admin/live",color:"bg-red-500/10 text-red-600"},{title:"Additional Services",description:"Manage additional service offerings",icon:zm,path:"/admin/additional-services",color:"bg-lime-500/10 text-lime-600"},{title:"Brokerage Resources",description:"Manage resources for brokerage managers",icon:zm,path:"/admin/brokerage-resources",color:"bg-slate-500/10 text-slate-600"},{title:"Agent Email Templates",description:"Manage curated email templates for agents",icon:Gs,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:zd,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:GS,path:"/admin/dashboard-management",color:"bg-teal-500/10 text-teal-600"},{title:"Manage Apps",description:"Configure app tiles and access requirements",icon:mv,path:"/admin/apps",color:"bg-purple-500/10 text-purple-600"},{title:"Email Templates",description:"Customize system email templates",icon:Gs,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:zd,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:KP,path:"/admin/onboarding-checklist",color:"bg-emerald-500/10 text-emerald-600"},{title:"Marketplace",description:"Manage store categories, products, and orders",icon:yw,path:"/admin/marketplace",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"Reward Store",description:"Manage reward items agents can redeem with points",icon:Oi,path:"/admin/reward-store",color:"bg-purple-500/10 text-purple-600"},{title:"Agent Points",description:"View agent points, leaderboard, and award bonus points",icon:xo,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:An,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:zd,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:Ai,path:"/admin/community",color:"bg-cyan-500/10 text-cyan-600"},{title:"Support Tickets",description:"View and respond to agent support requests",icon:eL,path:"/admin/support-tickets",color:"bg-rose-500/10 text-rose-600"},{title:"Wishlist",description:"Review and manage community feature requests",icon:W2,path:"/admin/wishlist",color:"bg-yellow-500/10 text-yellow-600"},{title:"Membership Reviews",description:"View member feedback and ratings",icon:oa,path:"/admin/membership-reviews",color:"bg-amber-500/10 text-amber-600"},{title:"Weekly Digest",description:"Configure automated weekly email digests",icon:Gs,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:_o,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:rm,path:"/admin/brokerage-content-activity",color:"bg-sky-500/10 text-sky-600"},{title:"Music Videos",description:"View all listing music videos created by agents across the platform",icon:ny,path:"/admin/music-videos",color:"bg-gradient-to-br from-pink-500/20 to-rose-500/10 text-pink-600"}]},lms:{label:"LevelUp U",sections:[{title:"Manage Courses",description:"Create and manage LMS training courses, modules, and access",icon:yd,path:"/admin/lms",color:"bg-gradient-to-br from-primary/20 to-primary/10 text-primary"}]},"agent-os":{label:"Agent OS",sections:[{title:"Agent OS Control Center",description:"Manage InnerCircle feature: relationship types, action types, scripts, plans & feature flags",icon:gi,path:"/admin/agent-os",color:"bg-gradient-to-br from-rose-500/20 to-pink-500/10 text-rose-600"},{title:"Listing Exchange",description:"Approve, feature, and moderate community listings",icon:Or,path:"/admin/listing-exchange",color:"bg-gradient-to-br from-blue-500/20 to-sky-500/10 text-blue-600"},{title:"Listing Leads",description:"View all leads from the public listings site with property & agent assignment",icon:Fo,path:"/admin/listing-leads",color:"bg-gradient-to-br from-teal-500/20 to-emerald-500/10 text-teal-600"},{title:"Public Site Leads",description:"Alerts signups, exit-intent captures & saved-home leads from listings.relevelup.com",icon:Fo,path:"/admin/public-site-leads",color:"bg-gradient-to-br from-amber-500/20 to-orange-500/10 text-amber-600"},{title:"Presentation Analytics",description:"Track agent presentation usage, views, and leads",icon:ny,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:rm,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:Xo,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:Gs,path:"/admin/beta/postcard-manager",color:"bg-gradient-to-br from-orange-500/20 to-amber-500/10 text-orange-600"},{title:"ReelFlow",description:"Turn property photos into cinematic video reels for social media",icon:qS,path:"/admin/beta/homereel",color:"bg-gradient-to-br from-violet-500/20 to-indigo-500/10 text-violet-600"}]},"lead-sites":{label:"Lead Sites",sections:[{title:"All Sites",description:"Overview of all agent websites with status and quick actions",icon:lc,path:"/admin/lead-sites",color:"bg-gradient-to-br from-sky-500/20 to-blue-500/10 text-sky-600"},{title:"MLS Feeds",description:"Manage MLS data feed connections, API keys, and coverage areas",icon:q7,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:go,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:br,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:br,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:Yl,path:"/admin/mls-fee-tracker",color:"bg-gradient-to-br from-teal-500/20 to-cyan-500/10 text-teal-600"}]}};function bHe(){const s=Ln();return console.log("[AdminDashboard] render"),e.jsx(Cs,{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(cbs,{})})]}),e.jsxs(Fr,{defaultValue:"users",className:"w-full",children:[e.jsx(Rr,{className:"w-full justify-start flex-wrap h-auto gap-1 bg-muted/50 p-1 overflow-x-auto",children:Object.entries(vHe).map(([t,n])=>e.jsx(Zt,{value:t,className:"data-[state=active]:bg-background",children:n.label},t))}),Object.entries(vHe).map(([t,n])=>e.jsx(is,{value:t,className:"mt-6",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:n.sections.map(r=>e.jsxs(fe,{className:"cursor-pointer hover:shadow-md transition-all hover:border-primary/50 group",onClick:()=>s(r.path),children:[e.jsxs(It,{className:"pb-3",children:[e.jsx("div",{className:`w-10 h-10 rounded-lg flex items-center justify-center ${r.color} mb-2 group-hover:scale-110 transition-transform`,children:e.jsx(r.icon,{className:"h-5 w-5"})}),e.jsx(Rt,{className:"text-base",children:r.title})]}),e.jsx(Ee,{className:"pt-0",children:e.jsx(Vn,{className:"text-sm",children:r.description})})]},r.path))})},t))]})]})})}const dbs=()=>{const{isAdmin:s}=vs(),t=Ln(),[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(!1),[c,d]=N.useState(null);N.useEffect(()=>{if(!s){t("/dashboard");return}u()},[s]);const u=async()=>{try{const{data:_,error:v}=await q.from("app_tiles").select("*").order("name");if(v)throw v;r(_||[])}catch(_){console.error("Error loading apps:",_),ae.error("Failed to load apps")}finally{i(!1)}},h=async _=>{_.preventDefault();const v=new FormData(_.currentTarget),j={name:v.get("name"),description:v.get("description"),icon:v.get("icon"),app_id:v.get("app_id"),target_url:v.get("target_url"),required_tags:v.get("required_tags").split(",").map(w=>w.trim()).filter(Boolean)};try{if(c){const{error:w}=await q.from("app_tiles").update(j).eq("id",c.id);if(w)throw w;ae.success("App updated successfully")}else{const{error:w}=await q.from("app_tiles").insert([j]);if(w)throw w;ae.success("App created successfully")}o(!1),d(null),u()}catch(w){console.error("Error saving app:",w),ae.error("Failed to save app")}},p=async _=>{if(confirm("Are you sure you want to delete this app?"))try{const{error:v}=await q.from("app_tiles").delete().eq("id",_);if(v)throw v;ae.success("App deleted successfully"),u()}catch(v){console.error("Error deleting app:",v),ae.error("Failed to delete app")}},f=_=>{d(_),o(!0)},y=()=>{d(null),o(!0)};return a?e.jsx("div",{className:"flex items-center justify-center min-h-screen",children:"Loading..."}):e.jsxs("div",{className:"min-h-screen bg-background",children:[e.jsx("header",{className:"border-b bg-card",children:e.jsx("div",{className:"container mx-auto px-4 py-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/dashboard"),children:[e.jsx(qr,{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(_s,{open:l,onOpenChange:o,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{onClick:y,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Add App"]})}),e.jsxs(bs,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(ws,{children:c?"Edit App":"Create New App"}),e.jsx(Jn,{children:"Configure the application tile settings"})]}),e.jsxs("form",{onSubmit:h,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"name",children:"App Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:c==null?void 0:c.name,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"app_id",children:"App ID"}),e.jsx(ye,{id:"app_id",name:"app_id",defaultValue:c==null?void 0:c.app_id,placeholder:"agent_connect",required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:c==null?void 0:c.description})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"icon",children:"Icon (emoji)"}),e.jsx(ye,{id:"icon",name:"icon",defaultValue:c==null?void 0:c.icon,placeholder:"🚀",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"target_url",children:"Target URL"}),e.jsx(ye,{id:"target_url",name:"target_url",type:"url",defaultValue:c==null?void 0:c.target_url,required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"required_tags",children:"Required Tags (comma-separated)"}),e.jsx(ye,{id:"required_tags",name:"required_tags",defaultValue:c==null?void 0:c.required_tags.join(", "),placeholder:"levelup-member, agent-connect"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{type:"submit",children:c?"Update":"Create"})]})]})]})]})]})})}),e.jsx("div",{className:"container mx-auto px-4 py-8",children:e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Application Tiles"}),e.jsx(Vn,{children:"Manage the apps that appear on the member dashboard"})]}),e.jsx(Ee,{children:n.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsxs(B,{onClick:y,children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create First App"]})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"App ID"}),e.jsx(Tt,{children:"Target URL"}),e.jsx(Tt,{children:"Tags"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:n.map(_=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"text-2xl",children:_.icon}),e.jsx(ht,{className:"font-medium",children:_.name}),e.jsx(ht,{className:"font-mono text-sm",children:_.app_id}),e.jsx(ht,{className:"text-sm text-muted-foreground max-w-xs truncate",children:_.target_url}),e.jsx(ht,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:_.required_tags.map(v=>e.jsx("span",{className:"text-xs bg-secondary text-secondary-foreground px-2 py-1 rounded",children:v},v))})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>f(_),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(_.id),children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},_.id))})]})})]})})]})};function Bd({title:s,description:t,children:n}){return e.jsxs("div",{className:"space-y-4",children:[e.jsx(In,{to:"/admin",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-2 text-muted-foreground hover:text-foreground",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back to Admin Dashboard"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:s}),t&&e.jsx("p",{className:"text-muted-foreground",children:t})]}),n]})]})}const _He=({expiresAt:s,className:t})=>{const n=new Date().getTime(),r=new Date(s).getTime(),a=Math.ceil((r-n)/(1e3*60*60*24));return a<=0?e.jsxs(Ue,{variant:"destructive",className:Mt("gap-1",t),children:[e.jsx(ic,{className:"h-3 w-3"}),"Trial Expired"]}):a<=1?e.jsxs(Ue,{variant:"destructive",className:Mt("gap-1",t),children:[e.jsx(pr,{className:"h-3 w-3"}),"Trial: <1 day left"]}):a<=3?e.jsxs(Ue,{className:Mt("gap-1 bg-amber-500 hover:bg-amber-600",t),children:[e.jsx(pr,{className:"h-3 w-3"}),"Trial: ",a," days left"]}):e.jsxs(Ue,{variant:"secondary",className:Mt("gap-1",t),children:[e.jsx(pr,{className:"h-3 w-3"}),"Trial: ",a," days left"]})},I0t=({open:s,onOpenChange:t,brokerages:n,fixedBrokerageId:r,onSuccess:a})=>{const{toast:i}=Fa(),l=N.useRef(null),[o,c]=N.useState([]),[d,u]=N.useState(""),[h,p]=N.useState(!1),[f,y]=N.useState("upload"),[_,v]=N.useState(null),j=()=>{c([]),u(""),y("upload"),v(null),l.current&&(l.current.value="")},w=()=>{j(),t(!1)},S=I=>{const F=I.split(` `).map(W=>W.trim()).filter(W=>W);if(F.length===0)return[];const z=F[0].toLowerCase(),Z=z.includes("first")||z.includes("last")||z.includes("email")||z.includes("name")||z.includes("phone")||z.includes("sms")||z.includes("consent")?F.slice(1):F,Y=[];for(const W of Z){const se=(W.includes(" ")?W.split(" "):W.split(",")).map(oe=>oe.trim().replace(/^["']|["']$/g,""));if(se.length>=2){let oe="",he="",ce="",me="",le;if(se.length===2){const Te=se[0].split(" ");oe=Te[0]||"",he=Te.slice(1).join(" ")||"",ce=se[1]}else if(se.length===3)oe=se[0],he=se[1],ce=se[2];else if(se.length===4)oe=se[0],he=se[1],ce=se[2],me=se[3];else if(se.length>=5){oe=se[0],he=se[1],ce=se[2],me=se[3];const Te=se[4].toLowerCase();le=Te==="true"||Te==="yes"||Te==="1"||Te==="y"}const ge=/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ce);Y.push({firstName:oe.trim(),lastName:he.trim(),email:ce.trim().toLowerCase(),phone:me.trim()||void 0,smsConsent:le,isValid:ge&&oe.trim().length>0,error:ge?oe.trim()?void 0:"Missing name":"Invalid email"})}}return Y},A=I=>{var H;const F=(H=I.target.files)==null?void 0:H[0];if(!F)return;const z=new FileReader;z.onload=Z=>{var ee;const Y=(ee=Z.target)==null?void 0:ee.result,W=S(Y);if(W.length===0){i({title:"No data found",description:"The CSV file appears to be empty or in an unsupported format.",variant:"destructive"});return}c(W),y("preview")},z.readAsText(F)},E=async()=>{const I=o.filter(z=>z.isValid);if(I.length===0){i({title:"No valid users",description:"There are no valid users to import.",variant:"destructive"});return}const F=r||d||null;p(!0);try{const{data:{session:z}}=await q.auth.getSession(),H=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:I.map(Y=>({firstName:Y.firstName,lastName:Y.lastName,email:Y.email,phone:Y.phone,smsConsent:Y.smsConsent})),brokerageId:F})}),Z=await H.json();if(!H.ok)throw new Error(Z.error||"Failed to import users");v(Z),y("result"),Z.created>0&&a(),i({title:"Import Complete",description:`${Z.created} user(s) created successfully.${Z.failed>0?` ${Z.failed} failed.`:""}`})}catch(z){console.error("Import error:",z),i({title:"Import Failed",description:z.message||"Failed to import users",variant:"destructive"})}finally{p(!1)}},O=o.filter(I=>I.isValid).length,D=o.filter(I=>!I.isValid).length;return e.jsx(_s,{open:s,onOpenChange:w,children:e.jsxs(bs,{className:"max-w-2xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(mw,{className:"h-5 w-5"}),"Import Agents from CSV"]}),e.jsx(Jn,{children:"Upload a CSV file with agent information. Each row should contain First Name, Last Name, and Email."})]}),f==="upload"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx("input",{type:"file",accept:".csv,.txt",ref:l,onChange:A,className:"hidden"}),e.jsx(_a,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(B,{onClick:()=>{var I;return(I=l.current)==null?void 0:I.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Expected CSV Format:"}),e.jsxs("code",{className:"text-xs block bg-background p-2 rounded",children:["First Name, Last Name, Email, Phone, SMS Consent",e.jsx("br",{}),"John, Doe, john@example.com, 555-123-4567, yes",e.jsx("br",{}),"Jane, Smith, jane@example.com, 555-987-6543, true"]}),e.jsx("p",{className:"text-muted-foreground mt-2 text-xs",children:"Phone and SMS Consent columns are optional. SMS Consent accepts: yes/no, true/false, 1/0, y/n."})]})]}),f==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[!r&&n&&n.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Assign to Brokerage (optional)"}),e.jsxs(us,{value:d||"none",onValueChange:I=>u(I==="none"?"":I),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a brokerage..."})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No brokerage"}),n.map(I=>e.jsx(Ze,{value:I.id,children:I.name},I.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(vr,{className:"h-4 w-4 text-green-500"}),e.jsxs("span",{children:[O," valid"]})]}),D>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsxs("span",{children:[D," invalid"]})]})]}),e.jsxs("div",{className:"flex-1 overflow-auto border rounded-lg",children:[e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/30",children:[e.jsx(Tt,{children:"First Name"}),e.jsx(Tt,{children:"Last Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"SMS"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(da,{children:o.slice(0,100).map((I,F)=>e.jsxs(Hs,{children:[e.jsx(ht,{children:I.firstName}),e.jsx(ht,{children:I.lastName}),e.jsx(ht,{children:I.email}),e.jsx(ht,{className:"text-muted-foreground",children:I.phone||"-"}),e.jsx(ht,{className:"text-muted-foreground",children:I.smsConsent===!0?"✓":I.smsConsent===!1?"✗":"-"}),e.jsx(ht,{children:I.isValid?e.jsx(Ue,{variant:"default",className:"bg-green-500/10 text-green-600",children:"Valid"}):e.jsx(Ue,{variant:"destructive",children:I.error||"Invalid"})})]},F))})]}),o.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",o.length," users"]})]})]}),f==="result"&&_&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsx(vr,{className:"h-12 w-12 mx-auto text-green-500 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),e.jsxs("p",{className:"text-muted-foreground mt-2",children:[_.created," agent(s) created and invited"]}),_.failed>0&&e.jsxs("p",{className:"text-destructive mt-1",children:[_.failed," failed to create"]})]}),_.errors.length>0&&e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-4 max-h-40 overflow-auto",children:[e.jsx("p",{className:"font-medium text-destructive text-sm mb-2",children:"Errors:"}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1",children:[_.errors.slice(0,10).map((I,F)=>e.jsxs("li",{children:["• ",I]},F)),_.errors.length>10&&e.jsxs("li",{children:["...and ",_.errors.length-10," more"]})]})]})]}),e.jsxs(Xn,{children:[f==="upload"&&e.jsx(B,{variant:"outline",onClick:w,children:"Cancel"}),f==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:j,children:"Back"}),e.jsx(B,{onClick:E,disabled:h||O===0,children:h?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${O} Agent${O!==1?"s":""}`})]}),f==="result"&&e.jsx(B,{onClick:w,children:"Done"})]})]})})};function Sc({sortKey:s,currentSortKey:t,currentDirection:n,onSort:r,children:a,className:i,...l}){const o=t===s;return e.jsx(Tt,{className:Mt("cursor-pointer select-none",i),...l,children:e.jsxs("button",{type:"button",className:"flex items-center gap-1 font-semibold hover:text-foreground transition-colors w-full text-left",onClick:()=>r(s),children:[a,o?n==="asc"?e.jsx(Iu,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(sm,{className:"h-3.5 w-3.5 shrink-0"}):e.jsx(ah,{className:"h-3.5 w-3.5 shrink-0 opacity-40"})]})})}function xU(s=null,t=null){const[n,r]=N.useState(s),[a,i]=N.useState(t),l=N.useCallback(c=>{n===c?a==="asc"?i("desc"):a==="desc"?(r(null),i(null)):i("asc"):(r(c),i("asc"))},[n,a]),o=N.useCallback((c,d)=>{if(!n||!a||!d[n])return c;const u=d[n];return[...c].sort((h,p)=>{const f=u(h),y=u(p);if(f==null&&y==null)return 0;if(f==null)return 1;if(y==null)return-1;let _;return typeof f=="string"&&typeof y=="string"?_=f.localeCompare(y,void 0,{sensitivity:"base"}):_=f-y,a==="asc"?_:-_})},[n,a]);return{sortKey:n,sortDirection:a,handleSort:l,sortData:o}}const ubs=[{type:"custom",title:"Great job!",message:"Keep up the amazing work!",icon:oa},{type:"custom",title:"You're on fire!",message:"Your dedication is inspiring!",icon:xo},{type:"custom",title:"Congratulations!",message:"You earned this celebration!",icon:ih}];function P0t({open:s,onOpenChange:t,userId:n,userName:r}){const[a,i]=N.useState("custom"),[l,o]=N.useState(""),[c,d]=N.useState(""),u=m7t(),h=f=>{i(f.type),o(f.title),d(f.message)},p=async f=>{if(f.preventDefault(),!l.trim()){Br({title:"Title required",description:"Please enter a celebration title",variant:"destructive"});return}try{await u.mutateAsync({user_id:n,celebration_type:a,title:l.trim(),message:c.trim()||void 0}),Br({title:"Celebration sent! 🎉",description:`${r} will see confetti on their next visit!`}),t(!1),o(""),d(""),i("custom")}catch{Br({title:"Error",description:"Failed to send celebration",variant:"destructive"})}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(ih,{className:"h-5 w-5 text-primary"}),"Send Celebration to ",r]}),e.jsx(Jn,{children:"They'll see confetti and this message next time they log in!"})]}),e.jsxs("div",{className:"mb-4",children:[e.jsx(ne,{className:"text-sm text-muted-foreground mb-2 block",children:"Quick presets:"}),e.jsx("div",{className:"flex gap-2 flex-wrap",children:ubs.map((f,y)=>e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(f),className:"text-xs",children:[e.jsx(f.icon,{className:"h-3 w-3 mr-1"}),f.title]},y))})]}),e.jsxs("form",{onSubmit:p,className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"type",children:"Celebration Type"}),e.jsxs(us,{value:a,onValueChange:f=>i(f),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"custom",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(oa,{className:"h-4 w-4"})," Custom"]})}),e.jsx(Ze,{value:"points_earned",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-4 w-4"})," Points Earned"]})}),e.jsx(Ze,{value:"listing_created",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4"})," Listing Created"]})}),e.jsx(Ze,{value:"deal_closed",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-4 w-4"})," Deal Closed"]})})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:l,onChange:f=>o(f.target.value),placeholder:"e.g., Congratulations!",maxLength:100})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"message",children:"Message (optional)"}),e.jsx(Ms,{id:"message",value:c,onChange:f=>d(f.target.value),placeholder:"Add a personal message...",rows:3,maxLength:500})]}),e.jsxs("div",{className:"flex gap-2 justify-end",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[e.jsx(ih,{className:"h-4 w-4 mr-2"}),u.isPending?"Sending...":"Send Celebration"]})]})]})]})})}const b2e={points_earned:{label:"Points Earned",icon:xo,color:"bg-yellow-500"},listing_created:{label:"Listing Created",icon:Or,color:"bg-blue-500"},deal_closed:{label:"Deal Closed",icon:Yl,color:"bg-green-500"},custom:{label:"Custom",icon:un,color:"bg-purple-500"}};function hbs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),{data:l=[],isLoading:o}=dt({queryKey:["admin-celebrations"],queryFn:async()=>{const{data:u,error:h}=await q.from("celebration_queue").select("*").order("created_at",{ascending:!1}).limit(500);if(h)throw h;const p=[...new Set([...u.map(_=>_.user_id),...u.map(_=>_.created_by).filter(Boolean)])],{data:f}=await q.from("profiles").select("id, name, email").in("id",p),y=new Map((f==null?void 0:f.map(_=>[_.id,_]))||[]);return u.map(_=>{var v,j,w;return{..._,user_name:((v=y.get(_.user_id))==null?void 0:v.name)||"Unknown",user_email:((j=y.get(_.user_id))==null?void 0:j.email)||"",creator_name:_.created_by?((w=y.get(_.created_by))==null?void 0:w.name)||"System":"Auto-triggered"}})}}),c=l.filter(u=>{var y,_;const h=((y=u.user_name)==null?void 0:y.toLowerCase().includes(s.toLowerCase()))||((_=u.user_email)==null?void 0:_.toLowerCase().includes(s.toLowerCase()))||u.title.toLowerCase().includes(s.toLowerCase()),p=n==="all"||u.celebration_type===n,f=a==="all"||a==="seen"&&u.seen_at||a==="unseen"&&!u.seen_at;return h&&p&&f}),d={total:l.length,seen:l.filter(u=>u.seen_at).length,unseen:l.filter(u=>!u.seen_at).length,byType:Object.keys(b2e).reduce((u,h)=>(u[h]=l.filter(p=>p.celebration_type===h).length,u),{})};return o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium",children:"Total Celebrations"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.total})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-green-600",children:"Seen"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold text-green-600",children:d.seen})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-orange-600",children:"Pending"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold text-orange-600",children:d.unseen})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-purple-600",children:"Custom Sent"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold text-purple-600",children:d.byType.custom||0})})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(ih,{className:"h-5 w-5"}),"Celebration History"]}),e.jsx(Vn,{children:"View all celebrations awarded to agents"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by agent name, email, or title...",value:s,onChange:u=>t(u.target.value),className:"pl-9"})]}),e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Filter by type"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),Object.entries(b2e).map(([u,h])=>e.jsx(Ze,{value:u,children:h.label},u))]})]}),e.jsxs(us,{value:a,onValueChange:i,children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(hs,{placeholder:"Status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"seen",children:"Seen"}),e.jsx(Ze,{value:"unseen",children:"Pending"})]})]})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Points"}),e.jsx(Tt,{children:"Created By"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(da,{children:c.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No celebrations found"})}):c.map(u=>{const h=b2e[u.celebration_type],p=h.icon;return e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(p,{className:"h-3 w-3"}),h.label]})}),e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:u.user_name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:u.user_email})]})}),e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:u.title}),u.message&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:u.message})]})}),e.jsx(ht,{children:u.points_amount?e.jsxs(Ue,{variant:"secondary",children:["+",u.points_amount]}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ht,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:u.creator_name})}),e.jsx(ht,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(u.created_at),"MMM d, yyyy h:mm a")})}),e.jsx(ht,{children:u.seen_at?e.jsx(Ue,{variant:"outline",className:"bg-green-50 text-green-700 border-green-200",children:"Seen"}):e.jsx(Ue,{variant:"outline",className:"bg-orange-50 text-orange-700 border-orange-200",children:"Pending"})})]},u.id)})})]})}),c.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-right",children:["Showing ",c.length," of ",l.length," celebrations"]})]})]})]})}const mbs=()=>{const{user:s}=vs(),{toast:t}=Fa(),[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(!1),[c,d]=N.useState("all"),[u,h]=N.useState("all"),[p,f]=N.useState("new"),[y,_]=N.useState(new Set),v=N.useCallback(async()=>{try{i(!0);const{data:Y,error:W}=await q.from("profiles").select("id, name, email, phone, is_trial, trial_started_at, trial_expires_at, subscription_status, subscription_end_date, converted_from_trial_at, created_at, last_login").or("is_trial.eq.true,subscription_status.eq.trialing,converted_from_trial_at.not.is.null");if(W)throw W;const{data:ee,error:se}=await q.from("trial_email_exports").select("user_id");if(se)throw se;const oe=new Set((ee||[]).map(ce=>ce.user_id)),he=(Y||[]).map(ce=>({...ce,converted_from_trial_at:ce.converted_from_trial_at??null,already_exported:oe.has(ce.id)}));he.sort((ce,me)=>new Date(me.created_at).getTime()-new Date(ce.created_at).getTime()),r(he)}catch(Y){console.error("Error loading trial users:",Y),t({title:"Error",description:"Failed to load trial users",variant:"destructive"})}finally{i(!1)}},[t]);N.useEffect(()=>{v()},[v]);const j=Y=>Y.trial_started_at?"ghl":"stripe",w=Y=>Y.trial_expires_at?Y.trial_expires_at:Y.subscription_end_date?Y.subscription_end_date:null,S=Y=>Y.converted_from_trial_at!==null,A=Y=>{if(S(Y))return!1;const W=w(Y);return W?new Date(W).getTime()<=Date.now():!1},E=n.filter(Y=>!(c!=="all"&&j(Y)!==c||u==="active"&&(A(Y)||S(Y))||u==="expired"&&!A(Y)||u==="converted"&&!S(Y)||p==="new"&&Y.already_exported||p==="exported"&&!Y.already_exported)),O=()=>{y.size===E.length?_(new Set):_(new Set(E.map(Y=>Y.id)))},D=Y=>{const W=new Set(y);W.has(Y)?W.delete(Y):W.add(Y),_(W)},I=async()=>{if(y.size===0){t({title:"No users selected",description:"Select users to export",variant:"destructive"});return}o(!0);try{const Y=n.filter(le=>y.has(le.id)),W="First Name,Last Name,Email,Phone,Trial Type,Status,Signup Date,Expiry Date",ee=Y.map(le=>{const ve=(le.name||"").split(" "),ge=ve[0]||"",Te=ve.slice(1).join(" ")||"",Ie=j(le)==="stripe"?"Credit Card Trial":"Free Trial (No CC)",Ce=S(le)?"Converted":A(le)?"Expired":"Active",Me=le.created_at?new Date(le.created_at).toLocaleDateString():"",Pe=w(le)?new Date(w(le)).toLocaleDateString():"";return`"${ge}","${Te}","${le.email}","${le.phone||""}","${Ie}","${Ce}","${Me}","${Pe}"`}),se=[W,...ee].join(` `),oe=new Blob([se],{type:"text/csv"}),he=URL.createObjectURL(oe),ce=document.createElement("a");ce.href=he,ce.download=`trial-users-${new Date().toISOString().split("T")[0]}.csv`,ce.click(),URL.revokeObjectURL(he);const me=Y.filter(le=>!le.already_exported).map(le=>({user_id:le.id,exported_by:s.id}));if(me.length>0){const{error:le}=await q.from("trial_email_exports").upsert(me,{onConflict:"user_id"});le&&console.error("Error marking exports:",le)}t({title:"Export complete",description:`Downloaded ${Y.length} trial user(s). ${me.length} newly marked as exported.`}),_(new Set),v()}catch(Y){console.error("Export error:",Y),t({title:"Error",description:"Failed to export",variant:"destructive"})}finally{o(!1)}},F=n.filter(Y=>!Y.already_exported).length,z=n.filter(Y=>Y.already_exported).length,H=n.filter(Y=>S(Y)).length,Z=n.filter(Y=>!A(Y)&&!S(Y)).length;return a?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-4",children:[e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"Total"}),e.jsx(Rt,{className:"text-2xl",children:n.length})]})}),e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"New (Not Exported)"}),e.jsx(Rt,{className:"text-2xl text-green-600",children:F})]})}),e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"Active Trials"}),e.jsx(Rt,{className:"text-2xl",children:Z})]})}),e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"Converted 🎉"}),e.jsx(Rt,{className:"text-2xl text-primary",children:H})]})}),e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"Already Exported"}),e.jsx(Rt,{className:"text-2xl text-muted-foreground",children:z})]})})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(us,{value:p,onValueChange:Y=>f(Y),children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Users"}),e.jsx(Ze,{value:"new",children:"New Only"}),e.jsx(Ze,{value:"exported",children:"Already Exported"})]})]}),e.jsxs(us,{value:c,onValueChange:Y=>d(Y),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Trial Types"}),e.jsx(Ze,{value:"stripe",children:"Credit Card Trial"}),e.jsx(Ze,{value:"ghl",children:"Free Trial (No CC)"})]})]}),e.jsxs(us,{value:u,onValueChange:Y=>h(Y),children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),e.jsx(Ze,{value:"active",children:"Active Trial"}),e.jsx(Ze,{value:"expired",children:"Expired"}),e.jsx(Ze,{value:"converted",children:"Converted ✓"})]})]}),e.jsx("div",{className:"ml-auto",children:e.jsxs(B,{onClick:I,disabled:l||y.size===0,children:[l?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Export Selected (",y.size,")"]})})]}),e.jsx("div",{className:"border rounded-lg",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(hi,{checked:E.length>0&&y.size===E.length,onCheckedChange:O})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Trial Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Signup Date"}),e.jsx(Tt,{children:"Last Login"}),e.jsx(Tt,{children:"Expires / Renews"}),e.jsx(Tt,{children:"Exported"})]})}),e.jsx(da,{children:E.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No trial users match the current filters"})}):E.map(Y=>{const W=j(Y),ee=S(Y),se=A(Y),oe=w(Y);return e.jsxs(Hs,{className:`hover:bg-muted/30 ${ee?"bg-primary/5":""}`,children:[e.jsx(ht,{children:e.jsx(hi,{checked:y.has(Y.id),onCheckedChange:()=>D(Y.id)})}),e.jsx(ht,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Y.name,ee&&e.jsx(go,{className:"h-3.5 w-3.5 text-primary"})]})}),e.jsx(ht,{className:"text-muted-foreground",children:Y.email}),e.jsx(ht,{children:W==="stripe"?e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(uf,{className:"h-3 w-3"}),"Credit Card"]}):e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(Gs,{className:"h-3 w-3"}),"Free (No CC)"]})}),e.jsx(ht,{children:ee?e.jsxs(Ue,{className:"bg-primary/10 text-primary hover:bg-primary/20 gap-1",children:[e.jsx(go,{className:"h-3 w-3"}),"Converted"]}):se?e.jsx(Ue,{variant:"destructive",children:"Expired"}):e.jsx(Ue,{className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active Trial"})}),e.jsx(ht,{className:"text-sm",children:Y.created_at?new Date(Y.created_at).toLocaleDateString():"—"}),e.jsx(ht,{className:"text-sm",children:Y.last_login?e.jsxs("div",{className:"flex flex-col",children:[e.jsx("span",{children:new Date(Y.last_login).toLocaleDateString()}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(Y.last_login).toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"})})]}):e.jsx("span",{className:"text-muted-foreground",children:"Never"})}),e.jsx(ht,{className:"text-sm",children:ee&&oe?e.jsxs("span",{className:"text-muted-foreground",children:["Renews ",new Date(oe).toLocaleDateString()]}):oe?new Date(oe).toLocaleDateString():"—"}),e.jsx(ht,{children:Y.already_exported?e.jsx(vr,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Ue,{variant:"outline",className:"text-green-600 border-green-300",children:"New"})})]},Y.id)})})]})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",E.length," of ",n.length," trial users · ",H," converted to paid"]})]})},pbs=s=>s==null?'""':`"${String(s).replace(/"/g,'""')}"`,fbs=()=>{const[s,t]=N.useState([]),[n,r]=N.useState(!0);N.useEffect(()=>{(async()=>{const{data:l,error:o}=await q.from("user_deletion_log").select("*").order("created_at",{ascending:!1});!o&&l&&t(l),r(!1)})()},[]);const a=()=>{if(s.length===0){ae.info("No deletion records to export");return}const i=["Date","Deleted User","Deleted Email","Brokerage","Type","Deleted By"],l=s.map(h=>[Ss(new Date(h.created_at),"MMM d, yyyy h:mm a"),h.deleted_user_name||"—",h.deleted_user_email||"—",h.brokerage_name||"—",h.deletion_type==="deleted"?"Account Deleted":"Removed",h.deleted_by_name||h.deleted_by_email||"—"]),o=[i.join(","),...l.map(h=>h.map(pbs).join(","))].join(` `),c=new Blob([o],{type:"text/csv"}),d=URL.createObjectURL(c),u=document.createElement("a");u.href=d,u.download=`deletion-log-${new Date().toISOString().split("T")[0]}.csv`,u.click(),URL.revokeObjectURL(d),ae.success(`Exported ${s.length} deletion record(s)`)};return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):s.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(_n,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{children:"No deletion records yet"})]})}):e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsx(Rt,{className:"text-lg",children:"User Deletion History"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]}),e.jsx(Ee,{children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Deleted By"})]})}),e.jsx(da,{children:s.map(i=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"whitespace-nowrap text-sm",children:Ss(new Date(i.created_at),"MMM d, yyyy h:mm a")}),e.jsx(ht,{className:"font-medium",children:i.deleted_user_name||"—"}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:i.deleted_user_email||"—"}),e.jsx(ht,{children:i.brokerage_name||"—"}),e.jsx(ht,{children:e.jsx(Ue,{variant:i.deletion_type==="deleted"?"destructive":"secondary",children:i.deletion_type==="deleted"?"Account Deleted":"Removed"})}),e.jsx(ht,{className:"text-sm",children:i.deleted_by_name||i.deleted_by_email||"—"})]},i.id))})]})})]})},YM=s=>{const{user:t}=vs(),n=Kt(),r=dt({queryKey:["teams",s],queryFn:async()=>{let h=q.from("teams").select("*").order("created_at",{ascending:!1});s&&(h=h.eq("brokerage_id",s));const{data:p,error:f}=await h;if(f)throw f;return p||[]},enabled:!!t}),a=h=>dt({queryKey:["team-members",h],queryFn:async()=>{const{data:p,error:f}=await q.from("team_members").select("*").eq("team_id",h).order("role",{ascending:!0});if(f)throw f;const y=(p||[]).map(j=>j.user_id),{data:_}=await q.from("profiles").select("id, name, email, avatar_url").in("id",y),v=new Map((_||[]).map(j=>[j.id,j]));return(p||[]).map(j=>({...j,profile:v.get(j.user_id)||null}))},enabled:!!h}),i=yt({mutationFn:async h=>{const p={name:h.name,created_by:t.id,description:h.description,contact_visibility:h.contact_visibility,lead_pond_enabled:h.lead_pond_enabled,shared_assets_enabled:h.shared_assets_enabled};h.brokerage_id&&(p.brokerage_id=h.brokerage_id);const{data:f,error:y}=await q.from("teams").insert(p).select().single();if(y)throw y;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team created!")},onError:h=>{ae.error("Failed to create team: "+h.message)}}),l=yt({mutationFn:async({id:h,...p})=>{const{data:f,error:y}=await q.from("teams").update(p).eq("id",h).select().single();if(y)throw y;return f},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team updated")},onError:h=>{ae.error("Failed to update team: "+h.message)}}),o=yt({mutationFn:async h=>{const{error:p}=await q.from("teams").delete().eq("id",h);if(p)throw p},onSuccess:()=>{n.invalidateQueries({queryKey:["teams"]}),ae.success("Team deleted")},onError:h=>{ae.error("Failed to delete team: "+h.message)}}),c=yt({mutationFn:async h=>{const{data:p,error:f}=await q.from("team_members").insert({team_id:h.team_id,user_id:h.user_id,role:h.role||"team_member"}).select().single();if(f)throw f.message.includes("duplicate")||f.message.includes("unique")?new Error("This agent is already on a team. They must be removed from their current team first."):f;return p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member added to team")},onError:h=>{ae.error(h.message)}}),d=yt({mutationFn:async h=>{const{error:p}=await q.from("team_members").delete().eq("id",h.member_id);if(p)throw p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member removed from team")},onError:h=>{ae.error("Failed to remove member: "+h.message)}}),u=yt({mutationFn:async h=>{const{error:p}=await q.from("team_members").update({role:h.role}).eq("id",h.member_id);if(p)throw p},onSuccess:(h,p)=>{n.invalidateQueries({queryKey:["team-members",p.team_id]}),ae.success("Member role updated")},onError:h=>{ae.error("Failed to update role: "+h.message)}});return{teams:r.data||[],isLoading:r.isLoading,createTeam:i,updateTeam:l,deleteTeam:o,addMember:c,removeMember:d,updateMemberRole:u,useTeamMembers:a}},xbs=()=>{const{user:s}=vs();return dt({queryKey:["team-contacts",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_contacts",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},L0t=s=>{const{user:t}=vs(),n=Kt(),r=dt({queryKey:["lead-pond",s],queryFn:async()=>{const{data:o,error:c}=await q.from("team_lead_pond").select("*").eq("team_id",s).order("created_at",{ascending:!1});if(c)throw c;if(!o||o.length===0)return[];const d=o.map(j=>j.contact_id),u=[...new Set(o.map(j=>j.added_by))],h=o.filter(j=>j.claimed_by).map(j=>j.claimed_by),p=[...new Set([...u,...h])],[f,y]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",d),q.from("profiles").select("id, name, avatar_url").in("id",p)]),_=new Map((f.data||[]).map(j=>[j.id,j])),v=new Map((y.data||[]).map(j=>[j.id,j]));return o.map(j=>({...j,status:j.claimed_by?"claimed":"available",contact:_.get(j.contact_id)||null,contributor:v.get(j.added_by)||null,claimer:j.claimed_by&&v.get(j.claimed_by)||null}))},enabled:!!s&&!!t}),a=yt({mutationFn:async o=>{const{data:c,error:d}=await q.rpc("add_to_lead_pond",{_contact_id:o.contact_id,_team_id:o.team_id,_notes:o.notes||null});if(d)throw d;return c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Contact added to Lead Pond")},onError:o=>{ae.error(o.message)}}),i=yt({mutationFn:async o=>{const{error:c}=await q.rpc("claim_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Lead claimed!")},onError:o=>{ae.error(o.message)}}),l=yt({mutationFn:async o=>{const{error:c}=await q.rpc("return_lead_pond_contact",{_lead_pond_id:o});if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["lead-pond"]}),ae.success("Lead returned to pond")},onError:o=>{ae.error(o.message)}});return{leadPondItems:r.data||[],isLoading:r.isLoading,addToLeadPond:a,claimLead:i,returnLead:l}},gbs=()=>{const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("transfer_contact",{_contact_id:t.contactId,_to_user_id:t.toUserId,_notes:t.notes||null});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error);return a},onSuccess:()=>{s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["team-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),ae.success("Contact transferred successfully")},onError:t=>{ae.error(t.message||"Failed to transfer contact")}})};function D0t({open:s,onOpenChange:t,contactIds:n,contactNames:r=[],onComplete:a}){var E;const{user:i}=vs(),{data:l}=Wv(),{useTeamMembers:o}=YM(),{data:c=[]}=o((l==null?void 0:l.teamId)||""),d=gbs(),[u,h]=N.useState(null),[p,f]=N.useState(""),[y,_]=N.useState(!1),v=c.filter(O=>O.user_id!==(i==null?void 0:i.id)),j=async()=>{if(u){_(!0);try{for(const O of n)await d.mutateAsync({contactId:O,toUserId:u,notes:p||void 0});t(!1),h(null),f(""),a==null||a()}catch{}finally{_(!1)}}},w=v.find(O=>O.user_id===u),S=n.length>1,A=r.length>0?S?`${r.length} contacts`:r[0]:S?`${n.length} contacts`:"this contact";return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(lw,{className:"h-5 w-5"}),"Transfer ",A]}),e.jsxs(Jn,{children:["Select a team member to transfer ",S?"these contacts":"this contact"," to. The contact will be removed from the current owner's CRM and added to the selected member's."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium mb-2 block",children:"Transfer to:"}),e.jsx("div",{className:"space-y-1 max-h-[240px] overflow-y-auto",children:v.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No other team members available"}):v.map(O=>{var D,I,F;return e.jsxs("button",{onClick:()=>h(O.user_id),className:`w-full flex items-center gap-3 p-3 rounded-lg text-left transition-colors ${u===O.user_id?"bg-primary/10 border border-primary/30":"hover:bg-accent border border-transparent"}`,children:[e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:((D=O.profile)==null?void 0:D.avatar_url)||""}),e.jsx(ea,{className:"text-xs",children:(((I=O.profile)==null?void 0:I.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:((F=O.profile)==null?void 0:F.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:O.role.replace("_"," ")})]})]},O.user_id)})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"transfer-notes",className:"text-sm font-medium",children:"Notes (optional)"}),e.jsx(Ms,{id:"transfer-notes",value:p,onChange:O=>f(O.target.value),placeholder:"Reason for transfer...",className:"mt-1",rows:2})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:j,disabled:!u||y,children:[y?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(lw,{className:"h-4 w-4 mr-2"}),"Transfer",w?` to ${(E=w.profile)==null?void 0:E.name}`:""]})]})]})})}const TIe=()=>{const s=Ln(),{data:t,isLoading:n}=xbs(),{data:r}=Wv(),[a,i]=N.useState(""),[l,o]=N.useState("all"),[c,d]=N.useState(null),[u,h]=N.useState(""),p=(r==null?void 0:r.role)==="team_leader",f=N.useMemo(()=>{if(!t)return[];const _=new Map;return t.forEach(v=>{_.has(v.owner_user_id)||_.set(v.owner_user_id,{id:v.owner_user_id,name:v.owner_name||"Unknown",avatar:v.owner_avatar_url})}),Array.from(_.values())},[t]),y=N.useMemo(()=>{if(!t)return[];let _=t;if(l!=="all"&&(_=_.filter(v=>v.owner_user_id===l)),a.trim()){const v=a.toLowerCase();_=_.filter(j=>{var w,S,A;return(j.first_name+" "+(j.last_name||"")).toLowerCase().includes(v)||((w=j.email)==null?void 0:w.toLowerCase().includes(v))||((S=j.phone)==null?void 0:S.includes(v))||((A=j.owner_name)==null?void 0:A.toLowerCase().includes(v))})}return _},[t,a,l]);return n?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-10 w-full"}),e.jsx(Ws,{className:"h-64 w-full"})]}):!t||t.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(An,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Team Contacts"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team contact sharing is not enabled, or you're not on a team. Ask your manager about contact visibility settings."})]})}):e.jsxs("div",{className:"space-y-4",children:[e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, phone, or agent...",value:a,onChange:_=>i(_.target.value),className:"pl-9"})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Filter by agent"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Team Members"}),f.map(_=>e.jsx(Ze,{value:_.id,children:_.name},_.id))]})]})]})})}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[y.length," contact",y.length!==1?"s":""," from ",f.length," teammate",f.length!==1?"s":""]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0 overflow-x-auto",children:e.jsxs(la,{className:"min-w-[800px]",children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Contact Info"}),e.jsx(Tt,{children:"Address"}),e.jsx(Tt,{children:"Lead Source"}),e.jsx(Tt,{children:"Date Added"}),p&&e.jsx(Tt,{className:"w-[80px]",children:"Actions"})]})}),e.jsx(da,{children:y.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:p?7:6,className:"text-center py-8 text-muted-foreground",children:a||l!=="all"?"No contacts match your filters":"No team contacts available"})}):y.map(_=>e.jsxs(Hs,{className:`hover:bg-accent/50 ${p?"cursor-pointer":""}`,onClick:p?()=>s(`/mission-control/contacts/${_.id}`):void 0,children:[e.jsx(ht,{className:"font-medium",children:e.jsxs("span",{className:p?"hover:text-primary hover:underline transition-colors":"",children:[_.first_name," ",_.last_name||""]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Jr,{className:"h-6 w-6",children:[e.jsx(ti,{src:_.owner_avatar_url||""}),e.jsx(ea,{className:"text-[10px]",children:(_.owner_name||"?").charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-sm text-muted-foreground truncate max-w-[120px]",children:_.owner_name||"Unknown"})]})}),e.jsx(ht,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[_.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Gs,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:_.email})]}),_.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Cr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{children:_.phone})]}),!_.email&&!_.phone&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"No contact info"})]})}),e.jsx(ht,{children:_.address?e.jsxs("div",{className:"flex items-center gap-1 text-sm text-muted-foreground",children:[e.jsx(ka,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate max-w-[180px]",children:_.address})]}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(ht,{children:_.lead_source?e.jsx(Ue,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:_.lead_source}):e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"—"})}),e.jsx(ht,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(_.created_at),"MMM d, yyyy")})}),p&&e.jsx(ht,{children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 px-2",onClick:v=>{v.stopPropagation(),d(_.id),h(`${_.first_name} ${_.last_name||""}`.trim())},title:"Transfer to team member",children:e.jsx(lw,{className:"h-4 w-4"})})})]},_.id))})]})})}),e.jsx(D0t,{open:!!c,onOpenChange:_=>{_||d(null)},contactIds:c?[c]:[],contactNames:u?[u]:[],onComplete:()=>d(null)})]})},EIe=({teamId:s})=>{const{user:t}=vs(),{leadPondItems:n,isLoading:r,claimLead:a,returnLead:i}=L0t(s);if(console.log("[LeadPondView] render — teamId:",s,"itemCount:",n.length,"loading:",r),r)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(c=>e.jsx(Ws,{className:"h-20 w-full"},c))});if(n.length===0)return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(db,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"Lead Pond is Empty"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Team members can contribute contacts here for others to claim and follow up with."})]})});const l=n.filter(c=>c.status==="available"),o=n.filter(c=>c.status==="claimed");return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Available (",l.length,")"]}),l.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No leads available right now."}):e.jsx("div",{className:"space-y-2",children:l.map(c=>{var d,u,h,p,f,y,_;return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((u=c.contact)==null?void 0:u.last_name)||""]}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 mt-1",children:[((h=c.contact)==null?void 0:h.email)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Gs,{className:"h-3 w-3"})," ",c.contact.email]}),((p=c.contact)==null?void 0:p.phone)&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Cr,{className:"h-3 w-3"})," ",c.contact.phone]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs(Jr,{className:"h-4 w-4",children:[e.jsx(ti,{src:((f=c.contributor)==null?void 0:f.avatar_url)||""}),e.jsx(ea,{className:"text-[8px]",children:(((y=c.contributor)==null?void 0:y.name)||"?").charAt(0)})]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["from ",((_=c.contributor)==null?void 0:_.name)||"Unknown"]})]})]}),e.jsxs(B,{size:"sm",onClick:()=>a.mutate(c.id),disabled:a.isPending,children:[e.jsx(Y7,{className:"mr-1 h-3 w-3"}),"Claim"]})]})},c.id)})})]}),o.length>0&&e.jsxs("div",{children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground mb-3",children:["Claimed (",o.length,")"]}),e.jsx("div",{className:"space-y-2",children:o.map(c=>{var d,u,h;return e.jsx(fe,{className:"opacity-75",children:e.jsxs(Ee,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(d=c.contact)==null?void 0:d.first_name," ",((u=c.contact)==null?void 0:u.last_name)||""]}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:e.jsxs(Ue,{variant:"secondary",className:"text-xs",children:["Claimed by ",((h=c.claimer)==null?void 0:h.name)||"Unknown"]})})]}),c.claimed_by===(t==null?void 0:t.id)&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>i.mutate(c.id),disabled:i.isPending,children:[e.jsx(Bm,{className:"mr-1 h-3 w-3"}),"Return"]})]})},c.id)})})]})]})},R0t=({teamId:s})=>{const{useTeamMembers:t}=YM(),{data:n=[]}=t(s),r=n.map(f=>f.user_id),a=new Map(n.map(f=>[f.user_id,f.profile])),{data:i=[],isLoading:l}=dt({queryKey:["team-shared-presentations",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:y}=await q.from("smart_presentations").select("id, owner_user_id, title, client_name, status, view_count, cta_clicked_count, share_token, created_at, published_at").in("owner_user_id",r).neq("status","archived").order("created_at",{ascending:!1});if(y)throw y;return f||[]},enabled:r.length>0}),{data:o=[],isLoading:c}=dt({queryKey:["team-shared-open-houses",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:y}=await q.from("open_houses").select("id, agent_id, property_address, city, state, event_date, is_active, visitor_count, slug, created_at").in("agent_id",r).order("event_date",{ascending:!1});if(y)throw y;return f||[]},enabled:r.length>0}),{data:d=[],isLoading:u}=dt({queryKey:["team-shared-videos",s,r],queryFn:async()=>{if(r.length===0)return[];const{data:f,error:y}=await q.from("agent_videos").select("id, owner_user_id, title, recipient_name, status, view_count, touch_type, share_token, created_at").in("owner_user_id",r).eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(y)throw y;return f||[]},enabled:r.length>0});if(l||c||u)return e.jsx("div",{className:"space-y-3",children:[1,2,3].map(f=>e.jsx(Ws,{className:"h-20 w-full"},f))});const p=f=>{const y=a.get(f);return{name:(y==null?void 0:y.name)||"Unknown",avatar:(y==null?void 0:y.avatar_url)||"",initials:((y==null?void 0:y.name)||"?").charAt(0).toUpperCase()}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(ny,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:i.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Presentations"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(Or,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:o.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Guest Books"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsx(fr,{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(Fr,{defaultValue:"presentations",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"presentations",children:["Presentations (",i.length,")"]}),e.jsxs(Zt,{value:"guest-books",children:["Guest Books (",o.length,")"]}),e.jsxs(Zt,{value:"videos",children:["Videos (",d.length,")"]})]}),e.jsx(is,{value:"presentations",className:"space-y-2",children:i.length===0?e.jsx(_2e,{icon:e.jsx(ny,{className:"h-10 w-10"}),label:"No presentations yet"}):i.map(f=>{const y=p(f.owner_user_id);return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Jr,{className:"h-8 w-8 shrink-0",children:[e.jsx(ti,{src:y.avatar}),e.jsx(ea,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||"Untitled"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",Ss(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Ue,{variant:f.status==="published"?"default":"secondary",className:"text-xs capitalize",children:f.status}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Sr,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})}),e.jsx(is,{value:"guest-books",className:"space-y-2",children:o.length===0?e.jsx(_2e,{icon:e.jsx(Or,{className:"h-10 w-10"}),label:"No guest books yet"}):o.map(f=>{const y=p(f.agent_id);return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Jr,{className:"h-8 w-8 shrink-0",children:[e.jsx(ti,{src:y.avatar}),e.jsx(ea,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.property_address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",Ss(new Date(f.event_date),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[f.is_active?e.jsx(Ue,{className:"text-xs",children:"Active"}):e.jsx(Ue,{variant:"secondary",className:"text-xs",children:"Inactive"}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(An,{className:"h-3 w-3"}),f.visitor_count||0]})]})]})},f.id)})}),e.jsx(is,{value:"videos",className:"space-y-2",children:d.length===0?e.jsx(_2e,{icon:e.jsx(fr,{className:"h-10 w-10"}),label:"No videos yet"}):d.map(f=>{const y=p(f.owner_user_id);return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Jr,{className:"h-8 w-8 shrink-0",children:[e.jsx(ti,{src:y.avatar}),e.jsx(ea,{className:"text-xs",children:y.initials})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:f.title||f.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[y.name," · ",Ss(new Date(f.created_at),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[e.jsx(Ue,{variant:"secondary",className:"text-xs capitalize",children:f.touch_type}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Sr,{className:"h-3 w-3"}),f.view_count||0]})]})]})},f.id)})})]})]})},_2e=({icon:s,label:t})=>e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-8 text-center text-muted-foreground",children:[s,e.jsx("p",{className:"mt-2 text-sm",children:t})]})}),O0t=({team:s,brokerageAgents:t,onBack:n,onUpdate:r,onAddMember:a,onRemoveMember:i,onUpdateRole:l,onDeleteTeam:o,isUpdating:c,isAddingMember:d})=>{var D,I;const{useTeamMembers:u}=YM(),{data:h=[],isLoading:p}=u(s.id),[f,y]=N.useState(!1),[_,v]=N.useState(""),[j,w]=N.useState("team_member"),{data:S}=dt({queryKey:["agents-on-other-teams",s.id],queryFn:async()=>{const{data:F}=await q.from("team_members").select("user_id, team_id, teams:team_id(name)").neq("team_id",s.id),z=new Map;return(F||[]).forEach(H=>{var Z;z.set(H.user_id,((Z=H.teams)==null?void 0:Z.name)||"another team")}),z}}),A=new Set(h.map(F=>F.user_id)),E=t.filter(F=>!A.has(F.id)),O=async()=>{_&&(await a(_,j),v(""),w("team_member"),y(!1))};return e.jsxs("div",{className:"space-y-6",children:[e.jsx(B,{variant:"ghost",onClick:n,className:"mb-2",children:"← Back to Teams"}),e.jsxs(Fr,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"members",children:"Members"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(bA,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),s.lead_pond_enabled&&e.jsxs(Zt,{value:"lead-pond",children:[e.jsx(db,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),s.shared_assets_enabled&&e.jsxs(Zt,{value:"shared-assets",children:[e.jsx(pf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(is,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"text-lg font-semibold",children:[s.name," — Members"]}),e.jsxs(_s,{open:f,onOpenChange:y,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),"Add Member"]})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Add Team Member"}),e.jsxs(Jn,{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(ne,{children:"Agent"}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[_&&(((D=E.find(F=>F.id===_))==null?void 0:D.name)||((I=E.find(F=>F.id===_))==null?void 0:I.email))||"Select an agent",e.jsx($g,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search agents..."}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:"No agents found."}),e.jsx(Jg,{children:E.map(F=>{const z=S==null?void 0:S.get(F.id);return e.jsxs(Zf,{value:F.name||F.email||F.id,disabled:!!z,onSelect:()=>v(F.id),children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",_===F.id?"opacity-100":"opacity-0")}),F.name||F.email,z&&e.jsxs("span",{className:"text-xs text-muted-foreground ml-1",children:["(on ",z,")"]})]},F.id)})})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Role"}),e.jsxs(us,{value:j,onValueChange:w,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"team_leader",children:"Team Leader"}),e.jsx(Ze,{value:"team_member",children:"Team Member"})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(!1),children:"Cancel"}),e.jsx(B,{onClick:O,disabled:!_||d,children:d?"Adding...":"Add to Team"})]})]})]})]}),p?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(F=>e.jsx(Ws,{className:"h-16 w-full"},F))}):h.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(An,{className:"h-10 w-10 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No members yet. Add agents to this team."})]})}):e.jsx("div",{className:"space-y-2",children:h.map(F=>{var z,H,Z,Y,W;return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center justify-between p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:((z=F.profile)==null?void 0:z.avatar_url)||""}),e.jsx(ea,{children:(((H=F.profile)==null?void 0:H.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Z=F.profile)==null?void 0:Z.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(Y=F.profile)==null?void 0:Y.email})]}),F.role==="team_leader"?e.jsxs(Ue,{className:"bg-[hsl(var(--chart-4)/0.1)] text-[hsl(var(--chart-4))] border-[hsl(var(--chart-4))]",children:[e.jsx(hf,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Ue,{variant:"secondary",children:"Member"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(us,{value:F.role,onValueChange:ee=>l(F.id,ee),children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"team_leader",children:"Team Leader"}),e.jsx(Ze,{value:"team_member",children:"Team Member"})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-muted-foreground hover:text-destructive",children:e.jsx(T9,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove Member?"}),e.jsxs(Mo,{children:["Remove ",((W=F.profile)==null?void 0:W.name)||"this member"," from ",s.name,"?"]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>i(F.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})]})]})]})},F.id)})})]}),e.jsx(is,{value:"contacts",className:"space-y-4",children:e.jsx(TIe,{})}),s.lead_pond_enabled&&e.jsx(is,{value:"lead-pond",className:"space-y-4",children:e.jsx(EIe,{teamId:s.id})}),s.shared_assets_enabled&&e.jsx(is,{value:"shared-assets",className:"space-y-4",children:e.jsx(R0t,{teamId:s.id})}),e.jsxs(is,{value:"settings",className:"space-y-4",children:[e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{className:"text-lg",children:"Team Settings"}),e.jsx(Vn,{children:"Configure how this team operates."})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Team Name"}),e.jsx(ye,{defaultValue:s.name,onBlur:F=>{F.target.value!==s.name&&r({name:F.target.value})}})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{defaultValue:s.description||"",onBlur:F=>{F.target.value!==(s.description||"")&&r({description:F.target.value||null})},rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Contact Visibility"}),e.jsxs(us,{defaultValue:s.contact_visibility,onValueChange:F=>r({contact_visibility:F}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"private",children:"Private — Members keep their contacts private"}),e.jsx(Ze,{value:"leader_only",children:"Leader Only — Only team leaders can see member contacts"}),e.jsx(Ze,{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(ne,{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(jn,{checked:s.lead_pond_enabled,onCheckedChange:F=>r({lead_pond_enabled:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:s.shared_assets_enabled,onCheckedChange:F=>r({shared_assets_enabled:F})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:s.shared_videos_enabled??!1,onCheckedChange:F=>r({shared_videos_enabled:F})})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsxs(B,{variant:"destructive",size:"sm",children:[e.jsx(_n,{className:"mr-2 h-4 w-4"}),"Delete Team"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Team?"}),e.jsxs(Mo,{children:['This will permanently delete "',s.name,'" and remove all team members. This cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>{o(),n()},className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Team"})]})]})]})]})]})]})},F0t=({open:s,onOpenChange:t,onCreateTeam:n,isCreating:r,brokerageAgents:a,isAdmin:i,allBrokerages:l,activeBrokerageId:o})=>{const[c,d]=N.useState(1),[u,h]=N.useState(""),[p,f]=N.useState(""),[y,_]=N.useState(""),[v,j]=N.useState(""),[w,S]=N.useState([]),A=()=>{d(1),h(""),f(""),_(""),j(""),S([])},E=F=>{F||A(),t(F)},O=async()=>{const F=y&&y!=="none"?y:o||null;await n({name:u.trim(),description:p.trim()||void 0,brokerage_id:F,leaderId:v||void 0,memberIds:w.length>0?w:void 0}),A()},D=F=>{F!==v&&S(z=>z.includes(F)?z.filter(H=>H!==F):[...z,F])},I=a.filter(F=>F.id!==v);return e.jsx(_s,{open:s,onOpenChange:E,children:e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsx(ws,{children:c===1?"Create New Team":"Assign Team Members"}),e.jsx(Jn,{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:Mt("h-1.5 flex-1 rounded-full transition-colors","bg-primary")}),e.jsx("div",{className:Mt("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(ne,{htmlFor:"team-name",children:"Team Name *"}),e.jsx(ye,{id:"team-name",value:u,onChange:F=>h(F.target.value),placeholder:"e.g., Downtown Squad",autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"team-desc",children:"Description"}),e.jsx(Ms,{id:"team-desc",value:p,onChange:F=>f(F.target.value),placeholder:"What is this team focused on?",rows:3})]}),i&&l&&l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Brokerage"}),e.jsxs(us,{value:y,onValueChange:_,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"No brokerage (independent team)"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No brokerage (independent)"}),l.map(F=>e.jsx(Ze,{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(ne,{className:"flex items-center gap-1.5",children:[e.jsx(hf,{className:"h-3.5 w-3.5 text-[hsl(var(--chart-4))]"}),"Team Leader"]}),e.jsxs(us,{value:v,onValueChange:F=>{j(F),S(z=>z.filter(H=>H!==F))},children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a team leader (optional)"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No leader for now"}),a.map(F=>e.jsx(Ze,{value:F.id,children:F.name||F.email||"Unknown"},F.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"flex items-center gap-1.5",children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Initial Members",w.length>0&&e.jsxs(Ue,{variant:"secondary",className:"ml-1 text-xs",children:[w.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:I.length===0?e.jsxs("div",{className:"p-4 text-center text-sm text-muted-foreground",children:[e.jsx(An,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"No agents available"]}):I.map(F=>{const z=w.includes(F.id);return e.jsxs("button",{type:"button",className:Mt("w-full flex items-center gap-3 p-3 text-left transition-colors hover:bg-accent/50",z&&"bg-primary/5"),onClick:()=>D(F.id),children:[e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:F.avatar_url||""}),e.jsx(ea,{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:Mt("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(Lr,{className:"h-3 w-3"})})]},F.id)})})]})]})}),e.jsx(Xn,{className:"gap-2 sm:gap-0",children:c===1?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>d(2),disabled:!u.trim(),children:["Next",e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>d(1),children:[e.jsx(qr,{className:"mr-2 h-4 w-4"}),"Back"]}),e.jsx(B,{onClick:O,disabled:r,children:r?"Creating…":"Create Team"})]})})]})})},ybs=()=>{const{teams:s,isLoading:t,createTeam:n,updateTeam:r,deleteTeam:a,addMember:i,removeMember:l,updateMemberRole:o}=YM(),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(""),{data:y}=dt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:E,error:O}=await q.from("brokerages").select("id, name").order("name");if(O)throw O;return E||[]}}),{data:_}=dt({queryKey:["admin-team-member-info",s.map(E=>E.id).join(",")],queryFn:async()=>{var F;if(s.length===0)return{};const{data:E}=await q.from("team_members").select("team_id, user_id, role").in("team_id",s.map(z=>z.id));if(!E)return{};const O=E.filter(z=>z.role==="team_leader").map(z=>z.user_id);let D={};if(O.length>0){const{data:z}=await q.from("profiles").select("id, name").in("id",O);z&&(D=Object.fromEntries(z.map(H=>[H.id,{name:H.name}])))}const I={};for(const z of s){const H=E.filter(Y=>Y.team_id===z.id),Z=H.find(Y=>Y.role==="team_leader");I[z.id]={count:H.length,leaderName:Z&&((F=D[Z.user_id])==null?void 0:F.name)||null}}return I},enabled:s.length>0}),v=(u==null?void 0:u.brokerage_id)||null,{data:j}=dt({queryKey:["brokerage-agents-for-teams",v],queryFn:async()=>{let E=q.from("profiles").select("id, name, email, avatar_url").order("name");v&&(E=E.eq("brokerage_id",v));const{data:O,error:D}=await E;if(D)throw D;return O||[]},enabled:!!u}),w=Object.fromEntries((y||[]).map(E=>[E.id,E.name])),S=async E=>{const O=await n.mutateAsync({name:E.name,brokerage_id:E.brokerage_id||null,description:E.description});if(E.leaderId&&E.leaderId!=="none"&&await i.mutateAsync({team_id:O.id,user_id:E.leaderId,role:"team_leader"}),E.memberIds)for(const D of E.memberIds)await i.mutateAsync({team_id:O.id,user_id:D,role:"team_member"});d(!1)};if(u)return e.jsx(O0t,{team:u,brokerageAgents:j||[],onBack:()=>h(null),onUpdate:E=>r.mutateAsync({id:u.id,...E}).then(O=>h(O)),onAddMember:(E,O)=>i.mutateAsync({team_id:u.id,user_id:E,role:O}),onRemoveMember:E=>l.mutateAsync({team_id:u.id,member_id:E}),onUpdateRole:(E,O)=>o.mutateAsync({team_id:u.id,member_id:E,role:O}),onDeleteTeam:()=>{a.mutate(u.id),h(null)},isUpdating:r.isPending,isAddingMember:i.isPending});const A=s.filter(E=>E.name.toLowerCase().includes(p.toLowerCase())||(E.description||"").toLowerCase().includes(p.toLowerCase()));return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search teams...",value:p,onChange:E=>f(E.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[A.length," of ",s.length," teams"]})]}),e.jsxs(B,{size:"sm",onClick:()=>d(!0),children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(F0t,{open:c,onOpenChange:d,onCreateTeam:S,isCreating:n.isPending,brokerageAgents:[],isAdmin:!0,allBrokerages:y,activeBrokerageId:null}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Team Name"}),e.jsx(Tt,{className:"font-semibold",children:"Brokerage"}),e.jsx(Tt,{className:"font-semibold",children:"Leader"}),e.jsx(Tt,{className:"font-semibold",children:"Members"}),e.jsx(Tt,{className:"font-semibold",children:"Visibility"}),e.jsx(Tt,{className:"w-[100px]"})]})}),e.jsx(da,{children:t?e.jsx(e.Fragment,{children:[1,2,3].map(E=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsx(Ws,{className:"h-4 w-32"})}),e.jsx(ht,{children:e.jsx(Ws,{className:"h-4 w-24"})}),e.jsx(ht,{children:e.jsx(Ws,{className:"h-4 w-28"})}),e.jsx(ht,{children:e.jsx(Ws,{className:"h-4 w-12"})}),e.jsx(ht,{children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(ht,{children:e.jsx(Ws,{className:"h-4 w-16"})})]},E))}):A.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center py-12 text-muted-foreground",children:p?"No teams match your search":"No teams found. Create one to get started."})}):A.map(E=>{const O=_==null?void 0:_[E.id];return e.jsxs(Hs,{className:"hover:bg-muted/30",children:[e.jsxs(ht,{children:[e.jsx("button",{onClick:()=>h(E),className:"text-primary hover:underline font-medium",children:E.name}),E.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:E.description})]}),e.jsx(ht,{children:E.brokerage_id?e.jsx("span",{className:"text-sm",children:w[E.brokerage_id]||"—"}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"Independent"})}),e.jsx(ht,{children:O!=null&&O.leaderName?e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(hf,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),O.leaderName]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No leader"})}),e.jsx(ht,{children:e.jsxs(Ue,{variant:"secondary",className:"text-xs",children:[e.jsx(An,{className:"h-3 w-3 mr-1"}),(O==null?void 0:O.count)??0]})}),e.jsx(ht,{children:e.jsxs("span",{className:"text-xs text-muted-foreground capitalize flex items-center gap-1",children:[e.jsx(Ih,{className:"h-3 w-3"}),E.contact_visibility.replace("_"," ")]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>h(E),title:"Edit team",children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete team "${E.name}"? This cannot be undone.`)&&a.mutate(E.id)},title:"Delete team",children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})})]},E.id)})})]})})]})};function wHe(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 vbs({open:s,onOpenChange:t,recipients:n}){const{toast:r}=Fa(),[a,i]=N.useState([]),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[y,_]=N.useState(!1),[v,j]=N.useState(!1),w=N.useMemo(()=>a.find(O=>O.id===c)||null,[a,c]);N.useEffect(()=>{s&&(o(!0),(async()=>{const O=new Date().toISOString(),{data:D,error:I}=await q.from("events").select("id,title,description,event_date,zoom_link,image_url,is_published").gte("event_date",O).order("event_date",{ascending:!0}).limit(50);I?r({title:"Could not load events",description:I.message,variant:"destructive"}):i(D||[]),o(!1)})())},[s,r]);const S=N.useMemo(()=>n.filter(O=>O.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(O.email)),[n]),A=()=>{if(!w){r({title:"Pick an event first",variant:"destructive"});return}if(S.length===0){r({title:"No valid recipient emails",variant:"destructive"});return}j(!0)},E=async()=>{if(w){j(!1),_(!0);try{const{data:{session:O}}=await q.auth.getSession(),D=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${O==null?void 0:O.access_token}`},body:JSON.stringify({event_id:w.id,recipients:S.map(H=>({email:H.email,name:H.name,user_id:H.id})),custom_subject:u.trim()||void 0,custom_intro:p.trim()||void 0})}),I=await D.json().catch(()=>({}));if(!D.ok)throw new Error((I==null?void 0:I.error)||"Failed to send event invite");const F=(I==null?void 0:I.sent)??0,z=(I==null?void 0:I.failed)??0;r({title:"Invites sent",description:`Sent: ${F}${z?` · Failed: ${z}`:""}`}),t(!1),f(""),h(""),d("")}catch(O){const D=O instanceof Error?O.message:"Send failed";r({title:"Send failed",description:D,variant:"destructive"})}finally{_(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5 text-primary"}),"Send Event Invite"]}),e.jsxs(Jn,{children:["Send a beautiful event invitation to ",S.length," selected member",S.length===1?"":"s",".",n.length!==S.length&&e.jsxs("span",{className:"block text-amber-600 mt-1",children:[n.length-S.length," skipped (missing or invalid email)"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{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(rs,{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(us,{value:c,onValueChange:d,children:[e.jsx(ls,{id:"event-select",children:e.jsx(hs,{placeholder:"Pick an upcoming event..."})}),e.jsx(cs,{children:a.map(O=>e.jsx(Ze,{value:O.id,children:e.jsxs("div",{className:"flex flex-col text-left",children:[e.jsx("span",{className:"font-medium",children:O.title}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[wHe(O.event_date),!O.is_published&&" · (Draft)"]})]})},O.id))})]})]}),w&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(yr,{className:"h-4 w-4 text-primary"}),w.title]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:wHe(w.event_date)}),w.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:w.description})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"subject",children:"Subject line (optional)"}),e.jsx(ye,{id:"subject",placeholder:w?`You're invited: ${w.title}`:"You're invited to...",value:u,onChange:O=>h(O.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(ne,{htmlFor:"intro",children:"Personal message (optional)"}),e.jsx(Ms,{id:"intro",placeholder:"Add a custom intro message... e.g. 'As a new member, we'd love to have you at our weekly onboarding event!'",value:p,onChange:O=>f(O.target.value),rows:4}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"This appears at the top of the email. Leave blank for a friendly default."})]}),e.jsxs("div",{className:"rounded-lg border p-3 bg-muted/20",children:[e.jsxs("div",{className:"text-xs font-medium text-muted-foreground mb-2",children:["RECIPIENTS (",S.length,")"]}),e.jsxs("div",{className:"flex flex-wrap gap-1 max-h-24 overflow-y-auto",children:[S.slice(0,30).map(O=>e.jsx(Ue,{variant:"secondary",className:"text-xs font-normal",children:O.name||O.email},O.id)),S.length>30&&e.jsxs(Ue,{variant:"outline",className:"text-xs",children:["+",S.length-30," more"]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsx(B,{onClick:A,disabled:y||!c||S.length===0,children:y?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-2"})," Send to ",S.length]})})]})]})}),e.jsx(Oo,{open:v,onOpenChange:j,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Send event invite?"}),e.jsx(Mo,{children:w?e.jsxs(e.Fragment,{children:["Send invite for ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',w.title,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[S.length," member",S.length===1?"":"s"]}),"?"]}):null})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(wo,{onClick:E,children:[e.jsx(lr,{className:"h-4 w-4 mr-2"})," Send"]})]})]})})]})}const bbs=()=>{const s=Ln(),{user:t,isAdmin:n}=vs(),{startImpersonation:r,isLoading:a}=A0e(),{toast:i}=Fa(),[l,o]=N.useState([]),[c,d]=N.useState([]),[u,h]=N.useState([]),[p,f]=N.useState({}),[y,_]=N.useState(!0);N.useState({});const[v,j]=N.useState(!1),[w,S]=N.useState({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),[A,E]=N.useState(!1),[O,D]=N.useState(""),[I,F]=N.useState(1),[z,H]=N.useState(50),[Z,Y]=N.useState("all"),[W,ee]=N.useState("all"),[se,oe]=N.useState("all"),[he,ce]=N.useState("all"),[me,le]=N.useState("all"),[ve,ge]=N.useState(!1),[Te,Ie]=N.useState(!1),[Ce,Me]=N.useState(!1),[Pe,Re]=N.useState(null),[Ae,Be]=N.useState(null),[we,Je]=N.useState(!1),[ke,it]=N.useState({name:"",email:"",brokerage_id:"",phone:""}),[je,He]=N.useState(null),[$e,Ke]=N.useState(!1),[Ge,rt]=N.useState(""),[tt,at]=N.useState(!1),[Ye,ut]=N.useState(!1),[_t,bt]=N.useState(null),[$t,Yt]=N.useState(""),[Ds,Ls]=N.useState(!1),[xs,Lt]=N.useState(!1),[Jt,gt]=N.useState(null),[zt,As]=N.useState(!1),[Xt,Qs]=N.useState(!1),[ks,$s]=N.useState(null),[an,tn]=N.useState(""),[er,xn]=N.useState(!1),[Pn,Qn]=N.useState({email:"",name:"",password:"",phone:""}),[sa,na]=N.useState(!1),[Es,mi]=N.useState(!1),[Ar,Hn]=N.useState(""),[Ts,Un]=N.useState(!1),[ir,Tr]=N.useState(!1),[ts,Fe]=N.useState(""),[Qe,ot]=N.useState(new Set),[St,Bt]=N.useState(!1),[Vt,fs]=N.useState(!1),[lt,ns]=N.useState(null),[Vs,ys]=N.useState(!1),[mn,On]=N.useState(null),[vn,Yn]=N.useState([]),[_r,wr]=N.useState([]),[Er,xa]=N.useState(!1),[Ki,io]=N.useState({});N.useEffect(()=>{!t||!n||(Mr(),qi())},[t,n]);const Xa=async()=>{try{const{data:Pt,error:dn}=await q.from("brokerage_manager_assignments").select("user_id, brokerage_id");if(dn)throw dn;const zn={};for(const Ir of Pt??[])zn[Ir.brokerage_id]||(zn[Ir.brokerage_id]=[]),zn[Ir.brokerage_id].push(Ir.user_id);f(zn)}catch(Pt){console.error("Error loading brokerage manager assignments:",Pt)}},Mr=async()=>{try{_(!0);const{data:Pt,error:dn}=await q.functions.invoke("get-user-details");if(dn)throw dn;const zn=Pt.users||[];o(zn),h(Pt.brokerages||[]),await Xa();const Ir=zn.filter(Gn=>Gn.roles.includes("assistant"));if(Ir.length>0){const Gn=Ir.map(Ya=>Ya.id),{data:ha}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("assistant_id",Gn);if(ha&&ha.length>0){const Ya=[...new Set(ha.map(kd=>kd.agent_id))],{data:ai}=await q.from("profiles").select("id, name, email").in("id",Ya),Dr={};for(const kd of ha){const pm=ai==null?void 0:ai.find(Vu=>Vu.id===kd.agent_id);pm&&(Dr[kd.assistant_id]={agent_name:pm.name||"",agent_email:pm.email||""})}io(Dr)}}}catch(Pt){console.error("Error loading members:",Pt),i({title:"Error",description:"Failed to load members",variant:"destructive"})}finally{_(!1)}},qi=async()=>{try{const{data:Pt,error:dn}=await q.from("app_tiles").select("id, name, icon, app_id, required_tags").order("name");if(dn)throw dn;d(Pt||[])}catch(Pt){console.error("Error loading apps:",Pt),i({title:"Error",description:"Failed to load apps",variant:"destructive"})}},Vi=async Pt=>{if(!ke.name.trim()||!ke.email.trim()){i({title:"Error",description:"Name and email are required",variant:"destructive"});return}if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ke.email)){i({title:"Error",description:"Please enter a valid email address",variant:"destructive"});return}try{const{error:zn}=await q.from("profiles").update({name:ke.name.trim(),email:ke.email.trim(),brokerage_id:ke.brokerage_id||null,phone:ke.phone.trim()||null}).eq("id",Pt);if(zn)throw zn;i({title:"Success",description:"Member details updated successfully"}),Re(null),Mr()}catch(zn){console.error("Error updating member:",zn),i({title:"Error",description:zn.message||"Failed to update member",variant:"destructive"})}},si=async Pt=>{try{const{data:{session:dn}}=await q.auth.getSession(),zn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dn==null?void 0:dn.access_token}`},body:JSON.stringify({userId:Pt})}),Ir=await zn.json();if(!zn.ok)throw new Error(Ir.error||"Failed to resend welcome email");i({title:"Success",description:"Welcome email sent successfully"})}catch(dn){console.error("Error resending welcome email:",dn),i({title:"Error",description:dn.message||"Failed to resend welcome email",variant:"destructive"})}},Yi=async(Pt,dn)=>{try{const{error:zn}=await q.functions.invoke("send-password-reset",{body:{email:Pt,redirectTo:window.location.origin}});if(zn)throw zn;i({title:"Password Reset Sent",description:`Password reset email sent to ${dn}`})}catch(zn){console.error("Error sending password reset:",zn),i({title:"Error",description:zn.message||"Failed to send password reset email",variant:"destructive"})}},Zi=async(Pt,dn)=>{if(confirm(`Are you sure you want to delete ${dn}? This action cannot be undone.`))try{const{data:{session:zn}}=await q.auth.getSession(),Ir=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Pt})}),Gn=await Ir.json();if(!Ir.ok)throw new Error(Gn.error||"Failed to delete user");i({title:"Success",description:"User deleted successfully"}),Mr()}catch(zn){console.error("Error deleting user:",zn),i({title:"Error",description:zn.message||"Failed to delete user",variant:"destructive"})}},aa=async()=>{if(!w.email||!w.name||!w.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}if(w.role==="brokerage_manager"&&!w.brokerage_id){i({title:"Error",description:"Please select a brokerage for this manager",variant:"destructive"});return}j(!0);try{const{data:{session:Pt}}=await q.auth.getSession(),dn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pt==null?void 0:Pt.access_token}`},body:JSON.stringify(w)}),zn=await dn.json();if(!dn.ok)throw new Error(zn.error||"Failed to create user");if(w.role&&w.role!=="user"&&zn.userId){const Ir=w.role==="brokerage_manager"?w.brokerage_id:void 0;await Nn(zn.userId,w.role,"add",Ir)}i({title:"Success",description:`User ${w.email} created successfully`}),S({email:"",name:"",password:"",brokerage_id:"",role:"user",phone:"",trial_days:""}),E(!1),Mr()}catch(Pt){console.error("Error creating user:",Pt),i({title:"Error",description:Pt.message||"Failed to create user",variant:"destructive"})}finally{j(!1)}},Nn=async(Pt,dn,zn,Ir)=>{try{const{data:{session:Gn}}=await q.auth.getSession(),ha={userId:Pt,role:dn,action:zn};if(dn==="brokerage_manager"){if(!Ir){i({title:"Error",description:"Please choose a brokerage for this manager assignment",variant:"destructive"});return}ha.brokerageId=Ir}const Ya=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gn==null?void 0:Gn.access_token}`},body:JSON.stringify(ha)}),ai=await Ya.json();if(!Ya.ok)throw new Error(ai.error||"Failed to manage user role");i({title:"Success",description:`Role ${zn==="add"?"added":"removed"} successfully`}),Mr()}catch(Gn){console.error("Error managing user role:",Gn),i({title:"Error",description:Gn.message||"Failed to manage user role",variant:"destructive"})}},La=(Pt,dn)=>dn.length===0?!0:dn.some(zn=>Pt.includes(zn)),so=async(Pt,dn,zn)=>{const Ir=`${Pt}-${dn.id}`;He(Ir);try{if(zn){const Gn=l.find(Ya=>Ya.id===Pt),ha=dn.required_tags.filter(Ya=>Gn==null?void 0:Gn.tags.includes(Ya));for(const Ya of ha){const{error:ai}=await q.from("user_tags").delete().eq("user_id",Pt).eq("tag",Ya);if(ai)throw ai}i({title:"Access Removed",description:`Removed access to ${dn.name}`})}else if(dn.required_tags.length>0){const{error:Gn}=await q.from("user_tags").insert({user_id:Pt,tag:dn.required_tags[0]});if(Gn)throw Gn;i({title:"Access Granted",description:`Granted access to ${dn.name}`})}await Mr()}catch(Gn){console.error("Error toggling access:",Gn),i({title:"Error",description:Gn.message||"Failed to update access",variant:"destructive"})}finally{He(null)}},tl=async()=>{const Pt=Ge.trim();if(!Pt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Pt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}if(u.find(zn=>zn.name.toLowerCase()===Pt.toLowerCase())){i({title:"Error",description:"A brokerage with this name already exists",variant:"destructive"});return}at(!0);try{const{error:zn}=await q.from("brokerages").insert({name:Pt});if(zn)throw zn;i({title:"Success",description:`Brokerage "${Pt}" created successfully`}),rt(""),Ke(!1),Mr()}catch(zn){console.error("Error creating brokerage:",zn),i({title:"Error",description:zn.message||"Failed to create brokerage",variant:"destructive"})}finally{at(!1)}},jl=Pt=>{bt(Pt),Yt(Pt.name),ut(!0)},No=()=>{bt(null),Yt(""),ut(!1)},jd=async()=>{if(!_t)return;const Pt=$t.trim();if(!Pt){i({title:"Error",description:"Brokerage name is required",variant:"destructive"});return}if(Pt.length>100){i({title:"Error",description:"Brokerage name must be less than 100 characters",variant:"destructive"});return}Ls(!0);try{const{error:dn}=await q.from("brokerages").update({name:Pt}).eq("id",_t.id);if(dn)throw dn;i({title:"Success",description:"Brokerage updated successfully"}),No(),Mr()}catch(dn){console.error("Error updating brokerage:",dn),i({title:"Error",description:dn.message||"Failed to update brokerage",variant:"destructive"})}finally{Ls(!1)}},Bu=async(Pt,dn)=>{var zn;if(!dn||typeof dn!="string"){i({title:"Error",description:"Please select a brokerage first",variant:"destructive"});return}try{const Ir={userId:Pt,role:"brokerage_manager",action:"add",brokerageId:dn};console.debug("[assignManagerToBrokerage] payload",Ir);const{data:{session:Gn}}=await q.auth.getSession(),ha=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gn==null?void 0:Gn.access_token}`},body:JSON.stringify(Ir)}),Ya=await ha.json();if(!ha.ok&&!((zn=Ya.error)!=null&&zn.includes("duplicate")))throw new Error(Ya.error||"Failed to add role");i({title:"Success",description:"Manager assigned to brokerage"}),await Mr()}catch(Ir){console.error("Error assigning manager:",Ir),i({title:"Error",description:Ir.message||"Failed to assign manager",variant:"destructive"})}},kf=Pt=>{gt(Pt),Lt(!0)},$u=async()=>{if(Jt){As(!0);try{const Pt=l.filter(Ir=>Ir.brokerage_id===Jt.id),{data:{session:dn}}=await q.auth.getSession();for(const Ir of Pt){const Gn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${dn==null?void 0:dn.access_token}`},body:JSON.stringify({userId:Ir.id})});if(!Gn.ok){const ha=await Gn.json();console.error(`Failed to delete user ${Ir.email}:`,ha.error)}}const{error:zn}=await q.from("brokerages").delete().eq("id",Jt.id);if(zn)throw zn;i({title:"Success",description:`Brokerage "${Jt.name}" and ${Pt.length} member(s) deleted`}),Lt(!1),gt(null),Mr()}catch(Pt){console.error("Error deleting brokerage:",Pt),i({title:"Error",description:Pt.message||"Failed to delete brokerage",variant:"destructive"})}finally{As(!1)}}},um=Pt=>{$s(Pt),tn(""),Qs(!0)},Uu=()=>{$s(null),tn(""),Qs(!1)},$d=async Pt=>{try{const{error:dn}=await q.from("profiles").update({brokerage_id:null}).eq("id",Pt);if(dn)throw dn;i({title:"Success",description:"User removed from brokerage"}),Mr()}catch(dn){console.error("Error removing user from brokerage:",dn),i({title:"Error",description:dn.message||"Failed to remove user",variant:"destructive"})}},s1=async(Pt,dn)=>{try{const{error:zn}=await q.from("profiles").update({brokerage_id:dn}).eq("id",Pt);if(zn)throw zn;i({title:"Success",description:"User added to brokerage"}),Mr()}catch(zn){console.error("Error adding user to brokerage:",zn),i({title:"Error",description:zn.message||"Failed to add user",variant:"destructive"})}},rj=async()=>{if(!ks||!Pn.email||!Pn.name||!Pn.password){i({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}na(!0);try{const{data:{session:Pt}}=await q.auth.getSession(),dn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pt==null?void 0:Pt.access_token}`},body:JSON.stringify({...Pn,brokerage_id:ks.id,role:"user"})}),zn=await dn.json();if(!dn.ok)throw new Error(zn.error||"Failed to create agent");i({title:"Success",description:`Agent ${Pn.email} created successfully`}),Qn({email:"",name:"",password:"",phone:""}),xn(!1),Mr()}catch(Pt){console.error("Error creating agent:",Pt),i({title:"Error",description:Pt.message||"Failed to create agent",variant:"destructive"})}finally{na(!1)}},hm=Pt=>l.filter(dn=>dn.brokerage_id===Pt),Ey=Pt=>{const dn=hm(Pt);if(!an)return dn;const zn=an.toLowerCase();return dn.filter(Ir=>Ir.name.toLowerCase().includes(zn)||Ir.email.toLowerCase().includes(zn))},Ay=Pt=>l.filter(dn=>dn.brokerage_id!==Pt),Sf=l.filter(Pt=>{var zn;if(O){const Ir=O.toLowerCase();if(!(Pt.name.toLowerCase().includes(Ir)||Pt.email.toLowerCase().includes(Ir)||((zn=Pt.brokerage_name)==null?void 0:zn.toLowerCase().includes(Ir))))return!1}if(Z==="claimed"&&!Pt.claimed||Z==="unclaimed"&&Pt.claimed||W!=="all"&&!Pt.roles.includes(W))return!1;const dn=Pt.is_trial||Pt.subscription_status==="trialing";if(se==="trial"&&!dn||se==="non-trial"&&dn||he==="none"&&Pt.brokerage_id||he!=="all"&&he!=="none"&&Pt.brokerage_id!==he)return!1;if(me!=="all"){if(!Pt.created_at)return!1;const Ir=parseInt(me,10),Gn=Date.now()-Ir*24*60*60*1e3;if(new Date(Pt.created_at).getTime(){var dn;return((dn=Pt.name)==null?void 0:dn.toLowerCase())||""},brokerage:Pt=>{var dn;return((dn=Pt.brokerage_name)==null?void 0:dn.toLowerCase())||""},status:Pt=>Pt.claimed?"active":"pending",role:Pt=>Pt.roles[0]||"",last_login:Pt=>Pt.last_sign_in_at?new Date(Pt.last_sign_in_at).getTime():null,created_at:Pt=>Pt.created_at?new Date(Pt.created_at).getTime():null}),Rh=mm.length,hx=z===0,qu=hx?1:Math.ceil(Rh/z),sl=hx?0:(I-1)*z,o0=hx?Rh:sl+z,mu=mm.slice(sl,o0),l0=Pt=>{D(Pt),F(1)},aj=Pt=>{H(Pt),F(1)},Cf=(Pt,dn)=>{Pt(dn),F(1)},Ka=async(Pt,dn)=>{Ie(!0);try{const zn=l.find(Ya=>Ya.id===Pt);if(!zn)return;const Ir=zn.trial_expires_at?new Date(zn.trial_expires_at):new Date,Gn=new Date(Ir.getTime()+dn*24*60*60*1e3),{error:ha}=await q.from("profiles").update({trial_expires_at:Gn.toISOString()}).eq("id",Pt);if(ha)throw ha;i({title:"Trial Extended",description:`Trial extended by ${dn} days`}),Mr()}catch(zn){console.error("Error extending trial:",zn),i({title:"Error",description:zn.message||"Failed to extend trial",variant:"destructive"})}finally{Ie(!1)}},My=async Pt=>{Me(!0);try{const{error:dn}=await q.from("profiles").update({is_trial:!1,trial_expires_at:null,trial_started_at:null,trial_claimed_at:null}).eq("id",Pt);if(dn)throw dn;i({title:"Account Converted",description:"User has been converted to a full account"}),Mr(),lg()}catch(dn){console.error("Error converting trial:",dn),i({title:"Error",description:dn.message||"Failed to convert account",variant:"destructive"})}finally{Me(!1)}},[Iy,Ym]=N.useState(!1),Zm=async(Pt,dn)=>{if(confirm(`Revert this user to a ${dn}-day free trial? This will clear their paid/grandfathered status. Any active Stripe subscription will need to be cancelled separately.`)){Ym(!0);try{const zn=new Date,Ir=new Date(zn.getTime()+dn*24*60*60*1e3),{error:Gn}=await q.from("profiles").update({is_trial:!0,trial_started_at:zn.toISOString(),trial_expires_at:Ir.toISOString(),trial_claimed_at:zn.toISOString(),is_grandfathered:!1,subscription_status:"none",subscription_end_date:null,subscription_product_id:null,subscription_price_id:null,converted_from_trial_at:null}).eq("id",Pt);if(Gn)throw Gn;i({title:"Reverted to Trial",description:`User is now on a ${dn}-day free trial.`}),Mr()}catch(zn){console.error("Error reverting to trial:",zn),i({title:"Error",description:zn.message||"Failed to revert to trial",variant:"destructive"})}finally{Ym(!1)}}},Ip=async Pt=>{xa(!0);try{const{data:dn}=await q.from("agent_assistant_assignments").select("id, assistant_id, permissions").eq("agent_id",Pt);if(dn&&dn.length>0){const Ir=dn.map(ha=>ha.assistant_id),{data:Gn}=await q.from("profiles").select("id, name, email").in("id",Ir);Yn(dn.map(ha=>{const Ya=Gn==null?void 0:Gn.find(ai=>ai.id===ha.assistant_id);return{id:ha.id,assistant_id:ha.assistant_id,assistant_name:(Ya==null?void 0:Ya.name)||"Unknown",assistant_email:(Ya==null?void 0:Ya.email)||"",permissions:ha.permissions||{}}}))}else Yn([]);const{data:zn}=await q.from("agent_assistant_assignments").select("id, agent_id, permissions").eq("assistant_id",Pt);if(zn&&zn.length>0){const Ir=zn.map(ha=>ha.agent_id),{data:Gn}=await q.from("profiles").select("id, name, email").in("id",Ir);wr(zn.map(ha=>{const Ya=Gn==null?void 0:Gn.find(ai=>ai.id===ha.agent_id);return{id:ha.id,agent_id:ha.agent_id,agent_name:(Ya==null?void 0:Ya.name)||"Unknown",agent_email:(Ya==null?void 0:Ya.email)||"",permissions:ha.permissions||{}}}))}else wr([])}catch(dn){console.error("Error loading assistant data:",dn)}finally{xa(!1)}},mx=Pt=>{Be(Pt),it({name:Pt.name,email:Pt.email,brokerage_id:Pt.brokerage_id||"",phone:Pt.phone||""}),Je(!0),Ip(Pt.id)},lg=()=>{Be(null),Je(!1),it({name:"",email:"",brokerage_id:"",phone:""})},Bb=async()=>{Ae&&(await Vi(Ae.id),lg())},Pp=Pt=>{ot(dn=>{const zn=new Set(dn);return zn.has(Pt)?zn.delete(Pt):zn.add(Pt),zn})},Qm=()=>{if(Qe.size===mu.length&&mu.every(Pt=>Qe.has(Pt.id))){const Pt=new Set(Qe);mu.forEach(dn=>Pt.delete(dn.id)),ot(Pt)}else{const Pt=new Set(Qe);mu.forEach(dn=>Pt.add(dn.id)),ot(Pt)}},Tf=()=>{ot(new Set)},Py=async()=>{if(Qe.size===0)return;Bt(!0);let Pt=0,dn=0;try{const{data:{session:zn}}=await q.auth.getSession();for(const Ir of Qe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Ir})})).ok?Pt++:dn++}catch{dn++}i({title:"Bulk Email Complete",description:`Sent ${Pt} emails${dn>0?`, ${dn} failed`:""}`}),Tf()}catch(zn){i({title:"Error",description:zn.message||"Failed to send emails",variant:"destructive"})}finally{Bt(!1)}},$b=async()=>{if(Qe.size===0)return;Bt(!0);let Pt=0,dn=0;try{const{data:{session:zn}}=await q.auth.getSession();for(const Ir of Qe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-password-reset",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({userId:Ir})})).ok?Pt++:dn++}catch{dn++}i({title:"Bulk Password Reset Complete",description:`Sent ${Pt} reset emails${dn>0?`, ${dn} failed`:""}`}),Tf()}catch(zn){i({title:"Error",description:zn.message||"Failed to send password reset emails",variant:"destructive"})}finally{Bt(!1)}},Nd=async()=>{if(Qe.size===0)return;const Pt=l.filter(Gn=>Qe.has(Gn.id)).map(Gn=>Gn.name).slice(0,5).join(", "),dn=Qe.size>5?` and ${Qe.size-5} more`:"";if(!confirm(`Are you sure you want to delete ${Qe.size} users (${Pt}${dn})? This action cannot be undone.`))return;Bt(!0);let zn=0,Ir=0;try{const{data:{session:Gn}}=await q.auth.getSession();for(const ha of Qe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/delete-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Gn==null?void 0:Gn.access_token}`},body:JSON.stringify({userId:ha})})).ok?zn++:Ir++}catch{Ir++}i({title:"Bulk Delete Complete",description:`Deleted ${zn} users${Ir>0?`, ${Ir} failed`:""}`}),Tf(),Mr()}catch(Gn){i({title:"Error",description:Gn.message||"Failed to delete users",variant:"destructive"})}finally{Bt(!1)}},Lc=async()=>{fs(!0);try{const{data:{session:Pt}}=await q.auth.getSession(),dn=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-phone-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Pt==null?void 0:Pt.access_token}`}});if(!dn.ok){const Ir=await dn.json();throw new Error(Ir.error||"Failed to sync phones")}const zn=await dn.json();i({title:"Phone Sync Complete",description:`Pulled ${zn.summary.pulledFromGHL} from GHL, pushed ${zn.summary.pushedToGHL} to GHL, ${zn.summary.alreadySynced} already synced`}),Mr()}catch(Pt){i({title:"Error",description:Pt.message||"Failed to sync phones with GHL",variant:"destructive"})}finally{fs(!1)}},Xm=async(Pt,dn)=>{ns(Pt);try{const{data:{session:zn}}=await q.auth.getSession(),{data:Ir}=await q.from("profiles").select("phone").eq("id",Pt).single(),Gn=(Ir==null?void 0:Ir.phone)||"",ha=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ghl-tag-sync",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${zn==null?void 0:zn.access_token}`},body:JSON.stringify({email:dn,action:"update",phone:Gn||void 0})});if(!ha.ok){const ai=await ha.json();throw new Error(ai.error||"Failed to sync with GHL")}const Ya=await fetch(`https://services.leadconnectorhq.com/contacts/lookup?locationId=&email=${encodeURIComponent(dn)}`,{method:"GET",headers:{"Content-Type":"application/json"}});i({title:"Phone Synced",description:Gn?`Phone ${Gn} synced to GHL`:"Sync attempted - run bulk sync to pull phone from GHL"}),Mr()}catch(zn){i({title:"Error",description:zn.message||"Failed to sync phone",variant:"destructive"})}finally{ns(null)}},Kc=async Pt=>{await r(Pt)},Jm=()=>{if(Qe.size===0){i({title:"No members selected",description:"Please select members to export",variant:"destructive"});return}const Pt=l.filter(ai=>Qe.has(ai.id)),dn=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],zn=Pt.map(ai=>[ai.name,ai.email,ai.phone||"",ai.brokerage_name||"",ai.roles.join("; "),ai.claimed?"Claimed":"Unclaimed",new Date(ai.created_at).toLocaleDateString()]),Ir=[dn.join(","),...zn.map(ai=>ai.map(Dr=>`"${(Dr||"").replace(/"/g,'""')}"`).join(","))].join(` `),Gn=new Blob([Ir],{type:"text/csv"}),ha=URL.createObjectURL(Gn),Ya=document.createElement("a");Ya.href=ha,Ya.download=`members-export-${new Date().toISOString().split("T")[0]}.csv`,Ya.click(),URL.revokeObjectURL(ha),i({title:"Export complete",description:`Exported ${Pt.length} member(s)`})},Lp=()=>{if(Sf.length===0){i({title:"No members to export",description:"Adjust filters to include at least one member",variant:"destructive"});return}const Pt=["Name","Email","Phone","Brokerage","Roles","Status","Created At"],dn=Sf.map(ai=>[ai.name,ai.email,ai.phone||"",ai.brokerage_name||"",ai.roles.join("; "),ai.claimed?"Claimed":"Unclaimed",ai.created_at?new Date(ai.created_at).toLocaleDateString():""]),zn=[Pt.join(","),...dn.map(ai=>ai.map(Dr=>`"${(Dr||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ir=new Blob([zn],{type:"text/csv"}),Gn=URL.createObjectURL(Ir),ha=document.createElement("a"),Ya=me!=="all"?`-last-${me}days`:"";ha.href=Gn,ha.download=`members-export${Ya}-${new Date().toISOString().split("T")[0]}.csv`,ha.click(),URL.revokeObjectURL(Gn),i({title:"Export complete",description:`Exported ${Sf.length} member(s)`})};return y?e.jsx(Cs,{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(Cs,{title:"Members",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Member Management",description:"Manage users, roles, and permissions",children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>s("/admin/unassigned-members"),className:"gap-2",children:[e.jsx(ic,{className:"h-4 w-4 text-amber-500"}),"Unassigned Members"]})}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:Lc,disabled:Vt,children:[Vt?e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}):e.jsx(Cr,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:Vt?"Syncing...":"Sync Phones with GHL"}),e.jsx("span",{className:"sm:hidden",children:Vt?"Syncing...":"Sync GHL"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>mi(!0),children:[e.jsx(mw,{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(_s,{open:A,onOpenChange:E,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Add Member"}),e.jsx("span",{className:"sm:hidden",children:"Add"})]})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create New User"}),e.jsx(Jn,{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(ne,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",placeholder:"John Doe",value:w.name,onChange:Pt=>S({...w,name:Pt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",placeholder:"john@example.com",value:w.email,onChange:Pt=>S({...w,email:Pt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"password",children:"Password"}),e.jsx(ye,{id:"password",type:"password",placeholder:"Min 6 characters",value:w.password,onChange:Pt=>S({...w,password:Pt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(ye,{id:"phone",type:"tel",placeholder:"555-123-4567",value:w.phone,onChange:Pt=>S({...w,phone:Pt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"brokerage",children:["Brokerage",w.role==="brokerage_manager"?" (required)":""]}),e.jsxs(us,{value:w.brokerage_id||"none",onValueChange:Pt=>S({...w,brokerage_id:Pt==="none"?"":Pt}),children:[e.jsx(ls,{id:"brokerage",children:e.jsx(hs,{placeholder:w.role==="brokerage_manager"?"Select brokerage":"Select brokerage (optional)"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"None"}),u.map(Pt=>e.jsx(Ze,{value:Pt.id,children:Pt.name},Pt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"role",children:"Role"}),e.jsxs(us,{value:w.role,onValueChange:Pt=>S({...w,role:Pt}),children:[e.jsx(ls,{id:"role",children:e.jsx(hs,{placeholder:"Select role"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"user",children:"User"}),e.jsx(Ze,{value:"moderator",children:"Moderator"}),e.jsx(Ze,{value:"brokerage_manager",children:"Brokerage Manager"}),e.jsx(Ze,{value:"admin",children:"Admin"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"trial_days",children:"Trial Period (optional)"}),e.jsxs(us,{value:w.trial_days||"none",onValueChange:Pt=>S({...w,trial_days:Pt==="none"?"":Pt}),children:[e.jsx(ls,{id:"trial_days",children:e.jsx(hs,{placeholder:"No trial (full access)"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No trial (full access)"}),e.jsx(Ze,{value:"7",children:"7-day trial"}),e.jsx(Ze,{value:"30",children:"30-day trial"}),e.jsx(Ze,{value:"60",children:"60-day trial"}),e.jsx(Ze,{value:"90",children:"90-day trial"}),e.jsx(Ze,{value:"365",children:"1-year trial"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Trial accounts don't require a credit card. Access expires after the trial period."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>E(!1),children:"Cancel"}),e.jsx(B,{onClick:aa,disabled:v,children:v?"Creating...":"Create User"})]})]})]})]})]}),e.jsxs(Fr,{defaultValue:new URLSearchParams(window.location.search).get("tab")||"members",className:"space-y-6",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"members",children:"Members"}),e.jsx(Zt,{value:"brokerages",children:"Brokerages"}),e.jsx(Zt,{value:"teams",children:"Teams"}),e.jsx(Zt,{value:"trials",children:"Trial Users"}),e.jsx(Zt,{value:"access",children:"Access Matrix"}),e.jsx(Zt,{value:"celebrations",children:"Celebrations"}),e.jsx(Zt,{value:"deletions",children:"Deletion Log"})]}),e.jsxs(is,{value:"members",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search members...",value:O,onChange:Pt=>l0(Pt.target.value),className:"pl-10 h-9"})]}),e.jsxs(us,{value:Z,onValueChange:Pt=>Cf(Y,Pt),children:[e.jsx(ls,{className:"w-[130px] h-9",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"claimed",children:"Active"}),e.jsx(Ze,{value:"unclaimed",children:"Pending"})]})]}),e.jsxs(us,{value:W,onValueChange:Pt=>Cf(ee,Pt),children:[e.jsx(ls,{className:"w-[130px] h-9",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Roles"}),e.jsx(Ze,{value:"admin",children:"Admin"}),e.jsx(Ze,{value:"brokerage_manager",children:"Manager"}),e.jsx(Ze,{value:"assistant",children:"Assistant"}),e.jsx(Ze,{value:"user",children:"User"})]})]}),e.jsxs(us,{value:se,onValueChange:Pt=>Cf(oe,Pt),children:[e.jsx(ls,{className:"w-[130px] h-9",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Users"}),e.jsx(Ze,{value:"trial",children:"Trial Only"}),e.jsx(Ze,{value:"non-trial",children:"Full Only"})]})]}),e.jsxs(us,{value:he,onValueChange:Pt=>Cf(ce,Pt),children:[e.jsx(ls,{className:"w-[150px] h-9",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Brokerages"}),e.jsx(Ze,{value:"none",children:"No Brokerage"}),u.map(Pt=>e.jsx(Ze,{value:Pt.id,children:Pt.name},Pt.id))]})]}),e.jsxs(us,{value:me,onValueChange:Pt=>Cf(le,Pt),children:[e.jsx(ls,{className:"w-[150px] h-9",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"Any Join Date"}),e.jsx(Ze,{value:"30",children:"Joined Last 30 Days"}),e.jsx(Ze,{value:"60",children:"Joined Last 60 Days"}),e.jsx(Ze,{value:"90",children:"Joined Last 90 Days"})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-9",onClick:Lp,title:"Export currently filtered members to CSV",children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"}),"Export Filtered"]}),(O||Z!=="all"||W!=="all"||se!=="all"||he!=="all"||me!=="all")&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-9",onClick:()=>{D(""),Y("all"),ee("all"),oe("all"),ce("all"),le("all"),F(1)},children:[e.jsx($n,{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:hx?`Showing all ${Rh} members`:`Showing ${sl+1}-${Math.min(o0,Rh)} of ${Rh} members`}),e.jsxs(us,{value:z.toString(),onValueChange:Pt=>aj(Number(Pt)),children:[e.jsx(ls,{className:"h-9 w-[110px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"50",children:"50 / page"}),e.jsx(Ze,{value:"100",children:"100 / page"}),e.jsx(Ze,{value:"250",children:"250 / page"}),e.jsx(Ze,{value:"0",children:"All"})]})]})]})]}),Qe.size>0&&e.jsxs("div",{className:"flex flex-col gap-2 p-3 bg-primary/10 border border-primary/20 rounded-lg",children:[mu.length>0&&mu.every(Pt=>Qe.has(Pt.id))&&mm.length>Qe.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 ",Qe.size," on this page are selected."]}),e.jsxs(B,{size:"sm",variant:"link",className:"h-auto p-0 text-primary",onClick:()=>ot(new Set(mm.map(Pt=>Pt.id))),children:["Select all ",mm.length," filtered members"]})]}),mm.length>0&&Qe.size===mm.length&&e.jsxs("div",{className:"px-1 text-sm text-muted-foreground",children:["All ",mm.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(S2,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm font-medium",children:[Qe.size," selected"]})]}),e.jsx("div",{className:"flex-1"}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:Py,disabled:St,children:[St?e.jsx(rs,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Gs,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Resend Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:$b,disabled:St,children:[St?e.jsx(rs,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(Ug,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Password Reset"}),e.jsx("span",{className:"sm:hidden",children:"Reset"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>ge(!0),disabled:St,className:"bg-primary/5 border-primary/30 text-primary hover:bg-primary/10",children:[e.jsx(uw,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Send Event Invite"}),e.jsx("span",{className:"sm:hidden",children:"Invite"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:Jm,children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Export"}),e.jsx("span",{className:"sm:hidden",children:"CSV"})]}),e.jsxs(B,{size:"sm",variant:"destructive",onClick:Nd,disabled:St,children:[St?e.jsx(rs,{className:"h-4 w-4 animate-spin mr-1"}):e.jsx(_n,{className:"h-4 w-4 mr-1"}),e.jsx("span",{className:"hidden sm:inline",children:"Delete"}),e.jsx("span",{className:"sm:hidden",children:"Del"})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:Tf,disabled:St,children:e.jsx($n,{className:"h-4 w-4"})})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"w-[50px]",children:e.jsx(hi,{checked:mu.length>0&&mu.every(Pt=>Qe.has(Pt.id)),onCheckedChange:Qm,"aria-label":"Select all on page"})}),e.jsx(Sc,{sortKey:"name",currentSortKey:mh,currentDirection:ux,onSort:mo,children:"Name"}),e.jsx(Sc,{sortKey:"brokerage",currentSortKey:mh,currentDirection:ux,onSort:mo,children:"Brokerage"}),e.jsx(Sc,{sortKey:"status",currentSortKey:mh,currentDirection:ux,onSort:mo,children:"Status"}),e.jsx(Sc,{sortKey:"role",currentSortKey:mh,currentDirection:ux,onSort:mo,children:"Role"}),e.jsx(Sc,{sortKey:"last_login",currentSortKey:mh,currentDirection:ux,onSort:mo,children:"Last Login"}),e.jsx(Sc,{sortKey:"created_at",currentSortKey:mh,currentDirection:ux,onSort:mo,children:"Member Since"}),e.jsx(Tt,{className:"w-[100px]"})]})}),e.jsx(da,{children:mu.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:8,className:"text-center py-12 text-muted-foreground",children:"No members found"})}):mu.map(Pt=>e.jsxs(Hs,{className:`hover:bg-muted/30 ${Qe.has(Pt.id)?"bg-primary/5":""}`,children:[e.jsx(ht,{children:e.jsx(hi,{checked:Qe.has(Pt.id),onCheckedChange:()=>Pp(Pt.id),"aria-label":`Select ${Pt.name}`})}),e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("button",{onClick:()=>mx(Pt),className:"text-primary hover:underline font-medium text-left",children:Pt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Pt.email})]})}),e.jsx(ht,{className:"text-muted-foreground",children:Pt.brokerage_name||"—"}),e.jsx(ht,{children:e.jsx("div",{className:"flex flex-col",children:(()=>{const dn=Pt.trial_expires_at||Pt.subscription_end_date;if((Pt.is_trial||Pt.subscription_status==="trialing")&&dn){const Ir=Math.ceil((new Date(dn).getTime()-Date.now())/864e5),Gn=Ir<=0,ha=Ir<=3;return e.jsx(Ue,{variant:"outline",className:Mt("w-fit",Gn?"border-destructive text-destructive":ha?"border-amber-500 text-amber-600":"border-violet-300 text-violet-700 bg-violet-50"),children:Gn?"Trial Expired":`Trial · ${Ir}d left`})}return e.jsx(Ue,{variant:Pt.claimed?"default":"secondary",className:Pt.claimed?"bg-primary text-primary-foreground w-fit":"w-fit",children:Pt.claimed?"Active":"Pending"})})()})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex flex-col",children:[Pt.roles.length>0?e.jsx("span",{className:"text-sm capitalize",children:Pt.roles[0]}):e.jsx("span",{className:"text-muted-foreground",children:"—"}),Pt.roles.includes("assistant")&&Ki[Pt.id]&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:["→ ",Ki[Pt.id].agent_name||Ki[Pt.id].agent_email]})]})}),e.jsx(ht,{className:"text-muted-foreground",children:Pt.last_sign_in_at?new Date(Pt.last_sign_in_at).toLocaleDateString():"—"}),e.jsx(ht,{className:"text-muted-foreground",children:Pt.created_at?new Date(Pt.created_at).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"}):"—"}),e.jsx(ht,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",onClick:()=>{On(Pt),ys(!0)},title:"Send celebration",children:e.jsx(ih,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>mx(Pt),title:"Edit member",children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Xm(Pt.id,Pt.email),disabled:lt===Pt.id,title:"Sync phone with GHL",children:lt===Pt.id?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Cr,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>si(Pt.id),title:"Resend welcome email",children:e.jsx(Gs,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>Yi(Pt.email,Pt.name),title:"Send password reset",children:e.jsx(SA,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Kc(Pt.id),disabled:a||Pt.id===(t==null?void 0:t.id),title:Pt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Pt.name}`,children:a?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(CA,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Zi(Pt.id,Pt.name),title:"Delete user",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Pt.id))})]})}),qu>1&&e.jsxs("div",{className:"flex items-center justify-between px-2 py-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Page ",I," of ",qu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>F(1),disabled:I===1,children:"First"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Pt=>Math.max(1,Pt-1)),disabled:I===1,children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex items-center gap-1",children:Array.from({length:Math.min(5,qu)},(Pt,dn)=>{let zn;return qu<=5||I<=3?zn=dn+1:I>=qu-2?zn=qu-4+dn:zn=I-2+dn,e.jsx(B,{variant:I===zn?"default":"outline",size:"sm",className:"h-8 w-8 p-0",onClick:()=>F(zn),children:zn},zn)})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Pt=>Math.min(qu,Pt+1)),disabled:I===qu,children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>F(qu),disabled:I===qu,children:"Last"})]})]})]}),e.jsx(_s,{open:we,onOpenChange:Je,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Edit Member"}),e.jsx(Jn,{children:"Update member details, roles, and app access"})]}),Ae&&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(ne,{htmlFor:"edit-name",children:"Name"}),e.jsx(ye,{id:"edit-name",value:ke.name,onChange:Pt=>it({...ke,name:Pt.target.value}),maxLength:100})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"edit-email",children:"Email"}),e.jsx(ye,{id:"edit-email",type:"email",value:ke.email,onChange:Pt=>it({...ke,email:Pt.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(ne,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(ye,{id:"edit-phone",type:"tel",value:ke.phone,onChange:Pt=>it({...ke,phone:Pt.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"edit-brokerage",children:"Brokerage"}),e.jsxs(us,{value:ke.brokerage_id||"none",onValueChange:Pt=>it({...ke,brokerage_id:Pt==="none"?"":Pt}),children:[e.jsx(ls,{id:"edit-brokerage",children:e.jsx(hs,{placeholder:"Select brokerage"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"None"}),u.map(Pt=>e.jsx(Ze,{value:Pt.id,children:Pt.name},Pt.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:[Ae.roles.map(Pt=>e.jsxs(Ue,{variant:"default",className:"gap-1",children:[e.jsx(Ih,{className:"h-3 w-3"}),Pt,Pt==="brokerage_manager"?e.jsx("span",{className:"text-xs text-muted-foreground ml-1",children:"(manage in Brokerages tab)"}):e.jsx("button",{onClick:()=>Nn(Ae.id,Pt,"remove"),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove role",children:e.jsx($n,{className:"h-3 w-3"})})]},Pt)),Ae.roles.length===0&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"No roles assigned"})]}),e.jsxs(us,{onValueChange:Pt=>Nn(Ae.id,Pt,"add"),children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Add role..."})}),e.jsxs(cs,{children:[!Ae.roles.includes("admin")&&e.jsx(Ze,{value:"admin",children:"Admin"}),!Ae.roles.includes("user")&&e.jsx(Ze,{value:"user",children:"User"})]})]}),!Ae.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"})]}),(vn.length>0||_r.length>0||Ae.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(An,{className:"h-4 w-4"}),"Assistant Relationships"]}),Er?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):e.jsxs("div",{className:"space-y-3",children:[vn.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:"}),vn.map(Pt=>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:Pt.assistant_name}),e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Assistant"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Pt.assistant_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Pt.permissions).filter(([,dn])=>dn).map(([dn])=>e.jsx(Ue,{variant:"secondary",className:"text-[10px] capitalize",children:dn},dn))})]},Pt.id))]}),_r.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:"}),_r.map(Pt=>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:Pt.agent_name}),e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Agent"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Pt.agent_email}),e.jsx("div",{className:"flex flex-wrap gap-1 mt-1",children:Object.entries(Pt.permissions).filter(([,dn])=>dn).map(([dn])=>e.jsx(Ue,{variant:"secondary",className:"text-[10px] capitalize",children:dn},dn))})]},Pt.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(Pt=>{const dn=La(Ae.tags,Pt.required_tags),zn=`${Ae.id}-${Pt.id}`,Ir=je===zn,Gn=Pt.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:Pt.icon}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:Pt.name}),Gn&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Available to all members"})]})]}),e.jsx("div",{className:"flex items-center gap-2",children:Ir?e.jsx(rs,{className:"h-4 w-4 animate-spin text-muted-foreground"}):Gn?e.jsx(Ue,{variant:"secondary",className:"text-xs",children:"Always On"}):e.jsx(jn,{checked:dn,onCheckedChange:()=>so(Ae.id,Pt,dn)})})]},Pt.id)})})]}),(Ae.is_trial||Ae.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(pr,{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:[Ae.trial_expires_at&&e.jsx(_He,{expiresAt:Ae.trial_expires_at}),!Ae.trial_expires_at&&Ae.subscription_status==="trialing"&&Ae.subscription_end_date&&e.jsx(_He,{expiresAt:Ae.subscription_end_date})]}),(Ae.trial_expires_at||Ae.subscription_end_date)&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["Expires: ",new Date(Ae.trial_expires_at||Ae.subscription_end_date).toLocaleDateString()]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Ka(Ae.id,7),disabled:Te,children:[e.jsx(Lg,{className:"h-4 w-4 mr-1"}),"+7 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Ka(Ae.id,14),disabled:Te,children:[e.jsx(Lg,{className:"h-4 w-4 mr-1"}),"+14 Days"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Ka(Ae.id,30),disabled:Te,children:[e.jsx(Lg,{className:"h-4 w-4 mr-1"}),"+30 Days"]}),e.jsxs(B,{size:"sm",variant:"default",onClick:()=>My(Ae.id),disabled:Ce,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(xb,{className:"h-4 w-4 mr-1"}),"Convert to Full Account"]})]}),Ae.trial_started_at&&e.jsxs("div",{className:"mt-3 text-xs text-muted-foreground",children:["Trial started: ",new Date(Ae.trial_started_at).toLocaleDateString(),Ae.trial_claimed_at&&e.jsxs("span",{children:[" • Claimed: ",new Date(Ae.trial_claimed_at).toLocaleDateString()]})]})]})]}),!(Ae.is_trial||Ae.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(pr,{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(Pt=>e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Zm(Ae.id,Pt),disabled:Iy,children:[e.jsx(Lg,{className:"h-4 w-4 mr-1"}),Pt,"-day trial"]},Pt))})]})]}),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:[Ae.email_confirmed_at&&e.jsxs("div",{children:["Claimed: ",new Date(Ae.email_confirmed_at).toLocaleString()]}),Ae.last_sign_in_at&&e.jsxs("div",{children:["Last login: ",new Date(Ae.last_sign_in_at).toLocaleString()]}),e.jsxs("div",{children:["Created: ",new Date(Ae.created_at).toLocaleString()]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:lg,children:"Cancel"}),e.jsx(B,{onClick:Bb,children:"Save Changes"})]})]})}),e.jsxs(is,{value:"access",children:[c.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"No apps configured yet"}),e.jsx(B,{onClick:()=>s("/admin/apps"),children:"Configure Apps"})]})}):e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Member Access Matrix"}),e.jsx(Vn,{children:"Toggle switches to grant or revoke app access for each member"})]}),e.jsxs("div",{className:"relative w-full sm:w-72",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents by name or email...",value:O,onChange:Pt=>{D(Pt.target.value),F(1)},className:"pl-9"})]})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left p-4 font-semibold sticky left-0 bg-card z-10",children:"Member"}),c.map(Pt=>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:Pt.icon}),e.jsx("span",{className:"text-sm",children:Pt.name})]})},Pt.id))]})}),e.jsxs("tbody",{children:[mu.map(Pt=>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:Pt.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Pt.email})]})}),c.map(dn=>{const zn=La(Pt.tags,dn.required_tags),Ir=`${Pt.id}-${dn.id}`,Gn=je===Ir;return e.jsx("td",{className:"p-4 text-center",children:e.jsx("div",{className:"flex items-center justify-center",children:Gn?e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"}):e.jsx(jn,{checked:zn,onCheckedChange:()=>so(Pt.id,dn,zn),disabled:dn.required_tags.length===0})})},dn.id)})]},Pt.id)),mu.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:c.length+1,className:"p-8 text-center text-muted-foreground",children:"No members found"})})]})]})}),qu>1&&e.jsxs("div",{className:"flex items-center justify-between px-2 py-4 border-t",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Showing ",sl+1,"-",Math.min(o0,Rh)," of ",Rh," • Page ",I," of ",qu]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Pt=>Math.max(1,Pt-1)),disabled:I===1,children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>F(Pt=>Math.min(qu,Pt+1)),disabled:I===qu,children:e.jsx(ga,{className:"h-4 w-4"})})]})]})]})]}),e.jsx("div",{className:"mt-6",children:e.jsx(B,{variant:"outline",onClick:()=>s("/admin/apps"),children:"Manage Apps"})})]}),e.jsxs(is,{value:"brokerages",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-1",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:Ar,onChange:Pt=>Hn(Pt.target.value),className:"pl-10"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground whitespace-nowrap",children:[u.filter(Pt=>Pt.name.toLowerCase().includes(Ar.toLowerCase())).length," of ",u.length," brokerages"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{const Pt=[];for(const Ya of u){const ai=p[Ya.id]??[];for(const Dr of ai){const kd=l.find(pm=>pm.id===Dr);if(kd){const pm=(kd.name||"").trim().split(/\s+/),Vu=pm[0]||"",cg=pm.slice(1).join(" ")||"";Pt.push({firstName:Vu,lastName:cg,email:kd.email,brokerageName:Ya.name})}}}if(Pt.length===0){i({title:"No managers found to export"});return}const zn=[["First Name","Last Name","Email","Brokerage Name"].join(","),...Pt.map(Ya=>[Ya.firstName,Ya.lastName,Ya.email,Ya.brokerageName].map(ai=>`"${(ai||"").replace(/"/g,'""')}"`).join(","))].join(` `),Ir=new Blob([zn],{type:"text/csv"}),Gn=URL.createObjectURL(Ir),ha=document.createElement("a");ha.href=Gn,ha.download=`brokerage-managers-${new Date().toISOString().slice(0,10)}.csv`,ha.click(),URL.revokeObjectURL(Gn),i({title:`Exported ${Pt.length} managers`})},children:[e.jsx(Ia,{className:"mr-2 h-4 w-4"}),"Export Managers"]}),e.jsxs(_s,{open:$e,onOpenChange:Ke,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Ua,{className:"mr-2 h-4 w-4"}),"Add Brokerage"]})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create New Brokerage"}),e.jsx(Jn,{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(ne,{htmlFor:"brokerage-name",children:"Brokerage Name"}),e.jsx(ye,{id:"brokerage-name",placeholder:"Enter brokerage name",value:Ge,onChange:Pt=>rt(Pt.target.value),maxLength:100})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ke(!1),children:"Cancel"}),e.jsx(B,{onClick:tl,disabled:tt,children:tt?"Creating...":"Create Brokerage"})]})]})]})]})]}),e.jsx("div",{className:"border rounded-lg bg-card overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Brokerage Name"}),e.jsx(Tt,{className:"font-semibold",children:"Manager(s)"}),e.jsx(Tt,{className:"font-semibold",children:"Agents"}),e.jsx(Tt,{className:"w-[150px]"})]})}),e.jsx(da,{children:(()=>{const Pt=u.filter(dn=>dn.name.toLowerCase().includes(Ar.toLowerCase()));return Pt.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:4,className:"text-center py-12 text-muted-foreground",children:Ar?"No brokerages match your search":"No brokerages found"})}):Pt.map(dn=>{const zn=l.filter(Ya=>Ya.brokerage_id===dn.id),Gn=(p[dn.id]??[]).map(Ya=>l.find(ai=>ai.id===Ya)).filter(Boolean),ha=zn.length;return e.jsxs(Hs,{className:"hover:bg-muted/30",children:[e.jsx(ht,{children:e.jsx("button",{onClick:()=>jl(dn),className:"text-primary hover:underline font-medium",children:dn.name})}),e.jsx(ht,{children:Gn.length>0?e.jsx("div",{className:"flex flex-wrap gap-1",children:Gn.map(Ya=>e.jsx(Ue,{variant:"secondary",className:"text-xs",children:Ya.name},Ya.id))}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"No manager"})}),e.jsxs(ht,{children:[ha," member",ha!==1?"s":""]}),e.jsx(ht,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"h-8",onClick:()=>um(dn),children:[e.jsx(An,{className:"h-4 w-4 mr-1"}),"Manage"]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>jl(dn),title:"Edit brokerage",children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>kf(dn),title:"Delete brokerage",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},dn.id)})})()})]})}),e.jsx(_s,{open:Ye,onOpenChange:ut,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Edit Brokerage"}),e.jsx(Jn,{children:"Update brokerage details and manage managers"})]}),_t&&e.jsxs("div",{className:"space-y-6 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"edit-brokerage-name",children:"Brokerage Name"}),e.jsx(ye,{id:"edit-brokerage-name",value:$t,onChange:Pt=>Yt(Pt.target.value),maxLength:100})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{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 dn=(p[_t.id]??[]).map(zn=>l.find(Ir=>Ir.id===zn)).filter(Boolean);return dn.length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No managers assigned"}):dn.map(zn=>e.jsxs(Ue,{variant:"default",className:"gap-1",children:[e.jsx(Ih,{className:"h-3 w-3"}),zn.name,e.jsx("button",{onClick:()=>Nn(zn.id,"brokerage_manager","remove",_t.id),className:"ml-1 rounded-full hover:bg-destructive/20",title:"Remove manager from this brokerage",children:e.jsx($n,{className:"h-3 w-3"})})]},zn.id))})()}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm text-muted-foreground",children:"Assign manager from existing members:"}),e.jsxs(il,{open:Ts,onOpenChange:Un,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":Ts,className:"w-full justify-between",children:["Search for a member...",e.jsx(gr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-full p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search by name or email..."}),e.jsxs(Qg,{className:"max-h-[200px]",children:[e.jsx(Xg,{children:"No members found."}),e.jsx(Jg,{children:(()=>{const Pt=new Set(p[_t.id]??[]);return l.filter(dn=>!Pt.has(dn.id)&&(n||dn.brokerage_id===_t.id)).map(dn=>e.jsxs(Zf,{value:`${dn.name} ${dn.email}`,onSelect:()=>{Bu(dn.id,_t.id),Un(!1)},children:[dn.name," (",dn.email,")"]},dn.id))})()})]})]})})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Members in this Brokerage"}),e.jsx("div",{className:"max-h-32 overflow-y-auto border rounded p-2",children:l.filter(Pt=>Pt.brokerage_id===_t.id).length===0?e.jsx("span",{className:"text-sm text-muted-foreground",children:"No members"}):l.filter(Pt=>Pt.brokerage_id===_t.id).map(Pt=>e.jsxs("div",{className:"text-sm py-1 flex items-center justify-between",children:[e.jsx("span",{children:Pt.name}),Pt.roles.includes("brokerage_manager")&&e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Manager"})]},Pt.id))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:No,children:"Cancel"}),e.jsx(B,{onClick:jd,disabled:Ds,children:Ds?"Saving...":"Save Changes"})]})]})}),e.jsx(_s,{open:xs,onOpenChange:Lt,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{className:"text-destructive",children:"Delete Brokerage"}),e.jsxs(Jn,{children:['Are you sure you want to delete "',Jt==null?void 0:Jt.name,'"?']})]}),e.jsx("div",{className:"py-4",children:e.jsxs("div",{className:"bg-destructive/10 border border-destructive/20 rounded-lg p-4 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-destructive",children:"Warning: This action cannot be undone!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"This will permanently delete:"}),e.jsxs("ul",{className:"text-sm text-muted-foreground list-disc list-inside",children:[e.jsxs("li",{children:['The brokerage "',Jt==null?void 0:Jt.name,'"']}),e.jsxs("li",{children:["All ",l.filter(Pt=>Pt.brokerage_id===(Jt==null?void 0:Jt.id)).length," member(s) assigned to this brokerage"]}),e.jsx("li",{children:"All their data, roles, and access"})]})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Lt(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:$u,disabled:zt,children:zt?"Deleting...":"Yes, Delete Brokerage"})]})]})}),e.jsx(_s,{open:Xt,onOpenChange:Qs,children:e.jsxs(bs,{className:"max-w-4xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-5 w-5"}),"Manage ",ks==null?void 0:ks.name]}),e.jsx(Jn,{children:"Add, remove, or manage users in this brokerage"})]}),ks&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search members...",value:an,onChange:Pt=>tn(Pt.target.value),className:"pl-10 h-9"})]}),e.jsxs(_s,{open:er,onOpenChange:xn,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Fo,{className:"h-4 w-4 mr-1"}),"Add New Agent"]})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Add New Agent"}),e.jsxs(Jn,{children:["Create a new agent for ",ks.name]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"agent-name",children:"Name"}),e.jsx(ye,{id:"agent-name",placeholder:"John Doe",value:Pn.name,onChange:Pt=>Qn({...Pn,name:Pt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"agent-email",children:"Email"}),e.jsx(ye,{id:"agent-email",type:"email",placeholder:"john@example.com",value:Pn.email,onChange:Pt=>Qn({...Pn,email:Pt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"agent-password",children:"Password"}),e.jsx(ye,{id:"agent-password",type:"password",placeholder:"Min 6 characters",value:Pn.password,onChange:Pt=>Qn({...Pn,password:Pt.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"agent-phone",children:"Phone (optional)"}),e.jsx(ye,{id:"agent-phone",type:"tel",placeholder:"555-123-4567",value:Pn.phone,onChange:Pt=>Qn({...Pn,phone:Pt.target.value})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>xn(!1),children:"Cancel"}),e.jsx(B,{onClick:rj,disabled:sa,children:sa?"Creating...":"Create Agent"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{className:"text-sm text-muted-foreground whitespace-nowrap",children:"Add existing user:"}),e.jsxs(il,{open:ir,onOpenChange:Tr,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":ir,className:"w-[300px] justify-between",children:["Select a user to add...",e.jsx(gr,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search users...",value:ts,onValueChange:Fe}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:"No users found."}),e.jsx(Jg,{children:Ay(ks.id).filter(Pt=>ts===""||Pt.name.toLowerCase().includes(ts.toLowerCase())||Pt.email.toLowerCase().includes(ts.toLowerCase())).map(Pt=>e.jsxs(Zf,{value:`${Pt.name} ${Pt.email}`,onSelect:()=>{s1(Pt.id,ks.id),Tr(!1),Fe("")},children:[Pt.name," (",Pt.email,")"]},Pt.id))})]})]})})]})]}),e.jsx("div",{className:"flex-1 overflow-auto border rounded-lg",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/30 hover:bg-muted/30",children:[e.jsx(Tt,{className:"font-semibold",children:"Name"}),e.jsx(Tt,{className:"font-semibold",children:"Email"}),e.jsx(Tt,{className:"font-semibold",children:"Status"}),e.jsx(Tt,{className:"font-semibold",children:"Role"}),e.jsx(Tt,{className:"w-[120px]"})]})}),e.jsx(da,{children:Ey(ks.id).length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:an?"No matching members found":"No members in this brokerage"})}):Ey(ks.id).map(Pt=>e.jsxs(Hs,{className:"hover:bg-muted/30",children:[e.jsx(ht,{className:"font-medium",children:Pt.name}),e.jsx(ht,{className:"text-muted-foreground",children:Pt.email}),e.jsx(ht,{children:Pt.claimed?e.jsx(Ue,{variant:"default",className:"bg-green-500/10 text-green-600 hover:bg-green-500/20",children:"Active"}):e.jsx(Ue,{variant:"secondary",children:"Pending"})}),e.jsx(ht,{children:Pt.roles.includes("brokerage_manager")?e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(Ih,{className:"h-3 w-3"}),"Manager"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Agent"})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex gap-1 justify-end",children:[!Pt.claimed&&e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>si(Pt.id),title:"Resend welcome email",children:e.jsx(Gs,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",onClick:()=>$d(Pt.id),title:"Remove from brokerage",children:e.jsx($n,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:()=>Kc(Pt.id),disabled:a||Pt.id===(t==null?void 0:t.id),title:Pt.id===(t==null?void 0:t.id)?"Cannot impersonate yourself":`Login as ${Pt.name}`,children:a?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(CA,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>Zi(Pt.id,Pt.name),title:"Delete user",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Pt.id))})]})}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[hm(ks.id).length," total member",hm(ks.id).length!==1?"s":""," •",hm(ks.id).filter(Pt=>Pt.roles.includes("brokerage_manager")).length," manager",hm(ks.id).filter(Pt=>Pt.roles.includes("brokerage_manager")).length!==1?"s":""]})]}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:Uu,children:"Close"})})]})})]}),e.jsx(is,{value:"teams",children:e.jsx(ybs,{})}),e.jsx(is,{value:"trials",children:e.jsx(mbs,{})}),e.jsx(is,{value:"celebrations",children:e.jsx(hbs,{})}),e.jsx(is,{value:"deletions",children:e.jsx(fbs,{})})]})]}),e.jsx(I0t,{open:Es,onOpenChange:mi,brokerages:u,onSuccess:Mr}),mn&&e.jsx(P0t,{open:Vs,onOpenChange:Pt=>{ys(Pt),Pt||On(null)},userId:mn.id,userName:mn.name}),e.jsx(vbs,{open:ve,onOpenChange:ge,recipients:l.filter(Pt=>Qe.has(Pt.id)).map(Pt=>({id:Pt.id,name:Pt.name,email:Pt.email}))})]})};function _bs(){const{toast:s}=Fa(),t=Kt(),[n,r]=N.useState(""),[a,i]=N.useState(new Set),[l,o]=N.useState({}),[c,d]=N.useState({}),[u,h]=N.useState(""),[p,f]=N.useState(!1),{data:y=[],isLoading:_}=dt({queryKey:["unassigned-members"],queryFn:async()=>{const{data:I,error:F}=await q.from("profiles").select("id, name, email, phone, created_at, subscription_status").is("brokerage_id",null).or("subscription_status.is.null,subscription_status.eq.none").order("created_at",{ascending:!1});if(F)throw F;return I||[]}}),{data:v=[]}=dt({queryKey:["brokerages-all"],queryFn:async()=>{const{data:I,error:F}=await q.from("brokerages").select("id, name").order("name");if(F)throw F;return I||[]}}),j=N.useMemo(()=>{const I=n.toLowerCase().trim();return I?y.filter(F=>(F.name||"").toLowerCase().includes(I)||(F.email||"").toLowerCase().includes(I)||(F.phone||"").toLowerCase().includes(I)):y},[y,n]),w=N.useMemo(()=>{var F;const I=new Map;for(const z of y){const H=(F=(z.email||"").split("@")[1])==null?void 0:F.toLowerCase();H&&(["gmail.com","yahoo.com","hotmail.com","outlook.com","icloud.com","aol.com","me.com","comcast.net"].includes(H)||I.set(H,(I.get(H)||0)+1))}return Array.from(I.entries()).sort((z,H)=>H[1]-z[1]).slice(0,10)},[y]),S=I=>{i(F=>{const z=new Set(F);return z.has(I)?z.delete(I):z.add(I),z})},A=()=>{a.size===j.length?i(new Set):i(new Set(j.map(I=>I.id)))},E=async(I,F)=>{if(F){d(z=>({...z,[I]:!0}));try{const{data:z,error:H}=await q.functions.invoke("assign-brokerage",{body:{userId:I,brokerageId:F}});if(H)throw H;if(z!=null&&z.error)throw new Error(z.error);s({title:"Assigned",description:"Member added to brokerage."}),t.invalidateQueries({queryKey:["unassigned-members"]}),i(Z=>{const Y=new Set(Z);return Y.delete(I),Y})}catch(z){s({title:"Failed",description:z.message,variant:"destructive"})}finally{d(z=>({...z,[I]:!1}))}}},O=async()=>{if(!u||a.size===0)return;f(!0);let I=0,F=0;for(const z of a)try{const{data:H,error:Z}=await q.functions.invoke("assign-brokerage",{body:{userId:z,brokerageId:u}});if(Z||H!=null&&H.error)throw new Error((Z==null?void 0:Z.message)||H.error);I++}catch{F++}f(!1),s({title:`Assigned ${I}${F?`, ${F} failed`:""}`,description:"Bulk assignment complete.",variant:F?"destructive":"default"}),i(new Set),h(""),t.invalidateQueries({queryKey:["unassigned-members"]})},D=(I,F)=>{const z={...l};for(const H of y)(H.email||"").toLowerCase().endsWith(`@${I}`)&&(z[H.id]=F);o(z),s({title:"Suggestions applied",description:`Pre-filled brokerage for @${I}`})};return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Unassigned Members",description:"Members with no brokerage and no active subscription — likely missed brokerage invites."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4"})," Orphan members"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-3xl font-bold",children:y.length})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4"})," Selected"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-3xl font-bold",children:a.size})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-sm font-medium text-muted-foreground flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," Top email domains"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-3xl font-bold",children:w.length})})]})]}),w.length>0&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Domain suggestions"})}),e.jsx(Ee,{children:e.jsx("div",{className:"flex flex-wrap gap-2",children:w.map(([I,F])=>{const z=v.find(H=>H.name.toLowerCase().replace(/[^a-z0-9]/g,"").includes(I.split(".")[0].toLowerCase()));return e.jsxs("div",{className:"flex items-center gap-2 rounded-md border bg-muted/30 px-3 py-2",children:[e.jsxs("span",{className:"font-mono text-sm",children:["@",I]}),e.jsx(Ue,{variant:"secondary",children:F}),e.jsxs(us,{onValueChange:H=>D(I,H),defaultValue:z==null?void 0:z.id,children:[e.jsx(ls,{className:"h-8 w-[220px]",children:e.jsx(hs,{placeholder:"Apply brokerage…"})}),e.jsx(cs,{children:v.map(H=>e.jsx(Ze,{value:H.id,children:H.name},H.id))})]})]},I)})})})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"relative w-full md:w-96",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:n,onChange:I=>r(I.target.value),placeholder:"Search name, email, phone…",className:"pl-9"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(ls,{className:"w-[240px]",children:e.jsx(hs,{placeholder:"Bulk assign to brokerage…"})}),e.jsx(cs,{children:v.map(I=>e.jsx(Ze,{value:I.id,children:I.name},I.id))})]}),e.jsxs(B,{onClick:O,disabled:!u||a.size===0||p,children:[p&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Assign ",a.size||""]})]})]}),e.jsx(Ee,{children:_?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsx("div",{className:"py-12 text-center text-muted-foreground",children:"🎉 No unassigned members."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-10",children:e.jsx(hi,{checked:a.size===j.length&&j.length>0,onCheckedChange:A})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Signed up"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Assign to brokerage"}),e.jsx(Tt,{className:"w-24"})]})}),e.jsx(da,{children:j.map(I=>{const F=l[I.id]||"";return e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsx(hi,{checked:a.has(I.id),onCheckedChange:()=>S(I.id)})}),e.jsx(ht,{className:"font-medium",children:I.name||"—"}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:I.email}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Uo(new Date(I.created_at),{addSuffix:!0})}),e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",children:I.subscription_status||"none"})}),e.jsx(ht,{children:e.jsxs(us,{value:F,onValueChange:z=>o(H=>({...H,[I.id]:z})),children:[e.jsx(ls,{className:"h-9 w-[240px]",children:e.jsx(hs,{placeholder:"Pick brokerage…"})}),e.jsx(cs,{children:v.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))})]})}),e.jsx(ht,{children:e.jsx(B,{size:"sm",disabled:!F||c[I.id],onClick:()=>E(I.id,F),children:c[I.id]?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):"Assign"})})]},I.id)})})]})})})]})]})})}const wbs=()=>{const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("");N.useEffect(()=>{y()},[]);const y=async()=>{const{data:E,error:O}=await q.from("invite_codes").select("*").order("created_at",{ascending:!1});O?(ae.error("Failed to load invite codes"),console.error(O)):t(E||[]),r(!1)},_=async E=>{if(E.preventDefault(),!l.trim()){ae.error("Please enter a code");return}i(!0);const{error:O}=await q.from("invite_codes").insert({code:l.trim().toUpperCase(),description:c.trim()||null,max_uses:u?parseInt(u):null,trial_days:p?parseInt(p):null});O?O.code==="23505"?ae.error("This code already exists"):(ae.error("Failed to create invite code"),console.error(O)):(ae.success("Invite code created"),o(""),d(""),h(""),f(""),y()),i(!1)},v=async(E,O)=>{const{error:D}=await q.from("invite_codes").update({is_active:!O}).eq("id",E);D?ae.error("Failed to update code"):t(s.map(I=>I.id===E?{...I,is_active:!O}:I))},j=async E=>{const{error:O}=await q.from("invite_codes").delete().eq("id",E);O?ae.error("Failed to delete code"):(ae.success("Code deleted"),t(s.filter(D=>D.id!==E)))},w="https://dashboard.relevelup.com",S=E=>{const O=`${w}/join?code=${E}`;navigator.clipboard.writeText(O),ae.success("Link copied to clipboard")},A=`${w}/join`;return e.jsx(Cs,{title:"Invite Codes",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Invite Codes",description:"Manage signup invite codes"}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Create New Code"}),e.jsxs(Vn,{children:["Share link: ",e.jsx("code",{className:"bg-muted px-2 py-1 rounded text-sm",children:A})]})]}),e.jsx(Ee,{children:e.jsxs("form",{onSubmit:_,className:"flex flex-wrap gap-4 items-end",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"code",children:"Code"}),e.jsx(ye,{id:"code",placeholder:"WELCOME2024",value:l,onChange:E=>o(E.target.value),className:"w-40"})]}),e.jsxs("div",{className:"space-y-2 flex-1 min-w-[200px]",children:[e.jsx(ne,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ye,{id:"description",placeholder:"For marketing campaign",value:c,onChange:E=>d(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"maxUses",children:"Max Uses"}),e.jsx(ye,{id:"maxUses",type:"number",placeholder:"Unlimited",value:u,onChange:E=>h(E.target.value),className:"w-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"trialDays",children:"Trial Days"}),e.jsx(ye,{id:"trialDays",type:"number",placeholder:"None",value:p,onChange:E=>f(E.target.value),className:"w-28"})]}),e.jsxs(B,{type:"submit",disabled:a,children:[a?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create"]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Active Codes"})}),e.jsx(Ee,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{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(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Code"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Uses"}),e.jsx(Tt,{children:"Trial"}),e.jsx(Tt,{children:"Created"}),e.jsx(Tt,{children:"Active"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(E=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-mono font-medium",children:E.code}),e.jsx(ht,{className:"text-muted-foreground",children:E.description||"—"}),e.jsxs(ht,{children:[E.uses_count,E.max_uses&&` / ${E.max_uses}`]}),e.jsx(ht,{children:E.trial_days?e.jsxs("span",{className:"text-amber-600 dark:text-amber-400 font-medium",children:[E.trial_days," days"]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ht,{className:"text-muted-foreground",children:Ss(new Date(E.created_at),"MMM d, yyyy")}),e.jsx(ht,{children:e.jsx(jn,{checked:E.is_active,onCheckedChange:()=>v(E.id,E.is_active)})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>S(E.code),title:"Copy invite link",children:e.jsx(Zr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>j(E.id),className:"text-destructive hover:text-destructive",title:"Delete code",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},E.id))})]})})]})]})})},R2=q;function Pfn(s){if(!s)return null;const t=s.trim();if(!t)return null;if(/^[\w-]{8,20}$/.test(t))return t;const n=[/youtu\.be\/([\w-]{8,20})/,/[?&]v=([\w-]{8,20})/,/youtube\.com\/live\/([\w-]{8,20})/,/youtube\.com\/embed\/([\w-]{8,20})/];for(const r of n){const a=t.match(r);if(a)return a[1]}return null}function jbs(s){return s.toLowerCase().replace(/[^a-z0-9\s-]/g,"").trim().replace(/\s+/g,"-").slice(0,70)}function Lfn(s,t){const n=`${window.location.origin}/live/${s}`;return t?`${n}?i=${t}`:n}function Dfn(){const s=Kt(),t=dt({queryKey:["live-events"],queryFn:async()=>{const{data:i,error:l}=await R2.from("live_events").select("*").order("starts_at",{ascending:!1});if(l)throw l;return i||[]}}),n=yt({mutationFn:async i=>{var d;const{data:l}=await q.auth.getUser(),{data:o,error:c}=await R2.from("live_events").insert({...i,created_by:(d=l.user)==null?void 0:d.id}).select().single();if(c)throw c;return o},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ae.success("Live event created")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not create event")}),r=yt({mutationFn:async({id:i,...l})=>{const{error:o}=await R2.from("live_events").update(l).eq("id",i);if(o)throw o},onSuccess:(i,l)=>{s.invalidateQueries({queryKey:["live-events"]}),s.invalidateQueries({queryKey:["live-event",l.id]}),ae.success("Saved")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not save")}),a=yt({mutationFn:async i=>{const{error:l}=await R2.from("live_events").delete().eq("id",i);if(l)throw l},onSuccess:()=>{s.invalidateQueries({queryKey:["live-events"]}),ae.success("Event deleted")},onError:i=>ae.error((i==null?void 0:i.message)||"Could not delete")});return{list:t,create:n,update:r,remove:a}}function Rfn(s){return dt({queryKey:["live-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await R2.from("live_events").select("*").eq("id",s).maybeSingle();if(n)throw n;return t}})}function Ofn(s){return dt({queryKey:["live-registrations",s],enabled:!!s,refetchInterval:2e4,queryFn:async()=>{const{data:t,error:n}=await R2.from("live_registrations").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]}})}function Ffn(s){const t=Kt(),n=dt({queryKey:["live-invites",s],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await R2.from("live_invites").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(l)throw l;return i||[]}}),r=yt({mutationFn:async i=>{const{data:l}=await q.auth.getUser(),o=i.map(u=>{var h;return{event_id:s,code:crypto.randomUUID().replace(/-/g,"").slice(0,12),name:u.name||null,email:u.email||null,phone:u.phone||null,brokerage:u.brokerage||null,created_by:(h=l.user)==null?void 0:h.id}}),{data:c,error:d}=await R2.from("live_invites").insert(o).select();if(d)throw d;return c||[]},onSuccess:i=>{t.invalidateQueries({queryKey:["live-invites",s]}),ae.success(`${i.length} invite link${i.length===1?"":"s"} created`)},onError:i=>ae.error((i==null?void 0:i.message)||"Could not create invites")}),a=yt({mutationFn:async i=>{const{error:l}=await R2.from("live_invites").delete().eq("id",i);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["live-invites",s]})});return{list:n,createMany:r,remove:a}}const gU=async s=>{try{const{data:t,error:n}=await q.from("push_notification_settings").select("is_enabled").eq("setting_key",s).maybeSingle();return n?(console.error("Error checking notification setting:",n),!0):(t==null?void 0:t.is_enabled)??!0}catch(t){return console.error("Error checking notification setting:",t),!0}},WD=async s=>{try{const{data:t,error:n}=await q.functions.invoke("send-push-notification",{body:s});return n?(console.error("Error sending notification:",n),{success:!1,error:n}):(console.log("Notification sent:",t),{success:!0,data:t})}catch(t){return console.error("Error sending notification:",t),{success:!1,error:t}}},Nbs=async(s,t)=>await gU("new_templates")?WD({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}),kbs=async(s,t)=>WD({title:"New Academy Video",body:`New video added: ${s}`,url:`/academy/${t}`}),Sbs=async(s,t)=>await gU("new_events")?WD({title:"New Event",body:`New event: ${s}`,url:`/events/${t}`}):(console.log("New event notifications are disabled"),{success:!1,skipped:!0}),Cbs=async(s,t)=>await gU("new_toolbox")?WD({title:"New Resource Kit",body:`New resource kit available: ${s}`,url:`/toolbox/${t}`}):(console.log("New toolbox notifications are disabled"),{success:!1,skipped:!0}),JCe=async(s,t)=>await gU("new_social_swag")?WD({title:"New Social Swag",body:`New social swag available: ${s}`,url:"/social-swag-2"}):(console.log("New social swag notifications are disabled"),{success:!1,skipped:!0}),Tbs=async(s,t)=>await gU("new_newsletters")?WD({title:"New Newsletter",body:`New newsletter available: ${s}`,url:`/newsletters/${t}`}):(console.log("New newsletter notifications are disabled"),{success:!1,skipped:!0}),w2e=400;function Ebs(s){const t=new Date(s);return new Intl.DateTimeFormat("en-US",{weekday:"long",month:"short",day:"numeric",hour:"numeric",minute:"2-digit",timeZone:"America/New_York"}).format(t)+" ET"}async function Abs(){const s=[];let t=0;const n=1e3;for(;;){const{data:r,error:a}=await q.from("profiles").select("id, name, email, event_invite_opt_out").not("email","is",null).neq("email","").eq("event_invite_opt_out",!1).order("created_at",{ascending:!1}).range(t,t+n-1);if(a)throw a;if(!r||r.length===0)break;for(const i of r)i.email&&/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(i.email)&&s.push({id:i.id,name:i.name||"",email:i.email});if(r.length{if(!s||!n)return;let se=!1;return(async()=>{h(!0);try{const[oe,he,ce]=await Promise.all([Abs(),jHe("event_registrations",n.id),jHe("event_attendees",n.id)]);if(se)return;f(oe),_(he),j(ce)}catch(oe){se||r({title:"Could not load audience",description:oe instanceof Error?oe.message:"Unknown error",variant:"destructive"})}finally{se||h(!1)}})(),()=>{se=!0}},[s,n,r]),N.useEffect(()=>{s||(E(null),d(""),o(""),i("not_registered"))},[s]);const z=N.useMemo(()=>a==="all"?p:a==="not_registered"?p.filter(se=>!y.has(se.id)):p.filter(se=>y.has(se.id)&&!v.has(se.id)),[a,p,y,v]),H={all:p.length,not_registered:p.filter(se=>!y.has(se.id)).length,registered_never_attended:p.filter(se=>y.has(se.id)&&!v.has(se.id)).length},Z=async se=>{const{data:{session:oe}}=await q.auth.getSession(),he=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/admin-send-event-invite",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${oe==null?void 0:oe.access_token}`},body:JSON.stringify({event_id:n.id,recipients:se.map(me=>({email:me.email,name:me.name,user_id:me.id})),custom_subject:l.trim()||void 0,custom_intro:c.trim()||void 0})}),ce=await he.json().catch(()=>({}));if(!he.ok)throw new Error((ce==null?void 0:ce.error)||`HTTP ${he.status}`);return{sent:(ce==null?void 0:ce.sent)??0,failed:(ce==null?void 0:ce.failed)??0}},Y=async()=>{var se;if(n){F(!0);try{const{data:{session:oe}}=await q.auth.getSession(),he=oe==null?void 0:oe.user;if(!(he!=null&&he.email))throw new Error("No signed-in email found");const ce=await Z([{id:he.id,name:((se=he.user_metadata)==null?void 0:se.name)||"",email:he.email}]);r({title:"Test sent",description:`Sent to ${he.email} · Sent: ${ce.sent} · Failed: ${ce.failed}`})}catch(oe){r({title:"Test failed",description:oe instanceof Error?oe.message:"Unknown error",variant:"destructive"})}finally{F(!1)}}},W=async()=>{if(!(!n||z.length===0)){D(!1),S(!0),E({done:0,total:z.length,sent:0,failed:0});try{let se=0,oe=0;for(let he=0;he!w&&t(se),children:e.jsxs(bs,{className:"max-w-2xl max-h-[92vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Invite Members to Event"]}),e.jsx(Jn,{children:n?e.jsxs("span",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Xf,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-foreground",children:n.title}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ebs(n.event_date)})]}):"Send a beautiful branded invite to members."})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4"})," Audience"]}),u?e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground py-2",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"})," Loading members..."]}):e.jsxs(ib,{value:a,onValueChange:se=>i(se),className:"space-y-2",children:[e.jsxs("label",{htmlFor:"aud-not-reg",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Ld,{value:"not_registered",id:"aud-not-reg",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Members not yet registered"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Skip anyone already registered for this event. Best for weekly boost sends."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:H.not_registered.toLocaleString()})]}),e.jsxs("label",{htmlFor:"aud-all",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Ld,{value:"all",id:"aud-all",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"All members with an email"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Everyone in the system. Use sparingly to avoid inbox fatigue."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:H.all.toLocaleString()})]}),e.jsxs("label",{htmlFor:"aud-reg-noatt",className:"flex items-start gap-3 rounded-lg border p-3 cursor-pointer hover:bg-muted/40 transition",children:[e.jsx(Ld,{value:"registered_never_attended",id:"aud-reg-noatt",className:"mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Registered but haven't attended"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Nudge people who signed up but didn't join the Zoom."})]}),e.jsx("span",{className:"text-sm font-semibold text-primary",children:H.registered_never_attended.toLocaleString()})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"ev-inv-subject",children:"Subject line (optional)"}),e.jsx(ye,{id:"ev-inv-subject",placeholder:n?`You're invited: ${n.title}`:"You're invited to...",value:l,onChange:se=>o(se.target.value),disabled:w}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave blank for the default."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"ev-inv-intro",children:"Personal message (optional)"}),e.jsx(Ms,{id:"ev-inv-intro",placeholder:"e.g. Our Wednesday live training this week is on lead conversion. Grab your seat — it's a game-changer.",value:c,onChange:se=>d(se.target.value),rows:4,disabled:w}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Appears at the top of the email above the event details."})]}),A&&e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:["Sending ",A.done.toLocaleString()," / ",A.total.toLocaleString()]}),e.jsxs("span",{className:"font-medium",children:["✓ ",A.sent.toLocaleString(),A.failed>0&&e.jsxs("span",{className:"text-destructive",children:[" · ✗ ",A.failed.toLocaleString()]})]})]}),e.jsx(fi,{value:ee})]})]}),e.jsxs(Xn,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:Y,disabled:w||I||u,children:I?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"})," Sending test..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"})," Send test to me"]})}),e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:w,children:"Cancel"}),e.jsx(B,{onClick:()=>D(!0),disabled:w||u||z.length===0,children:w?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-2"})," Send to ",z.length.toLocaleString()]})})]})]})}),e.jsx(Oo,{open:O,onOpenChange:D,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Send event invite?"}),e.jsxs(Mo,{children:["This will send a branded invite to"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[z.length.toLocaleString()," member",z.length===1?"":"s"]})," ","for"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:['"',n==null?void 0:n.title,'"']}),". This can't be undone."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(wo,{onClick:W,children:[e.jsx(lr,{className:"h-4 w-4 mr-2"})," Send now"]})]})]})})]})}const OH={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 Ibs(){const s=Ln(),t=Kt(),[n,r]=N.useState(!1),[a,i]=N.useState(null),[l,o]=N.useState(OH),[c,d]=N.useState(null),[u,h]=N.useState(null),[p,f]=N.useState(!1),y=N.useRef(null),[_,v]=N.useState(!1),[j,w]=N.useState(null),[S,A]=N.useState(!1),[E,O]=N.useState(null),[D,I]=N.useState(null),[F,z]=N.useState(!0),[H,Z]=N.useState(""),[Y,W]=N.useState(!1),[ee,se]=N.useState(null),{data:oe,isLoading:he}=dt({queryKey:["admin-events"],queryFn:async()=>{const{data:Ye,error:ut}=await q.from("events").select("*").order("event_date",{ascending:!0});if(ut)throw ut;return Ye}}),{data:ce}=dt({queryKey:["event-registrations-count"],queryFn:async()=>{let Ye=[],ut=0;const _t=1e3;for(;;){const{data:$t,error:Yt}=await q.from("event_registrations").select("event_id").range(ut,ut+_t-1);if(Yt)throw Yt;if(!$t||$t.length===0||(Ye=Ye.concat($t),$t.length<_t))break;ut+=_t}const bt={};return Ye.forEach($t=>{bt[$t.event_id]=(bt[$t.event_id]||0)+1}),bt}}),{data:me,isLoading:le}=dt({queryKey:["event-registrations-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:Ye,error:ut}=await q.from("event_registrations").select("id, user_id, registered_at, zoom_join_url, zoom_name, zoom_email").eq("event_id",j.id).order("registered_at",{ascending:!1});if(ut)throw ut;if(!Ye||Ye.length===0)return[];const _t=Ye.map(Yt=>Yt.user_id).filter(Boolean);let bt=[];if(_t.length>0){const{data:Yt,error:Ds}=await q.from("profiles").select("id, name, email").in("id",_t);if(Ds)throw Ds;bt=Yt||[]}const $t=new Map((bt==null?void 0:bt.map(Yt=>[Yt.id,Yt]))||[]);return Ye.map(Yt=>({...Yt,profiles:Yt.user_id&&$t.get(Yt.user_id)||null}))},enabled:!!j}),{data:ve,isLoading:ge}=dt({queryKey:["event-attendees-details",j==null?void 0:j.id],queryFn:async()=>{if(!j)return[];const{data:Ye,error:ut}=await q.from("event_attendees").select("id, user_id, zoom_email, zoom_name, join_time, leave_time, duration_minutes, manually_added, created_at").eq("event_id",j.id).order("created_at",{ascending:!1});if(ut)throw ut;if(!Ye||Ye.length===0)return[];const _t=Ye.map(Ls=>Ls.user_id).filter(Boolean);let bt=[];if(_t.length>0){const{data:Ls,error:xs}=await q.from("profiles").select("id, name, email").in("id",_t);if(xs)throw xs;bt=Ls||[]}const{data:$t}=await q.from("agent_points").select("user_id").eq("event_id",j.id),Yt=new Set(($t==null?void 0:$t.map(Ls=>Ls.user_id))||[]),Ds=new Map((bt==null?void 0:bt.map(Ls=>[Ls.id,Ls]))||[]);return Ye.map(Ls=>({...Ls,profiles:Ls.user_id&&Ds.get(Ls.user_id)||null,points_awarded:Ls.user_id?Yt.has(Ls.user_id):!1}))},enabled:!!j}),Te=Ye=>{w(Ye),v(!0)},Ie=yt({mutationFn:async Ye=>{const{data:{session:ut}}=await q.auth.getSession();if(!ut)throw new Error("Not authenticated");const _t=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-registrations",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ut.access_token}`},body:JSON.stringify({event_id:Ye})}),bt=await _t.json();if(!_t.ok)throw new Error(bt.error||"Failed to sync");return bt},onSuccess:Ye=>{t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ae.success(Ye.message)},onError:Ye=>{ae.error("Failed to sync: "+Ye.message)}}),Ce=yt({mutationFn:async Ye=>{const{data:{session:ut}}=await q.auth.getSession();if(!ut)throw new Error("Not authenticated");const _t=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/zoom-sync-attendees",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ut.access_token}`},body:JSON.stringify({event_id:Ye})}),bt=await _t.json();if(!_t.ok)throw new Error(bt.error||"Failed to sync attendees");return bt},onSuccess:Ye=>{t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]}),Ye!=null&&Ye.message?ae.success(Ye.message):ae.success(`Synced ${Ye.synced||0} attendees. ${Ye.points_awarded||0} points awarded!`)},onError:Ye=>{ae.error("Failed to sync attendees: "+Ye.message)}}),Me=yt({mutationFn:async()=>{const{data:Ye,error:ut}=await q.functions.invoke("zoom-retry-registrations",{body:{}});if(ut)throw ut;return Ye},onSuccess:Ye=>{t.invalidateQueries({queryKey:["event-registrations-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-registrations-count"]}),ae.success(`Retry complete: ${(Ye==null?void 0:Ye.successCount)??0} fixed, ${(Ye==null?void 0:Ye.failCount)??0} still failing, ${(Ye==null?void 0:Ye.rateLimitedCount)??0} rate-limited`)},onError:Ye=>{ae.error("Retry failed: "+Ye.message)}}),Pe=yt({mutationFn:async({eventId:Ye,testMode:ut})=>{const{data:{session:_t}}=await q.auth.getSession();if(!_t)throw new Error("Not authenticated");const bt=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/send-event-reminder",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${_t.access_token}`},body:JSON.stringify({event_id:Ye,test_mode:ut})}),$t=await bt.json();if(!bt.ok)throw new Error($t.error||"Failed to send reminders");return $t},onSuccess:Ye=>{Ye.test?ae.success(Ye.message||"Test email sent!"):ae.success(Ye.message||`Reminder emails sent to ${Ye.sent} registrants!`)},onError:Ye=>{ae.error("Failed to send reminders: "+Ye.message)}}),{data:Re}=dt({queryKey:["all-profiles-for-linking"],queryFn:async()=>{let Ye=[],ut=0;const _t=1e3;for(;;){const{data:bt,error:$t}=await q.from("profiles").select("id, name, email").order("name",{ascending:!0}).range(ut,ut+_t-1);if($t)throw $t;if(!bt||bt.length===0||(Ye=[...Ye,...bt],bt.length<_t))break;ut+=_t}return Ye},enabled:S}),Ae=yt({mutationFn:async({attendeeId:Ye,userId:ut,zoomEmail:_t,shouldSaveAlias:bt})=>{const{error:$t}=await q.from("event_attendees").update({user_id:ut}).eq("id",Ye);if($t)throw $t;if(bt&&_t){const{error:Ds}=await q.from("zoom_email_aliases").upsert({user_id:ut,zoom_email:_t.toLowerCase()},{onConflict:"zoom_email"});Ds&&console.error("Failed to save alias:",Ds)}const Yt=j==null?void 0:j.id;if(Yt){const{data:Ds}=await q.from("user_roles").select("id").eq("user_id",ut).eq("role","admin").single();if(!Ds){const{data:Ls}=await q.from("agent_points").select("id").eq("user_id",ut).eq("event_id",Yt).single();Ls||(await q.rpc("award_attendance_points",{p_user_id:ut,p_event_id:Yt,p_points:10,p_reason:"Event Attendance (Manual Link)"}),await q.rpc("check_and_award_badges",{p_user_id:ut}))}}return{userId:ut,zoomEmail:_t,shouldSaveAlias:bt}},onSuccess:Ye=>{t.invalidateQueries({queryKey:["event-attendees-details",j==null?void 0:j.id]}),t.invalidateQueries({queryKey:["event-leaderboard"]}),t.invalidateQueries({queryKey:["admin-agent-points"]});let ut="Attendee linked and points awarded!";Ye.shouldSaveAlias&&Ye.zoomEmail&&(ut+=` Email "${Ye.zoomEmail}" will be auto-matched in the future.`),ae.success(ut),A(!1),O(null),I(null),Z("")},onError:Ye=>{ae.error("Failed to link attendee: "+Ye.message)}}),Be=Ye=>{O(Ye),I(null),z(!0),Z(""),A(!0)},we=()=>{!E||!D||Ae.mutate({attendeeId:E.id,userId:D,zoomEmail:E.zoom_email,shouldSaveAlias:F})},Je=(Re==null?void 0:Re.filter(Ye=>{var _t,bt;if(!H)return!0;const ut=H.toLowerCase();return((_t=Ye.name)==null?void 0:_t.toLowerCase().includes(ut))||((bt=Ye.email)==null?void 0:bt.toLowerCase().includes(ut))}))||[],ke=async Ye=>{const ut=Ye.name.split(".").pop(),bt=`${`${crypto.randomUUID()}.${ut}`}`,{error:$t}=await q.storage.from("event-images").upload(bt,Ye);if($t)throw $t;const{data:{publicUrl:Yt}}=q.storage.from("event-images").getPublicUrl(bt);return Yt},it=Ye=>{var _t;const ut=(_t=Ye.target.files)==null?void 0:_t[0];if(ut){if(ut.size>5*1024*1024){ae.error("Image must be less than 5MB");return}d(ut),h(URL.createObjectURL(ut))}},je=()=>{d(null),h(null),o({...l,image_url:""}),y.current&&(y.current.value="")},He=yt({mutationFn:async Ye=>{f(!0);let ut=Ye.image_url;c&&(ut=await ke(c)||"");const _t=new Date(Ye.event_date),[bt,$t]=Ye.event_time.split(":");_t.setHours(parseInt(bt),parseInt($t));const Yt=[new Date(_t)];if(Ye.is_recurring&&Ye.recurrence_end_date){let Lt=new Date(_t);for(;Ye.recurrence_pattern==="weekly"?Lt=L2(Lt,1):Ye.recurrence_pattern==="biweekly"?Lt=L2(Lt,2):Lt=_f(Lt,1),!(Lt>Ye.recurrence_end_date);)Yt.push(new Date(Lt))}const Ds=Yt.map(Lt=>({title:Ye.title,description:Ye.description||null,image_url:ut||null,video_url:Ye.video_url||null,event_date:Lt.toISOString(),zoom_link:Ye.zoom_link,zoom_meeting_id:Ye.zoom_meeting_id||null,capacity:Ye.capacity?parseInt(Ye.capacity):null,is_published:Ye.is_published})),{data:Ls,error:xs}=await q.from("events").insert(Ds).select();if(xs)throw xs;return Ls&&Ls.length>0&&Sbs(Ye.title,Ls[0].id),Yt.length},onSuccess:Ye=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success(Ye>1?`${Ye} recurring events created successfully`:"Event created successfully"),r(!1),o(OH),d(null),h(null),f(!1)},onError:Ye=>{ae.error("Failed to create event: "+Ye.message),f(!1)}}),$e=yt({mutationFn:async({id:Ye,data:ut})=>{f(!0);let _t=ut.image_url;c&&(_t=await ke(c)||"");const bt=new Date(ut.event_date),[$t,Yt]=ut.event_time.split(":");bt.setHours(parseInt($t),parseInt(Yt));const{error:Ds}=await q.from("events").update({title:ut.title,description:ut.description||null,image_url:_t||null,video_url:ut.video_url||null,event_date:bt.toISOString(),zoom_link:ut.zoom_link,zoom_meeting_id:ut.zoom_meeting_id||null,capacity:ut.capacity?parseInt(ut.capacity):null,is_published:ut.is_published}).eq("id",Ye);if(Ds)throw Ds},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event updated successfully"),r(!1),i(null),o(OH),d(null),h(null),f(!1)},onError:Ye=>{ae.error("Failed to update event: "+Ye.message),f(!1)}}),Ke=yt({mutationFn:async Ye=>{const{error:ut}=await q.from("events").delete().eq("id",Ye);if(ut)throw ut},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-events"]}),ae.success("Event deleted successfully")},onError:Ye=>{ae.error("Failed to delete event: "+Ye.message)}}),Ge=yt({mutationFn:async Ye=>{var Lt;const{data:ut}=await q.auth.getUser(),_t=new Date(Ye.event_date),bt=new Date(_t.getTime()+60*60*1e3),$t=jbs(Ye.title),Yt=Math.random().toString(36).slice(2,7),Ds=`${$t}-${Yt}`,{data:Ls,error:xs}=await q.from("live_events").insert({slug:Ds,title:Ye.title,description:Ye.description||null,hero_image_url:Ye.image_url||null,starts_at:Ye.event_date,ends_at:bt.toISOString(),timezone:"America/New_York",status:"scheduled",is_published:!1,require_registration:!0,invite_only:!1,chat_enabled:!0,questions_mode:!1,replay_enabled:!0,auto_go_live:!0,auto_end:!0,zoom_meeting_id:Ye.zoom_meeting_id||null,cta_label:"Join the training",cta_url:Ye.zoom_link||"https://dashboard.relevelup.com/trial",created_by:(Lt=ut.user)==null?void 0:Lt.id,agenda:[],offer_bullets:[]}).select().single();if(xs)throw xs;return Ls},onSuccess:Ye=>{t.invalidateQueries({queryKey:["live-events"]}),ae.success("Cloned to LevelUp Live — configure stream next"),s(`/admin/live/${Ye.id}`)},onError:Ye=>{ae.error("Failed to clone to LevelUp Live: "+Ye.message)}}),rt=Ye=>{var _t;const ut=new Date(Ye.event_date);i(Ye),o({title:Ye.title,description:Ye.description||"",image_url:Ye.image_url||"",video_url:Ye.video_url||"",event_date:ut,event_time:Ss(ut,"HH:mm"),zoom_link:Ye.zoom_link,zoom_meeting_id:Ye.zoom_meeting_id||"",capacity:((_t=Ye.capacity)==null?void 0:_t.toString())||"",is_published:Ye.is_published,is_recurring:!1,recurrence_pattern:"weekly",recurrence_end_date:void 0}),h(Ye.image_url||null),d(null),r(!0)},tt=Ye=>{if(Ye.preventDefault(),!l.event_date){ae.error("Please select a date");return}if(l.is_recurring&&!l.recurrence_end_date){ae.error("Please select an end date for recurring events");return}a?$e.mutate({id:a.id,data:l}):He.mutate(l)},at=()=>{r(!1),i(null),o(OH),d(null),h(null)};return e.jsx("div",{className:"min-h-screen bg-background p-6",children:e.jsxs("div",{className:"max-w-6xl mx-auto space-y-6",children:[e.jsx(Bd,{title:"Event Management",description:"Create and manage upcoming events"}),e.jsxs(fe,{className:"mb-6",children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsx(Rt,{children:"All Events"}),e.jsxs(_s,{open:n,onOpenChange:Ye=>!Ye&&at(),children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Event"]})}),e.jsxs(bs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:a?"Edit Event":"Create New Event"})}),e.jsxs("form",{onSubmit:tt,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:l.title,onChange:Ye=>o({...l,title:Ye.target.value}),placeholder:"Event title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:l.description,onChange:Ye=>o({...l,description:Ye}),placeholder:"Event description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Event Image"}),e.jsx("input",{type:"file",ref:y,accept:"image/*",onChange:it,className:"hidden"}),u?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:u,alt:"Event preview",className:"w-full h-32 object-cover rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:je,children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs(B,{type:"button",variant:"outline",className:"w-full h-32 border-dashed flex flex-col gap-2",onClick:()=>{var Ye;return(Ye=y.current)==null?void 0:Ye.click()},children:[e.jsx(_a,{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(ne,{children:"Date *"}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!l.event_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),l.event_date?Ss(l.event_date,"PPP"):"Pick a date"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:l.event_date,onSelect:Ye=>o({...l,event_date:Ye}),initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"time",children:"Time *"}),e.jsx(ye,{id:"time",type:"time",value:l.event_time,onChange:Ye=>o({...l,event_time:Ye.target.value}),required:!0})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"zoom_link",children:"Zoom Link *"}),e.jsx(ye,{id:"zoom_link",value:l.zoom_link,onChange:Ye=>o({...l,zoom_link:Ye.target.value}),placeholder:"https://zoom.us/j/...",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"zoom_meeting_id",children:"Zoom Meeting ID (for API registration)"}),e.jsx(ye,{id:"zoom_meeting_id",value:l.zoom_meeting_id,onChange:Ye=>o({...l,zoom_meeting_id:Ye.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(ne,{htmlFor:"video_url",children:"Promo Video URL (optional)"}),e.jsx(ye,{id:"video_url",value:l.video_url,onChange:Ye=>o({...l,video_url:Ye.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(ne,{htmlFor:"capacity",children:"Capacity (optional)"}),e.jsx(ye,{id:"capacity",type:"number",value:l.capacity,onChange:Ye=>o({...l,capacity:Ye.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(u9,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ne,{htmlFor:"is_recurring",children:"Recurring Event"})]}),e.jsx(jn,{id:"is_recurring",checked:l.is_recurring,onCheckedChange:Ye=>o({...l,is_recurring:Ye})})]}),l.is_recurring&&e.jsxs("div",{className:"space-y-3 pt-1",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Frequency"}),e.jsxs(us,{value:l.recurrence_pattern,onValueChange:Ye=>o({...l,recurrence_pattern:Ye}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"weekly",children:"Weekly"}),e.jsx(Ze,{value:"biweekly",children:"Every 2 Weeks"}),e.jsx(Ze,{value:"monthly",children:"Monthly"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Repeat Until"}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!l.recurrence_end_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),l.recurrence_end_date?Ss(l.recurrence_end_date,"PPP"):"Pick end date"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:l.recurrence_end_date,onSelect:Ye=>o({...l,recurrence_end_date:Ye}),disabled:Ye=>Ye<(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 Ye=1,ut=new Date(l.event_date);for(;ut=l.recurrence_pattern==="weekly"?L2(ut,1):l.recurrence_pattern==="biweekly"?L2(ut,2):_f(ut,1),!(ut>l.recurrence_end_date);)Ye++;return Ye})()," events with the same Zoom link"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{htmlFor:"is_published",children:"Published"}),e.jsx(jn,{id:"is_published",checked:l.is_published,onCheckedChange:Ye=>o({...l,is_published:Ye})})]}),e.jsxs("div",{className:"flex gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:at,className:"flex-1",children:"Cancel"}),e.jsx(B,{type:"submit",className:"flex-1",disabled:He.isPending||$e.isPending||p,children:p?"Uploading...":a?"Update Event":l.is_recurring&&l.event_date&&l.recurrence_end_date?"Create Recurring Events":"Create Event"})]})]})]})]})]}),e.jsx(Ee,{children:he?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading events..."}):(oe==null?void 0:oe.length)===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No events yet. Create your first event!"}):(()=>{const Ye=new Date,ut=[...oe||[]],_t=ut.filter(Ls=>new Date(Ls.event_date)>=Ye).sort((Ls,xs)=>new Date(Ls.event_date).getTime()-new Date(xs.event_date).getTime()),bt=ut.filter(Ls=>new Date(Ls.event_date)new Date(xs.event_date).getTime()-new Date(Ls.event_date).getTime()),$t=_t[0],Yt=Ls=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:Ls.title}),e.jsx(ht,{className:"whitespace-nowrap",children:Ss(new Date(Ls.event_date),"PPP p")}),e.jsx(ht,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1",onClick:()=>Te(Ls),children:[e.jsx(An,{className:"h-4 w-4"}),(ce==null?void 0:ce[Ls.id])||0,Ls.capacity&&` / ${Ls.capacity}`]})}),e.jsx(ht,{children:e.jsx("span",{className:Mt("px-2 py-1 rounded-full text-xs font-medium",Ls.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:Ls.is_published?"Published":"Draft"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>{se(Ls),W(!0)},title:"Send invite email to members",children:[e.jsx(lr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"Invite Members"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ge.mutate(Ls),disabled:Ge.isPending,title:"Clone to LevelUp Live",children:[e.jsx(yf,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:"LevelUp Live"})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(Ls.zoom_link,"_blank"),title:"Open Zoom Link",children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>rt(Ls),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this event?")&&Ke.mutate(Ls.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},Ls.id),Ds=(Ls,xs)=>Ls.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:xs}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Date & Time"}),e.jsx(Tt,{children:"Registrations"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:Ls.map(Yt)})]});return e.jsxs("div",{className:"space-y-6",children:[$t&&e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/10 via-primary/5 to-transparent p-5",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-primary mb-1",children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),"Next Upcoming Event"]}),e.jsx("h3",{className:"text-xl font-bold truncate",children:$t.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Ss(new Date($t.event_date),"EEEE, PPP 'at' p")}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[(ce==null?void 0:ce[$t.id])||0," registered",$t.capacity?` of ${$t.capacity}`:""]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>{se($t),W(!0)},children:[e.jsx(lr,{className:"h-4 w-4"}),"Invite Members"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>Te($t),children:[e.jsx(An,{className:"h-4 w-4"}),"Registrations"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5 border-primary/50 text-primary hover:bg-primary/10",onClick:()=>Ge.mutate($t),disabled:Ge.isPending,children:[e.jsx(yf,{className:"h-4 w-4"}),"LevelUp Live"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>window.open($t.zoom_link,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4"}),"Zoom"]})]})]})}),e.jsxs(Fr,{defaultValue:"upcoming",className:"w-full",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"upcoming",className:"gap-2",children:[e.jsx(pr,{className:"h-4 w-4"}),"Upcoming",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:_t.length})]}),e.jsxs(Zt,{value:"past",className:"gap-2",children:[e.jsx(vr,{className:"h-4 w-4"}),"Past",e.jsx("span",{className:"ml-1 rounded-full bg-muted px-2 py-0.5 text-xs",children:bt.length})]})]}),e.jsx(is,{value:"upcoming",className:"mt-4",children:Ds(_t,"No upcoming events scheduled.")}),e.jsx(is,{value:"past",className:"mt-4",children:Ds(bt,"No past events.")})]})]})})()})]}),e.jsx(Mbs,{open:Y,onOpenChange:W,event:ee}),e.jsx(_s,{open:_,onOpenChange:v,children:e.jsxs(bs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),j==null?void 0:j.title]}),e.jsx(Jn,{children:"View registrations and attendees for this event"})]}),e.jsxs("div",{className:"flex items-center justify-end mb-4 gap-2 flex-wrap",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>Pe.mutate({eventId:j.id,testMode:!0}),disabled:Pe.isPending,children:[e.jsx(Gs,{className:Mt("h-4 w-4 mr-2",Pe.isPending&&"animate-spin")}),"Send Test to Me"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Pe.mutate({eventId:j.id}),disabled:Pe.isPending||!(me!=null&&me.length),children:[e.jsx(Gs,{className:Mt("h-4 w-4 mr-2",Pe.isPending&&"animate-spin")}),Pe.isPending?"Sending...":"Send Reminder to All"]}),(j==null?void 0:j.zoom_meeting_id)&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Ie.mutate(j.id),disabled:Ie.isPending,children:[e.jsx(Ei,{className:Mt("h-4 w-4 mr-2",Ie.isPending&&"animate-spin")}),Ie.isPending?"Syncing...":"Sync Registrations"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Me.mutate(),disabled:Me.isPending,children:[e.jsx(Ei,{className:Mt("h-4 w-4 mr-2",Me.isPending&&"animate-spin")}),Me.isPending?"Retrying...":"Retry Failed Registrations"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>Ce.mutate(j.id),disabled:Ce.isPending,children:[e.jsx(xo,{className:Mt("h-4 w-4 mr-2",Ce.isPending&&"animate-spin")}),Ce.isPending?"Syncing...":"Sync Attendees & Award Points"]})]})]}),e.jsxs(Fr,{defaultValue:"registrations",className:"w-full",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"registrations",className:"gap-2",children:[e.jsx(An,{className:"h-4 w-4"}),"Registrations (",(me==null?void 0:me.length)||0,")"]}),e.jsxs(Zt,{value:"attendees",className:"gap-2",children:[e.jsx(vr,{className:"h-4 w-4"}),"Attendees (",(ve==null?void 0:ve.length)||0,")"]})]}),e.jsx(is,{value:"registrations",className:"mt-4",children:le?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading registrations..."}):(me==null?void 0:me.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No registrations yet for this event."}),(j==null?void 0:j.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Registrations" to import from Zoom.'})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Registered"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(da,{children:me==null?void 0:me.map(Ye=>{var $t,Yt;const ut=(($t=Ye.profiles)==null?void 0:$t.name)||Ye.zoom_name||"Unknown",_t=((Yt=Ye.profiles)==null?void 0:Yt.email)||Ye.zoom_email||null,bt=!Ye.user_id;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ut,bt&&e.jsx("span",{className:"text-xs px-1.5 py-0.5 rounded bg-muted text-muted-foreground",children:"External"})]})}),e.jsx(ht,{children:_t?e.jsxs("a",{href:`mailto:${_t}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Gs,{className:"h-3 w-3"}),_t]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(ht,{className:"text-muted-foreground text-sm",children:Ss(new Date(Ye.registered_at),"MMM d, yyyy h:mm a")}),e.jsx(ht,{children:Ye.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"})})]},Ye.id)})})]})}),e.jsx(is,{value:"attendees",className:"mt-4",children:ge?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading attendees..."}):(ve==null?void 0:ve.length)===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No attendees recorded yet."}),(j==null?void 0:j.zoom_meeting_id)&&e.jsx("p",{className:"text-xs mt-2",children:'Click "Sync Attendees & Award Points" after the event ends to import actual participants from Zoom.'})]}):e.jsxs(e.Fragment,{children:[(ve==null?void 0:ve.filter(Ye=>!Ye.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(Bi,{className:"h-4 w-4 text-amber-600 dark:text-amber-400"}),e.jsxs("h4",{className:"font-medium text-amber-800 dark:text-amber-200",children:["Unmatched Attendees (",ve==null?void 0:ve.filter(Ye=>!Ye.user_id).length,")"]})]}),e.jsx("p",{className:"text-xs text-amber-700 dark:text-amber-300 mb-3",children:"These attendees couldn't be matched to a profile. Link them to award points."}),e.jsx("div",{className:"space-y-2",children:ve==null?void 0:ve.filter(Ye=>!Ye.user_id).map(Ye=>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:Ye.zoom_name||"Unknown"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ye.zoom_email||"No email"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Be(Ye),className:"gap-1",children:[e.jsx(Tl,{className:"h-3 w-3"}),"Link to Profile"]})]},Ye.id))})]}),e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Points"})]})}),e.jsx(da,{children:ve==null?void 0:ve.filter(Ye=>Ye.user_id).map(Ye=>{var bt,$t;const ut=((bt=Ye.profiles)==null?void 0:bt.name)||Ye.zoom_name||"Unknown",_t=(($t=Ye.profiles)==null?void 0:$t.email)||Ye.zoom_email||null;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[ut,Ye.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(ht,{children:_t?e.jsxs("a",{href:`mailto:${_t}`,className:"flex items-center gap-1 text-primary hover:underline",children:[e.jsx(Gs,{className:"h-3 w-3"}),_t]}):e.jsx("span",{className:"text-muted-foreground",children:"No email"})}),e.jsx(ht,{children:Ye.duration_minutes?e.jsxs("span",{className:"flex items-center gap-1 text-muted-foreground text-sm",children:[e.jsx(pr,{className:"h-3 w-3"}),Ye.duration_minutes," min"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ht,{children:Ye.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(xo,{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"})})]},Ye.id)})})]})]})})]})]})}),e.jsx(_s,{open:S,onOpenChange:A,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Tl,{className:"h-5 w-5"}),"Link Attendee to Profile"]}),e.jsx(Jn,{children:"Link this Zoom attendee to an existing member profile to award them points."})]}),E&&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:E.zoom_name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:E.zoom_email||"No email"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Search for a profile"}),e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:H,onChange:Ye=>Z(Ye.target.value),className:"pl-9"})]})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto border rounded-md",children:Je.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:Je.slice(0,20).map(Ye=>e.jsxs("button",{type:"button",onClick:()=>I(Ye.id),className:Mt("w-full p-3 text-left hover:bg-muted/50 transition-colors",D===Ye.id&&"bg-primary/10 border-l-2 border-primary"),children:[e.jsx("p",{className:"text-sm font-medium",children:Ye.name||"Unnamed"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ye.email})]},Ye.id))})}),E.zoom_email&&e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(hi,{id:"save-alias",checked:F,onCheckedChange:Ye=>z(Ye)}),e.jsx("label",{htmlFor:"save-alias",className:"text-sm text-muted-foreground cursor-pointer",children:"Remember this email for future auto-matching"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>A(!1),children:"Cancel"}),e.jsx(B,{onClick:we,disabled:!D||Ae.isPending,children:Ae.isPending?"Linking...":"Link & Award Points"})]})]})]})})]})})}const Pbs={ok:"bg-emerald-500/10 text-emerald-700 dark:text-emerald-400",error:"bg-red-500/10 text-red-700 dark:text-red-400",denied:"bg-amber-500/10 text-amber-700 dark:text-amber-400",rate_limited:"bg-orange-500/10 text-orange-700 dark:text-orange-400"};function Lbs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState("issues");async function l(){r(!0);let o=q.from("mcp_audit_log").select("id, user_id, tool_name, outcome, error_message, duration_ms, client_id, created_at").order("created_at",{ascending:!1}).limit(200);a==="issues"&&(o=o.in("outcome",["denied","rate_limited","error"]));const{data:c,error:d}=await o;d||t(c??[]),r(!1)}return N.useEffect(()=>{l()},[a]),e.jsx(Cs,{title:"MCP Audit Log",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"MCP Audit Log",description:"Recent LevelUp MCP tool calls — ChatGPT / Claude / Codex activity, denials, and rate limits."}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(uL,{className:"h-5 w-5"}),"Recent activity"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:a==="issues"?"default":"outline",size:"sm",onClick:()=>i("issues"),children:"Issues only"}),e.jsx(B,{variant:a==="all"?"default":"outline",size:"sm",onClick:()=>i("all"),children:"All calls"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:l,disabled:n,children:e.jsx(Ei,{className:`h-4 w-4 ${n?"animate-spin":""}`})})]})]}),e.jsx(Ee,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No entries."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"border-b text-left text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"py-2 pr-4",children:"When"}),e.jsx("th",{className:"py-2 pr-4",children:"Tool"}),e.jsx("th",{className:"py-2 pr-4",children:"Outcome"}),e.jsx("th",{className:"py-2 pr-4",children:"User"}),e.jsx("th",{className:"py-2 pr-4",children:"Client"}),e.jsx("th",{className:"py-2 pr-4",children:"ms"}),e.jsx("th",{className:"py-2 pr-4",children:"Error"})]})}),e.jsx("tbody",{children:s.map(o=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsx("td",{className:"py-2 pr-4 whitespace-nowrap",children:new Date(o.created_at).toLocaleString()}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.tool_name}),e.jsx("td",{className:"py-2 pr-4",children:e.jsx(Ue,{className:Pbs[o.outcome]??"",variant:"secondary",children:o.outcome})}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.user_id?o.user_id.slice(0,8):"—"}),e.jsx("td",{className:"py-2 pr-4 font-mono text-xs",children:o.client_id?o.client_id.slice(0,12):"—"}),e.jsx("td",{className:"py-2 pr-4",children:o.duration_ms??"—"}),e.jsx("td",{className:"py-2 pr-4 text-xs text-muted-foreground max-w-[24rem] truncate",children:o.error_message??""})]},o.id))})]})})})]})]})})}function Dbs({selectedKitIds:s,onChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l=[]}=dt({queryKey:["all-resource-kits-picker"],queryFn:async()=>{const{data:h,error:p}=await q.from("resource_kits").select("id, name, featured_image_url").eq("is_published",!0).order("name");if(p)throw p;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(p=>p!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Ec,{className:"h-4 w-4"}),"Linked Toolkits"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(Ue,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx($n,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(il,{open:a,onOpenChange:i,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(Ec,{className:"h-3.5 w-3.5"}),"Add Toolkit"]})}),e.jsxs(el,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(gr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search toolkits...",value:n,onChange:h=>r(h.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:n?"No toolkits found":"All toolkits selected"}):c.map(h=>e.jsxs("button",{type:"button",onClick:()=>{d(h.id),r("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[h.featured_image_url?e.jsx("img",{src:h.featured_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(Ec,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:h.name})]},h.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link toolkits that agents can download alongside this template."})]})}const Rbs=()=>{const{user:s}=vs(),{toast:t}=Fa(),n=Kt(),[r,a]=xl(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),[h,p]=N.useState(null),[f,y]=N.useState(0),[_,v]=N.useState(!1),[j,w]=N.useState(null),[S,A]=N.useState(""),[E,O]=N.useState([]),[D,I]=N.useState(""),[F,z]=N.useState(""),[H,Z]=N.useState(!1),[Y,W]=N.useState(!1),{data:ee=[]}=dt({queryKey:["template-categories"],queryFn:async()=>{const{data:je,error:He}=await q.from("template_categories").select("*").order("name");if(He)throw He;return je}}),{data:se=[]}=dt({queryKey:["template-types"],queryFn:async()=>{const{data:je,error:He}=await q.from("template_types").select("*").order("name");if(He)throw He;return je}}),{data:oe=[],isLoading:he}=dt({queryKey:["canva-templates-admin"],queryFn:async()=>{const{data:je,error:He}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).order("publish_date",{ascending:!1});if(He)throw He;const{data:$e,error:Ke}=await q.from("template_links").select("*").order("sort_order");if(Ke)throw Ke;const{data:Ge,error:rt}=await q.from("template_guides").select("*").order("sort_order");if(rt)throw rt;return je.map(at=>({...at,links:($e==null?void 0:$e.filter(Ye=>Ye.template_id===at.id))||[],guides:(Ge==null?void 0:Ge.filter(Ye=>Ye.template_id===at.id))||[]}))}});N.useEffect(()=>{const je=r.get("edit");if(je&&oe.length>0){const He=oe.find($e=>$e.id===je);He&&(Ie(He),a({},{replace:!0}))}},[oe,r]);const ce=yt({mutationFn:async je=>{const{data:He,error:$e}=await q.from("template_categories").insert({name:je}).select().single();if($e)throw $e;return He},onSuccess:je=>{n.invalidateQueries({queryKey:["template-categories"]}),u({...d,category_id:je.id}),I(""),Z(!1),t({title:"Category added"})},onError:je=>{t({title:"Error adding category",description:je.message,variant:"destructive"})}}),me=yt({mutationFn:async je=>{const{data:He,error:$e}=await q.from("template_types").insert({name:je}).select().single();if($e)throw $e;return He},onSuccess:je=>{n.invalidateQueries({queryKey:["template-types"]}),u({...d,type_id:je.id}),z(""),W(!1),t({title:"Type added"})},onError:je=>{t({title:"Error adding type",description:je.message,variant:"destructive"})}}),le=yt({mutationFn:async je=>{var rt;let He=je.existingImageUrl;if(je.image){const tt=je.image.name.split(".").pop(),at=`${Date.now()}-${Math.random().toString(36).substring(7)}.${tt}`,{error:Ye}=await q.storage.from("template-previews").upload(at,je.image);if(Ye)throw Ye;const{data:ut}=q.storage.from("template-previews").getPublicUrl(at);He=ut.publicUrl}const $e={name:je.template.name,description:je.template.description||null,category_id:je.template.category_id||null,type_id:je.template.type_id||null,preview_image_url:He,video_url:je.videoUrl||null,publish_date:je.template.publish_date?new Date(je.template.publish_date).toISOString():new Date().toISOString(),created_by:s==null?void 0:s.id};let Ke=je.templateId;if(Ke){const{error:tt}=await q.from("canva_templates").update($e).eq("id",Ke);if(tt)throw tt;const{error:at}=await q.from("template_links").delete().eq("template_id",Ke);if(at)throw at;const Ye=((rt=je.existingGuides)==null?void 0:rt.map(bt=>bt.id).filter(Boolean))||[],ut=je.template.guides.map(bt=>bt.id).filter(Boolean),_t=Ye.filter(bt=>!ut.includes(bt));_t.length>0&&await q.from("template_guides").delete().in("id",_t)}else{const{data:tt,error:at}=await q.from("canva_templates").insert($e).select().single();if(at)throw at;Ke=tt.id,Nbs(je.template.name,tt.id)}const Ge=je.template.links.filter(tt=>tt.title.trim()&&tt.canva_share_link.trim());if(Ge.length>0){const tt=Ge.map((Ye,ut)=>({template_id:Ke,title:Ye.title.trim(),canva_share_link:Ye.canva_share_link.trim(),sort_order:ut})),{error:at}=await q.from("template_links").insert(tt);if(at)throw at}for(let tt=0;tt0)){const{error:tt}=await q.from("resource_kit_templates").insert(je.linkedKitIds.map(at=>({template_id:Ke,kit_id:at})));if(tt)throw tt}},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),Te(),l(!1),t({title:o?"Template updated":"Template created"})},onError:je=>{t({title:"Error saving template",description:je.message,variant:"destructive"})}}),ve=yt({mutationFn:async je=>{const{error:He}=await q.from("canva_templates").delete().eq("id",je);if(He)throw He},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]}),t({title:"Template deleted"})},onError:je=>{t({title:"Error deleting template",description:je.message,variant:"destructive"})}}),ge=yt({mutationFn:async({id:je,is_featured:He})=>{const{error:$e}=await q.from("canva_templates").update({is_featured:He}).eq("id",je);if($e)throw $e},onSuccess:()=>{n.invalidateQueries({queryKey:["canva-templates-admin"]}),n.invalidateQueries({queryKey:["canva-templates"]})},onError:je=>{t({title:"Error updating featured",description:je.message,variant:"destructive"})}}),Te=()=>{u({name:"",description:"",category_id:"",type_id:"",publish_date:new Date().toISOString().split("T")[0],links:[{title:"",canva_share_link:"",sort_order:0}],guides:[],video_url:""}),w(null),A(""),c(null),Z(!1),W(!1),I(""),z(""),p(null),y(0),v(!1),O([])},Ie=async je=>{var $e;c(je),u({name:je.name,description:je.description||"",category_id:je.category_id||"",type_id:je.type_id||"",publish_date:je.publish_date?new Date(je.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],links:je.links&&je.links.length>0?je.links.map(Ke=>({id:Ke.id,title:Ke.title,canva_share_link:Ke.canva_share_link,sort_order:Ke.sort_order})):[{title:"",canva_share_link:"",sort_order:0}],guides:(($e=je.guides)==null?void 0:$e.map(Ke=>({id:Ke.id,name:Ke.name,file_url:Ke.file_url,file_type:Ke.file_type,file_size:Ke.file_size,sort_order:Ke.sort_order})))||[],video_url:je.video_url||""}),A(je.preview_image_url||""),p(null);const{data:He}=await q.from("resource_kit_templates").select("kit_id").eq("template_id",je.id);O((He||[]).map(Ke=>Ke.kit_id)),l(!0)},Ce=je=>{var $e;const He=($e=je.target.files)==null?void 0:$e[0];He&&(w(He),A(URL.createObjectURL(He)))},Me=()=>{u({...d,links:[...d.links,{title:"",canva_share_link:"",sort_order:d.links.length}]})},Pe=je=>{if(d.links.length<=1)return;const He=d.links.filter(($e,Ke)=>Ke!==je);u({...d,links:He})},Re=(je,He,$e)=>{const Ke=[...d.links];Ke[je]={...Ke[je],[He]:$e},u({...d,links:Ke})},Ae=je=>{const He=je.target.files;if(!He)return;const $e=Array.from(He).map((Ke,Ge)=>({name:Ke.name.replace(/\.[^/.]+$/,""),file_url:"",file_type:Ke.type,file_size:Ke.size,sort_order:d.guides.length+Ge,file:Ke}));u({...d,guides:[...d.guides,...$e]}),je.target.value=""},Be=je=>{const He=d.guides.filter(($e,Ke)=>Ke!==je);u({...d,guides:He})},we=(je,He)=>{const $e=[...d.guides];$e[je]={...$e[je],name:He},u({...d,guides:$e})},Je=async()=>{if(!h)return null;v(!0),y(0);try{const{data:je,error:He}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.name||h.name}});if(He)throw new Error(He.message);const{videoId:$e,libraryId:Ke}=je,{data:Ge,error:rt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$e}});if(rt)throw new Error(rt.message);const tt=new XMLHttpRequest;return await new Promise((Ye,ut)=>{tt.upload.addEventListener("progress",_t=>{if(_t.lengthComputable){const bt=Math.round(_t.loaded/_t.total*100);y(bt)}}),tt.addEventListener("load",()=>{tt.status>=200&&tt.status<300?Ye():ut(new Error(`Upload failed with status ${tt.status}`))}),tt.addEventListener("error",()=>ut(new Error("Upload failed"))),tt.open("PUT",Ge.uploadUrl),tt.setRequestHeader("AccessKey",Ge.apiKey),tt.send(h)}),`https://player.mediadelivery.net/embed/${Ke}/${$e}`}catch(je){return console.error("Bunny upload error:",je),t({title:"Video upload failed",description:je instanceof Error?je.message:"Unknown error",variant:"destructive"}),null}finally{v(!1)}},ke=je=>{var $e;const He=($e=je.target.files)==null?void 0:$e[0];He&&p(He),je.target.value=""},it=async je=>{if(je.preventDefault(),!d.name.trim()){t({title:"Please enter a template name",variant:"destructive"});return}if(d.links.filter(Ke=>Ke.title.trim()&&Ke.canva_share_link.trim()).length===0){t({title:"Please add at least one Canva link",variant:"destructive"});return}let $e=d.video_url;if(h){const Ke=await Je();if(!Ke)return;$e=Ke}le.mutate({template:d,image:j,existingImageUrl:(o==null?void 0:o.preview_image_url)||null,templateId:o==null?void 0:o.id,existingGuides:o==null?void 0:o.guides,videoUrl:$e,linkedKitIds:E})};return e.jsx(Cs,{title:"Manage Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Manage Templates",description:"Create and manage Canva templates"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Templates"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:oe.length})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Categories"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:ee.length})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Template Types"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:se.length})})]})]}),e.jsxs(_s,{open:i,onOpenChange:je=>{l(je),je||Te()},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Template"]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{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(ne,{htmlFor:"name",children:"Name *"}),e.jsx(ye,{id:"name",value:d.name,onChange:je=>u({...d,name:je.target.value}),placeholder:"Template name",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:d.description,onChange:je=>u({...d,description:je}),placeholder:"Brief description of the template",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Canva Links *"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Me,className:"gap-1",children:[e.jsx(Is,{className:"h-3 w-3"}),"Add Link"]})]}),e.jsx("div",{className:"space-y-3",children:d.links.map((je,He)=>e.jsxs("div",{className:"flex gap-2 items-start p-3 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ye,{value:je.title,onChange:$e=>Re(He,"title",$e.target.value),placeholder:"Link title (e.g., Instagram Post, Story)"}),e.jsx(ye,{value:je.canva_share_link,onChange:$e=>Re(He,"canva_share_link",$e.target.value),placeholder:"https://www.canva.com/design/..."})]}),d.links.length>1&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>Pe(He),children:e.jsx($n,{className:"h-4 w-4"})})]},He))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Category"}),H?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:D,onChange:je=>I(je.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>D.trim()&&ce.mutate(D.trim()),disabled:ce.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{Z(!1),I("")},children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:d.category_id,onValueChange:je=>u({...d,category_id:je}),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(cs,{children:ee.map(je=>e.jsx(Ze,{value:je.id,children:je.name},je.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>Z(!0),children:e.jsx(Is,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Template Type"}),Y?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:F,onChange:je=>z(je.target.value),placeholder:"New type name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>F.trim()&&me.mutate(F.trim()),disabled:me.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{W(!1),z("")},children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:d.type_id,onValueChange:je=>u({...d,type_id:je}),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select type"})}),e.jsx(cs,{children:se.map(je=>e.jsx(Ze,{value:je.id,children:je.name},je.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>W(!0),children:e.jsx(Is,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:d.publish_date,onChange:je=>u({...d,publish_date:je.target.value})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Templates are sorted by publish date (newest first) on the member page"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[S?e.jsxs("div",{className:"relative w-32 h-24 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("img",{src:S,alt:"Preview",className:"w-full h-full object-cover"}),e.jsx(B,{type:"button",size:"icon",variant:"destructive",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>{w(null),A("")},children:e.jsx($n,{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(Xo,{className:"h-8 w-8 text-muted-foreground/50"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:Ce,className:"cursor-pointer"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Upload a preview image for this template"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{children:"Video (Optional)"}),d.video_url&&!h?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(fr,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:"Video uploaded"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>u({...d,video_url:""}),className:"text-destructive hover:text-destructive",children:"Remove"})]}),e.jsx("div",{className:"aspect-video max-w-md rounded-lg overflow-hidden border",children:e.jsx("iframe",{src:d.video_url,className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})]}):_?e.jsxs("div",{className:"space-y-2 p-4 border rounded-lg bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),e.jsxs("span",{className:"text-sm",children:["Uploading video... ",f,"%"]})]}),e.jsx(fi,{value:f,className:"h-2"})]}):h?e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/30",children:[e.jsx(fr,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:h.name}),e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(h.size/1024/1024).toFixed(1)," MB"]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>p(null),children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(ye,{type:"file",accept:"video/*",onChange:ke,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(fr,{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(ne,{children:"Guide Files (PDFs)"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(ye,{type:"file",accept:".pdf,.doc,.docx",multiple:!0,onChange:Ae,className:"hidden"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",asChild:!0,children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-3 w-3"}),"Add Files"]})})]})]}),d.guides.length>0?e.jsx("div",{className:"space-y-2",children:d.guides.map((je,He)=>e.jsxs("div",{className:"flex gap-2 items-center p-3 border rounded-lg bg-muted/30",children:[e.jsx(br,{className:"h-5 w-5 text-muted-foreground shrink-0"}),e.jsx(ye,{value:je.name,onChange:$e=>we(He,$e.target.value),placeholder:"Guide name",className:"flex-1"}),je.file_size&&e.jsxs("span",{className:"text-xs text-muted-foreground shrink-0",children:[(je.file_size/1024).toFixed(0)," KB"]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"shrink-0 text-muted-foreground hover:text-destructive h-8 w-8",onClick:()=>Be(He),children:e.jsx($n,{className:"h-4 w-4"})})]},je.id||He))}):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(Dbs,{selectedKitIds:E,onChange:O}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{l(!1),Te()},children:"Cancel"}),e.jsx(B,{type:"submit",disabled:le.isPending,children:le.isPending?"Saving...":o?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:he?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading..."}):oe.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No templates yet. Add your first template!"}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Preview"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Links"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{className:"w-[72px] text-center",children:"Featured"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:oe.map(je=>{var He,$e,Ke,Ge,rt;return e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsx("div",{className:"w-16 h-12 rounded overflow-hidden bg-muted",children:je.preview_image_url?e.jsx("img",{src:je.preview_image_url,alt:je.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Xo,{className:"h-4 w-4 text-muted-foreground"})})})}),e.jsx(ht,{className:"font-medium",children:je.name}),e.jsx(ht,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsxs(Ue,{variant:"secondary",children:[((He=je.links)==null?void 0:He.length)||0," link",((($e=je.links)==null?void 0:$e.length)||0)!==1?"s":""]}),(((Ke=je.guides)==null?void 0:Ke.length)||0)>0&&e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(br,{className:"h-3 w-3"}),(Ge=je.guides)==null?void 0:Ge.length," guide",(((rt=je.guides)==null?void 0:rt.length)||0)!==1?"s":""]})]})}),e.jsx(ht,{children:je.category?e.jsx(Ue,{variant:"secondary",children:je.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ht,{children:je.type?e.jsx(Ue,{variant:"outline",children:je.type.name}):e.jsx("span",{className:"text-muted-foreground",children:"-"})}),e.jsx(ht,{className:"text-muted-foreground",children:new Date(je.publish_date).toLocaleDateString()}),e.jsx(ht,{className:"text-center",children:e.jsx(B,{type:"button",size:"icon",variant:"ghost",className:"mx-auto",title:je.is_featured?"Remove from featured templates":"Add to featured templates",onClick:()=>ge.mutate({id:je.id,is_featured:!je.is_featured}),children:e.jsx(oa,{className:`h-4 w-4 ${je.is_featured?"fill-yellow-400 text-yellow-400":"text-muted-foreground"}`})})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>Ie(je),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&ve.mutate(je.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},je.id)})})]})})})]})})};function z0t({selectedTemplateIds:s,onChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l=[]}=dt({queryKey:["all-canva-templates-picker"],queryFn:async()=>{const{data:h,error:p}=await q.from("canva_templates").select("id, name, preview_image_url").order("name");if(p)throw p;return h}}),o=l.filter(h=>s.includes(h.id)),c=l.filter(h=>!s.includes(h.id)&&h.name.toLowerCase().includes(n.toLowerCase())),d=h=>{t([...s,h])},u=h=>{t(s.filter(p=>p!==h))};return e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(WS,{className:"h-4 w-4"}),"Linked Templates"]}),o.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:o.map(h=>e.jsxs(Ue,{variant:"secondary",className:"gap-1 pr-1",children:[h.name,e.jsx("button",{type:"button",onClick:()=>u(h.id),className:"ml-1 rounded-full hover:bg-muted-foreground/20 p-0.5",children:e.jsx($n,{className:"h-3 w-3"})})]},h.id))}),e.jsxs(il,{open:a,onOpenChange:i,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-1",children:[e.jsx(WS,{className:"h-3.5 w-3.5"}),"Add Template"]})}),e.jsxs(el,{className:"w-80 p-2",align:"start",children:[e.jsxs("div",{className:"relative mb-2",children:[e.jsx(gr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search templates...",value:n,onChange:h=>r(h.target.value),className:"pl-7 h-8 text-sm"})]}),e.jsx("div",{className:"max-h-48 overflow-y-auto space-y-0.5",children:c.length===0?e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:n?"No templates found":"All templates selected"}):c.map(h=>e.jsxs("button",{type:"button",onClick:()=>{d(h.id),r("")},className:"w-full flex items-center gap-2 px-2 py-1.5 rounded-md hover:bg-muted text-left text-sm transition-colors",children:[h.preview_image_url?e.jsx("img",{src:h.preview_image_url,alt:"",className:"w-8 h-8 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-8 h-8 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(WS,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("span",{className:"truncate",children:h.name})]},h.id))})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link templates that agents can use alongside this content."})]})}const Obs=[{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"}],Fbs=()=>{const{user:s}=vs(),[t,n]=xl(),{toast:r}=Fa(),a=Kt(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({title:"",description:"",video_url:"",video_type:"youtube",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[h,p]=N.useState(null),[f,y]=N.useState(""),[_,v]=N.useState([]),[j,w]=N.useState([]),[S,A]=N.useState([]),[E,O]=N.useState([]),[D,I]=N.useState(""),[F,z]=N.useState(!1),[H,Z]=N.useState(null),[Y,W]=N.useState(0),[ee,se]=N.useState(!1),[oe,he]=N.useState(null),{data:ce=[]}=dt({queryKey:["academy-categories"],queryFn:async()=>{const{data:je,error:He}=await q.from("academy_categories").select("*").order("sort_order",{ascending:!0});if(He)throw He;return je}}),{data:me=[],isLoading:le}=dt({queryKey:["academy-videos-admin"],queryFn:async()=>{const{data:je,error:He}=await q.from("academy_videos").select(` *, category:academy_categories(id, name) `).order("publish_date",{ascending:!1});if(He)throw He;const{data:$e,error:Ke}=await q.from("academy_resources").select("*").order("sort_order");if(Ke)throw Ke;return je.map(rt=>({...rt,resources:($e==null?void 0:$e.filter(tt=>tt.video_id===rt.id))||[]}))}});N.useEffect(()=>{const je=t.get("edit");if(je&&me.length>0){const He=me.find($e=>$e.id===je);He&&(Re(He),n({},{replace:!0}))}},[me,t]);const ve=yt({mutationFn:async je=>{const{data:He,error:$e}=await q.from("academy_categories").insert({name:je,sort_order:ce.length}).select().single();if($e)throw $e;return He},onSuccess:je=>{a.invalidateQueries({queryKey:["academy-categories"]}),u({...d,category_id:je.id}),I(""),z(!1),r({title:"Category added"})},onError:je=>{r({title:"Error adding category",description:je.message,variant:"destructive"})}}),ge=yt({mutationFn:async je=>{let He=je.existingThumbnailUrl;if(je.thumbnail){const Ge=je.thumbnail.name.split(".").pop(),rt=`thumbnails/${Date.now()}-${Math.random().toString(36).substring(7)}.${Ge}`,{error:tt}=await q.storage.from("academy-resources").upload(rt,je.thumbnail);if(tt)throw tt;const{data:at}=q.storage.from("academy-resources").getPublicUrl(rt);He=at.publicUrl}const $e={title:je.video.title,description:je.video.description||null,video_url:je.video.video_url,video_type:je.video.video_type,duration:je.video.duration||null,thumbnail_url:He,category_id:je.video.category_id||null,publish_date:je.video.publish_date?new Date(je.video.publish_date).toISOString():new Date().toISOString(),is_published:je.video.is_published,created_by:s==null?void 0:s.id};let Ke=je.videoId;if(Ke){const{error:Ge}=await q.from("academy_videos").update($e).eq("id",Ke);if(Ge)throw Ge}else{const{data:Ge,error:rt}=await q.from("academy_videos").insert($e).select().single();if(rt)throw rt;Ke=Ge.id,kbs(je.video.title,Ge.id)}if(je.resourcesToDelete.length>0){const{error:Ge}=await q.from("academy_resources").delete().in("id",je.resourcesToDelete);if(Ge)throw Ge}for(let Ge=0;Ge0){const{error:Ge}=await q.from("academy_video_templates").insert(E.map(rt=>({video_id:Ke,template_id:rt})));if(Ge)throw Ge}},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),Pe(),l(!1),r({title:o?"Video updated":"Video created"})},onError:je=>{r({title:"Error saving video",description:je.message,variant:"destructive"})}}),Te=yt({mutationFn:async je=>{const{error:He}=await q.from("academy_videos").delete().eq("id",je);if(He)throw He},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]}),r({title:"Video deleted"})},onError:je=>{r({title:"Error deleting video",description:je.message,variant:"destructive"})}}),Ie=yt({mutationFn:async({id:je,is_published:He})=>{const{error:$e}=await q.from("academy_videos").update({is_published:He}).eq("id",je);if($e)throw $e},onSuccess:()=>{a.invalidateQueries({queryKey:["academy-videos-admin"]}),a.invalidateQueries({queryKey:["academy-videos"]})},onError:je=>{r({title:"Error updating video",description:je.message,variant:"destructive"})}}),Ce=async je=>{try{let He=je.public_slug||null,$e=!!je.is_public;if(!He||!$e){const Ge=(je.title||"video").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"").slice(0,60)||"video";if(!He){let tt=Ge;const{data:at}=await q.from("academy_videos").select("id").eq("public_slug",tt).maybeSingle();at&&at.id!==je.id&&(tt=`${Ge}-${je.id.slice(0,6)}`),He=tt}const{error:rt}=await q.from("academy_videos").update({public_slug:He,is_public:!0}).eq("id",je.id);if(rt)throw rt;a.invalidateQueries({queryKey:["academy-videos-admin"]})}const Ke=`${window.location.origin}/watch/${He}`;await navigator.clipboard.writeText(Ke),r({title:"Public link copied",description:Ke})}catch(He){r({title:"Could not copy link",description:He.message,variant:"destructive"})}},Me=async je=>{if(!confirm("Disable the public teaser link for this video?"))return;const{error:He}=await q.from("academy_videos").update({is_public:!1}).eq("id",je.id);if(He){r({title:"Error",description:He.message,variant:"destructive"});return}a.invalidateQueries({queryKey:["academy-videos-admin"]}),r({title:"Public link disabled"})},Pe=()=>{u({title:"",description:"",video_url:"",video_type:"bunny_stream",duration:"",category_id:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),p(null),y(""),v([]),w([]),A([]),c(null),O([]),I(""),Z(null),W(0),se(!1),he(null)},Re=async je=>{c(je),u({title:je.title,description:je.description||"",video_url:je.video_url,video_type:je.video_type,duration:je.duration||"",category_id:je.category_id||"",publish_date:je.publish_date?new Date(je.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:je.is_published}),y(je.thumbnail_url||""),w(je.resources||[]),v([]),A([]);const{data:He}=await q.from("academy_video_templates").select("template_id").eq("video_id",je.id);O((He||[]).map($e=>$e.template_id)),l(!0)},Ae=je=>{var $e;const He=($e=je.target.files)==null?void 0:$e[0];He&&(p(He),y(URL.createObjectURL(He)))},Be=je=>{const He=je.target.files;if(He){const $e=Array.from(He).map(Ke=>({file:Ke,title:Ke.name.replace(/\.[^/.]+$/,"")}));v([..._,...$e])}je.target.value=""},we=je=>{v(_.filter((He,$e)=>$e!==je))},Je=je=>{A([...S,je]),w(j.filter(He=>He.id!==je))},ke=async()=>{if(!H)return null;se(!0),W(0);try{const{data:je,error:He}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d.title||H.name}});if(He)throw new Error(He.message);const{videoId:$e,libraryId:Ke}=je;he($e);const{data:Ge,error:rt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:$e}});if(rt)throw new Error(rt.message);const tt=new XMLHttpRequest;return await new Promise((Ye,ut)=>{tt.upload.addEventListener("progress",_t=>{if(_t.lengthComputable){const bt=Math.round(_t.loaded/_t.total*100);W(bt)}}),tt.addEventListener("load",()=>{tt.status>=200&&tt.status<300?Ye():ut(new Error(`Upload failed with status ${tt.status}`))}),tt.addEventListener("error",()=>ut(new Error("Upload failed"))),tt.open("PUT",Ge.uploadUrl),tt.setRequestHeader("AccessKey",Ge.apiKey),tt.send(H)}),`https://player.mediadelivery.net/embed/${Ke}/${$e}`}catch(je){return console.error("Bunny upload error:",je),r({title:"Video upload failed",description:je instanceof Error?je.message:"Unknown error",variant:"destructive"}),null}finally{se(!1)}},it=async je=>{if(je.preventDefault(),!d.title.trim()){r({title:"Please enter a video title",variant:"destructive"});return}let He=d.video_url;if(d.video_type==="bunny_stream"&&H&&!o){const $e=await ke();if(!$e)return;He=$e}else if(!d.video_url.trim()&&d.video_type!=="bunny_stream"){r({title:"Please enter a video URL",variant:"destructive"});return}else if(d.video_type==="bunny_stream"&&!H&&!d.video_url&&!o){r({title:"Please select a video file to upload",variant:"destructive"});return}ge.mutate({video:{...d,video_url:He},thumbnail:h,existingThumbnailUrl:(o==null?void 0:o.thumbnail_url)||null,videoId:o==null?void 0:o.id,newResources:_,resourcesToDelete:S})};return e.jsx(Cs,{title:"Manage Academy",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Manage Academy",description:"Create and manage training videos and resources"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Videos"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:me.length})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:me.filter(je=>je.is_published).length})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Public Teasers"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:me.filter(je=>je.is_public).length})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Public Views"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:me.reduce((je,He)=>je+(He.public_view_count||0),0).toLocaleString()})})]})]}),e.jsxs(_s,{open:i,onOpenChange:je=>{l(je),je||Pe()},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Video"]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:o?"Edit Video":"Add New Video"})}),e.jsxs("form",{onSubmit:it,className:"space-y-6 pt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:d.title,onChange:je=>u({...d,title:je.target.value}),placeholder:"Video title",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:d.description,onChange:je=>u({...d,description:je}),placeholder:"Brief description of the video",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Video Type"}),e.jsxs(us,{value:d.video_type,onValueChange:je=>{u({...d,video_type:je,video_url:""}),Z(null)},disabled:ee,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Obs.map(je=>e.jsx(Ze,{value:je.value,children:je.label},je.value))})]})]}),d.video_type==="bunny_stream"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs(ne,{children:["Upload Video File ",!o&&"*"]}),o&&d.video_url&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Current video: ",e.jsx("a",{href:d.video_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"View"})]}),!o&&e.jsxs(e.Fragment,{children:[e.jsx(ye,{type:"file",accept:"video/*",onChange:je=>{var $e;const He=($e=je.target.files)==null?void 0:$e[0];He&&Z(He)},disabled:ee}),H&&e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(fr,{className:"h-4 w-4"}),H.name," (",(H.size/(1024*1024)).toFixed(1)," MB)"]}),ee&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{className:"text-sm",children:"Uploading to Bunny.net..."})]}),e.jsx(fi,{value:Y,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[Y,"%"]})]})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"video_url",children:"Video URL *"}),e.jsx(ye,{id:"video_url",value:d.video_url,onChange:je=>u({...d,video_url:je.target.value}),placeholder:"https://...",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"duration",children:"Duration"}),e.jsx(ye,{id:"duration",value:d.duration,onChange:je=>u({...d,duration:je.target.value}),placeholder:"e.g., 45:30"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:d.publish_date,onChange:je=>u({...d,publish_date:je.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Category"}),F?e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:D,onChange:je=>I(je.target.value),placeholder:"New category name",className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:()=>D.trim()&&ve.mutate(D.trim()),disabled:ve.isPending,children:"Add"}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",onClick:()=>{z(!1),I("")},children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:d.category_id,onValueChange:je=>u({...d,category_id:je}),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(cs,{children:ce.map(je=>e.jsx(Ze,{value:je.id,children:je.name},je.id))})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>z(!0),children:e.jsx(Is,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Thumbnail Image"}),e.jsxs("div",{className:"flex items-start gap-4",children:[f&&e.jsx("img",{src:f,alt:"Thumbnail preview",className:"w-32 h-20 object-cover rounded-md border"}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:Ae,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(ne,{children:"Resource Files"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{className:"cursor-pointer gap-1",children:[e.jsx(_a,{className:"h-3 w-3"}),"Add Files",e.jsx("input",{type:"file",multiple:!0,accept:".pdf,.pptx,.ppt,.xlsx,.xls,.docx,.doc,.zip",onChange:Be,className:"hidden"})]})})]}),(j.length>0||_.length>0)&&e.jsxs("div",{className:"space-y-2 mt-2",children:[j.map(je=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(br,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm truncate",children:je.title}),e.jsx(Ue,{variant:"outline",className:"text-xs",children:je.file_type}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>Je(je.id),className:"text-destructive hover:text-destructive",children:e.jsx($n,{className:"h-4 w-4"})})]},je.id)),_.map((je,He)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 border rounded-md bg-muted/30",children:[e.jsx(br,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:je.title,onChange:$e=>{const Ke=[..._];Ke[He].title=$e.target.value,v(Ke)},className:"flex-1 h-8",placeholder:"Resource title"}),e.jsx(Ue,{variant:"secondary",className:"text-xs",children:"New"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>we(He),className:"text-destructive hover:text-destructive",children:e.jsx($n,{className:"h-4 w-4"})})]},He))]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Supported: PDF, PowerPoint, Excel, Word, ZIP"})]}),e.jsx(z0t,{selectedTemplateIds:E,onChange:O}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{id:"is_published",checked:d.is_published,onCheckedChange:je=>u({...d,is_published:je})}),e.jsx(ne,{htmlFor:"is_published",children:"Published"})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),disabled:ee,children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ge.isPending||ee,children:ee?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):ge.isPending?"Saving...":o?"Update Video":"Add Video"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:le?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):me.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(fr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No videos yet"}),e.jsx("p",{className:"text-sm",children:"Add your first academy video"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Resources"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Public Views"}),e.jsx(Tt,{className:"w-[120px]",children:"Actions"})]})}),e.jsx(da,{children:me.map(je=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[je.thumbnail_url?e.jsx("img",{src:je.thumbnail_url,alt:"",className:"w-16 h-10 object-cover rounded"}):e.jsx("div",{className:"w-16 h-10 bg-muted rounded flex items-center justify-center",children:e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:je.title}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:je.video_type.replace("_"," ")})]})]})}),e.jsx(ht,{children:je.category?e.jsx(Ue,{variant:"outline",children:je.category.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ht,{children:je.duration||"-"}),e.jsx(ht,{children:je.resources&&je.resources.length>0?e.jsxs(Ue,{variant:"secondary",children:[je.resources.length," file(s)"]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ht,{children:new Date(je.publish_date).toLocaleDateString()}),e.jsx(ht,{children:e.jsx(jn,{checked:je.is_published,onCheckedChange:He=>Ie.mutate({id:je.id,is_published:He})})}),e.jsx(ht,{children:je.is_public?e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"text-sm font-medium",children:(je.public_view_count||0).toLocaleString()})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",title:je.is_public?"Copy public teaser link":"Make public & copy teaser link",onClick:()=>Ce(je),children:je.is_public?e.jsx(Zr,{className:"h-4 w-4 text-primary"}):e.jsx(Vl,{className:"h-4 w-4"})}),je.is_public&&e.jsx(B,{variant:"ghost",size:"sm",title:"Disable public link",onClick:()=>Me(je),children:e.jsx(lc,{className:"h-4 w-4 text-emerald-500"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Re(je),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Te.mutate(je.id),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},je.id))})]})})})]})})};function zbs(){var ge,Te,Ie;const s=Kt(),[t,n]=xl(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=N.useState(null),[h,p]=N.useState(""),[f,y]=N.useState([]),[_,v]=N.useState([]),[j,w]=N.useState([]),[S,A]=N.useState(null),{data:E,isLoading:O}=dt({queryKey:["resource-kits"],queryFn:async()=>{const{data:Ce,error:Me}=await q.from("resource_kits").select("*").order("publish_date",{ascending:!1});if(Me)throw Me;return Ce}}),{data:D}=dt({queryKey:["resource-kit-files"],queryFn:async()=>{const{data:Ce,error:Me}=await q.from("resource_kit_files").select("*").order("sort_order",{ascending:!0});if(Me)throw Me;return Ce}}),{data:I}=dt({queryKey:["resource-kit-links"],queryFn:async()=>{const{data:Ce,error:Me}=await q.from("resource_kit_links").select("*").order("sort_order",{ascending:!0});if(Me)throw Me;return Ce}});N.useEffect(()=>{const Ce=t.get("edit");if(Ce&&E&&E.length>0&&D&&I){const Me=E.find(Pe=>Pe.id===Ce);Me&&(z(Me),n({},{replace:!0}))}},[E,D,I,t]);const F=()=>{c({name:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),p(""),y([]),v([]),w([]),l(null)},z=async Ce=>{l(Ce),c({name:Ce.name,description:Ce.description||"",publish_date:Ce.publish_date.split("T")[0],is_published:Ce.is_published}),p(Ce.featured_image_url||"");const Me=(D==null?void 0:D.filter(Ae=>Ae.kit_id===Ce.id))||[];y(Me.map(Ae=>({id:Ae.id,name:Ae.name,file_url:Ae.file_url,file_type:Ae.file_type,file_size:Ae.file_size,sort_order:Ae.sort_order})));const Pe=(I==null?void 0:I.filter(Ae=>Ae.kit_id===Ce.id))||[];v(Pe.map(Ae=>({id:Ae.id,title:Ae.title,canva_share_link:Ae.canva_share_link,sort_order:Ae.sort_order})));const{data:Re}=await q.from("resource_kit_templates").select("template_id").eq("kit_id",Ce.id);w((Re||[]).map(Ae=>Ae.template_id)),a(!0)},H=Ce=>{var Pe;const Me=(Pe=Ce.target.files)==null?void 0:Pe[0];Me&&(u(Me),p(URL.createObjectURL(Me)))},Z=()=>{y([...f,{name:"",file_url:"",sort_order:f.length}])},Y=Ce=>{y(f.filter((Me,Pe)=>Pe!==Ce))},W=(Ce,Me,Pe)=>{const Re=[...f];Re[Ce]={...Re[Ce],[Me]:Pe},y(Re)},ee=()=>{v([..._,{title:"",canva_share_link:"",sort_order:_.length}])},se=Ce=>{v(_.filter((Me,Pe)=>Pe!==Ce))},oe=(Ce,Me,Pe)=>{const Re=[..._];Re[Ce]={...Re[Ce],[Me]:Pe},v(Re)},he=(Ce,Me)=>{var Re;const Pe=(Re=Me.target.files)==null?void 0:Re[0];if(Pe){const Ae=[...f],Be=Pe.name.replace(/\.[^/.]+$/,"");Ae[Ce]={...Ae[Ce],file:Pe,file_type:Pe.type,file_size:Pe.size,name:Ae[Ce].name||Be},y(Ae)}},ce=yt({mutationFn:async()=>{let Ce=(i==null?void 0:i.featured_image_url)||null;if(d){const Be=d.name.split(".").pop(),we=`${Date.now()}.${Be}`,{error:Je}=await q.storage.from("resource-kits").upload(`featured/${we}`,d);if(Je)throw Je;const{data:ke}=q.storage.from("resource-kits").getPublicUrl(`featured/${we}`);Ce=ke.publicUrl}const Me={name:o.name,description:o.description||null,featured_image_url:Ce,publish_date:o.publish_date,is_published:o.is_published};let Pe;const Re=!i,Ae=(i==null?void 0:i.is_published)||!1;if(i){const{error:Be}=await q.from("resource_kits").update(Me).eq("id",i.id);if(Be)throw Be;Pe=i.id;const we=(D==null?void 0:D.filter($e=>$e.kit_id===i.id).map($e=>$e.id))||[],Je=f.filter($e=>$e.id).map($e=>$e.id),ke=we.filter($e=>!Je.includes($e));ke.length>0&&await q.from("resource_kit_files").delete().in("id",ke);const it=(I==null?void 0:I.filter($e=>$e.kit_id===i.id).map($e=>$e.id))||[],je=_.filter($e=>$e.id).map($e=>$e.id),He=it.filter($e=>!je.includes($e));He.length>0&&await q.from("resource_kit_links").delete().in("id",He)}else{const{data:Be,error:we}=await q.from("resource_kits").insert(Me).select().single();if(we)throw we;Pe=Be.id}for(let Be=0;Be0){const{error:Be}=await q.from("resource_kit_templates").insert(j.map(we=>({kit_id:Pe,template_id:we})));if(Be)throw Be}return{kitId:Pe,kitName:o.name,isNewKit:Re,wasPublished:Ae,isPublished:o.is_published}},onSuccess:Ce=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),s.invalidateQueries({queryKey:["resource-kit-links"]}),ae.success(i?"Resource kit updated":"Resource kit created"),Ce.isPublished&&(Ce.isNewKit||!Ce.wasPublished)&&Cbs(Ce.kitName,Ce.kitId),a(!1),F()},onError:Ce=>{ae.error("Failed to save resource kit: "+Ce.message)}}),me=yt({mutationFn:async Ce=>{const{error:Me}=await q.from("resource_kits").delete().eq("id",Ce);if(Me)throw Me},onSuccess:()=>{s.invalidateQueries({queryKey:["resource-kits"]}),s.invalidateQueries({queryKey:["resource-kit-files"]}),ae.success("Resource kit deleted")},onError:Ce=>{ae.error("Failed to delete: "+Ce.message)}}),le=Ce=>{if(Ce.preventDefault(),!o.name){ae.error("Please enter a name");return}ce.mutate()},ve=Ce=>(D==null?void 0:D.filter(Me=>Me.kit_id===Ce).length)||0;return e.jsx(Cs,{title:"Toolbox Management",description:"Create and manage resource kits for agents",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Kits"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(E==null?void 0:E.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(E==null?void 0:E.filter(Ce=>Ce.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{F(),a(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Resource Kit"]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Files"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:O?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):(E==null?void 0:E.length)===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No resource kits yet. Create your first one!"})}):E==null?void 0:E.map(Ce=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Ce.featured_image_url?e.jsx("img",{src:Ce.featured_image_url,alt:Ce.name,className:"w-10 h-10 rounded object-cover"}):e.jsx("div",{className:"w-10 h-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Ec,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Ce.name}),Ce.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Ce.description})]})]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-4 w-4 text-muted-foreground"}),ve(Ce.id)]})}),e.jsx(ht,{children:Ss(new Date(Ce.publish_date),"MMM d, yyyy")}),e.jsx(ht,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Ce.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:Ce.is_published?"Published":"Draft"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const Me=(D==null?void 0:D.filter(Re=>Re.kit_id===Ce.id))||[],Pe=(I==null?void 0:I.filter(Re=>Re.kit_id===Ce.id))||[];A({...Ce,files:Me,links:Pe})},children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>z(Ce),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource kit?")&&me.mutate(Ce.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},Ce.id))})]})})}),e.jsx(_s,{open:r,onOpenChange:a,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:i?"Edit Resource Kit":"Add Resource Kit"})}),e.jsxs("form",{onSubmit:le,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Featured Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[h?e.jsx("img",{src:h,alt:"Preview",className:"w-24 h-24 rounded object-cover"}):e.jsx("div",{className:"w-24 h-24 rounded bg-muted flex items-center justify-center",children:e.jsx(Ec,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ye,{type:"file",accept:"image/*",onChange:H})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"name",children:"Name *"}),e.jsx(ye,{id:"name",value:o.name,onChange:Ce=>c({...o,name:Ce.target.value}),placeholder:"Resource Kit Name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:o.description,onChange:Ce=>c({...o,description:Ce}),placeholder:"Brief description of this resource kit",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:o.publish_date,onChange:Ce=>c({...o,publish_date:Ce.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(jn,{checked:o.is_published,onCheckedChange:Ce=>c({...o,is_published:Ce})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:o.is_published?"Visible to agents":"Hidden from agents"})]})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ne,{children:"Resource Files"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Z,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add File"]})]}),f.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No files added yet. Click "Add File" to include resources.'}):e.jsx("div",{className:"space-y-3",children:f.map((Ce,Me)=>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 ",Me+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>Y(Me),children:e.jsx($n,{className:"h-4 w-4"})})]}),e.jsx(ye,{placeholder:"File name (e.g., Getting Started Guide)",value:Ce.name,onChange:Pe=>W(Me,"name",Pe.target.value)}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"file",onChange:Pe=>he(Me,Pe),className:"flex-1"}),Ce.file_url&&!Ce.file&&e.jsx("a",{href:Ce.file_url,target:"_blank",rel:"noopener noreferrer",className:"text-sm text-primary hover:underline whitespace-nowrap",children:"Current file"}),Ce.file&&e.jsx("span",{className:"text-sm text-green-600 whitespace-nowrap",children:"New file selected"})]})]},Me))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ne,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ee,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Canva Link"]})]}),_.length===0?e.jsx("div",{className:"text-sm text-muted-foreground py-4 text-center border rounded-md border-dashed",children:'No Canva links added yet. Click "Add Canva Link" to include templates.'}):e.jsx("div",{className:"space-y-3",children:_.map((Ce,Me)=>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 ",Me+1]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>se(Me),children:e.jsx($n,{className:"h-4 w-4"})})]}),e.jsx(ye,{placeholder:"Link title (e.g., Social Media Post Template)",value:Ce.title,onChange:Pe=>oe(Me,"title",Pe.target.value)}),e.jsx(ye,{placeholder:"Canva share link (e.g., https://www.canva.com/design/...)",value:Ce.canva_share_link,onChange:Pe=>oe(Me,"canva_share_link",Pe.target.value)})]},Me))})]}),e.jsx(z0t,{selectedTemplateIds:j,onChange:w}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:ce.isPending,children:ce.isPending?"Saving...":i?"Update":"Create"})]})]})]})}),e.jsx(_s,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(ws,{children:S==null?void 0:S.name})}),e.jsxs("div",{className:"space-y-4",children:[(S==null?void 0:S.featured_image_url)&&e.jsx("img",{src:S.featured_image_url,alt:S.name,className:"w-full h-48 object-cover rounded-lg"}),(S==null?void 0:S.description)&&e.jsx("p",{className:"text-muted-foreground",children:S.description}),e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Resource Files (",((ge=S==null?void 0:S.files)==null?void 0:ge.length)||0,")"]}),((Te=S==null?void 0:S.files)==null?void 0:Te.length)===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No files in this kit"}):e.jsx("div",{className:"space-y-2",children:(Ie=S==null?void 0:S.files)==null?void 0:Ie.map(Ce=>e.jsxs("a",{href:Ce.file_url,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(br,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Ce.name})]},Ce.id))})]}),(S==null?void 0:S.links)&&S.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2",children:["Canva Links (",S.links.length,")"]}),e.jsx("div",{className:"space-y-2",children:S.links.map(Ce=>e.jsxs("a",{href:Ce.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 p-2 rounded-md hover:bg-muted transition-colors",children:[e.jsx(Yo,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"text-sm",children:Ce.title})]},Ce.id))})]})]})]})})]})})}const Bbs=()=>{const{user:s}=vs(),{toast:t}=Fa(),n=Kt(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),[d,u]=N.useState(null),[h,p]=N.useState(""),{data:f=[],isLoading:y}=dt({queryKey:["social-swag-admin"],queryFn:async()=>{const{data:I,error:F}=await q.from("social_swag").select("*").order("publish_date",{ascending:!1});if(F)throw F;const{data:z,error:H}=await q.from("social_swag_links").select("*").order("sort_order");if(H)throw H;return I.map(Y=>({...Y,links:(z==null?void 0:z.filter(W=>W.swag_id===Y.id))||[]}))}}),_=yt({mutationFn:async I=>{let F=I.existingImageUrl;if(I.image){const ee=I.image.name.split(".").pop(),se=`${Date.now()}-${Math.random().toString(36).substring(7)}.${ee}`,{error:oe}=await q.storage.from("template-previews").upload(se,I.image);if(oe)throw oe;const{data:he}=q.storage.from("template-previews").getPublicUrl(se);F=he.publicUrl}const z={title:I.item.title,description:I.item.description||null,preview_image_url:F,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};let H=I.itemId;const Z=!H,Y=(i==null?void 0:i.is_published)||!1;if(H){const{error:ee}=await q.from("social_swag").update(z).eq("id",H);if(ee)throw ee;await q.from("social_swag_links").delete().eq("swag_id",H)}else{const{data:ee,error:se}=await q.from("social_swag").insert(z).select().single();if(se)throw se;H=ee.id}const W=I.item.links.filter(ee=>ee.title.trim()&&ee.canva_share_link.trim());if(W.length>0){const ee=W.map((oe,he)=>({swag_id:H,title:oe.title.trim(),canva_share_link:oe.canva_share_link.trim(),sort_order:he})),{error:se}=await q.from("social_swag_links").insert(ee);if(se)throw se}return{itemId:H,itemTitle:I.item.title,isNewItem:Z,wasPublished:Y,isPublished:I.item.is_published}},onSuccess:I=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:i?"Item updated":"Item created"}),I.isPublished&&(I.isNewItem||!I.wasPublished)&&JCe(I.itemTitle,I.itemId),a(!1),j()},onError:I=>{t({title:"Error saving item",description:I.message,variant:"destructive"})}}),v=yt({mutationFn:async I=>{const{error:F}=await q.from("social_swag").delete().eq("id",I);if(F)throw F},onSuccess:()=>{n.invalidateQueries({queryKey:["social-swag-admin"]}),n.invalidateQueries({queryKey:["social-swag"]}),t({title:"Item deleted"})},onError:I=>{t({title:"Error deleting item",description:I.message,variant:"destructive"})}}),j=()=>{c({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,links:[{title:"",canva_share_link:"",sort_order:0}]}),u(null),p(""),l(null)},w=I=>{l(I),c({title:I.title,description:I.description||"",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,links:I.links&&I.links.length>0?I.links.map(F=>({id:F.id,title:F.title,canva_share_link:F.canva_share_link,sort_order:F.sort_order})):[{title:"",canva_share_link:"",sort_order:0}]}),p(I.preview_image_url||""),a(!0)},S=I=>{var z;const F=(z=I.target.files)==null?void 0:z[0];F&&(u(F),p(URL.createObjectURL(F)))},A=()=>{c({...o,links:[...o.links,{title:"",canva_share_link:"",sort_order:o.links.length}]})},E=I=>{if(o.links.length<=1)return;const F=o.links.filter((z,H)=>H!==I);c({...o,links:F})},O=(I,F,z)=>{const H=[...o.links];H[I]={...H[I],[F]:z},c({...o,links:H})},D=I=>{if(I.preventDefault(),!o.title.trim()){t({title:"Title is required",variant:"destructive"});return}_.mutate({item:o,image:d,existingImageUrl:(i==null?void 0:i.preview_image_url)||null,itemId:i==null?void 0:i.id})};return e.jsx(Cs,{title:"Manage Social Swag",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Manage Social Swag",description:"Create and manage social media content"}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Items"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(I=>I.is_published).length})})]})]}),e.jsxs(_s,{open:r,onOpenChange:I=>{a(I),I||j()},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Item"]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:i?"Edit Item":"Add New Item"})}),e.jsxs("form",{onSubmit:D,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:o.title,onChange:I=>c({...o,title:I.target.value}),placeholder:"Enter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:o.description,onChange:I=>c({...o,description:I}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{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(jn,{id:"is_published",checked:o.is_published,onCheckedChange:I=>c({...o,is_published:I})}),e.jsx(ne,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),p("")},children:e.jsx($n,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(Xo,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ye,{type:"file",accept:"image/*",onChange:S,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:A,children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"Add Link"]})]}),o.links.map((I,F)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4 pb-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"text-sm font-medium text-muted-foreground",children:["Link ",F+1]}),o.links.length>1&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"h-6 w-6 ml-auto",onClick:()=>E(F),children:e.jsx($n,{className:"h-3 w-3"})})]}),e.jsx(ye,{placeholder:"Link title (e.g., Instagram Post)",value:I.title,onChange:z=>O(F,"title",z.target.value)}),e.jsx(ye,{placeholder:"Canva share link",value:I.canva_share_link,onChange:z=>O(F,"canva_share_link",z.target.value)})]})},F))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:_.isPending,children:_.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:y?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No items yet. Click "Add Item" to create your first one.'}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-16",children:"Preview"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Links"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:f.map(I=>{var F;return e.jsxs(Hs,{children:[e.jsx(ht,{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(Xo,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx(ht,{className:"font-medium",children:I.title}),e.jsxs(ht,{children:[((F=I.links)==null?void 0:F.length)||0," links"]}),e.jsx(ht,{children:new Date(I.publish_date).toLocaleDateString()}),e.jsx(ht,{children:e.jsx(Ue,{variant:I.is_published?"default":"secondary",children:I.is_published?"Published":"Draft"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/social-swag/${I.id}`,"_blank"),children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>w(I),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this item?")&&v.mutate(I.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},I.id)})})]})})})]})})};function $bs(){for(var s=arguments.length,t=new Array(s),n=0;nr=>{t.forEach(a=>a(r))},t)}const ove=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function KD(s){const t=Object.prototype.toString.call(s);return t==="[object Window]"||t==="[object global]"}function AIe(s){return"nodeType"in s}function n0(s){var t,n;return s?KD(s)?s:AIe(s)&&(t=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function MIe(s){const{Document:t}=n0(s);return s instanceof t}function yU(s){return KD(s)?!1:s instanceof n0(s).HTMLElement}function B0t(s){return s instanceof n0(s).SVGElement}function YD(s){return s?KD(s)?s.document:AIe(s)?MIe(s)?s:yU(s)||B0t(s)?s.ownerDocument:document:document:document}const Iw=ove?N.useLayoutEffect:N.useEffect;function IIe(s){const t=N.useRef(s);return Iw(()=>{t.current=s}),N.useCallback(function(){for(var n=arguments.length,r=new Array(n),a=0;a{s.current=setInterval(r,a)},[]),n=N.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[t,n]}function NB(s,t){t===void 0&&(t=[s]);const n=N.useRef(s);return Iw(()=>{n.current!==s&&(n.current=s)},t),n}function vU(s,t){const n=N.useRef();return N.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...t])}function yxe(s){const t=IIe(s),n=N.useRef(null),r=N.useCallback(a=>{a!==n.current&&(t==null||t(a,n.current)),n.current=a},[]);return[n,r]}function e3e(s){const t=N.useRef();return N.useEffect(()=>{t.current=s},[s]),t.current}let j2e={};function bU(s,t){return N.useMemo(()=>{if(t)return t;const n=j2e[s]==null?0:j2e[s]+1;return j2e[s]=n,s+"-"+n},[s,t])}function $0t(s){return function(t){for(var n=arguments.length,r=new Array(n>1?n-1:0),a=1;a{const o=Object.entries(l);for(const[c,d]of o){const u=i[c];u!=null&&(i[c]=u+s*d)}return i},{...t})}}const PL=$0t(1),kB=$0t(-1);function qbs(s){return"clientX"in s&&"clientY"in s}function PIe(s){if(!s)return!1;const{KeyboardEvent:t}=n0(s.target);return t&&s instanceof t}function Vbs(s){if(!s)return!1;const{TouchEvent:t}=n0(s.target);return t&&s instanceof t}function t3e(s){if(Vbs(s)){if(s.touches&&s.touches.length){const{clientX:t,clientY:n}=s.touches[0];return{x:t,y:n}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:t,clientY:n}=s.changedTouches[0];return{x:t,y:n}}}return qbs(s)?{x:s.clientX,y:s.clientY}:null}const E4=Object.freeze({Translate:{toString(s){if(!s)return;const{x:t,y:n}=s;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:t,scaleY:n}=s;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(s){if(s)return[E4.Translate.toString(s),E4.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:t,duration:n,easing:r}=s;return t+" "+n+"ms "+r}}}),NHe="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function Hbs(s){return s.matches(NHe)?s:s.querySelector(NHe)}const Gbs={display:"none"};function Wbs(s){let{id:t,value:n}=s;return Ct.createElement("div",{id:t,style:Gbs},n)}function Kbs(s){let{id:t,announcement:n,ariaLiveType:r="assertive"}=s;const a={position:"fixed",top:0,left:0,width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0 0 0 0)",clipPath:"inset(100%)",whiteSpace:"nowrap"};return Ct.createElement("div",{id:t,style:a,role:"status","aria-live":r,"aria-atomic":!0},n)}function Ybs(){const[s,t]=N.useState("");return{announce:N.useCallback(r=>{r!=null&&t(r)},[]),announcement:s}}const U0t=N.createContext(null);function Zbs(s){const t=N.useContext(U0t);N.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(s)},[s,t])}function Qbs(){const[s]=N.useState(()=>new Set),t=N.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[N.useCallback(r=>{let{type:a,event:i}=r;s.forEach(l=>{var o;return(o=l[a])==null?void 0:o.call(l,i)})},[s]),t]}const Xbs={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. `},Jbs={onDragStart(s){let{active:t}=s;return"Picked up draggable item "+t.id+"."},onDragOver(s){let{active:t,over:n}=s;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(s){let{active:t,over:n}=s;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(s){let{active:t}=s;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function e_s(s){let{announcements:t=Jbs,container:n,hiddenTextDescribedById:r,screenReaderInstructions:a=Xbs}=s;const{announce:i,announcement:l}=Ybs(),o=bU("DndLiveRegion"),[c,d]=N.useState(!1);if(N.useEffect(()=>{d(!0)},[]),Zbs(N.useMemo(()=>({onDragStart(h){let{active:p}=h;i(t.onDragStart({active:p}))},onDragMove(h){let{active:p,over:f}=h;t.onDragMove&&i(t.onDragMove({active:p,over:f}))},onDragOver(h){let{active:p,over:f}=h;i(t.onDragOver({active:p,over:f}))},onDragEnd(h){let{active:p,over:f}=h;i(t.onDragEnd({active:p,over:f}))},onDragCancel(h){let{active:p,over:f}=h;i(t.onDragCancel({active:p,over:f}))}}),[i,t])),!c)return null;const u=Ct.createElement(Ct.Fragment,null,Ct.createElement(Wbs,{id:r,value:a.draggable}),Ct.createElement(Kbs,{id:o,announcement:l}));return n?qx.createPortal(u,n):u}var Am;(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"})(Am||(Am={}));function vxe(){}function A8(s,t){return N.useMemo(()=>({sensor:s,options:t??{}}),[s,t])}function lve(){for(var s=arguments.length,t=new Array(s),n=0;n[...t].filter(r=>r!=null),[...t])}const Cb=Object.freeze({x:0,y:0});function q0t(s,t){return Math.sqrt(Math.pow(s.x-t.x,2)+Math.pow(s.y-t.y,2))}function V0t(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return n-r}function t_s(s,t){let{data:{value:n}}=s,{data:{value:r}}=t;return r-n}function kHe(s){let{left:t,top:n,height:r,width:a}=s;return[{x:t,y:n},{x:t+a,y:n},{x:t,y:n+r},{x:t+a,y:n+r}]}function H0t(s,t){if(!s||s.length===0)return null;const[n]=s;return n[t]}function SHe(s,t,n){return t===void 0&&(t=s.left),n===void 0&&(n=s.top),{x:t+s.width*.5,y:n+s.height*.5}}const cve=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=SHe(t,t.left,t.top),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=q0t(SHe(c),a);i.push({id:o,data:{droppableContainer:l,value:d}})}}return i.sort(V0t)},s_s=s=>{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=kHe(t),i=[];for(const l of r){const{id:o}=l,c=n.get(o);if(c){const d=kHe(c),u=a.reduce((p,f,y)=>p+q0t(d[y],f),0),h=Number((u/4).toFixed(4));i.push({id:o,data:{droppableContainer:l,value:h}})}}return i.sort(V0t)};function n_s(s,t){const n=Math.max(t.top,s.top),r=Math.max(t.left,s.left),a=Math.min(t.left+t.width,s.left+s.width),i=Math.min(t.top+t.height,s.top+s.height),l=a-r,o=i-n;if(r{let{collisionRect:t,droppableRects:n,droppableContainers:r}=s;const a=[];for(const i of r){const{id:l}=i,o=n.get(l);if(o){const c=n_s(o,t);c>0&&a.push({id:l,data:{droppableContainer:i,value:c}})}}return a.sort(t_s)};function a_s(s,t,n){return{...s,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function G0t(s,t){return s&&t?{x:s.left-t.left,y:s.top-t.top}:Cb}function i_s(s){return function(n){for(var r=arguments.length,a=new Array(r>1?r-1:0),i=1;i({...l,top:l.top+s*o.y,bottom:l.bottom+s*o.y,left:l.left+s*o.x,right:l.right+s*o.x}),{...n})}}const o_s=i_s(1);function l_s(s){if(s.startsWith("matrix3d(")){const t=s.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(s.startsWith("matrix(")){const t=s.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function c_s(s,t,n){const r=l_s(t);if(!r)return s;const{scaleX:a,scaleY:i,x:l,y:o}=r,c=s.left-l-(1-a)*parseFloat(n),d=s.top-o-(1-i)*parseFloat(n.slice(n.indexOf(" ")+1)),u=a?s.width/a:s.width,h=i?s.height/i:s.height;return{width:u,height:h,top:d,right:c+u,bottom:d+h,left:c}}const d_s={ignoreTransform:!1};function ZD(s,t){t===void 0&&(t=d_s);let n=s.getBoundingClientRect();if(t.ignoreTransform){const{transform:d,transformOrigin:u}=n0(s).getComputedStyle(s);d&&(n=c_s(n,d,u))}const{top:r,left:a,width:i,height:l,bottom:o,right:c}=n;return{top:r,left:a,width:i,height:l,bottom:o,right:c}}function CHe(s){return ZD(s,{ignoreTransform:!0})}function u_s(s){const t=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function h_s(s,t){return t===void 0&&(t=n0(s).getComputedStyle(s)),t.position==="fixed"}function m_s(s,t){t===void 0&&(t=n0(s).getComputedStyle(s));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(a=>{const i=t[a];return typeof i=="string"?n.test(i):!1})}function dve(s,t){const n=[];function r(a){if(t!=null&&n.length>=t||!a)return n;if(MIe(a)&&a.scrollingElement!=null&&!n.includes(a.scrollingElement))return n.push(a.scrollingElement),n;if(!yU(a)||B0t(a)||n.includes(a))return n;const i=n0(s).getComputedStyle(a);return a!==s&&m_s(a,i)&&n.push(a),h_s(a,i)?n:r(a.parentNode)}return s?r(s):n}function W0t(s){const[t]=dve(s,1);return t??null}function N2e(s){return!ove||!s?null:KD(s)?s:AIe(s)?MIe(s)||s===YD(s).scrollingElement?window:yU(s)?s:null:null}function K0t(s){return KD(s)?s.scrollX:s.scrollLeft}function Y0t(s){return KD(s)?s.scrollY:s.scrollTop}function s3e(s){return{x:K0t(s),y:Y0t(s)}}var yp;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(yp||(yp={}));function Z0t(s){return!ove||!s?!1:s===document.scrollingElement}function Q0t(s){const t={x:0,y:0},n=Z0t(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},r={x:s.scrollWidth-n.width,y:s.scrollHeight-n.height},a=s.scrollTop<=t.y,i=s.scrollLeft<=t.x,l=s.scrollTop>=r.y,o=s.scrollLeft>=r.x;return{isTop:a,isLeft:i,isBottom:l,isRight:o,maxScroll:r,minScroll:t}}const p_s={x:.2,y:.2};function f_s(s,t,n,r,a){let{top:i,left:l,right:o,bottom:c}=n;r===void 0&&(r=10),a===void 0&&(a=p_s);const{isTop:d,isBottom:u,isLeft:h,isRight:p}=Q0t(s),f={x:0,y:0},y={x:0,y:0},_={height:t.height*a.y,width:t.width*a.x};return!d&&i<=t.top+_.height?(f.y=yp.Backward,y.y=r*Math.abs((t.top+_.height-i)/_.height)):!u&&c>=t.bottom-_.height&&(f.y=yp.Forward,y.y=r*Math.abs((t.bottom-_.height-c)/_.height)),!p&&o>=t.right-_.width?(f.x=yp.Forward,y.x=r*Math.abs((t.right-_.width-o)/_.width)):!h&&l<=t.left+_.width&&(f.x=yp.Backward,y.x=r*Math.abs((t.left+_.width-l)/_.width)),{direction:f,speed:y}}function x_s(s){if(s===document.scrollingElement){const{innerWidth:i,innerHeight:l}=window;return{top:0,left:0,right:i,bottom:l,width:i,height:l}}const{top:t,left:n,right:r,bottom:a}=s.getBoundingClientRect();return{top:t,left:n,right:r,bottom:a,width:s.clientWidth,height:s.clientHeight}}function X0t(s){return s.reduce((t,n)=>PL(t,s3e(n)),Cb)}function g_s(s){return s.reduce((t,n)=>t+K0t(n),0)}function y_s(s){return s.reduce((t,n)=>t+Y0t(n),0)}function v_s(s,t){if(t===void 0&&(t=ZD),!s)return;const{top:n,left:r,bottom:a,right:i}=t(s);W0t(s)&&(a<=0||i<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const b_s=[["x",["left","right"],g_s],["y",["top","bottom"],y_s]];class LIe{constructor(t,n){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const r=dve(n),a=X0t(r);this.rect={...t},this.width=t.width,this.height=t.height;for(const[i,l,o]of b_s)for(const c of l)Object.defineProperty(this,c,{get:()=>{const d=o(r),u=a[i]-d;return this.rect[c]+u},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class lz{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=t}add(t,n,r){var a;(a=this.target)==null||a.addEventListener(t,n,r),this.listeners.push([t,n,r])}}function __s(s){const{EventTarget:t}=n0(s);return s instanceof t?s:YD(s)}function k2e(s,t){const n=Math.abs(s.x),r=Math.abs(s.y);return typeof t=="number"?Math.sqrt(n**2+r**2)>t:"x"in t&&"y"in t?n>t.x&&r>t.y:"x"in t?n>t.x:"y"in t?r>t.y:!1}var yv;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(yv||(yv={}));function THe(s){s.preventDefault()}function w_s(s){s.stopPropagation()}var Sl;(function(s){s.Space="Space",s.Down="ArrowDown",s.Right="ArrowRight",s.Left="ArrowLeft",s.Up="ArrowUp",s.Esc="Escape",s.Enter="Enter",s.Tab="Tab"})(Sl||(Sl={}));const J0t={start:[Sl.Space,Sl.Enter],cancel:[Sl.Esc],end:[Sl.Space,Sl.Enter,Sl.Tab]},j_s=(s,t)=>{let{currentCoordinates:n}=t;switch(s.code){case Sl.Right:return{...n,x:n.x+25};case Sl.Left:return{...n,x:n.x-25};case Sl.Down:return{...n,y:n.y+25};case Sl.Up:return{...n,y:n.y-25}}};class uve{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new lz(YD(n)),this.windowListeners=new lz(n0(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(yv.Resize,this.handleCancel),this.windowListeners.add(yv.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(yv.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,r=t.node.current;r&&v_s(r),n(Cb)}handleKeyDown(t){if(PIe(t)){const{active:n,context:r,options:a}=this.props,{keyboardCodes:i=J0t,coordinateGetter:l=j_s,scrollBehavior:o="smooth"}=a,{code:c}=t;if(i.end.includes(c)){this.handleEnd(t);return}if(i.cancel.includes(c)){this.handleCancel(t);return}const{collisionRect:d}=r.current,u=d?{x:d.left,y:d.top}:Cb;this.referenceCoordinates||(this.referenceCoordinates=u);const h=l(t,{active:n,context:r.current,currentCoordinates:u});if(h){const p=kB(h,u),f={x:0,y:0},{scrollableAncestors:y}=r.current;for(const _ of y){const v=t.code,{isTop:j,isRight:w,isLeft:S,isBottom:A,maxScroll:E,minScroll:O}=Q0t(_),D=x_s(_),I={x:Math.min(v===Sl.Right?D.right-D.width/2:D.right,Math.max(v===Sl.Right?D.left:D.left+D.width/2,h.x)),y:Math.min(v===Sl.Down?D.bottom-D.height/2:D.bottom,Math.max(v===Sl.Down?D.top:D.top+D.height/2,h.y))},F=v===Sl.Right&&!w||v===Sl.Left&&!S,z=v===Sl.Down&&!A||v===Sl.Up&&!j;if(F&&I.x!==h.x){const H=_.scrollLeft+p.x,Z=v===Sl.Right&&H<=E.x||v===Sl.Left&&H>=O.x;if(Z&&!p.y){_.scrollTo({left:H,behavior:o});return}Z?f.x=_.scrollLeft-H:f.x=v===Sl.Right?_.scrollLeft-E.x:_.scrollLeft-O.x,f.x&&_.scrollBy({left:-f.x,behavior:o});break}else if(z&&I.y!==h.y){const H=_.scrollTop+p.y,Z=v===Sl.Down&&H<=E.y||v===Sl.Up&&H>=O.y;if(Z&&!p.x){_.scrollTo({top:H,behavior:o});return}Z?f.y=_.scrollTop-H:f.y=v===Sl.Down?_.scrollTop-E.y:_.scrollTop-O.y,f.y&&_.scrollBy({top:-f.y,behavior:o});break}}this.handleMove(t,PL(kB(h,this.referenceCoordinates),f))}}}handleMove(t,n){const{onMove:r}=this.props;t.preventDefault(),r(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}uve.activators=[{eventName:"onKeyDown",handler:(s,t,n)=>{let{keyboardCodes:r=J0t,onActivation:a}=t,{active:i}=n;const{code:l}=s.nativeEvent;if(r.start.includes(l)){const o=i.activatorNode.current;return o&&s.target!==o?!1:(s.preventDefault(),a==null||a({event:s.nativeEvent}),!0)}return!1}}];function EHe(s){return!!(s&&"distance"in s)}function AHe(s){return!!(s&&"delay"in s)}class DIe{constructor(t,n,r){var a;r===void 0&&(r=__s(t.event.target)),this.props=void 0,this.events=void 0,this.autoScrollEnabled=!0,this.document=void 0,this.activated=!1,this.initialCoordinates=void 0,this.timeoutId=null,this.listeners=void 0,this.documentListeners=void 0,this.windowListeners=void 0,this.props=t,this.events=n;const{event:i}=t,{target:l}=i;this.props=t,this.events=n,this.document=YD(l),this.documentListeners=new lz(this.document),this.listeners=new lz(r),this.windowListeners=new lz(n0(l)),this.initialCoordinates=(a=t3e(i))!=null?a:Cb,this.handleStart=this.handleStart.bind(this),this.handleMove=this.handleMove.bind(this),this.handleEnd=this.handleEnd.bind(this),this.handleCancel=this.handleCancel.bind(this),this.handleKeydown=this.handleKeydown.bind(this),this.removeTextSelection=this.removeTextSelection.bind(this),this.attach()}attach(){const{events:t,props:{options:{activationConstraint:n,bypassActivationConstraint:r}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(yv.Resize,this.handleCancel),this.windowListeners.add(yv.DragStart,THe),this.windowListeners.add(yv.VisibilityChange,this.handleCancel),this.windowListeners.add(yv.ContextMenu,THe),this.documentListeners.add(yv.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(AHe(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(EHe(n)){this.handlePending(n);return}}this.handleStart()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll(),setTimeout(this.documentListeners.removeAll,50),this.timeoutId!==null&&(clearTimeout(this.timeoutId),this.timeoutId=null)}handlePending(t,n){const{active:r,onPending:a}=this.props;a(r,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(yv.Click,w_s,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(yv.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:r,initialCoordinates:a,props:i}=this,{onMove:l,options:{activationConstraint:o}}=i;if(!a)return;const c=(n=t3e(t))!=null?n:Cb,d=kB(a,c);if(!r&&o){if(EHe(o)){if(o.tolerance!=null&&k2e(d,o.tolerance))return this.handleCancel();if(k2e(d,o.distance))return this.handleStart()}if(AHe(o)&&k2e(d,o.tolerance))return this.handleCancel();this.handlePending(o,d);return}t.cancelable&&t.preventDefault(),l(c)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Sl.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const N_s={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class QD extends DIe{constructor(t){const{event:n}=t,r=YD(n.target);super(t,N_s,r)}}QD.activators=[{eventName:"onPointerDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return!n.isPrimary||n.button!==0?!1:(r==null||r({event:n}),!0)}}];const k_s={move:{name:"mousemove"},end:{name:"mouseup"}};var n3e;(function(s){s[s.RightClick=2]="RightClick"})(n3e||(n3e={}));class S_s extends DIe{constructor(t){super(t,k_s,YD(t.event.target))}}S_s.activators=[{eventName:"onMouseDown",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;return n.button===n3e.RightClick?!1:(r==null||r({event:n}),!0)}}];const S2e={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class C_s extends DIe{constructor(t){super(t,S2e)}static setup(){return window.addEventListener(S2e.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(S2e.move.name,t)};function t(){}}}C_s.activators=[{eventName:"onTouchStart",handler:(s,t)=>{let{nativeEvent:n}=s,{onActivation:r}=t;const{touches:a}=n;return a.length>1?!1:(r==null||r({event:n}),!0)}}];var cz;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(cz||(cz={}));var bxe;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(bxe||(bxe={}));function T_s(s){let{acceleration:t,activator:n=cz.Pointer,canScroll:r,draggingRect:a,enabled:i,interval:l=5,order:o=bxe.TreeOrder,pointerCoordinates:c,scrollableAncestors:d,scrollableAncestorRects:u,delta:h,threshold:p}=s;const f=A_s({delta:h,disabled:!i}),[y,_]=Ubs(),v=N.useRef({x:0,y:0}),j=N.useRef({x:0,y:0}),w=N.useMemo(()=>{switch(n){case cz.Pointer:return c?{top:c.y,bottom:c.y,left:c.x,right:c.x}:null;case cz.DraggableRect:return a}},[n,a,c]),S=N.useRef(null),A=N.useCallback(()=>{const O=S.current;if(!O)return;const D=v.current.x*j.current.x,I=v.current.y*j.current.y;O.scrollBy(D,I)},[]),E=N.useMemo(()=>o===bxe.TreeOrder?[...d].reverse():d,[o,d]);N.useEffect(()=>{if(!i||!d.length||!w){_();return}for(const O of E){if((r==null?void 0:r(O))===!1)continue;const D=d.indexOf(O),I=u[D];if(!I)continue;const{direction:F,speed:z}=f_s(O,I,w,t,p);for(const H of["x","y"])f[H][F[H]]||(z[H]=0,F[H]=0);if(z.x>0||z.y>0){_(),S.current=O,y(A,l),v.current=z,j.current=F;return}}v.current={x:0,y:0},j.current={x:0,y:0},_()},[t,A,r,_,i,l,JSON.stringify(w),JSON.stringify(f),y,d,E,u,JSON.stringify(p)])}const E_s={x:{[yp.Backward]:!1,[yp.Forward]:!1},y:{[yp.Backward]:!1,[yp.Forward]:!1}};function A_s(s){let{delta:t,disabled:n}=s;const r=e3e(t);return vU(a=>{if(n||!r||!a)return E_s;const i={x:Math.sign(t.x-r.x),y:Math.sign(t.y-r.y)};return{x:{[yp.Backward]:a.x[yp.Backward]||i.x===-1,[yp.Forward]:a.x[yp.Forward]||i.x===1},y:{[yp.Backward]:a.y[yp.Backward]||i.y===-1,[yp.Forward]:a.y[yp.Forward]||i.y===1}}},[n,t,r])}function M_s(s,t){const n=t!=null?s.get(t):void 0,r=n?n.node.current:null;return vU(a=>{var i;return t==null?null:(i=r??a)!=null?i:null},[r,t])}function I_s(s,t){return N.useMemo(()=>s.reduce((n,r)=>{const{sensor:a}=r,i=a.activators.map(l=>({eventName:l.eventName,handler:t(l.handler,r)}));return[...n,...i]},[]),[s,t])}var SB;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(SB||(SB={}));var r3e;(function(s){s.Optimized="optimized"})(r3e||(r3e={}));const MHe=new Map;function P_s(s,t){let{dragging:n,dependencies:r,config:a}=t;const[i,l]=N.useState(null),{frequency:o,measure:c,strategy:d}=a,u=N.useRef(s),h=v(),p=NB(h),f=N.useCallback(function(j){j===void 0&&(j=[]),!p.current&&l(w=>w===null?j:w.concat(j.filter(S=>!w.includes(S))))},[p]),y=N.useRef(null),_=vU(j=>{if(h&&!n)return MHe;if(!j||j===MHe||u.current!==s||i!=null){const w=new Map;for(let S of s){if(!S)continue;if(i&&i.length>0&&!i.includes(S.id)&&S.rect.current){w.set(S.id,S.rect.current);continue}const A=S.node.current,E=A?new LIe(c(A),A):null;S.rect.current=E,E&&w.set(S.id,E)}return w}return j},[s,i,n,h,c]);return N.useEffect(()=>{u.current=s},[s]),N.useEffect(()=>{h||f()},[n,h]),N.useEffect(()=>{i&&i.length>0&&l(null)},[JSON.stringify(i)]),N.useEffect(()=>{h||typeof o!="number"||y.current!==null||(y.current=setTimeout(()=>{f(),y.current=null},o))},[o,h,f,...r]),{droppableRects:_,measureDroppableContainers:f,measuringScheduled:i!=null};function v(){switch(d){case SB.Always:return!1;case SB.BeforeDragging:return n;default:return!n}}}function eyt(s,t){return vU(n=>s?n||(typeof t=="function"?t(s):s):null,[t,s])}function L_s(s,t){return eyt(s,t)}function D_s(s){let{callback:t,disabled:n}=s;const r=IIe(t),a=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:i}=window;return new i(r)},[r,n]);return N.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function hve(s){let{callback:t,disabled:n}=s;const r=IIe(t),a=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:i}=window;return new i(r)},[n]);return N.useEffect(()=>()=>a==null?void 0:a.disconnect(),[a]),a}function R_s(s){return new LIe(ZD(s),s)}function IHe(s,t,n){t===void 0&&(t=R_s);const[r,a]=N.useState(null);function i(){a(c=>{if(!s)return null;if(s.isConnected===!1){var d;return(d=c??n)!=null?d:null}const u=t(s);return JSON.stringify(c)===JSON.stringify(u)?c:u})}const l=D_s({callback(c){if(s)for(const d of c){const{type:u,target:h}=d;if(u==="childList"&&h instanceof HTMLElement&&h.contains(s)){i();break}}}}),o=hve({callback:i});return Iw(()=>{i(),s?(o==null||o.observe(s),l==null||l.observe(document.body,{childList:!0,subtree:!0})):(o==null||o.disconnect(),l==null||l.disconnect())},[s]),r}function O_s(s){const t=eyt(s);return G0t(s,t)}const PHe=[];function F_s(s){const t=N.useRef(s),n=vU(r=>s?r&&r!==PHe&&s&&t.current&&s.parentNode===t.current.parentNode?r:dve(s):PHe,[s]);return N.useEffect(()=>{t.current=s},[s]),n}function z_s(s){const[t,n]=N.useState(null),r=N.useRef(s),a=N.useCallback(i=>{const l=N2e(i.target);l&&n(o=>o?(o.set(l,s3e(l)),new Map(o)):null)},[]);return N.useEffect(()=>{const i=r.current;if(s!==i){l(i);const o=s.map(c=>{const d=N2e(c);return d?(d.addEventListener("scroll",a,{passive:!0}),[d,s3e(d)]):null}).filter(c=>c!=null);n(o.length?new Map(o):null),r.current=s}return()=>{l(s),l(i)};function l(o){o.forEach(c=>{const d=N2e(c);d==null||d.removeEventListener("scroll",a)})}},[a,s]),N.useMemo(()=>s.length?t?Array.from(t.values()).reduce((i,l)=>PL(i,l),Cb):X0t(s):Cb,[s,t])}function LHe(s,t){t===void 0&&(t=[]);const n=N.useRef(null);return N.useEffect(()=>{n.current=null},t),N.useEffect(()=>{const r=s!==Cb;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?kB(s,n.current):Cb}function B_s(s){N.useEffect(()=>{if(!ove)return;const t=s.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of t)n==null||n()}},s.map(t=>{let{sensor:n}=t;return n}))}function $_s(s,t){return N.useMemo(()=>s.reduce((n,r)=>{let{eventName:a,handler:i}=r;return n[a]=l=>{i(l,t)},n},{}),[s,t])}function tyt(s){return N.useMemo(()=>s?u_s(s):null,[s])}const DHe=[];function U_s(s,t){t===void 0&&(t=ZD);const[n]=s,r=tyt(n?n0(n):null),[a,i]=N.useState(DHe);function l(){i(()=>s.length?s.map(c=>Z0t(c)?r:new LIe(t(c),c)):DHe)}const o=hve({callback:l});return Iw(()=>{o==null||o.disconnect(),l(),s.forEach(c=>o==null?void 0:o.observe(c))},[s]),a}function q_s(s){if(!s)return null;if(s.children.length>1)return s;const t=s.children[0];return yU(t)?t:s}function V_s(s){let{measure:t}=s;const[n,r]=N.useState(null),a=N.useCallback(d=>{for(const{target:u}of d)if(yU(u)){r(h=>{const p=t(u);return h?{...h,width:p.width,height:p.height}:p});break}},[t]),i=hve({callback:a}),l=N.useCallback(d=>{const u=q_s(d);i==null||i.disconnect(),u&&(i==null||i.observe(u)),r(u?t(u):null)},[t,i]),[o,c]=yxe(l);return N.useMemo(()=>({nodeRef:o,rect:n,setRef:c}),[n,o,c])}const H_s=[{sensor:QD,options:{}},{sensor:uve,options:{}}],G_s={current:{}},qme={draggable:{measure:CHe},droppable:{measure:CHe,strategy:SB.WhileDragging,frequency:r3e.Optimized},dragOverlay:{measure:ZD}};class dz extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,r;return(n=(r=this.get(t))==null?void 0:r.node.current)!=null?n:void 0}}const W_s={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new dz,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:vxe},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:qme,measureDroppableContainers:vxe,windowRect:null,measuringScheduled:!1},K_s={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:vxe,draggableNodes:new Map,over:null,measureDroppableContainers:vxe},mve=N.createContext(K_s),syt=N.createContext(W_s);function Y_s(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new dz}}}function Z_s(s,t){switch(t.type){case Am.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case Am.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 Am.DragEnd:case Am.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case Am.RegisterDroppable:{const{element:n}=t,{id:r}=n,a=new dz(s.droppable.containers);return a.set(r,n),{...s,droppable:{...s.droppable,containers:a}}}case Am.SetDroppableDisabled:{const{id:n,key:r,disabled:a}=t,i=s.droppable.containers.get(n);if(!i||r!==i.key)return s;const l=new dz(s.droppable.containers);return l.set(n,{...i,disabled:a}),{...s,droppable:{...s.droppable,containers:l}}}case Am.UnregisterDroppable:{const{id:n,key:r}=t,a=s.droppable.containers.get(n);if(!a||r!==a.key)return s;const i=new dz(s.droppable.containers);return i.delete(n),{...s,droppable:{...s.droppable,containers:i}}}default:return s}}function Q_s(s){let{disabled:t}=s;const{active:n,activatorEvent:r,draggableNodes:a}=N.useContext(mve),i=e3e(r),l=e3e(n==null?void 0:n.id);return N.useEffect(()=>{if(!t&&!r&&i&&l!=null){if(!PIe(i)||document.activeElement===i.target)return;const o=a.get(l);if(!o)return;const{activatorNode:c,node:d}=o;if(!c.current&&!d.current)return;requestAnimationFrame(()=>{for(const u of[c.current,d.current]){if(!u)continue;const h=Hbs(u);if(h){h.focus();break}}})}},[r,t,a,l,i]),null}function X_s(s,t){let{transform:n,...r}=t;return s!=null&&s.length?s.reduce((a,i)=>i({transform:a,...r}),n):n}function J_s(s){return N.useMemo(()=>({draggable:{...qme.draggable,...s==null?void 0:s.draggable},droppable:{...qme.droppable,...s==null?void 0:s.droppable},dragOverlay:{...qme.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 ews(s){let{activeNode:t,measure:n,initialRect:r,config:a=!0}=s;const i=N.useRef(!1),{x:l,y:o}=typeof a=="boolean"?{x:a,y:a}:a;Iw(()=>{if(!l&&!o||!t){i.current=!1;return}if(i.current||!r)return;const d=t==null?void 0:t.node.current;if(!d||d.isConnected===!1)return;const u=n(d),h=G0t(u,r);if(l||(h.x=0),o||(h.y=0),i.current=!0,Math.abs(h.x)>0||Math.abs(h.y)>0){const p=W0t(d);p&&p.scrollBy({top:h.y,left:h.x})}},[t,l,o,r,n])}const nyt=N.createContext({...Cb,scaleX:1,scaleY:1});var Yk;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(Yk||(Yk={}));const pve=N.memo(function(t){var n,r,a,i;let{id:l,accessibility:o,autoScroll:c=!0,children:d,sensors:u=H_s,collisionDetection:h=r_s,measuring:p,modifiers:f,...y}=t;const _=N.useReducer(Z_s,void 0,Y_s),[v,j]=_,[w,S]=Qbs(),[A,E]=N.useState(Yk.Uninitialized),O=A===Yk.Initialized,{draggable:{active:D,nodes:I,translate:F},droppable:{containers:z}}=v,H=D!=null?I.get(D):null,Z=N.useRef({initial:null,translated:null}),Y=N.useMemo(()=>{var an;return D!=null?{id:D,data:(an=H==null?void 0:H.data)!=null?an:G_s,rect:Z}:null},[D,H]),W=N.useRef(null),[ee,se]=N.useState(null),[oe,he]=N.useState(null),ce=NB(y,Object.values(y)),me=bU("DndDescribedBy",l),le=N.useMemo(()=>z.getEnabled(),[z]),ve=J_s(p),{droppableRects:ge,measureDroppableContainers:Te,measuringScheduled:Ie}=P_s(le,{dragging:O,dependencies:[F.x,F.y],config:ve.droppable}),Ce=M_s(I,D),Me=N.useMemo(()=>oe?t3e(oe):null,[oe]),Pe=$s(),Re=L_s(Ce,ve.draggable.measure);ews({activeNode:D!=null?I.get(D):null,config:Pe.layoutShiftCompensation,initialRect:Re,measure:ve.draggable.measure});const Ae=IHe(Ce,ve.draggable.measure,Re),Be=IHe(Ce?Ce.parentElement:null),we=N.useRef({activatorEvent:null,active:null,activeNode:Ce,collisionRect:null,collisions:null,droppableRects:ge,draggableNodes:I,draggingNode:null,draggingNodeRect:null,droppableContainers:z,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),Je=z.getNodeFor((n=we.current.over)==null?void 0:n.id),ke=V_s({measure:ve.dragOverlay.measure}),it=(r=ke.nodeRef.current)!=null?r:Ce,je=O?(a=ke.rect)!=null?a:Ae:null,He=!!(ke.nodeRef.current&&ke.rect),$e=O_s(He?null:Ae),Ke=tyt(it?n0(it):null),Ge=F_s(O?Je??Ce:null),rt=U_s(Ge),tt=X_s(f,{transform:{x:F.x-$e.x,y:F.y-$e.y,scaleX:1,scaleY:1},activatorEvent:oe,active:Y,activeNodeRect:Ae,containerNodeRect:Be,draggingNodeRect:je,over:we.current.over,overlayNodeRect:ke.rect,scrollableAncestors:Ge,scrollableAncestorRects:rt,windowRect:Ke}),at=Me?PL(Me,F):null,Ye=z_s(Ge),ut=LHe(Ye),_t=LHe(Ye,[Ae]),bt=PL(tt,ut),$t=je?o_s(je,tt):null,Yt=Y&&$t?h({active:Y,collisionRect:$t,droppableRects:ge,droppableContainers:le,pointerCoordinates:at}):null,Ds=H0t(Yt,"id"),[Ls,xs]=N.useState(null),Lt=He?tt:PL(tt,_t),Jt=a_s(Lt,(i=Ls==null?void 0:Ls.rect)!=null?i:null,Ae),gt=N.useRef(null),zt=N.useCallback((an,tn)=>{let{sensor:er,options:xn}=tn;if(W.current==null)return;const Pn=I.get(W.current);if(!Pn)return;const Qn=an.nativeEvent,sa=new er({active:W.current,activeNode:Pn,event:Qn,options:xn,context:we,onAbort(Es){if(!I.get(Es))return;const{onDragAbort:Ar}=ce.current,Hn={id:Es};Ar==null||Ar(Hn),w({type:"onDragAbort",event:Hn})},onPending(Es,mi,Ar,Hn){if(!I.get(Es))return;const{onDragPending:Un}=ce.current,ir={id:Es,constraint:mi,initialCoordinates:Ar,offset:Hn};Un==null||Un(ir),w({type:"onDragPending",event:ir})},onStart(Es){const mi=W.current;if(mi==null)return;const Ar=I.get(mi);if(!Ar)return;const{onDragStart:Hn}=ce.current,Ts={activatorEvent:Qn,active:{id:mi,data:Ar.data,rect:Z}};qx.unstable_batchedUpdates(()=>{Hn==null||Hn(Ts),E(Yk.Initializing),j({type:Am.DragStart,initialCoordinates:Es,active:mi}),w({type:"onDragStart",event:Ts}),se(gt.current),he(Qn)})},onMove(Es){j({type:Am.DragMove,coordinates:Es})},onEnd:na(Am.DragEnd),onCancel:na(Am.DragCancel)});gt.current=sa;function na(Es){return async function(){const{active:Ar,collisions:Hn,over:Ts,scrollAdjustedTranslate:Un}=we.current;let ir=null;if(Ar&&Un){const{cancelDrop:Tr}=ce.current;ir={activatorEvent:Qn,active:Ar,collisions:Hn,delta:Un,over:Ts},Es===Am.DragEnd&&typeof Tr=="function"&&await Promise.resolve(Tr(ir))&&(Es=Am.DragCancel)}W.current=null,qx.unstable_batchedUpdates(()=>{j({type:Es}),E(Yk.Uninitialized),xs(null),se(null),he(null),gt.current=null;const Tr=Es===Am.DragEnd?"onDragEnd":"onDragCancel";if(ir){const ts=ce.current[Tr];ts==null||ts(ir),w({type:Tr,event:ir})}})}}},[I]),As=N.useCallback((an,tn)=>(er,xn)=>{const Pn=er.nativeEvent,Qn=I.get(xn);if(W.current!==null||!Qn||Pn.dndKit||Pn.defaultPrevented)return;const sa={active:Qn};an(er,tn.options,sa)===!0&&(Pn.dndKit={capturedBy:tn.sensor},W.current=xn,zt(er,tn))},[I,zt]),Xt=I_s(u,As);B_s(u),Iw(()=>{Ae&&A===Yk.Initializing&&E(Yk.Initialized)},[Ae,A]),N.useEffect(()=>{const{onDragMove:an}=ce.current,{active:tn,activatorEvent:er,collisions:xn,over:Pn}=we.current;if(!tn||!er)return;const Qn={active:tn,activatorEvent:er,collisions:xn,delta:{x:bt.x,y:bt.y},over:Pn};qx.unstable_batchedUpdates(()=>{an==null||an(Qn),w({type:"onDragMove",event:Qn})})},[bt.x,bt.y]),N.useEffect(()=>{const{active:an,activatorEvent:tn,collisions:er,droppableContainers:xn,scrollAdjustedTranslate:Pn}=we.current;if(!an||W.current==null||!tn||!Pn)return;const{onDragOver:Qn}=ce.current,sa=xn.get(Ds),na=sa&&sa.rect.current?{id:sa.id,rect:sa.rect.current,data:sa.data,disabled:sa.disabled}:null,Es={active:an,activatorEvent:tn,collisions:er,delta:{x:Pn.x,y:Pn.y},over:na};qx.unstable_batchedUpdates(()=>{xs(na),Qn==null||Qn(Es),w({type:"onDragOver",event:Es})})},[Ds]),Iw(()=>{we.current={activatorEvent:oe,active:Y,activeNode:Ce,collisionRect:$t,collisions:Yt,droppableRects:ge,draggableNodes:I,draggingNode:it,draggingNodeRect:je,droppableContainers:z,over:Ls,scrollableAncestors:Ge,scrollAdjustedTranslate:bt},Z.current={initial:je,translated:$t}},[Y,Ce,Yt,$t,I,it,je,ge,z,Ls,Ge,bt]),T_s({...Pe,delta:F,draggingRect:$t,pointerCoordinates:at,scrollableAncestors:Ge,scrollableAncestorRects:rt});const Qs=N.useMemo(()=>({active:Y,activeNode:Ce,activeNodeRect:Ae,activatorEvent:oe,collisions:Yt,containerNodeRect:Be,dragOverlay:ke,draggableNodes:I,droppableContainers:z,droppableRects:ge,over:Ls,measureDroppableContainers:Te,scrollableAncestors:Ge,scrollableAncestorRects:rt,measuringConfiguration:ve,measuringScheduled:Ie,windowRect:Ke}),[Y,Ce,Ae,oe,Yt,Be,ke,I,z,ge,Ls,Te,Ge,rt,ve,Ie,Ke]),ks=N.useMemo(()=>({activatorEvent:oe,activators:Xt,active:Y,activeNodeRect:Ae,ariaDescribedById:{draggable:me},dispatch:j,draggableNodes:I,over:Ls,measureDroppableContainers:Te}),[oe,Xt,Y,Ae,j,me,I,Ls,Te]);return Ct.createElement(U0t.Provider,{value:S},Ct.createElement(mve.Provider,{value:ks},Ct.createElement(syt.Provider,{value:Qs},Ct.createElement(nyt.Provider,{value:Jt},d)),Ct.createElement(Q_s,{disabled:(o==null?void 0:o.restoreFocus)===!1})),Ct.createElement(e_s,{...o,hiddenTextDescribedById:me}));function $s(){const an=(ee==null?void 0:ee.autoScrollEnabled)===!1,tn=typeof c=="object"?c.enabled===!1:c===!1,er=O&&!an&&!tn;return typeof c=="object"?{...c,enabled:er}:{enabled:er}}}),tws=N.createContext(null),RHe="button",sws="Draggable";function nws(s){let{id:t,data:n,disabled:r=!1,attributes:a}=s;const i=bU(sws),{activators:l,activatorEvent:o,active:c,activeNodeRect:d,ariaDescribedById:u,draggableNodes:h,over:p}=N.useContext(mve),{role:f=RHe,roleDescription:y="draggable",tabIndex:_=0}=a??{},v=(c==null?void 0:c.id)===t,j=N.useContext(v?nyt:tws),[w,S]=yxe(),[A,E]=yxe(),O=$_s(l,t),D=NB(n);Iw(()=>(h.set(t,{id:t,key:i,node:w,activatorNode:A,data:D}),()=>{const F=h.get(t);F&&F.key===i&&h.delete(t)}),[h,t]);const I=N.useMemo(()=>({role:f,tabIndex:_,"aria-disabled":r,"aria-pressed":v&&f===RHe?!0:void 0,"aria-roledescription":y,"aria-describedby":u.draggable}),[r,f,_,v,y,u.draggable]);return{active:c,activatorEvent:o,activeNodeRect:d,attributes:I,isDragging:v,listeners:r?void 0:O,node:w,over:p,setNodeRef:S,setActivatorNodeRef:E,transform:j}}function rws(){return N.useContext(syt)}const aws="Droppable",iws={timeout:25};function ows(s){let{data:t,disabled:n=!1,id:r,resizeObserverConfig:a}=s;const i=bU(aws),{active:l,dispatch:o,over:c,measureDroppableContainers:d}=N.useContext(mve),u=N.useRef({disabled:n}),h=N.useRef(!1),p=N.useRef(null),f=N.useRef(null),{disabled:y,updateMeasurementsFor:_,timeout:v}={...iws,...a},j=NB(_??r),w=N.useCallback(()=>{if(!h.current){h.current=!0;return}f.current!=null&&clearTimeout(f.current),f.current=setTimeout(()=>{d(Array.isArray(j.current)?j.current:[j.current]),f.current=null},v)},[v]),S=hve({callback:w,disabled:y||!l}),A=N.useCallback((I,F)=>{S&&(F&&(S.unobserve(F),h.current=!1),I&&S.observe(I))},[S]),[E,O]=yxe(A),D=NB(t);return N.useEffect(()=>{!S||!E.current||(S.disconnect(),h.current=!1,S.observe(E.current))},[E,S]),N.useEffect(()=>(o({type:Am.RegisterDroppable,element:{id:r,key:i,disabled:n,node:E,rect:p,data:D}}),()=>o({type:Am.UnregisterDroppable,key:i,id:r})),[r]),N.useEffect(()=>{n!==u.current.disabled&&(o({type:Am.SetDroppableDisabled,id:r,key:i,disabled:n}),u.current.disabled=n)},[r,i,n,o]),{active:l,rect:p,isOver:(c==null?void 0:c.id)===r,node:E,over:c,setNodeRef:O}}function fve(s,t,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(t,1)[0]),r}function lws(s,t){return s.reduce((n,r,a)=>{const i=t.get(r);return i&&(n[a]=i),n},Array(s.length))}function FH(s){return s!==null&&s>=0}function cws(s,t){if(s===t)return!0;if(s.length!==t.length)return!1;for(let n=0;n{var t;let{rects:n,activeNodeRect:r,activeIndex:a,overIndex:i,index:l}=s;const o=(t=n[a])!=null?t:r;if(!o)return null;const c=uws(n,l,a);if(l===a){const d=n[i];return d?{x:aa&&l<=i?{x:-o.width-c,y:0,...zH}:l=i?{x:o.width+c,y:0,...zH}:{x:0,y:0,...zH}};function uws(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return!r||!a&&!i?0:n{let{rects:t,activeIndex:n,overIndex:r,index:a}=s;const i=fve(t,r,n),l=t[a],o=i[a];return!o||!l?null:{x:o.left-l.left,y:o.top-l.top,scaleX:o.width/l.width,scaleY:o.height/l.height}},BH={scaleX:1,scaleY:1},hws=s=>{var t;let{activeIndex:n,activeNodeRect:r,index:a,rects:i,overIndex:l}=s;const o=(t=i[n])!=null?t:r;if(!o)return null;if(a===n){const d=i[l];return d?{x:0,y:nn&&a<=l?{x:0,y:-o.height-c,...BH}:a=l?{x:0,y:o.height+c,...BH}:{x:0,y:0,...BH}};function mws(s,t,n){const r=s[t],a=s[t-1],i=s[t+1];return r?nr.map(O=>typeof O=="object"&&"id"in O?O.id:O),[r]),y=l!=null,_=l?f.indexOf(l.id):-1,v=d?f.indexOf(d.id):-1,j=N.useRef(f),w=!cws(f,j.current),S=v!==-1&&_===-1||w,A=dws(i);Iw(()=>{w&&y&&u(f)},[w,f,y,u]),N.useEffect(()=>{j.current=f},[f]);const E=N.useMemo(()=>({activeIndex:_,containerId:h,disabled:A,disableTransforms:S,items:f,overIndex:v,useDragOverlay:p,sortedRects:lws(f,c),strategy:a}),[_,h,A.draggable,A.droppable,S,f,v,c,p,a]);return Ct.createElement(ayt.Provider,{value:E},t)}const pws=s=>{let{id:t,items:n,activeIndex:r,overIndex:a}=s;return fve(n,r,a).indexOf(t)},fws=s=>{let{containerId:t,isSorting:n,wasDragging:r,index:a,items:i,newIndex:l,previousItems:o,previousContainerId:c,transition:d}=s;return!d||!r||o!==i&&a===l?!1:n?!0:l!==a&&t===c},xws={duration:200,easing:"ease"},iyt="transform",gws=E4.Transition.toString({property:iyt,duration:0,easing:"linear"}),yws={roleDescription:"sortable"};function vws(s){let{disabled:t,index:n,node:r,rect:a}=s;const[i,l]=N.useState(null),o=N.useRef(n);return Iw(()=>{if(!t&&n!==o.current&&r.current){const c=a.current;if(c){const d=ZD(r.current,{ignoreTransform:!0}),u={x:c.left-d.left,y:c.top-d.top,scaleX:c.width/d.width,scaleY:c.height/d.height};(u.x||u.y)&&l(u)}}n!==o.current&&(o.current=n)},[t,n,r,a]),N.useEffect(()=>{i&&l(null)},[i]),i}function gve(s){let{animateLayoutChanges:t=fws,attributes:n,disabled:r,data:a,getNewIndex:i=pws,id:l,strategy:o,resizeObserverConfig:c,transition:d=xws}=s;const{items:u,containerId:h,activeIndex:p,disabled:f,disableTransforms:y,sortedRects:_,overIndex:v,useDragOverlay:j,strategy:w}=N.useContext(ayt),S=bws(r,f),A=u.indexOf(l),E=N.useMemo(()=>({sortable:{containerId:h,index:A,items:u},...a}),[h,a,A,u]),O=N.useMemo(()=>u.slice(u.indexOf(l)),[u,l]),{rect:D,node:I,isOver:F,setNodeRef:z}=ows({id:l,data:E,disabled:S.droppable,resizeObserverConfig:{updateMeasurementsFor:O,...c}}),{active:H,activatorEvent:Z,activeNodeRect:Y,attributes:W,setNodeRef:ee,listeners:se,isDragging:oe,over:he,setActivatorNodeRef:ce,transform:me}=nws({id:l,data:E,attributes:{...yws,...n},disabled:S.draggable}),le=$bs(z,ee),ve=!!H,ge=ve&&!y&&FH(p)&&FH(v),Te=!j&&oe,Ie=Te&&ge?me:null,Me=ge?Ie??(o??w)({rects:_,activeNodeRect:Y,activeIndex:p,overIndex:v,index:A}):null,Pe=FH(p)&&FH(v)?i({id:l,items:u,activeIndex:p,overIndex:v}):A,Re=H==null?void 0:H.id,Ae=N.useRef({activeId:Re,items:u,newIndex:Pe,containerId:h}),Be=u!==Ae.current.items,we=t({active:H,containerId:h,isDragging:oe,isSorting:ve,id:l,index:A,items:u,newIndex:Ae.current.newIndex,previousItems:Ae.current.items,previousContainerId:Ae.current.containerId,transition:d,wasDragging:Ae.current.activeId!=null}),Je=vws({disabled:!we,index:A,node:I,rect:D});return N.useEffect(()=>{ve&&Ae.current.newIndex!==Pe&&(Ae.current.newIndex=Pe),h!==Ae.current.containerId&&(Ae.current.containerId=h),u!==Ae.current.items&&(Ae.current.items=u)},[ve,Pe,h,u]),N.useEffect(()=>{if(Re===Ae.current.activeId)return;if(Re!=null&&Ae.current.activeId==null){Ae.current.activeId=Re;return}const it=setTimeout(()=>{Ae.current.activeId=Re},50);return()=>clearTimeout(it)},[Re]),{active:H,activeIndex:p,attributes:W,data:E,rect:D,index:A,newIndex:Pe,items:u,isOver:F,isSorting:ve,isDragging:oe,listeners:se,node:I,overIndex:v,over:he,setNodeRef:le,setActivatorNodeRef:ce,setDroppableNodeRef:z,setDraggableNodeRef:ee,transform:Je??Me,transition:ke()};function ke(){if(Je||Be&&Ae.current.newIndex===A)return gws;if(!(Te&&!PIe(Z)||!d)&&(ve||we))return E4.Transition.toString({...d,property:iyt})}}function bws(s,t){var n,r;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(n=s==null?void 0:s.draggable)!=null?n:t.draggable,droppable:(r=s==null?void 0:s.droppable)!=null?r:t.droppable}}function _xe(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 _ws=[Sl.Down,Sl.Right,Sl.Up,Sl.Left],oyt=(s,t)=>{let{context:{active:n,collisionRect:r,droppableRects:a,droppableContainers:i,over:l,scrollableAncestors:o}}=t;if(_ws.includes(s.code)){if(s.preventDefault(),!n||!r)return;const c=[];i.getEnabled().forEach(h=>{if(!h||h!=null&&h.disabled)return;const p=a.get(h.id);if(p)switch(s.code){case Sl.Down:r.topp.top&&c.push(h);break;case Sl.Left:r.left>p.left&&c.push(h);break;case Sl.Right:r.left1&&(u=d[1].id),u!=null){const h=i.get(n.id),p=i.get(u),f=p?a.get(p.id):null,y=p==null?void 0:p.node.current;if(y&&f&&h&&p){const v=dve(y).some((O,D)=>o[D]!==O),j=lyt(h,p),w=wws(h,p),S=v||!j?{x:0,y:0}:{x:w?r.width-f.width:0,y:w?r.height-f.height:0},A={x:f.left,y:f.top};return S.x&&S.y?A:kB(A,S)}}}};function lyt(s,t){return!_xe(s)||!_xe(t)?!1:s.data.current.sortable.containerId===t.data.current.sortable.containerId}function wws(s,t){return!_xe(s)||!_xe(t)||!lyt(s,t)?!1:s.data.current.sortable.indext(s),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"destructive",size:"icon",className:"h-7 w-7",onClick:()=>n(s),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}),s.post_date&&e.jsx("div",{className:"absolute bottom-2 left-2",children:e.jsxs(Ue,{className:"bg-primary/90 text-primary-foreground text-[10px] gap-1 backdrop-blur-sm px-1.5 py-0.5",children:[e.jsx(yr,{className:"h-2.5 w-2.5"}),Ss(new Date(s.post_date+"T00:00:00"),"MMM d")]})})]}),e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-3",children:s.caption}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:Mt("w-full h-7 text-[11px] gap-1 justify-start font-normal",!s.post_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"h-3 w-3"}),s.post_date?Ss(new Date(s.post_date+"T00:00:00"),"MMM d, yyyy"):"Set post date"]})}),e.jsxs(el,{className:"w-auto p-0",align:"start",children:[e.jsx(Gg,{mode:"single",selected:s.post_date?new Date(s.post_date+"T00:00:00"):void 0,onSelect:h=>r(s.id,h?Ss(h,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"}),s.post_date&&e.jsx("div",{className:"p-2 border-t",children:e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>r(s.id,null),children:"Clear date"})})]})]})]})]})})}const Nws=()=>{const s=Kt(),[t,n]=N.useState("all"),[r,a]=N.useState(!1),[i,l]=N.useState(Ss(new Date,"yyyy-MM")),[o,c]=N.useState([]),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,y]=N.useState(null),[_,v]=N.useState(""),[j,w]=N.useState(null),[S,A]=N.useState(!1),[E,O]=N.useState(!1),[D,I]=N.useState(Ss(new Date,"yyyy-MM")),[F,z]=N.useState(null),[H,Z]=N.useState(""),[Y,W]=N.useState(""),[ee,se]=N.useState(""),[oe,he]=N.useState(!1),ce=lve(A8(QD,{activationConstraint:{distance:5}}),A8(uve,{coordinateGetter:oyt})),{data:me=[],isLoading:le}=dt({queryKey:["admin-social-swag-2"],queryFn:async()=>{const{data:at,error:Ye}=await q.from("social_swag_2").select("*").order("month",{ascending:!1}).order("sort_order");if(Ye)throw Ye;return at}}),{data:ve=[]}=dt({queryKey:["admin-social-swag-2-months"],queryFn:async()=>{const{data:at,error:Ye}=await q.from("social_swag_2_months").select("*").order("month",{ascending:!1});if(Ye)throw Ye;return at}}),{data:ge=[]}=dt({queryKey:["admin-social-swag-2-reels"],queryFn:async()=>{const{data:at,error:Ye}=await q.from("social_swag_2_reels").select("*").order("month",{ascending:!1});if(Ye)throw Ye;return at}}),Te=[...new Set(me.map(at=>at.month))].sort((at,Ye)=>Ye.localeCompare(at)),Ie=t==="all"?me:me.filter(at=>at.month===t),Ce=at=>{const Ye=qAe(at,"yyyy-MM",new Date);return Ss(Ye,"MMMM yyyy")},Me=at=>{y(at),v(at.caption),w(at.post_date)},Pe=async()=>{if(f){A(!0);try{const{error:at}=await q.from("social_swag_2").update({caption:_,post_date:j}).eq("id",f.id);if(at)throw at;ae.success("Image updated"),y(null),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})}catch{ae.error("Failed to update image")}finally{A(!1)}}},Re=async at=>{const{active:Ye,over:ut}=at;if(!ut||Ye.id===ut.id)return;const _t=Ie,bt=_t.findIndex(Ds=>Ds.id===Ye.id),$t=_t.findIndex(Ds=>Ds.id===ut.id);if(bt===-1||$t===-1)return;const Yt=fve(_t,bt,$t);s.setQueryData(["admin-social-swag-2"],Ds=>{if(!Ds)return Ds;const Ls={};return Yt.forEach((xs,Lt)=>{Ls[xs.id]=Lt}),Ds.map(xs=>Ls[xs.id]!==void 0?{...xs,sort_order:Ls[xs.id]}:xs).sort((xs,Lt)=>xs.month!==Lt.month?Lt.month.localeCompare(xs.month):xs.sort_order-Lt.sort_order)});try{await Promise.all(Yt.map((Ds,Ls)=>q.from("social_swag_2").update({sort_order:Ls}).eq("id",Ds.id)))}catch{ae.error("Failed to save order"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})}},Ae=at=>{const ut=Array.from(at.target.files||[]).sort((_t,bt)=>_t.name.localeCompare(bt.name,void 0,{numeric:!0,sensitivity:"base"})).slice(0,16-o.length).map(_t=>({file:_t,preview:URL.createObjectURL(_t),caption:""}));c(_t=>[..._t,...ut].slice(0,16))},Be=at=>{c(Ye=>{const ut=[...Ye];return URL.revokeObjectURL(ut[at].preview),ut.splice(at,1),ut})},we=(at,Ye)=>{c(ut=>{const _t=[...ut];return _t[at]={..._t[at],caption:Ye},_t})},Je=async()=>{var Ye;if(o.length===0){ae.error("Please add at least one image");return}if(o.filter(ut=>!ut.caption.trim()).length>0){ae.error("Please add captions to all images");return}u(!0);try{const{data:ut}=await q.from("social_swag_2").select("sort_order").eq("month",i).order("sort_order",{ascending:!1}).limit(1),_t=(((Ye=ut==null?void 0:ut[0])==null?void 0:Ye.sort_order)??-1)+1;for(let bt=0;bt{const Ye=at.image_url.split("/social-swag-2/");Ye[1]&&await q.storage.from("social-swag-2").remove([Ye[1]]);const{error:ut}=await q.from("social_swag_2").delete().eq("id",at.id);if(ut)throw ut},onSuccess:()=>{ae.success("Image deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2"]})},onError:()=>ae.error("Failed to delete image")}),it=yt({mutationFn:async({id:at,postDate:Ye})=>{const{error:ut}=await q.from("social_swag_2").update({post_date:Ye}).eq("id",at);if(ut)throw ut},onSuccess:()=>{ae.success("Post date updated"),s.invalidateQueries({queryKey:["admin-social-swag-2"]}),s.invalidateQueries({queryKey:["social-swag-2"]})},onError:()=>ae.error("Failed to update post date")}),je=yt({mutationFn:async({month:at,link:Ye})=>{const{error:ut}=await q.from("social_swag_2_months").upsert({month:at,canva_link:Ye||null},{onConflict:"month"});if(ut)throw ut},onSuccess:()=>{ae.success("Canva link updated"),p(null),s.invalidateQueries({queryKey:["admin-social-swag-2-months"]})},onError:()=>ae.error("Failed to update Canva link")}),He=at=>{var Ye;return((Ye=ve.find(ut=>ut.month===at))==null?void 0:Ye.canva_link)||""},$e=at=>ge.find(Ye=>Ye.month===at)||null,Ke=at=>{var ut;const Ye=(ut=at.target.files)==null?void 0:ut[0];Ye&&(z(Ye),Z(URL.createObjectURL(Ye)))},Ge=()=>{H&&URL.revokeObjectURL(H),z(null),Z(""),W(""),se("")},rt=async()=>{if(!F){ae.error("Please select an image");return}he(!0);try{const at=F.name.split(".").pop(),Ye=`reels/${D}-${Date.now()}.${at}`,{error:ut}=await q.storage.from("social-swag-2").upload(Ye,F);if(ut)throw ut;const{data:{publicUrl:_t}}=q.storage.from("social-swag-2").getPublicUrl(Ye),{error:bt}=await q.from("social_swag_2_reels").upsert({month:D,image_url:_t,canva_link:ee||null,caption:Y||null},{onConflict:"month"});if(bt)throw bt;ae.success("Reel uploaded successfully!"),JCe(`${Ce(D)} Reel`,"social-swag-2"),Ge(),O(!1),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})}catch(at){console.error("Reel upload error:",at),ae.error("Failed to upload reel")}finally{he(!1)}},tt=yt({mutationFn:async at=>{const Ye=at.image_url.split("/social-swag-2/");Ye[1]&&await q.storage.from("social-swag-2").remove([Ye[1]]);const{error:ut}=await q.from("social_swag_2_reels").delete().eq("id",at.id);if(ut)throw ut},onSuccess:()=>{ae.success("Reel deleted"),s.invalidateQueries({queryKey:["admin-social-swag-2-reels"]})},onError:()=>ae.error("Failed to delete reel")});return e.jsxs(Cs,{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(_s,{open:r,onOpenChange:a,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Upload Images"]})}),e.jsxs(bs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Upload Social Swag Images"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Month"}),e.jsx(ye,{type:"month",value:i,onChange:at=>l(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{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:Ae,className:"hidden",id:"swag-upload",disabled:o.length>=16}),e.jsxs("label",{htmlFor:"swag-upload",className:"cursor-pointer",children:[e.jsx(_a,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select images (max 16)"})]})]})]}),o.length>0&&e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:o.map((at,Ye)=>e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative aspect-[4/5] rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:at.preview,alt:`Upload ${Ye+1}`,className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6",onClick:()=>Be(Ye),children:e.jsx($n,{className:"h-3 w-3"})})]}),e.jsx(Ms,{placeholder:"Caption...",value:at.caption,onChange:ut=>we(Ye,ut.target.value),className:"text-xs h-20"})]},Ye))}),e.jsx(B,{onClick:Je,disabled:d||o.length===0,className:"w-full gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-4 w-4"}),"Upload ",o.length," Images"]})})]})]})]}),e.jsxs(_s,{open:E,onOpenChange:at=>{O(at),at||Ge()},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"gap-2",children:[e.jsx(Sh,{className:"h-4 w-4"}),"Upload Reel"]})}),e.jsxs(bs,{className:"max-w-lg max-h-[85vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Upload Monthly Reel"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Month"}),e.jsx(ye,{type:"month",value:D,onChange:at=>I(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Reel Preview Image"}),H?e.jsxs("div",{className:"relative aspect-[9/16] max-w-[120px] mx-auto rounded-lg overflow-hidden bg-muted",children:[e.jsx("img",{src:H,alt:"Reel preview",className:"w-full h-full object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{URL.revokeObjectURL(H),z(null),Z("")},children:e.jsx($n,{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:Ke,className:"hidden",id:"reel-upload"}),e.jsxs("label",{htmlFor:"reel-upload",className:"cursor-pointer",children:[e.jsx(Sh,{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(ne,{children:"Canva Download Link"}),e.jsx(ye,{value:ee,onChange:at=>se(at.target.value),placeholder:"https://www.canva.com/..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Caption"}),e.jsx(Ms,{value:Y,onChange:at=>W(at.target.value),placeholder:"Enter caption for this reel...",className:"h-24"})]}),e.jsx(B,{onClick:rt,disabled:oe||!F,className:"w-full gap-2",children:oe?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-4 w-4"}),"Upload Reel"]})})]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:me.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total Images"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-2xl font-bold",children:Te.length}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Months"})]})})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Fr,{value:t,onValueChange:n,children:e.jsxs(Rr,{children:[e.jsx(Zt,{value:"all",children:"All"}),Te.map(at=>e.jsx(Zt,{value:at,children:Ce(at)},at))]})}),t!=="all"&&e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Yo,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ne,{className:"text-sm text-muted-foreground",children:["Canva Edit Link for ",Ce(t)]}),(h==null?void 0:h.month)===t?e.jsxs("div",{className:"flex gap-2 mt-1",children:[e.jsx(ye,{value:h.link,onChange:at=>p({...h,link:at.target.value}),placeholder:"https://www.canva.com/..."}),e.jsx(B,{size:"sm",onClick:()=>je.mutate(h),children:"Save"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p(null),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("span",{className:"text-sm",children:He(t)||"No link set"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>p({month:t,link:He(t)}),children:"Edit"})]})]})]})})}),t!=="all"&&e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx(Sh,{className:"h-4 w-4 text-muted-foreground mt-1"}),e.jsxs("div",{className:"flex-1",children:[e.jsxs(ne,{className:"text-sm text-muted-foreground",children:["Reel for ",Ce(t)]}),(()=>{const at=$e(t);return at?e.jsxs("div",{className:"flex items-center gap-4 mt-2",children:[e.jsx("img",{src:at.image_url,alt:"Reel preview",className:"w-16 h-28 object-cover rounded"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("p",{className:"line-clamp-2",children:at.caption||"No caption"}),at.canva_link&&e.jsx("a",{href:at.canva_link,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-xs",children:"View Canva Link"})]}),e.jsx(B,{variant:"destructive",size:"sm",onClick:()=>tt.mutate(at),children:e.jsx(_n,{className:"h-4 w-4"})})]}):e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"No reel uploaded for this month"})})()]})]})})})]}),le?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):Ie.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Xo,{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(pve,{sensors:ce,collisionDetection:cve,onDragEnd:Re,children:e.jsx(xve,{items:Ie.map(at=>at.id),strategy:_U,children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:Ie.map(at=>e.jsx(jws,{item:at,onEdit:Me,onDelete:Ye=>ke.mutate(Ye),onDateChange:(Ye,ut)=>it.mutate({id:Ye,postDate:ut})},at.id))})})})]}),e.jsx(_s,{open:!!f,onOpenChange:at=>{at||y(null)},children:e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Edit Image"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"aspect-[4/5] max-h-48 w-full rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:f.image_url,alt:"Preview",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Caption"}),e.jsx(Ms,{value:_,onChange:at=>v(at.target.value),placeholder:"Enter caption...",className:"h-28"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Post Date"}),e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("flex-1 justify-start gap-2 font-normal",!j&&"text-muted-foreground"),children:[e.jsx(yr,{className:"h-4 w-4"}),j?Ss(new Date(j+"T00:00:00"),"MMM d, yyyy"):"Pick a date"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:j?new Date(j+"T00:00:00"):void 0,onSelect:at=>w(at?Ss(at,"yyyy-MM-dd"):null),className:"p-3 pointer-events-auto"})})]}),j&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>w(null),children:e.jsx($n,{className:"h-4 w-4"})})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>y(null),children:"Cancel"}),e.jsx(B,{onClick:Pe,disabled:S,className:"gap-2",children:S?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Saving..."]}):"Save Changes"})]})]})})]})},kws=()=>{const{toast:s}=Fa(),t=Kt(),[n,r]=N.useState("categories"),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState({name:"",description:"",icon:""}),[u,h]=N.useState(!1),[p,f]=N.useState(null),[y,_]=N.useState({name:"",description:"",icon:""}),[v,j]=N.useState(!1),[w,S]=N.useState(null),[A,E]=N.useState(""),{data:O=[],isLoading:D}=dt({queryKey:["admin-community-categories"],queryFn:async()=>{const{data:Re,error:Ae}=await q.from("community_categories").select("*").order("sort_order");if(Ae)throw Ae;return Re}}),{data:I=[],isLoading:F}=dt({queryKey:["admin-private-groups"],queryFn:async()=>{const{data:Re,error:Ae}=await q.from("community_private_groups").select("*").order("sort_order");if(Ae)throw Ae;return Re}}),{data:z=[]}=dt({queryKey:["admin-group-members",w==null?void 0:w.id],queryFn:async()=>{if(!w)return[];const{data:Re,error:Ae}=await q.from("community_private_group_members").select("*").eq("group_id",w.id);if(Ae)throw Ae;return Re},enabled:!!w}),{data:H=[]}=dt({queryKey:["admin-all-profiles"],queryFn:async()=>{let Ae=[],Be=0,we=!0;for(;we;){const{data:Je,error:ke}=await q.from("profiles").select("id, name, email, brokerage_id").order("name").range(Be,Be+1e3-1);if(ke)throw ke;Je&&Je.length>0?(Ae=[...Ae,...Je],Be+=1e3,we=Je.length===1e3):we=!1}return Ae}}),{data:Z=[]}=dt({queryKey:["admin-all-brokerages"],queryFn:async()=>{const{data:Re,error:Ae}=await q.from("brokerages").select("*").order("name");if(Ae)throw Ae;return Re}}),Y=yt({mutationFn:async Re=>{if(Re.id){const{error:Ae}=await q.from("community_categories").update({name:Re.name,description:Re.description||null,icon:Re.icon||null}).eq("id",Re.id);if(Ae)throw Ae}else{const Ae=Math.max(...O.map(we=>we.sort_order),0),{error:Be}=await q.from("community_categories").insert({name:Re.name,description:Re.description||null,icon:Re.icon||null,sort_order:Ae+1});if(Be)throw Be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),i(!1),o(null),d({name:"",description:"",icon:""}),s({title:l?"Category updated!":"Category created!"})},onError:Re=>{s({title:"Error",description:Re.message,variant:"destructive"})}}),W=yt({mutationFn:async Re=>{const{error:Ae}=await q.from("community_categories").delete().eq("id",Re);if(Ae)throw Ae},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-community-categories"]}),s({title:"Category deleted"})}}),ee=yt({mutationFn:async({id:Re,direction:Ae})=>{const Be=O.findIndex(we=>we.id===Re);if(Ae==="up"&&Be>0){const we=O[Be-1],Je=O[Be];await q.from("community_categories").update({sort_order:Je.sort_order}).eq("id",we.id),await q.from("community_categories").update({sort_order:we.sort_order}).eq("id",Je.id)}else if(Ae==="down"&&Bet.invalidateQueries({queryKey:["admin-community-categories"]})}),se=yt({mutationFn:async Re=>{if(Re.id){const{error:Ae}=await q.from("community_private_groups").update({name:Re.name,description:Re.description||null,icon:Re.icon||null}).eq("id",Re.id);if(Ae)throw Ae}else{const Ae=Math.max(...I.map(we=>we.sort_order),0),{error:Be}=await q.from("community_private_groups").insert({name:Re.name,description:Re.description||null,icon:Re.icon||null,sort_order:Ae+1});if(Be)throw Be}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),h(!1),f(null),_({name:"",description:"",icon:""}),s({title:p?"Private group updated!":"Private group created!"})},onError:Re=>{s({title:"Error",description:Re.message,variant:"destructive"})}}),oe=yt({mutationFn:async Re=>{const{error:Ae}=await q.from("community_private_groups").delete().eq("id",Re);if(Ae)throw Ae},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-private-groups"]}),s({title:"Private group deleted"})}}),he=yt({mutationFn:async({id:Re,direction:Ae})=>{const Be=I.findIndex(we=>we.id===Re);if(Ae==="up"&&Be>0){const we=I[Be-1],Je=I[Be];await q.from("community_private_groups").update({sort_order:Je.sort_order}).eq("id",we.id),await q.from("community_private_groups").update({sort_order:we.sort_order}).eq("id",Je.id)}else if(Ae==="down"&&Bet.invalidateQueries({queryKey:["admin-private-groups"]})}),ce=yt({mutationFn:async({groupId:Re,userId:Ae,isMember:Be})=>{if(Be){const{error:we}=await q.from("community_private_group_members").delete().eq("group_id",Re).eq("user_id",Ae);if(we)throw we}else{const{error:we}=await q.from("community_private_group_members").insert({group_id:Re,user_id:Ae});if(we)throw we}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",w==null?void 0:w.id]})}}),me=yt({mutationFn:async({groupId:Re,brokerageId:Ae,isMember:Be})=>{if(Be){const{error:we}=await q.from("community_private_group_members").delete().eq("group_id",Re).eq("brokerage_id",Ae);if(we)throw we}else{const{error:we}=await q.from("community_private_group_members").insert({group_id:Re,brokerage_id:Ae});if(we)throw we}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-group-members",w==null?void 0:w.id]})}}),le=Re=>{o(Re),d({name:Re.name,description:Re.description||"",icon:Re.icon||""}),i(!0)},ve=()=>{o(null),d({name:"",description:"",icon:""}),i(!0)},ge=Re=>{f(Re),_({name:Re.name,description:Re.description||"",icon:Re.icon||""}),h(!0)},Te=()=>{f(null),_({name:"",description:"",icon:""}),h(!0)},Ie=Re=>{S(Re),E(""),j(!0)},Ce=Re=>z.some(Ae=>Ae.user_id===Re),Me=Re=>z.some(Ae=>Ae.brokerage_id===Re),Pe=H.filter(Re=>Re.name.toLowerCase().includes(A.toLowerCase())||Re.email.toLowerCase().includes(A.toLowerCase()));return e.jsx(Cs,{title:"Community Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Community Management",description:"Manage categories and private groups for community discussions"}),e.jsxs(Fr,{value:n,onValueChange:r,children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"categories",children:"Public Categories"}),e.jsxs(Zt,{value:"private-groups",children:[e.jsx(Gc,{className:"h-4 w-4 mr-1"}),"Private Groups"]})]}),e.jsxs(is,{value:"categories",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Categories visible to all community members"}),e.jsxs(B,{onClick:ve,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-[50px]",children:"Order"}),e.jsx(Tt,{className:"w-[80px]",children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(da,{children:D?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):O.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first one!"})}):O.map((Re,Ae)=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ae===0,onClick:()=>ee.mutate({id:Re.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ae===O.length-1,onClick:()=>ee.mutate({id:Re.id,direction:"down"}),children:"↓"})]})}),e.jsx(ht,{className:"text-2xl",children:Re.icon||"📁"}),e.jsx(ht,{className:"font-medium",children:Re.name}),e.jsx(ht,{className:"text-muted-foreground",children:Re.description||"—"}),e.jsx(ht,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>le(Re),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this category? Posts will be uncategorized.")&&W.mutate(Re.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Re.id))})]})})})]}),e.jsxs(is,{value:"private-groups",className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Private groups visible only to assigned members or brokerages"}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ua,{className:"h-3 w-3"}),"Brokerage groups are created automatically and sync with brokerage names"]})]}),e.jsxs(B,{onClick:Te,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Private Group"]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-[50px]",children:"Order"}),e.jsx(Tt,{className:"w-[80px]",children:"Icon"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"w-[120px]",children:"Members"}),e.jsx(Tt,{className:"w-[140px]",children:"Actions"})]})}),e.jsx(da,{children:F?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):I.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No private groups yet. Create your first one!"})}):I.map((Re,Ae)=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ae===0,onClick:()=>he.mutate({id:Re.id,direction:"up"}),children:"↑"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",disabled:Ae===I.length-1,onClick:()=>he.mutate({id:Re.id,direction:"down"}),children:"↓"})]})}),e.jsx(ht,{className:"text-2xl",children:Re.icon||"🔒"}),e.jsx(ht,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2",children:[Re.name,Re.brokerage_id?e.jsxs(Ue,{variant:"outline",className:"text-xs bg-blue-50 text-blue-700 border-blue-200",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),"Auto-managed"]}):e.jsxs(Ue,{variant:"secondary",className:"text-xs",children:[e.jsx(Gc,{className:"h-3 w-3 mr-1"}),"Private"]})]})}),e.jsx(ht,{className:"text-muted-foreground",children:Re.description||"—"}),e.jsx(ht,{children:e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>Ie(Re),children:[e.jsx(An,{className:"h-4 w-4 mr-1"}),"Manage"]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex gap-1",children:[!Re.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ge(Re),children:e.jsx(ya,{className:"h-4 w-4"})}),!Re.brokerage_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{confirm("Delete this private group? All posts in this group will be deleted.")&&oe.mutate(Re.id)},children:e.jsx(_n,{className:"h-4 w-4"})}),Re.brokerage_id&&e.jsx("span",{className:"text-xs text-muted-foreground italic",children:"Managed via brokerage"})]})})]},Re.id))})]})})})]})]}),e.jsx(_s,{open:a,onOpenChange:i,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:l?"Edit Category":"Create Category"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(ye,{value:c.icon,onChange:Re=>d(Ae=>({...Ae,icon:Re.target.value})),placeholder:"💬",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ye,{value:c.name,onChange:Re=>d(Ae=>({...Ae,name:Re.target.value})),placeholder:"Category name",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ms,{value:c.description,onChange:Re=>d(Ae=>({...Ae,description:Re.target.value})),placeholder:"Brief description of this category",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>Y.mutate({...c,id:l==null?void 0:l.id}),disabled:!c.name.trim(),children:l?"Save Changes":"Create Category"})]})]})]})}),e.jsx(_s,{open:u,onOpenChange:h,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:p?"Edit Private Group":"Create Private Group"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Icon (emoji)"}),e.jsx(ye,{value:y.icon,onChange:Re=>_(Ae=>({...Ae,icon:Re.target.value})),placeholder:"🔒",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Name *"}),e.jsx(ye,{value:y.name,onChange:Re=>_(Ae=>({...Ae,name:Re.target.value})),placeholder:"e.g., Pioneers",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium",children:"Description"}),e.jsx(Ms,{value:y.description,onChange:Re=>_(Ae=>({...Ae,description:Re.target.value})),placeholder:"Brief description of this private group",className:"mt-1"})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>h(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>se.mutate({...y,id:p==null?void 0:p.id}),disabled:!y.name.trim(),children:p?"Save Changes":"Create Private Group"})]})]})]})}),e.jsx(_s,{open:v,onOpenChange:j,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(ws,{children:["Manage Members: ",w==null?void 0:w.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Fr,{defaultValue:"brokerages",children:[e.jsxs(Rr,{className:"w-full",children:[e.jsx(Zt,{value:"brokerages",className:"flex-1",children:"By Brokerage"}),e.jsx(Zt,{value:"users",className:"flex-1",children:"Individual Users"})]}),e.jsxs(is,{value:"brokerages",className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select brokerages to grant all their agents access to this private group."}),e.jsx(di,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Z.map(Re=>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(hi,{checked:Me(Re.id),onCheckedChange:()=>{w&&me.mutate({groupId:w.id,brokerageId:Re.id,isMember:Me(Re.id)})}}),e.jsx("span",{className:"font-medium",children:Re.name})]}),e.jsxs(Ue,{variant:"secondary",children:[H.filter(Ae=>Ae.brokerage_id===Re.id).length," agents"]})]},Re.id)),Z.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No brokerages found"})]})})]}),e.jsxs(is,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search users...",value:A,onChange:Re=>E(Re.target.value),className:"pl-9"})]}),e.jsx(di,{className:"h-[300px] border rounded-md p-4",children:e.jsxs("div",{className:"space-y-2",children:[Pe.map(Re=>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(hi,{checked:Ce(Re.id),onCheckedChange:()=>{w&&ce.mutate({groupId:w.id,userId:Re.id,isMember:Ce(Re.id)})}}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Re.name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Re.email})]})]})},Re.id)),Pe.length===0&&e.jsx("p",{className:"text-center text-muted-foreground py-4",children:"No users found"})]})})]})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{onClick:()=>j(!1),children:"Done"})})]})]})})]})})},OHe=s=>{switch(s){case"academy_video":return e.jsx(El,{className:"h-3 w-3"});case"template":return e.jsx(br,{className:"h-3 w-3"});case"toolbox":return e.jsx(Ec,{className:"h-3 w-3"});case"newsletter":return e.jsx(sy,{className:"h-3 w-3"});case"social_swag":return e.jsx(un,{className:"h-3 w-3"});default:return e.jsx(tr,{className:"h-3 w-3"})}},Sws=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}},Cws=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}},Tws=()=>{const{toast:s}=Fa(),[t,n]=N.useState([]),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState(!0),[d,u]=N.useState(""),[h,p]=N.useState(null),[f,y]=N.useState([]),[_,v]=N.useState([]);N.useEffect(()=>{j()},[]);const j=async()=>{try{c(!0);const{data:z,error:H}=await q.from("activity_logs").select(` id, user_id, app_name, launched_at, profiles ( name, email, brokerages ( name ) ) `).order("launched_at",{ascending:!1}).limit(5e3);if(H)throw H;const{data:Z,error:Y}=await q.from("content_engagement_logs").select(` id, user_id, resource_type, resource_id, resource_title, action_type, created_at `).order("created_at",{ascending:!1}).limit(5e3);if(Y)throw Y;const W=[...new Set((Z==null?void 0:Z.map(le=>le.user_id))||[])],{data:ee}=await q.from("profiles").select(` id, name, email, brokerages ( name ) `).in("id",W),se=new Map((ee==null?void 0:ee.map(le=>[le.id,le]))||[]),oe=(z==null?void 0:z.map(le=>{var ve,ge,Te,Ie;return{id:le.id,user_id:le.user_id,app_name:le.app_name,launched_at:le.launched_at,user_name:((ve=le.profiles)==null?void 0:ve.name)||"Unknown",user_email:((ge=le.profiles)==null?void 0:ge.email)||"Unknown",brokerage_name:((Ie=(Te=le.profiles)==null?void 0:Te.brokerages)==null?void 0:Ie.name)||null}}))||[],he=(Z==null?void 0:Z.map(le=>{var ge;const ve=se.get(le.user_id);return{id:le.id,user_id:le.user_id,resource_type:le.resource_type,resource_id:le.resource_id,resource_title:le.resource_title,action_type:le.action_type,created_at:le.created_at,user_name:(ve==null?void 0:ve.name)||"Unknown",user_email:(ve==null?void 0:ve.email)||"Unknown",brokerage_name:((ge=ve==null?void 0:ve.brokerages)==null?void 0:ge.name)||null}}))||[];n(oe),a(he);const ce=new Map;oe.forEach(le=>{if(!ce.has(le.user_id))ce.set(le.user_id,{user_id:le.user_id,user_name:le.user_name,user_email:le.user_email,brokerage_name:le.brokerage_name,last_activity_type:"app",last_activity_name:le.app_name,last_activity_at:le.launched_at,total_app_launches:1,total_content_views:0});else{const ve=ce.get(le.user_id);ve.total_app_launches++,new Date(le.launched_at)>new Date(ve.last_activity_at)&&(ve.last_activity_type="app",ve.last_activity_name=le.app_name,ve.last_activity_at=le.launched_at)}}),he.forEach(le=>{if(!ce.has(le.user_id))ce.set(le.user_id,{user_id:le.user_id,user_name:le.user_name,user_email:le.user_email,brokerage_name:le.brokerage_name,last_activity_type:le.resource_type,last_activity_name:le.resource_title,last_activity_at:le.created_at,total_app_launches:0,total_content_views:1});else{const ve=ce.get(le.user_id);ve.total_content_views++,new Date(le.created_at)>new Date(ve.last_activity_at)&&(ve.last_activity_type=le.resource_type,ve.last_activity_name=le.resource_title,ve.last_activity_at=le.created_at)}});const me=Array.from(ce.values()).sort((le,ve)=>new Date(ve.last_activity_at).getTime()-new Date(le.last_activity_at).getTime());l(me)}catch(z){console.error("Error loading activity:",z),s({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{c(!1)}},w=z=>{p({id:z.user_id,name:z.user_name,email:z.user_email});const H=t.filter(Y=>Y.user_id===z.user_id),Z=r.filter(Y=>Y.user_id===z.user_id);y(H),v(Z)},S=()=>{p(null),y([]),v([])},{sortKey:A,sortDirection:E,handleSort:O,sortData:D}=xU("last_activity_at","desc"),I=i.filter(z=>{var Z;if(!d)return!0;const H=d.toLowerCase();return z.user_name.toLowerCase().includes(H)||z.user_email.toLowerCase().includes(H)||((Z=z.brokerage_name)==null?void 0:Z.toLowerCase().includes(H))}),F=D(I,{user:z=>{var H;return((H=z.user_name)==null?void 0:H.toLowerCase())||""},brokerage:z=>{var H;return((H=z.brokerage_name)==null?void 0:H.toLowerCase())||""},last_activity_at:z=>new Date(z.last_activity_at).getTime(),apps:z=>z.total_app_launches,content:z=>z.total_content_views});return o?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"User Activity"}),e.jsx(Vn,{children:"App launches and content engagement - click to see full history"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"mb-4",children:e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or brokerage...",value:d,onChange:z=>u(z.target.value),className:"pl-9"})]})}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Sc,{sortKey:"user",currentSortKey:A,currentDirection:E,onSort:O,children:"User"}),e.jsx(Sc,{sortKey:"brokerage",currentSortKey:A,currentDirection:E,onSort:O,children:"Brokerage"}),e.jsx(Tt,{children:"Last Activity"}),e.jsx(Sc,{sortKey:"last_activity_at",currentSortKey:A,currentDirection:E,onSort:O,children:"Last Active"}),e.jsx(Sc,{sortKey:"apps",currentSortKey:A,currentDirection:E,onSort:O,className:"text-right",children:"Apps"}),e.jsx(Sc,{sortKey:"content",currentSortKey:A,currentDirection:E,onSort:O,className:"text-right",children:"Content"})]})}),e.jsx(da,{children:F.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center text-muted-foreground",children:"No activity found"})}):F.map(z=>e.jsxs(Hs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>w(z),children:[e.jsx(ht,{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(ht,{children:z.brokerage_name?e.jsx(Ue,{variant:"outline",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"-"})}),e.jsx(ht,{children:e.jsx("div",{className:"flex items-center gap-2",children:z.last_activity_type==="app"?e.jsxs(Ue,{variant:"secondary",children:[e.jsx(tr,{className:"h-3 w-3 mr-1"}),z.last_activity_name]}):e.jsxs(Ue,{variant:"outline",className:"flex items-center gap-1",children:[OHe(z.last_activity_type),e.jsx("span",{className:"max-w-32 truncate",children:z.last_activity_name})]})})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Uo(new Date(z.last_activity_at),{addSuffix:!0})}),e.jsx(ht,{className:"text-right",children:e.jsx(Ue,{variant:"outline",children:z.total_app_launches})}),e.jsx(ht,{className:"text-right",children:e.jsx(Ue,{variant:"outline",children:z.total_content_views})})]},z.user_id))})]})})]})]}),e.jsx(_s,{open:!!h,onOpenChange:z=>!z&&S(),children:e.jsxs(bs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(ws,{children:[h==null?void 0:h.name,"'s Activity"]}),e.jsx(Jn,{children:h==null?void 0:h.email})]}),e.jsxs(Fr,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"content",children:["Content (",_.length,")"]}),e.jsxs(Zt,{value:"apps",children:["App Launches (",f.length,")"]})]}),e.jsx(is,{value:"content",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(da,{children:_.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement"})}):_.map(z=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs(Ue,{variant:"outline",className:"flex items-center gap-1 w-fit",children:[OHe(z.resource_type),Sws(z.resource_type)]})}),e.jsx(ht,{className:"max-w-48",children:e.jsx("span",{className:"truncate block",children:z.resource_title})}),e.jsx(ht,{children:e.jsx(Ue,{variant:"secondary",children:Cws(z.action_type)})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Uo(new Date(z.created_at),{addSuffix:!0})})]},z.id))})]})})}),e.jsx(is,{value:"apps",className:"flex-1 overflow-auto mt-4",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(da,{children:f.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches"})}):f.map(z=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsx(Ue,{variant:"secondary",children:z.app_name})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Uo(new Date(z.launched_at),{addSuffix:!0})})]},z.id))})]})})})]})]})})]})},Ews=()=>{const{toast:s}=Fa(),[t,n]=N.useState({totalUsers:0,activeUsers:0,pendingUsers:0,totalBrokerages:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0,uniqueActiveThisWeek:0}),[r,a]=N.useState(!0);N.useEffect(()=>{i()},[]);const i=async()=>{try{a(!0);const{count:l}=await q.from("profiles").select("*",{count:"exact",head:!0}),{count:o}=await q.from("profiles").select("*",{count:"exact",head:!0}).not("last_login","is",null),c=(l||0)-(o||0),{count:d}=await q.from("brokerages").select("*",{count:"exact",head:!0}),{count:u}=await q.from("activity_logs").select("*",{count:"exact",head:!0}),h=new Date;h.setDate(h.getDate()-7);const{count:p}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",h.toISOString()),f=new Date;f.setMonth(f.getMonth()-1);const{count:y}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).gte("launched_at",f.toISOString()),{data:_}=await q.from("activity_logs").select("user_id").gte("launched_at",h.toISOString()),v=new Set(_==null?void 0:_.map(j=>j.user_id)).size;n({totalUsers:l||0,activeUsers:o||0,pendingUsers:c,totalBrokerages:d||0,totalLaunches:u||0,launchesThisWeek:p||0,launchesThisMonth:y||0,uniqueActiveThisWeek:v})}catch(l){console.error("Error loading analytics:",l),s({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{a(!1)}};return r?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total Users"}),e.jsx(An,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalUsers}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[t.activeUsers," active, ",t.pendingUsers," pending"]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(Pi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.activeUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:t.totalUsers>0?`${Math.round(t.activeUsers/t.totalUsers*100)}% of total`:"0% of total"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.pendingUsers}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Brokerages"}),e.jsx(Ua,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalBrokerages}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total brokerages"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(em,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Launches This Week"}),e.jsx(em,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Launches This Month"}),e.jsx(em,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Active This Week"}),e.jsx(go,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:t.uniqueActiveThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique users"})]})]})]})},FHe={event:"Event",template:"Template",academy_video:"Academy Video",resource_kit:"Resource Kit",newsletter:"Newsletter",social_swag:"Social Swag"},zHe={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 cyt({brokerageOnly:s=!1,brokerageId:t}){const[n,r]=N.useState([]),[a,i]=N.useState(!0),[l,o]=N.useState(""),[c,d]=N.useState("all");N.useEffect(()=>{u()},[t]);const u=async()=>{i(!0);try{let O=[];if(s&&t){const{data:W}=await q.from("profiles").select("id").eq("brokerage_id",t);if(O=(W==null?void 0:W.map(ee=>ee.id))||[],O.length===0){r([]),i(!1);return}}let D=q.from("resource_shares").select("*").order("created_at",{ascending:!1});s&&O.length>0&&(D=D.or(`sender_id.in.(${O.join(",")}),recipient_id.in.(${O.join(",")})`));const{data:I,error:F}=await D;if(F)throw F;const z=new Set;I==null||I.forEach(W=>{z.add(W.sender_id),z.add(W.recipient_id)});const{data:H}=await q.from("profiles").select("id, name, email").in("id",Array.from(z)),Z=new Map((H==null?void 0:H.map(W=>[W.id,W]))||[]),Y=(I==null?void 0:I.map(W=>({...W,sender:Z.get(W.sender_id),recipient:Z.get(W.recipient_id)})))||[];r(Y)}catch(O){console.error("Error loading shares:",O)}finally{i(!1)}},{sortKey:h,sortDirection:p,handleSort:f,sortData:y}=xU("created_at","desc"),_=n.filter(O=>{var F,z;const D=l===""||O.resource_title.toLowerCase().includes(l.toLowerCase())||((F=O.sender)==null?void 0:F.name.toLowerCase().includes(l.toLowerCase()))||((z=O.recipient)==null?void 0:z.name.toLowerCase().includes(l.toLowerCase())),I=c==="all"||O.resource_type===c;return D&&I}),v=y(_,{resource:O=>{var D;return((D=O.resource_title)==null?void 0:D.toLowerCase())||""},type:O=>O.resource_type,sender:O=>{var D,I;return((I=(D=O.sender)==null?void 0:D.name)==null?void 0:I.toLowerCase())||""},recipient:O=>{var D,I;return((I=(D=O.recipient)==null?void 0:D.name)==null?void 0:I.toLowerCase())||""},status:O=>O.is_read?1:0,created_at:O=>new Date(O.created_at).getTime()}),j=n.length,w=new Set(n.map(O=>O.sender_id)).size,S=new Set(n.map(O=>O.recipient_id)).size,A=n.length>0?Math.round(n.filter(O=>O.is_read).length/n.length*100):0,E=n.reduce((O,D)=>(O[D.resource_type]=(O[D.resource_type]||0)+1,O),{});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((O,D)=>e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ee,{children:e.jsx(Ws,{className:"h-8 w-16"})})]},D))}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-6",children:e.jsx(Ws,{className:"h-[300px]"})})})]}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total Shares"}),e.jsx(Vl,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:j})})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Active Sharers"}),e.jsx(An,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:w})})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Recipients Reached"}),e.jsx(go,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:S})})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Read Rate"}),e.jsx(br,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsxs("div",{className:"text-2xl font-bold",children:[A,"%"]})})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-sm font-medium",children:"Shares by Resource Type"})}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex flex-wrap gap-2",children:[Object.entries(E).map(([O,D])=>e.jsxs(Ue,{variant:"secondary",className:zHe[O],children:[FHe[O],": ",D]},O)),Object.keys(E).length===0&&e.jsx("span",{className:"text-muted-foreground text-sm",children:"No shares yet"})]})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Share History"}),e.jsxs(Vn,{children:["All resource shares ",s?"in your brokerage":"across the platform"]})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by resource, sender, or recipient...",value:l,onChange:O=>o(O.target.value),className:"pl-9"})]}),e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Resource type"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),e.jsx(Ze,{value:"event",children:"Events"}),e.jsx(Ze,{value:"template",children:"Templates"}),e.jsx(Ze,{value:"academy_video",children:"Academy Videos"}),e.jsx(Ze,{value:"resource_kit",children:"Resource Kits"}),e.jsx(Ze,{value:"newsletter",children:"Newsletters"}),e.jsx(Ze,{value:"social_swag",children:"Social Swag"})]})]})]}),e.jsx(di,{className:"h-[400px]",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Sc,{sortKey:"resource",currentSortKey:h,currentDirection:p,onSort:f,children:"Resource"}),e.jsx(Sc,{sortKey:"type",currentSortKey:h,currentDirection:p,onSort:f,children:"Type"}),e.jsx(Sc,{sortKey:"sender",currentSortKey:h,currentDirection:p,onSort:f,children:"Sender"}),e.jsx(Sc,{sortKey:"recipient",currentSortKey:h,currentDirection:p,onSort:f,children:"Recipient"}),e.jsx(Sc,{sortKey:"status",currentSortKey:h,currentDirection:p,onSort:f,children:"Status"}),e.jsx(Sc,{sortKey:"created_at",currentSortKey:h,currentDirection:p,onSort:f,children:"Date"})]})}),e.jsx(da,{children:v.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No shares found"})}):v.map(O=>{var D,I;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium max-w-[200px] truncate",children:O.resource_title}),e.jsx(ht,{children:e.jsx(Ue,{variant:"secondary",className:zHe[O.resource_type],children:FHe[O.resource_type]})}),e.jsx(ht,{children:((D=O.sender)==null?void 0:D.name)||"Unknown"}),e.jsx(ht,{children:((I=O.recipient)==null?void 0:I.name)||"Unknown"}),e.jsx(ht,{children:e.jsx(Ue,{variant:O.is_read?"default":"outline",children:O.is_read?"Read":"Unread"})}),e.jsx(ht,{className:"text-muted-foreground",children:Ss(new Date(O.created_at),"MMM d, yyyy")})]},O.id)})})]})})]})]})]})}const C2e={academy_video:{label:"Academy Videos",icon:fr,color:"bg-purple-100 text-purple-800",actionLabel:"Watched",actionIcon:Sr},template:{label:"Templates",icon:k2,color:"bg-blue-100 text-blue-800",actionLabel:"Accessed",actionIcon:Lm},toolbox:{label:"Toolkit",icon:gb,color:"bg-amber-100 text-amber-800",actionLabel:"Downloaded",actionIcon:Ia},newsletter:{label:"Newsletters",icon:Gs,color:"bg-emerald-100 text-emerald-800",actionLabel:"Clicked",actionIcon:Lm},social_swag:{label:"Social Swag",icon:pl,color:"bg-pink-100 text-pink-800",actionLabel:"Accessed",actionIcon:Lm},event:{label:"Events",icon:yr,color:"bg-cyan-100 text-cyan-800",actionLabel:"Registered",actionIcon:Lm}};function BHe(s){return s.resource_type==="toolbox"?s.total_downloads:s.total_clicks}function Aws(s,t){return s==="toolbox"?t.downloads:t.clicks}function Mws(){var O;const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(null),l=N.useRef(null),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=xU("total_views","desc");N.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:D,error:I}=await q.rpc("get_admin_content_engagement");if(I)throw I;t(D||[])}catch(D){console.error("Error loading content engagement:",D)}finally{r(!1)}},p=D=>{i(I=>{const F=I===D?null:D;return requestAnimationFrame(()=>{var z;(z=l.current)==null||z.scrollIntoView({behavior:"smooth",block:"start"})}),F})};if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-4",children:[...Array(4)].map((D,I)=>e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ee,{children:e.jsx(Ws,{className:"h-8 w-16"})})]},I))}),e.jsx(fe,{children:e.jsx(Ee,{className:"py-8",children:e.jsx(Ws,{className:"h-64 w-full"})})})]});const f=s.reduce((D,I)=>D+I.total_views,0),y=s.reduce((D,I)=>D+I.total_clicks,0),_=s.reduce((D,I)=>D+I.total_downloads,0),v=s.length,j=s.reduce((D,I)=>(D[I.resource_type]||(D[I.resource_type]={views:0,clicks:0,downloads:0,assets:0,uniqueUsers:0}),D[I.resource_type].views+=I.total_views,D[I.resource_type].clicks+=I.total_clicks,D[I.resource_type].downloads+=I.total_downloads,D[I.resource_type].assets+=1,D[I.resource_type].uniqueUsers+=I.unique_users,D),{}),w=a?s.filter(D=>D.resource_type===a):s,S=u(w,{asset:D=>{var I;return((I=D.resource_title)==null?void 0:I.toLowerCase())||""},type:D=>D.resource_type,views:D=>D.total_views,actions:D=>BHe(D),unique_users:D=>D.unique_users,last_activity:D=>D.last_engaged_at?new Date(D.last_engaged_at).getTime():0}),A=a?C2e[a]||{label:a,icon:Sr,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Lm}:null,E=A==null?void 0:A.icon;return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-5",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total Views"}),e.jsx(Sr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:f.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Across all content"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total Clicks"}),e.jsx(Lm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:y.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Link & Canva clicks"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Downloads"}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:_.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"PDF downloads"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Assets Tracked"}),e.jsx(go,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:v}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Unique content items"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Lm,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[f>0?Math.round((y+_)/f*100):0,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Of views → actions"})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Engagement by Content Type"}),e.jsx(Vn,{children:"Click a category to see individual asset performance"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"grid gap-3 grid-cols-2 md:grid-cols-3",children:Object.entries(j).map(([D,I])=>{const F=C2e[D]||{label:D,icon:Sr,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Lm},z=F.icon,H=a===D;return e.jsxs("button",{type:"button",onClick:()=>p(D),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors cursor-pointer ${H?"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(Sr,{className:"h-3 w-3"})," ",I.views]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(F.actionIcon,{className:"h-3 w-3"})," ",Aws(D,I)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(An,{className:"h-3 w-3"})," ",I.uniqueUsers]})]})]}),e.jsxs(Ue,{variant:"secondary",className:"text-[10px]",children:[I.assets," items"]})]},D)})})})]}),e.jsx("div",{ref:l,children:e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"text-sm font-medium flex items-center gap-2",children:A&&E?e.jsxs(e.Fragment,{children:[e.jsx(E,{className:"h-4 w-4"}),A.label," — Top Performers"]}):"Top Content by Engagement"}),e.jsx(Vn,{children:a?`${w.length} ${((O=A==null?void 0:A.label)==null?void 0:O.toLowerCase())||"items"} ranked by total interactions`:"All tracked assets ranked by total interactions"})]}),a&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>i(null),className:"gap-1",children:[e.jsx(qr,{className:"h-3.5 w-3.5"}),"Show All"]})]})}),e.jsx(Ee,{children:w.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(di,{className:"h-[400px]",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-[40px]",children:"#"}),e.jsx(Sc,{sortKey:"asset",currentSortKey:o,currentDirection:c,onSort:d,children:"Asset"}),!a&&e.jsx(Sc,{sortKey:"type",currentSortKey:o,currentDirection:c,onSort:d,children:"Type"}),e.jsx(Sc,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Views"}),e.jsx(Sc,{sortKey:"actions",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:A?A.actionLabel:"Actions"}),e.jsx(Sc,{sortKey:"unique_users",currentSortKey:o,currentDirection:c,onSort:d,className:"text-right",children:"Unique Users"}),e.jsx(Sc,{sortKey:"last_activity",currentSortKey:o,currentDirection:c,onSort:d,children:"Last Activity"})]})}),e.jsx(da,{children:S.map((D,I)=>{const F=C2e[D.resource_type]||{label:D.resource_type,color:"bg-muted text-muted-foreground",actionLabel:"Actions",actionIcon:Lm};return e.jsxs(Hs,{children:[e.jsx(ht,{className:"text-muted-foreground text-xs",children:I+1}),e.jsx(ht,{children:e.jsx("p",{className:"font-medium text-sm truncate max-w-[250px]",children:D.resource_title})}),!a&&e.jsx(ht,{children:e.jsx(Ue,{className:`text-[10px] ${F.color}`,children:F.label})}),e.jsx(ht,{className:"text-right font-medium",children:D.total_views}),e.jsx(ht,{className:"text-right font-medium",children:BHe(D)}),e.jsx(ht,{className:"text-right",children:D.unique_users}),e.jsx(ht,{className:"text-xs text-muted-foreground",children:D.last_engaged_at?Uo(new Date(D.last_engaged_at),{addSuffix:!0}):"—"})]},`${D.resource_type}-${D.resource_id}`)})})]})})})]})})]})}var Iws=Array.isArray,r0=Iws,Pws=typeof kh=="object"&&kh&&kh.Object===Object&&kh,dyt=Pws,Lws=dyt,Dws=typeof self=="object"&&self&&self.Object===Object&&self,Rws=Lws||Dws||Function("return this")(),Zw=Rws,Ows=Zw,Fws=Ows.Symbol,wU=Fws,$He=wU,uyt=Object.prototype,zws=uyt.hasOwnProperty,Bws=uyt.toString,xF=$He?$He.toStringTag:void 0;function $ws(s){var t=zws.call(s,xF),n=s[xF];try{s[xF]=void 0;var r=!0}catch{}var a=Bws.call(s);return r&&(t?s[xF]=n:delete s[xF]),a}var Uws=$ws,qws=Object.prototype,Vws=qws.toString;function Hws(s){return Vws.call(s)}var Gws=Hws,UHe=wU,Wws=Uws,Kws=Gws,Yws="[object Null]",Zws="[object Undefined]",qHe=UHe?UHe.toStringTag:void 0;function Qws(s){return s==null?s===void 0?Zws:Yws:qHe&&qHe in Object(s)?Wws(s):Kws(s)}var NN=Qws;function Xws(s){return s!=null&&typeof s=="object"}var kN=Xws,Jws=NN,ejs=kN,tjs="[object Symbol]";function sjs(s){return typeof s=="symbol"||ejs(s)&&Jws(s)==tjs}var XD=sjs,njs=r0,rjs=XD,ajs=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,ijs=/^\w*$/;function ojs(s,t){if(njs(s))return!1;var n=typeof s;return n=="number"||n=="symbol"||n=="boolean"||s==null||rjs(s)?!0:ijs.test(s)||!ajs.test(s)||t!=null&&s in Object(t)}var RIe=ojs;function ljs(s){var t=typeof s;return s!=null&&(t=="object"||t=="function")}var sC=ljs;const JD=_l(sC);var cjs=NN,djs=sC,ujs="[object AsyncFunction]",hjs="[object Function]",mjs="[object GeneratorFunction]",pjs="[object Proxy]";function fjs(s){if(!djs(s))return!1;var t=cjs(s);return t==hjs||t==mjs||t==ujs||t==pjs}var OIe=fjs;const ho=_l(OIe);var xjs=Zw,gjs=xjs["__core-js_shared__"],yjs=gjs,T2e=yjs,VHe=function(){var s=/[^.]+$/.exec(T2e&&T2e.keys&&T2e.keys.IE_PROTO||"");return s?"Symbol(src)_1."+s:""}();function vjs(s){return!!VHe&&VHe in s}var bjs=vjs,_js=Function.prototype,wjs=_js.toString;function jjs(s){if(s!=null){try{return wjs.call(s)}catch{}try{return s+""}catch{}}return""}var hyt=jjs,Njs=OIe,kjs=bjs,Sjs=sC,Cjs=hyt,Tjs=/[\\^$.*+?()[\]{}|]/g,Ejs=/^\[object .+?Constructor\]$/,Ajs=Function.prototype,Mjs=Object.prototype,Ijs=Ajs.toString,Pjs=Mjs.hasOwnProperty,Ljs=RegExp("^"+Ijs.call(Pjs).replace(Tjs,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function Djs(s){if(!Sjs(s)||kjs(s))return!1;var t=Njs(s)?Ljs:Ejs;return t.test(Cjs(s))}var Rjs=Djs;function Ojs(s,t){return s==null?void 0:s[t]}var Fjs=Ojs,zjs=Rjs,Bjs=Fjs;function $js(s,t){var n=Bjs(s,t);return zjs(n)?n:void 0}var ZM=$js,Ujs=ZM,qjs=Ujs(Object,"create"),yve=qjs,HHe=yve;function Vjs(){this.__data__=HHe?HHe(null):{},this.size=0}var Hjs=Vjs;function Gjs(s){var t=this.has(s)&&delete this.__data__[s];return this.size-=t?1:0,t}var Wjs=Gjs,Kjs=yve,Yjs="__lodash_hash_undefined__",Zjs=Object.prototype,Qjs=Zjs.hasOwnProperty;function Xjs(s){var t=this.__data__;if(Kjs){var n=t[s];return n===Yjs?void 0:n}return Qjs.call(t,s)?t[s]:void 0}var Jjs=Xjs,e2s=yve,t2s=Object.prototype,s2s=t2s.hasOwnProperty;function n2s(s){var t=this.__data__;return e2s?t[s]!==void 0:s2s.call(t,s)}var r2s=n2s,a2s=yve,i2s="__lodash_hash_undefined__";function o2s(s,t){var n=this.__data__;return this.size+=this.has(s)?0:1,n[s]=a2s&&t===void 0?i2s:t,this}var l2s=o2s,c2s=Hjs,d2s=Wjs,u2s=Jjs,h2s=r2s,m2s=l2s;function eR(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t-1}var A2s=E2s,M2s=vve;function I2s(s,t){var n=this.__data__,r=M2s(n,s);return r<0?(++this.size,n.push([s,t])):n[r][1]=t,this}var P2s=I2s,L2s=x2s,D2s=N2s,R2s=C2s,O2s=A2s,F2s=P2s;function tR(s){var t=-1,n=s==null?0:s.length;for(this.clear();++t0?1:-1},YE=function(t){return NM(t)&&t.indexOf("%")===t.length-1},ia=function(t){return iks(t)&&!jU(t)},dks=function(t){return jo(t)},Om=function(t){return ia(t)||NM(t)},uks=0,nR=function(t){var n=++uks;return"".concat(t||"").concat(n)},Zx=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,a=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!ia(t)&&!NM(t))return r;var i;if(YE(t)){var l=t.indexOf("%");i=n*parseFloat(t.slice(0,l))/100}else i=+t;return jU(i)&&(i=r),a&&i>n&&(i=n),i},cS=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},hks=function(t){if(!Array.isArray(t))return!1;for(var n=t.length,r={},a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function vks(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function i3e(s){"@babel/helpers - typeof";return i3e=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},i3e(s)}var XHe={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"},X2=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},JHe=null,A2e=null,WIe=function s(t){if(t===JHe&&Array.isArray(A2e))return A2e;var n=[];return N.Children.forEach(t,function(r){jo(r)||(tks.isFragment(r)?n=n.concat(s(r.props.children)):n.push(r))}),A2e=n,JHe=t,n};function hy(s,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(a){return X2(a)}):r=[X2(t)],WIe(s).forEach(function(a){var i=uy(a,"type.displayName")||uy(a,"type.name");r.indexOf(i)!==-1&&n.push(a)}),n}function B0(s,t){var n=hy(s,t);return n&&n[0]}var eGe=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,a=n.height;return!(!ia(r)||r<=0||!ia(a)||a<=0)},bks=["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"],_ks=function(t){return t&&t.type&&NM(t.type)&&bks.indexOf(t.type)>=0},wks=function(t){return t&&i3e(t)==="object"&&"clipDot"in t},jks=function(t,n,r,a){var i,l=(i=E2e==null?void 0:E2e[a])!==null&&i!==void 0?i:[];return n.startsWith("data-")||!ho(t)&&(a&&l.includes(n)||fks.includes(n))||r&&GIe.includes(n)},$i=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var a=t;if(N.isValidElement(t)&&(a=t.props),!JD(a))return null;var i={};return Object.keys(a).forEach(function(l){var o;jks((o=a)===null||o===void 0?void 0:o[l],l,n,r)&&(i[l]=a[l])}),i},o3e=function s(t,n){if(t===n)return!0;var r=N.Children.count(t);if(r!==N.Children.count(n))return!1;if(r===0)return!0;if(r===1)return tGe(Array.isArray(t)?t[0]:t,Array.isArray(n)?n[0]:n);for(var a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Tks(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function c3e(s){var t=s.children,n=s.width,r=s.height,a=s.viewBox,i=s.className,l=s.style,o=s.title,c=s.desc,d=Cks(s,Sks),u=a||{width:n,height:r,x:0,y:0},h=So("recharts-surface",i);return Ct.createElement("svg",l3e({},$i(d,!0,"svg"),{className:h,width:n,height:r,style:l,viewBox:"".concat(u.x," ").concat(u.y," ").concat(u.width," ").concat(u.height)}),Ct.createElement("title",null,o),Ct.createElement("desc",null,c),t)}var Eks=["children","className"];function d3e(){return d3e=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Mks(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var Wl=Ct.forwardRef(function(s,t){var n=s.children,r=s.className,a=Aks(s,Eks),i=So("recharts-layer",r);return Ct.createElement("g",d3e({className:i},$i(a,!0),{ref:t}),n)}),bb=function(t,n){for(var r=arguments.length,a=new Array(r>2?r-2:0),i=2;ia?0:a+t),n=n>a?a:n,n<0&&(n+=a),a=t>n?0:n-t>>>0,t>>>=0;for(var i=Array(a);++r=r?s:Lks(s,t,n)}var Rks=Dks,Oks="\\ud800-\\udfff",Fks="\\u0300-\\u036f",zks="\\ufe20-\\ufe2f",Bks="\\u20d0-\\u20ff",$ks=Fks+zks+Bks,Uks="\\ufe0e\\ufe0f",qks="\\u200d",Vks=RegExp("["+qks+Oks+$ks+Uks+"]");function Hks(s){return Vks.test(s)}var wyt=Hks;function Gks(s){return s.split("")}var Wks=Gks,jyt="\\ud800-\\udfff",Kks="\\u0300-\\u036f",Yks="\\ufe20-\\ufe2f",Zks="\\u20d0-\\u20ff",Qks=Kks+Yks+Zks,Xks="\\ufe0e\\ufe0f",Jks="["+jyt+"]",u3e="["+Qks+"]",h3e="\\ud83c[\\udffb-\\udfff]",eSs="(?:"+u3e+"|"+h3e+")",Nyt="[^"+jyt+"]",kyt="(?:\\ud83c[\\udde6-\\uddff]){2}",Syt="[\\ud800-\\udbff][\\udc00-\\udfff]",tSs="\\u200d",Cyt=eSs+"?",Tyt="["+Xks+"]?",sSs="(?:"+tSs+"(?:"+[Nyt,kyt,Syt].join("|")+")"+Tyt+Cyt+")*",nSs=Tyt+Cyt+sSs,rSs="(?:"+[Nyt+u3e+"?",u3e,kyt,Syt,Jks].join("|")+")",aSs=RegExp(h3e+"(?="+h3e+")|"+rSs+nSs,"g");function iSs(s){return s.match(aSs)||[]}var oSs=iSs,lSs=Wks,cSs=wyt,dSs=oSs;function uSs(s){return cSs(s)?dSs(s):lSs(s)}var hSs=uSs,mSs=Rks,pSs=wyt,fSs=hSs,xSs=xyt;function gSs(s){return function(t){t=xSs(t);var n=pSs(t)?fSs(t):void 0,r=n?n[0]:t.charAt(0),a=n?mSs(n,1).join(""):t.slice(1);return r[s]()+a}}var ySs=gSs,vSs=ySs,bSs=vSs("toUpperCase"),_Ss=bSs;const Pve=_l(_Ss);function xd(s){return function(){return s}}const Eyt=Math.cos,Nxe=Math.sin,Lb=Math.sqrt,kxe=Math.PI,Lve=2*kxe,m3e=Math.PI,p3e=2*m3e,SE=1e-6,wSs=p3e-SE;function Ayt(s){this._+=s[0];for(let t=1,n=s.length;t=0))throw new Error(`invalid digits: ${s}`);if(t>15)return Ayt;const n=10**t;return function(r){this._+=r[0];for(let a=1,i=r.length;aSE)if(!(Math.abs(h*c-d*u)>SE)||!i)this._append`L${this._x1=t},${this._y1=n}`;else{let f=r-l,y=a-o,_=c*c+d*d,v=f*f+y*y,j=Math.sqrt(_),w=Math.sqrt(p),S=i*Math.tan((m3e-Math.acos((_+p-v)/(2*j*w)))/2),A=S/w,E=S/j;Math.abs(A-1)>SE&&this._append`L${t+A*u},${n+A*h}`,this._append`A${i},${i},0,0,${+(h*f>u*y)},${this._x1=t+E*c},${this._y1=n+E*d}`}}arc(t,n,r,a,i,l){if(t=+t,n=+n,r=+r,l=!!l,r<0)throw new Error(`negative radius: ${r}`);let o=r*Math.cos(a),c=r*Math.sin(a),d=t+o,u=n+c,h=1^l,p=l?a-i:i-a;this._x1===null?this._append`M${d},${u}`:(Math.abs(this._x1-d)>SE||Math.abs(this._y1-u)>SE)&&this._append`L${d},${u}`,r&&(p<0&&(p=p%p3e+p3e),p>wSs?this._append`A${r},${r},0,1,${h},${t-o},${n-c}A${r},${r},0,1,${h},${this._x1=d},${this._y1=u}`:p>SE&&this._append`A${r},${r},0,${+(p>=m3e)},${h},${this._x1=t+r*Math.cos(i)},${this._y1=n+r*Math.sin(i)}`)}rect(t,n,r,a){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${r=+r}v${+a}h${-r}Z`}toString(){return this._}}function KIe(s){let t=3;return s.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);t=r}return s},()=>new NSs(t)}function YIe(s){return typeof s=="object"&&"length"in s?s:Array.from(s)}function Myt(s){this._context=s}Myt.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 Dve(s){return new Myt(s)}function Iyt(s){return s[0]}function Pyt(s){return s[1]}function Lyt(s,t){var n=xd(!0),r=null,a=Dve,i=null,l=KIe(o);s=typeof s=="function"?s:s===void 0?Iyt:xd(s),t=typeof t=="function"?t:t===void 0?Pyt:xd(t);function o(c){var d,u=(c=YIe(c)).length,h,p=!1,f;for(r==null&&(i=a(f=l())),d=0;d<=u;++d)!(d=f;--y)o.point(S[y],A[y]);o.lineEnd(),o.areaEnd()}j&&(S[p]=+s(v,p,h),A[p]=+t(v,p,h),o.point(r?+r(v,p,h):S[p],n?+n(v,p,h):A[p]))}if(w)return o=null,w+""||null}function u(){return Lyt().defined(a).curve(l).context(i)}return d.x=function(h){return arguments.length?(s=typeof h=="function"?h:xd(+h),r=null,d):s},d.x0=function(h){return arguments.length?(s=typeof h=="function"?h:xd(+h),d):s},d.x1=function(h){return arguments.length?(r=h==null?null:typeof h=="function"?h:xd(+h),d):r},d.y=function(h){return arguments.length?(t=typeof h=="function"?h:xd(+h),n=null,d):t},d.y0=function(h){return arguments.length?(t=typeof h=="function"?h:xd(+h),d):t},d.y1=function(h){return arguments.length?(n=h==null?null:typeof h=="function"?h:xd(+h),d):n},d.lineX0=d.lineY0=function(){return u().x(s).y(t)},d.lineY1=function(){return u().x(s).y(n)},d.lineX1=function(){return u().x(r).y(t)},d.defined=function(h){return arguments.length?(a=typeof h=="function"?h:xd(!!h),d):a},d.curve=function(h){return arguments.length?(l=h,i!=null&&(o=l(i)),d):l},d.context=function(h){return arguments.length?(h==null?i=o=null:o=l(i=h),d):i},d}class Dyt{constructor(t,n){this._context=t,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,n){switch(t=+t,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n);break}}this._x0=t,this._y0=n}}function kSs(s){return new Dyt(s,!0)}function SSs(s){return new Dyt(s,!1)}const ZIe={draw(s,t){const n=Lb(t/kxe);s.moveTo(n,0),s.arc(0,0,n,0,Lve)}},CSs={draw(s,t){const n=Lb(t/5)/2;s.moveTo(-3*n,-n),s.lineTo(-n,-n),s.lineTo(-n,-3*n),s.lineTo(n,-3*n),s.lineTo(n,-n),s.lineTo(3*n,-n),s.lineTo(3*n,n),s.lineTo(n,n),s.lineTo(n,3*n),s.lineTo(-n,3*n),s.lineTo(-n,n),s.lineTo(-3*n,n),s.closePath()}},Ryt=Lb(1/3),TSs=Ryt*2,ESs={draw(s,t){const n=Lb(t/TSs),r=n*Ryt;s.moveTo(0,-n),s.lineTo(r,0),s.lineTo(0,n),s.lineTo(-r,0),s.closePath()}},ASs={draw(s,t){const n=Lb(t),r=-n/2;s.rect(r,r,n,n)}},MSs=.8908130915292852,Oyt=Nxe(kxe/10)/Nxe(7*kxe/10),ISs=Nxe(Lve/10)*Oyt,PSs=-Eyt(Lve/10)*Oyt,LSs={draw(s,t){const n=Lb(t*MSs),r=ISs*n,a=PSs*n;s.moveTo(0,-n),s.lineTo(r,a);for(let i=1;i<5;++i){const l=Lve*i/5,o=Eyt(l),c=Nxe(l);s.lineTo(c*n,-o*n),s.lineTo(o*r-c*a,c*r+o*a)}s.closePath()}},M2e=Lb(3),DSs={draw(s,t){const n=-Lb(t/(M2e*3));s.moveTo(0,n*2),s.lineTo(-M2e*n,-n),s.lineTo(M2e*n,-n),s.closePath()}},nv=-.5,rv=Lb(3)/2,f3e=1/Lb(12),RSs=(f3e/2+1)*3,OSs={draw(s,t){const n=Lb(t/RSs),r=n/2,a=n*f3e,i=r,l=n*f3e+n,o=-i,c=l;s.moveTo(r,a),s.lineTo(i,l),s.lineTo(o,c),s.lineTo(nv*r-rv*a,rv*r+nv*a),s.lineTo(nv*i-rv*l,rv*i+nv*l),s.lineTo(nv*o-rv*c,rv*o+nv*c),s.lineTo(nv*r+rv*a,nv*a-rv*r),s.lineTo(nv*i+rv*l,nv*l-rv*i),s.lineTo(nv*o+rv*c,nv*c-rv*o),s.closePath()}};function FSs(s,t){let n=null,r=KIe(a);s=typeof s=="function"?s:xd(s||ZIe),t=typeof t=="function"?t:xd(t===void 0?64:+t);function a(){let i;if(n||(n=i=r()),s.apply(this,arguments).draw(n,+t.apply(this,arguments)),i)return n=null,i+""||null}return a.type=function(i){return arguments.length?(s=typeof i=="function"?i:xd(i),a):s},a.size=function(i){return arguments.length?(t=typeof i=="function"?i:xd(+i),a):t},a.context=function(i){return arguments.length?(n=i??null,a):n},a}function Sxe(){}function Cxe(s,t,n){s._context.bezierCurveTo((2*s._x0+s._x1)/3,(2*s._y0+s._y1)/3,(s._x0+2*s._x1)/3,(s._y0+2*s._y1)/3,(s._x0+4*s._x1+t)/6,(s._y0+4*s._y1+n)/6)}function Fyt(s){this._context=s}Fyt.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:Cxe(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:Cxe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function zSs(s){return new Fyt(s)}function zyt(s){this._context=s}zyt.prototype={areaStart:Sxe,areaEnd:Sxe,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:Cxe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function BSs(s){return new zyt(s)}function Byt(s){this._context=s}Byt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+s)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:Cxe(this,s,t);break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t}};function $Ss(s){return new Byt(s)}function $yt(s){this._context=s}$yt.prototype={areaStart:Sxe,areaEnd:Sxe,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 USs(s){return new $yt(s)}function nGe(s){return s<0?-1:1}function rGe(s,t,n){var r=s._x1-s._x0,a=t-s._x1,i=(s._y1-s._y0)/(r||a<0&&-0),l=(n-s._y1)/(a||r<0&&-0),o=(i*a+l*r)/(r+a);return(nGe(i)+nGe(l))*Math.min(Math.abs(i),Math.abs(l),.5*Math.abs(o))||0}function aGe(s,t){var n=s._x1-s._x0;return n?(3*(s._y1-s._y0)/n-t)/2:t}function I2e(s,t,n){var r=s._x0,a=s._y0,i=s._x1,l=s._y1,o=(i-r)/3;s._context.bezierCurveTo(r+o,a+o*t,i-o,l-o*n,i,l)}function Txe(s){this._context=s}Txe.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:I2e(this,this._t0,aGe(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(s,t){var n=NaN;if(s=+s,t=+t,!(s===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;break;case 2:this._point=3,I2e(this,aGe(this,n=rGe(this,s,t)),n);break;default:I2e(this,this._t0,n=rGe(this,s,t));break}this._x0=this._x1,this._x1=s,this._y0=this._y1,this._y1=t,this._t0=n}}};function Uyt(s){this._context=new qyt(s)}(Uyt.prototype=Object.create(Txe.prototype)).point=function(s,t){Txe.prototype.point.call(this,t,s)};function qyt(s){this._context=s}qyt.prototype={moveTo:function(s,t){this._context.moveTo(t,s)},closePath:function(){this._context.closePath()},lineTo:function(s,t){this._context.lineTo(t,s)},bezierCurveTo:function(s,t,n,r,a,i){this._context.bezierCurveTo(t,s,r,n,i,a)}};function qSs(s){return new Txe(s)}function VSs(s){return new Uyt(s)}function Vyt(s){this._context=s}Vyt.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var s=this._x,t=this._y,n=s.length;if(n)if(this._line?this._context.lineTo(s[0],t[0]):this._context.moveTo(s[0],t[0]),n===2)this._context.lineTo(s[1],t[1]);else for(var r=iGe(s),a=iGe(t),i=0,l=1;l=0;--t)a[t]=(l[t]-a[t+1])/i[t];for(i[n-1]=(s[n]+a[n-1])/2,t=0;t=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(s,t){switch(s=+s,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(s,t):this._context.moveTo(s,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(s,t);else{var n=this._x*(1-this._t)+s*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}}this._x=s,this._y=t}};function GSs(s){return new Rve(s,.5)}function WSs(s){return new Rve(s,0)}function KSs(s){return new Rve(s,1)}function M8(s,t){if((l=s.length)>1)for(var n=1,r,a,i=s[t[0]],l,o=i.length;n=0;)n[t]=t;return n}function YSs(s,t){return s[t]}function ZSs(s){const t=[];return t.key=s,t}function QSs(){var s=xd([]),t=x3e,n=M8,r=YSs;function a(i){var l=Array.from(s.apply(this,arguments),ZSs),o,c=l.length,d=-1,u;for(const h of i)for(o=0,++d;o0){for(var n,r,a=0,i=s[0].length,l;a0){for(var n=0,r=s[t[0]],a,i=r.length;n0)||!((i=(a=s[t[0]]).length)>0))){for(var n=0,r=1,a,i,l;r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function i4s(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var Hyt={symbolCircle:ZIe,symbolCross:CSs,symbolDiamond:ESs,symbolSquare:ASs,symbolStar:LSs,symbolTriangle:DSs,symbolWye:OSs},o4s=Math.PI/180,l4s=function(t){var n="symbol".concat(Pve(t));return Hyt[n]||ZIe},c4s=function(t,n,r){if(n==="area")return t;switch(r){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var a=18*o4s;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}},d4s=function(t,n){Hyt["symbol".concat(Pve(t))]=n},QIe=function(t){var n=t.type,r=n===void 0?"circle":n,a=t.size,i=a===void 0?64:a,l=t.sizeType,o=l===void 0?"area":l,c=a4s(t,t4s),d=lGe(lGe({},c),{},{type:r,size:i,sizeType:o}),u=function(){var v=l4s(r),j=FSs().type(v).size(c4s(i,o,r));return j()},h=d.className,p=d.cx,f=d.cy,y=$i(d,!0);return p===+p&&f===+f&&i===+i?Ct.createElement("path",g3e({},y,{className:So("recharts-symbols",h),transform:"translate(".concat(p,", ").concat(f,")"),d:u()})):null};QIe.registerSymbol=d4s;function I8(s){"@babel/helpers - typeof";return I8=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},I8(s)}function y3e(){return y3e=Object.assign?Object.assign.bind():function(s){for(var t=1;t`);var w=f.inactive?d:f.color;return Ct.createElement("li",y3e({className:v,style:h,key:"legend-item-".concat(y)},kM(r.props,f,y)),Ct.createElement(c3e,{width:l,height:l,viewBox:u,style:p},r.renderIcon(f)),Ct.createElement("span",{className:"recharts-legend-item-text",style:{color:w}},_?_(j,f,y):j))})}},{key:"render",value:function(){var r=this.props,a=r.payload,i=r.layout,l=r.align;if(!a||!a.length)return null;var o={padding:0,margin:0,textAlign:i==="horizontal"?l:"left"};return Ct.createElement("ul",{className:"recharts-default-legend",style:o},this.renderItems())}}])}(N.PureComponent);TB(XIe,"displayName","Legend");TB(XIe,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"middle",inactiveColor:"#ccc"});var b4s=bve;function _4s(){this.__data__=new b4s,this.size=0}var w4s=_4s;function j4s(s){var t=this.__data__,n=t.delete(s);return this.size=t.size,n}var N4s=j4s;function k4s(s){return this.__data__.get(s)}var S4s=k4s;function C4s(s){return this.__data__.has(s)}var T4s=C4s,E4s=bve,A4s=zIe,M4s=BIe,I4s=200;function P4s(s,t){var n=this.__data__;if(n instanceof E4s){var r=n.__data__;if(!A4s||r.lengtho))return!1;var d=i.get(s),u=i.get(t);if(d&&u)return d==t&&u==s;var h=-1,p=!0,f=n&tCs?new Q4s:void 0;for(i.set(s,t),i.set(t,s);++h-1&&s%1==0&&s-1&&s%1==0&&s<=a3s}var sPe=i3s,o3s=NN,l3s=sPe,c3s=kN,d3s="[object Arguments]",u3s="[object Array]",h3s="[object Boolean]",m3s="[object Date]",p3s="[object Error]",f3s="[object Function]",x3s="[object Map]",g3s="[object Number]",y3s="[object Object]",v3s="[object RegExp]",b3s="[object Set]",_3s="[object String]",w3s="[object WeakMap]",j3s="[object ArrayBuffer]",N3s="[object DataView]",k3s="[object Float32Array]",S3s="[object Float64Array]",C3s="[object Int8Array]",T3s="[object Int16Array]",E3s="[object Int32Array]",A3s="[object Uint8Array]",M3s="[object Uint8ClampedArray]",I3s="[object Uint16Array]",P3s="[object Uint32Array]",Id={};Id[k3s]=Id[S3s]=Id[C3s]=Id[T3s]=Id[E3s]=Id[A3s]=Id[M3s]=Id[I3s]=Id[P3s]=!0;Id[d3s]=Id[u3s]=Id[j3s]=Id[h3s]=Id[N3s]=Id[m3s]=Id[p3s]=Id[f3s]=Id[x3s]=Id[g3s]=Id[y3s]=Id[v3s]=Id[b3s]=Id[_3s]=Id[w3s]=!1;function L3s(s){return c3s(s)&&l3s(s.length)&&!!Id[o3s(s)]}var D3s=L3s;function R3s(s){return function(t){return s(t)}}var svt=R3s,Ixe={exports:{}};Ixe.exports;(function(s,t){var n=dyt,r=t&&!t.nodeType&&t,a=r&&!0&&s&&!s.nodeType&&s,i=a&&a.exports===r,l=i&&n.process,o=function(){try{var c=a&&a.require&&a.require("util").types;return c||l&&l.binding&&l.binding("util")}catch{}}();s.exports=o})(Ixe,Ixe.exports);var O3s=Ixe.exports,F3s=D3s,z3s=svt,fGe=O3s,xGe=fGe&&fGe.isTypedArray,B3s=xGe?z3s(xGe):F3s,nvt=B3s,$3s=VCs,U3s=ePe,q3s=r0,V3s=tvt,H3s=tPe,G3s=nvt,W3s=Object.prototype,K3s=W3s.hasOwnProperty;function Y3s(s,t){var n=q3s(s),r=!n&&U3s(s),a=!n&&!r&&V3s(s),i=!n&&!r&&!a&&G3s(s),l=n||r||a||i,o=l?$3s(s.length,String):[],c=o.length;for(var d in s)(t||K3s.call(s,d))&&!(l&&(d=="length"||a&&(d=="offset"||d=="parent")||i&&(d=="buffer"||d=="byteLength"||d=="byteOffset")||H3s(d,c)))&&o.push(d);return o}var Z3s=Y3s,Q3s=Object.prototype;function X3s(s){var t=s&&s.constructor,n=typeof t=="function"&&t.prototype||Q3s;return s===n}var J3s=X3s;function e5s(s,t){return function(n){return s(t(n))}}var rvt=e5s,t5s=rvt,s5s=t5s(Object.keys,Object),n5s=s5s,r5s=J3s,a5s=n5s,i5s=Object.prototype,o5s=i5s.hasOwnProperty;function l5s(s){if(!r5s(s))return a5s(s);var t=[];for(var n in Object(s))o5s.call(s,n)&&n!="constructor"&&t.push(n);return t}var c5s=l5s,d5s=OIe,u5s=sPe;function h5s(s){return s!=null&&u5s(s.length)&&!d5s(s)}var NU=h5s,m5s=Z3s,p5s=c5s,f5s=NU;function x5s(s){return f5s(s)?m5s(s):p5s(s)}var Ove=x5s,g5s=ICs,y5s=UCs,v5s=Ove;function b5s(s){return g5s(s,v5s,y5s)}var _5s=b5s,gGe=_5s,w5s=1,j5s=Object.prototype,N5s=j5s.hasOwnProperty;function k5s(s,t,n,r,a,i){var l=n&w5s,o=gGe(s),c=o.length,d=gGe(t),u=d.length;if(c!=u&&!l)return!1;for(var h=c;h--;){var p=o[h];if(!(l?p in t:N5s.call(t,p)))return!1}var f=i.get(s),y=i.get(t);if(f&&y)return f==t&&y==s;var _=!0;i.set(s,t),i.set(t,s);for(var v=l;++h-1}var jEs=wEs;function NEs(s,t,n){for(var r=-1,a=s==null?0:s.length;++r=zEs){var d=t?null:OEs(s);if(d)return FEs(d);l=!1,a=REs,c=new PEs}else c=t?[]:o;e:for(;++r=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function tAs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function sAs(s){return s.value}function nAs(s,t){if(Ct.isValidElement(s))return Ct.cloneElement(s,t);if(typeof s=="function")return Ct.createElement(s,t);t.ref;var n=eAs(t,GEs);return Ct.createElement(XIe,n)}var PGe=1,GA=function(s){function t(){var n;WEs(this,t);for(var r=arguments.length,a=new Array(r),i=0;iPGe||Math.abs(a.height-this.lastBoundingBox.height)>PGe)&&(this.lastBoundingBox.width=a.width,this.lastBoundingBox.height=a.height,r&&r(a)):(this.lastBoundingBox.width!==-1||this.lastBoundingBox.height!==-1)&&(this.lastBoundingBox.width=-1,this.lastBoundingBox.height=-1,r&&r(null))}},{key:"getBBoxSnapshot",value:function(){return this.lastBoundingBox.width>=0&&this.lastBoundingBox.height>=0?a2({},this.lastBoundingBox):{width:0,height:0}}},{key:"getDefaultPosition",value:function(r){var a=this.props,i=a.layout,l=a.align,o=a.verticalAlign,c=a.margin,d=a.chartWidth,u=a.chartHeight,h,p;if(!r||(r.left===void 0||r.left===null)&&(r.right===void 0||r.right===null))if(l==="center"&&i==="vertical"){var f=this.getBBoxSnapshot();h={left:((d||0)-f.width)/2}}else h=l==="right"?{right:c&&c.right||0}:{left:c&&c.left||0};if(!r||(r.top===void 0||r.top===null)&&(r.bottom===void 0||r.bottom===null))if(o==="middle"){var y=this.getBBoxSnapshot();p={top:((u||0)-y.height)/2}}else p=o==="bottom"?{bottom:c&&c.bottom||0}:{top:c&&c.top||0};return a2(a2({},h),p)}},{key:"render",value:function(){var r=this,a=this.props,i=a.content,l=a.width,o=a.height,c=a.wrapperStyle,d=a.payloadUniqBy,u=a.payload,h=a2(a2({position:"absolute",width:l||"auto",height:o||"auto"},this.getDefaultPosition(c)),c);return Ct.createElement("div",{className:"recharts-legend-wrapper",style:h,ref:function(f){r.wrapperNode=f}},nAs(i,a2(a2({},this.props),{},{payload:uvt(u,d,sAs)})))}}],[{key:"getWithHeight",value:function(r,a){var i=a2(a2({},this.defaultProps),r.props),l=i.layout;return l==="vertical"&&ia(r.props.height)?{height:r.props.height}:l==="horizontal"?{width:r.props.width||a}:null}}])}(N.PureComponent);Fve(GA,"displayName","Legend");Fve(GA,"defaultProps",{iconSize:14,layout:"horizontal",align:"center",verticalAlign:"bottom"});var LGe=wU,rAs=ePe,aAs=r0,DGe=LGe?LGe.isConcatSpreadable:void 0;function iAs(s){return aAs(s)||rAs(s)||!!(DGe&&s&&s[DGe])}var oAs=iAs,lAs=Jyt,cAs=oAs;function pvt(s,t,n,r,a){var i=-1,l=s.length;for(n||(n=cAs),a||(a=[]);++i0&&n(o)?t>1?pvt(o,t-1,n,r,a):lAs(a,o):r||(a[a.length]=o)}return a}var fvt=pvt;function dAs(s){return function(t,n,r){for(var a=-1,i=Object(t),l=r(t),o=l.length;o--;){var c=l[s?o:++a];if(n(i[c],c,i)===!1)break}return t}}var uAs=dAs,hAs=uAs,mAs=hAs(),pAs=mAs,fAs=pAs,xAs=Ove;function gAs(s,t){return s&&fAs(s,t,xAs)}var xvt=gAs,yAs=NU;function vAs(s,t){return function(n,r){if(n==null)return n;if(!yAs(n))return s(n,r);for(var a=n.length,i=t?a:-1,l=Object(n);(t?i--:++it||i&&l&&c&&!o&&!d||r&&l&&c||!n&&c||!a)return 1;if(!r&&!i&&!d&&s=o)return c;var d=n[r];return c*(d=="desc"?-1:1)}}return s.index-t.index}var PAs=IAs,R2e=UIe,LAs=qIe,DAs=Qw,RAs=gvt,OAs=TAs,FAs=svt,zAs=PAs,BAs=iR,$As=r0;function UAs(s,t,n){t.length?t=R2e(t,function(i){return $As(i)?function(l){return LAs(l,i.length===1?i[0]:i)}:i}):t=[BAs];var r=-1;t=R2e(t,FAs(DAs));var a=RAs(s,function(i,l,o){var c=R2e(t,function(d){return d(i)});return{criteria:c,index:++r,value:i}});return OAs(a,function(i,l){return zAs(i,l,n)})}var qAs=UAs;function VAs(s,t,n){switch(n.length){case 0:return s.call(t);case 1:return s.call(t,n[0]);case 2:return s.call(t,n[0],n[1]);case 3:return s.call(t,n[0],n[1],n[2])}return s.apply(t,n)}var HAs=VAs,GAs=HAs,OGe=Math.max;function WAs(s,t,n){return t=OGe(t===void 0?s.length-1:t,0),function(){for(var r=arguments,a=-1,i=OGe(r.length-t,0),l=Array(i);++a0){if(++t>=nMs)return arguments[0]}else t=0;return s.apply(void 0,arguments)}}var oMs=iMs,lMs=sMs,cMs=oMs,dMs=cMs(lMs),uMs=dMs,hMs=iR,mMs=KAs,pMs=uMs;function fMs(s,t){return pMs(mMs(s,t,hMs),s+"")}var xMs=fMs,gMs=FIe,yMs=NU,vMs=tPe,bMs=sC;function _Ms(s,t,n){if(!bMs(n))return!1;var r=typeof t;return(r=="number"?yMs(n)&&vMs(t,n.length):r=="string"&&t in n)?gMs(n[t],s):!1}var zve=_Ms,wMs=fvt,jMs=qAs,NMs=xMs,zGe=zve,kMs=NMs(function(s,t){if(s==null)return[];var n=t.length;return n>1&&zGe(s,t[0],t[1])?t=[]:n>2&&zGe(t[0],t[1],t[2])&&(t=[t[0]]),jMs(s,wMs(t,1),[])}),SMs=kMs;const aPe=_l(SMs);function EB(s){"@babel/helpers - typeof";return EB=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},EB(s)}function S3e(){return S3e=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=t.x),"".concat(gF,"-left"),ia(n)&&t&&ia(t.x)&&n=t.y),"".concat(gF,"-top"),ia(r)&&t&&ia(t.y)&&r_?Math.max(u,c[r]):Math.max(h,c[r])}function $Ms(s){var t=s.translateX,n=s.translateY,r=s.useTranslate3d;return{transform:r?"translate3d(".concat(t,"px, ").concat(n,"px, 0)"):"translate(".concat(t,"px, ").concat(n,"px)")}}function UMs(s){var t=s.allowEscapeViewBox,n=s.coordinate,r=s.offsetTopLeft,a=s.position,i=s.reverseDirection,l=s.tooltipBox,o=s.useTranslate3d,c=s.viewBox,d,u,h;return l.height>0&&l.width>0&&n?(u=UGe({allowEscapeViewBox:t,coordinate:n,key:"x",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.width,viewBox:c,viewBoxDimension:c.width}),h=UGe({allowEscapeViewBox:t,coordinate:n,key:"y",offsetTopLeft:r,position:a,reverseDirection:i,tooltipDimension:l.height,viewBox:c,viewBoxDimension:c.height}),d=$Ms({translateX:u,translateY:h,useTranslate3d:o})):d=zMs,{cssProperties:d,cssClasses:BMs({translateX:u,translateY:h,coordinate:n})}}function L8(s){"@babel/helpers - typeof";return L8=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},L8(s)}function qGe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function VGe(s){for(var t=1;tHGe||Math.abs(r.height-this.state.lastBoundingBox.height)>HGe)&&this.setState({lastBoundingBox:{width:r.width,height:r.height}})}else(this.state.lastBoundingBox.width!==-1||this.state.lastBoundingBox.height!==-1)&&this.setState({lastBoundingBox:{width:-1,height:-1}})}},{key:"componentDidMount",value:function(){document.addEventListener("keydown",this.handleKeyDown),this.updateBBox()}},{key:"componentWillUnmount",value:function(){document.removeEventListener("keydown",this.handleKeyDown)}},{key:"componentDidUpdate",value:function(){var r,a;this.props.active&&this.updateBBox(),this.state.dismissed&&(((r=this.props.coordinate)===null||r===void 0?void 0:r.x)!==this.state.dismissedAtCoordinate.x||((a=this.props.coordinate)===null||a===void 0?void 0:a.y)!==this.state.dismissedAtCoordinate.y)&&(this.state.dismissed=!1)}},{key:"render",value:function(){var r=this,a=this.props,i=a.active,l=a.allowEscapeViewBox,o=a.animationDuration,c=a.animationEasing,d=a.children,u=a.coordinate,h=a.hasPayload,p=a.isAnimationActive,f=a.offset,y=a.position,_=a.reverseDirection,v=a.useTranslate3d,j=a.viewBox,w=a.wrapperStyle,S=UMs({allowEscapeViewBox:l,coordinate:u,offsetTopLeft:f,position:y,reverseDirection:_,tooltipBox:this.state.lastBoundingBox,useTranslate3d:v,viewBox:j}),A=S.cssClasses,E=S.cssProperties,O=VGe(VGe({transition:p&&i?"transform ".concat(o,"ms ").concat(c):void 0},E),{},{pointerEvents:"none",visibility:!this.state.dismissed&&i&&h?"visible":"hidden",position:"absolute",top:0,left:0},w);return Ct.createElement("div",{tabIndex:-1,className:A,style:O,ref:function(I){r.wrapperNode=I}},d)}}])}(N.PureComponent),XMs=function(){return!(typeof window<"u"&&window.document&&window.document.createElement&&window.setTimeout)},_w={isSsr:XMs(),get:function(t){return _w[t]},set:function(t,n){if(typeof t=="string")_w[t]=n;else{var r=Object.keys(t);r&&r.length&&r.forEach(function(a){_w[a]=t[a]})}}};function D8(s){"@babel/helpers - typeof";return D8=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},D8(s)}function GGe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function WGe(s){for(var t=1;t0;return Ct.createElement(QMs,{allowEscapeViewBox:l,animationDuration:o,animationEasing:c,isAnimationActive:p,active:i,coordinate:u,hasPayload:O,offset:f,position:v,reverseDirection:j,useTranslate3d:w,viewBox:S,wrapperStyle:A},l6s(d,WGe(WGe({},this.props),{},{payload:E})))}}])}(N.PureComponent);iPe(_p,"displayName","Tooltip");iPe(_p,"defaultProps",{accessibilityLayer:!1,allowEscapeViewBox:{x:!1,y:!1},animationDuration:400,animationEasing:"ease",contentStyle:{},coordinate:{x:0,y:0},cursor:!0,cursorStyle:{},filterNull:!0,isAnimationActive:!_w.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 c6s=Zw,d6s=function(){return c6s.Date.now()},u6s=d6s,h6s=/\s/;function m6s(s){for(var t=s.length;t--&&h6s.test(s.charAt(t)););return t}var p6s=m6s,f6s=p6s,x6s=/^\s+/;function g6s(s){return s&&s.slice(0,f6s(s)+1).replace(x6s,"")}var y6s=g6s,v6s=y6s,KGe=sC,b6s=XD,YGe=NaN,_6s=/^[-+]0x[0-9a-f]+$/i,w6s=/^0b[01]+$/i,j6s=/^0o[0-7]+$/i,N6s=parseInt;function k6s(s){if(typeof s=="number")return s;if(b6s(s))return YGe;if(KGe(s)){var t=typeof s.valueOf=="function"?s.valueOf():s;s=KGe(t)?t+"":t}if(typeof s!="string")return s===0?s:+s;s=v6s(s);var n=w6s.test(s);return n||j6s.test(s)?N6s(s.slice(2),n?2:8):_6s.test(s)?YGe:+s}var jvt=k6s,S6s=sC,F2e=u6s,ZGe=jvt,C6s="Expected a function",T6s=Math.max,E6s=Math.min;function A6s(s,t,n){var r,a,i,l,o,c,d=0,u=!1,h=!1,p=!0;if(typeof s!="function")throw new TypeError(C6s);t=ZGe(t)||0,S6s(n)&&(u=!!n.leading,h="maxWait"in n,i=h?T6s(ZGe(n.maxWait)||0,t):i,p="trailing"in n?!!n.trailing:p);function f(O){var D=r,I=a;return r=a=void 0,d=O,l=s.apply(I,D),l}function y(O){return d=O,o=setTimeout(j,t),u?f(O):l}function _(O){var D=O-c,I=O-d,F=t-D;return h?E6s(F,i-I):F}function v(O){var D=O-c,I=O-d;return c===void 0||D>=t||D<0||h&&I>=i}function j(){var O=F2e();if(v(O))return w(O);o=setTimeout(j,_(O))}function w(O){return o=void 0,p&&r?f(O):(r=a=void 0,l)}function S(){o!==void 0&&clearTimeout(o),d=0,r=c=a=o=void 0}function A(){return o===void 0?l:w(F2e())}function E(){var O=F2e(),D=v(O);if(r=arguments,a=this,c=O,D){if(o===void 0)return y(c);if(h)return clearTimeout(o),o=setTimeout(j,t),f(c)}return o===void 0&&(o=setTimeout(j,t)),l}return E.cancel=S,E.flush=A,E}var M6s=A6s,I6s=M6s,P6s=sC,L6s="Expected a function";function D6s(s,t,n){var r=!0,a=!0;if(typeof s!="function")throw new TypeError(L6s);return P6s(n)&&(r="leading"in n?!!n.leading:r,a="trailing"in n?!!n.trailing:a),I6s(s,t,{leading:r,maxWait:t,trailing:a})}var R6s=D6s;const Nvt=_l(R6s);function MB(s){"@babel/helpers - typeof";return MB=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},MB(s)}function QGe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function VH(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&(Y=Nvt(Y,_,{trailing:!0,leading:!1}));var W=new ResizeObserver(Y),ee=E.current.getBoundingClientRect(),se=ee.width,oe=ee.height;return H(se,oe),W.observe(E.current),function(){W.disconnect()}},[H,_]);var Z=N.useMemo(function(){var Y=F.containerWidth,W=F.containerHeight;if(Y<0||W<0)return null;bb(YE(l)||YE(c),`The width(%s) and height(%s) are both fixed numbers, maybe you don't need to use a ResponsiveContainer.`,l,c),bb(!n||n>0,"The aspect(%s) must be greater than zero.",n);var ee=YE(l)?Y:l,se=YE(c)?W:c;n&&n>0&&(ee?se=ee/n:se&&(ee=se*n),p&&se>p&&(se=p)),bb(ee>0||se>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.`,ee,se,l,c,u,h,n);var oe=!Array.isArray(f)&&X2(f.type).endsWith("Chart");return Ct.Children.map(f,function(he){return Ct.isValidElement(he)?N.cloneElement(he,VH({width:ee,height:se},oe?{style:VH({height:"100%",width:"100%",maxHeight:se,maxWidth:ee},he.props.style)}:{})):he})},[n,f,c,p,h,u,F,l]);return Ct.createElement("div",{id:v?"".concat(v):void 0,className:So("recharts-responsive-container",j),style:VH(VH({},A),{},{width:l,height:c,minWidth:u,minHeight:h,maxHeight:p}),ref:E},Z)}),oR=function(t){return null};oR.displayName="Cell";function IB(s){"@babel/helpers - typeof";return IB=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},IB(s)}function JGe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function A3e(s){for(var t=1;t1&&arguments[1]!==void 0?arguments[1]:{};if(t==null||_w.isSsr)return{width:0,height:0};var r=Z6s(n),a=JSON.stringify({text:t,copyStyle:r});if(EI.widthCache[a])return EI.widthCache[a];try{var i=document.getElementById(eWe);i||(i=document.createElement("span"),i.setAttribute("id",eWe),i.setAttribute("aria-hidden","true"),document.body.appendChild(i));var l=A3e(A3e({},Y6s),r);Object.assign(i.style,l),i.textContent="".concat(t);var o=i.getBoundingClientRect(),c={width:o.width,height:o.height};return EI.widthCache[a]=c,++EI.cacheCount>K6s&&(EI.cacheCount=0,EI.widthCache={}),c}catch{return{width:0,height:0}}},Q6s=function(t){return{top:t.top+window.scrollY-document.documentElement.clientTop,left:t.left+window.scrollX-document.documentElement.clientLeft}};function PB(s){"@babel/helpers - typeof";return PB=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},PB(s)}function Rxe(s,t){return tIs(s)||eIs(s,t)||J6s(s,t)||X6s()}function X6s(){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 J6s(s,t){if(s){if(typeof s=="string")return tWe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return tWe(s,t)}}function tWe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function fIs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function oWe(s,t){return vIs(s)||yIs(s,t)||gIs(s,t)||xIs()}function xIs(){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 gIs(s,t){if(s){if(typeof s=="string")return lWe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return lWe(s,t)}}function lWe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[];return ee.reduce(function(se,oe){var he=oe.word,ce=oe.width,me=se[se.length-1];if(me&&(a==null||i||me.width+ce+roe.width?se:oe})};if(!u)return f;for(var _="…",v=function(ee){var se=h.slice(0,ee),oe=Tvt({breakAll:d,style:c,children:se+_}).wordsWithComputedWidth,he=p(oe),ce=he.length>l||y(he).width>Number(a);return[ce,he]},j=0,w=h.length-1,S=0,A;j<=w&&S<=h.length-1;){var E=Math.floor((j+w)/2),O=E-1,D=v(O),I=oWe(D,2),F=I[0],z=I[1],H=v(E),Z=oWe(H,1),Y=Z[0];if(!F&&!Y&&(j=E+1),F&&Y&&(w=E-1),!F&&Y){A=z;break}S++}return A||f},cWe=function(t){var n=jo(t)?[]:t.toString().split(Cvt);return[{words:n}]},_Is=function(t){var n=t.width,r=t.scaleToFit,a=t.children,i=t.style,l=t.breakAll,o=t.maxLines;if((n||r)&&!_w.isSsr){var c,d,u=Tvt({breakAll:l,children:a,style:i});if(u){var h=u.wordsWithComputedWidth,p=u.spaceWidth;c=h,d=p}else return cWe(a);return bIs({breakAll:l,children:a,maxLines:o,style:i},c,d,n,r)}return cWe(a)},dWe="#808080",SM=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.lineHeight,o=l===void 0?"1em":l,c=t.capHeight,d=c===void 0?"0.71em":c,u=t.scaleToFit,h=u===void 0?!1:u,p=t.textAnchor,f=p===void 0?"start":p,y=t.verticalAnchor,_=y===void 0?"end":y,v=t.fill,j=v===void 0?dWe:v,w=iWe(t,mIs),S=N.useMemo(function(){return _Is({breakAll:w.breakAll,children:w.children,maxLines:w.maxLines,scaleToFit:h,style:w.style,width:w.width})},[w.breakAll,w.children,w.maxLines,h,w.style,w.width]),A=w.dx,E=w.dy,O=w.angle,D=w.className,I=w.breakAll,F=iWe(w,pIs);if(!Om(r)||!Om(i))return null;var z=r+(ia(A)?A:0),H=i+(ia(E)?E:0),Z;switch(_){case"start":Z=z2e("calc(".concat(d,")"));break;case"middle":Z=z2e("calc(".concat((S.length-1)/2," * -").concat(o," + (").concat(d," / 2))"));break;default:Z=z2e("calc(".concat(S.length-1," * -").concat(o,")"));break}var Y=[];if(h){var W=S[0].width,ee=w.width;Y.push("scale(".concat((ia(ee)?ee/W:1)/W,")"))}return O&&Y.push("rotate(".concat(O,", ").concat(z,", ").concat(H,")")),Y.length&&(F.transform=Y.join(" ")),Ct.createElement("text",M3e({},$i(F,!0),{x:z,y:H,className:So("recharts-text",D),textAnchor:f,fill:j.includes("url")?dWe:j}),S.map(function(se,oe){var he=se.words.join(I?"":" ");return Ct.createElement("tspan",{x:z,dy:oe===0?Z:o,key:"".concat(he,"-").concat(oe)},he)}))};function p4(s,t){return s==null||t==null?NaN:st?1:s>=t?0:NaN}function wIs(s,t){return s==null||t==null?NaN:ts?1:t>=s?0:NaN}function oPe(s){let t,n,r;s.length!==2?(t=p4,n=(o,c)=>p4(s(o),c),r=(o,c)=>s(o)-c):(t=s===p4||s===wIs?s:jIs,n=s,r=s);function a(o,c,d=0,u=o.length){if(d>>1;n(o[h],c)<0?d=h+1:u=h}while(d>>1;n(o[h],c)<=0?d=h+1:u=h}while(dd&&r(o[h-1],c)>-r(o[h],c)?h-1:h}return{left:a,center:l,right:i}}function jIs(){return 0}function Evt(s){return s===null?NaN:+s}function*NIs(s,t){for(let n of s)n!=null&&(n=+n)>=n&&(yield n)}const kIs=oPe(p4),kU=kIs.right;oPe(Evt).center;class uWe extends Map{constructor(t,n=TIs){if(super(),Object.defineProperties(this,{_intern:{value:new Map},_key:{value:n}}),t!=null)for(const[r,a]of t)this.set(r,a)}get(t){return super.get(hWe(this,t))}has(t){return super.has(hWe(this,t))}set(t,n){return super.set(SIs(this,t),n)}delete(t){return super.delete(CIs(this,t))}}function hWe({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):n}function SIs({_intern:s,_key:t},n){const r=t(n);return s.has(r)?s.get(r):(s.set(r,n),n)}function CIs({_intern:s,_key:t},n){const r=t(n);return s.has(r)&&(n=s.get(r),s.delete(r)),n}function TIs(s){return s!==null&&typeof s=="object"?s.valueOf():s}function EIs(s=p4){if(s===p4)return Avt;if(typeof s!="function")throw new TypeError("compare is not a function");return(t,n)=>{const r=s(t,n);return r||r===0?r:(s(n,n)===0)-(s(t,t)===0)}}function Avt(s,t){return(s==null||!(s>=s))-(t==null||!(t>=t))||(st?1:0)}const AIs=Math.sqrt(50),MIs=Math.sqrt(10),IIs=Math.sqrt(2);function Oxe(s,t,n){const r=(t-s)/Math.max(0,n),a=Math.floor(Math.log10(r)),i=r/Math.pow(10,a),l=i>=AIs?10:i>=MIs?5:i>=IIs?2:1;let o,c,d;return a<0?(d=Math.pow(10,-a)/l,o=Math.round(s*d),c=Math.round(t*d),o/dt&&--c,d=-d):(d=Math.pow(10,a)*l,o=Math.round(s/d),c=Math.round(t/d),o*dt&&--c),c0))return[];if(s===t)return[s];const r=t=a))return[];const o=i-a+1,c=new Array(o);if(r)if(l<0)for(let d=0;d=r)&&(n=r);return n}function pWe(s,t){let n;for(const r of s)r!=null&&(n>r||n===void 0&&r>=r)&&(n=r);return n}function Mvt(s,t,n=0,r=1/0,a){if(t=Math.floor(t),n=Math.floor(Math.max(0,n)),r=Math.floor(Math.min(s.length-1,r)),!(n<=t&&t<=r))return s;for(a=a===void 0?Avt:EIs(a);r>n;){if(r-n>600){const c=r-n+1,d=t-n+1,u=Math.log(c),h=.5*Math.exp(2*u/3),p=.5*Math.sqrt(u*h*(c-h)/c)*(d-c/2<0?-1:1),f=Math.max(n,Math.floor(t-d*h/c+p)),y=Math.min(r,Math.floor(t+(c-d)*h/c+p));Mvt(s,t,f,y,a)}const i=s[t];let l=n,o=r;for(yF(s,n,t),a(s[r],i)>0&&yF(s,n,r);l0;)--o}a(s[n],i)===0?yF(s,n,o):(++o,yF(s,o,r)),o<=t&&(n=o+1),t<=o&&(r=o-1)}return s}function yF(s,t,n){const r=s[t];s[t]=s[n],s[n]=r}function PIs(s,t,n){if(s=Float64Array.from(NIs(s)),!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return pWe(s);if(t>=1)return mWe(s);var r,a=(r-1)*t,i=Math.floor(a),l=mWe(Mvt(s,i).subarray(0,i+1)),o=pWe(s.subarray(i+1));return l+(o-l)*(a-i)}}function LIs(s,t,n=Evt){if(!(!(r=s.length)||isNaN(t=+t))){if(t<=0||r<2)return+n(s[0],0,s);if(t>=1)return+n(s[r-1],r-1,s);var r,a=(r-1)*t,i=Math.floor(a),l=+n(s[i],i,s),o=+n(s[i+1],i+1,s);return l+(o-l)*(a-i)}}function DIs(s,t,n){s=+s,t=+t,n=(a=arguments.length)<2?(t=s,s=0,1):a<3?1:+n;for(var r=-1,a=Math.max(0,Math.ceil((t-s)/n))|0,i=new Array(a);++r>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?GH(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?GH(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=OIs.exec(s))?new Rg(t[1],t[2],t[3],1):(t=FIs.exec(s))?new Rg(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=zIs.exec(s))?GH(t[1],t[2],t[3],t[4]):(t=BIs.exec(s))?GH(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=$Is.exec(s))?_We(t[1],t[2]/100,t[3]/100,1):(t=UIs.exec(s))?_We(t[1],t[2]/100,t[3]/100,t[4]):fWe.hasOwnProperty(s)?yWe(fWe[s]):s==="transparent"?new Rg(NaN,NaN,NaN,0):null}function yWe(s){return new Rg(s>>16&255,s>>8&255,s&255,1)}function GH(s,t,n,r){return r<=0&&(s=t=n=NaN),new Rg(s,t,n,r)}function HIs(s){return s instanceof SU||(s=OB(s)),s?(s=s.rgb(),new Rg(s.r,s.g,s.b,s.opacity)):new Rg}function R3e(s,t,n,r){return arguments.length===1?HIs(s):new Rg(s,t,n,r??1)}function Rg(s,t,n,r){this.r=+s,this.g=+t,this.b=+n,this.opacity=+r}cPe(Rg,R3e,Pvt(SU,{brighter(s){return s=s==null?Fxe:Math.pow(Fxe,s),new Rg(this.r*s,this.g*s,this.b*s,this.opacity)},darker(s){return s=s==null?DB:Math.pow(DB,s),new Rg(this.r*s,this.g*s,this.b*s,this.opacity)},rgb(){return this},clamp(){return new Rg(WA(this.r),WA(this.g),WA(this.b),zxe(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:vWe,formatHex:vWe,formatHex8:GIs,formatRgb:bWe,toString:bWe}));function vWe(){return`#${ZE(this.r)}${ZE(this.g)}${ZE(this.b)}`}function GIs(){return`#${ZE(this.r)}${ZE(this.g)}${ZE(this.b)}${ZE((isNaN(this.opacity)?1:this.opacity)*255)}`}function bWe(){const s=zxe(this.opacity);return`${s===1?"rgb(":"rgba("}${WA(this.r)}, ${WA(this.g)}, ${WA(this.b)}${s===1?")":`, ${s})`}`}function zxe(s){return isNaN(s)?1:Math.max(0,Math.min(1,s))}function WA(s){return Math.max(0,Math.min(255,Math.round(s)||0))}function ZE(s){return s=WA(s),(s<16?"0":"")+s.toString(16)}function _We(s,t,n,r){return r<=0?s=t=n=NaN:n<=0||n>=1?s=t=NaN:t<=0&&(s=NaN),new nb(s,t,n,r)}function Lvt(s){if(s instanceof nb)return new nb(s.h,s.s,s.l,s.opacity);if(s instanceof SU||(s=OB(s)),!s)return new nb;if(s instanceof nb)return s;s=s.rgb();var t=s.r/255,n=s.g/255,r=s.b/255,a=Math.min(t,n,r),i=Math.max(t,n,r),l=NaN,o=i-a,c=(i+a)/2;return o?(t===i?l=(n-r)/o+(n0&&c<1?0:l,new nb(l,o,c,s.opacity)}function WIs(s,t,n,r){return arguments.length===1?Lvt(s):new nb(s,t,n,r??1)}function nb(s,t,n,r){this.h=+s,this.s=+t,this.l=+n,this.opacity=+r}cPe(nb,WIs,Pvt(SU,{brighter(s){return s=s==null?Fxe:Math.pow(Fxe,s),new nb(this.h,this.s,this.l*s,this.opacity)},darker(s){return s=s==null?DB:Math.pow(DB,s),new nb(this.h,this.s,this.l*s,this.opacity)},rgb(){var s=this.h%360+(this.h<0)*360,t=isNaN(s)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,a=2*n-r;return new Rg(B2e(s>=240?s-240:s+120,a,r),B2e(s,a,r),B2e(s<120?s+240:s-120,a,r),this.opacity)},clamp(){return new nb(wWe(this.h),WH(this.s),WH(this.l),zxe(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=zxe(this.opacity);return`${s===1?"hsl(":"hsla("}${wWe(this.h)}, ${WH(this.s)*100}%, ${WH(this.l)*100}%${s===1?")":`, ${s})`}`}}));function wWe(s){return s=(s||0)%360,s<0?s+360:s}function WH(s){return Math.max(0,Math.min(1,s||0))}function B2e(s,t,n){return(s<60?t+(n-t)*s/60:s<180?n:s<240?t+(n-t)*(240-s)/60:t)*255}const dPe=s=>()=>s;function KIs(s,t){return function(n){return s+n*t}}function YIs(s,t,n){return s=Math.pow(s,n),t=Math.pow(t,n)-s,n=1/n,function(r){return Math.pow(s+r*t,n)}}function ZIs(s){return(s=+s)==1?Dvt:function(t,n){return n-t?YIs(t,n,s):dPe(isNaN(t)?n:t)}}function Dvt(s,t){var n=t-s;return n?KIs(s,n):dPe(isNaN(s)?t:s)}const jWe=function s(t){var n=ZIs(t);function r(a,i){var l=n((a=R3e(a)).r,(i=R3e(i)).r),o=n(a.g,i.g),c=n(a.b,i.b),d=Dvt(a.opacity,i.opacity);return function(u){return a.r=l(u),a.g=o(u),a.b=c(u),a.opacity=d(u),a+""}}return r.gamma=s,r}(1);function QIs(s,t){t||(t=[]);var n=s?Math.min(t.length,s.length):0,r=t.slice(),a;return function(i){for(a=0;an&&(i=t.slice(n,i),o[l]?o[l]+=i:o[++l]=i),(r=r[0])===(a=a[0])?o[l]?o[l]+=a:o[++l]=a:(o[++l]=null,c.push({i:l,x:Bxe(r,a)})),n=$2e.lastIndex;return nt&&(n=s,s=t,t=n),function(r){return Math.max(s,Math.min(t,r))}}function lPs(s,t,n){var r=s[0],a=s[1],i=t[0],l=t[1];return a2?cPs:lPs,c=d=null,h}function h(p){return p==null||isNaN(p=+p)?i:(c||(c=o(s.map(r),t,n)))(r(l(p)))}return h.invert=function(p){return l(a((d||(d=o(t,s.map(r),Bxe)))(p)))},h.domain=function(p){return arguments.length?(s=Array.from(p,$xe),u()):s.slice()},h.range=function(p){return arguments.length?(t=Array.from(p),u()):t.slice()},h.rangeRound=function(p){return t=Array.from(p),n=uPe,u()},h.clamp=function(p){return arguments.length?(l=p?!0:Qx,u()):l!==Qx},h.interpolate=function(p){return arguments.length?(n=p,u()):n},h.unknown=function(p){return arguments.length?(i=p,h):i},function(p,f){return r=p,a=f,u()}}function hPe(){return Bve()(Qx,Qx)}function dPs(s){return Math.abs(s=Math.round(s))>=1e21?s.toLocaleString("en").replace(/,/g,""):s.toString(10)}function Uxe(s,t){if((n=(s=t?s.toExponential(t-1):s.toExponential()).indexOf("e"))<0)return null;var n,r=s.slice(0,n);return[r.length>1?r[0]+r.slice(2):r,+s.slice(n+1)]}function R8(s){return s=Uxe(Math.abs(s)),s?s[1]:NaN}function uPs(s,t){return function(n,r){for(var a=n.length,i=[],l=0,o=s[0],c=0;a>0&&o>0&&(c+o+1>r&&(o=Math.max(1,r-c)),i.push(n.substring(a-=o,a+o)),!((c+=o+1)>r));)o=s[l=(l+1)%s.length];return i.reverse().join(t)}}function hPs(s){return function(t){return t.replace(/[0-9]/g,function(n){return s[+n]})}}var mPs=/^(?:(.)?([<>=^]))?([+\-( ])?([$#])?(0)?(\d+)?(,)?(\.\d+)?(~)?([a-z%])?$/i;function FB(s){if(!(t=mPs.exec(s)))throw new Error("invalid format: "+s);var t;return new mPe({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]})}FB.prototype=mPe.prototype;function mPe(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+""}mPe.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 pPs(s){e:for(var t=s.length,n=1,r=-1,a;n0&&(r=0);break}return r>0?s.slice(0,r)+s.slice(a+1):s}var Rvt;function fPs(s,t){var n=Uxe(s,t);if(!n)return s+"";var r=n[0],a=n[1],i=a-(Rvt=Math.max(-8,Math.min(8,Math.floor(a/3)))*3)+1,l=r.length;return i===l?r:i>l?r+new Array(i-l+1).join("0"):i>0?r.slice(0,i)+"."+r.slice(i):"0."+new Array(1-i).join("0")+Uxe(s,Math.max(0,t+i-1))[0]}function kWe(s,t){var n=Uxe(s,t);if(!n)return s+"";var r=n[0],a=n[1];return a<0?"0."+new Array(-a).join("0")+r:r.length>a+1?r.slice(0,a+1)+"."+r.slice(a+1):r+new Array(a-r.length+2).join("0")}const SWe={"%":(s,t)=>(s*100).toFixed(t),b:s=>Math.round(s).toString(2),c:s=>s+"",d:dPs,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)=>kWe(s*100,t),r:kWe,s:fPs,X:s=>Math.round(s).toString(16).toUpperCase(),x:s=>Math.round(s).toString(16)};function CWe(s){return s}var TWe=Array.prototype.map,EWe=["y","z","a","f","p","n","µ","m","","k","M","G","T","P","E","Z","Y"];function xPs(s){var t=s.grouping===void 0||s.thousands===void 0?CWe:uPs(TWe.call(s.grouping,Number),s.thousands+""),n=s.currency===void 0?"":s.currency[0]+"",r=s.currency===void 0?"":s.currency[1]+"",a=s.decimal===void 0?".":s.decimal+"",i=s.numerals===void 0?CWe:hPs(TWe.call(s.numerals,String)),l=s.percent===void 0?"%":s.percent+"",o=s.minus===void 0?"−":s.minus+"",c=s.nan===void 0?"NaN":s.nan+"";function d(h){h=FB(h);var p=h.fill,f=h.align,y=h.sign,_=h.symbol,v=h.zero,j=h.width,w=h.comma,S=h.precision,A=h.trim,E=h.type;E==="n"?(w=!0,E="g"):SWe[E]||(S===void 0&&(S=12),A=!0,E="g"),(v||p==="0"&&f==="=")&&(v=!0,p="0",f="=");var O=_==="$"?n:_==="#"&&/[boxX]/.test(E)?"0"+E.toLowerCase():"",D=_==="$"?r:/[%p]/.test(E)?l:"",I=SWe[E],F=/[defgprs%]/.test(E);S=S===void 0?6:/[gprs]/.test(E)?Math.max(1,Math.min(21,S)):Math.max(0,Math.min(20,S));function z(H){var Z=O,Y=D,W,ee,se;if(E==="c")Y=I(H)+Y,H="";else{H=+H;var oe=H<0||1/H<0;if(H=isNaN(H)?c:I(Math.abs(H),S),A&&(H=pPs(H)),oe&&+H==0&&y!=="+"&&(oe=!1),Z=(oe?y==="("?y:o:y==="-"||y==="("?"":y)+Z,Y=(E==="s"?EWe[8+Rvt/3]:"")+Y+(oe&&y==="("?")":""),F){for(W=-1,ee=H.length;++Wse||se>57){Y=(se===46?a+H.slice(W+1):H.slice(W))+Y,H=H.slice(0,W);break}}}w&&!v&&(H=t(H,1/0));var he=Z.length+H.length+Y.length,ce=he>1)+Z+H+Y+ce.slice(he);break;default:H=ce+Z+H+Y;break}return i(H)}return z.toString=function(){return h+""},z}function u(h,p){var f=d((h=FB(h),h.type="f",h)),y=Math.max(-8,Math.min(8,Math.floor(R8(p)/3)))*3,_=Math.pow(10,-y),v=EWe[8+y/3];return function(j){return f(_*j)+v}}return{format:d,formatPrefix:u}}var KH,pPe,Ovt;gPs({thousands:",",grouping:[3],currency:["$",""]});function gPs(s){return KH=xPs(s),pPe=KH.format,Ovt=KH.formatPrefix,KH}function yPs(s){return Math.max(0,-R8(Math.abs(s)))}function vPs(s,t){return Math.max(0,Math.max(-8,Math.min(8,Math.floor(R8(t)/3)))*3-R8(Math.abs(s)))}function bPs(s,t){return s=Math.abs(s),t=Math.abs(t)-s,Math.max(0,R8(t)-R8(s))+1}function Fvt(s,t,n,r){var a=L3e(s,t,n),i;switch(r=FB(r??",f"),r.type){case"s":{var l=Math.max(Math.abs(s),Math.abs(t));return r.precision==null&&!isNaN(i=vPs(a,l))&&(r.precision=i),Ovt(r,l)}case"":case"e":case"g":case"p":case"r":{r.precision==null&&!isNaN(i=bPs(a,Math.max(Math.abs(s),Math.abs(t))))&&(r.precision=i-(r.type==="e"));break}case"f":case"%":{r.precision==null&&!isNaN(i=yPs(a))&&(r.precision=i-(r.type==="%")*2);break}}return pPe(r)}function nC(s){var t=s.domain;return s.ticks=function(n){var r=t();return I3e(r[0],r[r.length-1],n??10)},s.tickFormat=function(n,r){var a=t();return Fvt(a[0],a[a.length-1],n??10,r)},s.nice=function(n){n==null&&(n=10);var r=t(),a=0,i=r.length-1,l=r[a],o=r[i],c,d,u=10;for(o0;){if(d=P3e(l,o,n),d===c)return r[a]=l,r[i]=o,t(r);if(d>0)l=Math.floor(l/d)*d,o=Math.ceil(o/d)*d;else if(d<0)l=Math.ceil(l*d)/d,o=Math.floor(o*d)/d;else break;c=d}return s},s}function qxe(){var s=hPe();return s.copy=function(){return CU(s,qxe())},Qv.apply(s,arguments),nC(s)}function zvt(s){var t;function n(r){return r==null||isNaN(r=+r)?t:r}return n.invert=n,n.domain=n.range=function(r){return arguments.length?(s=Array.from(r,$xe),n):s.slice()},n.unknown=function(r){return arguments.length?(t=r,n):t},n.copy=function(){return zvt(s).unknown(t)},s=arguments.length?Array.from(s,$xe):[0,1],nC(n)}function Bvt(s,t){s=s.slice();var n=0,r=s.length-1,a=s[n],i=s[r],l;return iMath.pow(s,t)}function kPs(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 IWe(s){return(t,n)=>-s(-t,n)}function fPe(s){const t=s(AWe,MWe),n=t.domain;let r=10,a,i;function l(){return a=kPs(r),i=NPs(r),n()[0]<0?(a=IWe(a),i=IWe(i),s(_Ps,wPs)):s(AWe,MWe),t}return t.base=function(o){return arguments.length?(r=+o,l()):r},t.domain=function(o){return arguments.length?(n(o),l()):n()},t.ticks=o=>{const c=n();let d=c[0],u=c[c.length-1];const h=u0){for(;p<=f;++p)for(y=1;yu)break;j.push(_)}}else for(;p<=f;++p)for(y=r-1;y>=1;--y)if(_=p>0?y/i(-p):y*i(p),!(_u)break;j.push(_)}j.length*2{if(o==null&&(o=10),c==null&&(c=r===10?"s":","),typeof c!="function"&&(!(r%1)&&(c=FB(c)).precision==null&&(c.trim=!0),c=pPe(c)),o===1/0)return c;const d=Math.max(1,r*o/t.ticks().length);return u=>{let h=u/i(Math.round(a(u)));return h*rn(Bvt(n(),{floor:o=>i(Math.floor(a(o))),ceil:o=>i(Math.ceil(a(o)))})),t}function $vt(){const s=fPe(Bve()).domain([1,10]);return s.copy=()=>CU(s,$vt()).base(s.base()),Qv.apply(s,arguments),s}function PWe(s){return function(t){return Math.sign(t)*Math.log1p(Math.abs(t/s))}}function LWe(s){return function(t){return Math.sign(t)*Math.expm1(Math.abs(t))*s}}function xPe(s){var t=1,n=s(PWe(t),LWe(t));return n.constant=function(r){return arguments.length?s(PWe(t=+r),LWe(t)):t},nC(n)}function Uvt(){var s=xPe(Bve());return s.copy=function(){return CU(s,Uvt()).constant(s.constant())},Qv.apply(s,arguments)}function DWe(s){return function(t){return t<0?-Math.pow(-t,s):Math.pow(t,s)}}function SPs(s){return s<0?-Math.sqrt(-s):Math.sqrt(s)}function CPs(s){return s<0?-s*s:s*s}function gPe(s){var t=s(Qx,Qx),n=1;function r(){return n===1?s(Qx,Qx):n===.5?s(SPs,CPs):s(DWe(n),DWe(1/n))}return t.exponent=function(a){return arguments.length?(n=+a,r()):n},nC(t)}function yPe(){var s=gPe(Bve());return s.copy=function(){return CU(s,yPe()).exponent(s.exponent())},Qv.apply(s,arguments),s}function TPs(){return yPe.apply(null,arguments).exponent(.5)}function RWe(s){return Math.sign(s)*s*s}function EPs(s){return Math.sign(s)*Math.sqrt(Math.abs(s))}function qvt(){var s=hPe(),t=[0,1],n=!1,r;function a(i){var l=EPs(s(i));return isNaN(l)?r:n?Math.round(l):l}return a.invert=function(i){return s.invert(RWe(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,$xe)).map(RWe)),a):t.slice()},a.rangeRound=function(i){return a.range(i).round(!0)},a.round=function(i){return arguments.length?(n=!!i,a):n},a.clamp=function(i){return arguments.length?(s.clamp(i),a):s.clamp()},a.unknown=function(i){return arguments.length?(r=i,a):r},a.copy=function(){return qvt(s.domain(),t).round(n).clamp(s.clamp()).unknown(r)},Qv.apply(a,arguments),nC(a)}function Vvt(){var s=[],t=[],n=[],r;function a(){var l=0,o=Math.max(1,t.length);for(n=new Array(o-1);++l0?n[o-1]:s[0],o=n?[r[n-1],t]:[r[d-1],r[d]]},l.unknown=function(c){return arguments.length&&(i=c),l},l.thresholds=function(){return r.slice()},l.copy=function(){return Hvt().domain([s,t]).range(a).unknown(i)},Qv.apply(nC(l),arguments)}function Gvt(){var s=[.5],t=[0,1],n,r=1;function a(i){return i!=null&&i<=i?t[kU(s,i,0,r)]:n}return a.domain=function(i){return arguments.length?(s=Array.from(i),r=Math.min(s.length,t.length-1),a):s.slice()},a.range=function(i){return arguments.length?(t=Array.from(i),r=Math.min(s.length,t.length-1),a):t.slice()},a.invertExtent=function(i){var l=t.indexOf(i);return[s[l-1],s[l]]},a.unknown=function(i){return arguments.length?(n=i,a):n},a.copy=function(){return Gvt().domain(s).range(t).unknown(n)},Qv.apply(a,arguments)}const U2e=new Date,q2e=new Date;function Km(s,t,n,r){function a(i){return s(i=arguments.length===0?new Date:new Date(+i)),i}return a.floor=i=>(s(i=new Date(+i)),i),a.ceil=i=>(s(i=new Date(i-1)),t(i,1),s(i),i),a.round=i=>{const l=a(i),o=a.ceil(i);return i-l(t(i=new Date(+i),l==null?1:Math.floor(l)),i),a.range=(i,l,o)=>{const c=[];if(i=a.ceil(i),o=o==null?1:Math.floor(o),!(i0))return c;let d;do c.push(d=new Date(+i)),t(i,o),s(i);while(dKm(l=>{if(l>=l)for(;s(l),!i(l);)l.setTime(l-1)},(l,o)=>{if(l>=l)if(o<0)for(;++o<=0;)for(;t(l,-1),!i(l););else for(;--o>=0;)for(;t(l,1),!i(l););}),n&&(a.count=(i,l)=>(U2e.setTime(+i),q2e.setTime(+l),s(U2e),s(q2e),Math.floor(n(U2e,q2e))),a.every=i=>(i=Math.floor(i),!isFinite(i)||!(i>0)?null:i>1?a.filter(r?l=>r(l)%i===0:l=>a.count(0,l)%i===0):a)),a}const Vxe=Km(()=>{},(s,t)=>{s.setTime(+s+t)},(s,t)=>t-s);Vxe.every=s=>(s=Math.floor(s),!isFinite(s)||!(s>0)?null:s>1?Km(t=>{t.setTime(Math.floor(t/s)*s)},(t,n)=>{t.setTime(+t+n*s)},(t,n)=>(n-t)/s):Vxe);Vxe.range;const O2=1e3,Av=O2*60,F2=Av*60,dN=F2*24,vPe=dN*7,OWe=dN*30,V2e=dN*365,QE=Km(s=>{s.setTime(s-s.getMilliseconds())},(s,t)=>{s.setTime(+s+t*O2)},(s,t)=>(t-s)/O2,s=>s.getUTCSeconds());QE.range;const bPe=Km(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*O2)},(s,t)=>{s.setTime(+s+t*Av)},(s,t)=>(t-s)/Av,s=>s.getMinutes());bPe.range;const _Pe=Km(s=>{s.setUTCSeconds(0,0)},(s,t)=>{s.setTime(+s+t*Av)},(s,t)=>(t-s)/Av,s=>s.getUTCMinutes());_Pe.range;const wPe=Km(s=>{s.setTime(s-s.getMilliseconds()-s.getSeconds()*O2-s.getMinutes()*Av)},(s,t)=>{s.setTime(+s+t*F2)},(s,t)=>(t-s)/F2,s=>s.getHours());wPe.range;const jPe=Km(s=>{s.setUTCMinutes(0,0,0)},(s,t)=>{s.setTime(+s+t*F2)},(s,t)=>(t-s)/F2,s=>s.getUTCHours());jPe.range;const TU=Km(s=>s.setHours(0,0,0,0),(s,t)=>s.setDate(s.getDate()+t),(s,t)=>(t-s-(t.getTimezoneOffset()-s.getTimezoneOffset())*Av)/dN,s=>s.getDate()-1);TU.range;const $ve=Km(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/dN,s=>s.getUTCDate()-1);$ve.range;const Wvt=Km(s=>{s.setUTCHours(0,0,0,0)},(s,t)=>{s.setUTCDate(s.getUTCDate()+t)},(s,t)=>(t-s)/dN,s=>Math.floor(s/dN));Wvt.range;function QM(s){return Km(t=>{t.setDate(t.getDate()-(t.getDay()+7-s)%7),t.setHours(0,0,0,0)},(t,n)=>{t.setDate(t.getDate()+n*7)},(t,n)=>(n-t-(n.getTimezoneOffset()-t.getTimezoneOffset())*Av)/vPe)}const Uve=QM(0),Hxe=QM(1),APs=QM(2),MPs=QM(3),O8=QM(4),IPs=QM(5),PPs=QM(6);Uve.range;Hxe.range;APs.range;MPs.range;O8.range;IPs.range;PPs.range;function XM(s){return Km(t=>{t.setUTCDate(t.getUTCDate()-(t.getUTCDay()+7-s)%7),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCDate(t.getUTCDate()+n*7)},(t,n)=>(n-t)/vPe)}const qve=XM(0),Gxe=XM(1),LPs=XM(2),DPs=XM(3),F8=XM(4),RPs=XM(5),OPs=XM(6);qve.range;Gxe.range;LPs.range;DPs.range;F8.range;RPs.range;OPs.range;const NPe=Km(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());NPe.range;const kPe=Km(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());kPe.range;const uN=Km(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());uN.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Km(t=>{t.setFullYear(Math.floor(t.getFullYear()/s)*s),t.setMonth(0,1),t.setHours(0,0,0,0)},(t,n)=>{t.setFullYear(t.getFullYear()+n*s)});uN.range;const hN=Km(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());hN.every=s=>!isFinite(s=Math.floor(s))||!(s>0)?null:Km(t=>{t.setUTCFullYear(Math.floor(t.getUTCFullYear()/s)*s),t.setUTCMonth(0,1),t.setUTCHours(0,0,0,0)},(t,n)=>{t.setUTCFullYear(t.getUTCFullYear()+n*s)});hN.range;function Kvt(s,t,n,r,a,i){const l=[[QE,1,O2],[QE,5,5*O2],[QE,15,15*O2],[QE,30,30*O2],[i,1,Av],[i,5,5*Av],[i,15,15*Av],[i,30,30*Av],[a,1,F2],[a,3,3*F2],[a,6,6*F2],[a,12,12*F2],[r,1,dN],[r,2,2*dN],[n,1,vPe],[t,1,OWe],[t,3,3*OWe],[s,1,V2e]];function o(d,u,h){const p=uv).right(l,p);if(f===l.length)return s.every(L3e(d/V2e,u/V2e,h));if(f===0)return Vxe.every(Math.max(L3e(d,u,h),1));const[y,_]=l[p/l[f-1][2]53)return null;"w"in we||(we.w=1),"Z"in we?(ke=G2e(vF(we.y,0,1)),it=ke.getUTCDay(),ke=it>4||it===0?Gxe.ceil(ke):Gxe(ke),ke=$ve.offset(ke,(we.V-1)*7),we.y=ke.getUTCFullYear(),we.m=ke.getUTCMonth(),we.d=ke.getUTCDate()+(we.w+6)%7):(ke=H2e(vF(we.y,0,1)),it=ke.getDay(),ke=it>4||it===0?Hxe.ceil(ke):Hxe(ke),ke=TU.offset(ke,(we.V-1)*7),we.y=ke.getFullYear(),we.m=ke.getMonth(),we.d=ke.getDate()+(we.w+6)%7)}else("W"in we||"U"in we)&&("w"in we||(we.w="u"in we?we.u%7:"W"in we?1:0),it="Z"in we?G2e(vF(we.y,0,1)).getUTCDay():H2e(vF(we.y,0,1)).getDay(),we.m=0,we.d="W"in we?(we.w+6)%7+we.W*7-(it+5)%7:we.w+we.U*7-(it+6)%7);return"Z"in we?(we.H+=we.Z/100|0,we.M+=we.Z%100,G2e(we)):H2e(we)}}function I(Re,Ae,Be,we){for(var Je=0,ke=Ae.length,it=Be.length,je,He;Je=it)return-1;if(je=Ae.charCodeAt(Je++),je===37){if(je=Ae.charAt(Je++),He=E[je in FWe?Ae.charAt(Je++):je],!He||(we=He(Re,Be,we))<0)return-1}else if(je!=Be.charCodeAt(we++))return-1}return we}function F(Re,Ae,Be){var we=d.exec(Ae.slice(Be));return we?(Re.p=u.get(we[0].toLowerCase()),Be+we[0].length):-1}function z(Re,Ae,Be){var we=f.exec(Ae.slice(Be));return we?(Re.w=y.get(we[0].toLowerCase()),Be+we[0].length):-1}function H(Re,Ae,Be){var we=h.exec(Ae.slice(Be));return we?(Re.w=p.get(we[0].toLowerCase()),Be+we[0].length):-1}function Z(Re,Ae,Be){var we=j.exec(Ae.slice(Be));return we?(Re.m=w.get(we[0].toLowerCase()),Be+we[0].length):-1}function Y(Re,Ae,Be){var we=_.exec(Ae.slice(Be));return we?(Re.m=v.get(we[0].toLowerCase()),Be+we[0].length):-1}function W(Re,Ae,Be){return I(Re,t,Ae,Be)}function ee(Re,Ae,Be){return I(Re,n,Ae,Be)}function se(Re,Ae,Be){return I(Re,r,Ae,Be)}function oe(Re){return l[Re.getDay()]}function he(Re){return i[Re.getDay()]}function ce(Re){return c[Re.getMonth()]}function me(Re){return o[Re.getMonth()]}function le(Re){return a[+(Re.getHours()>=12)]}function ve(Re){return 1+~~(Re.getMonth()/3)}function ge(Re){return l[Re.getUTCDay()]}function Te(Re){return i[Re.getUTCDay()]}function Ie(Re){return c[Re.getUTCMonth()]}function Ce(Re){return o[Re.getUTCMonth()]}function Me(Re){return a[+(Re.getUTCHours()>=12)]}function Pe(Re){return 1+~~(Re.getUTCMonth()/3)}return{format:function(Re){var Ae=O(Re+="",S);return Ae.toString=function(){return Re},Ae},parse:function(Re){var Ae=D(Re+="",!1);return Ae.toString=function(){return Re},Ae},utcFormat:function(Re){var Ae=O(Re+="",A);return Ae.toString=function(){return Re},Ae},utcParse:function(Re){var Ae=D(Re+="",!0);return Ae.toString=function(){return Re},Ae}}}var FWe={"-":"",_:" ",0:"0"},Mp=/^\s*\d+/,qPs=/^%/,VPs=/[\\^$*+?|[\]().{}]/g;function Ql(s,t,n){var r=s<0?"-":"",a=(r?-s:s)+"",i=a.length;return r+(i[t.toLowerCase(),n]))}function GPs(s,t,n){var r=Mp.exec(t.slice(n,n+1));return r?(s.w=+r[0],n+r[0].length):-1}function WPs(s,t,n){var r=Mp.exec(t.slice(n,n+1));return r?(s.u=+r[0],n+r[0].length):-1}function KPs(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.U=+r[0],n+r[0].length):-1}function YPs(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.V=+r[0],n+r[0].length):-1}function ZPs(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.W=+r[0],n+r[0].length):-1}function zWe(s,t,n){var r=Mp.exec(t.slice(n,n+4));return r?(s.y=+r[0],n+r[0].length):-1}function BWe(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.y=+r[0]+(+r[0]>68?1900:2e3),n+r[0].length):-1}function QPs(s,t,n){var r=/^(Z)|([+-]\d\d)(?::?(\d\d))?/.exec(t.slice(n,n+6));return r?(s.Z=r[1]?0:-(r[2]+(r[3]||"00")),n+r[0].length):-1}function XPs(s,t,n){var r=Mp.exec(t.slice(n,n+1));return r?(s.q=r[0]*3-3,n+r[0].length):-1}function JPs(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.m=r[0]-1,n+r[0].length):-1}function $We(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.d=+r[0],n+r[0].length):-1}function eLs(s,t,n){var r=Mp.exec(t.slice(n,n+3));return r?(s.m=0,s.d=+r[0],n+r[0].length):-1}function UWe(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.H=+r[0],n+r[0].length):-1}function tLs(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.M=+r[0],n+r[0].length):-1}function sLs(s,t,n){var r=Mp.exec(t.slice(n,n+2));return r?(s.S=+r[0],n+r[0].length):-1}function nLs(s,t,n){var r=Mp.exec(t.slice(n,n+3));return r?(s.L=+r[0],n+r[0].length):-1}function rLs(s,t,n){var r=Mp.exec(t.slice(n,n+6));return r?(s.L=Math.floor(r[0]/1e3),n+r[0].length):-1}function aLs(s,t,n){var r=qPs.exec(t.slice(n,n+1));return r?n+r[0].length:-1}function iLs(s,t,n){var r=Mp.exec(t.slice(n));return r?(s.Q=+r[0],n+r[0].length):-1}function oLs(s,t,n){var r=Mp.exec(t.slice(n));return r?(s.s=+r[0],n+r[0].length):-1}function qWe(s,t){return Ql(s.getDate(),t,2)}function lLs(s,t){return Ql(s.getHours(),t,2)}function cLs(s,t){return Ql(s.getHours()%12||12,t,2)}function dLs(s,t){return Ql(1+TU.count(uN(s),s),t,3)}function Yvt(s,t){return Ql(s.getMilliseconds(),t,3)}function uLs(s,t){return Yvt(s,t)+"000"}function hLs(s,t){return Ql(s.getMonth()+1,t,2)}function mLs(s,t){return Ql(s.getMinutes(),t,2)}function pLs(s,t){return Ql(s.getSeconds(),t,2)}function fLs(s){var t=s.getDay();return t===0?7:t}function xLs(s,t){return Ql(Uve.count(uN(s)-1,s),t,2)}function Zvt(s){var t=s.getDay();return t>=4||t===0?O8(s):O8.ceil(s)}function gLs(s,t){return s=Zvt(s),Ql(O8.count(uN(s),s)+(uN(s).getDay()===4),t,2)}function yLs(s){return s.getDay()}function vLs(s,t){return Ql(Hxe.count(uN(s)-1,s),t,2)}function bLs(s,t){return Ql(s.getFullYear()%100,t,2)}function _Ls(s,t){return s=Zvt(s),Ql(s.getFullYear()%100,t,2)}function wLs(s,t){return Ql(s.getFullYear()%1e4,t,4)}function jLs(s,t){var n=s.getDay();return s=n>=4||n===0?O8(s):O8.ceil(s),Ql(s.getFullYear()%1e4,t,4)}function NLs(s){var t=s.getTimezoneOffset();return(t>0?"-":(t*=-1,"+"))+Ql(t/60|0,"0",2)+Ql(t%60,"0",2)}function VWe(s,t){return Ql(s.getUTCDate(),t,2)}function kLs(s,t){return Ql(s.getUTCHours(),t,2)}function SLs(s,t){return Ql(s.getUTCHours()%12||12,t,2)}function CLs(s,t){return Ql(1+$ve.count(hN(s),s),t,3)}function Qvt(s,t){return Ql(s.getUTCMilliseconds(),t,3)}function TLs(s,t){return Qvt(s,t)+"000"}function ELs(s,t){return Ql(s.getUTCMonth()+1,t,2)}function ALs(s,t){return Ql(s.getUTCMinutes(),t,2)}function MLs(s,t){return Ql(s.getUTCSeconds(),t,2)}function ILs(s){var t=s.getUTCDay();return t===0?7:t}function PLs(s,t){return Ql(qve.count(hN(s)-1,s),t,2)}function Xvt(s){var t=s.getUTCDay();return t>=4||t===0?F8(s):F8.ceil(s)}function LLs(s,t){return s=Xvt(s),Ql(F8.count(hN(s),s)+(hN(s).getUTCDay()===4),t,2)}function DLs(s){return s.getUTCDay()}function RLs(s,t){return Ql(Gxe.count(hN(s)-1,s),t,2)}function OLs(s,t){return Ql(s.getUTCFullYear()%100,t,2)}function FLs(s,t){return s=Xvt(s),Ql(s.getUTCFullYear()%100,t,2)}function zLs(s,t){return Ql(s.getUTCFullYear()%1e4,t,4)}function BLs(s,t){var n=s.getUTCDay();return s=n>=4||n===0?F8(s):F8.ceil(s),Ql(s.getUTCFullYear()%1e4,t,4)}function $Ls(){return"+0000"}function HWe(){return"%"}function GWe(s){return+s}function WWe(s){return Math.floor(+s/1e3)}var AI,Jvt,e1t;ULs({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 ULs(s){return AI=UPs(s),Jvt=AI.format,AI.parse,e1t=AI.utcFormat,AI.utcParse,AI}function qLs(s){return new Date(s)}function VLs(s){return s instanceof Date?+s:+new Date(+s)}function SPe(s,t,n,r,a,i,l,o,c,d){var u=hPe(),h=u.invert,p=u.domain,f=d(".%L"),y=d(":%S"),_=d("%I:%M"),v=d("%I %p"),j=d("%a %d"),w=d("%b %d"),S=d("%B"),A=d("%Y");function E(O){return(c(O)t(a/(s.length-1)))},n.quantiles=function(r){return Array.from({length:r+1},(a,i)=>PIs(s,i/r))},n.copy=function(){return r1t(t).domain(s)},SN.apply(n,arguments)}function Hve(){var s=0,t=.5,n=1,r=1,a,i,l,o,c,d=Qx,u,h=!1,p;function f(_){return isNaN(_=+_)?p:(_=.5+((_=+u(_))-i)*(r*_t}var l1t=QLs,XLs=Gve,JLs=l1t,e8s=iR;function t8s(s){return s&&s.length?XLs(s,e8s,JLs):void 0}var s8s=t8s;const Wve=_l(s8s);function n8s(s,t){return ss.e^i.s<0?1:-1;for(r=i.d.length,a=s.d.length,t=0,n=rs.d[t]^i.s<0?1:-1;return r===a?0:r>a^i.s<0?1:-1};ei.decimalPlaces=ei.dp=function(){var s=this,t=s.d.length-1,n=(t-s.e)*Dd;if(t=s.d[t],t)for(;t%10==0;t/=10)n--;return n<0?0:n};ei.dividedBy=ei.div=function(s){return J2(this,new this.constructor(s))};ei.dividedToIntegerBy=ei.idiv=function(s){var t=this,n=t.constructor;return nd(J2(t,new n(s),0,1),n.precision)};ei.equals=ei.eq=function(s){return!this.cmp(s)};ei.exponent=function(){return lm(this)};ei.greaterThan=ei.gt=function(s){return this.cmp(s)>0};ei.greaterThanOrEqualTo=ei.gte=function(s){return this.cmp(s)>=0};ei.isInteger=ei.isint=function(){return this.e>this.d.length-2};ei.isNegative=ei.isneg=function(){return this.s<0};ei.isPositive=ei.ispos=function(){return this.s>0};ei.isZero=function(){return this.s===0};ei.lessThan=ei.lt=function(s){return this.cmp(s)<0};ei.lessThanOrEqualTo=ei.lte=function(s){return this.cmp(s)<1};ei.logarithm=ei.log=function(s){var t,n=this,r=n.constructor,a=r.precision,i=a+5;if(s===void 0)s=new r(10);else if(s=new r(s),s.s<1||s.eq(Z0))throw Error(Hv+"NaN");if(n.s<1)throw Error(Hv+(n.s?"NaN":"-Infinity"));return n.eq(Z0)?new r(0):(iu=!1,t=J2(zB(n,i),zB(s,i),i),iu=!0,nd(t,a))};ei.minus=ei.sub=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?m1t(t,s):u1t(t,(s.s=-s.s,s))};ei.modulo=ei.mod=function(s){var t,n=this,r=n.constructor,a=r.precision;if(s=new r(s),!s.s)throw Error(Hv+"NaN");return n.s?(iu=!1,t=J2(n,s,0,1).times(s),iu=!0,n.minus(t)):nd(new r(n),a)};ei.naturalExponential=ei.exp=function(){return h1t(this)};ei.naturalLogarithm=ei.ln=function(){return zB(this)};ei.negated=ei.neg=function(){var s=new this.constructor(this);return s.s=-s.s||0,s};ei.plus=ei.add=function(s){var t=this;return s=new t.constructor(s),t.s==s.s?u1t(t,s):m1t(t,(s.s=-s.s,s))};ei.precision=ei.sd=function(s){var t,n,r,a=this;if(s!==void 0&&s!==!!s&&s!==1&&s!==0)throw Error(KA+s);if(t=lm(a)+1,r=a.d.length-1,n=r*Dd+1,r=a.d[r],r){for(;r%10==0;r/=10)n--;for(r=a.d[0];r>=10;r/=10)n++}return s&&t>n?t:n};ei.squareRoot=ei.sqrt=function(){var s,t,n,r,a,i,l,o=this,c=o.constructor;if(o.s<1){if(!o.s)return new c(0);throw Error(Hv+"NaN")}for(s=lm(o),iu=!1,a=Math.sqrt(+o),a==0||a==1/0?(t=tw(o.d),(t.length+s)%2==0&&(t+="0"),a=Math.sqrt(t),s=dR((s+1)/2)-(s<0||s%2),a==1/0?t="5e"+s:(t=a.toExponential(),t=t.slice(0,t.indexOf("e")+1)+s),r=new c(t)):r=new c(a.toString()),n=c.precision,a=l=n+3;;)if(i=r,r=i.plus(J2(o,i,l+2)).times(.5),tw(i.d).slice(0,l)===(t=tw(r.d)).slice(0,l)){if(t=t.slice(l-3,l+1),a==l&&t=="4999"){if(nd(i,n+1,0),i.times(i).eq(o)){r=i;break}}else if(t!="9999")break;l+=4}return iu=!0,nd(r,n)};ei.times=ei.mul=function(s){var t,n,r,a,i,l,o,c,d,u=this,h=u.constructor,p=u.d,f=(s=new h(s)).d;if(!u.s||!s.s)return new h(0);for(s.s*=u.s,n=u.e+s.e,c=p.length,d=f.length,c=0;){for(t=0,a=c+r;a>r;)o=i[a]+f[r]*p[a-r-1]+t,i[a--]=o%xp|0,t=o/xp|0;i[a]=(i[a]+t)%xp|0}for(;!i[--l];)i.pop();return t?++n:i.shift(),s.d=i,s.e=n,iu?nd(s,h.precision):s};ei.toDecimalPlaces=ei.todp=function(s,t){var n=this,r=n.constructor;return n=new r(n),s===void 0?n:(Pw(s,0,cR),t===void 0?t=r.rounding:Pw(t,0,8),nd(n,s+lm(n)+1,t))};ei.toExponential=function(s,t){var n,r=this,a=r.constructor;return s===void 0?n=CM(r,!0):(Pw(s,0,cR),t===void 0?t=a.rounding:Pw(t,0,8),r=nd(new a(r),s+1,t),n=CM(r,!0,s+1)),n};ei.toFixed=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?CM(a):(Pw(s,0,cR),t===void 0?t=i.rounding:Pw(t,0,8),r=nd(new i(a),s+lm(a)+1,t),n=CM(r.abs(),!1,s+lm(r)+1),a.isneg()&&!a.isZero()?"-"+n:n)};ei.toInteger=ei.toint=function(){var s=this,t=s.constructor;return nd(new t(s),lm(s)+1,t.rounding)};ei.toNumber=function(){return+this};ei.toPower=ei.pow=function(s){var t,n,r,a,i,l,o=this,c=o.constructor,d=12,u=+(s=new c(s));if(!s.s)return new c(Z0);if(o=new c(o),!o.s){if(s.s<1)throw Error(Hv+"Infinity");return o}if(o.eq(Z0))return o;if(r=c.precision,s.eq(Z0))return nd(o,r);if(t=s.e,n=s.d.length-1,l=t>=n,i=o.s,l){if((n=u<0?-u:u)<=d1t){for(a=new c(Z0),t=Math.ceil(r/Dd+4),iu=!1;n%2&&(a=a.times(o),ZWe(a.d,t)),n=dR(n/2),n!==0;)o=o.times(o),ZWe(o.d,t);return iu=!0,s.s<0?new c(Z0).div(a):nd(a,r)}}else if(i<0)throw Error(Hv+"NaN");return i=i<0&&s.d[Math.max(t,n)]&1?-1:1,o.s=1,iu=!1,a=s.times(zB(o,r+d)),iu=!0,a=h1t(a),a.s=i,a};ei.toPrecision=function(s,t){var n,r,a=this,i=a.constructor;return s===void 0?(n=lm(a),r=CM(a,n<=i.toExpNeg||n>=i.toExpPos)):(Pw(s,1,cR),t===void 0?t=i.rounding:Pw(t,0,8),a=nd(new i(a),s,t),n=lm(a),r=CM(a,s<=n||n<=i.toExpNeg,s)),r};ei.toSignificantDigits=ei.tosd=function(s,t){var n=this,r=n.constructor;return s===void 0?(s=r.precision,t=r.rounding):(Pw(s,1,cR),t===void 0?t=r.rounding:Pw(t,0,8)),nd(new r(n),s,t)};ei.toString=ei.valueOf=ei.val=ei.toJSON=ei[Symbol.for("nodejs.util.inspect.custom")]=function(){var s=this,t=lm(s),n=s.constructor;return CM(s,t<=n.toExpNeg||t>=n.toExpPos)};function u1t(s,t){var n,r,a,i,l,o,c,d,u=s.constructor,h=u.precision;if(!s.s||!t.s)return t.s||(t=new u(s)),iu?nd(t,h):t;if(c=s.d,d=t.d,l=s.e,a=t.e,c=c.slice(),i=l-a,i){for(i<0?(r=c,i=-i,o=d.length):(r=d,a=l,o=c.length),l=Math.ceil(h/Dd),o=l>o?l+1:o+1,i>o&&(i=o,r.length=1),r.reverse();i--;)r.push(0);r.reverse()}for(o=c.length,i=d.length,o-i<0&&(i=o,r=d,d=c,c=r),n=0;i;)n=(c[--i]=c[i]+d[i]+n)/xp|0,c[i]%=xp;for(n&&(c.unshift(n),++a),o=c.length;c[--o]==0;)c.pop();return t.d=c,t.e=a,iu?nd(t,h):t}function Pw(s,t,n){if(s!==~~s||sn)throw Error(KA+s)}function tw(s){var t,n,r,a=s.length-1,i="",l=s[0];if(a>0){for(i+=l,t=1;tl?1:-1;else for(o=c=0;oa[o]?1:-1;break}return c}function n(r,a,i){for(var l=0;i--;)r[i]-=l,l=r[i]1;)r.shift()}return function(r,a,i,l){var o,c,d,u,h,p,f,y,_,v,j,w,S,A,E,O,D,I,F=r.constructor,z=r.s==a.s?1:-1,H=r.d,Z=a.d;if(!r.s)return new F(r);if(!a.s)throw Error(Hv+"Division by zero");for(c=r.e-a.e,D=Z.length,E=H.length,f=new F(z),y=f.d=[],d=0;Z[d]==(H[d]||0);)++d;if(Z[d]>(H[d]||0)&&--c,i==null?w=i=F.precision:l?w=i+(lm(r)-lm(a))+1:w=i,w<0)return new F(0);if(w=w/Dd+2|0,d=0,D==1)for(u=0,Z=Z[0],w++;(d1&&(Z=s(Z,u),H=s(H,u),D=Z.length,E=H.length),A=D,_=H.slice(0,D),v=_.length;v=xp/2&&++O;do u=0,o=t(Z,_,D,v),o<0?(j=_[0],D!=v&&(j=j*xp+(_[1]||0)),u=j/O|0,u>1?(u>=xp&&(u=xp-1),h=s(Z,u),p=h.length,v=_.length,o=t(h,_,p,v),o==1&&(u--,n(h,D16)throw Error(EPe+lm(s));if(!s.s)return new u(Z0);for(t==null?(iu=!1,o=h):o=t,l=new u(.03125);s.abs().gte(.1);)s=s.times(l),d+=5;for(r=Math.log(TE(2,d))/Math.LN10*2+5|0,o+=r,n=a=i=new u(Z0),u.precision=o;;){if(a=nd(a.times(s),o),n=n.times(++c),l=i.plus(J2(a,n,o)),tw(l.d).slice(0,o)===tw(i.d).slice(0,o)){for(;d--;)i=nd(i.times(i),o);return u.precision=h,t==null?(iu=!0,nd(i,h)):i}i=l}}function lm(s){for(var t=s.e*Dd,n=s.d[0];n>=10;n/=10)t++;return t}function W2e(s,t,n){if(t>s.LN10.sd())throw iu=!0,n&&(s.precision=n),Error(Hv+"LN10 precision limit exceeded");return nd(new s(s.LN10),t)}function Zk(s){for(var t="";s--;)t+="0";return t}function zB(s,t){var n,r,a,i,l,o,c,d,u,h=1,p=10,f=s,y=f.d,_=f.constructor,v=_.precision;if(f.s<1)throw Error(Hv+(f.s?"NaN":"-Infinity"));if(f.eq(Z0))return new _(0);if(t==null?(iu=!1,d=v):d=t,f.eq(10))return t==null&&(iu=!0),W2e(_,d);if(d+=p,_.precision=d,n=tw(y),r=n.charAt(0),i=lm(f),Math.abs(i)<15e14){for(;r<7&&r!=1||r==1&&n.charAt(1)>3;)f=f.times(s),n=tw(f.d),r=n.charAt(0),h++;i=lm(f),r>1?(f=new _("0."+n),i++):f=new _(r+"."+n.slice(1))}else return c=W2e(_,d+2,v).times(i+""),f=zB(new _(r+"."+n.slice(1)),d-p).plus(c),_.precision=v,t==null?(iu=!0,nd(f,v)):f;for(o=l=f=J2(f.minus(Z0),f.plus(Z0),d),u=nd(f.times(f),d),a=3;;){if(l=nd(l.times(u),d),c=o.plus(J2(l,new _(a),d)),tw(c.d).slice(0,d)===tw(o.d).slice(0,d))return o=o.times(2),i!==0&&(o=o.plus(W2e(_,d+2,v).times(i+""))),o=J2(o,new _(h),d),_.precision=v,t==null?(iu=!0,nd(o,v)):o;o=c,a+=2}}function YWe(s,t){var n,r,a;for((n=t.indexOf("."))>-1&&(t=t.replace(".","")),(r=t.search(/e/i))>0?(n<0&&(n=r),n+=+t.slice(r+1),t=t.substring(0,r)):n<0&&(n=t.length),r=0;t.charCodeAt(r)===48;)++r;for(a=t.length;t.charCodeAt(a-1)===48;)--a;if(t=t.slice(r,a),t){if(a-=r,n=n-r-1,s.e=dR(n/Dd),s.d=[],r=(n+1)%Dd,n<0&&(r+=Dd),rWxe||s.e<-Wxe))throw Error(EPe+n)}else s.s=0,s.e=0,s.d=[0];return s}function nd(s,t,n){var r,a,i,l,o,c,d,u,h=s.d;for(l=1,i=h[0];i>=10;i/=10)l++;if(r=t-l,r<0)r+=Dd,a=t,d=h[u=0];else{if(u=Math.ceil((r+1)/Dd),i=h.length,u>=i)return s;for(d=i=h[u],l=1;i>=10;i/=10)l++;r%=Dd,a=r-Dd+l}if(n!==void 0&&(i=TE(10,l-a-1),o=d/i%10|0,c=t<0||h[u+1]!==void 0||d%i,c=n<4?(o||c)&&(n==0||n==(s.s<0?3:2)):o>5||o==5&&(n==4||c||n==6&&(r>0?a>0?d/TE(10,l-a):0:h[u-1])%10&1||n==(s.s<0?8:7))),t<1||!h[0])return c?(i=lm(s),h.length=1,t=t-i-1,h[0]=TE(10,(Dd-t%Dd)%Dd),s.e=dR(-t/Dd)||0):(h.length=1,h[0]=s.e=s.s=0),s;if(r==0?(h.length=u,i=1,u--):(h.length=u+1,i=TE(10,Dd-r),h[u]=a>0?(d/TE(10,l-a)%TE(10,a)|0)*i:0),c)for(;;)if(u==0){(h[0]+=i)==xp&&(h[0]=1,++s.e);break}else{if(h[u]+=i,h[u]!=xp)break;h[u--]=0,i=1}for(r=h.length;h[--r]===0;)h.pop();if(iu&&(s.e>Wxe||s.e<-Wxe))throw Error(EPe+lm(s));return s}function m1t(s,t){var n,r,a,i,l,o,c,d,u,h,p=s.constructor,f=p.precision;if(!s.s||!t.s)return t.s?t.s=-t.s:t=new p(s),iu?nd(t,f):t;if(c=s.d,h=t.d,r=t.e,d=s.e,c=c.slice(),l=d-r,l){for(u=l<0,u?(n=c,l=-l,o=h.length):(n=h,r=d,o=c.length),a=Math.max(Math.ceil(f/Dd),o)+2,l>a&&(l=a,n.length=1),n.reverse(),a=l;a--;)n.push(0);n.reverse()}else{for(a=c.length,o=h.length,u=a0;--a)c[o++]=0;for(a=h.length;a>l;){if(c[--a]0?i=i.charAt(0)+"."+i.slice(1)+Zk(r):l>1&&(i=i.charAt(0)+"."+i.slice(1)),i=i+(a<0?"e":"e+")+a):a<0?(i="0."+Zk(-a-1)+i,n&&(r=n-l)>0&&(i+=Zk(r))):a>=l?(i+=Zk(a+1-l),n&&(r=n-a-1)>0&&(i=i+"."+Zk(r))):((r=a+1)0&&(a+1===l&&(i+="."),i+=Zk(r))),s.s<0?"-"+i:i}function ZWe(s,t){if(s.length>t)return s.length=t,!0}function p1t(s){var t,n,r;function a(i){var l=this;if(!(l instanceof a))return new a(i);if(l.constructor=a,i instanceof a){l.s=i.s,l.e=i.e,l.d=(i=i.d)?i.slice():i;return}if(typeof i=="number"){if(i*0!==0)throw Error(KA+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 YWe(l,i.toString())}else if(typeof i!="string")throw Error(KA+i);if(i.charCodeAt(0)===45?(i=i.slice(1),l.s=-1):l.s=1,N8s.test(i))YWe(l,i);else throw Error(KA+i)}if(a.prototype=ei,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=p1t,a.config=a.set=k8s,s===void 0&&(s={}),s)for(r=["precision","rounding","toExpNeg","toExpPos","LN10"],t=0;t=a[t+1]&&r<=a[t+2])this[n]=r;else throw Error(KA+n+": "+r);if((r=s[n="LN10"])!==void 0)if(r==Math.LN10)this[n]=new this(r);else throw Error(KA+n+": "+r);return this}var APe=p1t(j8s);Z0=new APe(1);const zc=APe;function S8s(s){return A8s(s)||E8s(s)||T8s(s)||C8s()}function C8s(){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 T8s(s,t){if(s){if(typeof s=="string")return z3e(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return z3e(s,t)}}function E8s(s){if(typeof Symbol<"u"&&Symbol.iterator in Object(s))return Array.from(s)}function A8s(s){if(Array.isArray(s))return z3e(s)}function z3e(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=t?n.apply(void 0,a):s(t-l,QWe(function(){for(var o=arguments.length,c=new Array(o),d=0;ds.length)&&(t=s.length);for(var n=0,r=new Array(t);n"u"||!(Symbol.iterator in Object(s)))){var n=[],r=!0,a=!1,i=void 0;try{for(var l=s[Symbol.iterator](),o;!(r=(o=l.next()).done)&&(n.push(o.value),!(t&&n.length===t));r=!0);}catch(c){a=!0,i=c}finally{try{!r&&l.return!=null&&l.return()}finally{if(a)throw i}}return n}}function H8s(s){if(Array.isArray(s))return s}function v1t(s){var t=BB(s,2),n=t[0],r=t[1],a=n,i=r;return n>r&&(a=r,i=n),[a,i]}function b1t(s,t,n){if(s.lte(0))return new zc(0);var r=Zve.getDigitCount(s.toNumber()),a=new zc(10).pow(r),i=s.div(a),l=r!==1?.05:.1,o=new zc(Math.ceil(i.div(l).toNumber())).add(n).mul(l),c=o.mul(a);return t?c:new zc(Math.ceil(c))}function G8s(s,t,n){var r=1,a=new zc(s);if(!a.isint()&&n){var i=Math.abs(s);i<1?(r=new zc(10).pow(Zve.getDigitCount(s)-1),a=new zc(Math.floor(a.div(r).toNumber())).mul(r)):i>1&&(a=new zc(Math.floor(s)))}else s===0?a=new zc(Math.floor((t-1)/2)):n||(a=new zc(Math.floor(s)));var l=Math.floor((t-1)/2),o=L8s(P8s(function(c){return a.add(new zc(c-l).mul(r)).toNumber()}),B3e);return o(0,t)}function _1t(s,t,n,r){var a=arguments.length>4&&arguments[4]!==void 0?arguments[4]:0;if(!Number.isFinite((t-s)/(n-1)))return{step:new zc(0),tickMin:new zc(0),tickMax:new zc(0)};var i=b1t(new zc(t).sub(s).div(n-1),r,a),l;s<=0&&t>=0?l=new zc(0):(l=new zc(s).add(t).div(2),l=l.sub(new zc(l).mod(i)));var o=Math.ceil(l.sub(s).div(i).toNumber()),c=Math.ceil(new zc(t).sub(l).div(i).toNumber()),d=o+c+1;return d>n?_1t(s,t,n,r,a+1):(d0?c+(n-d):c,o=t>0?o:o+(n-d)),{step:i,tickMin:l.sub(new zc(o).mul(i)),tickMax:l.add(new zc(c).mul(i))})}function W8s(s){var t=BB(s,2),n=t[0],r=t[1],a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:6,i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=Math.max(a,2),o=v1t([n,r]),c=BB(o,2),d=c[0],u=c[1];if(d===-1/0||u===1/0){var h=u===1/0?[d].concat(U3e(B3e(0,a-1).map(function(){return 1/0}))):[].concat(U3e(B3e(0,a-1).map(function(){return-1/0})),[u]);return n>r?$3e(h):h}if(d===u)return G8s(d,a,i);var p=_1t(d,u,l,i),f=p.step,y=p.tickMin,_=p.tickMax,v=Zve.rangeStep(y,_.add(new zc(.1).mul(f)),f);return n>r?$3e(v):v}function K8s(s,t){var n=BB(s,2),r=n[0],a=n[1],i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,l=v1t([r,a]),o=BB(l,2),c=o[0],d=o[1];if(c===-1/0||d===1/0)return[r,a];if(c===d)return[c];var u=Math.max(t,2),h=b1t(new zc(d).sub(c).div(u-1),i,0),p=[].concat(U3e(Zve.rangeStep(new zc(c),new zc(d).sub(new zc(.99).mul(h)),h)),[d]);return r>a?$3e(p):p}var Y8s=g1t(W8s),Z8s=g1t(K8s),Q8s="Invariant failed";function TM(s,t){throw new Error(Q8s)}var X8s=["offset","layout","width","dataKey","data","dataPointFormatter","xAxis","yAxis"];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 Kxe(){return Kxe=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function aDs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function iDs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function oDs(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1&&arguments[1]!==void 0?arguments[1]:[],a=arguments.length>2?arguments[2]:void 0,i=arguments.length>3?arguments[3]:void 0,l=-1,o=(n=r==null?void 0:r.length)!==null&&n!==void 0?n:0;if(o<=1)return 0;if(i&&i.axisType==="angleAxis"&&Math.abs(Math.abs(i.range[1]-i.range[0])-360)<=1e-6)for(var c=i.range,d=0;d0?a[d-1].coordinate:a[o-1].coordinate,h=a[d].coordinate,p=d>=o-1?a[0].coordinate:a[d+1].coordinate,f=void 0;if(Yx(h-u)!==Yx(p-h)){var y=[];if(Yx(p-h)===Yx(c[1]-c[0])){f=p;var _=h+c[1]-c[0];y[0]=Math.min(_,(_+u)/2),y[1]=Math.max(_,(_+u)/2)}else{f=u;var v=p+c[1]-c[0];y[0]=Math.min(h,(v+h)/2),y[1]=Math.max(h,(v+h)/2)}var j=[Math.min(h,(f+h)/2),Math.max(h,(f+h)/2)];if(t>j[0]&&t<=j[1]||t>=y[0]&&t<=y[1]){l=a[d].index;break}}else{var w=Math.min(u,p),S=Math.max(u,p);if(t>(w+h)/2&&t<=(S+h)/2){l=a[d].index;break}}}else for(var A=0;A0&&A(r[A].coordinate+r[A-1].coordinate)/2&&t<=(r[A].coordinate+r[A+1].coordinate)/2||A===o-1&&t>(r[A].coordinate+r[A-1].coordinate)/2){l=r[A].index;break}return l},MPe=function(t){var n,r=t,a=r.type.displayName,i=(n=t.type)!==null&&n!==void 0&&n.defaultProps?eh(eh({},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},NDs=function(t){var n=t.barSize,r=t.totalSize,a=t.stackGroups,i=a===void 0?{}:a;if(!i)return{};for(var l={},o=Object.keys(i),c=0,d=o.length;c=0});if(j&&j.length){var w=j[0].type.defaultProps,S=w!==void 0?eh(eh({},w),j[0].props):j[0].props,A=S.barSize,E=S[v];l[E]||(l[E]=[]);var O=jo(A)?n:A;l[E].push({item:j[0],stackList:j.slice(1),barSize:jo(O)?void 0:Zx(O,r,0)})}}return l},kDs=function(t){var n=t.barGap,r=t.barCategoryGap,a=t.bandSize,i=t.sizeList,l=i===void 0?[]:i,o=t.maxBarSize,c=l.length;if(c<1)return null;var d=Zx(n,a,0,!0),u,h=[];if(l[0].barSize===+l[0].barSize){var p=!1,f=a/c,y=l.reduce(function(A,E){return A+E.barSize||0},0);y+=(c-1)*d,y>=a&&(y-=(c-1)*d,d=0),y>=a&&f>0&&(p=!0,f*=.9,y=c*f);var _=(a-y)/2>>0,v={offset:_-d,size:0};u=l.reduce(function(A,E){var O={item:E.item,position:{offset:v.offset+v.size+d,size:p?f:E.barSize}},D=[].concat(eKe(A),[O]);return v=D[D.length-1].position,E.stackList&&E.stackList.length&&E.stackList.forEach(function(I){D.push({item:I,position:v})}),D},h)}else{var j=Zx(r,a,0,!0);a-2*j-(c-1)*d<=0&&(d=0);var w=(a-2*j-(c-1)*d)/c;w>1&&(w>>=0);var S=o===+o?Math.min(w,o):w;u=l.reduce(function(A,E,O){var D=[].concat(eKe(A),[{item:E.item,position:{offset:j+(w+d)*O+(w-S)/2,size:S}}]);return E.stackList&&E.stackList.length&&E.stackList.forEach(function(I){D.push({item:I,position:D[D.length-1].position})}),D},h)}return u},SDs=function(t,n,r,a){var i=r.children,l=r.width,o=r.margin,c=l-(o.left||0)-(o.right||0),d=k1t({children:i,legendWidth:c});if(d){var u=a||{},h=u.width,p=u.height,f=d.align,y=d.verticalAlign,_=d.layout;if((_==="vertical"||_==="horizontal"&&y==="middle")&&f!=="center"&&ia(t[f]))return eh(eh({},t),{},RL({},f,t[f]+(h||0)));if((_==="horizontal"||_==="vertical"&&f==="center")&&y!=="middle"&&ia(t[y]))return eh(eh({},t),{},RL({},y,t[y]+(p||0)))}return t},CDs=function(t,n,r){return jo(n)?!0:t==="horizontal"?n==="yAxis":t==="vertical"||r==="x"?n==="xAxis":r==="y"?n==="yAxis":!0},S1t=function(t,n,r,a,i){var l=n.props.children,o=hy(l,AU).filter(function(d){return CDs(a,i,d.props.direction)});if(o&&o.length){var c=o.map(function(d){return d.props.dataKey});return t.reduce(function(d,u){var h=Dm(u,r);if(jo(h))return d;var p=Array.isArray(h)?[Kve(h),Wve(h)]:[h,h],f=c.reduce(function(y,_){var v=Dm(u,_,0),j=p[0]-Math.abs(Array.isArray(v)?v[0]:v),w=p[1]+Math.abs(Array.isArray(v)?v[1]:v);return[Math.min(j,y[0]),Math.max(w,y[1])]},[1/0,-1/0]);return[Math.min(f[0],d[0]),Math.max(f[1],d[1])]},[1/0,-1/0])}return null},TDs=function(t,n,r,a,i){var l=n.map(function(o){return S1t(t,o,r,i,a)}).filter(function(o){return!jo(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},C1t=function(t,n,r,a,i){var l=n.map(function(c){var d=c.props.dataKey;return r==="number"&&d&&S1t(t,c,d,a)||mz(t,d,r,i)});if(r==="number")return l.reduce(function(c,d){return[Math.min(c[0],d[0]),Math.max(c[1],d[1])]},[1/0,-1/0]);var o={};return l.reduce(function(c,d){for(var u=0,h=d.length;u=2?Yx(o[0]-o[1])*2*d:d,n&&(t.ticks||t.niceTicks)){var u=(t.ticks||t.niceTicks).map(function(h){var p=i?i.indexOf(h):h;return{coordinate:a(p)+d,value:h,offset:d}});return u.filter(function(h){return!jU(h.coordinate)})}return t.isCategorical&&t.categoricalDomain?t.categoricalDomain.map(function(h,p){return{coordinate:a(h)+d,value:h,index:p,offset:d}}):a.ticks&&!r?a.ticks(t.tickCount).map(function(h){return{coordinate:a(h)+d,value:h,offset:d}}):a.domain().map(function(h,p){return{coordinate:a(h)+d,value:i?i[h]:h,index:p,offset:d}})},K2e=new WeakMap,YH=function(t,n){if(typeof n!="function")return t;K2e.has(t)||K2e.set(t,new WeakMap);var r=K2e.get(t);if(r.has(n))return r.get(n);var a=function(){t.apply(void 0,arguments),n.apply(void 0,arguments)};return r.set(n,a),a},A1t=function(t,n,r){var a=t.scale,i=t.type,l=t.layout,o=t.axisType;if(a==="auto")return l==="radial"&&o==="radiusAxis"?{scale:LB(),realScaleType:"band"}:l==="radial"&&o==="angleAxis"?{scale:qxe(),realScaleType:"linear"}:i==="category"&&n&&(n.indexOf("LineChart")>=0||n.indexOf("AreaChart")>=0||n.indexOf("ComposedChart")>=0&&!r)?{scale:hz(),realScaleType:"point"}:i==="category"?{scale:LB(),realScaleType:"band"}:{scale:qxe(),realScaleType:"linear"};if(NM(a)){var c="scale".concat(Pve(a));return{scale:(KWe[c]||hz)(),realScaleType:KWe[c]?c:"point"}}return ho(a)?{scale:a}:{scale:hz(),realScaleType:"point"}},sKe=1e-4,M1t=function(t){var n=t.domain();if(!(!n||n.length<=2)){var r=n.length,a=t.range(),i=Math.min(a[0],a[1])-sKe,l=Math.max(a[0],a[1])+sKe,o=t(n[0]),c=t(n[r-1]);(ol||cl)&&t.domain([n[0],n[r-1]])}},EDs=function(t,n){if(!t)return null;for(var r=0,a=t.length;ra)&&(i[1]=a),i[0]>a&&(i[0]=a),i[1]=0?(t[o][r][0]=i,t[o][r][1]=i+c,i=t[o][r][1]):(t[o][r][0]=l,t[o][r][1]=l+c,l=t[o][r][1])}},IDs=function(t){var n=t.length;if(!(n<=0))for(var r=0,a=t[0].length;r=0?(t[l][r][0]=i,t[l][r][1]=i+o,i=t[l][r][1]):(t[l][r][0]=0,t[l][r][1]=0)}},PDs={sign:MDs,expand:XSs,none:M8,silhouette:JSs,wiggle:e4s,positive:IDs},LDs=function(t,n,r){var a=n.map(function(o){return o.props.dataKey}),i=PDs[r],l=QSs().keys(a).value(function(o,c){return+Dm(o,c,0)}).order(x3e).offset(i);return l(t)},DDs=function(t,n,r,a,i,l){if(!t)return null;var o=l?n.reverse():n,c={},d=o.reduce(function(h,p){var f,y=(f=p.type)!==null&&f!==void 0&&f.defaultProps?eh(eh({},p.type.defaultProps),p.props):p.props,_=y.stackId,v=y.hide;if(v)return h;var j=y[r],w=h[j]||{hasStack:!1,stackGroups:{}};if(Om(_)){var S=w.stackGroups[_]||{numericAxisId:r,cateAxisId:a,items:[]};S.items.push(p),w.hasStack=!0,w.stackGroups[_]=S}else w.stackGroups[nR("_stackId_")]={numericAxisId:r,cateAxisId:a,items:[p]};return eh(eh({},h),{},RL({},j,w))},c),u={};return Object.keys(d).reduce(function(h,p){var f=d[p];if(f.hasStack){var y={};f.stackGroups=Object.keys(f.stackGroups).reduce(function(_,v){var j=f.stackGroups[v];return eh(eh({},_),{},RL({},v,{numericAxisId:r,cateAxisId:a,items:j.items,stackedData:LDs(t,j.items,i)}))},y)}return eh(eh({},h),{},RL({},p,f))},u)},I1t=function(t,n){var r=n.realScaleType,a=n.type,i=n.tickCount,l=n.originalDomain,o=n.allowDecimals,c=r||n.scale;if(c!=="auto"&&c!=="linear")return null;if(i&&a==="number"&&l&&(l[0]==="auto"||l[1]==="auto")){var d=t.domain();if(!d.length)return null;var u=Y8s(d,i,o);return t.domain([Kve(u),Wve(u)]),{niceTicks:u}}if(i&&a==="number"){var h=t.domain(),p=Z8s(h,i,o);return{niceTicks:p}}return null};function nKe(s){var t=s.axis,n=s.ticks,r=s.bandSize,a=s.entry,i=s.index,l=s.dataKey;if(t.type==="category"){if(!t.allowDuplicatedCategory&&t.dataKey&&!jo(a[t.dataKey])){var o=wxe(n,"value",a[t.dataKey]);if(o)return o.coordinate+r/2}return n[i]?n[i].coordinate+r/2:null}var c=Dm(a,jo(l)?t.dataKey:l);return jo(c)?null:t.scale(c)}var rKe=function(t){var n=t.axis,r=t.ticks,a=t.offset,i=t.bandSize,l=t.entry,o=t.index;if(n.type==="category")return r[o]?r[o].coordinate+a:null;var c=Dm(l,n.dataKey,n.domain[o]);return jo(c)?null:n.scale(c)-i/2+a},RDs=function(t){var n=t.numericAxis,r=n.scale.domain();if(n.type==="number"){var a=Math.min(r[0],r[1]),i=Math.max(r[0],r[1]);return a<=0&&i>=0?0:i<0?i:a}return r[0]},ODs=function(t,n){var r,a=(r=t.type)!==null&&r!==void 0&&r.defaultProps?eh(eh({},t.type.defaultProps),t.props):t.props,i=a.stackId;if(Om(i)){var l=n[i];if(l){var o=l.items.indexOf(t);return o>=0?l.stackedData[o]:null}}return null},FDs=function(t){return t.reduce(function(n,r){return[Kve(r.concat([n[0]]).filter(ia)),Wve(r.concat([n[1]]).filter(ia))]},[1/0,-1/0])},P1t=function(t,n,r){return Object.keys(t).reduce(function(a,i){var l=t[i],o=l.stackedData,c=o.reduce(function(d,u){var h=FDs(u.slice(n,r+1));return[Math.min(d[0],h[0]),Math.max(d[1],h[1])]},[1/0,-1/0]);return[Math.min(c[0],a[0]),Math.max(c[1],a[1])]},[1/0,-1/0]).map(function(a){return a===1/0||a===-1/0?0:a})},aKe=/^dataMin[\s]*-[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,iKe=/^dataMax[\s]*\+[\s]*([0-9]+([.]{1}[0-9]+){0,1})$/,G3e=function(t,n,r){if(ho(t))return t(n,r);if(!Array.isArray(t))return n;var a=[];if(ia(t[0]))a[0]=r?t[0]:Math.min(t[0],n[0]);else if(aKe.test(t[0])){var i=+aKe.exec(t[0])[1];a[0]=n[0]-i}else ho(t[0])?a[0]=t[0](n[0]):a[0]=n[0];if(ia(t[1]))a[1]=r?t[1]:Math.max(t[1],n[1]);else if(iKe.test(t[1])){var l=+iKe.exec(t[1])[1];a[1]=n[1]+l}else ho(t[1])?a[1]=t[1](n[1]):a[1]=n[1];return a},Zxe=function(t,n,r){if(t&&t.scale&&t.scale.bandwidth){var a=t.scale.bandwidth();if(!r||a>0)return a}if(t&&n&&n.length>=2){for(var i=aPe(n,function(h){return h.coordinate}),l=1/0,o=1,c=i.length;os.length)&&(t=s.length);for(var n=0,r=new Array(t);n2&&arguments[2]!==void 0?arguments[2]:{top:0,right:0,bottom:0,left:0};return Math.min(Math.abs(t-(r.left||0)-(r.right||0)),Math.abs(n-(r.top||0)-(r.bottom||0)))/2},WDs=function(t,n,r,a,i){var l=t.width,o=t.height,c=t.startAngle,d=t.endAngle,u=Zx(t.cx,l,l/2),h=Zx(t.cy,o,o/2),p=R1t(l,o,r),f=Zx(t.innerRadius,p,0),y=Zx(t.outerRadius,p,p*.8),_=Object.keys(n);return _.reduce(function(v,j){var w=n[j],S=w.domain,A=w.reversed,E;if(jo(w.range))a==="angleAxis"?E=[c,d]:a==="radiusAxis"&&(E=[f,y]),A&&(E=[E[1],E[0]]);else{E=w.range;var O=E,D=$Ds(O,2);c=D[0],d=D[1]}var I=A1t(w,i),F=I.realScaleType,z=I.scale;z.domain(S).range(E),M1t(z);var H=I1t(z,b2(b2({},w),{},{realScaleType:F})),Z=b2(b2(b2({},w),H),{},{range:E,radius:y,realScaleType:F,scale:z,cx:u,cy:h,innerRadius:f,outerRadius:y,startAngle:c,endAngle:d});return b2(b2({},v),{},D1t({},j,Z))},{})},KDs=function(t,n){var r=t.x,a=t.y,i=n.x,l=n.y;return Math.sqrt(Math.pow(r-i,2)+Math.pow(a-l,2))},YDs=function(t,n){var r=t.x,a=t.y,i=n.cx,l=n.cy,o=KDs({x:r,y:a},{x:i,y:l});if(o<=0)return{radius:o};var c=(r-i)/o,d=Math.acos(c);return a>l&&(d=2*Math.PI-d),{radius:o,angle:GDs(d),angleInRadian:d}},ZDs=function(t){var n=t.startAngle,r=t.endAngle,a=Math.floor(n/360),i=Math.floor(r/360),l=Math.min(a,i);return{startAngle:n-l*360,endAngle:r-l*360}},QDs=function(t,n){var r=n.startAngle,a=n.endAngle,i=Math.floor(r/360),l=Math.floor(a/360),o=Math.min(i,l);return t+o*360},dKe=function(t,n){var r=t.x,a=t.y,i=YDs({x:r,y:a},n),l=i.radius,o=i.angle,c=n.innerRadius,d=n.outerRadius;if(ld)return!1;if(l===0)return!0;var u=ZDs(n),h=u.startAngle,p=u.endAngle,f=o,y;if(h<=p){for(;f>p;)f-=360;for(;f=h&&f<=p}else{for(;f>h;)f-=360;for(;f=p&&f<=h}return y?b2(b2({},n),{},{radius:l,angle:QDs(f,n)}):null},O1t=function(t){return!N.isValidElement(t)&&!ho(t)&&typeof t!="boolean"?t.className:""};function VB(s){"@babel/helpers - typeof";return VB=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},VB(s)}var XDs=["offset"];function JDs(s){return nRs(s)||sRs(s)||tRs(s)||eRs()}function eRs(){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 tRs(s,t){if(s){if(typeof s=="string")return W3e(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return W3e(s,t)}}function sRs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function nRs(s){if(Array.isArray(s))return W3e(s)}function W3e(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function aRs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function uKe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function Nm(s){for(var t=1;t=0?1:-1,S,A;a==="insideStart"?(S=f+w*l,A=_):a==="insideEnd"?(S=y-w*l,A=!_):a==="end"&&(S=y+w*l,A=_),A=j<=0?A:!A;var E=vd(d,u,v,S),O=vd(d,u,v,S+(A?1:-1)*359),D="M".concat(E.x,",").concat(E.y,` A`).concat(v,",").concat(v,",0,1,").concat(A?0:1,`, `).concat(O.x,",").concat(O.y),I=jo(t.id)?nR("recharts-radial-line-"):t.id;return Ct.createElement("text",HB({},r,{dominantBaseline:"central",className:So("recharts-radial-bar-label",o)}),Ct.createElement("defs",null,Ct.createElement("path",{id:I,d:D})),Ct.createElement("textPath",{xlinkHref:"#".concat(I)},n))},hRs=function(t){var n=t.viewBox,r=t.offset,a=t.position,i=n,l=i.cx,o=i.cy,c=i.innerRadius,d=i.outerRadius,u=i.startAngle,h=i.endAngle,p=(u+h)/2;if(a==="outside"){var f=vd(l,o,d+r,p),y=f.x,_=f.y;return{x:y,y:_,textAnchor:y>=l?"start":"end",verticalAnchor:"middle"}}if(a==="center")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"middle"};if(a==="centerTop")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"start"};if(a==="centerBottom")return{x:l,y:o,textAnchor:"middle",verticalAnchor:"end"};var v=(c+d)/2,j=vd(l,o,v,p),w=j.x,S=j.y;return{x:w,y:S,textAnchor:"middle",verticalAnchor:"middle"}},mRs=function(t){var n=t.viewBox,r=t.parentViewBox,a=t.offset,i=t.position,l=n,o=l.x,c=l.y,d=l.width,u=l.height,h=u>=0?1:-1,p=h*a,f=h>0?"end":"start",y=h>0?"start":"end",_=d>=0?1:-1,v=_*a,j=_>0?"end":"start",w=_>0?"start":"end";if(i==="top"){var S={x:o+d/2,y:c-h*a,textAnchor:"middle",verticalAnchor:f};return Nm(Nm({},S),r?{height:Math.max(c-r.y,0),width:d}:{})}if(i==="bottom"){var A={x:o+d/2,y:c+u+p,textAnchor:"middle",verticalAnchor:y};return Nm(Nm({},A),r?{height:Math.max(r.y+r.height-(c+u),0),width:d}:{})}if(i==="left"){var E={x:o-v,y:c+u/2,textAnchor:j,verticalAnchor:"middle"};return Nm(Nm({},E),r?{width:Math.max(E.x-r.x,0),height:u}:{})}if(i==="right"){var O={x:o+d+v,y:c+u/2,textAnchor:w,verticalAnchor:"middle"};return Nm(Nm({},O),r?{width:Math.max(r.x+r.width-O.x,0),height:u}:{})}var D=r?{width:d,height:u}:{};return i==="insideLeft"?Nm({x:o+v,y:c+u/2,textAnchor:w,verticalAnchor:"middle"},D):i==="insideRight"?Nm({x:o+d-v,y:c+u/2,textAnchor:j,verticalAnchor:"middle"},D):i==="insideTop"?Nm({x:o+d/2,y:c+p,textAnchor:"middle",verticalAnchor:y},D):i==="insideBottom"?Nm({x:o+d/2,y:c+u-p,textAnchor:"middle",verticalAnchor:f},D):i==="insideTopLeft"?Nm({x:o+v,y:c+p,textAnchor:w,verticalAnchor:y},D):i==="insideTopRight"?Nm({x:o+d-v,y:c+p,textAnchor:j,verticalAnchor:y},D):i==="insideBottomLeft"?Nm({x:o+v,y:c+u-p,textAnchor:w,verticalAnchor:f},D):i==="insideBottomRight"?Nm({x:o+d-v,y:c+u-p,textAnchor:j,verticalAnchor:f},D):JD(i)&&(ia(i.x)||YE(i.x))&&(ia(i.y)||YE(i.y))?Nm({x:o+Zx(i.x,d),y:c+Zx(i.y,u),textAnchor:"end",verticalAnchor:"end"},D):Nm({x:o+d/2,y:c+u/2,textAnchor:"middle",verticalAnchor:"middle"},D)},pRs=function(t){return"cx"in t&&ia(t.cx)};function wp(s){var t=s.offset,n=t===void 0?5:t,r=rRs(s,XDs),a=Nm({offset:n},r),i=a.viewBox,l=a.position,o=a.value,c=a.children,d=a.content,u=a.className,h=u===void 0?"":u,p=a.textBreakAll;if(!i||jo(o)&&jo(c)&&!N.isValidElement(d)&&!ho(d))return null;if(N.isValidElement(d))return N.cloneElement(d,a);var f;if(ho(d)){if(f=N.createElement(d,a),N.isValidElement(f))return f}else f=cRs(a);var y=pRs(i),_=$i(a,!0);if(y&&(l==="insideStart"||l==="insideEnd"||l==="end"))return uRs(a,f,_);var v=y?hRs(a):mRs(a);return Ct.createElement(SM,HB({className:So("recharts-label",h)},_,v,{breakAll:p}),f)}wp.displayName="Label";var F1t=function(t){var n=t.cx,r=t.cy,a=t.angle,i=t.startAngle,l=t.endAngle,o=t.r,c=t.radius,d=t.innerRadius,u=t.outerRadius,h=t.x,p=t.y,f=t.top,y=t.left,_=t.width,v=t.height,j=t.clockWise,w=t.labelViewBox;if(w)return w;if(ia(_)&&ia(v)){if(ia(h)&&ia(p))return{x:h,y:p,width:_,height:v};if(ia(f)&&ia(y))return{x:f,y,width:_,height:v}}return ia(h)&&ia(p)?{x:h,y:p,width:0,height:0}:ia(n)&&ia(r)?{cx:n,cy:r,startAngle:i||a||0,endAngle:l||a||0,innerRadius:d||0,outerRadius:u||c||o||0,clockWise:j}:t.viewBox?t.viewBox:{}},fRs=function(t,n){return t?t===!0?Ct.createElement(wp,{key:"label-implicit",viewBox:n}):Om(t)?Ct.createElement(wp,{key:"label-implicit",viewBox:n,value:t}):N.isValidElement(t)?t.type===wp?N.cloneElement(t,{key:"label-implicit",viewBox:n}):Ct.createElement(wp,{key:"label-implicit",content:t,viewBox:n}):ho(t)?Ct.createElement(wp,{key:"label-implicit",content:t,viewBox:n}):JD(t)?Ct.createElement(wp,HB({viewBox:n},t,{key:"label-implicit"})):null:null},xRs=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!t||!t.children&&r&&!t.label)return null;var a=t.children,i=F1t(t),l=hy(a,wp).map(function(c,d){return N.cloneElement(c,{viewBox:n||i,key:"label-".concat(d)})});if(!r)return l;var o=fRs(t.label,n||i);return[o].concat(JDs(l))};wp.parseViewBox=F1t;wp.renderCallByParent=xRs;function gRs(s){var t=s==null?0:s.length;return t?s[t-1]:void 0}var yRs=gRs;const vRs=_l(yRs);function GB(s){"@babel/helpers - typeof";return GB=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},GB(s)}var bRs=["valueAccessor"],_Rs=["data","dataKey","clockWise","id","textBreakAll"];function wRs(s){return SRs(s)||kRs(s)||NRs(s)||jRs()}function jRs(){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 NRs(s,t){if(s){if(typeof s=="string")return K3e(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return K3e(s,t)}}function kRs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function SRs(s){if(Array.isArray(s))return K3e(s)}function K3e(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function ARs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var MRs=function(t){return Array.isArray(t.value)?vRs(t.value):t.value};function eN(s){var t=s.valueAccessor,n=t===void 0?MRs:t,r=pKe(s,bRs),a=r.data,i=r.dataKey,l=r.clockWise,o=r.id,c=r.textBreakAll,d=pKe(r,_Rs);return!a||!a.length?null:Ct.createElement(Wl,{className:"recharts-label-list"},a.map(function(u,h){var p=jo(i)?n(u,h):Dm(u&&u.payload,i),f=jo(o)?{}:{id:"".concat(o,"-").concat(h)};return Ct.createElement(wp,Xxe({},$i(u,!0),d,f,{parentViewBox:u.parentViewBox,value:p,textBreakAll:c,viewBox:wp.parseViewBox(jo(l)?u:mKe(mKe({},u),{},{clockWise:l})),key:"label-".concat(h),index:h}))}))}eN.displayName="LabelList";function IRs(s,t){return s?s===!0?Ct.createElement(eN,{key:"labelList-implicit",data:t}):Ct.isValidElement(s)||ho(s)?Ct.createElement(eN,{key:"labelList-implicit",data:t,content:s}):JD(s)?Ct.createElement(eN,Xxe({data:t},s,{key:"labelList-implicit"})):null:null}function PRs(s,t){var n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;if(!s||!s.children&&n&&!s.label)return null;var r=s.children,a=hy(r,eN).map(function(l,o){return N.cloneElement(l,{data:t,key:"labelList-".concat(o)})});if(!n)return a;var i=IRs(s.label,t);return[i].concat(wRs(a))}eN.renderCallByParent=PRs;function WB(s){"@babel/helpers - typeof";return WB=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},WB(s)}function Y3e(){return Y3e=Object.assign?Object.assign.bind():function(s){for(var t=1;t180),",").concat(+(l>d),`, `).concat(h.x,",").concat(h.y,` `);if(a>0){var f=vd(n,r,a,l),y=vd(n,r,a,d);p+="L ".concat(y.x,",").concat(y.y,` A `).concat(a,",").concat(a,`,0, `).concat(+(Math.abs(c)>180),",").concat(+(l<=d),`, `).concat(f.x,",").concat(f.y," Z")}else p+="L ".concat(n,",").concat(r," Z");return p},FRs=function(t){var n=t.cx,r=t.cy,a=t.innerRadius,i=t.outerRadius,l=t.cornerRadius,o=t.forceCornerRadius,c=t.cornerIsExternal,d=t.startAngle,u=t.endAngle,h=Yx(u-d),p=ZH({cx:n,cy:r,radius:i,angle:d,sign:h,cornerRadius:l,cornerIsExternal:c}),f=p.circleTangency,y=p.lineTangency,_=p.theta,v=ZH({cx:n,cy:r,radius:i,angle:u,sign:-h,cornerRadius:l,cornerIsExternal:c}),j=v.circleTangency,w=v.lineTangency,S=v.theta,A=c?Math.abs(d-u):Math.abs(d-u)-_-S;if(A<0)return o?"M ".concat(y.x,",").concat(y.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 `):z1t({cx:n,cy:r,innerRadius:a,outerRadius:i,startAngle:d,endAngle:u});var E="M ".concat(y.x,",").concat(y.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(f.x,",").concat(f.y,` A`).concat(i,",").concat(i,",0,").concat(+(A>180),",").concat(+(h<0),",").concat(j.x,",").concat(j.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(w.x,",").concat(w.y,` `);if(a>0){var O=ZH({cx:n,cy:r,radius:a,angle:d,sign:h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),D=O.circleTangency,I=O.lineTangency,F=O.theta,z=ZH({cx:n,cy:r,radius:a,angle:u,sign:-h,isExternal:!0,cornerRadius:l,cornerIsExternal:c}),H=z.circleTangency,Z=z.lineTangency,Y=z.theta,W=c?Math.abs(d-u):Math.abs(d-u)-F-Y;if(W<0&&l===0)return"".concat(E,"L").concat(n,",").concat(r,"Z");E+="L".concat(Z.x,",").concat(Z.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(H.x,",").concat(H.y,` A`).concat(a,",").concat(a,",0,").concat(+(W>180),",").concat(+(h>0),",").concat(D.x,",").concat(D.y,` A`).concat(l,",").concat(l,",0,0,").concat(+(h<0),",").concat(I.x,",").concat(I.y,"Z")}else E+="L".concat(n,",").concat(r,"Z");return E},zRs={cx:0,cy:0,innerRadius:0,outerRadius:0,startAngle:0,endAngle:0,cornerRadius:0,forceCornerRadius:!1,cornerIsExternal:!1},B1t=function(t){var n=xKe(xKe({},zRs),t),r=n.cx,a=n.cy,i=n.innerRadius,l=n.outerRadius,o=n.cornerRadius,c=n.forceCornerRadius,d=n.cornerIsExternal,u=n.startAngle,h=n.endAngle,p=n.className;if(l0&&Math.abs(u-h)<360?v=FRs({cx:r,cy:a,innerRadius:i,outerRadius:l,cornerRadius:Math.min(_,y/2),forceCornerRadius:c,cornerIsExternal:d,startAngle:u,endAngle:h}):v=z1t({cx:r,cy:a,innerRadius:i,outerRadius:l,startAngle:u,endAngle:h}),Ct.createElement("path",Y3e({},$i(n,!0),{className:f,d:v,role:"img"}))};function KB(s){"@babel/helpers - typeof";return KB=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},KB(s)}function Z3e(){return Z3e=Object.assign?Object.assign.bind():function(s){for(var t=1;t0;)if(!n.equals(s[r],t[r],r,r,s,t,n))return!1;return!0}function eOs(s,t){return uR(s.getTime(),t.getTime())}function NKe(s,t,n){if(s.size!==t.size)return!1;for(var r={},a=s.entries(),i=0,l,o;(l=a.next())&&!l.done;){for(var c=t.entries(),d=!1,u=0;(o=c.next())&&!o.done;){var h=l.value,p=h[0],f=h[1],y=o.value,_=y[0],v=y[1];!d&&!r[u]&&(d=n.equals(p,_,i,u,s,t,n)&&n.equals(f,v,p,_,s,t,n))&&(r[u]=!0),u++}if(!d)return!1;i++}return!0}function tOs(s,t,n){var r=jKe(s),a=r.length;if(jKe(t).length!==a)return!1;for(var i;a-- >0;)if(i=r[a],i===H1t&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!V1t(t,i)||!n.equals(s[i],t[i],i,i,s,t,n))return!1;return!0}function NF(s,t,n){var r=_Ke(s),a=r.length;if(_Ke(t).length!==a)return!1;for(var i,l,o;a-- >0;)if(i=r[a],i===H1t&&(s.$$typeof||t.$$typeof)&&s.$$typeof!==t.$$typeof||!V1t(t,i)||!n.equals(s[i],t[i],i,i,s,t,n)||(l=wKe(s,i),o=wKe(t,i),(l||o)&&(!l||!o||l.configurable!==o.configurable||l.enumerable!==o.enumerable||l.writable!==o.writable)))return!1;return!0}function sOs(s,t){return uR(s.valueOf(),t.valueOf())}function nOs(s,t){return s.source===t.source&&s.flags===t.flags}function kKe(s,t,n){if(s.size!==t.size)return!1;for(var r={},a=s.values(),i,l;(i=a.next())&&!i.done;){for(var o=t.values(),c=!1,d=0;(l=o.next())&&!l.done;)!c&&!r[d]&&(c=n.equals(i.value,l.value,i.value,l.value,s,t,n))&&(r[d]=!0),d++;if(!c)return!1}return!0}function rOs(s,t){var n=s.length;if(t.length!==n)return!1;for(;n-- >0;)if(s[n]!==t[n])return!1;return!0}var aOs="[object Arguments]",iOs="[object Boolean]",oOs="[object Date]",lOs="[object Map]",cOs="[object Number]",dOs="[object Object]",uOs="[object RegExp]",hOs="[object Set]",mOs="[object String]",pOs=Array.isArray,SKe=typeof ArrayBuffer=="function"&&ArrayBuffer.isView?ArrayBuffer.isView:null,CKe=Object.assign,fOs=Object.prototype.toString.call.bind(Object.prototype.toString);function xOs(s){var t=s.areArraysEqual,n=s.areDatesEqual,r=s.areMapsEqual,a=s.areObjectsEqual,i=s.arePrimitiveWrappersEqual,l=s.areRegExpsEqual,o=s.areSetsEqual,c=s.areTypedArraysEqual;return function(u,h,p){if(u===h)return!0;if(u==null||h==null||typeof u!="object"||typeof h!="object")return u!==u&&h!==h;var f=u.constructor;if(f!==h.constructor)return!1;if(f===Object)return a(u,h,p);if(pOs(u))return t(u,h,p);if(SKe!=null&&SKe(u))return c(u,h,p);if(f===Date)return n(u,h,p);if(f===RegExp)return l(u,h,p);if(f===Map)return r(u,h,p);if(f===Set)return o(u,h,p);var y=fOs(u);return y===oOs?n(u,h,p):y===uOs?l(u,h,p):y===lOs?r(u,h,p):y===hOs?o(u,h,p):y===dOs?typeof u.then!="function"&&typeof h.then!="function"&&a(u,h,p):y===aOs?a(u,h,p):y===iOs||y===cOs||y===mOs?i(u,h,p):!1}}function gOs(s){var t=s.circular,n=s.createCustomConfig,r=s.strict,a={areArraysEqual:r?NF:JRs,areDatesEqual:eOs,areMapsEqual:r?bKe(NKe,NF):NKe,areObjectsEqual:r?NF:tOs,arePrimitiveWrappersEqual:sOs,areRegExpsEqual:nOs,areSetsEqual:r?bKe(kKe,NF):kKe,areTypedArraysEqual:r?NF:rOs};if(n&&(a=CKe({},a,n(a))),t){var i=XH(a.areArraysEqual),l=XH(a.areMapsEqual),o=XH(a.areObjectsEqual),c=XH(a.areSetsEqual);a=CKe({},a,{areArraysEqual:i,areMapsEqual:l,areObjectsEqual:o,areSetsEqual:c})}return a}function yOs(s){return function(t,n,r,a,i,l,o){return s(t,n,o)}}function vOs(s){var t=s.circular,n=s.comparator,r=s.createState,a=s.equals,i=s.strict;if(r)return function(c,d){var u=r(),h=u.cache,p=h===void 0?t?new WeakMap:void 0:h,f=u.meta;return n(c,d,{cache:p,equals:a,meta:f,strict:i})};if(t)return function(c,d){return n(c,d,{cache:new WeakMap,equals:a,meta:void 0,strict:i})};var l={cache:void 0,equals:a,meta:void 0,strict:i};return function(c,d){return n(c,d,l)}}var bOs=aC();aC({strict:!0});aC({circular:!0});aC({circular:!0,strict:!0});aC({createInternalComparator:function(){return uR}});aC({strict:!0,createInternalComparator:function(){return uR}});aC({circular:!0,createInternalComparator:function(){return uR}});aC({circular:!0,createInternalComparator:function(){return uR},strict:!0});function aC(s){s===void 0&&(s={});var t=s.circular,n=t===void 0?!1:t,r=s.createInternalComparator,a=s.createState,i=s.strict,l=i===void 0?!1:i,o=gOs(s),c=xOs(o),d=r?r(c):yOs(c);return vOs({circular:n,comparator:c,createState:a,equals:d,strict:l})}function _Os(s){typeof requestAnimationFrame<"u"&&requestAnimationFrame(s)}function TKe(s){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,n=-1,r=function a(i){n<0&&(n=i),i-n>t?(s(i),n=-1):_Os(a)};requestAnimationFrame(r)}function Q3e(s){"@babel/helpers - typeof";return Q3e=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},Q3e(s)}function wOs(s){return SOs(s)||kOs(s)||NOs(s)||jOs()}function jOs(){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 NOs(s,t){if(s){if(typeof s=="string")return EKe(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return EKe(s,t)}}function EKe(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n1?1:j<0?0:j},_=function(j){for(var w=j>1?1:j,S=w,A=0;A<8;++A){var E=h(S)-w,O=f(S);if(Math.abs(E-w)0&&arguments[0]!==void 0?arguments[0]:{},n=t.stiff,r=n===void 0?100:n,a=t.damping,i=a===void 0?8:a,l=t.dt,o=l===void 0?17:l,c=function(u,h,p){var f=-(u-h)*r,y=p*i,_=p+(f-y)*o/1e3,v=p*o/1e3+u;return Math.abs(v-h)s.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function nFs(s,t){if(s==null)return{};var n={},r=Object.keys(s),a,i;for(i=0;i=0)&&(n[a]=s[a]);return n}function Y2e(s){return oFs(s)||iFs(s)||aFs(s)||rFs()}function rFs(){throw new TypeError(`Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function aFs(s,t){if(s){if(typeof s=="string")return s5e(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return s5e(s,t)}}function iFs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function oFs(s){if(Array.isArray(s))return s5e(s)}function s5e(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n"u"||!Reflect.construct||Reflect.construct.sham)return!1;if(typeof Proxy=="function")return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){})),!0}catch{return!1}}function sge(s){return sge=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},sge(s)}var Lw=function(s){hFs(n,s);var t=mFs(n);function n(r,a){var i;lFs(this,n),i=t.call(this,r,a);var l=i.props,o=l.isActive,c=l.attributeName,d=l.from,u=l.to,h=l.steps,p=l.children,f=l.duration;if(i.handleStyleChange=i.handleStyleChange.bind(a5e(i)),i.changeStyle=i.changeStyle.bind(a5e(i)),!o||f<=0)return i.state={style:{}},typeof p=="function"&&(i.state={style:u}),r5e(i);if(h&&h.length)i.state={style:h[0].style};else if(d){if(typeof p=="function")return i.state={style:d},r5e(i);i.state={style:c?p7({},c,d):d}}else i.state={style:{}};return i}return dFs(n,[{key:"componentDidMount",value:function(){var a=this.props,i=a.isActive,l=a.canBegin;this.mounted=!0,!(!i||!l)&&this.runAnimation(this.props)}},{key:"componentDidUpdate",value:function(a){var i=this.props,l=i.isActive,o=i.canBegin,c=i.attributeName,d=i.shouldReAnimate,u=i.to,h=i.from,p=this.state.style;if(o){if(!l){var f={style:c?p7({},c,u):u};this.state&&p&&(c&&p[c]!==u||!c&&p!==u)&&this.setState(f);return}if(!(bOs(a.to,u)&&a.canBegin&&a.isActive)){var y=!a.canBegin||!a.isActive;this.manager&&this.manager.stop(),this.stopJSAnimation&&this.stopJSAnimation();var _=y||d?h:a.to;if(this.state&&p){var v={style:c?p7({},c,_):_};(c&&p[c]!==_||!c&&p!==_)&&this.setState(v)}this.runAnimation(R1(R1({},this.props),{},{from:_,begin:0}))}}}},{key:"componentWillUnmount",value:function(){this.mounted=!1;var a=this.props.onAnimationEnd;this.unSubscribe&&this.unSubscribe(),this.manager&&(this.manager.stop(),this.manager=null),this.stopJSAnimation&&this.stopJSAnimation(),a&&a()}},{key:"handleStyleChange",value:function(a){this.changeStyle(a)}},{key:"changeStyle",value:function(a){this.mounted&&this.setState({style:a})}},{key:"runJSAnimation",value:function(a){var i=this,l=a.from,o=a.to,c=a.duration,d=a.easing,u=a.begin,h=a.onAnimationEnd,p=a.onAnimationStart,f=eFs(l,o,qOs(d),c,this.changeStyle),y=function(){i.stopJSAnimation=f()};this.manager.start([p,u,y,c,h])}},{key:"runStepAnimation",value:function(a){var i=this,l=a.steps,o=a.begin,c=a.onAnimationStart,d=l[0],u=d.style,h=d.duration,p=h===void 0?0:h,f=function(_,v,j){if(j===0)return _;var w=v.duration,S=v.easing,A=S===void 0?"ease":S,E=v.style,O=v.properties,D=v.onAnimationEnd,I=j>0?l[j-1]:v,F=O||Object.keys(E);if(typeof A=="function"||A==="spring")return[].concat(Y2e(_),[i.runJSAnimation.bind(i,{from:I.style,to:E,duration:w,easing:A}),w]);var z=IKe(F,w,A),H=R1(R1(R1({},I.style),E),{},{transition:z});return[].concat(Y2e(_),[H,w,D]).filter(MOs)};return this.manager.start([c].concat(Y2e(l.reduce(f,[u,Math.max(p,o)])),[a.onAnimationEnd]))}},{key:"runAnimation",value:function(a){this.manager||(this.manager=COs());var i=a.begin,l=a.duration,o=a.attributeName,c=a.to,d=a.easing,u=a.onAnimationStart,h=a.onAnimationEnd,p=a.steps,f=a.children,y=this.manager;if(this.unSubscribe=y.subscribe(this.handleStyleChange),typeof d=="function"||typeof f=="function"||d==="spring"){this.runJSAnimation(a);return}if(p.length>1){this.runStepAnimation(a);return}var _=o?p7({},o,c):c,v=IKe(Object.keys(_),l,d);y.start([u,i,R1(R1({},_),{},{transition:v}),l,h])}},{key:"render",value:function(){var a=this.props,i=a.children;a.begin;var l=a.duration;a.attributeName,a.easing;var o=a.isActive;a.steps,a.from,a.to,a.canBegin,a.onAnimationEnd,a.shouldReAnimate,a.onAnimationReStart;var c=sFs(a,tFs),d=N.Children.count(i),u=this.state.style;if(typeof i=="function")return i(u);if(!o||d===0||l<=0)return i;var h=function(f){var y=f.props,_=y.style,v=_===void 0?{}:_,j=y.className,w=N.cloneElement(f,R1(R1({},c),{},{style:R1(R1({},v),u),className:j}));return w};return d===1?h(N.Children.only(i)):Ct.createElement("div",null,N.Children.map(i,function(p){return h(p)}))}}]),n}(N.PureComponent);Lw.displayName="Animate";Lw.defaultProps={begin:0,duration:1e3,from:"",to:"",attributeName:"",easing:"ease",isActive:!0,canBegin:!0,steps:[],onAnimationEnd:function(){},onAnimationStart:function(){}};Lw.propTypes={from:pc.oneOfType([pc.object,pc.string]),to:pc.oneOfType([pc.object,pc.string]),attributeName:pc.string,duration:pc.number,begin:pc.number,easing:pc.oneOfType([pc.string,pc.func]),steps:pc.arrayOf(pc.shape({duration:pc.number.isRequired,style:pc.object.isRequired,easing:pc.oneOfType([pc.oneOf(["ease","ease-in","ease-out","ease-in-out","linear"]),pc.func]),properties:pc.arrayOf("string"),onAnimationEnd:pc.func})),children:pc.oneOfType([pc.node,pc.func]),isActive:pc.bool,canBegin:pc.bool,onAnimationEnd:pc.func,shouldReAnimate:pc.bool,onAnimationStart:pc.func,onAnimationReStart:pc.func};function QB(s){"@babel/helpers - typeof";return QB=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},QB(s)}function nge(){return nge=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0?1:-1,c=r>=0?1:-1,d=a>=0&&r>=0||a<0&&r<0?1:0,u;if(l>0&&i instanceof Array){for(var h=[0,0,0,0],p=0,f=4;pl?l:i[p];u="M".concat(t,",").concat(n+o*h[0]),h[0]>0&&(u+="A ".concat(h[0],",").concat(h[0],",0,0,").concat(d,",").concat(t+c*h[0],",").concat(n)),u+="L ".concat(t+r-c*h[1],",").concat(n),h[1]>0&&(u+="A ".concat(h[1],",").concat(h[1],",0,0,").concat(d,`, `).concat(t+r,",").concat(n+o*h[1])),u+="L ".concat(t+r,",").concat(n+a-o*h[2]),h[2]>0&&(u+="A ".concat(h[2],",").concat(h[2],",0,0,").concat(d,`, `).concat(t+r-c*h[2],",").concat(n+a)),u+="L ".concat(t+c*h[3],",").concat(n+a),h[3]>0&&(u+="A ".concat(h[3],",").concat(h[3],",0,0,").concat(d,`, `).concat(t,",").concat(n+a-o*h[3])),u+="Z"}else if(l>0&&i===+i&&i>0){var y=Math.min(l,i);u="M ".concat(t,",").concat(n+o*y,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+c*y,",").concat(n,` L `).concat(t+r-c*y,",").concat(n,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+r,",").concat(n+o*y,` L `).concat(t+r,",").concat(n+a-o*y,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t+r-c*y,",").concat(n+a,` L `).concat(t+c*y,",").concat(n+a,` A `).concat(y,",").concat(y,",0,0,").concat(d,",").concat(t,",").concat(n+a-o*y," Z")}else u="M ".concat(t,",").concat(n," h ").concat(r," v ").concat(a," h ").concat(-r," Z");return u},jFs=function(t,n){if(!t||!n)return!1;var r=t.x,a=t.y,i=n.x,l=n.y,o=n.width,c=n.height;if(Math.abs(o)>0&&Math.abs(c)>0){var d=Math.min(i,i+o),u=Math.max(i,i+o),h=Math.min(l,l+c),p=Math.max(l,l+c);return r>=d&&r<=u&&a>=h&&a<=p}return!1},NFs={x:0,y:0,width:0,height:0,radius:0,isAnimationActive:!1,isUpdateAnimationActive:!1,animationBegin:0,animationDuration:1500,animationEasing:"ease"},IPe=function(t){var n=BKe(BKe({},NFs),t),r=N.useRef(),a=N.useState(-1),i=fFs(a,2),l=i[0],o=i[1];N.useEffect(function(){if(r.current&&r.current.getTotalLength)try{var A=r.current.getTotalLength();A&&o(A)}catch{}},[]);var c=n.x,d=n.y,u=n.width,h=n.height,p=n.radius,f=n.className,y=n.animationEasing,_=n.animationDuration,v=n.animationBegin,j=n.isAnimationActive,w=n.isUpdateAnimationActive;if(c!==+c||d!==+d||u!==+u||h!==+h||u===0||h===0)return null;var S=So("recharts-rectangle",f);return w?Ct.createElement(Lw,{canBegin:l>0,from:{width:u,height:h,x:c,y:d},to:{width:u,height:h,x:c,y:d},duration:_,animationEasing:y,isActive:w},function(A){var E=A.width,O=A.height,D=A.x,I=A.y;return Ct.createElement(Lw,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:_,isActive:j,easing:y},Ct.createElement("path",nge({},$i(n,!0),{className:S,d:$Ke(D,I,E,O,p),ref:r})))}):Ct.createElement("path",nge({},$i(n,!0),{className:S,d:$Ke(c,d,u,h,p)}))},kFs=["points","className","baseLinePoints","connectNulls"];function AP(){return AP=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function CFs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function UKe(s){return MFs(s)||AFs(s)||EFs(s)||TFs()}function TFs(){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 EFs(s,t){if(s){if(typeof s=="string")return i5e(s,t);var n=Object.prototype.toString.call(s).slice(8,-1);if(n==="Object"&&s.constructor&&(n=s.constructor.name),n==="Map"||n==="Set")return Array.from(s);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return i5e(s,t)}}function AFs(s){if(typeof Symbol<"u"&&s[Symbol.iterator]!=null||s["@@iterator"]!=null)return Array.from(s)}function MFs(s){if(Array.isArray(s))return i5e(s)}function i5e(s,t){(t==null||t>s.length)&&(t=s.length);for(var n=0,r=new Array(t);n0&&arguments[0]!==void 0?arguments[0]:[],n=[[]];return t.forEach(function(r){qKe(r)?n[n.length-1].push(r):n[n.length-1].length>0&&n.push([])}),qKe(t[0])&&n[n.length-1].push(t[0]),n[n.length-1].length<=0&&(n=n.slice(0,-1)),n},fz=function(t,n){var r=IFs(t);n&&(r=[r.reduce(function(i,l){return[].concat(UKe(i),UKe(l))},[])]);var a=r.map(function(i){return i.reduce(function(l,o,c){return"".concat(l).concat(c===0?"M":"L").concat(o.x,",").concat(o.y)},"")}).join("");return r.length===1?"".concat(a,"Z"):a},PFs=function(t,n,r){var a=fz(t,r);return"".concat(a.slice(-1)==="Z"?a.slice(0,-1):a,"L").concat(fz(n.reverse(),r).slice(1))},LFs=function(t){var n=t.points,r=t.className,a=t.baseLinePoints,i=t.connectNulls,l=SFs(t,kFs);if(!n||!n.length)return null;var o=So("recharts-polygon",r);if(a&&a.length){var c=l.stroke&&l.stroke!=="none",d=PFs(n,a,i);return Ct.createElement("g",{className:o},Ct.createElement("path",AP({},$i(l,!0),{fill:d.slice(-1)==="Z"?l.fill:"none",stroke:"none",d})),c?Ct.createElement("path",AP({},$i(l,!0),{fill:"none",d:fz(n,i)})):null,c?Ct.createElement("path",AP({},$i(l,!0),{fill:"none",d:fz(a,i)})):null)}var u=fz(n,i);return Ct.createElement("path",AP({},$i(l,!0),{fill:u.slice(-1)==="Z"?l.fill:"none",className:o,d:u}))};function o5e(){return o5e=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function $Fs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var UFs=function(t,n,r,a,i,l){return"M".concat(t,",").concat(i,"v").concat(a,"M").concat(l,",").concat(n,"h").concat(r)},qFs=function(t){var n=t.x,r=n===void 0?0:n,a=t.y,i=a===void 0?0:a,l=t.top,o=l===void 0?0:l,c=t.left,d=c===void 0?0:c,u=t.width,h=u===void 0?0:u,p=t.height,f=p===void 0?0:p,y=t.className,_=BFs(t,DFs),v=RFs({x:r,y:i,top:o,left:d,width:h,height:f},_);return!ia(r)||!ia(i)||!ia(h)||!ia(f)||!ia(o)||!ia(d)?null:Ct.createElement("path",l5e({},$i(v,!0),{className:So("recharts-cross",y),d:UFs(r,i,h,f,o,d)}))},VFs=Gve,HFs=l1t,GFs=Qw;function WFs(s,t){return s&&s.length?VFs(s,GFs(t),HFs):void 0}var KFs=WFs;const YFs=_l(KFs);var ZFs=Gve,QFs=Qw,XFs=c1t;function JFs(s,t){return s&&s.length?ZFs(s,QFs(t),XFs):void 0}var e7s=JFs;const t7s=_l(e7s);var s7s=["cx","cy","angle","ticks","axisLine"],n7s=["ticks","tick","angle","tickFormatter","stroke"];function $8(s){"@babel/helpers - typeof";return $8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},$8(s)}function xz(){return xz=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function r7s(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function a7s(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function WKe(s,t){for(var n=0;nZKe?l=a==="outer"?"start":"end":i<-ZKe?l=a==="outer"?"end":"start":l="middle",l}},{key:"renderAxisLine",value:function(){var r=this.props,a=r.cx,i=r.cy,l=r.radius,o=r.axisLine,c=r.axisLineType,d=o3(o3({},$i(this.props,!1)),{},{fill:"none"},$i(o,!1));if(c==="circle")return Ct.createElement(Qve,RE({className:"recharts-polar-angle-axis-line"},d,{cx:a,cy:i,r:l}));var u=this.props.ticks,h=u.map(function(p){return vd(a,i,l,p.coordinate)});return Ct.createElement(LFs,RE({className:"recharts-polar-angle-axis-line"},d,{points:h}))}},{key:"renderTicks",value:function(){var r=this,a=this.props,i=a.ticks,l=a.tick,o=a.tickLine,c=a.tickFormatter,d=a.stroke,u=$i(this.props,!1),h=$i(l,!1),p=o3(o3({},u),{},{fill:"none"},$i(o,!1)),f=i.map(function(y,_){var v=r.getTickLineCoord(y),j=r.getTickTextAnchor(y),w=o3(o3(o3({textAnchor:j},u),{},{stroke:"none",fill:d},h),{},{index:_,payload:y,x:v.x2,y:v.y2});return Ct.createElement(Wl,RE({className:So("recharts-polar-angle-axis-tick",O1t(l)),key:"tick-".concat(y.coordinate)},kM(r.props,y,_)),o&&Ct.createElement("line",RE({className:"recharts-polar-angle-axis-tick-line"},p,v)),l&&t.renderTickItem(l,w,c?c(y.value,_):y.value))});return Ct.createElement(Wl,{className:"recharts-polar-angle-axis-ticks"},f)}},{key:"render",value:function(){var r=this.props,a=r.ticks,i=r.radius,l=r.axisLine;return i<=0||!a||!a.length?null:Ct.createElement(Wl,{className:So("recharts-polar-angle-axis",this.props.className)},l&&this.renderAxisLine(),this.renderTicks())}}],[{key:"renderTickItem",value:function(r,a,i){var l;return Ct.isValidElement(r)?l=Ct.cloneElement(r,a):ho(r)?l=r(a):l=Ct.createElement(SM,RE({},a,{className:"recharts-polar-angle-axis-tick-value"}),i),l}}])}(N.PureComponent);e1e(t1e,"displayName","PolarAngleAxis");e1e(t1e,"axisType","angleAxis");e1e(t1e,"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 b7s=rvt,_7s=b7s(Object.getPrototypeOf,Object),w7s=_7s,j7s=NN,N7s=w7s,k7s=kN,S7s="[object Object]",C7s=Function.prototype,T7s=Object.prototype,sbt=C7s.toString,E7s=T7s.hasOwnProperty,A7s=sbt.call(Object);function M7s(s){if(!k7s(s)||j7s(s)!=S7s)return!1;var t=N7s(s);if(t===null)return!0;var n=E7s.call(t,"constructor")&&t.constructor;return typeof n=="function"&&n instanceof n&&sbt.call(n)==A7s}var I7s=M7s;const P7s=_l(I7s);var L7s=NN,D7s=kN,R7s="[object Boolean]";function O7s(s){return s===!0||s===!1||D7s(s)&&L7s(s)==R7s}var F7s=O7s;const z7s=_l(F7s);function JB(s){"@babel/helpers - typeof";return JB=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},JB(s)}function ige(){return ige=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);n0,from:{upperWidth:0,lowerWidth:0,height:p,x:c,y:d},to:{upperWidth:u,lowerWidth:h,height:p,x:c,y:d},duration:_,animationEasing:y,isActive:j},function(S){var A=S.upperWidth,E=S.lowerWidth,O=S.height,D=S.x,I=S.y;return Ct.createElement(Lw,{canBegin:l>0,from:"0px ".concat(l===-1?1:l,"px"),to:"".concat(l,"px 0px"),attributeName:"strokeDasharray",begin:v,duration:_,easing:y},Ct.createElement("path",ige({},$i(n,!0),{className:w,d:eYe(D,I,A,E,O),ref:r})))}):Ct.createElement("g",null,Ct.createElement("path",ige({},$i(n,!0),{className:w,d:eYe(c,d,u,h,p)})))},Z7s=["option","shapeType","propTransformer","activeClassName","isActive"];function e$(s){"@babel/helpers - typeof";return e$=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},e$(s)}function Q7s(s,t){if(s==null)return{};var n=X7s(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function X7s(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function tYe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function oge(s){for(var t=1;t0?uy(S,"paddingAngle",0):0;if(E){var D=H0(E.endAngle-E.startAngle,S.endAngle-S.startAngle),I=fd(fd({},S),{},{startAngle:w+O,endAngle:w+D(_)+O});v.push(I),w=I.endAngle}else{var F=S.endAngle,z=S.startAngle,H=H0(0,F-z),Z=H(_),Y=fd(fd({},S),{},{startAngle:w+O,endAngle:w+Z+O});v.push(Y),w=Y.endAngle}}),Ct.createElement(Wl,null,r.renderSectorsStatically(v))})}},{key:"attachKeyboardHandlers",value:function(r){var a=this;r.onkeydown=function(i){if(!i.altKey)switch(i.key){case"ArrowLeft":{var l=++a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[l].focus(),a.setState({sectorToFocus:l});break}case"ArrowRight":{var o=--a.state.sectorToFocus<0?a.sectorRefs.length-1:a.state.sectorToFocus%a.sectorRefs.length;a.sectorRefs[o].focus(),a.setState({sectorToFocus:o});break}case"Escape":{a.sectorRefs[a.state.sectorToFocus].blur(),a.setState({sectorToFocus:0});break}}}}},{key:"renderSectors",value:function(){var r=this.props,a=r.sectors,i=r.isAnimationActive,l=this.state.prevSectors;return i&&a&&a.length&&(!l||!EU(l,a))?this.renderSectorsWithAnimation():this.renderSectorsStatically(a)}},{key:"componentDidMount",value:function(){this.pieRef&&this.attachKeyboardHandlers(this.pieRef)}},{key:"render",value:function(){var r=this,a=this.props,i=a.hide,l=a.sectors,o=a.className,c=a.label,d=a.cx,u=a.cy,h=a.innerRadius,p=a.outerRadius,f=a.isAnimationActive,y=this.state.isAnimationFinished;if(i||!l||!l.length||!ia(d)||!ia(u)||!ia(h)||!ia(p))return null;var _=So("recharts-pie",o);return Ct.createElement(Wl,{tabIndex:this.props.rootTabIndex,className:_,ref:function(j){r.pieRef=j}},this.renderSectors(),c&&this.renderLabels(l),wp.renderCallByParent(this.props,null,!1),(!f||y)&&eN.renderCallByParent(this.props,l,!1))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return a.prevIsAnimationActive!==r.isAnimationActive?{prevIsAnimationActive:r.isAnimationActive,prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:[],isAnimationFinished:!0}:r.isAnimationActive&&r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curSectors:r.sectors,prevSectors:a.curSectors,isAnimationFinished:!0}:r.sectors!==a.curSectors?{curSectors:r.sectors,isAnimationFinished:!0}:null}},{key:"getTextAnchor",value:function(r,a){return r>a?"start":r=360?w:w-1)*c,A=v-w*f-S,E=a.reduce(function(I,F){var z=Dm(F,j,0);return I+(ia(z)?z:0)},0),O;if(E>0){var D;O=a.map(function(I,F){var z=Dm(I,j,0),H=Dm(I,u,F),Z=(ia(z)?z:0)/E,Y;F?Y=D.endAngle+Yx(_)*c*(z!==0?1:0):Y=l;var W=Y+Yx(_)*((z!==0?f:0)+Z*A),ee=(Y+W)/2,se=(y.innerRadius+y.outerRadius)/2,oe=[{name:H,value:z,payload:I,dataKey:j,type:p}],he=vd(y.cx,y.cy,se,ee);return D=fd(fd(fd({percent:Z,cornerRadius:i,name:H,tooltipPayload:oe,midAngle:ee,middleRadius:se,tooltipPosition:he},I),y),{},{value:Dm(I,j),startAngle:Y,endAngle:W,payload:I,paddingAngle:Yx(_)*c}),D})}return fd(fd({},y),{},{sectors:O,data:a})});var v9s=Math.ceil,b9s=Math.max;function _9s(s,t,n,r){for(var a=-1,i=b9s(v9s((t-s)/(n||1)),0),l=Array(i);i--;)l[r?i:++a]=s,s+=n;return l}var w9s=_9s,j9s=jvt,aYe=1/0,N9s=17976931348623157e292;function k9s(s){if(!s)return s===0?s:0;if(s=j9s(s),s===aYe||s===-aYe){var t=s<0?-1:1;return t*N9s}return s===s?s:0}var ibt=k9s,S9s=w9s,C9s=zve,Z2e=ibt;function T9s(s){return function(t,n,r){return r&&typeof r!="number"&&C9s(t,n,r)&&(n=r=void 0),t=Z2e(t),n===void 0?(n=t,t=0):n=Z2e(n),r=r===void 0?t0&&r.handleDrag(a.changedTouches[0])}),R0(r,"handleDragEnd",function(){r.setState({isTravellerMoving:!1,isSlideMoving:!1},function(){var a=r.props,i=a.endIndex,l=a.onDragEnd,o=a.startIndex;l==null||l({endIndex:i,startIndex:o})}),r.detachDragEndListener()}),R0(r,"handleLeaveWrapper",function(){(r.state.isTravellerMoving||r.state.isSlideMoving)&&(r.leaveTimer=window.setTimeout(r.handleDragEnd,r.props.leaveTimeOut))}),R0(r,"handleEnterSlideOrTraveller",function(){r.setState({isTextActive:!0})}),R0(r,"handleLeaveSlideOrTraveller",function(){r.setState({isTextActive:!1})}),R0(r,"handleSlideDragStart",function(a){var i=dYe(a)?a.changedTouches[0]:a;r.setState({isTravellerMoving:!1,isSlideMoving:!0,slideMoveStartX:i.pageX}),r.attachDragEndListener()}),r.travellerDragStartHandlers={startX:r.handleTravellerDragStart.bind(r,"startX"),endX:r.handleTravellerDragStart.bind(r,"endX")},r.state={},r}return U9s(t,s),F9s(t,[{key:"componentWillUnmount",value:function(){this.leaveTimer&&(clearTimeout(this.leaveTimer),this.leaveTimer=null),this.detachDragEndListener()}},{key:"getIndex",value:function(r){var a=r.startX,i=r.endX,l=this.state.scaleValues,o=this.props,c=o.gap,d=o.data,u=d.length-1,h=Math.min(a,i),p=Math.max(a,i),f=t.getIndexInRange(l,h),y=t.getIndexInRange(l,p);return{startIndex:f-f%c,endIndex:y===u?u:y-y%c}}},{key:"getTextOfTick",value:function(r){var a=this.props,i=a.data,l=a.tickFormatter,o=a.dataKey,c=Dm(i[r],o,r);return ho(l)?l(c,r):c}},{key:"attachDragEndListener",value:function(){window.addEventListener("mouseup",this.handleDragEnd,!0),window.addEventListener("touchend",this.handleDragEnd,!0),window.addEventListener("mousemove",this.handleDrag,!0)}},{key:"detachDragEndListener",value:function(){window.removeEventListener("mouseup",this.handleDragEnd,!0),window.removeEventListener("touchend",this.handleDragEnd,!0),window.removeEventListener("mousemove",this.handleDrag,!0)}},{key:"handleSlideDrag",value:function(r){var a=this.state,i=a.slideMoveStartX,l=a.startX,o=a.endX,c=this.props,d=c.x,u=c.width,h=c.travellerWidth,p=c.startIndex,f=c.endIndex,y=c.onChange,_=r.pageX-i;_>0?_=Math.min(_,d+u-h-o,d+u-h-l):_<0&&(_=Math.max(_,d-l,d-o));var v=this.getIndex({startX:l+_,endX:o+_});(v.startIndex!==p||v.endIndex!==f)&&y&&y(v),this.setState({startX:l+_,endX:o+_,slideMoveStartX:r.pageX})}},{key:"handleTravellerDragStart",value:function(r,a){var i=dYe(a)?a.changedTouches[0]:a;this.setState({isSlideMoving:!1,isTravellerMoving:!0,movingTravellerId:r,brushMoveStartX:i.pageX}),this.attachDragEndListener()}},{key:"handleTravellerMove",value:function(r){var a=this.state,i=a.brushMoveStartX,l=a.movingTravellerId,o=a.endX,c=a.startX,d=this.state[l],u=this.props,h=u.x,p=u.width,f=u.travellerWidth,y=u.onChange,_=u.gap,v=u.data,j={startX:this.state.startX,endX:this.state.endX},w=r.pageX-i;w>0?w=Math.min(w,h+p-f-d):w<0&&(w=Math.max(w,h-d)),j[l]=d+w;var S=this.getIndex(j),A=S.startIndex,E=S.endIndex,O=function(){var I=v.length-1;return l==="startX"&&(o>c?A%_===0:E%_===0)||oc?E%_===0:A%_===0)||o>c&&E===I};this.setState(R0(R0({},l,d+w),"brushMoveStartX",r.pageX),function(){y&&O()&&y(S)})}},{key:"handleTravellerMoveKeyboard",value:function(r,a){var i=this,l=this.state,o=l.scaleValues,c=l.startX,d=l.endX,u=this.state[a],h=o.indexOf(u);if(h!==-1){var p=h+r;if(!(p===-1||p>=o.length)){var f=o[p];a==="startX"&&f>=d||a==="endX"&&f<=c||this.setState(R0({},a,f),function(){i.props.onChange(i.getIndex({startX:i.state.startX,endX:i.state.endX}))})}}}},{key:"renderBackground",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.fill,d=r.stroke;return Ct.createElement("rect",{stroke:d,fill:c,x:a,y:i,width:l,height:o})}},{key:"renderPanorama",value:function(){var r=this.props,a=r.x,i=r.y,l=r.width,o=r.height,c=r.data,d=r.children,u=r.padding,h=N.Children.only(d);return h?Ct.cloneElement(h,{x:a,y:i,width:l,height:o,margin:u,compact:!0,data:c}):null}},{key:"renderTravellerLayer",value:function(r,a){var i,l,o=this,c=this.props,d=c.y,u=c.travellerWidth,h=c.height,p=c.traveller,f=c.ariaLabel,y=c.data,_=c.startIndex,v=c.endIndex,j=Math.max(r,this.props.x),w=Q2e(Q2e({},$i(this.props,!1)),{},{x:j,y:d,width:u,height:h}),S=f||"Min value: ".concat((i=y[_])===null||i===void 0?void 0:i.name,", Max value: ").concat((l=y[v])===null||l===void 0?void 0:l.name);return Ct.createElement(Wl,{tabIndex:0,role:"slider","aria-label":S,"aria-valuenow":r,className:"recharts-brush-traveller",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.travellerDragStartHandlers[a],onTouchStart:this.travellerDragStartHandlers[a],onKeyDown:function(E){["ArrowLeft","ArrowRight"].includes(E.key)&&(E.preventDefault(),E.stopPropagation(),o.handleTravellerMoveKeyboard(E.key==="ArrowRight"?1:-1,a))},onFocus:function(){o.setState({isTravellerFocused:!0})},onBlur:function(){o.setState({isTravellerFocused:!1})},style:{cursor:"col-resize"}},t.renderTraveller(p,w))}},{key:"renderSlide",value:function(r,a){var i=this.props,l=i.y,o=i.height,c=i.stroke,d=i.travellerWidth,u=Math.min(r,a)+d,h=Math.max(Math.abs(a-r)-d,0);return Ct.createElement("rect",{className:"recharts-brush-slide",onMouseEnter:this.handleEnterSlideOrTraveller,onMouseLeave:this.handleLeaveSlideOrTraveller,onMouseDown:this.handleSlideDragStart,onTouchStart:this.handleSlideDragStart,style:{cursor:"move"},stroke:"none",fill:c,fillOpacity:.2,x:u,y:l,width:h,height:o})}},{key:"renderText",value:function(){var r=this.props,a=r.startIndex,i=r.endIndex,l=r.y,o=r.height,c=r.travellerWidth,d=r.stroke,u=this.state,h=u.startX,p=u.endX,f=5,y={pointerEvents:"none",fill:d};return Ct.createElement(Wl,{className:"recharts-brush-texts"},Ct.createElement(SM,dge({textAnchor:"end",verticalAnchor:"middle",x:Math.min(h,p)-f,y:l+o/2},y),this.getTextOfTick(a)),Ct.createElement(SM,dge({textAnchor:"start",verticalAnchor:"middle",x:Math.max(h,p)+c+f,y:l+o/2},y),this.getTextOfTick(i)))}},{key:"render",value:function(){var r=this.props,a=r.data,i=r.className,l=r.children,o=r.x,c=r.y,d=r.width,u=r.height,h=r.alwaysShowText,p=this.state,f=p.startX,y=p.endX,_=p.isTextActive,v=p.isSlideMoving,j=p.isTravellerMoving,w=p.isTravellerFocused;if(!a||!a.length||!ia(o)||!ia(c)||!ia(d)||!ia(u)||d<=0||u<=0)return null;var S=So("recharts-brush",i),A=Ct.Children.count(l)===1,E=R9s("userSelect","none");return Ct.createElement(Wl,{className:S,onMouseLeave:this.handleLeaveWrapper,onTouchMove:this.handleTouchMove,style:E},this.renderBackground(),A&&this.renderPanorama(),this.renderSlide(f,y),this.renderTravellerLayer(f,"startX"),this.renderTravellerLayer(y,"endX"),(_||v||j||w||h)&&this.renderText())}}],[{key:"renderDefaultTraveller",value:function(r){var a=r.x,i=r.y,l=r.width,o=r.height,c=r.stroke,d=Math.floor(i+o/2)-1;return Ct.createElement(Ct.Fragment,null,Ct.createElement("rect",{x:a,y:i,width:l,height:o,fill:c,stroke:"none"}),Ct.createElement("line",{x1:a+1,y1:d,x2:a+l-1,y2:d,fill:"none",stroke:"#fff"}),Ct.createElement("line",{x1:a+1,y1:d+2,x2:a+l-1,y2:d+2,fill:"none",stroke:"#fff"}))}},{key:"renderTraveller",value:function(r,a){var i;return Ct.isValidElement(r)?i=Ct.cloneElement(r,a):ho(r)?i=r(a):i=t.renderDefaultTraveller(a),i}},{key:"getDerivedStateFromProps",value:function(r,a){var i=r.data,l=r.width,o=r.x,c=r.travellerWidth,d=r.updateId,u=r.startIndex,h=r.endIndex;if(i!==a.prevData||d!==a.prevUpdateId)return Q2e({prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l},i&&i.length?V9s({data:i,width:l,x:o,travellerWidth:c,startIndex:u,endIndex:h}):{scale:null,scaleValues:null});if(a.scale&&(l!==a.prevWidth||o!==a.prevX||c!==a.prevTravellerWidth)){a.scale.range([o,o+l-c]);var p=a.scale.domain().map(function(f){return a.scale(f)});return{prevData:i,prevTravellerWidth:c,prevUpdateId:d,prevX:o,prevWidth:l,startX:a.scale(r.startIndex),endX:a.scale(r.endIndex),scaleValues:p}}return null}},{key:"getIndexInRange",value:function(r,a){for(var i=r.length,l=0,o=i-1;o-l>1;){var c=Math.floor((l+o)/2);r[c]>a?o=c:l=c}return a>=r[o]?o:l}}])}(N.PureComponent);R0(H8,"displayName","Brush");R0(H8,"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 H9s=rPe;function G9s(s,t){var n;return H9s(s,function(r,a,i){return n=t(r,a,i),!n}),!!n}var W9s=G9s,K9s=Zyt,Y9s=Qw,Z9s=W9s,Q9s=r0,X9s=zve;function J9s(s,t,n){var r=Q9s(s)?K9s:Z9s;return n&&X9s(s,t,n)&&(t=void 0),r(s,Y9s(t))}var ezs=J9s;const tzs=_l(ezs);var Nw=function(t,n){var r=t.alwaysShow,a=t.ifOverflow;return r&&(a="extendDomain"),a===n},uYe=yvt;function szs(s,t,n){t=="__proto__"&&uYe?uYe(s,t,{configurable:!0,enumerable:!0,value:n,writable:!0}):s[t]=n}var nzs=szs,rzs=nzs,azs=xvt,izs=Qw;function ozs(s,t){var n={};return t=izs(t),azs(s,function(r,a,i){rzs(n,a,t(r,a,i))}),n}var lzs=ozs;const czs=_l(lzs);function dzs(s,t){for(var n=-1,r=s==null?0:s.length;++n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Czs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function Tzs(s,t){var n=s.x,r=s.y,a=Szs(s,wzs),i="".concat(n),l=parseInt(i,10),o="".concat(r),c=parseInt(o,10),d="".concat(t.height||a.height),u=parseInt(d,10),h="".concat(t.width||a.width),p=parseInt(h,10);return kF(kF(kF(kF(kF({},t),a),l?{x:l}:{}),c?{y:c}:{}),{},{height:u,width:p,name:t.name,radius:t.radius})}function mYe(s){return Ct.createElement(nbt,m5e({shapeType:"rectangle",propTransformer:Tzs,activeClassName:"recharts-active-bar"},s))}var Ezs=function(t){var n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0;return function(r,a){if(typeof t=="number")return t;var i=ia(r)||dks(r);return i?t(r,a):(i||TM(),n)}},Azs=["value","background"],ubt;function G8(s){"@babel/helpers - typeof";return G8=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},G8(s)}function Mzs(s,t){if(s==null)return{};var n=Izs(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function Izs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function hge(){return hge=Object.assign?Object.assign.bind():function(s){for(var t=1;t0&&Math.abs(ee)0&&Math.abs(W)0&&(Y=Math.min((Te||0)-(W[Ie-1]||0),Y))}),Number.isFinite(Y)){var ee=Y/Z,se=_.layout==="vertical"?r.height:r.width;if(_.padding==="gap"&&(D=ee*se/2),_.padding==="no-gap"){var oe=Zx(t.barCategoryGap,ee*se),he=ee*se/2;D=he-oe-(he-oe)/se*oe}}}a==="xAxis"?I=[r.left+(S.left||0)+(D||0),r.left+r.width-(S.right||0)-(D||0)]:a==="yAxis"?I=c==="horizontal"?[r.top+r.height-(S.bottom||0),r.top+(S.top||0)]:[r.top+(S.top||0)+(D||0),r.top+r.height-(S.bottom||0)-(D||0)]:I=_.range,E&&(I=[I[1],I[0]]);var ce=A1t(_,i,p),me=ce.scale,le=ce.realScaleType;me.domain(j).range(I),M1t(me);var ve=I1t(me,K1(K1({},_),{},{realScaleType:le}));a==="xAxis"?(H=v==="top"&&!A||v==="bottom"&&A,F=r.left,z=h[O]-H*_.height):a==="yAxis"&&(H=v==="left"&&!A||v==="right"&&A,F=h[O]-H*_.width,z=r.top);var ge=K1(K1(K1({},_),ve),{},{realScaleType:le,x:F,y:z,scale:me,width:a==="xAxis"?r.width:_.width,height:a==="yAxis"?r.height:_.height});return ge.bandSize=Zxe(ge,ve),!_.hide&&a==="xAxis"?h[O]+=(H?-1:1)*ge.height:_.hide||(h[O]+=(H?-1:1)*ge.width),K1(K1({},f),{},r1e({},y,ge))},{})},xbt=function(t,n){var r=t.x,a=t.y,i=n.x,l=n.y;return{x:Math.min(r,i),y:Math.min(a,l),width:Math.abs(i-r),height:Math.abs(l-a)}},qzs=function(t){var n=t.x1,r=t.y1,a=t.x2,i=t.y2;return xbt({x:n,y:r},{x:a,y:i})},gbt=function(){function s(t){Bzs(this,s),this.scale=t}return $zs(s,[{key:"domain",get:function(){return this.scale.domain}},{key:"range",get:function(){return this.scale.range}},{key:"rangeMin",get:function(){return this.range()[0]}},{key:"rangeMax",get:function(){return this.range()[1]}},{key:"bandwidth",get:function(){return this.scale.bandwidth}},{key:"apply",value:function(n){var r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},a=r.bandAware,i=r.position;if(n!==void 0){if(i)switch(i){case"start":return this.scale(n);case"middle":{var l=this.bandwidth?this.bandwidth()/2:0;return this.scale(n)+l}case"end":{var o=this.bandwidth?this.bandwidth():0;return this.scale(n)+o}default:return this.scale(n)}if(a){var c=this.bandwidth?this.bandwidth()/2:0;return this.scale(n)+c}return this.scale(n)}}},{key:"isInRange",value:function(n){var r=this.range(),a=r[0],i=r[r.length-1];return a<=i?n>=a&&n<=i:n>=i&&n<=a}}],[{key:"create",value:function(n){return new s(n)}}])}();r1e(gbt,"EPS",1e-4);var PPe=function(t){var n=Object.keys(t).reduce(function(r,a){return K1(K1({},r),{},r1e({},a,gbt.create(t[a])))},{});return K1(K1({},n),{},{apply:function(a){var i=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},l=i.bandAware,o=i.position;return czs(a,function(c,d){return n[d].apply(c,{bandAware:l,position:o})})},isInRange:function(a){return dbt(a,function(i,l){return n[l].isInRange(i)})}})};function Vzs(s){return(s%180+180)%180}var Hzs=function(t){var n=t.width,r=t.height,a=arguments.length>1&&arguments[1]!==void 0?arguments[1]:0,i=Vzs(a),l=i*Math.PI/180,o=Math.atan(r/n),c=l>o&&l-1?a[i?t[l]:l]:void 0}}var Zzs=Yzs,Qzs=ibt;function Xzs(s){var t=Qzs(s),n=t%1;return t===t?n?t-n:t:0}var Jzs=Xzs,eBs=dvt,tBs=Qw,sBs=Jzs,nBs=Math.max;function rBs(s,t,n){var r=s==null?0:s.length;if(!r)return-1;var a=n==null?0:sBs(n);return a<0&&(a=nBs(r+a,0)),eBs(s,tBs(t),a)}var aBs=rBs,iBs=Zzs,oBs=aBs,lBs=iBs(oBs),cBs=lBs;const dBs=_l(cBs);var uBs=pNs(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("")}),LPe=N.createContext(void 0),DPe=N.createContext(void 0),ybt=N.createContext(void 0),vbt=N.createContext({}),bbt=N.createContext(void 0),_bt=N.createContext(0),wbt=N.createContext(0),yYe=function(t){var n=t.state,r=n.xAxisMap,a=n.yAxisMap,i=n.offset,l=t.clipPathId,o=t.children,c=t.width,d=t.height,u=uBs(i);return Ct.createElement(LPe.Provider,{value:r},Ct.createElement(DPe.Provider,{value:a},Ct.createElement(vbt.Provider,{value:i},Ct.createElement(ybt.Provider,{value:u},Ct.createElement(bbt.Provider,{value:l},Ct.createElement(_bt.Provider,{value:d},Ct.createElement(wbt.Provider,{value:c},o)))))))},hBs=function(){return N.useContext(bbt)},jbt=function(t){var n=N.useContext(LPe);n==null&&TM();var r=n[t];return r==null&&TM(),r},mBs=function(){var t=N.useContext(LPe);return cS(t)},pBs=function(){var t=N.useContext(DPe),n=dBs(t,function(r){return dbt(r.domain,Number.isFinite)});return n||cS(t)},Nbt=function(t){var n=N.useContext(DPe);n==null&&TM();var r=n[t];return r==null&&TM(),r},fBs=function(){var t=N.useContext(ybt);return t},xBs=function(){return N.useContext(vbt)},RPe=function(){return N.useContext(wbt)},OPe=function(){return N.useContext(_bt)};function W8(s){"@babel/helpers - typeof";return W8=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},W8(s)}function gBs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function yBs(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);ns*a)return!1;var i=n();return s*(t-s*i/2-r)>=0&&s*(t+s*i/2-a)<=0}function JBs(s,t){return Mbt(s,t+1)}function e$s(s,t,n,r,a){for(var i=(r||[]).slice(),l=t.start,o=t.end,c=0,d=1,u=l,h=function(){var y=r==null?void 0:r[c];if(y===void 0)return{v:Mbt(r,d)};var _=c,v,j=function(){return v===void 0&&(v=n(y,_)),v},w=y.coordinate,S=c===0||gge(s,w,j,u,o);S||(c=0,u=l,d+=1),S&&(u=w+s*(j()/2+a),c+=d)},p;d<=i.length;)if(p=h(),p)return p.v;return[]}function a$(s){"@babel/helpers - typeof";return a$=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},a$(s)}function SYe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function Hf(s){for(var t=1;t0?f.coordinate-v*s:f.coordinate})}else i[p]=f=Hf(Hf({},f),{},{tickCoord:f.coordinate});var j=gge(s,f.tickCoord,_,o,c);j&&(c=f.tickCoord-s*(_()/2+a),i[p]=Hf(Hf({},f),{},{isShow:!0}))},u=l-1;u>=0;u--)d(u);return i}function a$s(s,t,n,r,a,i){var l=(r||[]).slice(),o=l.length,c=t.start,d=t.end;if(i){var u=r[o-1],h=n(u,o-1),p=s*(u.coordinate+s*h/2-d);l[o-1]=u=Hf(Hf({},u),{},{tickCoord:p>0?u.coordinate-p*s:u.coordinate});var f=gge(s,u.tickCoord,function(){return h},c,d);f&&(d=u.tickCoord-s*(h/2+a),l[o-1]=Hf(Hf({},u),{},{isShow:!0}))}for(var y=i?o-1:o,_=function(w){var S=l[w],A,E=function(){return A===void 0&&(A=n(S,w)),A};if(w===0){var O=s*(S.coordinate-s*E()/2-c);l[w]=S=Hf(Hf({},S),{},{tickCoord:O<0?S.coordinate-O*s:S.coordinate})}else l[w]=S=Hf(Hf({},S),{},{tickCoord:S.coordinate});var D=gge(s,S.tickCoord,E,c,d);D&&(c=S.tickCoord+s*(E()/2+a),l[w]=Hf(Hf({},S),{},{isShow:!0}))},v=0;v=2?Yx(a[1].coordinate-a[0].coordinate):1,j=XBs(i,v,f);return c==="equidistantPreserveStart"?e$s(v,j,_,a,l):(c==="preserveStart"||c==="preserveStartEnd"?p=a$s(v,j,_,a,l,c==="preserveStartEnd"):p=r$s(v,j,_,a,l),p.filter(function(w){return w.isShow}))}var i$s=["viewBox"],o$s=["viewBox"],l$s=["ticks"];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 IP(){return IP=Object.assign?Object.assign.bind():function(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function c$s(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function d$s(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function TYe(s,t){for(var n=0;n0?c(this.props):c(f)),l<=0||o<=0||!y||!y.length?null:Ct.createElement(Wl,{className:So("recharts-cartesian-axis",d),ref:function(v){r.layerReference=v}},i&&this.renderAxisLine(),this.renderTicks(y,this.state.fontSize,this.state.letterSpacing),wp.renderCallByParent(this.props))}}],[{key:"renderTickItem",value:function(r,a,i){var l,o=So(a.className,"recharts-cartesian-axis-tick-value");return Ct.isValidElement(r)?l=Ct.cloneElement(r,jm(jm({},a),{},{className:o})):ho(r)?l=r(jm(jm({},a),{},{className:o})):l=Ct.createElement(SM,IP({},a,{className:"recharts-cartesian-axis-tick-value"}),i),l}}])}(N.Component);$Pe(hR,"displayName","CartesianAxis");$Pe(hR,"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 g$s=["x1","y1","x2","y2","key"],y$s=["offset"];function EM(s){"@babel/helpers - typeof";return EM=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},EM(s)}function EYe(s,t){var n=Object.keys(s);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(s);t&&(r=r.filter(function(a){return Object.getOwnPropertyDescriptor(s,a).enumerable})),n.push.apply(n,r)}return n}function Yf(s){for(var t=1;t=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function w$s(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}var j$s=function(t){var n=t.fill;if(!n||n==="none")return null;var r=t.fillOpacity,a=t.x,i=t.y,l=t.width,o=t.height,c=t.ry;return Ct.createElement("rect",{x:a,y:i,ry:c,width:l,height:o,stroke:"none",fill:n,fillOpacity:r,className:"recharts-cartesian-grid-bg"})};function Lbt(s,t){var n;if(Ct.isValidElement(s))n=Ct.cloneElement(s,t);else if(ho(s))n=s(t);else{var r=t.x1,a=t.y1,i=t.x2,l=t.y2,o=t.key,c=AYe(t,g$s),d=$i(c,!1);d.offset;var u=AYe(d,y$s);n=Ct.createElement("line",XE({},u,{x1:r,y1:a,x2:i,y2:l,fill:"none",key:o}))}return n}function N$s(s){var t=s.x,n=s.width,r=s.horizontal,a=r===void 0?!0:r,i=s.horizontalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=Yf(Yf({},s),{},{x1:t,y1:o,x2:t+n,y2:o,key:"line-".concat(c),index:c});return Lbt(a,d)});return Ct.createElement("g",{className:"recharts-cartesian-grid-horizontal"},l)}function k$s(s){var t=s.y,n=s.height,r=s.vertical,a=r===void 0?!0:r,i=s.verticalPoints;if(!a||!i||!i.length)return null;var l=i.map(function(o,c){var d=Yf(Yf({},s),{},{x1:o,y1:t,x2:o,y2:t+n,key:"line-".concat(c),index:c});return Lbt(a,d)});return Ct.createElement("g",{className:"recharts-cartesian-grid-vertical"},l)}function S$s(s){var t=s.horizontalFill,n=s.fillOpacity,r=s.x,a=s.y,i=s.width,l=s.height,o=s.horizontalPoints,c=s.horizontal,d=c===void 0?!0:c;if(!d||!t||!t.length)return null;var u=o.map(function(p){return Math.round(p+a-a)}).sort(function(p,f){return p-f});a!==u[0]&&u.unshift(0);var h=u.map(function(p,f){var y=!u[f+1],_=y?a+l-p:u[f+1]-p;if(_<=0)return null;var v=f%t.length;return Ct.createElement("rect",{key:"react-".concat(f),y:p,x:r,height:_,width:i,stroke:"none",fill:t[v],fillOpacity:n,className:"recharts-cartesian-grid-bg"})});return Ct.createElement("g",{className:"recharts-cartesian-gridstripes-horizontal"},h)}function C$s(s){var t=s.vertical,n=t===void 0?!0:t,r=s.verticalFill,a=s.fillOpacity,i=s.x,l=s.y,o=s.width,c=s.height,d=s.verticalPoints;if(!n||!r||!r.length)return null;var u=d.map(function(p){return Math.round(p+i-i)}).sort(function(p,f){return p-f});i!==u[0]&&u.unshift(0);var h=u.map(function(p,f){var y=!u[f+1],_=y?i+o-p:u[f+1]-p;if(_<=0)return null;var v=f%r.length;return Ct.createElement("rect",{key:"react-".concat(f),x:p,y:l,width:_,height:c,stroke:"none",fill:r[v],fillOpacity:a,className:"recharts-cartesian-grid-bg"})});return Ct.createElement("g",{className:"recharts-cartesian-gridstripes-vertical"},h)}var T$s=function(t,n){var r=t.xAxis,a=t.width,i=t.height,l=t.offset;return E1t(BPe(Yf(Yf(Yf({},hR.defaultProps),r),{},{ticks:z2(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.left,l.left+l.width,n)},E$s=function(t,n){var r=t.yAxis,a=t.width,i=t.height,l=t.offset;return E1t(BPe(Yf(Yf(Yf({},hR.defaultProps),r),{},{ticks:z2(r,!0),viewBox:{x:0,y:0,width:a,height:i}})),l.top,l.top+l.height,n)},MI={horizontal:!0,vertical:!0,horizontalPoints:[],verticalPoints:[],stroke:"#ccc",fill:"none",verticalFill:[],horizontalFill:[]};function UPe(s){var t,n,r,a,i,l,o=RPe(),c=OPe(),d=xBs(),u=Yf(Yf({},s),{},{stroke:(t=s.stroke)!==null&&t!==void 0?t:MI.stroke,fill:(n=s.fill)!==null&&n!==void 0?n:MI.fill,horizontal:(r=s.horizontal)!==null&&r!==void 0?r:MI.horizontal,horizontalFill:(a=s.horizontalFill)!==null&&a!==void 0?a:MI.horizontalFill,vertical:(i=s.vertical)!==null&&i!==void 0?i:MI.vertical,verticalFill:(l=s.verticalFill)!==null&&l!==void 0?l:MI.verticalFill,x:ia(s.x)?s.x:d.left,y:ia(s.y)?s.y:d.top,width:ia(s.width)?s.width:d.width,height:ia(s.height)?s.height:d.height}),h=u.x,p=u.y,f=u.width,y=u.height,_=u.syncWithTicks,v=u.horizontalValues,j=u.verticalValues,w=mBs(),S=pBs();if(!ia(f)||f<=0||!ia(y)||y<=0||!ia(h)||h!==+h||!ia(p)||p!==+p)return null;var A=u.verticalCoordinatesGenerator||T$s,E=u.horizontalCoordinatesGenerator||E$s,O=u.horizontalPoints,D=u.verticalPoints;if((!O||!O.length)&&ho(E)){var I=v&&v.length,F=E({yAxis:S?Yf(Yf({},S),{},{ticks:I?v:S.ticks}):void 0,width:o,height:c,offset:d},I?!0:_);bb(Array.isArray(F),"horizontalCoordinatesGenerator should return Array but instead it returned [".concat(EM(F),"]")),Array.isArray(F)&&(O=F)}if((!D||!D.length)&&ho(A)){var z=j&&j.length,H=A({xAxis:w?Yf(Yf({},w),{},{ticks:z?j:w.ticks}):void 0,width:o,height:c,offset:d},z?!0:_);bb(Array.isArray(H),"verticalCoordinatesGenerator should return Array but instead it returned [".concat(EM(H),"]")),Array.isArray(H)&&(D=H)}return Ct.createElement("g",{className:"recharts-cartesian-grid"},Ct.createElement(j$s,{fill:u.fill,fillOpacity:u.fillOpacity,x:u.x,y:u.y,width:u.width,height:u.height,ry:u.ry}),Ct.createElement(N$s,XE({},u,{offset:d,horizontalPoints:O,xAxis:w,yAxis:S})),Ct.createElement(k$s,XE({},u,{offset:d,verticalPoints:D,xAxis:w,yAxis:S})),Ct.createElement(S$s,XE({},u,{horizontalPoints:O})),Ct.createElement(C$s,XE({},u,{verticalPoints:D})))}UPe.displayName="CartesianGrid";var A$s=["type","layout","connectNulls","ref"],M$s=["key"];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 MYe(s,t){if(s==null)return{};var n=I$s(s,t),r,a;if(Object.getOwnPropertySymbols){var i=Object.getOwnPropertySymbols(s);for(a=0;a=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function I$s(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function gz(){return gz=Object.assign?Object.assign.bind():function(s){for(var t=1;ts.length)&&(t=s.length);for(var n=0,r=new Array(t);nh){f=[].concat(II(c.slice(0,y)),[h-_]);break}var v=f.length%2===0?[0,p]:[p];return[].concat(II(t.repeat(c,u)),II(f),v).map(function(j){return"".concat(j,"px")}).join(", ")}),Y1(n,"id",nR("recharts-line-")),Y1(n,"pathRef",function(l){n.mainCurve=l}),Y1(n,"handleAnimationEnd",function(){n.setState({isAnimationFinished:!0}),n.props.onAnimationEnd&&n.props.onAnimationEnd()}),Y1(n,"handleAnimationStart",function(){n.setState({isAnimationFinished:!1}),n.props.onAnimationStart&&n.props.onAnimationStart()}),n}return U$s(t,s),F$s(t,[{key:"componentDidMount",value:function(){if(this.props.isAnimationActive){var r=this.getTotalLength();this.setState({totalLength:r})}}},{key:"componentDidUpdate",value:function(){if(this.props.isAnimationActive){var r=this.getTotalLength();r!==this.state.totalLength&&this.setState({totalLength:r})}}},{key:"getTotalLength",value:function(){var r=this.mainCurve;try{return r&&r.getTotalLength&&r.getTotalLength()||0}catch{return 0}}},{key:"renderErrorBar",value:function(r,a){if(this.props.isAnimationActive&&!this.state.isAnimationFinished)return null;var i=this.props,l=i.points,o=i.xAxis,c=i.yAxis,d=i.layout,u=i.children,h=hy(u,AU);if(!h)return null;var p=function(_,v){return{x:_.x,y:_.y,value:_.value,errorVal:Dm(_.payload,v)}},f={clipPath:r?"url(#clipPath-".concat(a,")"):null};return Ct.createElement(Wl,f,h.map(function(y){return Ct.cloneElement(y,{key:"bar-".concat(y.props.dataKey),data:l,xAxis:o,yAxis:c,layout:d,dataPointFormatter:p})}))}},{key:"renderDots",value:function(r,a,i){var l=this.props.isAnimationActive;if(l&&!this.state.isAnimationFinished)return null;var o=this.props,c=o.dot,d=o.points,u=o.dataKey,h=$i(this.props,!1),p=$i(c,!0),f=d.map(function(_,v){var j=P0(P0(P0({key:"dot-".concat(v),r:3},h),p),{},{index:v,cx:_.x,cy:_.y,value:_.value,dataKey:u,payload:_.payload,points:d});return t.renderDotItem(c,j)}),y={clipPath:r?"url(#clipPath-".concat(a?"":"dots-").concat(i,")"):null};return Ct.createElement(Wl,gz({className:"recharts-line-dots",key:"dots"},y),f)}},{key:"renderCurveStatically",value:function(r,a,i,l){var o=this.props,c=o.type,d=o.layout,u=o.connectNulls;o.ref;var h=MYe(o,A$s),p=P0(P0(P0({},$i(h,!0)),{},{fill:"none",className:"recharts-line-curve",clipPath:a?"url(#clipPath-".concat(i,")"):null,points:r},l),{},{type:c,layout:d,connectNulls:u});return Ct.createElement(Jxe,gz({},p,{pathRef:this.pathRef}))}},{key:"renderCurveWithAnimation",value:function(r,a){var i=this,l=this.props,o=l.points,c=l.strokeDasharray,d=l.isAnimationActive,u=l.animationBegin,h=l.animationDuration,p=l.animationEasing,f=l.animationId,y=l.animateNewValues,_=l.width,v=l.height,j=this.state,w=j.prevPoints,S=j.totalLength;return Ct.createElement(Lw,{begin:u,duration:h,isActive:d,easing:p,from:{t:0},to:{t:1},key:"line-".concat(f),onAnimationEnd:this.handleAnimationEnd,onAnimationStart:this.handleAnimationStart},function(A){var E=A.t;if(w){var O=w.length/o.length,D=o.map(function(Z,Y){var W=Math.floor(Y*O);if(w[W]){var ee=w[W],se=H0(ee.x,Z.x),oe=H0(ee.y,Z.y);return P0(P0({},Z),{},{x:se(E),y:oe(E)})}if(y){var he=H0(_*2,Z.x),ce=H0(v/2,Z.y);return P0(P0({},Z),{},{x:he(E),y:ce(E)})}return P0(P0({},Z),{},{x:Z.x,y:Z.y})});return i.renderCurveStatically(D,r,a)}var I=H0(0,S),F=I(E),z;if(c){var H="".concat(c).split(/[,\s]+/gim).map(function(Z){return parseFloat(Z)});z=i.getStrokeDasharray(F,S,H)}else z=i.generateSimpleStrokeDasharray(S,F);return i.renderCurveStatically(o,r,a,{strokeDasharray:z})})}},{key:"renderCurve",value:function(r,a){var i=this.props,l=i.points,o=i.isAnimationActive,c=this.state,d=c.prevPoints,u=c.totalLength;return o&&l&&l.length&&(!d&&u>0||!EU(d,l))?this.renderCurveWithAnimation(r,a):this.renderCurveStatically(l,r,a)}},{key:"render",value:function(){var r,a=this.props,i=a.hide,l=a.dot,o=a.points,c=a.className,d=a.xAxis,u=a.yAxis,h=a.top,p=a.left,f=a.width,y=a.height,_=a.isAnimationActive,v=a.id;if(i||!o||!o.length)return null;var j=this.state.isAnimationFinished,w=o.length===1,S=So("recharts-line",c),A=d&&d.allowDataOverflow,E=u&&u.allowDataOverflow,O=A||E,D=jo(v)?this.id:v,I=(r=$i(l,!1))!==null&&r!==void 0?r:{r:3,strokeWidth:2},F=I.r,z=F===void 0?3:F,H=I.strokeWidth,Z=H===void 0?2:H,Y=wks(l)?l:{},W=Y.clipDot,ee=W===void 0?!0:W,se=z*2+Z;return Ct.createElement(Wl,{className:S},A||E?Ct.createElement("defs",null,Ct.createElement("clipPath",{id:"clipPath-".concat(D)},Ct.createElement("rect",{x:A?p:p-f/2,y:E?h:h-y/2,width:A?f:f*2,height:E?y:y*2})),!ee&&Ct.createElement("clipPath",{id:"clipPath-dots-".concat(D)},Ct.createElement("rect",{x:p-se/2,y:h-se/2,width:f+se,height:y+se}))):null,!w&&this.renderCurve(O,D),this.renderErrorBar(O,D),(w||l)&&this.renderDots(O,ee,D),(!_||j)&&eN.renderCallByParent(this.props,o))}}],[{key:"getDerivedStateFromProps",value:function(r,a){return r.animationId!==a.prevAnimationId?{prevAnimationId:r.animationId,curPoints:r.points,prevPoints:a.curPoints}:r.points!==a.curPoints?{curPoints:r.points}:null}},{key:"repeat",value:function(r,a){for(var i=r.length%2!==0?[].concat(II(r),[0]):r,l=[],o=0;os.length)&&(t=s.length);for(var n=0,r=new Array(t);n=0)&&Object.prototype.propertyIsEnumerable.call(s,r)&&(n[r]=s[r])}return n}function MUs(s,t){if(s==null)return{};var n={};for(var r in s)if(Object.prototype.hasOwnProperty.call(s,r)){if(t.indexOf(r)>=0)continue;n[r]=s[r]}return n}function IUs(s,t){if(!(s instanceof t))throw new TypeError("Cannot call a class as a function")}function PUs(s,t){for(var n=0;ns.length)&&(t=s.length);for(var n=0,r=new Array(t);n0?l:t&&t.length&&ia(a)&&ia(i)?t.slice(a,i+1):[]};function Zbt(s){return s==="number"?[0,"auto"]:void 0}var I5e=function(t,n,r,a){var i=t.graphicalItems,l=t.tooltipAxis,o=c1e(n,t);return r<0||!i||!i.length||r>=o.length?null:i.reduce(function(c,d){var u,h=(u=d.props.data)!==null&&u!==void 0?u:n;h&&t.dataStartIndex+t.dataEndIndex!==0&&t.dataEndIndex-t.dataStartIndex>=r&&(h=h.slice(t.dataStartIndex,t.dataEndIndex+1));var p;if(l.dataKey&&!l.allowDuplicatedCategory){var f=h===void 0?o:h;p=wxe(f,l.dataKey,a)}else p=h&&h[r]||o[r];return p?[].concat(tD(c),[L1t(d,p)]):c},[])},zYe=function(t,n,r,a){var i=a||{x:t.chartX,y:t.chartY},l=HUs(i,r),o=t.orderedTooltipTicks,c=t.tooltipAxis,d=t.tooltipTicks,u=jDs(l,o,d,c);if(u>=0&&d){var h=d[u]&&d[u].value,p=I5e(t,n,u,h),f=GUs(r,o,u,i);return{activeTooltipIndex:u,activeLabel:h,activePayload:p,activeCoordinate:f}}return null},WUs=function(t,n){var r=n.axes,a=n.graphicalItems,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,p=t.stackOffset,f=T1t(u,i);return r.reduce(function(y,_){var v,j=_.type.defaultProps!==void 0?or(or({},_.type.defaultProps),_.props):_.props,w=j.type,S=j.dataKey,A=j.allowDataOverflow,E=j.allowDuplicatedCategory,O=j.scale,D=j.ticks,I=j.includeHidden,F=j[l];if(y[F])return y;var z=c1e(t.data,{graphicalItems:a.filter(function(ve){var ge,Te=l in ve.props?ve.props[l]:(ge=ve.type.defaultProps)===null||ge===void 0?void 0:ge[l];return Te===F}),dataStartIndex:c,dataEndIndex:d}),H=z.length,Z,Y,W;vUs(j.domain,A,w)&&(Z=G3e(j.domain,null,A),f&&(w==="number"||O!=="auto")&&(W=mz(z,S,"category")));var ee=Zbt(w);if(!Z||Z.length===0){var se,oe=(se=j.domain)!==null&&se!==void 0?se:ee;if(S){if(Z=mz(z,S,w),w==="category"&&f){var he=hks(Z);E&&he?(Y=Z,Z=cge(0,H)):E||(Z=oKe(oe,Z,_).reduce(function(ve,ge){return ve.indexOf(ge)>=0?ve:[].concat(tD(ve),[ge])},[]))}else if(w==="category")E?Z=Z.filter(function(ve){return ve!==""&&!jo(ve)}):Z=oKe(oe,Z,_).reduce(function(ve,ge){return ve.indexOf(ge)>=0||ge===""||jo(ge)?ve:[].concat(tD(ve),[ge])},[]);else if(w==="number"){var ce=TDs(z,a.filter(function(ve){var ge,Te,Ie=l in ve.props?ve.props[l]:(ge=ve.type.defaultProps)===null||ge===void 0?void 0:ge[l],Ce="hide"in ve.props?ve.props.hide:(Te=ve.type.defaultProps)===null||Te===void 0?void 0:Te.hide;return Ie===F&&(I||!Ce)}),S,i,u);ce&&(Z=ce)}f&&(w==="number"||O!=="auto")&&(W=mz(z,S,"category"))}else f?Z=cge(0,H):o&&o[F]&&o[F].hasStack&&w==="number"?Z=p==="expand"?[0,1]:P1t(o[F].stackGroups,c,d):Z=C1t(z,a.filter(function(ve){var ge=l in ve.props?ve.props[l]:ve.type.defaultProps[l],Te="hide"in ve.props?ve.props.hide:ve.type.defaultProps.hide;return ge===F&&(I||!Te)}),w,u,!0);if(w==="number")Z=E5e(h,Z,F,i,D),oe&&(Z=G3e(oe,Z,A));else if(w==="category"&&oe){var me=oe,le=Z.every(function(ve){return me.indexOf(ve)>=0});le&&(Z=me)}}return or(or({},y),{},Xi({},F,or(or({},j),{},{axisType:i,domain:Z,categoricalDomain:W,duplicateDomain:Y,originalDomain:(v=j.domain)!==null&&v!==void 0?v:ee,isCategorical:f,layout:u})))},{})},KUs=function(t,n){var r=n.graphicalItems,a=n.Axis,i=n.axisType,l=n.axisIdKey,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.layout,h=t.children,p=c1e(t.data,{graphicalItems:r,dataStartIndex:c,dataEndIndex:d}),f=p.length,y=T1t(u,i),_=-1;return r.reduce(function(v,j){var w=j.type.defaultProps!==void 0?or(or({},j.type.defaultProps),j.props):j.props,S=w[l],A=Zbt("number");if(!v[S]){_++;var E;return y?E=cge(0,f):o&&o[S]&&o[S].hasStack?(E=P1t(o[S].stackGroups,c,d),E=E5e(h,E,S,i)):(E=G3e(A,C1t(p,r.filter(function(O){var D,I,F=l in O.props?O.props[l]:(D=O.type.defaultProps)===null||D===void 0?void 0:D[l],z="hide"in O.props?O.props.hide:(I=O.type.defaultProps)===null||I===void 0?void 0:I.hide;return F===S&&!z}),"number",u),a.defaultProps.allowDataOverflow),E=E5e(h,E,S,i)),or(or({},v),{},Xi({},S,or(or({axisType:i},a.defaultProps),{},{hide:!0,orientation:uy(qUs,"".concat(i,".").concat(_%2),null),domain:E,originalDomain:A,isCategorical:y,layout:u})))}return v},{})},YUs=function(t,n){var r=n.axisType,a=r===void 0?"xAxis":r,i=n.AxisComp,l=n.graphicalItems,o=n.stackGroups,c=n.dataStartIndex,d=n.dataEndIndex,u=t.children,h="".concat(a,"Id"),p=hy(u,i),f={};return p&&p.length?f=WUs(t,{axes:p,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d}):l&&l.length&&(f=KUs(t,{Axis:i,graphicalItems:l,axisType:a,axisIdKey:h,stackGroups:o,dataStartIndex:c,dataEndIndex:d})),f},ZUs=function(t){var n=cS(t),r=z2(n,!1,!0);return{tooltipTicks:r,orderedTooltipTicks:aPe(r,function(a){return a.coordinate}),tooltipAxis:n,tooltipAxisBandSize:Zxe(n,r)}},BYe=function(t){var n=t.children,r=t.defaultShowTooltip,a=B0(n,H8),i=0,l=0;return t.data&&t.data.length!==0&&(l=t.data.length-1),a&&a.props&&(a.props.startIndex>=0&&(i=a.props.startIndex),a.props.endIndex>=0&&(l=a.props.endIndex)),{chartX:0,chartY:0,dataStartIndex:i,dataEndIndex:l,activeTooltipIndex:-1,isTooltipActive:!!r}},QUs=function(t){return!t||!t.length?!1:t.some(function(n){var r=X2(n&&n.type);return r&&r.indexOf("Bar")>=0})},$Ye=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"}},XUs=function(t,n){var r=t.props,a=t.graphicalItems,i=t.xAxisMap,l=i===void 0?{}:i,o=t.yAxisMap,c=o===void 0?{}:o,d=r.width,u=r.height,h=r.children,p=r.margin||{},f=B0(h,H8),y=B0(h,GA),_=Object.keys(c).reduce(function(E,O){var D=c[O],I=D.orientation;return!D.mirror&&!D.hide?or(or({},E),{},Xi({},I,E[I]+D.width)):E},{left:p.left||0,right:p.right||0}),v=Object.keys(l).reduce(function(E,O){var D=l[O],I=D.orientation;return!D.mirror&&!D.hide?or(or({},E),{},Xi({},I,uy(E,"".concat(I))+D.height)):E},{top:p.top||0,bottom:p.bottom||0}),j=or(or({},v),_),w=j.bottom;f&&(j.bottom+=f.props.height||H8.defaultProps.height),y&&n&&(j=SDs(j,a,r,n));var S=d-j.left-j.right,A=u-j.top-j.bottom;return or(or({brushBottom:w},j),{},{width:Math.max(S,0),height:Math.max(A,0)})},JUs=function(t,n){if(n==="xAxis")return t[n].width;if(n==="yAxis")return t[n].height},qPe=function(t){var n=t.chartName,r=t.GraphicalChild,a=t.defaultTooltipEventType,i=a===void 0?"axis":a,l=t.validateTooltipEventTypes,o=l===void 0?["axis"]:l,c=t.axisComponents,d=t.legendContent,u=t.formatAxisMap,h=t.defaultProps,p=function(j,w){var S=w.graphicalItems,A=w.stackGroups,E=w.offset,O=w.updateId,D=w.dataStartIndex,I=w.dataEndIndex,F=j.barSize,z=j.layout,H=j.barGap,Z=j.barCategoryGap,Y=j.maxBarSize,W=$Ye(z),ee=W.numericAxisName,se=W.cateAxisName,oe=QUs(S),he=[];return S.forEach(function(ce,me){var le=c1e(j.data,{graphicalItems:[ce],dataStartIndex:D,dataEndIndex:I}),ve=ce.type.defaultProps!==void 0?or(or({},ce.type.defaultProps),ce.props):ce.props,ge=ve.dataKey,Te=ve.maxBarSize,Ie=ve["".concat(ee,"Id")],Ce=ve["".concat(se,"Id")],Me={},Pe=c.reduce(function(rt,tt){var at=w["".concat(tt.axisType,"Map")],Ye=ve["".concat(tt.axisType,"Id")];at&&at[Ye]||tt.axisType==="zAxis"||TM();var ut=at[Ye];return or(or({},rt),{},Xi(Xi({},tt.axisType,ut),"".concat(tt.axisType,"Ticks"),z2(ut)))},Me),Re=Pe[se],Ae=Pe["".concat(se,"Ticks")],Be=A&&A[Ie]&&A[Ie].hasStack&&ODs(ce,A[Ie].stackGroups),we=X2(ce.type).indexOf("Bar")>=0,Je=Zxe(Re,Ae),ke=[],it=oe&&NDs({barSize:F,stackGroups:A,totalSize:JUs(Pe,se)});if(we){var je,He,$e=jo(Te)?Y:Te,Ke=(je=(He=Zxe(Re,Ae,!0))!==null&&He!==void 0?He:$e)!==null&&je!==void 0?je:0;ke=kDs({barGap:H,barCategoryGap:Z,bandSize:Ke!==Je?Ke:Je,sizeList:it[Ce],maxBarSize:$e}),Ke!==Je&&(ke=ke.map(function(rt){return or(or({},rt),{},{position:or(or({},rt.position),{},{offset:rt.position.offset-Ke/2})})}))}var Ge=ce&&ce.type&&ce.type.getComposedData;Ge&&he.push({props:or(or({},Ge(or(or({},Pe),{},{displayedData:le,props:j,dataKey:ge,item:ce,bandSize:Je,barPosition:ke,offset:E,stackedData:Be,layout:z,dataStartIndex:D,dataEndIndex:I}))),{},Xi(Xi(Xi({key:ce.key||"item-".concat(me)},ee,Pe[ee]),se,Pe[se]),"animationId",O)),childIndex:kks(ce,j.children),item:ce})}),he},f=function(j,w){var S=j.props,A=j.dataStartIndex,E=j.dataEndIndex,O=j.updateId;if(!eGe({props:S}))return null;var D=S.children,I=S.layout,F=S.stackOffset,z=S.data,H=S.reverseStackOrder,Z=$Ye(I),Y=Z.numericAxisName,W=Z.cateAxisName,ee=hy(D,r),se=DDs(z,ee,"".concat(Y,"Id"),"".concat(W,"Id"),F,H),oe=c.reduce(function(ve,ge){var Te="".concat(ge.axisType,"Map");return or(or({},ve),{},Xi({},Te,YUs(S,or(or({},ge),{},{graphicalItems:ee,stackGroups:ge.axisType===Y&&se,dataStartIndex:A,dataEndIndex:E}))))},{}),he=XUs(or(or({},oe),{},{props:S,graphicalItems:ee}),w==null?void 0:w.legendBBox);Object.keys(oe).forEach(function(ve){oe[ve]=u(S,oe[ve],he,ve.replace("Map",""),n)});var ce=oe["".concat(W,"Map")],me=ZUs(ce),le=p(S,or(or({},oe),{},{dataStartIndex:A,dataEndIndex:E,updateId:O,graphicalItems:ee,stackGroups:se,offset:he}));return or(or({formattedGraphicalItems:le,graphicalItems:ee,offset:he,stackGroups:se},me),oe)},y=function(v){function j(w){var S,A,E;return IUs(this,j),E=DUs(this,j,[w]),Xi(E,"eventEmitterSymbol",Symbol("rechartsEventEmitter")),Xi(E,"accessibilityManager",new yUs),Xi(E,"handleLegendBBoxUpdate",function(O){if(O){var D=E.state,I=D.dataStartIndex,F=D.dataEndIndex,z=D.updateId;E.setState(or({legendBBox:O},f({props:E.props,dataStartIndex:I,dataEndIndex:F,updateId:z},or(or({},E.state),{},{legendBBox:O}))))}}),Xi(E,"handleReceiveSyncEvent",function(O,D,I){if(E.props.syncId===O){if(I===E.eventEmitterSymbol&&typeof E.props.syncMethod!="function")return;E.applySyncEvent(D)}}),Xi(E,"handleBrushChange",function(O){var D=O.startIndex,I=O.endIndex;if(D!==E.state.dataStartIndex||I!==E.state.dataEndIndex){var F=E.state.updateId;E.setState(function(){return or({dataStartIndex:D,dataEndIndex:I},f({props:E.props,dataStartIndex:D,dataEndIndex:I,updateId:F},E.state))}),E.triggerSyncEvent({dataStartIndex:D,dataEndIndex:I})}}),Xi(E,"handleMouseEnter",function(O){var D=E.getMouseInfo(O);if(D){var I=or(or({},D),{},{isTooltipActive:!0});E.setState(I),E.triggerSyncEvent(I);var F=E.props.onMouseEnter;ho(F)&&F(I,O)}}),Xi(E,"triggeredAfterMouseMove",function(O){var D=E.getMouseInfo(O),I=D?or(or({},D),{},{isTooltipActive:!0}):{isTooltipActive:!1};E.setState(I),E.triggerSyncEvent(I);var F=E.props.onMouseMove;ho(F)&&F(I,O)}),Xi(E,"handleItemMouseEnter",function(O){E.setState(function(){return{isTooltipActive:!0,activeItem:O,activePayload:O.tooltipPayload,activeCoordinate:O.tooltipPosition||{x:O.cx,y:O.cy}}})}),Xi(E,"handleItemMouseLeave",function(){E.setState(function(){return{isTooltipActive:!1}})}),Xi(E,"handleMouseMove",function(O){O.persist(),E.throttleTriggeredAfterMouseMove(O)}),Xi(E,"handleMouseLeave",function(O){E.throttleTriggeredAfterMouseMove.cancel();var D={isTooltipActive:!1};E.setState(D),E.triggerSyncEvent(D);var I=E.props.onMouseLeave;ho(I)&&I(D,O)}),Xi(E,"handleOuterEvent",function(O){var D=Nks(O),I=uy(E.props,"".concat(D));if(D&&ho(I)){var F,z;/.*touch.*/i.test(D)?z=E.getMouseInfo(O.changedTouches[0]):z=E.getMouseInfo(O),I((F=z)!==null&&F!==void 0?F:{},O)}}),Xi(E,"handleClick",function(O){var D=E.getMouseInfo(O);if(D){var I=or(or({},D),{},{isTooltipActive:!0});E.setState(I),E.triggerSyncEvent(I);var F=E.props.onClick;ho(F)&&F(I,O)}}),Xi(E,"handleMouseDown",function(O){var D=E.props.onMouseDown;if(ho(D)){var I=E.getMouseInfo(O);D(I,O)}}),Xi(E,"handleMouseUp",function(O){var D=E.props.onMouseUp;if(ho(D)){var I=E.getMouseInfo(O);D(I,O)}}),Xi(E,"handleTouchMove",function(O){O.changedTouches!=null&&O.changedTouches.length>0&&E.throttleTriggeredAfterMouseMove(O.changedTouches[0])}),Xi(E,"handleTouchStart",function(O){O.changedTouches!=null&&O.changedTouches.length>0&&E.handleMouseDown(O.changedTouches[0])}),Xi(E,"handleTouchEnd",function(O){O.changedTouches!=null&&O.changedTouches.length>0&&E.handleMouseUp(O.changedTouches[0])}),Xi(E,"handleDoubleClick",function(O){var D=E.props.onDoubleClick;if(ho(D)){var I=E.getMouseInfo(O);D(I,O)}}),Xi(E,"handleContextMenu",function(O){var D=E.props.onContextMenu;if(ho(D)){var I=E.getMouseInfo(O);D(I,O)}}),Xi(E,"triggerSyncEvent",function(O){E.props.syncId!==void 0&&J2e.emit(eNe,E.props.syncId,O,E.eventEmitterSymbol)}),Xi(E,"applySyncEvent",function(O){var D=E.props,I=D.layout,F=D.syncMethod,z=E.state.updateId,H=O.dataStartIndex,Z=O.dataEndIndex;if(O.dataStartIndex!==void 0||O.dataEndIndex!==void 0)E.setState(or({dataStartIndex:H,dataEndIndex:Z},f({props:E.props,dataStartIndex:H,dataEndIndex:Z,updateId:z},E.state)));else if(O.activeTooltipIndex!==void 0){var Y=O.chartX,W=O.chartY,ee=O.activeTooltipIndex,se=E.state,oe=se.offset,he=se.tooltipTicks;if(!oe)return;if(typeof F=="function")ee=F(he,O);else if(F==="value"){ee=-1;for(var ce=0;ce=0){var Be,we;if(Y.dataKey&&!Y.allowDuplicatedCategory){var Je=typeof Y.dataKey=="function"?Ae:"payload.".concat(Y.dataKey.toString());Be=wxe(ce,Je,ee),we=me&&le&&wxe(le,Je,ee)}else Be=ce==null?void 0:ce[W],we=me&&le&&le[W];if(Ce||Ie){var ke=O.props.activeIndex!==void 0?O.props.activeIndex:W;return[N.cloneElement(O,or(or(or({},F.props),Pe),{},{activeIndex:ke})),null,null]}if(!jo(Be))return[Re].concat(tD(E.renderActivePoints({item:F,activePoint:Be,basePoint:we,childIndex:W,isRange:me})))}else{var it,je=(it=E.getItemByXY(E.state.activeCoordinate))!==null&&it!==void 0?it:{graphicalItem:Re},He=je.graphicalItem,$e=He.item,Ke=$e===void 0?O:$e,Ge=He.childIndex,rt=or(or(or({},F.props),Pe),{},{activeIndex:Ge});return[N.cloneElement(Ke,rt),null,null]}return me?[Re,null,null]:[Re,null]}),Xi(E,"renderCustomized",function(O,D,I){return N.cloneElement(O,or(or({key:"recharts-customized-".concat(I)},E.props),E.state))}),Xi(E,"renderMap",{CartesianGrid:{handler:eG,once:!0},ReferenceArea:{handler:E.renderReferenceElement},ReferenceLine:{handler:eG},ReferenceDot:{handler:E.renderReferenceElement},XAxis:{handler:eG},YAxis:{handler:eG},Brush:{handler:E.renderBrush,once:!0},Bar:{handler:E.renderGraphicChild},Line:{handler:E.renderGraphicChild},Area:{handler:E.renderGraphicChild},Radar:{handler:E.renderGraphicChild},RadialBar:{handler:E.renderGraphicChild},Scatter:{handler:E.renderGraphicChild},Pie:{handler:E.renderGraphicChild},Funnel:{handler:E.renderGraphicChild},Tooltip:{handler:E.renderCursor,once:!0},PolarGrid:{handler:E.renderPolarGrid,once:!0},PolarAngleAxis:{handler:E.renderPolarAxis},PolarRadiusAxis:{handler:E.renderPolarAxis},Customized:{handler:E.renderCustomized}}),E.clipPathId="".concat((S=w.id)!==null&&S!==void 0?S:nR("recharts"),"-clip"),E.throttleTriggeredAfterMouseMove=Nvt(E.triggeredAfterMouseMove,(A=w.throttleDelay)!==null&&A!==void 0?A:1e3/60),E.state={},E}return FUs(j,v),LUs(j,[{key:"componentDidMount",value:function(){var S,A;this.addListener(),this.accessibilityManager.setDetails({container:this.container,offset:{left:(S=this.props.margin.left)!==null&&S!==void 0?S:0,top:(A=this.props.margin.top)!==null&&A!==void 0?A:0},coordinateList:this.state.tooltipTicks,mouseHandlerCallback:this.triggeredAfterMouseMove,layout:this.props.layout}),this.displayDefaultTooltip()}},{key:"displayDefaultTooltip",value:function(){var S=this.props,A=S.children,E=S.data,O=S.height,D=S.layout,I=B0(A,_p);if(I){var F=I.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,H=I5e(this.state,E,F,z),Z=this.state.tooltipTicks[F].coordinate,Y=(this.state.offset.top+O)/2,W=D==="horizontal",ee=W?{x:Z,y:Y}:{y:Z,x:Y},se=this.state.formattedGraphicalItems.find(function(he){var ce=he.item;return ce.type.name==="Scatter"});se&&(ee=or(or({},ee),se.props.points[F].tooltipPosition),H=se.props.points[F].tooltipPayload);var oe={activeTooltipIndex:F,isTooltipActive:!0,activeLabel:z,activePayload:H,activeCoordinate:ee};this.setState(oe),this.renderCursor(I),this.accessibilityManager.setIndex(F)}}}},{key:"getSnapshotBeforeUpdate",value:function(S,A){if(!this.props.accessibilityLayer)return null;if(this.state.tooltipTicks!==A.tooltipTicks&&this.accessibilityManager.setDetails({coordinateList:this.state.tooltipTicks}),this.props.layout!==S.layout&&this.accessibilityManager.setDetails({layout:this.props.layout}),this.props.margin!==S.margin){var E,O;this.accessibilityManager.setDetails({offset:{left:(E=this.props.margin.left)!==null&&E!==void 0?E:0,top:(O=this.props.margin.top)!==null&&O!==void 0?O:0}})}return null}},{key:"componentDidUpdate",value:function(S){o3e([B0(S.children,_p)],[B0(this.props.children,_p)])||this.displayDefaultTooltip()}},{key:"componentWillUnmount",value:function(){this.removeListener(),this.throttleTriggeredAfterMouseMove.cancel()}},{key:"getTooltipEventType",value:function(){var S=B0(this.props.children,_p);if(S&&typeof S.props.shared=="boolean"){var A=S.props.shared?"axis":"item";return o.indexOf(A)>=0?A:i}return i}},{key:"getMouseInfo",value:function(S){if(!this.container)return null;var A=this.container,E=A.getBoundingClientRect(),O=Q6s(E),D={chartX:Math.round(S.pageX-O.left),chartY:Math.round(S.pageY-O.top)},I=E.width/A.offsetWidth||1,F=this.inRange(D.chartX,D.chartY,I);if(!F)return null;var z=this.state,H=z.xAxisMap,Z=z.yAxisMap,Y=this.getTooltipEventType(),W=zYe(this.state,this.props.data,this.props.layout,F);if(Y!=="axis"&&H&&Z){var ee=cS(H).scale,se=cS(Z).scale,oe=ee&&ee.invert?ee.invert(D.chartX):null,he=se&&se.invert?se.invert(D.chartY):null;return or(or({},D),{},{xValue:oe,yValue:he},W)}return W?or(or({},D),W):null}},{key:"inRange",value:function(S,A){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,O=this.props.layout,D=S/E,I=A/E;if(O==="horizontal"||O==="vertical"){var F=this.state.offset,z=D>=F.left&&D<=F.left+F.width&&I>=F.top&&I<=F.top+F.height;return z?{x:D,y:I}:null}var H=this.state,Z=H.angleAxisMap,Y=H.radiusAxisMap;if(Z&&Y){var W=cS(Z);return dKe({x:D,y:I},W)}return null}},{key:"parseEventsOfWrapper",value:function(){var S=this.props.children,A=this.getTooltipEventType(),E=B0(S,_p),O={};E&&A==="axis"&&(E.props.trigger==="click"?O={onClick:this.handleClick}:O={onMouseEnter:this.handleMouseEnter,onDoubleClick:this.handleDoubleClick,onMouseMove:this.handleMouseMove,onMouseLeave:this.handleMouseLeave,onTouchMove:this.handleTouchMove,onTouchStart:this.handleTouchStart,onTouchEnd:this.handleTouchEnd,onContextMenu:this.handleContextMenu});var D=jxe(this.props,this.handleOuterEvent);return or(or({},D),O)}},{key:"addListener",value:function(){J2e.on(eNe,this.handleReceiveSyncEvent)}},{key:"removeListener",value:function(){J2e.removeListener(eNe,this.handleReceiveSyncEvent)}},{key:"filterFormatItem",value:function(S,A,E){for(var O=this.state.formattedGraphicalItems,D=0,I=O.length;D{const{data:w,error:S}=await q.from("email_campaigns").select("*").eq("status","sent").order("sent_at",{ascending:!0});if(S)throw S;return w}}),{data:r}=dt({queryKey:["campaign-agent-profiles"],queryFn:async()=>{const{data:w,error:S}=await q.from("profiles").select("id, name, email");if(S)throw S;return w}});if(n)return e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"Loading analytics..."});const a=t||[],i=new Map((r||[]).map(w=>[w.id,w])),l=a.reduce((w,S)=>w+(S.sent_count||0),0),o=a.reduce((w,S)=>w+(S.open_count||0),0),c=a.reduce((w,S)=>w+(S.click_count||0),0),d=a.reduce((w,S)=>w+(S.bounce_count||0),0),u=a.reduce((w,S)=>w+(S.complaint_count||0),0),h=l>0?(o/l*100).toFixed(1):"0.0",p=l>0?(c/l*100).toFixed(1):"0.0",f=[{label:"Campaigns Sent",value:a.length,icon:lr,color:"text-foreground"},{label:"Total Emails Sent",value:l,icon:An,color:"text-green-600"},{label:"Avg Open Rate",value:`${h}%`,icon:Sr,color:"text-blue-600"},{label:"Avg Click Rate",value:`${p}%`,icon:Lm,color:"text-purple-600"},{label:"Total Bounces",value:d,icon:ic,color:"text-orange-600"},{label:"Complaints",value:u,icon:go,color:"text-destructive"}],y=new Map;a.forEach(w=>{var E,O;const S=w.user_id,A=y.get(S)||{name:((E=i.get(S))==null?void 0:E.name)||((O=i.get(S))==null?void 0:O.email)||"Unknown",campaigns:0,sent:0,opens:0,clicks:0};A.campaigns++,A.sent+=w.sent_count||0,A.opens+=w.open_count||0,A.clicks+=w.click_count||0,y.set(S,A)});const _=[...y.entries()].map(([w,S])=>({id:w,...S,openRate:S.sent>0?+(S.opens/S.sent*100).toFixed(1):0})).sort((w,S)=>S.sent-w.sent),v=_.slice(0,6).map(w=>({name:w.name,value:w.sent})),j=a.map(w=>{var S;return{name:w.name.length>20?w.name.slice(0,20)+"…":w.name,agent:((S=i.get(w.user_id))==null?void 0:S.name)||"Unknown",openRate:w.sent_count>0?+(w.open_count/w.sent_count*100).toFixed(1):0,clickRate:w.sent_count>0?+(w.click_count/w.sent_count*100).toFixed(1):0,sent:w.sent_count,date:w.sent_at?Ss(new Date(w.sent_at),"MMM d"):""}});return e.jsx("div",{className:"space-y-6",children:a.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(lr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No campaigns sent yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Campaign analytics will appear here after the first send."})]})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-6 gap-3",children:f.map(w=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-center",children:[e.jsx(w.icon,{className:`h-5 w-5 mx-auto mb-1 ${w.color}`}),e.jsx("p",{className:"text-2xl font-bold",children:w.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:w.label})]})},w.label))}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Open & Click Rates by Campaign"})}),e.jsx(Ee,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(ww,{width:"100%",height:"100%",children:e.jsxs(HPe,{data:j,children:[e.jsx(Rw,{dataKey:"date",fontSize:11}),e.jsx(Ow,{fontSize:11,unit:"%"}),e.jsx(_p,{formatter:w=>`${w}%`}),e.jsx(Dw,{dataKey:"openRate",fill:"hsl(220, 70%, 50%)",name:"Open Rate",radius:[2,2,0,0]}),e.jsx(Dw,{dataKey:"clickRate",fill:"hsl(270, 70%, 50%)",name:"Click Rate",radius:[2,2,0,0]})]})})})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Send Volume by Agent"})}),e.jsx(Ee,{children:e.jsx("div",{className:"h-[280px]",children:e.jsx(ww,{width:"100%",height:"100%",children:e.jsxs(GPe,{children:[e.jsx(Db,{data:v,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",outerRadius:100,label:({name:w,percent:S})=>`${w} (${(S*100).toFixed(0)}%)`,fontSize:11,children:v.map((w,S)=>e.jsx(oR,{fill:UYe[S%UYe.length]},S))}),e.jsx(_p,{})]})})})})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Send Volume Trend"})}),e.jsx(Ee,{children:e.jsx("div",{className:"h-[240px]",children:e.jsx(ww,{width:"100%",height:"100%",children:e.jsxs(VPe,{data:j,children:[e.jsx(Rw,{dataKey:"date",fontSize:11}),e.jsx(Ow,{fontSize:11}),e.jsx(_p,{}),e.jsx(JM,{type:"monotone",dataKey:"sent",stroke:"hsl(142, 71%, 45%)",strokeWidth:2,name:"Emails Sent",dot:{r:4}})]})})})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Agent Performance"})}),e.jsx(Ee,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b text-left text-muted-foreground",children:[e.jsx("th",{className:"pb-2 font-medium",children:"Agent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Campaigns"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Sent"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Opens"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Clicks"}),e.jsx("th",{className:"pb-2 font-medium text-center",children:"Open Rate"})]})}),e.jsx("tbody",{children:_.map(w=>e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30",children:[e.jsx("td",{className:"py-2.5 font-medium",children:w.name}),e.jsx("td",{className:"py-2.5 text-center",children:w.campaigns}),e.jsx("td",{className:"py-2.5 text-center",children:w.sent}),e.jsx("td",{className:"py-2.5 text-center",children:w.opens}),e.jsx("td",{className:"py-2.5 text-center",children:w.clicks}),e.jsx("td",{className:"py-2.5 text-center",children:e.jsxs(Ue,{variant:"outline",children:[w.openRate,"%"]})})]},w.id))})]})})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Campaign Leaderboard"})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-2",children:[...a].sort((w,S)=>{const A=w.sent_count>0?w.open_count/w.sent_count:0;return(S.sent_count>0?S.open_count/S.sent_count:0)-A}).slice(0,10).map((w,S)=>{const A=w.sent_count>0?(w.open_count/w.sent_count*100).toFixed(1):"0.0",E=w.sent_count>0?(w.click_count/w.sent_count*100).toFixed(1):"0.0",O=i.get(w.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/${w.id}`),children:[e.jsxs("span",{className:"text-lg font-bold text-muted-foreground w-6",children:["#",S+1]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:w.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(O==null?void 0:O.name)||"Unknown"," · ",w.sent_at?Ss(new Date(w.sent_at),"MMM d, yyyy"):""," · ",w.sent_count," sent"]})]}),e.jsxs("div",{className:"flex gap-3 text-xs",children:[e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"})," ",A,"%"]}),e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(Lm,{className:"h-3 w-3"})," ",E,"%"]})]})]},w.id)})})})]})]})})}const tqs=()=>{const{toast:s}=Fa(),[t,n]=N.useState(!0),[r,a]=N.useState([]),[i,l]=N.useState([]),[o,c]=N.useState({installs:0,activeAgents:0,impressions30d:0,leads30d:0});N.useEffect(()=>{d()},[]);const d=async()=>{try{n(!0);const u=new Date;u.setDate(u.getDate()-30);const h=u.toISOString(),{data:p}=await q.from("website_apps").select("slug, name").order("sort_order"),f=[];let y=0;for(;;){const{data:E,error:O}=await q.from("agent_website_app_installs").select("user_id, app_slug, enabled").range(y,y+999);if(O)throw O;if(f.push(...E||[]),!E||E.length<1e3)break;y+=1e3}const _=[];for(y=0;;){const{data:E,error:O}=await q.from("widget_events").select("user_id, app_slug, event_type, created_at").gte("created_at",h).order("created_at",{ascending:!1}).range(y,y+999);if(O)throw O;if(_.push(...E||[]),!E||E.length<1e3||(y+=1e3,y>2e4))break}const v=new Map;for(const E of p||[])v.set(E.slug,{app_slug:E.slug,app_name:E.name,installs:0,enabled:0,impressions:0,expands:0,cta_clicks:0,lead_captures:0});for(const E of f){const O=v.get(E.app_slug);O&&(O.installs+=1,E.enabled&&(O.enabled+=1))}for(const E of _){const O=v.get(E.app_slug);O&&(E.event_type==="impression"?O.impressions+=1:E.event_type==="expand"?O.expands+=1:E.event_type==="cta_click"?O.cta_clicks+=1:E.event_type==="lead_capture"&&(O.lead_captures+=1))}const j=new Map;for(const E of f){if(!E.enabled)continue;const O=j.get(E.user_id)||{user_id:E.user_id,name:null,email:null,apps_enabled:[],events_30d:0,leads_30d:0};O.apps_enabled.includes(E.app_slug)||O.apps_enabled.push(E.app_slug),j.set(E.user_id,O)}for(const E of _){const O=j.get(E.user_id);O&&(O.events_30d+=1,E.event_type==="lead_capture"&&(O.leads_30d+=1))}const w=Array.from(j.keys());if(w.length>0){const{data:E}=await q.from("profiles").select("id, name, email").in("id",w);for(const O of E||[]){const D=j.get(O.id);D&&(D.name=O.name,D.email=O.email)}}const S=Array.from(v.values()),A=Array.from(j.values()).sort((E,O)=>O.events_30d-E.events_30d);a(S),l(A),c({installs:S.reduce((E,O)=>E+O.enabled,0),activeAgents:A.length,impressions30d:S.reduce((E,O)=>E+O.impressions,0),leads30d:S.reduce((E,O)=>E+O.lead_captures,0)})}catch(u){console.error(u),s({title:"Error",description:u.message||"Failed to load website app analytics",variant:"destructive"})}finally{n(!1)}};return t?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-4",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Active Installs"}),e.jsx(lc,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.installs}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Apps turned on across all agents"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Agents Using Apps"}),e.jsx(An,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"At least one app enabled"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Impressions (30d)"}),e.jsx(Sr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.impressions30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Widget views on lead sites"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Leads Captured (30d)"}),e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:o.leads30d}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total submissions"})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"App Performance (last 30 days)"})}),e.jsx(Ee,{children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{className:"text-right",children:"Installs"}),e.jsx(Tt,{className:"text-right",children:"Enabled"}),e.jsx(Tt,{className:"text-right",children:"Impressions"}),e.jsx(Tt,{className:"text-right",children:"Expands"}),e.jsx(Tt,{className:"text-right",children:"CTA Clicks"}),e.jsx(Tt,{className:"text-right",children:"Leads"}),e.jsx(Tt,{className:"text-right",children:"Conv. Rate"})]})}),e.jsxs(da,{children:[r.map(u=>{const h=u.impressions>0?(u.lead_captures/u.impressions*100).toFixed(1):"—";return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:u.app_name}),e.jsx(ht,{className:"text-right",children:u.installs}),e.jsx(ht,{className:"text-right",children:u.enabled}),e.jsx(ht,{className:"text-right",children:u.impressions}),e.jsx(ht,{className:"text-right",children:u.expands}),e.jsx(ht,{className:"text-right",children:u.cta_clicks}),e.jsx(ht,{className:"text-right font-semibold",children:u.lead_captures}),e.jsx(ht,{className:"text-right text-muted-foreground",children:h==="—"?"—":`${h}%`})]},u.app_slug)}),r.length===0&&e.jsx(Hs,{children:e.jsx(ht,{colSpan:8,className:"text-center text-muted-foreground py-6",children:"No data yet"})})]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Agent Usage (last 30 days)"})}),e.jsxs(Ee,{children:[e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Apps Enabled"}),e.jsx(Tt,{className:"text-right",children:"Events (30d)"}),e.jsx(Tt,{className:"text-right",children:"Leads (30d)"})]})}),e.jsxs(da,{children:[i.slice(0,100).map(u=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:u.name||"—"}),e.jsx(ht,{className:"text-muted-foreground",children:u.email||"—"}),e.jsx(ht,{children:e.jsx("div",{className:"flex flex-wrap gap-1",children:u.apps_enabled.map(h=>e.jsx(Ue,{variant:"secondary",className:"text-xs",children:h},h))})}),e.jsx(ht,{className:"text-right",children:u.events_30d}),e.jsx(ht,{className:"text-right font-semibold",children:u.leads_30d})]},u.user_id)),i.length===0&&e.jsx(Hs,{children:e.jsx(ht,{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."]})]})]})]})},sqs=()=>{const[s,t]=N.useState([]),[n,r]=N.useState([]),[a,i]=N.useState({}),[l,o]=N.useState(!0);N.useEffect(()=>{c()},[]);const c=async()=>{o(!0);try{const[{data:h},{data:p}]=await Promise.all([q.rpc("get_extension_usage_summary"),q.from("extension_usage_events").select("id, user_id, action, metadata, created_at").order("created_at",{ascending:!1}).limit(50)]),f=h||[],y=p||[];t(f),r(y);const _=Array.from(new Set(y.map(v=>v.user_id)));if(_.length){const{data:v}=await q.from("profiles").select("id, name, email").in("id",_),j={};(v||[]).forEach(w=>{j[w.id]={name:w.name,email:w.email}}),i(j)}}finally{o(!1)}},d=s.reduce((h,p)=>({users:h.users+1,contacts:h.contacts+Number(p.contacts_saved||0),listings:h.listings+Number(p.listings_imported||0),activities:h.activities+Number(p.activities_logged||0),events:h.events+Number(p.total_events||0)}),{users:0,contacts:0,listings:0,activities:0,events:0});if(l)return e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});const u=h=>{switch(h){case"contact_saved":return"Contact saved";case"listing_imported":return"Listing imported";case"activity_logged":return"Activity logged";case"template_used":return"Template used";case"paired":return"Extension paired";default:return h}};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-5",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Active Users"}),e.jsx(An,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.users}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Using extension"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total Actions"}),e.jsx(yA,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:d.events}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All events"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Contacts Saved"}),e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.contacts})})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Listings Imported"}),e.jsx(Or,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.listings})})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Activities Logged"}),e.jsx(Ai,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:d.activities})})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Users by Extension Activity"})}),e.jsx(Ee,{children:s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No extension usage yet. Once agents install and use the Chrome Extension, their activity will appear here."}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{className:"text-right",children:"Total"}),e.jsx(Tt,{className:"text-right",children:"Contacts"}),e.jsx(Tt,{className:"text-right",children:"Listings"}),e.jsx(Tt,{className:"text-right",children:"Activities"}),e.jsx(Tt,{children:"First Used"}),e.jsx(Tt,{children:"Last Used"})]})}),e.jsx(da,{children:s.map(h=>e.jsxs(Hs,{children:[e.jsxs(ht,{children:[e.jsx("div",{className:"font-medium",children:h.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.email})]}),e.jsx(ht,{className:"text-right font-medium",children:h.total_events}),e.jsx(ht,{className:"text-right",children:h.contacts_saved}),e.jsx(ht,{className:"text-right",children:h.listings_imported}),e.jsx(ht,{className:"text-right",children:h.activities_logged}),e.jsx(ht,{className:"text-xs text-muted-foreground",children:h.first_event_at?Ss(new Date(h.first_event_at),"MMM d, yyyy"):"—"}),e.jsx(ht,{className:"text-xs text-muted-foreground",children:h.last_event_at?Ss(new Date(h.last_event_at),"MMM d, h:mm a"):"—"})]},h.user_id))})]})})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Recent Activity"})}),e.jsx(Ee,{children:n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No recent events."}):e.jsx("div",{className:"space-y-2",children:n.map(h=>{const p=a[h.user_id];return e.jsxs("div",{className:"flex items-center justify-between border-b pb-2 last:border-0",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Ue,{variant:"secondary",children:u(h.action)}),e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:(p==null?void 0:p.name)||(p==null?void 0:p.email)||h.user_id.slice(0,8)}),h.metadata&&Object.keys(h.metadata).length>0&&e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-md",children:JSON.stringify(h.metadata)})]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(h.created_at),"MMM d, h:mm a")})]},h.id)})})})]})]})},nqs=()=>e.jsx(Cs,{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(Fr,{defaultValue:"analytics",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"website-apps",children:"Website Apps"}),e.jsx(Zt,{value:"extension",children:"Chrome Extension"}),e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"email-campaigns",children:"Email Campaigns"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"shares",children:"Shares"})]}),e.jsx(is,{value:"analytics",className:"space-y-4",children:e.jsx(Ews,{})}),e.jsx(is,{value:"website-apps",className:"space-y-4",children:e.jsx(tqs,{})}),e.jsx(is,{value:"extension",className:"space-y-4",children:e.jsx(sqs,{})}),e.jsx(is,{value:"content",className:"space-y-4",children:e.jsx(Mws,{})}),e.jsx(is,{value:"email-campaigns",className:"space-y-4",children:e.jsx(eqs,{})}),e.jsx(is,{value:"activity",className:"space-y-4",children:e.jsx(Tws,{})}),e.jsx(is,{value:"shares",className:"space-y-4",children:e.jsx(cyt,{})})]})]})});function rqs(){const s=Kt(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState([]),[f,y]=N.useState([]),[_,v]=N.useState([]),[j,w]=N.useState(!1),[S,A]=N.useState(null),[E,O]=N.useState(""),{data:D,isLoading:I}=dt({queryKey:["brokerage-resources"],queryFn:async()=>{const{data:we,error:Je}=await q.from("brokerage_resources").select("*").order("publish_date",{ascending:!1});if(Je)throw Je;return we}}),{data:F}=dt({queryKey:["brokerage-resource-pdfs"],queryFn:async()=>{const{data:we,error:Je}=await q.from("brokerage_resource_pdfs").select("*").order("sort_order",{ascending:!0});if(Je)throw Je;return we}}),{data:z}=dt({queryKey:["brokerage-resource-videos"],queryFn:async()=>{const{data:we,error:Je}=await q.from("brokerage_resource_videos").select("*").order("sort_order",{ascending:!0});if(Je)throw Je;return we}}),{data:H}=dt({queryKey:["brokerage-resource-links"],queryFn:async()=>{const{data:we,error:Je}=await q.from("brokerage_resource_links").select("*").order("sort_order",{ascending:!0});if(Je)throw Je;return we}}),{data:Z,isLoading:Y}=dt({queryKey:["brokerage-resource-categories"],queryFn:async()=>{const{data:we,error:Je}=await q.from("brokerage_resource_categories").select("*").order("sort_order",{ascending:!0});if(Je)throw Je;return we}}),W=()=>{l({title:"",description:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1,category_id:""}),c(null),u(""),p([]),y([]),v([]),a(null),O("")},ee=we=>{a(we),l({title:we.title,description:we.description||"",publish_date:we.publish_date.split("T")[0],is_published:we.is_published,category_id:we.category_id||""}),u(we.preview_image_url||""),O("");const Je=(F==null?void 0:F.filter(je=>je.resource_id===we.id))||[];p(Je.map(je=>({id:je.id,name:je.name,file_url:je.file_url,file_size:je.file_size,sort_order:je.sort_order})));const ke=(z==null?void 0:z.filter(je=>je.resource_id===we.id))||[];y(ke.map(je=>({id:je.id,title:je.title,video_url:je.video_url,sort_order:je.sort_order})));const it=(H==null?void 0:H.filter(je=>je.resource_id===we.id))||[];v(it.map(je=>({id:je.id,title:je.title,canva_share_link:je.canva_share_link,sort_order:je.sort_order}))),n(!0)},se=we=>{var ke;const Je=(ke=we.target.files)==null?void 0:ke[0];Je&&(c(Je),u(URL.createObjectURL(Je)))},oe=()=>{p([...h,{name:"",file_url:"",sort_order:h.length}])},he=we=>{p(h.filter((Je,ke)=>ke!==we))},ce=(we,Je,ke)=>{const it=[...h];if(Je==="file"&&ke instanceof File){const je=ke.name.replace(/\.[^/.]+$/,"");it[we]={...it[we],file:ke,file_size:ke.size,name:it[we].name||je}}else it[we]={...it[we],[Je]:ke};p(it)},me=()=>{y([...f,{title:"",video_url:"",sort_order:f.length}])},le=we=>{y(f.filter((Je,ke)=>ke!==we))},ve=(we,Je,ke)=>{const it=[...f];Je==="file"&&ke instanceof File?it[we]={...it[we],file:ke}:it[we]={...it[we],[Je]:ke},y(it)},ge=()=>{v([..._,{title:"",canva_share_link:"",sort_order:_.length}])},Te=we=>{v(_.filter((Je,ke)=>ke!==we))},Ie=(we,Je,ke)=>{const it=[..._];it[we]={...it[we],[Je]:ke},v(it)},Ce=async(we,Je)=>{try{const ke=await q.functions.invoke("bunny-upload",{body:{action:"create",title:we.name}});if(ke.error)throw ke.error;const{videoId:it,uploadUrl:je,libraryId:He}=ke.data,$e=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:it,libraryId:He}});if($e.error)throw $e.error;const{uploadUrl:Ke,apiKey:Ge}=$e.data,rt=new XMLHttpRequest;return rt.open("PUT",Ke,!0),rt.setRequestHeader("AccessKey",Ge),rt.upload.onprogress=tt=>{if(tt.lengthComputable){const at=Math.round(tt.loaded/tt.total*100),Ye=[...f];Ye[Je]={...Ye[Je],uploadProgress:at},y(Ye)}},await new Promise((tt,at)=>{rt.onload=()=>rt.status>=200&&rt.status<300?tt():at(new Error("Upload failed")),rt.onerror=()=>at(new Error("Upload failed")),rt.send(we)}),`https://iframe.mediadelivery.net/embed/${He}/${it}`}catch(ke){throw console.error("Bunny upload error:",ke),ke}},Me=yt({mutationFn:async we=>{const{data:Je,error:ke}=await q.from("brokerage_resource_categories").insert({name:we,sort_order:(Z==null?void 0:Z.length)||0}).select().single();if(ke)throw ke;return Je},onSuccess:we=>{s.invalidateQueries({queryKey:["brokerage-resource-categories"]}),l({...i,category_id:we.id}),O(""),ae.success("Category created")},onError:we=>{ae.error("Failed to create category: "+we.message)}}),Pe=yt({mutationFn:async()=>{w(!0);let we=(r==null?void 0:r.preview_image_url)||null;if(o){const it=o.name.split(".").pop(),je=`${Date.now()}.${it}`,{error:He}=await q.storage.from("brokerage-resources").upload(`previews/${je}`,o);if(He)throw He;const{data:$e}=q.storage.from("brokerage-resources").getPublicUrl(`previews/${je}`);we=$e.publicUrl}const Je={title:i.title,description:i.description||null,preview_image_url:we,publish_date:i.publish_date,is_published:i.is_published,category_id:i.category_id||null};let ke;if(r){const{error:it}=await q.from("brokerage_resources").update(Je).eq("id",r.id);if(it)throw it;ke=r.id;const je=(F==null?void 0:F.filter(ut=>ut.resource_id===r.id).map(ut=>ut.id))||[],He=h.filter(ut=>ut.id).map(ut=>ut.id),$e=je.filter(ut=>!He.includes(ut));$e.length>0&&await q.from("brokerage_resource_pdfs").delete().in("id",$e);const Ke=(z==null?void 0:z.filter(ut=>ut.resource_id===r.id).map(ut=>ut.id))||[],Ge=f.filter(ut=>ut.id).map(ut=>ut.id),rt=Ke.filter(ut=>!Ge.includes(ut));rt.length>0&&await q.from("brokerage_resource_videos").delete().in("id",rt);const tt=(H==null?void 0:H.filter(ut=>ut.resource_id===r.id).map(ut=>ut.id))||[],at=_.filter(ut=>ut.id).map(ut=>ut.id),Ye=tt.filter(ut=>!at.includes(ut));Ye.length>0&&await q.from("brokerage_resource_links").delete().in("id",Ye)}else{const{data:it,error:je}=await q.from("brokerage_resources").insert(Je).select().single();if(je)throw je;ke=it.id}for(let it=0;it{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success(r?"Resource updated":"Resource created"),n(!1),W(),w(!1)},onError:we=>{ae.error("Failed to save resource: "+we.message),w(!1)}}),Re=yt({mutationFn:async we=>{const{error:Je}=await q.from("brokerage_resources").delete().eq("id",we);if(Je)throw Je},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-resources"]}),s.invalidateQueries({queryKey:["brokerage-resource-pdfs"]}),s.invalidateQueries({queryKey:["brokerage-resource-videos"]}),s.invalidateQueries({queryKey:["brokerage-resource-links"]}),ae.success("Resource deleted")},onError:we=>{ae.error("Failed to delete: "+we.message)}}),Ae=we=>{if(we.preventDefault(),!i.title){ae.error("Please enter a title");return}Pe.mutate()},Be=we=>{const Je=(F==null?void 0:F.filter(je=>je.resource_id===we).length)||0,ke=(z==null?void 0:z.filter(je=>je.resource_id===we).length)||0,it=(H==null?void 0:H.filter(je=>je.resource_id===we).length)||0;return{pdfCount:Je,videoCount:ke,linkCount:it}};return e.jsx(Cs,{title:"Brokerage Resources Management",description:"Create and manage resources for brokerage managers",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Resources"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(D==null?void 0:D.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(D==null?void 0:D.filter(we=>we.is_published).length)||0})})]})]}),e.jsxs(B,{onClick:()=>{W(),n(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Resource"]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Content"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:I?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center py-8",children:"Loading..."})}):(D==null?void 0:D.length)===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No brokerage resources yet. Create your first one!"})}):D==null?void 0:D.map(we=>{const{pdfCount:Je,videoCount:ke,linkCount:it}=Be(we.id),je=Z==null?void 0:Z.find(He=>He.id===we.category_id);return e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[we.preview_image_url?e.jsx("img",{src:we.preview_image_url,alt:we.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(zm,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:we.title}),we.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:we.description})]})]})}),e.jsx(ht,{children:je?e.jsx("span",{className:"inline-flex items-center px-2 py-1 rounded-full text-xs font-medium bg-muted",children:je.name}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ht,{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(br,{className:"h-3.5 w-3.5"}),Je]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),ke]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Yo,{className:"h-3.5 w-3.5"}),it]})]})}),e.jsx(ht,{children:Ss(new Date(we.publish_date),"MMM d, yyyy")}),e.jsx(ht,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${we.is_published?"bg-green-100 text-green-800":"bg-yellow-100 text-yellow-800"}`,children:we.is_published?"Published":"Draft"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{const He=(F==null?void 0:F.filter(Ge=>Ge.resource_id===we.id))||[],$e=(z==null?void 0:z.filter(Ge=>Ge.resource_id===we.id))||[],Ke=(H==null?void 0:H.filter(Ge=>Ge.resource_id===we.id))||[];A({...we,pdfs:He,videos:$e,links:Ke})},children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ee(we),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Delete this resource?")&&Re.mutate(we.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},we.id)})})]})})}),e.jsx(_s,{open:t,onOpenChange:n,children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:r?"Edit Brokerage Resource":"Add Brokerage Resource"})}),e.jsxs("form",{onSubmit:Ae,className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{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(zm,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx(ye,{type:"file",accept:"image/*",onChange:se})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:i.title,onChange:we=>l({...i,title:we.target.value}),placeholder:"Resource Title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(oh,{className:"h-4 w-4"}),"Category"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:i.category_id,onValueChange:we=>l({...i,category_id:we}),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select a category"})}),e.jsx(cs,{children:Z==null?void 0:Z.map(we=>e.jsx(Ze,{value:we.id,children:we.name},we.id))})]}),i.category_id&&e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>l({...i,category_id:""}),children:e.jsx($n,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Or create new category...",value:E,onChange:we=>O(we.target.value),className:"flex-1"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",disabled:!E.trim()||Me.isPending,onClick:()=>Me.mutate(E.trim()),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add"]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:i.description,onChange:we=>l({...i,description:we}),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(ne,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:i.publish_date,onChange:we=>l({...i,publish_date:we.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Published"}),e.jsxs("div",{className:"flex items-center space-x-2 pt-2",children:[e.jsx(jn,{checked:i.is_published,onCheckedChange:we=>l({...i,is_published:we})}),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(ne,{className:"flex items-center gap-2",children:[e.jsx(br,{className:"h-4 w-4"}),"PDF Documents (",h.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:oe,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add PDF"]})]}),h.map((we,Je)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(ye,{placeholder:"PDF Name",value:we.name,onChange:ke=>ce(Je,"name",ke.target.value),className:"flex-1"}),e.jsx(ye,{type:"file",accept:".pdf",onChange:ke=>{var je;const it=(je=ke.target.files)==null?void 0:je[0];it&&ce(Je,"file",it)},className:"flex-1"}),we.file_url&&!we.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Uploaded"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>he(Je),children:e.jsx($n,{className:"h-4 w-4"})})]},Je))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-4 w-4"}),"Videos (",f.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:me,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Video"]})]}),f.map((we,Je)=>e.jsxs("div",{className:"space-y-2 p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{placeholder:"Video Title",value:we.title,onChange:ke=>ve(Je,"title",ke.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>le(Je),children:e.jsx($n,{className:"h-4 w-4"})})]}),e.jsx(ye,{type:"file",accept:"video/*",onChange:ke=>{var je;const it=(je=ke.target.files)==null?void 0:je[0];it&&ve(Je,"file",it)}}),we.uploadProgress!==void 0&&we.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:`${we.uploadProgress}%`}})}),we.video_url&&!we.file&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Video uploaded"})]},Je))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Yo,{className:"h-4 w-4"}),"Canva Links (",_.length,")"]}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ge,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),_.map((we,Je)=>e.jsxs("div",{className:"flex items-center gap-2 p-3 border rounded-lg bg-muted/50",children:[e.jsx(ye,{placeholder:"Link Title",value:we.title,onChange:ke=>Ie(Je,"title",ke.target.value),className:"flex-1"}),e.jsx(ye,{placeholder:"Canva Share Link",value:we.canva_share_link,onChange:ke=>Ie(Je,"canva_share_link",ke.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>Te(Je),children:e.jsx($n,{className:"h-4 w-4"})})]},Je))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:Pe.isPending||j,children:Pe.isPending||j?"Saving...":r?"Update":"Create"})]})]})]})}),e.jsx(_s,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:S==null?void 0:S.title})}),S&&e.jsxs("div",{className:"space-y-4",children:[S.preview_image_url&&e.jsx("img",{src:S.preview_image_url,alt:S.title,className:"w-full h-48 object-cover rounded-lg"}),S.description&&e.jsx("p",{className:"text-muted-foreground",children:S.description}),S.pdfs&&S.pdfs.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(br,{className:"h-4 w-4"}),"PDF Documents (",S.pdfs.length,")"]}),e.jsx("div",{className:"space-y-1",children:S.pdfs.map(we=>e.jsx("a",{href:we.file_url,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:we.name},we.id))})]}),S.videos&&S.videos.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(fr,{className:"h-4 w-4"}),"Videos (",S.videos.length,")"]}),e.jsx("div",{className:"space-y-2",children:S.videos.map(we=>e.jsx("div",{className:"p-2 border rounded",children:e.jsx("p",{className:"font-medium text-sm",children:we.title})},we.id))})]}),S.links&&S.links.length>0&&e.jsxs("div",{children:[e.jsxs("h4",{className:"font-medium mb-2 flex items-center gap-2",children:[e.jsx(Yo,{className:"h-4 w-4"}),"Canva Links (",S.links.length,")"]}),e.jsx("div",{className:"space-y-1",children:S.links.map(we=>e.jsx("a",{href:we.canva_share_link,target:"_blank",rel:"noopener noreferrer",className:"block p-2 border rounded hover:bg-muted",children:we.title},we.id))})]})]})]})})]})})}const Qbt=[{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 aqs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[y,_]=N.useState(""),[v,j]=N.useState(""),[w,S]=N.useState(""),[A,E]=N.useState(""),[O,D]=N.useState("Learn More"),[I,F]=N.useState("top"),[z,H]=N.useState(""),[Z,Y]=N.useState(!0),[W,ee]=N.useState(""),[se,oe]=N.useState("");N.useEffect(()=>{he()},[]);const he=async()=>{try{const{data:Me,error:Pe}=await q.from("dashboard_banners").select("*").order("placement").order("sort_order");if(Pe)throw Pe;t(Me||[])}catch(Me){ae.error("Failed to load banners: "+Me.message)}finally{r(!1)}},ce=()=>{_(""),j(""),S(""),E(""),D("Learn More"),F("top"),H(""),Y(!0),ee(""),oe(""),d(null)},me=Me=>{d(Me),_(Me.title),j(Me.description||""),S(Me.image_url),E(Me.link_url||""),D(Me.link_text||"Learn More"),F(Me.placement),H(Me.section_after||""),Y(Me.is_active),ee(Me.start_date?Ss(new Date(Me.start_date),"yyyy-MM-dd'T'HH:mm"):""),oe(Me.end_date?Ss(new Date(Me.end_date),"yyyy-MM-dd'T'HH:mm"):""),i(!0)},le=async Me=>{var Re;const Pe=(Re=Me.target.files)==null?void 0:Re[0];if(Pe){h(!0);try{const Ae=Pe.name.split(".").pop(),Be=`${Date.now()}.${Ae}`,{error:we}=await q.storage.from("banner-images").upload(Be,Pe);if(we)throw we;const{data:{publicUrl:Je}}=q.storage.from("banner-images").getPublicUrl(Be);S(Je),ae.success("Image uploaded successfully")}catch(Ae){ae.error("Failed to upload image: "+Ae.message)}finally{h(!1)}}},ve=async()=>{if(!y.trim()||!w){ae.error("Please fill in required fields (title and image)");return}f(!0);try{const Me={title:y.trim(),description:v.trim()||null,image_url:w,link_url:A.trim()||null,link_text:O.trim()||"Learn More",placement:I,section_after:I==="between"?z:null,is_active:Z,start_date:W?new Date(W).toISOString():null,end_date:se?new Date(se).toISOString():null};if(c){const{error:Pe}=await q.from("dashboard_banners").update(Me).eq("id",c.id);if(Pe)throw Pe;ae.success("Banner updated successfully")}else{const Pe=s.filter(Ae=>Ae.placement===I).length,{error:Re}=await q.from("dashboard_banners").insert({...Me,sort_order:Pe});if(Re)throw Re;ae.success("Banner created successfully")}i(!1),ce(),he()}catch(Me){ae.error("Failed to save banner: "+Me.message)}finally{f(!1)}},ge=async()=>{if(c)try{const{error:Me}=await q.from("dashboard_banners").delete().eq("id",c.id);if(Me)throw Me;ae.success("Banner deleted successfully"),o(!1),d(null),he()}catch(Me){ae.error("Failed to delete banner: "+Me.message)}},Te=async Me=>{try{const{error:Pe}=await q.from("dashboard_banners").update({is_active:!Me.is_active}).eq("id",Me.id);if(Pe)throw Pe;ae.success(Me.is_active?"Banner deactivated":"Banner activated"),he()}catch(Pe){ae.error("Failed to update banner: "+Pe.message)}},Ie=s.filter(Me=>Me.placement==="top"),Ce=s.filter(Me=>Me.placement==="between");return n?e.jsx(Cs,{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(Cs,{title:"Dashboard Management",description:"Configure dashboard modules and banners",children:[e.jsxs("div",{className:"space-y-8",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"h-5 w-5"}),"Hero Banners (Top of Dashboard)"]}),e.jsx(Vn,{children:"These banners appear in a rotating carousel at the top of the dashboard"})]}),e.jsxs(_s,{open:a&&I==="top",onOpenChange:Me=>{Me||ce(),i(Me),Me&&F("top")},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ce(),F("top")},children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Add Hero Banner"]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{children:[c?"Edit":"Create"," Banner"]}),e.jsx(Jn,{children:"Configure the banner's content and display settings"})]}),e.jsx(qYe,{title:y,setTitle:_,description:v,setDescription:j,imageUrl:w,linkUrl:A,setLinkUrl:E,linkText:O,setLinkText:D,placement:I,setPlacement:F,sectionAfter:z,setSectionAfter:H,isActive:Z,setIsActive:Y,startDate:W,setStartDate:ee,endDate:se,setEndDate:oe,handleImageUpload:le,uploading:u,showPlacementOptions:!1}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ce()},children:"Cancel"}),e.jsx(B,{onClick:ve,disabled:p,children:p?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ee,{children:Ie.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:Ie.map(Me=>e.jsx(VYe,{banner:Me,onEdit:()=>me(Me),onDelete:()=>{d(Me),o(!0)},onToggleActive:()=>Te(Me)},Me.id))})})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Xo,{className:"h-5 w-5"}),"Section Banners"]}),e.jsx(Vn,{children:"These banners appear between dashboard content sections"})]}),e.jsxs(_s,{open:a&&I==="between",onOpenChange:Me=>{Me||ce(),i(Me),Me&&F("between")},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{onClick:()=>{ce(),F("between")},children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Add Section Banner"]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{children:[c?"Edit":"Create"," Section Banner"]}),e.jsx(Jn,{children:"Configure where this banner appears between sections"})]}),e.jsx(qYe,{title:y,setTitle:_,description:v,setDescription:j,imageUrl:w,linkUrl:A,setLinkUrl:E,linkText:O,setLinkText:D,placement:I,setPlacement:F,sectionAfter:z,setSectionAfter:H,isActive:Z,setIsActive:Y,startDate:W,setStartDate:ee,endDate:se,setEndDate:oe,handleImageUpload:le,uploading:u,showPlacementOptions:!0}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{i(!1),ce()},children:"Cancel"}),e.jsx(B,{onClick:ve,disabled:p,children:p?"Saving...":c?"Update Banner":"Create Banner"})]})]})]})]}),e.jsx(Ee,{children:Ce.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No section banners yet. Add your first banner above."}):e.jsx("div",{className:"space-y-3",children:Ce.map(Me=>e.jsx(VYe,{banner:Me,onEdit:()=>me(Me),onDelete:()=>{d(Me),o(!0)},onToggleActive:()=>Te(Me),showSection:!0},Me.id))})})]})]}),e.jsx(_s,{open:l,onOpenChange:o,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Delete Banner"}),e.jsxs(Jn,{children:['Are you sure you want to delete "',c==null?void 0:c.title,'"? This action cannot be undone.']})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:ge,children:"Delete"})]})]})})]})}function qYe({title:s,setTitle:t,description:n,setDescription:r,imageUrl:a,linkUrl:i,setLinkUrl:l,linkText:o,setLinkText:c,placement:d,setPlacement:u,sectionAfter:h,setSectionAfter:p,isActive:f,setIsActive:y,startDate:_,setStartDate:v,endDate:j,setEndDate:w,handleImageUpload:S,uploading:A,showPlacementOptions:E}){return e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",placeholder:"Banner headline...",value:s,onChange:O=>t(O.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",placeholder:"Optional banner description...",value:n,onChange:O=>r(O.target.value),rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Banner Image *"}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:S,disabled:A,className:"flex-1"}),A&&e.jsx("span",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),a&&e.jsx("div",{className:"mt-2 relative rounded-lg overflow-hidden border",children:e.jsx("img",{src:a,alt:"Preview",className:"w-full h-40 object-cover"})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"linkUrl",children:"Link URL (optional)"}),e.jsx(ye,{id:"linkUrl",placeholder:"https://...",value:i,onChange:O=>l(O.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"linkText",children:"Button Text"}),e.jsx(ye,{id:"linkText",placeholder:"Learn More",value:o,onChange:O=>c(O.target.value)})]})]}),E&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Placement"}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select section placement..."})}),e.jsx(cs,{children:Qbt.map(O=>e.jsx(Ze,{value:O.value,children:O.label},O.value))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"startDate",className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Start Date (optional)"]}),e.jsx(ye,{id:"startDate",type:"datetime-local",value:_,onChange:O=>v(O.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"endDate",className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"End Date (optional)"]}),e.jsx(ye,{id:"endDate",type:"datetime-local",value:j,onChange:O=>w(O.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(jn,{id:"isActive",checked:f,onCheckedChange:y}),e.jsx(ne,{htmlFor:"isActive",children:"Active"})]})})]})}function VYe({banner:s,onEdit:t,onDelete:n,onToggleActive:r,showSection:a=!1}){var c;const i=(c=Qbt.find(d=>d.value===s.section_after))==null?void 0:c.label,[l,o]=N.useState(null);return N.useEffect(()=>{(async()=>{const{count:u}=await q.from("content_engagement_logs").select("*",{count:"exact",head:!0}).eq("resource_id",s.id).eq("action_type","click_link");o(u??0)})()},[s.id]),e.jsxs("div",{className:"flex items-center gap-4 p-3 border rounded-lg bg-card hover:bg-accent/50 transition-colors",children:[e.jsx(Pu,{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(Ue,{variant:"secondary",children:"Inactive"}),s.start_date&&new Date(s.start_date)>new Date&&e.jsx(Ue,{variant:"outline",children:"Scheduled"})]}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.description}),a&&i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i})]}),l!==null&&e.jsxs("div",{className:"flex items-center gap-1 text-destructive",title:"Button clicks",children:[e.jsx(oc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-semibold",children:l})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[s.link_url&&e.jsx("a",{href:s.link_url,target:"_blank",rel:"noopener noreferrer",children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(tr,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:r,children:s.is_active?e.jsx(Sr,{className:"h-4 w-4"}):e.jsx(mf,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:t,children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})]})}const tG={open:{label:"Open",icon:pr,color:"bg-yellow-500"},in_progress:{label:"In Progress",icon:Zl,color:"bg-blue-500"},resolved:{label:"Resolved",icon:Pi,color:"bg-green-500"},closed:{label:"Closed",icon:Uc,color:"bg-muted-foreground"}},HYe={general:"General Support",technology:"Technology Support",crm:"CRM Support",marketing:"Marketing Support"};function iqs(){var I,F;const{user:s}=vs(),t=Kt(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState([]),[c,d]=N.useState("all"),[u,h]=N.useState("all"),[p,f]=N.useState(!1),{data:y=[],isLoading:_}=dt({queryKey:["admin-support-tickets",c,u],queryFn:async()=>{let z=q.from("support_tickets").select("*, profiles!support_tickets_user_id_fkey(name, email)").order("created_at",{ascending:!1});c!=="all"&&(z=z.eq("status",c)),u!=="all"&&(z=z.eq("category",u));const{data:H,error:Z}=await z;if(Z)throw Z;return H}}),{data:v=[]}=dt({queryKey:["admin-users-notifications"],queryFn:async()=>{const{data:z,error:H}=await q.from("user_roles").select("user_id").eq("role","admin");if(H)throw H;const Z=z.map(he=>he.user_id),{data:Y,error:W}=await q.from("profiles").select("id, name, email").in("id",Z);if(W)throw W;const{data:ee,error:se}=await q.from("support_notification_settings").select("user_id, receive_notifications");if(se)throw se;const oe=new Map((ee==null?void 0:ee.map(he=>[he.user_id,he.receive_notifications]))||[]);return Y.map(he=>({...he,receives_notifications:oe.get(he.id)||!1}))}}),{data:j=[]}=dt({queryKey:["admin-ticket-replies",n==null?void 0:n.id],queryFn:async()=>{if(!n)return[];const{data:z,error:H}=await q.from("support_ticket_replies").select("*, profiles(name)").eq("ticket_id",n.id).order("created_at",{ascending:!0});if(H)throw H;return z},enabled:!!n}),w=yt({mutationFn:async({userId:z,enabled:H})=>{const{data:Z}=await q.from("support_notification_settings").select("id").eq("user_id",z).maybeSingle();if(Z){const{error:Y}=await q.from("support_notification_settings").update({receive_notifications:H}).eq("user_id",z);if(Y)throw Y}else{const{error:Y}=await q.from("support_notification_settings").insert({user_id:z,receive_notifications:H});if(Y)throw Y}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-users-notifications"]}),ae.success("Notification settings updated")},onError:()=>{ae.error("Failed to update settings")}}),S=yt({mutationFn:async({ticketId:z,status:H})=>{const{error:Z}=await q.from("support_tickets").update({status:H}).eq("id",z);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),n&&r({...n,status:n.status}),ae.success("Status updated")},onError:()=>{ae.error("Failed to update status")}}),A=yt({mutationFn:async({ticketId:z,assignedTo:H})=>{const{error:Z}=await q.from("support_tickets").update({assigned_to:H}).eq("id",z);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]}),ae.success("Ticket assigned")},onError:()=>{ae.error("Failed to assign ticket")}}),E=yt({mutationFn:async({content:z,attachments:H})=>{var Y,W;if(!n||!s)throw new Error("Missing data");const{error:Z}=await q.from("support_ticket_replies").insert({ticket_id:n.id,user_id:s.id,content:z,is_admin_reply:!0,attachments:H});if(Z)throw Z;try{await q.functions.invoke("support-reply-notify",{body:{ticketId:n.id,ticketSubject:n.subject,replyContent:z,userEmail:(Y=n.profiles)==null?void 0:Y.email,userName:(W=n.profiles)==null?void 0:W.name}})}catch(ee){console.error("Failed to send reply notification:",ee)}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-ticket-replies",n==null?void 0:n.id]}),i(""),o([]),ae.success("Reply sent!")},onError:()=>{ae.error("Failed to send reply")}}),O=()=>{!a.trim()&&l.length===0||E.mutate({content:a,attachments:l})};N.useEffect(()=>{const z=q.channel("admin-tickets").on("postgres_changes",{event:"*",schema:"public",table:"support_tickets"},()=>{t.invalidateQueries({queryKey:["admin-support-tickets"]})}).subscribe();return()=>{q.removeChannel(z)}},[t]);const D=y.filter(z=>z.status==="open").length;return n?(tG[n.status].icon,e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>r(null),children:e.jsx(qr,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h1",{className:"text-2xl font-bold",children:n.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ue,{variant:"secondary",children:HYe[n.category]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:["from ",((I=n.profiles)==null?void 0:I.name)||"Unknown"," (",(F=n.profiles)==null?void 0:F.email,")"]})]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm",children:"Status"})}),e.jsx(Ee,{children:e.jsxs(us,{value:n.status,onValueChange:z=>{S.mutate({ticketId:n.id,status:z}),r({...n,status:z})},children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"open",children:"Open"}),e.jsx(Ze,{value:"in_progress",children:"In Progress"}),e.jsx(Ze,{value:"resolved",children:"Resolved"}),e.jsx(Ze,{value:"closed",children:"Closed"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm",children:"Assigned To"})}),e.jsx(Ee,{children:e.jsxs(us,{value:n.assigned_to||"unassigned",onValueChange:z=>{const H=z==="unassigned"?null:z;A.mutate({ticketId:n.id,assignedTo:H}),r({...n,assigned_to:H})},children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Unassigned"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"unassigned",children:"Unassigned"}),v.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))]})]})})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Vn,{children:["Created on ",Ss(new Date(n.created_at),"MMM d, yyyy 'at' h:mm a")]})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Conversation"})}),e.jsxs(Ee,{children:[e.jsx(di,{className:"h-[300px] pr-4",children:j.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No replies yet"}):e.jsx("div",{className:"space-y-4",children:j.map(z=>{var H,Z;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?`${((H=z.profiles)==null?void 0:H.name)||"Admin"} (Support)`:((Z=z.profiles)==null?void 0:Z.name)||"User"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(z.created_at),"MMM d, h:mm a")})]}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:z.content}),z.attachments&&z.attachments.length>0&&e.jsx(M0t,{attachments:z.attachments})]},z.id)})})}),e.jsx(al,{className:"my-4"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ms,{placeholder:"Type your reply...",value:a,onChange:z=>i(z.target.value),className:"min-h-[80px]"}),e.jsx(B,{onClick:O,disabled:!a.trim()&&l.length===0||E.isPending,className:"self-end",children:e.jsx(lr,{className:"h-4 w-4"})})]}),e.jsx(A0t,{value:l,onChange:o,disabled:E.isPending})]})]})]})]})})):e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Support Tickets"}),e.jsxs("p",{className:"text-muted-foreground",children:["Manage support requests from agents",D>0&&e.jsxs(Ue,{variant:"destructive",className:"ml-2",children:[D," open"]})]})]}),e.jsxs(_s,{open:p,onOpenChange:f,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Ko,{className:"h-4 w-4 mr-2"}),"Notification Settings"]})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Email Notification Settings"}),e.jsx(Jn,{children:"Choose which admins receive email notifications for new support tickets."})]}),e.jsx("div",{className:"space-y-4 mt-4",children:v.map(z=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Wi,{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(nm,{className:"h-4 w-4 text-primary"}):e.jsx(cw,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(jn,{checked:z.receives_notifications,onCheckedChange:H=>w.mutate({userId:z.id,enabled:H})})]})]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-4 items-center",children:[e.jsx(Fr,{value:c,onValueChange:d,className:"w-auto",children:e.jsxs(Rr,{children:[e.jsx(Zt,{value:"all",children:"All"}),e.jsx(Zt,{value:"open",children:"Open"}),e.jsx(Zt,{value:"in_progress",children:"In Progress"}),e.jsx(Zt,{value:"resolved",children:"Resolved"}),e.jsx(Zt,{value:"closed",children:"Closed"})]})}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"All Categories"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Categories"}),e.jsx(Ze,{value:"general",children:"General Support"}),e.jsx(Ze,{value:"technology",children:"Technology Support"}),e.jsx(Ze,{value:"crm",children:"CRM Support"}),e.jsx(Ze,{value:"marketing",children:"Marketing Support"})]})]})]}),e.jsx("div",{className:"mt-4",children:_?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading tickets..."}):y.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"text-center py-12",children:[e.jsx(Zl,{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:y.map(z=>{var Z,Y;const H=tG[z.status].icon;return e.jsx(fe,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>r(z),children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-medium truncate",children:z.subject}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 flex-wrap",children:[e.jsx(Ue,{variant:"outline",className:"text-xs",children:HYe[z.category]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(Z=z.profiles)==null?void 0:Z.name," • ",Ss(new Date(z.created_at),"MMM d, yyyy")]}),z.assigned_to&&e.jsxs(Ue,{variant:"secondary",className:"text-xs gap-1",children:[e.jsx(Wi,{className:"h-3 w-3"}),((Y=v.find(W=>W.id===z.assigned_to))==null?void 0:Y.name)||"Assigned"]})]})]}),e.jsxs(Ue,{className:tG[z.status].color,children:[e.jsx(H,{className:"h-3 w-3 mr-1"}),tG[z.status].label]})]})})},z.id)})})})]})]})})}const Xbt=Nf.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 oqs({content:s,onChange:t,variables:n}){const r=A6e({extensions:[I6e,U6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline"}}),q6e.configure({types:["heading","paragraph"]}),V6e,Xbt],content:s,onUpdate:({editor:l})=>{t(l.getHTML())}});N.useEffect(()=>{r&&s!==r.getHTML()&&r.commands.setContent(s)},[s,r]);const a=l=>{r&&r.chain().focus().insertContent(`{{${l.key}}}`).run()},i=()=>{if(!r)return;const l=r.getAttributes("link").href,o=window.prompt("URL",l);if(o!==null){if(o===""){r.chain().focus().extendMarkRange("link").unsetLink().run();return}r.chain().focus().extendMarkRange("link").setLink({href:o}).run()}};return r?e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-1 p-2 border-b bg-muted/30",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBold().run(),className:r.isActive("bold")?"bg-muted":"",children:e.jsx($S,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleItalic().run(),className:r.isActive("italic")?"bg-muted":"",children:e.jsx(HS,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleBulletList().run(),className:r.isActive("bulletList")?"bg-muted":"",children:e.jsx(Sp,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleOrderedList().run(),className:r.isActive("orderedList")?"bg-muted":"",children:e.jsx(ub,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("left").run(),className:r.isActive({textAlign:"left"})?"bg-muted":"",children:e.jsx(fA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("center").run(),className:r.isActive({textAlign:"center"})?"bg-muted":"",children:e.jsx(pA,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().setTextAlign("right").run(),className:r.isActive({textAlign:"right"})?"bg-muted":"",children:e.jsx(xA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:i,className:r.isActive("link")?"bg-muted":"",children:e.jsx(Yo,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().toggleCodeBlock().run(),className:r.isActive("codeBlock")?"bg-muted":"",children:e.jsx(vA,{className:"h-4 w-4"})}),e.jsx("div",{className:"w-px h-6 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().undo().run(),disabled:!r.can().undo(),children:e.jsx(n4,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>r.chain().focus().redo().run(),disabled:!r.can().redo(),children:e.jsx(JS,{className:"h-4 w-4"})}),e.jsx("div",{className:"flex-1"}),n.length>0&&e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",children:[e.jsx(xL,{className:"h-4 w-4"}),"Insert Variable"]})}),e.jsx(gc,{align:"end",className:"w-64",children:n.map(l=>e.jsxs(Kr,{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(T6e,{editor:r,className:"prose prose-sm max-w-none p-4 min-h-[300px] focus:outline-none [&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[280px]"}),n.length>0&&e.jsxs("div",{className:"border-t p-3 bg-muted/20",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Available variables (click to copy):"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(l=>e.jsx(Ue,{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 lqs(){const s=Kt(),[t,n]=N.useState(null),[r,a]=N.useState(null),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(!0),[f,y]=N.useState("visual"),{data:_,isLoading:v}=dt({queryKey:["email-templates"],queryFn:async()=>{const{data:E,error:O}=await q.from("email_templates").select("*").order("name");if(O)throw O;return E.map(D=>({...D,available_variables:D.available_variables||[]}))}}),j=yt({mutationFn:async E=>{const{error:O}=await q.from("email_templates").update({subject:E.subject,body_html:E.body_html,description:E.description,is_active:E.is_active}).eq("id",E.id);if(O)throw O},onSuccess:()=>{s.invalidateQueries({queryKey:["email-templates"]}),ae.success("Email template updated successfully"),n(null)},onError:E=>{ae.error("Failed to update template: "+E.message)}}),w=E=>{n(E),l(E.subject),c(E.body_html),u(E.description||""),p(E.is_active),y("visual")},S=()=>{t&&j.mutate({id:t.id,subject:i,body_html:o,description:d,is_active:h})},A=(E,O)=>{let D=E;return O.forEach(I=>{const F=`{{${I.key}}}`,z=`[${I.label}]`;D=D.replace(new RegExp(F.replace(/[{}]/g,"\\$&"),"g"),z)}),D};return t?e.jsxs(Cs,{title:"Edit Email Template",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(B,{variant:"ghost",onClick:()=>n(null),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"}),"Back to Templates"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(B,{variant:"outline",onClick:()=>a(t),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{onClick:S,disabled:j.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),j.isPending?"Saving...":"Save Changes"]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5"}),t.name]}),e.jsxs(Vn,{className:"mt-1",children:["Template slug: ",e.jsx("code",{className:"bg-muted px-1 rounded",children:t.slug})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{htmlFor:"active-toggle",children:"Active"}),e.jsx(jn,{id:"active-toggle",checked:h,onCheckedChange:p})]})]})}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",value:d,onChange:E=>u(E.target.value),placeholder:"Brief description of when this email is sent",rows:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"subject",children:"Email Subject"}),e.jsx(ye,{id:"subject",value:i,onChange:E=>l(E.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(ne,{children:"Email Body"}),e.jsx(Fr,{value:f,onValueChange:E=>y(E),children:e.jsxs(Rr,{className:"h-8",children:[e.jsxs(Zt,{value:"visual",className:"text-xs px-3 h-6",children:[e.jsx(mb,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Zt,{value:"html",className:"text-xs px-3 h-6",children:[e.jsx(vA,{className:"h-3 w-3 mr-1"}),"HTML"]})]})})]}),f==="visual"?e.jsx(oqs,{content:o,onChange:c,variables:t.available_variables}):e.jsx(Ms,{value:o,onChange:E=>c(E.target.value),className:"font-mono text-sm min-h-[400px]",placeholder:"HTML email body"})]})]})]})]}),e.jsx(_s,{open:!!r,onOpenChange:()=>a(null),children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Email Preview"}),e.jsxs(Jn,{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(Cs,{title:"Email Templates",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Email Templates"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Manage and customize system email templates"})]}),v?e.jsx("div",{className:"grid gap-4",children:[...Array(4)].map((E,O)=>e.jsx(fe,{children:e.jsxs(It,{children:[e.jsx(Ws,{className:"h-5 w-48"}),e.jsx(Ws,{className:"h-4 w-96"})]})},O))}):e.jsx("div",{className:"grid gap-4",children:_==null?void 0:_.map(E=>e.jsxs(fe,{className:"hover:shadow-md transition-shadow",children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs(Rt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(Gs,{className:"h-5 w-5 text-muted-foreground"}),E.name,!E.is_active&&e.jsx(Ue,{variant:"secondary",children:"Inactive"})]}),e.jsx(Vn,{children:E.description})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>a(E),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Preview"]}),e.jsxs(B,{size:"sm",onClick:()=>w(E),children:[e.jsx(wu,{className:"h-4 w-4 mr-2"}),"Edit"]})]})]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:"Subject:"}),e.jsx("code",{className:"bg-muted px-2 py-0.5 rounded text-sm",children:E.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:E.available_variables.map(O=>e.jsx(Ue,{variant:"outline",className:"font-mono text-xs",children:`{{${O.key}}}`},O.key))})]})]})})]},E.id))}),e.jsx(_s,{open:!!r&&!t,onOpenChange:()=>a(null),children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{children:["Email Preview: ",r==null?void 0:r.name]}),e.jsxs(Jn,{children:["Subject: ",r==null?void 0:r.subject.replace(/\{\{(\w+)\}\}/g,"[$1]")]})]}),r&&e.jsx("div",{className:"border rounded-lg p-4 bg-white",children:e.jsx("div",{dangerouslySetInnerHTML:{__html:A(r.body_html,r.available_variables)}})})]})})]})})}function cqs(){const s=Kt(),[t,n]=N.useState("templates"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),[f,y]=N.useState({name:"",description:"",icon:"📧"}),{data:_=[]}=dt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:z,error:H}=await q.from("email_template_categories").select("*").order("sort_order");if(H)throw H;return z}}),{data:v=[],isLoading:j}=dt({queryKey:["agent-email-templates-admin"],queryFn:async()=>{const{data:z,error:H}=await q.from("agent_email_templates").select("*, category:email_template_categories(*)").order("sort_order");if(H)throw H;return z}}),w=yt({mutationFn:async z=>{const H={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:Z}=await q.from("agent_email_templates").update(H).eq("id",z.id);if(Z)throw Z}else{const{error:Z}=await q.from("agent_email_templates").insert(H);if(Z)throw Z}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),c(!1),ae.success(r?"Template updated":"Template created")},onError:()=>ae.error("Failed to save template")}),S=yt({mutationFn:async z=>{const{error:H}=await q.from("agent_email_templates").delete().eq("id",z);if(H)throw H},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-templates-admin"]}),ae.success("Template deleted")}}),A=yt({mutationFn:async z=>{const H={name:z.name,description:z.description||null,icon:z.icon};if(z.id){const{error:Z}=await q.from("email_template_categories").update(H).eq("id",z.id);if(Z)throw Z}else{const Z=_.length>0?Math.max(..._.map(W=>W.sort_order))+1:0,{error:Y}=await q.from("email_template_categories").insert({...H,sort_order:Z});if(Y)throw Y}},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),u(!1),ae.success(i?"Category updated":"Category created")},onError:()=>ae.error("Failed to save category")}),E=yt({mutationFn:async z=>{const{error:H}=await q.from("email_template_categories").delete().eq("id",z);if(H)throw H},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-email-template-categories"]}),ae.success("Category deleted")}}),O=()=>{a(null),p({title:"",subject:"",body:"",description:"",tone:"",category_id:"",is_active:!0}),c(!0)},D=z=>{a(z),p({title:z.title,subject:z.subject,body:z.body,description:z.description||"",tone:z.tone||"",category_id:z.category_id||"",is_active:z.is_active}),c(!0)},I=()=>{l(null),y({name:"",description:"",icon:"📧"}),u(!0)},F=z=>{l(z),y({name:z.name,description:z.description||"",icon:z.icon}),u(!0)};return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 animate-fade-in",children:[e.jsx(Bd,{title:"Agent Email Templates",description:"Manage email templates that agents use when composing emails from Mission Control."}),e.jsxs(Fr,{value:t,onValueChange:n,children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"templates",className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"})," Templates"]}),e.jsxs(Zt,{value:"categories",className:"gap-2",children:[e.jsx(pf,{className:"h-4 w-4"})," Categories"]})]}),e.jsxs(is,{value:"templates",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:O,className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"})," Add Template"]})}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Template"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Category"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Tone"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:j?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8",children:e.jsx(rs,{className:"h-6 w-6 animate-spin mx-auto"})})}):v.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No templates yet. Create your first one!"})}):v.map(z=>e.jsxs(Hs,{children:[e.jsx(ht,{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(ht,{className:"hidden md:table-cell",children:z.category?e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[z.category.icon," ",z.category.name]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ht,{className:"hidden md:table-cell",children:z.tone?e.jsx(Ue,{variant:"secondary",children:z.tone}):"—"}),e.jsx(ht,{children:e.jsx(Ue,{variant:z.is_active?"default":"secondary",children:z.is_active?"Active":"Inactive"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>D(z),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&S.mutate(z.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},z.id))})]})})})]}),e.jsxs(is,{value:"categories",className:"space-y-4",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:I,className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"})," Add Category"]})}),e.jsx("div",{className:"grid gap-3 sm:grid-cols-2 lg:grid-cols-3",children:_.map(z=>e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx("span",{className:"text-lg",children:z.icon})," ",z.name]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>F(z),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive",onClick:()=>{confirm("Delete this category?")&&E.mutate(z.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:z.description||"No description"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:[v.filter(H=>H.category_id===z.id).length," templates"]})]})]},z.id))})]})]}),e.jsx(_s,{open:o,onOpenChange:c,children:e.jsxs(bs,{className:"sm:max-w-[700px] max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:r?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:h.title,onChange:z=>p(H=>({...H,title:z.target.value})),placeholder:"e.g. Quick Check-in"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Category"}),e.jsxs(us,{value:h.category_id,onValueChange:z=>p(H=>({...H,category_id:z})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(cs,{children:_.map(z=>e.jsxs(Ze,{value:z.id,children:[z.icon," ",z.name]},z.id))})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Subject Line"}),e.jsx(ye,{value:h.subject,onChange:z=>p(H=>({...H,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(ne,{children:"Email Body"}),e.jsx(Ms,{value:h.body,onChange:z=>p(H=>({...H,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(ne,{children:"Description (internal)"}),e.jsx(ye,{value:h.description,onChange:z=>p(H=>({...H,description:z.target.value})),placeholder:"Short description for admin reference"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Tone"}),e.jsx(ye,{value:h.tone,onChange:z=>p(H=>({...H,tone:z.target.value})),placeholder:"e.g. Warm & Casual"})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:h.is_active,onCheckedChange:z=>p(H=>({...H,is_active:z}))}),e.jsx(ne,{children:"Active"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>w.mutate({...h,id:r==null?void 0:r.id}),disabled:w.isPending||!h.title||!h.subject||!h.body,children:[w.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),r?"Save Changes":"Create Template"]})]})]})}),e.jsx(_s,{open:d,onOpenChange:u,children:e.jsxs(bs,{className:"sm:max-w-[450px]",children:[e.jsx(js,{children:e.jsx(ws,{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(ne,{children:"Icon"}),e.jsx(ye,{value:f.icon,onChange:z=>y(H=>({...H,icon:z.target.value})),className:"text-center text-lg"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Name"}),e.jsx(ye,{value:f.name,onChange:z=>y(H=>({...H,name:z.target.value})),placeholder:"e.g. Check-in & Stay in Touch"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Description"}),e.jsx(ye,{value:f.description,onChange:z=>y(H=>({...H,description:z.target.value})),placeholder:"Brief description of this category"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>A.mutate({...f,id:i==null?void 0:i.id}),disabled:A.isPending||!f.name,children:[A.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),i?"Save Changes":"Create Category"]})]})]})})]})})}const dqs=({brokerageId:s})=>{var Tr,ts;const{toast:t}=Fa(),n=Ln(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,y]=N.useState(!1),[_,v]=N.useState({}),[j,w]=N.useState(!1),[S,A]=N.useState(!1),[E,O]=N.useState({email:"",name:"",password:"",phone:""}),[D,I]=N.useState(!1),[F,z]=N.useState(null),[H,Z]=N.useState(!1),[Y,W]=N.useState(!1),[ee,se]=N.useState(!1),[oe,he]=N.useState(""),[ce,me]=N.useState(!1),[le,ve]=N.useState([]),[ge,Te]=N.useState(!1),[Ie,Ce]=N.useState(!1),[Me,Pe]=N.useState(null),[Re,Ae]=N.useState({name:"",phone:"",email:""}),[Be,we]=N.useState(!1),[Je,ke]=N.useState(!1),[it,je]=N.useState(null),[He,$e]=N.useState("asc"),[Ke,Ge]=N.useState(!1),[rt,tt]=N.useState(null),[at,Ye]=N.useState(!1),[ut,_t]=N.useState(null),[bt,$t]=N.useState(""),[Yt,Ds]=N.useState(!1),[Ls,xs]=N.useState(null);N.useEffect(()=>{Jt(),Lt()},[s]);const Lt=async()=>{try{const{data:Fe,error:Qe}=await q.from("brokerage_manager_assignments").select("user_id").eq("brokerage_id",s);if(Qe)throw Qe;ve((Fe==null?void 0:Fe.map(ot=>ot.user_id))||[])}catch(Fe){console.error("Error loading brokerage managers:",Fe)}},Jt=async()=>{try{l(!0);const{data:Fe,error:Qe}=await q.functions.invoke("get-brokerage-agents",{body:{brokerageId:s}});if(Qe)throw Qe;const ot=Fe.agents||[];if(a(ot),ot.length>0){const St=ot.map(Vt=>Vt.id),{data:Bt}=await q.from("agent_assistant_assignments").select("agent_id, assistant_id").in("agent_id",St);if(Bt&&Bt.length>0){const Vt=Bt.map(ns=>ns.assistant_id),{data:fs}=await q.from("profiles").select("id, name, email").in("id",Vt),lt={};for(const ns of Bt){const Vs=fs==null?void 0:fs.find(ys=>ys.id===ns.assistant_id);Vs&&(lt[ns.agent_id]={name:Vs.name||"",email:Vs.email||""})}v(lt)}else v({})}}catch(Fe){console.error("Error loading agents:",Fe),t({title:"Error",description:"Failed to load agents",variant:"destructive"})}finally{l(!1)}},gt=async()=>{if(!E.email||!E.name||!E.password){t({title:"Error",description:"Please fill in all fields",variant:"destructive"});return}A(!0);try{const{data:{session:Fe}}=await q.auth.getSession(),Qe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/create-user",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Fe==null?void 0:Fe.access_token}`},body:JSON.stringify({...E,brokerageId:s})}),ot=await Qe.json();if(!Qe.ok)throw new Error(ot.error||"Failed to create agent");t({title:"Success",description:`Agent ${E.email} created successfully`}),O({email:"",name:"",password:"",phone:""}),w(!1),Jt()}catch(Fe){console.error("Error creating agent:",Fe),t({title:"Error",description:Fe.message||"Failed to create agent",variant:"destructive"})}finally{A(!1)}},zt=async Fe=>{try{const{data:{session:Qe}}=await q.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qe==null?void 0:Qe.access_token}`},body:JSON.stringify({userId:Fe})}),St=await ot.json();if(!ot.ok)throw new Error(St.error||"Failed to resend welcome email");t({title:"Success",description:"Welcome email sent successfully"})}catch(Qe){console.error("Error resending welcome email:",Qe),t({title:"Error",description:Qe.message||"Failed to resend welcome email",variant:"destructive"})}},As=async(Fe,Qe)=>{try{const{error:ot}=await q.functions.invoke("send-password-reset",{body:{email:Fe,redirectTo:window.location.origin}});if(ot)throw ot;t({title:"Password Reset Sent",description:`Password reset email sent to ${Qe}`})}catch(ot){console.error("Error sending password reset:",ot),t({title:"Error",description:ot.message||"Failed to send password reset email",variant:"destructive"})}},Xt=Fe=>{z(Fe),I(!0)},Qs=Fe=>{Pe(Fe),Ae({name:Fe.name,phone:Fe.phone||"",email:Fe.email}),Ce(!0)},ks=async()=>{if(!Me)return;if(!Re.name.trim()){t({title:"Error",description:"Name is required",variant:"destructive"});return}const Fe=Re.email.trim().toLowerCase()!==Me.email.toLowerCase();we(!0);try{if(Fe){if(!Re.email.trim())throw new Error("Email is required");ke(!0);const{data:{session:ot}}=await q.auth.getSession(),St=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${ot==null?void 0:ot.access_token}`},body:JSON.stringify({agentId:Me.id,newEmail:Re.email.trim(),brokerageId:s})}),Bt=await St.json();if(ke(!1),!St.ok)throw new Error(Bt.error||"Failed to update email")}const{error:Qe}=await q.from("profiles").update({name:Re.name.trim(),phone:Re.phone.trim()||null}).eq("id",Me.id);if(Qe)throw Qe;t({title:"Success",description:"Agent profile updated successfully"}),Ce(!1),Pe(null),Jt()}catch(Qe){console.error("Error updating agent:",Qe),t({title:"Error",description:Qe.message||"Failed to update agent",variant:"destructive"})}finally{we(!1),ke(!1)}},$s=async()=>{if(!oe){t({title:"Error",description:"Please select an agent to promote",variant:"destructive"});return}me(!0);try{const{data:{session:Fe}}=await q.auth.getSession(),Qe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Fe==null?void 0:Fe.access_token}`},body:JSON.stringify({userId:oe,role:"brokerage_manager",action:"add",brokerageId:s})}),ot=await Qe.json();if(!Qe.ok)throw new Error(ot.error||"Failed to add brokerage manager");t({title:"Success",description:"Brokerage manager added successfully"}),se(!1),he(""),Lt()}catch(Fe){console.error("Error adding brokerage manager:",Fe),t({title:"Error",description:Fe.message||"Failed to add brokerage manager",variant:"destructive"})}finally{me(!1)}},an=async Fe=>{try{const{data:{session:Qe}}=await q.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/manage-user-roles",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qe==null?void 0:Qe.access_token}`},body:JSON.stringify({userId:Fe,role:"brokerage_manager",action:"remove",brokerageId:s})}),St=await ot.json();if(!ot.ok)throw new Error(St.error||"Failed to remove brokerage manager");t({title:"Success",description:"Brokerage manager role removed"}),Lt()}catch(Qe){console.error("Error removing brokerage manager:",Qe),t({title:"Error",description:Qe.message||"Failed to remove brokerage manager",variant:"destructive"})}},tn=Fe=>le.includes(Fe),er=Fe=>{_t(Fe),$t(""),Ye(!0)},xn=async()=>{if(!(!ut||!bt)){if(bt.length<6){t({title:"Error",description:"Password must be at least 6 characters",variant:"destructive"});return}Ds(!0);try{const{data:{session:Fe}}=await q.auth.getSession(),Qe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Fe==null?void 0:Fe.access_token}`},body:JSON.stringify({agentId:ut.id,brokerageId:s,action:"set_password",newPassword:bt})}),ot=await Qe.json();if(!Qe.ok)throw new Error(ot.error||"Failed to set password");t({title:"Success",description:`Password set for ${ut.name}`}),Ye(!1),_t(null),$t("")}catch(Fe){console.error("Error setting password:",Fe),t({title:"Error",description:Fe.message||"Failed to set password",variant:"destructive"})}finally{Ds(!1)}}},Pn=async Fe=>{xs(Fe.id);try{const{data:{session:Qe}}=await q.auth.getSession(),ot=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/update-agent-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Qe==null?void 0:Qe.access_token}`},body:JSON.stringify({agentId:Fe.id,brokerageId:s,action:"claim_account"})}),St=await ot.json();if(!ot.ok)throw new Error(St.error||"Failed to claim account");t({title:"Success",description:`Account claimed for ${Fe.name}`}),Jt()}catch(Qe){console.error("Error claiming account:",Qe),t({title:"Error",description:Qe.message||"Failed to claim account",variant:"destructive"})}finally{xs(null)}},Qn=async()=>{if(F){Z(!0);try{const{data:{session:Fe}}=await q.auth.getSession(),Qe=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/remove-agent",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${Fe==null?void 0:Fe.access_token}`},body:JSON.stringify({userId:F.id,brokerageId:s})}),ot=await Qe.json();if(!Qe.ok)throw new Error(ot.error||"Failed to remove agent");t({title:"Success",description:`${F.name} has been removed from your brokerage`}),I(!1),z(null),Jt()}catch(Fe){console.error("Error removing agent:",Fe),t({title:"Error",description:Fe.message||"Failed to remove agent",variant:"destructive"})}finally{Z(!1)}}},sa=Fe=>{const Qe=Fe.trim().split(" ");return Qe.length>1?Qe[Qe.length-1].toLowerCase():Fe.toLowerCase()},na=Fe=>{it===Fe?$e(He==="asc"?"desc":"asc"):(je(Fe),$e("asc"))},Es=Fe=>it!==Fe?e.jsx(ah,{className:"ml-1 h-4 w-4"}):He==="asc"?e.jsx(Iu,{className:"ml-1 h-4 w-4"}):e.jsx(sm,{className:"ml-1 h-4 w-4"}),mi=r.filter(Fe=>{if(d==="active"&&!Fe.claimed||d==="pending"&&Fe.claimed)return!1;if(!o)return!0;const Qe=o.toLowerCase();return Fe.name.toLowerCase().includes(Qe)||Fe.email.toLowerCase().includes(Qe)}),Ar=[...mi].sort((Fe,Qe)=>{if(!it)return 0;let ot=0;return it==="name"?ot=sa(Fe.name).localeCompare(sa(Qe.name)):it==="status"&&(ot=Fe.claimed===Qe.claimed?0:Fe.claimed?-1:1),He==="asc"?ot:-ot});mi.filter(Fe=>Fe.claimed&&!tn(Fe.id));const Hn=Fe=>{p(Qe=>{const ot=new Set(Qe);return ot.has(Fe)?ot.delete(Fe):ot.add(Fe),ot})},Ts=()=>{h.size===Ar.length?p(new Set):p(new Set(Ar.map(Fe=>Fe.id)))},Un=()=>{p(new Set)},ir=async()=>{const Fe=Array.from(h);if(Fe.length===0)return;y(!0);let Qe=0,ot=0;try{const{data:{session:St}}=await q.auth.getSession();for(const Bt of Fe)try{(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/resend-welcome-email",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${St==null?void 0:St.access_token}`},body:JSON.stringify({userId:Bt})})).ok?Qe++:ot++}catch{ot++}Qe>0?t({title:"Success",description:`Welcome emails sent to ${Qe} agent${Qe>1?"s":""}${ot>0?` (${ot} failed)`:""}`}):t({title:"Error",description:"Failed to send welcome emails",variant:"destructive"}),Un()}catch(St){console.error("Error bulk sending welcome emails:",St),t({title:"Error",description:St.message||"Failed to send welcome emails",variant:"destructive"})}finally{y(!1)}};return i?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Agents"}),e.jsx(Vn,{children:"Manage your brokerage's agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>se(!0),children:[e.jsx(Ih,{className:"mr-2 h-4 w-4"}),"Add Brokerage Manager"]}),e.jsxs(B,{variant:"outline",onClick:()=>W(!0),children:[e.jsx(mw,{className:"mr-2 h-4 w-4"}),"Import CSV"]}),e.jsxs(B,{onClick:()=>w(!0),children:[e.jsx(Fo,{className:"mr-2 h-4 w-4"}),"Add Agent"]})]})]})}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"mb-4 flex flex-col gap-4 sm:flex-row sm:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-3 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:o,onChange:Fe=>c(Fe.target.value),className:"pl-9"})]}),e.jsxs(us,{value:d,onValueChange:Fe=>u(Fe),children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(hs,{placeholder:"Filter by status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Agents"}),e.jsx(Ze,{value:"active",children:"Active"}),e.jsx(Ze,{value:"pending",children:"Pending"})]})]})]}),h.size>0&&e.jsxs("div",{className:"mb-4 flex items-center gap-3 rounded-lg border bg-muted/50 p-3",children:[e.jsxs("span",{className:"text-sm font-medium",children:[h.size," agent",h.size>1?"s":""," selected"]}),e.jsx("div",{className:"flex-1"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{const Qe=r.filter(ot=>h.has(ot.id)&&ot.email).map(ot=>({email:ot.email,name:ot.name}));sessionStorage.setItem("campaign_direct_recipients",JSON.stringify(Qe)),n("/admin/email-campaigns/new?directMode=1",{state:{directRecipients:Qe}})},disabled:f,children:[e.jsx(zd,{className:"mr-2 h-4 w-4"}),"Email Agents (",h.size,")"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:ir,disabled:f,children:[e.jsx(Gs,{className:"mr-2 h-4 w-4"}),f?"Sending...":"Resend Welcome Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:Un,children:"Clear"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(hi,{checked:Ar.length>0&&h.size===Ar.length,onCheckedChange:Ts,"aria-label":"Select all"})}),e.jsx(Tt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>na("name"),children:["Name (Last)",Es("name")]})}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:e.jsxs(B,{variant:"ghost",size:"sm",className:"-ml-3 h-8 hover:bg-transparent",onClick:()=>na("status"),children:["Status",Es("status")]})}),e.jsx(Tt,{children:"Actions"})]})}),e.jsx(da,{children:Ar.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center text-muted-foreground",children:"No agents found"})}):Ar.map(Fe=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsx(hi,{checked:h.has(Fe.id),onCheckedChange:()=>Hn(Fe.id),"aria-label":`Select ${Fe.name}`})}),e.jsx(ht,{className:"font-medium",children:Fe.name}),e.jsx(ht,{children:Fe.email}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[Fe.claimed?e.jsx(Ue,{variant:"default",children:"Active"}):e.jsx(Ue,{variant:"secondary",children:"Pending"}),tn(Fe.id)&&e.jsxs(Ue,{variant:"outline",className:"border-primary text-primary",children:[e.jsx(eg,{className:"mr-1 h-3 w-3"}),"Manager"]}),_[Fe.id]&&e.jsxs(Ue,{variant:"outline",className:"text-xs",children:[e.jsx(An,{className:"mr-1 h-3 w-3"}),"Asst: ",_[Fe.id].name||_[Fe.id].email]})]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-1 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{tt(Fe),Ge(!0)},title:"Send celebration",className:"text-yellow-500 hover:text-yellow-600 hover:bg-yellow-50",children:e.jsx(ih,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Qs(Fe),title:"Edit agent",children:e.jsx(ya,{className:"h-4 w-4"})}),!Fe.claimed&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>zt(Fe.id),title:"Resend welcome email",children:e.jsx(Gs,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Pn(Fe),title:"Claim account for agent",disabled:Ls===Fe.id,className:"text-green-600 hover:text-green-700 hover:bg-green-50",children:e.jsx(xb,{className:"h-4 w-4"})})]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>er(Fe),title:"Set password",className:"text-blue-600 hover:text-blue-700 hover:bg-blue-50",children:e.jsx(Gc,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>As(Fe.email,Fe.name),title:"Send password reset email",children:e.jsx(SA,{className:"h-4 w-4"})}),tn(Fe.id)&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>an(Fe.id),title:"Remove manager role",className:"text-orange-500 hover:text-orange-600",children:e.jsx(Ih,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>Xt(Fe),className:"text-destructive hover:text-destructive",title:"Remove agent",children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Fe.id))})]})})]})]}),e.jsx(_s,{open:j,onOpenChange:w,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Add New Agent"}),e.jsx(Jn,{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(ne,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",value:E.name,onChange:Fe=>O({...E,name:Fe.target.value}),placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:E.email,onChange:Fe=>O({...E,email:Fe.target.value}),placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"phone",children:"Phone (optional)"}),e.jsx(ye,{id:"phone",type:"tel",value:E.phone,onChange:Fe=>O({...E,phone:Fe.target.value}),placeholder:"555-123-4567"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"password",children:"Temporary Password"}),e.jsx(ye,{id:"password",type:"password",value:E.password,onChange:Fe=>O({...E,password:Fe.target.value}),placeholder:"Temporary password"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>w(!1),children:"Cancel"}),e.jsx(B,{onClick:gt,disabled:S,children:S?"Creating...":"Create Agent"})]})]})}),e.jsx(_s,{open:D,onOpenChange:I,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Remove Agent"}),e.jsxs(Jn,{children:["Are you sure you want to remove ",e.jsx("strong",{children:F==null?void 0:F.name})," from your brokerage? This will revoke their access to the dashboard."]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>I(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Qn,disabled:H,children:H?"Removing...":"Remove Agent"})]})]})}),e.jsx(I0t,{open:Y,onOpenChange:W,fixedBrokerageId:s,onSuccess:Jt}),e.jsx(_s,{open:ee,onOpenChange:se,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Add Brokerage Manager"}),e.jsx(Jn,{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(ne,{children:"Select Agent"}),e.jsxs(il,{open:ge,onOpenChange:Te,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":ge,className:"w-full justify-between",children:[oe?((Tr=r.find(Fe=>Fe.id===oe))==null?void 0:Tr.name)+" ("+((ts=r.find(Fe=>Fe.id===oe))==null?void 0:ts.email)+")":"Select an agent to promote...",e.jsx($g,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-full p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search by name or email..."}),e.jsxs(Qg,{className:"max-h-[200px]",children:[e.jsx(Xg,{children:"No eligible agents found."}),e.jsx(Jg,{children:r.filter(Fe=>!tn(Fe.id)).map(Fe=>e.jsxs(Zf,{value:`${Fe.name} ${Fe.email}`,onSelect:()=>{he(Fe.id),Te(!1)},children:[e.jsx(Lr,{className:`mr-2 h-4 w-4 ${oe===Fe.id?"opacity-100":"opacity-0"}`}),Fe.name," (",Fe.email,")"]},Fe.id))})]})]})})]}),r.filter(Fe=>!tn(Fe.id)).length===0&&e.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"All agents are already brokerage managers."})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>se(!1),children:"Cancel"}),e.jsx(B,{onClick:$s,disabled:ce||!oe,children:ce?"Adding...":"Add as Manager"})]})]})}),e.jsx(_s,{open:Ie,onOpenChange:Ce,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Edit Agent"}),e.jsxs(Jn,{children:["Update profile information for ",Me==null?void 0:Me.name]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"edit-name",children:"Name"}),e.jsx(ye,{id:"edit-name",value:Re.name,onChange:Fe=>Ae({...Re,name:Fe.target.value}),placeholder:"Agent name"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"edit-email",children:"Email"}),e.jsx(ye,{id:"edit-email",type:"email",value:Re.email,onChange:Fe=>Ae({...Re,email:Fe.target.value}),placeholder:"agent@example.com"}),Re.email.trim().toLowerCase()!==(Me==null?void 0:Me.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(ne,{htmlFor:"edit-phone",children:"Phone"}),e.jsx(ye,{id:"edit-phone",type:"tel",value:Re.phone,onChange:Fe=>Ae({...Re,phone:Fe.target.value}),placeholder:"555-123-4567"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ce(!1),children:"Cancel"}),e.jsx(B,{onClick:ks,disabled:Be||Je,children:Je?"Updating email...":Be?"Saving...":"Save Changes"})]})]})}),rt&&e.jsx(P0t,{open:Ke,onOpenChange:Fe=>{Ge(Fe),Fe||tt(null)},userId:rt.id,userName:rt.name}),e.jsx(_s,{open:at,onOpenChange:Ye,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Set Password"}),e.jsxs(Jn,{children:["Set a new password for ",ut==null?void 0:ut.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(ne,{htmlFor:"new-password",children:"New Password"}),e.jsx(ye,{id:"new-password",type:"password",value:bt,onChange:Fe=>$t(Fe.target.value),placeholder:"Enter new password (min 6 characters)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Make sure to communicate this password to the agent through a secure channel."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ye(!1),children:"Cancel"}),e.jsx(B,{onClick:xn,disabled:Yt||!bt||bt.length<6,children:Yt?"Setting...":"Set Password"})]})]})})]})},uqs={academy_video:"Academy Video",template:"Template",toolbox:"Toolbox Resource",newsletter:"Newsletter",social_swag:"Social Swag",event:"Event"},hqs={view:"Viewed",click_canva:"Opened Canva",click_pdf:"Downloaded PDF",click_video:"Watched Video",click_link:"Clicked Link",register:"Registered"},mqs=s=>{switch(s){case"academy_video":return e.jsx(fr,{className:"h-4 w-4"});case"template":return e.jsx(br,{className:"h-4 w-4"});case"toolbox":return e.jsx(br,{className:"h-4 w-4"});case"newsletter":return e.jsx(sy,{className:"h-4 w-4"});case"social_swag":return e.jsx(un,{className:"h-4 w-4"});case"event":return e.jsx(yr,{className:"h-4 w-4"});default:return e.jsx(tr,{className:"h-4 w-4"})}},pqs=({brokerageId:s})=>{const{toast:t}=Fa(),[n,r]=N.useState([]),[a,i]=N.useState([]),[l,o]=N.useState([]),[c,d]=N.useState(!0),[u,h]=N.useState(null);N.useEffect(()=>{p()},[s]);const p=async()=>{try{d(!0);const{data:_,error:v}=await q.from("profiles").select("id, name, email").eq("brokerage_id",s);if(v)throw v;const j=_.map(H=>H.id),w=new Map(_.map(H=>[H.id,H]));if(j.length===0){r([]),i([]),o([]);return}const{data:S,error:A}=await q.from("activity_logs").select("*").in("user_id",j).order("launched_at",{ascending:!1});if(A)throw A;const E=S.map(H=>{var Z,Y;return{id:H.id,user_id:H.user_id,app_name:H.app_name,launched_at:H.launched_at,user_name:((Z=w.get(H.user_id))==null?void 0:Z.name)||"Unknown",user_email:((Y=w.get(H.user_id))==null?void 0:Y.email)||"Unknown"}});r(E);const{data:O,error:D}=await q.from("content_engagement_logs").select("*").in("user_id",j).order("created_at",{ascending:!1});if(D)throw D;const I=(O||[]).map(H=>{var Z,Y;return{id:H.id,user_id:H.user_id,resource_type:H.resource_type,resource_id:H.resource_id,resource_title:H.resource_title,action_type:H.action_type,created_at:H.created_at,user_name:((Z=w.get(H.user_id))==null?void 0:Z.name)||"Unknown",user_email:((Y=w.get(H.user_id))==null?void 0:Y.email)||"Unknown"}});i(I);const F=new Map;_.forEach(H=>{F.set(H.id,{user_id:H.id,user_name:H.name,user_email:H.email,app_launches:0,content_views:0,last_activity:""})}),E.forEach(H=>{const Z=F.get(H.user_id);Z&&(Z.app_launches++,(!Z.last_activity||new Date(H.launched_at)>new Date(Z.last_activity))&&(Z.last_activity=H.launched_at))}),I.forEach(H=>{const Z=F.get(H.user_id);Z&&(Z.content_views++,(!Z.last_activity||new Date(H.created_at)>new Date(Z.last_activity))&&(Z.last_activity=H.created_at))});const z=Array.from(F.values()).filter(H=>H.app_launches>0||H.content_views>0).sort((H,Z)=>new Date(Z.last_activity).getTime()-new Date(H.last_activity).getTime());o(z)}catch(_){console.error("Error loading activity:",_),t({title:"Error",description:"Failed to load activity logs",variant:"destructive"})}finally{d(!1)}},f=_=>n.filter(v=>v.user_id===_),y=_=>a.filter(v=>v.user_id===_);return c?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Agent Activity"}),e.jsx(Vn,{children:"Track app usage and content engagement - click an agent for details"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"App Launches"}),e.jsx(Tt,{className:"text-center",children:"Content Views"}),e.jsx(Tt,{children:"Last Active"})]})}),e.jsx(da,{children:l.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:4,className:"text-center text-muted-foreground",children:"No activity yet"})}):l.map(_=>e.jsxs(Hs,{className:"cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>h({id:_.user_id,name:_.user_name,email:_.user_email}),children:[e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:_.user_name}),e.jsx("div",{className:"text-sm text-muted-foreground",children:_.user_email})]})}),e.jsx(ht,{className:"text-center",children:e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(El,{className:"h-3 w-3"}),_.app_launches]})}),e.jsx(ht,{className:"text-center",children:e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(br,{className:"h-3 w-3"}),_.content_views]})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:_.last_activity&&Uo(new Date(_.last_activity),{addSuffix:!0})})]},_.user_id))})]})})})]}),e.jsx(_s,{open:!!u,onOpenChange:_=>!_&&h(null),children:e.jsxs(bs,{className:"max-w-3xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(ws,{children:[u==null?void 0:u.name,"'s Activity"]}),e.jsx(Jn,{children:u==null?void 0:u.email})]}),e.jsxs(Fr,{defaultValue:"content",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"content",children:"Content Engagement"}),e.jsx(Zt,{value:"apps",children:"App Launches"})]}),e.jsx(is,{value:"content",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Resource"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(da,{children:u&&y(u.id).length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:4,className:"text-center text-muted-foreground",children:"No content engagement yet"})}):u&&y(u.id).map(_=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"max-w-[200px] truncate font-medium",children:_.resource_title}),e.jsx(ht,{children:e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[mqs(_.resource_type),uqs[_.resource_type]||_.resource_type]})}),e.jsx(ht,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:hqs[_.action_type]||_.action_type})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Uo(new Date(_.created_at),{addSuffix:!0})})]},_.id))})]})})}),e.jsx(is,{value:"apps",className:"flex-1 overflow-auto",children:e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"App"}),e.jsx(Tt,{children:"Time"})]})}),e.jsx(da,{children:u&&f(u.id).length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:2,className:"text-center text-muted-foreground",children:"No app launches yet"})}):u&&f(u.id).map(_=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",children:_.app_name})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Uo(new Date(_.launched_at),{addSuffix:!0})})]},_.id))})]})})})]})]})})]})},fqs=({brokerageId:s})=>{const{toast:t}=Fa(),[n,r]=N.useState({totalAgents:0,activeAgents:0,pendingAgents:0,totalLaunches:0,launchesThisWeek:0,launchesThisMonth:0}),[a,i]=N.useState(!0);N.useEffect(()=>{l()},[s]);const l=async()=>{try{i(!0);const{data:o,error:c}=await q.from("profiles").select("id").eq("brokerage_id",s);if(c)throw c;const d=o.map(E=>E.id),u=d.length;if(d.length===0){i(!1);return}const{data:h,error:p}=await q.from("profiles").select("id, email").in("id",d);if(p)throw p;const{count:f}=await q.from("profiles").select("*",{count:"exact",head:!0}).eq("brokerage_id",s).not("last_login","is",null),y=f||0,_=u-y,{count:v}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d),j=new Date;j.setDate(j.getDate()-7);const{count:w}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",j.toISOString()),S=new Date;S.setMonth(S.getMonth()-1);const{count:A}=await q.from("activity_logs").select("*",{count:"exact",head:!0}).in("user_id",d).gte("launched_at",S.toISOString());r({totalAgents:u,activeAgents:y,pendingAgents:_,totalLaunches:v||0,launchesThisWeek:w||0,launchesThisMonth:A||0})}catch(o){console.error("Error loading analytics:",o),t({title:"Error",description:"Failed to load analytics",variant:"destructive"})}finally{i(!1)}};return a?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total Agents"}),e.jsx(An,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalAgents}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[n.activeAgents," active, ",n.pendingAgents," pending"]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Active Agents"}),e.jsx(Pi,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.activeAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:n.totalAgents>0?`${Math.round(n.activeAgents/n.totalAgents*100)}% of total`:"0% of total"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Pending Invites"}),e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.pendingAgents}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Awaiting setup"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total App Launches"}),e.jsx(em,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.totalLaunches}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"All time"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"This Week"}),e.jsx(em,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisWeek}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 7 days"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"This Month"}),e.jsx(em,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsxs(Ee,{children:[e.jsx("div",{className:"text-2xl font-bold",children:n.launchesThisMonth}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Last 30 days"})]})]})]})},xqs=({brokerageId:s})=>{const[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({description:"",maxUses:""});N.useEffect(()=>{h()},[s]);const h=async()=>{try{const{data:j,error:w}=await q.from("invite_codes").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(w)throw w;n(j||[])}catch(j){console.error("Error loading invite codes:",j),ae.error("Failed to load invite links")}finally{a(!1)}},p=()=>Math.random().toString(36).substring(2,8).toUpperCase(),f=async()=>{l(!0);try{const j=p(),{error:w}=await q.from("invite_codes").insert({code:j,description:d.description||null,max_uses:d.maxUses?parseInt(d.maxUses):null,brokerage_id:s,is_active:!0});if(w)throw w;ae.success("Invite link created!"),c(!1),u({description:"",maxUses:""}),h()}catch(j){console.error("Error creating invite code:",j),ae.error("Failed to create invite link")}finally{l(!1)}},y=async j=>{try{const{error:w}=await q.from("invite_codes").delete().eq("id",j);if(w)throw w;ae.success("Invite link deleted"),n(t.filter(S=>S.id!==j))}catch(w){console.error("Error deleting invite code:",w),ae.error("Failed to delete invite link")}},_=async(j,w)=>{try{const{error:S}=await q.from("invite_codes").update({is_active:!w}).eq("id",j);if(S)throw S;n(t.map(A=>A.id===j?{...A,is_active:!w}:A)),ae.success(`Invite link ${w?"deactivated":"activated"}`)}catch(S){console.error("Error toggling invite code:",S),ae.error("Failed to update invite link")}},v=j=>{const w=`${window.location.origin}/join?code=${j}`;navigator.clipboard.writeText(w),ae.success("Link copied to clipboard!")};return r?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-8",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})})}):e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Yo,{className:"h-5 w-5"}),"Agent Invite Links"]}),e.jsx(Vn,{children:"Create shareable links for agents to join your brokerage"})]}),e.jsxs(_s,{open:o,onOpenChange:c,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Link"]})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create Invite Link"}),e.jsx(Jn,{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(ne,{htmlFor:"description",children:"Description (optional)"}),e.jsx(ye,{id:"description",placeholder:"e.g., New agent recruiting campaign",value:d.description,onChange:j=>u({...d,description:j.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"maxUses",children:"Max Uses (optional)"}),e.jsx(ye,{id:"maxUses",type:"number",placeholder:"Leave empty for unlimited",value:d.maxUses,onChange:j=>u({...d,maxUses:j.target.value})})]}),e.jsx(B,{onClick:f,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Invite Link"})]})]})]})]}),e.jsx(Ee,{children:t.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Yo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No invite links yet"}),e.jsx("p",{className:"text-sm",children:"Create one to start inviting agents"})]}):e.jsx("div",{className:"space-y-3",children:t.map(j=>e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("code",{className:"text-sm font-mono bg-muted px-2 py-0.5 rounded",children:j.code}),e.jsx(Ue,{variant:j.is_active?"default":"secondary",children:j.is_active?"Active":"Inactive"})]}),j.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:j.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[j.uses_count," uses",j.max_uses&&` / ${j.max_uses} max`]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.code),title:"Copy link",children:e.jsx(Zr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>_(j.id,j.is_active),title:j.is_active?"Deactivate":"Activate",children:j.is_active?"Disable":"Enable"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>y(j.id),className:"text-destructive hover:text-destructive",title:"Delete",children:e.jsx(_n,{className:"h-4 w-4"})})]})]},j.id))})})]})},gqs=({open:s,onOpenChange:t,referralCode:n,brokerageId:r,senderName:a,brokerageName:i,onInvitesSent:l})=>{const[o,c]=N.useState(""),[d,u]=N.useState([]),[h,p]=N.useState(""),[f,y]=N.useState(!1),_=A=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(A),v=()=>{const A=o.trim().toLowerCase();if(A&&_(A)&&!d.includes(A)){if(d.length>=10){ae.error("Maximum 10 emails per invite");return}u([...d,A]),c("")}else A&&!_(A)?ae.error("Please enter a valid email address"):d.includes(A)&&ae.error("Email already added")},j=A=>{u(d.filter(E=>E!==A))},w=A=>{(A.key==="Enter"||A.key===",")&&(A.preventDefault(),v())},S=async()=>{if(d.length===0){ae.error("Please add at least one email address");return}y(!0);try{const{data:A,error:E}=await q.functions.invoke("send-referral-invite",{body:{emails:d,personalMessage:h.trim()||void 0,referralCode:n,brokerageId:r,senderName:a,brokerageName:i}});if(E)throw E;A.successCount===A.totalCount?ae.success(`${A.successCount} invite${A.successCount>1?"s":""} sent successfully!`):ae.warning(`${A.successCount} of ${A.totalCount} invites sent. Some failed.`),u([]),p(""),t(!1),l==null||l()}catch(A){console.error("Error sending invites:",A),ae.error("Failed to send invites. Please try again.")}finally{y(!1)}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[550px]",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5 text-primary"}),"Invite Broker Friends"]}),e.jsx(Jn,{children:"Send a personalized email invitation to broker owners you know. They'll receive a beautiful email highlighting LevelUp's features."})]}),e.jsxs("div",{className:"bg-gradient-to-r from-primary/10 to-primary/5 border border-primary/20 rounded-lg p-4 flex items-center gap-3",children:[e.jsx("div",{className:"bg-primary/20 rounded-full p-2",children:e.jsx(Oi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:"Earn $25/month for each referral!"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"When they sign up and stay for 30 days, you save on your membership forever."})]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"email",children:"Email Addresses (up to 10)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{id:"email",type:"email",placeholder:"Enter email and press Enter",value:o,onChange:A=>c(A.target.value),onKeyDown:w,onBlur:v}),e.jsx(B,{type:"button",variant:"secondary",onClick:v,children:"Add"})]}),d.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:d.map(A=>e.jsxs(Ue,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[A,e.jsx("button",{type:"button",onClick:()=>j(A),className:"ml-1 rounded-full p-0.5 hover:bg-muted",children:e.jsx($n,{className:"h-3 w-3"})})]},A))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"message",children:"Personal Message (optional)"}),e.jsx(Ms,{id:"message",placeholder:"Add a personal note that will appear at the top of the email...",value:h,onChange:A=>p(A.target.value),rows:3,maxLength:500}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[h.length,"/500 characters"]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"What they'll receive:"]}),e.jsxs("ul",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Beautiful branded email from you"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Your personal message (if added)"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Key LevelUp features for brokerages"]}),e.jsxs("li",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"w-1 h-1 rounded-full bg-primary"}),"Direct signup link with your referral code"]})]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:S,disabled:d.length===0||f,children:f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-current border-t-transparent mr-2"}),"Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Send ",d.length>0&&`(${d.length})`," Invite",d.length!==1?"s":""]})})]})]})})},yqs=({brokerageId:s,refreshTrigger:t})=>{const[n,r]=N.useState([]),[a,i]=N.useState(!0);N.useEffect(()=>{l()},[s,t]);const l=async()=>{try{const{data:c,error:d}=await q.from("referral_invites").select("*").eq("referrer_brokerage_id",s).order("sent_at",{ascending:!1}).limit(20);if(d)throw d;r(c||[])}catch(c){console.error("Error fetching invites:",c)}finally{i(!1)}},o=c=>{switch(c){case"signed_up":return e.jsxs(Ue,{className:"bg-green-100 text-green-800 gap-1",children:[e.jsx(Pi,{className:"h-3 w-3"}),"Signed Up"]});case"expired":return e.jsxs(Ue,{variant:"outline",className:"text-muted-foreground gap-1",children:[e.jsx(Uc,{className:"h-3 w-3"}),"Expired"]});default:return e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),"Pending"]})}};return a?e.jsx("div",{className:"flex justify-center py-4",children:e.jsx("div",{className:"h-5 w-5 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):n.length===0?e.jsxs("div",{className:"text-center py-6 text-muted-foreground",children:[e.jsx(Gs,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:"No invites sent yet"}),e.jsx("p",{className:"text-xs",children:"Start inviting broker friends to earn rewards!"})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium mb-3",children:"Recent Invites"}),n.map(c=>e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:c.recipient_email}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent ",Ss(new Date(c.sent_at),"MMM d, yyyy")]})]}),o(c.status)]},c.id))]})},vqs=()=>{const{brokerageId:s,user:t}=vs(),[n,r]=N.useState(null),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState([]),[u,h]=N.useState(!0),[p,f]=N.useState(!1),[y,_]=N.useState(0);N.useEffect(()=>{s&&v()},[s]);const v=async()=>{try{const[O,D]=await Promise.all([q.from("brokerages").select("name").eq("id",s).single(),t?q.from("profiles").select("name").eq("id",t.id).single():Promise.resolve({data:null})]);O.data&&i(O.data.name),D.data&&o(D.data.name||"A LevelUp Member");const{data:I}=await q.from("referral_codes").select("code").eq("brokerage_id",s).single();if(I)r(I.code);else{const z=`REF${s==null?void 0:s.slice(0,8).toUpperCase()}`;await q.from("referral_codes").insert({brokerage_id:s,code:z}),r(z)}const{data:F}=await q.from("referrals").select(` *, referred_user:profiles!referred_user_id(name, email), referred_brokerage:brokerages!referred_brokerage_id(name) `).eq("referrer_brokerage_id",s).order("created_at",{ascending:!1});d(F||[])}catch(O){console.error("Error fetching referral data:",O)}finally{h(!1)}},j=()=>{const O=`https://dashboard.relevelup.com/?ref=${n}`;navigator.clipboard.writeText(O),ae.success("Referral link copied to clipboard!")},w=c.filter(O=>O.status==="qualified").length,S=c.filter(O=>O.status==="pending").length,A=w*25,E=Math.max(0,Math.ceil((299-A)/25));return u?null:e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-gradient-to-r from-primary/10 via-primary/5 to-background border-b",children:e.jsxs("div",{className:"px-6 py-6",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-2",children:[e.jsx("div",{className:"bg-primary/20 rounded-full p-2",children:e.jsx(Oi,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-bold",children:"Referral Rewards Program"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Earn $25/month off your membership for every broker you refer"})]})]}),e.jsx("div",{className:"mt-4 bg-background/80 rounded-lg p-4 border",children:e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"text-3xl font-bold text-primary",children:["$",A]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Savings"})]}),A>0&&e.jsxs("div",{className:"flex items-center gap-1 text-green-600",children:[e.jsx(Pi,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm font-medium",children:"Active"})]})]}),E>0&&A<299&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm font-medium",children:["Refer ",E," more = ",e.jsx("span",{className:"text-primary",children:"FREE membership!"})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Your membership could cost $0/month"})]}),A>=299&&e.jsxs("div",{className:"flex items-center gap-2 text-primary",children:[e.jsx(un,{className:"h-5 w-5"}),e.jsx("span",{className:"font-bold",children:"FREE Membership Unlocked!"})]})]})})]})}),e.jsxs(Ee,{className:"pt-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsxs(B,{onClick:()=>f(!0),className:"w-full",size:"lg",children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Invite Broker Friends"]}),e.jsxs(B,{onClick:j,variant:"outline",className:"w-full",size:"lg",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Copy Referral Link"]})]}),e.jsxs("div",{className:"p-4 bg-muted/50 rounded-lg",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Your Referral Link"}),e.jsxs("code",{className:"block px-3 py-2 bg-background rounded border text-sm break-all",children:["https://dashboard.relevelup.com/?ref=",n]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"text-center p-4 bg-green-50 dark:bg-green-950/20 rounded-lg border border-green-200 dark:border-green-900",children:[e.jsx(Yl,{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(An,{className:"h-5 w-5 mx-auto text-primary mb-1"}),e.jsx("p",{className:"text-2xl font-bold",children:w}),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(pr,{className:"h-5 w-5 mx-auto text-amber-600 mb-1"}),e.jsx("p",{className:"text-2xl font-bold text-amber-700 dark:text-amber-400",children:S}),e.jsx("p",{className:"text-xs text-amber-600 dark:text-amber-500",children:"Pending (30 days)"})]})]}),e.jsxs("div",{className:"bg-muted/30 rounded-lg p-4",children:[e.jsx("h4",{className:"font-semibold text-sm mb-3",children:"How It Works"}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"1"}),e.jsx("p",{children:"Share your referral link or send an invite email to broker friends"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"2"}),e.jsx("p",{children:"They sign up and subscribe to LevelUp"})]}),e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"bg-primary text-primary-foreground rounded-full w-5 h-5 flex items-center justify-center text-xs shrink-0",children:"3"}),e.jsx("p",{children:"After 30 days, you get $25/month off your membership - forever!"})]})]})]}),e.jsx(yqs,{brokerageId:s,refreshTrigger:y}),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(O=>{var D,I;return e.jsxs("div",{className:"flex items-center justify-between p-2.5 bg-muted/30 rounded-lg",children:[e.jsx("span",{className:"text-sm truncate",children:((D=O.referred_brokerage)==null?void 0:D.name)||((I=O.referred_user)==null?void 0:I.email)||"Pending setup"}),e.jsxs(Ue,{variant:O.status==="qualified"?"default":O.status==="pending"?"secondary":"destructive",className:O.status==="qualified"?"bg-green-600":"",children:[O.status==="qualified"&&e.jsx(Pi,{className:"h-3 w-3 mr-1"}),O.status]})]},O.id)})]})]})]}),e.jsx(gqs,{open:p,onOpenChange:f,referralCode:n||"",brokerageId:s||"",senderName:l||"A LevelUp Member",brokerageName:a,onInvitesSent:()=>_(O=>O+1)})]})},bqs=({brokerageId:s})=>{const t=Ln(),{teams:n,isLoading:r}=YM(s),{data:a,isLoading:i}=dt({queryKey:["team-aggregate-stats",s,n.map(u=>u.id)],queryFn:async()=>{if(n.length===0)return[];const u=n.map(O=>O.id),{data:h}=await q.from("team_members").select("team_id, user_id, role").in("team_id",u);if(!h||h.length===0)return n.map(O=>({team_id:O.id,team_name:O.name,member_count:0,leader_name:null,leader_avatar:null,total_contacts:0,total_deals:0,total_videos:0}));const p=h.map(O=>O.user_id),f=h.filter(O=>O.role==="team_leader").map(O=>O.user_id),{data:y}=await q.from("profiles").select("id, name, avatar_url").in("id",f),_=new Map((y||[]).map(O=>[O.id,O])),{data:v}=await q.from("innercircle_contacts").select("owner_user_id").in("owner_user_id",p),{data:j}=await q.from("deal_pipeline").select("owner_user_id").in("owner_user_id",p),{data:w}=await q.from("agent_videos").select("owner_user_id").in("owner_user_id",p).eq("is_deleted",!1),S=new Map;(v||[]).forEach(O=>{S.set(O.owner_user_id,(S.get(O.owner_user_id)||0)+1)});const A=new Map;(j||[]).forEach(O=>{A.set(O.owner_user_id,(A.get(O.owner_user_id)||0)+1)});const E=new Map;return(w||[]).forEach(O=>{E.set(O.owner_user_id,(E.get(O.owner_user_id)||0)+1)}),n.map(O=>{const D=h.filter(W=>W.team_id===O.id),I=D.find(W=>W.role==="team_leader"),F=I?_.get(I.user_id):null,z=D.map(W=>W.user_id),H=z.reduce((W,ee)=>W+(S.get(ee)||0),0),Z=z.reduce((W,ee)=>W+(A.get(ee)||0),0),Y=z.reduce((W,ee)=>W+(E.get(ee)||0),0);return{team_id:O.id,team_name:O.name,member_count:D.length,leader_name:(F==null?void 0:F.name)||null,leader_avatar:(F==null?void 0:F.avatar_url)||null,total_contacts:H,total_deals:Z,total_videos:Y}})},enabled:n.length>0});if(r||i)return e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(u=>e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Ws,{className:"h-5 w-32"})}),e.jsx(Ee,{children:e.jsx(Ws,{className:"h-24 w-full"})})]},u))});if(n.length===0)return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(An,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create teams to organize your agents and track their performance."}),e.jsx(B,{onClick:()=>t("/brokerage/teams"),children:"Manage Teams"})]})});const o=(a||[]).reduce((u,h)=>u+h.member_count,0),c=(a||[]).reduce((u,h)=>u+h.total_contacts,0),d=(a||[]).reduce((u,h)=>u+h.total_deals,0);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 grid-cols-2 md:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(An,{className:"h-4 w-4"})," Teams"]}),e.jsx("p",{className:"text-2xl font-bold",children:n.length})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(An,{className:"h-4 w-4"})," Total Members"]}),e.jsx("p",{className:"text-2xl font-bold",children:o})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(bA,{className:"h-4 w-4"})," Total Contacts"]}),e.jsx("p",{className:"text-2xl font-bold",children:c.toLocaleString()})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground mb-1",children:[e.jsx(zm,{className:"h-4 w-4"})," Total Deals"]}),e.jsx("p",{className:"text-2xl font-bold",children:d.toLocaleString()})]})})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:(a||[]).map(u=>e.jsxs(fe,{className:"hover:shadow-md transition-shadow",children:[e.jsxs(It,{className:"pb-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Rt,{className:"text-lg",children:u.team_name}),e.jsxs(Ue,{variant:"secondary",children:[u.member_count," members"]})]}),u.leader_name&&e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsxs(Jr,{className:"h-6 w-6",children:[e.jsx(ti,{src:u.leader_avatar||""}),e.jsx(ea,{className:"text-xs",children:u.leader_name.charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(hf,{className:"h-3 w-3 text-amber-500"}),u.leader_name]})]})]}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_contacts.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_deals.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-semibold",children:u.total_videos.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Videos"})]})]})})]},u.team_id))}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{variant:"outline",onClick:()=>t("/brokerage/teams"),children:"Manage Teams →"})})]})},_qs=()=>{const{user:s,isBrokerageManager:t,brokerageId:n,isAdmin:r,managedBrokerages:a,selectedBrokerageId:i,setSelectedBrokerageId:l}=vs(),o=Ln(),{toast:c}=Fa(),[d,u]=N.useState(""),[h,p]=N.useState(!0),f=i||(a.length>0?a[0].id:n);N.useEffect(()=>{if(!s||!t&&!r){o("/dashboard");return}!i&&a.length>0&&l(a[0].id),f?y():a.length===0&&!n&&p(!1)},[s,t,r,f,o,a,i]);const y=async()=>{if(!f){p(!1);return}try{const{data:_,error:v}=await q.from("brokerages").select("name").eq("id",f).single();if(v)throw v;u(_.name)}catch(_){console.error("Error loading brokerage info:",_),c({title:"Error",description:"Failed to load brokerage information",variant:"destructive"})}finally{p(!1)}};return h?e.jsx(Cs,{title:"Manage Brokerages",description:"Loading brokerage information...",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):f?e.jsx(Cs,{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(us,{value:i||"",onValueChange:l,children:[e.jsxs(ls,{className:"w-[280px]",children:[e.jsx(Ua,{className:"mr-2 h-4 w-4"}),e.jsx(hs,{placeholder:"Select brokerage"})]}),e.jsx(cs,{children:a.map(_=>e.jsx(Ze,{value:_.id,children:_.name},_.id))})]})]}),e.jsxs(Fr,{defaultValue:"agents",className:"space-y-4",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-4 md:grid-cols-8",children:[e.jsx(Zt,{value:"agents",children:"Agents"}),e.jsx(Zt,{value:"teams",children:"Teams"}),e.jsx(Zt,{value:"invite",children:"Invite Links"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"leaderboard",children:"Leaderboard"}),e.jsx(Zt,{value:"activity",children:"Activity"}),e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"shares",children:"Shares"})]}),e.jsx(is,{value:"agents",className:"space-y-4",children:e.jsx(dqs,{brokerageId:f})}),e.jsx(is,{value:"teams",className:"space-y-4",children:e.jsx(bqs,{brokerageId:f})}),e.jsx(is,{value:"invite",className:"space-y-4",children:e.jsx(xqs,{brokerageId:f})}),e.jsx(is,{value:"referrals",className:"space-y-4",children:e.jsx(vqs,{})}),e.jsx(is,{value:"leaderboard",className:"space-y-4",children:e.jsx(yxt,{brokerageId:f,title:`${d} Event Leaderboard`,showUserStats:!1})}),e.jsx(is,{value:"activity",className:"space-y-4",children:e.jsx(pqs,{brokerageId:f})}),e.jsx(is,{value:"analytics",className:"space-y-4",children:e.jsx(fqs,{brokerageId:f})}),e.jsx(is,{value:"shares",className:"space-y-4",children:e.jsx(cyt,{brokerageOnly:!0,brokerageId:f})})]})]})}):e.jsx(Cs,{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(Ua,{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 wqs({brokerageId:s,canManage:t}){const{user:n}=vs(),[r,a]=N.useState([]),[i,l]=N.useState(!0),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,y]=N.useState(!1),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState(!1),E=async()=>{try{const{data:z,error:H}=await q.from("brokerage_announcements").select("*").eq("brokerage_id",s).order("is_pinned",{ascending:!1}).order("pinned_at",{ascending:!1,nullsFirst:!1}).order("created_at",{ascending:!1});if(H)throw H;const Z=z;if(Z&&Z.length>0){const Y=[...new Set(Z.map(oe=>oe.created_by))],{data:W}=await q.from("profiles").select("id, name, avatar_url").in("id",Y),ee=new Map((W==null?void 0:W.map(oe=>[oe.id,oe]))||[]),se=Z.map(oe=>({...oe,author:ee.get(oe.created_by)||{name:"Unknown",avatar_url:null}}));a(se)}else a([])}catch(z){console.error("Error fetching announcements:",z)}finally{l(!1)}};N.useEffect(()=>{E()},[s]);const O=()=>{v(""),w(""),A(!1),u(null)},D=z=>{z?(u(z),v(z.title),w(z.content),A(z.is_pinned)):O(),c(!0)},I=async()=>{if(!_.trim()||!j.trim()){ae.error("Please fill in all fields");return}y(!0);try{if(d){const{error:z}=await q.from("brokerage_announcements").update({title:_.trim(),content:j.trim(),is_pinned:S,pinned_at:S?new Date().toISOString():null}).eq("id",d.id);if(z)throw z;ae.success("Announcement updated")}else{const{error:z}=await q.from("brokerage_announcements").insert({brokerage_id:s,created_by:n==null?void 0:n.id,title:_.trim(),content:j.trim(),is_pinned:S,pinned_at:S?new Date().toISOString():null});if(z)throw z;ae.success("Announcement created")}c(!1),O(),E()}catch(z){console.error("Error saving announcement:",z),ae.error("Failed to save announcement")}finally{y(!1)}},F=async()=>{if(h)try{const{error:z}=await q.from("brokerage_announcements").delete().eq("id",h);if(z)throw z;ae.success("Announcement deleted"),E()}catch(z){console.error("Error deleting announcement:",z),ae.error("Failed to delete announcement")}finally{p(null)}};return i?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(zd,{className:"h-5 w-5"}),"Announcements"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:e.jsx("div",{className:"h-20 bg-muted rounded"})})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(zd,{className:"h-5 w-5 text-primary"}),"Announcements"]}),t&&e.jsxs(B,{size:"sm",onClick:()=>D(),className:"gap-1",children:[e.jsx(Is,{className:"h-4 w-4"}),"New"]})]}),e.jsx(Ee,{children:r.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No announcements yet"}):e.jsx("div",{className:"space-y-4",children:r.map(z=>{var H,Z,Y,W;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(XS,{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(Jr,{className:"h-5 w-5",children:[e.jsx(ti,{src:((H=z.author)==null?void 0:H.avatar_url)||void 0}),e.jsx(ea,{className:"text-[10px]",children:((Y=(Z=z.author)==null?void 0:Z.name)==null?void 0:Y.charAt(0))||"?"})]}),e.jsx("span",{children:(W=z.author)==null?void 0:W.name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:Ss(new Date(z.created_at),"MMM d, yyyy")})]})]}),t&&e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>D(z),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>p(z.id),children:e.jsx(_n,{className:"h-4 w-4"})})]})]})},z.id)})})})]}),e.jsx(_s,{open:o,onOpenChange:c,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:d?"Edit Announcement":"New Announcement"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",value:_,onChange:z=>v(z.target.value),placeholder:"Announcement title..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"content",children:"Content"}),e.jsx(Ms,{id:"content",value:j,onChange:z=>w(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(jn,{id:"pinned",checked:S,onCheckedChange:A}),e.jsxs(ne,{htmlFor:"pinned",className:"flex items-center gap-1 cursor-pointer",children:[e.jsx(XS,{className:"h-4 w-4"}),"Pin to top"]})]})}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:I,disabled:f,children:f?"Saving...":d?"Update":"Create"})]})]})]})}),e.jsx(Oo,{open:!!h,onOpenChange:()=>p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Announcement"}),e.jsx(Mo,{children:"Are you sure you want to delete this announcement? This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:F,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function jqs({brokerageId:s,canManage:t=!1}){const{startImpersonation:n,isLoading:r}=A0e(),{user:a}=vs(),[i,l]=N.useState([]),[o,c]=N.useState(!0),[d,u]=N.useState(""),[h,p]=N.useState(new Set);N.useEffect(()=>{(async()=>{try{const{data:_,error:v}=await q.from("profiles").select("id, name, email, phone, avatar_url, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("brokerage_id",s).order("name");if(v)throw v;if(l(_||[]),_&&_.length>0){const j=_.map(S=>S.id),{data:w}=await q.from("agent_assistant_assignments").select("agent_id").in("agent_id",j);w&&p(new Set(w.map(S=>S.agent_id)))}}catch(_){console.error("Error fetching agents:",_)}finally{c(!1)}})()},[s]);const f=i.filter(y=>{var _,v;return y.name.toLowerCase().includes(d.toLowerCase())||y.email.toLowerCase().includes(d.toLowerCase())||((_=y.title)==null?void 0:_.toLowerCase().includes(d.toLowerCase()))||((v=y.areas_served)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))});return o?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"Agent Roster"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:[1,2,3,4].map(y=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-48 bg-muted rounded-lg"})},y))})})]}):e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4 space-y-0",children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5 text-primary"}),"Agent Roster",e.jsxs("span",{className:"text-sm font-normal text-muted-foreground",children:["(",i.length,")"]})]}),e.jsxs("div",{className:"relative w-full sm:w-64",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:d,onChange:y=>u(y.target.value),className:"pl-9"})]})]}),e.jsx(Ee,{children:f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d?"No agents match your search":"No agents in this brokerage yet"}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-4",children:f.map(y=>e.jsx(Nqs,{agent:y,hasAssistant:h.has(y.id),canImpersonate:t&&y.id!==(a==null?void 0:a.id),onImpersonate:()=>n(y.id,"/my-brokerage"),impersonationLoading:r},y.id))})})]})}function Nqs({agent:s,hasAssistant:t,canImpersonate:n,onImpersonate:r,impersonationLoading:a}){const i=s.name.split(" ").map(l=>l[0]).join("").toUpperCase().slice(0,2);return e.jsxs("div",{className:"group relative bg-card border rounded-xl p-4 hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"flex flex-col items-center text-center mb-3",children:[e.jsxs(Jr,{className:"h-20 w-20 mb-3 ring-2 ring-background shadow-md",children:[e.jsx(ti,{src:s.avatar_url||void 0,alt:s.name}),e.jsx(ea,{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(Ue,{variant:"outline",className:"text-[10px] mt-1",children:"Has Assistant"})]}),s.bio&&e.jsx("p",{className:"text-xs text-muted-foreground text-center line-clamp-2 mb-3",children:s.bio}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[s.areas_served&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(ka,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.areas_served})]}),s.years_experience&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[s.years_experience," ",s.years_experience===1?"year":"years"," experience"]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[n&&e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8 text-blue-600 hover:text-blue-700 hover:bg-blue-50",onClick:r,disabled:a,children:e.jsx(CA,{className:"h-4 w-4"})})}),e.jsxs(Nc,{children:["Login as ",s.name]})]}),s.phone&&e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`tel:${s.phone}`,title:`Call ${s.name}`,children:e.jsx(Cr,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:`mailto:${s.email}`,title:`Email ${s.name}`,children:e.jsx(Gs,{className:"h-4 w-4"})})}),s.linkedin_url&&e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.linkedin_url,target:"_blank",rel:"noopener noreferrer",title:"LinkedIn",children:e.jsx(xf,{className:"h-4 w-4"})})}),s.instagram_url&&e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",asChild:!0,children:e.jsx("a",{href:s.instagram_url,target:"_blank",rel:"noopener noreferrer",title:"Instagram",children:e.jsx(ou,{className:"h-4 w-4"})})})]})]})}function kqs({brokerageId:s}){const[t,n]=N.useState([]),[r,a]=N.useState(!0);if(N.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){n([]),a(!1);return}const u=c.map(_=>_.id),{data:h,error:p}=await q.from("agent_attendance_stats").select("user_id, total_points").in("user_id",u).order("total_points",{ascending:!1});if(p)throw p;const f=new Map(c.map(_=>[_.id,_])),y=(h||[]).filter(_=>_.total_points>0).map(_=>{const v=f.get(_.user_id);return{user_id:_.user_id,total_points:_.total_points,name:(v==null?void 0:v.name)||"Unknown",avatar_url:(v==null?void 0:v.avatar_url)||null}});n(y)}catch(c){console.error("Error fetching leaderboard:",c)}finally{a(!1)}})()},[s]),r)return e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5"}),"Team Leaderboard"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"animate-pulse space-y-3",children:[1,2,3].map(o=>e.jsx("div",{className:"h-12 bg-muted rounded"},o))})})]});const i=o=>o===1?"text-yellow-500":o===2?"text-gray-400":o===3?"text-amber-600":"text-muted-foreground",l=o=>o<=3?e.jsx(K2,{className:Mt("h-5 w-5",i(o))}):e.jsx("span",{className:"w-5 text-center text-sm text-muted-foreground",children:o});return e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5 text-primary"}),"Team Leaderboard"]})}),e.jsx(Ee,{children:t.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No points earned yet. Attend events to earn points!"}):e.jsx("div",{className:"space-y-2",children:t.slice(0,10).map((o,c)=>{const d=o.name.split(" ").map(h=>h[0]).join("").toUpperCase().slice(0,2),u=c+1;return e.jsxs("div",{className:Mt("flex items-center gap-3 p-2 rounded-lg",u<=3&&"bg-muted/50"),children:[e.jsx("div",{className:"w-6 flex justify-center",children:l(u)}),e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:o.avatar_url||void 0}),e.jsx(ea,{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 Sqs({brokerageId:s}){const t=Ln(),[n,r]=N.useState([]),[a,i]=N.useState(!0);N.useEffect(()=>{(async()=>{try{const{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").eq("brokerage_id",s);if(d)throw d;if(!c||c.length===0){r([]),i(!1);return}const u=c.map(_=>_.id),h=new Map(c.map(_=>[_.id,_])),{data:p,error:f}=await q.from("listings").select(` id, slug, property_address, city, price, property_type, agent_id, listing_photos(photo_url) `).in("agent_id",u).eq("status","active").order("created_at",{ascending:!1}).limit(6);if(f)throw f;const y=(p||[]).map(_=>({id:_.id,slug:_.slug,property_address:_.property_address,city:_.city,price:_.price,property_type:_.property_type,agent_id:_.agent_id,agent:h.get(_.agent_id)||null,photos:_.listing_photos||[]}));r(y)}catch(c){console.error("Error fetching listings:",c)}finally{i(!1)}})()},[s]);const l=o=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(o);return a?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-5 w-5"}),"Brokerage Listings"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[1,2].map(o=>e.jsx("div",{className:"animate-pulse",children:e.jsx("div",{className:"h-32 bg-muted rounded-lg"})},o))})})]}):e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-4",children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-5 w-5 text-primary"}),"Brokerage Listings"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>t("/mission-control/listings"),className:"gap-1",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Listing"]})]}),e.jsxs(Ee,{children:[n.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Or,{className:"h-10 w-10 text-muted-foreground mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No active listings from your brokerage yet"}),e.jsxs(B,{size:"sm",onClick:()=>t("/mission-control/listings/new"),className:"gap-1",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Your First Listing"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:n.map(o=>e.jsxs("div",{onClick:()=>window.open(`https://listings.relevelup.com/${o.slug||o.id}`,"_blank"),className:"group cursor-pointer border rounded-lg overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"relative h-24 bg-muted",children:[o.photos&&o.photos.length>0?e.jsx("img",{src:o.photos[0].photo_url,alt:o.property_address||"Listing",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Or,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("div",{className:"absolute top-2 left-2",children:e.jsx("span",{className:"text-[10px] font-medium bg-primary text-primary-foreground px-1.5 py-0.5 rounded uppercase",children:o.property_type.replace("_"," ")})})]}),e.jsxs("div",{className:"p-2.5",children:[e.jsx("p",{className:"font-semibold text-sm text-primary",children:l(o.price)}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:o.property_address||"Address not available"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:o.city}),o.agent&&e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-1.5 truncate",children:["Listed by ",o.agent.name]})]})]},o.id))}),n.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>t("/mission-control/listings"),children:["View All Listings",e.jsx(tr,{className:"h-3 w-3 ml-1"})]})]})]})}function Cqs(){const{user:s,isAdmin:t,isBrokerageManager:n}=vs(),r=Ln(),[a,i]=N.useState(!0),[l,o]=N.useState(null),[c,d]=N.useState(""),[u,h]=N.useState(0),[p,f]=N.useState(!1),[y,_]=N.useState(!1);return N.useEffect(()=>{(async()=>{if(s)try{const{data:j}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(j!=null&&j.brokerage_id)){i(!1);return}o(j.brokerage_id);const{data:w}=await q.from("brokerages").select("name").eq("id",j.brokerage_id).maybeSingle();w&&d(w.name);const{count:S}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("brokerage_id",j.brokerage_id);if(h(S||0),t)f(!0),_(!0);else if(n){const{data:A}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",j.brokerage_id).maybeSingle();f(!!A),_(!!A)}}catch(j){console.error("Error fetching brokerage info:",j)}finally{i(!1)}})()},[s,t,n]),a?e.jsx(Cs,{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(Cs,{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(An,{className:"h-5 w-5 text-primary"}),e.jsxs("span",{className:"font-medium",children:[u," ",u===1?"Agent":"Agents"]})]}),y&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>r("/brokerage-content"),children:[e.jsx(rm,{className:"h-4 w-4 mr-2"}),"Brokerage Content"]}),e.jsxs(B,{onClick:()=>r(`/mission-control/listings/new?brokerage=${l}`),children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})]}),e.jsx(wqs,{brokerageId:l,canManage:p}),e.jsx(jqs,{brokerageId:l,canManage:p}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-8",children:[e.jsx(kqs,{brokerageId:l}),e.jsx(Sqs,{brokerageId:l})]})]})}):e.jsx(Cs,{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(Ua,{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 Tqs(s){if(!s)return null;try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}function Eqs(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 GYe={video:{icon:El,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:br,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:yr,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:pl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function Aqs({item:s,canManage:t}){const[n,r]=N.useState(!1),[a,i]=N.useState(null),l=Ons(),o=Ln(),c=GYe[s.content_type]||GYe.link,d=c.icon,u=N.useMemo(()=>s.thumbnail_url?s.thumbnail_url:s.content_type==="graphic"&&s.file_url?s.file_url:s.content_type==="video"?Tqs(s.url):null,[s]);N.useEffect(()=>{u||!s.url||s.content_type!=="video"||!Eqs(s.url)||fetch(`https://www.youtube.com/oembed?url=${encodeURIComponent(s.url)}&format=json`).then(y=>y.ok?y.json():null).then(y=>{y!=null&&y.thumbnail_url&&i(y.thumbnail_url)}).catch(()=>{})},[s.url,s.content_type,u]);const h=u||a,p=()=>{o(`/brokerage-content/${s.id}`)},f=async()=>{try{await l.mutateAsync(s.id),ae.success("Content deleted")}catch{ae.error("Failed to delete")}r(!1)};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"group overflow-hidden transition-all duration-200 hover:shadow-lg hover:border-primary/30 cursor-pointer",onClick:p,children:[h?e.jsx("div",{className:"aspect-video bg-muted/50 overflow-hidden",children:e.jsx("img",{src:h,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300",referrerPolicy:"no-referrer"})}):e.jsx("div",{className:"aspect-video bg-muted/30 flex items-center justify-center",children:e.jsx(d,{className:"h-12 w-12 text-muted-foreground/30"})}),e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsxs(Ue,{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(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:[s.category.icon," ",s.category.name]})]}),e.jsx("h3",{className:"font-semibold text-sm text-foreground group-hover:text-primary transition-colors truncate",children:s.title}),s.description&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:s.description}),s.content_type==="event"&&s.event_date&&e.jsxs("p",{className:"text-xs text-primary mt-2 font-medium",children:["📅 ",Ss(new Date(s.event_date),"MMM d, yyyy · h:mm a")]}),e.jsxs("p",{className:"text-[10px] text-muted-foreground mt-2",children:["Added ",Ss(new Date(s.created_at),"MMM d, yyyy")]})]}),t&&e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,onClick:y=>y.stopPropagation(),children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",children:e.jsx(Ag,{className:"h-4 w-4"})})}),e.jsx(gc,{align:"end",children:e.jsxs(Kr,{onClick:y=>{y.stopPropagation(),r(!0)},className:"text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete"]})})]})]})})]}),e.jsx(Oo,{open:n,onOpenChange:r,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Content"}),e.jsxs(Mo,{children:['Are you sure you want to delete "',s.title,'"? This cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:f,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Mqs(s){try{const t=new URL(s),n=t.hostname.replace("www.","");let r=null;if(n==="youtube.com"||n==="m.youtube.com"?r=t.searchParams.get("v"):n==="youtu.be"&&(r=t.pathname.slice(1)),r)return`https://img.youtube.com/vi/${r}/hqdefault.jpg`}catch{}return null}const WYe=[{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 Iqs({brokerageId:s,categories:t}){var ve;const{user:n}=vs(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(""),[d,u]=N.useState("📁"),[h,p]=N.useState(!1);N.useRef(null);const[f,y]=N.useState("video"),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState(""),[E,O]=N.useState(""),[D,I]=N.useState(""),[F,z]=N.useState(""),[H,Z]=N.useState(""),Y=Rns(),W=Fns(s),ee=zns(),se=Bns(s),oe=()=>{y("video"),v(""),w(""),A(""),O(""),I(""),z(""),Z("")},he=async(ge,Te)=>{var Ce;const Ie=(Ce=ge.target.files)==null?void 0:Ce[0];if(Ie){p(!0);try{const Me=Ie.name.split(".").pop(),Pe=`${s}/${Date.now()}-${Math.random().toString(36).slice(2)}.${Me}`,{error:Re}=await q.storage.from("brokerage-content").upload(Pe,Ie);if(Re)throw Re;const{data:{publicUrl:Ae}}=q.storage.from("brokerage-content").getPublicUrl(Pe);Te==="file"?(O(Ae),f==="graphic"&&!D&&I(Ae)):I(Ae),ae.success("File uploaded")}catch(Me){ae.error(Me.message||"Upload failed")}finally{p(!1)}}},ce=async()=>{if(!_.trim()){ae.error("Title is required");return}if(n)try{await Y.mutateAsync({brokerage_id:s,category_id:H||null,content_type:f,title:_.trim(),description:j.trim()||null,url:S.trim()||null,file_url:E.trim()||null,thumbnail_url:D.trim()||null,event_date:F?new Date(F).toISOString():null,created_by:n.id}),ae.success("Content added!"),oe(),a(!1)}catch(ge){ae.error(ge.message||"Failed to add content")}},me=async()=>{if(o.trim())try{await W.mutateAsync({name:o.trim(),icon:d,sort_order:t.length}),c(""),u("📁"),ae.success("Category created")}catch(ge){ae.error(ge.message||"Failed to create category")}},le=async()=>{try{await se.mutateAsync(),ae.success("Default categories created")}catch{ae.error("Failed to create defaults")}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-3",children:[e.jsxs(_s,{open:r,onOpenChange:a,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Content"]})}),e.jsxs(bs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{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(ne,{children:"Content Type"}),e.jsxs(us,{value:f,onValueChange:y,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:WYe.map(ge=>e.jsx(Ze,{value:ge.value,children:ge.label},ge.value))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(ve=WYe.find(ge=>ge.value===f))==null?void 0:ve.hint})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Category"}),e.jsxs(us,{value:H,onValueChange:Z,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select category (optional)"})}),e.jsx(cs,{children:t.map(ge=>e.jsxs(Ze,{value:ge.id,children:[ge.icon," ",ge.name]},ge.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Title *"}),e.jsx(ye,{value:_,onChange:ge=>v(ge.target.value),placeholder:"Content title"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{value:j,onChange:ge=>w(ge.target.value),placeholder:"Brief description...",rows:2})]}),["video","link","graphic","event"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:f==="video"?"Video URL":f==="graphic"?"Canva / Image URL":f==="event"?"Event Link (Zoom, etc.)":"URL"}),e.jsx(ye,{value:S,onChange:ge=>{const Te=ge.target.value;if(A(Te),f==="video"&&!D){const Ie=Mqs(Te);Ie&&I(Ie)}},placeholder:"https://..."})]}),["pdf","graphic"].includes(f)&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:f==="pdf"?"Upload PDF":"Upload Image"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"file",accept:f==="pdf"?".pdf,.doc,.docx":"image/*",onChange:ge=>he(ge,"file"),disabled:h}),h&&e.jsx(rs,{className:"h-4 w-4 animate-spin"})]}),E&&e.jsx("p",{className:"text-xs text-green-600",children:"✓ File uploaded"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Thumbnail Image (optional)"}),e.jsx(ye,{type:"file",accept:"image/*",onChange:ge=>he(ge,"thumbnail"),disabled:h}),D&&e.jsxs("div",{className:"relative w-20 h-20 rounded overflow-hidden",children:[e.jsx("img",{src:D,className:"w-full h-full object-cover",alt:"thumb"}),e.jsx("button",{onClick:()=>I(""),className:"absolute top-0 right-0 bg-background/80 rounded-bl p-0.5",children:e.jsx($n,{className:"h-3 w-3"})})]})]}),f==="event"&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Event Date & Time"}),e.jsx(ye,{type:"datetime-local",value:F,onChange:ge=>z(ge.target.value)})]}),e.jsxs(B,{onClick:ce,disabled:Y.isPending||!_.trim(),className:"w-full",children:[Y.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin mr-2"}):e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Content"]})]})]})]}),e.jsxs(_s,{open:i,onOpenChange:l,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",children:[e.jsx(Ko,{className:"h-4 w-4 mr-2"}),"Categories"]})}),e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Manage Categories"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[t.length===0&&e.jsxs("div",{className:"text-center py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No categories yet"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:le,disabled:se.isPending,children:[se.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin mr-2"}):null,"Create Default Categories"]})]}),t.map(ge=>e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-lg border",children:[e.jsxs("span",{className:"text-sm",children:[ge.icon," ",ge.name]}),!ge.is_default&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:async()=>{await ee.mutateAsync(ge.id),ae.success("Category deleted")},children:e.jsx($n,{className:"h-4 w-4"})})]},ge.id)),e.jsxs("div",{className:"flex gap-2 pt-2 border-t",children:[e.jsx(ye,{value:d,onChange:ge=>u(ge.target.value),className:"w-14 text-center",maxLength:2}),e.jsx(ye,{value:o,onChange:ge=>c(ge.target.value),placeholder:"New category name",className:"flex-1",onKeyDown:ge=>ge.key==="Enter"&&me()}),e.jsx(B,{size:"sm",onClick:me,disabled:!o.trim(),children:"Add"})]})]})]})]})]})}function Pqs(){const{user:s,isAdmin:t,isBrokerageManager:n}=vs(),[r,a]=N.useState(!0),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,y]=N.useState("");N.useEffect(()=>{(async()=>{if(s)try{const{data:A}=await q.from("profiles").select("brokerage_id").eq("id",s.id).maybeSingle();if(!(A!=null&&A.brokerage_id)){a(!1);return}l(A.brokerage_id);const{data:E}=await q.from("brokerages").select("name").eq("id",A.brokerage_id).maybeSingle();if(E&&c(E.name),t)u(!0);else if(n){const{data:O}=await q.from("brokerage_manager_assignments").select("id").eq("user_id",s.id).eq("brokerage_id",A.brokerage_id).maybeSingle();u(!!O)}}catch(A){console.error("Error fetching brokerage info:",A)}finally{a(!1)}})()},[s,t,n]);const{data:_=[]}=Pns(i),{data:v=[],isLoading:j}=Lns(i,h),w=N.useMemo(()=>{if(!f.trim())return v;const S=f.toLowerCase();return v.filter(A=>{var E;return A.title.toLowerCase().includes(S)||((E=A.description)==null?void 0:E.toLowerCase().includes(S))||A.content_type.toLowerCase().includes(S)})},[v,f]);return r?e.jsx(Cs,{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(Cs,{title:`${o} Content`,description:"Brokerage Content Hub",children:e.jsxs("div",{className:"space-y-6",children:[d&&i&&e.jsx(Iqs,{brokerageId:i,categories:_}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search content...",value:f,onChange:S=>y(S.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{variant:h===null?"default":"outline",size:"sm",onClick:()=>p(null),children:"All"}),_.map(S=>e.jsxs(B,{variant:h===S.id?"default":"outline",size:"sm",onClick:()=>p(S.id),children:[e.jsx("span",{className:"mr-1",children:S.icon}),S.name]},S.id))]})]}),j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):w.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(pf,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:f.trim()?"No matching content found":"No content yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:f.trim()?"Try a different search term or category.":d?"Add your first piece of content above.":"Your brokerage hasn't added content yet."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:w.map(S=>e.jsx(Aqs,{item:S,canManage:d},S.id))})]})}):e.jsx(Cs,{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(Ua,{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 KYe={video:{icon:El,label:"Video",color:"bg-red-500/10 text-red-600 dark:text-red-400"},pdf:{icon:br,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:yr,label:"Event",color:"bg-purple-500/10 text-purple-600 dark:text-purple-400"},graphic:{icon:pl,label:"Graphic",color:"bg-amber-500/10 text-amber-600 dark:text-amber-400"}};function Lqs(s){try{const t=new URL(s),n=t.hostname.replace("www.","");if(t.pathname==="/playlist"){const r=t.searchParams.get("list");if(r)return`https://www.youtube.com/embed/videoseries?list=${r}`}if(n==="youtube.com"||n==="m.youtube.com"){const r=t.searchParams.get("v");if(r){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${r}`;return a&&(i+=`?list=${a}`),i}}if(n==="youtu.be"){const r=t.pathname.slice(1);if(r){const a=t.searchParams.get("list");let i=`https://www.youtube.com/embed/${r}`;return a&&(i+=`?list=${a}`),i}}if(n==="youtube.com"&&t.pathname.startsWith("/embed/"))return s}catch{}return null}function Dqs(s){try{const t=new URL(s).hostname.replace("www.","");return["youtube.com","youtu.be","m.youtube.com"].includes(t)}catch{return!1}}function Rqs(s){try{return new URL(s).hostname.includes("vimeo.com")}catch{return!1}}function Oqs(s){try{const t=s.match(/vimeo\.com\/(\d+)/);if(t)return`https://player.vimeo.com/video/${t[1]}`}catch{}return null}function Fqs(){const{contentId:s}=bi(),{data:t,isLoading:n}=dt({queryKey:["brokerage-content-detail",s],queryFn:async()=>{const{data:d,error:u}=await q.from("brokerage_content").select(` *, category:brokerage_content_categories(*) `).eq("id",s).single();if(u)throw u;return d},enabled:!!s});if(n)return e.jsx(Cs,{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(Cs,{title:"Brokerage Content",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Ua,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Content not found"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"This content may have been removed."}),e.jsx(B,{asChild:!0,className:"mt-4",children:e.jsx(In,{to:"/brokerage-content",children:"Back to Content"})})]})});const r=KYe[t.content_type]||KYe.link,a=r.icon,i=t.url||t.file_url,l=i&&Dqs(i)?Lqs(i):null,o=i&&Rqs(i)?Oqs(i):null,c=l||o;return e.jsx(Cs,{title:t.title,children:e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,className:"gap-2",children:e.jsxs(In,{to:"/brokerage-content",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back to Content"]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ue,{variant:"secondary",className:`text-xs px-2 py-0.5 ${r.color}`,children:[e.jsx(a,{className:"h-3 w-3 mr-1"}),r.label]}),t.category&&e.jsxs(Ue,{variant:"outline",className:"text-xs px-2 py-0.5",children:[t.category.icon," ",t.category.name]}),e.jsxs("span",{className:"text-xs text-muted-foreground ml-auto",children:["Added ",Ss(new Date(t.created_at),"MMMM d, yyyy")]})]}),e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:t.title}),c&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("div",{className:"relative w-full bg-black",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:c,className:"absolute top-0 left-0 w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,title:t.title})})}),t.content_type==="graphic"&&t.file_url&&!c&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("img",{src:t.file_url,alt:t.title,className:"w-full max-h-[600px] object-contain bg-muted"})}),!c&&t.content_type!=="graphic"&&t.thumbnail_url&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("img",{src:t.thumbnail_url,alt:t.title,className:"w-full max-h-[400px] object-cover"})}),t.description&&e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:t.description})})}),t.content_type==="event"&&t.event_date&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(yr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium text-foreground",children:"Event Date"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:Ss(new Date(t.event_date),"EEEE, MMMM d, yyyy · h:mm a")})]})]})}),e.jsxs("div",{className:"flex flex-wrap gap-3",children:[t.file_url&&e.jsx(B,{asChild:!0,size:"lg",children:e.jsxs("a",{href:t.file_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),t.content_type==="pdf"?"Download Document":"Download File"]})}),t.url&&e.jsx(B,{variant:t.file_url?"outline":"default",asChild:!0,size:"lg",children:e.jsxs("a",{href:t.url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),c?"Open on YouTube":t.content_type==="event"?"Join Event":t.content_type==="graphic"?"Open in Canva":"Open Link"]})})]})]})})}const jge={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 zqs(s="open"){const{user:t}=vs();return dt({queryKey:["brokerage-help-requests",s,t==null?void 0:t.id],queryFn:async()=>{if(!t)return[];let n=q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, avatar_url)").order("created_at",{ascending:!1});if(s==="open")n=n.eq("status","open");else if(s==="mine")n=n.eq("requester_user_id",t.id);else if(s==="filled")n=n.in("status",["filled","completed"]);else if(s==="my_claims"){const{data:i}=await q.from("brokerage_help_claims").select("request_id").eq("claimant_user_id",t.id),l=(i||[]).map(o=>o.request_id);if(l.length===0)return[];n=n.in("id",l)}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function Bqs(s){return dt({queryKey:["brokerage-help-request",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("brokerage_help_requests").select("*, requester:profiles!brokerage_help_requests_requester_user_id_fkey(name, email, phone, avatar_url)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function $qs(s){return dt({queryKey:["brokerage-help-claims",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("brokerage_help_claims").select("*, claimant:profiles!brokerage_help_claims_claimant_user_id_fkey(name, email, phone, avatar_url)").eq("request_id",s).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Uqs(){const s=Kt(),{user:t,brokerageId:n}=vs();return yt({mutationFn:async r=>{if(!t||!n)throw new Error("You must be in a brokerage to post.");const{data:a,error:i}=await q.from("brokerage_help_requests").insert({...r,brokerage_id:n,requester_user_id:t.id}).select().single();if(i)throw i;try{await q.functions.invoke("brokerage-help-notify",{body:{request_id:a.id}})}catch(l){console.warn("notify failed (non-blocking):",l)}return a},onSuccess:()=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function qqs(){const s=Kt(),{user:t}=vs();return yt({mutationFn:async({request_id:n,note:r})=>{if(!t)throw new Error("Not signed in");const{data:a,error:i}=await q.from("brokerage_help_claims").insert({request_id:n,claimant_user_id:t.id,note:r}).select().single();if(i)throw i;return a},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",r.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function Vqs(){const s=Kt();return yt({mutationFn:async({claim_id:t,request_id:n,claimant_user_id:r})=>{const{error:a}=await q.from("brokerage_help_claims").update({status:"accepted",responded_at:new Date().toISOString()}).eq("id",t);if(a)throw a;const{error:i}=await q.from("brokerage_help_requests").update({status:"filled",assigned_user_id:r}).eq("id",n);if(i)throw i;try{await q.functions.invoke("brokerage-help-claim-decision",{body:{claim_id:t}})}catch(l){console.warn("claim decision notify failed:",l)}},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-request",n.request_id]}),s.invalidateQueries({queryKey:["brokerage-help-requests"]})}})}function Hqs(){const s=Kt();return yt({mutationFn:async({claim_id:t})=>{const{error:n}=await q.from("brokerage_help_claims").update({status:"declined",responded_at:new Date().toISOString()}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-claims",n.request_id]})}})}function Gqs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"cancelled"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function Wqs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("brokerage_help_requests").update({status:"completed"}).eq("id",t);if(n)throw n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["brokerage-help-requests"]}),s.invalidateQueries({queryKey:["brokerage-help-request",n]})}})}function Kqs(){const{user:s,brokerageId:t}=vs(),n=Kt(),r=dt({queryKey:["brokerage-help-prefs",s==null?void 0:s.id,t],queryFn:async()=>{if(!s||!t)return null;const{data:i,error:l}=await q.from("brokerage_help_notification_prefs").select("*").eq("user_id",s.id).eq("brokerage_id",t).maybeSingle();if(l)throw l;return i},enabled:!!s&&!!t}),a=yt({mutationFn:async i=>{if(!s||!t)throw new Error("No user/brokerage");const{error:l}=await q.from("brokerage_help_notification_prefs").upsert({user_id:s.id,brokerage_id:t,email_enabled:i},{onConflict:"user_id,brokerage_id"});if(l)throw l},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-help-prefs"]})}});return{...r,setEmailEnabled:a.mutate,isSaving:a.isPending}}function Yqs(s,t){if(!s)return null;const n=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),r=n(s,{weekday:"short",month:"short",day:"numeric",hour:"numeric",minute:"2-digit"});if(t){const a=n(t,{hour:"numeric",minute:"2-digit"});return`${r} – ${a} ET`}return`${r} ET`}function Zqs(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 Qqs({req:s,onClick:t}){var i;const n=jge[s.request_type],r=Yqs(s.event_start_at,s.event_end_at),a=[s.address,s.city,s.state].filter(Boolean).join(", ");return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition group",onClick:t,children:e.jsxs(Ee,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Ue,{variant:"secondary",className:"text-xs",children:[n.emoji," ",n.label]}),s.status!=="open"&&e.jsx(Ue,{variant:"outline",className:"text-xs capitalize",children:s.status})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground group-hover:translate-x-0.5 transition"})]}),e.jsx("h3",{className:"font-semibold text-base mb-2 line-clamp-2",children:s.title}),e.jsxs("div",{className:"space-y-1.5 text-sm text-muted-foreground",children:[r&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:r})]}),a&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ka,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"line-clamp-1",children:a})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:Zqs(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 Xqs(){var c;const s=Ln(),{brokerageId:t}=vs(),[n,r]=N.useState("open"),{data:a=[],isLoading:i}=zqs(n),l=Kqs(),o=((c=l.data)==null?void 0:c.email_enabled)??!0;return t?e.jsx(Cs,{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(Fr,{value:n,onValueChange:d=>r(d),children:e.jsxs(Rr,{children:[e.jsx(Zt,{value:"open",children:"Open"}),e.jsx(Zt,{value:"mine",children:"My Posts"}),e.jsx(Zt,{value:"my_claims",children:"My Claims"}),e.jsx(Zt,{value:"filled",children:"Filled"})]})}),e.jsxs(B,{onClick:()=>s("/brokerage/help-board/new"),className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"})," Post Request"]})]}),e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ee,{className:"flex items-center justify-between py-3 px-5",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[o?e.jsx(nm,{className:"h-4 w-4 text-primary"}):e.jsx(cw,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx(ne,{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(jn,{id:"email-notif",checked:o,disabled:l.isLoading||l.isSaving,onCheckedChange:d=>l.setEmailEnabled(d)})]})}),i?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a.length===0?e.jsx(fe,{className:"bg-muted/30 border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(X1,{className:"h-12 w-12 text-muted-foreground/50 mb-3"}),e.jsx("p",{className:"font-medium",children:"Nothing here yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:n==="open"?"No open requests right now — be the first to post one!":"Check back later."})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:a.map(d=>e.jsx(Qqs,{req:d,onClick:()=>s(`/brokerage/help-board/${d.id}`)},d.id))})]})}):e.jsx(Cs,{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(X1,{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 Jqs(){const s=Ln(),{toast:t}=Fa(),n=Uqs(),[r,a]=N.useState("open_house"),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState(""),[E,O]=N.useState(""),[D,I]=N.useState(""),[F,z]=N.useState("goodwill"),[H,Z]=N.useState(""),[Y,W]=N.useState(""),ee=r==="open_house"||r==="showing_coverage",se=r!=="general",oe=(ce,me)=>!ce||!me?null:`${ce}T${me}:00`,he=async ce=>{if(ce.preventDefault(),!i.trim()){t({title:"Add a title",description:"Tell teammates what you need help with.",variant:"destructive"});return}try{const me=oe(d,h),le=oe(d,f);await n.mutateAsync({request_type:r,title:i.trim(),description:o.trim()||null,event_start_at:me,event_end_at:le,address:ee&&_.trim()||null,city:ee&&j.trim()||null,state:ee&&S.trim()||null,zip:ee&&E.trim()||null,mls_number:D.trim()||null,compensation_type:F,compensation_amount:H?Number(H):null,compensation_notes:Y.trim()||null}),t({title:"Posted!",description:"Your teammates have been notified."}),s("/brokerage/help-board")}catch(me){t({title:"Could not post",description:(me==null?void 0:me.message)??"Something went wrong.",variant:"destructive"})}};return e.jsx(Cs,{title:"Post a Help Request",description:"Ask a teammate to cover for you",children:e.jsxs("div",{className:"max-w-2xl mx-auto",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/brokerage/help-board"),className:"mb-4 gap-2",children:[e.jsx(qr,{className:"h-4 w-4"})," Back to board"]}),e.jsx("form",{onSubmit:he,children:e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"What do you need help with?"}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Object.keys(jge).map(ce=>{const me=jge[ce],le=ce===r;return e.jsxs("button",{type:"button",onClick:()=>a(ce),className:`text-left p-3 rounded-lg border-2 transition ${le?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"text-lg",children:me.emoji}),e.jsx("div",{className:"font-medium text-sm mt-1",children:me.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:me.description})]},ce)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:i,onChange:ce=>l(ce.target.value),placeholder:r==="open_house"?"Open house at 123 Oak St — Sat 1-3pm":"Quick description",maxLength:120,required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Details"}),e.jsx(Ms,{id:"description",value:o,onChange:ce=>c(ce.target.value),placeholder:"Any context — lockbox code instructions later, what to expect, etc.",rows:3,maxLength:1e3})]}),se&&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(ne,{htmlFor:"date",children:"Date"}),e.jsx(ye,{id:"date",type:"date",value:d,onChange:ce=>u(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"start",children:"Start"}),e.jsx(ye,{id:"start",type:"time",value:h,onChange:ce=>p(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"end",children:"End"}),e.jsx(ye,{id:"end",type:"time",value:f,onChange:ce=>y(ce.target.value)})]})]}),ee&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"address",children:"Address"}),e.jsx(ye,{id:"address",value:_,onChange:ce=>v(ce.target.value),placeholder:"123 Oak St"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(ne,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:j,onChange:ce=>w(ce.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:S,onChange:ce=>A(ce.target.value.toUpperCase()),maxLength:2})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"zip",children:"Zip"}),e.jsx(ye,{id:"zip",value:E,onChange:ce=>O(ce.target.value),maxLength:10})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"mls",children:"MLS # (optional)"}),e.jsx(ye,{id:"mls",value:D,onChange:ce=>I(ce.target.value)})]})]})]}),e.jsxs("div",{className:"space-y-3 pt-2 border-t",children:[e.jsx(ne,{children:"Compensation"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-2",children:[{val:"goodwill",label:"Goodwill",sub:"Pay it forward"},{val:"flat_fee",label:"Flat Fee",sub:"Dollar amount"},{val:"referral_percent",label:"Referral %",sub:"On the deal"}].map(ce=>{const me=F===ce.val;return e.jsxs("button",{type:"button",onClick:()=>z(ce.val),className:`text-left p-3 rounded-lg border-2 transition ${me?"border-primary bg-primary/5":"border-border hover:border-primary/40"}`,children:[e.jsx("div",{className:"font-medium text-sm",children:ce.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:ce.sub})]},ce.val)})}),F!=="goodwill"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"amount",children:F==="flat_fee"?"Amount ($)":"Percent (%)"}),e.jsx(ye,{id:"amount",type:"number",min:"0",step:F==="referral_percent"?"1":"5",value:H,onChange:ce=>Z(ce.target.value),placeholder:F==="flat_fee"?"100":"25"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"comp-notes",children:"Compensation notes"}),e.jsx(ye,{id:"comp-notes",value:Y,onChange:ce=>W(ce.target.value),placeholder:"e.g. Venmo same day, or split any leads",maxLength:200})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{type:"button",variant:"ghost",onClick:()=>s("/brokerage/help-board"),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:n.isPending,className:"gap-2",children:[n.isPending&&e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Post & Notify Brokerage"]})]})]})})})]})})}function eVs(s,t){if(!s)return null;const n=(a,i)=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",...i}).format(new Date(a)),r=n(s,{weekday:"long",month:"long",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"});return t?`${r} – ${n(t,{hour:"numeric",minute:"2-digit"})} ET`:`${r} ET`}function sNe(s){return s?s.split(" ").map(t=>t[0]).slice(0,2).join("").toUpperCase():"?"}function tVs(){var D,I,F,z,H,Z,Y,W;const{id:s}=bi(),t=Ln(),{user:n}=vs(),{toast:r}=Fa(),{data:a,isLoading:i}=Bqs(s),{data:l=[]}=$qs(s),o=qqs(),c=Vqs(),d=Hqs(),u=Gqs(),h=Wqs(),[p,f]=N.useState("");if(i)return e.jsx(Cs,{title:"Loading...",description:"",children:e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-primary"})})});if(!a)return e.jsxs(Cs,{title:"Not Found",description:"",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(qr,{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 y=jge[a.request_type],_=eVs(a.event_start_at,a.event_end_at),v=[a.address,a.city,a.state,a.zip].filter(Boolean).join(", "),j=(n==null?void 0:n.id)===a.requester_user_id,w=l.find(ee=>ee.claimant_user_id===(n==null?void 0:n.id)),S=l.find(ee=>ee.status==="accepted"),A=a.status==="open",E=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)",O=async()=>{if(!p.trim()){r({title:"Add a quick note",description:"Let the requester know you're available."});return}try{await o.mutateAsync({request_id:a.id,note:p.trim()}),r({title:"You're in!",description:"The requester will review and pick someone."}),f("")}catch(ee){r({title:"Could not submit",description:ee==null?void 0:ee.message,variant:"destructive"})}};return e.jsx(Cs,{title:a.title,description:`${y.emoji} ${y.label}`,children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/brokerage/help-board"),className:"gap-2",children:[e.jsx(qr,{className:"h-4 w-4"})," Back to board"]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(Ue,{variant:"secondary",children:[y.emoji," ",y.label]}),e.jsx(Ue,{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(Jr,{className:"h-7 w-7",children:[e.jsx(ti,{src:((D=a.requester)==null?void 0:D.avatar_url)||void 0}),e.jsx(ea,{children:sNe((I=a.requester)==null?void 0:I.name)})]}),e.jsx("span",{children:((F=a.requester)==null?void 0:F.name)||"Teammate"})]})]}),e.jsx("h1",{className:"text-2xl font-bold",children:a.title}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3 pt-2",children:[_&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(pr,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"When"}),e.jsx("div",{children:_})]})]}),v&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(ka,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Where"}),e.jsx("div",{children:v})]})]}),e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(Yl,{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:E})]})]}),a.mls_number&&e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[e.jsx(VS,{className:"h-4 w-4 text-primary mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"MLS"}),e.jsx("div",{children:a.mls_number})]})]})]}),a.description&&e.jsxs("div",{className:"pt-3 border-t",children:[e.jsx("h3",{className:"text-xs uppercase tracking-wide font-semibold text-muted-foreground mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm whitespace-pre-wrap",children:a.description})]}),a.compensation_notes&&e.jsxs("p",{className:"text-sm text-muted-foreground italic",children:["💰 ",a.compensation_notes]})]})}),!j&&A&&!w&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-3",children:[e.jsx("h3",{className:"font-semibold",children:"Offer to cover this"}),e.jsx(Ms,{placeholder:"Quick note — e.g. 'I'm 10 min away and free that day'",value:p,onChange:ee=>f(ee.target.value),rows:3,maxLength:400}),e.jsxs(B,{onClick:O,disabled:o.isPending,className:"gap-2",children:[o.isPending&&e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"I can cover this"]})]})}),!j&&w&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx(Lr,{className:"h-5 w-5 text-primary"}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium capitalize",children:["Your offer: ",w.status]}),e.jsxs("div",{className:"text-muted-foreground",children:[w.status==="pending"&&"Waiting for the requester to pick.",w.status==="accepted"&&"You're confirmed — see contact info below.",w.status==="declined"&&"They went with someone else this time."]})]})]})}),S&&(j||S.claimant_user_id===(n==null?void 0:n.id))&&e.jsx(fe,{className:"border-primary/30",children:e.jsxs(Ee,{className:"p-6",children:[e.jsx("h3",{className:"font-semibold mb-3",children:"Confirmed coverage"}),e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsxs(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:((z=S.claimant)==null?void 0:z.avatar_url)||void 0}),e.jsx(ea,{children:sNe((H=S.claimant)==null?void 0:H.name)})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:(Z=S.claimant)==null?void 0:Z.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Covering this request"})]})]}),e.jsxs("div",{className:"space-y-1.5 text-sm",children:[((Y=S.claimant)==null?void 0:Y.email)&&e.jsxs("a",{href:`mailto:${S.claimant.email}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Gs,{className:"h-4 w-4"})," ",S.claimant.email]}),((W=S.claimant)==null?void 0:W.phone)&&e.jsxs("a",{href:`tel:${S.claimant.phone}`,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(Cr,{className:"h-4 w-4"})," ",S.claimant.phone]})]})]})}),j&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-3",children:[e.jsxs("h3",{className:"font-semibold",children:["Interested agents (",l.length,")"]}),l.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No claims yet. Hang tight — your teammates were just notified."}),l.map(ee=>{var se,oe,he,ce,me;return e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg border",children:[e.jsxs(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:((se=ee.claimant)==null?void 0:se.avatar_url)||void 0}),e.jsx(ea,{children:sNe((oe=ee.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:((he=ee.claimant)==null?void 0:he.name)||"Teammate"}),e.jsx(Ue,{variant:"outline",className:"capitalize text-xs",children:ee.status})]}),ee.note&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1",children:['"',ee.note,'"']}),ee.status==="pending"&&A&&e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsxs(B,{size:"sm",onClick:()=>c.mutate({claim_id:ee.id,request_id:a.id,claimant_user_id:ee.claimant_user_id}),disabled:c.isPending,className:"gap-1",children:[e.jsx(Lr,{className:"h-3.5 w-3.5"})," Pick ",((me=(ce=ee.claimant)==null?void 0:ce.name)==null?void 0:me.split(" ")[0])||"them"]}),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>d.mutate({claim_id:ee.id,request_id:a.id}),disabled:d.isPending,className:"gap-1",children:[e.jsx($n,{className:"h-3.5 w-3.5"})," Pass"]})]})]})]},ee.id)}),j&&A&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u.mutate(a.id),disabled:u.isPending,children:"Cancel request"})}),j&&a.status==="filled"&&e.jsx("div",{className:"pt-3 border-t flex justify-end",children:e.jsx(B,{size:"sm",onClick:()=>h.mutate(a.id),disabled:h.isPending,children:"Mark complete"})})]})})]})})}function Jbt({onSelect:s,maxHeight:t="460px"}){const[n,r]=N.useState(""),[a,i]=N.useState("all"),{data:l=[],isLoading:o}=dt({queryKey:["newsletter-graphics-picker"],queryFn:async()=>{const{data:u,error:h}=await q.from("newsletter_graphics").select("*").eq("is_active",!0).order("is_featured",{ascending:!1}).order("sort_order",{ascending:!0}).order("created_at",{ascending:!1});if(h)throw h;return u||[]}}),c=N.useMemo(()=>{const u=new Set;return l.forEach(h=>u.add(h.category||"general")),["all",...Array.from(u).sort()]},[l]),d=N.useMemo(()=>{const u=n.trim().toLowerCase();return l.filter(h=>a!=="all"&&h.category!==a?!1:u?h.title.toLowerCase().includes(u)||(h.description||"").toLowerCase().includes(u)||(h.tags||[]).some(p=>p.toLowerCase().includes(u)):!0)},[l,n,a]);return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{value:n,onChange:u=>r(u.target.value),placeholder:"Search graphics...",className:"pl-8 h-9"})]}),c.length>1&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:c.map(u=>e.jsx("button",{onClick:()=>i(u),className:`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${a===u?"bg-primary text-primary-foreground":"bg-muted hover:bg-muted/70 text-muted-foreground"}`,children:u==="all"?"All":u},u))}),e.jsx(di,{style:{maxHeight:t},className:"rounded-md border",children:o?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):d.length===0?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Xo,{className:"h-8 w-8 text-muted-foreground/50 mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l.length===0?"No graphics available yet":"No graphics match your search"})]}):e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 p-2",children:d.map(u=>e.jsxs("button",{onClick:()=>s(u),className:"group relative rounded-md overflow-hidden border bg-muted/30 hover:ring-2 hover:ring-primary hover:border-primary transition-all text-left",title:u.title,children:[e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:u.thumbnail_url||u.image_url,alt:u.title,loading:"lazy",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-200"})}),u.is_featured&&e.jsxs(Ue,{className:"absolute top-1 left-1 h-5 px-1.5 gap-0.5 text-[10px] bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(oa,{className:"h-2.5 w-2.5 fill-current"}),"Featured"]}),e.jsxs("div",{className:"p-1.5 bg-background",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:u.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground truncate",children:u.category})]})]},u.id))})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center",children:[d.length," graphic",d.length===1?"":"s",a!=="all"?` in ${a}`:""]})]})}const sVs=[{key:"search",label:"Search for Properties",icon:gr,defaultText:"Search for Properties",placeholder:"https://your-website.com/search",helper:"Link to your home search page"},{key:"call",label:"Call Agent",icon:Cr,defaultText:"Call Me",hrefPrefix:"tel:",placeholder:"+15555551234",helper:"Your phone number"},{key:"email",label:"Email Agent",icon:Gs,defaultText:"Email Me",hrefPrefix:"mailto:",placeholder:"you@email.com",helper:"Your email address"},{key:"schedule",label:"Schedule a Call",icon:yr,defaultText:"Schedule a Call",placeholder:"https://calendly.com/you",helper:"Link to your booking page"},{key:"listings",label:"View My Listings",icon:Or,defaultText:"View My Listings",placeholder:"https://your-website.com/listings",helper:"Link to your listings page"},{key:"valuation",label:"Get Home Value",icon:Yl,defaultText:"Get My Home Value",placeholder:"https://your-website.com/home-value",helper:"Link to your home valuation page"},{key:"openhouse",label:"See Open Houses",icon:ka,defaultText:"See Open Houses",placeholder:"https://your-website.com/open-houses",helper:"Link to your open houses page"},{key:"forward",label:"Forward to a Friend",icon:Vl,defaultText:"Forward to a Friend",isForward:!0,placeholder:"Optional landing page (or leave blank)",helper:"Opens recipient's email pre-filled — leave blank to default"},{key:"custom",label:"Custom Button",icon:oc,defaultText:"Learn More",placeholder:"https://...",helper:"Any link you want"}];function YYe(s){const t=s.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|v\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/);return t?t[1]:null}function nVs(s){const t=s.match(/vimeo\.com\/(?:video\/)?(\d+)/);return t?t[1]:null}function e_t({html:s,onChange:t}){const{user:n}=vs(),r=N.useRef(null),a=N.useRef(""),i=N.useRef(t);i.current=t;const[l,o]=N.useState("desktop"),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,y]=N.useState(""),_=N.useRef(null),v=()=>{var gt;const Lt=(gt=r.current)==null?void 0:gt.contentDocument,Jt=Lt==null?void 0:Lt.getSelection();Jt&&Jt.rangeCount>0&&(Lt!=null&&Lt.body.contains(Jt.anchorNode))&&(_.current=Jt.getRangeAt(0).cloneRange())},j=()=>{var Xt;const Lt=c.current,Jt=(Xt=r.current)==null?void 0:Xt.contentDocument;if(!Lt||!Jt)return;let gt=h.trim();gt&&!/^(https?:|mailto:|tel:|#|\/)/i.test(gt)&&(gt="https://"+gt),Lt.setAttribute("href",gt),Lt.setAttribute("target","_blank");const zt=f.trim();zt&&zt!==(Lt.textContent||"").trim()&&(Lt.textContent=zt);const As=` `+Jt.documentElement.outerHTML;a.current=As,i.current(As),u(!1)};N.useEffect(()=>{var gt,zt;const Lt=r.current;if(!Lt||a.current===s)return;const Jt=()=>{const As=Lt.contentDocument;if(!As)return;As.open(),As.write(s||""),As.close(),a.current=s;const Xt=As.body;if(!Xt)return;Xt.setAttribute("contenteditable","true"),Xt.style.outline="none",Xt.style.minHeight="400px",Xt.style.cursor="text";const Qs=()=>{const $s=` `+As.documentElement.outerHTML;a.current=$s,i.current($s)};Xt.addEventListener("input",Qs),Xt.addEventListener("blur",Qs),Xt.addEventListener("mouseup",v),Xt.addEventListener("keyup",v),As.addEventListener("selectionchange",v);const ks=$s=>{var Qn;const an=$s.target,tn=an==null?void 0:an.closest("a");if(tn){if($s.metaKey||$s.ctrlKey||$s.shiftKey)return;$s.preventDefault(),$s.stopPropagation(),c.current=tn,p(tn.getAttribute("href")||""),y((tn.textContent||"").trim()),u(!0);return}const er=As.getSelection();if(!er)return;const xn=(Qn=As.caretRangeFromPoint)==null?void 0:Qn.call(As,$s.clientX,$s.clientY),Pn=xn==null?void 0:xn.startContainer;if(Pn&&Pn.nodeType===Node.TEXT_NODE){const sa=Pn.textContent||"",na=xn.startOffset,Es=sa.lastIndexOf("[",na),mi=sa.indexOf("]",na);if(Es!==-1&&mi!==-1&&mi>Es){const Ar=As.createRange();Ar.setStart(Pn,Es),Ar.setEnd(Pn,mi+1),er.removeAllRanges(),er.addRange(Ar),_.current=Ar.cloneRange()}}};Xt.addEventListener("click",ks,!0)};((gt=Lt.contentDocument)==null?void 0:gt.readyState)==="complete"||(zt=Lt.contentDocument)!=null&&zt.body?Jt():Lt.addEventListener("load",Jt,{once:!0})},[s]);const w=(Lt,Jt)=>{var As;const gt=(As=r.current)==null?void 0:As.contentDocument;if(!gt)return;gt.body.focus(),gt.execCommand(Lt,!1,Jt);const zt=` `+gt.documentElement.outerHTML;a.current=zt,i.current(zt)},S=()=>{const Lt=window.prompt("Enter URL (https://...)");Lt&&w("createLink",Lt)},A=(Lt,Jt)=>{var As;const gt=(As=r.current)==null?void 0:As.contentDocument;if(!gt)return;if(gt.body.focus(),Jt==="cursor"&&_.current&>.body.contains(_.current.startContainer)){const Xt=gt.getSelection();if(Xt){Xt.removeAllRanges(),Xt.addRange(_.current),gt.execCommand("insertHTML",!1,Lt);const Qs=` `+gt.documentElement.outerHTML;a.current=Qs,i.current(Qs);return}}Jt==="top"?gt.body.insertAdjacentHTML("afterbegin",Lt):gt.body.insertAdjacentHTML("beforeend",Lt);const zt=` `+gt.documentElement.outerHTML;a.current=zt,i.current(zt)},[E,O]=N.useState(!1),[D,I]=N.useState(null),[F,z]=N.useState(""),[H,Z]=N.useState(""),[Y,W]=N.useState("#406E71"),[ee,se]=N.useState("cursor"),oe=Lt=>{I(Lt),z(Lt.defaultText),Z(""),O(!0)},he=()=>{if(!D)return;const Lt=H.trim();if(!D.isForward&&!Lt)return;let Jt=Lt;if(D.isForward){const Xt=Lt||"",Qs=encodeURIComponent("You should see this newsletter"),ks=encodeURIComponent(Xt?`I thought you'd like this — take a look: ${Xt} `:`I thought you'd like this newsletter — take a look! `);Jt=`mailto:?subject=${Qs}&body=${ks}`}else D.hrefPrefix==="tel:"?Jt="tel:"+Lt.replace(/[^0-9+]/g,""):D.hrefPrefix==="mailto:"?Jt="mailto:"+Lt:/^https?:\/\//i.test(Lt)||(Jt="https://"+Lt);const gt=(F||D.defaultText).replace(/[<>]/g,""),zt=Y||"#406E71",As=`
${gt}

 

`;A(As,ee),O(!1)},[ce,me]=N.useState(!1),[le,ve]=N.useState(""),[ge,Te]=N.useState(""),[Ie,Ce]=N.useState(""),[Me,Pe]=N.useState("cursor"),Re=(()=>{if(ge.trim())return ge.trim();const Lt=YYe(le);return Lt?`https://i.ytimg.com/vi/${Lt}/hqdefault.jpg`:""})(),Ae=()=>{ve(""),Te(""),Ce(""),me(!0)},Be=()=>{const Lt=le.trim();if(!Lt)return;let Jt=Lt;/^https?:\/\//i.test(Jt)||(Jt="https://"+Jt);const gt=YYe(Jt),zt=gt?null:nVs(Jt);let As=ge.trim();!As&>&&(As=`https://i.ytimg.com/vi/${gt}/hqdefault.jpg`),!As&&zt&&(As=`https://vumbnail.com/${zt}.jpg`),As||(As="https://placehold.co/600x340/406E71/ffffff?text=Watch+Video");const Xt=(Ie||"Watch the video").replace(/[<>]/g,""),Qs=`
${Xt}
▶ ${Xt}

 

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

 

`.trim();A(gt,Ge),Je(!1)},{data:$t,isLoading:Yt}=dt({queryKey:["newsletter-editor-videos",n==null?void 0:n.id],enabled:!!(n!=null&&n.id)&&ce,queryFn:async()=>{const{data:Lt,error:Jt}=await q.from("agent_videos").select("id, title, thumbnail_url, share_token, duration_seconds, created_at").eq("owner_user_id",n.id).eq("is_deleted",!1).eq("status","ready").not("share_token","is",null).order("created_at",{ascending:!1}).limit(50);if(Jt)throw Jt;return Lt||[]}}),Ds=Lt=>{Lt.share_token&&(ve(`https://video.relevelup.com/share/video/${Lt.share_token}`),Te(`https://video.relevelup.com/thumb/${Lt.share_token}`),Ce(Lt.title||"Watch the video"))},Ls=l==="mobile"?390:"100%",xs=l==="mobile"?390:void 0;return e.jsxs("div",{className:"rounded-md border overflow-hidden bg-background",children:[e.jsxs("div",{className:"flex items-center gap-1 border-b bg-muted/40 px-2 py-1.5 flex-wrap",children:[e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>w("bold"),title:"Bold",children:e.jsx($S,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>w("italic"),title:"Italic",children:e.jsx(HS,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>w("underline"),title:"Underline",children:e.jsx(fL,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>w("insertUnorderedList"),title:"Bullet list",children:e.jsx(Sp,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>w("insertOrderedList"),title:"Numbered list",children:e.jsx(ub,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:S,title:"Insert link",children:e.jsx(Yo,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>w("undo"),title:"Undo",children:e.jsx(n4,{className:"h-3.5 w-3.5"})}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>w("redo"),title:"Redo",children:e.jsx(JS,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"w-px h-5 bg-border mx-1"}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert CTA Button",children:[e.jsx(oc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"CTA Button"})]})}),e.jsxs(gc,{align:"start",className:"w-56 bg-popover z-50",children:[e.jsx(cM,{children:"Insert a call-to-action"}),e.jsx(Kg,{}),sVs.map(Lt=>{const Jt=Lt.icon;return e.jsxs(Kr,{onClick:()=>oe(Lt),children:[e.jsx(Jt,{className:"h-4 w-4 mr-2"}),Lt.label]},Lt.key)})]})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert image",onClick:ut,children:[e.jsx(Xo,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-xs font-medium",children:"Image"})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 px-2 gap-1.5",title:"Insert video block",onClick:Ae,children:[e.jsx(fr,{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(IL,{type:"single",value:l,onValueChange:Lt=>Lt&&o(Lt),size:"sm",className:"h-7",children:[e.jsx(HA,{value:"desktop",className:"h-7 px-2",title:"Desktop preview",children:e.jsx(mb,{className:"h-3.5 w-3.5"})}),e.jsx(HA,{value:"mobile",className:"h-7 px-2",title:"Mobile preview",children:e.jsx(tg,{className:"h-3.5 w-3.5"})})]})})]}),e.jsxs("div",{className:"px-3 py-1.5 bg-primary/5 border-b text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(oc,{className:"h-3 w-3"}),e.jsxs("span",{children:["Tip: click where you want to add an image, video, or button — or click a ",e.jsx("em",{children:"[ bracketed placeholder ]"})," to replace it. Click any button/link to edit where it goes."]})]}),e.jsx("div",{className:"bg-muted/20 flex justify-center overflow-auto",style:{padding:l==="mobile"?16:0},children:e.jsx("iframe",{ref:r,title:"Newsletter visual editor",className:"bg-white",style:{width:Ls,maxWidth:xs,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(_s,{open:d,onOpenChange:u,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Edit link"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"link-edit-text",children:"Button / link text"}),e.jsx(ye,{id:"link-edit-text",value:f,onChange:Lt=>y(Lt.target.value),placeholder:"Click here"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"link-edit-href",children:"Where should this link go?"}),e.jsx(ye,{id:"link-edit-href",value:h,onChange:Lt=>p(Lt.target.value),placeholder:"https://your-website.com/...",autoFocus:!0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Use https://… for a web page, mailto:you@email.com for email, or tel:+15555551234 for a phone number."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>u(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:j,disabled:!h.trim(),children:"Save link"})]})]})}),e.jsx(_s,{open:E,onOpenChange:O,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsx(js,{children:e.jsxs(ws,{children:["Insert ",(D==null?void 0:D.label)||"CTA Button"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"cta-text",children:"Button text"}),e.jsx(ye,{id:"cta-text",value:F,onChange:Lt=>z(Lt.target.value),placeholder:D==null?void 0:D.defaultText})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"cta-value",children:D==null?void 0:D.helper}),e.jsx(ye,{id:"cta-value",value:H,onChange:Lt=>Z(Lt.target.value),placeholder:D==null?void 0:D.placeholder,autoFocus:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"cta-color",children:"Button color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{id:"cta-color",type:"color",value:Y,onChange:Lt=>W(Lt.target.value),className:"h-9 w-16 p-1 cursor-pointer"}),e.jsx(ye,{value:Y,onChange:Lt=>W(Lt.target.value),className:"flex-1"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Position"}),e.jsxs(ib,{value:ee,onValueChange:Lt=>se(Lt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"cursor",id:"cta-cursor"}),e.jsxs(ne,{htmlFor:"cta-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"top",id:"cta-top"}),e.jsxs(ne,{htmlFor:"cta-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Iu,{className:"h-3.5 w-3.5"}),"Top of newsletter"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"bottom",id:"cta-bottom"}),e.jsxs(ne,{htmlFor:"cta-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(sm,{className:"h-3.5 w-3.5"}),"Bottom of newsletter"]})]})]})]}),e.jsx("div",{className:"rounded-md border bg-muted/30 p-4 flex justify-center",children:e.jsx("div",{style:{backgroundColor:Y,color:"#ffffff",borderRadius:6,padding:"14px 28px",fontFamily:"Arial, sans-serif",fontWeight:600,fontSize:16},children:F||(D==null?void 0:D.defaultText)})})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>O(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:he,disabled:!(D!=null&&D.isForward)&&!H.trim(),children:"Insert Button"})]})]})}),e.jsx(_s,{open:ce,onOpenChange:me,children:e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Insert Video Block"})}),e.jsxs(Fr,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"library",children:"My Library"}),e.jsx(Zt,{value:"url",children:"From URL"}),e.jsx(Zt,{value:"record",children:"Record New"})]}),e.jsxs(is,{value:"library",className:"space-y-3 mt-2",children:[Yt?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground",children:[e.jsx(rs,{className:"h-5 w-5 animate-spin mx-auto mb-2"}),"Loading your videos..."]}):!$t||$t.length===0?e.jsxs("div",{className:"text-center py-8 text-sm text-muted-foreground border rounded-md",children:[e.jsx(fr,{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:$t.map(Lt=>{const Jt=le.includes(Lt.share_token||"___"),gt=Lt.share_token?`https://video.relevelup.com/thumb/${Lt.share_token}`:Lt.thumbnail_url||"";return e.jsxs("button",{type:"button",onClick:()=>Ds(Lt),className:`group text-left rounded-md border-2 overflow-hidden transition-all ${Jt?"border-primary ring-2 ring-primary/30":"border-transparent hover:border-primary/40"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[gt?e.jsx("img",{src:gt,alt:Lt.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(fr,{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(El,{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:Lt.title||"Untitled"})})]},Lt.id)})}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"vid-title-lib",className:"text-xs",children:"Caption (optional)"}),e.jsx(ye,{id:"vid-title-lib",value:Ie,onChange:Lt=>Ce(Lt.target.value),placeholder:"Watch the video"})]})]}),e.jsxs(is,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"vid-url",children:"Video URL"}),e.jsx(ye,{id:"vid-url",value:le,onChange:Lt=>ve(Lt.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(ne,{htmlFor:"vid-title",children:"Caption (optional)"}),e.jsx(ye,{id:"vid-title",value:Ie,onChange:Lt=>Ce(Lt.target.value),placeholder:"Watch the video"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"vid-thumb",children:"Custom thumbnail URL (optional)"}),e.jsx(ye,{id:"vid-thumb",value:ge,onChange:Lt=>Te(Lt.target.value),placeholder:"https://... (only if not YouTube/Vimeo)"})]})]}),e.jsx(is,{value:"record",className:"mt-2",children:e.jsxs("div",{className:"rounded-md border bg-muted/30 p-5 text-center space-y-3",children:[e.jsx(fr,{className:"h-10 w-10 mx-auto text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Record a quick video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:`Record a personal intro, market update, or property tour. When you're done, it'll show up in "My Library" and you can pick it from there.`})]}),e.jsx(B,{type:"button",onClick:()=>{window.open("/mission-control/video/record","_blank")},children:"Open Video Recorder"}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Opens in a new tab — come back here when you're done."})]})})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[e.jsx(ne,{children:"Position"}),e.jsxs(ib,{value:Me,onValueChange:Lt=>Pe(Lt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"cursor",id:"vid-cursor"}),e.jsxs(ne,{htmlFor:"vid-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"top",id:"vid-top"}),e.jsxs(ne,{htmlFor:"vid-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Iu,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"bottom",id:"vid-bottom"}),e.jsxs(ne,{htmlFor:"vid-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(sm,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]}),Re&&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:Re,alt:"thumbnail",className:"w-full rounded-md",style:{maxHeight:180,objectFit:"cover"},onError:Lt=>{Lt.target.style.opacity="0.3"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 rounded-full bg-black/65 text-white flex items-center justify-center",style:{width:56,height:56,fontSize:24},children:"▶"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>me(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:Be,disabled:!le.trim(),children:"Insert Video"})]})]})}),e.jsx(_s,{open:we,onOpenChange:Je,children:e.jsxs(bs,{className:"sm:max-w-md max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Insert Image"})}),e.jsxs(Fr,{defaultValue:"library",className:"space-y-3",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-3",children:[e.jsx(Zt,{value:"library",children:"Library"}),e.jsx(Zt,{value:"upload",children:"Upload"}),e.jsx(Zt,{value:"url",children:"From URL"})]}),e.jsx(is,{value:"library",className:"mt-2",children:e.jsx(Jbt,{maxHeight:"380px",onSelect:Lt=>{it(Lt.image_url),je||He(Lt.title)}})}),e.jsxs(is,{value:"upload",className:"space-y-3 mt-2",children:[e.jsx("input",{ref:Ye,type:"file",accept:"image/png,image/jpeg,image/webp,image/gif",className:"hidden",onChange:Lt=>{var gt;const Jt=(gt=Lt.target.files)==null?void 0:gt[0];Jt&&_t(Jt),Lt.target.value=""}}),ke?e.jsxs("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:[e.jsx("img",{src:ke,alt:"Preview",className:"w-full max-h-48 object-contain"}),e.jsxs("div",{className:"flex justify-between items-center p-2 text-xs",children:[e.jsx("span",{className:"text-muted-foreground truncate",children:"Uploaded ✓"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:()=>it(""),children:"Replace"})]})]}):e.jsx("button",{type:"button",onClick:()=>{var Lt;return(Lt=Ye.current)==null?void 0:Lt.click()},disabled:tt,className:"w-full rounded-md border-2 border-dashed border-border hover:border-primary/50 hover:bg-muted/40 transition-colors py-10 text-center disabled:opacity-60",children:tt?e.jsxs(e.Fragment,{children:[e.jsx(rs,{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(_a,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Click to upload an image"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WEBP, GIF · up to 10MB"})]})})]}),e.jsxs(is,{value:"url",className:"space-y-3 mt-2",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"img-url",children:"Image URL"}),e.jsx(ye,{id:"img-url",value:ke,onChange:Lt=>it(Lt.target.value),placeholder:"https://..."})]}),ke&&/^https?:\/\//i.test(ke)&&e.jsx("div",{className:"rounded-md border overflow-hidden bg-muted/30",children:e.jsx("img",{src:ke,alt:"Preview",className:"w-full max-h-48 object-contain",onError:Lt=>{Lt.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(ne,{htmlFor:"img-alt",children:"Alt text (for accessibility)"}),e.jsx(ye,{id:"img-alt",value:je,onChange:Lt=>He(Lt.target.value),placeholder:"Describe the image"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Size"}),e.jsxs(ib,{value:$e,onValueChange:Lt=>Ke(Lt),className:"flex gap-4",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"full",id:"img-full"}),e.jsx(ne,{htmlFor:"img-full",className:"cursor-pointer font-normal",children:"Full width"})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"half",id:"img-half"}),e.jsx(ne,{htmlFor:"img-half",className:"cursor-pointer font-normal",children:"Half width"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Position"}),e.jsxs(ib,{value:Ge,onValueChange:Lt=>rt(Lt),className:"flex gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"cursor",id:"img-cursor"}),e.jsxs(ne,{htmlFor:"img-cursor",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(oc,{className:"h-3.5 w-3.5"}),"At cursor"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"top",id:"img-top"}),e.jsxs(ne,{htmlFor:"img-top",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(Iu,{className:"h-3.5 w-3.5"}),"Top"]})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(Ld,{value:"bottom",id:"img-bottom"}),e.jsxs(ne,{htmlFor:"img-bottom",className:"flex items-center gap-1.5 cursor-pointer font-normal",children:[e.jsx(sm,{className:"h-3.5 w-3.5"}),"Bottom"]})]})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>Je(!1),children:"Cancel"}),e.jsx(B,{type:"button",onClick:bt,disabled:!ke.trim()||tt,children:"Insert Image"})]})]})})]})}const ZYe="newsletter-content",rVs="inline-images";function aVs(s,t){const n=atob(s),r=new Array(n.length);for(let a=0;a{const{data:I}=await q.from("team_members").select("team_id, role").eq("user_id",a.id).maybeSingle();return I}}),E=(A==null?void 0:A.role)==="team_leader",O=(A==null?void 0:A.team_id)??null;N.useEffect(()=>{s&&(d((n==null?void 0:n.title)??""),h((n==null?void 0:n.description)??""),f((n==null?void 0:n.html_content)??lVs()),_((n==null?void 0:n.is_template)??!1),j((n==null?void 0:n.share_scope)??"private"))},[s,n]);const D=async()=>{if(a){if(!c.trim()){ae.error("Please enter a title");return}if(!p.trim()){ae.error("Newsletter content is empty");return}S(!0);try{const I=await iVs(p);I!==p&&f(I);const F={user_id:a.id,title:c.trim(),description:u.trim()||null,html_content:I,is_template:y,share_scope:v,shared_team_id:v==="team"?O:null,shared_brokerage_id:v==="brokerage"?o:null};if(v==="team"&&!O){ae.error("You must be a team leader to share with a team"),S(!1);return}if(v==="brokerage"&&!l){ae.error("Only brokerage managers can share to a brokerage"),S(!1);return}if(v==="global"&&!i){ae.error("Only admins can publish global starter templates"),S(!1);return}let z;if(n!=null&&n.id?{error:z}=await q.from("agent_custom_newsletters").update(F).eq("id",n.id):{error:z}=await q.from("agent_custom_newsletters").insert(F),z)throw z;ae.success(n!=null&&n.id?"Saved":"Newsletter created"),r==null||r(),t(!1)}catch(I){ae.error(I.message||"Failed to save")}finally{S(!1)}}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-6xl h-[92vh] flex flex-col p-0",children:[e.jsx(js,{className:"px-6 pt-6 pb-3 border-b",children:e.jsx(ws,{children:n!=null&&n.id?"Edit Newsletter":"Create Newsletter"})}),e.jsxs("div",{className:"flex-1 overflow-y-auto px-6 py-4 space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"acn-title",children:"Title *"}),e.jsx(ye,{id:"acn-title",value:c,onChange:I=>d(I.target.value),placeholder:"e.g. June Market Update"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"acn-desc",children:"Description (optional)"}),e.jsx(ye,{id:"acn-desc",value:u,onChange:I=>h(I.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(jn,{id:"acn-template",checked:y,onCheckedChange:_}),e.jsx(ne,{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"})]}),(E||l||i)&&e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx(ne,{className:"text-sm font-semibold",children:"Sharing"}),e.jsxs(ib,{value:v,onValueChange:I=>j(I),className:"space-y-2",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ld,{value:"private",id:"s-private",className:"mt-0.5"}),e.jsxs(ne,{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"})]})]}),E&&e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Ld,{value:"team",id:"s-team",className:"mt-0.5"}),e.jsxs(ne,{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(Ld,{value:"brokerage",id:"s-brokerage",className:"mt-0.5"}),e.jsxs(ne,{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(Ld,{value:"global",id:"s-global",className:"mt-0.5"}),e.jsxs(ne,{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(ne,{className:"mb-2 block",children:"Content"}),e.jsx(e_t,{html:p,onChange:f})]})]}),e.jsxs(Xn,{className:"px-6 py-3 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:w,children:"Cancel"}),e.jsxs(B,{onClick:D,disabled:w,children:[w?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),n!=null&&n.id?"Save Changes":"Create"]})]})]})})}function lVs(){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 mR(){var a;const{user:s}=vs(),{data:t,isLoading:n}=dt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,staleTime:60*1e3,queryFn:async()=>{var d,u,h,p;const[i,l]=await Promise.all([q.from("mass_email_settings").select("reply_to_email, display_name").eq("user_id",s.id).maybeSingle(),q.from("profiles").select("email, name").eq("id",s.id).maybeSingle()]),o=i.data,c=l.data;return{reply_to_email:((d=o==null?void 0:o.reply_to_email)==null?void 0:d.trim())||((u=c==null?void 0:c.email)==null?void 0:u.trim())||s.email||null,display_name:((h=o==null?void 0:o.display_name)==null?void 0:h.trim())||((p=c==null?void 0:c.name)==null?void 0:p.trim())||null}}});return{isReady:!!((a=t==null?void 0:t.reply_to_email)!=null&&a.trim()),isLoading:n,settings:t}}function d1e(){const{user:s}=vs();return dt({queryKey:["verified-sender-check",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("id, email, status").eq("user_id",s.id),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]),r=t.data||[],a=r.filter(l=>l.status==="verified"),i=r.filter(l=>l.status==="pending");return{hasVerifiedSes:a.length>0,hasPendingSes:i.length>0,hasAnySender:r.length>0,hasGmail:!!n.data,verifiedEmails:a.map(l=>l.email),pendingEmails:i.map(l=>l.email)}}})}function u1e({open:s,onOpenChange:t,hasPending:n,pendingEmails:r}){const a=Ln();return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-amber-500/10 text-amber-600 flex items-center justify-center",children:e.jsx(Bi,{className:"h-5 w-5"})}),e.jsx(ws,{children:"Verify your sending email first"})]}),e.jsx(Jn,{className:"pt-2",children:`Before you can send emails through Amazon, your "from" address needs to be verified so inboxes trust it and it doesn't land in spam.`})]}),n&&r&&r.length>0?e.jsxs("div",{className:"rounded-lg border bg-amber-500/5 p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-medium text-amber-700",children:[e.jsx(pr,{className:"h-4 w-4"})," Waiting for you to click Amazon's link"]}),r.map(i=>e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"truncate",children:i})]},i)),e.jsx("p",{className:"text-xs text-muted-foreground pt-1",children:"Check that inbox (and your spam folder) for an email from Amazon Web Services and click the verification link."})]}):e.jsx("div",{className:"rounded-lg border bg-muted/40 p-3 text-sm text-muted-foreground",children:"It only takes a minute — add your email address on the Integrations page, then click the verification link Amazon sends you."}),e.jsxs(Xn,{className:"gap-2 sm:gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Not now"}),e.jsxs(B,{onClick:()=>{t(!1),a("/mission-control/integrations")},children:[e.jsx(tr,{className:"h-4 w-4 mr-1"}),n?"Manage senders":"Verify my email"]})]})]})})}function pR(){const s=wa();return dt({queryKey:["custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tags").select("*").eq("owner_user_id",s).order("name");if(n)throw n;return t},enabled:!!s})}function cVs(s){return dt({queryKey:["contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("*, tag:contact_custom_tags(*)").eq("contact_id",s);if(n)throw n;return t},enabled:!!s})}function WPe(){const s=Kt(),t=wa();return yt({mutationFn:async({name:n,color:r})=>{const{data:a,error:i}=await q.from("contact_custom_tags").insert({owner_user_id:t,name:n.trim(),color:r||"#6366F1"}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]})}})}function dVs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("contact_custom_tags").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function uVs(){const s=Kt();return yt({mutationFn:async({id:t,name:n,color:r})=>{const a={};n!==void 0&&(a.name=n.trim()),r!==void 0&&(a.color=r);const{error:i}=await q.from("contact_custom_tags").update(a).eq("id",t);if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["custom-tags"]}),s.invalidateQueries({queryKey:["contact-custom-tags"]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function t_t(){const s=Kt();return yt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").insert({contact_id:t,tag_id:n});if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function hVs(){const s=Kt();return yt({mutationFn:async({contactId:t,tagId:n})=>{const{error:r}=await q.from("contact_custom_tag_assignments").delete().eq("contact_id",t).eq("tag_id",n);if(r)throw r},onSuccess:(t,{contactId:n})=>{s.invalidateQueries({queryKey:["contact-custom-tags",n]}),s.invalidateQueries({queryKey:["all-contact-custom-tags"]})}})}function h1e(){const s=wa();return dt({queryKey:["all-contact-custom-tags",s],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_custom_tag_assignments").select("contact_id, tag_id, tag:contact_custom_tags(id, name, color)");if(n)throw n;return t},enabled:!!s})}function s_t(){const{user:s}=vs();return dt({queryKey:["contact-smart-lists",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_smart_lists").select("*").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function mVs(){const s=Kt(),{user:t}=vs();return yt({mutationFn:async({name:n,filters:r,sort_by:a})=>{const{data:i,error:l}=await q.from("contact_smart_lists").insert({owner_user_id:t.id,name:n,filters:r,sort_by:a}).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Br({title:"Smart filter saved"})},onError:n=>{Br({title:"Error saving smart filter",description:n.message,variant:"destructive"})}})}function pVs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("contact_smart_lists").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-smart-lists"]}),Br({title:"Smart filter deleted"})}})}const QYe=s=>s.replace(/&/g,"&").replace(//g,">").replace(/"/g,""");function XYe(s,t,n,r){const a=t.name||`${t.first_name||""} ${t.last_name||""}`.trim()||"there",i=new Date,l=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"long",day:"numeric",year:"numeric"}).format(i),o=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric"}).format(i),c={first_name:t.first_name||"there",last_name:t.last_name||"",name:a,full_name:a,email:t.email||"",phone:t.phone||"",address:t.address||"",city:t.city||"",state:t.state||"",zip:t.zip||t.zip_code||"",agent_name:(n==null?void 0:n.name)||"",agent_email:(n==null?void 0:n.email)||"",agent_phone:(n==null?void 0:n.phone)||"",agent_title:(n==null?void 0:n.title)||"",brokerage:r||"",current_date:l,current_year:o};return s.replace(/\{\{\s*(\w+)\s*\}\}/g,(d,u)=>c[u]??`{{${u}}}`)}function fVs(s,t,n,r){const a=t.trim()?`
${QYe(t).replace(/\n/g,"
")}
`:"",i=n.trim()?`
${QYe(n).replace(/\n/g,"
")}
`:"",l=r?`
${r}
`:"";return`${a} ${s} ${i} ${l}`}function xVs(s,t,n){const r=(s==null?void 0:s.name)||"Your Agent",a=(s==null?void 0:s.email)||"",i=(t==null?void 0:t.name)||"",l=[t==null?void 0:t.city,t==null?void 0:t.state].filter(Boolean).join(", "),o=a?`mailto:${encodeURIComponent(a)}?subject=${encodeURIComponent("Unsubscribe")}&body=${encodeURIComponent(`Please remove ${n} from your newsletter list.`)}`:"#";return`
${r}${i?" • "+i:""}
${l?`
${l}
`:""}
You're receiving this because ${r} thought you'd find it useful. Unsubscribe
`}const gVs=["free","act now","click here","limited time","urgent","$$$","100% free","guarantee","no obligation","risk-free","winner","cash bonus","make money","earn extra","amazing"];function yVs(s,t){const n=[],r=s.trim();if(r.length>0){r.length<10&&n.push("Subject line is very short — most opened subjects are 30-60 characters."),r.length>90&&n.push("Subject line is very long — many inboxes truncate after 60-70 characters.");const l=r.replace(/[^A-Za-z]/g,""),o=r.replace(/[^A-Z]/g,"");l.length>6&&o.length/l.length>.6&&n.push("Subject is mostly uppercase — this often triggers spam filters."),(r.match(/!/g)||[]).length>=3&&n.push("Too many exclamation marks in the subject.");const d=r.toLowerCase(),u=gVs.filter(h=>d.includes(h));u.length>0&&n.push(`Subject contains spam-trigger words: ${u.slice(0,3).join(", ")}.`)}const a=t.replace(/<[^>]+>/g," ").replace(/\s+/g," ").trim();return a.length<40&&n.push("Email body is very short — add more text so it doesn't look like a spam blast."),(t.match(/0&&a.length<80&&n.push("Email is mostly images with little text — many spam filters block these."),n}function KPe({open:s,onOpenChange:t,newsletterId:n,newsletterTitle:r,htmlCode:a}){const{user:i}=vs();Dh();const{isReady:l,settings:o}=mR(),{data:c}=d1e(),[d,u]=N.useState(!1),h=wa(),{data:p}=dt({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:Ts}=await q.from("profiles").select("name, email, phone, avatar_url, title, email_signature, use_email_signature").eq("id",i.id).maybeSingle();return Ts}}),[f,y]=N.useState("visual"),[_,v]=N.useState("all"),[j,w]=N.useState(""),[S,A]=N.useState(""),[E,O]=N.useState(""),[D,I]=N.useState(""),[F,z]=N.useState(!0),[H,Z]=N.useState([]),[Y,W]=N.useState(null),[ee,se]=N.useState(new Set),[oe,he]=N.useState(""),[ce,me]=N.useState(!1),[le,ve]=N.useState(!1),[ge,Te]=N.useState(!1),[Ie,Ce]=N.useState({sent:0,failed:0,total:0,currentName:""}),[Me,Pe]=N.useState(!0),[Re,Ae]=N.useState(!1),[Be,we]=N.useState([]),[Je,ke]=N.useState(!1),[it,je]=N.useState(new Set),[He,$e]=N.useState("now"),[Ke,Ge]=N.useState(""),{data:rt=[]}=pR(),{data:tt=[]}=h1e(),{data:at=[]}=s_t(),{data:Ye=[],isLoading:ut}=dt({queryKey:["newsletter-send-contacts",h],enabled:!!h&&s,queryFn:async()=>{const Ts=[];let Un=0;const ir=1e3;for(;;){const{data:Tr,error:ts}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, address, city, state, zip, zip_code").eq("owner_user_id",h).not("email","is",null).neq("email","").order("first_name").range(Un,Un+ir-1);if(ts)throw ts;if(!Tr||Tr.length===0||(Ts.push(...Tr),Tr.length{const{data:Ts}=await q.from("ses_suppressed_emails").select("email");return(Ts||[]).map(Un=>Un.email.toLowerCase())}}),{data:bt}=dt({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:Ts}=await q.from("profiles").select("brokerage_id").eq("id",i.id).maybeSingle();if(!(Ts!=null&&Ts.brokerage_id))return null;const{data:Un}=await q.from("brokerages").select("name, city, state").eq("id",Ts.brokerage_id).maybeSingle();return Un}}),{data:$t}=dt({queryKey:["newsletter-active-lead-site",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{if(!h)return null;const{data:Ts}=await q.from("lead_sites").select("id, subdomain_slug, mls_provider_id, mls_agent_id, mls_agent_key, is_active").eq("agent_id",h).eq("is_active",!0).not("mls_provider_id","is",null).order("created_at",{ascending:!0}).limit(1).maybeSingle();return Ts}}),Yt=!!($t!=null&&$t.mls_provider_id),Ds=($t==null?void 0:$t.mls_agent_id)||($t==null?void 0:$t.mls_agent_key)||null,{data:Ls=[],isLoading:xs}=dt({queryKey:["newsletter-agent-listings",h,Ds],enabled:!!h&&!!Ds&&Je,staleTime:60*1e3,queryFn:async()=>{if(!Ds)return[];const{data:Ts}=await q.from("mlsgrid_listings").select("listing_key, address, city, state, list_price, bedrooms, bathrooms_total, living_area, photos, standard_status, modification_timestamp").eq("list_agent_mls_id",Ds).eq("standard_status","Active").order("modification_timestamp",{ascending:!1}).limit(30);return Ts||[]}}),{data:Lt=[],isLoading:Jt}=dt({queryKey:["newsletter-exchange-listings",h],enabled:!!h&&Je,staleTime:60*1e3,queryFn:async()=>{const{data:Ts}=await q.from("listings").select("id, slug, property_address, city, state, price, bedrooms, bathrooms, square_footage, status, created_at").eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]).order("created_at",{ascending:!1}).limit(30),Un=Ts||[];if(Un.length===0)return[];const ir=Un.map(Qe=>Qe.id),{data:Tr}=await q.from("listing_photos").select("listing_id, photo_url, is_primary, sort_order").in("listing_id",ir),ts=new Map,Fe=new Map;for(const Qe of Tr||[])Qe.is_primary&&!ts.has(Qe.listing_id)&&ts.set(Qe.listing_id,Qe.photo_url),Fe.has(Qe.listing_id)||Fe.set(Qe.listing_id,Qe.photo_url);return Un.map(Qe=>({...Qe,_photo:ts.get(Qe.id)||Fe.get(Qe.id)||""}))}}),{data:gt=!1}=dt({queryKey:["newsletter-exchange-listings-exists",h],enabled:!!h&&s,staleTime:5*60*1e3,queryFn:async()=>{const{count:Ts}=await q.from("listings").select("id",{count:"exact",head:!0}).eq("agent_id",h).in("status",["active","coming_soon","office_exclusive","pre_market"]);return(Ts||0)>0}}),zt=N.useMemo(()=>{const Ts=new Set(_t);return Ye.filter(Un=>Un.email&&Un.email.includes("@")&&!Ts.has(Un.email.toLowerCase()))},[Ye,_t]),As=N.useMemo(()=>{if(H.length===0)return null;const Ts=new Set;for(const Un of tt)H.includes(Un.tag_id)&&Ts.add(Un.contact_id);return Ts},[tt,H]),Xt=N.useMemo(()=>at.find(Ts=>Ts.id===Y)||null,[at,Y]),Qs=N.useMemo(()=>{var Ts;if(_==="all")return zt;if(_==="tags")return As?zt.filter(Un=>As.has(Un.id)):[];if(_==="smartlists"){if(!Xt)return[];const Un=(((Ts=Xt.filters)==null?void 0:Ts.search)||"").toLowerCase().trim();return Un?zt.filter(ir=>`${ir.first_name||""} ${ir.last_name||""}`.toLowerCase().includes(Un)||(ir.email||"").toLowerCase().includes(Un)):zt}return zt.filter(Un=>ee.has(Un.id))},[_,zt,As,Xt,ee]),ks=N.useMemo(()=>{if(!oe.trim())return zt;const Ts=oe.toLowerCase();return zt.filter(Un=>`${Un.first_name||""} ${Un.last_name||""}`.toLowerCase().includes(Ts))},[zt,oe]);N.useEffect(()=>{s&&(w(""),A(`Hi {{first_name}}, Sharing this month's update — hope you find something useful!`),O(`As always, reach out anytime if I can help. Talk soon!`),I(a||""),y("light"),v("all"),Z([]),W(null),se(new Set),he(""),me(!1),z(!0),Pe(!0),we([]),$e("now"),Ge(""),Ce({sent:0,failed:0,total:0,currentName:""}))},[s,r,a]);const $s=l,an=!!(j.trim()&&$s&&Qs.length>0&&!le),tn=Ts=>{const Un=f==="advanced"||f==="visual"?D:a,ir=F&&(p!=null&&p.email_signature)?p.email_signature:null;let Tr;return f==="light"?Tr=fVs(Un,S,E,ir):Tr=ir?`${Un}
${ir}
`:Un,Me&&(Tr+=xVs(p??null,bt??null,Ts.email)),XYe(Tr,Ts,p??null,(bt==null?void 0:bt.name)??null)},er=N.useMemo(()=>tn({first_name:"Friend",last_name:"",email:"preview@example.com",phone:"",address:"",city:"",state:"",zip:""}),[f,S,E,D,a,F,p,Me,bt]),xn=N.useMemo(()=>yVs(j,f==="advanced"||f==="visual"?D:a),[j,f,D,a]),Pn=async()=>{Ae(!0),we([]);try{const Ts=f==="advanced"||f==="visual"?D:a,{data:Un,error:ir}=await q.functions.invoke("generate-newsletter-subjects",{body:{newsletterTitle:r,bodyHtml:Ts,currentSubject:j}});if(ir)throw ir;const Tr=Un==null?void 0:Un.subjects;if(!Array.isArray(Tr)||Tr.length===0)throw new Error("No subjects returned");we(Tr)}catch(Ts){const Un=(Ts==null?void 0:Ts.message)||"Failed to generate subjects";Un.includes("credits exhausted")||Un.includes("402")?ae.error("AI credits exhausted. Please add credits to your workspace."):Un.includes("Rate limit")||Un.includes("429")?ae.error("Rate limit hit — try again in a moment."):ae.error(Un)}finally{Ae(!1)}},Qn=Ts=>Ts?"$"+Number(Ts).toLocaleString("en-US"):"",sa=()=>{var Fe,Qe;if(it.size===0){ae.error("Pick at least one listing first.");return}const Ts=($t==null?void 0:$t.subdomain_slug)||"",Un=Ts?`https://${Ts}.relevelup.com`:"https://relevelup.com",ir=[];for(const ot of Ls){const St=`mls:${ot.listing_key}`;if(!it.has(St))continue;const Bt=Array.isArray(ot.photos)&&ot.photos.length>0?typeof ot.photos[0]=="string"?ot.photos[0]:((Fe=ot.photos[0])==null?void 0:Fe.MediaURL)||((Qe=ot.photos[0])==null?void 0:Qe.url)||"":"",Vt=ot.bedrooms?`${ot.bedrooms} bd`:"",fs=ot.bathrooms_total?`${ot.bathrooms_total} ba`:"",lt=ot.living_area?`${Number(ot.living_area).toLocaleString()} sqft`:"";ir.push({url:`${Un}/listings/${ot.listing_key}`,photo:Bt,price:Qn(ot.list_price),addr:`${ot.address||""}${ot.city?", "+ot.city:""}`,stats:[Vt,fs,lt].filter(Boolean).join(" • ")})}for(const ot of Lt){const St=`ex:${ot.id}`;if(!it.has(St))continue;const Bt=ot.bedrooms?`${ot.bedrooms} bd`:"",Vt=ot.bathrooms?`${ot.bathrooms} ba`:"",fs=ot.square_footage?`${Number(ot.square_footage).toLocaleString()} sqft`:"";ir.push({url:`https://listings.relevelup.com/${ot.slug||ot.id}`,photo:ot._photo||"",price:Qn(ot.price),addr:`${ot.property_address||""}${ot.city?", "+ot.city:""}`,stats:[Bt,Vt,fs].filter(Boolean).join(" • ")})}const ts=`

Featured Listings

${ir.map(ot=>`
${ot.photo?`${ot.addr}`:""}
${ot.price}
${ot.addr}
${ot.stats}
`.trim()).join(` `)}
`.trim();I(ot=>(ot||a||"")+` `+ts),y("visual"),je(new Set),ke(!1),ae.success(`Added ${ir.length} listing${ir.length===1?"":"s"} to your newsletter.`)},na=()=>tn({first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"}).replace(/__FN__/g,"{{first_name}}").replace(/__LN__/g,"{{last_name}}").replace(/__EM__/g,"{{email}}").replace(/__NAME__/g,"{{name}}").replace(/__PHONE__/g,"{{phone}}").replace(/__ADDR__/g,"{{address}}").replace(/__CITY__/g,"{{city}}").replace(/__STATE__/g,"{{state}}").replace(/__ZIP__/g,"{{zip}}"),Es=()=>XYe(j,{first_name:"__FN__",last_name:"__LN__",email:"__EM__",name:"__NAME__",phone:"__PHONE__",address:"__ADDR__",city:"__CITY__",state:"__STATE__",zip:"__ZIP__"},p??null,(bt==null?void 0:bt.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}}"),mi=()=>{if(an){if(He==="later"){if(!Ke){ae.error("Pick a date and time to schedule.");return}const Ts=new Date(Ke).getTime();if(Number.isNaN(Ts)||Ts{if(!(!an||!i)){Te(!1),ve(!0),Ce({sent:0,failed:0,total:Qs.length,currentName:"Preparing campaign…"});try{const Un=`${((o==null?void 0:o.display_name)||"ReLevelUp").toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,ir=na(),Tr=Es(),ts=He==="later",{data:Fe,error:Qe}=await q.from("email_campaigns").insert({user_id:h||i.id,name:`Newsletter: ${r}`,subject:Tr,body_html:ir,from_email:Un,reply_to_email:(o==null?void 0:o.reply_to_email)||null,total_recipients:Qs.length,status:ts?"scheduled":"draft",scheduled_at:ts?new Date(Ke).toISOString():null}).select("id").single();if(Qe)throw Qe;Ce(St=>({...St,currentName:"Adding recipients…"}));const ot=Qs.map(St=>({campaign_id:Fe.id,contact_id:St.id,email:St.email,name:[St.first_name,St.last_name].filter(Boolean).join(" ")||null,status:"pending"}));for(let St=0;St({...fs,sent:Math.min(St+Bt.length,ot.length)}))}if(ts){const{error:St}=await q.functions.invoke("ses-schedule-campaign",{body:{action:"schedule",campaign_id:Fe.id}});if(St)throw St;ae.success(`Newsletter scheduled for ${new Date(Ke).toLocaleString()}.`)}else{const{error:St}=await q.functions.invoke("ses-send-campaign",{body:{action:"send_campaign",campaign_id:Fe.id}});if(St)throw St;ae.success(`Sending to ${Qs.length} contact${Qs.length===1?"":"s"}! Open & click tracking will appear in Sent Emails.`)}t(!1)}catch(Ts){console.error("Newsletter send failed:",Ts),ae.error(`Failed to send: ${Ts.message||"Unknown error"}`)}finally{ve(!1)}}},Hn=Ts=>{se(Un=>{const ir=new Set(Un);return ir.has(Ts)?ir.delete(Ts):ir.add(Ts),ir})};return e.jsxs(_s,{open:s,onOpenChange:Ts=>!le&&t(Ts),children:[e.jsxs(bs,{className:"max-w-5xl max-h-[92vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(lr,{className:"h-5 w-5"})," Send Newsletter"]})}),!$s&&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(Bi,{className:"h-5 w-5 text-destructive shrink-0 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold text-destructive",children:"Set up Mass Email first"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"You need to verify your sender email before you can send newsletters. It only takes a minute — we'll send a verification email to confirm you own the address."}),e.jsx(B,{size:"sm",className:"mt-3",onClick:()=>{window.open("/mission-control/integrations#mass-email","_blank")},children:"Set up Mass Email →"})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-2 gap-6",children:[e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Subject"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 gap-1 text-xs",onClick:Pn,disabled:Re,title:"Generate subject lines with AI",children:[Re?e.jsx(rs,{className:"h-3 w-3 animate-spin"}):e.jsx(un,{className:"h-3 w-3"}),"AI Suggestions"]})]}),e.jsx(ye,{value:j,onChange:Ts=>w(Ts.target.value),placeholder:"Newsletter subject"}),Be.length>0&&e.jsxs("div",{className:"rounded-md border bg-primary/5 p-2 space-y-1",children:[e.jsx("p",{className:"text-[11px] font-medium text-muted-foreground px-1",children:"Click to use:"}),Be.map((Ts,Un)=>e.jsxs("button",{type:"button",onClick:()=>{w(Ts),we([])},className:"w-full text-left text-sm px-2 py-1.5 rounded hover:bg-primary/10 transition-colors",children:[e.jsx(un,{className:"h-3 w-3 inline-block mr-1.5 text-primary"}),Ts]},Un))]}),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}}"})]})]}),xn.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(uL,{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:xn.map((Ts,Un)=>e.jsx("li",{children:Ts},Un))})]}),(Yt||gt)&&e.jsxs("div",{className:"rounded-lg border border-primary/30 bg-primary/5 p-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"text-xs",children:[e.jsxs("div",{className:"font-medium flex items-center gap-1.5",children:[e.jsx(Or,{className:"h-3.5 w-3.5 text-primary"}),"Insert your active listings"]}),e.jsx("p",{className:"text-muted-foreground mt-0.5",children:Yt&>?"Pick from your live MLS listings or your Listing Exchange listings.":Yt?"Pick from your live MLS listings and drop them into the email.":"Pick from your Listing Exchange listings and drop them into the email."})]}),e.jsx(B,{type:"button",size:"sm",variant:"outline",onClick:()=>ke(!0),children:"Choose listings"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Editing"}),e.jsxs(Fr,{value:f,onValueChange:Ts=>y(Ts),children:[e.jsxs(Rr,{className:"grid grid-cols-3 w-full",children:[e.jsxs(Zt,{value:"visual",children:[e.jsx(Im,{className:"h-3 w-3 mr-1"}),"Visual"]}),e.jsxs(Zt,{value:"light",children:[e.jsx(br,{className:"h-3 w-3 mr-1"}),"Quick edit"]}),e.jsxs(Zt,{value:"advanced",children:[e.jsx(N2,{className:"h-3 w-3 mr-1"}),"HTML"]})]}),e.jsx(is,{value:"visual",className:"mt-3",children:e.jsx(e_t,{html:D,onChange:I})}),e.jsxs(is,{value:"light",className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Personal intro (above newsletter)"}),e.jsx(Ms,{value:S,onChange:Ts=>A(Ts.target.value),rows:4,placeholder:"Hi {{first_name}}, ..."})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Personal outro (below newsletter)"}),e.jsx(Ms,{value:E,onChange:Ts=>O(Ts.target.value),rows:3,placeholder:"Talk soon!"})]})]}),e.jsxs(is,{value:"advanced",className:"mt-3",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Edit full HTML"}),e.jsx(Ms,{value:D,onChange:Ts=>I(Ts.target.value),rows:14,className:"font-mono text-xs"})]})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Append my email signature"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:p!=null&&p.email_signature?"Will append the signature from your profile.":"No signature set. Add one in Profile → Email Signature."})]}),e.jsx(jn,{checked:F&&!!(p!=null&&p.email_signature),disabled:!(p!=null&&p.email_signature),onCheckedChange:z})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-sm font-medium",children:"Include unsubscribe footer"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds your brokerage info and a one-click unsubscribe link. Strongly recommended for deliverability."})]}),e.jsx(jn,{checked:Me,onCheckedChange:Pe})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Recipients"}),e.jsxs(Fr,{value:_,onValueChange:Ts=>v(Ts),children:[e.jsxs(Rr,{className:"grid grid-cols-4 w-full",children:[e.jsxs(Zt,{value:"all",children:[e.jsx(An,{className:"h-3 w-3 mr-1"}),"All"]}),e.jsxs(Zt,{value:"tags",children:[e.jsx(oh,{className:"h-3 w-3 mr-1"}),"Tags"]}),e.jsxs(Zt,{value:"smartlists",children:[e.jsx(J7,{className:"h-3 w-3 mr-1"}),"Lists"]}),e.jsxs(Zt,{value:"individual",children:[e.jsx(Wi,{className:"h-3 w-3 mr-1"}),"Pick"]})]}),e.jsx(is,{value:"all",className:"mt-3",children:e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 text-sm",children:["Send to ",e.jsx("strong",{children:zt.length})," contact",zt.length===1?"":"s"," with a valid, non-suppressed email."]})}),e.jsxs(is,{value:"tags",className:"mt-3 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Select one or more tags"}),e.jsx(di,{className:"h-40 rounded-lg border p-2",children:rt.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No tags yet. Add tags to contacts to use this option."}):rt.map(Ts=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(hi,{checked:H.includes(Ts.id),onCheckedChange:Un=>Z(ir=>Un?[...ir,Ts.id]:ir.filter(Tr=>Tr!==Ts.id))}),e.jsx("span",{className:"inline-block h-2 w-2 rounded-full",style:{background:Ts.color||"#406E71"}}),e.jsx("span",{className:"text-sm",children:Ts.name})]},Ts.id))})]}),e.jsxs(is,{value:"smartlists",className:"mt-3 space-y-2",children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:"Pick a saved smart list"}),e.jsx(di,{className:"h-40 rounded-lg border p-2",children:at.length===0?e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No smart lists yet. Save one from the contacts page."}):at.map(Ts=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx("input",{type:"radio",name:"smartlist",checked:Y===Ts.id,onChange:()=>W(Ts.id)}),e.jsx("span",{className:"text-sm",children:Ts.name})]},Ts.id))})]}),e.jsxs(is,{value:"individual",className:"mt-3 space-y-2",children:[e.jsx(ye,{placeholder:"Search contacts...",value:oe,onChange:Ts=>he(Ts.target.value)}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:[ee.size," selected"]}),e.jsx("button",{type:"button",className:"underline",onClick:()=>se(new Set),children:"Clear"})]}),e.jsxs(di,{className:"h-48 rounded-lg border p-2",children:[ut&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"Loading contacts…"}),!ut&&ks.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground p-2",children:"No matching contacts."}),ks.slice(0,200).map(Ts=>e.jsxs("label",{className:"flex items-center gap-2 p-1.5 hover:bg-muted rounded cursor-pointer",children:[e.jsx(hi,{checked:ee.has(Ts.id),onCheckedChange:()=>Hn(Ts.id)}),e.jsxs("div",{className:"text-sm flex-1 min-w-0",children:[e.jsxs("div",{className:"truncate",children:[Ts.first_name," ",Ts.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:Ts.email})]})]},Ts.id)),ks.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(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(vr,{className:"h-3 w-3"})," ",Qs.length," recipient",Qs.length===1?"":"s"]}),$s&&e.jsxs(Ue,{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(ne,{children:"Preview"}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>me(Ts=>!Ts),children:ce?e.jsxs(e.Fragment,{children:[e.jsx(mf,{className:"h-3 w-3 mr-1"}),"Hide"]}):e.jsxs(e.Fragment,{children:[e.jsx(Sr,{className:"h-3 w-3 mr-1"}),"Show"]})})]}),ce?e.jsx("div",{className:"rounded-lg border overflow-hidden bg-white",children:e.jsx("iframe",{title:"newsletter-preview",srcDoc:er,className:"w-full h-[560px] bg-white",sandbox:""})}):e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:["Click ",e.jsx("strong",{children:"Show"})," to preview how the email looks. Merge tags use sample data (Friend)."]})]})]}),le&&e.jsxs("div",{className:"space-y-2 rounded-lg border p-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),"Sending to ",Ie.currentName||"..."]}),e.jsxs("span",{className:"text-muted-foreground",children:[Ie.sent+Ie.failed," / ",Ie.total]})]}),e.jsx(fi,{value:Ie.total?(Ie.sent+Ie.failed)/Ie.total*100:0}),Ie.failed>0&&e.jsxs("p",{className:"text-xs text-destructive",children:[Ie.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(pr,{className:"h-4 w-4"})," When to send"]}),e.jsxs(ib,{value:He,onValueChange:Ts=>$e(Ts),className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(Ld,{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(Ld,{value:"later",id:"send-later"}),e.jsxs("span",{className:"text-sm flex items-center gap-1",children:[e.jsx(Xf,{className:"h-3.5 w-3.5"})," Schedule for later"]})]}),He==="later"&&e.jsx(ye,{type:"datetime-local",value:Ke,onChange:Ts=>Ge(Ts.target.value),className:"sm:ml-2 w-full sm:w-auto",min:new Date(Date.now()+5*6e4).toISOString().slice(0,16)})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Suppressed/unsubscribed contacts are skipped automatically. Open & click tracking is included."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:le,children:"Cancel"}),e.jsx(B,{onClick:mi,disabled:!an,children:le?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}),"Working…"]}):He==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Xf,{className:"h-4 w-4 mr-1"}),"Schedule for ",Qs.length]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Send to ",Qs.length]})})]})]})]})]}),e.jsx(Oo,{open:ge,onOpenChange:Te,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:He==="later"?"Schedule newsletter?":"Send newsletter?"}),e.jsxs(Mo,{children:[He==="later"?"Schedule ":"Send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',j,'"']})," to"," ",e.jsxs("span",{className:"font-medium text-foreground",children:[Qs.length," contact",Qs.length===1?"":"s"]}),He==="later"&&Ke?` for ${new Date(Ke).toLocaleString()}`:"","? Suppressed and unsubscribed contacts are skipped automatically."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:Ar,children:He==="later"?e.jsxs(e.Fragment,{children:[e.jsx(Xf,{className:"h-4 w-4 mr-1"}),"Schedule"]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Send to ",Qs.length]})})]})]})}),e.jsx(_s,{open:Je,onOpenChange:ke,children:e.jsxs(bs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-5 w-5"})," Choose listings to insert"]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pick up to 6 listings. They'll be added as an email-safe grid."}),(xs||Jt)&&e.jsxs("div",{className:"text-sm text-muted-foreground p-6 text-center",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin inline-block mr-2"}),"Loading your listings…"]}),!xs&&!Jt&&Ls.length===0&&Lt.length===0&&e.jsx("div",{className:"rounded-lg border bg-muted/30 p-6 text-center text-sm text-muted-foreground",children:"No listings found. Add a listing on the Listing Exchange or connect your MLS to get started."}),Ls.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"From your MLS"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Ls.map(Ts=>{var ts,Fe;const Un=`mls:${Ts.listing_key}`,ir=it.has(Un),Tr=Array.isArray(Ts.photos)&&Ts.photos.length>0?typeof Ts.photos[0]=="string"?Ts.photos[0]:((ts=Ts.photos[0])==null?void 0:ts.MediaURL)||((Fe=Ts.photos[0])==null?void 0:Fe.url)||"":"";return e.jsxs("button",{type:"button",onClick:()=>{je(Qe=>{const ot=new Set(Qe);return ot.has(Un)?ot.delete(Un):ot.size<6?ot.add(Un):ae.error("Max 6 listings per newsletter"),ot})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${ir?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Tr&&e.jsx("img",{src:Tr,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:Ts.list_price?`$${Number(Ts.list_price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:Ts.address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[Ts.city,Ts.state?`, ${Ts.state}`:""]})]}),ir&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(vr,{className:"h-4 w-4"})})]},Un)})})]}),Lt.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-[11px] font-semibold uppercase tracking-wide text-muted-foreground",children:"From your Listing Exchange"}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:Lt.map(Ts=>{const Un=`ex:${Ts.id}`,ir=it.has(Un);return e.jsxs("button",{type:"button",onClick:()=>{je(Tr=>{const ts=new Set(Tr);return ts.has(Un)?ts.delete(Un):ts.size<6?ts.add(Un):ae.error("Max 6 listings per newsletter"),ts})},className:`relative rounded-lg border-2 overflow-hidden text-left transition-all ${ir?"border-primary ring-2 ring-primary/30":"border-border hover:border-primary/50"}`,children:[Ts._photo&&e.jsx("img",{src:Ts._photo,alt:"",className:"w-full h-32 object-cover"}),e.jsxs("div",{className:"p-2",children:[e.jsx("div",{className:"text-sm font-semibold text-primary",children:Ts.price?`$${Number(Ts.price).toLocaleString()}`:""}),e.jsx("div",{className:"text-xs truncate",children:Ts.property_address}),e.jsxs("div",{className:"text-[11px] text-muted-foreground truncate",children:[Ts.city,Ts.state?`, ${Ts.state}`:""]})]}),ir&&e.jsx("div",{className:"absolute top-1 right-1 bg-primary text-primary-foreground rounded-full p-0.5",children:e.jsx(vr,{className:"h-4 w-4"})})]},Un)})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ke(!1),children:"Cancel"}),e.jsxs(B,{onClick:sa,disabled:it.size===0,children:["Insert ",it.size>0?it.size:""," listing",it.size===1?"":"s"]})]})]})}),e.jsx(u1e,{open:d,onOpenChange:u,hasPending:!!(c!=null&&c.hasPendingSes),pendingEmails:c==null?void 0:c.pendingEmails})]})}function vVs(){const{user:s}=vs(),t=Kt(),[n,r]=N.useState("starters"),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState(null),[u,h]=N.useState(null),{data:p,isLoading:f}=dt({queryKey:["agent-custom-newsletters",s==null?void 0:s.id],enabled:!!(s!=null&&s.id),queryFn:async()=>{const{data:D,error:I}=await q.from("agent_custom_newsletters").select("*").order("updated_at",{ascending:!1});if(I)throw I;return D||[]}}),y=()=>t.invalidateQueries({queryKey:["agent-custom-newsletters"]}),_=(p==null?void 0:p.filter(D=>D.user_id===(s==null?void 0:s.id)&&!D.is_template))??[],v=(p==null?void 0:p.filter(D=>D.user_id===(s==null?void 0:s.id)&&D.is_template))??[],j=(p==null?void 0:p.filter(D=>D.user_id!==(s==null?void 0:s.id)&&D.is_template&&(D.share_scope==="team"||D.share_scope==="brokerage"||D.share_scope==="global")))??[],w=(p==null?void 0:p.filter(D=>D.share_scope==="global"&&D.is_template))??[],S=n==="starters"?w:n==="mine"?_:n==="templates"?v:j.filter(D=>D.share_scope!=="global"),A=async D=>{if(!s)return;const{error:I}=await q.from("agent_custom_newsletters").insert({user_id:s.id,title:`${D.title} (Copy)`,description:D.description,html_content:D.html_content,is_template:!1,share_scope:"private"});if(I){ae.error(I.message);return}ae.success('Duplicated to "My Newsletters"'),y(),r("mine")},E=async D=>{const{error:I}=await q.from("agent_custom_newsletters").delete().eq("id",D);if(I){ae.error(I.message);return}ae.success("Deleted"),h(null),y()},O=D=>D.share_scope==="global"?e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),"Starter"]}):D.share_scope==="brokerage"?e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(Ua,{className:"h-3 w-3"}),"Brokerage"]}):D.share_scope==="team"?e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(An,{className:"h-3 w-3"}),"Team"]}):e.jsxs(Ue,{variant:"outline",className:"gap-1 text-muted-foreground",children:[e.jsx(Gc,{className:"h-3 w-3"}),"Private"]});return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:n==="starters"?"default":"outline",size:"sm",onClick:()=>r("starters"),className:"gap-1.5",children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Starter Templates (",w.length,")"]}),e.jsxs(B,{variant:n==="mine"?"default":"outline",size:"sm",onClick:()=>r("mine"),children:["My Newsletters (",_.length,")"]}),e.jsxs(B,{variant:n==="templates"?"default":"outline",size:"sm",onClick:()=>r("templates"),children:["My Templates (",v.length,")"]}),e.jsxs(B,{variant:n==="shared"?"default":"outline",size:"sm",onClick:()=>r("shared"),children:["Shared with Me (",j.filter(D=>D.share_scope!=="global").length,")"]})]}),e.jsxs(B,{onClick:()=>{o(null),i(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Create Newsletter"]})]}),f&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((D,I)=>e.jsx(Ws,{className:"h-48 w-full"},I))}),n==="starters"&&!f&&e.jsxs("div",{className:"rounded-lg border border-primary/20 bg-primary/5 px-4 py-3 text-sm flex items-start gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("span",{children:["Click ",e.jsx("strong",{children:"Use"}),' on any starter to copy it into your "My Newsletters" — then edit, send, or save as your own template.']})]}),!f&&S.length===0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(br,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),n==="starters"&&e.jsx("p",{children:"No starter templates available yet."}),n==="mine"&&e.jsx("p",{children:`You haven't created any newsletters yet. Try a Starter Template or click "Create Newsletter"!`}),n==="templates"&&e.jsx("p",{children:`You haven't saved any templates yet. Toggle "Save as reusable template" when creating a newsletter.`}),n==="shared"&&e.jsx("p",{children:"No team or brokerage templates have been shared with you yet."})]})}),!f&&S.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:S.map(D=>{const I=D.user_id===(s==null?void 0:s.id);return e.jsxs(fe,{className:"overflow-hidden hover:shadow-md transition-shadow",children:[e.jsxs("div",{className:"aspect-[3/2] bg-muted relative overflow-hidden",children:[D.thumbnail_url?e.jsx("img",{src:D.thumbnail_url,alt:D.title,className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full p-3 overflow-hidden pointer-events-none",dangerouslySetInnerHTML:{__html:`
${D.html_content}
`}}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1",children:[D.is_template&&e.jsx(Ue,{className:"bg-primary/90",children:"Template"}),O(D)]})]}),e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold line-clamp-1",children:D.title}),D.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:D.description}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:["Updated ",Ss(new Date(D.updated_at||D.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsxs(B,{size:"sm",onClick:()=>d(D),className:"flex-1 min-w-[80px]",children:[e.jsx(lr,{className:"h-3.5 w-3.5 mr-1"})," Send"]}),I?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{o(D),i(!0)},children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(D),children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>h(D.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>A(D),children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"})," Use"]})]})]})]},D.id)})}),e.jsx(oVs,{open:a,onOpenChange:i,initial:l,onSaved:y}),c&&e.jsx(KPe,{open:!!c,onOpenChange:D=>!D&&d(null),newsletterId:c.id,newsletterTitle:c.title,htmlCode:c.html_content}),e.jsx(Oo,{open:!!u,onOpenChange:D=>!D&&h(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this newsletter?"}),e.jsx(Mo,{children:"This cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>u&&E(u),children:"Delete"})]})]})})]})}function bVs(){const s=Ln(),[t,n]=N.useState(""),[r,a]=N.useState("grid"),[i,l]=N.useState(null),{data:o,isLoading:c}=dt({queryKey:["newsletters"],queryFn:async()=>{const{data:E,error:O}=await q.from("newsletter_content").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(O)throw O;return E}}),{data:d}=dt({queryKey:["newsletter-likes-all"],queryFn:async()=>{const{data:E}=await q.from("newsletter_likes").select("newsletter_id");return E||[]}}),{data:u}=dt({queryKey:["newsletter-comments-all"],queryFn:async()=>{const{data:E}=await q.from("newsletter_comments").select("newsletter_id");return E||[]}}),{data:h}=dt({queryKey:["newsletter-resource-counts"],queryFn:async()=>{const[E,O,D,I]=await Promise.all([q.from("newsletter_canva_links").select("newsletter_id"),q.from("newsletter_pdfs").select("newsletter_id"),q.from("newsletter_videos").select("newsletter_id"),q.from("newsletter_drive_links").select("newsletter_id")]);return{canva:E.data||[],pdfs:O.data||[],videos:D.data||[],drives:I.data||[]}}}),p=E=>(d==null?void 0:d.filter(O=>O.newsletter_id===E).length)||0,f=E=>(u==null?void 0:u.filter(O=>O.newsletter_id===E).length)||0,y=E=>{var O;return((O=h==null?void 0:h.canva)==null?void 0:O.filter(D=>D.newsletter_id===E).length)||0},_=E=>{var O;return((O=h==null?void 0:h.pdfs)==null?void 0:O.filter(D=>D.newsletter_id===E).length)||0},v=E=>{var O;return((O=h==null?void 0:h.videos)==null?void 0:O.filter(D=>D.newsletter_id===E).length)||0},j=E=>{var O;return((O=h==null?void 0:h.drives)==null?void 0:O.filter(D=>D.newsletter_id===E).length)||0},w=E=>y(E)+_(E)+v(E)+j(E),S=o==null?void 0:o.filter(E=>{var O;return E.title.toLowerCase().includes(t.toLowerCase())||((O=E.description)==null?void 0:O.toLowerCase().includes(t.toLowerCase()))}),A=E=>{s(`/newsletters/${E}`)};return e.jsx(Cs,{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(Fr,{defaultValue:"custom",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"custom",children:"Build & Send"}),e.jsx(Zt,{value:"curated",children:"Curated Monthly"})]}),e.jsx(is,{value:"custom",className:"mt-2",children:e.jsx(vVs,{})}),e.jsxs(is,{value:"curated",className:"space-y-6 mt-2",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search newsletters...",value:t,onChange:E=>n(E.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[t&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>n(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:r==="grid"?"secondary":"outline",size:"icon",onClick:()=>a("grid"),className:"rounded-full",children:e.jsx(ff,{className:"h-4 w-4"})}),e.jsx(B,{variant:r==="list"?"secondary":"outline",size:"icon",onClick:()=>a("list"),className:"rounded-full",children:e.jsx(Sp,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[(S==null?void 0:S.length)||0," item",(S==null?void 0:S.length)!==1?"s":""," found"]}),c&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(8)].map((E,O)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-0",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full"}),e.jsxs("div",{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-full"})]})]})},O))}),!c&&(S==null?void 0:S.length)===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx(br,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("div",{className:"text-muted-foreground mb-4",children:t?"No newsletters match your search":"No newsletters available yet"}),t&&e.jsx(B,{variant:"outline",onClick:()=>n(""),children:"Clear Search"})]}),!c&&S&&S.length>0&&e.jsx("div",{className:r==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-3",children:S.map(E=>{const O=w(E.id),D=y(E.id),I=_(E.id),F=v(E.id);return r==="grid"?e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(E.id),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:E.preview_image_url?e.jsx("img",{src:E.preview_image_url,alt:E.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(br,{className:"h-16 w-16"})})}),e.jsxs(Ee,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:E.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-1 text-xs text-muted-foreground",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(E.publish_date),"MMM d, yyyy")]})]}),E.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:E.description.replace(/<[^>]*>/g,"")}),O>0&&e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[D>0&&e.jsxs(Ue,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(pl,{className:"h-3 w-3"})," ",D," Template",D>1?"s":""]}),I>0&&e.jsxs(Ue,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(Ia,{className:"h-3 w-3"})," ",I," PDF",I>1?"s":""]}),F>0&&e.jsxs(Ue,{variant:"secondary",className:"text-xs gap-1 font-normal",children:[e.jsx(El,{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($m,{className:"h-3 w-3"})," ",p(E.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zl,{className:"h-3 w-3"})," ",f(E.id)]})]}),E.html_code&&e.jsxs(B,{size:"sm",className:"w-full bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(E)},children:[e.jsx(lr,{className:"h-4 w-4 mr-1.5"}),"Send Newsletter"]})]})]},E.id):e.jsx(fe,{className:"group overflow-hidden hover:shadow-md transition-all duration-200 cursor-pointer border-border/50",onClick:()=>A(E.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:E.preview_image_url?e.jsx("img",{src:E.preview_image_url,alt:E.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(br,{className:"h-10 w-10"})})}),e.jsxs(Ee,{className:"p-4 flex-1 flex flex-col justify-center gap-2",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1",children:E.title}),e.jsxs("div",{className:"flex items-center gap-1.5 mt-0.5 text-xs text-muted-foreground",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(E.publish_date),"MMM d, yyyy")]})]}),E.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:E.description.replace(/<[^>]*>/g,"")}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[O>0&&e.jsxs("span",{children:[O," resource",O>1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx($m,{className:"h-3 w-3"})," ",p(E.id)]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zl,{className:"h-3 w-3"})," ",f(E.id)]})]})]}),E.html_code&&e.jsx("div",{className:"p-3 flex items-center shrink-0",children:e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:z=>{z.stopPropagation(),l(E)},children:[e.jsx(lr,{className:"h-4 w-4 mr-1.5"}),"Send"]})})]})},E.id)})})]})]}),(i==null?void 0:i.html_code)&&e.jsx(KPe,{open:!!i,onOpenChange:E=>!E&&l(null),newsletterId:i.id,newsletterTitle:i.title,htmlCode:i.html_code})]})})}function _Vs({rows:s}){if(!s||s.length===0)return null;const t=s.filter(n=>n.columns.some(r=>r.title||r.description||r.image_url));return t.length===0?null:e.jsx("div",{className:"space-y-6",children:t.map((n,r)=>{const a=n.columns.filter(i=>i.title||i.description||i.image_url);return a.length===0?null:e.jsx("div",{className:"grid gap-4",style:{gridTemplateColumns:`repeat(${a.length}, minmax(0, 1fr))`},children:a.map((i,l)=>e.jsxs(fe,{className:"overflow-hidden border-border/50",children:[i.image_url&&e.jsx("img",{src:i.image_url,alt:i.title||"",className:"w-full h-40 object-cover"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[i.title&&e.jsx("h4",{className:"font-semibold text-foreground",children:i.title}),i.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:i.description})]})]},l))},r)})})}function wVs(){const{id:s}=bi(),t=Ln(),{user:n}=vs(),{toast:r}=Fa(),a=Kt(),{trackEngagement:i}=UD(),[l,o]=N.useState(""),[c,d]=N.useState(!1),{data:u,isLoading:h}=dt({queryKey:["newsletter",s],queryFn:async()=>{const{data:D,error:I}=await q.from("newsletter_content").select("*").eq("id",s).single();if(I)throw I;return D},enabled:!!s});N.useEffect(()=>{u&&i("newsletter",u.id,u.title,"view")},[u==null?void 0:u.id]);const{data:p}=dt({queryKey:["newsletter-drives",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_drive_links").select("*").eq("newsletter_id",s).order("sort_order");return D||[]},enabled:!!s}),{data:f}=dt({queryKey:["newsletter-pdfs",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_pdfs").select("*").eq("newsletter_id",s).order("sort_order");return D||[]},enabled:!!s}),{data:y}=dt({queryKey:["newsletter-videos",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_videos").select("*").eq("newsletter_id",s).order("sort_order");return D||[]},enabled:!!s}),{data:_}=dt({queryKey:["newsletter-canva-links",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_canva_links").select("*").eq("newsletter_id",s).order("sort_order");return D||[]},enabled:!!s}),{data:v}=dt({queryKey:["newsletter-likes",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_likes").select("*").eq("newsletter_id",s);return D||[]},enabled:!!s}),{data:j}=dt({queryKey:["newsletter-comments",s],queryFn:async()=>{const{data:D}=await q.from("newsletter_comments").select("*, profiles:user_id(name)").eq("newsletter_id",s).order("created_at",{ascending:!1});return D||[]},enabled:!!s}),w=v==null?void 0:v.some(D=>D.user_id===(n==null?void 0:n.id)),S=yt({mutationFn:async()=>{w?await q.from("newsletter_likes").delete().eq("newsletter_id",s).eq("user_id",n==null?void 0:n.id):await q.from("newsletter_likes").insert({newsletter_id:s,user_id:n==null?void 0:n.id})},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-likes",s]})}}),A=yt({mutationFn:async D=>{const{error:I}=await q.from("newsletter_comments").insert({newsletter_id:s,user_id:n==null?void 0:n.id,content:D});if(I)throw I},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),o(""),r({title:"Comment added"})}}),E=yt({mutationFn:async D=>{const{error:I}=await q.from("newsletter_comments").delete().eq("id",D);if(I)throw I},onSuccess:()=>{a.invalidateQueries({queryKey:["newsletter-comments",s]}),r({title:"Comment deleted"})}}),O=D=>{if(D.includes("player.mediadelivery.net")||D.includes("iframe.mediadelivery.net")){const I=D.match(/embed\/(\d+)\/([a-f0-9-]+)/);if(I)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://iframe.mediadelivery.net/embed/${I[1]}/${I[2]}?autoplay=false`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}if(D.includes("youtube.com")||D.includes("youtu.be")){const I=D.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([^&\s]+)/);if(I)return e.jsx("div",{className:"relative w-full pt-[56.25%]",children:e.jsx("iframe",{src:`https://www.youtube.com/embed/${I[1]}`,className:"absolute inset-0 w-full h-full rounded-lg",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}return e.jsxs("a",{href:D,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(El,{className:"h-4 w-4"})," Watch Video"]})};return h?e.jsx(Cs,{title:"",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-32"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-32 w-full"})]})}):u?e.jsx(Cs,{title:"",description:"",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/newsletters"),className:"mb-4",children:[e.jsx(qr,{className:"mr-2 h-4 w-4"})," Back to Newsletters"]}),u.preview_image_url&&e.jsx("img",{src:u.preview_image_url,alt:u.title,className:"w-full h-64 md:h-80 object-cover rounded-lg"}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-3xl font-bold",children:u.title}),e.jsx("p",{className:"text-muted-foreground mt-1",children:Ss(new Date(u.publish_date),"MMMM d, yyyy")})]}),u.description&&e.jsx("div",{className:"text-lg text-muted-foreground prose prose-sm max-w-none dark:prose-invert [&_p]:mb-4 [&_p:last-child]:mb-0 whitespace-pre-line",dangerouslySetInnerHTML:{__html:u.description}}),e.jsx(_Vs,{rows:u.content_blocks||[]}),e.jsxs("div",{className:"flex items-center gap-4 flex-wrap",children:[e.jsx(HD,{resourceType:"newsletter",resourceId:u.id,resourceTitle:u.title}),e.jsxs(B,{variant:w?"default":"outline",size:"sm",onClick:()=>S.mutate(),children:[e.jsx(gi,{className:`h-4 w-4 mr-1 ${w?"fill-current":""}`}),(v==null?void 0:v.length)||0," ",(v==null?void 0:v.length)===1?"Like":"Likes"]}),u.html_code&&e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-[#2a4c64] to-[#406E71] text-white hover:opacity-90",onClick:()=>d(!0),children:[e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Send Newsletter"]})]}),u.html_code&&e.jsx(KPe,{open:c,onOpenChange:d,newsletterId:u.id,newsletterTitle:u.title,htmlCode:u.html_code}),_&&_.length>0&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Canva Templates"})}),e.jsx(Ee,{className:"space-y-2",children:_.map(D=>e.jsxs("a",{href:D.canva_share_link,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_canva"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(pl,{className:"h-5 w-5 text-purple-500"}),e.jsx("span",{className:"font-medium",children:D.title}),e.jsx(tr,{className:"h-4 w-4 text-muted-foreground ml-auto"})]},D.id))})]}),p&&p.length>0&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Google Drive Files"})}),e.jsx(Ee,{className:"space-y-2",children:p.map(D=>e.jsxs("a",{href:D.drive_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_link"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(tr,{className:"h-5 w-5 text-primary"}),e.jsx("span",{className:"font-medium",children:D.title})]},D.id))})]}),f&&f.length>0&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"PDF Downloads"})}),e.jsx(Ee,{className:"space-y-2",children:f.map(D=>e.jsxs("a",{href:D.file_url,target:"_blank",rel:"noopener noreferrer",onClick:()=>i("newsletter",u.id,u.title,"click_pdf"),className:"flex items-center gap-3 p-3 rounded-lg hover:bg-muted transition-colors",children:[e.jsx(br,{className:"h-5 w-5 text-red-500"}),e.jsx("span",{className:"font-medium flex-1",children:D.name}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground"})]},D.id))})]}),y&&y.length>0&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Videos"})}),e.jsx(Ee,{className:"space-y-6",children:y.map(D=>e.jsxs("div",{className:"space-y-2",children:[e.jsx("h4",{className:"font-medium",children:D.title}),O(D.video_url)]},D.id))})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-lg",children:["Comments (",(j==null?void 0:j.length)||0,")"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Ms,{placeholder:"Write a comment...",value:l,onChange:D=>o(D.target.value),className:"flex-1"}),e.jsx(B,{onClick:()=>l.trim()&&A.mutate(l),disabled:!l.trim()||A.isPending,children:e.jsx(lr,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(D=>{var I,F,z;return e.jsxs("div",{className:"flex gap-3",children:[e.jsx(Jr,{className:"h-8 w-8",children:e.jsx(ea,{children:((F=(I=D.profiles)==null?void 0:I.name)==null?void 0:F[0])||"U"})}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium text-sm",children:((z=D.profiles)==null?void 0:z.name)||"User"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(D.created_at),"MMM d, yyyy")}),D.user_id===(n==null?void 0:n.id)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>E.mutate(D.id),children:e.jsx(_n,{className:"h-3 w-3"})})]})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:D.content})]})]},D.id)})})]})]})]})}):e.jsx(Cs,{title:"Not Found",description:"",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Newsletter not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/newsletters"),children:"Back to Newsletters"})]})})}function jVs({rows:s,onChange:t}){const[n,r]=N.useState(null),[a,i]=N.useState(null),l=()=>{t([...s,{columns:[{title:"",description:""},{title:"",description:""},{title:"",description:""}]}])},o=h=>{t(s.filter((p,f)=>f!==h))},c=(h,p,f,y)=>{const _=[...s];_[h]={..._[h],columns:_[h].columns.map((v,j)=>j===p?{...v,[f]:y}:v)},t(_)},d=async(h,p,f)=>{var v;const y=(v=f.target.files)==null?void 0:v[0];if(!y)return;const _=`${h}-${p}`;r(_);try{const j=`content-blocks/${Date.now()}-${y.name}`,{error:w}=await q.storage.from("newsletter-content").upload(j,y);if(!w){const{data:S}=q.storage.from("newsletter-content").getPublicUrl(j);c(h,p,"image_url",S.publicUrl)}}finally{r(null)}},u=(h,p)=>{c(h,p,"image_url","")};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-base font-medium",children:"Content Blocks (3-Column Rows)"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:l,children:[e.jsx(Is,{className:"mr-1 h-3 w-3"})," Add Row"]})]}),s.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"No content block rows yet. Add a row to create a 3-column layout."}),s.map((h,p)=>e.jsxs(fe,{className:"relative",children:[e.jsx(B,{type:"button",variant:"ghost",size:"icon",className:"absolute top-2 right-2 h-6 w-6 text-muted-foreground hover:text-destructive",onClick:()=>o(p),children:e.jsx($n,{className:"h-4 w-4"})}),e.jsxs(Ee,{className:"p-4 pt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(Pu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Row ",p+1]})]}),e.jsx("div",{className:"grid grid-cols-3 gap-3",children:h.columns.map((f,y)=>{const _=`${p}-${y}`;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 ",y+1]}),f.image_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:f.image_url,alt:"",className:"w-full h-20 object-cover rounded"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>u(p,y),children:e.jsx($n,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-1.5",children:[e.jsx(ye,{type:"file",accept:"image/*",className:"hidden",id:`block-img-${_}`,onChange:v=>d(p,y,v)}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",disabled:n===_,asChild:!0,children:e.jsx("label",{htmlFor:`block-img-${_}`,className:"cursor-pointer",children:n===_?"...":e.jsxs(e.Fragment,{children:[e.jsx(Xo,{className:"h-3 w-3 mr-1"})," Upload"]})})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"text-xs h-8",onClick:()=>i({row:p,col:y}),children:[e.jsx(qg,{className:"h-3 w-3 mr-1"})," Library"]})]}),e.jsx(ye,{placeholder:"Title",value:f.title,onChange:v=>c(p,y,"title",v.target.value),className:"h-8 text-sm"}),e.jsx(Ms,{placeholder:"Description",value:f.description,onChange:v=>c(p,y,"description",v.target.value),className:"text-sm min-h-[60px] resize-none"})]},y)})})]})]},p)),e.jsx(_s,{open:!!a,onOpenChange:h=>!h&&i(null),children:e.jsxs(bs,{className:"sm:max-w-2xl",children:[e.jsx(js,{children:e.jsx(ws,{children:"Choose a Graphic"})}),e.jsx(Jbt,{onSelect:h=>{a&&(c(a.row,a.col,"image_url",h.image_url),i(null))}})]})})]})}function NVs(){const{toast:s}=Fa(),t=Kt(),[n,r]=N.useState(!1),[a,i]=N.useState(null),[l,o]=N.useState({title:"",description:"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),[c,d]=N.useState(null),[u,h]=N.useState(null),[p,f]=N.useState([]),[y,_]=N.useState([]),[v,j]=N.useState([]),[w,S]=N.useState([]),[A,E]=N.useState([]),[O,D]=N.useState(""),[I,F]=N.useState([]),[z,H]=N.useState(!1),{data:Z,isLoading:Y}=dt({queryKey:["admin-newsletters"],queryFn:async()=>{const{data:Me,error:Pe}=await q.from("newsletter_content").select("*").order("publish_date",{ascending:!1});if(Pe)throw Pe;return Me}}),W=yt({mutationFn:async Me=>{const{data:Pe,error:Re}=await q.from("newsletter_content").insert({title:Me.title,description:Me.description||null,preview_image_url:Me.preview_image_url,publish_date:Me.publish_date,is_published:Me.is_published,content_blocks:Me.content_blocks,html_code:Me.html_code}).select().single();if(Re)throw Re;return Pe},onSuccess:async Me=>{await oe(Me.id),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter created successfully"}),Me.is_published&&Tbs(Me.title,Me.id),me()},onError:Me=>{s({title:"Error creating newsletter",description:Me.message,variant:"destructive"})}}),ee=yt({mutationFn:async Me=>{const{error:Pe}=await q.from("newsletter_content").update({title:Me.title,description:Me.description||null,preview_image_url:Me.preview_image_url,publish_date:Me.publish_date,is_published:Me.is_published,content_blocks:Me.content_blocks,html_code:Me.html_code}).eq("id",Me.id);if(Pe)throw Pe;return Me.id},onSuccess:async Me=>{await oe(Me),t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter updated successfully"}),me()},onError:Me=>{s({title:"Error updating newsletter",description:Me.message,variant:"destructive"})}}),se=yt({mutationFn:async Me=>{const{error:Pe}=await q.from("newsletter_content").delete().eq("id",Me);if(Pe)throw Pe},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-newsletters"]}),s({title:"Newsletter deleted successfully"})},onError:Me=>{s({title:"Error deleting newsletter",description:Me.message,variant:"destructive"})}}),oe=async Me=>{await q.from("newsletter_drive_links").delete().eq("newsletter_id",Me),await q.from("newsletter_pdfs").delete().eq("newsletter_id",Me),await q.from("newsletter_videos").delete().eq("newsletter_id",Me),await q.from("newsletter_canva_links").delete().eq("newsletter_id",Me);for(const Pe of I){const Re=`${Me}/${Date.now()}-${Pe.file.name}`,{error:Ae}=await q.storage.from("newsletter-content").upload(Re,Pe.file);if(!Ae){const{data:Be}=q.storage.from("newsletter-content").getPublicUrl(Re);y.push({name:Pe.name,file_url:Be.publicUrl,file_size:Pe.file.size,sort_order:y.length})}}p.length>0&&await q.from("newsletter_drive_links").insert(p.map((Pe,Re)=>({newsletter_id:Me,title:Pe.title,drive_url:Pe.drive_url,sort_order:Re}))),y.length>0&&await q.from("newsletter_pdfs").insert(y.map((Pe,Re)=>({newsletter_id:Me,name:Pe.name,file_url:Pe.file_url,file_size:Pe.file_size||null,sort_order:Re}))),v.length>0&&await q.from("newsletter_videos").insert(v.map((Pe,Re)=>({newsletter_id:Me,title:Pe.title,video_url:Pe.video_url,sort_order:Re}))),w.length>0&&await q.from("newsletter_canva_links").insert(w.map((Pe,Re)=>({newsletter_id:Me,title:Pe.title,canva_share_link:Pe.canva_share_link,sort_order:Re})))},he=async Me=>{i(Me),o({title:Me.title,description:Me.description||"",publish_date:Ss(new Date(Me.publish_date),"yyyy-MM-dd'T'HH:mm"),is_published:Me.is_published}),h(Me.preview_image_url),E(Me.content_blocks||[]),D(Me.html_code||"");const[Pe,Re,Ae,Be]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",Me.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",Me.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",Me.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",Me.id).order("sort_order")]);f(Pe.data||[]),_(Re.data||[]),j(Ae.data||[]),S(Be.data||[]),F([]),r(!0)},ce=async Me=>{const[Pe,Re,Ae,Be]=await Promise.all([q.from("newsletter_drive_links").select("*").eq("newsletter_id",Me.id).order("sort_order"),q.from("newsletter_pdfs").select("*").eq("newsletter_id",Me.id).order("sort_order"),q.from("newsletter_videos").select("*").eq("newsletter_id",Me.id).order("sort_order"),q.from("newsletter_canva_links").select("*").eq("newsletter_id",Me.id).order("sort_order")]);i(null),o({title:`${Me.title} (Copy)`,description:Me.description||"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),h(Me.preview_image_url),E(Me.content_blocks||[]),D(Me.html_code||""),f((Pe.data||[]).map(({id:we,...Je})=>Je)),_((Re.data||[]).map(({id:we,...Je})=>Je)),j((Ae.data||[]).map(({id:we,...Je})=>Je)),S((Be.data||[]).map(({id:we,...Je})=>Je)),F([]),r(!0)},me=()=>{r(!1),i(null),o({title:"",description:"",publish_date:Ss(new Date,"yyyy-MM-dd'T'HH:mm"),is_published:!1}),d(null),h(null),f([]),_([]),j([]),S([]),E([]),D(""),F([])},le=async Me=>{var Re;const Pe=(Re=Me.target.files)==null?void 0:Re[0];Pe&&(d(Pe),h(URL.createObjectURL(Pe)))},ve=async()=>{if(!l.title){s({title:"Title is required",variant:"destructive"});return}H(!0);let Me=u;if(c){const Pe=`previews/${Date.now()}-${c.name}`,{error:Re}=await q.storage.from("newsletter-content").upload(Pe,c);if(!Re){const{data:Ae}=q.storage.from("newsletter-content").getPublicUrl(Pe);Me=Ae.publicUrl}}a?ee.mutate({id:a.id,...l,preview_image_url:Me,content_blocks:A,html_code:O||null}):W.mutate({...l,preview_image_url:Me,content_blocks:A,html_code:O||null}),H(!1)},ge=()=>f([...p,{title:"",drive_url:"",sort_order:p.length}]),Te=()=>j([...v,{title:"",video_url:"",sort_order:v.length}]),Ie=()=>S([...w,{title:"",canva_share_link:"",sort_order:w.length}]),Ce=Me=>{const Pe=Me.target.files;if(!Pe)return;const Re=Array.from(Pe).map(Ae=>({file:Ae,name:Ae.name.replace(/\.[^/.]+$/,"")}));F([...I,...Re])};return e.jsx(Cs,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Newsletter Content",description:"Manage monthly newsletter templates and resources"}),e.jsxs("div",{className:"flex flex-col sm:flex-row justify-between items-start sm:items-center gap-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(Z==null?void 0:Z.length)||0})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(Z==null?void 0:Z.filter(Me=>Me.is_published).length)||0})})]})]}),e.jsxs(_s,{open:n,onOpenChange:Me=>!Me&&me(),children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{onClick:()=>r(!0),children:[e.jsx(Is,{className:"mr-2 h-4 w-4"})," Add Newsletter"]})}),e.jsxs(bs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{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(ne,{children:"Title *"}),e.jsx(ye,{value:l.title,onChange:Me=>o({...l,title:Me.target.value}),placeholder:"Newsletter title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Publish Date"}),e.jsx(ye,{type:"datetime-local",value:l.publish_date,onChange:Me=>o({...l,publish_date:Me.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:l.description,onChange:Me=>o({...l,description:Me}),placeholder:"Newsletter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Preview Image"}),e.jsxs("div",{className:"flex items-center gap-4",children:[u&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:u,alt:"Preview",className:"h-20 w-32 object-cover rounded-md"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute -top-2 -right-2 h-5 w-5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>{d(null),h(null)},children:e.jsx($n,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx(ye,{type:"file",accept:"image/*",onChange:le,className:"hidden",id:"preview-upload"}),e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("label",{htmlFor:"preview-upload",className:"cursor-pointer",children:[e.jsx(_a,{className:"mr-2 h-4 w-4"})," Upload Image"]})})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:l.is_published,onCheckedChange:Me=>o({...l,is_published:Me})}),e.jsx(ne,{children:"Published"})]}),e.jsx(jVs,{rows:A,onChange:E}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{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:O,onChange:Me=>D(Me.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(ne,{className:"text-base font-medium",children:"Canva Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Ie,children:[e.jsx(Is,{className:"mr-1 h-3 w-3"})," Add Canva Link"]})]}),w.map((Me,Pe)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Link title",value:Me.title,onChange:Re=>{const Ae=[...w];Ae[Pe].title=Re.target.value,S(Ae)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Canva share link",value:Me.canva_share_link,onChange:Re=>{const Ae=[...w];Ae[Pe].canva_share_link=Re.target.value,S(Ae)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>S(w.filter((Re,Ae)=>Ae!==Pe)),children:e.jsx($n,{className:"h-4 w-4"})})]},Pe))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-base font-medium",children:"Google Drive Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:ge,children:[e.jsx(Is,{className:"mr-1 h-3 w-3"})," Add Link"]})]}),p.map((Me,Pe)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Link title",value:Me.title,onChange:Re=>{const Ae=[...p];Ae[Pe].title=Re.target.value,f(Ae)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Google Drive URL",value:Me.drive_url,onChange:Re=>{const Ae=[...p];Ae[Pe].drive_url=Re.target.value,f(Ae)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>f(p.filter((Re,Ae)=>Ae!==Pe)),children:e.jsx($n,{className:"h-4 w-4"})})]},Pe))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-base font-medium",children:"PDF Files"}),e.jsxs("div",{children:[e.jsx(ye,{type:"file",accept:".pdf",multiple:!0,onChange:Ce,className:"hidden",id:"pdf-upload"}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("label",{htmlFor:"pdf-upload",className:"cursor-pointer",children:[e.jsx(_a,{className:"mr-1 h-3 w-3"})," Upload PDF"]})})]})]}),y.map((Me,Pe)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(br,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"flex-1 text-sm",children:Me.name}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>_(y.filter((Re,Ae)=>Ae!==Pe)),children:e.jsx($n,{className:"h-4 w-4"})})]},`existing-${Pe}`)),I.map((Me,Pe)=>e.jsxs("div",{className:"flex gap-2 items-center bg-muted/50 p-2 rounded",children:[e.jsx(br,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:Me.name,onChange:Re=>{const Ae=[...I];Ae[Pe].name=Re.target.value,F(Ae)},className:"flex-1 h-8",placeholder:"PDF name"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"(new)"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>F(I.filter((Re,Ae)=>Ae!==Pe)),children:e.jsx($n,{className:"h-4 w-4"})})]},`pending-${Pe}`))]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-base font-medium",children:"Video Links"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:Te,children:[e.jsx(Is,{className:"mr-1 h-3 w-3"})," Add Video"]})]}),v.map((Me,Pe)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{placeholder:"Video title",value:Me.title,onChange:Re=>{const Ae=[...v];Ae[Pe].title=Re.target.value,j(Ae)},className:"w-1/3"}),e.jsx(ye,{placeholder:"Video URL",value:Me.video_url,onChange:Re=>{const Ae=[...v];Ae[Pe].video_url=Re.target.value,j(Ae)},className:"flex-1"}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>j(v.filter((Re,Ae)=>Ae!==Pe)),children:e.jsx($n,{className:"h-4 w-4"})})]},Pe))]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:me,children:"Cancel"}),e.jsx(B,{onClick:ve,disabled:z||W.isPending||ee.isPending,children:z?"Uploading...":a?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:Y?e.jsx(Hs,{children:e.jsx(ht,{colSpan:4,className:"text-center py-8",children:"Loading..."})}):(Z==null?void 0:Z.length)===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:4,className:"text-center py-8 text-muted-foreground",children:"No newsletters yet. Create your first one!"})}):Z==null?void 0:Z.map(Me=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[Me.preview_image_url?e.jsx("img",{src:Me.preview_image_url,alt:Me.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(br,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Me.title}),Me.description&&e.jsx("div",{className:"text-sm text-muted-foreground line-clamp-1",children:Me.description.replace(/<[^>]*>/g,"")})]})]})}),e.jsx(ht,{children:Ss(new Date(Me.publish_date),"MMM d, yyyy")}),e.jsx(ht,{children:e.jsx("span",{className:`inline-flex items-center px-2 py-1 rounded-full text-xs font-medium ${Me.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:Me.is_published?"Published":"Draft"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>he(Me),title:"Edit",children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ce(Me),title:"Duplicate",children:e.jsx(Zr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",title:"Delete",onClick:()=>{confirm("Are you sure you want to delete this newsletter?")&&se.mutate(Me.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},Me.id))})]})})})]})})}const kVs=["Headers","Footers","Seasonal","Holidays","Market Updates","Just Sold","Just Listed","Open House","Buyer Tips","Seller Tips","Testimonials","CTAs & Buttons","Dividers","General"];function SVs(){const s=Kt(),t=N.useRef(null),[n,r]=N.useState(""),[a,i]=N.useState("all"),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),{data:y=[],isLoading:_}=dt({queryKey:["admin-newsletter-graphics"],queryFn:async()=>{const{data:H,error:Z}=await q.from("newsletter_graphics").select("*").order("is_featured",{ascending:!1}).order("created_at",{ascending:!1});if(Z)throw Z;return H||[]}}),v=N.useMemo(()=>{const H=new Set(kVs);return y.forEach(Z=>H.add(Z.category)),Array.from(H).sort()},[y]),j=N.useMemo(()=>{const H=n.trim().toLowerCase();return y.filter(Z=>a!=="all"&&Z.category!==a?!1:H?Z.title.toLowerCase().includes(H)||(Z.description||"").toLowerCase().includes(H)||Z.tags.some(Y=>Y.toLowerCase().includes(H)):!0)},[y,n,a]),w=()=>{f({title:"",description:"",image_url:"",category:"General",tags:"",is_active:!0,is_featured:!1}),o(null)},S=()=>{w(),d(!0)},A=H=>{o(H),f({title:H.title,description:H.description||"",image_url:H.image_url,category:H.category,tags:H.tags.join(", "),is_active:H.is_active,is_featured:H.is_featured}),d(!0)},E=async H=>{var Z;if(!H.type.startsWith("image/")){ae.error("Please choose an image file");return}if(H.size>15*1024*1024){ae.error("Image must be under 15MB");return}h(!0);try{const Y=((Z=H.name.split(".").pop())==null?void 0:Z.toLowerCase())||"png",W=`graphics-library/${Date.now()}-${Math.random().toString(36).slice(2,8)}.${Y}`,{error:ee}=await q.storage.from("newsletter-content").upload(W,H,{cacheControl:"31536000",upsert:!1,contentType:H.type});if(ee)throw ee;const{data:se}=q.storage.from("newsletter-content").getPublicUrl(W);f(oe=>({...oe,image_url:se.publicUrl,title:oe.title||H.name.replace(/\.[^.]+$/,"").replace(/[-_]/g," ")})),ae.success("Uploaded")}catch(Y){ae.error(Y.message||"Upload failed")}finally{h(!1),t.current&&(t.current.value="")}},O=yt({mutationFn:async()=>{var Y;if(!p.image_url)throw new Error("Please upload an image");if(!p.title.trim())throw new Error("Please add a title");const H=p.tags.split(",").map(W=>W.trim()).filter(Boolean),Z={title:p.title.trim(),description:p.description.trim()||null,image_url:p.image_url,category:p.category||"General",tags:H,is_active:p.is_active,is_featured:p.is_featured};if(l){const{error:W}=await q.from("newsletter_graphics").update(Z).eq("id",l.id);if(W)throw W}else{const{data:W}=await q.auth.getUser(),{error:ee}=await q.from("newsletter_graphics").insert({...Z,created_by:(Y=W.user)==null?void 0:Y.id});if(ee)throw ee}},onSuccess:()=>{ae.success(l?"Updated":"Graphic added to library"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}),d(!1),w()},onError:H=>ae.error(H.message||"Save failed")}),D=yt({mutationFn:async H=>{const{error:Z}=await q.from("newsletter_graphics").delete().eq("id",H);if(Z)throw Z},onSuccess:()=>{ae.success("Deleted"),s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]})},onError:H=>ae.error(H.message||"Delete failed")}),I=async H=>{const{error:Z}=await q.from("newsletter_graphics").update({is_active:!H.is_active}).eq("id",H.id);Z?ae.error(Z.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},F=async H=>{const{error:Z}=await q.from("newsletter_graphics").update({is_featured:!H.is_featured}).eq("id",H.id);Z?ae.error(Z.message):(s.invalidateQueries({queryKey:["admin-newsletter-graphics"]}),s.invalidateQueries({queryKey:["newsletter-graphics-picker"]}))},z=H=>{navigator.clipboard.writeText(H),ae.success("URL copied")};return e.jsxs(Cs,{children:[e.jsxs("div",{className:"p-4 md:p-6 max-w-7xl mx-auto space-y-5",children:[e.jsx(Bd,{title:"Newsletter Graphics Library",description:"Upload branded graphics agents can drop into their newsletters and email campaigns."}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex flex-col md:flex-row gap-3 md:items-center",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:n,onChange:H=>r(H.target.value),placeholder:"Search graphics by title, tag, description...",className:"pl-9"})]}),e.jsxs(us,{value:a,onValueChange:i,children:[e.jsx(ls,{className:"w-full md:w-56",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All categories"}),v.map(H=>e.jsx(Ze,{value:H,children:H},H))]})]}),e.jsxs(B,{onClick:S,className:"gap-1.5 whitespace-nowrap",children:[e.jsx(ty,{className:"h-4 w-4"})," Add Graphic"]})]})}),_?e.jsx("div",{className:"flex justify-center py-16",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-16 text-center",children:[e.jsx(Xo,{className:"h-10 w-10 mx-auto mb-3 text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:y.length===0?"No graphics uploaded yet — add your first one to get started.":"No graphics match your filters."}),y.length===0&&e.jsxs(B,{onClick:S,className:"gap-1.5",children:[e.jsx(ty,{className:"h-4 w-4"})," Upload First Graphic"]})]})}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-4",children:j.map(H=>e.jsxs(fe,{className:`overflow-hidden group ${H.is_active?"":"opacity-60"}`,children:[e.jsxs("div",{className:"aspect-video bg-muted relative overflow-hidden",children:[e.jsx("img",{src:H.image_url,alt:H.title,loading:"lazy",className:"w-full h-full object-cover"}),H.is_featured&&e.jsxs(Ue,{className:"absolute top-2 left-2 gap-0.5 bg-amber-500 hover:bg-amber-500 text-white border-0",children:[e.jsx(oa,{className:"h-3 w-3 fill-current"})," Featured"]}),!H.is_active&&e.jsx(Ue,{variant:"secondary",className:"absolute top-2 right-2",children:"Hidden"})]}),e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm truncate",children:H.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:H.category})]}),H.tags.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1",children:H.tags.slice(0,3).map(Z=>e.jsx(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:Z},Z))}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t",children:[e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>A(H),title:"Edit",children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>F(H),title:H.is_featured?"Unfeature":"Feature",children:e.jsx(oa,{className:`h-3.5 w-3.5 ${H.is_featured?"fill-amber-500 text-amber-500":""}`})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>z(H.image_url),title:"Copy URL",children:e.jsx(Zr,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:H.is_active,onCheckedChange:()=>I(H)}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:()=>{confirm(`Delete "${H.title}"?`)&&D.mutate(H.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]})]},H.id))})]}),e.jsx(_s,{open:c,onOpenChange:d,children:e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:l?"Edit Graphic":"Add New Graphic"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Image"}),e.jsx("input",{ref:t,type:"file",accept:"image/*",className:"hidden",onChange:H=>{var Y;const Z=(Y=H.target.files)==null?void 0:Y[0];Z&&E(Z)}}),p.image_url?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border bg-muted/30 mt-1.5",children:[e.jsx("img",{src:p.image_url,alt:"Preview",className:"w-full max-h-64 object-contain"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>f(H=>({...H,image_url:""})),children:e.jsx($n,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{type:"button",onClick:()=>{var H;return(H=t.current)==null?void 0:H.click()},disabled:u,className:"w-full mt-1.5 rounded-lg border-2 border-dashed border-border hover:border-primary/50 hover:bg-muted/40 transition-colors py-10 text-center disabled:opacity-60",children:u?e.jsxs(e.Fragment,{children:[e.jsx(rs,{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(_a,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm font-medium",children:"Click to upload image"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"PNG, JPG, WEBP, GIF · up to 15MB"})]})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"g-title",children:"Title *"}),e.jsx(ye,{id:"g-title",value:p.title,onChange:H=>f(Z=>({...Z,title:H.target.value})),placeholder:"e.g. Fall Market Update Banner"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"g-desc",children:"Description"}),e.jsx(Ms,{id:"g-desc",value:p.description,onChange:H=>f(Z=>({...Z,description:H.target.value})),placeholder:"Short note about when to use this graphic",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Category"}),e.jsxs(us,{value:p.category,onValueChange:H=>f(Z=>({...Z,category:H})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:v.map(H=>e.jsx(Ze,{value:H,children:H},H))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"g-tags",children:"Tags (comma-separated)"}),e.jsx(ye,{id:"g-tags",value:p.tags,onChange:H=>f(Z=>({...Z,tags:H.target.value})),placeholder:"fall, autumn, banner"})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show at top of the picker"})]}),e.jsx(jn,{checked:p.is_featured,onCheckedChange:H=>f(Z=>({...Z,is_featured:H}))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-md border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents"})]}),e.jsx(jn,{checked:p.is_active,onCheckedChange:H=>f(Z=>({...Z,is_active:H}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>O.mutate(),disabled:O.isPending,children:[O.isPending&&e.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),l?"Save Changes":"Add to Library"]})]})]})})]})}const JYe={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 CVs(){const{user:s}=vs(),{toast:t}=Fa(),n=Ln(),r=Kt(),[a,i]=N.useState(""),[l,o]=N.useState("popular"),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),[y,_]=N.useState(!1),{data:v=[],isLoading:j}=dt({queryKey:["wishlist-items",l,y],queryFn:async()=>{let O=q.from("wishlist_items").select("*");y&&s&&(O=O.eq("user_id",s.id)),l==="latest"?O=O.order("created_at",{ascending:!1}):l==="popular"?O=O.order("vote_count",{ascending:!1}):l==="trending"&&(O=O.order("vote_count",{ascending:!1}));const{data:D,error:I}=await O;if(I)throw I;const F=[...new Set((D==null?void 0:D.map(se=>se.user_id))||[])],{data:z}=await q.from("profiles").select("id, name").in("id",F),H=new Map((z==null?void 0:z.map(se=>[se.id,se]))||[]);let Z=[];if(s){const{data:se}=await q.from("wishlist_votes").select("item_id").eq("user_id",s.id);Z=(se==null?void 0:se.map(oe=>oe.item_id))||[]}const Y=(D==null?void 0:D.map(se=>se.id))||[],{data:W}=await q.from("wishlist_comments").select("item_id").in("item_id",Y),ee=new Map;return W==null||W.forEach(se=>{ee.set(se.item_id,(ee.get(se.item_id)||0)+1)}),D==null?void 0:D.map(se=>{const oe=H.get(se.user_id),he=(oe==null?void 0:oe.name)||"Unknown";return{...se,user_name:he,user_initials:he.split(" ").map(ce=>ce[0]).join("").toUpperCase().slice(0,2),has_voted:Z.includes(se.id),comment_count:ee.get(se.id)||0}})}}),w=yt({mutationFn:async({title:O,description:D})=>{const{error:I}=await q.from("wishlist_items").insert({user_id:s.id,title:O,description:D});if(I)throw I},onSuccess:()=>{r.invalidateQueries({queryKey:["wishlist-items"]}),d(!1),h(""),f(""),t({title:"Idea submitted!",description:"Your idea has been added to the wishlist."})},onError:O=>{t({title:"Error",description:O.message,variant:"destructive"})}}),S=yt({mutationFn:async({itemId:O,hasVoted:D})=>{if(D){const{error:I}=await q.from("wishlist_votes").delete().eq("item_id",O).eq("user_id",s.id);if(I)throw I;return{itemId:O,wasAdded:!1}}else{const{error:I}=await q.from("wishlist_votes").insert({item_id:O,user_id:s.id});if(I)throw I;return{itemId:O,wasAdded:!0}}},onSuccess:async O=>{if(r.invalidateQueries({queryKey:["wishlist-items"]}),O!=null&&O.wasAdded){const D=v.find(F=>F.id===O.itemId),I=((D==null?void 0:D.vote_count)||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:O.itemId,voteCount:I}}).catch(console.error)}},onError:O=>{t({title:"Error",description:O.message,variant:"destructive"})}}),A=v.filter(O=>O.title.toLowerCase().includes(a.toLowerCase())||O.description.toLowerCase().includes(a.toLowerCase())),E=()=>{if(!u.trim()||!p.trim()){t({title:"Error",description:"Please fill in both title and description.",variant:"destructive"});return}w.mutate({title:u.trim(),description:p.trim()})};return e.jsx(Cs,{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(W2,{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(_s,{open:c,onOpenChange:d,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Idea"]})}),e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{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(ne,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",placeholder:"Give your idea a clear title...",value:u,onChange:O=>h(O.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",placeholder:"Describe your idea in detail. What problem does it solve? How would it help agents?",value:p,onChange:O=>f(O.target.value),rows:4})]}),e.jsx(B,{onClick:E,className:"w-full",disabled:w.isPending,children:w.isPending?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Submitting..."]}):"Submit Idea"})]})]})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 mb-6",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search ideas...",value:a,onChange:O=>i(O.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsx(Fr,{value:l,onValueChange:O=>o(O),children:e.jsxs(Rr,{children:[e.jsx(Zt,{value:"popular",children:"Most Popular"}),e.jsx(Zt,{value:"latest",children:"Latest"}),e.jsx(Zt,{value:"trending",children:"Trending"})]})})})]}),e.jsx("div",{className:"flex items-center gap-2 mb-4",children:e.jsx(B,{variant:y?"default":"outline",size:"sm",onClick:()=>_(!y),children:y?"Show All Ideas":"My Ideas"})}),j?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(rs,{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(W2,{className:"h-12 w-12 text-muted-foreground mx-auto mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No ideas yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to submit an idea!"}),e.jsxs(B,{onClick:()=>d(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Idea"]})]}):e.jsx("div",{className:"space-y-3",children:A.map(O=>e.jsx("div",{className:"bg-card border rounded-lg p-4 hover:shadow-md transition-shadow cursor-pointer",onClick:()=>n(`/wishlist/${O.id}`),children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:D=>{D.stopPropagation(),S.mutate({itemId:O.id,hasVoted:O.has_voted||!1})},className:Mt("flex flex-col items-center justify-center min-w-[50px] py-2 px-3 rounded-lg border transition-colors",O.has_voted?"bg-primary/10 border-primary text-primary":"bg-muted/50 border-border hover:bg-muted"),children:[e.jsx(Iu,{className:Mt("h-4 w-4",O.has_voted&&"fill-current")}),e.jsx("span",{className:"text-sm font-semibold",children:O.vote_count})]}),e.jsx(Jr,{className:"h-10 w-10 bg-primary/20",children:e.jsx(ea,{className:"bg-primary/20 text-primary text-sm font-medium",children:O.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:O.title}),e.jsx(Ue,{className:Mt("text-xs",JYe[O.status].color),children:JYe[O.status].label})]}),e.jsx("p",{className:"text-muted-foreground text-sm line-clamp-2",children:O.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:O.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(O.created_at).toLocaleDateString()})]})]}),e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Ai,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:O.comment_count})]})]})},O.id))})]})})}const eZe={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 TVs(){const{itemId:s}=bi(),t=Ln(),{user:n}=vs(),{toast:r}=Fa(),a=Kt(),[i,l]=N.useState(""),{data:o=!1}=dt({queryKey:["user-is-admin",n==null?void 0:n.id],queryFn:async()=>{if(!n)return!1;const{data:v,error:j}=await q.from("user_roles").select("role").eq("user_id",n.id).eq("role","admin").maybeSingle();return!j&&!!v},enabled:!!n}),{data:c,isLoading:d}=dt({queryKey:["wishlist-item",s],queryFn:async()=>{const{data:v,error:j}=await q.from("wishlist_items").select("*").eq("id",s).single();if(j)throw j;const{data:w}=await q.from("profiles").select("name").eq("id",v.user_id).single();let S=!1;if(n){const{data:A}=await q.from("wishlist_votes").select("id").eq("item_id",s).eq("user_id",n.id).maybeSingle();S=!!A}return{...v,user_name:(w==null?void 0:w.name)||"Unknown",user_initials:((w==null?void 0:w.name)||"U").split(" ").map(A=>A[0]).join("").toUpperCase().slice(0,2),has_voted:S}}}),{data:u=[],isLoading:h}=dt({queryKey:["wishlist-comments",s],queryFn:async()=>{const{data:v,error:j}=await q.from("wishlist_comments").select("*").eq("item_id",s).order("created_at",{ascending:!0});if(j)throw j;const w=[...new Set((v==null?void 0:v.map(E=>E.user_id))||[])],{data:S}=await q.from("profiles").select("id, name").in("id",w),A=new Map((S==null?void 0:S.map(E=>[E.id,E]))||[]);return v==null?void 0:v.map(E=>{const O=A.get(E.user_id),D=(O==null?void 0:O.name)||"Unknown";return{...E,user_name:D,user_initials:D.split(" ").map(I=>I[0]).join("").toUpperCase().slice(0,2)}})}}),p=yt({mutationFn:async v=>{if(v){const{error:j}=await q.from("wishlist_votes").delete().eq("item_id",s).eq("user_id",n.id);if(j)throw j;return{wasAdded:!1}}else{const{error:j}=await q.from("wishlist_votes").insert({item_id:s,user_id:n.id});if(j)throw j;return{wasAdded:!0}}},onSuccess:async v=>{if(a.invalidateQueries({queryKey:["wishlist-item",s]}),a.invalidateQueries({queryKey:["wishlist-items"]}),v!=null&&v.wasAdded&&c){const j=(c.vote_count||0)+1;q.functions.invoke("wishlist-notify",{body:{itemId:s,voteCount:j}}).catch(console.error)}},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),f=yt({mutationFn:async v=>{const{error:j}=await q.from("wishlist_comments").insert({item_id:s,user_id:n.id,content:v});if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),l(""),r({title:"Comment added!"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),y=yt({mutationFn:async v=>{const{error:j}=await q.from("wishlist_comments").delete().eq("id",v);if(j)throw j},onSuccess:()=>{a.invalidateQueries({queryKey:["wishlist-comments",s]}),r({title:"Comment deleted"})},onError:v=>{r({title:"Error",description:v.message,variant:"destructive"})}}),_=()=>{i.trim()&&f.mutate(i.trim())};return d?e.jsx(Cs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx(Ws,{className:"h-8 w-32 mb-6"}),e.jsx(Ws,{className:"h-48 w-full mb-6"}),e.jsx(Ws,{className:"h-32 w-full"})]})}):c?e.jsx(Cs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/wishlist"),className:"mb-4",children:[e.jsx(qr,{className:"h-4 w-4 mr-2"}),"Back to Wishlist"]}),e.jsx("div",{className:"bg-card border rounded-lg p-6 mb-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("button",{onClick:()=>p.mutate(c.has_voted),className:Mt("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(Iu,{className:Mt("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(Ue,{className:Mt("text-xs",eZe[c.status].color),children:eZe[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(Jr,{className:"h-6 w-6",children:e.jsx(ea,{className:"bg-primary/20 text-primary text-xs",children:c.user_initials})}),e.jsx("span",{children:c.user_name}),e.jsx("span",{children:"•"}),e.jsx("span",{children:new Date(c.created_at).toLocaleDateString()})]})]})]})}),e.jsxs("div",{className:"bg-card border rounded-lg p-6",children:[e.jsxs("h2",{className:"text-lg font-semibold mb-4",children:["Comments (",u.length,")"]}),e.jsxs("div",{className:"flex gap-3 mb-6",children:[e.jsx(gxe,{placeholder:o?"Share your thoughts... Use # to link templates":"Share your thoughts on this idea...",value:i,onChange:l,minHeight:"60px",mentionFormat:"encoded",enableTemplateMentions:o}),e.jsx(B,{onClick:_,disabled:!i.trim()||f.isPending,size:"icon",className:"h-auto",children:f.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"})})]}),h?e.jsx("div",{className:"space-y-4",children:[1,2].map(v=>e.jsx(Ws,{className:"h-20 w-full"},v))}):u.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No comments yet. Be the first to share your thoughts!"}):e.jsx("div",{className:"space-y-4",children:u.map(v=>e.jsxs("div",{className:"flex gap-3 p-3 bg-muted/30 rounded-lg",children:[e.jsx(Jr,{className:"h-8 w-8",children:e.jsx(ea,{className:"bg-primary/20 text-primary text-xs",children:v.user_initials})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium text-sm",children:v.user_name}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(v.created_at).toLocaleDateString()})]}),e.jsx(CIe,{content:v.content,className:"text-sm text-foreground"})]}),(n==null?void 0:n.id)===v.user_id&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive",onClick:()=>y.mutate(v.id),children:e.jsx(_n,{className:"h-4 w-4"})})]},v.id))})]})]})}):e.jsx(Cs,{title:"Wishlist",children:e.jsxs("div",{className:"max-w-3xl mx-auto text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Item not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/wishlist"),children:"Go back to Wishlist"})]})})}const tZe={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"}},sZe=["open","under_review","planned","in_progress","launched","declined"];function EVs(){const{toast:s}=Fa(),t=Ln(),n=Kt(),[r,a]=N.useState(""),[i,l]=N.useState("all"),[o,c]=N.useState(!1),[d,u]=N.useState(null),{data:h=[],isLoading:p}=dt({queryKey:["admin-wishlist-items"],queryFn:async()=>{const{data:j,error:w}=await q.from("wishlist_items").select("*").order("vote_count",{ascending:!1});if(w)throw w;const S=[...new Set((j==null?void 0:j.map(F=>F.user_id))||[])],{data:A}=await q.from("profiles").select("id, name, email").in("id",S),E=new Map((A==null?void 0:A.map(F=>[F.id,F]))||[]),O=(j==null?void 0:j.map(F=>F.id))||[],{data:D}=await q.from("wishlist_comments").select("item_id").in("item_id",O),I=new Map;return D==null||D.forEach(F=>{I.set(F.item_id,(I.get(F.item_id)||0)+1)}),j==null?void 0:j.map(F=>{const z=E.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:I.get(F.id)||0}})}}),f=yt({mutationFn:async({itemId:j,status:w})=>{const{error:S}=await q.from("wishlist_items").update({status:w}).eq("id",j);if(S)throw S},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),s({title:"Status updated!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),y=yt({mutationFn:async j=>{const{error:w}=await q.from("wishlist_items").delete().eq("id",j);if(w)throw w},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-wishlist-items"]}),c(!1),u(null),s({title:"Item deleted!"})},onError:j=>{s({title:"Error",description:j.message,variant:"destructive"})}}),_=h.filter(j=>{const w=j.title.toLowerCase().includes(r.toLowerCase())||j.description.toLowerCase().includes(r.toLowerCase())||j.user_name.toLowerCase().includes(r.toLowerCase()),S=i==="all"||j.status===i;return w&&S}),v={total:h.length,open:h.filter(j=>j.status==="open").length,inProgress:h.filter(j=>j.status==="in_progress").length,launched:h.filter(j=>j.status==="launched").length,highVotes:h.filter(j=>j.vote_count>=10).length};return e.jsx(Cs,{title:"Admin - Wishlist",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/admin"),children:e.jsx(qr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Wishlist Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Review and manage community ideas"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-4",children:[e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Total Ideas"}),e.jsx("p",{className:"text-2xl font-bold",children:v.total})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Open"}),e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:v.open})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"In Progress"}),e.jsx("p",{className:"text-2xl font-bold text-orange-600",children:v.inProgress})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Launched"}),e.jsx("p",{className:"text-2xl font-bold text-green-600",children:v.launched})]}),e.jsxs("div",{className:"bg-card border rounded-lg p-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"10+ Votes"}),e.jsx("p",{className:"text-2xl font-bold text-primary",children:v.highVotes})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search ideas, users...",value:r,onChange:j=>a(j.target.value),className:"pl-10"})]}),e.jsxs(us,{value:i,onValueChange:j=>l(j),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Filter by status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),sZe.map(j=>e.jsx(Ze,{value:j,children:tZe[j].label},j))]})]})]}),p?e.jsx("div",{className:"space-y-2",children:[1,2,3,4,5].map(j=>e.jsx(Ws,{className:"h-16 w-full"},j))}):e.jsx("div",{className:"bg-card border rounded-lg overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-[60px]",children:"Votes"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Submitted By"}),e.jsx(Tt,{className:"hidden sm:table-cell",children:"Comments"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-[100px]",children:"Actions"})]})}),e.jsx(da,{children:_.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No items found"})}):_.map(j=>e.jsxs(Hs,{className:Mt(j.vote_count>=10&&"bg-primary/5"),children:[e.jsx(ht,{children:e.jsx(Ue,{variant:j.vote_count>=10?"default":"secondary",children:j.vote_count})}),e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium line-clamp-1",children:j.title}),e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:j.description})]})}),e.jsx(ht,{className:"hidden md:table-cell",children:e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:j.user_name}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j.user_email})]})}),e.jsx(ht,{className:"hidden sm:table-cell",children:j.comment_count}),e.jsx(ht,{children:e.jsxs(us,{value:j.status,onValueChange:w=>f.mutate({itemId:j.id,status:w}),children:[e.jsx(ls,{className:"w-[140px] h-8",children:e.jsx(hs,{})}),e.jsx(cs,{children:sZe.map(w=>e.jsx(Ze,{value:w,children:tZe[w].label},w))})]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>window.open(`/wishlist/${j.id}`,"_blank"),children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>{u(j.id),c(!0)},children:e.jsx(_n,{className:"h-4 w-4"})})]})})]},j.id))})]})}),e.jsx(_s,{open:o,onOpenChange:c,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Delete Wishlist Item"})}),e.jsx("p",{className:"text-muted-foreground",children:"Are you sure you want to delete this idea? This will also delete all votes and comments."}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>d&&y.mutate(d),disabled:y.isPending,children:y.isPending?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Deleting..."]}):"Delete"})]})]})})]})})}function AVs(){const{user:s}=vs(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState(""),[E,O]=N.useState(""),[D,I]=N.useState(!1),[F,z]=N.useState(""),[H,Z]=N.useState("once"),[Y,W]=N.useState([]),[ee,se]=N.useState([]),[oe,he]=N.useState(!1),[ce,me]=N.useState(!1),[le,ve]=N.useState([]),[ge,Te]=N.useState({total:0,dismissed:0});N.useEffect(()=>{Ie()},[]);const Ie=async()=>{const{data:at,error:Ye}=await q.from("levelup_briefs").select("*").order("created_at",{ascending:!1});Ye?(ae.error("Failed to fetch briefs"),console.error(Ye)):n(at||[]),a(!1)},Ce=()=>{y(""),v(""),w(""),A(""),O(""),I(!1),z(new Date().toISOString().slice(0,16)),Z("once"),W([]),se([]),c(null)},Me=()=>{Ce(),l(!0)},Pe=async at=>{c(at),y(at.title),v(at.description||""),w(at.video_url||""),A(at.graphic_url||""),O(at.graphic_link_url||""),I(at.is_published),z(at.publish_date.slice(0,16)),Z(at.show_frequency);const{data:Ye}=await q.from("levelup_brief_links").select("*").eq("brief_id",at.id).order("sort_order");W((Ye==null?void 0:Ye.map(_t=>({title:_t.title,url:_t.url})))||[]);const{data:ut}=await q.from("levelup_brief_polls").select("*").eq("brief_id",at.id).order("sort_order");if(ut){const _t=[];for(const bt of ut){const{data:$t}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",bt.id).order("sort_order");_t.push({question:bt.question,poll_type:bt.poll_type,options:($t==null?void 0:$t.map(Yt=>Yt.option_text))||[]})}se(_t)}l(!0)},Re=async at=>{var ut;const Ye=(ut=at.target.files)==null?void 0:ut[0];if(Ye){he(!0);try{const _t=await q.functions.invoke("bunny-upload",{body:{action:"create",title:Ye.name.replace(/\.[^/.]+$/,"")}});if(_t.error)throw _t.error;const{videoId:bt,libraryId:$t}=_t.data,Yt=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:bt}});if(Yt.error)throw Yt.error;const{uploadUrl:Ds,apiKey:Ls}=Yt.data,xs=new XMLHttpRequest;await new Promise((Jt,gt)=>{xs.upload.addEventListener("progress",zt=>{if(zt.lengthComputable){const As=Math.round(zt.loaded/zt.total*100);console.log("Upload progress:",As)}}),xs.addEventListener("load",()=>{xs.status>=200&&xs.status<300?Jt():gt(new Error(`Upload failed with status ${xs.status}`))}),xs.addEventListener("error",()=>gt(new Error("Upload failed"))),xs.open("PUT",Ds),xs.setRequestHeader("AccessKey",Ls),xs.send(Ye)});const Lt=`https://player.mediadelivery.net/embed/${$t}/${bt}`;w(Lt),ae.success("Video uploaded successfully! It may take a few minutes to process.")}catch(_t){console.error("Upload error:",_t),ae.error("Failed to upload video")}finally{he(!1)}}},Ae=async()=>{if(!f.trim()){ae.error("Title is required");return}try{let at;if(o){const{error:Ye}=await q.from("levelup_briefs").update({title:f,description:_||null,video_url:j||null,graphic_url:S||null,graphic_link_url:E||null,is_published:D,publish_date:F,show_frequency:H}).eq("id",o.id);if(Ye)throw Ye;at=o.id,await q.from("levelup_brief_links").delete().eq("brief_id",at);const{data:ut}=await q.from("levelup_brief_polls").select("id").eq("brief_id",at);if(ut)for(const _t of ut)await q.from("levelup_brief_poll_options").delete().eq("poll_id",_t.id);await q.from("levelup_brief_polls").delete().eq("brief_id",at)}else{const{data:Ye,error:ut}=await q.from("levelup_briefs").insert({title:f,description:_||null,video_url:j||null,graphic_url:S||null,graphic_link_url:E||null,is_published:D,publish_date:F,show_frequency:H,created_by:s==null?void 0:s.id}).select().single();if(ut)throw ut;at=Ye.id}if(Y.length>0){const Ye=Y.map((ut,_t)=>({brief_id:at,title:ut.title,url:ut.url,sort_order:_t}));await q.from("levelup_brief_links").insert(Ye)}for(let Ye=0;Ye0){const $t=ut.options.map((Yt,Ds)=>({poll_id:_t.id,option_text:Yt,sort_order:Ds}));await q.from("levelup_brief_poll_options").insert($t)}}ae.success(o?"Brief updated":"Brief created"),l(!1),Ce(),Ie()}catch(at){console.error("Error saving brief:",at),ae.error("Failed to save brief")}},Be=async at=>{if(confirm("Are you sure you want to delete this brief?"))try{const{error:Ye}=await q.from("levelup_briefs").delete().eq("id",at);if(Ye)throw Ye;ae.success("Brief deleted"),Ie()}catch(Ye){console.error("Error deleting brief:",Ye),ae.error("Failed to delete brief")}},we=async at=>{p(at);const{count:Ye}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",at.id),{count:ut}=await q.from("levelup_brief_views").select("*",{count:"exact",head:!0}).eq("brief_id",at.id).not("dismissed_at","is",null);Te({total:Ye||0,dismissed:ut||0});const{data:_t}=await q.from("levelup_brief_polls").select("*").eq("brief_id",at.id).order("sort_order");if(_t){const bt=[];for(const $t of _t){const{data:Yt}=await q.from("levelup_brief_poll_options").select("*").eq("poll_id",$t.id).order("sort_order"),{data:Ds}=await q.from("levelup_brief_poll_responses").select("option_id, user_id").eq("poll_id",$t.id),Ls=[...new Set((Ds==null?void 0:Ds.map(zt=>zt.user_id))||[])];let xs={};if(Ls.length>0){const{data:zt}=await q.from("profiles").select("id, name, email").in("id",Ls);zt&&zt.forEach(As=>{xs[As.id]=As.name||As.email||"Unknown"})}const Lt=(Ds||[]).map(zt=>({optionId:zt.option_id,userName:xs[zt.user_id]||"Unknown",userId:zt.user_id})),Jt={};let gt=0;Yt&&Yt.forEach(zt=>{const As=(Ds==null?void 0:Ds.filter(Xt=>Xt.option_id===zt.id).length)||0;Jt[zt.id]=As,gt+=As}),bt.push({...$t,options:Yt||[],results:Jt,respondents:Lt,totalResponses:$t.poll_type==="single"?new Set(Ds==null?void 0:Ds.map(zt=>zt.user_id)).size:gt})}ve(bt)}u(!0)},Je=()=>{W([...Y,{title:"",url:""}])},ke=(at,Ye,ut)=>{const _t=[...Y];_t[at][Ye]=ut,W(_t)},it=at=>{W(Y.filter((Ye,ut)=>ut!==at))},je=()=>{se([...ee,{question:"",poll_type:"single",options:["",""]}])},He=(at,Ye)=>{const ut=[...ee];ut[at].question=Ye,se(ut)},$e=(at,Ye)=>{const ut=[...ee];ut[at].poll_type=Ye,se(ut)},Ke=at=>{const Ye=[...ee];Ye[at].options.push(""),se(Ye)},Ge=(at,Ye,ut)=>{const _t=[...ee];_t[at].options[Ye]=ut,se(_t)},rt=(at,Ye)=>{const ut=[...ee];ut[at].options=ut[at].options.filter((_t,bt)=>bt!==Ye),se(ut)},tt=at=>{se(ee.filter((Ye,ut)=>ut!==at))};return e.jsxs(Cs,{title:"The LevelUp Brief",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"The LevelUp Brief",description:"Create engaging popup briefs for your agents",children:e.jsxs(B,{onClick:Me,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create Brief"]})}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Frequency"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:r?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8",children:"Loading..."})}):t.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No briefs created yet"})}):t.map(at=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:at.title}),e.jsx(ht,{children:e.jsx(Ue,{variant:at.is_published?"default":"secondary",children:at.is_published?"Published":"Draft"})}),e.jsx(ht,{className:"capitalize",children:at.show_frequency.replace("_"," ")}),e.jsx(ht,{children:Ss(new Date(at.publish_date),"MMM d, yyyy h:mm a")}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>we(at),children:e.jsx(_o,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Pe(at),children:e.jsx(wu,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Be(at.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},at.id))})]})})})]}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:o?"Edit Brief":"Create New Brief"})}),e.jsxs(Fr,{defaultValue:"content",className:"w-full",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"media",children:"Media"}),e.jsx(Zt,{value:"links",children:"Links"}),e.jsx(Zt,{value:"polls",children:"Polls"})]}),e.jsxs(is,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Title *"}),e.jsx(ye,{value:f,onChange:at=>y(at.target.value),placeholder:"What's happening at LevelUp..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:_,onChange:at=>v(at),placeholder:"Brief overview for agents...",minHeight:"120px"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Publish Date"}),e.jsx(ye,{type:"datetime-local",value:F,onChange:at=>z(at.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Show Frequency"}),e.jsxs(us,{value:H,onValueChange:Z,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"once",children:"Once (until dismissed)"}),e.jsx(Ze,{value:"every_login",children:"Every login"}),e.jsx(Ze,{value:"daily",children:"Daily"})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(jn,{checked:D,onCheckedChange:I}),e.jsx(ne,{children:"Publish immediately"})]})]}),e.jsxs(is,{value:"media",className:"space-y-6 mt-4",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Video (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Upload Video to Bunny.net"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ye,{type:"file",accept:"video/*",onChange:Re,disabled:oe})}),oe&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Or paste embed URL"}),e.jsx(ye,{value:j,onChange:at=>w(at.target.value),placeholder:"https://iframe.mediadelivery.net/embed/..."})]}),j&&e.jsx("div",{className:"aspect-video rounded-lg overflow-hidden bg-muted",children:e.jsx("iframe",{src:j,className:"w-full h-full",allow:"autoplay; fullscreen",allowFullScreen:!0})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-4",children:[e.jsx("h4",{className:"font-semibold text-sm text-foreground",children:"Graphic / Image (optional)"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Upload Image"}),e.jsx("div",{className:"flex gap-2",children:e.jsx(ye,{type:"file",accept:"image/*",onChange:async at=>{var ut;const Ye=(ut=at.target.files)==null?void 0:ut[0];if(Ye){me(!0);try{const _t=Ye.name.split(".").pop(),bt=`brief-graphics/${Date.now()}.${_t}`,{error:$t}=await q.storage.from("banner-images").upload(bt,Ye,{upsert:!0});if($t)throw $t;const{data:Yt}=q.storage.from("banner-images").getPublicUrl(bt);A(Yt.publicUrl),ae.success("Image uploaded!")}catch(_t){console.error(_t),ae.error("Failed to upload image")}finally{me(!1)}}},disabled:ce})}),ce&&e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Or paste Image URL"}),e.jsx(ye,{value:S,onChange:at=>A(at.target.value),placeholder:"https://example.com/image.png"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Click-through Link (optional)"}),e.jsx(ye,{value:E,onChange:at=>O(at.target.value),placeholder:"https://example.com/landing-page"})]}),S&&e.jsx("div",{className:"rounded-lg overflow-hidden bg-muted border",children:e.jsx("img",{src:S,alt:"Brief graphic preview",className:"w-full object-contain max-h-64"})})]})]}),e.jsxs(is,{value:"links",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ne,{children:"Quick Links"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Je,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Link"]})]}),Y.map((at,Ye)=>e.jsxs("div",{className:"flex gap-2 items-start",children:[e.jsx(ye,{value:at.title,onChange:ut=>ke(Ye,"title",ut.target.value),placeholder:"Link title",className:"flex-1"}),e.jsx(ye,{value:at.url,onChange:ut=>ke(Ye,"url",ut.target.value),placeholder:"https://...",className:"flex-[2]"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>it(Ye),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]},Ye)),Y.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No links added yet"})]}),e.jsxs(is,{value:"polls",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ne,{children:"Polls"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:je,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Poll"]})]}),ee.map((at,Ye)=>e.jsx(fe,{className:"p-4",children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(ye,{value:at.question,onChange:ut=>He(Ye,ut.target.value),placeholder:"Poll question...",className:"flex-1 mr-2"}),e.jsxs(us,{value:at.poll_type,onValueChange:ut=>$e(Ye,ut),children:[e.jsx(ls,{className:"w-32",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"single",children:"Single"}),e.jsx(Ze,{value:"multi",children:"Multi-select"})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>tt(Ye),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]}),e.jsxs("div",{className:"space-y-2 pl-4",children:[at.options.map((ut,_t)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:ut,onChange:bt=>Ge(Ye,_t,bt.target.value),placeholder:`Option ${_t+1}`}),at.options.length>2&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>rt(Ye,_t),children:e.jsx(_n,{className:"h-4 w-4 text-muted-foreground"})})]},_t)),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>Ke(Ye),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Option"]})]})]})},Ye)),ee.length===0&&e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls added yet"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:Ae,children:o?"Update Brief":"Create Brief"})]})]})}),e.jsx(_s,{open:d,onOpenChange:u,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(ws,{children:["Results: ",h==null?void 0:h.title]})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Views"})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-2xl font-bold",children:ge.total})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Dismissed"})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-2xl font-bold",children:ge.dismissed})})]})]}),le.length>0?e.jsxs("div",{className:"space-y-4",children:[e.jsx("h3",{className:"font-semibold",children:"Poll Results"}),le.map(at=>e.jsxs(fe,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-3",children:at.question}),e.jsx("div",{className:"space-y-2",children:at.options.map(Ye=>{const ut=at.results[Ye.id]||0,_t=at.totalResponses>0?Math.round(ut/at.totalResponses*100):0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:Ye.option_text}),e.jsxs("span",{className:"text-muted-foreground",children:[ut," (",_t,"%)"]})]}),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:`${_t}%`}})}),ut>0&&e.jsx("div",{className:"flex flex-wrap gap-1 pt-1",children:(at.respondents||[]).filter(bt=>bt.optionId===Ye.id).map((bt,$t)=>e.jsx(Ue,{variant:"secondary",className:"text-xs font-normal",children:bt.userName},$t))})]},Ye.id)})})]},at.id))]}):e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No polls in this brief"})]})]})})]})}const MVs=()=>{const{user:s}=vs(),{toast:t}=Fa(),n=Kt(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),[d,u]=N.useState(null),[h,p]=N.useState(""),{data:f=[],isLoading:y}=dt({queryKey:["additional-services-admin"],queryFn:async()=>{const{data:E,error:O}=await q.from("additional_services").select("*").order("publish_date",{ascending:!1});if(O)throw O;return E}}),_=yt({mutationFn:async E=>{let O=E.existingImageUrl;if(E.image){const I=E.image.name.split(".").pop(),F=`${Date.now()}-${Math.random().toString(36).substring(7)}.${I}`,{error:z}=await q.storage.from("service-images").upload(F,E.image);if(z)throw z;const{data:H}=q.storage.from("service-images").getPublicUrl(F);O=H.publicUrl}const D={name:E.item.name,description:E.item.description||null,preview_image_url:O,signup_link_url:E.item.signup_link_url,publish_date:E.item.publish_date?new Date(E.item.publish_date).toISOString():new Date().toISOString(),is_published:E.item.is_published,created_by:s==null?void 0:s.id};if(E.itemId){const{error:I}=await q.from("additional_services").update(D).eq("id",E.itemId);if(I)throw I}else{const{error:I}=await q.from("additional_services").insert(D);if(I)throw I}},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:i?"Service updated":"Service created"}),a(!1),j()},onError:E=>{t({title:"Error saving service",description:E.message,variant:"destructive"})}}),v=yt({mutationFn:async E=>{const{error:O}=await q.from("additional_services").delete().eq("id",E);if(O)throw O},onSuccess:()=>{n.invalidateQueries({queryKey:["additional-services-admin"]}),n.invalidateQueries({queryKey:["additional-services"]}),t({title:"Service deleted"})},onError:E=>{t({title:"Error deleting service",description:E.message,variant:"destructive"})}}),j=()=>{c({name:"",description:"",signup_link_url:"",publish_date:new Date().toISOString().split("T")[0],is_published:!1}),u(null),p(""),l(null)},w=E=>{l(E),c({name:E.name,description:E.description||"",signup_link_url:E.signup_link_url,publish_date:E.publish_date?new Date(E.publish_date).toISOString().split("T")[0]:new Date().toISOString().split("T")[0],is_published:E.is_published}),p(E.preview_image_url||""),a(!0)},S=E=>{var D;const O=(D=E.target.files)==null?void 0:D[0];O&&(u(O),p(URL.createObjectURL(O)))},A=E=>{if(E.preventDefault(),!o.name.trim()){t({title:"Name is required",variant:"destructive"});return}if(!o.signup_link_url.trim()){t({title:"Signup link URL is required",variant:"destructive"});return}_.mutate({item:o,image:d,existingImageUrl:(i==null?void 0:i.preview_image_url)||null,itemId:i==null?void 0:i.id})};return e.jsx(Cs,{title:"Manage Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Services"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.length})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Published"})}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:f.filter(E=>E.is_published).length})})]})]}),e.jsxs(_s,{open:r,onOpenChange:E=>{a(E),E||j()},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Service"]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{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(ne,{htmlFor:"name",children:"Name *"}),e.jsx(ye,{id:"name",value:o.name,onChange:E=>c({...o,name:E.target.value}),placeholder:"Enter service name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ab,{content:o.description,onChange:E=>c({...o,description:E}),placeholder:"Enter description",minHeight:"120px"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"signup_link_url",children:"Signup Link URL *"}),e.jsx(ye,{id:"signup_link_url",type:"url",value:o.signup_link_url,onChange:E=>c({...o,signup_link_url:E.target.value}),placeholder:"https://example.com/signup"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"publish_date",children:"Publish Date"}),e.jsx(ye,{id:"publish_date",type:"date",value:o.publish_date,onChange:E=>c({...o,publish_date:E.target.value})})]}),e.jsxs("div",{className:"flex items-center space-x-2",children:[e.jsx(jn,{id:"is_published",checked:o.is_published,onCheckedChange:E=>c({...o,is_published:E})}),e.jsx(ne,{htmlFor:"is_published",children:"Published"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Preview Image"}),h?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:h,alt:"Preview",className:"w-full max-h-48 object-contain rounded-lg border"}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-6 w-6",onClick:()=>{u(null),p("")},children:e.jsx($n,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-4 text-center",children:[e.jsx(Xo,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx(ye,{type:"file",accept:"image/*",onChange:S,className:"cursor-pointer"})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:_.isPending,children:_.isPending?"Saving...":i?"Update":"Create"})]})]})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:y?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:'No services yet. Click "Add Service" to create your first one.'}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-16",children:"Preview"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Signup Link"}),e.jsx(Tt,{children:"Publish Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:f.map(E=>e.jsxs(Hs,{children:[e.jsx(ht,{children:E.preview_image_url?e.jsx("img",{src:E.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(Xo,{className:"h-5 w-5 text-muted-foreground"})})}),e.jsx(ht,{className:"font-medium",children:E.name}),e.jsx(ht,{children:e.jsxs("a",{href:E.signup_link_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline flex items-center gap-1",children:[e.jsx(tr,{className:"h-3 w-3"}),"Link"]})}),e.jsx(ht,{children:new Date(E.publish_date).toLocaleDateString()}),e.jsx(ht,{children:e.jsx(Ue,{variant:E.is_published?"default":"secondary",children:E.is_published?"Published":"Draft"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>w(E),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{confirm("Are you sure you want to delete this service?")&&v.mutate(E.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},E.id))})]})})})]})})};function IVs(){const{toast:s}=Fa(),[t,n]=N.useState([]),[r,a]=N.useState(!0),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""});N.useEffect(()=>{h()},[]);const h=async()=>{try{const{data:v,error:j}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"list"}});if(j)throw j;n(v.coupons||[])}catch(v){console.error("Error fetching coupons:",v),s({title:"Error",description:"Failed to load coupons",variant:"destructive"})}finally{a(!1)}},p=async()=>{if(!d.name){s({title:"Error",description:"Please enter a coupon name",variant:"destructive"});return}if(d.discountType==="percent"&&!d.percentOff){s({title:"Error",description:"Please enter a percent off value",variant:"destructive"});return}if(d.discountType==="amount"&&!d.amountOff){s({title:"Error",description:"Please enter an amount off value",variant:"destructive"});return}if(d.duration==="repeating"&&!d.durationInMonths){s({title:"Error",description:"Please enter duration in months",variant:"destructive"});return}l(!0);try{const v={action:"create",name:d.name,duration:d.duration,promotion_code:d.promotionCode.trim()||void 0};d.discountType==="percent"?v.percent_off=parseFloat(d.percentOff):(v.amount_off=Math.round(parseFloat(d.amountOff)*100),v.currency="usd"),d.duration==="repeating"&&(v.duration_in_months=parseInt(d.durationInMonths));const{data:j,error:w}=await q.functions.invoke("stripe-manage-coupons",{body:v});if(w)throw w;s({title:"Success",description:"Coupon created successfully"}),c(!1),u({name:"",promotionCode:"",discountType:"percent",percentOff:"",amountOff:"",duration:"once",durationInMonths:""}),h()}catch(v){console.error("Error creating coupon:",v),s({title:"Error",description:v.message||"Failed to create coupon",variant:"destructive"})}finally{l(!1)}},f=async v=>{if(confirm("Are you sure you want to delete this coupon?"))try{const{error:j}=await q.functions.invoke("stripe-manage-coupons",{body:{action:"delete",couponId:v}});if(j)throw j;s({title:"Success",description:"Coupon deleted successfully"}),h()}catch(j){console.error("Error deleting coupon:",j),s({title:"Error",description:j.message||"Failed to delete coupon",variant:"destructive"})}},y=v=>v.percent_off?`${v.percent_off}% off`:v.amount_off?`$${(v.amount_off/100).toFixed(2)} off`:"N/A",_=v=>{switch(v.duration){case"once":return"Once";case"forever":return"Forever";case"repeating":return`${v.duration_in_months} months`;default:return v.duration}};return e.jsx(Cs,{title:"Subscription Discounts",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Subscription Discounts",description:"Create and manage discount coupons for subscriptions",children:e.jsxs(_s,{open:o,onOpenChange:c,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Coupon"]})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create New Coupon"}),e.jsx(Jn,{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(ne,{children:"Promotion Code (what users will type)"}),e.jsx(ye,{placeholder:"e.g., BROKERAGE50",value:d.promotionCode,onChange:v=>u({...d,promotionCode:v.target.value.toUpperCase().replace(/[^A-Z0-9]/g,"")}),className:"font-mono uppercase"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Letters and numbers only. This is the code users enter at checkout."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Coupon Name (internal label)"}),e.jsx(ye,{placeholder:"e.g., 50% Off Brokerage Launch",value:d.name,onChange:v=>u({...d,name:v.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Discount Type"}),e.jsxs(us,{value:d.discountType,onValueChange:v=>{const j=v==="amount"&&d.duration==="forever"?"once":d.duration;u({...d,discountType:v,duration:j})},children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"percent",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(QS,{className:"mr-2 h-4 w-4"}),"Percentage Off"]})}),e.jsx(Ze,{value:"amount",children:e.jsxs("span",{className:"flex items-center",children:[e.jsx(Yl,{className:"mr-2 h-4 w-4"}),"Fixed Amount Off"]})})]})]})]}),d.discountType==="percent"?e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Percent Off"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",min:"1",max:"100",placeholder:"20",value:d.percentOff,onChange:v=>u({...d,percentOff:v.target.value})}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Amount Off (USD)"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(ye,{type:"number",min:"1",placeholder:"10.00",className:"pl-7",value:d.amountOff,onChange:v=>u({...d,amountOff:v.target.value})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Duration"}),e.jsxs(us,{value:d.duration,onValueChange:v=>u({...d,duration:v}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"once",children:"Once (first payment only)"}),e.jsx(Ze,{value:"repeating",children:"Multiple months"}),e.jsxs(Ze,{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(ne,{children:"Number of Months"}),e.jsx(ye,{type:"number",min:"1",placeholder:"3",value:d.durationInMonths,onChange:v=>u({...d,durationInMonths:v.target.value})})]}),e.jsx(B,{onClick:p,disabled:i,className:"w-full",children:i?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}),"Creating..."]}):"Create Coupon"})]})]})]})}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Active Coupons"}),e.jsx(Vn,{children:"Share coupon codes with users to give them discounts on subscriptions"})]}),e.jsx(Ee,{children:r?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(rs,{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(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Promo Code"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Discount"}),e.jsx(Tt,{children:"Duration"}),e.jsx(Tt,{children:"Redemptions"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:t.map(v=>{var j;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-mono font-medium",children:((j=v.promotion_codes)==null?void 0:j.length)>0?v.promotion_codes.join(", "):e.jsx("span",{className:"text-muted-foreground text-xs",children:"No promo code"})}),e.jsx(ht,{children:v.name||"-"}),e.jsx(ht,{children:y(v)}),e.jsx(ht,{children:_(v)}),e.jsx(ht,{children:v.times_redeemed}),e.jsx(ht,{children:e.jsx(Ue,{variant:v.valid?"default":"secondary",children:v.valid?"Active":"Inactive"})}),e.jsx(ht,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>f(v.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})})]},v.id)})})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"How to Use Coupons"})}),e.jsxs(Ee,{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{children:"1. Create a coupon above with your desired discount."}),e.jsx("p",{children:'2. Share the coupon code (shown in the "Code" column) with users.'}),e.jsx("p",{children:"3. Users can enter the code during checkout to receive the discount."}),e.jsx("p",{children:"4. Alternatively, you can create a promotion code in Stripe dashboard for public-facing promotions."})]})]})]})})}const nNe={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 PVs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),[l,o]=N.useState(null),{data:c,isLoading:d,refetch:u}=dt({queryKey:["admin-subscriptions"],queryFn:async()=>{const{data:j,error:w}=await q.from("profiles").select(` *, brokerages:brokerage_id (id, name) `).order("created_at",{ascending:!1});if(w)throw w;return j}}),{data:h}=dt({queryKey:["admin-brokerages-subscriptions"],queryFn:async()=>{const{data:j,error:w}=await q.from("brokerages").select("*").order("name");if(w)throw w;return await Promise.all((j||[]).map(async A=>{const{data:E}=await q.from("profiles").select("id, name, email, subscription_status, subscription_product_id").eq("brokerage_id",A.id),{data:O}=await q.from("user_roles").select("user_id").eq("role","brokerage_manager"),D=(O==null?void 0:O.map(z=>z.user_id))||[],I=(E==null?void 0:E.filter(z=>D.includes(z.id)))||[],F=(E==null?void 0:E.length)||0;return{...A,managers:I,agentCount:F}}))}}),{data:p}=dt({queryKey:["admin-website-subscriptions"],queryFn:async()=>{const{data:j,error:w}=await q.from("local_move_subscriptions").select("*").order("created_at",{ascending:!1});if(w)throw w;return j}}),f=j=>{if(j.is_grandfathered)return{status:"Grandfathered",badge:"Legacy",variant:"secondary"};if(j.brokerage_id&&!j.subscription_product_id)return{status:"Brokerage",badge:"Team Member",variant:"outline"};if(j.is_trial&&j.trial_expires_at)return new Date(j.trial_expires_at)>new Date?{status:"Trial",badge:"Active Trial",variant:"default"}:{status:"Trial Expired",badge:"Expired",variant:"destructive"};if(j.subscription_status==="active"||j.subscription_status==="trialing"){const w=nNe[j.subscription_product_id];return{status:(w==null?void 0:w.name)||"Active",badge:j.subscription_status==="trialing"?"Trial":"Active",variant:"default"}}return j.subscription_status==="canceled"||j.subscription_status==="past_due"?{status:"Canceled",badge:"Inactive",variant:"destructive"}:{status:"None",badge:"No Subscription",variant:"outline"}},y=c==null?void 0:c.filter(j=>{var S,A;if(!(((S=j.name)==null?void 0:S.toLowerCase().includes(s.toLowerCase()))||((A=j.email)==null?void 0:A.toLowerCase().includes(s.toLowerCase()))))return!1;if(a!=="all"){const E=j.subscription_source||"platform";if(a==="platform"&&E==="local_move_website"||a==="local_move_website"&&E!=="local_move_website")return!1}switch(f(j),n){case"active":return j.subscription_status==="active";case"trialing":return j.subscription_status==="trialing"||j.is_trial&&new Date(j.trial_expires_at)>new Date;case"grandfathered":return j.is_grandfathered;case"brokerage":return j.brokerage_id&&!j.subscription_product_id&&!j.is_grandfathered;case"expired":return j.subscription_status==="canceled"||j.subscription_status==="past_due"||j.is_trial&&new Date(j.trial_expires_at)<=new Date;case"none":return!j.subscription_status||j.subscription_status==="none";default:return!0}}),_={totalUsers:(c==null?void 0:c.length)||0,activeSubscriptions:(c==null?void 0:c.filter(j=>j.subscription_status==="active").length)||0,trials:(c==null?void 0:c.filter(j=>j.subscription_status==="trialing"||j.is_trial&&new Date(j.trial_expires_at)>new Date).length)||0,grandfathered:(c==null?void 0:c.filter(j=>j.is_grandfathered).length)||0,brokerageMembers:(c==null?void 0:c.filter(j=>j.brokerage_id&&!j.subscription_product_id&&!j.is_grandfathered).length)||0,individualSubscribers:(c==null?void 0:c.filter(j=>j.subscription_status==="active"&&j.subscription_product_id==="prod_Tc07cYplXUGNkm").length)||0,brokerageSubscribers:(c==null?void 0:c.filter(j=>j.subscription_status==="active"&&(j.subscription_product_id==="prod_Tc08MupgoVySDG"||j.subscription_product_id==="prod_Tc09N1tJ4RrAFn")).length)||0},v=j=>{window.open(`https://dashboard.stripe.com/customers/${j}`,"_blank")};return e.jsx(Cs,{title:"Subscription Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Subscription Management",description:"Track and manage all subscriptions",children:e.jsxs(B,{onClick:()=>u(),variant:"outline",size:"sm",children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"}),"Refresh"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Users"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:_.totalUsers})]})}),e.jsx(fe,{className:"border-green-500/50",children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(uf,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active Paid"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-green-600",children:_.activeSubscriptions})]})}),e.jsx(fe,{className:"border-blue-500/50",children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Trials"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-blue-600",children:_.trials})]})}),e.jsx(fe,{className:"border-purple-500/50",children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(hf,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Grandfathered"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-purple-600",children:_.grandfathered})]})}),e.jsx(fe,{className:"border-orange-500/50",children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Members"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1 text-orange-600",children:_.brokerageMembers})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(xb,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Individual"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:_.individualSubscribers})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Brokerage Subs"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:_.brokerageSubscribers})]})})]}),e.jsxs(Fr,{defaultValue:"users",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"users",children:"All Users"}),e.jsx(Zt,{value:"brokerages",children:"Brokerages"}),e.jsxs(Zt,{value:"websites",className:"gap-2",children:[e.jsx(lc,{className:"h-4 w-4"}),"Website Subscriptions",p&&p.length>0&&e.jsx(Ue,{variant:"secondary",className:"ml-1",children:p.length})]})]}),e.jsxs(is,{value:"users",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:s,onChange:j=>t(j.target.value),className:"pl-9"})]}),e.jsxs(us,{value:a,onValueChange:j=>i(j),children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Source"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Sources"}),e.jsx(Ze,{value:"platform",children:"Platform"}),e.jsx(Ze,{value:"local_move_website",children:"Local Move Website"})]})]}),e.jsxs(us,{value:n,onValueChange:j=>r(j),children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(hs,{placeholder:"Filter by status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),e.jsx(Ze,{value:"active",children:"Active Subscriptions"}),e.jsx(Ze,{value:"trialing",children:"Trials"}),e.jsx(Ze,{value:"grandfathered",children:"Grandfathered"}),e.jsx(Ze,{value:"brokerage",children:"Brokerage Members"}),e.jsx(Ze,{value:"expired",children:"Expired/Canceled"}),e.jsx(Ze,{value:"none",children:"No Subscription"})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Plan"}),e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{children:"End Date"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:d?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center py-8",children:"Loading subscriptions..."})}):(y==null?void 0:y.length)===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center py-8 text-muted-foreground",children:"No users found"})}):y==null?void 0:y.map(j=>{var A,E;const w=f(j),S=nNe[j.subscription_product_id];return e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.email})]})}),e.jsx(ht,{children:e.jsx(Ue,{variant:w.variant,children:w.badge})}),e.jsx(ht,{children:e.jsx("span",{className:"text-sm",children:j.is_grandfathered?"Legacy Access":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(S==null?void 0:S.name)||w.status})}),e.jsx(ht,{children:(A=j.brokerages)!=null&&A.name?e.jsx("span",{className:"text-sm",children:j.brokerages.name}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ht,{children:j.subscription_end_date?e.jsx("span",{className:"text-sm",children:Ss(new Date(j.subscription_end_date),"MMM d, yyyy")}):j.trial_expires_at?e.jsxs("span",{className:"text-sm text-blue-600",children:["Trial: ",Ss(new Date(j.trial_expires_at),"MMM d, yyyy")]}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[j.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.stripe_customer_id),children:e.jsx(tr,{className:"h-4 w-4"})}),e.jsxs(_s,{children:[e.jsx(ki,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",onClick:()=>o(j),children:"Details"})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Subscription Details"}),e.jsxs(Jn,{children:[j.name," (",j.email,")"]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Status"}),e.jsx(Ue,{variant:w.variant,className:"mt-1",children:w.badge})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Plan"}),e.jsx("p",{className:"font-medium",children:j.is_grandfathered?"Grandfathered (Legacy)":j.brokerage_id&&!j.subscription_product_id?"Brokerage Subscription":(S==null?void 0:S.name)||"None"})]}),j.brokerage_id&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Brokerage"}),e.jsx("p",{className:"font-medium",children:((E=j.brokerages)==null?void 0:E.name)||"Unknown"})]}),j.subscription_end_date&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Current Period End"}),e.jsx("p",{className:"font-medium",children:Ss(new Date(j.subscription_end_date),"MMMM d, yyyy")})]}),j.trial_expires_at&&e.jsxs("div",{children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Trial Expires"}),e.jsx("p",{className:"font-medium",children:Ss(new Date(j.trial_expires_at),"MMMM d, yyyy")})]}),j.stripe_customer_id&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Stripe Customer ID"}),e.jsx("p",{className:"font-mono text-sm",children:j.stripe_customer_id})]})]}),j.stripe_customer_id&&e.jsxs(B,{className:"w-full",onClick:()=>v(j.stripe_customer_id),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"View in Stripe Dashboard"]})]})]})]})]})})]},j.id)})})]})})})]}),e.jsx(is,{value:"brokerages",className:"space-y-4",children:e.jsx("div",{className:"grid gap-4",children:h==null?void 0:h.map(j=>{var S,A;const w=(S=j.managers)==null?void 0:S.some(E=>E.subscription_status==="active"&&(E.subscription_product_id==="prod_Tc08MupgoVySDG"||E.subscription_product_id==="prod_Tc09N1tJ4RrAFn"));return e.jsxs(fe,{children:[e.jsx(It,{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(Ua,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:j.name}),e.jsxs(Vn,{children:[j.agentCount," agents"]})]})]}),e.jsx(Ue,{variant:w?"default":"outline",children:w?"Active Subscription":"No Active Subscription"})]})}),e.jsx(Ee,{children:((A=j.managers)==null?void 0:A.length)>0?e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Managers:"}),j.managers.map(E=>{const O=nNe[E.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:E.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:E.email})]}),e.jsx("div",{className:"text-right",children:O?e.jsxs("div",{children:[e.jsx(Ue,{variant:"default",children:O.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:O.price})]}):e.jsx(Ue,{variant:"outline",children:"No Subscription"})})]},E.id)})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No managers assigned"})})]},j.id)})})}),e.jsx(is,{value:"websites",className:"space-y-4",children:e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(lc,{className:"h-5 w-5 text-primary"}),"Local Move Website Subscriptions"]}),e.jsx(Vn,{children:"$249 setup fee + $99/mo subscriptions from TheLocalMove.com agent websites"})]}),e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Setup Fee"}),e.jsx(Tt,{children:"Monthly"}),e.jsx(Tt,{children:"Next Renewal"}),e.jsx(Tt,{children:"Started"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:p?p.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:7,className:"text-center py-8 text-muted-foreground",children:"No website subscriptions yet"})}):p.map(j=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:j.agent_name||"—"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:j.agent_email})]})}),e.jsx(ht,{children:e.jsx(Ue,{variant:j.status==="active"?"default":j.status==="canceled"?"destructive":"outline",children:j.status})}),e.jsx(ht,{children:j.setup_fee_paid?e.jsxs(Ue,{variant:"secondary",children:["Paid · $",(j.setup_fee_amount_cents/100).toFixed(0)]}):e.jsx(Ue,{variant:"outline",children:"Unpaid"})}),e.jsxs(ht,{className:"font-medium",children:["$",(j.monthly_amount_cents/100).toFixed(0),"/mo"]}),e.jsx(ht,{children:j.current_period_end?e.jsx("span",{className:"text-sm",children:Ss(new Date(j.current_period_end),"MMM d, yyyy")}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"—"})}),e.jsx(ht,{children:e.jsx("span",{className:"text-sm",children:Ss(new Date(j.created_at),"MMM d, yyyy")})}),e.jsx(ht,{className:"text-right",children:j.stripe_customer_id&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>v(j.stripe_customer_id),children:e.jsx(tr,{className:"h-4 w-4"})})})]},j.id)):e.jsx(Hs,{children:e.jsx(ht,{colSpan:7,className:"text-center py-8",children:"Loading…"})})})]})})]})})]})]})})}function LVs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(""),[l,o]=N.useState("all"),[c,d]=N.useState({total:0,qualified:0,pending:0,cancelled:0,totalDiscounts:0});N.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:y,error:_}=await q.from("referrals").select(` *, referrer_brokerage:brokerages!referrer_brokerage_id(name), referred_brokerage:brokerages!referred_brokerage_id(name), referred_user:profiles!referred_user_id(name, email) `).order("created_at",{ascending:!1});if(_)throw _;t(y||[]);const v=(y==null?void 0:y.filter(S=>S.status==="qualified").length)||0,j=(y==null?void 0:y.filter(S=>S.status==="pending").length)||0,w=(y==null?void 0:y.filter(S=>S.status==="cancelled").length)||0;d({total:(y==null?void 0:y.length)||0,qualified:v,pending:j,cancelled:w,totalDiscounts:v*25})}catch(y){console.error("Error fetching referrals:",y),ae.error("Failed to load referrals")}finally{r(!1)}},h=async()=>{try{ae.loading("Processing qualifications...");const{error:y}=await q.functions.invoke("process-referral-qualifications");if(y)throw y;ae.dismiss(),ae.success("Qualifications processed successfully"),u()}catch(y){ae.dismiss(),console.error("Error processing qualifications:",y),ae.error("Failed to process qualifications")}},p=s.filter(y=>{var j,w,S,A,E,O;const _=((w=(j=y.referrer_brokerage)==null?void 0:j.name)==null?void 0:w.toLowerCase().includes(a.toLowerCase()))||((A=(S=y.referred_brokerage)==null?void 0:S.name)==null?void 0:A.toLowerCase().includes(a.toLowerCase()))||((O=(E=y.referred_user)==null?void 0:E.email)==null?void 0:O.toLowerCase().includes(a.toLowerCase())),v=l==="all"||y.status===l;return _&&v}),f=y=>{switch(y){case"qualified":return e.jsxs(Ue,{className:"bg-green-100 text-green-800",children:[e.jsx(Pi,{className:"h-3 w-3 mr-1"}),"Qualified"]});case"pending":return e.jsxs(Ue,{variant:"secondary",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),"Pending"]});case"cancelled":return e.jsxs(Ue,{variant:"destructive",children:[e.jsx(Uc,{className:"h-3 w-3 mr-1"}),"Cancelled"]});default:return e.jsx(Ue,{children:y})}};return e.jsx(Cs,{title:"Referral Program",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Referral Program",description:"Track and manage brokerage referrals",children:e.jsxs(B,{onClick:h,variant:"outline",children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"}),"Process Qualifications"]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-5 gap-4",children:[e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Referrals"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pi,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.qualified}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Qualified"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5 text-amber-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.pending}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Pending"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Uc,{className:"h-5 w-5 text-red-600"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:c.cancelled}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Cancelled"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-5 w-5 text-green-600"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:["$",c.totalDiscounts]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Monthly Discounts"})]})]})})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"All Referrals"}),e.jsx(Vn,{children:"View and manage all referral relationships"})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"flex gap-4 mb-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by brokerage or email...",value:a,onChange:y=>i(y.target.value),className:"pl-10"})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Filter by status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),e.jsx(Ze,{value:"pending",children:"Pending"}),e.jsx(Ze,{value:"qualified",children:"Qualified"}),e.jsx(Ze,{value:"cancelled",children:"Cancelled"})]})]})]}),n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Referrer"}),e.jsx(Tt,{children:"Referred"}),e.jsx(Tt,{children:"Signup Date"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Qualified Date"}),e.jsx(Tt,{children:"Discount"})]})}),e.jsx(da,{children:p.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:6,className:"text-center text-muted-foreground py-8",children:"No referrals found"})}):p.map(y=>{var _,v,j,w;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:((_=y.referrer_brokerage)==null?void 0:_.name)||"Unknown"}),e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("p",{children:((v=y.referred_brokerage)==null?void 0:v.name)||((j=y.referred_user)==null?void 0:j.name)||"Pending setup"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(w=y.referred_user)==null?void 0:w.email})]})}),e.jsx(ht,{children:Ss(new Date(y.signup_date),"MMM d, yyyy")}),e.jsx(ht,{children:f(y.status)}),e.jsx(ht,{children:y.qualified_date?Ss(new Date(y.qualified_date),"MMM d, yyyy"):"-"}),e.jsx(ht,{children:y.discount_applied?e.jsx(Ue,{variant:"outline",className:"text-green-600",children:"$25/mo applied"}):e.jsx("span",{className:"text-muted-foreground",children:"-"})})]},y.id)})})]})]})]})]})})}const rNe=[{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"}],DVs=[{value:"brokerage_manager",label:"Brokerage Manager"},{value:"agent",label:"Agent"}];function RVs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(null),[c,d]=N.useState({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0});N.useEffect(()=>{u()},[]);const u=async()=>{try{const{data:w,error:S}=await q.from("onboarding_checklist_items").select("*").order("target_role").order("sort_order");if(S)throw S;t(w||[])}catch(w){console.error("Error fetching checklist items:",w),ae.error("Failed to load checklist items")}finally{r(!1)}},h=()=>{o(null),d({title:"",description:"",action_type:"view_template",target_role:"agent",is_active:!0}),i(!0)},p=w=>{o(w),d({title:w.title,description:w.description||"",action_type:w.action_type,target_role:w.target_role,is_active:w.is_active}),i(!0)},f=async()=>{if(!c.title.trim()){ae.error("Title is required");return}try{if(l){const{error:w}=await q.from("onboarding_checklist_items").update({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active}).eq("id",l.id);if(w)throw w;ae.success("Checklist item updated")}else{const w=s.filter(A=>A.target_role===c.target_role).reduce((A,E)=>Math.max(A,E.sort_order),-1),{error:S}=await q.from("onboarding_checklist_items").insert({title:c.title,description:c.description||null,action_type:c.action_type,target_role:c.target_role,is_active:c.is_active,sort_order:w+1});if(S)throw S;ae.success("Checklist item created")}i(!1),u()}catch(w){console.error("Error saving checklist item:",w),ae.error("Failed to save checklist item")}},y=async w=>{if(confirm("Are you sure you want to delete this checklist item?"))try{const{error:S}=await q.from("onboarding_checklist_items").delete().eq("id",w);if(S)throw S;ae.success("Checklist item deleted"),u()}catch(S){console.error("Error deleting checklist item:",S),ae.error("Failed to delete checklist item")}},_=async w=>{try{const{error:S}=await q.from("onboarding_checklist_items").update({is_active:!w.is_active}).eq("id",w.id);if(S)throw S;ae.success(w.is_active?"Item deactivated":"Item activated"),u()}catch(S){console.error("Error toggling item:",S),ae.error("Failed to update item")}},v=s.filter(w=>w.target_role==="brokerage_manager"),j=s.filter(w=>w.target_role==="agent");return e.jsxs(Cs,{title:"Onboarding Checklist",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold",children:"Onboarding Checklist"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage checklist items shown to new users on their dashboard"})]}),e.jsxs(B,{onClick:h,className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Item"]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Ue,{variant:"secondary",children:"Brokerage Manager"}),"Checklist Items"]})}),e.jsx(Ee,{children:v.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for brokerage managers"}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:v.map((w,S)=>{var A;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"text-muted-foreground",children:S+1}),e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:w.title}),w.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:w.description})]})}),e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",children:((A=rNe.find(E=>E.value===w.action_type))==null?void 0:A.label)||w.action_type})}),e.jsx(ht,{children:e.jsx(jn,{checked:w.is_active,onCheckedChange:()=>_(w)})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(w),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>y(w.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},w.id)})})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Ue,{variant:"secondary",children:"Agent"}),"Checklist Items"]})}),e.jsx(Ee,{children:j.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-4",children:"No checklist items for agents"}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:j.map((w,S)=>{var A;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"text-muted-foreground",children:S+1}),e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:w.title}),w.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-1",children:w.description})]})}),e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",children:((A=rNe.find(E=>E.value===w.action_type))==null?void 0:A.label)||w.action_type})}),e.jsx(ht,{children:e.jsx(jn,{checked:w.is_active,onCheckedChange:()=>_(w)})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(w),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>y(w.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},w.id)})})]})})]})]}),e.jsx(_s,{open:a,onOpenChange:i,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{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(ne,{htmlFor:"title",children:"Title *"}),e.jsx(ye,{id:"title",value:c.title,onChange:w=>d({...c,title:w.target.value}),placeholder:"e.g., Watch your first academy video"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",value:c.description,onChange:w=>d({...c,description:w.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(ne,{children:"Target Role"}),e.jsxs(us,{value:c.target_role,onValueChange:w=>d({...c,target_role:w}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:DVs.map(w=>e.jsx(Ze,{value:w.value,children:w.label},w.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Action Type"}),e.jsxs(us,{value:c.action_type,onValueChange:w=>d({...c,action_type:w}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:rNe.map(w=>e.jsx(Ze,{value:w.value,children:w.label},w.value))})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{id:"is_active",checked:c.is_active,onCheckedChange:w=>d({...c,is_active:w})}),e.jsx(ne,{htmlFor:"is_active",children:"Active"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsx(B,{onClick:f,children:l?"Save Changes":"Create Item"})]})]})})]})}function OVs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("name"),[l,o]=N.useState("asc"),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(""),[y,_]=N.useState(""),{data:v}=dt({queryKey:["admin-brokerages"],queryFn:async()=>{const{data:z,error:H}=await q.from("brokerages").select("id, name").order("name");if(H)throw H;return z}}),j=async z=>{let Z=[],Y=0,W=!0;for(;W;){const{data:ee,error:se}=await z(Y,Y+1e3-1);if(se)throw se;ee&&ee.length>0?(Z=[...Z,...ee],Y+=1e3,W=ee.length===1e3):W=!1}return Z},{data:w,isLoading:S}=dt({queryKey:["admin-agent-os-user-stats"],queryFn:async()=>{const z=await j((Pe,Re)=>q.from("profiles").select("id, name, email, brokerage_id, created_at").range(Pe,Re)),{data:H}=await q.from("brokerages").select("id, name"),Z=new Map((H==null?void 0:H.map(Pe=>[Pe.id,Pe.name]))||[]),[{data:Y},{data:W},{data:ee},{data:se},{data:oe},{data:he},{data:ce}]=await Promise.all([q.rpc("get_admin_contact_counts"),q.rpc("get_admin_video_counts"),q.rpc("get_admin_popby_counts"),q.rpc("get_admin_listing_counts"),q.rpc("get_admin_deal_counts"),q.rpc("get_admin_portal_counts"),q.rpc("get_admin_sendable_card_counts")]),me=new Map;Y==null||Y.forEach(Pe=>me.set(Pe.owner_user_id,Pe.contact_count));const le=new Map;W==null||W.forEach(Pe=>le.set(Pe.owner_user_id,Pe.video_count));const ve=new Map;ee==null||ee.forEach(Pe=>ve.set(Pe.owner_user_id,Pe.popby_count));const ge=new Map;se==null||se.forEach(Pe=>ge.set(Pe.agent_id,Pe.listing_count));const Te=new Map;oe==null||oe.forEach(Pe=>Te.set(Pe.owner_user_id,Pe.deal_count));const Ie=new Map;he==null||he.forEach(Pe=>Ie.set(Pe.owner_user_id,{total:Pe.portal_count,active:Pe.active_portal_count}));const Ce=new Map;return ce==null||ce.forEach(Pe=>Ce.set(Pe.owner_user_id,{total:Pe.card_count,sent:Pe.sent_card_count,views:Pe.total_card_views})),z.map(Pe=>{const Re=Ie.get(Pe.id),Ae=Ce.get(Pe.id);return{id:Pe.id,name:Pe.name||"Unknown",email:Pe.email||"",brokerage_id:Pe.brokerage_id,brokerage_name:Pe.brokerage_id&&Z.get(Pe.brokerage_id)||null,contact_count:me.get(Pe.id)||0,video_count:le.get(Pe.id)||0,popby_count:ve.get(Pe.id)||0,listing_count:ge.get(Pe.id)||0,deal_count:Te.get(Pe.id)||0,portal_count:(Re==null?void 0:Re.total)||0,active_portal_count:(Re==null?void 0:Re.active)||0,card_count:(Ae==null?void 0:Ae.total)||0,sent_card_count:(Ae==null?void 0:Ae.sent)||0,total_card_views:(Ae==null?void 0:Ae.views)||0,created_at:Pe.created_at}})}}),A=N.useMemo(()=>{if(!w)return[];let z=w.filter(H=>{const Z=s.toLowerCase(),Y=!s||H.name.toLowerCase().includes(Z)||H.email.toLowerCase().includes(Z),W=n==="all"||n==="none"&&!H.brokerage_id||H.brokerage_id===n,ee=parseInt(c)||0,se=parseInt(u)||0,oe=parseInt(p)||0,he=parseInt(y)||0,ce=H.contact_count>=ee&&H.video_count>=se&&H.popby_count>=oe&&H.listing_count>=he;return Y&&W&&ce});return z.sort((H,Z)=>{let Y=0;return a==="name"?Y=H.name.localeCompare(Z.name):Y=H[a]-Z[a],l==="asc"?Y:-Y}),z},[w,s,n,a,l,c,u,p,y]),E=z=>{a===z?o(l==="asc"?"desc":"asc"):(i(z),o("desc"))},O=()=>{const z=["Name","Email","Brokerage","Contacts","Videos","Popbys","Listings","Deals","Portals (Active)","Cards Created","Cards Sent","Card Views"],H=A.map(se=>[se.name,se.email,se.brokerage_name||"None",se.contact_count,se.video_count,se.popby_count,se.listing_count,se.deal_count,`${se.portal_count} (${se.active_portal_count})`,se.card_count,se.sent_card_count,se.total_card_views]),Z=[z.join(","),...H.map(se=>se.map(oe=>`"${oe}"`).join(","))].join(` `),Y=new Blob([Z],{type:"text/csv"}),W=URL.createObjectURL(Y),ee=document.createElement("a");ee.href=W,ee.download=`agent-os-user-stats-${new Date().toISOString().split("T")[0]}.csv`,ee.click(),URL.revokeObjectURL(W)},D=N.useMemo(()=>A.length?A.reduce((z,H)=>({contacts:z.contacts+H.contact_count,videos:z.videos+H.video_count,popbys:z.popbys+H.popby_count,listings:z.listings+H.listing_count,deals:z.deals+H.deal_count,portals:z.portals+H.portal_count,activePortals:z.activePortals+H.active_portal_count,cards:z.cards+H.card_count,sentCards:z.sentCards+H.sent_card_count,cardViews:z.cardViews+H.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]),I=N.useMemo(()=>A.length?{portals:A.filter(z=>z.portal_count>0).length,cards:A.filter(z=>z.card_count>0).length}:{portals:0,cards:0},[A]),F=({field:z,children:H})=>e.jsx(Tt,{className:"cursor-pointer hover:bg-muted/50 select-none",onClick:()=>E(z),children:e.jsxs("div",{className:"flex items-center gap-1",children:[H,e.jsx(ah,{className:`h-3 w-3 ${a===z?"text-primary":"text-muted-foreground"}`})]})});return e.jsx(Vw,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsxs(fe,{className:"border-blue-500/20 bg-gradient-to-br from-blue-500/5 to-transparent",children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(hw,{className:"h-4 w-4 text-blue-500"}),"Client Portals"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid grid-cols-3 gap-4 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:I.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:D.portals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Portals"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:D.activePortals}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Active Portals"})]})]})})]}),e.jsxs(fe,{className:"border-violet-500/20 bg-gradient-to-br from-violet-500/5 to-transparent",children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Gs,{className:"h-4 w-4 text-violet-500"}),"Card Studio"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid grid-cols-4 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:I.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Agents Using"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:D.cards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Created"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:D.sentCards}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Cards Sent"})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:D.cardViews}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Total Views"})]})]})})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"User Activity Analytics"]}),e.jsx(Vn,{children:"View all users and their Agent OS usage metrics"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:O,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Export CSV"]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-4 md:grid-cols-6",children:[e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:s,onChange:z=>t(z.target.value),className:"pl-9"})]})}),e.jsx("div",{children:e.jsxs(us,{value:n,onValueChange:r,children:[e.jsxs(ls,{children:[e.jsx(Ua,{className:"h-4 w-4 mr-2 text-muted-foreground"}),e.jsx(hs,{placeholder:"Brokerage"})]}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Brokerages"}),e.jsx(Ze,{value:"none",children:"No Brokerage"}),v==null?void 0:v.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))]})]})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min contacts",value:c,onChange:z=>d(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min videos",value:u,onChange:z=>h(z.target.value),min:"0"})}),e.jsx("div",{children:e.jsx(ye,{type:"number",placeholder:"Min popbys",value:p,onChange:z=>f(z.target.value),min:"0"})})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-8 text-sm",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:A.length}),e.jsx("div",{className:"text-muted-foreground",children:"Users"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:D.contacts.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Contacts"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:D.videos.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Videos"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:D.popbys.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Popbys"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:D.listings.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Listings"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:D.deals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Deals"})]}),e.jsxs("div",{className:"bg-blue-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:D.portals.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Portals"})]}),e.jsxs("div",{className:"bg-violet-500/10 rounded-lg p-3 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:D.cards.toLocaleString()}),e.jsx("div",{className:"text-muted-foreground",children:"Cards"})]})]}),S?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"rounded-md border overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(F,{field:"name",children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{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(hw,{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(Gs,{className:"h-3 w-3 text-violet-500"}),"Cards"]})})]})}),e.jsx(da,{children:A.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:"No users found matching your filters"})}):A.map(z=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:z.name}),e.jsx(ht,{className:"text-muted-foreground",children:z.email}),e.jsx(ht,{children:z.brokerage_name?e.jsx(Ue,{variant:"secondary",children:z.brokerage_name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ht,{children:e.jsx(Ue,{variant:z.contact_count>0?"default":"outline",children:z.contact_count})}),e.jsx(ht,{children:e.jsx(Ue,{variant:z.video_count>0?"default":"outline",children:z.video_count})}),e.jsx(ht,{children:e.jsx(Ue,{variant:z.popby_count>0?"default":"outline",children:z.popby_count})}),e.jsx(ht,{children:e.jsx(Ue,{variant:z.listing_count>0?"default":"outline",children:z.listing_count})}),e.jsx(ht,{children:e.jsx(Ue,{variant:z.deal_count>0?"default":"outline",children:z.deal_count})}),e.jsx(ht,{children:z.portal_count>0?e.jsxs(Bc,{children:[e.jsx($c,{children:e.jsxs(Ue,{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(Nc,{children:[e.jsxs("p",{children:[z.portal_count," total portals"]}),e.jsxs("p",{children:[z.active_portal_count," currently active"]})]})]}):e.jsx(Ue,{variant:"outline",children:"0"})}),e.jsx(ht,{children:z.card_count>0?e.jsxs(Bc,{children:[e.jsx($c,{children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ue,{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(lr,{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(Sr,{className:"h-3 w-3"}),z.total_card_views]})]})}),e.jsxs(Nc,{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(Ue,{variant:"outline",children:"0"})})]},z.id))})]})})]})]})]})})}function FVs(){Fa(),Kt();const[s,t]=N.useState("user-analytics"),{data:n}=dt({queryKey:["admin-feature-flags"],queryFn:async()=>{const{data:f,error:y}=await q.from("feature_flags").select("*").order("key");if(y)throw y;return f}}),{data:r,isLoading:a}=dt({queryKey:["admin-relationship-types"],queryFn:async()=>{const{data:f,error:y}=await q.from("relationship_types").select("*").order("sort_order");if(y)throw y;return f}}),{data:i,isLoading:l}=dt({queryKey:["admin-action-types"],queryFn:async()=>{const{data:f,error:y}=await q.from("action_types").select("*").order("sort_order");if(y)throw y;return f}}),{data:o,isLoading:c}=dt({queryKey:["admin-action-scripts"],queryFn:async()=>{const{data:f,error:y}=await q.from("action_scripts").select("*, action_type:action_types(*)");if(y)throw y;return f}}),{data:d,isLoading:u}=dt({queryKey:["admin-touchpoint-plans"],queryFn:async()=>{const{data:f,error:y}=await q.from("touchpoint_plans").select("*").order("name");if(y)throw y;return f}}),{data:h,isLoading:p}=dt({queryKey:["admin-popby-items"],queryFn:async()=>{const{data:f,error:y}=await q.from("popby_items").select("*").is("owner_user_id",null).order("name");if(y)throw y;return f}});return e.jsx(Cs,{title:"Agent OS Control Center",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Agent OS Control Center",description:"Manage InnerCircle settings, scripts, and touchpoint plans"}),e.jsxs(Fr,{value:s,onValueChange:t,children:[e.jsxs(Rr,{className:"grid w-full grid-cols-9",children:[e.jsxs(Zt,{value:"user-analytics",className:"gap-2",children:[e.jsx(_o,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Users"})]}),e.jsxs(Zt,{value:"relationship-types",className:"gap-2",children:[e.jsx(An,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Relationships"})]}),e.jsxs(Zt,{value:"action-types",className:"gap-2",children:[e.jsx(Cr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Actions"})]}),e.jsxs(Zt,{value:"scripts",className:"gap-2",children:[e.jsx(br,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Scripts"})]}),e.jsxs(Zt,{value:"video-scripts",className:"gap-2",children:[e.jsx(Sh,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Video Scripts"})]}),e.jsxs(Zt,{value:"plans",className:"gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Plans"})]}),e.jsxs(Zt,{value:"popbys",className:"gap-2",children:[e.jsx(Oi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Popbys"})]}),e.jsxs(Zt,{value:"settings",className:"gap-2",children:[e.jsx(Ko,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Settings"})]}),e.jsxs(Zt,{value:"feature-flags",className:"gap-2",children:[e.jsx(V2,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline",children:"Flags"})]})]}),e.jsx(is,{value:"user-analytics",className:"mt-6",children:e.jsx(OVs,{})}),e.jsx(is,{value:"relationship-types",className:"mt-6",children:e.jsx(zVs,{types:r||[],isLoading:a})}),e.jsx(is,{value:"action-types",className:"mt-6",children:e.jsx(BVs,{types:i||[],isLoading:l})}),e.jsx(is,{value:"scripts",className:"mt-6",children:e.jsx($Vs,{scripts:o||[],actionTypes:i||[],isLoading:c})}),e.jsx(is,{value:"video-scripts",className:"mt-6",children:e.jsx(HVs,{})}),e.jsx(is,{value:"plans",className:"mt-6",children:e.jsx(UVs,{plans:d||[],actionTypes:i||[],scripts:o||[],isLoading:u})}),e.jsx(is,{value:"popbys",className:"mt-6",children:e.jsx(VVs,{items:h||[],isLoading:p})}),e.jsx(is,{value:"settings",className:"mt-6",children:e.jsx(GVs,{})}),e.jsx(is,{value:"feature-flags",className:"mt-6",children:e.jsx(qVs,{flags:n||[]})})]})]})})}function zVs({types:s,isLoading:t}){const{toast:n}=Fa(),r=Kt(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=yt({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("relationship_types").update({name:u.name,description:u.description,icon:u.icon}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("relationship_types").insert([{name:u.name,description:u.description,icon:u.icon,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-relationship-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("relationship_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-relationship-types"]})};return e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Relationship Types"}),e.jsx(Vn,{children:"Define the relationship categories for InnerCircle contacts"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Type"]})]}),e.jsx(Ee,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-12"}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(u=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsx(Pu,{className:"h-4 w-4 text-muted-foreground cursor-grab"})}),e.jsx(ht,{className:"font-medium",children:u.name}),e.jsx(ht,{className:"text-muted-foreground",children:u.description}),e.jsx(ht,{children:e.jsx(jn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(ht,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(ya,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(_s,{open:l,onOpenChange:o,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsxs(ws,{children:[a?"Edit":"Add"," Relationship Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"icon",children:"Icon"}),e.jsx(ye,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., star, heart, user"})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function BVs({types:s,isLoading:t}){const{toast:n}=Fa(),r=Kt(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=yt({mutationFn:async u=>{if(u.id){const{error:h}=await q.from("action_types").update({name:u.name,description:u.description,icon:u.icon,color:u.color}).eq("id",u.id);if(h)throw h}else{const{error:h}=await q.from("action_types").insert([{name:u.name,description:u.description,icon:u.icon,color:u.color,sort_order:s.length}]);if(h)throw h}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-action-types"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:u=>{n({title:"Error",description:u.message,variant:"destructive"})}}),d=async u=>{await q.from("action_types").update({active:!u.active}).eq("id",u.id),r.invalidateQueries({queryKey:["admin-action-types"]})};return e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Action Types"}),e.jsx(Vn,{children:"Define the types of touchpoint actions agents can take"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Action"]})]}),e.jsx(Ee,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Color"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(u=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:u.name}),e.jsx(ht,{className:"text-muted-foreground",children:u.description}),e.jsx(ht,{children:u.color&&e.jsx("div",{className:"w-6 h-6 rounded",style:{backgroundColor:u.color}})}),e.jsx(ht,{children:e.jsx(jn,{checked:u.active,onCheckedChange:()=>d(u)})}),e.jsx(ht,{children:e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(u),o(!0)},children:e.jsx(ya,{className:"h-4 w-4"})})})]},u.id))})]})}),e.jsx(_s,{open:l,onOpenChange:o,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsxs(ws,{children:[a?"Edit":"Add"," Action Type"]})}),e.jsxs("form",{onSubmit:u=>{u.preventDefault();const h=new FormData(u.currentTarget);c.mutate({id:a==null?void 0:a.id,name:h.get("name"),description:h.get("description"),icon:h.get("icon"),color:h.get("color")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||""})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"icon",children:"Icon"}),e.jsx(ye,{id:"icon",name:"icon",defaultValue:(a==null?void 0:a.icon)||"",placeholder:"e.g., phone, message"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"color",children:"Color"}),e.jsx(ye,{id:"color",name:"color",type:"color",defaultValue:(a==null?void 0:a.color)||"#6366f1"})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function $Vs({scripts:s,actionTypes:t,isLoading:n}){const{toast:r}=Fa(),a=Kt(),[i,l]=N.useState(null),[o,c]=N.useState(!1),d=yt({mutationFn:async h=>{if(h.id){const{error:p}=await q.from("action_scripts").update({title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:h.active}).eq("id",h.id);if(p)throw p}else{const{error:p}=await q.from("action_scripts").insert([{title:h.title,action_type_id:h.action_type_id,tone:h.tone,script_body:h.script_body,active:!0}]);if(p)throw p}},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),c(!1),l(null),r({title:"Saved successfully"})},onError:h=>{r({title:"Error",description:h.message,variant:"destructive"})}}),u=yt({mutationFn:async h=>{const{error:p}=await q.from("action_scripts").delete().eq("id",h);if(p)throw p},onSuccess:()=>{a.invalidateQueries({queryKey:["admin-action-scripts"]}),r({title:"Deleted successfully"})}});return e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Script Library"}),e.jsx(Vn,{children:"Create and manage scripts for each action type"})]}),e.jsxs(B,{onClick:()=>{l(null),c(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ee,{children:n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Action Type"}),e.jsx(Tt,{children:"Tone"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(h=>{var p;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:h.title}),e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",children:((p=h.action_type)==null?void 0:p.name)||"Unknown"})}),e.jsx(ht,{className:"text-muted-foreground",children:h.tone}),e.jsx(ht,{children:e.jsx(Ue,{variant:h.active?"default":"secondary",children:h.active?"Active":"Inactive"})}),e.jsxs(ht,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{l(h),c(!0)},children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutate(h.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})]},h.id)})})]})}),e.jsx(_s,{open:o,onOpenChange:c,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(ws,{children:[i?"Edit":"Add"," Script"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const p=new FormData(h.currentTarget);d.mutate({id:i==null?void 0:i.id,title:p.get("title"),action_type_id:p.get("action_type_id"),tone:p.get("tone"),script_body:p.get("script_body"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",name:"title",defaultValue:i==null?void 0:i.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"action_type_id",children:"Action Type"}),e.jsxs(us,{name:"action_type_id",defaultValue:i==null?void 0:i.action_type_id,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select action type"})}),e.jsx(cs,{children:t.map(h=>e.jsx(Ze,{value:h.id,children:h.name},h.id))})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"tone",children:"Tone (optional)"}),e.jsx(ye,{id:"tone",name:"tone",defaultValue:(i==null?void 0:i.tone)||"",placeholder:"e.g., Friendly, Professional, Casual"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ms,{id:"script_body",name:"script_body",defaultValue:i==null?void 0:i.script_body,rows:8,required:!0,placeholder:`Use {{FirstName}}, {{LastName}}, and {{AgentName}} as placeholders. Example: Hey {{FirstName}}, it's {{AgentName}}. I was thinking about you and wanted to check in...`})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:d.isPending,children:[d.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function UVs({plans:s,actionTypes:t,scripts:n,isLoading:r}){const{toast:a}=Fa(),i=Kt(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(!1),[y,_]=N.useState(null),[v,j]=N.useState(null),{data:w}=dt({queryKey:["plan-items",u],queryFn:async()=>{if(!u)return[];const{data:F,error:z}=await q.from("touchpoint_plan_items").select("*").eq("plan_id",u).order("month_number");if(z)throw z;return F},enabled:!!u}),S=yt({mutationFn:async F=>{if(F.id){const{error:z}=await q.from("touchpoint_plans").update({name:F.name,description:F.description,active:F.active}).eq("id",F.id);if(z)throw z}else{const{error:z}=await q.from("touchpoint_plans").insert([{name:F.name,description:F.description,active:!0}]);if(z)throw z}},onSuccess:()=>{i.invalidateQueries({queryKey:["admin-touchpoint-plans"]}),d(!1),o(null),a({title:"Saved successfully"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),A=yt({mutationFn:async F=>{if(F.id){const{error:z}=await q.from("touchpoint_plan_items").update({action_type_id:F.action_type_id,default_script_id:F.default_script_id,notes:F.notes}).eq("id",F.id);if(z)throw z}else{const{error:z}=await q.from("touchpoint_plan_items").insert([{plan_id:F.plan_id,month_number:F.month_number,action_type_id:F.action_type_id,default_script_id:F.default_script_id,notes:F.notes}]);if(z)throw z}},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]}),a({title:"Item saved"})}}),E=yt({mutationFn:async F=>{const{error:z}=await q.from("touchpoint_plan_items").delete().eq("id",F);if(z)throw z},onSuccess:()=>{i.invalidateQueries({queryKey:["plan-items",u]})}}),O=yt({mutationFn:async F=>{const{data:z,error:H}=await q.from("action_scripts").insert([{...F,active:!0}]).select().single();if(H)throw H;return z},onSuccess:async F=>{i.invalidateQueries({queryKey:["admin-action-scripts"]}),y&&await A.mutateAsync({id:y.itemId,plan_id:u,month_number:y.month,action_type_id:y.actionTypeId,default_script_id:F.id}),f(!1),_(null),a({title:"Script created and assigned"})},onError:F=>{a({title:"Error",description:F.message,variant:"destructive"})}}),D=(F,z,H)=>{_({month:F,actionTypeId:z,itemId:H}),f(!0)},I=F=>n.find(z=>z.id===F);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Touchpoint Plans"}),e.jsx(Vn,{children:"Create annual touchpoint plans that agents can apply to their contacts"})]}),e.jsxs(B,{onClick:()=>{o(null),d(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Plan"]})]}),e.jsx(Ee,{children:r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(F=>e.jsxs(fe,{className:`cursor-pointer transition-colors ${u===F.id?"border-primary":""}`,onClick:()=>h(F.id),children:[e.jsx(It,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Rt,{className:"text-base",children:F.name}),e.jsx(B,{variant:"ghost",size:"icon",onClick:z=>{z.stopPropagation(),o(F),d(!0)},children:e.jsx(ya,{className:"h-4 w-4"})})]})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2",children:F.description}),e.jsx(Ue,{variant:F.active?"default":"secondary",className:"mt-2",children:F.active?"Active":"Inactive"})]})]},F.id))})})]}),u&&e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Plan Schedule"}),e.jsx(Vn,{children:"Configure the monthly touchpoint schedule. Select an action type for each month, then assign or create a script."})]}),e.jsx(Ee,{children:e.jsx("div",{className:"grid gap-3",children:Array.from({length:12},(F,z)=>z+1).map(F=>{const z=w==null?void 0:w.find(Y=>Y.month_number===F),H=z!=null&&z.default_script_id?I(z.default_script_id):null,Z=n.filter(Y=>Y.action_type_id===(z==null?void 0:z.action_type_id)&&Y.active);return e.jsxs("div",{className:"p-4 border rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"w-20 font-medium text-sm",children:["Month ",F]}),e.jsxs(us,{value:(z==null?void 0:z.action_type_id)||"none",onValueChange:Y=>{Y==="none"&&z?E.mutate(z.id):Y!=="none"&&A.mutate({id:z==null?void 0:z.id,plan_id:u,month_number:F,action_type_id:Y,default_script_id:null})},children:[e.jsx(ls,{className:"w-40",children:e.jsx(hs,{placeholder:"No action"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No action"}),t.filter(Y=>Y.active).map(Y=>e.jsx(Ze,{value:Y.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[Y.color&&e.jsx("span",{className:"w-3 h-3 rounded-full",style:{backgroundColor:Y.color}}),Y.name]})},Y.id))]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(us,{value:z.default_script_id||"none",onValueChange:Y=>{j(null),A.mutate({id:z.id,default_script_id:Y==="none"?null:Y})},children:[e.jsx(ls,{className:"w-56",children:e.jsx(hs,{placeholder:"Select script"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No default script"}),Z.map(Y=>e.jsxs(Ze,{value:Y.id,children:[Y.title," ",Y.tone&&`(${Y.tone})`]},Y.id))]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>D(F,z.action_type_id,z.id),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"}),"New Script"]}),H&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>j((v==null?void 0:v.id)===H.id?null:H),children:(v==null?void 0:v.id)===H.id?"Hide":"Preview"})]})]}),v&&(z==null?void 0:z.default_script_id)===v.id&&e.jsxs("div",{className:"ml-24 p-3 bg-muted rounded-lg text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ue,{variant:"outline",children:v.title}),v.tone&&e.jsx(Ue,{variant:"secondary",children:v.tone})]}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:v.script_body})]})]},F)})})})]}),e.jsx(_s,{open:c,onOpenChange:d,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsxs(ws,{children:[l?"Edit":"Add"," Touchpoint Plan"]})}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const z=new FormData(F.currentTarget);S.mutate({id:l==null?void 0:l.id,name:z.get("name"),description:z.get("description"),active:!0})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:l==null?void 0:l.name,required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:(l==null?void 0:l.description)||"",rows:3})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:S.isPending,children:[S.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})}),e.jsx(_s,{open:p,onOpenChange:f,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create New Script"}),e.jsxs(Jn,{children:["Create a script for Month ",y==null?void 0:y.month,". Use ","{{FirstName}}",", ","{{LastName}}",", and ","{{AgentName}}"," as placeholders."]})]}),e.jsxs("form",{onSubmit:F=>{F.preventDefault();const z=new FormData(F.currentTarget);O.mutate({title:z.get("title"),action_type_id:y.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(ne,{htmlFor:"script_title",children:"Title"}),e.jsx(ye,{id:"script_title",name:"title",placeholder:"e.g., Warm Check-In",required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"script_tone",children:"Tone"}),e.jsx(ye,{id:"script_tone",name:"tone",placeholder:"e.g., Friendly, Professional"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"script_body",children:"Script Body"}),e.jsx(Ms,{id:"script_body",name:"script_body",rows:6,required:!0,placeholder:"Hey {{FirstName}}, it's {{AgentName}}. I was thinking about you and wanted to check in..."})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:O.isPending,children:[O.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Create & Assign"]})]})]})]})})]})}function qVs({flags:s}){const{toast:t}=Fa(),n=Kt(),r=async(a,i)=>{const{error:l}=await q.from("feature_flags").update({...i,updated_at:new Date().toISOString()}).eq("id",a.id);l?t({title:"Error",description:l.message,variant:"destructive"}):(n.invalidateQueries({queryKey:["admin-feature-flags"]}),t({title:"Flag updated"}))};return e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Feature Flags"}),e.jsx(Vn,{children:"Control which features are enabled for members"})]}),e.jsx(Ee,{children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Flag"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Notes"}),e.jsx(Tt,{children:"Last Updated"})]})}),e.jsx(da,{children:s.map(a=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-mono text-sm",children:a.key}),e.jsx(ht,{children:e.jsx(jn,{checked:a.enabled,onCheckedChange:i=>r(a,{enabled:i})})}),e.jsx(ht,{children:e.jsx(ye,{defaultValue:a.notes||"",placeholder:"Add notes...",className:"max-w-xs",onBlur:i=>{i.target.value!==a.notes&&r(a,{notes:i.target.value})}})}),e.jsx(ht,{className:"text-muted-foreground text-sm",children:new Date(a.updated_at).toLocaleDateString()})]},a.id))})]})})]})}function VVs({items:s,isLoading:t}){const{toast:n}=Fa(),r=Kt(),[a,i]=N.useState(null),[l,o]=N.useState(!1),c=yt({mutationFn:async h=>{if(h.id){const{error:p}=await q.from("popby_items").update({name:h.name,description:h.description}).eq("id",h.id);if(p)throw p}else{const{error:p}=await q.from("popby_items").insert([{name:h.name,description:h.description,owner_user_id:null}]);if(p)throw p}},onSuccess:()=>{r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),o(!1),i(null),n({title:"Saved successfully"})},onError:h=>{n({title:"Error",description:h.message,variant:"destructive"})}}),d=async h=>{await q.from("popby_items").update({is_active:!h.is_active}).eq("id",h.id),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]})},u=async h=>{await q.from("popby_items").delete().eq("id",h),r.invalidateQueries({queryKey:["admin-popby-items"]}),r.invalidateQueries({queryKey:["popby-items"]}),n({title:"Deleted successfully"})};return e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Popby Ideas"}),e.jsx(Vn,{children:"Manage global popby ideas that all agents can see"})]}),e.jsxs(B,{onClick:()=>{i(null),o(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsx(Ee,{children:t?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Oi,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No popby ideas yet. Add your first one!"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:s.map(h=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:h.name}),e.jsx(ht,{className:"text-muted-foreground",children:h.description}),e.jsx(ht,{children:e.jsx(jn,{checked:h.is_active,onCheckedChange:()=>d(h)})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{i(h),o(!0)},children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u(h.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},h.id))})]})}),e.jsx(_s,{open:l,onOpenChange:o,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsxs(ws,{children:[a?"Edit":"Add"," Popby Idea"]})}),e.jsxs("form",{onSubmit:h=>{h.preventDefault();const p=new FormData(h.currentTarget);c.mutate({id:a==null?void 0:a.id,name:p.get("name"),description:p.get("description")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",name:"name",defaultValue:a==null?void 0:a.name,required:!0,placeholder:"e.g., Homemade Cookies"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",name:"description",defaultValue:(a==null?void 0:a.description)||"",placeholder:"Brief description of the popby idea..."})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:c.isPending,children:[c.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function HVs(){var f;const{toast:s}=Fa(),t=Kt(),[n,r]=N.useState(null),[a,i]=N.useState(!1),{data:l,isLoading:o}=dt({queryKey:["admin-video-script-categories"],queryFn:async()=>{const{data:y,error:_}=await q.from("video_script_categories").select("*").order("sort_order");if(_)throw _;return y}}),{data:c,isLoading:d}=dt({queryKey:["admin-video-scripts"],queryFn:async()=>{const{data:y,error:_}=await q.from("video_scripts").select("*, category:video_script_categories(*)").order("title");if(_)throw _;return y}}),u=yt({mutationFn:async y=>{var _,v;if(y.id){const{error:j}=await q.from("video_scripts").update({title:y.title,script_text:y.script_text,category_id:y.category_id,tags:((_=y.tags)==null?void 0:_.split(",").map(w=>w.trim()).filter(Boolean))||[]}).eq("id",y.id);if(j)throw j}else{const{error:j}=await q.from("video_scripts").insert([{title:y.title,script_text:y.script_text,category_id:y.category_id||null,tags:((v=y.tags)==null?void 0:v.split(",").map(w=>w.trim()).filter(Boolean))||[]}]);if(j)throw j}},onSuccess:()=>{t.invalidateQueries({queryKey:["admin-video-scripts"]}),i(!1),r(null),s({title:"Video script saved!"})},onError:y=>s({title:"Error",description:y.message,variant:"destructive"})}),h=async y=>{await q.from("video_scripts").update({is_active:!y.is_active}).eq("id",y.id),t.invalidateQueries({queryKey:["admin-video-scripts"]})},p=async y=>{confirm("Delete this video script?")&&(await q.from("video_scripts").delete().eq("id",y),t.invalidateQueries({queryKey:["admin-video-scripts"]}),s({title:"Script deleted"}))};return e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Video Scripts"}),e.jsx(Vn,{children:"Manage teleprompter scripts for Quick Video Touch"})]}),e.jsxs(B,{onClick:()=>{r(null),i(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Script"]})]}),e.jsx(Ee,{children:d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Title"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"w-24",children:"Actions"})]})}),e.jsx(da,{children:c==null?void 0:c.map(y=>{var _;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:y.title}),e.jsx(ht,{className:"text-muted-foreground",children:((_=y.category)==null?void 0:_.name)||"Uncategorized"}),e.jsx(ht,{children:e.jsx(jn,{checked:y.is_active,onCheckedChange:()=>h(y)})}),e.jsxs(ht,{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>{r(y),i(!0)},children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(y.id),children:e.jsx(_n,{className:"h-4 w-4"})})]})]},y.id)})})]})}),e.jsx(_s,{open:a,onOpenChange:i,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(ws,{children:[n?"Edit":"Add"," Video Script"]})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault();const _=new FormData(y.currentTarget);u.mutate({id:n==null?void 0:n.id,title:_.get("title"),script_text:_.get("script_text"),category_id:_.get("category_id")||null,tags:_.get("tags")})},children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",name:"title",defaultValue:n==null?void 0:n.title,required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"category_id",children:"Category"}),e.jsxs(us,{name:"category_id",defaultValue:(n==null?void 0:n.category_id)||"",children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(cs,{children:l==null?void 0:l.map(y=>e.jsx(Ze,{value:y.id,children:y.name},y.id))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"script_text",children:"Script Text"}),e.jsx(Ms,{id:"script_text",name:"script_text",defaultValue:n==null?void 0:n.script_text,rows:6,required:!0,placeholder:"Enter the teleprompter script..."})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"tags",children:"Tags (comma-separated)"}),e.jsx(ye,{id:"tags",name:"tags",defaultValue:((f=n==null?void 0:n.tags)==null?void 0:f.join(", "))||"",placeholder:"birthday, follow-up, thank-you"})]})]}),e.jsxs(Xn,{className:"mt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>i(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:u.isPending,children:[u.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save"]})]})]})]})})]})}function GVs(){const{toast:s}=Fa(),[t,n]=N.useState(""),[r,a]=N.useState(!0),[i,l]=N.useState(!1);N.useEffect(()=>{(async()=>{a(!0);try{const{data:d}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();d!=null&&d.value&&n(d.value)}catch(d){console.error("Error fetching settings:",d)}a(!1)})()},[]);const o=async()=>{l(!0);try{await q.from("settings").upsert({key:"mapbox_public_token",value:t.trim()}),s({title:"Mapbox token saved!"})}catch{s({title:"Error saving token",variant:"destructive"})}l(!1)};return r?e.jsx(fe,{children:e.jsx(Ee,{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})})}):e.jsx("div",{className:"space-y-6",children:e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(ka,{className:"h-5 w-5"}),"Popby Map Settings"]}),e.jsx(Vn,{children:"Configure the map feature for popbys"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"mapbox-token",children:"Mapbox Public Token"}),e.jsx(ye,{id:"mapbox-token",placeholder:"pk.eyJ1I...",value:t,onChange:c=>n(c.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Get your token at"," ",e.jsx("a",{href:"https://mapbox.com/",target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline",children:"mapbox.com"}),". This token will be used by all agents for the popby map feature."]})]}),e.jsxs(B,{onClick:o,disabled:i,children:[i&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Token"]}),t&&e.jsx(Ue,{variant:"secondary",className:"ml-2",children:"Token configured"})]})]})})}const WVs=()=>{const[s,t]=N.useState(""),[n,r]=N.useState("grid"),a=Ln(),{data:i=[],isLoading:l}=dt({queryKey:["additional-services"],queryFn:async()=>{const{data:c,error:d}=await q.from("additional_services").select("*").eq("is_published",!0).order("publish_date",{ascending:!1});if(d)throw d;return c}}),o=i.filter(c=>{var u;return c.name.toLowerCase().includes(s.toLowerCase())||((u=c.description)==null?void 0:u.toLowerCase().includes(s.toLowerCase()))});return e.jsx(Cs,{title:"Additional Services",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Additional Services"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Explore our additional services and offerings"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search services...",value:s,onChange:c=>t(c.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"flex gap-2",children:[s&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>t(""),children:"Clear"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:n==="grid"?"secondary":"outline",size:"icon",onClick:()=>r("grid"),className:"rounded-full",children:e.jsx(ff,{className:"h-4 w-4"})}),e.jsx(B,{variant:n==="list"?"secondary":"outline",size:"icon",onClick:()=>r("list"),className:"rounded-full",children:e.jsx(Sp,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[o.length," service",o.length!==1?"s":""," found"]}),l&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:[...Array(4)].map((c,d)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"})]})},d))}),!l&&o.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"text-muted-foreground mb-4",children:s?"No services match your search":"No additional services available yet"}),s&&e.jsx(B,{variant:"outline",onClick:()=>t(""),children:"Clear Search"})]}),!l&&o.length>0&&e.jsx("div",{className:n==="grid"?"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6":"space-y-4",children:o.map(c=>e.jsxs(fe,{className:`group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer ${n==="list"?"flex flex-row":""}`,onClick:()=>a(`/additional-services/${c.id}`),children:[e.jsx("div",{className:`relative overflow-hidden bg-muted ${n==="list"?"w-48 shrink-0":"aspect-[3/2]"}`,children:c.preview_image_url?e.jsx("img",{src:c.preview_image_url,alt:c.name,className:"w-full h-full object-contain group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(un,{className:"h-8 w-8"})})}),e.jsxs(Ee,{className:`p-4 flex flex-col ${n==="list"?"flex-1":""}`,children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:c.name}),c.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 flex-1",children:qz(c.description)})]})]},c.id))})]})})},KVs=()=>{const{serviceId:s}=bi(),t=Ln(),{data:n,isLoading:r}=dt({queryKey:["additional-service",s],queryFn:async()=>{const{data:a,error:i}=await q.from("additional_services").select("*").eq("id",s).eq("is_published",!0).single();if(i)throw i;return a},enabled:!!s});return r?e.jsx(Cs,{title:"Loading...",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-64 w-full rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full"})]})}):n?e.jsx(Cs,{title:n.name,children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/additional-services"),className:"gap-2",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back to Services"]}),e.jsx(fe,{className:"overflow-hidden",children:e.jsx("div",{className:"relative bg-muted",children:n.preview_image_url?e.jsx("img",{src:n.preview_image_url,alt:n.name,className:"w-full h-auto max-h-[500px] object-contain mx-auto"}):e.jsx("div",{className:"w-full h-64 flex items-center justify-center text-muted-foreground",children:e.jsx(un,{className:"h-16 w-16"})})})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground mb-2",children:n.name}),e.jsxs("div",{className:"flex items-center text-sm text-muted-foreground",children:[e.jsx(yr,{className:"h-4 w-4 mr-1"}),"Published ",Ss(new Date(n.publish_date),"MMMM d, yyyy")]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none text-muted-foreground [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:n.description}}),e.jsx("div",{className:"pt-4 border-t",children:e.jsxs(B,{size:"lg",className:"gap-2",onClick:()=>window.open(n.signup_link_url,"_blank"),children:[e.jsx(tr,{className:"h-5 w-5"}),"Sign Up Now"]})})]})})]})}):e.jsx(Cs,{title:"Not Found",children:e.jsxs("div",{className:"max-w-4xl mx-auto text-center py-12",children:[e.jsx("h2",{className:"text-2xl font-bold text-foreground mb-4",children:"Service Not Found"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"The service you're looking for doesn't exist or has been removed."}),e.jsxs(B,{onClick:()=>t("/additional-services"),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"}),"Back to Services"]})]})})},SF=[{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 YVs(){const[s,t]=N.useState(SF[0].id),n=SF.find(r=>r.id===s)||SF[0];return e.jsx(Cs,{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(US,{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(us,{value:s,onValueChange:t,children:[e.jsx(ls,{className:"w-full",children:e.jsx(hs,{placeholder:"Select a tool"})}),e.jsx(cs,{children:SF.map(r=>e.jsx(Ze,{value:r.id,children:r.name},r.id))})]})}),e.jsx("div",{className:"hidden md:block",children:e.jsx(Fr,{value:s,onValueChange:t,className:"w-full",children:e.jsx(Rr,{className:"w-full flex-wrap h-auto gap-1 bg-muted p-1",children:SF.map(r=>e.jsx(Zt,{value:r.id,className:"flex-1 min-w-[150px] text-xs lg:text-sm whitespace-normal h-auto py-2",children:r.name},r.id))})})}),e.jsx("div",{className:"flex justify-center",children:e.jsx("div",{className:"w-full max-w-[700px]",dangerouslySetInnerHTML:{__html:n.iframe}})})]})})}const nZe="agent-os-onboarding-completed",sG=[{icon:tx,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:im,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:An,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:Cl,iconColor:"text-white",bgGradient:"from-emerald-500 via-teal-500 to-cyan-500",title:"Touchpoint Plans",description:"Assign automated touchpoint schedules to your contact groups. Each plan tells you exactly who to reach out to and when—with pre-written scripts to make it easy.",highlights:["Pre-built 12-month plans","Create your own custom plans","Scripts for calls, texts, and emails","Automatic daily action items"]},{icon:Oi,iconColor:"text-white",bgGradient:"from-orange-500 via-amber-500 to-yellow-500",title:"Popbys",description:"Pop-by visits are one of the most powerful ways to stay top-of-mind. Track your gift drop-offs and see who's due for a visit on the map.",highlights:["Track pop-by gift ideas","Set visit frequency by contact type","Log completed pop-bys","Map view for route planning"]},{icon:_o,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"]}],ZVs=()=>{const[s,t]=N.useState(!1),[n,r]=N.useState(0),[a,i]=N.useState(!1);N.useEffect(()=>{if(!localStorage.getItem(nZe)){const y=setTimeout(()=>t(!0),500);return()=>clearTimeout(y)}},[]);const l=()=>{n{r(n+1),i(!1)},150)):c()},o=()=>{c()},c=()=>{localStorage.setItem(nZe,"true"),t(!1)},d=sG[n],u=d.icon,h=n===sG.length-1,p=f=>{f||c(),t(f)};return e.jsx(_s,{open:s,onOpenChange:p,children:e.jsxs(bs,{className:"sm:max-w-lg overflow-hidden p-0 gap-0",children:[e.jsxs("div",{className:`relative bg-gradient-to-br ${d.bgGradient} p-8 pb-12 transition-all duration-500`,children:[e.jsxs("div",{className:"absolute inset-0 overflow-hidden",children:[e.jsx("div",{className:"absolute -top-4 -right-4 w-32 h-32 bg-white/10 rounded-full blur-2xl animate-pulse"}),e.jsx("div",{className:"absolute -bottom-8 -left-8 w-40 h-40 bg-white/10 rounded-full blur-3xl animate-pulse",style:{animationDelay:"1s"}}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-64 h-64 bg-white/5 rounded-full blur-3xl"})]}),e.jsxs("div",{className:`relative mx-auto flex h-20 w-20 items-center justify-center transition-all duration-300 ${a?"scale-75 opacity-0":"scale-100 opacity-100"}`,children:[e.jsx("div",{className:"absolute inset-0 bg-white/20 rounded-2xl blur-xl"}),e.jsx("div",{className:"relative flex h-20 w-20 items-center justify-center rounded-2xl bg-white/20 backdrop-blur-sm border border-white/30 shadow-2xl",children:e.jsx(u,{className:`h-10 w-10 ${d.iconColor} drop-shadow-lg`})})]}),n===0&&e.jsxs("div",{className:"absolute top-4 right-4 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm border border-white/30 text-white text-xs font-medium flex items-center gap-1.5",children:[e.jsx(un,{className:"h-3 w-3"}),"Beta"]})]}),e.jsxs("div",{className:"p-6 pt-4",children:[e.jsxs(js,{className:"text-center sm:text-center pb-2",children:[e.jsx(ws,{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(Jn,{className:`text-base pt-2 transition-all duration-300 delay-75 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.description})]}),d.highlights&&e.jsx("div",{className:`space-y-2.5 py-4 transition-all duration-300 delay-100 ${a?"translate-y-2 opacity-0":"translate-y-0 opacity-100"}`,children:d.highlights.map((f,y)=>e.jsxs("div",{className:"flex items-center gap-3 group",style:{transitionDelay:`${150+y*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(Lr,{className:"h-3.5 w-3.5 text-white"})}),e.jsx("span",{className:"text-sm text-muted-foreground group-hover:text-foreground transition-colors",children:f})]},y))}),e.jsx("div",{className:"flex justify-center gap-2 py-4",children:sG.map((f,y)=>e.jsx("button",{onClick:()=>{y!==n&&(i(!0),setTimeout(()=>{r(y),i(!1)},150))},className:`h-2 rounded-full transition-all duration-300 ${y===n?"w-8 bg-gradient-to-r "+d.bgGradient:y{const{user:s}=vs();return dt({queryKey:["contact-snoozes",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_snoozes").select("*").gte("snoozed_until",new Date().toISOString());if(n)throw n;return t},enabled:!!s})},XVs=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async({contactId:n,days:r})=>{if(!(t!=null&&t.id))throw new Error("Not authenticated");const a=Bl(new Date,r);await q.from("contact_snoozes").delete().eq("contact_id",n);const{error:i}=await q.from("contact_snoozes").insert({contact_id:n,owner_user_id:t.id,snoozed_until:a.toISOString()});if(i)throw i},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),s.invalidateQueries({queryKey:["today-actions"]}),s.invalidateQueries({queryKey:["popby-logs"]}),Br({title:"Touch snoozed!",description:"Contact has been snoozed."})},onError:n=>{Br({title:"Error snoozing contact",description:n.message,variant:"destructive"})}})},JVs=()=>{const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("contact_snoozes").delete().eq("contact_id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["contact-snoozes"]}),Br({title:"Snooze cancelled"})},onError:t=>{Br({title:"Error cancelling snooze",description:t.message,variant:"destructive"})}})},eHs=[{label:"1 week",days:7},{label:"2 weeks",days:14},{label:"1 month",days:30}];function m1e({open:s,onOpenChange:t,contactId:n,contactName:r}){const[a,i]=N.useState(null),l=XVs(),o=async()=>{a&&(await l.mutateAsync({contactId:n,days:a}),i(null),t(!1))},c=d=>Ss(Bl(new Date,d),"MMM d, yyyy");return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Snooze Touch"]}),e.jsxs(Jn,{children:["Postpone the next scheduled touch for ",r,". Select how long to snooze."]})]}),e.jsx("div",{className:"space-y-3 py-4",children:eHs.map(d=>e.jsxs("button",{type:"button",onClick:()=>i(d.days),className:Mt("w-full flex items-center justify-between p-3 rounded-lg border transition-colors",a===d.days?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"),children:[e.jsx("span",{className:"font-medium",children:d.label}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(yr,{className:"h-3.5 w-3.5"}),"Until ",c(d.days)]})]},d.days))}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:o,disabled:!a||l.isPending,children:l.isPending?"Snoozing...":"Snooze Touch"})]})]})})}const tHs={Crown:hf,FileText:br,Users:An,Globe:lc,Star:oa,Phone:Cr,MessageSquare:Ai,PenTool:ZS,Video:fr,Gift:Oi};function sHs({actions:s,onMarkComplete:t,onViewScript:n,isLoading:r,buildSmsLink:a,buildEmailLink:i,onGmailCompose:l}){const o=Ln(),[c,d]=N.useState("name"),[u,h]=N.useState("asc"),[p,f]=N.useState(null),[y,_]=N.useState(""),v=E=>{c===E?h(O=>O==="asc"?"desc":"asc"):(d(E),h("asc"))},j=N.useMemo(()=>[...s].sort((E,O)=>{var I,F;let D=0;switch(c){case"name":{const z=`${E.contact.first_name} ${E.contact.last_name||""}`.toLowerCase(),H=`${O.contact.first_name} ${O.contact.last_name||""}`.toLowerCase();D=z.localeCompare(H);break}case"relationship_type":D=(E.relationshipTypeName||"").localeCompare(O.relationshipTypeName||"");break;case"action_type":D=(((I=E.actionType)==null?void 0:I.name)||"").localeCompare(((F=O.actionType)==null?void 0:F.name)||"");break;case"last_touch":D=(E.monthNumber||0)-(O.monthNumber||0);break}return u==="asc"?D:-D}),[s,c,u]),w=E=>tHs[E||"Phone"]||Cr,S=({field:E,children:O})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>v(E),children:[O,c===E?u==="asc"?e.jsx(Iu,{className:"ml-2 h-4 w-4"}):e.jsx(sm,{className:"ml-2 h-4 w-4"}):e.jsx(ah,{className:"ml-2 h-4 w-4 opacity-50"})]}),A=(E,O,D)=>{f(E),_(`${O} ${D||""}`.trim())};return s.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/50",children:[e.jsx(Tt,{className:"w-[180px]",children:e.jsx(S,{field:"name",children:"Contact"})}),e.jsx(Tt,{className:"w-[130px]",children:e.jsx(S,{field:"relationship_type",children:"Type"})}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(S,{field:"action_type",children:"Action"})}),e.jsx(Tt,{className:"w-[130px]",children:"Phone"}),e.jsx(Tt,{className:"w-[200px]",children:"Quick Actions"})]})}),e.jsx(da,{children:j.map((E,O)=>{var Z,Y,W,ee,se,oe;const D=E.isSpecialDate,I=E.specialDateType,F=D?I==="birthday"?Ah:Or:w(((Z=E.actionType)==null?void 0:Z.icon)||null),z=E.contact.phone,H=E.contact.email;return e.jsxs(Hs,{className:Mt("hover:bg-muted/50 transition-colors",D&&I==="birthday"&&"bg-pink-50/50 dark:bg-pink-950/20",D&&I==="anniversary"&&"bg-purple-50/50 dark:bg-purple-950/20"),children:[e.jsx(ht,{className:"font-medium",children:e.jsx("div",{children:e.jsxs("button",{onClick:()=>o(`/mission-control/contacts/${E.contact.id}`),className:"truncate max-w-[160px] text-left hover:text-primary hover:underline transition-colors",children:[E.contact.first_name," ",E.contact.last_name]})})}),e.jsx(ht,{children:E.relationshipTypeName?e.jsx(Ue,{variant:"secondary",className:"text-xs",children:E.relationshipTypeName}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ht,{children:e.jsx("div",{className:"flex items-center gap-1.5",children:D?e.jsx(Ue,{className:Mt("gap-1",I==="birthday"&&"bg-pink-500 hover:bg-pink-600",I==="anniversary"&&"bg-purple-500 hover:bg-purple-600"),children:I==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Ah,{className:"h-3 w-3"})," Birthday"]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-3 w-3"})," Anniversary"]})}):e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(F,{className:"h-3 w-3"}),(Y=E.actionType)==null?void 0:Y.name]})})}),e.jsx(ht,{children:z?e.jsx("span",{className:"text-sm font-mono",children:E.contact.phone}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-1",children:[z&&e.jsx("a",{href:`tel:${E.contact.phone}`,className:"p-1.5 rounded bg-primary/10 hover:bg-primary/20 text-primary transition-colors",title:"Call",children:e.jsx(Cr,{className:"h-3.5 w-3.5"})}),z&&e.jsx("a",{href:a(E.contact.phone,(W=E.script)==null?void 0:W.script_body,E.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(Ai,{className:"h-3.5 w-3.5"})}),H&&(l?e.jsx("button",{onClick:()=>l({id:E.contact.id,first_name:E.contact.first_name,last_name:E.contact.last_name,email:E.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(Gs,{className:"h-3.5 w-3.5"})}):e.jsx("a",{href:i(E.contact.email,(ee=E.script)==null?void 0:ee.script_body,(se=E.script)==null?void 0:se.email_subject,(oe=E.actionType)==null?void 0:oe.name,E.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(Gs,{className:"h-3.5 w-3.5"})})),D&&e.jsxs("button",{onClick:()=>{const he=`${E.contact.first_name}${E.contact.last_name?" "+E.contact.last_name:""}`,ce=I==="birthday"?"birthday":"home_anniversary",me=new URLSearchParams({cardType:ce,contactId:E.contact.id,name:he,...E.contact.address?{address:E.contact.address}:{},...I==="anniversary"&&E.contact.home_anniversary?{date:E.contact.home_anniversary}:{}});o(`/mission-control/card-studio?${me.toString()}`)},className:Mt("h-7 px-2 rounded text-xs font-semibold flex items-center gap-1 transition-colors",I==="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 ${I==="birthday"?"Birthday":"Anniversary"} Card`,children:[e.jsx(Gs,{className:"h-3.5 w-3.5"}),"Send Card"]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:()=>A(E.contact.id,E.contact.first_name,E.contact.last_name),title:"Snooze",children:e.jsx(gf,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{variant:"default",size:"sm",className:"h-7 px-2 text-xs ml-1",onClick:()=>{var he;return t(E.contact.id,E.actionType.id,(he=E.script)==null?void 0:he.id)},disabled:r,children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1"}),"Done"]})]})})]},`${E.contact.id}-${O}`)})})]})}),e.jsx(m1e,{open:!!p,onOpenChange:E=>!E&&f(null),contactId:p||"",contactName:y})]})}function nHs({onSelect:s}){const{user:t}=vs(),[n,r]=N.useState("root"),[a,i]=N.useState(null),{data:l=[],isLoading:o}=dt({queryKey:["agent-email-template-categories"],queryFn:async()=>{const{data:j,error:w}=await q.from("email_template_categories").select("*").order("sort_order");if(w)throw w;return j}}),{data:c=[],isLoading:d}=dt({queryKey:["agent-email-templates",a],enabled:n==="category"&&!!a,queryFn:async()=>{const{data:j,error:w}=await q.from("agent_email_templates").select("*").eq("is_active",!0).eq("category_id",a).order("sort_order");if(w)throw w;return j}}),{data:u=[],isLoading:h}=dt({queryKey:["picker-campaign-templates",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:j,error:w}=await q.from("campaign_templates").select("id,name,subject,body_html,is_shared,user_id,updated_at").or(`user_id.eq.${t.id},is_shared.eq.true`).order("updated_at",{ascending:!1});if(w)throw w;return j}}),p=u.filter(j=>j.user_id===(t==null?void 0:t.id)&&!j.is_shared),f=u.filter(j=>j.is_shared),y=l.find(j=>j.id===a);if(o)return e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})});const _=j=>{s({title:j.name,subject:j.subject,body:j.body_html})};if(n==="root")return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Your templates"}),e.jsxs("button",{onClick:()=>r("my"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(Wi,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"My Saved Templates"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[p.length," template",p.length===1?"":"s"," you've created"]})]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"})]}),e.jsxs("button",{onClick:()=>r("shared"),className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-md bg-blue-500/10 text-blue-600 dark:text-blue-400 flex items-center justify-center",children:e.jsx(lc,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"Shared Library"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[f.length," team template",f.length===1?"":"s"]})]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-1",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground px-1 mb-1.5",children:"Quick scripts by category"}),e.jsx("div",{className:"max-h-[200px] overflow-y-auto space-y-1 pr-1",children:l.map(j=>e.jsxs("button",{onClick:()=>{i(j.id),r("category")},className:"w-full flex items-center justify-between p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx("span",{className:"text-lg",children:j.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:j.name}),j.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:j.description})]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0"})]},j.id))})]})]});const v=e.jsxs("button",{onClick:()=>{r("root"),i(null)},className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground transition-colors",children:[e.jsx(ml,{className:"h-3.5 w-3.5"}),"Back"]});return n==="my"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(Wi,{className:"h-3.5 w-3.5"})," My Saved Templates"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):p.length===0?e.jsxs("div",{className:"text-center py-6 space-y-2",children:[e.jsx(un,{className:"h-6 w-6 text-muted-foreground mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You haven't created any templates yet."}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Create beautiful templates in ",e.jsx("span",{className:"font-medium",children:"Email Templates"})," in the sidebar — they'll appear here."]})]}):e.jsx(di,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:p.map(j=>e.jsxs("button",{onClick:()=>_(j),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:j.name}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:j.subject||"(no subject)"})]},j.id))})})]}):n==="shared"?e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx(lc,{className:"h-3.5 w-3.5"})," Shared Library"]}),h?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No shared templates yet."}):e.jsx(di,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:f.map(j=>e.jsxs("button",{onClick:()=>_(j),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:j.name}),e.jsx(Ue,{variant:"secondary",className:"text-[10px] shrink-0",children:"Shared"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:j.subject||"(no subject)"})]},j.id))})})]}):e.jsxs("div",{className:"space-y-2",children:[v,e.jsxs("p",{className:"text-xs font-medium flex items-center gap-1.5",children:[e.jsx("span",{children:y==null?void 0:y.icon})," ",y==null?void 0:y.name]}),d?e.jsx("div",{className:"flex items-center justify-center py-6",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):c.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No templates in this category"}):e.jsx(di,{className:"max-h-[280px]",children:e.jsx("div",{className:"space-y-1",children:c.map(j=>e.jsxs("button",{onClick:()=>s(j),className:"w-full p-2.5 rounded-lg border hover:bg-accent transition-colors text-left",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"font-medium text-sm",children:j.title}),j.tone&&e.jsx(Ue,{variant:"secondary",className:"text-[10px] shrink-0",children:j.tone})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 line-clamp-1",children:j.subject})]},j.id))})})]})}function p1e(){const{user:s}=vs(),t=Kt(),{data:n,isLoading:r}=dt({queryKey:["contact-intake-page",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:d,error:u}=await q.from("contact_intake_pages").select("*").eq("user_id",s.id).maybeSingle();if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),a=yt({mutationFn:async d=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:u,error:h}=await q.from("contact_intake_pages").insert({user_id:s.id,slug:d.toLowerCase().replace(/[^a-z0-9-]/g,"-")}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ae.success("Connect page created!")},onError:d=>{var u;(u=d.message)!=null&&u.includes("duplicate")?ae.error("That slug is already taken. Try another."):ae.error("Failed to create page")}}),i=yt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page");const{error:u}=await q.from("contact_intake_pages").update({...d,updated_at:new Date().toISOString()}).eq("id",n.id);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-intake-page"]}),ae.success("Page updated!")},onError:()=>ae.error("Failed to update page")}),{data:l=[],isLoading:o}=dt({queryKey:["contact-intake-submissions",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:d,error:u}=await q.from("contact_intake_submissions").select("*").eq("agent_user_id",s.id).order("created_at",{ascending:!1}).limit(100);if(u)throw u;return d},enabled:!!(s!=null&&s.id)}),c=yt({mutationFn:async d=>{if(!(n!=null&&n.id))throw new Error("No intake page. Create your Connect page first.");const{data:u,error:h}=await q.from("contact_intake_tokens").insert({contact_id:d,intake_page_id:n.id}).select("token").single();if(h)throw h;return`${window.location.origin}/connect/${n.slug}?t=${u.token}`}});return{intakePage:n,isLoading:r,createPage:a,updatePage:i,submissions:l,loadingSubmissions:o,generateUpdateLink:c}}function n_t({value:s,onChange:t,userId:n,placeholder:r}){const[a,i]=N.useState(!1),[l,o]=N.useState([]),[c,d]=N.useState(!1),[u,h]=N.useState(0),p=N.useRef(null),f=N.useRef(null);N.useEffect(()=>{const _=v=>{p.current&&!p.current.contains(v.target)&&i(!1)};return document.addEventListener("mousedown",_),()=>document.removeEventListener("mousedown",_)},[]),N.useEffect(()=>{f.current&&clearTimeout(f.current);const _=s.trim();if(!n||_.length<1||_.includes("@")&&_.indexOf("@")>0&&/\S+@\S+\.\S+/.test(_)){o([]);return}return f.current=setTimeout(async()=>{d(!0);const v=`%${_}%`,j=q,{data:w,error:S}=await j.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",n).not("email","is",null).or(`first_name.ilike.${v},last_name.ilike.${v},email.ilike.${v}`).order("first_name",{ascending:!0}).limit(8);d(!1),!S&&w&&(o(w),h(0),i(w.length>0))},180),()=>{f.current&&clearTimeout(f.current)}},[s,n]);const y=_=>{_.email&&(t(_.email),i(!1))};return e.jsxs("div",{ref:p,className:"relative",children:[e.jsx(ye,{id:"gmail-to",value:s,onChange:_=>t(_.target.value),onFocus:()=>l.length>0&&i(!0),onKeyDown:_=>{!a||l.length===0||(_.key==="ArrowDown"?(_.preventDefault(),h(v=>Math.min(v+1,l.length-1))):_.key==="ArrowUp"?(_.preventDefault(),h(v=>Math.max(v-1,0))):_.key==="Enter"?(_.preventDefault(),y(l[u])):_.key==="Escape"&&i(!1))},placeholder:r||"Start typing a name or email...",autoComplete:"off"}),a&&e.jsx("div",{className:"absolute z-50 mt-1 w-full rounded-md border bg-popover shadow-lg max-h-72 overflow-y-auto",children:c&&l.length===0?e.jsxs("div",{className:"px-3 py-2 text-sm text-muted-foreground flex items-center gap-2",children:[e.jsx(rs,{className:"h-3 w-3 animate-spin"})," Searching..."]}):l.map((_,v)=>{const j=[_.first_name,_.last_name].filter(Boolean).join(" ")||"(No name)";return e.jsxs("button",{type:"button",onMouseEnter:()=>h(v),onClick:()=>y(_),className:`w-full flex items-center gap-2 px-3 py-2 text-left text-sm border-b last:border-b-0 ${v===u?"bg-accent":"bg-popover"}`,children:[e.jsx(Wi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium truncate",children:j}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:_.email})]})]},_.id)})})]})}function rHs(s){if(!/<[a-z][\s\S]*>/i.test(s)||typeof window>"u")return s;const t=s.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),n=document.createElement("div");return n.innerHTML=t,(n.textContent||n.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()}const aNe=25*1024*1024,rZe=Math.floor(6.5*1024*1024),aHs=750*1024,i2=50,iHs=["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 nG(s){return s<1024?s+" B":s<1024*1024?(s/1024).toFixed(1)+" KB":(s/(1024*1024)).toFixed(1)+" MB"}function oHs(s){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{const a=r.result;t(a.split(",")[1])},r.onerror=n,r.readAsDataURL(s)})}function lHs(s){if(!s)return"";const t=s.trim();return t.split(/\s+/)[0]||t}function o2(s,t){const n=lHs(t.first_name),r=t.last_name||"";let a=s.replace(/\{\{first_name\}\}/gi,n).replace(/\{\{last_name\}\}/gi,r).replace(/\{\{full_name\}\}/gi,`${n} ${r}`.trim());return t.updateLink&&(a=a.replace(/\{\{update_link\}\}/gi,t.updateLink)),a}function Xv({open:s,onOpenChange:t,contact:n,bulkContacts:r,defaultSubject:a="",defaultBody:i="",gmailEmail:l,onSendComplete:o,sendSource:c,logTouchpoint:d=!0}){const{user:u}=vs(),h=Kt(),{isReady:p,settings:f}=mR(),{data:y}=d1e(),[_,v]=N.useState(!1),{intakePage:j}=p1e(),w=j?`https://contacts.relevelup.com/${j.slug}`:null,S=!!r&&r.length>0,A=p,E=S?r:n?[n]:[],O=E[0],D=S?Math.ceil(E.length/i2):1,I=S&&E.length>i2,[F,z]=N.useState((O==null?void 0:O.email)||""),[H,Z]=N.useState(a),[Y,W]=N.useState(i),[ee,se]=N.useState(!1),[oe,he]=N.useState(!1),[ce,me]=N.useState([]),le=N.useRef(new Map),[ve,ge]=N.useState(a),[Te,Ie]=N.useState(i),[Ce,Me]=N.useState("composing"),[Pe,Re]=N.useState(0),[Ae,Be]=N.useState(0),[we,Je]=N.useState(0),[ke,it]=N.useState(0),je=N.useRef(!1),[He,$e]=N.useState(null);N.useEffect(()=>{if(s){const zt=/<[a-z][\s\S]*>/i.test(i),As=zt?rHs(i):i;at.current=zt?{plain:As,html:i}:null,z((O==null?void 0:O.email)||""),ge(a),Ie(As),Z(o2(a,O||{first_name:""})),W(o2(As,O||{first_name:""})),he(!a&&!i),me([]),le.current=new Map,Me("composing"),Re(0),Be(0),Je(0),it(0),je.current=!1,$e(null)}},[s,O,a,i]);const Ke=async zt=>{const As=zt.target.files;if(!As)return;const Xt=ce.reduce(($s,an)=>$s+an.size,0),Qs=[];let ks=Xt;for(const $s of Array.from(As)){if(!iHs.includes($s.type)){ae.error(`${$s.name}: Unsupported file type`);continue}if(ks+$s.size>aNe){ae.error(`Total attachments exceed ${nG(aNe)} limit`);break}try{const an=await oHs($s);Qs.push({name:$s.name,type:$s.type,size:$s.size,data:an}),ks+=$s.size}catch{ae.error(`Failed to read ${$s.name}`)}}me($s=>[...$s,...Qs]),zt.target.value=""},Ge=zt=>{const As=ce[zt];As&&le.current.delete(`${As.name}::${As.size}`),me(Xt=>Xt.filter((Qs,ks)=>ks!==zt))},rt=async()=>{if(ce.length===0||!u)return{inline:[],paths:[]};const zt=[],As=[];for(const Xt of ce){const Qs=`${Xt.name}::${Xt.size}`,ks=le.current.get(Qs);if(ks){As.push(ks);continue}if(Xt.size<=aHs){zt.push(Xt);continue}const $s=Xt.name.replace(/[^a-zA-Z0-9._-]/g,"_"),an=`${u.id}/${Date.now()}-${$s}`,tn=atob(Xt.data),er=new Uint8Array(tn.length);for(let Pn=0;Pn{if(!/<[a-z][\s\S]*>/i.test(zt)||typeof window>"u")return zt;const As=zt.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*[^>]*>/gi,` `).replace(/<\s*li\b[^>]*>/gi,"• ").replace(/<\s*(p|div|h[1-6]|tr)\b[^>]*>/gi,""),Xt=document.createElement("div");return Xt.innerHTML=As,(Xt.textContent||Xt.innerText||"").replace(/\u00a0/g," ").replace(/\n{3,}/g,` `).trim()},at=N.useRef(null),Ye=zt=>{const As=/<[a-z][\s\S]*>/i.test(zt.body),Xt=As?tt(zt.body):zt.body;at.current=As?{plain:Xt,html:zt.body}:null,ge(zt.subject),Ie(Xt),Z(o2(zt.subject,O||{first_name:""})),W(o2(Xt,O||{first_name:""})),he(!1)},ut=zt=>/<\s*(p|div|span|table|tr|td|img|br|h[1-6]|a|body|html|section|article|ul|ol|li)\b/i.test(zt)?zt:zt.split(/\n\n+/).map(As=>`

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

`).join(""),_t=(zt,As)=>{const Xt="https://relzejiswnotikjgvjhz.supabase.co/functions/v1/bulk-email-track";let Qs=zt.replace(/]*?)href=(["'])(.*?)\2([^>]*)>/gi,($s,an,tn,er,xn)=>{if(!er||/^(mailto:|tel:|#)/i.test(er)||er.includes("/bulk-email-track")||er.includes("/ses-campaign-track"))return $s;const Pn=`${Xt}?s=${As}&t=click&u=${encodeURIComponent(er)}`;return``});const ks=``;return/<\/body>/i.test(Qs)?Qs=Qs.replace(/<\/body>/i,`${ks}`):Qs=`${Qs}${ks}`,Qs},bt=async zt=>{if(!(zt!=null&&zt.email))return ae.error("Please enter a recipient email"),!1;const As=zt||{first_name:""},Xt=o2(ve,As),Qs=at.current,ks=Qs&&Te===Qs.plain,$s=o2(ks?Qs.html:Te,As);let an=ks?$s:ut($s);const tn=u&&zt.id?crypto.randomUUID():null;tn&&(an=_t(an,tn));try{if(u&&zt.email){const Pn=new Date(Date.now()-6e5).toISOString(),{data:Qn}=await q.from("bulk_email_sends").select("id").eq("user_id",u.id).eq("contact_email",zt.email).eq("subject",Xt).gte("sent_at",Pn).limit(1);if(Qn&&Qn.length>0)return console.log(`Skipping duplicate send to ${zt.email} (same subject within 10 min)`),ae.info(`Skipped ${zt.first_name||zt.email} — already sent this in the last 10 min`),!0}const{inline:er,paths:xn}=await rt();if(A){const Pn=(f==null?void 0:f.display_name)||"ReLevelUp",Qn=`${Pn.toLowerCase().replace(/[^a-z]/g,".")}@send.relevelup.com`,sa=`${Pn} <${Qn}>`;let na=xn[0];if(!na&&er.length>0&&u){const Ar=er[0],Hn=Ar.name.replace(/[^a-zA-Z0-9._-]/g,"_"),Ts=`${u.id}/${Date.now()}-${Hn}`,Un=atob(Ar.data),ir=new Uint8Array(Un.length);for(let ts=0;ts({name:sa,type:na,data:Es})),attachment_paths:xn}});if(Qn)throw Qn;if(!(Pn!=null&&Pn.success))throw new Error((Pn==null?void 0:Pn.error)||"Failed to send")}if(u&&zt.id&&tn&&(await q.from("bulk_email_sends").insert({id:tn,user_id:u.id,contact_id:zt.id,contact_email:zt.email,subject:Xt,source:c||(A?"ses_bulk":"sphere_gaps")}),d))try{await q.from("contact_touch_logs").insert({owner_user_id:u.id,contact_id:zt.id,action_type_id:"9a88a47c-cb2a-4401-a2b5-111a76b19f9d",notes:`Mass Email: ${Xt}`,completed_at:new Date().toISOString()})}catch(Pn){console.warn("touch log insert failed",Pn)}return!0}catch(er){return console.error("Send error:",er),ae.error("Failed to send to "+zt.first_name+": "+(er instanceof Error?er.message:"Unknown error")),!1}},$t=()=>{const zt=Pe*i2;return E.slice(zt,zt+i2)},Yt=async()=>{if(!H||!Y){ae.error("Please fill in subject and message");return}const zt=$t();se(!0),Me("sending");let As=0,Xt=0;for(let ks=0;kssetTimeout(an,150));Be(ks=>ks+As),Je(ks=>ks+Xt),se(!1),h.invalidateQueries({queryKey:["bulk-email-sends"]}),h.invalidateQueries({queryKey:["contact-touch-logs"]}),h.invalidateQueries({queryKey:["contacts-last-touch"]}),Pe>=D-1||je.current?Me("all_done"):Me("batch_complete")},Ds=async()=>{if(!H||!Y){ae.error("Please fill in subject and message");return}if(A&&y&&!y.hasVerifiedSes&&!y.hasGmail){v(!0);return}if(!S){const zt=O||{id:"",first_name:"",last_name:"",email:F.trim()};if(!zt.email){ae.error("Please enter a recipient email");return}se(!0);try{await bt(zt)&&(h.invalidateQueries({queryKey:["bulk-email-sends"]}),ae.success("Email sent successfully!"),t(!1),o==null||o())}finally{se(!1)}return}await Yt()},Ls=async()=>{Re(zt=>zt+1),it(0),await new Promise(zt=>setTimeout(zt,50)),await Yt()};N.useEffect(()=>{},[Pe]);const xs=()=>{if(ee){je.current=!0;return}t(!1),o==null||o()},Lt=Pe*i2,Jt=Math.min(Lt+i2,E.length),gt=S&&E.length>0?Math.round((Ae+we)/E.length*100):0;return e.jsxs(_s,{open:s,onOpenChange:xs,children:[e.jsxs(bs,{className:"sm:max-w-[600px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:`h-5 w-5 ${A?"text-orange-500":"text-red-500"}`}),S?`Send to ${E.length} Contacts`:"Compose Email"]}),A?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-medium",children:"Mass Email"})," (reply-to: ",f==null?void 0:f.reply_to_email,")"]}):l?e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:l})]}):null,S&&Ce==="composing"&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Composing email for ",e.jsxs("span",{className:"font-medium",children:[E.length," contacts"]}),". You'll review each personalized email before sending."]})]}),Ce==="sending"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(rs,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending batch ",Pe+1," of ",D,"..."]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[ke," of ",$t().length," in this batch"]})]}),e.jsx(fi,{value:ke/$t().length*100,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-xs text-muted-foreground",children:[e.jsxs("span",{children:["Overall: ",Ae+we," / ",E.length]}),e.jsxs("span",{children:[Ae," sent • ",we," failed"]})]}),e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{je.current=!0},children:"Stop Sending"})]}),Ce==="batch_complete"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(vr,{className:"h-8 w-8 text-emerald-500 mx-auto"}),e.jsxs("p",{className:"font-medium",children:["Batch ",Pe+1," Complete!"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Ae," sent, ",we," failed so far"]})]}),e.jsx(fi,{value:gt,className:"h-2"}),e.jsxs("p",{className:"text-xs text-center text-muted-foreground",children:[E.length-Ae-we," contacts remaining (",D-Pe-1," batches left)"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:xs,children:"Done for Now"}),e.jsxs(B,{className:"flex-1 gap-2",onClick:Ls,children:[e.jsx(lr,{className:"h-4 w-4"}),"Send Next ",Math.min(i2,E.length-Jt)," Contacts"]})]})]}),Ce==="all_done"&&e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx(vr,{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:[Ae," emails sent successfully",we>0&&e.jsxs("span",{className:"text-destructive",children:[" • ",we," failed"]})]})]}),e.jsx(B,{className:"w-full",onClick:xs,children:"Close"})]}),Ce==="composing"&&e.jsxs("div",{className:"space-y-4",children:[oe?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(br,{className:"h-4 w-4"})," Choose a Template"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>he(!1),className:"h-7 px-2 text-xs",children:[e.jsx($n,{className:"h-3 w-3 mr-1"})," Write from scratch"]})]}),e.jsx(nHs,{onSelect:Ye})]}):e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",onClick:()=>he(!0),children:[e.jsx(br,{className:"h-4 w-4"}),"Browse Templates"]}),e.jsx(al,{}),!S&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"gmail-to",children:"To"}),e.jsx(n_t,{value:F,onChange:z,userId:u==null?void 0:u.id})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"gmail-subject",children:"Subject"}),e.jsx(ye,{id:"gmail-subject",value:H,onChange:zt=>{Z(zt.target.value),ge(zt.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(ne,{htmlFor:"gmail-body",children:"Message"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(Ue,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{W(zt=>zt+"{{first_name}}"),Ie(zt=>zt+"{{first_name}}")},children:"{{first_name}}"}),e.jsx(Ue,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-accent",onClick:()=>{W(zt=>zt+"{{last_name}}"),Ie(zt=>zt+"{{last_name}}")},children:"{{last_name}}"}),w&&e.jsx(Ue,{variant:"outline",className:"text-[10px] cursor-pointer hover:bg-primary/10 border-primary/40 text-primary",onClick:()=>{const zt=` When you get a sec, can you share your latest contact info with me? It only takes about a minute: ${w} `;W(As=>As+zt),Ie(As=>As+zt)},title:"Insert your Connect Page link",children:"+ Connect Page"})]})]}),e.jsx(Ms,{id:"gmail-body",value:Y,onChange:zt=>{W(zt.target.value),Ie(zt.target.value)},placeholder:"Write your message...",rows:10,className:"resize-y"}),S&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Use ","{{first_name}}",", ","{{last_name}}"," to personalize. You'll preview each recipient's email in the next step."]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"gap-2",onClick:()=>{var zt;return(zt=document.getElementById("gmail-attachments"))==null?void 0:zt.click()},disabled:ee,children:[e.jsx(YS,{className:"h-4 w-4"}),"Attach Files"]}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["PDF, images, Word, Excel (max ",nG(aNe)," 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:Ke})]}),ce.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:ce.map((zt,As)=>e.jsxs(Ue,{variant:"secondary",className:"gap-1.5 pl-2 pr-1 py-1",children:[e.jsx(YS,{className:"h-3 w-3"}),e.jsx("span",{className:"max-w-[140px] truncate text-xs",children:zt.name}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:["(",nG(zt.size),")"]}),e.jsx("button",{type:"button",onClick:()=>Ge(As),className:"ml-0.5 rounded-full p-0.5 hover:bg-muted",children:e.jsx($n,{className:"h-3 w-3"})})]},As))}),A&&ce.some(zt=>zt.size>rZe)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Files over ",nG(rZe)," will be sent as secure download links."]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),S?e.jsxs(B,{onClick:()=>{$e(E[0]||null),Me("reviewing")},disabled:!H||!Y,className:"gap-2",children:["Review Emails",e.jsx(Oa,{className:"h-4 w-4"})]}):e.jsxs(B,{onClick:Ds,disabled:ee||!H||!Y||!F.trim(),className:"gap-2",children:[ee?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"}),ee?"Sending...":"Send Email"]})]})]}),Ce==="reviewing"&&S&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("p",{className:"text-xs text-primary bg-primary/10 rounded-md px-2.5 py-1.5",children:["✉️ Click any recipient below to preview the ",e.jsx("span",{className:"font-semibold",children:"exact personalized email"})," they will receive."]}),I&&e.jsxs("p",{className:"text-xs text-amber-600 bg-amber-500/10 rounded-md px-2.5 py-1.5",children:["📦 ",E.length," contacts will be sent in ",D," batches of up to ",i2,". You'll confirm before each batch."]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ne,{children:["Recipients (",E.length,")"]}),e.jsx("div",{className:"bg-muted p-1.5 rounded-md space-y-0.5 max-h-32 overflow-y-auto",children:E.map(zt=>e.jsxs("div",{className:`text-sm px-2 py-1 rounded cursor-pointer transition-colors ${(He==null?void 0:He.id)===zt.id?"bg-primary/10 text-primary font-medium":"text-muted-foreground hover:bg-accent hover:text-foreground"}`,onClick:()=>$e(zt),children:[zt.first_name," ",zt.last_name," — ",zt.email]},zt.id))})]}),He&&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(Gs,{className:"h-3.5 w-3.5"}),"Preview for ",He.first_name," ",He.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:"})," ",He.email]}),e.jsxs("p",{children:[e.jsx("span",{className:"text-muted-foreground text-xs",children:"Subject:"})," ",o2(ve,He)]})]}),e.jsx(al,{}),e.jsx("div",{className:"text-sm whitespace-pre-wrap bg-background rounded p-2.5 max-h-40 overflow-y-auto border",children:o2(Te,He)})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>{Me("composing"),$e(null)},children:[e.jsx(qr,{className:"h-4 w-4 mr-1"}),"Back to Edit"]}),e.jsxs(B,{onClick:Ds,disabled:ee,className:"gap-2",children:[ee?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"}),I?`Send First ${i2}`:`Send to ${E.length}`]})]})]})]}),e.jsx(u1e,{open:_,onOpenChange:v,hasPending:!!(y!=null&&y.hasPendingSes),pendingEmails:y==null?void 0:y.pendingEmails})]})}function cHs(){const s=Ln(),{data:t}=ax(),{data:n}=aU(),r=Tye(),{isGmailConnected:a,gmailEmail:i}=Dh(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(new Set),p=wf(new Date),f=Bl(p,30),y=E=>{if(!E)return null;const O=E.split(/[-/T]/);if(O.length<3)return null;const D=parseInt(O[1],10)-1,I=parseInt(O[2],10);return isNaN(D)||isNaN(I)?null:new Date(p.getFullYear(),D,I)},_=N.useMemo(()=>{if(!t)return[];const E=[];for(const O of t){if(O.birthday){const D=y(O.birthday);D&&(ql(D,p)||Ov(D,p)&&yb(D,f))&&E.push({contact:O,type:"birthday",date:D,daysUntil:Vx(D,p),dateStr:O.birthday})}if(O.home_anniversary){const D=y(O.home_anniversary);D&&(ql(D,p)||Ov(D,p)&&yb(D,f))&&E.push({contact:O,type:"anniversary",date:D,daysUntil:Vx(D,p),dateStr:O.home_anniversary})}if(O.wedding_anniversary){const D=y(O.wedding_anniversary);D&&(ql(D,p)||Ov(D,p)&&yb(D,f))&&E.push({contact:O,type:"wedding_anniversary",date:D,daysUntil:Vx(D,p),dateStr:O.wedding_anniversary})}}return E.sort((O,D)=>O.daysUntil-D.daysUntil),E},[t]),v=E=>E==="birthday"?"Birthday":E==="wedding_anniversary"?"Wedding Anniversary":"Home Anniversary",j=async E=>{const O=(n==null?void 0:n.find(D=>D.name==="Call"))||(n==null?void 0:n[0]);if(O)try{await r.mutateAsync({contactId:E.contact.id,actionTypeId:O.id,notes:`${v(E.type)} outreach`}),h(D=>new Set(D).add(`${E.contact.id}-${E.type}`)),Br({title:"Touch logged!",description:`Logged outreach for ${E.contact.first_name}`})}catch{Br({title:"Error",description:"Failed to log touch",variant:"destructive"})}},w=E=>{const O=`${E.contact.first_name}${E.contact.last_name?" "+E.contact.last_name:""}`,D=E.type==="birthday"?"birthday":E.type==="wedding_anniversary"?"wedding_anniversary":"home_anniversary",I=new URLSearchParams({cardType:D,contactId:E.contact.id,name:O,...E.contact.address?{address:E.contact.address}:{},...(E.type==="anniversary"||E.type==="wedding_anniversary")&&E.dateStr?{date:E.dateStr}:{}});s(`/mission-control/card-studio?${I.toString()}`)},S=E=>E===0?"Today!":E===1?"Tomorrow":`${E} days`,A=E=>E===0?"bg-red-500/15 text-red-600 dark:text-red-400 border-red-500/30":E<=3?"bg-amber-500/15 text-amber-600 dark:text-amber-400 border-amber-500/30":E<=7?"bg-blue-500/15 text-blue-600 dark:text-blue-400 border-blue-500/30":"bg-muted text-muted-foreground border-border";return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:[e.jsx(Cl,{className:"h-5 w-5 text-primary"}),"Upcoming Milestones",e.jsx(Ue,{variant:"secondary",className:"text-xs font-normal",children:"Next 30 days"})]}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[_.length," event",_.length!==1?"s":""]})]})}),e.jsxs(Ee,{className:"space-y-2",children:[_.length===0&&e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ah,{className:"h-8 w-8 mx-auto mb-2 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No birthdays or anniversaries in the next 30 days."}),e.jsx("p",{className:"text-xs mt-1",children:"Add dates to your contacts to see upcoming milestones here."})]}),_.map((E,O)=>{var z,H;const D=`${E.contact.id}-${E.type}`,I=u.has(D),F=`${((z=E.contact.first_name)==null?void 0:z[0])||""}${((H=E.contact.last_name)==null?void 0:H[0])||""}`.toUpperCase();return e.jsxs("div",{className:Mt("p-3 rounded-lg border transition-colors",E.daysUntil===0&&E.type==="birthday"?"bg-pink-500/10 border-pink-500/30 dark:bg-pink-900/20 dark:border-pink-800/40":E.daysUntil===0&&(E.type==="anniversary"||E.type==="wedding_anniversary")?"bg-blue-500/10 border-blue-500/30 dark:bg-blue-900/20 dark:border-blue-800/40":E.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(Jr,{className:Mt("h-10 w-10",E.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(ea,{className:Mt("text-xs font-medium",E.type==="birthday"?"bg-pink-100 text-pink-700 dark:bg-pink-900/40 dark:text-pink-300":"bg-blue-100 text-blue-700 dark:bg-blue-900/40 dark:text-blue-300"),children:F})}),e.jsx("span",{className:"absolute -bottom-1.5 -right-1.5 text-base leading-none drop-shadow-sm",children:E.type==="birthday"?"🎂":E.type==="wedding_anniversary"?"💍":"🏠"})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium text-sm truncate",children:[E.contact.first_name," ",E.contact.last_name||""]}),e.jsx(Ue,{variant:"outline",className:Mt("text-[10px] shrink-0 whitespace-nowrap",A(E.daysUntil)),children:S(E.daysUntil)})]}),e.jsxs("div",{className:Mt("text-xs flex items-center gap-1.5 mt-0.5",E.type==="birthday"?"text-pink-600/80 dark:text-pink-400/80":"text-blue-600/80 dark:text-blue-400/80"),children:[E.type==="birthday"?e.jsxs(e.Fragment,{children:[e.jsx(Ah,{className:"h-3 w-3"})," Birthday"]}):E.type==="wedding_anniversary"?e.jsxs(e.Fragment,{children:[e.jsx(gi,{className:"h-3 w-3"})," Wedding Anniversary"]}):e.jsxs(e.Fragment,{children:[e.jsx(Or,{className:"h-3 w-3"})," Home Anniversary"]}),e.jsx("span",{children:"·"}),e.jsx("span",{children:Ss(E.date,"MMM d")})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1 mt-2 pl-[52px]",children:[E.contact.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Call",asChild:!0,children:e.jsx("a",{href:`tel:${E.contact.phone}`,children:e.jsx(Cr,{className:"h-3.5 w-3.5"})})}),E.contact.phone&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Text",asChild:!0,children:e.jsx("a",{href:`sms:${E.contact.phone}`,children:e.jsx(Ai,{className:"h-3.5 w-3.5"})})}),E.contact.email&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Email",onClick:()=>{a?(o({id:E.contact.id,first_name:E.contact.first_name,last_name:E.contact.last_name,email:E.contact.email}),d(!0)):window.location.href=`mailto:${E.contact.email}`},children:e.jsx(Gs,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"Record video",onClick:()=>s(`/mission-control/video/record?contactId=${E.contact.id}`),children:e.jsx(fr,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{variant:"ghost",size:"sm",className:Mt("h-7 px-2 gap-1 text-xs",E.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 ${E.type==="birthday"?"birthday":"anniversary"} card`,onClick:()=>w(E),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Card"})]}),e.jsx(B,{variant:"ghost",size:"icon",className:Mt("h-7 w-7",I&&"text-green-600"),title:"Log a touch",disabled:I||r.isPending,onClick:()=>j(E),children:e.jsx(vr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",title:"View contact",onClick:()=>s(`/mission-control/contacts/${E.contact.id}`),children:e.jsx(Sr,{className:"h-3.5 w-3.5"})})]})]},`${D}-${O}`)})]})]}),a&&l&&e.jsx(Xv,{open:c,onOpenChange:d,contact:l,gmailEmail:i})]})}function dHs(s){const[t,n]=N.useState([]),[r,a]=N.useState(!1),{data:i,isLoading:l}=dt({queryKey:["active-visitors",s],queryFn:async()=>{if(!s)return[];try{await q.rpc("cleanup_stale_visitors")}catch{}const{data:u}=await q.from("lead_site_active_visitors").select("*").eq("lead_site_id",s).gte("last_seen_at",new Date(Date.now()-2*60*1e3).toISOString()).order("last_seen_at",{ascending:!1});if(!u)return[];const h=u.map(y=>y.contact_id).filter(Boolean);let p={};if(h.length>0){const{data:y}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").in("id",h);(y||[]).forEach(_=>{p[_.id]=_})}const f=u.map(y=>y.auth_user_id).filter(Boolean);if(f.length>0){const{data:y}=await q.from("lead_site_consumer_profiles").select("user_id, name, phone, contact_id").eq("lead_site_id",s).in("user_id",f);(y||[]).forEach(_=>{const v=u.find(j=>j.auth_user_id===_.user_id);v&&!v.contact_id&&_.contact_id&&(v.contact_id=_.contact_id),v&&!p[v.contact_id||""]&&_.name&&(p[v.contact_id||v.auth_user_id||""]={first_name:_.name.split(" ")[0],last_name:_.name.split(" ").slice(1).join(" ")||null,email:null,phone:_.phone})})}return u.map(y=>{var _,v;return{...y,contact_name:p[y.contact_id||y.auth_user_id||""]?`${p[y.contact_id||y.auth_user_id||""].first_name} ${p[y.contact_id||y.auth_user_id||""].last_name||""}`.trim():null,contact_email:((_=p[y.contact_id||y.auth_user_id||""])==null?void 0:_.email)||null,contact_phone:((v=p[y.contact_id||y.auth_user_id||""])==null?void 0:v.phone)||null}})},enabled:!!s,refetchInterval:6e4});N.useEffect(()=>{if(!s)return;const u=q.channel(`active-visitors-${s}`).on("postgres_changes",{event:"*",schema:"public",table:"lead_site_active_visitors",filter:`lead_site_id=eq.${s}`},h=>{h.eventType==="INSERT"?n(p=>p.find(y=>y.id===h.new.id)?p:[h.new,...p]):h.eventType==="UPDATE"?n(p=>p.map(f=>f.id===h.new.id?{...f,...h.new}:f)):h.eventType==="DELETE"&&n(p=>p.filter(f=>f.id!==h.old.id))}).subscribe(h=>{h==="SUBSCRIBED"&&a(!0)});return()=>{q.removeChannel(u)}},[s]);const o=r&&t.length>0?uHs([...t,...i||[]]):i||[],c=Date.now(),d=o.filter(u=>c-new Date(u.last_seen_at).getTime()<2*60*1e3);return{activeVisitors:d,isLoading:l,count:d.length}}function uHs(s){const t=new Set;return s.filter(n=>t.has(n.id)?!1:(t.add(n.id),!0))}const hHs={property_view:{label:"Viewed",icon:Sr,color:"text-blue-500",bgColor:"bg-blue-500/10"},new_lead:{label:"New Lead",icon:Fo,color:"text-emerald-500",bgColor:"bg-emerald-500/10"},saved_listing:{label:"Saved",icon:gi,color:"text-rose-500",bgColor:"bg-rose-500/10"}};function mHs(){const{user:s}=vs(),t=Ln(),{isGmailConnected:n,gmailEmail:r}=Dh(),{leadSite:a}=Ap(),{count:i}=dHs(a==null?void 0:a.id),[l,o]=N.useState(!1),[c,d]=N.useState(null),{data:u,isLoading:h}=dt({queryKey:["lead-site-activity",s==null?void 0:s.id],queryFn:async()=>{const{data:j,error:w}=await q.rpc("get_lead_site_activity",{_user_id:s.id});if(w)throw w;return j},enabled:!!s,refetchInterval:6e4});if(h||!(u!=null&&u.has_site))return null;const p=(u.activities||[]).filter(j=>j.visitor_name&&j.visitor_name!=="Site Visitor"),f=p.filter(j=>j.activity_type==="new_lead"),y=(u.activities||[]).filter(j=>j.activity_type==="property_view").length,_=(u.activities||[]).filter(j=>j.activity_type==="saved_listing").length,v=j=>{if(j.visitor_email)if(n){const w=(j.visitor_name||"").split(" ");d({id:j.contact_id||"",first_name:w[0]||"",last_name:w.slice(1).join(" ")||null,email:j.visitor_email}),o(!0)}else window.location.href=`mailto:${j.visitor_email}`};return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"p-1.5 bg-primary/10 rounded-lg",children:e.jsx(lc,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Website Activity"}),i>0&&e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-0.5 rounded-full bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 text-[11px] font-semibold",children:[e.jsxs("span",{className:"relative flex h-1.5 w-1.5",children:[e.jsx("span",{className:"animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"}),e.jsx("span",{className:"relative inline-flex rounded-full h-1.5 w-1.5 bg-emerald-500"})]}),i," Live"]})]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-primary gap-1",onClick:()=>t("/mission-control/website-activity"),children:["View All",e.jsx(Oa,{className:"h-4 w-4"})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-emerald-500/5 border border-emerald-200 dark:border-emerald-800",children:[e.jsx(Fo,{className:"h-4 w-4 text-emerald-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-emerald-600 dark:text-emerald-400",children:f.length}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"New Leads"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-blue-500/5 border border-blue-200 dark:border-blue-800",children:[e.jsx(Sr,{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:y}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Views"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 p-3 rounded-lg bg-rose-500/5 border border-rose-200 dark:border-rose-800",children:[e.jsx(gi,{className:"h-4 w-4 text-rose-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-rose-600 dark:text-rose-400",children:_}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Saved"})]})]})]}),p.length>0?e.jsxs("div",{className:"space-y-2",children:[p.slice(0,5).map((j,w)=>{const S=hHs[j.activity_type],A=S.icon,E=Uo(new Date(j.occurred_at),{addSuffix:!0});return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border bg-card hover:shadow-sm transition-shadow",children:[e.jsx("div",{className:`p-1.5 rounded-md ${S.bgColor}`,children:e.jsx(A,{className:`h-3.5 w-3.5 ${S.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{className:"font-medium text-sm text-primary hover:underline text-left truncate block",onClick:()=>{j.contact_id&&t(`/mission-control/contacts/${j.contact_id}`)},children:j.visitor_name}),e.jsxs("div",{className:"flex items-center gap-2 text-[11px] text-muted-foreground",children:[e.jsx("span",{children:S.label}),j.mls_number&&e.jsxs("span",{children:["· MLS# ",j.mls_number]}),j.lead_type&&e.jsxs("span",{children:["· ",j.lead_type]}),e.jsxs("span",{children:["· ",E]})]})]}),e.jsxs("div",{className:"flex items-center gap-0.5 shrink-0",children:[j.visitor_email&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>v(j),children:e.jsx(Gs,{className:"h-3.5 w-3.5"})}),j.visitor_phone&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`tel:${j.visitor_phone}`,children:e.jsx(Cr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 text-primary",onClick:()=>window.location.href=`sms:${j.visitor_phone}`,children:e.jsx(Ai,{className:"h-3.5 w-3.5"})})]}),j.contact_id&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0",onClick:()=>t(`/mission-control/contacts/${j.contact_id}`),children:e.jsx(ga,{className:"h-3.5 w-3.5"})})]})]},`${j.activity_type}-${j.occurred_at}-${w}`)}),p.length>5&&e.jsxs(B,{variant:"outline",className:"w-full text-xs",onClick:()=>t("/mission-control/website-activity"),children:["View ",p.length-5," more activities",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]})]}):e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 text-center",children:[e.jsx(em,{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:y>0?`${y} anonymous listing views recorded.`:"Lead engagement will appear here as visitors interact with your site."}),e.jsxs(B,{variant:"outline",size:"sm",className:"mt-3",onClick:()=>t("/mission-control/website-activity"),children:["View Full Activity",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]})]})}),n&&c&&e.jsx(Xv,{open:l,onOpenChange:o,contact:c,gmailEmail:r})]})}const aZe={Crown:hf,FileText:br,Users:An,Globe:lc,Star:oa,Phone:Cr,MessageSquare:Ai,PenTool:ZS,Video:fr,Gift:Oi},pHs={"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 fHs(){var Ge,rt,tt,at,Ye,ut;const s=Ln(),{user:t}=vs(),{data:n}=ky(),{data:r}=kmt(),{data:a}=ax(),{data:i}=aU(),{data:l}=Amt(),o=Mns(),c=JMe(),d=Ens(90),u=Tye(),[h,p]=N.useState(null),[f,y]=N.useState(null),[_,v]=N.useState(!1),[j,w]=N.useState(""),[S,A]=N.useState(!1),[E,O]=N.useState(""),[D,I]=N.useState(vfe()),[F,z]=N.useState("cards"),[H,Z]=N.useState(!1),[Y,W]=N.useState(null),[ee,se]=N.useState(null),[oe,he]=N.useState(""),{isGmailConnected:ce,gmailEmail:me}=Dh(),le=()=>{const _t=parseInt(E,10);if(isNaN(_t)||_t<1){Br({title:"Invalid goal",description:"Please enter a number greater than 0",variant:"destructive"});return}I(_t),Emt(_t),A(!1),Br({title:"Goal updated",description:`Weekly touch goal set to ${_t}`})},ve=()=>{O(D.toString()),A(!0)};N.useEffect(()=>{(async()=>{if(!(t!=null&&t.id))return;const{data:bt}=await q.from("profiles").select("name").eq("id",t.id).single();bt!=null&&bt.name&&w(bt.name.split(" ")[0])})()},[t==null?void 0:t.id]),N.useEffect(()=>{o.mutate()},[]);const ge=wf(new Date),Te=Bl(ge,7),Ie=_t=>{if(!_t)return null;const bt=_t.split(/[-/T]/);if(bt.length<3)return null;const $t=parseInt(bt[1],10)-1,Yt=parseInt(bt[2],10);return isNaN($t)||isNaN(Yt)?null:new Date(ge.getFullYear(),$t,Yt)},Ce=(a==null?void 0:a.filter(_t=>{const bt=Ie(_t.birthday),$t=Ie(_t.home_anniversary);return bt&&ql(bt,ge)||$t&&ql($t,ge)}))||[];a!=null&&a.filter(_t=>{if(!_t.birthday&&!_t.home_anniversary)return!1;const bt=$t=>{if(!$t)return!1;const Yt=Ie($t);return Yt?Ov(Yt,ge)&&yb(Yt,Te):!1};return bt(_t.birthday)||bt(_t.home_anniversary)}).slice(0,5);const Me=[],Pe=(i==null?void 0:i.find(_t=>_t.name==="Call"))||(i==null?void 0:i[0]);for(const _t of Ce){const bt=Ie(_t.birthday),$t=Ie(_t.home_anniversary),Yt=bt&&ql(bt,ge),Ds=$t&&ql($t,ge);Yt&&Me.push({contact:_t,actionType:Pe||{id:"special-date-birthday",name:"Birthday Call",icon:"Cake",color:"#EC4899",description:"Wish them happy birthday!",active:!0,sort_order:0,created_at:"",updated_at:""},planName:"🎂 Birthday Today!",relationshipTypeName:((tt=(rt=(Ge=_t.tags)==null?void 0:Ge[0])==null?void 0:rt.relationship_type)==null?void 0:tt.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"birthday"}),Ds&&Me.push({contact:_t,actionType:Pe||{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:((ut=(Ye=(at=_t.tags)==null?void 0:at[0])==null?void 0:Ye.relationship_type)==null?void 0:ut.name)||"",monthNumber:0,isSpecialDate:!0,specialDateType:"anniversary"})}const Ae=l!==void 0?l||[]:(a==null?void 0:a.slice(0,5).map((_t,bt)=>{var Yt,Ds,Ls;const $t=i==null?void 0:i[bt%((i==null?void 0:i.length)||1)];return $t?{contact:_t,actionType:$t,planName:"Quick Touch",relationshipTypeName:((Ls=(Ds=(Yt=_t.tags)==null?void 0:Yt[0])==null?void 0:Ds.relationship_type)==null?void 0:Ls.name)||"",monthNumber:0}:null}).filter(Boolean))||[],Be=[...Me,...Ae],we=async(_t,bt,$t)=>{await u.mutateAsync({contactId:_t,actionTypeId:bt,scriptUsedId:$t}),v(!1),y(null)},Je=_t=>{_t.script?(y(_t),v(!0)):we(_t.contact.id,_t.actionType.id)},ke=_t=>aZe[_t||"Phone"]||Cr,it=_t=>aZe[_t||"Users"]||An,je=(_t,bt)=>_t.replace(/\{\{FirstName\}\}/g,bt.first_name).replace(/\{\{LastName\}\}/g,bt.last_name||"").replace(/\{\{AgentName\}\}/g,j||"there"),He=(_t,bt)=>({Call:`Thinking of you, ${bt}!`,Text:`Quick hello, ${bt}`,Email:`Checking in, ${bt}`,"Handwritten Note":`A note for ${bt}`,Video:`Video message for ${bt}`,Gift:`Something special for you, ${bt}`})[_t]||`Hello ${bt}!`,$e=(_t,bt,$t)=>{const Yt=`sms:${_t}`;if(bt&&$t){const Ds=je(bt,$t);return`${Yt}?body=${encodeURIComponent(Ds)}`}return Yt},Ke=(_t,bt,$t,Yt,Ds)=>{const Ls=`mailto:${_t}`,xs=[];if(Ds){const Lt=$t||He(Yt||"Email",Ds.first_name);if(xs.push(`subject=${encodeURIComponent(Lt)}`),bt){const Jt=je(bt,Ds);xs.push(`body=${encodeURIComponent(Jt)}`)}}return xs.length>0?`${Ls}?${xs.join("&")}`:Ls};return e.jsxs(e.Fragment,{children:[e.jsxs(Cs,{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(mHs,{}),e.jsxs("section",{children:[e.jsx("h2",{className:"text-xl font-semibold mb-4",children:"Your Sphere"}),e.jsx("div",{className:"flex flex-wrap gap-3",children:n==null?void 0:n.filter(_t=>_t.active).map(_t=>{const bt=it(_t.icon),$t=(r==null?void 0:r[_t.id])||0,Yt=h===_t.id,Ds=pHs[_t.name]||"bg-secondary text-secondary-foreground";return e.jsxs("button",{onClick:()=>{Yt?(p(null),s("/mission-control/contacts")):(p(_t.id),s(`/mission-control/contacts?type=${_t.id}`))},className:` flex items-center gap-2 px-4 py-3 rounded-lg border transition-all ${Yt?Ds:"bg-card hover:bg-accent"} `,children:[e.jsx(bt,{className:"h-5 w-5"}),e.jsxs("div",{className:"text-left",children:[e.jsx("div",{className:"font-medium",children:_t.name}),e.jsxs("div",{className:`text-sm ${Yt?"opacity-90":"text-muted-foreground"}`,children:[$t," Contacts"]})]})]},_t.id)})})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-3",children:[e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),className:"w-full bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(Sh,{className:"h-4 w-4 mr-1"}),"Quick Video"]}),e.jsxs(B,{onClick:()=>s("/mission-control/contacts"),className:"w-full",variant:"outline",children:["View Contacts",e.jsx(ga,{className:"h-4 w-4 ml-1"})]}),e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/video-library"),className:"w-full",children:"Video Library"}),e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/plans"),className:"w-full",children:"Manage Plans"})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-4",children:[e.jsx("h2",{className:"text-xl font-semibold",children:"Today in Your InnerCircle"}),l!==void 0&&e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(un,{className:"h-3 w-3"}),"Plan-based"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-1 border rounded-lg p-0.5",children:[e.jsx(B,{variant:F==="cards"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("cards"),title:"Card view",children:e.jsx(ff,{className:"h-4 w-4"})}),e.jsx(B,{variant:F==="table"?"secondary":"ghost",size:"sm",className:"h-7 px-2",onClick:()=>z("table"),title:"Table view",children:e.jsx(Sp,{className:"h-4 w-4"})})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:Be.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx("p",{children:"No actions scheduled for today."}),e.jsx("p",{className:"text-sm mt-1",children:"Add contacts and enable touchpoint plans to get started."}),e.jsx(B,{variant:"outline",className:"mt-4",onClick:()=>s("/mission-control/plans"),children:"Manage Plans"})]}):F==="table"?e.jsx(sHs,{actions:Be,onMarkComplete:we,onViewScript:Je,isLoading:u.isPending,buildSmsLink:$e,buildEmailLink:Ke,onGmailCompose:ce?_t=>{W(_t),Z(!0)}:void 0}):e.jsxs("div",{className:"flex gap-3 overflow-x-auto pb-2",children:[Be.map((_t,bt)=>{var gt,zt,As,Xt,Qs,ks,$s;const $t=_t.isSpecialDate,Yt=_t.specialDateType,Ds=$t?Yt==="birthday"?Ah:Or:ke(((gt=_t.actionType)==null?void 0:gt.icon)||null),Ls=_t.contact.phone,xs=_t.contact.email,Lt=$t?Yt==="birthday"?"#EC4899":"#8B5CF6":((zt=_t.actionType)==null?void 0:zt.color)||"#3B82F6",Jt=$t?Yt==="birthday"?"🎂 Birthday Today!":"🏠 Home Anniversary!":(As=_t.actionType)==null?void 0:As.name;return e.jsxs("div",{className:`flex-shrink-0 w-[260px] border rounded-lg overflow-hidden ${$t?"ring-2 ring-offset-2":""}`,style:$t?{"--tw-ring-color":Lt}:void 0,children:[e.jsxs("div",{className:"p-3 text-white flex items-center gap-2",style:{backgroundColor:Lt},children:[e.jsx(Ds,{className:"h-4 w-4"}),e.jsx("span",{className:"font-medium text-sm",children:Jt})]}),e.jsxs("div",{className:"p-3 space-y-2",children:[e.jsxs("button",{onClick:()=>s(`/mission-control/contacts/${_t.contact.id}`),className:"font-medium text-sm hover:text-primary hover:underline transition-colors text-left",children:[_t.contact.first_name," ",_t.contact.last_name]}),e.jsxs("div",{className:"flex gap-1.5",children:[Ls&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${_t.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(Cr,{className:"h-3 w-3"}),"Call"]}),e.jsxs("a",{href:$e(_t.contact.phone,(Xt=_t.script)==null?void 0:Xt.script_body,_t.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(Ai,{className:"h-3 w-3"}),"Text"]})]}),xs&&(ce?e.jsxs("button",{onClick:()=>{W({id:_t.contact.id,first_name:_t.contact.first_name,last_name:_t.contact.last_name,email:_t.contact.email}),Z(!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(Gs,{className:"h-3 w-3"}),"Email"]}):e.jsxs("a",{href:Ke(_t.contact.email,(Qs=_t.script)==null?void 0:Qs.script_body,(ks=_t.script)==null?void 0:ks.email_subject,($s=_t.actionType)==null?void 0:$s.name,_t.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(Gs,{className:"h-3 w-3"}),"Email"]}))]}),$t&&e.jsxs("button",{onClick:()=>{const an=`${_t.contact.first_name}${_t.contact.last_name?" "+_t.contact.last_name:""}`,tn=Yt==="birthday"?"birthday":"home_anniversary",er=new URLSearchParams({cardType:tn,contactId:_t.contact.id,name:an,..._t.contact.address?{address:_t.contact.address}:{},...Yt==="anniversary"&&_t.contact.home_anniversary?{date:_t.contact.home_anniversary}:{}});s(`/mission-control/card-studio?${er.toString()}`)},className:"w-full flex items-center justify-center gap-1.5 px-2 py-1.5 rounded text-xs font-semibold bg-gradient-to-r from-pink-500/15 to-violet-500/15 hover:from-pink-500/25 hover:to-violet-500/25 text-pink-600 dark:text-pink-400 transition-colors",children:[e.jsx(Gs,{className:"h-3 w-3"}),"Send ",Yt==="birthday"?"Birthday":"Anniversary"," Card"]}),!Ls&&!xs&&e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No contact info"}),e.jsxs("div",{className:"flex gap-1 flex-wrap",children:[_t.relationshipTypeName&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:_t.relationshipTypeName}),_t.monthNumber>0&&e.jsxs(Ue,{variant:"outline",className:"text-xs",children:["Month ",_t.monthNumber]})]}),_t.script&&e.jsx(B,{size:"sm",variant:"outline",className:"w-full",onClick:()=>Je(_t),children:"View Script"}),e.jsxs("div",{className:"flex gap-1.5",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"flex-1 gap-1",onClick:()=>{se(_t.contact.id),he(`${_t.contact.first_name} ${_t.contact.last_name||""}`.trim())},children:[e.jsx(gf,{className:"h-3.5 w-3.5"}),"Snooze"]}),e.jsx(B,{size:"sm",className:"flex-1",onClick:()=>{var an;return we(_t.contact.id,_t.actionType.id,(an=_t.script)==null?void 0:an.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]},_t.contact.id+bt)}),e.jsx("div",{className:"flex-shrink-0 w-[100px] border rounded-lg flex items-center justify-center",children:e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"ghost",className:"h-full w-full",children:[e.jsx(Kf,{className:"h-5 w-5 mr-2"}),"More"]})}),e.jsx(gc,{children:e.jsx(Kr,{onClick:()=>s("/mission-control/contacts"),children:"View all contacts"})})]})})]})})})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Rt,{className:"text-lg",children:"Momentum"}),e.jsxs(_s,{open:S,onOpenChange:A,children:[e.jsx(ki,{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(Ko,{className:"h-4 w-4 text-muted-foreground hover:text-primary"})})}),e.jsxs(bs,{className:"sm:max-w-[360px]",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Set Weekly Goal"}),e.jsx(Jn,{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(ne,{htmlFor:"weekly-goal-ic",children:"Weekly touch goal"}),e.jsx(ye,{id:"weekly-goal-ic",type:"number",min:"1",value:E,onChange:_t=>O(_t.target.value),placeholder:"20",onKeyDown:_t=>{_t.key==="Enter"&&le()}})]}),e.jsx(B,{onClick:le,className:"w-full",children:"Save Goal"})]})]})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(fi,{value:Math.min(c.actionsThisWeek/D*100,100),className:"h-3 w-full max-w-full"}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Hc,{className:"h-5 w-5 text-orange-500"}),e.jsxs("span",{className:"font-medium",children:[c.actionsThisWeek," / ",D]}),e.jsx("span",{className:"text-muted-foreground",children:"Actions Completed This Week"})]}),c.streak>0&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx("span",{className:"text-lg",children:"🔥"}),e.jsx("span",{className:"font-medium",children:"Great Job!"}),e.jsxs("span",{className:"text-muted-foreground",children:["Keep Your Streak Going! (",c.streak," days)"]})]}),d.count>0&&e.jsxs("button",{onClick:()=>s("/mission-control/contacts?filter=not-touched-90"),className:"flex items-start gap-2 text-sm pt-2 border-t w-full text-left hover:bg-accent/50 -mx-4 px-4 py-2 rounded-md transition-colors",children:[e.jsx(pr,{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(ga,{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(Vmt,{}),e.jsx(cHs,{})]})]}),e.jsx(_s,{open:_,onOpenChange:v,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{className:"flex items-center gap-2",children:f&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"w-3 h-3 rounded-full",style:{backgroundColor:f.actionType.color||"#3B82F6"}}),f.actionType.name," Script"]})})}),f&&f.script&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["For: ",e.jsxs("span",{className:"font-medium text-foreground",children:[f.contact.first_name," ",f.contact.last_name]})]}),e.jsx("div",{className:"bg-muted p-4 rounded-lg",children:e.jsx("p",{className:"whitespace-pre-wrap",children:je(f.script.script_body,f.contact)})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>v(!1),children:"Close"}),e.jsx(B,{className:"flex-1",onClick:()=>{var _t;return we(f.contact.id,f.actionType.id,(_t=f.script)==null?void 0:_t.id)},disabled:u.isPending,children:"Mark Complete"})]})]})]})}),e.jsx(ZVs,{})]}),ce&&Y&&e.jsx(Xv,{open:H,onOpenChange:Z,contact:Y,gmailEmail:me}),e.jsx(m1e,{open:!!ee,onOpenChange:_t=>!_t&&se(null),contactId:ee||"",contactName:oe})]})}const xHs=[{value:"bidirectional",label:"Two-Way",icon:ah,tooltip:"Sync contacts in both directions"},{value:"push_only",label:"Push Only",icon:Iu,tooltip:"Only push Agent OS → BoldTrail"},{value:"pull_only",label:"Pull Only",icon:sm,tooltip:"Only pull BoldTrail → Agent OS"}];function P5e({value:s,onChange:t,size:n="default"}){const r=n==="sm"?"text-xs":"text-sm";return e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:`font-medium ${r} text-muted-foreground`,children:"Sync Direction"}),e.jsx(IL,{type:"single",value:s,onValueChange:a=>{a&&t(a)},className:"justify-start",children:xHs.map(a=>e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsxs(HA,{value:a.value,"aria-label":a.tooltip,className:`gap-1.5 ${r} border border-transparent data-[state=on]:!bg-primary data-[state=on]:!text-primary-foreground data-[state=on]:!border-primary data-[state=on]:shadow-sm`,children:[e.jsx(a.icon,{className:n==="sm"?"h-3 w-3":"h-4 w-4"}),a.label]})}),e.jsx(Nc,{children:a.tooltip})]},a.value))})]})}function iZe(){const s=Kt(),[t,n]=N.useState(!1),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,y]=N.useState(0),_=N.useRef(!1),{data:v}=dt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(z)throw z;return F}}),j=(v==null?void 0:v.sync_direction)||"bidirectional",w=d??j,S=yt({mutationFn:async()=>{const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(z)throw z;if(F!=null&&F.error)throw new Error(F.error);return F},onSuccess:F=>{u(null),a(F),n(!0)},onError:F=>{ae.error(F.message||"Failed to generate sync preview")}}),A=yt({mutationFn:async()=>{_.current=!1,p("Initializing sync..."),y(5);const{data:F,error:z}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:w}});if(z)throw z;if(F!=null&&F.error)throw new Error(F.error);const H=F;let Z=H.sync_log_id,Y=H.next_phase,W=H.next_offset,ee=H.push_total||0,se=H.pull_total||0,oe=H.update_total||0,he=0,ce=0,me=0;for(;Y!=="finalize"&&!_.current;){const ge=ee+se+oe;Y==="fetch_bt"?p("Fetching BoldTrail contacts..."):Y==="analyze"?(p("Analyzing contacts..."),y(15)):Y==="push"?(p(`Pushing contacts to BoldTrail... (${he}/${ee})`),y(ge>0?he/ge*90:0)):Y==="pull"?(p(`Pulling contacts from BoldTrail... (${ce}/${se})`),y(ge>0?(ee+ce)/ge*90:0)):Y==="update"&&(p(`Updating existing contacts... (${me}/${oe})`),y(ge>0?(ee+se+me)/ge*90:0));const{data:Te,error:Ie}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:Y,offset:W,sync_log_id:Z,sync_direction:w}});if(Ie)throw Ie;if(Te!=null&&Te.error)throw new Error(Te.error);const Ce=Te;he+=Ce.chunk_pushed||0,ce+=Ce.chunk_pulled||0,me+=Ce.chunk_updated||0,Ce.push_total!==void 0&&(ee=Ce.push_total||0),Ce.pull_total!==void 0&&(se=Ce.pull_total||0),Ce.update_total!==void 0&&(oe=Ce.update_total||0),Ce.progress&&p(Ce.progress),Y=Ce.next_phase,W=Ce.next_offset}p("Finalizing sync..."),y(95);const{data:le,error:ve}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:Z,sync_direction:w}});if(ve)throw ve;return y(100),le},onSuccess:F=>{p(null),y(0),n(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]});const z=[`Pushed ${F.contacts_pushed||0}`,`pulled ${F.contacts_pulled||0}`,`updated ${F.contacts_updated||0}`,`skipped ${F.contacts_skipped||0} duplicates`];ae.success(`Sync complete! ${z.join(", ")}.`)},onError:F=>{p(null),y(0),ae.error(F.message||"Sync failed")}});if(!(v!=null&&v.connected))return null;const E=w==="pull_only"?0:(r==null?void 0:r.to_push)??0,O=w==="push_only"?0:(r==null?void 0:r.to_pull)??0,D=(r==null?void 0:r.to_update)??0,I=E>0||O>0||D>0;return e.jsxs(e.Fragment,{children:[e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",onClick:()=>S.mutate(),disabled:S.isPending,className:"shrink-0",children:S.isPending?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(ah,{className:"h-4 w-4 text-emerald-600"})})}),e.jsx(Nc,{children:"Sync with BoldTrail"})]}),e.jsx(_s,{open:t,onOpenChange:F=>{A.isPending||n(F)},children:e.jsxs(bs,{className:"sm:max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(ah,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Jn,{children:"Review what will happen when you sync your contacts."})]}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsx(P5e,{value:w,onChange:u,size:"sm"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${w==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:E}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Iu,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${w==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:O}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(sm,{className:"h-3 w-3"})," Pull to Agent OS"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-amber-600",children:D}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(dL,{className:"h-3 w-3"})," To update"]})]}),e.jsxs("div",{className:"rounded-lg border p-3 text-center",children:[e.jsx("p",{className:"text-2xl font-bold text-muted-foreground",children:r.already_synced}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(An,{className:"h-3 w-3"})," Already synced"]})]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground text-center",children:["Agent OS: ",r.agent_os_total," contacts · BoldTrail: ",r.boldtrail_total," contacts"]}),D>0&&e.jsxs("div",{className:"text-xs text-muted-foreground text-center bg-amber-50 dark:bg-amber-950/30 rounded-md p-2",children:[e.jsx(dL,{className:"h-3 w-3 inline mr-1"}),D," contacts have missing fields that will be filled from the other system"]}),E>0&&e.jsxs(oy,{open:i,onOpenChange:l,children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Iu,{className:"h-3 w-3 text-emerald-600"}),E," contacts to push to BoldTrail"]}),e.jsx(ao,{className:`h-3 w-3 transition-transform ${i?"rotate-180":""}`})]})}),e.jsx(cy,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.push_preview.map((F,z)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:F.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:F.email})]},z)),r.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_push-20," more"]})]})})]}),O>0&&e.jsxs(oy,{open:o,onOpenChange:c,children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sm,{className:"h-3 w-3 text-blue-600"}),O," contacts to pull from BoldTrail"]}),e.jsx(ao,{className:`h-3 w-3 transition-transform ${o?"rotate-180":""}`})]})}),e.jsx(cy,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[r.pull_preview.map((F,z)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:F.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:F.email})]},z)),r.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",r.to_pull-20," more"]})]})})]}),!I&&!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(fi,{value:f||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:h||"Sync in progress..."})]}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),disabled:A.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>A.mutate(),disabled:A.isPending||!I,className:"gap-2",children:[A.isPending?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(ah,{className:"h-4 w-4"}),A.isPending?"Syncing...":"Sync Now"]})]})]})]})})]})}const gHs=()=>{const{user:s}=vs();return dt({queryKey:["popby-items",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("popby_items").select("*").or(`owner_user_id.is.null,owner_user_id.eq.${s==null?void 0:s.id}`).eq("is_active",!0).order("name");if(n)throw n;return t},enabled:!!s})},f1e=s=>{const{user:t}=vs();return dt({queryKey:["popby-logs",t==null?void 0:t.id,s],queryFn:async()=>{let n=q.from("popby_logs").select("*").order("completed_at",{ascending:!1});if(s){const i=new Date;i.setDate(i.getDate()-s),n=n.gte("completed_at",i.toISOString())}const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})},YPe=()=>{const{user:s}=vs();return dt({queryKey:["relationship-type-popby-defaults",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("relationship_type_popby_defaults").select("*");if(n)throw n;return t},enabled:!!s})},r_t=()=>{const{user:s}=vs();return dt({queryKey:["contact-popby-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_popby_settings").select("*");if(n)throw n;return t},enabled:!!s})},yHs=()=>{const{data:s}=ax();ky();const{data:t}=f1e(),{data:n}=r_t(),{data:r}=YPe(),a=new Map;t==null||t.forEach(d=>{const u=a.get(d.contact_id);(!u||new Date(d.completed_at)>new Date(u))&&a.set(d.contact_id,d.completed_at)});const i=new Map;r==null||r.forEach(d=>i.set(d.relationship_type_id,d.frequency_days));const l=new Map;n==null||n.filter(d=>d.is_active).forEach(d=>{l.set(d.contact_id,d.frequency_days)});const o=wf(new Date);return(s||[]).map(d=>{let u=90;if(l.has(d.id))u=l.get(d.id);else if(d.tags&&d.tags.length>0){const _=d.tags.map(v=>i.get(v.relationship_type_id)).filter(v=>v!==void 0);_.length>0&&(u=Math.min(..._))}const h=a.get(d.id)||null,p=h?Vv(o,wf(new Date(h))):null,f=p===null||p>=u,y=f&&p!==null?p-u:0;return{...d,lastPopby:h,daysSinceLastPopby:p,frequencyDays:u,isDue:f,daysOverdue:y}}).sort((d,u)=>u.daysOverdue-d.daysOverdue)},a_t=()=>yHs().filter(t=>t.isDue),vHs=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{const{error:r}=await q.from("popby_items").insert({...n,owner_user_id:t==null?void 0:t.id});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-items"]}),Br({title:"Popby item created!"})},onError:n=>{Br({title:"Error creating popby item",description:n.message,variant:"destructive"})}})},bHs=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{const r=new Date().toISOString(),{error:a}=await q.from("popby_logs").insert({...n,owner_user_id:t==null?void 0:t.id,completed_at:r});if(a)throw a;try{const{data:i}=await q.from("action_types").select("id").ilike("name","Pop-By").eq("active",!0).maybeSingle();i!=null&&i.id&&await q.from("contact_touch_logs").insert({owner_user_id:t==null?void 0:t.id,contact_id:n.contact_id,action_type_id:i.id,notes:n.notes??"Pop-by logged",completed_at:r})}catch(i){console.error("Failed to log corresponding touch for popby",i)}},onSuccess:()=>{s.invalidateQueries({queryKey:["popby-logs"]}),s.invalidateQueries({queryKey:["contact-touch-logs"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),Br({title:"Popby logged!"})},onError:n=>{Br({title:"Error logging popby",description:n.message,variant:"destructive"})}})},_Hs=()=>{const s=Kt(),{user:t}=vs();return yt({mutationFn:async n=>{const{error:r}=await q.from("relationship_type_popby_defaults").upsert({...n,owner_user_id:t==null?void 0:t.id},{onConflict:"relationship_type_id,owner_user_id"});if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["relationship-type-popby-defaults"]}),Br({title:"Frequency updated!"})},onError:n=>{Br({title:"Error updating frequency",description:n.message,variant:"destructive"})}})},wHs=()=>{const{data:s}=f1e(30),t=a_t(),n=new Date;n.setDate(n.getDate()-7);const r=(s==null?void 0:s.filter(i=>new Date(i.completed_at)>=n).length)||0,a=(s==null?void 0:s.length)||0;return{thisWeekCount:r,thisMonthCount:a,dueCount:t.length}};function jHs(){const{user:s}=vs();return dt({queryKey:["contact-touch-logs",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("contact_touch_logs").select("*").order("completed_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function i_t(s){const{data:t}=jHs(),{data:n}=r_t(),{data:r}=YPe(),{data:a}=QVs();return N.useMemo(()=>{const i=a==null?void 0:a.find(v=>v.contact_id===s.id),l=i?new Date(i.snoozed_until):null,o=wf(new Date);if(l&&!yb(l,o))return{nextTouchDate:l,daysUntil:Vv(l,o),status:"snoozed",frequencyDays:90,lastTouchDate:null,snoozedUntil:l};const d=((t==null?void 0:t.filter(v=>v.contact_id===s.id))||[]).sort((v,j)=>new Date(j.completed_at).getTime()-new Date(v.completed_at).getTime())[0],u=d?new Date(d.completed_at):null;let h=90;const p=n==null?void 0:n.find(v=>v.contact_id===s.id&&v.is_active);if(p)h=p.frequency_days;else if(s.tags&&s.tags.length>0){const v=s.tags.map(j=>{const w=r==null?void 0:r.find(S=>S.relationship_type_id===j.relationship_type_id);return w==null?void 0:w.frequency_days}).filter(j=>j!==void 0);v.length>0&&(h=Math.min(...v))}if(!u)return{nextTouchDate:null,daysUntil:null,status:"never-touched",frequencyDays:h,lastTouchDate:null,snoozedUntil:null};const f=Bl(wf(u),h),y=Vv(f,o);let _;return y<0?_="overdue":y<=7?_="due-soon":_="on-track",{nextTouchDate:f,daysUntil:y,status:_,frequencyDays:h,lastTouchDate:u,snoozedUntil:null}},[s,t,n,r,a])}function L5e({contact:s}){const t=i_t(s),r=(()=>{switch(t.status){case"overdue":return{variant:"destructive",icon:Bi,text:`${Math.abs(t.daysUntil)} days overdue`,className:""};case"due-soon":return{variant:"secondary",icon:pr,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:vr,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:gf,text:`Snoozed until ${Ss(t.snoozedUntil,"MMM d")}`,className:"bg-slate-100 text-slate-700 dark:bg-slate-800 dark:text-slate-300"};case"never-touched":return{variant:"outline",icon:yr,text:"Never touched",className:"border-dashed"}}})(),a=r.icon;return e.jsxs(Ue,{variant:r.variant,className:Mt("gap-1",r.className),children:[e.jsx(a,{className:"h-3 w-3"}),r.text]})}function NHs({contact:s,onLogTouch:t,onSnooze:n}){const r=i_t(s),a=JVs(),[i,l]=N.useState(!1),o=()=>{switch(r.status){case"overdue":return"text-destructive";case"due-soon":return"text-amber-600 dark:text-amber-400";case"on-track":return"text-emerald-600 dark:text-emerald-400";case"snoozed":return"text-slate-600 dark:text-slate-400";case"never-touched":return"text-muted-foreground"}},c=()=>{switch(r.status){case"overdue":return e.jsx(Bi,{className:"h-5 w-5 text-destructive"});case"due-soon":return e.jsx(pr,{className:"h-5 w-5 text-amber-600 dark:text-amber-400"});case"on-track":return e.jsx(vr,{className:"h-5 w-5 text-emerald-600 dark:text-emerald-400"});case"snoozed":return e.jsx(gf,{className:"h-5 w-5 text-slate-600 dark:text-slate-400"});case"never-touched":return e.jsx(yr,{className:"h-5 w-5 text-muted-foreground"})}},d=()=>{switch(r.status){case"overdue":return`${Math.abs(r.daysUntil)} days overdue`;case"due-soon":return r.daysUntil===0?"Due today!":`Due in ${r.daysUntil} days`;case"on-track":return`On track - ${r.daysUntil} days remaining`;case"snoozed":return`Snoozed for ${r.daysUntil} more days`;case"never-touched":return"No touches logged yet"}},u=async()=>{await a.mutateAsync(s.id)};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"Next Touch"]})}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[c(),e.jsx("span",{className:Mt("font-medium",o()),children:d()})]}),r.status==="snoozed"&&r.snoozedUntil&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Snoozed until:"})," ",Ss(r.snoozedUntil,"MMMM d, yyyy")]}),r.status!=="snoozed"&&r.nextTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Scheduled:"})," ",Ss(r.nextTouchDate,"MMMM d, yyyy")]}),r.lastTouchDate&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("span",{className:"font-medium",children:"Last touch:"})," ",Ss(r.lastTouchDate,"MMM d, yyyy")]}),r.status!=="snoozed"&&e.jsxs("div",{className:"text-xs text-muted-foreground border-t pt-2",children:["Touch frequency: Every ",r.frequencyDays," days"]}),r.status==="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"flex-1",onClick:u,disabled:a.isPending,children:[e.jsx($n,{className:"h-4 w-4 mr-1"}),"Cancel Snooze"]}),t&&e.jsx(B,{size:"sm",className:"flex-1",onClick:t,children:"Log Touch"})]}),r.status!=="snoozed"&&e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"flex-1",onClick:()=>l(!0),children:[e.jsx(gf,{className:"h-4 w-4 mr-1"}),"Snooze"]}),(r.status==="overdue"||r.status==="due-soon"||r.status==="never-touched")&&t&&e.jsx(B,{size:"sm",className:"flex-1",variant:r.status==="overdue"?"default":"outline",onClick:t,children:"Log Touch"})]})]})]}),e.jsx(m1e,{open:i,onOpenChange:l,contactId:s.id,contactName:`${s.first_name} ${s.last_name||""}`.trim()})]})}const iNe=768;function fR(){const[s,t]=N.useState(void 0);return N.useEffect(()=>{const n=window.matchMedia(`(max-width: ${iNe-1}px)`),r=()=>{t(window.innerWidthn.removeEventListener("change",r)},[]),!!s}function kHs(){const{user:s}=vs(),{hasLeadSite:t,leadSite:n}=Ap(),{data:r,isLoading:a}=dt({queryKey:["website-active-contacts",s==null?void 0:s.id,n==null?void 0:n.id],queryFn:async()=>{if(!n)return new Set;const{data:i}=await q.from("lead_site_visitors").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),{data:l}=await q.from("lead_site_consumer_profiles").select("contact_id").eq("lead_site_id",n.id).not("contact_id","is",null),o=new Set;return(i||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),(l||[]).forEach(c=>{c.contact_id&&o.add(c.contact_id)}),o},enabled:!!s&&t,staleTime:5*60*1e3});return{activeContactIds:r??new Set,hasLeadSite:t,isLoading:a}}const SHs={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"}},CHs={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 yz({score:s,showScore:t=!1,showTooltip:n=!0,size:r="sm",className:a}){const i=SHs[s.status],l=CHs[r],o=e.jsxs("div",{className:Mt("inline-flex items-center rounded-full font-medium",i.bgLightClass,i.textClass,l.badge,l.text,a),children:[e.jsx("span",{className:Mt("rounded-full",i.bgClass,l.dot)}),t?e.jsx("span",{children:s.score}):e.jsx("span",{children:i.label})]});return n?e.jsx(Vw,{children:e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:o}),e.jsx(Nc,{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:Mt("font-bold",i.textClass),children:[s.score,"/100"]})]}),e.jsx(fi,{value:s.score,className:"h-2"}),e.jsxs("div",{className:"space-y-1.5 text-xs",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recency"}),e.jsxs("span",{children:[s.breakdown.recency,"/40"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Touchpoints (12mo)"}),e.jsxs("span",{children:[s.breakdown.touchpoints,"/30"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Transactions"}),e.jsxs("span",{children:[s.breakdown.transactions,"/20"]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Referrals"}),e.jsxs("span",{children:[s.breakdown.referrals,"/10"]})]})]}),s.daysSinceTouch!==null&&e.jsxs("p",{className:"text-xs text-muted-foreground pt-1 border-t",children:["Last contact: ",s.daysSinceTouch===0?"Today":`${s.daysSinceTouch} days ago`]}),s.daysSinceTouch===null&&e.jsx("p",{className:"text-xs text-muted-foreground pt-1 border-t italic",children:"Never contacted"})]})})]})}):o}const THs=[{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}],rG=s=>{if(!s||!s.trim())return null;const t=s.trim();if(/^\d{4}-\d{2}-\d{2}$/.test(t))return t;const n=t.match(/^(\d{1,2})[\/\-](\d{1,2})(?:[\/\-](\d{2,4}))?$/);if(n){const a=n[1].padStart(2,"0"),i=n[2].padStart(2,"0");let l="2000";n[3]&&(l=n[3].length===2?(parseInt(n[3])>50?"19":"20")+n[3]:n[3]);const o=parseInt(a),c=parseInt(i);if(o>=1&&o<=12&&c>=1&&c<=31)return`${l}-${a}-${i}`}const r=new Date(t);return isNaN(r.getTime())?null:r.toISOString().split("T")[0]},EHs=({open:s,onOpenChange:t,relationshipTypes:n,onSuccess:r})=>{const{user:a}=vs(),{toast:i}=Fa(),l=N.useRef(null),[o,c]=N.useState("upload"),[d,u]=N.useState([]),[h,p]=N.useState([]),[f,y]=N.useState({}),[_,v]=N.useState([]),[j,w]=N.useState([]),[S,A]=N.useState([]),[E,O]=N.useState(""),[D,I]=N.useState(!1),[F,z]=N.useState([]),[H,Z]=N.useState(!1),[Y,W]=N.useState(null);N.useEffect(()=>{!s||!(a!=null&&a.id)||(async()=>{const{data:Ae}=await q.from("contact_custom_tags").select("id, name, color").eq("owner_user_id",a.id).order("name");w(Ae||[])})()},[s,a==null?void 0:a.id]);const ee=Ae=>{A(Be=>Be.includes(Ae)?Be.filter(we=>we!==Ae):[...Be,Ae])},se=async()=>{const Ae=E.trim();if(!(!Ae||!(a!=null&&a.id))){I(!0);try{const{data:Be,error:we}=await q.from("contact_custom_tags").insert({owner_user_id:a.id,name:Ae}).select("id, name, color").single();if(we)throw we;Be&&(w(Je=>[...Je,Be].sort((ke,it)=>ke.name.localeCompare(it.name))),A(Je=>[...Je,Be.id]),O(""))}catch(Be){i({title:"Could not create tag",description:Be.message||"Try a different name.",variant:"destructive"})}finally{I(!1)}}},oe=()=>{c("upload"),u([]),p([]),y({}),v([]),A([]),O(""),z([]),W(null),l.current&&(l.current.value="")},he=()=>{oe(),t(!1)},ce=Ae=>{const Be=Ae.split(` `).map(He=>He.trim()).filter(He=>He);if(Be.length===0)return{headers:[],data:[]};const we=He=>{const $e=[];let Ke="",Ge=!1;for(let rt=0;rt0&&(Je[0]=Je[0].replace(/^\uFEFF/,""));const ke=new Map,it=Je.map((He,$e)=>{let Ke=(He||"").trim();Ke||(Ke=`Column ${$e+1}`);const Ge=ke.get(Ke)||0;return ke.set(Ke,Ge+1),Ge===0?Ke:`${Ke} (${Ge+1})`}),je=Be.slice(1).map(we);return{headers:it,data:je}},me=Ae=>{var Je;const Be=(Je=Ae.target.files)==null?void 0:Je[0];if(!Be)return;const we=new FileReader;we.onload=ke=>{var Ke;const it=(Ke=ke.target)==null?void 0:Ke.result,{headers:je,data:He}=ce(it);if(je.length===0){i({title:"No data found",description:"The CSV file appears to be empty.",variant:"destructive"});return}u(je),p(He);const $e={};je.forEach(Ge=>{const rt=Ge.toLowerCase().replace(/[_\s-]/g,"");rt.includes("firstname")||rt==="first"?$e.first_name=Ge:rt.includes("lastname")||rt==="last"?$e.last_name=Ge:rt.includes("spouse")&&rt.includes("email")?$e.spouse_email=Ge:rt.includes("spouse")||rt.includes("partner")?$e.spouse_name=Ge:rt.includes("email")?$e.email=Ge:rt.includes("phone")||rt.includes("mobile")||rt.includes("cell")?$e.phone=Ge:rt.includes("address")||rt.includes("street")?$e.address=Ge:rt==="city"?$e.city=Ge:rt==="state"||rt==="province"?$e.state=Ge:rt==="zip"||rt==="zipcode"||rt==="postalcode"?$e.zip=Ge:rt.includes("company")||rt.includes("organization")||rt.includes("business")?$e.company_name=Ge:rt.includes("jobtitle")||rt.includes("title")&&!rt.includes("spouse")?$e.job_title=Ge:rt.includes("birthday")||rt.includes("dob")||rt.includes("birthdate")?$e.birthday=Ge:rt.includes("anniversary")||rt.includes("homeanniversary")?$e.home_anniversary=Ge:(rt.includes("notes")||rt.includes("comment"))&&($e.notes=Ge)}),y($e),c("mapping")},we.readAsText(Be)},le=(Ae,Be)=>{y(we=>{if(Be==="none"){const{[Ae]:Je,...ke}=we;return ke}return{...we,[Ae]:Be}})},ve=Ae=>{v(Be=>Be.includes(Ae)?Be.filter(we=>we!==Ae):[...Be,Ae])},ge=async()=>{if(!(a!=null&&a.id))return;const{data:Ae}=await q.from("innercircle_contacts").select("id, email, phone").eq("owner_user_id",a.id),Be=new Set((Ae||[]).filter(ke=>ke.email).map(ke=>ke.email.toLowerCase())),we=new Set((Ae||[]).filter(ke=>ke.phone).map(ke=>ke.phone.replace(/[^0-9]/g,""))),Je=h.map(ke=>{const it=rt=>{const tt=f[rt];if(!tt)return"";const at=d.indexOf(tt);return at>=0?(ke[at]||"").trim():""},je=it("first_name"),He=it("email"),$e=it("phone"),Ke=je.length>0,Ge=!!(He&&Be.has(He.toLowerCase())||$e&&we.has($e.replace(/[^0-9]/g,"")));return{first_name:je,last_name:it("last_name"),email:He,phone:$e,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:Ke,isDuplicate:Ge,error:Ke?void 0:"First name is required"}});z(Je),c("preview")},Te=Ae=>{const Be=Ae.trim().split(/\s+/);return{first_name:Be[0],last_name:Be.length>1?Be.slice(1).join(" "):null}},Ie=async()=>{if(!(a!=null&&a.id))return;const Ae=F.filter(ke=>ke.isValid);if(Ae.length===0){i({title:"No valid contacts",description:"There are no valid contacts to import.",variant:"destructive"});return}Z(!0);let Be=0,we=0,Je=0;try{for(const ke of Ae)try{let it=null;if(ke.email){const{data:$e}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",ke.email).maybeSingle();it=$e}if(!it&&ke.phone){const $e=ke.phone.replace(/[^0-9]/g,""),{data:Ke}=await q.from("innercircle_contacts").select("id, phone").eq("owner_user_id",a.id).not("phone","is",null);if(Ke){const Ge=Ke.find(rt=>rt.phone&&rt.phone.replace(/[^0-9]/g,"")===$e);Ge&&(it={id:Ge.id})}}const je={owner_user_id:a.id,first_name:ke.first_name,last_name:ke.last_name||null,email:ke.email||null,phone:ke.phone||null,address:ke.address||null,city:ke.city||null,state:ke.state||null,zip:ke.zip||null,spouse_name:ke.spouse_name||null,spouse_email:ke.spouse_email||null,company_name:ke.company_name||null,job_title:ke.job_title||null,birthday:rG(ke.birthday),home_anniversary:rG(ke.home_anniversary),notes:ke.notes||null};let He=null;if(it){const{data:$e}=await q.from("innercircle_contacts").select("*").eq("id",it.id).single();if($e){const Ke={},Ge=["last_name","email","phone","address","city","state","zip","spouse_name","spouse_email","company_name","job_title","birthday","home_anniversary","notes"];for(const rt of Ge){const tt=$e[rt],at=je[rt];(!tt||tt==="")&&at&&(Ke[rt]=at)}Object.keys(Ke).length>0&&await q.from("innercircle_contacts").update(Ke).eq("id",it.id)}He=it.id,we++}else{const{data:$e,error:Ke}=await q.from("innercircle_contacts").insert(je).select("id").single();Ke?(console.error("Insert error for contact:",ke.first_name,Ke),Je++):$e?(He=$e.id,_.length>0&&await q.from("innercircle_contact_tags").insert(_.map(Ge=>({contact_id:$e.id,relationship_type_id:Ge}))),Be++):Je++}if(He&&S.length>0&&await q.from("contact_custom_tag_assignments").upsert(S.map($e=>({contact_id:He,tag_id:$e})),{onConflict:"contact_id,tag_id",ignoreDuplicates:!0}),He&&ke.spouse_name){const $e=Te(ke.spouse_name);let Ke=null;if(ke.spouse_email){const{data:rt}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("email",ke.spouse_email).maybeSingle();Ke=rt}if(!Ke){const{data:rt}=await q.from("innercircle_contacts").select("id").eq("owner_user_id",a.id).eq("first_name",$e.first_name).eq("last_name",$e.last_name||ke.last_name||"").maybeSingle();Ke=rt}let Ge=null;if(Ke){Ge=Ke.id;const rt=rG(ke.home_anniversary);rt&&await q.from("innercircle_contacts").update({home_anniversary:rt}).eq("id",Ke.id).is("home_anniversary",null)}else{const{data:rt}=await q.from("innercircle_contacts").insert({owner_user_id:a.id,first_name:$e.first_name,last_name:$e.last_name||ke.last_name||null,email:ke.spouse_email||null,address:ke.address||null,city:ke.city||null,state:ke.state||null,zip:ke.zip||null,home_anniversary:rG(ke.home_anniversary),spouse_name:`${ke.first_name}${ke.last_name?" "+ke.last_name:""}`,spouse_email:ke.email||null,notes:`Spouse of ${ke.first_name} ${ke.last_name||""} (imported via CSV)`.trim()}).select("id").single();rt&&(Ge=rt.id,Be++)}Ge&&(await q.from("innercircle_contacts").update({spouse_contact_id:Ge}).eq("id",He),await q.from("innercircle_contacts").update({spouse_contact_id:He}).eq("id",Ge))}}catch(it){console.error("Error importing contact:",it),Je++}W({created:Be,updated:we,failed:Je}),c("result"),(Be>0||we>0)&&r(),i({title:"Import Complete",description:`${Be} created, ${we} updated${Je>0?`, ${Je} failed`:""}.`})}catch(ke){console.error("Import error:",ke),i({title:"Import Failed",description:ke.message||"Failed to import contacts",variant:"destructive"})}finally{Z(!1)}},Ce=F.filter(Ae=>Ae.isValid).length,Me=F.filter(Ae=>!Ae.isValid).length,Pe=F.filter(Ae=>Ae.isValid&&Ae.isDuplicate).length,Re=Ce-Pe;return e.jsx(_s,{open:s,onOpenChange:he,children:e.jsxs(bs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(mw,{className:"h-5 w-5"}),"Import Contacts from CSV"]}),e.jsx(Jn,{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:me,className:"hidden"}),e.jsx(_a,{className:"h-10 w-10 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Click to upload or drag and drop a CSV file"}),e.jsx(B,{onClick:()=>{var Ae;return(Ae=l.current)==null?void 0:Ae.click()},children:"Select CSV File"})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4 text-sm",children:[e.jsx("p",{className:"font-medium mb-2",children:"Supported Fields:"}),e.jsx("p",{className:"text-muted-foreground text-xs mb-3",children:"First Name, Last Name, Email, Phone, Street Address, City, State, Zip, Spouse Name, Spouse Email, Company, Job Title, Birthday, Home Anniversary, Notes"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const Ae=`First Name,Last Name,Email,Phone,Street Address,City,State,Zip,Spouse Name,Spouse Email,Company,Job Title,Birthday,Home Anniversary,Notes John,Doe,john@example.com,555-123-4567,123 Main St,Austin,TX,78701,Jane Doe,jane@example.com,ABC Realty,Real Estate Agent,1985-06-15,2020-03-22,Met at open house`,Be=new Blob([Ae],{type:"text/csv"}),we=URL.createObjectURL(Be),Je=document.createElement("a");Je.href=we,Je.download="contact_import_template.csv",Je.click(),URL.revokeObjectURL(we)},children:[e.jsx(Ia,{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(ne,{className:"text-base font-medium",children:"Map CSV Columns to Contact Fields"}),e.jsx("div",{className:"grid gap-3",children:THs.map(Ae=>e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs(ne,{className:"w-40 text-sm",children:[Ae.label,Ae.required&&e.jsx("span",{className:"text-destructive ml-1",children:"*"})]}),e.jsxs(us,{value:f[Ae.key]||"none",onValueChange:Be=>le(Ae.key,Be),children:[e.jsx(ls,{className:"w-48",children:e.jsx(hs,{placeholder:"Select column..."})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"-- Not mapped --"}),d.map(Be=>e.jsx(Ze,{value:Be,children:Be},Be))]})]})]},Ae.key))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{className:"text-base font-medium",children:"Apply Relationship Types (optional)"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:n.map(Ae=>e.jsx(Ue,{variant:_.includes(Ae.id)?"default":"outline",className:"cursor-pointer",onClick:()=>ve(Ae.id),children:Ae.name},Ae.id))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{className:"text-base font-medium",children:"Apply Tags to All Imported Contacts (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every contact in this CSV — both newly created and merged duplicates — will receive the selected tags."}),j.length>0&&e.jsx("div",{className:"flex flex-wrap gap-2",children:j.map(Ae=>{const Be=S.includes(Ae.id);return e.jsxs(Ue,{variant:Be?"default":"outline",className:"cursor-pointer gap-1",style:Be&&Ae.color?{backgroundColor:Ae.color,borderColor:Ae.color}:void 0,onClick:()=>ee(Ae.id),children:[Ae.name,Be&&e.jsx($n,{className:"h-3 w-3"})]},Ae.id)})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{placeholder:"Create a new tag (e.g. Open House Oct 2026)",value:E,onChange:Ae=>O(Ae.target.value),onKeyDown:Ae=>{Ae.key==="Enter"&&(Ae.preventDefault(),se())},className:"max-w-xs"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:se,disabled:!E.trim()||D,children:[D?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add Tag"]})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-lg p-3 text-sm",children:e.jsxs("p",{className:"text-muted-foreground",children:["Preview: ",h.length," row(s) found in CSV"]})})]}),o==="preview"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{children:[Re," new"]})]}),Pe>0&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsxs("span",{children:[Pe," existing (will merge gaps)"]})]}),Me>0&&e.jsxs("div",{className:"flex items-center gap-2 text-destructive",children:[e.jsx(Bi,{className:"h-4 w-4"}),e.jsxs("span",{children:[Me," invalid"]})]})]}),Pe>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(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/30",children:[e.jsx(Tt,{children:"First Name"}),e.jsx(Tt,{children:"Last Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(da,{children:F.slice(0,100).map((Ae,Be)=>e.jsxs(Hs,{children:[e.jsx(ht,{children:Ae.first_name}),e.jsx(ht,{children:Ae.last_name}),e.jsx(ht,{children:Ae.email}),e.jsx(ht,{children:Ae.phone}),e.jsx(ht,{children:Ae.isValid?Ae.isDuplicate?e.jsx(Ue,{variant:"outline",className:"bg-accent text-accent-foreground",children:"Merge"}):e.jsx(Ue,{variant:"secondary",className:"bg-primary/10 text-primary",children:"New"}):e.jsx(Ue,{variant:"destructive",children:Ae.error||"Invalid"})})]},Be))})]}),F.length>100&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-2",children:["Showing first 100 of ",F.length," contacts"]})]})]}),o==="result"&&Y&&e.jsxs("div",{className:"space-y-4 py-4 text-center",children:[e.jsx(vr,{className:"h-12 w-12 mx-auto text-primary"}),e.jsx("h3",{className:"text-lg font-semibold",children:"Import Complete"}),e.jsxs("p",{className:"text-muted-foreground",children:[Y.created," created, ",Y.updated," merged"]}),Y.failed>0&&e.jsxs("p",{className:"text-destructive",children:[Y.failed," failed to import"]})]}),e.jsxs(Xn,{children:[o==="upload"&&e.jsx(B,{variant:"outline",onClick:he,children:"Cancel"}),o==="mapping"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:oe,children:"Back"}),e.jsx(B,{onClick:ge,disabled:!f.first_name,children:"Continue"})]}),o==="preview"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",onClick:()=>c("mapping"),children:"Back"}),e.jsx(B,{onClick:Ie,disabled:H||Ce===0,children:H?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"mr-2 h-4 w-4 animate-spin"}),"Importing..."]}):`Import ${Ce} Contact${Ce!==1?"s":""}`})]}),o==="result"&&e.jsx(B,{onClick:he,children:"Done"})]})]})})};function AHs(){return"contacts"in navigator&&"ContactsManager"in window}function MHs(s){const t=[],n=s.split("BEGIN:VCARD").filter(r=>r.trim());for(const r of n){const a=r.split(/\r?\n/);let i="",l="",o="",c="",d="";for(const u of a){const h=u.replace(/^\s+/,"");if(h.startsWith("N:")||h.startsWith("N;")){const f=h.substring(h.indexOf(":")+1).split(";");l=(f[0]||"").trim(),i=(f[1]||"").trim()}if((h.startsWith("FN:")||h.startsWith("FN;"))&&!i){const f=h.substring(h.indexOf(":")+1).trim().split(" ");i=f[0]||"",l=f.slice(1).join(" ")}(h.startsWith("EMAIL")||h.match(/^item\d+\.EMAIL/i))&&!o&&(o=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("TEL")||h.match(/^item\d+\.TEL/i))&&!c&&(c=h.substring(h.indexOf(":")+1).trim()),(h.startsWith("ADR")||h.match(/^item\d+\.ADR/i))&&!d&&(d=h.substring(h.indexOf(":")+1).split(";").map(y=>y.trim()).filter(Boolean).join(", "))}(i||l)&&t.push({first_name:i,last_name:l,email:o,phone:c,address:d})}return t}function IHs({open:s,onOpenChange:t,onComplete:n}){vs();const{data:r}=ax(),a=Cye(),i=N.useRef(null),[l,o]=N.useState("choose"),[c,d]=N.useState([]),[u,h]=N.useState(new Set),[p,f]=N.useState(0),[y,_]=N.useState(0),v=AHs(),j=N.useCallback(z=>{if(!r)return z;const H=new Set(r.filter(Y=>Y.email).map(Y=>Y.email.toLowerCase())),Z=new Set(r.filter(Y=>Y.phone).map(Y=>Y.phone.replace(/\D/g,"")));return z.map(Y=>{var se,oe;const W=(se=Y.email)==null?void 0:se.toLowerCase(),ee=(oe=Y.phone)==null?void 0:oe.replace(/\D/g,"");return W&&H.has(W)?{...Y,isDuplicate:!0,duplicateField:"email"}:ee&&ee.length>=7&&Z.has(ee)?{...Y,isDuplicate:!0,duplicateField:"phone"}:Y})},[r]),w=async()=>{try{const z=["name","email","tel","address"],H=await navigator.contacts.select(z,{multiple:!0});if(!H||H.length===0)return;const Z=H.map(ee=>{var he,ce,me,le;const oe=(((he=ee.name)==null?void 0:he[0])||"").split(" ");return{first_name:oe[0]||"",last_name:oe.slice(1).join(" "),email:((ce=ee.email)==null?void 0:ce[0])||"",phone:((me=ee.tel)==null?void 0:me[0])||"",address:(le=ee.address)!=null&&le[0]?[ee.address[0].streetAddress,ee.address[0].city,ee.address[0].region,ee.address[0].postalCode].filter(Boolean).join(", "):""}}),Y=j(Z);d(Y);const W=new Set;Y.forEach((ee,se)=>{ee.isDuplicate||W.add(se)}),h(W),o("preview")}catch(z){console.error("Contact Picker error:",z),Br({title:"Could not access contacts",description:"Please try the file upload option instead.",variant:"destructive"})}},S=z=>{var Y;const H=(Y=z.target.files)==null?void 0:Y[0];if(!H)return;const Z=new FileReader;Z.onload=W=>{var ce;const ee=(ce=W.target)==null?void 0:ce.result,se=MHs(ee);if(se.length===0){Br({title:"No contacts found",description:"The file didn't contain any valid contacts.",variant:"destructive"});return}const oe=j(se);d(oe);const he=new Set;oe.forEach((me,le)=>{me.isDuplicate||he.add(le)}),h(he),o("preview")},Z.readAsText(H),i.current&&(i.current.value="")},A=async()=>{const z=c.filter((Z,Y)=>u.has(Y));if(z.length===0)return;o("importing");let H=0;for(const Z of z)try{await a.mutateAsync({first_name:Z.first_name,last_name:Z.last_name||void 0,email:Z.email||void 0,phone:Z.phone||void 0,address:Z.address||void 0}),H++,_(Math.round(H/z.length*100))}catch(Y){console.error(`Failed to import ${Z.first_name} ${Z.last_name}:`,Y)}f(H),o("done")},E=z=>{h(H=>{const Z=new Set(H);return Z.has(z)?Z.delete(z):Z.add(z),Z})},O=()=>{u.size===c.length?h(new Set):h(new Set(c.map((z,H)=>H)))},D=z=>{z||(o("choose"),d([]),h(new Set),f(0),_(0),l==="done"&&n()),t(z)},I=c.filter(z=>z.isDuplicate).length,F=u.size;return e.jsx(_s,{open:s,onOpenChange:D,children:e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh]",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(tg,{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(Jn,{children:"Add contacts from your phone directly into Agent OS."})]}),l==="choose"&&e.jsxs("div",{className:"space-y-4 pt-2",children:[v&&e.jsxs(B,{onClick:w,className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(tg,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Select from Phone"}),e.jsx("div",{className:"text-xs opacity-80",children:"Pick contacts directly from your device"})]})]}),e.jsxs("div",{className:"relative",children:[v&&e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),v&&e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-background px-2 text-muted-foreground",children:"or"})})]}),e.jsxs(B,{variant:v?"outline":"default",onClick:()=>{var z;return(z=i.current)==null?void 0:z.click()},className:"w-full h-auto py-4 flex flex-col items-center gap-2",children:[e.jsx(_a,{className:"h-6 w-6"}),e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"font-semibold",children:"Upload Contact File"}),e.jsx("div",{className:"text-xs opacity-80",children:v?"Import a .vcf file exported from your Contacts app":"Export contacts from your phone as a .vcf file, then upload here"})]})]}),e.jsx("input",{ref:i,type:"file",accept:".vcf,.vcard",onChange:S,className:"hidden"}),!v&&e.jsxs("div",{className:"rounded-lg bg-muted p-3 text-sm text-muted-foreground space-y-2",children:[e.jsx("p",{className:"font-medium",children:"How to export contacts:"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"iPhone:"}),e.jsx("p",{className:"text-xs",children:'Open Contacts → select contacts → Share → choose "Export vCard"'})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-xs",children:"Android:"}),e.jsx("p",{className:"text-xs",children:"Open Contacts → Menu → Export → save as .vcf file"})]})]})]}),l==="preview"&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("span",{children:[c.length," contact",c.length!==1?"s":""," found",I>0&&e.jsxs("span",{className:"text-amber-600 ml-1",children:["(",I," already exist)"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:O,children:u.size===c.length?"Deselect All":"Select All"})]}),e.jsx(di,{className:"h-[350px] rounded-md border",children:e.jsx("div",{className:"divide-y",children:c.map((z,H)=>e.jsxs("div",{className:`flex items-start gap-3 p-3 cursor-pointer hover:bg-accent/50 transition-colors ${z.isDuplicate?"opacity-60":""}`,onClick:()=>E(H),children:[e.jsx(hi,{checked:u.has(H),onCheckedChange:()=>E(H),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(Ue,{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})]})]})]},H))})}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o("choose"),children:"Back"}),e.jsxs(B,{onClick:A,disabled:F===0,children:["Import ",F," Contact",F!==1?"s":""]})]})]}),l==="importing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-8",children:[e.jsx(rs,{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:[y,"% 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:`${y}%`}})})]}),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(Lr,{className:"h-6 w-6 text-emerald-600"})}),e.jsxs("div",{className:"text-center",children:[e.jsxs("p",{className:"font-semibold text-lg",children:[p," contact",p!==1?"s":""," imported!"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Your contacts are now in Agent OS and ready for touchpoint plans."})]}),e.jsx(B,{onClick:()=>D(!1),className:"mt-2",children:"Done"})]})]})})}function PHs(s){return dt({queryKey:["video-share-recipients",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("video_id",s).order("sent_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function LHs(){const{user:s}=vs();return dt({queryKey:["video-share-stats",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("video_share_recipients").select("*").eq("owner_user_id",s.id);if(n)throw n;const r=t;return{totalSent:r.length,totalOpened:r.filter(a=>a.opened_at).length,totalClicked:r.filter(a=>a.clicked_at).length,totalWatched:r.filter(a=>a.watched_at).length,openRate:r.length>0?Math.round(r.filter(a=>a.opened_at).length/r.length*100):0,clickRate:r.length>0?Math.round(r.filter(a=>a.clicked_at).length/r.length*100):0,watchRate:r.length>0?Math.round(r.filter(a=>a.watched_at).length/r.length*100):0}},enabled:!!(s!=null&&s.id)})}function DHs(){const{user:s}=vs();return dt({queryKey:["video-share-history",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("video_share_recipients").select(` *, agent_videos!inner(id, title, thumbnail_url, share_token, duration_seconds) `).eq("owner_user_id",s.id).order("sent_at",{ascending:!1}).limit(200);if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function o_t(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("video_share_recipients").insert([{video_id:n.video_id,owner_user_id:s.id,recipient_email:n.recipient_email,recipient_name:n.recipient_name||null,contact_id:n.contact_id||null,sent_via:n.sent_via||"gmail",share_token:"placeholder"}]).select().single();if(a)throw a;return r},onSuccess:n=>{t.invalidateQueries({queryKey:["video-share-recipients",n.video_id]}),t.invalidateQueries({queryKey:["video-share-stats"]}),t.invalidateQueries({queryKey:["video-share-history"]})}})}function l_t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=open`}function c_t(s){return`https://relzejiswnotikjgvjhz.supabase.co/functions/v1/track-video-share?t=${s}&e=click`}const RHs=100;function OHs({open:s,onOpenChange:t,contacts:n,isGmailConnected:r,isMassEmailReady:a,onSendComplete:i}){const l=Ln(),o=wa(),c=o_t(),[d,u]=N.useState([]),[h,p]=N.useState(!1),[f,y]=N.useState(""),[_,v]=N.useState(null),[j,w]=N.useState(""),[S,A]=N.useState(""),[E,O]=N.useState(!1),[D,I]=N.useState({done:0,total:0,failed:0}),F=n.filter(oe=>!!oe.email),z=n.length-F.length,H=F.length>RHs;N.useEffect(()=>{s&&(v(null),y(""),I({done:0,total:0,failed:0}))},[s]),N.useEffect(()=>{!s||!o||(p(!0),q.from("agent_videos").select("id, title, share_token, thumbnail_url, playback_url, duration_seconds, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:oe})=>{u(oe||[]),p(!1)}))},[s,o]),N.useEffect(()=>{if(!_)return;const oe=_.title||"a quick video";w(`I recorded a video for you — ${oe}`),A("Hey {{first_name}}! I recorded a quick video just for you. Click below to watch it:")},[_]);const Z=d.filter(oe=>!f||(oe.title||"").toLowerCase().includes(f.toLowerCase())),Y=(oe,he)=>{if(!_)return"";const ce=_.share_token?`https://video.relevelup.com/share/video/${_.share_token}`:"",me=_.share_token?`https://video.relevelup.com/thumb/${_.share_token}`:_.thumbnail_url||"",le=_.title||"Video Message",ge=S.replace(/\{\{first_name\}\}/gi,oe).split(/\n\n+/).map(Ce=>`

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

`).join(""),Te=he?c_t(he):ce,Ie=he?``:"";return`
`},W=async()=>{if(!_)return;O(!0),I({done:0,total:F.length,failed:0});let oe=0,he=0;for(const ce of F)try{let me;try{me=(await c.mutateAsync({video_id:_.id,recipient_email:ce.email,recipient_name:`${ce.first_name} ${ce.last_name||""}`.trim(),contact_id:ce.id,sent_via:"gmail"})).share_token}catch(Ie){console.warn("Tracking record failed for",ce.email,Ie)}const le=Y(ce.first_name,me),ve=j.replace(/\{\{first_name\}\}/gi,ce.first_name),{data:ge,error:Te}=await q.functions.invoke("gmail-send",{body:{to:ce.email,subject:ve,body:le,contactId:ce.id}});if(Te||!(ge!=null&&ge.success))throw new Error((ge==null?void 0:ge.error)||(Te==null?void 0:Te.message)||"Send failed");oe+=1}catch(me){console.error("Failed to send to",ce.email,me),he+=1}finally{I({done:oe+he,total:F.length,failed:he}),await new Promise(me=>setTimeout(me,250))}O(!1),he===0?ae.success(`Video sent to ${oe} ${oe===1?"contact":"contacts"}!`):ae.warning(`Sent to ${oe}, ${he} failed. Check console for details.`),t(!1),i==null||i()},ee=()=>{if(!_)return;const oe=Y("there",void 0);l("/admin/email-campaigns/new",{state:{directRecipients:F.map(he=>({email:he.email,name:`${he.first_name} ${he.last_name||""}`.trim()})),initialSubject:j,initialBodyHtml:oe}}),t(!1)},se=!!_&&!!j.trim()&&F.length>0&&(H?a:r);return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[640px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5 text-primary"}),"Send Video to ",F.length," ",F.length===1?"Contact":"Contacts"]}),e.jsxs(Jn,{children:[H?e.jsxs("span",{className:"flex items-center gap-1.5 text-amber-600",children:[e.jsx(zd,{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(Gs,{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:[H&&!a&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Bi,{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."]})]}),!H&&!r&&e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-destructive/10 text-destructive text-sm",children:[e.jsx(Bi,{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(ne,{children:"Choose a video"}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"gap-1",onClick:()=>l("/innercircle/videos/record"),children:[e.jsx(Is,{className:"h-3.5 w-3.5"})," Record new"]})]}),e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search your video library...",value:f,onChange:oe=>y(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:h?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{className:"h-14 w-full"})]}):Z.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."}):Z.map(oe=>{const he=(_==null?void 0:_.id)===oe.id;return e.jsxs("button",{type:"button",onClick:()=>v(oe),className:`w-full flex items-center gap-3 p-2 rounded-md border text-left transition-colors ${he?"border-primary bg-primary/5":"border-border hover:border-primary/50 hover:bg-accent/50"}`,children:[e.jsxs("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden relative",children:[oe.thumbnail_url?e.jsx("img",{src:oe.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer"}):e.jsx(Sh,{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(El,{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(al,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"bulk-video-subject",children:"Subject"}),e.jsx(ye,{id:"bulk-video-subject",value:j,onChange:oe=>w(oe.target.value),placeholder:"I recorded a video for you"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ne,{htmlFor:"bulk-video-message",children:["Personal message ",e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(use ","{{first_name}}"," to personalize)"]})]}),e.jsx(Ms,{id:"bulk-video-message",value:S,onChange:oe=>A(oe.target.value),rows:4,className:"resize-y"})]}),E&&D.total>0&&e.jsxs("div",{className:"p-3 rounded-md bg-muted text-sm",children:["Sending… ",D.done," / ",D.total,D.failed>0&&e.jsxs("span",{className:"text-destructive ml-2",children:["(",D.failed," failed)"]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:E,children:"Cancel"}),H?e.jsxs(B,{onClick:ee,disabled:!se,className:"gap-2",children:[e.jsx(zd,{className:"h-4 w-4"}),"Continue in Mass Email"]}):e.jsxs(B,{onClick:W,disabled:!se||E,className:"gap-2",children:[E?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"}),E?"Sending…":`Send to ${F.length}`]})]})]})]})})}function ZPe(){const s=wa();return dt({queryKey:["drip-campaigns",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaigns").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("is_starter",{ascending:!1}).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function FHs(s){return dt({queryKey:["drip-campaign",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_campaigns").select("*").eq("id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function zHs(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_campaigns").insert({owner_user_id:s,name:n.name,description:n.description??null,category:n.category??"nurture",icon:n.icon??"🌱",cover_color:n.cover_color??"from-emerald-500 to-teal-600",goal:n.goal??null,is_active:!1}).select().single();if(a)throw a;return r},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function d_t(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_campaigns").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["drip-campaigns"]}),s.invalidateQueries({queryKey:["drip-campaign",n.id]})}})}function BHs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("drip_campaigns").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["drip-campaigns"]})})}function $Hs(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const[{data:r,error:a},{data:i,error:l}]=await Promise.all([q.from("drip_campaigns").select("*").eq("id",n).single(),q.from("drip_campaign_steps").select("*").eq("campaign_id",n).order("step_order")]);if(a)throw a;if(l)throw l;const{data:o,error:c}=await q.from("drip_campaigns").insert({owner_user_id:s,name:r.name,description:r.description,category:r.category,icon:r.icon,cover_color:r.cover_color,goal:r.goal,is_active:!1,is_starter:!1}).select().single();if(c)throw c;if(i&&i.length>0){const d=i.map(h=>({campaign_id:o.id,step_order:h.step_order,channel:h.channel,subject:h.subject,body:h.body,video_url:h.video_url,delay_type:h.delay_type,delay_days:h.delay_days,delay_hours:h.delay_hours,anchor_field:h.anchor_field,anchor_offset_days:h.anchor_offset_days,send_window_start:h.send_window_start,send_window_end:h.send_window_end})),{error:u}=await q.from("drip_campaign_steps").insert(d);if(u)throw u}return o},onSuccess:()=>t.invalidateQueries({queryKey:["drip-campaigns"]})})}function u_t(s){return dt({queryKey:["drip-campaign-steps",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_steps").select("*").eq("campaign_id",s).order("step_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function UHs(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("drip_campaign_steps").insert({campaign_id:t.campaign_id,step_order:t.step_order,channel:t.channel??"email",subject:t.subject??"",body:t.body??"",video_url:t.video_url??null,delay_type:t.delay_type??"relative",delay_days:t.delay_days??0,delay_hours:t.delay_hours??0,anchor_field:t.anchor_field??null,anchor_offset_days:t.anchor_offset_days??0}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["drip-campaign-steps",n.campaign_id]})})}function qHs(){const s=Kt();return yt({mutationFn:async({id:t,campaign_id:n,...r})=>{const{data:a,error:i}=await q.from("drip_campaign_steps").update(r).eq("id",t).select().single();if(i)throw i;return{data:a,campaign_id:n}},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t.campaign_id]})})}function VHs(){const s=Kt();return yt({mutationFn:async({id:t,campaign_id:n})=>{const{error:r}=await q.from("drip_campaign_steps").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>s.invalidateQueries({queryKey:["drip-campaign-steps",t]})})}function HHs(s){return dt({queryKey:["campaign-enrollments",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("*, contact:innercircle_contacts(id, first_name, last_name, email)").eq("campaign_id",s).order("enrolled_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function GHs(s){return dt({queryKey:["campaign-enrollment-count",s],queryFn:async()=>{if(!s)return 0;const{count:t,error:n}=await q.from("drip_campaign_enrollments").select("id",{count:"exact",head:!0}).eq("campaign_id",s).eq("status","active");if(n)throw n;return t??0},enabled:!!s,staleTime:3e4})}function h_t(){const s=Kt();return yt({mutationFn:async({campaignId:t,contactIds:n})=>{const{data:r,error:a}=await q.functions.invoke("enroll-contacts-in-campaign",{body:{campaign_id:t,contact_ids:n}});if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}function WHs(){const s=Kt();return yt({mutationFn:async({id:t,status:n})=>{const r={status:n};n==="paused"&&(r.paused_at=new Date().toISOString()),n==="exited"&&(r.exited_at=new Date().toISOString(),r.exit_reason="manual");const{data:a,error:i}=await q.from("drip_campaign_enrollments").update(r).eq("id",t).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["campaign-enrollments"]}),s.invalidateQueries({queryKey:["contact-campaigns"]})}})}const KHs=[{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"}],x1e={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"},YHs={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 e6({userId:s,onSelect:t,onSelectVideo:n,triggerLabel:r="Library",triggerSize:a="sm",triggerVariant:i="outline",triggerClassName:l}){const[o,c]=N.useState(!1),[d,u]=N.useState([]),[h,p]=N.useState(!1),[f,y]=N.useState("");N.useEffect(()=>{!o||!s||(p(!0),q.from("agent_videos").select("id, title, recipient_name, playback_url, thumbnail_url, created_at, duration_seconds").eq("owner_user_id",s).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1}).limit(50).then(({data:v})=>{u(v||[]),p(!1)}))},[o,s]);const _=d.filter(v=>!f||(v.title||v.recipient_name||"").toLowerCase().includes(f.toLowerCase()));return e.jsxs(_s,{open:o,onOpenChange:c,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:i,size:a,className:l||"gap-1.5 shrink-0",children:[e.jsx(Sh,{className:"h-3.5 w-3.5"}),r]})}),e.jsxs(bs,{className:"max-w-lg max-h-[70vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Select from Video Library"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a video from your library"})]}),e.jsxs("div",{className:"relative mb-3",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos...",value:f,onChange:v=>y(v.target.value),className:"pl-10"})]}),e.jsx("div",{className:"flex-1 overflow-y-auto space-y-2 min-h-0",children:h?e.jsxs(e.Fragment,{children:[e.jsx(Ws,{className:"h-16 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]}):_.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:d.length===0?"No videos in your library yet":"No videos match your search"}):_.map(v=>e.jsxs("button",{onClick:()=>{t(v.playback_url||""),n==null||n(v),c(!1)},className:"w-full flex items-center gap-3 p-3 rounded-lg border border-border hover:border-primary/50 hover:bg-accent/50 transition-colors text-left",children:[e.jsx("div",{className:"w-16 h-10 rounded bg-muted flex items-center justify-center shrink-0 overflow-hidden",children:v.thumbnail_url?e.jsx("img",{src:v.thumbnail_url,alt:"",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:j=>{const w=j.currentTarget.parentElement;if(w){j.currentTarget.remove();const S=document.createElement("span");S.innerHTML="🎬",S.className="text-lg",w.appendChild(S)}}}):e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.title||v.recipient_name||"Untitled Video"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[v.duration_seconds?`${Math.round(v.duration_seconds)}s`:"",v.created_at?` · ${new Date(v.created_at).toLocaleDateString()}`:""]})]})]},v.id))})]})]})}function ZHs(){return dt({queryKey:["video-script-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("video_script_categories").select("*").order("sort_order");if(t)throw t;return s}})}function QHs(s){return dt({queryKey:["video-scripts",s],queryFn:async()=>{let t=q.from("video_scripts").select("*, category:video_script_categories(*)").eq("is_active",!0).order("title");const{data:n,error:r}=await t;if(r)throw r;return n}})}function XHs(){const{user:s}=vs();return dt({queryKey:["user-video-scripts",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("user_video_scripts").select("*, category:video_script_categories(*)").eq("owner_user_id",s.id).order("title");if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function JHs(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("user_video_scripts").insert([{owner_user_id:s.id,source_script_id:n.id,category_id:n.category_id,title:n.title,script_text:n.script_text,tags:n.tags,is_custom:!1}]).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["user-video-scripts"]})}})}function eGs(s){const{user:t}=vs();return dt({queryKey:["agent-videos",t==null?void 0:t.id,s],queryFn:async()=>{if(!(t!=null&&t.id))return[];let n=q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("owner_user_id",t.id).order("created_at",{ascending:!1});n=n.eq("is_deleted",!1);const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!(t!=null&&t.id)})}function tGs(s){return dt({queryKey:["agent-video",s],queryFn:async()=>{const{data:t,error:n}=await q.from("agent_videos").select("*, contact:innercircle_contacts(id, first_name, last_name)").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function CN(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:r,error:a}=await q.from("agent_videos").insert([{owner_user_id:s.id,contact_id:n.contact_id,bunny_video_id:n.bunny_video_id,playback_url:n.playback_url,thumbnail_url:n.thumbnail_url,preview_url:n.preview_url,duration_seconds:n.duration_seconds,file_size_mb:n.file_size_mb||0,title:n.title,notes:n.notes,task_id:n.task_id,status:n.status||"processing",touch_type:n.touch_type||"video",page_template:"default",category:n.category||"general"}]).select("*, share_token").single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["agent-videos"]}),t.invalidateQueries({queryKey:["storage-usage"]})}})}function sGs(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("agent_videos").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["agent-video",t.id]})}})}function nGs(){const s=Kt();return yt({mutationFn:async({id:t,bunnyVideoId:n,hardDelete:r=!1})=>{if(console.log("Deleting video:",{id:t,bunnyVideoId:n,hardDelete:r}),n){console.log("Calling bunny-upload delete for videoId:",n);const{data:a,error:i}=await q.functions.invoke("bunny-upload",{body:{action:"delete",videoId:n,isAgentVideo:!0}});i?console.error("Failed to delete from Bunny:",i):console.log("Bunny delete response:",a)}else console.warn("No bunnyVideoId provided, skipping Bunny.net deletion");if(r){console.log("Hard deleting from database:",t);const{error:a}=await q.from("agent_videos").delete().eq("id",t);if(a)throw a}else{console.log("Soft deleting from database:",t);const{error:a}=await q.from("agent_videos").update({is_deleted:!0}).eq("id",t);if(a)throw a}console.log("Video deletion complete")},onSuccess:()=>{s.invalidateQueries({queryKey:["agent-videos"]}),s.invalidateQueries({queryKey:["storage-usage"]})}})}function g1e(){const{user:s}=vs();return dt({queryKey:["storage-usage",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return null;const{data:t,error:n}=await q.from("agent_storage_usage").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t||{user_id:s.id,total_storage_mb:0,storage_tier:"basic",max_storage_mb:1024}},enabled:!!(s!=null&&s.id)})}function m_t(){const{data:s,isLoading:t}=g1e(),n=s?s.total_storage_mb0?s.total_storage_mb/s.max_storage_mb*100:0,i=a>=80;return{canRecord:n,remainingMb:r,usagePercent:a,isNearLimit:i,storage:s,isLoading:t}}async function t6(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:s,isAgentVideo:!0}});if(n)throw n;return t}async function s6(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}async function Fw(s){const{data:t,error:n}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:s,isAgentVideo:!0}});if(n)throw n;return t}function rGs(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async({contactId:n,videoId:r,notes:a})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{data:i}=await q.from("action_types").select("id").eq("name","Video").single();if(!i)throw new Error("Video action type not found");const{data:l,error:o}=await q.from("contact_touch_logs").insert([{owner_user_id:s.id,contact_id:n,action_type_id:i.id,notes:a||`Quick Video Touch - Video ID: ${r}`}]).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["contact-touch-logs"]}),t.invalidateQueries({queryKey:["contacts"]})}})}function p_t({open:s,onOpenChange:t,onUploadComplete:n}){const{data:r}=ax(),{data:a}=g1e(),i=CN(),l=N.useRef(null),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(!1),[j,w]=N.useState(0),[S,A]=N.useState("idle"),E=(a==null?void 0:a.total_storage_mb)||0,D=((a==null?void 0:a.max_storage_mb)||1024)-E,I=Z=>{var ee;const Y=(ee=Z.target.files)==null?void 0:ee[0];if(!Y)return;if(!Y.type.startsWith("video/")){ae.error("Please select a video file");return}const W=Y.size/(1024*1024);if(W>500){ae.error("Video file must be less than 500MB");return}if(W>D){ae.error(`Not enough storage. You have ${D.toFixed(1)} MB remaining.`);return}c(Y),d||u(Y.name.replace(/\.[^/.]+$/,""))},F=async()=>{if(!o){ae.error("Please select a video file");return}v(!0),w(0),A("creating");try{const{data:Z,error:Y}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:d||o.name,isAgentVideo:!0}});if(Y)throw new Error(Y.message);const{videoId:W,libraryId:ee}=Z;A("uploading");const{data:se,error:oe}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:W,isAgentVideo:!0}});if(oe)throw new Error(oe.message);await new Promise((me,le)=>{const ve=new XMLHttpRequest;ve.upload.addEventListener("progress",ge=>{if(ge.lengthComputable){const Te=Math.round(ge.loaded/ge.total*100);w(Te)}}),ve.addEventListener("load",()=>{ve.status>=200&&ve.status<300?me():le(new Error(`Upload failed with status ${ve.status}`))}),ve.addEventListener("error",()=>le(new Error("Upload failed"))),ve.open("PUT",se.uploadUrl),ve.setRequestHeader("AccessKey",se.apiKey),ve.send(o)}),A("processing");const he=o.size/(1024*1024),ce=`https://iframe.mediadelivery.net/embed/${ee}/${W}`;await i.mutateAsync({bunny_video_id:W,playback_url:ce,file_size_mb:he,title:d||o.name,notes:h||void 0,contact_id:f||void 0,status:"processing",touch_type:"video_upload"}),ae.success("Video uploaded successfully! Processing may take a few minutes."),n==null||n(ce),z()}catch(Z){console.error("Upload error:",Z),ae.error(Z instanceof Error?Z.message:"Failed to upload video")}finally{v(!1),A("idle")}},z=()=>{_||(c(null),u(""),p(""),y(""),w(0),A("idle"),t(!1))},H=()=>{switch(S){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${j}%`;case"processing":return"Saving video...";default:return""}};return e.jsx(_s,{open:s,onOpenChange:z,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Upload Video"}),e.jsx(Jn,{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(ne,{children:"Video File"}),o?e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted rounded-lg",children:[e.jsx(fr,{className:"h-8 w-8 text-primary flex-shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium truncate",children:o.name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(o.size/(1024*1024)).toFixed(1)," MB"]})]}),!_&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:Z=>{Z.stopPropagation(),c(null)},children:e.jsx($n,{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 Z;return(Z=l.current)==null?void 0:Z.click()},children:[e.jsx(_a,{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:I,disabled:_})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"title",children:"Title"}),e.jsx(ye,{id:"title",value:d,onChange:Z=>u(Z.target.value),placeholder:"Enter video title",disabled:_})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Associate with Contact (optional)"}),e.jsxs(us,{value:f||"__none__",onValueChange:Z=>y(Z==="__none__"?"":Z),disabled:_,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a contact"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"__none__",children:"No contact"}),r==null?void 0:r.map(Z=>e.jsxs(Ze,{value:Z.id,children:[Z.first_name," ",Z.last_name||""]},Z.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"notes",children:"Notes (optional)"}),e.jsx(Ms,{id:"notes",value:h,onChange:Z=>p(Z.target.value),placeholder:"Add any notes about this video",rows:2,disabled:_})]}),_&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:H()})]}),e.jsx(fi,{value:S==="uploading"?j:S==="processing"?100:10})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:z,disabled:_,children:"Cancel"}),e.jsx(B,{onClick:F,disabled:!o||_,children:_?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Upload Video"]})})]})]})})}const aGs=["🌱","💎","🏠","🔑","📧","💌","🎂","🥂","🤝","⭐","🎉","📞"],iGs={" ":" ","&":"&","<":"<",">":">",""":'"',"'":"'"},oZe=s=>s?/<\/?[a-z][\s\S]*>/i.test(s)?s.replace(//gi,"").replace(//gi,"").replace(//gi,` `).replace(/<\/p\s*>/gi,` `).replace(/<\/div\s*>/gi,` `).replace(/<\/h[1-6]\s*>/gi,` `).replace(/<\/li\s*>/gi,` `).replace(/]*>/gi,"• ").replace(/<[^>]+>/g,"").replace(/&(nbsp|amp|lt|gt|quot);|'/gi,t=>iGs[t.toLowerCase()]||t).replace(/\n{3,}/g,` `).replace(/[ \t]+\n/g,` `).trim():s:"";function f_t({open:s,onOpenChange:t,campaignId:n}){const[r,a]=N.useState(n??null),[i,l]=N.useState("details");N.useEffect(()=>{a(n??null),l("details")},[n,s]);const o=r,c=!!o,{data:d}=FHs(o||void 0),{data:u,isLoading:h}=u_t(o||void 0),p=zHs(),f=d_t(),y=UHs(),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState("nurture"),[E,O]=N.useState("🌱"),[D,I]=N.useState("");N.useEffect(()=>{d?(v(d.name),w(d.description||""),A(d.category),O(d.icon),I(d.goal||"")):c||(v(""),w(""),A("nurture"),O("🌱"),I(""))},[d,c,s]);const F=YHs[S],z=async()=>{if(!_.trim()){ae.error("Give your campaign a name");return}try{if(c&&o)await f.mutateAsync({id:o,name:_,description:j,category:S,icon:E,goal:D,cover_color:F}),ae.success("Campaign updated");else{const Z=await p.mutateAsync({name:_,description:j,category:S,icon:E,goal:D,cover_color:F});return ae.success("Campaign created — now add your first step!"),a(Z.id),l("steps"),Z}}catch(Z){ae.error(Z.message||"Failed to save")}},H=async()=>{if(!o){ae.error("Save the campaign first, then add steps");return}const Z=((u==null?void 0:u.length)||0)+1;try{await y.mutateAsync({campaign_id:o,step_order:Z,channel:"email",subject:"",body:"",delay_type:"relative",delay_days:Z===1?0:2,delay_hours:0})}catch{ae.error("Failed to add step")}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{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:E}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx(ws,{className:"text-lg font-bold text-white",children:c?"Edit Campaign":"Create New Campaign"}),e.jsx(Jn,{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(Fr,{value:i,onValueChange:Z=>l(Z),className:"flex-1 flex flex-col overflow-hidden min-h-0",children:[e.jsxs(Rr,{className:"mx-5 mt-4 grid grid-cols-2 w-fit",children:[e.jsx(Zt,{value:"details",children:"Details"}),e.jsxs(Zt,{value:"steps",disabled:!c,children:["Steps ",u&&u.length>0&&e.jsx(Ue,{variant:"secondary",className:"ml-1.5 text-[10px]",children:u.length})]})]}),e.jsx(is,{value:"details",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(di,{className:"h-full",children:e.jsxs("div",{className:"p-5 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Campaign Name *"}),e.jsx(ye,{value:_,onChange:Z=>v(Z.target.value),placeholder:"e.g. New Buyer Lead — 7 Touch Nurture",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Description"}),e.jsx(Ms,{value:j,onChange:Z=>w(Z.target.value),placeholder:"What's this campaign for? When should you use it?",rows:2,className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Goal (optional)"}),e.jsx(ye,{value:D,onChange:Z=>I(Z.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(ne,{className:"text-xs",children:"Category"}),e.jsxs(us,{value:S,onValueChange:Z=>A(Z),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(cs,{children:Object.entries(x1e).map(([Z,Y])=>e.jsx(Ze,{value:Z,children:Y},Z))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Icon"}),e.jsx("div",{className:"flex gap-1.5 flex-wrap mt-1",children:aGs.map(Z=>e.jsx("button",{type:"button",onClick:()=>O(Z),className:`h-8 w-8 rounded-md text-lg flex items-center justify-center transition-all ${E===Z?"bg-primary/15 ring-2 ring-primary":"hover:bg-muted"}`,children:Z},Z))})]})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx("p",{className:"text-xs text-muted-foreground",children:c?"Save changes, then jump to the Steps tab to manage your sequence.":"Save to create the campaign, then you can add steps to it."})})]})})}),e.jsx(is,{value:"steps",className:"flex-1 overflow-hidden mt-0 min-h-0",children:e.jsx(di,{className:"h-full",children:e.jsx("div",{className:"p-5 space-y-3",children:h?e.jsx("div",{className:"text-center text-sm text-muted-foreground py-8",children:"Loading steps…"}):!u||u.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl",children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No steps yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build your sequence — each step waits for its delay, then sends."}),e.jsxs(B,{size:"sm",onClick:H,disabled:y.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," Add first step"]})]}):e.jsxs(e.Fragment,{children:[u.map((Z,Y)=>e.jsx(oGs,{step:Z,index:Y,totalSteps:u.length},Z.id)),e.jsxs(B,{variant:"outline",size:"sm",onClick:H,disabled:y.isPending,className:"w-full",children:[y.isPending?e.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Add another step"]})]})})})})]}),e.jsxs(Xn,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:c?"Done":"Cancel"}),e.jsxs(B,{onClick:z,disabled:p.isPending||f.isPending,children:[(p.isPending||f.isPending)&&e.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),c?"Save Changes":"Create Campaign"]})]})]})})}function oGs({step:s,index:t,totalSteps:n}){const r=qHs(),a=VHs(),i=wa(),[l,o]=N.useState(!1),[c,d]=N.useState(()=>({...s,body:oZe(s.body)})),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[y,_]=N.useState(""),[v,j]=N.useState(!1);N.useEffect(()=>{d({...s,body:oZe(s.body)})},[s]);const w=JSON.stringify(c)!==JSON.stringify(s),S=async()=>{h(!0);try{await r.mutateAsync({id:s.id,campaign_id:s.campaign_id,channel:c.channel,subject:c.subject,body:c.body,video_url:c.video_url,delay_type:c.delay_type,delay_days:c.delay_days,delay_hours:c.delay_hours,anchor_field:c.anchor_field,anchor_offset_days:c.anchor_offset_days}),ae.success(`Step ${t+1} saved`)}catch{ae.error("Failed to save step")}finally{h(!1)}},A=async()=>{if(confirm(`Delete step ${t+1}?`))try{await a.mutateAsync({id:s.id,campaign_id:s.campaign_id}),ae.success("Step deleted")}catch{ae.error("Failed to delete")}},E=D=>{d({...c,body:c.body+D})},O=()=>{if(c.delay_type==="calendar_anchor"){const I=c.anchor_field==="birthday"?"birthday":"home anniversary",F=c.anchor_offset_days||0;return F===0?`On their ${I}`:F<0?`${Math.abs(F)}d before ${I}`:`${F}d after ${I}`}if(t===0&&!c.delay_days&&!c.delay_hours)return"Sends immediately";const D=[];return c.delay_days&&D.push(`${c.delay_days}d`),c.delay_hours&&D.push(`${c.delay_hours}h`),t===0?`After ${D.join(" ")||"0"}`:`+${D.join(" ")||"0"}`};return e.jsxs("div",{className:"border rounded-lg bg-card overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-2 p-3 hover:bg-muted/30 cursor-pointer",onClick:()=>o(!l),children:[e.jsx("div",{className:"h-7 w-7 shrink-0 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:t+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[c.delay_type==="calendar_anchor"?e.jsx(yr,{className:"h-3 w-3"}):e.jsx(pr,{className:"h-3 w-3"}),e.jsx("span",{children:O()}),e.jsx("span",{children:"·"}),c.channel==="email"?e.jsx(Gs,{className:"h-3 w-3"}):e.jsx(Ai,{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(ex,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ao,{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(ne,{className:"text-xs",children:"Channel"}),e.jsxs(us,{value:c.channel,onValueChange:D=>d({...c,channel:D}),children:[e.jsx(ls,{className:"mt-1 h-9",children:e.jsx(hs,{})}),e.jsx(cs,{children:e.jsx(Ze,{value:"email",children:"📧 Email"})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Timing Type"}),e.jsxs(us,{value:c.delay_type,onValueChange:D=>d({...c,delay_type:D}),children:[e.jsx(ls,{className:"mt-1 h-9",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"relative",children:"⏱ Relative delay"}),e.jsx(Ze,{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(ne,{className:"text-xs",children:"Days delay"}),e.jsx(ye,{type:"number",min:0,value:c.delay_days,onChange:D=>d({...c,delay_days:parseInt(D.target.value)||0}),className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Hours delay"}),e.jsx(ye,{type:"number",min:0,max:23,value:c.delay_hours,onChange:D=>d({...c,delay_hours:parseInt(D.target.value)||0}),className:"mt-1 h-9"})]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Anchor"}),e.jsxs(us,{value:c.anchor_field||"birthday",onValueChange:D=>d({...c,anchor_field:D}),children:[e.jsx(ls,{className:"mt-1 h-9",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"birthday",children:"🎂 Birthday"}),e.jsx(Ze,{value:"home_anniversary",children:"🏠 Home Anniversary"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Offset (days, negative = before)"}),e.jsx(ye,{type:"number",value:c.anchor_offset_days||0,onChange:D=>d({...c,anchor_offset_days:parseInt(D.target.value)||0}),className:"mt-1 h-9",placeholder:"0 = on the day, -7 = week before"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Subject Line"}),e.jsx(ye,{value:c.subject,onChange:D=>d({...c,subject:D.target.value}),placeholder:"e.g. Quick question about your home search, {{client_first_name}}",className:"mt-1 h-9"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ne,{className:"text-xs",children:"Email Body"}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[c.body.length," chars"]})]}),e.jsx(Ms,{value:c.body,onChange:D=>d({...c,body:D.target.value}),placeholder:`Hi {{client_first_name}}, I wanted to reach out and...`,rows:6,className:"mt-1 font-mono text-xs"}),e.jsxs("div",{className:"flex flex-wrap gap-1 mt-2",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground mr-1",children:"Insert:"}),KHs.map(D=>e.jsx("button",{type:"button",onClick:()=>E(D.key),className:"text-[10px] px-1.5 py-0.5 rounded bg-primary/10 text-primary hover:bg-primary/20",children:D.label},D.key))]})]}),e.jsxs("div",{children:[e.jsx(ne,{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(fr,{className:"h-3 w-3 inline mr-1 text-primary"}),c.video_url.length>50?c.video_url.slice(0,50)+"...":c.video_url]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>d({...c,video_url:null}),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5 flex-wrap",children:[e.jsx(e6,{userId:i||void 0,onSelect:D=>d({...c,video_url:D}),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1 min-w-[120px]"}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1 text-xs flex-1 min-w-[120px]",onClick:()=>j(!0),children:[e.jsx(_a,{className:"h-3 w-3"})," Upload"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1 min-w-[120px]",onClick:()=>{_(""),f(!0)},children:[e.jsx(Yo,{className:"h-3 w-3"})," Paste URL"]}),e.jsx(p_t,{open:v,onOpenChange:j,onUploadComplete:D=>d({...c,video_url:D})}),e.jsx(_s,{open:p,onOpenChange:f,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Add video URL"}),e.jsx(Jn,{children:"Paste a YouTube, Loom, or direct video URL."})]}),e.jsx(ye,{value:y,onChange:D=>_(D.target.value),placeholder:"https://...",autoFocus:!0,onKeyDown:D=>{D.key==="Enter"&&y.trim()&&(d({...c,video_url:y.trim()}),f(!1))}}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{disabled:!y.trim(),onClick:()=>{d({...c,video_url:y.trim()}),f(!1)},children:"Add video"})]})]})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:A,className:"text-destructive hover:text-destructive",children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1"})," Delete step"]}),e.jsxs(B,{size:"sm",onClick:S,disabled:!w||u,children:[u&&e.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Save step"]})]})]})]})}function lGs({open:s,onOpenChange:t,contactIds:n,onSuccess:r}){const{data:a,isLoading:i}=ZPe(),l=h_t(),[o,c]=N.useState(""),[d,u]=N.useState(null),[h,p]=N.useState(!1),f=(a||[]).filter(v=>!v.is_starter),y=f.filter(v=>v.name.toLowerCase().includes(o.toLowerCase())||(v.description||"").toLowerCase().includes(o.toLowerCase())),_=async()=>{if(d)try{const v=await l.mutateAsync({campaignId:d,contactIds:n}),j=[`${v.enrolled} enrolled`];v.skipped>0&&j.push(`${v.skipped} skipped`),v.errors>0&&j.push(`${v.errors} errors`),ae.success(j.join(" · ")),t(!1),u(null),r==null||r()}catch(v){ae.error(v.message||"Failed to enroll contacts")}};return e.jsxs(_s,{open:s,onOpenChange:t,children:[e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Enroll in Drip Campaign"]}),e.jsxs(Jn,{children:[n.length," contact",n.length!==1?"s":""," will be added to the selected campaign. Already-enrolled contacts will be skipped."]})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search campaigns...",value:o,onChange:v=>c(v.target.value),className:"pl-9 h-9"})]}),e.jsx(di,{className:"h-[320px] -mx-1 px-1",children:i?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"Loading..."}):y.length===0?e.jsx("div",{className:"text-center py-8",children:f.length===0?e.jsxs(e.Fragment,{children:[e.jsx(un,{className:"h-8 w-8 text-muted-foreground/40 mx-auto mb-2"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No campaigns yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Build a custom drip campaign to nurture these contacts on autopilot."}),e.jsxs(B,{size:"sm",onClick:()=>p(!0),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," Create campaign"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"No campaigns match your search."})}):e.jsx("div",{className:"space-y-1.5",children:y.map(v=>e.jsxs("button",{onClick:()=>u(v.id),className:`w-full flex items-start gap-3 p-3 rounded-lg border text-left transition-all ${d===v.id?"border-primary bg-primary/5 ring-1 ring-primary":"border-border hover:border-primary/40 hover:bg-muted/30"}`,children:[e.jsx("div",{className:`shrink-0 h-9 w-9 rounded-lg bg-gradient-to-br ${v.cover_color} flex items-center justify-center text-lg`,children:v.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:v.name}),v.is_active&&e.jsx(Ue,{variant:"outline",className:"text-[9px] bg-emerald-500/10 text-emerald-600 border-emerald-200 px-1 py-0",children:"Active"})]}),v.description&&e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-0.5",children:v.description})]}),d===v.id&&e.jsx(Lr,{className:"h-4 w-4 text-primary shrink-0 mt-1"})]},v.id))})})]}),e.jsxs(Xn,{className:"gap-2 sm:gap-2",children:[f.length>0&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>p(!0),className:"mr-auto text-xs",children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," New campaign"]}),e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:_,disabled:!d||l.isPending,children:[l.isPending&&e.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}),"Enroll ",n.length," contact",n.length!==1?"s":""]})]})]}),e.jsx(f_t,{open:h,onOpenChange:p})]})}function cGs({selectedIds:s,contacts:t,onClearSelection:n,onSendToLeadPond:r,showLeadPondAction:a,onTransfer:i,showTransferAction:l}){const o=Ln(),{data:c}=ky(),d=XMe(),u=Kt(),{isGmailConnected:h}=Dh(),{isReady:p}=mR(),{data:f}=pR(),y=WPe(),_=t_t(),[v,j]=N.useState(!1),[w,S]=N.useState(!1),[A,E]=N.useState(!1),[O,D]=N.useState(!1),[I,F]=N.useState(!1),[z,H]=N.useState(""),Z=s.size;if(Z===0)return null;const Y=async me=>{j(!0);try{const ve=Array.from(s).map(Te=>({contact_id:Te,relationship_type_id:me})),{error:ge}=await q.from("innercircle_contact_tags").upsert(ve,{onConflict:"contact_id,relationship_type_id",ignoreDuplicates:!0});if(ge)throw ge;u.invalidateQueries({queryKey:["innercircle-contacts"]}),u.invalidateQueries({queryKey:["innercircle-contact-counts"]}),Br({title:`Assigned type to ${Z} contacts`}),n()}catch(le){Br({title:"Error assigning type",description:le.message,variant:"destructive"})}finally{j(!1)}},W=async me=>{j(!0);try{const le=Array.from(s);for(const ve of le)try{await _.mutateAsync({contactId:ve,tagId:me})}catch{}u.invalidateQueries({queryKey:["all-contact-custom-tags"]}),Br({title:`Tagged ${Z} contacts`}),F(!1),H("")}catch(le){Br({title:"Error adding tags",description:le.message,variant:"destructive"})}finally{j(!1)}},ee=async()=>{if(z.trim()){j(!0);try{const me=await y.mutateAsync({name:z.trim()});await W(me.id)}catch(me){Br({title:"Error creating tag",description:me.message,variant:"destructive"}),j(!1)}}},se=(f==null?void 0:f.filter(me=>me.name.toLowerCase().includes(z.toLowerCase())))||[],oe=f==null?void 0:f.find(me=>me.name.toLowerCase()===z.trim().toLowerCase()),he=()=>{const me=t.filter(Me=>s.has(Me.id)),le=["First Name","Last Name","Email","Phone","Address","Birthday","Home Anniversary","Notes","Relationship Types"],ve=me.map(Me=>{var Pe;return[Me.first_name,Me.last_name||"",Me.email||"",Me.phone||"",Me.address||"",Me.birthday||"",Me.home_anniversary||"",Me.notes||"",((Pe=Me.tags)==null?void 0:Pe.map(Re=>{var Ae;return(Ae=Re.relationship_type)==null?void 0:Ae.name}).join("; "))||""]}),ge=[le.join(","),...ve.map(Me=>Me.map(Pe=>`"${(Pe||"").replace(/"/g,'""')}"`).join(","))].join(` `),Te=new Blob([ge],{type:"text/csv"}),Ie=URL.createObjectURL(Te),Ce=document.createElement("a");Ce.href=Ie,Ce.download=`contacts-export-${new Date().toISOString().slice(0,10)}.csv`,Ce.click(),URL.revokeObjectURL(Ie),Br({title:`Exported ${Z} contacts`})},ce=async()=>{if(confirm(`Are you sure you want to delete ${Z} contacts? This cannot be undone.`)){j(!0);try{const me=Array.from(s);for(const le of me)await d.mutateAsync(le);n()}catch(me){Br({title:"Error deleting contacts",description:me.message,variant:"destructive"})}finally{j(!1)}}};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-primary/5 border border-primary/20 rounded-lg",children:[e.jsxs(Ue,{variant:"secondary",className:"font-semibold",children:[Z," selected"]}),e.jsxs(us,{onValueChange:Y,disabled:v,children:[e.jsx(ls,{className:"w-[180px] h-8",children:e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(oh,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm",children:"Assign Type"})]})}),e.jsx(cs,{children:c==null?void 0:c.filter(me=>me.active).map(me=>e.jsx(Ze,{value:me.id,children:me.name},me.id))})]}),e.jsxs(il,{open:I,onOpenChange:F,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",disabled:v,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"}),"Add Tag"]})}),e.jsxs(el,{className:"w-56 p-2",align:"start",children:[e.jsx(ye,{placeholder:"Search or create tag...",value:z,onChange:me=>H(me.target.value),onKeyDown:me=>{me.key==="Enter"&&z.trim()&&!oe?(me.preventDefault(),ee()):me.key==="Enter"&&oe&&(me.preventDefault(),W(oe.id))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[se.map(me=>e.jsxs("button",{onClick:()=>W(me.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:me.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:me.name})]},me.id)),z.trim()&&!oe&&e.jsxs("button",{onClick:ee,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(Is,{className:"h-3.5 w-3.5"}),'Create "',z.trim(),'"']}),se.length===0&&!z.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create a tag"})]})]})]}),h&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>S(!0),disabled:v,children:[e.jsx(Gs,{className:"h-3.5 w-3.5 mr-1"}),"Email"]}),p&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{const me=Array.from(s).join(",");o(`/admin/email-campaigns/new?contactIds=${me}`)},disabled:v,children:[e.jsx(zd,{className:"h-3.5 w-3.5 mr-1"}),"Mass Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>E(!0),disabled:v,children:[e.jsx(fr,{className:"h-3.5 w-3.5 mr-1"}),"Send Video"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>D(!0),disabled:v,children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1"}),"Enroll in Campaign"]}),a&&r&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>r(Array.from(s)),disabled:v,children:[e.jsx(db,{className:"h-3.5 w-3.5 mr-1"}),"Send to Lead Pond"]}),l&&i&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>i(Array.from(s)),disabled:v,children:[e.jsx(lw,{className:"h-3.5 w-3.5 mr-1"}),"Transfer"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:he,disabled:v,children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1"}),"Export"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ce,disabled:v,className:"text-destructive hover:text-destructive",children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1"}),"Delete"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:n,className:"ml-auto",children:[e.jsx($n,{className:"h-3.5 w-3.5 mr-1"}),"Clear"]})]}),e.jsx(lGs,{open:O,onOpenChange:D,contactIds:Array.from(s),onSuccess:n}),e.jsx(Xv,{open:w,onOpenChange:S,bulkContacts:Array.from(s).map(me=>{const le=t.find(ve=>ve.id===me);return le?{id:le.id,first_name:le.first_name,last_name:le.last_name,email:le.email||""}:null}).filter(me=>me!==null&&me.email!==""),onSendComplete:()=>{S(!1),n()}}),e.jsx(OHs,{open:A,onOpenChange:E,contacts:Array.from(s).map(me=>t.find(le=>le.id===me)).filter(me=>!!me).map(me=>({id:me.id,first_name:me.first_name,last_name:me.last_name,email:me.email})),isGmailConnected:!!h,isMassEmailReady:!!p,onSendComplete:()=>{E(!1),n()}})]})}function lZe({contact:s,onEdit:t,onDelete:n,onSnooze:r,onSendToLeadPond:a,showLeadPondAction:i,onTransfer:l,showTransferAction:o}){const c=Ln(),{isReady:d}=mR(),u=`${s.first_name} ${s.last_name||""}`.trim();return e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:h=>h.stopPropagation(),children:e.jsx(Kf,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",onClick:h=>h.stopPropagation(),children:[e.jsxs(Kr,{onClick:()=>c(`/mission-control/contacts/${s.id}?tab=activity&action=log`),children:[e.jsx(Cr,{className:"h-4 w-4 mr-2"}),"Log Touch"]}),e.jsxs(Kr,{onClick:()=>c(`/mission-control/video?contactId=${s.id}`),children:[e.jsx(fr,{className:"h-4 w-4 mr-2"}),"Send Video"]}),e.jsxs(Kr,{onClick:()=>c(`/mission-control/popbys?contactId=${s.id}`),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"Schedule Pop-by"]}),d&&s.email&&e.jsxs(Kr,{onClick:()=>c(`/admin/email-campaigns/new?contactIds=${s.id}`),children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Mass Email"]}),e.jsxs(Kr,{onClick:()=>r(s.id,u),children:[e.jsx(gf,{className:"h-4 w-4 mr-2"}),"Snooze"]}),i&&a&&e.jsxs(Kr,{onClick:()=>a(s.id),children:[e.jsx(db,{className:"h-4 w-4 mr-2"}),"Send to Lead Pond"]}),o&&l&&e.jsxs(Kr,{onClick:()=>l(s.id),children:[e.jsx(lw,{className:"h-4 w-4 mr-2"}),"Transfer to Team Member"]}),e.jsxs(Kr,{onClick:()=>t(s),children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Kr,{onClick:()=>n(s.id),className:"text-destructive focus:text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})}function cZe({currentFilters:s,currentSortBy:t,onApplySmartList:n}){const{data:r}=s_t(),a=mVs(),i=pVs(),[l,o]=N.useState(!1),[c,d]=N.useState(""),u=s.search||s.type&&s.type!=="all"||s.status&&s.status!=="all"||s.behavior&&Object.values(s.behavior).some(p=>p!==void 0&&p!==!1),h=async()=>{c.trim()&&(await a.mutateAsync({name:c.trim(),filters:s,sort_by:t}),d(""),o(!1))};return e.jsxs(e.Fragment,{children:[e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Lv,{className:"h-3.5 w-3.5"}),"Smart Filters",r&&r.length>0&&e.jsx(Ue,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:r.length}),e.jsx(ao,{className:"h-3.5 w-3.5"})]})}),e.jsxs(gc,{align:"start",className:"w-56",children:[r&&r.length>0?e.jsxs(e.Fragment,{children:[r.map(p=>e.jsxs(Kr,{className:"flex items-center justify-between group",children:[e.jsx("span",{className:"flex-1 cursor-pointer",onClick:()=>n(p.filters,p.sort_by),children:p.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-6 w-6 p-0 opacity-0 group-hover:opacity-100",onClick:f=>{f.stopPropagation(),i.mutate(p.id)},children:e.jsx(_n,{className:"h-3 w-3 text-destructive"})})]},p.id)),e.jsx(Kg,{})]}):e.jsx(Kr,{disabled:!0,className:"text-muted-foreground text-xs",children:"No saved filters yet"}),u&&e.jsxs(Kr,{onClick:()=>o(!0),children:[e.jsx(L7,{className:"h-4 w-4 mr-2"}),"Save Current Filter"]})]})]}),e.jsx(_s,{open:l,onOpenChange:o,children:e.jsxs(bs,{className:"max-w-sm",children:[e.jsx(js,{children:e.jsx(ws,{children:"Save Smart Filter"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(ye,{placeholder:"e.g. Buyers in 40205",value:c,onChange:p=>d(p.target.value),onKeyDown:p=>p.key==="Enter"&&h(),autoFocus:!0}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:h,disabled:!c.trim()||a.isPending,children:"Save"})]})]})]})})]})}const dGs=[{value:"today",label:"Today"},{value:"7d",label:"Last 7 days"},{value:"30d",label:"Last 30 days"},{value:"90d",label:"Last 90 days"},{value:"never",label:"Never active"}];function uGs({open:s,onOpenChange:t,hasLeadSite:n,behavior:r,onApply:a,selectedType:i,onSelectedTypeChange:l,relationshipTypes:o}){const[c,d]=N.useState(r),[u,h]=N.useState(n?"behavior":"contact");N.useEffect(()=>{s&&d(r)},[s,r]);const p=y=>d(_=>({..._,...y})),f=Object.entries(c).filter(([,y])=>y!==void 0&&y!==!1).length;return e.jsx(t0,{open:s,onOpenChange:t,children:e.jsxs(og,{side:"right",className:"w-full sm:max-w-lg overflow-y-auto",children:[e.jsxs(jy,{children:[e.jsxs(Ny,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),"Advanced Filters"]}),e.jsx(Z$,{children:"Slice your database by website activity, contact details, and engagement."})]}),e.jsxs(Fr,{value:u,onValueChange:y=>h(y),className:"mt-4",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-3",children:[e.jsxs(Zt,{value:"contact",className:"gap-1.5",children:[e.jsx(An,{className:"h-3.5 w-3.5"})," Contact"]}),e.jsxs(Zt,{value:"behavior",disabled:!n,className:"gap-1.5",children:[e.jsx(em,{className:"h-3.5 w-3.5"})," Behavior"]}),e.jsx(Zt,{value:"engagement",children:"Engagement"})]}),e.jsx(is,{value:"contact",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Contact Type"}),e.jsxs(us,{value:i,onValueChange:l,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"All types"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),o==null?void 0:o.map(y=>e.jsx(Ze,{value:y.id,children:y.name},y.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More contact-detail filters (assigned user, city, address) coming soon."})]})}),e.jsx(is,{value:"behavior",className:"space-y-6 mt-4",children:n?e.jsxs(e.Fragment,{children:[e.jsxs(aG,{title:"Last Active On Site",children:[e.jsx(ib,{value:c.lastActive||"",onValueChange:y=>p({lastActive:y||void 0}),className:"grid grid-cols-2 gap-2",children:dGs.map(y=>e.jsxs("label",{className:"flex items-center gap-2 rounded-md border px-3 py-2 cursor-pointer hover:bg-accent",children:[e.jsx(Ld,{value:y.value}),e.jsx("span",{className:"text-sm",children:y.label})]},y.value))}),c.lastActive&&e.jsx(B,{variant:"ghost",size:"sm",className:"mt-1 h-7 px-2 text-xs",onClick:()=>p({lastActive:void 0}),children:"Clear"})]}),e.jsxs(aG,{title:"Registration",children:[e.jsx(l2,{label:"Registered on lead site",checked:c.registered==="yes",onChange:y=>p({registered:y?"yes":void 0})}),e.jsx(l2,{label:"Anonymous visitors only",checked:c.registered==="no",onChange:y=>p({registered:y?"no":void 0})})]}),e.jsxs(aG,{title:"Property Activity",children:[e.jsx(l2,{label:"Viewed any listing",checked:c.viewedListing==="any",onChange:y=>p({viewedListing:y?"any":void 0})}),e.jsx(l2,{label:"Hot buyer — 3+ views in last 7 days",checked:c.viewedListing==="multiple7d",onChange:y=>p({viewedListing:y?"multiple7d":void 0})}),e.jsx(l2,{label:"Saved a property",checked:!!c.savedProperty,onChange:y=>p({savedProperty:y||void 0})}),e.jsx(l2,{label:"Has an active saved search / alert",checked:!!c.hasSavedSearch,onChange:y=>p({hasSavedSearch:y||void 0})})]}),e.jsxs(aG,{title:"Requests",children:[e.jsx(l2,{label:"Requested a showing / asked a question",checked:!!c.requestedShowing,onChange:y=>p({requestedShowing:y||void 0})}),e.jsx(l2,{label:"Requested a home valuation",checked:!!c.requestedValuation,onChange:y=>p({requestedValuation:y||void 0})})]})]}):e.jsx("div",{className:"rounded-md border border-dashed p-4 text-sm text-muted-foreground",children:"Connect a Lead Site with MLS to unlock website behavior filters."})}),e.jsxs(is,{value:"engagement",className:"space-y-4 mt-4",children:[e.jsx(l2,{label:"Any website activity",checked:!!c.websiteActiveOnly,onChange:y=>p({websiteActiveOnly:y||void 0})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"More engagement filters (last emailed, awaiting response, past-due tasks) are in the pipeline."})]})]}),e.jsxs(tdt,{className:"mt-6 flex-row gap-2 sm:justify-between",children:[e.jsx(B,{variant:"ghost",onClick:()=>d({}),disabled:f===0,children:"Clear behavior filters"}),e.jsx(B,{onClick:()=>{a(c),t(!1)},children:"Apply"})]})]})})}function aG({title:s,children:t}){return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:s}),e.jsx("div",{className:"space-y-2",children:t})]})}function l2({label:s,checked:t,onChange:n}){return e.jsxs("div",{className:"flex items-center justify-between rounded-md border px-3 py-2",children:[e.jsx("span",{className:"text-sm",children:s}),e.jsx(jn,{checked:t,onCheckedChange:n})]})}function hGs({behavior:s,onRemove:t,onClearAll:n}){const r=mGs(s);return r.length===0?null:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[r.map(({key:a,label:i})=>e.jsxs("span",{className:"inline-flex items-center gap-1 rounded-full bg-primary/10 text-primary text-xs px-2.5 py-1",children:[i,e.jsx("button",{onClick:()=>t(a),className:"hover:bg-primary/20 rounded-full h-4 w-4 inline-flex items-center justify-center","aria-label":`Remove ${i}`,children:"×"})]},a)),e.jsx("button",{onClick:n,className:"text-xs text-primary underline underline-offset-2 hover:no-underline",children:"Clear"})]})}function mGs(s){const t=[];if(s.lastActive){const n={today:"Active today","7d":"Active last 7 days","30d":"Active last 30 days","90d":"Active last 90 days",never:"Never active"};t.push({key:"lastActive",label:n[s.lastActive]})}return s.registered==="yes"&&t.push({key:"registered",label:"Registered"}),s.registered==="no"&&t.push({key:"registered",label:"Anonymous visitor"}),s.viewedListing==="any"&&t.push({key:"viewedListing",label:"Viewed a listing"}),s.viewedListing==="multiple7d"&&t.push({key:"viewedListing",label:"🔥 Hot buyer (3+ views/7d)"}),s.savedProperty&&t.push({key:"savedProperty",label:"Saved a property"}),s.hasSavedSearch&&t.push({key:"hasSavedSearch",label:"Active saved search"}),s.requestedShowing&&t.push({key:"requestedShowing",label:"Requested showing/question"}),s.requestedValuation&&t.push({key:"requestedValuation",label:"Requested valuation"}),s.websiteActiveOnly&&t.push({key:"websiteActiveOnly",label:"Any website activity"}),t}async function PI(s){const n=[];for(let r=0;r<50;r++){const{data:a,error:i}=await s(r*1e3,r*1e3+1e3-1);if(i)throw i;const l=a||[];if(n.push(...l),l.length<1e3)break}return n}function CF(){return{lastActiveAt:null,registered:!1,propertyViewCount:0,propertyViewCount7d:0,savedListingCount:0,activeSavedSearchCount:0,showingRequests:0,valuationRequests:0,viewedCities:[],viewedZips:[]}}function pGs(){const{user:s}=vs(),{leadSite:t,hasLeadSite:n}=Ap(),{data:r,isLoading:a}=dt({queryKey:["contact-behavior-summary",s==null?void 0:s.id,t==null?void 0:t.id],queryFn:async()=>{const i=new Map;if(!t)return i;const l=(j,w)=>{const S=i.get(j)||CF();i.set(j,{...S,...w})},o=await PI((j,w)=>q.from("lead_site_visitors").select("id, contact_id, last_seen_at, email").eq("lead_site_id",t.id).not("contact_id","is",null).range(j,w)),c=new Map,d=new Map;o.forEach(j=>{if(!j.contact_id)return;c.set(j.id,j.contact_id),j.email&&d.set(j.email.toLowerCase(),j.contact_id);const w=i.get(j.contact_id);(!w||!w.lastActiveAt||j.last_seen_at>w.lastActiveAt)&&l(j.contact_id,{lastActiveAt:j.last_seen_at})});const u=await PI((j,w)=>q.from("lead_site_consumer_profiles").select("contact_id, user_id").eq("lead_site_id",t.id).not("contact_id","is",null).range(j,w)),h=new Map;u.forEach(j=>{j.contact_id&&(h.set(j.user_id,j.contact_id),l(j.contact_id,{registered:!0}))});const p=new Date(Date.now()-7*24*60*60*1e3).toISOString();return(await PI((j,w)=>q.from("lead_site_property_views").select("visitor_id, viewed_at, property_address").eq("lead_site_id",t.id).not("visitor_id","is",null).range(j,w))).forEach(j=>{const w=j.visitor_id?c.get(j.visitor_id):null;if(!w)return;const S=i.get(w)||CF();S.propertyViewCount+=1,j.viewed_at>=p&&(S.propertyViewCount7d+=1),i.set(w,S)}),(await PI((j,w)=>q.from("lead_site_saved_listings").select("user_id, mls_number").eq("lead_site_id",t.id).range(j,w))).forEach(j=>{const w=h.get(j.user_id);if(!w)return;const S=i.get(w)||CF();S.savedListingCount+=1,i.set(w,S)}),(await PI((j,w)=>q.from("lead_site_saved_searches").select("user_id").eq("lead_site_id",t.id).eq("is_active",!0).range(j,w))).forEach(j=>{const w=h.get(j.user_id);if(!w)return;const S=i.get(w)||CF();S.activeSavedSearchCount+=1,i.set(w,S)}),(await PI((j,w)=>q.from("lead_site_leads").select("email, lead_type").eq("lead_site_id",t.id).not("email","is",null).range(j,w))).forEach(j=>{if(!j.email)return;const w=d.get(j.email.toLowerCase());if(!w)return;const S=i.get(w)||CF(),A=(j.lead_type||"").toLowerCase();(A.includes("showing")||A.includes("question")||A==="contact")&&(S.showingRequests+=1),(A.includes("valuation")||A.includes("cma")||A.includes("home_value"))&&(S.valuationRequests+=1),i.set(w,S)}),i},enabled:!!s&&n,staleTime:5*60*1e3});return{behaviorMap:r??new Map,hasLeadSite:n,isLoading:a}}function dZe(s){if(!s)return null;const t=Ll(s);if(!t)return null;const n=new Date;n.setHours(0,0,0,0);const r=new Date(n.getFullYear(),t.getMonth(),t.getDate());return rs.relationshipScore.status==="at-risk"},{key:"never-contacted",title:"Never Contacted",subtitle:"No outreach yet",icon:Fo,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:pr,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:Tv,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:Ah,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:Or,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:zm,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:lc,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:un,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:ic,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,n;return!((t=s.email)!=null&&t.trim())&&!((n=s.phone)!=null&&n.trim())}}];function fGs({contacts:s,contactDealsMap:t,websiteActiveIds:n,activeKey:r,onSelect:a}){const i=N.useRef(null),l=N.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":n.size,"missing-info":0,vips:0};if(!s)return c;for(const d of s){const u={hasDeal:!!(t&&t[d.id]),daysToBirthday:dZe(d.birthday),daysToAnniv:dZe(d.home_anniversary)};for(const h of uZe)h.key!=="website-active"&&h.match(d,u)&&c[h.key]++}return c},[s,t,n]),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(un,{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:[r&&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($n,{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(ml,{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(ga,{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:uZe.map(c=>{const d=c.icon,u=l[c.key],h=r===c.key,p=u===0;return e.jsxs("button",{onClick:()=>a(h?null:c.key),disabled:p&&!h,className:`group relative shrink-0 snap-start w-[180px] text-left rounded-xl border transition-all duration-200 overflow-hidden ${h?"border-[#406E71] ring-2 ring-[#406E71]/30 shadow-lg scale-[1.02] bg-card":p?"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:u.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 x_t="innercircle_geocode_cache_v1";function xGs(){try{return JSON.parse(localStorage.getItem(x_t)||"{}")}catch{return{}}}function gGs(s){try{localStorage.setItem(x_t,JSON.stringify(s))}catch{}}function yGs(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 vGs({open:s,onOpenChange:t,contacts:n,onCitySelect:r}){const a=N.useRef(null),i=N.useRef(null),[l,o]=N.useState(""),[c,d]=N.useState(!0),[u,h]=N.useState([]),[p,f]=N.useState({done:0,total:0}),[y,_]=N.useState(!1),[v,j]=N.useState("heat");N.useEffect(()=>{if(!s)return;let S=!1;return(async()=>{d(!0);const{data:A}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();S||(o((A==null?void 0:A.value)||""),d(!1))})(),()=>{S=!0}},[s]),N.useEffect(()=>{if(!s||!l)return;let S=!1;return(async()=>{const E=xGs(),O=n.map(W=>({c:W,addr:yGs(W)})).filter(W=>W.addr),D=[],I=[];for(const{c:W,addr:ee}of O){const se=E[ee];se!==null&&(se?D.push({id:W.id,name:`${W.first_name||""} ${W.last_name||""}`.trim(),city:W.city||null,state:W.state||null,zip:W.zip||W.zip_code||null,lat:se.lat,lng:se.lng}):I.push({c:W,addr:ee}))}if(S||h(D),f({done:D.length,total:O.length}),I.length===0)return;_(!0);const F=6;let z=0;const H={...E},Z=[...D],Y=async()=>{var W;for(;z{S=!0}},[s,l,n]);const w=N.useMemo(()=>{const S=new Map;for(const A of n){const E=(A.city||"").trim();if(!E)continue;const O=(A.state||"").trim()||null,D=`${E.toLowerCase()}|${O||""}`,I=S.get(D);I?I.count++:S.set(D,{city:E,state:O,count:1})}return Array.from(S.values()).sort((A,E)=>E.count-A.count)},[n]);return N.useEffect(()=>{if(!(!s||!l||!a.current||i.current))return ul.accessToken=l,i.current=new ul.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[-98.5795,39.8283],zoom:3.5}),i.current.addControl(new ul.NavigationControl,"top-right"),()=>{var S;(S=i.current)==null||S.remove(),i.current=null}},[s,l]),N.useEffect(()=>{const S=i.current;if(!S||u.length===0)return;const A=()=>{const O={type:"FeatureCollection",features:u.map(I=>({type:"Feature",properties:{id:I.id,name:I.name},geometry:{type:"Point",coordinates:[I.lng,I.lat]}}))},D=S.getSource("contacts-src");if(D?D.setData(O):(S.addSource("contacts-src",{type:"geojson",data:O}),S.addLayer({id:"contacts-heat",type:"heatmap",source:"contacts-src",maxzoom:15,paint:{"heatmap-weight":1,"heatmap-intensity":["interpolate",["linear"],["zoom"],0,1,15,3],"heatmap-color":["interpolate",["linear"],["heatmap-density"],0,"rgba(64,110,113,0)",.2,"rgba(64,110,113,0.4)",.4,"rgba(56,189,248,0.6)",.6,"rgba(250,204,21,0.7)",.8,"rgba(249,115,22,0.85)",1,"rgba(220,38,38,1)"],"heatmap-radius":["interpolate",["linear"],["zoom"],0,12,9,30,15,60],"heatmap-opacity":["interpolate",["linear"],["zoom"],13,1,15,.6]}}),S.addLayer({id:"contacts-points",type:"circle",source:"contacts-src",paint:{"circle-radius":["interpolate",["linear"],["zoom"],0,4,8,5,16,9],"circle-color":"#406E71","circle-stroke-color":"#ffffff","circle-stroke-width":1.5,"circle-opacity":.9}}),S.on("click","contacts-points",I=>{var H;const F=(H=I.features)==null?void 0:H[0];if(!F)return;const z=F.geometry.coordinates.slice();new ul.Popup({offset:12}).setLngLat(z).setHTML(`
${F.properties.name||"Contact"}
`).addTo(S)}),S.on("mouseenter","contacts-points",()=>{S.getCanvas().style.cursor="pointer"}),S.on("mouseleave","contacts-points",()=>{S.getCanvas().style.cursor=""})),S.getLayer("contacts-heat")&&S.setLayoutProperty("contacts-heat","visibility",v==="heat"?"visible":"none"),S.getLayer("contacts-points")&&(S.setPaintProperty("contacts-points","circle-opacity",v==="points"?.9:0),S.setLayoutProperty("contacts-points","visibility","visible")),u.length>0&&!S._fitDone){const I=new ul.LngLatBounds;u.forEach(F=>I.extend([F.lng,F.lat]));try{S.fitBounds(I,{padding:60,maxZoom:11,duration:600}),S._fitDone=!0}catch{}}};S.isStyleLoaded()?A():S.once("load",A)},[u,v]),e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-6xl w-[95vw] h-[90vh] p-0 flex flex-col",children:[e.jsx(js,{className:"p-4 pb-2 border-b",children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Hc,{className:"h-5 w-5 text-orange-500"}),"Geographic Heat Map",e.jsxs(Ue,{variant:"secondary",className:"ml-2",children:[u.length," mapped · ",w.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(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):l?e.jsxs(e.Fragment,{children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),e.jsxs("div",{className:"absolute top-3 left-3 flex flex-col gap-2 z-10",children:[e.jsxs("div",{className:"bg-background/95 backdrop-blur rounded-md shadow-md border p-1 flex",children:[e.jsxs(B,{size:"sm",variant:v==="heat"?"default":"ghost",onClick:()=>j("heat"),className:"h-8",children:[e.jsx(Hc,{className:"h-3.5 w-3.5 mr-1"})," Heat"]}),e.jsxs(B,{size:"sm",variant:v==="points"?"default":"ghost",onClick:()=>j("points"),className:"h-8",children:[e.jsx(X7,{className:"h-3.5 w-3.5 mr-1"})," Pins"]})]}),y&&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(rs,{className:"h-3 w-3 animate-spin"}),"Mapping ",p.done," / ",p.total]})]})]}):e.jsxs("div",{className:"h-full flex flex-col items-center justify-center gap-3 p-6 text-center",children:[e.jsx(Bi,{className:"h-10 w-10 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Mapbox token is not set. Contact your administrator."})]})]})}),e.jsxs("div",{className:"w-full md:w-72 border-t md:border-t-0 md:border-l flex flex-col bg-muted/30 min-h-[200px]",children:[e.jsxs("div",{className:"p-3 border-b bg-background",children:[e.jsxs("h3",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(ka,{className:"h-4 w-4 text-primary"}),"Top Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Tap a city to filter your contacts"})]}),e.jsx(di,{className:"flex-1",children:e.jsxs("div",{className:"p-2 space-y-1.5",children:[w.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."}),w.slice(0,50).map((S,A)=>{var D;const E=((D=w[0])==null?void 0:D.count)||1,O=S.count/E*100;return e.jsx(fe,{className:"cursor-pointer hover:border-primary transition-colors overflow-hidden",onClick:()=>{r==null||r(S.city,S.state),t(!1)},children:e.jsxs(Ee,{className:"p-2.5 relative",children:[e.jsx("div",{className:"absolute inset-y-0 left-0 bg-primary/10",style:{width:`${O}%`}}),e.jsxs("div",{className:"relative flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[S.city,S.state?`, ${S.state}`:""]}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:A===0?"🔥 Hottest market":`Rank #${A+1}`})]}),e.jsx(Ue,{variant:"secondary",className:"shrink-0",children:S.count})]})]})},`${S.city}-${S.state}-${A}`)})]})})]})]})]})})}function EE(s){if(!s)return null;try{const t=s.split(/[-/T]/);if(t.length<3)return null;const n=parseInt(t[1],10)-1,r=parseInt(t[2],10);if(isNaN(n)||isNaN(r))return null;const a=new Date;a.setHours(0,0,0,0);let i=new Date(a.getFullYear(),n,r);return i.setHours(0,0,0,0),in)return null;const a=t==="birthday"?"🎂":"🏡",i=r===0?t==="birthday"?"Birthday today!":"Anniversary today!":r===1?t==="birthday"?"Birthday tomorrow":"Anniversary tomorrow":`${a} in ${r}d`;return{emoji:a,label:i,daysUntil:r}}function hZe({birthday:s,homeAnniversary:t,weddingAnniversary:n,className:r,contactId:a,contactName:i,contactAddress:l}){const o=Ln(),c=oNe(s,"birthday",7),d=oNe(t,"anniversary",7),u=oNe(n||null,"anniversary",7);if(!c&&!d&&!u)return null;const h=(p,f,y)=>{y.stopPropagation();const _=new URLSearchParams;a&&_.set("contactId",a),i&&_.set("name",i),l&&_.set("address",l),(p==="home_anniversary"||p==="wedding_anniversary")&&f&&_.set("date",f),_.set("cardType",p),o(`/mission-control/card-studio?${_.toString()}`)};return e.jsxs("div",{className:Mt("flex flex-wrap gap-1",r),children:[c&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Ue,{variant:"secondary",className:Mt("text-[10px] gap-0.5 font-medium",c.daysUntil===0?"bg-pink-100 text-pink-700 dark:bg-pink-900/30 dark:text-pink-400 animate-pulse":"bg-pink-50 text-pink-600 dark:bg-pink-900/20 dark:text-pink-400"),children:c.label}),a&&e.jsxs("button",{onClick:p=>h("birthday",s,p),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-pink-500/15 text-pink-600 dark:text-pink-400 hover:bg-pink-500/25 transition-colors",title:"Send a birthday card",children:[e.jsx(Gs,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),d&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(Ue,{variant:"secondary",className:Mt("text-[10px] gap-0.5 font-medium",d.daysUntil===0?"bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400 animate-pulse":"bg-blue-50 text-blue-600 dark:bg-blue-900/20 dark:text-blue-400"),children:d.label}),a&&e.jsxs("button",{onClick:p=>h("home_anniversary",t,p),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-blue-500/15 text-blue-600 dark:text-blue-400 hover:bg-blue-500/25 transition-colors",title:"Send an anniversary card",children:[e.jsx(Gs,{className:"h-2.5 w-2.5"}),"Send Card"]})]}),u&&e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsxs(Ue,{variant:"secondary",className:Mt("text-[10px] gap-0.5 font-medium",u.daysUntil===0?"bg-rose-100 text-rose-700 dark:bg-rose-900/30 dark:text-rose-400 animate-pulse":"bg-rose-50 text-rose-600 dark:bg-rose-900/20 dark:text-rose-400"),children:["💍 ",u.label.replace(/^[^\w]+/,"")]}),a&&e.jsxs("button",{onClick:p=>h("wedding_anniversary",n||null,p),className:"inline-flex items-center gap-0.5 px-1.5 py-0.5 rounded-full text-[9px] font-semibold bg-rose-500/15 text-rose-600 dark:text-rose-400 hover:bg-rose-500/25 transition-colors",title:"Send a wedding anniversary card",children:[e.jsx(Gs,{className:"h-2.5 w-2.5"}),"Send Card"]})]})]})}function mZe({deal:s}){if(!s||!s.stage)return null;const{stage:t}=s;return e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1 font-medium whitespace-nowrap",style:{borderColor:t.color,color:t.color,backgroundColor:`${t.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:t.color}}),t.name]})}function pZe({count:s,className:t}){return!s||s<=0?null:e.jsxs(Ue,{variant:"outline",className:Mt("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(RA,{className:"h-2.5 w-2.5"}),s===1?"In drip":`${s} drips`]})}function bGs(){const s=wa();return dt({queryKey:["contacts-campaign-counts",s],queryFn:async()=>{if(!s)return{};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("contact_id, status").eq("owner_user_id",s).eq("status","active");if(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&(r[a.contact_id]=(r[a.contact_id]||0)+1)}),r},enabled:!!s,staleTime:6e4})}function _Gs(){const s=wa();return dt({queryKey:["contact-deals-map",s],queryFn:async()=>{const{data:t,error:n}=await q.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(n)throw n;const r={};return(t||[]).forEach(a=>{a.contact_id&&!r[a.contact_id]&&(r[a.contact_id]=a)}),r},enabled:!!s})}function wGs({contactId:s,compact:t=!1}){const{data:n}=pR(),{data:r}=cVs(s),a=WPe(),i=t_t(),l=hVs(),[o,c]=N.useState(!1),[d,u]=N.useState(""),h=N.useRef(null),p=new Set((r==null?void 0:r.map(j=>j.tag_id))||[]),f=(n==null?void 0:n.filter(j=>j.name.toLowerCase().includes(d.toLowerCase())))||[],y=n==null?void 0:n.find(j=>j.name.toLowerCase()===d.trim().toLowerCase()),_=async j=>{p.has(j.id)?await l.mutateAsync({contactId:s,tagId:j.id}):await i.mutateAsync({contactId:s,tagId:j.id})},v=async()=>{if(!(!d.trim()||y))try{const j=await a.mutateAsync({name:d.trim()});await i.mutateAsync({contactId:s,tagId:j.id}),u("")}catch{}};return e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5",children:[r==null?void 0:r.map(j=>{var w,S,A;return e.jsxs(Ue,{variant:"outline",className:"text-xs gap-1 pr-1",style:{borderColor:((w=j.tag)==null?void 0:w.color)||"#6366F1",color:((S=j.tag)==null?void 0:S.color)||"#6366F1"},children:[e.jsx(oh,{className:"h-2.5 w-2.5"}),(A=j.tag)==null?void 0:A.name,e.jsx("button",{onClick:E=>{E.stopPropagation(),l.mutate({contactId:s,tagId:j.tag_id})},className:"ml-0.5 rounded-full hover:bg-accent p-0.5",children:e.jsx($n,{className:"h-2.5 w-2.5"})})]},j.id)}),e.jsxs(il,{open:o,onOpenChange:c,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:t?"h-6 w-6 p-0":"h-6 px-2 text-xs",onClick:j=>j.stopPropagation(),children:[e.jsx(Is,{className:"h-3 w-3"}),!t&&e.jsx("span",{className:"ml-1",children:"Tag"})]})}),e.jsxs(el,{className:"w-56 p-2",align:"start",onClick:j=>j.stopPropagation(),children:[e.jsx(ye,{ref:h,placeholder:"Search or create tag...",value:d,onChange:j=>u(j.target.value),onKeyDown:j=>{j.key==="Enter"&&d.trim()&&!y?(j.preventDefault(),v()):j.key==="Enter"&&y&&!p.has(y.id)&&(j.preventDefault(),_(y))},className:"h-8 text-sm mb-2"}),e.jsxs("div",{className:"max-h-[200px] overflow-y-auto space-y-0.5",children:[f.map(j=>e.jsxs("button",{onClick:()=>_(j),className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors",children:[e.jsx("div",{className:"h-3 w-3 rounded-full shrink-0",style:{backgroundColor:j.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:j.name}),p.has(j.id)&&e.jsx(Lr,{className:"h-3.5 w-3.5 text-primary shrink-0"})]},j.id)),d.trim()&&!y&&e.jsxs("button",{onClick:v,className:"flex items-center gap-2 w-full px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors text-primary",children:[e.jsx(Is,{className:"h-3.5 w-3.5"}),'Create "',d.trim(),'"']}),f.length===0&&!d.trim()&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-2",children:"Type to create your first tag"})]})]})]})]})}function fZe({contactId:s,tags:t}){return!t||t.length===0?null:e.jsx(e.Fragment,{children:t.map(n=>{var r,a,i;return e.jsx(Ue,{variant:"outline",className:"text-[10px] gap-0.5",style:{borderColor:((r=n.tag)==null?void 0:r.color)||"#6366F1",color:((a=n.tag)==null?void 0:a.color)||"#6366F1"},children:(i=n.tag)==null?void 0:i.name},n.tag_id)})})}const iG=["#6366F1","#8B5CF6","#EC4899","#EF4444","#F97316","#F59E0B","#10B981","#14B8A6","#06B6D4","#3B82F6","#6B7280","#1F2937"];function jGs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=pR(),a=WPe(),i=uVs(),l=dVs(),[o,c]=N.useState(""),[d,u]=N.useState(iG[0]),[h,p]=N.useState(null),[f,y]=N.useState(""),[_,v]=N.useState(""),j=async()=>{if(o.trim())try{await a.mutateAsync({name:o.trim(),color:d}),c(""),u(iG[0]),Br({title:"Tag created"})}catch(E){Br({title:"Error",description:E.message,variant:"destructive"})}},w=async E=>{if(f.trim())try{await i.mutateAsync({id:E,name:f.trim(),color:_}),p(null),Br({title:"Tag updated"})}catch(O){Br({title:"Error",description:O.message,variant:"destructive"})}},S=async(E,O)=>{if(confirm(`Delete tag "${O}"? It will be removed from all contacts.`))try{await l.mutateAsync(E),Br({title:"Tag deleted"})}catch(D){Br({title:"Error",description:D.message,variant:"destructive"})}},A=E=>{p(E.id),y(E.name),v(E.color)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Manage Tags"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"New tag name...",value:o,onChange:E=>c(E.target.value),onKeyDown:E=>E.key==="Enter"&&j(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:j,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:iG.map(E=>e.jsx("button",{onClick:()=>u(E),className:`h-6 w-6 rounded-full border-2 transition-transform ${d===E?"border-foreground scale-110":"border-transparent hover:scale-105"}`,style:{backgroundColor:E}},E))})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[320px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tags yet. Create one above!"}),n==null?void 0:n.map(E=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:h===E.id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"flex flex-wrap gap-1",children:iG.map(O=>e.jsx("button",{onClick:()=>v(O),className:`h-5 w-5 rounded-full border-2 ${_===O?"border-foreground":"border-transparent"}`,style:{backgroundColor:O}},O))}),e.jsx(ye,{value:f,onChange:O=>y(O.target.value),onKeyDown:O=>O.key==="Enter"&&w(E.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>w(E.id),children:e.jsx(Lr,{className:"h-4 w-4 text-primary"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>p(null),children:e.jsx($n,{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:E.color}}),e.jsx("span",{className:"flex-1 text-sm",children:E.name}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>A(E),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>S(E.id,E.name),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})},E.id))]})]})})}function NGs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=qD(),a=t6e(),i=mrs(),l=prs(),[o,c]=N.useState(""),[d,u]=N.useState(null),[h,p]=N.useState(""),f=async()=>{if(o.trim())try{await a.mutateAsync(o.trim()),c("")}catch(j){ae.error(j.message||"Failed to add lead source")}},y=async j=>{if(h.trim())try{await i.mutateAsync({id:j,name:h.trim()}),u(null)}catch(w){ae.error(w.message||"Failed to update")}},_=async(j,w)=>{if(confirm(`Remove lead source "${w}"? Contacts using it will keep the label but it won't appear in new dropdowns.`))try{await l.mutateAsync(j)}catch(S){ae.error(S.message||"Failed to remove")}},v=j=>{u(j.id),p(j.name)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Manage Lead Sources"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"New lead source name...",value:o,onChange:j=>c(j.target.value),onKeyDown:j=>j.key==="Enter"&&f(),className:"flex-1 h-9"}),e.jsxs(B,{size:"sm",onClick:f,disabled:!o.trim()||a.isPending,className:"h-9",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add"]})]}),e.jsxs("div",{className:"mt-2 space-y-1 max-h-[360px] overflow-y-auto",children:[r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Loading..."}),(n==null?void 0:n.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No lead sources yet. Create one above!"}),n==null?void 0:n.map(j=>e.jsx("div",{className:"flex items-center gap-2 p-2 rounded-lg hover:bg-accent/50 group",children:d===j.id?e.jsxs(e.Fragment,{children:[e.jsx(ye,{value:h,onChange:w=>p(w.target.value),onKeyDown:w=>w.key==="Enter"&&y(j.id),className:"flex-1 h-8 text-sm",autoFocus:!0}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>y(j.id),children:e.jsx(Lr,{className:"h-4 w-4 text-primary"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>u(null),children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"flex-1 text-sm",children:j.name}),j.owner_user_id&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>v(j),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 w-7 p-0 opacity-0 group-hover:opacity-100 transition-opacity text-destructive hover:text-destructive",onClick:()=>_(j.id,j.name),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}),!j.owner_user_id&&e.jsx("span",{className:"text-xs text-muted-foreground",children:"Default"})]})},j.id))]})]})})}function g_t({value:s,onChange:t,label:n="Lead Source"}){const{data:r}=qD(),a=t6e(),[i,l]=N.useState(!1),[o,c]=N.useState(""),d=async()=>{if(o.trim())try{const u=await a.mutateAsync(o.trim());u&&(t(u.id),c(""),l(!1))}catch{}};return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:n}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:s||"_none",onValueChange:u=>t(u==="_none"?"":u),children:[e.jsx(ls,{className:"flex-1",children:e.jsx(hs,{placeholder:"Select lead source"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"_none",children:"No source"}),r==null?void 0:r.map(u=>e.jsx(Ze,{value:u.id,children:u.name},u.id))]})]}),e.jsx(B,{type:"button",variant:"outline",size:"icon",className:"shrink-0",onClick:()=>l(!i),children:i?e.jsx($n,{className:"h-4 w-4"}):e.jsx(Is,{className:"h-4 w-4"})})]}),i&&e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"New lead source name...",value:o,onChange:u=>c(u.target.value),onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())},className:"flex-1"}),e.jsx(B,{type:"button",size:"sm",onClick:d,disabled:!o.trim()||a.isPending,children:"Add"})]})]})}function D5e({contactId:s,currentSpouseContactId:t,currentSpouseName:n,currentSpouseEmail:r,onLink:a,onUnlink:i,isEditing:l}){const o=Ln(),c=wa(),[d,u]=N.useState(!1),[h,p]=N.useState(""),{data:f}=dt({queryKey:["innercircle-contact-spouse",t],queryFn:async()=>{const{data:_,error:v}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, birthday").eq("id",t).maybeSingle();if(v)throw v;return _},enabled:!!t}),{data:y}=dt({queryKey:["spouse-search",c,s,h],queryFn:async()=>{let _=q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("owner_user_id",c).is("synced_source",null).neq("id",s).order("first_name").limit(20);if(h.trim()){const w=h.replace(/[,()%]/g," ").trim();w&&(_=_.or(`first_name.ilike.%${w}%,last_name.ilike.%${w}%,email.ilike.%${w}%,phone.ilike.%${w}%`))}const{data:v,error:j}=await _;if(j)throw j;return v},enabled:d&&!!c});if(t&&f){const _=`${f.first_name} ${f.last_name||""}`.trim();return e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{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(Wi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("button",{onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"text-sm font-medium text-primary hover:underline truncate block",children:_}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[f.phone,f.email].filter(Boolean).join(" · ")||"No contact info"})]}),l&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:i,className:"shrink-0 h-7 px-2",children:[e.jsx(OA,{className:"h-3.5 w-3.5 mr-1"}),"Unlink"]}),!l&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>o(`/mission-control/contacts/${f.id}`),className:"shrink-0 h-7 px-2",children:e.jsx(Oa,{className:"h-3.5 w-3.5"})})]})]})}return!t&&(n||r)?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{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(Wi,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("span",{className:"text-sm",children:n}),r&&e.jsx("span",{className:"text-xs text-muted-foreground block truncate",children:r})]}),l&&e.jsxs(il,{open:d,onOpenChange:u,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{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(el,{className:"w-72 p-2",align:"end",children:e.jsx(xZe,{search:h,setSearch:p,results:y,onSelect:_=>{a(_),u(!1),p("")}})})]})]})]}):l?e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Spouse / Partner"}),e.jsxs(il,{open:d,onOpenChange:u,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{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(el,{className:"w-72 p-2",align:"start",children:e.jsx(xZe,{search:h,setSearch:p,results:y,onSelect:_=>{a(_),u(!1),p("")}})})]})]}):null}function xZe({search:s,setSearch:t,results:n,onSelect:r}){return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{value:s,onChange:a=>t(a.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(di,{className:"max-h-48",children:n&&n.length>0?e.jsx("div",{className:"space-y-0.5",children:n.map(a=>e.jsxs("button",{onClick:()=>r(a.id),className:"w-full text-left px-2 py-1.5 rounded hover:bg-accent transition-colors",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[a.first_name," ",a.last_name]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:[a.phone,a.email].filter(Boolean).join(" · ")||"No contact info"})]},a.id))}):e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:s?"No contacts found":"Type to search contacts"})})]})}function kGs(){var fs;const s=Ln(),[t,n]=xl(),{user:r}=vs(),a=fR(),i=Kt(),l=t.get("type"),o=t.get("filter")??t.get("status"),c=t.get("new")==="true",{contactsWithScores:d,isLoading:u}=Mye(),{activeContactIds:h,hasLeadSite:p}=kHs(),{data:f}=bGs(),{data:y}=ky(),{data:_}=_Gs(),{data:v}=pR(),{data:j}=h1e(),[w,S]=N.useState(new Set),[A,E]=N.useState("any"),O=Cye(),D=QMe(),I=XMe(),F=Smt(),[z,H]=N.useState(""),[Z,Y]=N.useState(!1),[W,ee]=N.useState(l||"all"),[se,oe]=N.useState(o||"all"),[he,ce]=N.useState("date-added"),[me,le]=N.useState("all"),[ve,ge]=N.useState({}),[Te,Ie]=N.useState(!1),{behaviorMap:Ce,hasLeadSite:Me}=pGs(),[Pe,Re]=N.useState(c),[Ae,Be]=N.useState(null),[we,Je]=N.useState(!1),[ke,it]=N.useState(!1),[je,He]=N.useState(null),[$e,Ke]=N.useState(""),[Ge,rt]=N.useState(new Set),[tt,at]=N.useState(!1),Ye=Math.max(1,parseInt(t.get("page")||"1",10)||1),[ut,_t]=N.useState(Ye),bt=N.useCallback(lt=>{_t(ns=>{const Vs=typeof lt=="function"?lt(ns):lt;return n(ys=>{const mn=new URLSearchParams(ys);return Vs<=1?mn.delete("page"):mn.set("page",String(Vs)),mn},{replace:!0}),Vs})},[]),[$t,Yt]=N.useState(50),[Ds,Ls]=N.useState("my"),[xs,Lt]=N.useState(!1),[Jt,gt]=N.useState(!1),{data:zt}=Wv(),{addToLeadPond:As}=L0t(zt==null?void 0:zt.teamId),Xt=!!((fs=zt==null?void 0:zt.team)!=null&&fs.lead_pond_enabled&&(zt!=null&&zt.teamId)),Qs=!!(zt!=null&&zt.teamId),[ks,$s]=N.useState([]),[an,tn]=N.useState(!1),er=lt=>{$s([lt]),tn(!0)},xn=lt=>{$s(lt),tn(!0)},Pn=lt=>{zt!=null&&zt.teamId&&As.mutate({contact_id:lt,team_id:zt.teamId})},Qn=lt=>{zt!=null&&zt.teamId&<.forEach(ns=>{As.mutate({contact_id:ns,team_id:zt.teamId})})},sa=N.useCallback(lt=>{at(!1),rt(ns=>{const Vs=new Set(ns);return Vs.has(lt)?Vs.delete(lt):Vs.add(lt),Vs})},[]);N.useEffect(()=>{if(!(r!=null&&r.id))return;const lt=q.channel(`innercircle_contacts_inserts_${r.id}`).on("postgres_changes",{event:"INSERT",schema:"public",table:"innercircle_contacts",filter:`owner_user_id=eq.${r.id}`},()=>{i.invalidateQueries({queryKey:["innercircle-contacts"]}),i.invalidateQueries({queryKey:["innercircle-contact-counts"]})}).subscribe();return()=>{q.removeChannel(lt)}},[i,r==null?void 0:r.id]),N.useEffect(()=>{o&&oe(o)},[o]);const[na,Es]=N.useState({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]});N.useEffect(()=>{c&&Re(!0)},[c]),N.useEffect(()=>{var lt;Ae&&Es({first_name:Ae.first_name||"",last_name:Ae.last_name||"",email:Ae.email||"",phone:Ae.phone||"",address:Ae.address||"",city:Ae.city||"",state:Ae.state||"",zip_code:Ae.zip_code||"",birthday:Ae.birthday||"",home_anniversary:Ae.home_anniversary||"",spouse_name:Ae.spouse_name||"",spouse_email:Ae.spouse_email||"",lead_source_id:Ae.lead_source_id||"",notes:Ae.notes||"",tagIds:((lt=Ae.tags)==null?void 0:lt.map(ns=>ns.relationship_type_id))||[]})},[Ae]);const mi=N.useMemo(()=>{const lt=new Set;return v==null||v.forEach(ns=>{(ns.name==="Recruits"||ns.name==="Brokerage Agents")&<.add(ns.id)}),lt},[v]),Ar=N.useMemo(()=>Array.from(w).some(lt=>mi.has(lt)),[w,mi]),Hn=N.useMemo(()=>{if(!d)return[];let lt=d.filter(ys=>{var wr,Er,xa,Ki,io,Xa,Mr,qi,Vi,si,Yi;if(!Ar&&ys.synced_source)return!1;const mn=z===""||`${ys.first_name} ${ys.last_name}`.toLowerCase().includes(z.toLowerCase())||((wr=ys.email)==null?void 0:wr.toLowerCase().includes(z.toLowerCase()))||((Er=ys.phone)==null?void 0:Er.includes(z))||((xa=ys.city)==null?void 0:xa.toLowerCase().includes(z.toLowerCase()))||((Ki=ys.state)==null?void 0:Ki.toLowerCase().includes(z.toLowerCase()))||((io=ys.address)==null?void 0:io.toLowerCase().includes(z.toLowerCase()))||((Xa=ys.zip_code)==null?void 0:Xa.toLowerCase().includes(z.toLowerCase())),On=W==="all"||((Mr=ys.tags)==null?void 0:Mr.some(Zi=>Zi.relationship_type_id===W)),vn=w.size===0||(()=>{const Zi=(j==null?void 0:j.filter(aa=>aa.contact_id===ys.id).map(aa=>aa.tag_id))||[];return A==="any"?Zi.some(aa=>w.has(aa)):Array.from(w).every(aa=>Zi.includes(aa))})(),Yn=!!((qi=ys.address)!=null&&qi.trim()||(Vi=ys.city)!=null&&Vi.trim()||(si=ys.state)!=null&&si.trim()||(Yi=ys.zip_code)!=null&&Yi.trim());return mn&&On&&vn&&(me==="all"||me==="has-address"&&Yn||me==="no-address"&&!Yn)});se==="not-touched-90"?lt=lt.filter(ys=>{const mn=ys.relationshipScore.daysSinceTouch;return mn===null||mn>90}):se==="at-risk"?lt=lt.filter(ys=>ys.relationshipScore.status==="at-risk"):se==="cooling"?lt=lt.filter(ys=>ys.relationshipScore.status==="cooling"):se==="warm"?lt=lt.filter(ys=>ys.relationshipScore.status==="warm"):se==="has-deal"?lt=lt.filter(ys=>_&&_[ys.id]):se==="no-deal"?lt=lt.filter(ys=>!_||!_[ys.id]):se==="open-house"?lt=lt.filter(ys=>{var On;return(((On=ys.lead_source_ref)==null?void 0:On.name)||ys.lead_source)==="Open House"}):se==="website-active"?lt=lt.filter(ys=>h.has(ys.id)):se==="never-contacted"?lt=lt.filter(ys=>ys.relationshipScore.daysSinceTouch===null):se==="vips"?lt=lt.filter(ys=>ys.relationshipScore.score>=80):se==="missing-info"?lt=lt.filter(ys=>{var mn,On;return!((mn=ys.email)!=null&&mn.trim())&&!((On=ys.phone)!=null&&On.trim())}):se==="birthdays-soon"?lt=lt.filter(ys=>{const mn=EE(ys.birthday);return mn!==null&&mn<=30}):se==="anniversary-soon"?lt=lt.filter(ys=>{const mn=EE(ys.home_anniversary);return mn!==null&&mn<=30}):se==="in-drip"?lt=lt.filter(ys=>((f==null?void 0:f[ys.id])??0)>0):se==="not-in-drip"&&(lt=lt.filter(ys=>((f==null?void 0:f[ys.id])??0)===0));const ns=ve;if(ns.lastActive||ns.registered||ns.viewedListing||ns.savedProperty||ns.hasSavedSearch||ns.requestedShowing||ns.requestedValuation||ns.websiteActiveOnly){const ys=Date.now(),mn={today:24*60*60*1e3,"7d":7*24*60*60*1e3,"30d":30*24*60*60*1e3,"90d":90*24*60*60*1e3};lt=lt.filter(On=>{const vn=Ce.get(On.id);if(ns.lastActive==="never"){if(vn!=null&&vn.lastActiveAt)return!1}else if(ns.lastActive){const Yn=ys-mn[ns.lastActive];if(!(vn!=null&&vn.lastActiveAt)||new Date(vn.lastActiveAt).getTime()0)||ns.viewedListing==="multiple7d"&&!(vn&&vn.propertyViewCount7d>=3)||ns.savedProperty&&!(vn&&vn.savedListingCount>0)||ns.hasSavedSearch&&!(vn&&vn.activeSavedSearchCount>0)||ns.requestedShowing&&!(vn&&vn.showingRequests>0)||ns.requestedValuation&&!(vn&&vn.valuationRequests>0)||ns.websiteActiveOnly&&!h.has(On.id))})}return lt=[...lt].sort((ys,mn)=>{switch(he){case"important-dates":{const On=EE(ys.birthday),vn=EE(mn.birthday),Yn=EE(ys.home_anniversary),_r=EE(mn.home_anniversary),wr=[On,Yn].filter(xa=>xa!==null).sort((xa,Ki)=>(xa??1/0)-(Ki??1/0))[0]??1/0,Er=[vn,_r].filter(xa=>xa!==null).sort((xa,Ki)=>(xa??1/0)-(Ki??1/0))[0]??1/0;return wr-Er}case"last-touched":{const On=ys.relationshipScore.lastTouchDate,vn=mn.relationshipScore.lastTouchDate;return!On&&!vn?0:On?vn?new Date(On).getTime()-new Date(vn).getTime():1:-1}case"next-touch":{const On=ys.relationshipScore.daysSinceTouch,vn=mn.relationshipScore.daysSinceTouch;return On===null&&vn===null?0:On===null?-1:vn===null?1:vn-On}case"score":return ys.relationshipScore.score-mn.relationshipScore.score;case"date-added":{const On=ys.created_at,vn=mn.created_at;return!On&&!vn?0:On?vn?new Date(vn).getTime()-new Date(On).getTime():-1:1}case"last-name":{const On=(ys.last_name||"").toLowerCase(),vn=(mn.last_name||"").toLowerCase();if(On!==vn)return On.localeCompare(vn);const Yn=(ys.first_name||"").toLowerCase(),_r=(mn.first_name||"").toLowerCase();return Yn.localeCompare(_r)}case"name":default:{const On=`${ys.first_name||""} ${ys.last_name||""}`.toLowerCase(),vn=`${mn.first_name||""} ${mn.last_name||""}`.toLowerCase();return On.localeCompare(vn)}}}),lt},[d,z,W,w,A,se,he,_,j,h,f,me,ve,Ce,Ar]),Ts=Hn.length,Un=Math.max(1,Math.ceil(Ts/$t)),ir=Math.min(ut,Un),Tr=N.useMemo(()=>{const lt=(ir-1)*$t;return Hn.slice(lt,lt+$t)},[Hn,ir,$t]),ts=N.useRef(!1);N.useEffect(()=>{if(!ts.current){ts.current=!0;return}bt(1)},[z,W,w,A,se,he,me,ve]);const Fe=N.useCallback(()=>{at(!1),rt(lt=>lt.size>0?new Set:new Set(Tr.map(ns=>ns.id)))},[Tr]),Qe=N.useCallback(()=>{at(!0),rt(new Set(Hn.map(lt=>lt.id)))},[Hn]),ot=N.useCallback((lt,ns)=>{H(lt.search||""),ee(lt.type||"all"),oe(lt.status||"all"),ge(lt.behavior||{}),ce(ns||"name")},[]),St=()=>{Es({first_name:"",last_name:"",email:"",phone:"",address:"",city:"",state:"",zip_code:"",birthday:"",home_anniversary:"",spouse_name:"",spouse_email:"",lead_source_id:"",notes:"",tagIds:[]})},Bt=async lt=>{lt.preventDefault();const ns={...na,lead_source_id:na.lead_source_id||null};Ae?(await D.mutateAsync({id:Ae.id,...ns}),Be(null)):(await O.mutateAsync(ns),Re(!1)),St()},Vt=async lt=>{confirm("Are you sure you want to delete this contact?")&&await I.mutateAsync(lt)};return e.jsx(Cs,{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"})]}),zt&&e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsx("button",{onClick:()=>Ls("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Ds==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Contacts"}),(zt.team.contact_visibility==="full_team"||zt.team.contact_visibility==="leader_only"&&zt.role==="team_leader")&&e.jsxs("button",{onClick:()=>Ls("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Ds==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"Team"]}),zt.team.lead_pond_enabled&&e.jsxs("button",{onClick:()=>Ls("lead-pond"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${Ds==="lead-pond"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(db,{className:"h-3.5 w-3.5"}),"Lead Pond"]})]})]}),e.jsx("div",{className:"flex items-center gap-4",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(ml,{className:"h-4 w-4 mr-1"}),"Back"]})}),Ds==="team"?e.jsx(TIe,{}):Ds==="lead-pond"&&zt?e.jsx(EIe,{teamId:zt.teamId}):e.jsxs(e.Fragment,{children:[e.jsx(fGs,{contacts:d,contactDealsMap:_,websiteActiveIds:h,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"}[se]??null,onSelect:lt=>{const Vs=lt?{"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"}[lt]:"all";oe(Vs),bt(1)}}),e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"p-3 sm:p-4 bg-background",children:[e.jsxs("div",{className:"sm:hidden space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-0",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search contacts...",value:z,onChange:lt=>H(lt.target.value),className:"pl-9 h-10 rounded-xl bg-muted/40"})]}),e.jsxs(t0,{children:[e.jsx(Y$,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl relative shrink-0","aria-label":"Filters",children:[e.jsx(e4,{className:"h-4 w-4"}),(()=>{const lt=(W!=="all"?1:0)+(se!=="all"?1:0)+(me!=="all"?1:0)+w.size+Object.values(ve).filter(ns=>ns!==void 0&&ns!==!1).length;return lt>0?e.jsx("span",{className:"absolute -top-1 -right-1 h-4 min-w-[16px] px-1 rounded-full bg-primary text-primary-foreground text-[10px] font-bold flex items-center justify-center",children:lt}):null})()]})}),e.jsxs(og,{side:"bottom",className:"h-[85vh] rounded-t-2xl overflow-y-auto",children:[e.jsx(jy,{className:"text-left",children:e.jsx(Ny,{children:"Filters & Views"})}),e.jsxs("div",{className:"space-y-5 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsxs(us,{value:W,onValueChange:ee,children:[e.jsx(ls,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(hs,{placeholder:"All Types"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),y==null?void 0:y.filter(lt=>lt.active).map(lt=>e.jsx(Ze,{value:lt.id,children:lt.name},lt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Status"}),e.jsxs(us,{value:se,onValueChange:oe,children:[e.jsx(ls,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(hs,{placeholder:"All Status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"warm",children:"🟢 Warm"}),e.jsx(Ze,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ze,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ze,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ze,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ze,{value:"open-house",children:"🏠 Open House"}),p&&e.jsx(Ze,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ze,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ze,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsxs(us,{value:me,onValueChange:lt=>le(lt),children:[e.jsx(ls,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(hs,{placeholder:"All Addresses"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Addresses"}),e.jsx(Ze,{value:"has-address",children:"Has Address"}),e.jsx(Ze,{value:"no-address",children:"No Address"})]})]})]}),v&&v.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tags"}),e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-md p-0.5",children:[e.jsx("button",{onClick:()=>E("any"),className:`px-2 py-0.5 rounded text-xs font-medium ${A==="any"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"Any"}),e.jsx("button",{onClick:()=>E("all"),className:`px-2 py-0.5 rounded text-xs font-medium ${A==="all"?"bg-background shadow-sm":"text-muted-foreground"}`,children:"All"})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:v.map(lt=>{const ns=w.has(lt.id);return e.jsxs("button",{onClick:()=>{S(Vs=>{const ys=new Set(Vs);return ys.has(lt.id)?ys.delete(lt.id):ys.add(lt.id),ys})},className:`inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full text-xs border transition-colors ${ns?"bg-primary text-primary-foreground border-primary":"bg-background border-border"}`,children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:lt.color}}),lt.name]},lt.id)})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Sort by"}),e.jsxs(us,{value:he,onValueChange:ce,children:[e.jsx(ls,{className:"h-11 rounded-xl bg-muted/40",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"name",children:"Name (A-Z)"}),e.jsx(Ze,{value:"last-name",children:"Last Name (A-Z)"}),e.jsx(Ze,{value:"important-dates",children:"Important Dates"}),e.jsx(Ze,{value:"last-touched",children:"Last Touched"}),e.jsx(Ze,{value:"next-touch",children:"Next Touch Due"}),e.jsx(Ze,{value:"score",children:"Relationship Score"}),e.jsx(Ze,{value:"date-added",children:"Date Added"})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Ie(!0),children:[e.jsx(un,{className:"h-4 w-4"})," Advanced"]}),e.jsxs(B,{variant:"outline",className:"h-11 rounded-xl gap-1.5",onClick:()=>Lt(!0),children:[e.jsx(oh,{className:"h-4 w-4"})," Manage Tags"]})]}),e.jsx("div",{children:e.jsx(cZe,{currentFilters:{search:z,type:W,status:se,behavior:ve},currentSortBy:he,onApplySmartList:ot})}),e.jsx(B,{variant:"ghost",className:"w-full h-11 rounded-xl text-muted-foreground",onClick:()=>{ee("all"),oe("all"),le("all"),S(new Set),ge({})},children:"Clear all filters"})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{onClick:()=>Re(!0),className:"h-11 rounded-xl",children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add Contact"]}),e.jsxs(B,{onClick:()=>Y(!0),className:"h-11 rounded-xl bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white border-0",children:[e.jsx(Hc,{className:"h-4 w-4 mr-1.5"})," Heat Map"]})]}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full h-10 rounded-xl gap-2",children:[e.jsx(_a,{className:"h-4 w-4"})," Import & Sync"]})}),e.jsxs(gc,{align:"center",className:"w-[calc(100vw-2rem)] max-w-sm",children:[e.jsxs(Kr,{onClick:()=>Je(!0),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(Kr,{onClick:()=>it(!0),children:[e.jsx(tg,{className:"h-4 w-4 mr-2"})," Import from Phone"]}),e.jsx("div",{className:"px-1 py-1 [&_button]:w-full [&_button]:justify-start [&_button]:h-9",children:e.jsx(iZe,{})})]})]})]}),e.jsxs("div",{className:"hidden sm:flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[280px]",children:[e.jsx(gr,{className:"absolute left-3.5 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or phone...",value:z,onChange:lt=>H(lt.target.value),className:"pl-10 h-10 rounded-xl bg-muted/40 border-border focus-visible:ring-primary/20"})]}),e.jsxs("div",{className:"inline-flex items-center gap-1 p-1 bg-muted rounded-xl border border-border",children:[e.jsxs("button",{type:"button",className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-semibold rounded-lg bg-background shadow-sm text-foreground",children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"Grid"]}),e.jsxs("button",{type:"button",onClick:()=>Y(!0),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs font-medium rounded-lg text-muted-foreground hover:text-foreground hover:bg-background/60 transition-colors",children:[e.jsx(Hc,{className:"h-3.5 w-3.5 text-orange-600"}),"Heat Map"]})]}),e.jsxs("div",{className:"inline-flex rounded-xl overflow-hidden shadow-sm",children:[e.jsxs(B,{onClick:()=>Re(!0),className:"rounded-none rounded-l-xl h-10 px-4 gap-2 shadow-none",children:[e.jsx(Is,{className:"h-4 w-4"}),"Add Contact"]}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{className:"rounded-none rounded-r-xl h-10 px-2.5 border-l border-primary-foreground/20 shadow-none","aria-label":"More import options",children:e.jsx(ga,{className:"h-4 w-4 rotate-90"})})}),e.jsxs(gc,{align:"end",children:[e.jsxs(Kr,{onClick:()=>Je(!0),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Import CSV"]}),e.jsxs(Kr,{onClick:()=>it(!0),children:[e.jsx(tg,{className:"h-4 w-4 mr-2"}),"Import from Phone"]})]})]})]}),e.jsx(iZe,{}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"icon",className:"h-10 w-10 rounded-xl",title:"Sort contacts",children:e.jsx(ah,{className:"h-4 w-4"})})}),e.jsxs(el,{align:"end",className:"w-56 p-2",children:[e.jsx("div",{className:"text-xs font-semibold text-muted-foreground px-2 py-1.5",children:"Sort by"}),[{v:"name",l:"Name (A-Z)"},{v:"last-name",l:"Last Name (A-Z)"},{v:"important-dates",l:"Important Dates"},{v:"last-touched",l:"Last Touched"},{v:"next-touch",l:"Next Touch Due"},{v:"score",l:"Relationship Score"},{v:"date-added",l:"Date Added"}].map(lt=>e.jsx("button",{onClick:()=>ce(lt.v),className:`w-full text-left px-2 py-1.5 rounded-md text-sm hover:bg-accent transition-colors ${he===lt.v?"bg-accent font-medium text-primary":""}`,children:lt.l},lt.v))]})]})]})]}),e.jsxs("div",{className:"hidden sm:flex px-3 sm:px-4 py-3 bg-muted/40 border-t flex-wrap items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(us,{value:W,onValueChange:ee,children:[e.jsx(ls,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(hs,{placeholder:"All Types"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),y==null?void 0:y.filter(lt=>lt.active).map(lt=>e.jsx(Ze,{value:lt.id,children:lt.name},lt.id))]})]}),e.jsxs(us,{value:se,onValueChange:oe,children:[e.jsx(ls,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(hs,{placeholder:"All Status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"warm",children:"🟢 Warm"}),e.jsx(Ze,{value:"cooling",children:"🟡 Cooling Off"}),e.jsx(Ze,{value:"at-risk",children:"🔴 At Risk"}),e.jsx(Ze,{value:"has-deal",children:"📋 Has Deal"}),e.jsx(Ze,{value:"no-deal",children:"📭 No Deal"}),e.jsx(Ze,{value:"open-house",children:"🏠 Open House"}),p&&e.jsx(Ze,{value:"website-active",children:"🌐 Website Active"}),e.jsx(Ze,{value:"in-drip",children:"🌱 In Drip Campaign"}),e.jsx(Ze,{value:"not-in-drip",children:"🚫 Not In Drip"})]})]}),e.jsxs(us,{value:me,onValueChange:lt=>le(lt),children:[e.jsx(ls,{className:"h-8 text-xs rounded-lg bg-background w-auto min-w-[130px] gap-2",children:e.jsx(hs,{placeholder:"All Addresses"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Addresses"}),e.jsx(Ze,{value:"has-address",children:"Has Address"}),e.jsx(Ze,{value:"no-address",children:"No Address"})]})]}),v&&v.length>0&&e.jsxs("div",{className:"inline-flex items-center bg-background border rounded-lg overflow-hidden h-8",children:[e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs("button",{className:"pl-2.5 pr-2 h-full text-xs font-medium text-muted-foreground hover:text-foreground inline-flex items-center gap-1.5",children:[e.jsx(oh,{className:"h-3.5 w-3.5"}),w.size===0?"Filter by Tags":`${w.size} tag${w.size>1?"s":""}`]})}),e.jsx(el,{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:()=>E("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:()=>E("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:v.map(lt=>{const ns=w.has(lt.id);return e.jsxs("button",{onClick:()=>{S(Vs=>{const ys=new Set(Vs);return ys.has(lt.id)?ys.delete(lt.id):ys.add(lt.id),ys})},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(hi,{checked:ns,className:"pointer-events-none"}),e.jsx("div",{className:"h-2.5 w-2.5 rounded-full shrink-0",style:{backgroundColor:lt.color}}),e.jsx("span",{className:"flex-1 text-left truncate",children:lt.name})]},lt.id)})}),w.size>0&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>S(new Set),children:"Clear tags"})]})})]}),e.jsx("div",{className:"w-px h-4 bg-border"}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx("button",{className:"px-2 h-full text-muted-foreground hover:text-primary transition-colors",title:"Manage tags & lead sources",children:e.jsx(Ko,{className:"h-3.5 w-3.5"})})}),e.jsxs(gc,{align:"end",children:[e.jsxs(Kr,{onClick:()=>Lt(!0),children:[e.jsx(oh,{className:"h-4 w-4 mr-2"}),"Manage Tags"]}),e.jsxs(Kr,{onClick:()=>gt(!0),children:[e.jsx(db,{className:"h-4 w-4 mr-2"}),"Manage Lead Sources"]})]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(cZe,{currentFilters:{search:z,type:W,status:se,behavior:ve},currentSortBy:he,onApplySmartList:ot}),e.jsx("div",{className:"h-5 w-px bg-border"}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 h-8 rounded-lg border-[#2a4c64]/20 text-[#2a4c64] hover:bg-[#2a4c64]/5 hover:text-[#2a4c64]",onClick:()=>Ie(!0),children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"Advanced Filters",Object.values(ve).filter(lt=>lt!==void 0&<!==!1).length>0&&e.jsx(Ue,{variant:"secondary",className:"h-5 px-1.5 text-[10px]",children:Object.values(ve).filter(lt=>lt!==void 0&<!==!1).length})]})]})]}),Object.values(ve).some(lt=>lt!==void 0&<!==!1)&&e.jsx("div",{className:"px-3 sm:px-4 py-3 border-t bg-background",children:e.jsx(hGs,{behavior:ve,onRemove:lt=>ge(ns=>{const Vs={...ns};return delete Vs[lt],Vs}),onClearAll:()=>ge({})})})]}),e.jsx(uGs,{open:Te,onOpenChange:Ie,hasLeadSite:Me||p,behavior:ve,onApply:ge,selectedType:W,onSelectedTypeChange:ee,relationshipTypes:y}),e.jsx(cGs,{selectedIds:Ge,contacts:Hn,onClearSelection:()=>{rt(new Set),at(!1)},showLeadPondAction:Xt,onSendToLeadPond:Qn,showTransferAction:Qs,onTransfer:xn}),Ge.size>0&&Ge.size===Tr.length&&!tt&&Ts>$t&&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 ",Tr.length," contacts on this page are selected."]}),e.jsxs(B,{variant:"link",size:"sm",className:"h-auto p-0 font-semibold",onClick:Qe,children:["Select all ",Ts.toLocaleString()," matching contacts"]})]}),tt&&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 ",Ts.toLocaleString()," matching contacts are selected.",e.jsx(B,{variant:"link",size:"sm",className:"h-auto p-0",onClick:()=>{rt(new Set),at(!1)},children:"Clear selection"})]}),Ts>$t&&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 ",(ir-1)*$t+1,"–",Math.min(ir*$t,Ts)," of ",Ts.toLocaleString()," contacts"]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:ir<=1,onClick:()=>bt(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:ir<=1,onClick:()=>bt(lt=>lt-1),children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",ir," of ",Un]}),e.jsx(B,{variant:"outline",size:"sm",disabled:ir>=Un,onClick:()=>bt(lt=>lt+1),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:ir>=Un,onClick:()=>bt(Un),children:"Last"})]})]}),a?e.jsx("div",{className:"space-y-3",children:u?e.jsx(fe,{className:"p-6 text-center text-muted-foreground",children:"Loading contacts..."}):Hn.length===0?e.jsx(fe,{className:"p-6 text-center text-muted-foreground",children:z||W!=="all"||se!=="all"||me!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"}):Tr.map(lt=>{var Vs,ys,mn;const{relationshipScore:ns}=lt;return e.jsx(fe,{className:"cursor-pointer hover:bg-accent/50 transition-colors",onClick:()=>{const On=new URLSearchParams;z&&On.set("search",z),W!=="all"&&On.set("type",W),se!=="all"&&On.set("filter",se),w.size>0&&(On.set("tags",Array.from(w).join(",")),On.set("tagMode",A));const vn=On.toString();s(`/mission-control/contacts/${lt.id}${vn?`?${vn}`:""}`)},children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsxs("h3",{className:"font-semibold text-base truncate",children:[lt.first_name," ",lt.last_name]}),e.jsx(pZe,{count:(f==null?void 0:f[lt.id])??0}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground shrink-0 ml-auto"})]}),e.jsxs("div",{className:"space-y-1 text-sm mb-3",children:[lt.email&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Gs,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{className:"truncate",children:lt.email})]}),lt.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Cr,{className:"h-3.5 w-3.5 shrink-0"}),e.jsx("span",{children:lt.phone})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1 mb-2",children:[e.jsx(yz,{score:ns,size:"sm"}),e.jsx(L5e,{contact:lt}),(((Vs=lt.lead_source_ref)==null?void 0:Vs.name)||lt.lead_source)&&e.jsx(Ue,{variant:"outline",className:"text-xs gap-1 border-primary/30 text-primary",children:((ys=lt.lead_source_ref)==null?void 0:ys.name)||lt.lead_source}),(mn=lt.tags)==null?void 0:mn.map(On=>{var vn;return e.jsx(Ue,{variant:"secondary",className:"text-xs",children:(vn=On.relationship_type)==null?void 0:vn.name},On.id)}),e.jsx(fZe,{contactId:lt.id,tags:j==null?void 0:j.filter(On=>On.contact_id===lt.id)}),e.jsx(mZe,{deal:_==null?void 0:_[lt.id]})]}),e.jsx(hZe,{birthday:lt.birthday,homeAnniversary:lt.home_anniversary,weddingAnniversary:lt.wedding_anniversary,className:"mb-2",contactId:lt.id,contactName:`${lt.first_name}${lt.last_name?" "+lt.last_name:""}`,contactAddress:[lt.address,lt.city,lt.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[ns.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),Ss(new Date(ns.lastTouchDate),"MMM d")]}):e.jsx("span",{className:"italic",children:"Never contacted"}),lt.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(Ll(lt.birthday),"MMM d")]}),lt.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Or,{className:"h-3 w-3"}),Ss(Ll(lt.home_anniversary),"MMM d")]}),lt.created_at&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Is,{className:"h-3 w-3"}),"Added ",Ss(new Date(lt.created_at),"MMM d, yyyy")]})]})]}),e.jsx("div",{className:"ml-2",onClick:On=>On.stopPropagation(),children:e.jsx(lZe,{contact:lt,onEdit:Be,onDelete:Vt,onSnooze:(On,vn)=>{He(On),Ke(vn)},showLeadPondAction:Xt,onSendToLeadPond:Pn,showTransferAction:Qs,onTransfer:er})})]})})},lt.id)})}):e.jsx(fe,{children:e.jsx(Ee,{className:"p-0 overflow-x-auto",children:e.jsxs(la,{className:"min-w-[800px]",children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(hi,{checked:Tr.length>0&&Tr.every(lt=>Ge.has(lt.id)),onCheckedChange:()=>Fe()})}),e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Score"}),e.jsx(Tt,{children:"Contact Info"}),e.jsx(Tt,{children:"Types / Pipeline"}),e.jsx(Tt,{children:"Last Contact"}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>ce(he==="date-added"?"name":"date-added"),children:e.jsxs("div",{className:"flex items-center gap-1",children:["Date Added",he==="date-added"&&e.jsx(ah,{className:"h-3 w-3"})]})}),e.jsx(Tt,{children:"Important Dates"}),e.jsx(Tt,{className:"w-[50px]",children:"Actions"})]})}),e.jsx(da,{children:u?e.jsx(Hs,{children:e.jsx(ht,{colSpan:10,className:"text-center py-8",children:"Loading contacts..."})}):Hn.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:10,className:"text-center py-8 text-muted-foreground",children:z||W!=="all"||se!=="all"||me!=="all"?"No contacts match your search":"No contacts yet. Add your first contact!"})}):Tr.map(lt=>{var ys,mn,On;const{relationshipScore:ns}=lt,Vs=_==null?void 0:_[lt.id];return e.jsxs(Hs,{className:`cursor-pointer hover:bg-accent/50 ${Ge.has(lt.id)?"bg-accent/30":""}`,onClick:()=>{const vn=new URLSearchParams;z&&vn.set("search",z),W!=="all"&&vn.set("type",W),se!=="all"&&vn.set("status",se),w.size>0&&(vn.set("tags",Array.from(w).join(",")),vn.set("tagMode",A));const Yn=vn.toString();s(`/mission-control/contacts/${lt.id}${Yn?`?${Yn}`:""}`)},children:[e.jsx(ht,{onClick:vn=>vn.stopPropagation(),children:e.jsx(hi,{checked:Ge.has(lt.id),onCheckedChange:()=>sa(lt.id)})}),e.jsx(ht,{className:"font-medium",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("span",{children:[lt.first_name," ",lt.last_name]}),e.jsx(pZe,{count:(f==null?void 0:f[lt.id])??0})]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx(yz,{score:ns,size:"sm"}),e.jsx(L5e,{contact:lt})]})}),e.jsx(ht,{children:e.jsx(yz,{score:ns,size:"sm",showScore:!0})}),e.jsx(ht,{children:e.jsxs("div",{className:"space-y-1 text-sm",children:[lt.email&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Gs,{className:"h-3 w-3"}),lt.email]}),lt.phone&&e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(Cr,{className:"h-3 w-3"}),lt.phone]})]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex flex-wrap gap-1",children:[(((ys=lt.lead_source_ref)==null?void 0:ys.name)||lt.lead_source)&&e.jsx(Ue,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((mn=lt.lead_source_ref)==null?void 0:mn.name)||lt.lead_source}),(On=lt.tags)==null?void 0:On.map(vn=>{var Yn;return e.jsx(Ue,{variant:"secondary",className:"text-xs",children:(Yn=vn.relationship_type)==null?void 0:Yn.name},vn.id)}),e.jsx(fZe,{contactId:lt.id,tags:j==null?void 0:j.filter(vn=>vn.contact_id===lt.id)}),e.jsx(mZe,{deal:Vs})]})}),e.jsx(ht,{children:e.jsx("div",{className:"text-sm",children:ns.lastTouchDate?e.jsxs("div",{className:"flex items-center gap-1 text-muted-foreground",children:[e.jsx(pr,{className:"h-3 w-3"}),Ss(new Date(ns.lastTouchDate),"MMM d, yyyy")]}):e.jsx("span",{className:"text-muted-foreground text-xs italic",children:"Never contacted"})})}),e.jsx(ht,{children:e.jsx("span",{className:"text-sm text-muted-foreground",children:lt.created_at?Ss(new Date(lt.created_at),"MMM d, yyyy"):"—"})}),e.jsx(ht,{children:e.jsxs("div",{className:"space-y-1",children:[e.jsx(hZe,{birthday:lt.birthday,homeAnniversary:lt.home_anniversary,weddingAnniversary:lt.wedding_anniversary,contactId:lt.id,contactName:`${lt.first_name}${lt.last_name?" "+lt.last_name:""}`,contactAddress:[lt.address,lt.city,lt.state].filter(Boolean).join(", ")}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[lt.birthday&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(Ll(lt.birthday),"MMM d")]}),lt.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Or,{className:"h-3 w-3"}),Ss(Ll(lt.home_anniversary),"MMM d")]})]})]})}),e.jsx(ht,{children:e.jsx(lZe,{contact:lt,onEdit:Be,onDelete:Vt,onSnooze:(vn,Yn)=>{He(vn),Ke(Yn)},showLeadPondAction:Xt,onSendToLeadPond:Pn,showTransferAction:Qs,onTransfer:er})})]},lt.id)})})]})})}),Ts>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 ",(ir-1)*$t+1,"–",Math.min(ir*$t,Ts)," of ",Ts.toLocaleString()," contacts"]}),e.jsxs(us,{value:String($t),onValueChange:lt=>{Yt(Number(lt)),bt(1)},children:[e.jsx(ls,{className:"w-[80px] h-8",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"50",children:"50"}),e.jsx(Ze,{value:"100",children:"100"}),e.jsx(Ze,{value:"250",children:"250"})]})]}),e.jsx("span",{className:"text-xs",children:"per page"})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"sm",disabled:ir<=1,onClick:()=>bt(1),children:"First"}),e.jsx(B,{variant:"outline",size:"sm",disabled:ir<=1,onClick:()=>bt(lt=>lt-1),children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsxs("span",{className:"px-3 text-sm font-medium",children:["Page ",ir," of ",Un]}),e.jsx(B,{variant:"outline",size:"sm",disabled:ir>=Un,onClick:()=>bt(lt=>lt+1),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"sm",disabled:ir>=Un,onClick:()=>bt(Un),children:"Last"})]})]}),e.jsx(_s,{open:Pe||!!Ae,onOpenChange:lt=>{lt||(Re(!1),Be(null),St())},children:e.jsxs(bs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:Ae?"Edit Contact":"Add Contact"})}),e.jsxs("form",{onSubmit:Bt,className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"first_name",children:"First Name *"}),e.jsx(ye,{id:"first_name",value:na.first_name,onChange:lt=>Es({...na,first_name:lt.target.value}),required:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ye,{id:"last_name",value:na.last_name,onChange:lt=>Es({...na,last_name:lt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:na.email,onChange:lt=>Es({...na,email:lt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"phone",children:"Phone"}),e.jsx(ye,{id:"phone",value:na.phone,onChange:lt=>Es({...na,phone:lt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"address",children:"Address"}),e.jsx(ye,{id:"address",value:na.address,onChange:lt=>Es({...na,address:lt.target.value}),placeholder:"Street address"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:na.city,onChange:lt=>Es({...na,city:lt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:na.state,onChange:lt=>Es({...na,state:lt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"zip_code",children:"Zip"}),e.jsx(ye,{id:"zip_code",value:na.zip_code,onChange:lt=>Es({...na,zip_code:lt.target.value})})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"birthday",children:"Birthday"}),e.jsx(ye,{id:"birthday",type:"date",value:na.birthday,onChange:lt=>Es({...na,birthday:lt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ye,{id:"home_anniversary",type:"date",value:na.home_anniversary,onChange:lt=>Es({...na,home_anniversary:lt.target.value})})]})]}),Ae&&e.jsx(D5e,{contactId:Ae.id,currentSpouseContactId:(Ae==null?void 0:Ae.spouse_contact_id)||null,currentSpouseName:(Ae==null?void 0:Ae.spouse_name)||null,currentSpouseEmail:(Ae==null?void 0:Ae.spouse_email)||null,onLink:lt=>F.mutate({contactId:Ae.id,spouseContactId:lt}),onUnlink:()=>F.mutate({contactId:Ae.id,spouseContactId:null}),isEditing:!0}),e.jsx(g_t,{value:na.lead_source_id,onChange:lt=>Es({...na,lead_source_id:lt})}),e.jsxs("div",{children:[e.jsx(ne,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:y==null?void 0:y.filter(lt=>lt.active).map(lt=>e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(hi,{checked:na.tagIds.includes(lt.id),onCheckedChange:ns=>{Es(ns?{...na,tagIds:[...na.tagIds,lt.id]}:{...na,tagIds:na.tagIds.filter(Vs=>Vs!==lt.id)})}}),e.jsx("span",{className:"text-sm",children:lt.name})]},lt.id))})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"notes",children:"Notes"}),e.jsx(Ms,{id:"notes",value:na.notes,onChange:lt=>Es({...na,notes:lt.target.value}),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>{Re(!1),Be(null),St()},children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:O.isPending||D.isPending,children:[Ae?"Update":"Create"," Contact"]})]})]})]})}),e.jsx(EHs,{open:we,onOpenChange:Je,relationshipTypes:(y==null?void 0:y.filter(lt=>lt.active))||[],onSuccess:()=>{Je(!1)}}),e.jsx(IHs,{open:ke,onOpenChange:it,onComplete:()=>it(!1)}),e.jsx(m1e,{open:!!je,onOpenChange:lt=>{lt||He(null)},contactId:je||"",contactName:$e}),e.jsx(jGs,{open:xs,onOpenChange:Lt}),e.jsx(NGs,{open:Jt,onOpenChange:gt}),e.jsx(vGs,{open:Z,onOpenChange:Y,contacts:d||[],onCitySelect:lt=>{H(lt),bt(1)}}),e.jsx(D0t,{open:an,onOpenChange:tn,contactIds:ks,contactNames:ks.map(lt=>{const ns=Hn.find(Vs=>Vs.id===lt);return ns?`${ns.first_name} ${ns.last_name||""}`.trim():""}),onComplete:()=>{$s([]),rt(new Set),at(!1)}})]})]})})}const SGs="9a88a47c-cb2a-4401-a2b5-111a76b19f9d";function CGs({open:s,onOpenChange:t,contact:n}){var Z;const{user:r}=vs(),a=Ln(),i=Kt(),{intakePage:l,isLoading:o}=p1e(),{isGmailConnected:c,gmailEmail:d}=Dh(),u=Tye(),{data:h}=dt({queryKey:["profile-for-invite",r==null?void 0:r.id],enabled:!!(r!=null&&r.id)&&s,queryFn:async()=>{const{data:Y}=await q.from("profiles").select("name, email, avatar_url").eq("id",r.id).maybeSingle();return Y}}),p=(h==null?void 0:h.name)||((Z=r==null?void 0:r.email)==null?void 0:Z.split("@")[0])||"Your Agent",f=p.split(" ")[0],y=l?`https://contacts.relevelup.com/${l.slug}`:"",_=N.useMemo(()=>`Hi ${n.first_name}, I'm updating my contact list and want to make sure I have your latest info — the best phone, email, address, and a couple of dates I love to remember (like your birthday and home anniversary). It only takes about a minute, and it helps me stay in touch the right way. Thanks so much!`,[n.first_name]),[v,j]=N.useState("gmail"),[w,S]=N.useState(""),[A,E]=N.useState(""),[O,D]=N.useState(!1);N.useEffect(()=>{s&&(S(`Quick favor, ${n.first_name} — can you update your info?`),E(_),j(c?"gmail":"system"))},[s,_,n.first_name,c]);const I=N.useMemo(()=>A.split(/\n\n+/).map(Y=>`

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

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

A note from ${p}

${I}

Update Your Info

Takes about a minute — promise

Share My Info →

${y}

Sent with care by ${p}

Powered by ReLevelUp

`,z=async()=>{if(!l){ae.error("Set up your Connect Page first",{action:{label:"Set Up",onClick:()=>a("/mission-control/connect-page")}});return}if(!w.trim()||!A.trim()){ae.error("Subject and message are required");return}D(!0);const Y=F();try{if(v==="gmail"&&c){const{data:W,error:ee}=await q.functions.invoke("gmail-send",{body:{to:n.email,subject:w,body:Y,contactId:n.id}});if(ee)throw ee;if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Failed to send")}else{const{data:W,error:ee}=await q.functions.invoke("send-connect-invite",{body:{contactEmail:n.email,subject:w,htmlBody:Y,replyToEmail:(h==null?void 0:h.email)||(r==null?void 0:r.email),agentName:p}});if(ee)throw ee;if(!(W!=null&&W.success))throw new Error((W==null?void 0:W.error)||"Failed to send")}try{await u.mutateAsync({contactId:n.id,actionTypeId:SGs,notes:`Sent Connect Page invite — Subject: "${w}"`})}catch(W){console.warn("Failed to log activity:",W)}i.invalidateQueries({queryKey:["contact-touch-logs"]}),ae.success("Connect Page invite sent!"),t(!1)}catch(W){console.error("Send error:",W),ae.error(W instanceof Error?W.message:"Failed to send invite")}finally{D(!1)}},H=F();return e.jsx(_s,{open:s,onOpenChange:Y=>!O&&t(Y),children:e.jsxs(bs,{className:"sm:max-w-[720px] max-h-[92vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Send Connect Page Invite"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Ask ",e.jsxs("span",{className:"font-medium",children:[n.first_name," ",n.last_name||""]})," to share their latest contact info — takes them about a minute."]})]}),o?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-primary"})}):l?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Send From"}),e.jsx(Fr,{value:v,onValueChange:Y=>j(Y),className:"mt-1.5",children:e.jsxs(Rr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"gmail",disabled:!c,children:[e.jsx(Gs,{className:"h-3.5 w-3.5 mr-1.5"}),c?`Gmail (${d})`:"Gmail (not connected)"]}),e.jsxs(Zt,{value:"system",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"}),"System Email"]})]})}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1.5",children:v==="gmail"?"Replies go directly to your Gmail inbox.":`Sent from notifications@dashboard.relevelup.com — replies go to ${(h==null?void 0:h.email)||(r==null?void 0:r.email)||"your account email"}.`})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"invite-subject",children:"Subject"}),e.jsx(ye,{id:"invite-subject",value:w,onChange:Y=>S(Y.target.value),className:"mt-1.5"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"invite-message",children:"Personal Message"}),e.jsx(Ms,{id:"invite-message",value:A,onChange:Y=>E(Y.target.value),rows:6,className:"mt-1.5 resize-none"}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"The Connect Page button is added below your message automatically."})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1.5",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Preview"}),e.jsxs("a",{href:y,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-primary hover:underline flex items-center gap-1",children:["Open Connect Page ",e.jsx(tr,{className:"h-3 w-3"})]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden bg-muted/30",children:e.jsx("iframe",{srcDoc:H,title:"Email preview",sandbox:"",className:"w-full h-[420px] bg-background"})})]}),e.jsxs("div",{className:"flex items-center justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:O,children:"Cancel"}),e.jsx(B,{onClick:z,disabled:O,children:O?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-1.5 animate-spin"})," Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-1.5"})," Send Invite"]})})]})]}):e.jsxs("div",{className:"space-y-4 py-6 text-center",children:[e.jsx(Bi,{className:"h-10 w-10 text-amber-500 mx-auto"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"You haven't set up a Connect Page yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Create yours in one click — it only takes a moment."})]}),e.jsxs(B,{onClick:()=>a("/mission-control/connect-page"),children:[e.jsx(Tl,{className:"h-4 w-4 mr-1"})," Set Up Connect Page"]})]})]})})}function TGs(){const{user:s}=vs();return dt({queryKey:["cmas",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("agent_id",s.id).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function EGs(s){return dt({queryKey:["cma",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cmas").select("*").eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function AGs(s){return dt({queryKey:["cma-comps",s],queryFn:async()=>{const{data:t,error:n}=await q.from("cma_comps").select("*").eq("cma_id",s).order("position",{ascending:!0});if(n)throw n;return t||[]},enabled:!!s})}function y_t(){const s=Kt(),{user:t}=vs(),{leadSite:n}=Ap();return yt({mutationFn:async r=>{const{data:a,error:i}=await q.from("cmas").insert({agent_id:t.id,lead_site_id:(n==null?void 0:n.id)??null,contact_id:r.contactId??null,deal_id:r.dealId??null,buyer_mode:!!r.buyerMode,title:r.title??r.subject.address,subject:r.subject,settings:{sqftPct:.2,monthsBack:6,statuses:["Active","Pending","Closed"]}}).select("*").single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function MGs(){const s=Kt();return yt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("cmas").update(n).eq("id",t).select("*").single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["cma",n.id]}),s.invalidateQueries({queryKey:["cmas"]})}})}function IGs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("cmas").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["cmas"]})})}function PGs(){const{leadSite:s}=Ap();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-subject-lookup",{body:{...t,leadSiteId:(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function LGs(){const{leadSite:s}=Ap();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("cma-comp-search",{body:{...t,leadSiteId:t.leadSiteId??(s==null?void 0:s.id)??null}});if(r)throw r;return n}})}function DGs(){const s=Kt();return yt({mutationFn:async({cmaId:t,comps:n})=>{if(await q.from("cma_comps").delete().eq("cma_id",t),!n.length)return;const r=n.map((i,l)=>({cma_id:t,mls_number:i.mlsNumber??null,source_provider:i.source_provider??null,selected:i.selected!==!1,manual:!!i.manual,score:i.score??null,position:l,snapshot:i})),{error:a}=await q.from("cma_comps").insert(r);if(a)throw a},onSuccess:(t,n)=>s.invalidateQueries({queryKey:["cma-comps",n.cmaId]})})}function gZe(s,t){const n=t.filter(h=>{var p,f;return h.selected!==!1&&(((p=h.snapshot)==null?void 0:p.sqft)||h.sqft)&&(((f=h.snapshot)==null?void 0:f.price)||h.price)});if(!n.length||!s.sqft)return{low:null,likely:null,high:null,ppsf:null};const r=n.map(h=>{const p=h.snapshot||h;return(p.soldPrice||p.price)/p.sqft}).filter(h=>Number.isFinite(h)&&h>0).sort((h,p)=>h-p);if(!r.length)return{low:null,likely:null,high:null,ppsf:null};const a=r[Math.floor(r.length/2)],i=r.reduce((h,p)=>h+p,0)/r.length,l=r.reduce((h,p)=>h+(p-i)**2,0)/r.length,o=Math.sqrt(l),c=Math.round(a*s.sqft),d=Math.round((a-o)*s.sqft),u=Math.round((a+o)*s.sqft);return{low:d,likely:c,high:u,ppsf:Math.round(a)}}function RGs(s){return dt({queryKey:["contact-video-replies",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("video_replies").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url) `).eq("contact_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function OGs(s){return dt({queryKey:["client-portal",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("deal_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function QPe(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("client_portals").insert({deal_id:n.deal_id,owner_user_id:s,slug:"",is_enabled:n.is_enabled??!0,visibility:n.visibility||"private",require_onboarding:n.require_onboarding??!0,allow_spouse:n.allow_spouse??!1,client_name:n.client_name||null,client_email:n.client_email||null,client_phone:n.client_phone||null,invite_method:n.invite_method||"email"}).select().single();if(a)throw a;return r},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["client-portal",r.deal_id]})}})}function xR(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("client_portals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function v_t(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:new Date().toISOString(),is_enabled:!1}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function b_t(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("client_portals").update({archived_at:null}).eq("id",t).select().single();if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t.deal_id]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function __t(){const s=Kt();return yt({mutationFn:async({id:t,dealId:n})=>{await q.from("portal_updates").delete().eq("portal_id",t);const{error:r}=await q.from("client_portals").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["client-portal",t]}),s.invalidateQueries({queryKey:["all-client-portals"]})}})}function FGs(s){return dt({queryKey:["portal-updates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_updates").select("*").eq("portal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function w_t(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("portal_updates").insert({portal_id:t.portal_id,title:t.title,content:t.content||null,video_url:t.video_url||null,is_stage_change:t.is_stage_change||!1}).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["portal-updates",n.portal_id]})}})}function zGs(){const s=wa();return dt({queryKey:["portal-custom-questions",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_custom_questions").select("*").eq("owner_user_id",s).eq("is_active",!0).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function BGs(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("portal_custom_questions").insert({owner_user_id:s,question_text:n.question_text,field_type:n.field_type,options:n.options||[],is_required:n.is_required||!1,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function $Gs(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_custom_questions").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function UGs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("portal_custom_questions").update({is_active:!1}).eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-custom-questions"]})}})}function kw(s){const t=window.location.hostname;return t==="localhost"||t.includes("lovable.app")?`${window.location.origin}/portal/${s}`:`https://clients.relevelup.com/${s}`}function qGs({contactId:s}){const t=Ln(),n=Kt(),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(null),_=xR(),v=w_t(),{data:j,isLoading:w}=dt({queryKey:["contact-portals",s],queryFn:async()=>{const{data:I,error:F}=await q.from("deal_pipeline").select("id, deal_name, deal_type").eq("contact_id",s);if(F)throw F;if(!I||I.length===0)return[];const z=I.map(Y=>Y.id),{data:H,error:Z}=await q.from("client_portals").select("*").in("deal_id",z).is("archived_at",null);if(Z)throw Z;return(H||[]).map(Y=>({...Y,deal:I.find(W=>W.id===Y.deal_id)}))},enabled:!!s}),S=(j==null?void 0:j.map(I=>I.id))||[],{data:A}=dt({queryKey:["contact-portal-updates",S],queryFn:async()=>{if(S.length===0)return{};const{data:I,error:F}=await q.from("portal_updates").select("*").in("portal_id",S).order("created_at",{ascending:!1});if(F)throw F;const z={};return(I||[]).forEach(H=>{z[H.portal_id]||(z[H.portal_id]=H)}),z},enabled:S.length>0}),E=I=>{navigator.clipboard.writeText(kw(I)),a(I),ae.success("Portal link copied!"),setTimeout(()=>a(null),2e3)},O=async I=>{d.trim()&&(await v.mutateAsync({portal_id:I,title:d,content:h||void 0}),c(!1),u(""),p(""),n.invalidateQueries({queryKey:["contact-portal-updates"]}),ae.success("Portal update posted!"))},D=async()=>{f&&(await _.mutateAsync({id:f.id,welcome_message:f.welcome_message,next_step_text:f.next_step_text,is_enabled:f.is_enabled,show_post_close_tips:f.show_post_close_tips,review_url:f.review_url}),l(!1),y(null),n.invalidateQueries({queryKey:["contact-portals",s]}),ae.success("Portal settings updated!"))};return w||!j||j.length===0?null:e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(lc,{className:"h-4 w-4"}),"Client Portal"]})}),e.jsx(Ee,{className:"space-y-3",children:j.map(I=>{var Z,Y,W;const F=((Z=I.stage_mapping)==null?void 0:Z.length)>0?I.stage_mapping:xye(((Y=I.deal)==null?void 0:Y.deal_type)||"buyer"),z=F==null?void 0:F[I.current_stage_index??0],H=A==null?void 0:A[I.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:((W=I.deal)==null?void 0:W.deal_name)||"Portal"}),z&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Stage: ",z.label||z.name]})]}),e.jsx(Ue,{variant:I.is_enabled?"default":"secondary",className:"text-[10px] flex-shrink-0",children:I.is_enabled?"Active":"Disabled"})]}),H&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-2",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:H.title}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Ss(new Date(H.created_at),"MMM d, yyyy")})]}),e.jsxs("div",{className:"flex flex-wrap gap-1.5",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>E(I.slug),children:[r===I.slug?e.jsx(Lr,{className:"h-3 w-3 mr-1"}):e.jsx(Zr,{className:"h-3 w-3 mr-1"}),"Copy Link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>window.open(kw(I.slug),"_blank"),children:[e.jsx(tr,{className:"h-3 w-3 mr-1"}),"View"]}),e.jsxs(_s,{open:o,onOpenChange:c,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>c(!0),children:[e.jsx(Ai,{className:"h-3 w-3 mr-1"}),"Post Update"]})}),e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:d,onChange:ee=>u(ee.target.value),placeholder:"e.g. Inspection completed!"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Details (optional)"}),e.jsx(Ms,{value:h,onChange:ee=>p(ee.target.value),placeholder:"Add more details...",rows:3})]}),e.jsxs(B,{onClick:()=>O(I.id),disabled:!d.trim()||v.isPending,className:"w-full",children:[e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Post Update"]})]})]})]}),e.jsxs(_s,{open:i,onOpenChange:l,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>{y({...I}),l(!0)},children:[e.jsx(Ko,{className:"h-3 w-3 mr-1"}),"Settings"]})}),e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Portal Settings"})}),f&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Portal Enabled"}),e.jsx(jn,{checked:f.is_enabled,onCheckedChange:ee=>y({...f,is_enabled:ee})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Welcome Message"}),e.jsx(Ms,{value:f.welcome_message||"",onChange:ee=>y({...f,welcome_message:ee.target.value}),placeholder:"Welcome to your home journey!",rows:2})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Next Step"}),e.jsx(ye,{value:f.next_step_text||"",onChange:ee=>y({...f,next_step_text:ee.target.value}),placeholder:"What your client should do next..."})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Review URL"}),e.jsx(ye,{value:f.review_url||"",onChange:ee=>y({...f,review_url:ee.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Show Post-Close Tips"}),e.jsx(jn,{checked:f.show_post_close_tips,onCheckedChange:ee=>y({...f,show_post_close_tips:ee})})]}),e.jsx(al,{}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:D,disabled:_.isPending,className:"flex-1",children:"Save Settings"}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/pipeline?deal=${I.deal_id}`),children:[e.jsx(Oa,{className:"h-4 w-4 mr-1"}),"Full Settings"]})]})]})]})]})]}),j.length>1&&e.jsx(al,{})]},I.id)})})]})}function VGs({contactId:s}){const{data:t}=dt({queryKey:["agent-lead-sites-slugs"],queryFn:async()=>{const{data:l,error:o}=await q.from("lead_sites").select("id, subdomain_slug").eq("is_active",!0);if(o)throw o;return new Map((l||[]).map(c=>[c.id,c.subdomain_slug]))},staleTime:6e5}),n=t&&t.size>0,{data:r,isLoading:a}=dt({queryKey:["contact-property-views",s],queryFn:async()=>{const{data:l,error:o}=await q.rpc("get_contact_property_views",{p_contact_id:s});if(o)throw o;return l||[]},enabled:!!s&&!!n});if(!n||a||!r||r.length===0)return null;const i=l=>{const o=t==null?void 0:t.get(l.lead_site_id);return o?`https://${o}.thelocalmove.com/listing/${l.mls_number}`:null};return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{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(Sr,{className:"h-4 w-4 text-primary"})}),"Property Activity",e.jsxs(Ue,{variant:"secondary",className:"text-xs ml-auto",children:[r.length," ",r.length===1?"property":"properties"]})]})}),e.jsx(Ee,{className:"pt-0",children:e.jsx("div",{className:"space-y-1",children:r.map(l=>{const o=i(l),c=l.property_address||`MLS# ${l.mls_number}`;return e.jsxs("a",{href:o||"#",target:"_blank",rel:"noopener noreferrer",onClick:d=>{o||d.preventDefault()},className:"group flex items-center gap-3 p-2.5 rounded-lg hover:bg-muted/60 transition-colors",children:[l.photo_url?e.jsx("div",{className:"h-10 w-10 rounded-lg overflow-hidden flex-shrink-0 bg-muted",children:e.jsx("img",{src:l.photo_url,alt:c,className:"w-full h-full object-cover"})}):e.jsx("div",{className:"h-9 w-9 rounded-lg bg-gradient-to-br from-primary/15 to-primary/5 flex items-center justify-center flex-shrink-0",children:e.jsx(Or,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"flex items-center gap-1.5",children:e.jsx("span",{className:"font-medium text-sm truncate",children:c})}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(pr,{className:"h-3 w-3"}),e.jsx("span",{title:Ss(new Date(l.viewed_at),"PPp"),children:Uo(new Date(l.viewed_at),{addSuffix:!0})})]})]}),o&&e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]},l.mls_number)})})})]})}const HGs=["Single Family","Condo","Townhouse","Multi-Family","Land","Commercial"];function yZe({value:s,onChange:t,onAdd:n,suggestions:r,placeholder:a,icon:i}){const[l,o]=N.useState(!1),c=N.useRef(null),d=N.useRef(null);N.useEffect(()=>{const h=p=>{d.current&&!d.current.contains(p.target)&&c.current&&!c.current.contains(p.target)&&o(!1)};return document.addEventListener("mousedown",h),()=>document.removeEventListener("mousedown",h)},[]);const u=r.filter(h=>h.toLowerCase().includes(s.toLowerCase()));return e.jsxs("div",{className:"relative flex-1",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ye,{ref:c,value:s,onChange:h=>{t(h.target.value),o(!0)},onFocus:()=>o(!0),placeholder:a,onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),u.length>0?n(u[0]):n(s))}}),r.length>0&&e.jsx(ao,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>n(s),children:e.jsx(Is,{className:"h-4 w-4"})})]}),l&&u.length>0&&e.jsx("div",{ref:d,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:u.map(h=>e.jsxs("button",{type:"button",className:"w-full text-left px-3 py-2 text-sm hover:bg-accent hover:text-accent-foreground transition-colors flex items-center gap-2",onClick:()=>{n(h),o(!1)},children:[i||e.jsx(ka,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),h]},h))})]})}function GGs({contactId:s,contactName:t}){var le,ve,ge;const{user:n}=vs(),r=wa(),{hasLeadSite:a}=Ap(),i=Kt(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(!1),[y,_]=N.useState(""),[v,j]=N.useState(null),[w,S]=N.useState(!1),[A,E]=N.useState(!1),{data:O}=dt({queryKey:["agent-lead-site-config",r],queryFn:async()=>{const{data:Te,error:Ie}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(Ie||!Te)return{cities:[],zipCodes:[]};const Ce=Te.theme_config||{},Me=Array.isArray(Ce.searchCities)?Ce.searchCities:[];Te.mls_market_area&&!Me.includes(Te.mls_market_area)&&Me.unshift(Te.mls_market_area);const Pe=Array.isArray(Ce.searchZipCodes)?Ce.searchZipCodes:[];return{cities:Me,zipCodes:Pe}},enabled:!!r}),{data:D,isLoading:I}=dt({queryKey:["contact-property-alert",s],queryFn:async()=>{const{data:Te,error:Ie}=await q.from("contact_property_alerts").select("*").eq("contact_id",s).maybeSingle();if(Ie)throw Ie;return Te},enabled:!!s&&!!n}),[F,z]=N.useState({}),H=()=>{z({is_active:(D==null?void 0:D.is_active)??!0,min_price:(D==null?void 0:D.min_price)??null,max_price:(D==null?void 0:D.max_price)??null,min_beds:(D==null?void 0:D.min_beds)??null,min_baths:(D==null?void 0:D.min_baths)??null,min_sqft:(D==null?void 0:D.min_sqft)??null,max_sqft:(D==null?void 0:D.max_sqft)??null,cities:(D==null?void 0:D.cities)??[],zip_codes:(D==null?void 0:D.zip_codes)??[],property_types:(D==null?void 0:D.property_types)??[],frequency:(D==null?void 0:D.frequency)??"daily"}),o(!0)},Z=yt({mutationFn:async()=>{const Te={contact_id:s,owner_user_id:r,is_active:F.is_active??!0,min_price:F.min_price||null,max_price:F.max_price||null,min_beds:F.min_beds||null,min_baths:F.min_baths||null,min_sqft:F.min_sqft||null,max_sqft:F.max_sqft||null,cities:F.cities||[],zip_codes:F.zip_codes||[],property_types:F.property_types||[],frequency:F.frequency||"daily"};if(D!=null&&D.id){const{error:Ie}=await q.from("contact_property_alerts").update(Te).eq("id",D.id);if(Ie)throw Ie}else{const{error:Ie}=await q.from("contact_property_alerts").insert(Te);if(Ie)throw Ie}},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert saved!")},onError:Te=>{ae.error(Te.message||"Failed to save alert")}}),Y=yt({mutationFn:async()=>{if(!(D!=null&&D.id))return;const{error:Te}=await q.from("contact_property_alerts").delete().eq("id",D.id);if(Te)throw Te},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-property-alert",s]}),o(!1),ae.success("Property alert removed")}}),W=Te=>{var Ce;const Ie=Te.trim();Ie&&!((Ce=F.cities)!=null&&Ce.includes(Ie))&&z(Me=>({...Me,cities:[...Me.cities||[],Ie]})),d("")},ee=Te=>{var Ce;const Ie=Te.trim();Ie&&!((Ce=F.zip_codes)!=null&&Ce.includes(Ie))&&z(Me=>({...Me,zip_codes:[...Me.zip_codes||[],Ie]})),h("")},se=Te=>{z(Ie=>{const Ce=Ie.property_types||[];return{...Ie,property_types:Ce.includes(Te)?Ce.filter(Me=>Me!==Te):[...Ce,Te]}})},oe=async()=>{if(D!=null&&D.id){S(!0),f(!0),_(""),j(null);try{const{data:Te,error:Ie}=await q.functions.invoke("process-property-alerts",{body:{alert_id:D.id,mode:"preview"}});if(Ie)throw Ie;Te!=null&&Te.html?(_(Te.html),j({count:Te.listings_count||0,recipient:Te.recipient,subject:Te.subject})):j({count:0,message:(Te==null?void 0:Te.message)||"No matching listings found right now."})}catch(Te){ae.error(Te.message||"Failed to generate preview"),f(!1)}finally{S(!1)}}},he=async()=>{if(D!=null&&D.id&&confirm(`Send property alert email to ${t} now?`)){E(!0);try{const{data:Te,error:Ie}=await q.functions.invoke("process-property-alerts",{body:{alert_id:D.id,mode:"send"}});if(Ie)throw Ie;Te!=null&&Te.sent_count?(ae.success(`Sent ${Te.sent_count} ${Te.sent_count===1?"listing":"listings"} to ${Te.recipient}`),i.invalidateQueries({queryKey:["contact-property-alert",s]})):ae.info((Te==null?void 0:Te.message)||"No new matching listings to send right now.")}catch(Te){ae.error(Te.message||"Failed to send alert")}finally{E(!1)}}};if(!a||I)return null;if(D&&!l)return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx("div",{className:`h-7 w-7 rounded-lg flex items-center justify-center ${D.is_active?"bg-green-500/10":"bg-muted"}`,children:D.is_active?e.jsx(nm,{className:"h-4 w-4 text-green-600"}):e.jsx(cw,{className:"h-4 w-4 text-muted-foreground"})}),"Property Alerts",e.jsxs(Ue,{variant:D.is_active?"default":"secondary",className:"text-xs ml-auto",children:[D.is_active?"Active":"Paused"," · ",D.frequency]})]})}),e.jsxs(Ee,{className:"pt-0 space-y-2",children:[e.jsxs("div",{className:"flex flex-wrap gap-1.5 text-xs",children:[D.min_price||D.max_price?e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(Yl,{className:"h-3 w-3"}),D.min_price?`$${(D.min_price/1e3).toFixed(0)}k`:"$0"," - ",D.max_price?`$${(D.max_price/1e3).toFixed(0)}k`:"Any"]}):null,D.min_beds?e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(U2,{className:"h-3 w-3"}),D.min_beds,"+ beds"]}):null,D.min_baths?e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(kp,{className:"h-3 w-3"}),D.min_baths,"+ baths"]}):null,(le=D.cities)==null?void 0:le.map(Te=>e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),Te]},Te)),(ve=D.zip_codes)==null?void 0:ve.map(Te=>e.jsx(Ue,{variant:"outline",children:Te},Te)),(ge=D.property_types)==null?void 0:ge.map(Te=>e.jsx(Ue,{variant:"outline",children:Te},Te))]}),D.last_sent_at&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sent: ",new Date(D.last_sent_at).toLocaleDateString()]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:oe,disabled:w,children:[w?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Sr,{className:"h-4 w-4 mr-1"}),"Preview Email"]}),e.jsxs(B,{size:"sm",onClick:he,disabled:A||!D.is_active,title:D.is_active?"Send this alert email now":"Activate alert to send",children:[A?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Send Now"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:H,children:"Manage Alert"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>Y.mutate(),disabled:Y.isPending,children:[Y.isPending?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($n,{className:"h-4 w-4 mr-1"}),"Remove"]})]})]})]}),e.jsx(_s,{open:p,onOpenChange:f,children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Property Alert Email Preview"}),(v==null?void 0:v.subject)&&e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5 pt-1",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"To:"})," ",v.recipient]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Subject:"})," ",v.subject]}),e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:"Listings:"})," ",v.count]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden border rounded-md bg-muted/30",children:w?e.jsxs("div",{className:"flex items-center justify-center h-96 text-muted-foreground",children:[e.jsx(rs,{className:"h-5 w-5 mr-2 animate-spin"})," Building preview…"]}):y?e.jsx("iframe",{srcDoc:y,title:"Property alert preview",className:"w-full h-[65vh] bg-white rounded-md"}):e.jsx("div",{className:"flex items-center justify-center h-96 text-sm text-muted-foreground p-6 text-center",children:(v==null?void 0:v.message)||"No matching listings found right now."})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Close"}),y&&e.jsxs(B,{onClick:()=>{f(!1),he()},disabled:A||!D.is_active,children:[e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Send to ",t]})]})]})})]});const ce=((O==null?void 0:O.cities)||[]).filter(Te=>{var Ie;return!((Ie=F.cities)!=null&&Ie.includes(Te))}),me=((O==null?void 0:O.zipCodes)||[]).filter(Te=>{var Ie;return!((Ie=F.zip_codes)!=null&&Ie.includes(Te))});return l?e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(nm,{className:"h-4 w-4 text-primary"}),D?"Edit":"Setup"," Property Alert for ",t]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Alert Active"}),e.jsx(jn,{checked:F.is_active??!0,onCheckedChange:Te=>z(Ie=>({...Ie,is_active:Te}))})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Yl,{className:"h-3.5 w-3.5"})," Price Range"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{type:"number",placeholder:"Min price",value:F.min_price??"",onChange:Te=>z(Ie=>({...Ie,min_price:Te.target.value?Number(Te.target.value):null}))}),e.jsx(ye,{type:"number",placeholder:"Max price",value:F.max_price??"",onChange:Te=>z(Ie=>({...Ie,max_price:Te.target.value?Number(Te.target.value):null}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(U2,{className:"h-3.5 w-3.5"})," Min Beds"]}),e.jsxs(us,{value:F.min_beds?String(F.min_beds):"any",onValueChange:Te=>z(Ie=>({...Ie,min_beds:Te==="any"?null:Number(Te)})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Any"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"any",children:"Any"}),[1,2,3,4,5].map(Te=>e.jsxs(Ze,{value:String(Te),children:[Te,"+"]},Te))]})]})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(kp,{className:"h-3.5 w-3.5"})," Min Baths"]}),e.jsxs(us,{value:F.min_baths?String(F.min_baths):"any",onValueChange:Te=>z(Ie=>({...Ie,min_baths:Te==="any"?null:Number(Te)})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Any"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"any",children:"Any"}),[1,1.5,2,2.5,3,4].map(Te=>e.jsxs(Ze,{value:String(Te),children:[Te,"+"]},Te))]})]})]})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Z2,{className:"h-3.5 w-3.5"})," Square Feet"]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{type:"number",placeholder:"Min sqft",value:F.min_sqft??"",onChange:Te=>z(Ie=>({...Ie,min_sqft:Te.target.value?Number(Te.target.value):null}))}),e.jsx(ye,{type:"number",placeholder:"Max sqft",value:F.max_sqft??"",onChange:Te=>z(Ie=>({...Ie,max_sqft:Te.target.value?Number(Te.target.value):null}))})]})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Cities"]}),e.jsx(yZe,{value:c,onChange:d,onAdd:W,suggestions:ce,placeholder:"Type to search cities..."}),F.cities&&F.cities.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:F.cities.map(Te=>e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[Te,e.jsx("button",{onClick:()=>z(Ie=>{var Ce;return{...Ie,cities:(Ce=Ie.cities)==null?void 0:Ce.filter(Me=>Me!==Te)}}),children:e.jsx($n,{className:"h-3 w-3"})})]},Te))})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"mb-1.5",children:"Zip Codes"}),e.jsx(yZe,{value:u,onChange:h,onAdd:ee,suggestions:me,placeholder:"Type to search zip codes...",icon:e.jsx("span",{className:"text-xs text-muted-foreground font-mono",children:"#"})}),F.zip_codes&&F.zip_codes.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:F.zip_codes.map(Te=>e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[Te,e.jsx("button",{onClick:()=>z(Ie=>{var Ce;return{...Ie,zip_codes:(Ce=Ie.zip_codes)==null?void 0:Ce.filter(Me=>Me!==Te)}}),children:e.jsx($n,{className:"h-3 w-3"})})]},Te))})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(Or,{className:"h-3.5 w-3.5"})," Property Types"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:HGs.map(Te=>{var Ie;return e.jsx(Ue,{variant:(Ie=F.property_types)!=null&&Ie.includes(Te)?"default":"outline",className:"cursor-pointer",onClick:()=>se(Te),children:Te},Te)})})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"mb-1.5",children:"Frequency"}),e.jsxs(us,{value:F.frequency||"daily",onValueChange:Te=>z(Ie=>({...Ie,frequency:Te})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"daily",children:"Daily"}),e.jsx(Ze,{value:"weekly",children:"Weekly"})]})]})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>Z.mutate(),disabled:Z.isPending,className:"flex-1",children:[Z.isPending?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-1"}),"Save Alert"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),D&&e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>Y.mutate(),disabled:Y.isPending,children:e.jsx($n,{className:"h-4 w-4"})})]})]})]}):e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("button",{onClick:H,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(nm,{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 WGs({contactId:s,contactName:t}){var se;const{user:n}=vs(),r=wa(),{hasLeadSite:a}=Ap(),i=Kt(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState([]),[p,f]=N.useState(!1),[y,_]=N.useState(!1),[v,j]=N.useState(!1),[w,S]=N.useState(""),A=N.useRef(null),E=N.useRef(null),{data:O}=dt({queryKey:["agent-lead-site-cities",r],queryFn:async()=>{const{data:oe,error:he}=await q.from("lead_sites").select("theme_config, mls_market_area").eq("agent_id",r).eq("is_active",!0).order("created_at",{ascending:!0}).limit(1).maybeSingle();if(he||!oe)return[];const ce=oe.theme_config||{},me=Array.isArray(ce.searchCities)?ce.searchCities:[];return oe.mls_market_area&&!me.includes(oe.mls_market_area)&&me.unshift(oe.mls_market_area),me},enabled:!!r}),{data:D,isLoading:I}=dt({queryKey:["contact-market-report",s],queryFn:async()=>{const{data:oe,error:he}=await q.from("innercircle_contacts").select("market_report_enabled, market_report_cities").eq("id",s).single();if(he)throw he;return oe},enabled:!!s&&!!n});N.useEffect(()=>{const oe=he=>{E.current&&!E.current.contains(he.target)&&A.current&&!A.current.contains(he.target)&&_(!1)};return document.addEventListener("mousedown",oe),()=>document.removeEventListener("mousedown",oe)},[]);const F=()=>{f((D==null?void 0:D.market_report_enabled)??!1),h((D==null?void 0:D.market_report_cities)??[]),o(!0)},z=oe=>{const he=(oe||c).trim();he&&!u.includes(he)&&h([...u,he]),d(""),_(!1)},H=(O||[]).filter(oe=>!u.includes(oe)&&oe.toLowerCase().includes(c.toLowerCase())),Z=yt({mutationFn:async()=>{const{data:oe,error:he}=await q.functions.invoke("send-market-report",{body:{action:"preview",agentId:r,cities:(D==null?void 0:D.market_report_cities)??[]}});if(he)throw new Error(he.message||"Failed to generate preview");if(oe&&!oe.ok&&oe.error)throw new Error(oe.error);return oe},onSuccess:oe=>{S(oe.html),j(!0)},onError:oe=>{ae.error(oe.message||"Failed to generate preview")}}),Y=yt({mutationFn:async()=>{const{data:oe,error:he}=await q.functions.invoke("send-market-report",{body:{action:"send",agentId:r,cities:(D==null?void 0:D.market_report_cities)??[],contactIds:[s]}});if(he)throw new Error(he.message||"Failed to send report");if(oe&&!oe.ok&&oe.error)throw new Error(oe.error);return oe},onSuccess:()=>{ae.success(`Market report sent to ${t}!`)},onError:oe=>{ae.error(oe.message||"Failed to send report")}}),W=yt({mutationFn:async()=>{const{error:oe}=await q.from("innercircle_contacts").update({market_report_enabled:p,market_report_cities:u}).eq("id",s);if(oe)throw oe},onSuccess:()=>{i.invalidateQueries({queryKey:["contact-market-report",s]}),o(!1),ae.success(p?"Monthly market report enabled!":"Market report disabled")},onError:oe=>{ae.error(oe.message||"Failed to save")}}),ee=yt({mutationFn:async()=>{const{error:oe}=await q.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),f(!1),h([]),ae.success("Market report removed")},onError:oe=>{ae.error(oe.message||"Failed to remove market report")}});return!a||I?null:D!=null&&D.market_report_enabled&&!l?e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{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(_o,{className:"h-4 w-4 text-primary"})}),"Monthly Market Report",e.jsx(Ue,{variant:"default",className:"text-xs ml-auto",children:"Active"})]})}),e.jsxs(Ee,{className:"pt-0 space-y-2",children:[e.jsx("div",{className:"flex flex-wrap gap-1.5 text-xs",children:((se=D.market_report_cities)==null?void 0:se.length)>0?D.market_report_cities.map(oe=>e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(ka,{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(B,{variant:"outline",size:"sm",onClick:()=>Z.mutate(),disabled:Z.isPending,className:"flex-1",children:[Z.isPending?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Sr,{className:"h-4 w-4 mr-1"}),"Preview"]}),e.jsxs(B,{variant:"default",size:"sm",onClick:()=>Y.mutate(),disabled:Y.isPending,className:"flex-1",children:[Y.isPending?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Send Now"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:F,className:"flex-1",children:"Manage"}),e.jsxs(B,{variant:"destructive",size:"sm",onClick:()=>ee.mutate(),disabled:ee.isPending,className:"flex-1",children:[ee.isPending?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($n,{className:"h-4 w-4 mr-1"}),"Remove"]})]}),e.jsx(_s,{open:v,onOpenChange:j,children:e.jsxs(bs,{className:"max-w-3xl max-h-[85vh] overflow-hidden flex flex-col",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(_o,{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:w}})}),e.jsxs("div",{className:"flex gap-2 pt-4 border-t",children:[e.jsxs(B,{onClick:()=>{j(!1),Y.mutate()},disabled:Y.isPending,className:"flex-1",children:[Y.isPending?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(lr,{className:"h-4 w-4 mr-1"}),"Send to ",t]}),e.jsx(B,{variant:"outline",onClick:()=>j(!1),children:"Close"})]})]})})]})]}):l?e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(_o,{className:"h-4 w-4 text-primary"}),"Market Report for ",t]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Send Monthly Report"}),e.jsx(jn,{checked:p,onCheckedChange:f})]}),p&&e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-1 mb-1.5",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," Report Cities"]}),e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Select cities from your website's configured areas."}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(ye,{ref:A,value:c,onChange:oe=>{d(oe.target.value),_(!0)},onFocus:()=>_(!0),placeholder:"Type to search cities...",onKeyDown:oe=>{oe.key==="Enter"&&(oe.preventDefault(),H.length>0?z(H[0]):z())}}),e.jsx(ao,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground pointer-events-none"})]}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:()=>z(),children:e.jsx(Is,{className:"h-4 w-4"})})]}),y&&H.length>0&&e.jsx("div",{ref:E,className:"absolute z-50 mt-1 w-full max-h-60 overflow-y-auto rounded-md border bg-popover shadow-md",children:H.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(ka,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),oe]},oe))})]}),u.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1 mt-2",children:u.map(oe=>e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[oe,e.jsx("button",{onClick:()=>h(u.filter(he=>he!==oe)),children:e.jsx($n,{className:"h-3 w-3"})})]},oe))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>W.mutate(),disabled:W.isPending,className:"flex-1",children:[W.isPending?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-1"}),"Save"]}),e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"})]})]})]}):e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("button",{onClick:F,className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed border-primary/30 hover:bg-primary/5 transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-primary/10 flex items-center justify-center flex-shrink-0",children:e.jsx(_o,{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 KGs(s){return dt({queryKey:["contact-drip-activity",s],queryFn:async()=>{if(!s)return{enrollments:[],stepLogs:[]};const{data:t,error:n}=await q.from("drip_campaign_enrollments").select("id, campaign_id, current_step, status, next_send_at, enrolled_at, completed_at, exited_at, exit_reason").eq("contact_id",s).order("enrolled_at",{ascending:!1});if(n)throw console.error("[ContactDripActivity] enrollments error",n),n;const r=(t||[]).map(c=>c.id),a=Array.from(new Set((t||[]).map(c=>c.campaign_id)));let i=new Map;if(a.length>0){const{data:c}=await q.from("drip_campaigns").select("id, name, description, is_active").in("id",a);(c||[]).forEach(d=>i.set(d.id,d))}const l=(t||[]).map(c=>({...c,campaign:i.get(c.campaign_id)||null}));let o=[];if(r.length>0){const{data:c,error:d}=await q.from("drip_campaign_step_log").select("id, enrollment_id, campaign_id, step_order, channel, recipient_email, subject, status, error_message, sent_at").in("enrollment_id",r).order("sent_at",{ascending:!1});d?console.error("[ContactDripActivity] step log error",d):o=(c||[]).map(u=>{var h;return{...u,campaign:{name:((h=i.get(u.campaign_id))==null?void 0:h.name)??""}}})}return{enrollments:l,stepLogs:o}},enabled:!!s})}function YGs(s){switch(s){case"active":return e.jsx(Ue,{variant:"secondary",className:"bg-emerald-500/10 text-emerald-600 border-emerald-500/20",children:"Active"});case"paused":return e.jsx(Ue,{variant:"secondary",className:"bg-amber-500/10 text-amber-600 border-amber-500/20",children:"Paused"});case"completed":return e.jsx(Ue,{variant:"secondary",className:"bg-sky-500/10 text-sky-600 border-sky-500/20",children:"Completed"});case"exited":return e.jsx(Ue,{variant:"outline",children:"Exited"});default:return e.jsx(Ue,{variant:"outline",children:s})}}function vZe(s){return s==="sent"?e.jsx(vr,{className:"h-4 w-4 text-emerald-500"}):s==="failed"?e.jsx(ic,{className:"h-4 w-4 text-destructive"}):s==="skipped"?e.jsx(gf,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(pr,{className:"h-4 w-4 text-muted-foreground"})}function ZGs({contactId:s}){const t=Ln(),{data:n,isLoading:r}=KGs(s),[a,i]=N.useState(null);if(r)return null;const l=(n==null?void 0:n.enrollments)||[],o=(n==null?void 0:n.stepLogs)||[];return l.length===0&&o.length===0?null:e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2 text-base",children:[e.jsx(RA,{className:"h-5 w-5 text-emerald-500"}),"Drip Campaign Activity"]})}),e.jsxs(Ee,{className:"space-y-4",children:[l.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Enrollments"}),l.map(c=>{var d;return e.jsxs("button",{onClick:()=>t("/mission-control/smart-drips"),className:"w-full text-left flex items-start gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-emerald-500/10 flex items-center justify-center text-emerald-600 flex-shrink-0",children:e.jsx(RA,{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"}),YGs(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: ",Uo(new Date(c.next_send_at),{addSuffix:!0})]}),c.completed_at&&e.jsxs(e.Fragment,{children:[" · Completed ",Uo(new Date(c.completed_at),{addSuffix:!0})]}),c.exited_at&&!c.completed_at&&e.jsxs(e.Fragment,{children:[" · ",c.exit_reason||"Exited"," ",Uo(new Date(c.exited_at),{addSuffix:!0})]})]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]},c.id)})]}),o.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("p",{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:["Send History (",o.length,")"]}),e.jsxs("div",{className:"space-y-1",children:[o.slice(0,8).map(c=>{var d,u;return e.jsxs(_s,{open:(a==null?void 0:a.id)===c.id,onOpenChange:h=>!h&&i(null),children:[e.jsx(ki,{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:vZe(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(Ai,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}):e.jsx(Gs,{className:"h-3 w-3 text-muted-foreground flex-shrink-0"}),e.jsx("p",{className:"text-sm truncate",children:c.subject||`${c.channel.toUpperCase()} step ${c.step_order+1}`})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:[((d=c.campaign)==null?void 0:d.name)||"Campaign"," · ",Ss(new Date(c.sent_at),"MMM d, h:mm a")]}),c.status==="failed"&&c.error_message&&e.jsx("p",{className:"text-xs text-destructive mt-0.5 truncate",children:c.error_message})]})]})}),e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[vZe(c.status),c.subject||"Drip step"]})}),e.jsxs("div",{className:"space-y-2 text-sm",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Campaign"}),e.jsx("span",{className:"font-medium",children:((u=c.campaign)==null?void 0:u.name)||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Channel"}),e.jsx("span",{className:"font-medium uppercase",children:c.channel})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Step"}),e.jsxs("span",{className:"font-medium",children:["#",c.step_order+1]})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Recipient"}),e.jsx("span",{className:"font-medium",children:c.recipient_email||"—"})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Status"}),e.jsx("span",{className:"font-medium capitalize",children:c.status})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:"Sent"}),e.jsx("span",{className:"font-medium",children:Ss(new Date(c.sent_at),"MMM d, yyyy h:mm a")})]}),c.error_message&&e.jsx("div",{className:"rounded-md border border-destructive/30 bg-destructive/5 p-2 text-destructive text-xs",children:c.error_message})]})]})]},c.id)}),o.length>8&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full text-xs",onClick:()=>t("/mission-control/smart-drips"),children:"View all in Smart Drips"})]})]})]})]})}function j_t({contactId:s}={}){const{user:t}=vs();return dt({queryKey:["sent-emails",t==null?void 0:t.id,s??"all"],enabled:!!t,queryFn:async()=>{const n=t.id;let r=q.from("gmail_sent_emails").select("id, contact_id, to_email, subject, sent_at, source").eq("user_id",n).or("source.is.null,source.neq.drip_campaign").order("sent_at",{ascending:!1}).limit(1e3);s&&(r=r.eq("contact_id",s));let a=q.from("bulk_email_sends").select("id, contact_id, contact_email, subject, sent_at, source, opened_at, clicked_at").eq("user_id",n).order("sent_at",{ascending:!1}).limit(1e3);s&&(a=a.eq("contact_id",s));const i=await q.from("email_campaigns").select("id, subject").eq("user_id",n),l=(i.data||[]).map(_=>_.id),o=new Map((i.data||[]).map(_=>[_.id,_.subject]));let c=[];if(l.length>0){let _=q.from("email_campaign_recipients").select("id, contact_id, email, sent_at, campaign_id, opened_at, clicked_at").in("campaign_id",l).eq("status","sent").not("sent_at","is",null).order("sent_at",{ascending:!1}).limit(1e3);s&&(_=_.eq("contact_id",s)),c=(await _).data||[]}const[d,u]=await Promise.all([r,a]),h=(d.data||[]).map(_=>({id:`g-${_.id}`,channel:_.source==="portal_invite"?"Client Portal Invite":"Gmail",subject:_.subject,to_email:_.to_email,contact_id:_.contact_id,sent_at:_.sent_at,source:_.source})),p=(u.data||[]).map(_=>({id:`b-${_.id}`,channel:"Mass Email",subject:_.subject,to_email:_.contact_email,contact_id:_.contact_id,sent_at:_.sent_at,source:_.source,opened_at:_.opened_at,clicked_at:_.clicked_at})),f=c.map(_=>({id:`c-${_.id}`,channel:"Campaign",subject:o.get(_.campaign_id)||"(campaign)",to_email:_.email,contact_id:_.contact_id,sent_at:_.sent_at,source:null,campaign_id:_.campaign_id,opened_at:_.opened_at,clicked_at:_.clicked_at})),y=[...h,...p,...f];return y.sort((_,v)=>_.sent_at0&&e.jsx(Ue,{variant:"secondary",className:"ml-1",children:t.length})]})}),e.jsx(Ee,{children:n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):t.length===0?e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(Gs,{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(Ue,{variant:"outline",className:`text-xs ${QGs[l.channel]}`,children:l.channel}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(l.sent_at),"MMM d, yyyy h:mm a")})]}),e.jsx("p",{className:"text-sm font-medium truncate",children:l.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["to ",l.to_email]})]})},l.id))}),t.length>5&&e.jsx(B,{variant:"ghost",size:"sm",className:"w-full mt-3",onClick:()=>a(!r),children:r?"Show less":`Show all ${t.length}`}),e.jsx("div",{className:"mt-3 pt-3 border-t",children:e.jsx(In,{to:"/mission-control/sent-emails",className:"text-xs text-primary hover:underline",children:"View all sent emails →"})})]})})]})}function JGs({videoId:s}){var l;const{data:t,isLoading:n,error:r}=tGs(s);if(n)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"w-full aspect-video rounded-lg"}),e.jsx(Ws,{className:"h-4 w-1/3"})]});if(r||!t||t.is_deleted)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-8 text-center",children:[e.jsx(ic,{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 eWs({contactId:s}){const t=Ln(),[n,r]=N.useState(!1),{data:a,isLoading:i}=dt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:p}=await q.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(p)throw p;return h},enabled:!!s}),l=async(h,p)=>{const f=p==="done"?"todo":"done";await q.from("deal_tasks").update({status:f,completed_at:f==="done"?new Date().toISOString():null}).eq("id",h),window.dispatchEvent(new CustomEvent("refetch-contact-tasks"))},{refetch:o}=dt({queryKey:["deal-tasks","contact",s],queryFn:async()=>{const{data:h,error:p}=await q.from("deal_tasks").select(` id, title, priority, status, due_date, completed_at, deal:deal_pipeline(id, deal_name) `).eq("contact_id",s).order("status").order("due_date",{ascending:!0,nullsFirst:!1});if(p)throw p;return h},enabled:!!s}),c={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"},d=(a==null?void 0:a.filter(h=>h.status!=="done"))||[],u=(a==null?void 0:a.filter(h=>h.status==="done"))||[];return e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(Lr,{className:"h-4 w-4"}),"Tasks",d.length>0&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:d.length})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/tasks"),children:"View All"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>r(!0),children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]})]})}),e.jsx(Ee,{className:"space-y-1",children:i?e.jsx(Ws,{className:"h-8 w-full"}):d.length===0&&u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No tasks yet"}):e.jsxs(e.Fragment,{children:[d.map(h=>e.jsxs("button",{onClick:async()=>{await l(h.id,h.status),o()},className:"w-full text-left flex items-center gap-2 px-2 py-1.5 rounded hover:bg-muted/50 transition-colors group",children:[e.jsx("div",{className:"h-4 w-4 rounded-full border-2 border-muted-foreground/30 shrink-0 group-hover:border-primary"}),e.jsxs("span",{className:"text-sm flex-1 truncate",children:[c[h.priority]," ",h.title]}),h.due_date&&e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ss(new Date(h.due_date),"MMM d")})]},h.id)),u.length>0&&e.jsx("div",{className:"pt-1 border-t mt-1",children:e.jsxs("p",{className:"text-[10px] text-muted-foreground px-2 py-1",children:[u.length," completed"]})})]})}),n&&e.jsx(tWs,{contactId:s,open:n,onOpenChange:h=>{r(h),h||o()}})]})}function tWs({contactId:s,open:t,onOpenChange:n}){const[r,a]=N.useState(""),[i,l]=N.useState("medium"),[o,c]=N.useState(),{data:d}=dt({queryKey:["session"],queryFn:async()=>{const{data:h}=await q.auth.getSession();return h.session}}),u=async()=>{var p;if(!r.trim()||!((p=d==null?void 0:d.user)!=null&&p.id))return;const{error:h}=await q.from("deal_tasks").insert([{owner_user_id:d.user.id,contact_id:s,title:r.trim(),priority:i,status:"todo",due_date:o?Ss(o,"yyyy-MM-dd"):null}]);if(h){console.error("Task create error:",h);return}n(!1)};return e.jsx(_s,{open:t,onOpenChange:n,children:e.jsxs(bs,{className:"sm:max-w-[400px]",children:[e.jsx(js,{children:e.jsx(ws,{children:"Add Task"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:r,onChange:h=>a(h.target.value),placeholder:"Task title...",onKeyDown:h=>h.key==="Enter"&&u()})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Priority"}),e.jsxs("select",{value:i,onChange:h=>l(h.target.value),className:"w-full h-10 rounded-md border border-input bg-background px-3 text-sm",children:[e.jsx("option",{value:"low",children:"🟢 Low"}),e.jsx("option",{value:"medium",children:"🟡 Medium"}),e.jsx("option",{value:"high",children:"🟠 High"}),e.jsx("option",{value:"urgent",children:"🔴 Urgent"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Due Date"}),e.jsx(ye,{type:"date",value:o?Ss(o,"yyyy-MM-dd"):"",onChange:h=>c(h.target.value?new Date(h.target.value+"T00:00:00"):void 0)})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Cancel"}),e.jsx(B,{onClick:u,disabled:!r.trim(),children:"Create Task"})]})]})]})})}function sWs({contactId:s}){const t=Ln(),{data:n,isLoading:r}=dt({queryKey:["contact-linked-deals",s],queryFn:async()=>{const{data:a,error:i}=await q.from("deal_pipeline").select(` id, deal_name, deal_type, expected_price, property_address, stage:deal_pipeline_stages(id, name, color, icon, is_won_stage, is_lost_stage) `).eq("contact_id",s).order("updated_at",{ascending:!1});if(i)throw i;return a},enabled:!!s});return r||!n||n.length===0?null:e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(zm,{className:"h-4 w-4"}),"Linked Deals"]})}),e.jsx(Ee,{className:"space-y-2",children:n.map(a=>{const i=a.stage;return e.jsx("button",{onClick:()=>t(`/mission-control/pipeline?deal=${a.id}`),className:"w-full text-left p-3 rounded-lg border hover:bg-accent transition-colors group",children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.deal_name}),a.property_address&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.property_address}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ue,{variant:"outline",className:"text-[10px] capitalize",children:a.deal_type}),i&&e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1",style:{borderColor:i.color,color:i.color,backgroundColor:`${i.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:i.color}}),i.name]})]})]}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors flex-shrink-0"})]})},a.id)})})]})}function nWs(){var Lt,Jt,gt,zt,As;const{contactId:s}=bi(),t=Ln(),[n]=xl(),r=n.get("search")||"",a=n.get("type")||"all",i=n.get("status")||n.get("filter")||"all",l=n.get("tags")||"",o=n.get("tagMode")==="all"?"all":"any",c=N.useMemo(()=>new Set(l.split(",").map(Xt=>Xt.trim()).filter(Boolean)),[l]),{data:d,isLoading:u}=yns(s||""),{data:h}=ky(),{data:p}=aU(),{data:f}=iU(3650),{data:y}=f1e(365),{data:_}=RGs(s),{contactsWithScores:v}=Mye(),{data:j}=h1e(),w=QMe(),S=XMe(),A=Tye(),E=Smt(),[O,D]=N.useState(!1),[I,F]=N.useState({}),[z,H]=N.useState(!1),[Z,Y]=N.useState(null),[W,ee]=N.useState(""),[se,oe]=N.useState(void 0),[he,ce]=N.useState(""),[me,le]=N.useState(null),[ve,ge]=N.useState(!1),[Te,Ie]=N.useState(null),[Ce,Me]=N.useState(!1),{isGmailConnected:Pe,gmailEmail:Re}=Dh(),{isReady:Ae}=mR(),Be=Ae||Pe,we=y_t(),[Je,ke]=N.useState(!1),{data:it}=dt({queryKey:["cma-eligible"],queryFn:async()=>{const{data:{user:Xt}}=await q.auth.getUser();if(!Xt)return!1;const{data:Qs}=await q.from("lead_sites").select("id, mls_provider_id, no_mls_mode, is_active").eq("agent_id",Xt.id);return(Qs||[]).some(ks=>ks.is_active&&ks.mls_provider_id&&!ks.no_mls_mode)}}),je=async()=>{var an,tn,er,xn;if(!d)return;const Xt=(an=d.address)==null?void 0:an.trim(),Qs=(tn=d.city)==null?void 0:tn.trim(),ks=(er=d.state)==null?void 0:er.trim().toUpperCase(),$s=((xn=d.zip_code)==null?void 0:xn.trim())||"";if(!Xt||!Qs||!ks){ae.error("Add a full address (street, city, state) before creating a CMA.");return}try{ke(!0);const Pn=await we.mutateAsync({subject:{address:Xt,city:Qs,state:ks,zip:$s},contactId:d.id,title:`${d.first_name||""} ${d.last_name||""}`.trim()+" — "+Xt});t(`/mission-control/cma/${Pn.id}`)}catch(Pn){ae.error("Could not create CMA: "+((Pn==null?void 0:Pn.message)||"unknown error"))}finally{ke(!1)}},{data:He}=dt({queryKey:["gmail-sent-emails",s],queryFn:async()=>{const{data:Xt,error:Qs}=await q.from("gmail_sent_emails").select("*").eq("contact_id",s).order("sent_at",{ascending:!1});if(Qs)throw Qs;return Xt},enabled:!!s}),$e=Xt=>{if(!Xt)return null;const Qs=Xt.match(/Video ID:\s*([a-f0-9-]+)/i);return Qs?Qs[1]:null},Ke=N.useMemo(()=>{if(!v)return[];const Xt=new Map;if(c.size>0&&j)for(const ks of j)Xt.has(ks.contact_id)||Xt.set(ks.contact_id,new Set),Xt.get(ks.contact_id).add(ks.tag_id);let Qs=v.filter(ks=>{var er,xn,Pn;const $s=r===""||`${ks.first_name} ${ks.last_name}`.toLowerCase().includes(r.toLowerCase())||((er=ks.email)==null?void 0:er.toLowerCase().includes(r.toLowerCase()))||((xn=ks.phone)==null?void 0:xn.includes(r)),an=a==="all"||((Pn=ks.tags)==null?void 0:Pn.some(Qn=>Qn.relationship_type_id===a));let tn=!0;if(c.size>0){const Qn=Xt.get(ks.id)||new Set;o==="all"?tn=Array.from(c).every(sa=>Qn.has(sa)):tn=Array.from(c).some(sa=>Qn.has(sa))}return $s&&an&&tn});return i==="not-touched-90"?Qs=Qs.filter(ks=>{const $s=ks.relationshipScore.daysSinceTouch;return $s===null||$s>90}):i==="at-risk"?Qs=Qs.filter(ks=>ks.relationshipScore.status==="at-risk"):i==="cooling"?Qs=Qs.filter(ks=>ks.relationshipScore.status==="cooling"):i==="warm"&&(Qs=Qs.filter(ks=>ks.relationshipScore.status==="warm")),Qs.map(ks=>ks.id)},[v,r,a,i,c,o,j]),Ge=Ke.indexOf(s||""),rt=Ge>0?Ke[Ge-1]:null,tt=Ge1&&Ge!==-1,Ye=Xt=>{const Qs=new URLSearchParams;r&&Qs.set("search",r),a!=="all"&&Qs.set("type",a),i!=="all"&&Qs.set("status",i),c.size>0&&(Qs.set("tags",Array.from(c).join(",")),Qs.set("tagMode",o));const ks=Qs.toString();return`/mission-control/contacts/${Xt}${ks?`?${ks}`:""}`},ut=N.useMemo(()=>{const Xt=((f==null?void 0:f.filter(ks=>ks.contact_id===s))||[]).map(ks=>{var er,xn,Pn;const $s=$e(ks.notes);let an=((er=ks.action_type)==null?void 0:er.name)||"Touch",tn=ks.notes;if(an==="Other"&&((xn=ks.notes)!=null&&xn.startsWith("["))){const Qn=ks.notes.indexOf("]");Qn>0&&(an=ks.notes.substring(1,Qn),tn=ks.notes.substring(Qn+1).replace(/^\s*—\s*/,"").trim()||null)}return{id:ks.id,type:"touch",completed_at:ks.completed_at,name:an,color:((Pn=ks.action_type)==null?void 0:Pn.color)||"#3B82F6",notes:tn,videoId:$s}}),Qs=((y==null?void 0:y.filter(ks=>ks.contact_id===s))||[]).map(ks=>({id:ks.id,type:"popby",completed_at:ks.completed_at,name:"Pop-by",color:"#F97316",notes:ks.notes,videoId:null}));return[...Xt,...Qs].sort((ks,$s)=>new Date($s.completed_at).getTime()-new Date(ks.completed_at).getTime())},[f,y,s]),_t=()=>{var Xt;d&&(F({first_name:d.first_name||"",last_name:d.last_name||"",email:d.email||"",phone:d.phone||"",address:d.address||"",city:d.city||"",state:d.state||"",zip_code:d.zip_code||"",birthday:d.birthday||"",home_anniversary:d.home_anniversary||"",wedding_anniversary:d.wedding_anniversary||"",spouse_birthday:d.spouse_birthday||"",spouse_name:d.spouse_name||"",spouse_email:d.spouse_email||"",company_name:d.company_name||"",job_title:d.job_title||"",lead_source_id:d.lead_source_id||"",notes:d.notes||"",tagIds:((Xt=d.tags)==null?void 0:Xt.map(Qs=>Qs.relationship_type_id))||[]}),D(!0))},bt=async()=>{await w.mutateAsync({id:s,...I,lead_source_id:I.lead_source_id||null}),D(!1)},$t=async()=>{confirm("Are you sure you want to delete this contact?")&&(await S.mutateAsync(s),t("/mission-control/contacts"))},Ds=((Lt=p==null?void 0:p.find(Xt=>Xt.id===Z))==null?void 0:Lt.name)==="Other",Ls=async()=>{if(!Z||Ds&&!he.trim())return;const Xt=se?new Date(se.getFullYear(),se.getMonth(),se.getDate(),12,0,0).toISOString():void 0,Qs=Ds?`[${he.trim()}]${W?" — "+W:""}`:W;await A.mutateAsync({contactId:s,actionTypeId:Z,notes:Qs,completedAt:Xt}),H(!1),Y(null),ee(""),oe(void 0),ce("")},xs=(Xt,Qs)=>{Be&&d?(Ie({email:Xt,name:Qs||`${d.first_name} ${d.last_name||""}`.trim()}),ge(!0)):window.location.href=`mailto:${Xt}`};return u?e.jsx(Cs,{title:"Contact Details",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):d?e.jsxs(e.Fragment,{children:[e.jsx(Cs,{title:`${d.first_name} ${d.last_name||""}`,description:"Contact details and activity",children:e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>{window.history.length>1?t(-1):t("/mission-control/contacts")},children:[e.jsx(ml,{className:"h-4 w-4 mr-1"}),"Back to Contacts"]}),at&&e.jsxs("div",{className:"flex items-center gap-1 ml-2 border-l pl-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>rt&&t(Ye(rt)),disabled:!rt,className:"px-2",children:[e.jsx(ml,{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:[Ge+1," of ",Ke.length]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>tt&&t(Ye(tt)),disabled:!tt,className:"px-2",children:[e.jsx("span",{className:"sr-only sm:not-sr-only sm:mr-1",children:"Next"}),e.jsx(ga,{className:"h-4 w-4"})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 w-full sm:w-auto justify-end flex-wrap",children:[d.email&&e.jsxs(B,{variant:"outline",onClick:()=>xs(d.email,`${d.first_name} ${d.last_name||""}`.trim()),children:[e.jsx(Gs,{className:"h-4 w-4 mr-1"}),"Email"]}),d.email&&e.jsxs(B,{variant:"outline",onClick:()=>Me(!0),className:"border-primary/40 text-primary hover:bg-primary/10",children:[e.jsx(un,{className:"h-4 w-4 mr-1"}),"Send Connect Page"]}),e.jsxs(B,{variant:"default",onClick:()=>t(`/mission-control/video/record?contact_id=${s}`),className:"bg-gradient-to-r from-primary to-primary/80",children:[e.jsx(fr,{className:"h-4 w-4 mr-1"}),"Quick Video Touch"]}),e.jsxs(_s,{open:z,onOpenChange:H,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Log Action"]})}),e.jsxs(bs,{className:"max-h-[85vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Log an Action"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Action Type"}),e.jsx("div",{className:"grid grid-cols-2 gap-2 mt-2",children:p==null?void 0:p.filter(Xt=>Xt.active).map(Xt=>e.jsxs("button",{onClick:()=>Y(Xt.id),className:` p-3 rounded-lg border text-left transition-all ${Z===Xt.id?"border-primary bg-primary/10":"hover:bg-accent"} `,children:[e.jsx("div",{className:"font-medium",children:Xt.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Xt.description})]},Xt.id))}),Ds&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ne,{htmlFor:"custom-action-name",children:"What did you do?"}),e.jsx(ye,{id:"custom-action-name",value:he,onChange:Xt=>ce(Xt.target.value),placeholder:"e.g. Met a client for lunch, Dropped off a gift...",className:"mt-1"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Date (optional — backdate if needed)"}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("w-full justify-start text-left font-normal mt-2",!se&&"text-muted-foreground"),children:[e.jsx(yr,{className:"h-4 w-4 mr-2"}),se?Ss(se,"PPP"):"Today (default)"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:se,onSelect:oe,disabled:Xt=>Xt>new Date,initialFocus:!0,className:Mt("p-3 pointer-events-auto")})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"action-notes",children:"Notes (optional)"}),e.jsx(Ms,{id:"action-notes",value:W,onChange:Xt=>ee(Xt.target.value),placeholder:"Add any notes about this interaction...",rows:3})]}),e.jsxs(B,{onClick:Ls,disabled:!Z||Ds&&!he.trim()||A.isPending,className:"w-full",children:[e.jsx(Lr,{className:"h-4 w-4 mr-1"}),"Complete Action"]})]})]})]}),e.jsxs(B,{variant:"outline",onClick:_t,children:[e.jsx(wu,{className:"h-4 w-4 mr-1"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:$t,children:e.jsx(_n,{className:"h-4 w-4"})})]})]}),e.jsx("div",{className:"bg-card border rounded-lg p-4 sm:p-6",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center gap-4",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs("h1",{className:"text-2xl sm:text-3xl font-bold",children:[d.first_name," ",d.last_name||""]}),(((Jt=d.lead_source_ref)==null?void 0:Jt.name)||d.lead_source)&&e.jsx(Ue,{variant:"outline",className:"text-xs border-primary/30 text-primary",children:((gt=d.lead_source_ref)==null?void 0:gt.name)||d.lead_source})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mt-2 text-muted-foreground",children:[d.email&&e.jsxs("button",{onClick:()=>xs(d.email),className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Gs,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:d.email})]}),d.phone&&e.jsxs("a",{href:`tel:${d.phone}`,className:"flex items-center gap-1 hover:text-primary transition-colors",children:[e.jsx(Cr,{className:"h-4 w-4"}),e.jsx("span",{className:"text-sm",children:d.phone})]})]})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx(L5e,{contact:d}),(zt=d.tags)==null?void 0:zt.map(Xt=>{const Qs=h==null?void 0:h.find(ks=>ks.id===Xt.relationship_type_id);return Qs?e.jsx(Ue,{variant:"secondary",className:"text-xs",children:Qs.name},Xt.id):null})]}),e.jsx("div",{className:"mt-2",children:e.jsx(wGs,{contactId:s})})]})}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"md:col-span-2",children:[e.jsx(It,{children:e.jsx(Rt,{children:"Contact Information"})}),e.jsx(Ee,{children:O?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(ne,{htmlFor:"first_name",children:"First Name"}),e.jsx(ye,{id:"first_name",value:I.first_name,onChange:Xt=>F({...I,first_name:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"last_name",children:"Last Name"}),e.jsx(ye,{id:"last_name",value:I.last_name,onChange:Xt=>F({...I,last_name:Xt.target.value})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"email",children:"Email"}),e.jsx(ye,{id:"email",type:"email",value:I.email,onChange:Xt=>F({...I,email:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"phone",children:"Phone"}),e.jsx(ye,{id:"phone",value:I.phone,onChange:Xt=>F({...I,phone:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"address",children:"Street Address"}),e.jsx(ye,{id:"address",value:I.address,onChange:Xt=>F({...I,address:Xt.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:I.city,onChange:Xt=>F({...I,city:Xt.target.value}),placeholder:"City"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:I.state,onChange:Xt=>F({...I,state:Xt.target.value}),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"zip_code",children:"Zip Code"}),e.jsx(ye,{id:"zip_code",value:I.zip_code,onChange:Xt=>F({...I,zip_code:Xt.target.value}),placeholder:"12345"})]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"birthday",children:"Birthday"}),e.jsx(ye,{id:"birthday",type:"date",value:I.birthday,onChange:Xt=>F({...I,birthday:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"home_anniversary",children:"Home Anniversary"}),e.jsx(ye,{id:"home_anniversary",type:"date",value:I.home_anniversary,onChange:Xt=>F({...I,home_anniversary:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"wedding_anniversary",children:"Wedding Anniversary"}),e.jsx(ye,{id:"wedding_anniversary",type:"date",value:I.wedding_anniversary||"",onChange:Xt=>F({...I,wedding_anniversary:Xt.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"spouse_birthday",children:"Spouse Birthday"}),e.jsx(ye,{id:"spouse_birthday",type:"date",value:I.spouse_birthday,onChange:Xt=>F({...I,spouse_birthday:Xt.target.value})})]})]}),e.jsx(al,{}),e.jsx(D5e,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:(d==null?void 0:d.spouse_name)||null,currentSpouseEmail:(d==null?void 0:d.spouse_email)||null,onLink:Xt=>E.mutate({contactId:s,spouseContactId:Xt}),onUnlink:()=>E.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(ne,{htmlFor:"company_name",children:"Company"}),e.jsx(ye,{id:"company_name",value:I.company_name,onChange:Xt=>F({...I,company_name:Xt.target.value}),placeholder:"Enter company name"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"job_title",children:"Job Title"}),e.jsx(ye,{id:"job_title",value:I.job_title,onChange:Xt=>F({...I,job_title:Xt.target.value}),placeholder:"Enter job title"})]})]}),e.jsx(g_t,{value:I.lead_source_id||"",onChange:Xt=>F({...I,lead_source_id:Xt})}),e.jsxs("div",{children:[e.jsx(ne,{children:"Relationship Types"}),e.jsx("div",{className:"flex flex-wrap gap-2 mt-2",children:h==null?void 0:h.filter(Xt=>Xt.active).map(Xt=>{var Qs;return e.jsxs("label",{className:"flex items-center gap-2 cursor-pointer",children:[e.jsx(hi,{checked:(Qs=I.tagIds)==null?void 0:Qs.includes(Xt.id),onCheckedChange:ks=>{var $s;F(ks?{...I,tagIds:[...I.tagIds||[],Xt.id]}:{...I,tagIds:($s=I.tagIds)==null?void 0:$s.filter(an=>an!==Xt.id)})}}),e.jsx("span",{className:"text-sm",children:Xt.name})]},Xt.id)})})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"notes",children:"Notes"}),e.jsx(Ms,{id:"notes",value:I.notes,onChange:Xt=>F({...I,notes:Xt.target.value}),rows:4})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{onClick:bt,disabled:w.isPending,children:"Save Changes"}),e.jsx(B,{variant:"outline",onClick:()=>D(!1),children:"Cancel"})]})]}):e.jsxs("div",{className:"space-y-4",children:[ut.length>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3 flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"text-sm",children:[e.jsx("span",{className:"font-medium",children:"Last Contacted:"})," ",Ss(new Date(ut[0].completed_at),"MMM d, yyyy")," ","(",ut[0].name,")"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row sm:gap-6 gap-2",children:[d.email&&e.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[e.jsx(Gs,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("button",{onClick:()=>xs(d.email),className:"text-primary hover:underline truncate text-left",children:d.email})]}),d.phone&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cr,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx("a",{href:`tel:${d.phone}`,className:"text-primary hover:underline",children:d.phone})]})]}),(d.address||d.city||d.state||d.zip_code)&&e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(ka,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{className:"flex flex-col",children:[d.address&&e.jsx("span",{children:d.address}),(d.city||d.state||d.zip_code)&&e.jsxs("span",{className:"text-muted-foreground",children:[[d.city,d.state].filter(Boolean).join(", "),d.zip_code&&` ${d.zip_code}`]})]})]}),it&&d.address&&d.city&&d.state&&e.jsxs(B,{size:"sm",variant:"outline",onClick:je,disabled:Je,children:[Je?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(dw,{className:"h-4 w-4 mr-1"}),"Create CMA"]})]}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[d.birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Birthday: ",Ss(Ll(d.birthday),Ll(d.birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.home_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Home Anniversary: ",Ss(Ll(d.home_anniversary),Ll(d.home_anniversary).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.spouse_birthday&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Spouse Birthday: ",Ss(Ll(d.spouse_birthday),Ll(d.spouse_birthday).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.wedding_anniversary&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(gi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Wedding Anniversary: ",Ss(Ll(d.wedding_anniversary),Ll(d.wedding_anniversary).getFullYear()===1900?"MMMM d":"MMMM d, yyyy")]})]}),d.created_at&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Date Added: ",Ss(new Date(d.created_at),"MMMM d, yyyy")]})]})]}),e.jsx(al,{}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:[e.jsx(D5e,{contactId:s,currentSpouseContactId:(d==null?void 0:d.spouse_contact_id)||null,currentSpouseName:d.spouse_name||null,currentSpouseEmail:d.spouse_email||null,onLink:Xt=>E.mutate({contactId:s,spouseContactId:Xt}),onUnlink:()=>E.mutate({contactId:s,spouseContactId:null}),isEditing:!1}),(d.company_name||d.job_title)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{children:d.job_title&&d.company_name?`${d.job_title} at ${d.company_name}`:d.job_title||d.company_name})]})]}),e.jsx(al,{}),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:(As=d.tags)!=null&&As.length?d.tags.map(Xt=>{var Qs;return e.jsx(Ue,{variant:"secondary",children:(Qs=Xt.relationship_type)==null?void 0:Qs.name},Xt.id)}):e.jsx("span",{className:"text-sm text-muted-foreground",children:"No relationship types assigned"})})]}),d.notes&&e.jsxs(e.Fragment,{children:[e.jsx(al,{}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:d.notes})]})]})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(NHs,{contact:d,onLogTouch:()=>H(!0)}),e.jsx(sWs,{contactId:s}),e.jsx(qGs,{contactId:s}),e.jsx(VGs,{contactId:s}),e.jsx(GGs,{contactId:s,contactName:d.first_name}),e.jsx(WGs,{contactId:s,contactName:d.first_name}),e.jsx(eWs,{contactId:s}),e.jsx(ZGs,{contactId:s}),e.jsx(XGs,{contactId:s}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Activity Log"})}),e.jsx(Ee,{children:ut.length>0?e.jsx("div",{className:"space-y-4",children:ut.map(Xt=>{var Qs;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[e.jsx("div",{className:"h-8 w-8 rounded-full flex items-center justify-center text-white text-xs",style:{backgroundColor:Xt.color},children:Xt.type==="popby"?e.jsx(Oi,{className:"h-4 w-4"}):(Qs=Xt.name)==null?void 0:Qs.charAt(0)}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:Xt.name}),Xt.videoId&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>le(Xt.videoId),children:[e.jsx(El,{className:"h-3 w-3 mr-1"}),"Preview"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(Xt.completed_at),"MMM d, yyyy h:mm a")}),Xt.notes&&!Xt.videoId&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:Xt.notes})]})]},Xt.id)})}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"})})]}),_&&_.length>0&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Ai,{className:"h-5 w-5 text-primary"}),"Video Replies"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-4",children:_.map(Xt=>{var Qs,ks;return e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0",children:[(Qs=Xt.video)!=null&&Qs.thumbnail_url?e.jsx("img",{src:Xt.video.thumbnail_url,alt:Xt.video.title||"Video",className:"h-12 w-16 object-cover rounded cursor-pointer hover:opacity-80 transition-opacity",onClick:()=>le(Xt.video_id)}):e.jsx("div",{className:"h-12 w-16 bg-muted rounded flex items-center justify-center cursor-pointer hover:bg-muted/80 transition-colors",onClick:()=>le(Xt.video_id),children:e.jsx(fr,{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: ",((ks=Xt.video)==null?void 0:ks.title)||"Untitled Video"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"h-6 px-2 text-xs flex-shrink-0",onClick:()=>le(Xt.video_id),children:[e.jsx(El,{className:"h-3 w-3 mr-1"}),"Watch"]})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(Xt.created_at),"MMM d, yyyy h:mm a")}),Xt.message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:['"',Xt.message,'"']})]})]},Xt.id)})})})]}),He&&He.length>0&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(lr,{className:"h-5 w-5 text-sky-500"}),"Sent Emails"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-3",children:He.map(Xt=>e.jsxs(_s,{children:[e.jsx(ki,{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(Gs,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:Xt.subject}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["To: ",Xt.to_email," · ",Ss(new Date(Xt.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground mt-1 flex-shrink-0"})]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[85vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5 text-sky-500"}),Xt.subject]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["To: ",Xt.to_email," · ",Ss(new Date(Xt.sent_at),"MMM d, yyyy h:mm a")]})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-hidden rounded-lg border bg-white",children:e.jsx("iframe",{srcDoc:Xt.body,className:"w-full h-[400px] border-0",sandbox:"",title:`Email: ${Xt.subject}`})})]})]},Xt.id))})})]})]}),e.jsx(_s,{open:!!me,onOpenChange:Xt=>!Xt&&le(null),children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsx(ws,{children:"Video Preview"})}),me&&e.jsx(JGs,{videoId:me})]})})]})]})}),Be&&d&&Te&&e.jsx(Xv,{open:ve,onOpenChange:ge,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:Te.email},gmailEmail:Re}),d&&d.email&&e.jsx(CGs,{open:Ce,onOpenChange:Me,contact:{id:d.id,first_name:d.first_name,last_name:d.last_name,email:d.email}})]}):e.jsx(Cs,{title:"Contact Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This contact was not found."}),e.jsx(B,{onClick:()=>t("/mission-control/contacts"),children:"Back to Contacts"})]})})}function rWs({rangeDays:s}){const{user:t}=vs(),n=Kt(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),{data:d=[],isLoading:u}=dt({queryKey:["newsletter-campaigns",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let f=q.from("email_campaigns").select("id, name, subject, status, sent_at, scheduled_at, created_at, total_recipients, sent_count, open_count, click_count, bounce_count").eq("user_id",t.id).like("name","Newsletter:%").order("created_at",{ascending:!1}).limit(50);if(s){const v=new Date(Date.now()-s*864e5).toISOString();f=f.gte("created_at",v)}const{data:y,error:_}=await f;if(_)throw _;return y||[]}}),{data:h}=dt({queryKey:["newsletter-campaign-recipients",r],enabled:!!r,queryFn:async()=>{const{data:f,error:y}=await q.from("email_campaign_recipients").select("id, email, name, status, sent_at, opened_at, clicked_at, error_message").eq("campaign_id",r).order("sent_at",{ascending:!1}).limit(2e3);if(y)throw y;return f||[]}}),p=async()=>{if(!(!i||!t)){c(!0);try{const{data:f,error:y}=await q.from("email_campaign_recipients").select("email, name, contact_id").eq("campaign_id",i.id).eq("status","sent").is("opened_at",null).limit(5e3);if(y)throw y;if(!f||f.length===0){ae.info("All recipients opened — nothing to resend!"),l(null),c(!1);return}const{data:_}=await q.from("email_campaigns").select("subject, body_html, from_email, reply_to_email").eq("id",i.id).single();if(!_)throw new Error("Original campaign not found");const{data:v,error:j}=await q.from("email_campaigns").insert({user_id:t.id,name:`${i.name} (Resend to non-openers)`,subject:_.subject,body_html:_.body_html,from_email:_.from_email,reply_to_email:_.reply_to_email,total_recipients:f.length,status:"draft"}).select("id").single();if(j)throw j;const w=f.map(A=>({campaign_id:v.id,contact_id:A.contact_id,email:A.email,name:A.name,status:"pending"}));for(let A=0;A{const y=f.sent_count||0,_=y>0?f.open_count/y*100:0,v=y>0?f.click_count/y*100:0,j=f.sent_at?Vv(new Date,new Date(f.sent_at)):0,w=f.status==="sent"&&j>=3&&y>0&&f.open_counta(f.id),children:[e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1"})," Details"]}),w&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l(f),children:[e.jsx(PA,{className:"h-3.5 w-3.5 mr-1"})," Resend"]})]})]}),f.status==="sent"&&y>0&&e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mt-3",children:[e.jsx(oG,{icon:e.jsx(lr,{className:"h-3.5 w-3.5"}),label:"Sent",value:y,sub:`of ${f.total_recipients}`}),e.jsx(oG,{icon:e.jsx(Sr,{className:"h-3.5 w-3.5 text-blue-600"}),label:"Opens",value:f.open_count,sub:`${_.toFixed(1)}%`,children:e.jsx(fi,{value:_,className:"h-1 mt-1"})}),e.jsx(oG,{icon:e.jsx(oc,{className:"h-3.5 w-3.5 text-purple-600"}),label:"Clicks",value:f.click_count,sub:`${v.toFixed(1)}%`,children:e.jsx(fi,{value:v,className:"h-1 mt-1"})}),e.jsx(oG,{icon:e.jsx(rL,{className:"h-3.5 w-3.5 text-orange-600"}),label:"Bounces",value:f.bounce_count,sub:f.bounce_count>0?"review":"none"})]})]},f.id)})})]})}),e.jsx(t0,{open:!!r,onOpenChange:f=>!f&&a(null),children:e.jsxs(og,{className:"w-full sm:max-w-2xl overflow-y-auto",children:[e.jsx(jy,{children:e.jsx(Ny,{children:"Recipient Activity"})}),e.jsx("div",{className:"mt-4 space-y-1",children:h?h.length===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No recipients yet."}):e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"text-xs uppercase text-muted-foreground border-b",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-2",children:"Recipient"}),e.jsx("th",{className:"text-left py-2",children:"Opened"}),e.jsx("th",{className:"text-left py-2",children:"Clicked"}),e.jsx("th",{className:"text-left py-2",children:"Status"})]})}),e.jsx("tbody",{children:h.map(f=>e.jsxs("tr",{className:"border-b last:border-0",children:[e.jsxs("td",{className:"py-2",children:[e.jsx("div",{className:"font-medium truncate max-w-[180px]",children:f.name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate max-w-[180px]",children:f.email})]}),e.jsx("td",{className:"py-2 text-xs",children:f.opened_at?e.jsx(Ue,{variant:"default",className:"text-xs",children:Ss(new Date(f.opened_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-2 text-xs",children:f.clicked_at?e.jsx(Ue,{variant:"default",className:"text-xs bg-purple-600",children:Ss(new Date(f.clicked_at),"MMM d")}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsxs("td",{className:"py-2 text-xs",children:[f.status==="sent"&&e.jsx(Ue,{variant:"outline",className:"text-xs",children:"sent"}),f.status==="pending"&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:"queued"}),f.status==="failed"&&e.jsx(Ue,{variant:"destructive",className:"text-xs",title:f.error_message||"",children:"failed"}),f.status==="suppressed"&&e.jsx(Ue,{variant:"outline",className:"text-xs",children:"suppressed"})]})]},f.id))})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"})})]})}),e.jsx(Oo,{open:!!i,onOpenChange:f=>!f&&l(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Resend to non-openers?"}),e.jsxs(Mo,{children:["This will send ",e.jsxs("span",{className:"font-medium text-foreground",children:['"',i==null?void 0:i.subject,'"']})," again only to contacts who didn't open the original. Consider tweaking the subject next time — but a clean resend is a great way to recover lost opens."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{disabled:o,children:"Cancel"}),e.jsx(wo,{onClick:p,disabled:o,children:o?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}),"Resending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(PA,{className:"h-4 w-4 mr-1"}),"Resend"]})})]})]})})]})}function oG({icon:s,label:t,value:n,sub:r,children:a}){return e.jsxs("div",{className:"rounded-lg border bg-muted/20 p-2.5",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[s,t]}),e.jsxs("div",{className:"flex items-baseline gap-1.5 mt-0.5",children:[e.jsx("span",{className:"text-lg font-bold",children:n.toLocaleString()}),r&&e.jsx("span",{className:"text-xs text-muted-foreground",children:r})]}),a]})}function aWs(){const{user:s}=vs(),t=Ln(),n=Kt(),{data:r=[],isLoading:a}=dt({queryKey:["scheduled-email-campaigns",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("email_campaigns").select("id, name, subject, scheduled_at, total_recipients, status, created_at").eq("user_id",s.id).eq("status","scheduled").order("scheduled_at",{ascending:!0});if(u)throw u;return d||[]},refetchInterval:3e4}),i=async(d,u)=>{const{data:{session:h}}=await q.auth.getSession(),f=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-schedule-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${h.access_token}`},body:JSON.stringify({action:d,campaign_id:u})})).json();if(!f.success)throw new Error(f.error||`Failed to ${d}`);return f},l=yt({mutationFn:d=>i("cancel",d),onSuccess:()=>{ae.success("Schedule cancelled — saved as draft"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),o=yt({mutationFn:d=>i("delete",d),onSuccess:()=>{ae.success("Scheduled email deleted"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)}),c=yt({mutationFn:async({id:d,iso:u})=>{const{error:h}=await q.from("email_campaigns").update({scheduled_at:u,status:"scheduled"}).eq("id",d);if(h)throw h;await i("schedule",d)},onSuccess:()=>{ae.success("Send time updated"),n.invalidateQueries({queryKey:["scheduled-email-campaigns"]})},onError:d=>ae.error(d.message)});return a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading scheduled emails..."}):r.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(pr,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No scheduled emails."}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Emails you schedule for the future will appear here."})]})}):e.jsx("div",{className:"space-y-3",children:r.map(d=>e.jsx(iWs,{campaign:d,onEdit:()=>t(`/admin/email-campaigns/new?edit=${d.id}`),onCancel:()=>l.mutate(d.id),onDelete:()=>o.mutate(d.id),onReschedule:u=>c.mutate({id:d.id,iso:u}),isBusy:l.isPending||o.isPending||c.isPending},d.id))})}function iWs({campaign:s,onEdit:t,onCancel:n,onDelete:r,onReschedule:a,isBusy:i}){const l=s.scheduled_at?new Date(s.scheduled_at):null,[o,c]=N.useState(!1),[d,u]=N.useState(l||void 0),[h,p]=N.useState(l?`${String(l.getHours()).padStart(2,"0")}:${String(l.getMinutes()).padStart(2,"0")}`:"09:00"),f=()=>{if(!d)return ae.error("Pick a date");const y=new Date(`${Ss(d,"yyyy-MM-dd")}T${h}:00`).toISOString();if(new Date(y).getTime()yp(y.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:f,disabled:i,children:[i&&e.jsx(rs,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save new time"]})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",disabled:i,children:[e.jsx(Uc,{className:"h-3.5 w-3.5 mr-1.5"})," Cancel Send"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Cancel this scheduled send?"}),e.jsxs(Mo,{children:["The email will move back to ",e.jsx("strong",{children:"Draft"})," and won't send at the scheduled time. You can re-schedule or delete it later."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep scheduled"}),e.jsx(wo,{onClick:n,children:"Cancel send"})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"ghost",className:"text-destructive hover:text-destructive",disabled:i,children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1.5"})," Delete"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this scheduled email?"}),e.jsx(Mo,{children:"This permanently removes the scheduled email and all its recipient records. This can't be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep"}),e.jsx(wo,{onClick:r,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete permanently"})]})]})]})]})]})})})}const bZe=["Gmail","Mass Email","Campaign","Client Portal Invite"],oWs={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 lWs(){const{user:s}=vs(),[t,n]=xl(),{data:r=[],isLoading:a}=j_t(),[i,l]=N.useState(""),[o,c]=N.useState("all"),[d,u]=N.useState("30"),[h,p]=N.useState(!1),[f,y]=N.useState(t.get("tab")==="scheduled"?"scheduled":"sent"),{gmailEmail:_}=Dh(),{data:v=0}=dt({queryKey:["scheduled-email-count",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{count:E}=await q.from("email_campaigns").select("id",{count:"exact",head:!0}).eq("user_id",s.id).eq("status","scheduled");return E||0},refetchInterval:3e4});N.useEffect(()=>{const E=new URLSearchParams(t);f==="scheduled"?E.set("tab","scheduled"):E.delete("tab"),n(E,{replace:!0})},[f]);const j=N.useMemo(()=>Array.from(new Set(r.map(E=>E.contact_id).filter(Boolean))),[r]),{data:w}=dt({queryKey:["sent-emails-contact-names",s==null?void 0:s.id,j.length],enabled:j.length>0,queryFn:async()=>{const{data:E}=await q.from("innercircle_contacts").select("id, first_name, last_name").in("id",j),O=new Map;return(E||[]).forEach(D=>{O.set(D.id,[D.first_name,D.last_name].filter(Boolean).join(" ")||"Contact")}),O}}),S=N.useMemo(()=>{const E=d==="all"?null:Date.now()-parseInt(d)*864e5,O=i.trim().toLowerCase();return r.filter(D=>{if(o!=="all"&&D.channel!==o||E&&new Date(D.sent_at).getTime(){const E={};let O=0,D=0,I=0;return S.forEach(F=>{E[F.channel]=(E[F.channel]||0)+1,(F.channel==="Campaign"||F.channel==="Mass Email")&&(I++,F.opened_at&&O++,F.clicked_at&&D++)}),{byChannel:E,opened:O,clicked:D,trackable:I}},[S]);return e.jsx(Cs,{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(lr,{className:"h-6 w-6"})," Sent Emails"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All emails you've sent through LevelUp — Gmail, mass emails, campaigns, and client portal invites."})]}),e.jsxs(B,{onClick:()=>p(!0),children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"})," Send Email"]})]}),e.jsxs(Fr,{value:f,onValueChange:E=>y(E),className:"space-y-6",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"sent",className:"gap-2",children:[e.jsx(lr,{className:"h-4 w-4"})," Sent"]}),e.jsxs(Zt,{value:"scheduled",className:"gap-2",children:[e.jsx(pr,{className:"h-4 w-4"})," Scheduled",v>0&&e.jsx(Ue,{variant:"secondary",className:"ml-1 h-5 min-w-5 px-1.5 text-xs",children:v})]})]}),e.jsxs(is,{value:"sent",className:"space-y-6 mt-0",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"py-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground uppercase",children:"Total Sent"}),e.jsx("p",{className:"text-2xl font-bold",children:S.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1 truncate",children:bZe.map(E=>A.byChannel[E]?`${A.byChannel[E]} ${E}`:null).filter(Boolean).join(" · ")||"—"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(vr,{className:"h-3 w-3"})," Delivered"]}),e.jsx("p",{className:"text-2xl font-bold",children:S.length}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"All sends completed"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"})," Opened"]}),e.jsx("p",{className:"text-2xl font-bold",children:A.opened}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:A.trackable>0?`${Math.round(A.opened/A.trackable*100)}% of ${A.trackable} tracked`:"No tracked emails"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"py-4",children:[e.jsxs("p",{className:"text-xs text-muted-foreground uppercase flex items-center gap-1",children:[e.jsx(oc,{className:"h-3 w-3"})," Clicked"]}),e.jsx("p",{className:"text-2xl font-bold",children:A.clicked}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:A.trackable>0?`${Math.round(A.clicked/A.trackable*100)}% of ${A.trackable} tracked`:"No tracked emails"})]})})]}),e.jsxs("p",{className:"text-xs text-muted-foreground -mt-2",children:[e.jsx(fw,{className:"h-3 w-3 inline mr-1"}),"Open & click tracking is available for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search subject, recipient, contact...",value:i,onChange:E=>l(E.target.value),className:"pl-9"})]}),e.jsxs(us,{value:o,onValueChange:c,children:[e.jsx(ls,{className:"w-[200px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Channels"}),bZe.map(E=>e.jsx(Ze,{value:E,children:E},E))]})]}),e.jsxs(us,{value:d,onValueChange:u,children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"7",children:"Last 7 days"}),e.jsx(Ze,{value:"30",children:"Last 30 days"}),e.jsx(Ze,{value:"90",children:"Last 90 days"}),e.jsx(Ze,{value:"365",children:"Last year"}),e.jsx(Ze,{value:"all",children:"All time"})]})]})]}),e.jsx(rWs,{rangeDays:d==="all"?null:parseInt(d)}),a?e.jsx("div",{className:"text-center py-12 text-muted-foreground",children:"Loading..."}):S.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(Gs,{className:"h-12 w-12 text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No sent emails match your filters."})]})}):e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs("div",{className:"overflow-x-auto",children:[e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-muted/50 text-xs uppercase text-muted-foreground",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Channel"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Subject"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Recipient"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:"Contact"}),e.jsx("th",{className:"text-left py-3 px-4 font-medium",children:e.jsx(Vw,{children:e.jsxs(Bc,{children:[e.jsxs($c,{className:"inline-flex items-center gap-1",children:["Engagement ",e.jsx(fw,{className:"h-3 w-3"})]}),e.jsx(Nc,{className:"max-w-xs",children:"Open & click tracking works for Mass Emails and Campaigns. Emails sent through your connected Gmail inbox aren't tracked."})]})})})]})}),e.jsx("tbody",{children:S.slice(0,500).map(E=>{const O=E.contact_id?w==null?void 0:w.get(E.contact_id):null,D=E.channel==="Campaign"||E.channel==="Mass Email";return e.jsxs("tr",{className:"border-t hover:bg-muted/30",children:[e.jsx("td",{className:"py-3 px-4 whitespace-nowrap text-muted-foreground",children:Ss(new Date(E.sent_at),"MMM d, yyyy h:mm a")}),e.jsx("td",{className:"py-3 px-4",children:e.jsx(Ue,{variant:"outline",className:oWs[E.channel],children:E.channel})}),e.jsx("td",{className:"py-3 px-4 max-w-xs truncate font-medium",children:E.subject}),e.jsx("td",{className:"py-3 px-4 text-muted-foreground",children:E.to_email}),e.jsx("td",{className:"py-3 px-4",children:E.contact_id&&O?e.jsx(In,{to:`/mission-control/contacts/${E.contact_id}`,className:"text-primary hover:underline",children:O}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx("td",{className:"py-3 px-4",children:D?e.jsxs("div",{className:"flex flex-wrap gap-1",children:[e.jsxs(Ue,{variant:"outline",className:"bg-slate-50 text-slate-700 border-slate-200 gap-1",children:[e.jsx(vr,{className:"h-3 w-3"})," Delivered"]}),E.opened_at&&e.jsxs(Ue,{variant:"outline",className:"bg-blue-50 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"})," Opened"]}),E.clicked_at&&e.jsxs(Ue,{variant:"outline",className:"bg-emerald-50 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(oc,{className:"h-3 w-3"})," Clicked"]})]}):e.jsx("span",{className:"text-xs text-muted-foreground",children:"Not tracked"})})]},E.id)})})]}),S.length>500&&e.jsxs("p",{className:"text-xs text-muted-foreground text-center py-3 border-t",children:["Showing first 500 of ",S.length," — narrow your filters to see more."]})]})})})]}),e.jsx(is,{value:"scheduled",className:"mt-0",children:e.jsx(aWs,{})})]}),e.jsx(Xv,{open:h,onOpenChange:p,gmailEmail:_})]})})}const _Ze={Crown:hf,FileText:br,Users:An,Globe:lc,Star:oa,Phone:Cr,MessageSquare:Ai,PenTool:ZS,Video:fr,Gift:Oi},lG=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];function cWs(){var bt,$t;const s=Ln(),{user:t}=vs(),{data:n}=ky(),{data:r}=bns(),{data:a}=Cns(),{data:i}=kmt(),{data:l}=aU(),{data:o}=vns(),c=Tns(),d=_ns(),u=jns(),h=Nns(),p=kns(),f=Sns(),y=wns(),[_,v]=N.useState(null),[j,w]=N.useState(!1),[S,A]=N.useState(null),[E,O]=N.useState(""),[D,I]=N.useState(""),[F,z]=N.useState([]),[H,Z]=N.useState(null),[Y,W]=N.useState(null),[ee,se]=N.useState(null),[oe,he]=N.useState(!1),[ce,me]=N.useState(""),[le,ve]=N.useState(""),[ge,Te]=N.useState(""),[Ie,Ce]=N.useState(""),Me=(Yt,Ds)=>a==null?void 0:a.some(Ls=>Ls.plan_id===Yt&&Ls.relationship_type_id===Ds&&Ls.active),Pe=Yt=>a==null?void 0:a.find(Ds=>Ds.relationship_type_id===Yt&&Ds.active),Re=async(Yt,Ds)=>{const Ls=Me(Yt,Ds);await c.mutateAsync({planId:Yt,relationshipTypeId:Ds,active:!Ls})},Ae=(r==null?void 0:r.filter(Yt=>Yt.active&&!Yt.owner_user_id))||[],Be=(r==null?void 0:r.filter(Yt=>Yt.owner_user_id===(t==null?void 0:t.id)))||[],we=n==null?void 0:n.find(Yt=>Yt.id===_),Je=_?Pe(_):null,ke=r==null?void 0:r.find(Yt=>Yt.id===(Je==null?void 0:Je.plan_id)),it=async()=>{if(!E.trim())return;const Yt=await d.mutateAsync({name:E,description:D});Yt&&F.length>0&&await p.mutateAsync({planId:Yt.id,items:F}),Ke()},je=async()=>{!E.trim()||!S||(await u.mutateAsync({id:S,name:E,description:D}),await p.mutateAsync({planId:S,items:F}),Ke())},He=Yt=>{var Ds;A(Yt.id),O(Yt.name),I(Yt.description||""),z(((Ds=Yt.items)==null?void 0:Ds.map(Ls=>({month_number:Ls.month_number,action_type_id:Ls.action_type_id,default_script_id:Ls.default_script_id||void 0,notes:Ls.notes||void 0})))||[]),w(!0)},$e=async(Yt,Ds)=>{if(Yt.owner_user_id===(t==null?void 0:t.id)){He(Yt);return}try{const Ls=await y.mutateAsync({sourcePlanId:Yt.id,newName:`${Yt.name} (My Copy)`});if(!Ls)return;await c.mutateAsync({planId:Yt.id,relationshipTypeId:Ds,active:!1}),await c.mutateAsync({planId:Ls.id,relationshipTypeId:Ds,active:!0}),A(Ls.id),O(Ls.name),I(Ls.description||""),z((Yt.items||[]).map(xs=>({month_number:xs.month_number,action_type_id:xs.action_type_id,default_script_id:xs.default_script_id||void 0,notes:xs.notes||void 0}))),w(!0)}catch{}},Ke=()=>{w(!1),A(null),O(""),I(""),z([])},Ge=(Yt,Ds)=>{W(Ds)},rt=(Yt,Ds,Ls)=>{z(xs=>[...xs.filter(Jt=>Jt.month_number!==Yt),{month_number:Yt,action_type_id:Ds,default_script_id:Ls}]),Z(null),W(null)},tt=Yt=>{z(Ds=>Ds.filter(Ls=>Ls.month_number!==Yt))},at=async()=>{if(!ce.trim()||!le.trim()||!Y)return;const Yt=await f.mutateAsync({actionTypeId:Y,title:ce,scriptBody:le,emailSubject:ge||void 0,tone:Ie||void 0});Yt&&H!==null&&rt(H,Y,Yt.id),he(!1),me(""),ve(""),Te(""),Ce("")},Ye=Y?o==null?void 0:o.filter(Yt=>Yt.action_type_id===Y&&Yt.active):[],ut=Yt=>_Ze[Yt||"Phone"]||Cr,_t=Yt=>_Ze[Yt||"Users"]||An;return e.jsxs(Cs,{title:"Touchpoint Plans",description:"Assign plans to your contact groups",children:[e.jsxs("div",{className:"space-y-6 overflow-x-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Touchpoint Plans"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row items-start sm:items-center justify-between gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>s("/mission-control"),children:[e.jsx(ml,{className:"h-4 w-4 mr-1"}),"Back"]}),e.jsxs(B,{onClick:()=>w(!0),className:"w-full sm:w-auto",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create Custom Plan"]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"space-y-3",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Your Contact Groups"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Select a group to assign a touchpoint plan"}),n==null?void 0:n.filter(Yt=>Yt.active).map(Yt=>{const Ds=_t(Yt.icon),Ls=(i==null?void 0:i[Yt.id])||0,xs=Pe(Yt.id),Lt=r==null?void 0:r.find(gt=>gt.id===(xs==null?void 0:xs.plan_id)),Jt=_===Yt.id;return e.jsxs("button",{onClick:()=>v(Yt.id),className:` w-full flex items-center gap-3 p-4 rounded-lg border text-left transition-all ${Jt?"border-primary bg-primary/5 ring-2 ring-primary":"hover:bg-accent"} `,children:[e.jsx(Ds,{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:Yt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Ls," contacts"]})]}),Lt?e.jsxs(Ue,{variant:"secondary",className:"text-xs",children:[e.jsx(Pi,{className:"h-3 w-3 mr-1"}),Lt.name.split(" ")[0]]}):e.jsx(Ue,{variant:"outline",className:"text-xs text-muted-foreground",children:"No plan"})]},Yt.id)})]}),e.jsx("div",{className:"lg:col-span-2",children:_&&we?e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[(()=>{const Yt=_t(we.icon);return e.jsx(Yt,{className:"h-5 w-5"})})(),we.name," Touchpoint Plan"]}),e.jsxs(Vn,{children:["Choose a plan for your ",we.name," contacts"]})]}),e.jsxs(Ee,{className:"space-y-6",children:[ke&&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(Pi,{className:"h-4 w-4 text-green-500"}),"Currently using: ",ke.name]}),ke.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:ke.description})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:y.isPending||c.isPending,onClick:()=>$e(ke,_),children:[e.jsx(_v,{className:"h-4 w-4 mr-1"}),"Edit Steps"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>Re(ke.id,_),children:"Disable"})]})]}),ke.items&&ke.items.length>0&&e.jsxs("div",{className:"mt-4",children:[e.jsxs("div",{className:"text-sm font-medium mb-2 flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4"}),"12-Month Schedule"]}),e.jsx("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:lG.map((Yt,Ds)=>{var Jt,gt;const Ls=((Jt=ke.items)==null?void 0:Jt.filter(zt=>zt.month_number===Ds+1))||[],xs=(gt=Ls[0])==null?void 0:gt.action_type,Lt=xs?ut(xs.icon):null;return e.jsxs("div",{className:` p-2 rounded border text-center ${Ls.length>0?"bg-primary/10 border-primary":"bg-muted"} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground",children:Yt}),Lt&&e.jsx(Lt,{className:"h-4 w-4 mx-auto mt-1",style:{color:(xs==null?void 0:xs.color)||"#3B82F6"}})]},Ds)})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-3",children:ke?"Switch to a Different Plan":"Choose a Plan"}),Ae.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"}),Ae.map(Yt=>{var Ls;const Ds=(ke==null?void 0:ke.id)===Yt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Ds?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Yt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Ls=Yt.items)==null?void 0:Ls.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>se(Yt.id),children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Duplicate as my own plan",disabled:y.isPending,onClick:()=>{const xs=`${Yt.name} (Copy)`;y.mutate({sourcePlanId:Yt.id,newName:xs})},children:e.jsx(Zr,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:Ds?"outline":"default",disabled:Ds||c.isPending,onClick:()=>Re(Yt.id,_),children:Ds?"Active":"Use This"})]})]},Yt.id)})]}),Be.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"My Custom Plans"}),Be.map(Yt=>{var Ls;const Ds=(ke==null?void 0:ke.id)===Yt.id;return e.jsxs("div",{className:` flex items-center justify-between p-3 rounded-lg border ${Ds?"opacity-50":"hover:bg-accent"} `,children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Yt.name}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[((Ls=Yt.items)==null?void 0:Ls.length)||0," touchpoints/year"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",title:"View plan details",onClick:()=>se(Yt.id),children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Edit plan",onClick:()=>He(Yt),children:e.jsx(_v,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",title:"Delete plan",onClick:()=>h.mutate(Yt.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})}),e.jsx(B,{size:"sm",variant:Ds?"outline":"default",disabled:Ds||c.isPending,onClick:()=>Re(Yt.id,_),children:Ds?"Active":"Use This"})]})]},Yt.id)})]}),Ae.length===0&&Be.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No plans available. Create a custom plan to get started."})]})]})]}):e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(yr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"Select a contact group to view and assign plans"})]})})})]}),e.jsx(fe,{className:"bg-muted/50",children:e.jsx(Ee,{className:"py-4",children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[e.jsx("strong",{children:"How it works:"})," When you assign a plan to a contact group, those contacts will appear in your daily suggested actions based on the plan's schedule."]})})})]}),e.jsx(_s,{open:j,onOpenChange:Yt=>{Yt?w(!0):Ke()},children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:S?"Edit Touchpoint Plan":"Create Custom Touchpoint Plan"})}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"plan-name",children:"Plan Name"}),e.jsx(ye,{id:"plan-name",value:E,onChange:Yt=>O(Yt.target.value),placeholder:"e.g., My VIP Plan"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"plan-description",children:"Description (optional)"}),e.jsx(Ms,{id:"plan-description",value:D,onChange:Yt=>I(Yt.target.value),placeholder:"Describe your plan...",rows:2})]})]}),e.jsxs("div",{children:[e.jsx(ne,{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:lG.map((Yt,Ds)=>{const Ls=Ds+1,xs=F.find(gt=>gt.month_number===Ls),Lt=xs?l==null?void 0:l.find(gt=>gt.id===xs.action_type_id):null,Jt=Lt?ut(Lt.icon):null;return e.jsxs("div",{className:"relative",children:[e.jsxs("button",{type:"button",onClick:()=>Z(H===Ls?null:Ls),className:` w-full p-3 rounded-lg border text-center transition-all ${xs?"bg-primary/10 border-primary":"bg-muted hover:bg-accent"} ${H===Ls?"ring-2 ring-primary":""} `,children:[e.jsx("div",{className:"text-xs text-muted-foreground font-medium",children:Yt}),Jt?e.jsx(Jt,{className:"h-5 w-5 mx-auto mt-1",style:{color:(Lt==null?void 0:Lt.color)||"#3B82F6"}}):e.jsx(Is,{className:"h-5 w-5 mx-auto mt-1 text-muted-foreground/50"})]}),xs&&e.jsx("button",{type:"button",onClick:gt=>{gt.stopPropagation(),tt(Ls)},className:"absolute -top-1 -right-1 p-1 bg-destructive text-destructive-foreground rounded-full",children:e.jsx($n,{className:"h-3 w-3"})})]},Ds)})}),H!==null&&!Y&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"text-sm font-medium mb-2",children:["Step 1: Select action for ",lG[H-1],":"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l==null?void 0:l.filter(Yt=>Yt.active).map(Yt=>{const Ds=ut(Yt.icon);return e.jsxs("button",{type:"button",onClick:()=>Ge(H,Yt.id),className:"flex items-center gap-2 px-3 py-2 rounded-lg border bg-background hover:bg-accent transition-colors",children:[e.jsx(Ds,{className:"h-4 w-4",style:{color:Yt.color||"#3B82F6"}}),e.jsx("span",{className:"text-sm",children:Yt.name})]},Yt.id)})})]}),H!==null&&Y&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-sm font-medium",children:"Step 2: Select a script (optional)"}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>W(null),children:[e.jsx(ml,{className:"h-4 w-4 mr-1"})," Back"]})]}),e.jsxs("div",{className:"space-y-2 max-h-[300px] overflow-y-auto pr-1",children:[e.jsx("button",{type:"button",onClick:()=>rt(H,Y),className:"w-full flex items-center gap-3 p-3 rounded-lg border bg-background hover:bg-accent transition-colors text-left",children:e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"No Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Use without a predefined script"})]})}),Ye==null?void 0:Ye.map(Yt=>e.jsx("button",{type:"button",onClick:()=>rt(H,Y,Yt.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:Yt.title}),Yt.tone&&e.jsx(Ue,{variant:"secondary",className:"text-xs mt-1",children:Yt.tone}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1 line-clamp-2",children:[Yt.script_body.substring(0,100),"..."]})]})},Yt.id)),e.jsxs("button",{type:"button",onClick:()=>he(!0),className:"w-full flex items-center gap-3 p-3 rounded-lg border border-dashed bg-background hover:bg-accent transition-colors text-left",children:[e.jsx(Is,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-medium text-sm",children:"Create Custom Script"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Write your own script for this action"})]})]})]})]})]}),F.length>0&&e.jsxs("div",{className:"text-sm text-muted-foreground",children:[F.length," touchpoint",F.length!==1?"s":""," per year"]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:Ke,children:"Cancel"}),e.jsxs(B,{onClick:S?je:it,disabled:!E.trim()||d.isPending||u.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),S?"Save Changes":"Create Plan"]})]})]})}),e.jsx(_s,{open:oe,onOpenChange:he,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(ws,{children:"Create Custom Script"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"script-title",children:"Script Title"}),e.jsx(ye,{id:"script-title",value:ce,onChange:Yt=>me(Yt.target.value),placeholder:"e.g., Friendly Check-in Call"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"script-tone",children:"Tone (optional)"}),e.jsxs(us,{value:Ie,onValueChange:Ce,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select tone..."})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"friendly",children:"Friendly"}),e.jsx(Ze,{value:"professional",children:"Professional"}),e.jsx(Ze,{value:"casual",children:"Casual"}),e.jsx(Ze,{value:"formal",children:"Formal"})]})]})]}),(($t=(bt=l==null?void 0:l.find(Yt=>Yt.id===Y))==null?void 0:bt.name)==null?void 0:$t.toLowerCase().includes("email"))&&e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"script-email-subject",children:"Email Subject"}),e.jsx(ye,{id:"script-email-subject",value:ge,onChange:Yt=>Te(Yt.target.value),placeholder:"e.g., Quick Hello!"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"script-body",children:"Script Content"}),e.jsx(Ms,{id:"script-body",value:le,onChange:Yt=>ve(Yt.target.value),placeholder:"Write your script here... You can use {{FirstName}} and {{LastName}} as placeholders.",rows:6}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Tip: Use ","{{FirstName}}"," and ","{{LastName}}"," as placeholders"]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>he(!1),children:"Cancel"}),e.jsxs(B,{onClick:at,disabled:!ce.trim()||!le.trim()||f.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Create & Use Script"]})]})]})}),e.jsx(_s,{open:!!ee,onOpenChange:Yt=>{Yt||se(null)},children:e.jsx(bs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:(()=>{const Yt=r==null?void 0:r.find(xs=>xs.id===ee);if(!Yt)return null;const Ds=Yt.owner_user_id===(t==null?void 0:t.id),Ls=[...Yt.items||[]].sort((xs,Lt)=>xs.month_number-Lt.month_number);return e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[Yt.name,!Ds&&e.jsx(Ue,{variant:"secondary",children:"Template"})]}),Yt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:Yt.description})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[Ls.length," touchpoint",Ls.length!==1?"s":""," per year"]}),e.jsx("div",{className:"space-y-2",children:Array.from({length:12},(xs,Lt)=>Lt+1).map(xs=>{const Lt=Ls.find(As=>As.month_number===xs),Jt=Lt?l==null?void 0:l.find(As=>As.id===Lt.action_type_id):null,gt=Lt!=null&&Lt.default_script_id?o==null?void 0:o.find(As=>As.id===Lt.default_script_id):null,zt=Jt?ut(Jt.icon):null;return e.jsxs("div",{className:`p-3 rounded-lg border flex items-start gap-3 ${Lt?"bg-muted/30":"opacity-60"}`,children:[e.jsx("div",{className:"w-16 shrink-0 font-medium text-sm",children:lG[xs-1]}),Lt&&Jt?e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[zt&&e.jsx(zt,{className:"h-4 w-4",style:{color:Jt.color||"#3B82F6"}}),e.jsx("span",{className:"font-medium text-sm",children:Jt.name}),gt&&e.jsx(Ue,{variant:"outline",className:"text-xs",children:gt.title})]}),gt&&e.jsx("div",{className:"mt-2 text-sm text-muted-foreground whitespace-pre-wrap bg-background p-2 rounded border",children:gt.script_body}),Lt.notes&&e.jsx("div",{className:"mt-1 text-xs text-muted-foreground italic",children:Lt.notes})]}):e.jsx("div",{className:"flex-1 text-sm text-muted-foreground",children:"No touchpoint scheduled"})]},xs)})})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>se(null),children:"Close"}),Ds?e.jsxs(B,{onClick:()=>{const xs=r==null?void 0:r.find(Lt=>Lt.id===ee);xs&&(se(null),He(xs))},children:[e.jsx(_v,{className:"h-4 w-4 mr-2"}),"Edit Plan"]}):e.jsxs(B,{disabled:y.isPending,onClick:()=>{y.mutate({sourcePlanId:Yt.id,newName:`${Yt.name} (Copy)`}),se(null)},children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Duplicate to Edit"]})]})]})})()})})]})}const lNe="https://cma.relevelup.com";function N_t({open:s,onOpenChange:t,cma:n}){var se;const{user:r}=vs(),{toast:a}=Fa(),[i,l]=N.useState([]),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState(!1),[S,A]=N.useState(null),[E,O]=N.useState(!1),[D,I]=N.useState(!1),[F,z]=N.useState(null);N.useEffect(()=>{!s||!r||(async()=>{var Te;const[oe,he,ce,me,le]=await Promise.all([q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",r.id).not("email","is",null).order("first_name"),q.from("profiles").select("name, email, phone, brokerage_name, avatar_url, email_signature").eq("id",r.id).maybeSingle(),q.from("gmail_integrations").select("id, is_active").eq("user_id",r.id).maybeSingle(),q.from("ses_verified_emails").select("email, status").eq("user_id",r.id).eq("status","Success").limit(1),q.from("mass_email_settings").select("*").eq("user_id",r.id).maybeSingle()]),ve=(oe.data||[]).filter(Ie=>Ie.email&&Ie.email.includes("@"));l(ve),A(he.data||null),O(!!((Te=ce.data)!=null&&Te.is_active)),I(!!(me.data&&me.data.length>0)),z(le.data||null);const ge=n.contact_id?ve.find(Ie=>Ie.id===n.contact_id):null;ge&&(c(ge),p(ge.email))})()},[s,r,n.contact_id]),N.useEffect(()=>{var me;if(!s)return;const oe=((me=n.subject)==null?void 0:me.address)||"your home",he=((S==null?void 0:S.name)||"").split(" ")[0]||"your agent",ce=(o==null?void 0:o.first_name)||"there";y(`Your home value report for ${oe}`),v(`Hi ${ce}, I put together a fresh market analysis for ${oe}. It pulls live comparable sales, active listings, and pending homes near you so you can see exactly where your value sits today. Take a look here — it only takes a minute: {{cma_link}} When you've had a chance to review, I'd love to hear your thoughts. Reply to this email or give me a call any time. Talk soon, ${(S==null?void 0:S.name)||he}`)},[s,o==null?void 0:o.id,S==null?void 0:S.name,(se=n.subject)==null?void 0:se.address]);const H=N.useMemo(()=>E?"Gmail (your inbox)":D?"Amazon SES":null,[E,D]),Z=!!(h.trim()&&f.trim()&&_.trim()&&H&&!j),Y=oe=>{c(oe),p(oe.email||""),u(!1)},W=oe=>{const he=`${lNe}/${n.share_token}?e=${oe}`,le=_.replace(/&/g,"&").replace(//g,">").replace(/\{\{cma_link\}\}/g,`View Your Home Value Report`).split(/\n{2,}/).map(Te=>`

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

`).join(""),ve=S!=null&&S.use_email_signature&&(S!=null&&S.email_signature)?`
${S.email_signature}
`:`
${S!=null&&S.name?`
${S.name}
`:""} ${S!=null&&S.brokerage_name?`
${S.brokerage_name}
`:""} ${S!=null&&S.phone?`
${S.phone}
`:""} ${S!=null&&S.email?``:""}
`,ge=``;return`
${le} ${ve}
Prepared with LevelUp · ReLevelUp Real Estate
${ge}
`},ee=async()=>{if(!(!r||!Z)){w(!0);try{const{data:oe,error:he}=await q.from("cma_email_sends").insert({cma_id:n.id,agent_id:r.id,contact_id:(o==null?void 0:o.id)??null,recipient_email:h.trim(),subject:f.trim(),sent_via:E?"gmail":"ses"}).select("id").single();if(he)throw he;const ce=W(oe.id);if(E){const{data:me,error:le}=await q.functions.invoke("gmail-send",{body:{to:h.trim(),subject:f.trim(),body:ce}});if(le)throw le;if(!(me!=null&&me.success))throw new Error((me==null?void 0:me.error)||"Gmail send failed")}else if(D){const me=(F==null?void 0:F.display_name)||(S==null?void 0:S.name)||"ReLevelUp",le=`${me.toLowerCase().replace(/[^a-z]/g,".").replace(/^\.+|\.+$/g,"")||"noreply"}@send.relevelup.com`,{data:ve,error:ge}=await q.functions.invoke("ses-send-campaign",{body:{action:"test_send",to:h.trim(),from_email:`${me} <${le}>`,subject:f.trim(),body_html:ce,reply_to:(F==null?void 0:F.reply_to_email)||(S==null?void 0:S.email)||void 0}});if(ge)throw ge;if(!(ve!=null&&ve.success))throw new Error((ve==null?void 0:ve.error)||"SES send failed")}o&&!n.contact_id&&await q.from("cmas").update({contact_id:o.id}).eq("id",n.id),a({title:"CMA sent",description:`Delivered to ${h.trim()}`}),t(!1)}catch(oe){console.error("Send CMA error:",oe),a({title:"Send failed",description:oe.message||"Could not send email",variant:"destructive"})}finally{w(!1)}}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"w-5 h-5"}),"Send CMA to contact"]})}),H?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Sending via ",e.jsx("span",{className:"font-semibold text-foreground",children:H})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Contact"}),e.jsxs(il,{open:d,onOpenChange:u,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[o?`${o.first_name} ${o.last_name||""}`.trim():"Pick a contact (optional)",e.jsx($g,{className:"w-4 h-4 opacity-50"})]})}),e.jsx(el,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search contacts…"}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:"No contacts with email found."}),e.jsx(Jg,{children:i.map(oe=>e.jsxs(Zf,{value:`${oe.first_name} ${oe.last_name||""} ${oe.email}`,onSelect:()=>Y(oe),children:[e.jsx(Lr,{className:Mt("w-4 h-4 mr-2",(o==null?void 0:o.id)===oe.id?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium",children:[oe.first_name," ",oe.last_name||""]}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:oe.email})]})]},oe.id))})]})]})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"To email"}),e.jsx(ye,{type:"email",value:h,onChange:oe=>p(oe.target.value),placeholder:"client@example.com"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Subject"}),e.jsx(ye,{value:f,onChange:oe=>y(oe.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Message"}),e.jsx(Ms,{rows:10,value:_,onChange:oe=>v(oe.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[e.jsx("code",{children:"{{cma_link}}"})," will be replaced with a styled button linking to ",e.jsxs("code",{children:["cma.relevelup.com/",n.share_token]}),". Email opens are tracked and shown on the contact's Signals."]})]}),e.jsxs("div",{className:"rounded border bg-muted/40 p-3 text-sm flex items-center gap-2",children:[e.jsx(tr,{className:"w-4 h-4 text-muted-foreground"}),e.jsx("span",{className:"text-muted-foreground",children:"Public link:"}),e.jsx("a",{className:"text-primary underline truncate",href:`${lNe}/${n.share_token}`,target:"_blank",rel:"noreferrer",children:`${lNe}/${n.share_token}`})]})]}):e.jsx("div",{className:"p-4 rounded border bg-amber-50 text-amber-900 text-sm",children:"Connect Gmail or set up Amazon SES under Integrations to send CMAs by email."}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:ee,disabled:!Z,children:[j?e.jsx(rs,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(lr,{className:"w-4 h-4 mr-2"}),"Send CMA"]})]})]})})}function dWs({onCreated:s}){const[t,n]=N.useState(!1),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),h=PGs(),p=y_t(),{toast:f}=Fa(),[y,_]=N.useState([]),v=async()=>{var S;_([]);try{const A=await h.mutateAsync({address:r,city:i,state:o,zip:d});_(A.matches||[]),(S=A.matches)!=null&&S.length||f({title:"No MLS match",description:'Use "Create from manual entry" below.'})}catch(A){f({title:"Search failed",description:A.message,variant:"destructive"})}},j=async S=>{const A=await p.mutateAsync({subject:S});n(!1),s(A.id)},w=async()=>{if(!r||!i||!o){f({title:"Address, city, state required"});return}const S=await p.mutateAsync({subject:{address:r,city:i,state:o,zip:d}});n(!1),s(S.id)};return e.jsxs(_s,{open:t,onOpenChange:n,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"New CMA"]})}),e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsx(ws,{children:"Start a CMA"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(ye,{className:"md:col-span-2",placeholder:"Street address",value:r,onChange:S=>a(S.target.value)}),e.jsx(ye,{placeholder:"City",value:i,onChange:S=>l(S.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"ST",maxLength:2,value:o,onChange:S=>c(S.target.value.toUpperCase())}),e.jsx(ye,{placeholder:"ZIP",value:d,onChange:S=>u(S.target.value)})]})]}),e.jsxs(B,{onClick:v,disabled:!r||h.isPending,className:"w-full",children:[h.isPending?e.jsx(rs,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(gr,{className:"w-4 h-4 mr-2"}),"Find in MLS"]}),y.length>0&&e.jsxs("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[y.length," match(es) — pick the subject property:"]}),y.map((S,A)=>{var E;return e.jsxs("button",{onClick:()=>j(S),className:"w-full text-left p-3 border rounded hover:bg-accent transition",children:[e.jsx("div",{className:"font-medium",children:S.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[S.city,", ",S.state," ",S.zip," · ",S.bedrooms??"?"," bd / ",S.bathrooms??"?"," ba · ",((E=S.sqft)==null?void 0:E.toLocaleString())??"?"," sqft",S.mlsNumber?` · MLS# ${S.mlsNumber}`:""," · ",S.source_provider]})]},A)})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsxs(B,{variant:"outline",onClick:w,disabled:p.isPending,className:"w-full",children:[e.jsx(Or,{className:"w-4 h-4 mr-2"}),"Create from manual entry"]})})]})]})]})}function uWs(){const{data:s,isLoading:t}=TGs(),n=IGs(),r=Ln(),{toast:a}=Fa(),[i,l]=N.useState(null);return e.jsx(Cs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-6xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-6",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl md:text-3xl font-bold flex items-center gap-2",children:[e.jsx(br,{className:"w-7 h-7"})," CMAs"]}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Comparative Market Analyses — interactive, shareable, no static PDFs."})]}),e.jsx(dWs,{onCreated:o=>r(`/mission-control/cma/${o}`)})]}),t?e.jsx("p",{className:"text-muted-foreground",children:"Loading…"}):s!=null&&s.length?e.jsx("div",{className:"grid gap-3",children:s.map(o=>{var c,d,u;return e.jsx(fe,{className:"hover:shadow-md transition",children:e.jsxs(Ee,{className:"p-4 flex flex-wrap items-center gap-3 justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-[200px]",children:[e.jsx("div",{className:"font-semibold",children:o.title||((c=o.subject)==null?void 0:c.address)||"Untitled CMA"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[(d=o.subject)==null?void 0:d.city,", ",(u=o.subject)==null?void 0:u.state," · ",o.buyer_mode?"Buyer":"Seller"," ·"," ",e.jsx(Ue,{variant:o.status==="shared"?"default":"secondary",className:"ml-1",children:o.status})]}),o.price_likely?e.jsxs("div",{className:"text-sm mt-1",children:["Suggested: ",e.jsxs("span",{className:"font-medium",children:["$",o.price_likely.toLocaleString()]}),o.price_low&&o.price_high?e.jsxs("span",{className:"text-muted-foreground",children:[" · $",o.price_low.toLocaleString(),"–$",o.price_high.toLocaleString()]}):null]}):null]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>r(`/mission-control/cma/${o.id}`),children:"Open"}),o.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{const h=`https://cma.relevelup.com/${o.share_token}`;navigator.clipboard.writeText(h),a({title:"Share link copied"})},children:e.jsx(tr,{className:"w-4 h-4"})}),e.jsxs(B,{variant:"secondary",size:"sm",onClick:()=>l(o),children:[e.jsx(Gs,{className:"w-4 h-4 mr-1"}),"Send"]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{confirm("Delete this CMA?")&&n.mutate(o.id)},children:e.jsx(_n,{className:"w-4 h-4"})})]})]})},o.id)})}):e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 text-center text-muted-foreground",children:"No CMAs yet. Start one above."})}),i&&e.jsx(N_t,{open:!!i,onOpenChange:o=>!o&&l(null),cma:i})]})})}function hWs(s){return s?/Closed|Sold/i.test(s)?"#16a34a":/Pending|Contingent|Under Contract/i.test(s)?"#f59e0b":/Active/i.test(s)?"#2563eb":"#64748b":"#64748b"}function wZe(s,t,n){const a=n*1.60934,i=[],l=a/(111.32*Math.cos(s*Math.PI/180)),o=a/110.574;for(let c=0;c<64;c++){const d=c/64*(2*Math.PI);i.push([t+l*Math.cos(d),s+o*Math.sin(d)])}return i.push(i[0]),{type:"Feature",geometry:{type:"Polygon",coordinates:[i]},properties:{}}}function mWs({subject:s,comps:t,radiusMiles:n,onMarkerClick:r}){const a=N.useRef(null),i=N.useRef(null),l=N.useRef([]),[o,c]=N.useState(null);N.useEffect(()=>{let u=!1;return(async()=>{const{data:h}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();!u&&(h!=null&&h.value)&&c(h.value)})(),()=>{u=!0}},[]);const d=N.useMemo(()=>{const u=Number(s==null?void 0:s.latitude),h=Number(s==null?void 0:s.longitude);return!Number.isFinite(u)||!Number.isFinite(h)?null:{lat:u,lng:h}},[s==null?void 0:s.latitude,s==null?void 0:s.longitude]);return N.useEffect(()=>{if(!o||!a.current||i.current||!d)return;ul.accessToken=o;const u=new ul.Map({container:a.current,style:"mapbox://styles/mapbox/light-v11",center:[d.lng,d.lat],zoom:12});return u.addControl(new ul.NavigationControl({showCompass:!1}),"top-right"),u.on("load",()=>{u.addSource("radius",{type:"geojson",data:wZe(d.lat,d.lng,n)}),u.addLayer({id:"radius-fill",type:"fill",source:"radius",paint:{"fill-color":"#2563eb","fill-opacity":.08}}),u.addLayer({id:"radius-line",type:"line",source:"radius",paint:{"line-color":"#2563eb","line-width":2,"line-dasharray":[2,2],"line-opacity":.5}})}),i.current=u,()=>{u.remove(),i.current=null}},[o,d]),N.useEffect(()=>{const u=i.current;if(!u||!d)return;const h=()=>{const p=u.getSource("radius");p&&p.setData(wZe(d.lat,d.lng,n))};u.isStyleLoaded()?h():u.once("load",h)},[n,d]),N.useEffect(()=>{const u=i.current;if(!u||!d)return;l.current.forEach(v=>v.remove()),l.current=[];const h=document.createElement("div");h.style.cssText=` width: 28px; height: 28px; border-radius: 50%; background: hsl(222 47% 11%); border: 3px solid white; box-shadow: 0 4px 12px rgba(0,0,0,0.3); display: flex; align-items: center; justify-content: center; color: white; font-size: 12px; font-weight: 700; `,h.textContent="★";const p=new ul.Marker({element:h}).setLngLat([d.lng,d.lat]).setPopup(new ul.Popup({offset:18}).setHTML(`Subject
${s.address??""}`)).addTo(u);l.current.push(p);const f=new ul.LngLatBounds;f.extend([d.lng,d.lat]),t.forEach((v,j)=>{const w=Number(v.latitude),S=Number(v.longitude);if(!Number.isFinite(w)||!Number.isFinite(S))return;const A=hWs(v.status),E=document.createElement("div");E.style.cssText="width:22px;height:22px;";const O=document.createElement("div");O.style.cssText=` width: 22px; height: 22px; border-radius: 50%; background: ${A}; border: 2px solid white; box-shadow: 0 2px 6px rgba(0,0,0,0.25); cursor: pointer; opacity: ${v.selected===!1?.4:1}; transition: transform 0.15s; transform-origin: center; `,O.onmouseenter=()=>{O.style.transform="scale(1.25)"},O.onmouseleave=()=>{O.style.transform="scale(1)"},r&&(O.onclick=()=>r(j)),E.appendChild(O);const D=v.soldPrice||v.price,I=new ul.Popup({offset:14}).setHTML(`
${v.address??""}
${v.status??""}`+(D?` · $${D.toLocaleString()}`:"")+"
"),F=new ul.Marker({element:E}).setLngLat([S,w]).setPopup(I).addTo(u);l.current.push(F),f.extend([S,w])});const _=n*1.60934/110.574;f.extend([d.lng,d.lat+_]),f.extend([d.lng,d.lat-_]);try{u.fitBounds(f,{padding:60,maxZoom:14,duration:600})}catch{}},[t,d,n,s.address,r]),d?e.jsxs("div",{className:"relative w-full h-[420px] rounded-xl overflow-hidden border shadow-sm",children:[e.jsx("div",{ref:a,className:"absolute inset-0"}),!o&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-muted/40 text-sm text-muted-foreground",children:"Loading map…"}),e.jsxs("div",{className:"absolute bottom-3 left-3 bg-background/95 backdrop-blur rounded-lg shadow-md border px-3 py-2 text-xs space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"hsl(222 47% 11%)"}}),"Subject"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#2563eb"}}),"Active"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#f59e0b"}}),"Pending"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"inline-block w-3 h-3 rounded-full",style:{background:"#16a34a"}}),"Closed"]})]})]}):e.jsx("div",{className:"w-full h-[420px] rounded-xl border bg-muted/30 flex items-center justify-center text-sm text-muted-foreground",children:"Subject property has no coordinates — map unavailable."})}let wg=null;function pWs(){if(wg)return wg;try{const s=document.createElement("canvas"),t=s.getContext("webgl2")||s.getContext("webgl");if(!t)return wg={canRunVirtualBg:!1,reason:"WebGL is not supported on this device"},wg;const n=t.getExtension("WEBGL_debug_renderer_info"),r=n?t.getParameter(n.UNMASKED_RENDERER_WEBGL):"Unknown",a=["swiftshader","llvmpipe","software","microsoft basic render"],i=(r||"").toLowerCase();if(a.some(c=>i.includes(c)))return wg={canRunVirtualBg:!1,reason:"Your device uses a software renderer which may cause lag",renderer:r},wg;const o=performance;return o.memory&&o.memory.jsHeapSizeLimit<256*1024*1024?(wg={canRunVirtualBg:!1,reason:"Limited device memory detected",renderer:r},wg):navigator.hardwareConcurrency&&navigator.hardwareConcurrency<2?(wg={canRunVirtualBg:!1,reason:"Single-core device detected — virtual backgrounds may cause lag",renderer:r},wg):(wg={canRunVirtualBg:!0,renderer:r},wg)}catch{return wg={canRunVirtualBg:!0},wg}}const fWs=[{type:"none",label:"Off"},{type:"blur",label:"Blur"}];function xWs({value:s,onChange:t,isLoading:n=!1,disabled:r=!1,className:a}){const i=N.useRef(null),[l,o]=N.useState(!1),[c]=N.useState(()=>pWs()),d=!c.canRunVirtualBg,{data:u=[],refetch:h}=dt({queryKey:["video-backgrounds"],queryFn:async()=>{const{data:{user:v}}=await q.auth.getUser();if(!v)return[];const{data:j,error:w}=await q.from("video_backgrounds").select("*").eq("is_active",!0).order("sort_order",{ascending:!0});return w?(console.error("Failed to load backgrounds:",w),[]):j||[]}}),p=u.map(v=>({type:"image",label:v.name,imageUrl:v.image_url,thumbnail:v.thumbnail_url||v.image_url})),f=[...fWs,...p],y=v=>v.type!==s.type?!1:v.type==="image"?v.imageUrl===s.imageUrl:!0,_=async v=>{var w;const j=(w=v.target.files)==null?void 0:w[0];if(j){if(!j.type.startsWith("image/")){ae.error("Please select an image file");return}if(j.size>5*1024*1024){ae.error("Image must be under 5MB");return}o(!0);try{const{data:{user:S}}=await q.auth.getUser();if(!S)throw new Error("Not authenticated");const A=j.name.split(".").pop()||"jpg",E=`${S.id}/${crypto.randomUUID()}.${A}`,{error:O}=await q.storage.from("video-backgrounds").upload(E,j,{contentType:j.type});if(O)throw O;const{data:D}=q.storage.from("video-backgrounds").getPublicUrl(E),I=D.publicUrl,{error:F}=await q.from("video_backgrounds").insert({name:j.name.replace(/\.[^.]+$/,""),image_url:I,thumbnail_url:I,category:"custom",is_stock:!1,user_id:S.id});if(F)throw F;await h(),t({type:"image",imageUrl:I,blurRadius:15}),ae.success("Background uploaded!")}catch(S){console.error("Upload error:",S),ae.error("Failed to upload background")}finally{o(!1),i.current&&(i.current.value="")}}};return e.jsxs("div",{className:Mt("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(ic,{className:"h-3 w-3 flex-shrink-0"}),e.jsx("span",{children:c.reason||"Virtual backgrounds may cause lag on this device"})]}),e.jsxs("div",{className:"flex items-center gap-2 overflow-x-auto py-2 px-1 scrollbar-none",children:[e.jsx("span",{className:"text-xs text-muted-foreground whitespace-nowrap mr-1 font-medium",children:"Background:"}),n&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(rs,{className:"h-3 w-3 animate-spin"}),e.jsx("span",{children:"Loading…"})]}),f.map((v,j)=>{const w=y(v);return e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({type:v.type,imageUrl:v.imageUrl,blurRadius:15}),className:Mt("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",w?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"opacity-50 cursor-not-allowed"),children:[e.jsxs("div",{className:"w-12 h-8 rounded flex items-center justify-center overflow-hidden bg-muted",children:[v.type==="none"&&e.jsx(WP,{className:"h-4 w-4 text-muted-foreground"}),v.type==="blur"&&e.jsx("div",{className:"w-full h-full bg-gradient-to-br from-primary/20 to-primary/40 flex items-center justify-center",children:e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Blur"})}),v.type==="image"&&v.thumbnail&&e.jsx("img",{src:v.thumbnail,alt:v.label,className:"w-full h-full object-cover"})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground truncate max-w-14",children:v.label})]},`${v.type}-${v.imageUrl||j}`)}),e.jsxs("button",{type:"button",disabled:r||l,onClick:()=>{var v;return(v=i.current)==null?void 0:v.click()},className:Mt("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 border-dashed p-1 transition-all","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30","border-muted-foreground/30 bg-muted/30",(r||l)&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:l?e.jsx(rs,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(Is,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l?"Uploading":"Custom"})]}),e.jsx("input",{ref:i,type:"file",accept:"image/*",className:"hidden",onChange:_}),e.jsxs("button",{type:"button",disabled:r,onClick:()=>t({...s,mirror:!s.mirror}),className:Mt("flex-shrink-0 flex flex-col items-center gap-0.5 rounded-lg border-2 p-1 transition-all ml-1","hover:border-primary/50 focus:outline-none focus:ring-2 focus:ring-primary/30",s.mirror?"border-primary bg-primary/10":"border-transparent bg-muted/50",r&&"opacity-50 cursor-not-allowed"),children:[e.jsx("div",{className:"w-12 h-8 rounded flex items-center justify-center",children:e.jsx(W7,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Mirror"})]})]})]})}var sD=typeof self<"u"?self:{};function k_t(s,t){e:{for(var n=["CLOSURE_FLAGS"],r=sD,a=0;a>6|192;else{if(t>=55296&&t<=57343){if(t<=56319&&a=56320&&i<=57343){t=1024*(t-55296)+i-56320+65536,r[n++]=t>>18|240,r[n++]=t>>12&63|128,r[n++]=t>>6&63|128,r[n++]=63&t|128;continue}a--}t=65533}r[n++]=t>>12|224,r[n++]=t>>6&63|128}r[n++]=63&t|128}}s=n===r.length?r:r.subarray(0,n)}return s}function C_t(s){sD.setTimeout(()=>{throw s},0)}var R5e,bWs=k_t(610401301,!1),NZe=k_t(748402147,!0);function kZe(){var s=sD.navigator;return s&&(s=s.userAgent)?s:""}const SZe=sD.navigator;function y1e(s){return y1e[" "](s),s}R5e=SZe&&SZe.userAgentData||null,y1e[" "]=function(){};const T_t={};let f7=null;function _Ws(s){const t=s.length;let n=3*t/4;n%3?n=Math.floor(n):"=.".indexOf(s[t-1])!=-1&&(n="=.".indexOf(s[t-2])!=-1?n-2:n-1);const r=new Uint8Array(n);let a=0;return function(i,l){function o(d){for(;c>4),h!=64&&(l(u<<4&240|h>>2),p!=64&&l(h<<6&192|p))}}(s,function(i){r[a++]=i}),a!==n?r.subarray(0,a):r}function E_t(){if(!f7){f7={};var s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789".split(""),t=["+/=","+/","-_=","-_.","-_"];for(let n=0;n<5;n++){const r=s.concat(t[n].split(""));T_t[n]=r;for(let a=0;a0)&&(kZe().indexOf("Trident")!=-1||kZe().indexOf("MSIE")!=-1))&&typeof btoa=="function";const CZe=/[-_.]/g,jWs={"-":"+",_:"/",".":"="};function NWs(s){return jWs[s]||""}function M_t(s){if(!A_t)return _Ws(s);s=CZe.test(s)?s.replace(CZe,NWs):s,s=atob(s);const t=new Uint8Array(s.length);for(let n=0;n=t||(n[s]=r+1,P_t(s=Error(),"incident"),C_t(s))}}function gR(){return typeof BigInt=="function"}var yR=typeof Symbol=="function"&&typeof Symbol()=="symbol";function Xw(s,t,n=!1){return typeof Symbol=="function"&&typeof Symbol()=="symbol"?n&&Symbol.for&&s?Symbol.for(s):s!=null?Symbol(s):Symbol():t}var CWs=Xw("jas",void 0,!0),TZe=Xw(void 0,"0di"),TF=Xw(void 0,"1oa"),my=Xw(void 0,Symbol()),TWs=Xw(void 0,"0ub"),EWs=Xw(void 0,"0ubs"),F5e=Xw(void 0,"0ubsb"),AWs=Xw(void 0,"0actk"),aD=Xw("m_m","Pa",!0),EZe=Xw();const L_t={Ga:{value:0,configurable:!0,writable:!0,enumerable:!1}},D_t=Object.defineProperties,yi=yR?CWs:"Ga";var n6;const AZe=[];function MU(s,t){yR||yi in s||D_t(s,L_t),s[yi]|=t}function Hm(s,t){yR||yi in s||D_t(s,L_t),s[yi]=t}function IU(s){return MU(s,34),s}function l$(s){return MU(s,8192),s}Hm(AZe,7),n6=Object.freeze(AZe);var iD={};function gy(s,t){return t===void 0?s.h!==MM&&!!(2&(0|s.v[yi])):!!(2&t)&&s.h!==MM}const MM={};function eLe(s,t){if(s!=null){if(typeof s=="string")s=s?new Sw(s,nD):AM();else if(s.constructor!==Sw)if(XPe(s))s=s.length?new Sw(new Uint8Array(s),nD):AM();else{if(!t)throw Error();s=void 0}}return s}class MZe{constructor(t,n,r){this.g=t,this.h=n,this.l=r}next(){const t=this.g.next();return t.done||(t.value=this.h.call(this.l,t.value)),t}[Symbol.iterator](){return this}}var MWs=Object.freeze({});function R_t(s,t,n){const r=128&t?0:-1,a=s.length;var i;(i=!!a)&&(i=(i=s[a-1])!=null&&typeof i=="object"&&i.constructor===Object);const l=a+(i?-1:0);for(t=128&t?1:0;ttypeof s=="number"),IZe=v1e(s=>typeof s=="string"),PWs=v1e(s=>typeof s=="boolean"),b1e=typeof sD.BigInt=="function"&&typeof sD.BigInt(0)=="bigint";function py(s){var t=s;if(IZe(t)){if(!/^\s*(?:-?[1-9]\d*|0)?\s*$/.test(t))throw Error(String(t))}else if(IWs(t)&&!Number.isSafeInteger(t))throw Error(String(t));return b1e?BigInt(s):s=PWs(s)?s?"1":"0":IZe(s)?s.trim()||"0":String(s)}var z5e=v1e(s=>b1e?s>=DWs&&s<=OWs:s[0]==="-"?PZe(s,LWs):PZe(s,RWs));const LWs=Number.MIN_SAFE_INTEGER.toString(),DWs=b1e?BigInt(Number.MIN_SAFE_INTEGER):void 0,RWs=Number.MAX_SAFE_INTEGER.toString(),OWs=b1e?BigInt(Number.MAX_SAFE_INTEGER):void 0;function PZe(s,t){if(s.length>t.length)return!1;if(s.lengtha)return!1;if(r>>0;Nu=t,Yh=(s-t)/4294967296>>>0}function oD(s){if(s<0){LZe(-s);const[t,n]=nLe(Nu,Yh);Nu=t>>>0,Yh=n>>>0}else LZe(s)}function tLe(s){const t=zWs||(zWs=new DataView(new ArrayBuffer(8)));t.setFloat32(0,+s,!0),Yh=0,Nu=t.getUint32(0,!0)}function F_t(s,t){const n=4294967296*t+(s>>>0);return Number.isSafeInteger(n)?n:c$(s,t)}function BWs(s,t){return py(gR()?BigInt.asUintN(64,(BigInt(t>>>0)<>>0)):c$(s,t))}function z_t(s,t){return gR()?py(BigInt.asIntN(64,(BigInt.asUintN(32,BigInt(t))<>>=0,(t>>>=0)<=2097151)var n=""+(4294967296*t+s);else gR()?n=""+(BigInt(t)<>>24|t<<8))+6710656*(t=t>>16&65535),n+=8147497*t,t*=2,s>=1e7&&(n+=s/1e7>>>0,s%=1e7),n>=1e7&&(t+=n/1e7>>>0,n%=1e7),n=t+DZe(n)+DZe(s));return n}function DZe(s){return s=String(s),"0000000".slice(s.length)+s}function sLe(s,t){if(2147483648&t)if(gR())s=""+(BigInt(0|t)<>>0));else{const[n,r]=nLe(s,t);s="-"+c$(n,r)}else s=c$(s,t);return s}function _1e(s){if(s.length<16)oD(Number(s));else if(gR())s=BigInt(s),Nu=Number(s&BigInt(4294967295))>>>0,Yh=Number(s>>BigInt(32)&BigInt(4294967295));else{const t=+(s[0]==="-");Yh=Nu=0;const n=s.length;for(let r=t,a=(n-t)%6+t;a<=n;r=a,a+=6){const i=Number(s.slice(r,a));Yh*=1e6,Nu=1e6*Nu+i,Nu>=4294967296&&(Yh+=Math.trunc(Nu/4294967296),Yh>>>=0,Nu>>>=0)}if(t){const[r,a]=nLe(Nu,Yh);Nu=r,Yh=a}}}function nLe(s,t){return t=~t,s?s=1+~s:t+=1,[s,t]}function _b(s){return Array.prototype.slice.call(s)}const PU=typeof BigInt=="function"?BigInt.asIntN:void 0,$Ws=typeof BigInt=="function"?BigInt.asUintN:void 0,IM=Number.isSafeInteger,w1e=Number.isFinite,lD=Math.trunc,UWs=py(0);function x7(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 sw(s){return s==null||typeof s=="number"?s:s==="NaN"||s==="Infinity"||s==="-Infinity"?Number(s):void 0}function d$(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 B_t(s){return s==null||typeof s=="boolean"?s:typeof s=="number"?!!s:void 0}const qWs=/^-?([1-9][0-9]*|0)(\.[0-9]+)?$/;function LU(s){switch(typeof s){case"bigint":return!0;case"number":return w1e(s);case"string":return qWs.test(s);default:return!1}}function bR(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return w1e(s)?0|s:void 0}function $_t(s){if(s==null)return s;if(typeof s=="string"&&s)s=+s;else if(typeof s!="number")return;return w1e(s)?s>>>0:void 0}function U_t(s){const t=s.length;return(s[0]==="-"?t<20||t===20&&s<="-9223372036854775808":t<19||t===19&&s<="9223372036854775807")?s:(_1e(s),sLe(Nu,Yh))}function rLe(s){if(s=lD(s),!IM(s)){oD(s);var t=Nu,n=Yh;(s=2147483648&n)&&(n=~n>>>0,(t=1+~t>>>0)==0&&(n=n+1>>>0)),s=typeof(t=F_t(t,n))=="number"?s?-t:t:s?"-"+t:t}return s}function q_t(s){var t=lD(Number(s));return IM(t)?String(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),U_t(s))}function V_t(s){var t=lD(Number(s));return IM(t)?py(t):((t=s.indexOf("."))!==-1&&(s=s.substring(0,t)),gR()?py(PU(64,BigInt(s))):py(U_t(s)))}function H_t(s){return IM(s)?s=py(rLe(s)):(s=lD(s),IM(s)?s=String(s):(oD(s),s=sLe(Nu,Yh)),s=py(s)),s}function Nge(s){const t=typeof s;return s==null?s:t==="bigint"?py(PU(64,s)):LU(s)?t==="string"?V_t(s):H_t(s):void 0}function G_t(s){if(typeof s!="string")throw Error();return s}function DU(s){if(s!=null&&typeof s!="string")throw Error();return s}function vf(s){return s==null||typeof s=="string"?s:void 0}function aLe(s,t,n,r){return s!=null&&s[aD]===iD?s:Array.isArray(s)?((r=(n=0|s[yi])|32&r|2&r)!==n&&Hm(s,r),new t(s)):(n?2&r?((s=t[TZe])||(IU((s=new t).v),s=t[TZe]=s),t=s):t=new t:t=void 0,t)}function VWs(s,t,n){if(t)e:{if(!LU(t=s))throw O5e("int64");switch(typeof t){case"string":t=V_t(t);break e;case"bigint":t=py(PU(64,t));break e;default:t=H_t(t)}}else t=Nge(s);return(s=t)==null?n?UWs:void 0:s}const HWs={};let GWs=function(){try{return y1e(new class extends Map{constructor(){super()}}),!1}catch{return!0}}();class dNe{constructor(){this.g=new Map}get(t){return this.g.get(t)}set(t,n){return this.g.set(t,n),this.size=this.g.size,this}delete(t){return t=this.g.delete(t),this.size=this.g.size,t}clear(){this.g.clear(),this.size=this.g.size}has(t){return this.g.has(t)}entries(){return this.g.entries()}keys(){return this.g.keys()}values(){return this.g.values()}forEach(t,n){return this.g.forEach(t,n)}[Symbol.iterator](){return this.entries()}}const WWs=GWs?(Object.setPrototypeOf(dNe.prototype,Map.prototype),Object.defineProperties(dNe.prototype,{size:{value:0,configurable:!0,enumerable:!0,writable:!0}}),dNe):class extends Map{constructor(){super()}};function RZe(s){return s}function uNe(s){if(2&s.J)throw Error("Cannot mutate an immutable Map")}var mN=class extends WWs{constructor(s,t,n=RZe,r=RZe){super(),this.J=0|s[yi],this.K=t,this.S=n,this.fa=this.K?KWs:r;for(let a=0;a{s.call(t,a.get(r),r,a)}):super.forEach(s,t)}set(s,t){return uNe(this),(s=this.S(s,!0,!1))==null?this:t==null?(super.delete(s),this):super.set(s,this.fa(t,!0,!0,this.K,!1,this.J))}Ma(s){const t=this.S(s[0],!1,!0);s=s[1],s=this.K?s===void 0?null:s:this.fa(s,!1,!0,void 0,!1,this.J),super.set(t,s)}has(s){return super.has(this.S(s,!1,!1))}get(s){s=this.S(s,!1,!1);const t=super.get(s);if(t!==void 0){var n=this.K;return n?((n=this.fa(t,!1,!0,n,this.ra,this.J))!==t&&super.set(s,n),n):t}}[Symbol.iterator](){return this.entries()}};function KWs(s,t,n,r,a,i){return s=aLe(s,r,n,i),a&&(s=oLe(s)),s}function YWs(s){return[s,this.get(s)]}let ZWs;function OZe(){return ZWs||(ZWs=new mN(IU([]),void 0,void 0,void 0,HWs))}function j1e(s){return my?s[my]:void 0}function kge(s,t){for(const n in s)!isNaN(n)&&t(s,+n,s[n])}mN.prototype.toJSON=void 0;var B5e=class{};const QWs={Ka:!0};function XWs(s,t){t<100||rD(EWs,1)}function N1e(s,t,n,r){const a=r!==void 0;r=!!r;var i,l=my;!a&&yR&&l&&(i=s[l])&&kge(i,XWs),l=[];var o=s.length;let c;i=4294967295;let d=!1;const u=!!(64&t),h=u?128&t?0:-1:void 0;1&t||(c=o&&s[o-1],c!=null&&typeof c=="object"&&c.constructor===Object?i=--o:c=void 0,!u||128&t||a||(d=!0,i=i-h+h)),t=void 0;for(var p=0;p=i){const y=p-h;(t??(t={}))[y]=f}else l[p]=f}if(c)for(let f in c){if((o=c[f])==null||(o=n(o,r))==null)continue;let y;p=+f,u&&!Number.isNaN(p)&&(y=p+h){y[v]=_b(j)}),y.da=f.da,y}(s)),l}function JWs(s){return s[0]=u$(s[0]),s[1]=u$(s[1]),s}function u$(s){switch(typeof s){case"number":return Number.isFinite(s)?s:""+s;case"bigint":return z5e(s)?Number(s):""+s;case"boolean":return s?1:0;case"object":if(Array.isArray(s)){var t=0|s[yi];return s.length===0&&1&t?void 0:N1e(s,t,u$)}if(s!=null&&s[aD]===iD)return W_t(s);if(s instanceof Sw){if((t=s.g)==null)s="";else if(typeof t=="string")s=t;else{if(A_t){for(var n="",r=0,a=t.length-10240;r>2];i=n[(3&i)<<4|l>>4],l=n[(15&l)<<2|o>>6],o=n[63&o],r[u++]=c+i+l+o}switch(c=0,o=a,t.length-d){case 2:o=n[(15&(c=t[d+1]))<<2]||a;case 1:t=t[d],r[u]=n[t>>2]+n[(3&t)<<4|c>>4]+o+a}t=r.join("")}s=s.g=t}return s}return s instanceof mN?s=s.size!==0?s.V(JWs):void 0:void 0}return s}let eKs,tKs;function W_t(s){return N1e(s=s.v,0|s[yi],u$)}function YA(s,t){return K_t(s,t[0],t[1])}function K_t(s,t,n,r=0){if(s==null){var a=32;n?(s=[n],a|=128):s=[],t&&(a=-16760833&a|(1023&t)<<14)}else{if(!Array.isArray(s))throw Error("narr");if(a=0|s[yi],NZe&&1&a)throw Error("rfarr");if(2048&a&&!(2&a)&&function(){if(NZe)throw Error("carr");rD(AWs,5)}(),256&a)throw Error("farr");if(64&a)return(a|r)!==a&&Hm(s,a|r),s;if(n&&(a|=128,n!==s[0]))throw Error("mid");e:{a|=64;var i=(n=s).length;if(i){var l=i-1;const c=n[l];if(c!=null&&typeof c=="object"&&c.constructor===Object){if((l-=t=128&a?0:-1)>=1024)throw Error("pvtlmt");for(var o in c)(i=+o)1024)throw Error("spvt");a=-16760833&a|(1023&o)<<14}}}return Hm(s,64|a|r),s}function sKs(s,t){if(typeof s!="object")return s;if(Array.isArray(s)){var n=0|s[yi];return s.length===0&&1&n?void 0:FZe(s,n,t)}if(s!=null&&s[aD]===iD)return zZe(s);if(s instanceof mN){if(2&(t=s.J))return s;if(!s.size)return;if(n=IU(s.V()),s.K)for(s=0;s=i)if(l=s[i],l!=null&&typeof l=="object"&&l.constructor===Object)n=l[t],o=!0;else{if(a!==i)return;n=l}else n=s[a];if(r&&n!=null){if((r=r(n))==null)return r;if(!Object.is(r,n))return o?l[t]=r:s[a]=r,r}return n}}function qc(s,t,n,r){jR(s),Um(s=s.v,0|s[yi],t,n,r)}function Um(s,t,n,r,a){const i=n+(a?0:-1);var l=s.length-1;if(l>=1+(a?0:-1)&&i>=l){const o=s[l];if(o!=null&&typeof o=="object"&&o.constructor===Object)return o[n]=r,t}return i<=l?(s[i]=r,t):(r!==void 0&&(n>=(l=(t??(t=0|s[yi]))>>14&1023||536870912)?r!=null&&(s[l+(a?0:-1)]={[n]:r}):s[i]=r),t)}function JE(){return MWs===void 0?2:4}function eA(s,t,n,r,a){let i=s.v,l=0|i[yi];r=gy(s,l)?1:r,a=!!a||r===3,r===2&&wR(s)&&(i=s.v,l=0|i[yi]);let o=(s=cLe(i,t))===n6?7:0|s[yi],c=dLe(o,l);var d=!(4&c);if(d){4&c&&(s=_b(s),o=0,c=QA(c,l),l=Um(i,l,t,s));let u=0,h=0;for(;u{const o=aLe(l,n,!1,t);return i=o!==l&&o!=null,o}))!=null)return i&&!gy(r)&&r6(s,t),r}function Kl(s,t,n,r){let a=s.v,i=0|a[yi];if((t=ewt(a,i,t,n,r))==null)return t;if(i=0|a[yi],!gy(s,i)){const l=oLe(t);l!==t&&(wR(s)&&(a=s.v,i=0|a[yi]),i=Um(a,i,n,t=l,r),r6(a,i))}return t}function twt(s,t,n,r,a,i,l,o){var c=gy(s,n);i=c?1:i,l=!!l||i===3,c=o&&!c,(i===2||c)&&wR(s)&&(n=0|(t=s.v)[yi]);var d=(s=cLe(t,a))===n6?7:0|s[yi],u=dLe(d,n);if(o=!(4&u)){var h=s,p=n;const f=!!(2&u);f&&(p|=2);let y=!f,_=!0,v=0,j=0;for(;v32)for(a|=(127&n)>>4,i=3;i<32&&128&n;i+=7)n=l[o++],a|=(127&n)<>>0,a>>>0);throw Error()}function gLe(s){let t=0,n=s.g;const r=n+10,a=s.h;for(;n>>0}function Cge(s){var t=s.h;const n=s.g;var r=t[n],a=t[n+1];const i=t[n+2];return t=t[n+3],XA(s,s.g+4),s=2*((a=(r<<0|a<<8|i<<16|t<<24)>>>0)>>31)+1,r=a>>>23&255,a&=8388607,r==255?a?NaN:s*(1/0):r==0?1401298464324817e-60*s*a:s*Math.pow(2,r-150)*(a+8388608)}function nKs(s){return A4(s)}function XA(s,t){if(s.g=t,t>s.l)throw Error()}function nwt(s,t){if(t<0)throw Error();const n=s.g;if((t=n+t)>s.l)throw Error();return s.g=t,n}function rwt(s,t){if(t==0)return AM();var n=nwt(s,t);return s.Y&&s.j?n=s.h.subarray(n,n+t):(s=s.h,n=n===(t=n+t)?new Uint8Array(0):FWs?s.slice(n,t):new Uint8Array(s.subarray(n,t))),n.length==0?AM():new Sw(n,nD)}var BZe=[];function awt(s,t,n,r){if(Tge.length){const a=Tge.pop();return a.o(r),a.g.init(s,t,n,r),a}return new rKs(s,t,n,r)}function iwt(s){s.g.clear(),s.l=-1,s.h=-1,Tge.length<100&&Tge.push(s)}function owt(s){var t=s.g;if(t.g==t.l)return!1;s.m=s.g.g;var n=zw(s.g);if(t=n>>>3,!((n&=7)>=0&&n<=5)||t<1)throw Error();return s.l=t,s.h=n,!0}function Hme(s){switch(s.h){case 0:s.h!=0?Hme(s):gLe(s.g);break;case 1:XA(s=s.g,s.g+8);break;case 2:if(s.h!=2)Hme(s);else{var t=zw(s.g);XA(s=s.g,s.g+t)}break;case 5:XA(s=s.g,s.g+4);break;case 3:for(t=s.l;;){if(!owt(s))throw Error();if(s.h==4){if(s.l!=t)throw Error();break}Hme(s)}break;default:throw Error()}}function RU(s,t,n){const r=s.g.l;var a=zw(s.g);let i=(a=s.g.g+a)-r;if(i<=0&&(s.g.l=a,n(t,s,void 0,void 0,void 0),i=a-s.g.g),i)throw Error();return s.g.g=a,s.g.l=r,t}function yLe(s){var t=zw(s.g),n=nwt(s=s.g,t);if(s=s.h,gWs){var r,a=s;(r=cNe)||(r=cNe=new TextDecoder("utf-8",{fatal:!0})),t=n+t,a=n===0&&t===a.length?a:a.subarray(n,t);try{var i=r.decode(a)}catch(o){if(cG===void 0){try{r.decode(new Uint8Array([128]))}catch{}try{r.decode(new Uint8Array([97])),cG=!0}catch{cG=!1}}throw!cG&&(cNe=void 0),o}}else{t=(i=n)+t,n=[];let o,c=null;for(;i=t?l3():(o=s[i++],l<194||(192&o)!=128?(i--,l3()):n.push((31&l)<<6|63&o)):l<240?i>=t-1?l3():(o=s[i++],(192&o)!=128||l===224&&o<160||l===237&&o>=160||(192&(r=s[i++]))!=128?(i--,l3()):n.push((15&l)<<12|(63&o)<<6|63&r)):l<=244?i>=t-2?l3():(o=s[i++],(192&o)!=128||o-144+(l<<28)>>30||(192&(r=s[i++]))!=128||(192&(a=s[i++]))!=128?(i--,l3()):(l=(7&l)<<18|(63&o)<<12|(63&r)<<6|63&a,l-=65536,n.push(55296+(l>>10&1023),56320+(1023&l)))):l3(),n.length>=8192&&(c=jZe(c,n),n.length=0)}i=jZe(c,n)}return i}function lwt(s){const t=zw(s.g);return rwt(s.g,t)}function S1e(s,t,n){var r=zw(s.g);for(r=s.g.g+r;s.g.g>>0,this.g=t>>>0}};let aKs;function UZe(s){return s?/^-?\d+$/.test(s)?(_1e(s),new U5e(Nu,Yh)):null:iKs||(iKs=new U5e(0,0))}var U5e=class{constructor(s,t){this.h=s>>>0,this.g=t>>>0}};let iKs;function OL(s,t,n){for(;n>0||t>127;)s.g.push(127&t|128),t=(t>>>7|n<<25)>>>0,n>>>=7;s.g.push(t)}function kR(s,t){for(;t>127;)s.g.push(127&t|128),t>>>=7;s.g.push(t)}function C1e(s,t){if(t>=0)kR(s,t);else{for(let n=0;n<9;n++)s.g.push(127&t|128),t>>=7;s.g.push(1)}}function vLe(s){var t=Nu;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 cD(s,t){t.length!==0&&(s.l.push(t),s.h+=t.length)}function Jv(s,t,n){kR(s.g,8*t+n)}function bLe(s,t){return Jv(s,t,2),t=s.g.end(),cD(s,t),t.push(s.h),t}function _Le(s,t){var n=t.pop();for(n=s.h+s.g.length()-n;n>127;)t.push(127&n|128),n>>>=7,s.h++;t.push(n),s.h++}function T1e(s,t,n){Jv(s,t,2),kR(s.g,n.length),cD(s,s.g.end()),cD(s,n)}function Ege(s,t,n,r){n!=null&&(t=bLe(s,t),r(n,s),_Le(s,t))}function Jw(){const s=class{constructor(){throw Error()}};return Object.setPrototypeOf(s,s.prototype),s}var wLe=Jw(),cwt=Jw(),jLe=Jw(),NLe=Jw(),kLe=Jw(),dwt=Jw(),oKs=Jw(),E1e=Jw(),uwt=Jw(),hwt=Jw();function ej(s,t,n){var r=s.v;my&&my in r&&(r=r[my])&&delete r[t.g],t.h?t.j(s,t.h,t.g,n,t.l):t.j(s,t.g,n,t.l)}var vi=class{constructor(s,t){this.v=K_t(s,t,void 0,2048)}toJSON(){return W_t(this)}j(){var a;var s=UKs,t=this.v,n=s.g,r=my;if(yR&&r&&((a=t[r])==null?void 0:a[n])!=null&&rD(TWs,3),t=s.g,EZe&&my&&EZe===void 0&&(r=(n=this.v)[my])&&(r=r.da))try{r(n,t,QWs)}catch(i){C_t(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[yi];return lLe(this,s,t)?iLe(this,s,!0):new this.constructor(_R(s,t,!1))}};vi.prototype[aD]=iD,vi.prototype.toString=function(){return this.v.toString()};var SR=class{constructor(s,t,n){this.g=s,this.h=t,s=wLe,this.l=!!s&&n===s||!1}};function A1e(s,t){return new SR(s,t,wLe)}function mwt(s,t,n,r,a){Ege(s,n,gwt(t,r),a)}const lKs=A1e(function(s,t,n,r,a){return s.h===2&&(RU(s,mLe(t,r,n),a),!0)},mwt),cKs=A1e(function(s,t,n,r,a){return s.h===2&&(RU(s,mLe(t,r,n),a),!0)},mwt);var M1e=Symbol(),I1e=Symbol(),q5e=Symbol(),qZe=Symbol(),VZe=Symbol();let pwt,fwt;function a6(s,t,n,r){var a=r[s];if(a)return a;(a={}).qa=r,a.T=function(h){switch(typeof h){case"boolean":return eKs||(eKs=[0,void 0,!0]);case"number":return h>0?void 0:h===0?tKs||(tKs=[0,void 0]):[-h,void 0];case"string":return[0,h];case"object":return h}}(r[0]);var i=r[1];let l=1;i&&i.constructor===Object&&(a.ba=i,typeof(i=r[++l])=="function"&&(a.ma=!0,pwt??(pwt=i),fwt??(fwt=r[l+1]),i=r[l+=2]));const o={};for(;i&&Array.isArray(i)&&i.length&&typeof i[0]=="number"&&i[0]>0;){for(var c=0;ca(i,l,o,r):a}function CLe(s,t,n,r,a){const i=n.g;let l,o;s[t]=(c,d,u)=>i(c,d,u,o||(o=a6(I1e,SLe,CLe,r).T),l||(l=TLe(r)),a)}function TLe(s){let t=s[q5e];if(t!=null)return t;const n=a6(I1e,SLe,CLe,s);return t=n.ma?(r,a)=>pwt(r,a,n):(r,a)=>{for(;owt(a)&&a.h!=4;){var i=a.l,l=n[i];if(l==null){var o=n.ba;o&&(o=o[i])&&(o=uKs(o))!=null&&(l=n[i]=o)}if(l==null||!l(a,r,i)){if(l=(o=a).m,Hme(o),o.ha)var c=void 0;else c=o.g.g-l,o.g.g=l,c=rwt(o.g,c);l=void 0,o=r,c&&((l=o[my]??(o[my]=new B5e))[i]??(l[i]=[])).push(c)}}return(r=j1e(r))&&(r.da=n.qa[VZe]),!0},s[q5e]=t,s[VZe]=dKs.bind(s),t}function dKs(s,t,n,r){var a=this[I1e];const i=this[q5e],l=YA(void 0,a.T),o=j1e(s);if(o){var c=!1,d=a.ba;if(d){if(a=(u,h,p)=>{if(p.length!==0)if(d[h])for(const f of p){u=awt(f);try{c=!0,i(l,u)}finally{iwt(u)}}else r==null||r(s,h,p)},t==null)kge(o,a);else if(o!=null){const u=o[t];u&&a(o,t,u)}if(c){let u=0|s[yi];if(2&u&&2048&u&&!(n!=null&&n.Ka))throw Error();const h=vR(u),p=(f,y)=>{if(pN(s,f,h)!=null){if((n==null?void 0:n.Qa)===1)return;throw Error()}y!=null&&(u=Um(s,u,f,y,h)),delete o[f]};t==null?R_t(l,0|l[yi],(f,y)=>{p(f,y)}):p(t,pN(l,t,h))}}}}function uKs(s){const t=(s=xwt(s))[0].g;if(s=s[1]){const n=TLe(s),r=a6(I1e,SLe,CLe,s).T;return(a,i,l)=>t(a,i,l,r,n)}return t}function P1e(s,t,n){s[t]=n.h}function L1e(s,t,n,r){let a,i;const l=n.h;s[t]=(o,c,d)=>l(o,c,d,i||(i=a6(M1e,P1e,L1e,r).T),a||(a=ywt(r)))}function ywt(s){let t=s[qZe];if(!t){const n=a6(M1e,P1e,L1e,s);t=(r,a)=>vwt(r,a,n),s[qZe]=t}return t}function vwt(s,t,n){R_t(s,0|s[yi],(r,a)=>{if(a!=null){var i=function(l,o){var c=l[o];if(c)return c;if((c=l.ba)&&(c=c[o])){var d=(c=xwt(c))[0].h;if(c=c[1]){const u=ywt(c),h=a6(M1e,P1e,L1e,c).T;c=l.ma?fwt(h,u):(p,f,y)=>d(p,f,y,h,u)}else c=d;return l[o]=c}}(n,r);i?i(t,a,r):r<500||rD(F5e,3)}}),(s=j1e(s))&&kge(s,(r,a,i)=>{for(cD(t,t.g.end()),r=0;r{Ege(s,n,YA([l,i],r),a)});else if(Array.isArray(t)){for(let i=0;i>BigInt(32))),OL(s.g,n.h,n.g);break;default:n=UZe(t),OL(s.g,n.h,n.g)}}function wwt(s,t,n){(t=bR(t))!=null&&t!=null&&(Jv(s,n,0),C1e(s.g,t))}function jwt(s,t,n){(t=B_t(t))!=null&&(Jv(s,n,0),s.g.g.push(t?1:0))}function Nwt(s,t,n){(t=vf(t))!=null&&T1e(s,n,S_t(t))}function kwt(s,t,n,r,a){Ege(s,n,gwt(t,r),a)}function Swt(s,t,n){(t=t==null||typeof t=="string"||t instanceof Sw?t:void 0)!=null&&T1e(s,n,fLe(t,!0).buffer)}function Cwt(s,t,n){(t=$_t(t))!=null&&t!=null&&(Jv(s,n,0),kR(s.g,t))}function Twt(s,t,n){return(s.h===5||s.h===2)&&(t=NR(t,0|t[yi],n),s.h==2?S1e(s,Cge,t):t.push(Cge(s.g)),!0)}var Jh=cx(function(s,t,n){return s.h===5&&(dx(t,n,Cge(s.g)),!0)},bwt,E1e),pKs=TR(Twt,function(s,t,n){if((t=CR(sw,t))!=null)for(let l=0;l=0?r=String(a):((a=r.indexOf("."))!==-1&&(r=r.substring(0,a)),(a=r[0]!=="-"&&((a=r.length)<20||a===20&&r<="18446744073709551615"))||(_1e(r),r=c$(Nu,Yh))),r;if(a==="number")return(r=lD(r))>=0&&IM(r)||(oD(r),r=F_t(Nu,Yh)),r}}(t),t!=null&&(typeof t=="string"&&$Ze(t),t!=null))switch(Jv(s,n,0),typeof t){case"number":s=s.g,oD(t),OL(s,Nu,Yh);break;case"bigint":n=BigInt.asUintN(64,t),n=new $5e(Number(n&BigInt(4294967295)),Number(n>>BigInt(32))),OL(s.g,n.h,n.g);break;default:n=$Ze(t),OL(s.g,n.h,n.g)}},oKs),Fm=cx(function(s,t,n){return s.h===0&&(dx(t,n,A4(s.g)),!0)},wwt,NLe),OU=TR(function(s,t,n){return(s.h===0||s.h===2)&&(t=NR(t,0|t[yi],n),s.h==2?S1e(s,A4,t):t.push(A4(s.g)),!0)},function(s,t,n){if((t=CR(bR,t))!=null&&t.length){n=bLe(s,n);for(let r=0;r{{const i={ea:!0};r&&Object.assign(i,r),n=awt(n,void 0,void 0,i);try{const l=new s,o=l.v;TLe(t)(o,n);var a=l}finally{iwt(n)}}return a}}function D1e(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}}}};vwt(this.v,t,a6(M1e,P1e,L1e,s)),cD(t,t.g.end());const n=new Uint8Array(t.h),r=t.l,a=r.length;let i=0;for(let l=0;la;n=WZe.createPolicy("goog#html",{createHTML:r,createScript:r,createScriptURL:r})}catch{}return n}()),s=(t=pNe)?t.createScriptURL(s):s,new class{constructor(n){this.g=n}toString(){return this.g+""}}(s)}function dG(s,...t){if(t.length===0)return KZe(s[0]);let n=s[0];for(let r=0;r({index:Mv(r,1)??0??-1,score:_h(r,2)??0,categoryName:vf(Eu(r,3))??""??"",displayName:vf(Eu(r,4))??""??""})),headIndex:t,headName:n}}function GKs(s){const t={classifications:fN(s,CKs,1).map(n=>{var r;return OLe(((r=Kl(n,Owt,4))==null?void 0:r.g())??[],Mv(n,2)??0,vf(Eu(n,3))??"")})};return function(n){return n==null?n:typeof n=="bigint"?(z5e(n)?n=Number(n):(n=PU(64,n),n=z5e(n)?Number(n):String(n)),n):LU(n)?typeof n=="number"?rLe(n):q_t(n):void 0}(Eu(s,2,void 0,void 0,Nge))!=null&&(t.timestampMs=djt(Eu(s,2,void 0,void 0,Nge)??Y_t)),t}function ujt(s){var l,o;var t=eA(s,3,sw,JE()),n=eA(s,2,bR,JE()),r=eA(s,1,vf,JE()),a=eA(s,9,vf,JE());const i={categories:[],keypoints:[]};for(let c=0;ct>127?t-256:t)}function iQe(s,t){if(s.length!==t.length)throw Error(`Cannot compute cosine similarity between embeddings of different sizes (${s.length} vs. ${t.length}).`);let n=0,r=0,a=0;for(let i=0;i=1&&Number(s[1])>=17))}async function oQe(s){if(typeof importScripts!="function"){const t=document.createElement("script");return t.src=s.toString(),t.crossOrigin="anonymous",new Promise((n,r)=>{t.addEventListener("load",()=>{n()},!1),t.addEventListener("error",a=>{r(a)},!1),document.body.appendChild(t)})}try{importScripts(s.toString())}catch(t){if(!(t instanceof TypeError))throw t;await self.import(s.toString())}}function pjt(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 wi(s,t,n){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target"),n(t=s.i.stringToNewUTF8(t)),s.i._free(t)}function lQe(s,t,n){if(!s.i.canvas)throw Error("No OpenGL canvas configured.");if(n?s.i._bindTextureToStream(n):s.i._bindTextureToCanvas(),!(n=s.i.canvas.getContext("webgl2")||s.i.canvas.getContext("webgl")))throw Error("Failed to obtain WebGL context from the provided canvas. `getContext()` should only be invoked with `webgl` or `webgl2`.");s.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!0),n.texImage2D(n.TEXTURE_2D,0,n.RGBA,n.RGBA,n.UNSIGNED_BYTE,t),s.i.gpuOriginForWebTexturesIsBottomLeft&&n.pixelStorei(n.UNPACK_FLIP_Y_WEBGL,!1);const[r,a]=pjt(t);return!s.l||r===s.i.canvas.width&&a===s.i.canvas.height||(s.i.canvas.width=r,s.i.canvas.height=a),[r,a]}function cQe(s,t,n){s.m||console.error("No wasm multistream support detected: ensure dependency inclusion of :gl_graph_runner_internal_multi_input target");const r=new Uint32Array(t.length);for(let a=0;a>2),n(t);for(const a of r)s.i._free(a);s.i._free(t)}function k_(s,t,n){s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=n}function kk(s,t,n){let r=[];s.i.simpleListeners=s.i.simpleListeners||{},s.i.simpleListeners[t]=(a,i,l)=>{i?(n(r,l),r=[]):r.push(a)}}aP.forVisionTasks=function(s,t=!1){return hG("vision",s??dG``,t)},aP.forTextTasks=function(s,t=!1){return hG("text",s??dG``,t)},aP.forGenAiTasks=function(s,t=!1){return hG("genai",s??dG``,t)},aP.forAudioTasks=function(s,t=!1){return hG("audio",s??dG``,t)},aP.isSimdSupported=function(s=!1){return hjt(s)};async function KKs(s,t,n,r){return s=await(async(a,i,l,o,c)=>{if(i&&await oQe(i),!self.ModuleFactory||l&&(await oQe(l),!self.ModuleFactory))throw Error("ModuleFactory not set.");return self.Module&&c&&((i=self.Module).locateFile=c.locateFile,c.mainScriptUrlOrBlob&&(i.mainScriptUrlOrBlob=c.mainScriptUrlOrBlob)),c=await self.ModuleFactory(self.Module||c),self.ModuleFactory=self.Module=void 0,new a(c,o)})(s,n.wasmLoaderPath,n.assetLoaderPath,t,{locateFile:a=>a.endsWith(".wasm")?n.wasmBinaryPath.toString():n.assetBinaryPath&&a.endsWith(".data")?n.assetBinaryPath.toString():a}),await s.o(r),s}function gNe(s,t){const n=Kl(s.baseOptions,Age,1)||new Age;typeof t=="string"?(qc(n,2,DU(t)),qc(n,1)):t instanceof Uint8Array&&(qc(n,1,eLe(t,!1)),qc(n,2)),Gi(s.baseOptions,0,1,n)}function dQe(s){try{const t=s.H.length;if(t===1)throw Error(s.H[0].message);if(t>1)throw Error("Encountered multiple errors: "+s.H.map(n=>n.message).join(", "))}finally{s.H=[]}}function ci(s,t){s.C=Math.max(s.C,t)}function z1e(s,t){s.B=new a0,yy(s.B,2,"PassThroughCalculator"),cu(s.B,"free_memory"),Pl(s.B,"free_memory_unused_out"),Du(t,"free_memory"),e1(t,s.B)}function dD(s,t){cu(s.B,t),Pl(s.B,t+"_unused_out")}function B1e(s){s.g.addBoolToStream(!0,"free_memory",s.C)}var K5e=class{constructor(s){this.g=s,this.H=[],this.C=0,this.g.setAutoRenderToScreen(!1)}l(s,t=!0){var n,r,a,i,l,o;if(t){const c=s.baseOptions||{};if((n=s.baseOptions)!=null&&n.modelAssetBuffer&&((r=s.baseOptions)!=null&&r.modelAssetPath))throw Error("Cannot set both baseOptions.modelAssetPath and baseOptions.modelAssetBuffer");if(!((a=Kl(this.baseOptions,Age,1))!=null&&a.g()||(i=Kl(this.baseOptions,Age,1))!=null&&i.l()||(l=s.baseOptions)!=null&&l.modelAssetBuffer||(o=s.baseOptions)!=null&&o.modelAssetPath))throw Error("Either baseOptions.modelAssetPath or baseOptions.modelAssetBuffer must be set");if(function(d,u){let h=Kl(d.baseOptions,tQe,3);if(!h){var p=h=new tQe,f=new YZe;vz(p,4,Gme,f)}"delegate"in u&&(u.delegate==="GPU"?(u=h,p=new bKs,vz(u,2,Gme,p)):(u=h,p=new YZe,vz(u,4,Gme,p))),Gi(d.baseOptions,0,3,h)}(this,c),c.modelAssetPath)return fetch(c.modelAssetPath.toString()).then(d=>{if(d.ok)return d.arrayBuffer();throw Error(`Failed to fetch model: ${c.modelAssetPath} (${d.status})`)}).then(d=>{try{this.g.i.FS_unlink("/model.dat")}catch{}this.g.i.FS_createDataFile("/","model.dat",new Uint8Array(d),!0,!1,!1),gNe(this,"/model.dat"),this.m(),this.L()});if(c.modelAssetBuffer instanceof Uint8Array)gNe(this,c.modelAssetBuffer);else if(c.modelAssetBuffer)return async function(d){const u=[];for(var h=0;;){const{done:p,value:f}=await d.read();if(p)break;u.push(f),h+=f.length}if(u.length===0)return new Uint8Array(0);if(u.length===1)return u[0];d=new Uint8Array(h),h=0;for(const p of u)d.set(p,h),h+=p.length;return d}(c.modelAssetBuffer).then(d=>{gNe(this,d),this.m(),this.L()})}return this.m(),this.L(),Promise.resolve()}L(){}ca(){let s;if(this.g.ca(t=>{s=_Ks(t)}),!s)throw Error("Failed to retrieve CalculatorGraphConfig");return s}setGraph(s,t){this.g.attachErrorListener((n,r)=>{this.H.push(Error(r))}),this.g.Ja(),this.g.setGraph(s,t),this.B=void 0,dQe(this)}finishProcessing(){this.g.finishProcessing(),dQe(this)}close(){this.B=void 0,this.g.closeGraph()}};function f4(s,t){if(!s)throw Error(`Unable to obtain required WebGL resource: ${t}`);return s}K5e.prototype.close=K5e.prototype.close;class YKs{constructor(t,n,r,a){this.g=t,this.h=n,this.m=r,this.l=a}bind(){this.g.bindVertexArray(this.h)}close(){this.g.deleteVertexArray(this.h),this.g.deleteBuffer(this.m),this.g.deleteBuffer(this.l)}}function uQe(s,t,n){const r=s.g;if(n=f4(r.createShader(n),"Failed to create WebGL shader"),r.shaderSource(n,t),r.compileShader(n),!r.getShaderParameter(n,r.COMPILE_STATUS))throw Error(`Could not compile WebGL shader: ${r.getShaderInfoLog(n)}`);return r.attachShader(s.h,n),n}function hQe(s,t){const n=s.g,r=f4(n.createVertexArray(),"Failed to create vertex array");n.bindVertexArray(r);const a=f4(n.createBuffer(),"Failed to create buffer");n.bindBuffer(n.ARRAY_BUFFER,a),n.enableVertexAttribArray(s.O),n.vertexAttribPointer(s.O,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array([-1,-1,-1,1,1,1,1,-1]),n.STATIC_DRAW);const i=f4(n.createBuffer(),"Failed to create buffer");return n.bindBuffer(n.ARRAY_BUFFER,i),n.enableVertexAttribArray(s.L),n.vertexAttribPointer(s.L,2,n.FLOAT,!1,0,0),n.bufferData(n.ARRAY_BUFFER,new Float32Array(t?[0,1,0,0,1,0,1,1]:[0,0,0,1,1,1,1,0]),n.STATIC_DRAW),n.bindBuffer(n.ARRAY_BUFFER,null),n.bindVertexArray(null),new YKs(n,r,a,i)}function FLe(s,t){if(s.g){if(t!==s.g)throw Error("Cannot change GL context once initialized")}else s.g=t}function ZKs(s,t,n,r){return FLe(s,t),s.h||(s.m(),s.D()),n?(s.u||(s.u=hQe(s,!0)),n=s.u):(s.A||(s.A=hQe(s,!1)),n=s.A),t.useProgram(s.h),n.bind(),s.l(),s=r(),n.g.bindVertexArray(null),s}function fjt(s,t,n){return FLe(s,t),s=f4(t.createTexture(),"Failed to create texture"),t.bindTexture(t.TEXTURE_2D,s),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_S,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_WRAP_T,t.CLAMP_TO_EDGE),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MIN_FILTER,n??t.LINEAR),t.texParameteri(t.TEXTURE_2D,t.TEXTURE_MAG_FILTER,n??t.LINEAR),t.bindTexture(t.TEXTURE_2D,null),s}function xjt(s,t,n){FLe(s,t),s.B||(s.B=f4(t.createFramebuffer(),"Failed to create framebuffe.")),t.bindFramebuffer(t.FRAMEBUFFER,s.B),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,n,0)}function QKs(s){var t;(t=s.g)==null||t.bindFramebuffer(s.g.FRAMEBUFFER,null)}var gjt=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=f4(s.createProgram(),"Failed to create WebGL program"),this.X=uQe(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=uQe(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 A2(s,t){switch(t){case 0:return s.g.find(n=>n instanceof Uint8Array);case 1:return s.g.find(n=>n instanceof Float32Array);case 2:return s.g.find(n=>typeof WebGLTexture<"u"&&n instanceof WebGLTexture);default:throw Error(`Type is not supported: ${t}`)}}function Y5e(s){var t=A2(s,1);if(!t){if(t=A2(s,0))t=new Float32Array(t).map(r=>r/255);else{t=new Float32Array(s.width*s.height);const r=uD(s);var n=zLe(s);if(xjt(n,r,yjt(s)),"iPad Simulator;iPhone Simulator;iPod Simulator;iPad;iPhone;iPod".split(";").includes(navigator.platform)||navigator.userAgent.includes("Mac")&&"document"in self&&"ontouchend"in self.document){n=new Float32Array(s.width*s.height*4),r.readPixels(0,0,s.width,s.height,r.RGBA,r.FLOAT,n);for(let a=0,i=0;aMath.round(255*n))),s.g.push(t)),t;var s,t}ia(){return Y5e(this)}N(){return yjt(this)}clone(){const s=[];for(const t of this.g){let n;if(t instanceof Uint8Array)n=new Uint8Array(t);else if(t instanceof Float32Array)n=new Float32Array(t);else{if(!(t instanceof WebGLTexture))throw Error(`Type is not supported: ${t}`);{const r=uD(this),a=zLe(this);r.activeTexture(r.TEXTURE1),n=fjt(a,r,this.m?r.LINEAR:r.NEAREST),r.bindTexture(r.TEXTURE_2D,n);const i=vjt(this);r.texImage2D(r.TEXTURE_2D,0,i,this.width,this.height,0,r.RED,r.FLOAT,null),r.bindTexture(r.TEXTURE_2D,null),xjt(a,r,n),ZKs(a,r,!1,()=>{bjt(this),r.clearColor(0,0,0,0),r.clear(r.COLOR_BUFFER_BIT),r.drawArrays(r.TRIANGLE_FAN,0,4),Z5e(this)}),QKs(a),Z5e(this)}}s.push(n)}return new pp(s,this.m,this.R(),this.canvas,this.l,this.width,this.height)}close(){this.j&&uD(this).deleteTexture(A2(this,2)),mQe=-1}};pp.prototype.close=pp.prototype.close,pp.prototype.clone=pp.prototype.clone,pp.prototype.getAsWebGLTexture=pp.prototype.N,pp.prototype.getAsFloat32Array=pp.prototype.ia,pp.prototype.getAsUint8Array=pp.prototype.ja,pp.prototype.hasWebGLTexture=pp.prototype.R,pp.prototype.hasFloat32Array=pp.prototype.ka,pp.prototype.hasUint8Array=pp.prototype.Fa;var mQe=250;function Rb(...s){return s.map(([t,n])=>({start:t,end:n}))}const XKs=function(s){return class extends s{Ja(){this.i._registerModelResourcesGraphService()}}}((pQe=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:mjt()?this.i.canvas=new OffscreenCanvas(1,1):(console.warn("OffscreenCanvas not supported and GraphRunner constructor glCanvas parameter is undefined. Creating backup canvas."),this.i.canvas=document.createElement("canvas"))}async initializeGraph(s){const t=await(await fetch(s)).arrayBuffer();s=!(s.endsWith(".pbtxt")||s.endsWith(".textproto")),this.setGraph(new Uint8Array(t),s)}setGraphFromString(s){this.setGraph(new TextEncoder().encode(s),!1)}setGraph(s,t){const n=s.length,r=this.i._malloc(n);this.i.HEAPU8.set(s,r),t?this.i._changeBinaryGraph(n,r):this.i._changeTextGraph(n,r),this.i._free(r)}configureAudio(s,t,n,r,a){this.i._configureAudio||console.warn('Attempting to use configureAudio without support for input audio. Is build dep ":gl_graph_runner_audio" missing?'),wi(this,r||"input_audio",i=>{wi(this,a=a||"audio_header",l=>{this.i._configureAudio(i,l,s,t??0,n)})})}setAutoResizeCanvas(s){this.l=s}setAutoRenderToScreen(s){this.i._setAutoRenderToScreen(s)}setGpuBufferVerticalFlip(s){this.i.gpuOriginForWebTexturesIsBottomLeft=s}ca(s){k_(this,"__graph_config__",t=>{s(t)}),wi(this,"__graph_config__",t=>{this.i._getGraphConfig(t,void 0)}),delete this.i.simpleListeners.__graph_config__}attachErrorListener(s){this.i.errorListener=s}attachEmptyPacketListener(s,t){this.i.emptyPacketListeners=this.i.emptyPacketListeners||{},this.i.emptyPacketListeners[s]=t}addAudioToStream(s,t,n){this.addAudioToStreamWithShape(s,0,0,t,n)}addAudioToStreamWithShape(s,t,n,r,a){const i=4*s.length;this.h!==i&&(this.g&&this.i._free(this.g),this.g=this.i._malloc(i),this.h=i),this.i.HEAPF32.set(s,this.g/4),wi(this,r,l=>{this.i._addAudioToInputStream(this.g,t,n,l,a)})}addGpuBufferToStream(s,t,n){wi(this,t,r=>{const[a,i]=lQe(this,s,r);this.i._addBoundTextureToStream(r,a,i,n)})}addBoolToStream(s,t,n){wi(this,t,r=>{this.i._addBoolToInputStream(s,r,n)})}addDoubleToStream(s,t,n){wi(this,t,r=>{this.i._addDoubleToInputStream(s,r,n)})}addFloatToStream(s,t,n){wi(this,t,r=>{this.i._addFloatToInputStream(s,r,n)})}addIntToStream(s,t,n){wi(this,t,r=>{this.i._addIntToInputStream(s,r,n)})}addUintToStream(s,t,n){wi(this,t,r=>{this.i._addUintToInputStream(s,r,n)})}addStringToStream(s,t,n){wi(this,t,r=>{wi(this,s,a=>{this.i._addStringToInputStream(a,r,n)})})}addStringRecordToStream(s,t,n){wi(this,t,r=>{cQe(this,Object.keys(s),a=>{cQe(this,Object.values(s),i=>{this.i._addFlatHashMapToInputStream(a,i,Object.keys(s).length,r,n)})})})}addProtoToStream(s,t,n,r){wi(this,n,a=>{wi(this,t,i=>{const l=this.i._malloc(s.length);this.i.HEAPU8.set(s,l),this.i._addProtoToInputStream(l,s.length,i,a,r),this.i._free(l)})})}addEmptyPacketToStream(s,t){wi(this,s,n=>{this.i._addEmptyPacketToInputStream(n,t)})}addBoolVectorToStream(s,t,n){wi(this,t,r=>{const a=this.i._allocateBoolVector(s.length);if(!a)throw Error("Unable to allocate new bool vector on heap.");for(const i of s)this.i._addBoolVectorEntry(a,i);this.i._addBoolVectorToInputStream(a,r,n)})}addDoubleVectorToStream(s,t,n){wi(this,t,r=>{const a=this.i._allocateDoubleVector(s.length);if(!a)throw Error("Unable to allocate new double vector on heap.");for(const i of s)this.i._addDoubleVectorEntry(a,i);this.i._addDoubleVectorToInputStream(a,r,n)})}addFloatVectorToStream(s,t,n){wi(this,t,r=>{const a=this.i._allocateFloatVector(s.length);if(!a)throw Error("Unable to allocate new float vector on heap.");for(const i of s)this.i._addFloatVectorEntry(a,i);this.i._addFloatVectorToInputStream(a,r,n)})}addIntVectorToStream(s,t,n){wi(this,t,r=>{const a=this.i._allocateIntVector(s.length);if(!a)throw Error("Unable to allocate new int vector on heap.");for(const i of s)this.i._addIntVectorEntry(a,i);this.i._addIntVectorToInputStream(a,r,n)})}addUintVectorToStream(s,t,n){wi(this,t,r=>{const a=this.i._allocateUintVector(s.length);if(!a)throw Error("Unable to allocate new unsigned int vector on heap.");for(const i of s)this.i._addUintVectorEntry(a,i);this.i._addUintVectorToInputStream(a,r,n)})}addStringVectorToStream(s,t,n){wi(this,t,r=>{const a=this.i._allocateStringVector(s.length);if(!a)throw Error("Unable to allocate new string vector on heap.");for(const i of s)wi(this,i,l=>{this.i._addStringVectorEntry(a,l)});this.i._addStringVectorToInputStream(a,r,n)})}addBoolToInputSidePacket(s,t){wi(this,t,n=>{this.i._addBoolToInputSidePacket(s,n)})}addDoubleToInputSidePacket(s,t){wi(this,t,n=>{this.i._addDoubleToInputSidePacket(s,n)})}addFloatToInputSidePacket(s,t){wi(this,t,n=>{this.i._addFloatToInputSidePacket(s,n)})}addIntToInputSidePacket(s,t){wi(this,t,n=>{this.i._addIntToInputSidePacket(s,n)})}addUintToInputSidePacket(s,t){wi(this,t,n=>{this.i._addUintToInputSidePacket(s,n)})}addStringToInputSidePacket(s,t){wi(this,t,n=>{wi(this,s,r=>{this.i._addStringToInputSidePacket(r,n)})})}addProtoToInputSidePacket(s,t,n){wi(this,n,r=>{wi(this,t,a=>{const i=this.i._malloc(s.length);this.i.HEAPU8.set(s,i),this.i._addProtoToInputSidePacket(i,s.length,a,r),this.i._free(i)})})}addBoolVectorToInputSidePacket(s,t){wi(this,t,n=>{const r=this.i._allocateBoolVector(s.length);if(!r)throw Error("Unable to allocate new bool vector on heap.");for(const a of s)this.i._addBoolVectorEntry(r,a);this.i._addBoolVectorToInputSidePacket(r,n)})}addDoubleVectorToInputSidePacket(s,t){wi(this,t,n=>{const r=this.i._allocateDoubleVector(s.length);if(!r)throw Error("Unable to allocate new double vector on heap.");for(const a of s)this.i._addDoubleVectorEntry(r,a);this.i._addDoubleVectorToInputSidePacket(r,n)})}addFloatVectorToInputSidePacket(s,t){wi(this,t,n=>{const r=this.i._allocateFloatVector(s.length);if(!r)throw Error("Unable to allocate new float vector on heap.");for(const a of s)this.i._addFloatVectorEntry(r,a);this.i._addFloatVectorToInputSidePacket(r,n)})}addIntVectorToInputSidePacket(s,t){wi(this,t,n=>{const r=this.i._allocateIntVector(s.length);if(!r)throw Error("Unable to allocate new int vector on heap.");for(const a of s)this.i._addIntVectorEntry(r,a);this.i._addIntVectorToInputSidePacket(r,n)})}addUintVectorToInputSidePacket(s,t){wi(this,t,n=>{const r=this.i._allocateUintVector(s.length);if(!r)throw Error("Unable to allocate new unsigned int vector on heap.");for(const a of s)this.i._addUintVectorEntry(r,a);this.i._addUintVectorToInputSidePacket(r,n)})}addStringVectorToInputSidePacket(s,t){wi(this,t,n=>{const r=this.i._allocateStringVector(s.length);if(!r)throw Error("Unable to allocate new string vector on heap.");for(const a of s)wi(this,a,i=>{this.i._addStringVectorEntry(r,i)});this.i._addStringVectorToInputSidePacket(r,n)})}attachBoolListener(s,t){k_(this,s,t),wi(this,s,n=>{this.i._attachBoolListener(n)})}attachBoolVectorListener(s,t){kk(this,s,t),wi(this,s,n=>{this.i._attachBoolVectorListener(n)})}attachIntListener(s,t){k_(this,s,t),wi(this,s,n=>{this.i._attachIntListener(n)})}attachIntVectorListener(s,t){kk(this,s,t),wi(this,s,n=>{this.i._attachIntVectorListener(n)})}attachUintListener(s,t){k_(this,s,t),wi(this,s,n=>{this.i._attachUintListener(n)})}attachUintVectorListener(s,t){kk(this,s,t),wi(this,s,n=>{this.i._attachUintVectorListener(n)})}attachDoubleListener(s,t){k_(this,s,t),wi(this,s,n=>{this.i._attachDoubleListener(n)})}attachDoubleVectorListener(s,t){kk(this,s,t),wi(this,s,n=>{this.i._attachDoubleVectorListener(n)})}attachFloatListener(s,t){k_(this,s,t),wi(this,s,n=>{this.i._attachFloatListener(n)})}attachFloatVectorListener(s,t){kk(this,s,t),wi(this,s,n=>{this.i._attachFloatVectorListener(n)})}attachStringListener(s,t){k_(this,s,t),wi(this,s,n=>{this.i._attachStringListener(n)})}attachStringVectorListener(s,t){kk(this,s,t),wi(this,s,n=>{this.i._attachStringVectorListener(n)})}attachProtoListener(s,t,n){k_(this,s,t),wi(this,s,r=>{this.i._attachProtoListener(r,n||!1)})}attachProtoVectorListener(s,t,n){kk(this,s,t),wi(this,s,r=>{this.i._attachProtoVectorListener(r,n||!1)})}attachAudioListener(s,t,n){this.i._attachAudioListener||console.warn('Attempting to use attachAudioListener without support for output audio. Is build dep ":gl_graph_runner_audio_out" missing?'),k_(this,s,(r,a)=>{r=new Float32Array(r.buffer,r.byteOffset,r.length/4),t(r,a)}),wi(this,s,r=>{this.i._attachAudioListener(r,n||!1)})}finishProcessing(){this.i._waitUntilIdle()}closeGraph(){this.i._closeGraph(),this.i.simpleListeners=void 0,this.i.emptyPacketListeners=void 0}},class extends pQe{get ga(){return this.i}pa(s,t,n){wi(this,t,r=>{const[a,i]=lQe(this,s,r);this.ga._addBoundTextureAsImageToStream(r,a,i,n)})}Z(s,t){k_(this,s,t),wi(this,s,n=>{this.ga._attachImageListener(n)})}aa(s,t){kk(this,s,t),wi(this,s,n=>{this.ga._attachImageVectorListener(n)})}}));var pQe,Ob=class extends XKs{};async function Hl(s,t,n){return async function(r,a,i,l){return KKs(r,a,i,l)}(s,n.canvas??(mjt()?void 0:document.createElement("canvas")),t,n)}function _jt(s,t,n,r){if(s.U){const i=new Uwt;if(n!=null&&n.regionOfInterest){if(!s.oa)throw Error("This task doesn't support region-of-interest.");var a=n.regionOfInterest;if(a.left>=a.right||a.top>=a.bottom)throw Error("Expected RectF with left < right and top < bottom.");if(a.left<0||a.top<0||a.right>1||a.bottom>1)throw Error("Expected RectF values to be in [0,1].");Ti(i,1,(a.left+a.right)/2),Ti(i,2,(a.top+a.bottom)/2),Ti(i,4,a.right-a.left),Ti(i,3,a.bottom-a.top)}else Ti(i,1,.5),Ti(i,2,.5),Ti(i,4,1),Ti(i,3,1);if(n!=null&&n.rotationDegrees){if((n==null?void 0:n.rotationDegrees)%90!=0)throw Error("Expected rotation to be a multiple of 90°.");if(Ti(i,5,-Math.PI*n.rotationDegrees/180),(n==null?void 0:n.rotationDegrees)%180!=0){const[l,o]=pjt(t);n=_h(i,3)*o/l,a=_h(i,4)*l/o,Ti(i,4,n),Ti(i,3,a)}}s.g.addProtoToStream(i.g(),"mediapipe.NormalizedRect",s.U,r)}s.g.pa(t,s.X,r??performance.now()),s.finishProcessing()}function Fb(s,t,n){var r;if((r=s.baseOptions)!=null&&r.g())throw Error("Task is not initialized with image mode. 'runningMode' must be set to 'IMAGE'.");_jt(s,t,n,s.C+1)}function sj(s,t,n,r){var a;if(!((a=s.baseOptions)!=null&&a.g()))throw Error("Task is not initialized with video mode. 'runningMode' must be set to 'VIDEO'.");_jt(s,t,n,r)}function hD(s,t,n,r){var a=t.data;const i=t.width,l=i*(t=t.height);if((a instanceof Uint8Array||a instanceof Float32Array)&&a.length!==l)throw Error("Unsupported channel count: "+a.length/l);return s=new pp([a],n,!1,s.g.i.canvas,s.P,i,t),r?s.clone():s}var vy=class extends K5e{constructor(s,t,n,r){super(s),this.g=s,this.X=t,this.U=n,this.oa=r,this.P=new gjt}l(s,t=!0){if("runningMode"in s&&qc(this.baseOptions,2,d$(!!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()}};vy.prototype.close=vy.prototype.close;var iv=class extends vy{constructor(s,t){super(new Ob(s,t),"image_in","norm_rect_in",!1),this.j={detections:[]},Gi(s=this.h=new O1e,0,1,t=new dh),Ti(this.h,2,.5),Ti(this.h,3,.3)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){return"minDetectionConfidence"in s&&Ti(this.h,2,s.minDetectionConfidence??.5),"minSuppressionThreshold"in s&&Ti(this.h,3,s.minSuppressionThreshold??.3),this.l(s)}F(s,t){return this.j={detections:[]},Fb(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},sj(this,s,n,t),this.j}m(){var s=new Cy;Du(s,"image_in"),Du(s,"norm_rect_in"),ac(s,"detections");const t=new Sy;ej(t,PKs,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.face_detector.FaceDetectorGraph"),cu(n,"IMAGE:image_in"),cu(n,"NORM_RECT:norm_rect_in"),Pl(n,"DETECTIONS:detections"),n.o(t),e1(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=zwt(i),this.j.detections.push(ujt(r));ci(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{ci(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};iv.prototype.detectForVideo=iv.prototype.G,iv.prototype.detect=iv.prototype.F,iv.prototype.setOptions=iv.prototype.o,iv.createFromModelPath=async function(s,t){return Hl(iv,s,{baseOptions:{modelAssetPath:t}})},iv.createFromModelBuffer=function(s,t){return Hl(iv,s,{baseOptions:{modelAssetBuffer:t}})},iv.createFromOptions=function(s,t){return Hl(iv,s,t)};var BLe=Rb([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]),$Le=Rb([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]),ULe=Rb([276,283],[283,282],[282,295],[295,285],[300,293],[293,334],[334,296],[296,336]),wjt=Rb([474,475],[475,476],[476,477],[477,474]),qLe=Rb([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]),VLe=Rb([46,53],[53,52],[52,65],[65,55],[70,63],[63,105],[105,66],[66,107]),jjt=Rb([469,470],[470,471],[471,472],[472,469]),HLe=Rb([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]),Njt=[...BLe,...$Le,...ULe,...qLe,...VLe,...HLe],kjt=Rb([127,34],[34,139],[139,127],[11,0],[0,37],[37,11],[232,231],[231,120],[120,232],[72,37],[37,39],[39,72],[128,121],[121,47],[47,128],[232,121],[121,128],[128,232],[104,69],[69,67],[67,104],[175,171],[171,148],[148,175],[118,50],[50,101],[101,118],[73,39],[39,40],[40,73],[9,151],[151,108],[108,9],[48,115],[115,131],[131,48],[194,204],[204,211],[211,194],[74,40],[40,185],[185,74],[80,42],[42,183],[183,80],[40,92],[92,186],[186,40],[230,229],[229,118],[118,230],[202,212],[212,214],[214,202],[83,18],[18,17],[17,83],[76,61],[61,146],[146,76],[160,29],[29,30],[30,160],[56,157],[157,173],[173,56],[106,204],[204,194],[194,106],[135,214],[214,192],[192,135],[203,165],[165,98],[98,203],[21,71],[71,68],[68,21],[51,45],[45,4],[4,51],[144,24],[24,23],[23,144],[77,146],[146,91],[91,77],[205,50],[50,187],[187,205],[201,200],[200,18],[18,201],[91,106],[106,182],[182,91],[90,91],[91,181],[181,90],[85,84],[84,17],[17,85],[206,203],[203,36],[36,206],[148,171],[171,140],[140,148],[92,40],[40,39],[39,92],[193,189],[189,244],[244,193],[159,158],[158,28],[28,159],[247,246],[246,161],[161,247],[236,3],[3,196],[196,236],[54,68],[68,104],[104,54],[193,168],[168,8],[8,193],[117,228],[228,31],[31,117],[189,193],[193,55],[55,189],[98,97],[97,99],[99,98],[126,47],[47,100],[100,126],[166,79],[79,218],[218,166],[155,154],[154,26],[26,155],[209,49],[49,131],[131,209],[135,136],[136,150],[150,135],[47,126],[126,217],[217,47],[223,52],[52,53],[53,223],[45,51],[51,134],[134,45],[211,170],[170,140],[140,211],[67,69],[69,108],[108,67],[43,106],[106,91],[91,43],[230,119],[119,120],[120,230],[226,130],[130,247],[247,226],[63,53],[53,52],[52,63],[238,20],[20,242],[242,238],[46,70],[70,156],[156,46],[78,62],[62,96],[96,78],[46,53],[53,63],[63,46],[143,34],[34,227],[227,143],[123,117],[117,111],[111,123],[44,125],[125,19],[19,44],[236,134],[134,51],[51,236],[216,206],[206,205],[205,216],[154,153],[153,22],[22,154],[39,37],[37,167],[167,39],[200,201],[201,208],[208,200],[36,142],[142,100],[100,36],[57,212],[212,202],[202,57],[20,60],[60,99],[99,20],[28,158],[158,157],[157,28],[35,226],[226,113],[113,35],[160,159],[159,27],[27,160],[204,202],[202,210],[210,204],[113,225],[225,46],[46,113],[43,202],[202,204],[204,43],[62,76],[76,77],[77,62],[137,123],[123,116],[116,137],[41,38],[38,72],[72,41],[203,129],[129,142],[142,203],[64,98],[98,240],[240,64],[49,102],[102,64],[64,49],[41,73],[73,74],[74,41],[212,216],[216,207],[207,212],[42,74],[74,184],[184,42],[169,170],[170,211],[211,169],[170,149],[149,176],[176,170],[105,66],[66,69],[69,105],[122,6],[6,168],[168,122],[123,147],[147,187],[187,123],[96,77],[77,90],[90,96],[65,55],[55,107],[107,65],[89,90],[90,180],[180,89],[101,100],[100,120],[120,101],[63,105],[105,104],[104,63],[93,137],[137,227],[227,93],[15,86],[86,85],[85,15],[129,102],[102,49],[49,129],[14,87],[87,86],[86,14],[55,8],[8,9],[9,55],[100,47],[47,121],[121,100],[145,23],[23,22],[22,145],[88,89],[89,179],[179,88],[6,122],[122,196],[196,6],[88,95],[95,96],[96,88],[138,172],[172,136],[136,138],[215,58],[58,172],[172,215],[115,48],[48,219],[219,115],[42,80],[80,81],[81,42],[195,3],[3,51],[51,195],[43,146],[146,61],[61,43],[171,175],[175,199],[199,171],[81,82],[82,38],[38,81],[53,46],[46,225],[225,53],[144,163],[163,110],[110,144],[52,65],[65,66],[66,52],[229,228],[228,117],[117,229],[34,127],[127,234],[234,34],[107,108],[108,69],[69,107],[109,108],[108,151],[151,109],[48,64],[64,235],[235,48],[62,78],[78,191],[191,62],[129,209],[209,126],[126,129],[111,35],[35,143],[143,111],[117,123],[123,50],[50,117],[222,65],[65,52],[52,222],[19,125],[125,141],[141,19],[221,55],[55,65],[65,221],[3,195],[195,197],[197,3],[25,7],[7,33],[33,25],[220,237],[237,44],[44,220],[70,71],[71,139],[139,70],[122,193],[193,245],[245,122],[247,130],[130,33],[33,247],[71,21],[21,162],[162,71],[170,169],[169,150],[150,170],[188,174],[174,196],[196,188],[216,186],[186,92],[92,216],[2,97],[97,167],[167,2],[141,125],[125,241],[241,141],[164,167],[167,37],[37,164],[72,38],[38,12],[12,72],[38,82],[82,13],[13,38],[63,68],[68,71],[71,63],[226,35],[35,111],[111,226],[101,50],[50,205],[205,101],[206,92],[92,165],[165,206],[209,198],[198,217],[217,209],[165,167],[167,97],[97,165],[220,115],[115,218],[218,220],[133,112],[112,243],[243,133],[239,238],[238,241],[241,239],[214,135],[135,169],[169,214],[190,173],[173,133],[133,190],[171,208],[208,32],[32,171],[125,44],[44,237],[237,125],[86,87],[87,178],[178,86],[85,86],[86,179],[179,85],[84,85],[85,180],[180,84],[83,84],[84,181],[181,83],[201,83],[83,182],[182,201],[137,93],[93,132],[132,137],[76,62],[62,183],[183,76],[61,76],[76,184],[184,61],[57,61],[61,185],[185,57],[212,57],[57,186],[186,212],[214,207],[207,187],[187,214],[34,143],[143,156],[156,34],[79,239],[239,237],[237,79],[123,137],[137,177],[177,123],[44,1],[1,4],[4,44],[201,194],[194,32],[32,201],[64,102],[102,129],[129,64],[213,215],[215,138],[138,213],[59,166],[166,219],[219,59],[242,99],[99,97],[97,242],[2,94],[94,141],[141,2],[75,59],[59,235],[235,75],[24,110],[110,228],[228,24],[25,130],[130,226],[226,25],[23,24],[24,229],[229,23],[22,23],[23,230],[230,22],[26,22],[22,231],[231,26],[112,26],[26,232],[232,112],[189,190],[190,243],[243,189],[221,56],[56,190],[190,221],[28,56],[56,221],[221,28],[27,28],[28,222],[222,27],[29,27],[27,223],[223,29],[30,29],[29,224],[224,30],[247,30],[30,225],[225,247],[238,79],[79,20],[20,238],[166,59],[59,75],[75,166],[60,75],[75,240],[240,60],[147,177],[177,215],[215,147],[20,79],[79,166],[166,20],[187,147],[147,213],[213,187],[112,233],[233,244],[244,112],[233,128],[128,245],[245,233],[128,114],[114,188],[188,128],[114,217],[217,174],[174,114],[131,115],[115,220],[220,131],[217,198],[198,236],[236,217],[198,131],[131,134],[134,198],[177,132],[132,58],[58,177],[143,35],[35,124],[124,143],[110,163],[163,7],[7,110],[228,110],[110,25],[25,228],[356,389],[389,368],[368,356],[11,302],[302,267],[267,11],[452,350],[350,349],[349,452],[302,303],[303,269],[269,302],[357,343],[343,277],[277,357],[452,453],[453,357],[357,452],[333,332],[332,297],[297,333],[175,152],[152,377],[377,175],[347,348],[348,330],[330,347],[303,304],[304,270],[270,303],[9,336],[336,337],[337,9],[278,279],[279,360],[360,278],[418,262],[262,431],[431,418],[304,408],[408,409],[409,304],[310,415],[415,407],[407,310],[270,409],[409,410],[410,270],[450,348],[348,347],[347,450],[422,430],[430,434],[434,422],[313,314],[314,17],[17,313],[306,307],[307,375],[375,306],[387,388],[388,260],[260,387],[286,414],[414,398],[398,286],[335,406],[406,418],[418,335],[364,367],[367,416],[416,364],[423,358],[358,327],[327,423],[251,284],[284,298],[298,251],[281,5],[5,4],[4,281],[373,374],[374,253],[253,373],[307,320],[320,321],[321,307],[425,427],[427,411],[411,425],[421,313],[313,18],[18,421],[321,405],[405,406],[406,321],[320,404],[404,405],[405,320],[315,16],[16,17],[17,315],[426,425],[425,266],[266,426],[377,400],[400,369],[369,377],[322,391],[391,269],[269,322],[417,465],[465,464],[464,417],[386,257],[257,258],[258,386],[466,260],[260,388],[388,466],[456,399],[399,419],[419,456],[284,332],[332,333],[333,284],[417,285],[285,8],[8,417],[346,340],[340,261],[261,346],[413,441],[441,285],[285,413],[327,460],[460,328],[328,327],[355,371],[371,329],[329,355],[392,439],[439,438],[438,392],[382,341],[341,256],[256,382],[429,420],[420,360],[360,429],[364,394],[394,379],[379,364],[277,343],[343,437],[437,277],[443,444],[444,283],[283,443],[275,440],[440,363],[363,275],[431,262],[262,369],[369,431],[297,338],[338,337],[337,297],[273,375],[375,321],[321,273],[450,451],[451,349],[349,450],[446,342],[342,467],[467,446],[293,334],[334,282],[282,293],[458,461],[461,462],[462,458],[276,353],[353,383],[383,276],[308,324],[324,325],[325,308],[276,300],[300,293],[293,276],[372,345],[345,447],[447,372],[352,345],[345,340],[340,352],[274,1],[1,19],[19,274],[456,248],[248,281],[281,456],[436,427],[427,425],[425,436],[381,256],[256,252],[252,381],[269,391],[391,393],[393,269],[200,199],[199,428],[428,200],[266,330],[330,329],[329,266],[287,273],[273,422],[422,287],[250,462],[462,328],[328,250],[258,286],[286,384],[384,258],[265,353],[353,342],[342,265],[387,259],[259,257],[257,387],[424,431],[431,430],[430,424],[342,353],[353,276],[276,342],[273,335],[335,424],[424,273],[292,325],[325,307],[307,292],[366,447],[447,345],[345,366],[271,303],[303,302],[302,271],[423,266],[266,371],[371,423],[294,455],[455,460],[460,294],[279,278],[278,294],[294,279],[271,272],[272,304],[304,271],[432,434],[434,427],[427,432],[272,407],[407,408],[408,272],[394,430],[430,431],[431,394],[395,369],[369,400],[400,395],[334,333],[333,299],[299,334],[351,417],[417,168],[168,351],[352,280],[280,411],[411,352],[325,319],[319,320],[320,325],[295,296],[296,336],[336,295],[319,403],[403,404],[404,319],[330,348],[348,349],[349,330],[293,298],[298,333],[333,293],[323,454],[454,447],[447,323],[15,16],[16,315],[315,15],[358,429],[429,279],[279,358],[14,15],[15,316],[316,14],[285,336],[336,9],[9,285],[329,349],[349,350],[350,329],[374,380],[380,252],[252,374],[318,402],[402,403],[403,318],[6,197],[197,419],[419,6],[318,319],[319,325],[325,318],[367,364],[364,365],[365,367],[435,367],[367,397],[397,435],[344,438],[438,439],[439,344],[272,271],[271,311],[311,272],[195,5],[5,281],[281,195],[273,287],[287,291],[291,273],[396,428],[428,199],[199,396],[311,271],[271,268],[268,311],[283,444],[444,445],[445,283],[373,254],[254,339],[339,373],[282,334],[334,296],[296,282],[449,347],[347,346],[346,449],[264,447],[447,454],[454,264],[336,296],[296,299],[299,336],[338,10],[10,151],[151,338],[278,439],[439,455],[455,278],[292,407],[407,415],[415,292],[358,371],[371,355],[355,358],[340,345],[345,372],[372,340],[346,347],[347,280],[280,346],[442,443],[443,282],[282,442],[19,94],[94,370],[370,19],[441,442],[442,295],[295,441],[248,419],[419,197],[197,248],[263,255],[255,359],[359,263],[440,275],[275,274],[274,440],[300,383],[383,368],[368,300],[351,412],[412,465],[465,351],[263,467],[467,466],[466,263],[301,368],[368,389],[389,301],[395,378],[378,379],[379,395],[412,351],[351,419],[419,412],[436,426],[426,322],[322,436],[2,164],[164,393],[393,2],[370,462],[462,461],[461,370],[164,0],[0,267],[267,164],[302,11],[11,12],[12,302],[268,12],[12,13],[13,268],[293,300],[300,301],[301,293],[446,261],[261,340],[340,446],[330,266],[266,425],[425,330],[426,423],[423,391],[391,426],[429,355],[355,437],[437,429],[391,327],[327,326],[326,391],[440,457],[457,438],[438,440],[341,382],[382,362],[362,341],[459,457],[457,461],[461,459],[434,430],[430,394],[394,434],[414,463],[463,362],[362,414],[396,369],[369,262],[262,396],[354,461],[461,457],[457,354],[316,403],[403,402],[402,316],[315,404],[404,403],[403,315],[314,405],[405,404],[404,314],[313,406],[406,405],[405,313],[421,418],[418,406],[406,421],[366,401],[401,361],[361,366],[306,408],[408,407],[407,306],[291,409],[409,408],[408,291],[287,410],[410,409],[409,287],[432,436],[436,410],[410,432],[434,416],[416,411],[411,434],[264,368],[368,383],[383,264],[309,438],[438,457],[457,309],[352,376],[376,401],[401,352],[274,275],[275,4],[4,274],[421,428],[428,262],[262,421],[294,327],[327,358],[358,294],[433,416],[416,367],[367,433],[289,455],[455,439],[439,289],[462,370],[370,326],[326,462],[2,326],[326,370],[370,2],[305,460],[460,455],[455,305],[254,449],[449,448],[448,254],[255,261],[261,446],[446,255],[253,450],[450,449],[449,253],[252,451],[451,450],[450,252],[256,452],[452,451],[451,256],[341,453],[453,452],[452,341],[413,464],[464,463],[463,413],[441,413],[413,414],[414,441],[258,442],[442,441],[441,258],[257,443],[443,442],[442,257],[259,444],[444,443],[443,259],[260,445],[445,444],[444,260],[467,342],[342,445],[445,467],[459,458],[458,250],[250,459],[289,392],[392,290],[290,289],[290,328],[328,460],[460,290],[376,433],[433,435],[435,376],[250,290],[290,392],[392,250],[411,416],[416,433],[433,411],[341,463],[463,464],[464,341],[453,464],[464,465],[465,453],[357,465],[465,412],[412,357],[343,412],[412,399],[399,343],[360,363],[363,440],[440,360],[437,399],[399,456],[456,437],[420,456],[456,363],[363,420],[401,435],[435,288],[288,401],[372,383],[383,353],[353,372],[339,255],[255,249],[249,339],[448,261],[261,255],[255,448],[133,243],[243,190],[190,133],[133,155],[155,112],[112,133],[33,246],[246,247],[247,33],[33,130],[130,25],[25,33],[398,384],[384,286],[286,398],[362,398],[398,414],[414,362],[362,463],[463,341],[341,362],[263,359],[359,467],[467,263],[263,249],[249,255],[255,263],[466,467],[467,260],[260,466],[75,60],[60,166],[166,75],[238,239],[239,79],[79,238],[162,127],[127,139],[139,162],[72,11],[11,37],[37,72],[121,232],[232,120],[120,121],[73,72],[72,39],[39,73],[114,128],[128,47],[47,114],[233,232],[232,128],[128,233],[103,104],[104,67],[67,103],[152,175],[175,148],[148,152],[119,118],[118,101],[101,119],[74,73],[73,40],[40,74],[107,9],[9,108],[108,107],[49,48],[48,131],[131,49],[32,194],[194,211],[211,32],[184,74],[74,185],[185,184],[191,80],[80,183],[183,191],[185,40],[40,186],[186,185],[119,230],[230,118],[118,119],[210,202],[202,214],[214,210],[84,83],[83,17],[17,84],[77,76],[76,146],[146,77],[161,160],[160,30],[30,161],[190,56],[56,173],[173,190],[182,106],[106,194],[194,182],[138,135],[135,192],[192,138],[129,203],[203,98],[98,129],[54,21],[21,68],[68,54],[5,51],[51,4],[4,5],[145,144],[144,23],[23,145],[90,77],[77,91],[91,90],[207,205],[205,187],[187,207],[83,201],[201,18],[18,83],[181,91],[91,182],[182,181],[180,90],[90,181],[181,180],[16,85],[85,17],[17,16],[205,206],[206,36],[36,205],[176,148],[148,140],[140,176],[165,92],[92,39],[39,165],[245,193],[193,244],[244,245],[27,159],[159,28],[28,27],[30,247],[247,161],[161,30],[174,236],[236,196],[196,174],[103,54],[54,104],[104,103],[55,193],[193,8],[8,55],[111,117],[117,31],[31,111],[221,189],[189,55],[55,221],[240,98],[98,99],[99,240],[142,126],[126,100],[100,142],[219,166],[166,218],[218,219],[112,155],[155,26],[26,112],[198,209],[209,131],[131,198],[169,135],[135,150],[150,169],[114,47],[47,217],[217,114],[224,223],[223,53],[53,224],[220,45],[45,134],[134,220],[32,211],[211,140],[140,32],[109,67],[67,108],[108,109],[146,43],[43,91],[91,146],[231,230],[230,120],[120,231],[113,226],[226,247],[247,113],[105,63],[63,52],[52,105],[241,238],[238,242],[242,241],[124,46],[46,156],[156,124],[95,78],[78,96],[96,95],[70,46],[46,63],[63,70],[116,143],[143,227],[227,116],[116,123],[123,111],[111,116],[1,44],[44,19],[19,1],[3,236],[236,51],[51,3],[207,216],[216,205],[205,207],[26,154],[154,22],[22,26],[165,39],[39,167],[167,165],[199,200],[200,208],[208,199],[101,36],[36,100],[100,101],[43,57],[57,202],[202,43],[242,20],[20,99],[99,242],[56,28],[28,157],[157,56],[124,35],[35,113],[113,124],[29,160],[160,27],[27,29],[211,204],[204,210],[210,211],[124,113],[113,46],[46,124],[106,43],[43,204],[204,106],[96,62],[62,77],[77,96],[227,137],[137,116],[116,227],[73,41],[41,72],[72,73],[36,203],[203,142],[142,36],[235,64],[64,240],[240,235],[48,49],[49,64],[64,48],[42,41],[41,74],[74,42],[214,212],[212,207],[207,214],[183,42],[42,184],[184,183],[210,169],[169,211],[211,210],[140,170],[170,176],[176,140],[104,105],[105,69],[69,104],[193,122],[122,168],[168,193],[50,123],[123,187],[187,50],[89,96],[96,90],[90,89],[66,65],[65,107],[107,66],[179,89],[89,180],[180,179],[119,101],[101,120],[120,119],[68,63],[63,104],[104,68],[234,93],[93,227],[227,234],[16,15],[15,85],[85,16],[209,129],[129,49],[49,209],[15,14],[14,86],[86,15],[107,55],[55,9],[9,107],[120,100],[100,121],[121,120],[153,145],[145,22],[22,153],[178,88],[88,179],[179,178],[197,6],[6,196],[196,197],[89,88],[88,96],[96,89],[135,138],[138,136],[136,135],[138,215],[215,172],[172,138],[218,115],[115,219],[219,218],[41,42],[42,81],[81,41],[5,195],[195,51],[51,5],[57,43],[43,61],[61,57],[208,171],[171,199],[199,208],[41,81],[81,38],[38,41],[224,53],[53,225],[225,224],[24,144],[144,110],[110,24],[105,52],[52,66],[66,105],[118,229],[229,117],[117,118],[227,34],[34,234],[234,227],[66,107],[107,69],[69,66],[10,109],[109,151],[151,10],[219,48],[48,235],[235,219],[183,62],[62,191],[191,183],[142,129],[129,126],[126,142],[116,111],[111,143],[143,116],[118,117],[117,50],[50,118],[223,222],[222,52],[52,223],[94,19],[19,141],[141,94],[222,221],[221,65],[65,222],[196,3],[3,197],[197,196],[45,220],[220,44],[44,45],[156,70],[70,139],[139,156],[188,122],[122,245],[245,188],[139,71],[71,162],[162,139],[149,170],[170,150],[150,149],[122,188],[188,196],[196,122],[206,216],[216,92],[92,206],[164,2],[2,167],[167,164],[242,141],[141,241],[241,242],[0,164],[164,37],[37,0],[11,72],[72,12],[12,11],[12,38],[38,13],[13,12],[70,63],[63,71],[71,70],[31,226],[226,111],[111,31],[36,101],[101,205],[205,36],[203,206],[206,165],[165,203],[126,209],[209,217],[217,126],[98,165],[165,97],[97,98],[237,220],[220,218],[218,237],[237,239],[239,241],[241,237],[210,214],[214,169],[169,210],[140,171],[171,32],[32,140],[241,125],[125,237],[237,241],[179,86],[86,178],[178,179],[180,85],[85,179],[179,180],[181,84],[84,180],[180,181],[182,83],[83,181],[181,182],[194,201],[201,182],[182,194],[177,137],[137,132],[132,177],[184,76],[76,183],[183,184],[185,61],[61,184],[184,185],[186,57],[57,185],[185,186],[216,212],[212,186],[186,216],[192,214],[214,187],[187,192],[139,34],[34,156],[156,139],[218,79],[79,237],[237,218],[147,123],[123,177],[177,147],[45,44],[44,4],[4,45],[208,201],[201,32],[32,208],[98,64],[64,129],[129,98],[192,213],[213,138],[138,192],[235,59],[59,219],[219,235],[141,242],[242,97],[97,141],[97,2],[2,141],[141,97],[240,75],[75,235],[235,240],[229,24],[24,228],[228,229],[31,25],[25,226],[226,31],[230,23],[23,229],[229,230],[231,22],[22,230],[230,231],[232,26],[26,231],[231,232],[233,112],[112,232],[232,233],[244,189],[189,243],[243,244],[189,221],[221,190],[190,189],[222,28],[28,221],[221,222],[223,27],[27,222],[222,223],[224,29],[29,223],[223,224],[225,30],[30,224],[224,225],[113,247],[247,225],[225,113],[99,60],[60,240],[240,99],[213,147],[147,215],[215,213],[60,20],[20,166],[166,60],[192,187],[187,213],[213,192],[243,112],[112,244],[244,243],[244,233],[233,245],[245,244],[245,128],[128,188],[188,245],[188,114],[114,174],[174,188],[134,131],[131,220],[220,134],[174,217],[217,236],[236,174],[236,198],[198,134],[134,236],[215,177],[177,58],[58,215],[156,143],[143,124],[124,156],[25,110],[110,7],[7,25],[31,228],[228,25],[25,31],[264,356],[356,368],[368,264],[0,11],[11,267],[267,0],[451,452],[452,349],[349,451],[267,302],[302,269],[269,267],[350,357],[357,277],[277,350],[350,452],[452,357],[357,350],[299,333],[333,297],[297,299],[396,175],[175,377],[377,396],[280,347],[347,330],[330,280],[269,303],[303,270],[270,269],[151,9],[9,337],[337,151],[344,278],[278,360],[360,344],[424,418],[418,431],[431,424],[270,304],[304,409],[409,270],[272,310],[310,407],[407,272],[322,270],[270,410],[410,322],[449,450],[450,347],[347,449],[432,422],[422,434],[434,432],[18,313],[313,17],[17,18],[291,306],[306,375],[375,291],[259,387],[387,260],[260,259],[424,335],[335,418],[418,424],[434,364],[364,416],[416,434],[391,423],[423,327],[327,391],[301,251],[251,298],[298,301],[275,281],[281,4],[4,275],[254,373],[373,253],[253,254],[375,307],[307,321],[321,375],[280,425],[425,411],[411,280],[200,421],[421,18],[18,200],[335,321],[321,406],[406,335],[321,320],[320,405],[405,321],[314,315],[315,17],[17,314],[423,426],[426,266],[266,423],[396,377],[377,369],[369,396],[270,322],[322,269],[269,270],[413,417],[417,464],[464,413],[385,386],[386,258],[258,385],[248,456],[456,419],[419,248],[298,284],[284,333],[333,298],[168,417],[417,8],[8,168],[448,346],[346,261],[261,448],[417,413],[413,285],[285,417],[326,327],[327,328],[328,326],[277,355],[355,329],[329,277],[309,392],[392,438],[438,309],[381,382],[382,256],[256,381],[279,429],[429,360],[360,279],[365,364],[364,379],[379,365],[355,277],[277,437],[437,355],[282,443],[443,283],[283,282],[281,275],[275,363],[363,281],[395,431],[431,369],[369,395],[299,297],[297,337],[337,299],[335,273],[273,321],[321,335],[348,450],[450,349],[349,348],[359,446],[446,467],[467,359],[283,293],[293,282],[282,283],[250,458],[458,462],[462,250],[300,276],[276,383],[383,300],[292,308],[308,325],[325,292],[283,276],[276,293],[293,283],[264,372],[372,447],[447,264],[346,352],[352,340],[340,346],[354,274],[274,19],[19,354],[363,456],[456,281],[281,363],[426,436],[436,425],[425,426],[380,381],[381,252],[252,380],[267,269],[269,393],[393,267],[421,200],[200,428],[428,421],[371,266],[266,329],[329,371],[432,287],[287,422],[422,432],[290,250],[250,328],[328,290],[385,258],[258,384],[384,385],[446,265],[265,342],[342,446],[386,387],[387,257],[257,386],[422,424],[424,430],[430,422],[445,342],[342,276],[276,445],[422,273],[273,424],[424,422],[306,292],[292,307],[307,306],[352,366],[366,345],[345,352],[268,271],[271,302],[302,268],[358,423],[423,371],[371,358],[327,294],[294,460],[460,327],[331,279],[279,294],[294,331],[303,271],[271,304],[304,303],[436,432],[432,427],[427,436],[304,272],[272,408],[408,304],[395,394],[394,431],[431,395],[378,395],[395,400],[400,378],[296,334],[334,299],[299,296],[6,351],[351,168],[168,6],[376,352],[352,411],[411,376],[307,325],[325,320],[320,307],[285,295],[295,336],[336,285],[320,319],[319,404],[404,320],[329,330],[330,349],[349,329],[334,293],[293,333],[333,334],[366,323],[323,447],[447,366],[316,15],[15,315],[315,316],[331,358],[358,279],[279,331],[317,14],[14,316],[316,317],[8,285],[285,9],[9,8],[277,329],[329,350],[350,277],[253,374],[374,252],[252,253],[319,318],[318,403],[403,319],[351,6],[6,419],[419,351],[324,318],[318,325],[325,324],[397,367],[367,365],[365,397],[288,435],[435,397],[397,288],[278,344],[344,439],[439,278],[310,272],[272,311],[311,310],[248,195],[195,281],[281,248],[375,273],[273,291],[291,375],[175,396],[396,199],[199,175],[312,311],[311,268],[268,312],[276,283],[283,445],[445,276],[390,373],[373,339],[339,390],[295,282],[282,296],[296,295],[448,449],[449,346],[346,448],[356,264],[264,454],[454,356],[337,336],[336,299],[299,337],[337,338],[338,151],[151,337],[294,278],[278,455],[455,294],[308,292],[292,415],[415,308],[429,358],[358,355],[355,429],[265,340],[340,372],[372,265],[352,346],[346,280],[280,352],[295,442],[442,282],[282,295],[354,19],[19,370],[370,354],[285,441],[441,295],[295,285],[195,248],[248,197],[197,195],[457,440],[440,274],[274,457],[301,300],[300,368],[368,301],[417,351],[351,465],[465,417],[251,301],[301,389],[389,251],[394,395],[395,379],[379,394],[399,412],[412,419],[419,399],[410,436],[436,322],[322,410],[326,2],[2,393],[393,326],[354,370],[370,461],[461,354],[393,164],[164,267],[267,393],[268,302],[302,12],[12,268],[312,268],[268,13],[13,312],[298,293],[293,301],[301,298],[265,446],[446,340],[340,265],[280,330],[330,425],[425,280],[322,426],[426,391],[391,322],[420,429],[429,437],[437,420],[393,391],[391,326],[326,393],[344,440],[440,438],[438,344],[458,459],[459,461],[461,458],[364,434],[434,394],[394,364],[428,396],[396,262],[262,428],[274,354],[354,457],[457,274],[317,316],[316,402],[402,317],[316,315],[315,403],[403,316],[315,314],[314,404],[404,315],[314,313],[313,405],[405,314],[313,421],[421,406],[406,313],[323,366],[366,361],[361,323],[292,306],[306,407],[407,292],[306,291],[291,408],[408,306],[291,287],[287,409],[409,291],[287,432],[432,410],[410,287],[427,434],[434,411],[411,427],[372,264],[264,383],[383,372],[459,309],[309,457],[457,459],[366,352],[352,401],[401,366],[1,274],[274,4],[4,1],[418,421],[421,262],[262,418],[331,294],[294,358],[358,331],[435,433],[433,367],[367,435],[392,289],[289,439],[439,392],[328,462],[462,326],[326,328],[94,2],[2,370],[370,94],[289,305],[305,455],[455,289],[339,254],[254,448],[448,339],[359,255],[255,446],[446,359],[254,253],[253,449],[449,254],[253,252],[252,450],[450,253],[252,256],[256,451],[451,252],[256,341],[341,452],[452,256],[414,413],[413,463],[463,414],[286,441],[441,414],[414,286],[286,258],[258,441],[441,286],[258,257],[257,442],[442,258],[257,259],[259,443],[443,257],[259,260],[260,444],[444,259],[260,467],[467,445],[445,260],[309,459],[459,250],[250,309],[305,289],[289,290],[290,305],[305,290],[290,460],[460,305],[401,376],[376,435],[435,401],[309,250],[250,392],[392,309],[376,411],[411,433],[433,376],[453,341],[341,464],[464,453],[357,453],[453,465],[465,357],[343,357],[357,412],[412,343],[437,343],[343,399],[399,437],[344,360],[360,440],[440,344],[420,437],[437,456],[456,420],[360,420],[420,363],[363,360],[361,401],[401,288],[288,361],[265,372],[372,353],[353,265],[390,339],[339,249],[249,390],[339,448],[448,255],[255,339]);function fQe(s){s.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]}}var Ku=class extends vy{constructor(s,t){super(new Ob(s,t),"image_in","norm_rect",!1),this.j={faceLandmarks:[],faceBlendshapes:[],facialTransformationMatrixes:[]},this.outputFacialTransformationMatrixes=this.outputFaceBlendshapes=!1,Gi(s=this.h=new Wwt,0,1,t=new dh),this.A=new Gwt,Gi(this.h,0,3,this.A),this.u=new O1e,Gi(this.h,0,2,this.u),xN(this.u,4,1),Ti(this.u,2,.5),Ti(this.A,2,.5),Ti(this.h,4,.5)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){return"numFaces"in s&&xN(this.u,4,s.numFaces??1),"minFaceDetectionConfidence"in s&&Ti(this.u,2,s.minFaceDetectionConfidence??.5),"minTrackingConfidence"in s&&Ti(this.h,4,s.minTrackingConfidence??.5),"minFacePresenceConfidence"in s&&Ti(this.A,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"outputFacialTransformationMatrixes"in s&&(this.outputFacialTransformationMatrixes=!!s.outputFacialTransformationMatrixes),this.l(s)}F(s,t){return fQe(this),Fb(this,s,t),this.j}G(s,t,n){return fQe(this),sj(this,s,n,t),this.j}m(){var s=new Cy;Du(s,"image_in"),Du(s,"norm_rect"),ac(s,"face_landmarks");const t=new Sy;ej(t,DKs,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.face_landmarker.FaceLandmarkerGraph"),cu(n,"IMAGE:image_in"),cu(n,"NORM_RECT:norm_rect"),Pl(n,"NORM_LANDMARKS:face_landmarks"),n.o(t),e1(s,n),this.g.attachProtoVectorListener("face_landmarks",(r,a)=>{for(const i of r)r=FU(i),this.j.faceLandmarks.push(F1e(r));ci(this,a)}),this.g.attachEmptyPacketListener("face_landmarks",r=>{ci(this,r)}),this.outputFaceBlendshapes&&(ac(s,"blendshapes"),Pl(n,"BLENDSHAPES:blendshapes"),this.g.attachProtoVectorListener("blendshapes",(r,a)=>{if(this.outputFaceBlendshapes)for(const i of r)r=R1e(i),this.j.faceBlendshapes.push(OLe(r.g()??[]));ci(this,a)}),this.g.attachEmptyPacketListener("blendshapes",r=>{ci(this,r)})),this.outputFacialTransformationMatrixes&&(ac(s,"face_geometry"),Pl(n,"FACE_GEOMETRY:face_geometry"),this.g.attachProtoVectorListener("face_geometry",(r,a)=>{if(this.outputFacialTransformationMatrixes)for(const i of r)(r=Kl(r=LKs(i),kKs,2))&&this.j.facialTransformationMatrixes.push({rows:Mv(r,1)??0??0,columns:Mv(r,2)??0??0,data:eA(r,3,sw,JE()).slice()??[]});ci(this,a)}),this.g.attachEmptyPacketListener("face_geometry",r=>{ci(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Ku.prototype.detectForVideo=Ku.prototype.G,Ku.prototype.detect=Ku.prototype.F,Ku.prototype.setOptions=Ku.prototype.o,Ku.createFromModelPath=function(s,t){return Hl(Ku,s,{baseOptions:{modelAssetPath:t}})},Ku.createFromModelBuffer=function(s,t){return Hl(Ku,s,{baseOptions:{modelAssetBuffer:t}})},Ku.createFromOptions=function(s,t){return Hl(Ku,s,t)},Ku.FACE_LANDMARKS_LIPS=BLe,Ku.FACE_LANDMARKS_LEFT_EYE=$Le,Ku.FACE_LANDMARKS_LEFT_EYEBROW=ULe,Ku.FACE_LANDMARKS_LEFT_IRIS=wjt,Ku.FACE_LANDMARKS_RIGHT_EYE=qLe,Ku.FACE_LANDMARKS_RIGHT_EYEBROW=VLe,Ku.FACE_LANDMARKS_RIGHT_IRIS=jjt,Ku.FACE_LANDMARKS_FACE_OVAL=HLe,Ku.FACE_LANDMARKS_CONTOURS=Njt,Ku.FACE_LANDMARKS_TESSELATION=kjt;var GLe=Rb([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 xQe(s){s.gestures=[],s.landmarks=[],s.worldLandmarks=[],s.handedness=[]}function gQe(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 yQe(s,t=!0){const n=[];for(const a of s){var r=R1e(a);s=[];for(const i of r.g())r=t&&Mv(i,1)!=null?Mv(i,1)??0:-1,s.push({score:_h(i,2)??0,index:r,categoryName:vf(Eu(i,3))??""??"",displayName:vf(Eu(i,4))??""??""});n.push(s)}return n}var T0=class extends vy{constructor(s,t){super(new Ob(s,t),"image_in","norm_rect",!1),this.gestures=[],this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Gi(s=this.j=new Zwt,0,1,t=new dh),this.u=new PLe,Gi(this.j,0,2,this.u),this.D=new ILe,Gi(this.u,0,3,this.D),this.A=new Ywt,Gi(this.u,0,2,this.A),this.h=new RKs,Gi(this.j,0,3,this.h),Ti(this.A,2,.5),Ti(this.u,4,.5),Ti(this.D,2,.5)}get baseOptions(){return Kl(this.j,dh,1)}set baseOptions(s){Gi(this.j,0,1,s)}o(s){var a,i,l,o;if(xN(this.A,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ti(this.A,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ti(this.u,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ti(this.D,2,s.minHandPresenceConfidence??.5),s.cannedGesturesClassifierOptions){var t=new DI,n=t,r=W5e(s.cannedGesturesClassifierOptions,(a=Kl(this.h,DI,3))==null?void 0:a.l());Gi(n,0,2,r),Gi(this.h,0,3,t)}else s.cannedGesturesClassifierOptions===void 0&&((i=Kl(this.h,DI,3))==null||i.g());return s.customGesturesClassifierOptions?(Gi(n=t=new DI,0,2,r=W5e(s.customGesturesClassifierOptions,(l=Kl(this.h,DI,4))==null?void 0:l.l())),Gi(this.h,0,4,t)):s.customGesturesClassifierOptions===void 0&&((o=Kl(this.h,DI,4))==null||o.g()),this.l(s)}Ha(s,t){return xQe(this),Fb(this,s,t),gQe(this)}Ia(s,t,n){return xQe(this),sj(this,s,n,t),gQe(this)}m(){var s=new Cy;Du(s,"image_in"),Du(s,"norm_rect"),ac(s,"hand_gestures"),ac(s,"hand_landmarks"),ac(s,"world_hand_landmarks"),ac(s,"handedness");const t=new Sy;ej(t,OKs,this.j);const n=new a0;yy(n,2,"mediapipe.tasks.vision.gesture_recognizer.GestureRecognizerGraph"),cu(n,"IMAGE:image_in"),cu(n,"NORM_RECT:norm_rect"),Pl(n,"HAND_GESTURES:hand_gestures"),Pl(n,"LANDMARKS:hand_landmarks"),Pl(n,"WORLD_LANDMARKS:world_hand_landmarks"),Pl(n,"HANDEDNESS:handedness"),n.o(t),e1(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r){r=FU(i);const l=[];for(const o of fN(r,$wt,1))l.push({x:_h(o,1)??0,y:_h(o,2)??0,z:_h(o,3)??0,visibility:_h(o,4)??0});this.landmarks.push(l)}ci(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{ci(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r){r=FL(i);const l=[];for(const o of fN(r,Bwt,1))l.push({x:_h(o,1)??0,y:_h(o,2)??0,z:_h(o,3)??0,visibility:_h(o,4)??0});this.worldLandmarks.push(l)}ci(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{ci(this,r)}),this.g.attachProtoVectorListener("hand_gestures",(r,a)=>{this.gestures.push(...yQe(r,!1)),ci(this,a)}),this.g.attachEmptyPacketListener("hand_gestures",r=>{ci(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{this.handedness.push(...yQe(r)),ci(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{ci(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};function vQe(s){return{landmarks:s.landmarks,worldLandmarks:s.worldLandmarks,handednesses:s.handedness,handedness:s.handedness}}T0.prototype.recognizeForVideo=T0.prototype.Ia,T0.prototype.recognize=T0.prototype.Ha,T0.prototype.setOptions=T0.prototype.o,T0.createFromModelPath=function(s,t){return Hl(T0,s,{baseOptions:{modelAssetPath:t}})},T0.createFromModelBuffer=function(s,t){return Hl(T0,s,{baseOptions:{modelAssetBuffer:t}})},T0.createFromOptions=function(s,t){return Hl(T0,s,t)},T0.HAND_CONNECTIONS=GLe;var E0=class extends vy{constructor(s,t){super(new Ob(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Gi(s=this.h=new PLe,0,1,t=new dh),this.u=new ILe,Gi(this.h,0,3,this.u),this.j=new Ywt,Gi(this.h,0,2,this.j),xN(this.j,3,1),Ti(this.j,2,.5),Ti(this.u,2,.5),Ti(this.h,4,.5)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){return"numHands"in s&&xN(this.j,3,s.numHands??1),"minHandDetectionConfidence"in s&&Ti(this.j,2,s.minHandDetectionConfidence??.5),"minTrackingConfidence"in s&&Ti(this.h,4,s.minTrackingConfidence??.5),"minHandPresenceConfidence"in s&&Ti(this.u,2,s.minHandPresenceConfidence??.5),this.l(s)}F(s,t){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],Fb(this,s,t),vQe(this)}G(s,t,n){return this.landmarks=[],this.worldLandmarks=[],this.handedness=[],sj(this,s,n,t),vQe(this)}m(){var s=new Cy;Du(s,"image_in"),Du(s,"norm_rect"),ac(s,"hand_landmarks"),ac(s,"world_hand_landmarks"),ac(s,"handedness");const t=new Sy;ej(t,FKs,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.hand_landmarker.HandLandmarkerGraph"),cu(n,"IMAGE:image_in"),cu(n,"NORM_RECT:norm_rect"),Pl(n,"LANDMARKS:hand_landmarks"),Pl(n,"WORLD_LANDMARKS:world_hand_landmarks"),Pl(n,"HANDEDNESS:handedness"),n.o(t),e1(s,n),this.g.attachProtoVectorListener("hand_landmarks",(r,a)=>{for(const i of r)r=FU(i),this.landmarks.push(F1e(r));ci(this,a)}),this.g.attachEmptyPacketListener("hand_landmarks",r=>{ci(this,r)}),this.g.attachProtoVectorListener("world_hand_landmarks",(r,a)=>{for(const i of r)r=FL(i),this.worldLandmarks.push(_z(r));ci(this,a)}),this.g.attachEmptyPacketListener("world_hand_landmarks",r=>{ci(this,r)}),this.g.attachProtoVectorListener("handedness",(r,a)=>{var i=this.handedness,l=i.push;const o=[];for(const c of r){r=R1e(c);const d=[];for(const u of r.g())d.push({score:_h(u,2)??0,index:Mv(u,1)??0??-1,categoryName:vf(Eu(u,3))??""??"",displayName:vf(Eu(u,4))??""??""});o.push(d)}l.call(i,...o),ci(this,a)}),this.g.attachEmptyPacketListener("handedness",r=>{ci(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};E0.prototype.detectForVideo=E0.prototype.G,E0.prototype.detect=E0.prototype.F,E0.prototype.setOptions=E0.prototype.o,E0.createFromModelPath=function(s,t){return Hl(E0,s,{baseOptions:{modelAssetPath:t}})},E0.createFromModelBuffer=function(s,t){return Hl(E0,s,{baseOptions:{modelAssetBuffer:t}})},E0.createFromOptions=function(s,t){return Hl(E0,s,t)},E0.HAND_CONNECTIONS=GLe;var Sjt=Rb([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 bQe(s){s.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]}}function _Qe(s){try{if(!s.D)return s.h;s.D(s.h)}finally{B1e(s)}}function pG(s,t){s=FU(s),t.push(F1e(s))}var Qd=class extends vy{constructor(s,t){super(new Ob(s,t),"input_frames_image",null,!1),this.h={faceLandmarks:[],faceBlendshapes:[],poseLandmarks:[],poseWorldLandmarks:[],poseSegmentationMasks:[],leftHandLandmarks:[],leftHandWorldLandmarks:[],rightHandLandmarks:[],rightHandWorldLandmarks:[]},this.outputPoseSegmentationMasks=this.outputFaceBlendshapes=!1,Gi(s=this.j=new tjt,0,1,t=new dh),this.I=new ILe,Gi(this.j,0,2,this.I),this.W=new zKs,Gi(this.j,0,3,this.W),this.u=new O1e,Gi(this.j,0,4,this.u),this.O=new Gwt,Gi(this.j,0,5,this.O),this.A=new Jwt,Gi(this.j,0,6,this.A),this.M=new ejt,Gi(this.j,0,7,this.M),Ti(this.u,2,.5),Ti(this.u,3,.3),Ti(this.O,2,.5),Ti(this.A,2,.5),Ti(this.A,3,.3),Ti(this.M,2,.5),Ti(this.I,2,.5)}get baseOptions(){return Kl(this.j,dh,1)}set baseOptions(s){Gi(this.j,0,1,s)}o(s){return"minFaceDetectionConfidence"in s&&Ti(this.u,2,s.minFaceDetectionConfidence??.5),"minFaceSuppressionThreshold"in s&&Ti(this.u,3,s.minFaceSuppressionThreshold??.3),"minFacePresenceConfidence"in s&&Ti(this.O,2,s.minFacePresenceConfidence??.5),"outputFaceBlendshapes"in s&&(this.outputFaceBlendshapes=!!s.outputFaceBlendshapes),"minPoseDetectionConfidence"in s&&Ti(this.A,2,s.minPoseDetectionConfidence??.5),"minPoseSuppressionThreshold"in s&&Ti(this.A,3,s.minPoseSuppressionThreshold??.3),"minPosePresenceConfidence"in s&&Ti(this.M,2,s.minPosePresenceConfidence??.5),"outputPoseSegmentationMasks"in s&&(this.outputPoseSegmentationMasks=!!s.outputPoseSegmentationMasks),"minHandLandmarksConfidence"in s&&Ti(this.I,2,s.minHandLandmarksConfidence??.5),this.l(s)}F(s,t,n){const r=typeof t!="function"?t:{};return this.D=typeof t=="function"?t:n,bQe(this),Fb(this,s,r),_Qe(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.D=typeof n=="function"?n:r,bQe(this),sj(this,s,a,t),_Qe(this)}m(){var s=new Cy;Du(s,"input_frames_image"),ac(s,"pose_landmarks"),ac(s,"pose_world_landmarks"),ac(s,"face_landmarks"),ac(s,"left_hand_landmarks"),ac(s,"left_hand_world_landmarks"),ac(s,"right_hand_landmarks"),ac(s,"right_hand_world_landmarks");const t=new Sy,n=new HZe;yy(n,1,"type.googleapis.com/mediapipe.tasks.vision.holistic_landmarker.proto.HolisticLandmarkerGraphOptions"),function(a,i){if(i!=null)if(Array.isArray(i))qc(a,2,N1e(i,0,u$));else{if(!(typeof i=="string"||i instanceof Sw||XPe(i)))throw Error("invalid value in Any.value field: "+i+" expected a ByteString, a base64 encoded string, a Uint8Array or a jspb array");Qk(a,2,eLe(i,!1),AM())}}(n,this.j.g());const r=new a0;yy(r,2,"mediapipe.tasks.vision.holistic_landmarker.HolisticLandmarkerGraph"),pLe(r,8,HZe,n),cu(r,"IMAGE:input_frames_image"),Pl(r,"POSE_LANDMARKS:pose_landmarks"),Pl(r,"POSE_WORLD_LANDMARKS:pose_world_landmarks"),Pl(r,"FACE_LANDMARKS:face_landmarks"),Pl(r,"LEFT_HAND_LANDMARKS:left_hand_landmarks"),Pl(r,"LEFT_HAND_WORLD_LANDMARKS:left_hand_world_landmarks"),Pl(r,"RIGHT_HAND_LANDMARKS:right_hand_landmarks"),Pl(r,"RIGHT_HAND_WORLD_LANDMARKS:right_hand_world_landmarks"),r.o(t),e1(s,r),z1e(this,s),this.g.attachProtoListener("pose_landmarks",(a,i)=>{pG(a,this.h.poseLandmarks),ci(this,i)}),this.g.attachEmptyPacketListener("pose_landmarks",a=>{ci(this,a)}),this.g.attachProtoListener("pose_world_landmarks",(a,i)=>{var l=this.h.poseWorldLandmarks;a=FL(a),l.push(_z(a)),ci(this,i)}),this.g.attachEmptyPacketListener("pose_world_landmarks",a=>{ci(this,a)}),this.outputPoseSegmentationMasks&&(Pl(r,"POSE_SEGMENTATION_MASK:pose_segmentation_mask"),dD(this,"pose_segmentation_mask"),this.g.Z("pose_segmentation_mask",(a,i)=>{this.h.poseSegmentationMasks=[hD(this,a,!0,!this.D)],ci(this,i)}),this.g.attachEmptyPacketListener("pose_segmentation_mask",a=>{this.h.poseSegmentationMasks=[],ci(this,a)})),this.g.attachProtoListener("face_landmarks",(a,i)=>{pG(a,this.h.faceLandmarks),ci(this,i)}),this.g.attachEmptyPacketListener("face_landmarks",a=>{ci(this,a)}),this.outputFaceBlendshapes&&(ac(s,"extra_blendshapes"),Pl(r,"FACE_BLENDSHAPES:extra_blendshapes"),this.g.attachProtoListener("extra_blendshapes",(a,i)=>{var l=this.h.faceBlendshapes;this.outputFaceBlendshapes&&(a=R1e(a),l.push(OLe(a.g()??[]))),ci(this,i)}),this.g.attachEmptyPacketListener("extra_blendshapes",a=>{ci(this,a)})),this.g.attachProtoListener("left_hand_landmarks",(a,i)=>{pG(a,this.h.leftHandLandmarks),ci(this,i)}),this.g.attachEmptyPacketListener("left_hand_landmarks",a=>{ci(this,a)}),this.g.attachProtoListener("left_hand_world_landmarks",(a,i)=>{var l=this.h.leftHandWorldLandmarks;a=FL(a),l.push(_z(a)),ci(this,i)}),this.g.attachEmptyPacketListener("left_hand_world_landmarks",a=>{ci(this,a)}),this.g.attachProtoListener("right_hand_landmarks",(a,i)=>{pG(a,this.h.rightHandLandmarks),ci(this,i)}),this.g.attachEmptyPacketListener("right_hand_landmarks",a=>{ci(this,a)}),this.g.attachProtoListener("right_hand_world_landmarks",(a,i)=>{var l=this.h.rightHandWorldLandmarks;a=FL(a),l.push(_z(a)),ci(this,i)}),this.g.attachEmptyPacketListener("right_hand_world_landmarks",a=>{ci(this,a)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Qd.prototype.detectForVideo=Qd.prototype.G,Qd.prototype.detect=Qd.prototype.F,Qd.prototype.setOptions=Qd.prototype.o,Qd.createFromModelPath=function(s,t){return Hl(Qd,s,{baseOptions:{modelAssetPath:t}})},Qd.createFromModelBuffer=function(s,t){return Hl(Qd,s,{baseOptions:{modelAssetBuffer:t}})},Qd.createFromOptions=function(s,t){return Hl(Qd,s,t)},Qd.HAND_CONNECTIONS=GLe,Qd.POSE_CONNECTIONS=Sjt,Qd.FACE_LANDMARKS_LIPS=BLe,Qd.FACE_LANDMARKS_LEFT_EYE=$Le,Qd.FACE_LANDMARKS_LEFT_EYEBROW=ULe,Qd.FACE_LANDMARKS_LEFT_IRIS=wjt,Qd.FACE_LANDMARKS_RIGHT_EYE=qLe,Qd.FACE_LANDMARKS_RIGHT_EYEBROW=VLe,Qd.FACE_LANDMARKS_RIGHT_IRIS=jjt,Qd.FACE_LANDMARKS_FACE_OVAL=HLe,Qd.FACE_LANDMARKS_CONTOURS=Njt,Qd.FACE_LANDMARKS_TESSELATION=kjt;var ov=class extends vy{constructor(s,t){super(new Ob(s,t),"input_image","norm_rect",!0),this.j={classifications:[]},Gi(s=this.h=new sjt,0,1,t=new dh)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){return Gi(this.h,0,2,W5e(s,Kl(this.h,ALe,2))),this.l(s)}sa(s,t){return this.j={classifications:[]},Fb(this,s,t),this.j}ta(s,t,n){return this.j={classifications:[]},sj(this,s,n,t),this.j}m(){var s=new Cy;Du(s,"input_image"),Du(s,"norm_rect"),ac(s,"classifications");const t=new Sy;ej(t,BKs,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.image_classifier.ImageClassifierGraph"),cu(n,"IMAGE:input_image"),cu(n,"NORM_RECT:norm_rect"),Pl(n,"CLASSIFICATIONS:classifications"),n.o(t),e1(s,n),this.g.attachProtoListener("classifications",(r,a)=>{this.j=GKs(TKs(r)),ci(this,a)}),this.g.attachEmptyPacketListener("classifications",r=>{ci(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};ov.prototype.classifyForVideo=ov.prototype.ta,ov.prototype.classify=ov.prototype.sa,ov.prototype.setOptions=ov.prototype.o,ov.createFromModelPath=function(s,t){return Hl(ov,s,{baseOptions:{modelAssetPath:t}})},ov.createFromModelBuffer=function(s,t){return Hl(ov,s,{baseOptions:{modelAssetBuffer:t}})},ov.createFromOptions=function(s,t){return Hl(ov,s,t)};var A0=class extends vy{constructor(s,t){super(new Ob(s,t),"image_in","norm_rect",!0),this.h=new njt,this.embeddings={embeddings:[]},Gi(s=this.h,0,1,t=new dh)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){var t=this.h,n=Kl(this.h,eQe,2);return n=n?n.clone():new eQe,s.l2Normalize!==void 0?qc(n,1,d$(s.l2Normalize)):"l2Normalize"in s&&qc(n,1),s.quantize!==void 0?qc(n,2,d$(s.quantize)):"quantize"in s&&qc(n,2),Gi(t,0,2,n),this.l(s)}za(s,t){return Fb(this,s,t),this.embeddings}Aa(s,t,n){return sj(this,s,n,t),this.embeddings}m(){var s=new Cy;Du(s,"image_in"),Du(s,"norm_rect"),ac(s,"embeddings_out");const t=new Sy;ej(t,$Ks,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.image_embedder.ImageEmbedderGraph"),cu(n,"IMAGE:image_in"),cu(n,"NORM_RECT:norm_rect"),Pl(n,"EMBEDDINGS:embeddings_out"),n.o(t),e1(s,n),this.g.attachProtoListener("embeddings_out",(r,a)=>{r=MKs(r),this.embeddings=function(i){return{embeddings:fN(i,AKs,1).map(l=>{var d,u;const o={headIndex:Mv(l,3)??0??-1,headName:vf(Eu(l,4))??""??""};var c=l.v;return ewt(c,0|c[yi],JZe,hNe(l,1))!==void 0?(l=eA(l=Kl(l,JZe,hNe(l,1),void 0),1,sw,JE()),o.floatEmbedding=l.slice()):(c=new Uint8Array(0),o.quantizedEmbedding=((u=(d=Kl(l,EKs,hNe(l,2),void 0))==null?void 0:d.na())==null?void 0:u.h())??c),o}),timestampMs:djt(Eu(i,2,void 0,void 0,Nge)??Y_t)}}(r),ci(this,a)}),this.g.attachEmptyPacketListener("embeddings_out",r=>{ci(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};A0.cosineSimilarity=function(s,t){if(s.floatEmbedding&&t.floatEmbedding)s=iQe(s.floatEmbedding,t.floatEmbedding);else{if(!s.quantizedEmbedding||!t.quantizedEmbedding)throw Error("Cannot compute cosine similarity between quantized and float embeddings.");s=iQe(aQe(s.quantizedEmbedding),aQe(t.quantizedEmbedding))}return s},A0.prototype.embedForVideo=A0.prototype.Aa,A0.prototype.embed=A0.prototype.za,A0.prototype.setOptions=A0.prototype.o,A0.createFromModelPath=function(s,t){return Hl(A0,s,{baseOptions:{modelAssetPath:t}})},A0.createFromModelBuffer=function(s,t){return Hl(A0,s,{baseOptions:{modelAssetBuffer:t}})},A0.createFromOptions=function(s,t){return Hl(A0,s,t)};var Q5e=class{constructor(s,t,n){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=n}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(n=>{n.close()}),(t=this.categoryMask)==null||t.close()}};function JKs(s){var n,r;const t=function(a){return fN(a,a0,1)}(s.ca()).filter(a=>(vf(Eu(a,1))??"").includes("mediapipe.tasks.TensorsToSegmentationCalculator"));if(s.u=[],t.length>1)throw Error("The graph has more than one mediapipe.tasks.TensorsToSegmentationCalculator.");t.length===1&&(((r=(n=Kl(t[0],Sy,7))==null?void 0:n.j())==null?void 0:r.g())??new Map).forEach((a,i)=>{s.u[Number(i)]=vf(Eu(a,1))??""})}function wQe(s){s.categoryMask=void 0,s.confidenceMasks=void 0,s.qualityScores=void 0}function jQe(s){try{const t=new Q5e(s.confidenceMasks,s.categoryMask,s.qualityScores);if(!s.j)return t;s.j(t)}finally{B1e(s)}}Q5e.prototype.close=Q5e.prototype.close;var Rx=class extends vy{constructor(s,t){super(new Ob(s,t),"image_in","norm_rect",!1),this.u=[],this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new RLe,this.A=new rjt,Gi(this.h,0,3,this.A),Gi(s=this.h,0,1,t=new dh)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?qc(this.h,2,DU(s.displayNamesLocale)):"displayNamesLocale"in s&&qc(this.h,2),"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}L(){JKs(this)}segment(s,t,n){const r=typeof t!="function"?t:{};return this.j=typeof t=="function"?t:n,wQe(this),Fb(this,s,r),jQe(this)}La(s,t,n,r){const a=typeof n!="function"?n:{};return this.j=typeof n=="function"?n:r,wQe(this),sj(this,s,a,t),jQe(this)}Da(){return this.u}m(){var s=new Cy;Du(s,"image_in"),Du(s,"norm_rect");const t=new Sy;ej(t,ijt,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.image_segmenter.ImageSegmenterGraph"),cu(n,"IMAGE:image_in"),cu(n,"NORM_RECT:norm_rect"),n.o(t),e1(s,n),z1e(this,s),this.outputConfidenceMasks&&(ac(s,"confidence_masks"),Pl(n,"CONFIDENCE_MASKS:confidence_masks"),dD(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>hD(this,i,!0,!this.j)),ci(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],ci(this,r)})),this.outputCategoryMask&&(ac(s,"category_mask"),Pl(n,"CATEGORY_MASK:category_mask"),dD(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=hD(this,r,!1,!this.j),ci(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,ci(this,r)})),ac(s,"quality_scores"),Pl(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,ci(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,ci(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};Rx.prototype.getLabels=Rx.prototype.Da,Rx.prototype.segmentForVideo=Rx.prototype.La,Rx.prototype.segment=Rx.prototype.segment,Rx.prototype.setOptions=Rx.prototype.o,Rx.createFromModelPath=function(s,t){return Hl(Rx,s,{baseOptions:{modelAssetPath:t}})},Rx.createFromModelBuffer=function(s,t){return Hl(Rx,s,{baseOptions:{modelAssetBuffer:t}})},Rx.createFromOptions=function(s,t){return Hl(Rx,s,t)};var X5e=class{constructor(s,t,n){this.confidenceMasks=s,this.categoryMask=t,this.qualityScores=n}close(){var s,t;(s=this.confidenceMasks)==null||s.forEach(n=>{n.close()}),(t=this.categoryMask)==null||t.close()}};X5e.prototype.close=X5e.prototype.close;var S_=class extends vy{constructor(s,t){super(new Ob(s,t),"image_in","norm_rect_in",!1),this.outputCategoryMask=!1,this.outputConfidenceMasks=!0,this.h=new RLe,this.u=new rjt,Gi(this.h,0,3,this.u),Gi(s=this.h,0,1,t=new dh)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){return"outputCategoryMask"in s&&(this.outputCategoryMask=s.outputCategoryMask??!1),"outputConfidenceMasks"in s&&(this.outputConfidenceMasks=s.outputConfidenceMasks??!0),super.l(s)}segment(s,t,n,r){const a=typeof n!="function"?n:{};if(this.j=typeof n=="function"?n:r,this.qualityScores=this.categoryMask=this.confidenceMasks=void 0,n=this.C+1,r=new ojt,t.keypoint&&t.scribble)throw Error("Cannot provide both keypoint and scribble.");if(t.keypoint){var i=new xNe;Qk(i,3,d$(!0),!1),Qk(i,1,x7(t.keypoint.x),0),Qk(i,2,x7(t.keypoint.y),0),vz(r,1,G5e,i)}else{if(!t.scribble)throw Error("Must provide either a keypoint or a scribble.");{const o=new qKs;for(i of t.scribble)Qk(t=new xNe,3,d$(!0),!1),Qk(t,1,x7(i.x),0),Qk(t,2,x7(i.y),0),pLe(o,1,xNe,t);vz(r,2,G5e,o)}}this.g.addProtoToStream(r.g(),"mediapipe.tasks.vision.interactive_segmenter.proto.RegionOfInterest","roi_in",n),Fb(this,s,a);e:{try{const o=new X5e(this.confidenceMasks,this.categoryMask,this.qualityScores);if(!this.j){var l=o;break e}this.j(o)}finally{B1e(this)}l=void 0}return l}m(){var s=new Cy;Du(s,"image_in"),Du(s,"roi_in"),Du(s,"norm_rect_in");const t=new Sy;ej(t,ijt,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.interactive_segmenter.InteractiveSegmenterGraphV2"),cu(n,"IMAGE:image_in"),cu(n,"ROI:roi_in"),cu(n,"NORM_RECT:norm_rect_in"),n.o(t),e1(s,n),z1e(this,s),this.outputConfidenceMasks&&(ac(s,"confidence_masks"),Pl(n,"CONFIDENCE_MASKS:confidence_masks"),dD(this,"confidence_masks"),this.g.aa("confidence_masks",(r,a)=>{this.confidenceMasks=r.map(i=>hD(this,i,!0,!this.j)),ci(this,a)}),this.g.attachEmptyPacketListener("confidence_masks",r=>{this.confidenceMasks=[],ci(this,r)})),this.outputCategoryMask&&(ac(s,"category_mask"),Pl(n,"CATEGORY_MASK:category_mask"),dD(this,"category_mask"),this.g.Z("category_mask",(r,a)=>{this.categoryMask=hD(this,r,!1,!this.j),ci(this,a)}),this.g.attachEmptyPacketListener("category_mask",r=>{this.categoryMask=void 0,ci(this,r)})),ac(s,"quality_scores"),Pl(n,"QUALITY_SCORES:quality_scores"),this.g.attachFloatVectorListener("quality_scores",(r,a)=>{this.qualityScores=r,ci(this,a)}),this.g.attachEmptyPacketListener("quality_scores",r=>{this.categoryMask=void 0,ci(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};S_.prototype.segment=S_.prototype.segment,S_.prototype.setOptions=S_.prototype.o,S_.createFromModelPath=function(s,t){return Hl(S_,s,{baseOptions:{modelAssetPath:t}})},S_.createFromModelBuffer=function(s,t){return Hl(S_,s,{baseOptions:{modelAssetBuffer:t}})},S_.createFromOptions=function(s,t){return Hl(S_,s,t)};var lv=class extends vy{constructor(s,t){super(new Ob(s,t),"input_frame_gpu","norm_rect",!1),this.j={detections:[]},Gi(s=this.h=new ljt,0,1,t=new dh)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){return s.displayNamesLocale!==void 0?qc(this.h,2,DU(s.displayNamesLocale)):"displayNamesLocale"in s&&qc(this.h,2),s.maxResults!==void 0?xN(this.h,3,s.maxResults):"maxResults"in s&&qc(this.h,3),s.scoreThreshold!==void 0?Ti(this.h,4,s.scoreThreshold):"scoreThreshold"in s&&qc(this.h,4),s.categoryAllowlist!==void 0?Sge(this.h,5,s.categoryAllowlist):"categoryAllowlist"in s&&qc(this.h,5),s.categoryDenylist!==void 0?Sge(this.h,6,s.categoryDenylist):"categoryDenylist"in s&&qc(this.h,6),this.l(s)}F(s,t){return this.j={detections:[]},Fb(this,s,t),this.j}G(s,t,n){return this.j={detections:[]},sj(this,s,n,t),this.j}m(){var s=new Cy;Du(s,"input_frame_gpu"),Du(s,"norm_rect"),ac(s,"detections");const t=new Sy;ej(t,VKs,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.ObjectDetectorGraph"),cu(n,"IMAGE:input_frame_gpu"),cu(n,"NORM_RECT:norm_rect"),Pl(n,"DETECTIONS:detections"),n.o(t),e1(s,n),this.g.attachProtoVectorListener("detections",(r,a)=>{for(const i of r)r=zwt(i),this.j.detections.push(ujt(r));ci(this,a)}),this.g.attachEmptyPacketListener("detections",r=>{ci(this,r)}),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};lv.prototype.detectForVideo=lv.prototype.G,lv.prototype.detect=lv.prototype.F,lv.prototype.setOptions=lv.prototype.o,lv.createFromModelPath=async function(s,t){return Hl(lv,s,{baseOptions:{modelAssetPath:t}})},lv.createFromModelBuffer=function(s,t){return Hl(lv,s,{baseOptions:{modelAssetBuffer:t}})},lv.createFromOptions=function(s,t){return Hl(lv,s,t)};var J5e=class{constructor(s,t,n){this.landmarks=s,this.worldLandmarks=t,this.segmentationMasks=n}close(){var s;(s=this.segmentationMasks)==null||s.forEach(t=>{t.close()})}};function NQe(s){s.landmarks=[],s.worldLandmarks=[],s.segmentationMasks=void 0}function kQe(s){try{const t=new J5e(s.landmarks,s.worldLandmarks,s.segmentationMasks);if(!s.u)return t;s.u(t)}finally{B1e(s)}}J5e.prototype.close=J5e.prototype.close;var M0=class extends vy{constructor(s,t){super(new Ob(s,t),"image_in","norm_rect",!1),this.landmarks=[],this.worldLandmarks=[],this.outputSegmentationMasks=!1,Gi(s=this.h=new cjt,0,1,t=new dh),this.A=new ejt,Gi(this.h,0,3,this.A),this.j=new Jwt,Gi(this.h,0,2,this.j),xN(this.j,4,1),Ti(this.j,2,.5),Ti(this.A,2,.5),Ti(this.h,4,.5)}get baseOptions(){return Kl(this.h,dh,1)}set baseOptions(s){Gi(this.h,0,1,s)}o(s){return"numPoses"in s&&xN(this.j,4,s.numPoses??1),"minPoseDetectionConfidence"in s&&Ti(this.j,2,s.minPoseDetectionConfidence??.5),"minTrackingConfidence"in s&&Ti(this.h,4,s.minTrackingConfidence??.5),"minPosePresenceConfidence"in s&&Ti(this.A,2,s.minPosePresenceConfidence??.5),"outputSegmentationMasks"in s&&(this.outputSegmentationMasks=s.outputSegmentationMasks??!1),this.l(s)}F(s,t,n){const r=typeof t!="function"?t:{};return this.u=typeof t=="function"?t:n,NQe(this),Fb(this,s,r),kQe(this)}G(s,t,n,r){const a=typeof n!="function"?n:{};return this.u=typeof n=="function"?n:r,NQe(this),sj(this,s,a,t),kQe(this)}m(){var s=new Cy;Du(s,"image_in"),Du(s,"norm_rect"),ac(s,"normalized_landmarks"),ac(s,"world_landmarks"),ac(s,"segmentation_masks");const t=new Sy;ej(t,HKs,this.h);const n=new a0;yy(n,2,"mediapipe.tasks.vision.pose_landmarker.PoseLandmarkerGraph"),cu(n,"IMAGE:image_in"),cu(n,"NORM_RECT:norm_rect"),Pl(n,"NORM_LANDMARKS:normalized_landmarks"),Pl(n,"WORLD_LANDMARKS:world_landmarks"),n.o(t),e1(s,n),z1e(this,s),this.g.attachProtoVectorListener("normalized_landmarks",(r,a)=>{this.landmarks=[];for(const i of r)r=FU(i),this.landmarks.push(F1e(r));ci(this,a)}),this.g.attachEmptyPacketListener("normalized_landmarks",r=>{this.landmarks=[],ci(this,r)}),this.g.attachProtoVectorListener("world_landmarks",(r,a)=>{this.worldLandmarks=[];for(const i of r)r=FL(i),this.worldLandmarks.push(_z(r));ci(this,a)}),this.g.attachEmptyPacketListener("world_landmarks",r=>{this.worldLandmarks=[],ci(this,r)}),this.outputSegmentationMasks&&(Pl(n,"SEGMENTATION_MASK:segmentation_masks"),dD(this,"segmentation_masks"),this.g.aa("segmentation_masks",(r,a)=>{this.segmentationMasks=r.map(i=>hD(this,i,!0,!this.u)),ci(this,a)}),this.g.attachEmptyPacketListener("segmentation_masks",r=>{this.segmentationMasks=[],ci(this,r)})),s=s.g(),this.setGraph(new Uint8Array(s),!0)}};M0.prototype.detectForVideo=M0.prototype.G,M0.prototype.detect=M0.prototype.F,M0.prototype.setOptions=M0.prototype.o,M0.createFromModelPath=function(s,t){return Hl(M0,s,{baseOptions:{modelAssetPath:t}})},M0.createFromModelBuffer=function(s,t){return Hl(M0,s,{baseOptions:{modelAssetBuffer:t}})},M0.createFromOptions=function(s,t){return Hl(M0,s,t)},M0.POSE_CONNECTIONS=Sjt;let tA=null,g7=null;async function eYs(){return tA||g7||(g7=(async()=>{const s=await aP.forVisionTasks("https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@latest/wasm");return tA=await Rx.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}),tA})(),g7)}function tYs(s,t,n,r,a){const i=new Float32Array(s.length);for(let l=0;l=0&&(o-=s[c+u]);const p=Math.min(h,n-1)-Math.max(u+1,0)+1;i[c+d]=o/p}}for(let l=0;l=0&&(o-=i[d*n+l]);const h=Math.min(u,r-1)-Math.max(d+1,0)+1;t[c*n+l]=o/h}}}function sYs(){tA&&(tA.close(),tA=null,g7=null)}function nYs(s,t){const n=N.useRef(null),r=N.useRef(null),a=N.useRef(null),i=N.useRef(null),l=N.useRef(0);N.useRef(0);const[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(null),f=t.type!=="none"&&s!==null;return N.useEffect(()=>{if(t.type==="image"&&t.imageUrl){const y=new Image;y.crossOrigin="anonymous",y.src=t.imageUrl,y.onload=()=>{i.current=y}}else i.current=null},[t.type,t.imageUrl]),N.useEffect(()=>{if(!f||!s){a.current&&(a.current.srcObject=null,a.current=null);return}const y=document.createElement("video");return y.srcObject=s,y.muted=!0,y.playsInline=!0,y.autoplay=!0,y.play().catch(()=>{}),a.current=y,()=>{y.srcObject=null,a.current=null}},[f,s]),N.useEffect(()=>{if(!f){c(null),p(null);return}let y=!1;return(async()=>{u(!0),p(null);try{const v=await eYs();if(y)return;u(!1);const j=a.current;if(!j||(await new Promise(Me=>{if(j.videoWidth>0)return Me();j.onloadedmetadata=()=>Me(),setTimeout(Me,2e3)}),y))return;const w=j.videoWidth||640,S=j.videoHeight||480,A=n.current;if(!A)return;A.width=w,A.height=S;const E=A.getContext("2d",{willReadFrequently:!1,alpha:!1});r.current||(r.current=document.createElement("canvas"));const O=r.current;O.width=w,O.height=S;const D=O.getContext("2d",{willReadFrequently:!1}),I=document.createElement("canvas");I.width=w,I.height=S;const F=I.getContext("2d",{alpha:!1}),z=document.createElement("canvas");z.width=w,z.height=S;const H=z.getContext("2d",{willReadFrequently:!1}),Z=H.createImageData(w,S),Y=Z.data;for(let Me=0;MeW.addTrack(Me)),y||c(W);const se=t.blurRadius??15,oe=t.mirror??!1,he=new Float32Array(w*S),ce=new Float32Array(w*S),me=new Float32Array(w*S);let le=!1;const ve=4,ge=.35,Te=typeof j.requestVideoFrameCallback=="function",Ie=()=>{if(y||!a.current)return;const Me=a.current;if(Me.readyState<2){Ce(Me);return}try{const Pe=performance.now(),Ae=v.segmentForVideo(Me,Pe).confidenceMasks;if(Ae&&Ae.length>0){ce.fill(0);for(let Be=1;Be1?1:it}}if(tYs(ce,he,w,S,ve),le)for(let Be=0;Be=1?255:Je*255|0}if(H.putImageData(Z,0,0),t.type==="blur")F.filter=`blur(${se}px)`,F.drawImage(Me,0,0,w,S),F.filter="none",E.drawImage(I,0,0);else if(t.type==="image"&&i.current){const Be=i.current,we=Be.width/Be.height,Je=w/S;let ke=0,it=0,je=Be.width,He=Be.height;we>Je?(je=Be.height*Je,ke=(Be.width-je)/2):(He=Be.width/Je,it=(Be.height-He)/2),E.drawImage(Be,ke,it,je,He,0,0,w,S)}else E.fillStyle="#000",E.fillRect(0,0,w,S);D.globalCompositeOperation="source-over",D.clearRect(0,0,w,S),D.drawImage(Me,0,0,w,S),D.globalCompositeOperation="destination-in",D.drawImage(z,0,0),D.globalCompositeOperation="source-over",oe?(E.save(),E.translate(w,0),E.scale(-1,1),E.drawImage(O,0,0),E.restore()):E.drawImage(O,0,0);for(const Be of Ae)Be.close()}else E.drawImage(Me,0,0,w,S)}catch{E.drawImage(Me,0,0,w,S)}Ce(Me)},Ce=Me=>{y||(Te?Me.requestVideoFrameCallback(()=>Ie()):l.current=requestAnimationFrame(Ie))};Ce(j)}catch(v){console.error("[useVirtualBackground] init error:",v),y||(u(!1),p(v.message||"Failed to initialize virtual background"))}})(),()=>{y=!0,l.current&&cancelAnimationFrame(l.current),c(null)}},[f,t.type,t.blurRadius,t.imageUrl,s]),N.useEffect(()=>()=>{sYs()},[]),{canvasRef:n,compositedStream:o,isLoading:d,isActive:f,error:h}}function i6({maxDurationSeconds:s=600,onRecordingComplete:t,onError:n,onRecordingStateChange:r,className:a,teleprompterContent:i}){const l=N.useRef(null),o=N.useRef(null),c=N.useRef(null),[d,u]=N.useState(null),h=N.useRef([]),p=N.useRef(null),f=N.useRef(null),y=N.useRef(null),_=N.useRef(null),v=fR(),[j,w]=N.useState("camera"),S=N.useRef(null),A=N.useRef(null),E=N.useRef(null),O=N.useRef(null),D=N.useRef(null),I=N.useRef(null),[F,z]=N.useState(!0),[H,Z]=N.useState(!0),[Y,W]=N.useState(null),[ee,se]=N.useState(!1),[oe,he]=N.useState(!1),[ce,me]=N.useState(null),[le,ve]=N.useState(null),[ge,Te]=N.useState(0),[Ie,Ce]=N.useState("user"),[Me,Pe]=N.useState(0),[Re,Ae]=N.useState(!1),[Be,we]=N.useState(!0),[Je,ke]=N.useState(null),[it,je]=N.useState(!1),[He,$e]=N.useState(null),Ke=N.useRef(null),[Ge,rt]=N.useState(()=>{try{const Hn=localStorage.getItem("video-bg-config");if(Hn)return JSON.parse(Hn)}catch{}return{type:"none"}});N.useEffect(()=>{try{localStorage.setItem("video-bg-config",JSON.stringify(Ge))}catch{}},[Ge]);const[tt,at]=N.useState([]),[Ye,ut]=N.useState([]),[_t,bt]=N.useState(()=>{try{return localStorage.getItem("video-mic-id")||""}catch{return""}}),[$t,Yt]=N.useState(()=>{try{return localStorage.getItem("video-cam-id")||""}catch{return""}});N.useEffect(()=>{try{localStorage.setItem("video-mic-id",_t)}catch{}},[_t]),N.useEffect(()=>{try{localStorage.setItem("video-cam-id",$t)}catch{}},[$t]),N.useEffect(()=>{var Ts,Un,ir;if(!((Ts=navigator.mediaDevices)!=null&&Ts.enumerateDevices))return;const Hn=async()=>{try{const Tr=await navigator.mediaDevices.enumerateDevices();at(Tr.filter(ts=>ts.kind==="audioinput")),ut(Tr.filter(ts=>ts.kind==="videoinput"))}catch(Tr){console.warn("[VideoRecorder] enumerateDevices failed",Tr)}};return Hn(),(ir=(Un=navigator.mediaDevices).addEventListener)==null||ir.call(Un,"devicechange",Hn),()=>{var Tr,ts;return(ts=(Tr=navigator.mediaDevices).removeEventListener)==null?void 0:ts.call(Tr,"devicechange",Hn)}},[Y]);const{canvasRef:Ds,compositedStream:Ls,isLoading:xs,isActive:Lt,error:Jt}=nYs(d,Ge),gt=N.useRef(n);gt.current=n;const zt=N.useCallback(Hn=>{z(Hn)},[]),As=N.useRef(F),Xt=N.useCallback(()=>{E.current&&(cancelAnimationFrame(E.current),E.current=null),O.current&&(O.current.terminate(),O.current=null),S.current&&(S.current.getTracks().forEach(Hn=>Hn.stop()),S.current=null),D.current&&(D.current.getTracks().forEach(Hn=>Hn.stop()),D.current=null),I.current&&(I.current.srcObject=null,I.current=null)},[]),Qs=N.useCallback(async()=>{var Hn;try{const Ts=await navigator.mediaDevices.getDisplayMedia({video:{width:{ideal:1920},height:{ideal:1080}},audio:!0});S.current=Ts;let Un=null;try{Un=await navigator.mediaDevices.getUserMedia({video:$t?{deviceId:{exact:$t},width:{ideal:320},height:{ideal:240}}:{width:{ideal:320},height:{ideal:240}},audio:!1})}catch{console.warn("[VideoRecorder] No webcam for PiP overlay")}let ir=null;try{ir=await navigator.mediaDevices.getUserMedia({audio:{echoCancellation:!0,noiseSuppression:!0,..._t?{deviceId:{exact:_t}}:{}}}),console.log("[VideoRecorder] mic acquired for screen recording",ir.getAudioTracks().map(Yn=>Yn.label))}catch(Yn){console.warn("[VideoRecorder] No mic audio for screen recording",Yn);try{ir=await navigator.mediaDevices.getUserMedia({audio:!0})}catch{}}const Tr=Ts.getVideoTracks()[0],ts=Tr.getSettings(),Fe=ts.width||1920,Qe=ts.height||1080,ot=document.createElement("canvas");ot.width=Fe,ot.height=Qe,A.current=ot;const St=ot.getContext("2d");let Bt=null;Un&&(Bt=document.createElement("video"),Bt.srcObject=Un,Bt.muted=!0,Bt.playsInline=!0,Bt.autoplay=!0,await Bt.play(),I.current=Bt);const Vt=document.createElement("video");Vt.srcObject=Ts,Vt.muted=!0,Vt.playsInline=!0,Vt.autoplay=!0,await Vt.play();const fs=()=>{if(St.drawImage(Vt,0,0,Fe,Qe),Bt&&Bt.readyState>=2){const Yn=Math.round(Fe*.2),_r=Math.round(Yn*(Bt.videoHeight/Bt.videoWidth||.75)),wr=Fe-Yn-20,Er=Qe-_r-20,xa=12;St.save(),St.beginPath(),St.moveTo(wr+xa,Er),St.lineTo(wr+Yn-xa,Er),St.quadraticCurveTo(wr+Yn,Er,wr+Yn,Er+xa),St.lineTo(wr+Yn,Er+_r-xa),St.quadraticCurveTo(wr+Yn,Er+_r,wr+Yn-xa,Er+_r),St.lineTo(wr+xa,Er+_r),St.quadraticCurveTo(wr,Er+_r,wr,Er+_r-xa),St.lineTo(wr,Er+xa),St.quadraticCurveTo(wr,Er,wr+xa,Er),St.closePath(),St.clip(),St.translate(wr+Yn,Er),St.scale(-1,1),St.drawImage(Bt,0,0,Yn,_r),St.restore(),St.strokeStyle="rgba(255,255,255,0.6)",St.lineWidth=2,St.beginPath(),St.moveTo(wr+xa,Er),St.lineTo(wr+Yn-xa,Er),St.quadraticCurveTo(wr+Yn,Er,wr+Yn,Er+xa),St.lineTo(wr+Yn,Er+_r-xa),St.quadraticCurveTo(wr+Yn,Er+_r,wr+Yn-xa,Er+_r),St.lineTo(wr+xa,Er+_r),St.quadraticCurveTo(wr,Er+_r,wr,Er+_r-xa),St.lineTo(wr,Er+xa),St.quadraticCurveTo(wr,Er,wr+xa,Er),St.closePath(),St.stroke()}},lt="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}}",ns=new Blob([lt],{type:"application/javascript"}),Vs=new Worker(URL.createObjectURL(ns));O.current=Vs,Vs.onmessage=()=>fs(),Vs.postMessage({type:"start",fps:30}),fs();const ys=ot.captureStream(30),mn=[],On=Ts.getAudioTracks();On.length&&mn.push(...On),ir&&mn.push(...ir.getAudioTracks());const vn=new MediaStream([...ys.getVideoTracks(),...mn]);return D.current=vn,Tr.onended=()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),Xt()},vn}catch(Ts){return console.error("[VideoRecorder] Screen capture error:",Ts),Ts.name!=="NotAllowedError"&&((Hn=gt.current)==null||Hn.call(gt,"Failed to start screen capture: "+(Ts.message||"Unknown error"))),null}},[Xt]),ks=N.useCallback(async()=>{var Ts,Un;Z(!0),ke(null);const Hn=v&&F;console.log("[VideoRecorder] initCamera start",{isMobile:v,usePortraitMode:F,shouldBePortrait:Hn,facingMode:Ie});try{if(!navigator.mediaDevices||!navigator.mediaDevices.getUserMedia)throw new Error("Camera not available in this browser or context. Try opening in a new tab.");c.current&&(console.log("[VideoRecorder] stopping existing stream"),c.current.getTracks().forEach(St=>St.stop()));const ir=v&&Hn?{width:{ideal:720},height:{ideal:1280}}:{width:{ideal:1280},height:{ideal:720}},Tr=$t?{...ir,deviceId:{exact:$t}}:{...ir,facingMode:{ideal:Ie}},ts={echoCancellation:!0,noiseSuppression:!0,..._t?{deviceId:{exact:_t}}:{}};console.log("[VideoRecorder] requesting getUserMedia",Tr);const Fe=await navigator.mediaDevices.getUserMedia({video:Tr,audio:ts});if(console.log("[VideoRecorder] getUserMedia success"),Fe.getVideoTracks().length===0)throw new Error("Camera stream started but no video track was provided.");c.current=Fe,u(Fe),W(!0);const ot=Fe.getVideoTracks()[0].getSettings();if(console.log("[VideoRecorder] Camera initialized with dimensions:",ot.width,"x",ot.height),l.current){const St=l.current;St.srcObject=Fe,St.muted=!0,St.playsInline=!0,St.autoplay=!0,St.setAttribute("muted",""),St.setAttribute("playsinline",""),St.setAttribute("autoplay","");try{(Ts=St.load)==null||Ts.call(St)}catch(Vt){console.warn("[VideoRecorder] videoEl.load failed",Vt)}const Bt=async()=>{try{return await St.play(),console.log("[VideoRecorder] preview play ok"),je(!1),setTimeout(()=>{console.debug("[VideoRecorder] preview metrics",{readyState:St.readyState,videoWidth:St.videoWidth,videoHeight:St.videoHeight})},300),!0}catch(Vt){return console.warn("[VideoRecorder] preview play blocked",Vt),je(!0),!1}};await new Promise(Vt=>{let fs=!1;const lt=()=>{fs||(fs=!0,Vt())},ns=()=>{Bt().finally(lt)};St.onloadedmetadata=ns,St.onloadeddata=ns,setTimeout(lt,1500)})}try{f.current=new AudioContext;const St=f.current.createMediaStreamSource(Fe);y.current=f.current.createAnalyser(),y.current.fftSize=256,St.connect(y.current);const Bt=()=>{if(y.current){const Vt=new Uint8Array(y.current.frequencyBinCount);y.current.getByteFrequencyData(Vt);const fs=Vt.reduce((lt,ns)=>lt+ns)/Vt.length;Pe(Math.min(100,fs/128*100))}_.current=requestAnimationFrame(Bt)};Bt()}catch(St){console.warn("Audio context not available:",St)}}catch(ir){console.error("Camera initialization error:",ir),W(!1);let Tr="Failed to access camera or microphone.";ir.name==="NotAllowedError"?Tr="Camera permission denied. Please allow camera access in your browser settings.":ir.name==="NotFoundError"?Tr="No camera found. Please connect a camera and try again.":ir.name==="NotReadableError"?Tr="Camera is in use by another application. Please close other apps using the camera.":ir.message&&(Tr=ir.message),ke(Tr),(Un=gt.current)==null||Un.call(gt,Tr)}finally{Z(!1)}},[Ie,v,F,_t,$t]);N.useEffect(()=>{As.current!==F&&Y&&!ee&&!le&&(As.current=F,ks())},[F,Y,ee,le,ks]),N.useEffect(()=>(ks(),()=>{c.current&&c.current.getTracks().forEach(Hn=>Hn.stop()),p.current&&clearInterval(p.current),_.current&&cancelAnimationFrame(_.current),f.current&&f.current.close(),Ke.current&&clearInterval(Ke.current),le&&URL.revokeObjectURL(le),Xt()}),[ks,le]),N.useEffect(()=>{if(H||Y!==!0||le)return;const Hn=c.current,Ts=l.current;!Hn||!Ts||Lt||(Ts.srcObject!==Hn&&(Ts.srcObject=Hn,Ts.muted=!0,Ts.playsInline=!0,Ts.autoplay=!0,Ts.setAttribute("muted",""),Ts.setAttribute("playsinline",""),Ts.setAttribute("autoplay","")),Ts.play().then(()=>je(!1)).catch(Un=>{je(!0),console.warn("Live preview play blocked on mount:",Un)}))},[Y,H,le,Lt]),N.useEffect(()=>{r==null||r(ee)},[ee,r]);const $s=N.useCallback(async()=>{if(le)return;const Hn=l.current;if(Hn)try{await Hn.play(),je(!1)}catch(Ts){je(!0),console.warn("Live preview still blocked (needs user gesture):",Ts)}},[le]),an=N.useCallback(()=>{o.current&&o.current.state!=="inactive"&&o.current.stop(),p.current&&(clearInterval(p.current),p.current=null),Xt(),se(!1),he(!1)},[Xt]),tn=N.useCallback(async()=>{let Hn=null;if(j==="screen"){if(Hn=await Qs(),!Hn)return}else Hn=Lt&&Ls?Ls:c.current;if(!Hn)return;$s(),h.current=[],Te(0);const Un=["video/webm;codecs=vp9,opus","video/webm;codecs=vp8,opus","video/webm;codecs=vp9","video/webm;codecs=vp8","video/webm","video/mp4"].find(Tr=>MediaRecorder.isTypeSupported(Tr)),ir=new MediaRecorder(Hn,Un?{mimeType:Un,videoBitsPerSecond:j==="screen"?4e6:25e5}:{videoBitsPerSecond:j==="screen"?4e6:25e5});ir.ondataavailable=Tr=>{Tr.data.size>0&&h.current.push(Tr.data)},ir.onstop=()=>{var Qe;const Tr=ir.mimeType||Un||((Qe=h.current[0])==null?void 0:Qe.type)||"video/webm",ts=new Blob(h.current,{type:Tr});me(ts);const Fe=URL.createObjectURL(ts);ve(Fe)},o.current=ir,ir.start(100),se(!0),p.current=setInterval(()=>{Te(Tr=>Tr>=s-1?(an(),s):Tr+1)},1e3)},[$s,s,an,Lt,Ls,j,Qs]),er=N.useCallback(()=>{Ke.current&&(clearInterval(Ke.current),Ke.current=null),$e(3);let Hn=3;Ke.current=setInterval(()=>{Hn-=1,Hn<=0?(Ke.current&&clearInterval(Ke.current),Ke.current=null,$e(null),tn()):$e(Hn)},1e3)},[tn]),xn=N.useCallback(()=>{o.current&&o.current.state==="recording"&&(o.current.pause(),he(!0),p.current&&clearInterval(p.current))},[]),Pn=N.useCallback(()=>{o.current&&o.current.state==="paused"&&(o.current.resume(),he(!1),p.current=setInterval(()=>{Te(Hn=>Hn>=s-1?(an(),s):Hn+1)},1e3))},[s,an]),Qn=N.useCallback(()=>{le&&URL.revokeObjectURL(le),me(null),ve(null),Te(0),Ae(!1),we(!0),l.current&&c.current&&!Lt&&(l.current.srcObject=c.current,l.current.muted=!0,$s())},[$s,le,Lt]),sa=N.useCallback(()=>{Ce(Hn=>Hn==="user"?"environment":"user")},[]),na=N.useCallback(()=>{ce&&t(ce,ge)},[ce,ge,t]),Es=N.useCallback(()=>{l.current&&le&&(Re?l.current.pause():(we(!1),l.current.muted=!1,l.current.play()),Ae(!Re))},[le,Re]);N.useEffect(()=>{if(!le)return;const Hn=l.current;if(!Hn)return;we(!1),Hn.pause(),Hn.removeAttribute("src"),Hn.srcObject=null,Hn.load(),Hn.src=le,Hn.currentTime=0,Hn.playsInline=!0,Hn.muted=!1,Hn.onended=()=>Ae(!1);const Ts=()=>{var Tr;const Un=Hn.error,ir=Un?`Recorded video failed to play (code ${Un.code}). Likely unsupported format/codec in this browser.`:"Recorded video failed to play.";console.warn("[VideoRecorder] recorded playback error",Un),(Tr=gt.current)==null||Tr.call(gt,ir)};return Hn.addEventListener("error",Ts),Hn.load(),()=>{Hn.removeEventListener("error",Ts)}},[le]);const mi=Hn=>{const Ts=Math.floor(Hn/60),Un=Hn%60;return`${Ts}:${Un.toString().padStart(2,"0")}`},Ar=j==="screen"?"aspect-video":v&&F?"aspect-[9/16]":"aspect-video";return H?e.jsx("div",{className:Mt("flex items-center justify-center bg-black rounded-lg",Ar,a),children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(rs,{className:"h-12 w-12 animate-spin mx-auto mb-4"}),e.jsx("p",{children:"Initializing camera..."})]})}):Y===!1?e.jsx("div",{className:Mt("flex items-center justify-center bg-black rounded-lg",Ar,a),children:e.jsxs("div",{className:"text-center text-white p-8 max-w-md",children:[e.jsx(Bi,{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:Je||"Please allow camera and microphone access to record videos."}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(B,{onClick:()=>ks(),variant:"secondary",className:"w-full",children:[e.jsx(Ei,{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:Mt("flex flex-col gap-2",a),children:[!ee&&!le&&e.jsxs("div",{className:"flex items-center justify-center gap-1 p-1 bg-muted rounded-lg",children:[e.jsxs(B,{variant:j==="camera"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>w("camera"),children:[e.jsx(Jf,{className:"h-4 w-4"}),"Camera"]}),e.jsxs(B,{variant:j==="screen"?"default":"ghost",size:"sm",className:"gap-1.5 flex-1",onClick:()=>w("screen"),children:[e.jsx(MA,{className:"h-4 w-4"}),"Screen"]})]}),j==="camera"&&!ee&&!le&&e.jsx(xWs,{value:Ge,onChange:rt,isLoading:xs,disabled:ee}),!ee&&!le&&(tt.length>0||Ye.length>0)&&e.jsxs("div",{className:"flex flex-wrap items-center gap-3 px-3 py-2 bg-muted/40 rounded-lg",children:[tt.length>0&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Dv,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(us,{value:_t||"default",onValueChange:Hn=>bt(Hn==="default"?"":Hn),children:[e.jsx(ls,{className:"h-8 text-xs",children:e.jsx(hs,{placeholder:"Default microphone"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"default",children:"Default microphone"}),tt.map(Hn=>e.jsx(Ze,{value:Hn.deviceId,children:Hn.label||`Microphone ${Hn.deviceId.slice(0,6)}`},Hn.deviceId))]})]})]}),Ye.length>1&&j==="camera"&&e.jsxs("div",{className:"flex items-center gap-2 flex-1 min-w-[200px]",children:[e.jsx(Jf,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsxs(us,{value:$t||"default",onValueChange:Hn=>Yt(Hn==="default"?"":Hn),children:[e.jsx(ls,{className:"h-8 text-xs",children:e.jsx(hs,{placeholder:"Default camera"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"default",children:"Default camera"}),Ye.map(Hn=>e.jsx(Ze,{value:Hn.deviceId,children:Hn.label||`Camera ${Hn.deviceId.slice(0,6)}`},Hn.deviceId))]})]})]})]}),j==="camera"&&v&&!ee&&!le&&e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2 bg-muted/50 rounded-lg",children:[e.jsx(mb,{className:Mt("h-4 w-4",F?"text-muted-foreground":"text-primary")}),e.jsx(ne,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Landscape"}),e.jsx(jn,{id:"orientation-toggle",checked:F,onCheckedChange:zt}),e.jsx(ne,{htmlFor:"orientation-toggle",className:"text-sm text-muted-foreground",children:"Portrait"}),e.jsx(tg,{className:Mt("h-4 w-4",F?"text-primary":"text-muted-foreground")})]}),j==="screen"&&!ee&&!le&&e.jsxs("div",{className:"flex items-center justify-center gap-2 py-3 px-4 bg-muted/50 rounded-lg text-sm text-muted-foreground",children:[e.jsx(MA,{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:Mt("relative bg-black rounded-lg overflow-hidden"),onPointerDown:()=>{$s()},children:[e.jsx("video",{ref:l,src:le??void 0,className:Mt("w-full bg-black",F&&!le?"object-contain":"object-cover",Ar,!le&&Ie==="user"!==(Ge.mirror??!1)&&"scale-x-[-1]",Lt&&!le&&"hidden"),playsInline:!0,controls:!!le,muted:le?Be:!0,autoPlay:!le},le??"live"),Lt&&!le&&e.jsx("canvas",{ref:Ds,className:Mt("w-full bg-black",F?"object-contain":"object-cover",Ar,Ie==="user"!==(Ge.mirror??!1)&&"scale-x-[-1]")}),Lt&&xs&&!le&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/60 z-20",children:e.jsxs("div",{className:"text-center text-white",children:[e.jsx(rs,{className:"h-8 w-8 animate-spin mx-auto mb-2"}),e.jsx("p",{className:"text-sm",children:"Loading virtual background…"})]})}),!le&&it&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40",children:e.jsx(B,{type:"button",variant:"secondary",onClick:()=>void $s(),className:"bg-white/20 hover:bg-white/30 text-white",children:"Tap to enable preview"})}),i&&!le&&e.jsx("div",{className:"absolute inset-0 pointer-events-none",children:i}),He!==null&&!le&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center z-30 pointer-events-none",children:e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx("div",{className:"text-white font-bold drop-shadow-lg animate-scale-in",style:{fontSize:"96px",lineHeight:1,textShadow:"0 4px 16px rgba(0,0,0,0.8)"},children:He},He),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),ee&&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:Mt("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:[mi(ge)," / ",mi(s)]})]}),ee&&e.jsx("div",{className:"absolute top-0 left-0 right-0",children:e.jsx(fi,{value:ge/s*100,className:"h-1 rounded-none"})}),!le&&e.jsxs("div",{className:"absolute bottom-20 left-4 flex items-center gap-2 bg-black/50 px-3 py-1.5 rounded-full",children:[e.jsx(Dv,{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:`${Me}%`}})})]}),e.jsx("div",{className:"absolute bottom-4 left-0 right-0 flex justify-center gap-3 px-4",children:le?e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",size:"lg",className:"bg-white/20 hover:bg-white/30 text-white",onClick:Qn,children:[e.jsx(Ei,{className:"h-5 w-5 mr-2"}),"Re-record"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:Es,children:Re?e.jsx(gf,{className:"h-5 w-5"}):e.jsx(El,{className:"h-5 w-5"})}),e.jsxs(B,{size:"lg",className:"bg-green-500 hover:bg-green-600 text-white",onClick:na,children:[e.jsx(Lr,{className:"h-5 w-5 mr-2"}),"Use This Video"]})]}):e.jsxs(e.Fragment,{children:[j==="camera"?e.jsx(B,{variant:"secondary",size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:sa,disabled:ee||He!==null,children:e.jsx(Bm,{className:"h-5 w-5"})}):e.jsx("div",{className:"h-12 w-12"}),!ee&&He===null?e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:j==="screen"?tn:er,children:j==="screen"?e.jsx(MA,{className:"h-6 w-6"}):e.jsx(fr,{className:"h-6 w-6"})}):e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"icon",className:"h-12 w-12 rounded-full bg-white/20 hover:bg-white/30 text-white",onClick:oe?Pn:xn,children:oe?e.jsx(El,{className:"h-5 w-5"}):e.jsx(gf,{className:"h-5 w-5"})}),e.jsx(B,{size:"icon",className:"h-16 w-16 rounded-full bg-red-500 hover:bg-red-600 text-white",onClick:an,children:e.jsx(ay,{className:"h-6 w-6 fill-current"})})]}),e.jsx("div",{className:"h-12 w-12"})]})})]})]})}function rYs({open:s,onOpenChange:t,onUploaded:n}){const{user:r}=vs(),{toast:a}=Fa(),[i,l]=N.useState(!1),o=async(c,d)=>{if(r){l(!0);try{const u=c.type.includes("mp4")?"mp4":"webm",h=`${r.id}/${crypto.randomUUID()}.${u}`,{error:p}=await q.storage.from("cma-videos").upload(h,c,{contentType:c.type||"video/webm",upsert:!1});if(p)throw p;const{data:f,error:y}=await q.storage.from("cma-videos").createSignedUrl(h,60*60*24*365*5);if(y||!(f!=null&&f.signedUrl))throw y||new Error("Could not sign video URL");n(f.signedUrl,Math.round(d)),a({title:"Video added to your CMA"}),t(!1)}catch(u){a({title:"Upload failed",description:u==null?void 0:u.message,variant:"destructive"})}finally{l(!1)}}};return e.jsx(_s,{open:s,onOpenChange:c=>!i&&t(c),children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Record a personal message"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"A 30-second hello goes a long way. Welcome your client, explain the price, and invite their reply."})]}),i?e.jsxs("div",{className:"py-12 flex flex-col items-center gap-3",children:[e.jsx(rs,{className:"w-8 h-8 animate-spin text-primary"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Uploading your video…"})]}):e.jsx(i6,{maxDurationSeconds:180,onRecordingComplete:o})]})})}function aYs({value:s,onChange:t}){const{user:n}=vs(),[r,a]=N.useState(!1);return e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(fr,{className:"w-4 h-4"}),"Personal Video Message"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds the human touch your client will remember. Plays right at the top of the CMA."})]}),e.jsxs(Ee,{className:"space-y-3",children:[s!=null&&s.url?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative rounded-lg overflow-hidden bg-black aspect-video group",children:[e.jsx("video",{src:s.url,poster:s.thumb,controls:!0,className:"w-full h-full object-cover"}),e.jsx("button",{className:"absolute top-2 right-2 bg-black/60 text-white rounded-full p-1.5 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>t(null),"aria-label":"Remove video",type:"button",children:e.jsx($n,{className:"w-3.5 h-3.5"})})]}),e.jsxs("p",{className:"text-xs text-emerald-700 flex items-center gap-1",children:[e.jsx(El,{className:"w-3 h-3"})," Video attached"]})]}):e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(e6,{userId:n==null?void 0:n.id,triggerLabel:"Pick from Library",triggerVariant:"outline",triggerSize:"default",triggerClassName:"w-full justify-center gap-2",onSelect:()=>{},onSelectVideo:i=>t({url:i.playback_url,thumb:i.thumbnail_url,label:i.title||i.recipient_name})}),e.jsxs(B,{variant:"outline",onClick:()=>a(!0),className:"gap-2",children:[e.jsx(fr,{className:"w-4 h-4"}),"Record New"]})]}),e.jsx(rYs,{open:r,onOpenChange:a,onUploaded:i=>t({url:i,label:"Personal message"})})]})]})}function Z1(s){const t=Number(String(s).replace(/[^0-9.]/g,""));return Number.isFinite(t)&&t>0?t:null}function iYs({open:s,onOpenChange:t,subject:n,onSave:r,isSaving:a}){const[i,l]=N.useState({bedrooms:"",bathrooms:"",sqft:"",yearBuilt:"",propertyType:"",propertySubType:""});N.useEffect(()=>{s&&l({bedrooms:(n==null?void 0:n.bedrooms)!=null?String(n.bedrooms):"",bathrooms:(n==null?void 0:n.bathrooms)!=null?String(n.bathrooms):"",sqft:(n==null?void 0:n.sqft)!=null?String(n.sqft):"",yearBuilt:(n==null?void 0:n.yearBuilt)!=null?String(n.yearBuilt):"",propertyType:(n==null?void 0:n.propertyType)||"Residential",propertySubType:(n==null?void 0:n.propertySubType)||"Single Family"})},[s,n]);const o=async()=>{await r({bedrooms:Z1(i.bedrooms),bathrooms:Z1(i.bathrooms),sqft:Z1(i.sqft),yearBuilt:Z1(i.yearBuilt),propertyType:i.propertyType||null,propertySubType:i.propertySubType||null}),t(!1)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(ws,{children:"Fill in the subject property basics"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"When the MLS feed does not return the home details, add the basics here and LevelUp will keep the CMA moving."}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Beds"}),e.jsx(ye,{inputMode:"decimal",value:i.bedrooms,onChange:c=>l(d=>({...d,bedrooms:c.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Baths"}),e.jsx(ye,{inputMode:"decimal",value:i.bathrooms,onChange:c=>l(d=>({...d,bathrooms:c.target.value})),placeholder:"2"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Sq Ft"}),e.jsx(ye,{inputMode:"numeric",value:i.sqft,onChange:c=>l(d=>({...d,sqft:c.target.value})),placeholder:"1850"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Year Built"}),e.jsx(ye,{inputMode:"numeric",value:i.yearBuilt,onChange:c=>l(d=>({...d,yearBuilt:c.target.value})),placeholder:"2006"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Property Type"}),e.jsx(ye,{value:i.propertyType,onChange:c=>l(d=>({...d,propertyType:c.target.value})),placeholder:"Residential"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Subtype"}),e.jsx(ye,{value:i.propertySubType,onChange:c=>l(d=>({...d,propertySubType:c.target.value})),placeholder:"Single Family"})]})]}),e.jsxs(B,{className:"w-full",onClick:o,disabled:a,children:[a?e.jsx(rs,{className:"w-4 h-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"w-4 h-4 mr-2"}),"Save subject details"]})]})]})})}function oYs({open:s,onOpenChange:t,subject:n,onAdd:r}){const[a,i]=N.useState({address:"",city:"",state:"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""});N.useEffect(()=>{s&&i({address:"",city:(n==null?void 0:n.city)||"",state:(n==null?void 0:n.state)||"",status:"Closed",price:"",bedrooms:"",bathrooms:"",sqft:"",yearBuilt:""})},[s,n]);const l=()=>{const o=Z1(a.price),c=Z1(a.sqft);!a.address.trim()||!o||!c||(r({mlsNumber:`manual-${Date.now()}`,source_provider:"manual",manual:!0,selected:!0,score:100,address:a.address.trim(),city:a.city||(n==null?void 0:n.city)||"",state:(a.state||(n==null?void 0:n.state)||"").toUpperCase(),status:a.status||"Closed",price:o,soldPrice:/closed|sold/i.test(a.status)?o:null,bedrooms:Z1(a.bedrooms),bathrooms:Z1(a.bathrooms),sqft:c,yearBuilt:Z1(a.yearBuilt),photos:[]}),t(!1))};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsx(ws,{children:"Add a comparable manually"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Use this when the MLS feed misses a property or you already know the best comp. Add at least the address, price, and square footage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-3",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{className:"text-xs",children:"Address"}),e.jsx(ye,{value:a.address,onChange:o=>i(c=>({...c,address:o.target.value})),placeholder:"123 Comparable St"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"City"}),e.jsx(ye,{value:a.city,onChange:o=>i(c=>({...c,city:o.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"State"}),e.jsx(ye,{maxLength:2,value:a.state,onChange:o=>i(c=>({...c,state:o.target.value.toUpperCase()}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Status"}),e.jsx(ye,{value:a.status,onChange:o=>i(c=>({...c,status:o.target.value})),placeholder:"Closed"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Price"}),e.jsx(ye,{inputMode:"numeric",value:a.price,onChange:o=>i(c=>({...c,price:o.target.value})),placeholder:"525000"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Sq Ft"}),e.jsx(ye,{inputMode:"numeric",value:a.sqft,onChange:o=>i(c=>({...c,sqft:o.target.value})),placeholder:"1800"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Beds"}),e.jsx(ye,{inputMode:"decimal",value:a.bedrooms,onChange:o=>i(c=>({...c,bedrooms:o.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Baths"}),e.jsx(ye,{inputMode:"decimal",value:a.bathrooms,onChange:o=>i(c=>({...c,bathrooms:o.target.value})),placeholder:"2"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Year Built"}),e.jsx(ye,{className:"max-w-[180px]",inputMode:"numeric",value:a.yearBuilt,onChange:o=>i(c=>({...c,yearBuilt:o.target.value})),placeholder:"2005"})]}),e.jsxs(B,{className:"w-full",onClick:l,disabled:!a.address.trim()||!Z1(a.price)||!Z1(a.sqft),children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Add comp to CMA"]})]})]})})}function lYs(){var Ce,Me,Pe,Re,Ae,Be,we;const{id:s}=bi(),t=Ln(),{toast:n}=Fa(),{data:r,isLoading:a}=EGs(s),{data:i}=AGs(s),l=MGs(),o=LGs(),c=DGs(),{leadSite:d,isLoading:u}=Ap(),[h,p]=N.useState([]),[f,y]=N.useState({sqftPct:.2,monthsBack:6,maxMiles:5,statuses:["Active","Pending","Closed"]}),[_,v]=N.useState(null),[j,w]=N.useState(!1),[S,A]=N.useState({low:"",likely:"",high:"",note:""}),[E,O]=N.useState(!1),[D,I]=N.useState(!1),[F,z]=N.useState(!1),[H,Z]=N.useState(null),Y=async Je=>{var Ke,Ge;if(!r||!(Je!=null&&Je.address)||!(Je!=null&&Je.city)||!(Je!=null&&Je.state))return Je;let ke={...Je};const it=async rt=>{const{data:tt,error:at}=await q.functions.invoke("cma-subject-lookup",{body:{address:rt.address,city:rt.city,state:rt.state,zip:rt.zip,latitude:rt.latitude,longitude:rt.longitude,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id}});if(at)throw at;return(tt==null?void 0:tt.matches)||[]},je=rt=>{const at=rt.find(bt=>Number.isFinite(Number(bt.latitude))&&Number.isFinite(Number(bt.longitude)))||rt[0];if(!at)return;const Ye=typeof at.match_type=="string"&&at.match_type.startsWith("nearby-"),ut=Ye&&Number.isFinite(Number(ke.latitude))&&Number.isFinite(Number(ke.longitude)),_t=bt=>at[bt]!==void 0&&at[bt]!==null&&at[bt]!==""&&at[bt]!==0?at[bt]:ke[bt];ke={...ke,bedrooms:_t("bedrooms"),bathrooms:_t("bathrooms"),sqft:_t("sqft"),yearBuilt:_t("yearBuilt"),lotSize:_t("lotSize"),propertyType:_t("propertyType"),propertySubType:_t("propertySubType"),source_provider:at.source_provider??ke.source_provider,match_type:at.match_type??ke.match_type,matched_mls_address:Ye?at.address:ke.matched_mls_address,latitude:ut?ke.latitude:at.latitude??ke.latitude,longitude:ut?ke.longitude:at.longitude??ke.longitude,mlsNumber:Ye?ke.mlsNumber:at.mlsNumber??ke.mlsNumber,photos:!Ye&&Array.isArray(at.photos)&&at.photos.length?at.photos:ke.photos}};je(await it(ke));const He=()=>Number.isFinite(Number(ke.latitude))&&Number.isFinite(Number(ke.longitude));if(!He()){const{data:rt}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle(),tt=rt==null?void 0:rt.value;if(tt){const at=encodeURIComponent(`${ke.address}, ${ke.city}, ${ke.state} ${ke.zip||""}`.trim()),ut=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${at}.json?access_token=${tt}&limit=1&country=us`)).json(),_t=(Ge=(Ke=ut==null?void 0:ut.features)==null?void 0:Ke[0])==null?void 0:Ge.center;Array.isArray(_t)&&_t.length===2&&(ke.longitude=_t[0],ke.latitude=_t[1])}}if((!ke.bedrooms||!ke.bathrooms||!ke.sqft||!ke.yearBuilt)&&He())try{je(await it(ke))}catch(rt){console.warn("second-pass subject lookup failed",rt)}return JSON.stringify(ke)!==JSON.stringify(Je)&&await l.mutateAsync({id:r.id,patch:{subject:ke}}),ke};N.useEffect(()=>{var it,je;r!=null&&r.settings&&y({sqftPct:r.settings.sqftPct??.2,monthsBack:r.settings.monthsBack??6,maxMiles:r.settings.maxMiles??5,statuses:r.settings.statuses??["Active","Pending","Closed"]});const Je=(it=r==null?void 0:r.settings)==null?void 0:it.priceOverride;Je!=null&&Je.enabled&&(w(!0),A({low:Je.low!=null?String(Je.low):"",likely:Je.likely!=null?String(Je.likely):"",high:Je.high!=null?String(Je.high):"",note:Je.note??""}));const ke=(je=r==null?void 0:r.settings)==null?void 0:je.personalVideo;ke!=null&&ke.url&&Z({url:ke.url,thumb:ke.thumb,label:ke.label})},[r==null?void 0:r.id]);const W=N.useRef(!1);N.useEffect(()=>{W.current||i!=null&&i.length&&(p(i.map(Je=>({...Je.snapshot,selected:Je.selected,manual:Je.manual,score:Je.score}))),W.current=!0)},[i]);const ee=N.useRef(null);N.useEffect(()=>{if(!r||u)return;const Je=r.subject||{},ke=Number.isFinite(Number(Je.latitude))&&Number.isFinite(Number(Je.longitude)),it=!!(Number(Je.bedrooms)||Number(Je.bathrooms)||Number(Je.sqft)||Number(Je.yearBuilt));if(ke&&it)return;const je=`${r.id}:${(d==null?void 0:d.id)??r.lead_site_id??"no-site"}`;ee.current!==je&&(!Je.address||!Je.city||!Je.state||(ee.current=je,(async()=>{try{await Y(Je)}catch(He){console.warn("subject enrich failed",He)}})()))},[r==null?void 0:r.id,r==null?void 0:r.lead_site_id,d==null?void 0:d.id,u]);const se=N.useMemo(()=>r?gZe(r.subject,h):null,[r,h]),oe=async()=>{if(r)try{const Je=await Y(r.subject),ke=await o.mutateAsync({subject:Je,filters:f,leadSiteId:(d==null?void 0:d.id)??r.lead_site_id});p(ke.comps.map(it=>({...it,selected:!0})).slice(0,12)),n({title:`Found ${ke.comps.length} comps`,description:`Top ${Math.min(12,ke.comps.length)} auto-selected.`})}catch(Je){n({title:"Search failed",description:Je.message,variant:"destructive"})}},he=Je=>{p(ke=>ke.map((it,je)=>je===Je?{...it,selected:!it.selected}:it))},ce=Je=>{p(ke=>ke.filter((it,je)=>je!==Je))},me=async Je=>{if(!r)return;const ke=Object.fromEntries(Object.entries(Je).filter(([,je])=>je!=null&&je!=="")),it={...r.subject,...ke,manually_enriched:!0};await l.mutateAsync({id:r.id,patch:{subject:it}}),n({title:"Subject details saved",description:it.sqft?"You can now find comps or add your own.":"Add square footage to unlock suggested pricing."})},le=Je=>{p(ke=>[{...Je,selected:!0,manual:!0},...ke]),n({title:"Manual comp added"})},ve=async(Je=!1)=>{if(!r)return;const ke=gZe(r.subject,h),it=Ge=>{const rt=Number(String(Ge).replace(/[^0-9.]/g,""));return Number.isFinite(rt)&&rt>0?Math.round(rt):null},je=j?it(S.likely):null,He=j?it(S.low):null,$e=j?it(S.high):null,Ke=j&&je;await l.mutateAsync({id:r.id,patch:{settings:{...f,priceOverride:{enabled:j,low:He,likely:je,high:$e,note:S.note||null},personalVideo:H},price_low:Ke?He??je:ke.low??null,price_likely:Ke?je:ke.likely??null,price_high:Ke?$e??je:ke.high??null,status:Je?"shared":r.status}}),await c.mutateAsync({cmaId:r.id,comps:h}),n({title:Je?"CMA published":"CMA saved"})},ge=r?`https://cma.relevelup.com/${r.share_token}`:"";if(a||!r)return e.jsx(Cs,{children:e.jsx("div",{className:"p-6",children:e.jsx(rs,{className:"w-6 h-6 animate-spin"})})});const Te=h.filter(Je=>Je.selected).length,Ie=!((Ce=r.subject)!=null&&Ce.bedrooms)||!((Me=r.subject)!=null&&Me.bathrooms)||!((Pe=r.subject)!=null&&Pe.sqft)||!((Re=r.subject)!=null&&Re.yearBuilt);return e.jsx(Cs,{children:e.jsxs("div",{className:"container mx-auto p-4 md:p-6 max-w-7xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4 gap-2 flex-wrap",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/cma"),children:[e.jsx(qr,{className:"w-4 h-4 mr-1"})," All CMAs"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>ve(!1),disabled:l.isPending,children:[e.jsx(Jo,{className:"w-4 h-4 mr-1"}),"Save"]}),e.jsxs(B,{onClick:()=>ve(!0),disabled:l.isPending,children:[e.jsx(Vl,{className:"w-4 h-4 mr-1"}),"Publish & Share"]}),r.status==="shared"&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"secondary",onClick:()=>{navigator.clipboard.writeText(ge),n({title:"Link copied"})},children:[e.jsx(tr,{className:"w-4 h-4 mr-1"}),"Copy Link"]}),e.jsxs(B,{onClick:()=>O(!0),children:[e.jsx(Gs,{className:"w-4 h-4 mr-1"}),"Send to Contact"]})]})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"lg:col-span-1 space-y-4",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Subject Property"})}),e.jsxs(Ee,{className:"space-y-2 text-sm",children:[e.jsx("div",{className:"font-semibold",children:r.subject.address}),e.jsxs("div",{className:"text-muted-foreground",children:[r.subject.city,", ",r.subject.state," ",r.subject.zip]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-2",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Beds:"})," ",r.subject.bedrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Baths:"})," ",r.subject.bathrooms??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"SqFt:"})," ",((Ae=r.subject.sqft)==null?void 0:Ae.toLocaleString())??"—"]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Year:"})," ",r.subject.yearBuilt??"—"]})]}),Ie&&e.jsxs("div",{className:"rounded-lg border border-amber-200 bg-amber-50 p-3 text-amber-950 space-y-2",children:[e.jsx("p",{className:"font-medium",children:"No panic — we can still build this."}),e.jsx("p",{className:"text-xs leading-relaxed",children:"If the MLS/feed does not return beds, baths, sqft, or year, add them manually and LevelUp will use them for comps and pricing."}),e.jsxs(B,{size:"sm",variant:"outline",className:"bg-white",onClick:()=>I(!0),children:[e.jsx(ya,{className:"w-3.5 h-3.5 mr-1"}),"Fill in property details"]})]}),!Ie&&e.jsxs(B,{size:"sm",variant:"ghost",className:"px-0",onClick:()=>I(!0),children:[e.jsx(ya,{className:"w-3.5 h-3.5 mr-1"}),"Edit details"]}),!r.subject.sqft&&e.jsxs("div",{className:"pt-2 border-t",children:[e.jsx(ne,{className:"text-xs",children:"Subject SqFt (needed for price band)"}),e.jsx(ye,{type:"number",defaultValue:"",onBlur:async Je=>{const ke=Number(Je.target.value);ke>0&&await l.mutateAsync({id:r.id,patch:{subject:{...r.subject,sqft:ke}}})}})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(dw,{className:"w-4 h-4"}),"Suggested Price"]})}),e.jsxs(Ee,{className:"space-y-3",children:[se!=null&&se.likely?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"text-3xl font-bold",children:["$",(j&&Number(S.likely)>0?Number(S.likely):se.likely).toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:["Comps suggest: $",(Be=se.low)==null?void 0:Be.toLocaleString()," – $",(we=se.high)==null?void 0:we.toLocaleString()]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",se.ppsf,"/sqft median · ",Te," comps"]})]}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add comps with sqft + price to see suggested pricing."}),e.jsxs("div",{className:"pt-3 border-t space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{htmlFor:"override-toggle",className:"text-sm font-medium",children:"Override with my price"}),e.jsx(jn,{id:"override-toggle",checked:j,onCheckedChange:w})]}),j&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"My suggested price"}),e.jsx(ye,{type:"number",placeholder:"e.g. 750000",value:S.likely,onChange:Je=>A(ke=>({...ke,likely:Je.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Range low"}),e.jsx(ye,{type:"number",placeholder:"optional",value:S.low,onChange:Je=>A(ke=>({...ke,low:Je.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Range high"}),e.jsx(ye,{type:"number",placeholder:"optional",value:S.high,onChange:Je=>A(ke=>({...ke,high:Je.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Why this price (optional)"}),e.jsx(Ms,{rows:2,maxLength:500,placeholder:"Notes shown to your client",value:S.note,onChange:Je=>A(ke=>({...ke,note:Je.target.value}))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Save to apply. Your price will replace the comp-based number on the shared report."})]})]})]})]}),e.jsx(aYs,{value:H,onChange:Z}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Filters"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"text-xs",children:["SqFt tolerance: ±",Math.round(f.sqftPct*100),"%"]}),e.jsx(jp,{value:[f.sqftPct*100],min:5,max:50,step:5,onValueChange:([Je])=>y(ke=>({...ke,sqftPct:Je/100}))})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"text-xs",children:["Search radius: ",f.maxMiles," mi"]}),e.jsx(jp,{value:[f.maxMiles],min:1,max:25,step:1,onValueChange:([Je])=>y(ke=>({...ke,maxMiles:Je}))})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"text-xs",children:["Sold within: ",f.monthsBack," months"]}),e.jsx(jp,{value:[f.monthsBack],min:1,max:24,step:1,onValueChange:([Je])=>y(ke=>({...ke,monthsBack:Je}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs",children:"Status"}),["Active","Pending","Closed"].map(Je=>e.jsxs("label",{className:"flex items-center gap-2 text-sm",children:[e.jsx(hi,{checked:f.statuses.includes(Je),onCheckedChange:ke=>y(it=>({...it,statuses:ke?[...it.statuses,Je]:it.statuses.filter(je=>je!==Je)}))})," ",Je]},Je))]}),e.jsxs(B,{className:"w-full",onClick:oe,disabled:o.isPending,children:[o.isPending?e.jsx(rs,{className:"w-4 h-4 animate-spin mr-2"}):e.jsx(un,{className:"w-4 h-4 mr-2"}),"Find Comps"]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:()=>z(!0),children:[e.jsx(Is,{className:"w-4 h-4 mr-2"}),"Add a comp manually"]})]})]})]}),e.jsxs("div",{className:"lg:col-span-2 space-y-3",children:[e.jsx(mWs,{subject:r.subject,comps:h,radiusMiles:f.maxMiles,onMarkerClick:Je=>v(Je)}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h2",{className:"text-lg font-semibold",children:["Comparables (",h.length,")"]}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Te," selected"]})]}),h.length?e.jsx("div",{className:"space-y-2",children:h.map((Je,ke)=>{var it;return e.jsx(fe,{className:Je.selected?"":"opacity-50",children:e.jsxs(Ee,{className:"p-3 flex gap-3 items-center",children:[e.jsx(hi,{checked:Je.selected,onCheckedChange:()=>he(ke)}),e.jsxs("button",{type:"button",onClick:()=>v(ke),className:"flex gap-3 items-center flex-1 min-w-0 text-left hover:bg-muted/40 -mx-1 px-1 py-1 rounded transition",children:[e.jsx(hfe,{photos:Je.photos,className:"w-20 h-16 rounded flex-none"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"font-medium truncate hover:underline",children:Je.address}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[Je.city,", ",Je.state," · ",Je.bedrooms??"?","bd/",Je.bathrooms??"?","ba · ",((it=Je.sqft)==null?void 0:it.toLocaleString())??"?"," sqft",Je.yearBuilt?` · ${Je.yearBuilt}`:""]}),e.jsxs("div",{className:"text-xs mt-0.5",children:[e.jsx(Ue,{variant:"outline",className:"mr-1",children:Je.status}),Je.score!=null&&e.jsxs("span",{className:"text-muted-foreground",children:["Score ",Je.score]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"font-semibold",children:["$",(Je.soldPrice||Je.price||0).toLocaleString()]}),Je.sqft&&(Je.soldPrice||Je.price)?e.jsxs("div",{className:"text-xs text-muted-foreground",children:["$",Math.round((Je.soldPrice||Je.price)/Je.sqft),"/sqft"]}):null]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>v(ke),title:"View details",children:e.jsx(Sr,{className:"w-4 h-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>ce(ke),title:"Remove",children:e.jsx(_n,{className:"w-4 h-4"})})]})},ke)})}):e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 text-center text-muted-foreground",children:e.jsxs("div",{className:"max-w-md mx-auto space-y-3",children:[e.jsxs("p",{children:["Click ",e.jsx("strong",{children:"Find Comps"})," to auto-pull from your MLS."]}),e.jsx("p",{className:"text-sm",children:"If nothing comes back, you are not stuck — use LevelUp's fallback template: enter the subject details, add 2–3 known comps, then set your suggested price."}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2",children:[Ie&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>I(!0),children:"Fill subject details"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>z(!0),children:"Add manual comp"})]})]})})})]})]}),e.jsx(ght,{comp:_!=null?h[_]:null,open:_!=null,onClose:()=>v(null)}),e.jsx(iYs,{open:D,onOpenChange:I,subject:r.subject,onSave:me,isSaving:l.isPending}),e.jsx(oYs,{open:F,onOpenChange:z,subject:r.subject,onAdd:le}),e.jsx(N_t,{open:E,onOpenChange:O,cma:r})]})})}function cYs(s,t,n,r){const a=d=>d*Math.PI/180,l=a(n-s),o=a(r-t),c=Math.sin(l/2)**2+Math.cos(a(s))*Math.cos(a(n))*Math.sin(o/2)**2;return 2*3958.8*Math.asin(Math.sqrt(c))}const Cjt="popby_geocode_cache_v1";function dYs(){try{return JSON.parse(localStorage.getItem(Cjt)||"{}")}catch{return{}}}function uYs(s){try{localStorage.setItem(Cjt,JSON.stringify(s))}catch{}}function hYs({contacts:s,onLogPopby:t}){const[n,r]=N.useState(null),[a,i]=N.useState("idle"),[l,o]=N.useState(5),[c,d]=N.useState(""),[u,h]=N.useState(new Map),[p,f]=N.useState(!1);N.useEffect(()=>{(async()=>{const{data:w}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();w!=null&&w.value&&d(w.value)})()},[]);const y=N.useMemo(()=>s.filter(w=>w.isDue&&(w.address||w.city&&w.state||w.zip)),[s]),_=()=>{if(!("geolocation"in navigator)){i("unavailable");return}i("loading"),navigator.geolocation.getCurrentPosition(w=>{r({lat:w.coords.latitude,lng:w.coords.longitude}),i("ok")},()=>{i("denied")},{enableHighAccuracy:!0,timeout:1e4,maximumAge:6e4})};N.useEffect(()=>{if(!c||!n||y.length===0)return;let w=!1;const S=dYs(),A=new Map;y.forEach(O=>{const D=[O.address,O.city,O.state,O.zip].filter(Boolean).join("|").toLowerCase();S[D]&&A.set(O.id,S[D])}),h(new Map(A));const E=y.filter(O=>!([O.address,O.city,O.state,O.zip].filter(Boolean).join("|").toLowerCase()in S));if(E.length!==0)return f(!0),(async()=>{const O=[...E],D=async()=>{var I,F;for(;O.length&&!w;){const z=O.shift(),H=[z.address,z.city,z.state,z.zip].filter(Boolean),Z=H.join("|").toLowerCase(),Y=H.join(", ");try{const ee=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(Y)}.json?limit=1&access_token=${c}`)).json();if((F=(I=ee==null?void 0:ee.features)==null?void 0:I[0])!=null&&F.center){const[se,oe]=ee.features[0].center;S[Z]={lat:oe,lng:se},A.set(z.id,{lat:oe,lng:se})}else S[Z]=null}catch{}}};await Promise.all([D(),D(),D(),D()]),w||(uYs(S),h(new Map(A)),f(!1))})(),()=>{w=!0}},[c,n,y]);const v=N.useMemo(()=>{if(!n)return[];const w=[];return y.forEach(S=>{const A=u.get(S.id);if(!A)return;const E=cYs(n.lat,n.lng,A.lat,A.lng);E<=l&&w.push({...S,distanceMiles:E,lat:A.lat,lng:A.lng})}),w.sort((S,A)=>S.distanceMiles-A.distanceMiles)},[n,y,u,l]),j=w=>{const A=/iPad|iPhone|iPod/.test(navigator.userAgent)?`https://maps.apple.com/?daddr=${w.lat},${w.lng}`:`https://www.google.com/maps/dir/?api=1&destination=${w.lat},${w.lng}`;window.open(A,"_blank","noopener")};return e.jsxs(fe,{className:"border-primary/30 bg-gradient-to-br from-primary/5 to-transparent",children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2 text-lg",children:[e.jsx(tL,{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(us,{value:String(l),onValueChange:w=>o(Number(w)),children:[e.jsx(ls,{className:"w-[110px] h-9",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"2",children:"2 miles"}),e.jsx(Ze,{value:"5",children:"5 miles"}),e.jsx(Ze,{value:"10",children:"10 miles"}),e.jsx(Ze,{value:"25",children:"25 miles"})]})]}),e.jsxs(B,{size:"sm",variant:a==="ok"?"outline":"default",onClick:_,disabled:a==="loading",children:[a==="loading"?e.jsx(Ei,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx(tL,{className:"h-4 w-4 mr-1"}),a==="ok"?"Refresh":"Use my location"]})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[a==="idle"&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:[e.jsx(ka,{className:"h-8 w-8 mx-auto mb-2 opacity-50"}),"Tap ",e.jsx("span",{className:"font-medium text-foreground",children:'"Use my location"'})," to see who's close by right now."]}),a==="denied"&&e.jsxs("div",{className:"text-center py-6 text-sm text-destructive flex flex-col items-center gap-2",children:[e.jsx(Bi,{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&&y.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&&y.length>0&&p&&v.length===0&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{className:"h-14 w-full"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Locating contacts…"})]}),a==="ok"&&c&&!p&&v.length===0&&y.length>0&&e.jsxs("div",{className:"text-center py-6 text-sm text-muted-foreground",children:["No due contacts within ",l," miles. Try widening the radius."]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(Ue,{variant:"secondary",className:"font-medium",children:[v.length," nearby"]}),p&&e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Ei,{className:"h-3 w-3 animate-spin"})," still locating…"]})]}),e.jsx("div",{className:"space-y-2",children:v.map(w=>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:[w.first_name," ",w.last_name]}),e.jsx(Ue,{variant:"outline",className:"text-xs",children:w.distanceMiles<1?`${(w.distanceMiles*5280).toFixed(0)} ft`:`${w.distanceMiles.toFixed(1)} mi`}),w.daysOverdue>0&&e.jsxs(Ue,{variant:"destructive",className:"text-xs",children:[w.daysOverdue,"d overdue"]})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate mt-0.5",children:[w.address,w.city,w.state].filter(Boolean).join(", ")})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[w.phone&&e.jsx(B,{size:"icon",variant:"ghost",asChild:!0,className:"h-9 w-9",title:"Call",children:e.jsx("a",{href:`tel:${w.phone}`,children:e.jsx(Cr,{className:"h-4 w-4"})})}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>j(w),className:"h-9 w-9",title:"Directions",children:e.jsx(r9,{className:"h-4 w-4"})}),e.jsxs(B,{size:"sm",onClick:()=>t(w),children:[e.jsx(Oi,{className:"h-4 w-4 mr-1"}),"Log"]})]})]},w.id))})]})]})]})}const mYs="0dde5abb-0005-4c8c-a471-30d0cbc9e280",pYs=[{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 fYs(){const s=Ln(),t=a_t(),{data:n}=gHs(),{data:r}=ky(),{data:a}=YPe(),{data:i}=f1e(90),{data:l}=ax(),o=wHs(),c=bHs(),d=vHs(),u=_Hs(),{data:h=[],isLoading:p}=dt({queryKey:["popby-templates"],queryFn:async()=>{const{data:ee,error:se}=await q.from("canva_templates").select(` *, category:template_categories(id, name), type:template_types(id, name) `).eq("category_id",mYs).order("publish_date",{ascending:!1});if(se)throw se;const{data:oe}=await q.from("template_likes").select("template_id"),{data:he}=await q.from("template_comments").select("template_id"),ce=new Map;oe==null||oe.forEach(le=>{ce.set(le.template_id,(ce.get(le.template_id)||0)+1)});const me=new Map;return he==null||he.forEach(le=>{me.set(le.template_id,(me.get(le.template_id)||0)+1)}),(ee||[]).map(le=>({...le,likesCount:ce.get(le.id)||0,commentsCount:me.get(le.id)||0}))}}),f=ee=>{const se=l==null?void 0:l.find(oe=>oe.id===ee);return se?`${se.first_name} ${se.last_name||""}`.trim():"Unknown"},y=ee=>{if(!ee)return null;const se=n==null?void 0:n.find(oe=>oe.id===ee);return(se==null?void 0:se.name)||null},[_,v]=N.useState(null),[j,w]=N.useState(!1),[S,A]=N.useState(!1),[E,O]=N.useState(!1),[D,I]=N.useState({popby_item_id:"",notes:""}),[F,z]=N.useState({name:"",description:""}),H=async()=>{_&&(await c.mutateAsync({contact_id:_.id,popby_item_id:D.popby_item_id||void 0,notes:D.notes||void 0}),w(!1),v(null),I({popby_item_id:"",notes:""}))},Z=async()=>{F.name.trim()&&(await d.mutateAsync({name:F.name.trim(),description:F.description.trim()||void 0}),O(!1),z({name:"",description:""}))},Y=async(ee,se)=>{await u.mutateAsync({relationship_type_id:ee,frequency_days:parseInt(se)})},W=ee=>{var oe;const se=a==null?void 0:a.find(he=>he.relationship_type_id===ee);return((oe=se==null?void 0:se.frequency_days)==null?void 0:oe.toString())||"90"};return e.jsx(Cs,{title:"Popbys",description:"Drop off gifts to stay top of mind",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Popbys"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-primary",children:o.thisWeekCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Week"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-emerald-500",children:o.thisMonthCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"This Month"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-3xl font-bold text-amber-500",children:o.dueCount}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"Due Now"})]})})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{onClick:()=>s("/mission-control/popbys/map"),children:[e.jsx(ka,{className:"h-4 w-4 mr-2"}),"View Map"]}),e.jsxs(B,{variant:"outline",onClick:()=>A(!0),children:[e.jsx(Ko,{className:"h-4 w-4 mr-2"}),"Frequency Settings"]}),e.jsxs(B,{variant:"outline",onClick:()=>O(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Popby Idea"]})]}),e.jsxs(Fr,{defaultValue:"due",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"due",children:"Due for Popby"}),e.jsx(Zt,{value:"activity",children:"Recent Activity"}),e.jsx(Zt,{value:"library",children:"Popby Library"}),e.jsx(Zt,{value:"templates",children:"Popby Templates"})]}),e.jsxs(is,{value:"due",className:"space-y-4 mt-4",children:[e.jsx(hYs,{contacts:t||[],onLogPopby:ee=>{v(ee),w(!0)}}),!t||t.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Oi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No contacts due for a popby right now!"}),e.jsx("p",{className:"text-sm mt-1",children:"Great job staying connected."})]})}):e.jsx("div",{className:"space-y-3",children:t.map(ee=>e.jsx(fe,{className:"hover:shadow-md transition-shadow",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("span",{className:"font-medium",children:[ee.first_name," ",ee.last_name]}),ee.daysOverdue>0&&e.jsxs(Ue,{variant:"destructive",className:"text-xs",children:[ee.daysOverdue,"+ days overdue"]}),ee.daysSinceLastPopby===null&&e.jsx(Ue,{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:[ee.address&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),ee.city||ee.address]}),ee.tags&&ee.tags.length>0&&e.jsx("span",{children:ee.tags.map(se=>{var oe;return(oe=se.relationship_type)==null?void 0:oe.name}).join(", ")})]}),ee.lastPopby&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Last popby: ",Ss(new Date(ee.lastPopby),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ee.phone&&e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsx("a",{href:`tel:${ee.phone}`,children:e.jsx(Cr,{className:"h-4 w-4"})})}),e.jsxs(B,{size:"sm",onClick:()=>{v(ee),w(!0)},children:[e.jsx(Pi,{className:"h-4 w-4 mr-1"}),"Log Popby"]})]})]})})},ee.id))})]}),e.jsx(is,{value:"activity",className:"space-y-4 mt-4",children:!i||i.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(pr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby activity yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Start logging popbys to see your history here."})]})}):e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Recent Popby Log"})}),e.jsx(Ee,{className:"space-y-3",children:i.map(ee=>e.jsxs("div",{className:"flex items-start gap-3 pb-3 border-b last:border-0 last:pb-0",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/10 flex items-center justify-center",children:e.jsx(Oi,{className:"h-5 w-5 text-orange-500"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium",children:f(ee.contact_id)}),y(ee.popby_item_id)&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:y(ee.popby_item_id)})]}),e.jsx("div",{className:"text-sm text-muted-foreground",children:Ss(new Date(ee.completed_at),"MMM d, yyyy h:mm a")}),ee.notes&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:ee.notes})]})]},ee.id))})]})}),e.jsx(is,{value:"library",className:"space-y-4 mt-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[n==null?void 0:n.map(ee=>e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Oi,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-medium",children:ee.name}),ee.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:ee.description}),!ee.owner_user_id&&e.jsx(Ue,{variant:"secondary",className:"mt-2 text-xs",children:"Shared"})]})]})})},ee.id)),e.jsx(fe,{className:"border-dashed cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>O(!0),children:e.jsx(Ee,{className:"p-4 flex items-center justify-center h-full min-h-[100px]",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Is,{className:"h-8 w-8 mx-auto mb-2"}),e.jsx("p",{children:"Add New Popby Idea"})]})})})]})}),e.jsxs(is,{value:"templates",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:[h.length," template",h.length!==1?"s":""," found"]}),p&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:[...Array(4)].map((ee,se)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx(Ws,{className:"aspect-[3/2] w-full rounded-lg mb-4"}),e.jsx(Ws,{className:"h-5 w-3/4 mb-2"}),e.jsx(Ws,{className:"h-4 w-full mb-4"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(Ws,{className:"h-5 w-16"}),e.jsx(Ws,{className:"h-5 w-20"})]})]})},se))}),!p&&h.length===0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-8 text-center text-muted-foreground",children:[e.jsx(Ec,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No popby templates available yet!"}),e.jsx("p",{className:"text-sm mt-1",children:"Check back soon for new templates."})]})}),!p&&h.length>0&&e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6",children:h.map(ee=>e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-all duration-200 cursor-pointer",onClick:()=>s(`/templates/${ee.id}`),children:[e.jsx("div",{className:"relative overflow-hidden bg-muted aspect-[3/2]",children:ee.preview_image_url?e.jsx("img",{src:ee.preview_image_url,alt:ee.name,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No Preview"})}),e.jsxs(Ee,{className:"p-4 flex flex-col",children:[e.jsx("h3",{className:"font-semibold text-foreground line-clamp-1 mb-1",children:ee.name}),ee.description&&e.jsx("p",{className:"text-sm text-muted-foreground line-clamp-2 mb-3 flex-1",children:qz(ee.description)}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-3",children:e.jsx(Ue,{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($m,{className:"h-3.5 w-3.5"}),ee.likesCount]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Zl,{className:"h-3.5 w-3.5"}),ee.commentsCount]})]}),e.jsxs(B,{size:"sm",className:"w-full gap-2",onClick:se=>{se.stopPropagation(),s(`/templates/${ee.id}`)},children:[e.jsx(tr,{className:"h-4 w-4"}),"View Template"]})]})]},ee.id))})]})]}),e.jsx(_s,{open:j,onOpenChange:w,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsxs(ws,{children:["Log Popby for ",_==null?void 0:_.first_name," ",_==null?void 0:_.last_name]})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Popby Item (optional)"}),e.jsxs(us,{value:D.popby_item_id,onValueChange:ee=>I(se=>({...se,popby_item_id:ee})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a popby item..."})}),e.jsx(cs,{children:n==null?void 0:n.map(ee=>e.jsx(Ze,{value:ee.id,children:ee.name},ee.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Notes (optional)"}),e.jsx(Ms,{placeholder:"Any notes about this popby...",value:D.notes,onChange:ee=>I(se=>({...se,notes:ee.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>w(!1),children:"Cancel"}),e.jsx(B,{onClick:H,disabled:c.isPending,children:"Log Popby"})]})]})}),e.jsx(_s,{open:S,onOpenChange:A,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Popby Frequency Settings"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Set default popby frequency for each relationship type. You can override these per-contact."}),r==null?void 0:r.map(ee=>e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsx(ne,{className:"font-medium",children:ee.name}),e.jsxs(us,{value:W(ee.id),onValueChange:se=>Y(ee.id,se),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsx(cs,{children:pYs.map(se=>e.jsx(Ze,{value:se.value,children:se.label},se.value))})]})]},ee.id))]}),e.jsx(Xn,{children:e.jsx(B,{onClick:()=>A(!1),children:"Done"})})]})}),e.jsx(_s,{open:E,onOpenChange:O,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Add Popby Idea"})}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Name *"}),e.jsx(ye,{placeholder:"e.g., Homemade cookies",value:F.name,onChange:ee=>z(se=>({...se,name:ee.target.value}))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{placeholder:"Optional description...",value:F.description,onChange:ee=>z(se=>({...se,description:ee.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>O(!1),children:"Cancel"}),e.jsx(B,{onClick:Z,disabled:!F.name.trim()||d.isPending,children:"Add Item"})]})]})})]})})}const xYs=Gw({property_address:fo().min(1,"Property address is required"),city:fo().optional(),state:fo().optional(),zip:fo().optional(),transaction_type:XAe(["buyer","seller"]),close_date:fo().min(1,"Close date is required"),sale_price:z9().min(0,"Sale price must be positive"),commission_amount:z9().optional(),lead_source_id:fo().optional(),client_type_id:fo().optional(),contact_id:fo().optional(),notes:fo().optional(),is_win:PGt()});function Tjt({open:s,onOpenChange:t,transaction:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(""),h=Eye(),p=frs(),{data:f}=qD(),{data:y}=ky(),{data:_}=ax(),v=Cye(),j=t6e(),{data:w}=Aye(),S=(w==null?void 0:w.show_commission)??!0,A=bye({resolver:_ye(xYs),defaultValues:{property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1}});N.useEffect(()=>{n?A.reset({property_address:n.property_address,city:n.city||"",state:n.state||"",zip:n.zip||"",transaction_type:n.transaction_type,close_date:n.close_date,sale_price:Number(n.sale_price),commission_amount:n.commission_amount?Number(n.commission_amount):void 0,lead_source_id:n.lead_source_id||void 0,client_type_id:n.client_type_id||void 0,contact_id:n.contact_id||void 0,notes:n.notes||"",is_win:n.is_win}):A.reset({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:new Date().toISOString().split("T")[0],sale_price:0,commission_amount:void 0,lead_source_id:void 0,client_type_id:void 0,contact_id:void 0,notes:"",is_win:!1})},[n,A]);const E=async F=>{const z={property_address:F.property_address,transaction_type:F.transaction_type,close_date:F.close_date,sale_price:F.sale_price,is_win:F.is_win,commission_amount:F.commission_amount||null,lead_source_id:F.lead_source_id||null,client_type_id:F.client_type_id||null,contact_id:F.contact_id||null,city:F.city||null,state:F.state||null,zip:F.zip||null,notes:F.notes||null};n?await p.mutateAsync({id:n.id,...z}):await h.mutateAsync(z),t(!1)},O=async()=>{if(!i.trim())return;const[F,...z]=i.trim().split(" "),H=z.join(" ")||null,Z=await v.mutateAsync({first_name:F,last_name:H,tagIds:[]});Z&&(A.setValue("contact_id",Z.id),l(""),c(!1),a(!1))},D=async()=>{if(!d.trim())return;const F=await j.mutateAsync(d.trim());F&&(A.setValue("lead_source_id",F.id),u(""))},I=_==null?void 0:_.find(F=>F.id===A.watch("contact_id"));return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg max-h-[90vh]",children:[e.jsx(js,{children:e.jsx(ws,{children:n?"Edit Transaction":"Add Transaction"})}),e.jsx(di,{className:"max-h-[70vh] pr-4",children:e.jsx(wye,{...A,children:e.jsxs("form",{onSubmit:A.handleSubmit(E),className:"space-y-4",children:[e.jsx(_u,{control:A.control,name:"property_address",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Property Address *"}),e.jsx(nu,{children:e.jsx(ye,{placeholder:"123 Main St",...F})}),e.jsx(Wx,{})]})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2",children:[e.jsx(_u,{control:A.control,name:"city",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"City"}),e.jsx(nu,{children:e.jsx(ye,{placeholder:"City",...F})})]})}),e.jsx(_u,{control:A.control,name:"state",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"State"}),e.jsx(nu,{children:e.jsx(ye,{placeholder:"TX",...F})})]})}),e.jsx(_u,{control:A.control,name:"zip",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Zip"}),e.jsx(nu,{children:e.jsx(ye,{placeholder:"75001",...F})})]})})]}),e.jsx(_u,{control:A.control,name:"transaction_type",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Transaction Type *"}),e.jsxs(us,{onValueChange:F.onChange,value:F.value,children:[e.jsx(nu,{children:e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select type"})})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"})]})]}),e.jsx(Wx,{})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsx(_u,{control:A.control,name:"close_date",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Close Date *"}),e.jsx(nu,{children:e.jsx(ye,{type:"date",...F})}),e.jsx(Wx,{})]})}),e.jsx(_u,{control:A.control,name:"sale_price",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Sale Price *"}),e.jsx(nu,{children:e.jsx(ye,{type:"number",placeholder:"0",...F,onChange:z=>F.onChange(Number(z.target.value))})}),e.jsx(Wx,{})]})})]}),S&&e.jsx(_u,{control:A.control,name:"commission_amount",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Commission"}),e.jsx(nu,{children:e.jsx(ye,{type:"number",placeholder:"0",...F,value:F.value??"",onChange:z=>F.onChange(z.target.value?Number(z.target.value):void 0)})})]})}),e.jsx(_u,{control:A.control,name:"lead_source_id",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Lead Source"}),e.jsxs(us,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(nu,{children:e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select source"})})}),e.jsx(cs,{children:f==null?void 0:f.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))})]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Add custom source...",value:d,onChange:F=>u(F.target.value),className:"flex-1"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:D,disabled:!d.trim(),children:e.jsx(Is,{className:"h-4 w-4"})})]}),e.jsx(_u,{control:A.control,name:"client_type_id",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Client Type"}),e.jsxs(us,{onValueChange:F.onChange,value:F.value||"",children:[e.jsx(nu,{children:e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select client type"})})}),e.jsx(cs,{children:y==null?void 0:y.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))})]})]})}),e.jsx(_u,{control:A.control,name:"contact_id",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Client Contact"}),e.jsxs(il,{open:r,onOpenChange:a,children:[e.jsx(ol,{asChild:!0,children:e.jsx(nu,{children:e.jsxs(B,{variant:"outline",role:"combobox",className:Mt("w-full justify-between",!F.value&&"text-muted-foreground"),children:[I?`${I.first_name} ${I.last_name||""}`.trim():"Select contact",e.jsx($g,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})})}),e.jsxs(el,{className:"w-full p-0",align:"start",children:[e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search contacts..."}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:e.jsxs("div",{className:"p-2 space-y-2",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"No contact found."}),!o&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>c(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add New Contact"]})]})}),e.jsx(Jg,{children:_==null?void 0:_.map(z=>e.jsxs(Zf,{value:`${z.first_name} ${z.last_name||""}`,onSelect:()=>{F.onChange(z.id),a(!1)},children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",z.id===F.value?"opacity-100":"opacity-0")}),z.first_name," ",z.last_name||""]},z.id))})]})]}),o&&e.jsxs("div",{className:"p-2 border-t space-y-2",children:[e.jsx(ye,{placeholder:"Enter contact name...",value:i,onChange:z=>l(z.target.value)}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:O,disabled:!i.trim()||v.isPending,children:"Add Contact"}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{c(!1),l("")},children:"Cancel"})]})]})]})]})]})}),e.jsx(_u,{control:A.control,name:"notes",render:({field:F})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Notes"}),e.jsx(nu,{children:e.jsx(Ms,{placeholder:"Any notes about this transaction...",...F})})]})}),e.jsx(_u,{control:A.control,name:"is_win",render:({field:F})=>e.jsxs(tu,{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(su,{children:"Mark as Win 🏆"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Highlight this as a notable success"})]}),e.jsx(nu,{children:e.jsx(jn,{checked:F.value,onCheckedChange:F.onChange})})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:h.isPending||p.isPending,children:[n?"Update":"Add"," Transaction"]})]})]})})})]})})}function WLe({transactions:s,showCommission:t,isLoading:n,agentNameMap:r,readOnly:a}){const[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(""),[h,p]=N.useState("all"),[f,y]=N.useState("all"),[_,v]=N.useState("all"),[j,w]=N.useState(!1),S=xrs(),A=Eye(),{data:E}=qD();ky();const O=fR(),D=z=>{const{id:H,created_at:Z,updated_at:Y,lead_source:W,client_type:ee,contact:se,...oe}=z;A.mutate(oe)},I=()=>{o&&(S.mutate(o),c(null))},F=s.filter(z=>{var se,oe,he,ce;const H=d===""||z.property_address.toLowerCase().includes(d.toLowerCase())||((oe=(se=z.contact)==null?void 0:se.first_name)==null?void 0:oe.toLowerCase().includes(d.toLowerCase()))||((ce=(he=z.contact)==null?void 0:he.last_name)==null?void 0:ce.toLowerCase().includes(d.toLowerCase())),Z=h==="all"||z.transaction_type===h,Y=f==="all"||z.lead_source_id===f,W=_==="all"||z.client_type_id===_,ee=!j||z.is_win;return H&&Z&&Y&&W&&ee});return n?e.jsx(fe,{children:e.jsx(Ee,{className:"p-6 space-y-4",children:[1,2,3].map(z=>e.jsx(Ws,{className:"h-16 w-full"},z))})}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(It,{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(Rt,{children:["Transactions (",F.length,")"]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search...",value:d,onChange:z=>u(z.target.value),className:"pl-8 w-[150px]"})]}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(ls,{className:"w-[100px]",children:e.jsx(hs,{placeholder:"Type"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"})]})]}),e.jsxs(us,{value:f,onValueChange:y,children:[e.jsx(ls,{className:"w-[130px]",children:e.jsx(hs,{placeholder:"Lead Source"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Sources"}),E==null?void 0:E.map(z=>e.jsx(Ze,{value:z.id,children:z.name},z.id))]})]}),e.jsxs(B,{variant:j?"default":"outline",size:"sm",onClick:()=>w(!j),children:[e.jsx(fc,{className:"h-4 w-4 mr-1"}),"Wins"]})]})]})}),e.jsx(Ee,{children:F.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No transactions found"}):O?e.jsx("div",{className:"space-y-3",children:F.map(z=>e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("span",{className:"font-medium truncate",children:z.property_address}),z.is_win&&e.jsx(fc,{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(Ue,{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: "}),E9e(z.close_date)]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Price: "}),jc(z.sale_price)]}),t&&z.commission_amount&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Commission: "}),jc(z.commission_amount)]}),z.lead_source&&e.jsxs("div",{children:[e.jsx("span",{className:"text-muted-foreground",children:"Source: "}),z.lead_source.name]}),z.contact&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Client: "}),z.contact.first_name," ",z.contact.last_name]}),r&&e.jsxs("div",{className:"col-span-2",children:[e.jsx("span",{className:"text-muted-foreground",children:"Agent: "}),r[z.owner_user_id]||"Unknown"]})]}),!a&&e.jsxs("div",{className:"flex justify-end gap-2 mt-3 pt-3 border-t",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>l(z),children:e.jsx(wu,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>D(z),children:e.jsx(Zr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(z.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})]},z.id))}):e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[r&&e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Close Date"}),e.jsx(Tt,{children:"Sale Price"}),t&&e.jsx(Tt,{children:"Commission"}),e.jsx(Tt,{children:"Lead Source"}),e.jsx(Tt,{children:"Client"}),!a&&e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(da,{children:F.map(z=>{var H;return e.jsxs(Hs,{children:[r&&e.jsx(ht,{className:"font-medium text-sm",children:r[z.owner_user_id]||"Unknown"}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[z.is_win&&e.jsx(fc,{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(ht,{children:e.jsx(Ue,{variant:z.transaction_type==="buyer"?"default":"secondary",children:z.transaction_type})}),e.jsx(ht,{children:E9e(z.close_date)}),e.jsx(ht,{children:jc(z.sale_price)}),t&&e.jsx(ht,{children:z.commission_amount?jc(z.commission_amount):"-"}),e.jsx(ht,{children:((H=z.lead_source)==null?void 0:H.name)||"-"}),e.jsx(ht,{children:z.contact?`${z.contact.first_name} ${z.contact.last_name||""}`.trim():"-"}),!a&&e.jsx(ht,{children:e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Ag,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",children:[e.jsxs(Kr,{onClick:()=>l(z),children:[e.jsx(wu,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsxs(Kr,{onClick:()=>D(z),children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Duplicate"]}),e.jsxs(Kr,{onClick:()=>c(z.id),className:"text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},z.id)})})]})})})]}),e.jsx(Tjt,{open:!!i,onOpenChange:z=>!z&&l(null),transaction:i||void 0}),e.jsx(Oo,{open:!!o,onOpenChange:z=>!z&&c(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Transaction?"}),e.jsx(Mo,{children:"This action cannot be undone. This will permanently delete this transaction."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:I,className:"bg-destructive text-destructive-foreground",children:"Delete"})]})]})})]})}function Ejt({goals:s,stats:t,year:n,showCommission:r}){const a=new Date().getMonth()+1,i=new Date().getFullYear()===n?a:12,l=12-i,o=(p,f)=>{if(!f||f===0)return null;const y=Math.min(p/f*100,100),_=Math.max(f-p,0),v=l>0?_/l:0,j=i/12*100,w=y>=j?"ahead":y>=j*.8?"on-track":"behind";return{percent:y,remaining:_,pace:v,status:w}},c=o(t.totalTransactions,s.transactions_goal),d=o(t.totalVolume,s.volume_goal),u=r?o(t.totalCommission,s.gci_goal):null,h=p=>{switch(p){case"ahead":return e.jsxs(Ue,{className:"bg-green-500 text-white",children:[e.jsx(go,{className:"h-3 w-3 mr-1"}),"Ahead"]});case"on-track":return e.jsxs(Ue,{variant:"secondary",children:[e.jsx(hb,{className:"h-3 w-3 mr-1"}),"On Track"]});case"behind":return e.jsxs(Ue,{variant:"destructive",children:[e.jsx(fb,{className:"h-3 w-3 mr-1"}),"Behind"]});default:return null}};return!s.transactions_goal&&!s.volume_goal&&!s.gci_goal?null:e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ac,{className:"h-5 w-5 text-primary"}),e.jsxs(Rt,{children:[n," Goals Progress"]})]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[s.transactions_goal&&c&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Transactions"}),h(c.status)]}),e.jsx(fi,{value:c.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[t.totalTransactions," of ",s.transactions_goal]}),e.jsxs("span",{children:[Math.round(c.percent),"%"]})]}),c.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",Math.ceil(c.pace),"/month to hit goal"]})]}),s.volume_goal&&d&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"Volume"}),h(d.status)]}),e.jsx(fi,{value:d.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[jc(t.totalVolume,!0)," of ",jc(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 ",jc(d.pace,!0),"/month"]})]}),r&&s.gci_goal&&u&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:"GCI"}),h(u.status)]}),e.jsx(fi,{value:u.percent,className:"h-2"}),e.jsxs("div",{className:"flex justify-between text-sm text-muted-foreground",children:[e.jsxs("span",{children:[jc(t.totalCommission,!0)," of ",jc(s.gci_goal,!0)]}),e.jsxs("span",{children:[Math.round(u.percent),"%"]})]}),u.remaining>0&&l>0&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Need ",jc(u.pace,!0),"/month"]})]})]})})]})}const gYs={light:"",dark:".dark"},Ajt=N.createContext(null);function Mjt(){const s=N.useContext(Ajt);if(!s)throw new Error("useChart must be used within a ");return s}const Ijt=N.forwardRef(({id:s,className:t,children:n,config:r,...a},i)=>{const l=N.useId(),o=`chart-${s||l.replace(/:/g,"")}`;return e.jsx(Ajt.Provider,{value:{config:r},children:e.jsxs("div",{"data-chart":o,ref:i,className:Mt("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(yYs,{id:o,config:r}),e.jsx(ww,{children:n})]})})});Ijt.displayName="Chart";const yYs=({id:s,config:t})=>{const n=Object.entries(t).filter(([r,a])=>a.theme||a.color);return n.length?e.jsx("style",{dangerouslySetInnerHTML:{__html:Object.entries(gYs).map(([r,a])=>` ${a} [data-chart=${s}] { ${n.map(([i,l])=>{var c;const o=((c=l.theme)==null?void 0:c[r])||l.color;return o?` --color-${i}: ${o};`:null}).join(` `)} } `).join(` `)}}):null},Pjt=N.forwardRef(({active:s,payload:t,className:n,indicator:r="dot",hideLabel:a=!1,hideIndicator:i=!1,label:l,labelFormatter:o,labelClassName:c,formatter:d,color:u,nameKey:h,labelKey:p},f)=>{const{config:y}=Mjt(),_=N.useMemo(()=>{var E;if(a||!(t!=null&&t.length))return null;const[j]=t,w=`${p||j.dataKey||j.name||"value"}`,S=eTe(y,j,w),A=!p&&typeof l=="string"?((E=y[l])==null?void 0:E.label)||l:S==null?void 0:S.label;return o?e.jsx("div",{className:Mt("font-medium",c),children:o(A,t)}):A?e.jsx("div",{className:Mt("font-medium",c),children:A}):null},[l,o,t,a,c,y,p]);if(!s||!(t!=null&&t.length))return null;const v=t.length===1&&r!=="dot";return e.jsxs("div",{ref:f,className:Mt("grid min-w-[8rem] items-start gap-1.5 rounded-lg border border-border/50 bg-background px-2.5 py-1.5 text-xs shadow-xl",n),children:[v?null:_,e.jsx("div",{className:"grid gap-1.5",children:t.map((j,w)=>{const S=`${h||j.name||j.dataKey||"value"}`,A=eTe(y,j,S),E=u||j.payload.fill||j.color;return e.jsx("div",{className:Mt("flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5 [&>svg]:text-muted-foreground",r==="dot"&&"items-center"),children:d&&(j==null?void 0:j.value)!==void 0&&j.name?d(j.value,j.name,j,w,j.payload):e.jsxs(e.Fragment,{children:[A!=null&&A.icon?e.jsx(A.icon,{}):!i&&e.jsx("div",{className:Mt("shrink-0 rounded-[2px] border-[--color-border] bg-[--color-bg]",{"h-2.5 w-2.5":r==="dot","w-1":r==="line","w-0 border-[1.5px] border-dashed bg-transparent":r==="dashed","my-0.5":v&&r==="dashed"}),style:{"--color-bg":E,"--color-border":E}}),e.jsxs("div",{className:Mt("flex flex-1 justify-between leading-none",v?"items-end":"items-center"),children:[e.jsxs("div",{className:"grid gap-1.5",children:[v?_:null,e.jsx("span",{className:"text-muted-foreground",children:(A==null?void 0:A.label)||j.name})]}),j.value&&e.jsx("span",{className:"font-mono font-medium tabular-nums text-foreground",children:j.value.toLocaleString()})]})]})},j.dataKey)})})]})});Pjt.displayName="ChartTooltip";const vYs=N.forwardRef(({className:s,hideIcon:t=!1,payload:n,verticalAlign:r="bottom",nameKey:a},i)=>{const{config:l}=Mjt();return n!=null&&n.length?e.jsx("div",{ref:i,className:Mt("flex items-center justify-center gap-4",r==="top"?"pb-3":"pt-3",s),children:n.map(o=>{const c=`${a||o.dataKey||"value"}`,d=eTe(l,o,c);return e.jsxs("div",{className:Mt("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});vYs.displayName="ChartLegend";function eTe(s,t,n){if(typeof t!="object"||t===null)return;const r="payload"in t&&typeof t.payload=="object"&&t.payload!==null?t.payload:void 0;let a=n;return n in t&&typeof t[n]=="string"?a=t[n]:r&&n in r&&typeof r[n]=="string"&&(a=r[n]),a in s?s[a]:s[n]}const fG=["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 KLe({stats:s,year:t}){const n=s.transactionsByMonth.some(a=>a.count>0),r=s.leadSourceBreakdown.length>0;return!n&&!r?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 text-center text-muted-foreground",children:"Add transactions to see your performance charts"})}):e.jsxs("div",{className:"grid gap-6",children:[n&&e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Transactions by Month"})}),e.jsx(Ee,{className:"overflow-hidden",children:e.jsx(Ijt,{config:{count:{label:"Transactions",color:"hsl(var(--primary))"}},className:"h-[250px]",children:e.jsx(ww,{width:"100%",height:"100%",children:e.jsxs(HPe,{data:s.transactionsByMonth,margin:{top:5,right:10,left:0,bottom:5},children:[e.jsx(UPe,{strokeDasharray:"3 3",className:"stroke-muted"}),e.jsx(Rw,{dataKey:"month",tick:{fontSize:11},className:"fill-muted-foreground",interval:0}),e.jsx(Ow,{allowDecimals:!1,tick:{fontSize:12},className:"fill-muted-foreground",width:30}),e.jsx(_p,{content:e.jsx(Pjt,{})}),e.jsx(Dw,{dataKey:"count",fill:"hsl(var(--primary))",radius:[4,4,0,0],name:"Transactions"})]})})})})]}),r&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ee,{children:[e.jsx("div",{className:"h-[250px]",children:e.jsx(ww,{width:"100%",height:"100%",children:e.jsxs(GPe,{children:[e.jsx(Db,{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(oR,{fill:fG[i%fG.length]},`cell-${i}`))}),e.jsx(_p,{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:fG[i%fG.length]}}),e.jsx("span",{className:"text-muted-foreground",children:a.name})]},a.name))})]})]})]})}function bYs(s){if(!s||!s.trim())return null;const t=s.trim(),n=["yyyy-MM-dd","M/d/yyyy","MM/dd/yyyy","M-d-yyyy","MM-dd-yyyy","MM/dd/yy","M/d/yy"];for(const r of n)try{const a=qAe(t,r,new Date);if(f4e(a))return Ss(a,"yyyy-MM-dd")}catch{}try{const r=new Date(t);if(f4e(r))return Ss(r,"yyyy-MM-dd")}catch{}return null}const _Ys=["property_address","city","state","zip","transaction_type","close_date","sale_price","commission_amount","lead_source","client_type","is_win","notes"];function wYs({open:s,onOpenChange:t}){const[n,r]=N.useState([]),[a,i]=N.useState(!1),[l,o]=N.useState(0),{data:c}=qD(),{data:d}=ky(),u=Eye(),h=()=>{const j=_Ys.join(","),w=["123 Main St","Dallas","TX","75001","buyer","2024-06-15","450000","13500","Referral","Past Client","yes","Great transaction!"].join(","),S=`${j} ${w}`,A=new Blob([S],{type:"text/csv"}),E=URL.createObjectURL(A),O=document.createElement("a");O.href=E,O.download="transaction-import-template.csv",O.click(),URL.revokeObjectURL(E)},p=j=>{const w=j.split(` `).filter(A=>A.trim());if(w.length<2)return[];const S=w[0].split(",").map(A=>A.trim().toLowerCase().replace(/['"]/g,""));return w.slice(1).map((A,E)=>{var oe,he,ce,me;const O=[];let D="",I=!1;for(const le of A)le==='"'?I=!I:le===","&&!I?(O.push(D.trim()),D=""):D+=le;O.push(D.trim());const F=le=>{var ge;const ve=S.indexOf(le);return ve>=0?(ge=O[ve])==null?void 0:ge.replace(/^["']|["']$/g,"").trim():""},z=(oe=F("transaction_type"))==null?void 0:oe.toLowerCase(),H=(he=F("sale_price"))==null?void 0:he.replace(/[$,]/g,""),Z=(ce=F("commission_amount"))==null?void 0:ce.replace(/[$,]/g,""),Y=(me=F("is_win"))==null?void 0:me.toLowerCase(),W=F("close_date"),ee=bYs(W);let se;return F("property_address")?["buyer","seller"].includes(z)?ee?(!H||isNaN(Number(H)))&&(se="Invalid sale price"):se=`Invalid date format: "${W}" - use MM/DD/YYYY or YYYY-MM-DD`:se='Transaction type must be "buyer" or "seller"':se="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:ee||"",sale_price:Number(H)||0,commission_amount:Z?Number(Z):null,lead_source_name:F("lead_source"),client_type_name:F("client_type"),is_win:["yes","true","1"].includes(Y),notes:F("notes"),error:se}})},f=j=>{var A;const w=(A=j.target.files)==null?void 0:A[0];if(!w)return;const S=new FileReader;S.onload=E=>{var I;const O=(I=E.target)==null?void 0:I.result,D=p(O);r(D)},S.readAsText(w)},y=async()=>{const j=n.filter(A=>!A.error);if(j.length===0){ae.error("No valid transactions to import");return}i(!0),o(0);let w=0,S=0;for(let A=0;AI.name.toLowerCase()===E.lead_source_name.toLowerCase()),D=d==null?void 0:d.find(I=>I.name.toLowerCase()===E.client_type_name.toLowerCase());await u.mutateAsync({property_address:E.property_address,city:E.city||null,state:E.state||null,zip:E.zip||null,transaction_type:E.transaction_type,close_date:E.close_date,sale_price:E.sale_price,commission_amount:E.commission_amount,lead_source_id:(O==null?void 0:O.id)||null,client_type_id:(D==null?void 0:D.id)||null,contact_id:null,notes:E.notes||null,is_win:E.is_win}),w++}catch(O){S++,console.error("Failed to import transaction:",O)}o(Math.round((A+1)/j.length*100))}i(!1),w>0&&ae.success(`Imported ${w} transaction${w>1?"s":""}`),S>0&&ae.error(`Failed to import ${S} transaction${S>1?"s":""}`),r([]),t(!1)},_=n.filter(j=>!j.error).length,v=n.filter(j=>j.error).length;return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh]",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Import Transactions"}),e.jsx(Jn,{children:"Upload a CSV file with your past transactions"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 border rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Download Template"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Get a CSV template with the correct format"})]}),e.jsxs(B,{variant:"outline",onClick:h,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Template"]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"csv-file",children:"Upload CSV File"}),e.jsx(ye,{id:"csv-file",type:"file",accept:".csv",onChange:f})]}),n.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ue,{variant:"outline",children:[n.length," rows found"]}),_>0&&e.jsxs(Ue,{className:"bg-green-500 text-white",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"}),_," valid"]}),v>0&&e.jsxs(Ue,{variant:"destructive",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"}),v," errors"]})]}),e.jsx(di,{className:"h-[200px] border rounded-lg",children:e.jsxs("div",{className:"p-2 space-y-2",children:[n.slice(0,10).map((j,w)=>e.jsxs("div",{className:`p-2 rounded text-sm ${j.error?"bg-destructive/10":"bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"font-medium",children:j.property_address||"(no address)"}),e.jsx(Ue,{variant:j.transaction_type==="buyer"?"default":"secondary",children:j.transaction_type})]}),e.jsxs("div",{className:"text-muted-foreground",children:[j.close_date," • $",j.sale_price.toLocaleString()]}),j.error&&e.jsx(oIe,{variant:"destructive",className:"mt-1 py-1",children:e.jsx(lIe,{className:"text-xs",children:j.error})})]},w)),n.length>10&&e.jsxs("p",{className:"text-center text-sm text-muted-foreground",children:["...and ",n.length-10," more"]})]})}),a&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"w-full bg-muted rounded-full h-2",children:e.jsx("div",{className:"bg-primary h-2 rounded-full transition-all",style:{width:`${l}%`}})}),e.jsxs("p",{className:"text-sm text-center text-muted-foreground",children:["Importing... ",l,"%"]})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:y,disabled:_===0||a,children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Import ",_," Transaction",_!==1?"s":""]})]})]})]})})}const jYs=Gw({transactions_goal:z9().min(0).optional(),volume_goal:z9().min(0).optional(),gci_goal:z9().min(0).optional()});function NYs({open:s,onOpenChange:t,year:n,existingGoals:r}){const a=grs(),{data:i}=Aye(),l=(i==null?void 0:i.show_commission)??!0,o=bye({resolver:_ye(jYs),defaultValues:{transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0}});N.useEffect(()=>{r?o.reset({transactions_goal:r.transactions_goal??void 0,volume_goal:r.volume_goal?Number(r.volume_goal):void 0,gci_goal:r.gci_goal?Number(r.gci_goal):void 0}):o.reset({transactions_goal:void 0,volume_goal:void 0,gci_goal:void 0})},[r,o,s]);const c=async d=>{await a.mutateAsync({year:n,transactions_goal:d.transactions_goal??null,volume_goal:d.volume_goal??null,gci_goal:l?d.gci_goal??null:null}),t(!1)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{children:[n," Goals"]}),e.jsx(Jn,{children:"Set your annual targets to track your progress throughout the year."})]}),e.jsx(wye,{...o,children:e.jsxs("form",{onSubmit:o.handleSubmit(c),className:"space-y-4",children:[e.jsx(_u,{control:o.control,name:"transactions_goal",render:({field:d})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Transactions Goal"}),e.jsx(nu,{children:e.jsx(ye,{type:"number",placeholder:"e.g., 24",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(Mme,{children:"Total number of deals you want to close"}),e.jsx(Wx,{})]})}),e.jsx(_u,{control:o.control,name:"volume_goal",render:({field:d})=>e.jsxs(tu,{children:[e.jsx(su,{children:"Volume Goal ($)"}),e.jsx(nu,{children:e.jsx(ye,{type:"number",placeholder:"e.g., 5000000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(Mme,{children:"Total sales volume you want to achieve"}),e.jsx(Wx,{})]})}),l&&e.jsx(_u,{control:o.control,name:"gci_goal",render:({field:d})=>e.jsxs(tu,{children:[e.jsx(su,{children:"GCI Goal ($)"}),e.jsx(nu,{children:e.jsx(ye,{type:"number",placeholder:"e.g., 150000",...d,value:d.value??"",onChange:u=>d.onChange(u.target.value?Number(u.target.value):void 0)})}),e.jsx(Mme,{children:"Gross commission income target"}),e.jsx(Wx,{})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:a.isPending,children:"Save Goals"})]})]})})]})})}function YLe({transactions:s,isLoading:t}){const n=N.useRef(null),r=N.useRef(null),a=N.useRef([]),i=N.useRef(null),{isAdmin:l}=vs(),[o,c]=N.useState(""),[d,u]=N.useState(!0),[h,p]=N.useState(0),[f,y]=N.useState(!1),_=s.filter(j=>j.latitude!=null&&j.longitude!=null),v=s.filter(j=>j.latitude==null||j.longitude==null);return N.useEffect(()=>{(async()=>{u(!0);try{const{data:w}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();w!=null&&w.value&&c(w.value)}catch(w){console.error("Error fetching mapbox token:",w)}u(!1)})()},[]),N.useEffect(()=>{if(!o||v.length===0||f)return;(async()=>{var S;y(!0);let w=0;for(const A of v){const E=[A.property_address,A.city,A.state,A.zip].filter(Boolean).join(", ");if(E)try{const D=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(E)}.json?access_token=${o}&limit=1`)).json();if((S=D.features)!=null&&S[0]){const[I,F]=D.features[0].center;await q.from("scorecard_transactions").update({latitude:F,longitude:I}).eq("id",A.id),A.latitude=F,A.longitude=I,w++}}catch(O){console.error("Geocode error:",O)}}p(w),y(!1)})()},[o,s]),N.useEffect(()=>{if(!n.current||!o||r.current)return;ul.accessToken=o;const j=s.filter(A=>A.latitude!=null&&A.longitude!=null);let w=[-98.5795,39.8283],S=4;if(j.length>0){const A=j.reduce((O,D)=>O+D.longitude,0)/j.length,E=j.reduce((O,D)=>O+D.latitude,0)/j.length;w=[A,E],S=j.length===1?12:10}return r.current=new ul.Map({container:n.current,style:"mapbox://styles/mapbox/light-v11",zoom:S,center:w}),r.current.addControl(new ul.NavigationControl,"top-right"),()=>{var A;(A=r.current)==null||A.remove(),r.current=null}},[o]),N.useEffect(()=>{var w;if(!r.current||!o)return;a.current.forEach(S=>S.remove()),a.current=[],(w=i.current)==null||w.remove();const j=s.filter(S=>S.latitude!=null&&S.longitude!=null);if(j.forEach(S=>{var F;const A=S.transaction_type==="buyer",E=A?"#3B82F6":"#10B981",O=document.createElement("div");O.className="cursor-pointer",O.innerHTML=`
${A?'':''}
`;const D=new ul.Popup({offset:25,closeButton:!0}).setHTML(`
${S.property_address}
${S.city?`
${S.city}${S.state?", "+S.state:""} ${S.zip||""}
`:""}
${A?"Buyer":"Seller"} $${Number(S.sale_price).toLocaleString()}
Closed: ${Ll(S.close_date).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})} ${(F=S.lead_source)!=null&&F.name?" · "+S.lead_source.name:""}
${S.contact?`
Client: ${S.contact.first_name} ${S.contact.last_name||""}
`:""}
`),I=new ul.Marker(O).setLngLat([S.longitude,S.latitude]).setPopup(D).addTo(r.current);a.current.push(I)}),j.length>1){const S=new ul.LngLatBounds;j.forEach(A=>S.extend([A.longitude,A.latitude])),r.current.fitBounds(S,{padding:60,maxZoom:13})}else j.length===1&&r.current.flyTo({center:[j[0].longitude,j[0].latitude],zoom:12})},[s,o,f]),d||t?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center h-[50vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(ka,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Transactions Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add transactions to see them plotted on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#3B82F6"}}),e.jsx("span",{children:"Buyer"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-4 h-4 rounded-full border-2 border-white shadow",style:{background:"#10B981"}}),e.jsx("span",{children:"Seller"})]}),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[_.length," of ",s.length," mapped",f&&" · Geocoding..."]})]}),e.jsx("div",{ref:n,className:"w-full h-[55vh] rounded-lg shadow-lg border"})]}):e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center h-[50vh] text-center gap-3",children:[e.jsx(Bi,{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 Ljt=()=>{const{data:s}=Wv();return dt({queryKey:["team-scorecard-members",s==null?void 0:s.teamId],queryFn:async()=>{const{data:t,error:n}=await q.from("team_members").select("user_id").eq("team_id",s.teamId);if(n)throw n;const r=t.map(l=>l.user_id),{data:a,error:i}=await q.from("profiles").select("id, name, email, avatar_url").in("id",r);if(i)throw i;return a||[]},enabled:!!(s!=null&&s.teamId)&&(s==null?void 0:s.role)==="team_leader"})},kYs=s=>{const{data:t}=Wv(),{data:n}=Ljt();return dt({queryKey:["team-scorecard-transactions",t==null?void 0:t.teamId,s],queryFn:async()=>{const r=n.map(o=>o.id);let a=q.from("scorecard_transactions").select(` *, lead_source:lead_sources(id, name), client_type:relationship_types(id, name), contact:innercircle_contacts(id, first_name, last_name) `).in("owner_user_id",r).order("close_date",{ascending:!1});s&&(a=a.gte("close_date",`${s}-01-01`).lte("close_date",`${s}-12-31`));const{data:i,error:l}=await a;if(l)throw l;return i},enabled:!!n&&n.length>0})};function SYs(s,t){const n=t.filter(i=>i.owner_user_id===s.id),r=n.reduce((i,l)=>i+Number(l.sale_price),0),a=n.reduce((i,l)=>i+(Number(l.commission_amount)||0),0);return{member:s,totalTransactions:n.length,buyerCount:n.filter(i=>i.transaction_type==="buyer").length,sellerCount:n.filter(i=>i.transaction_type==="seller").length,totalVolume:r,averagePrice:n.length>0?r/n.length:0,totalGCI:a}}function CYs(s,t){return s?s.split(" ").map(n=>n[0]).join("").toUpperCase().slice(0,2):t[0].toUpperCase()}function TYs({year:s}){var p;const{data:t,isLoading:n}=Ljt(),{data:r,isLoading:a}=kYs(s),i=Ln(),l=n||a,{aggregate:o,memberStats:c,topPerformer:d,agentNameMap:u,teamChartStats:h}=N.useMemo(()=>{if(!t||!r)return{aggregate:null,memberStats:[],topPerformer:null,agentNameMap:{},teamChartStats:null};const f=t.map(z=>SYs(z,r));f.sort((z,H)=>H.totalVolume-z.totalVolume);const y={};t.forEach(z=>{y[z.id]=z.name||z.email});const _=r.length,v=r.reduce((z,H)=>z+Number(H.sale_price),0),j=r.reduce((z,H)=>z+(Number(H.commission_amount)||0),0),w=r.filter(z=>z.transaction_type==="buyer").length,S=r.filter(z=>z.transaction_type==="seller").length,A={};r.forEach(z=>{var Z;const H=((Z=z.lead_source)==null?void 0:Z.name)||"Unknown";A[H]=(A[H]||0)+1});const E=Object.entries(A).sort((z,H)=>H[1]-z[1])[0],O={};r.forEach(z=>{const H=Ll(z.close_date).toLocaleString("default",{month:"short"});O[H]=(O[H]||0)+1});const I=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"].map(z=>({month:z,count:O[z]||0})),F=Object.entries(A).map(([z,H])=>({name:z,count:H})).sort((z,H)=>H.count-z.count);return{aggregate:{totalTxns:_,buyerCount:w,sellerCount:S,totalVolume:v,avgPrice:_>0?v/_:0,totalGCI:j,topSource:E?{name:E[0],count:E[1]}:null,memberCount:t.length},memberStats:f,topPerformer:f[0]||null,agentNameMap:y,teamChartStats:{transactionsByMonth:I,leadSourceBreakdown:F}}},[t,r]);return l?e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[1,2,3,4].map(f=>e.jsx(Ws,{className:"h-24"},f))}),e.jsx(Ws,{className:"h-64"})]}):!o||c.length===0?e.jsx(fe,{className:"py-12",children:e.jsxs(Ee,{className:"text-center space-y-2",children:[e.jsx(An,{className:"h-10 w-10 mx-auto text-muted-foreground"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No Team Data"}),e.jsxs("p",{className:"text-muted-foreground",children:["No scorecard transactions found for your team members in ",s,"."]})]})}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-6 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(An,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Members"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.memberCount})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Or,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Team Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:o.totalTxns}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.buyerCount,"B / ",o.sellerCount,"S"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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:jc(o.totalVolume,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(go,{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:jc(o.avgPrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{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:jc(o.totalGCI,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((p=o.topSource)==null?void 0:p.name)||"-"}),o.topSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[o.topSource.count," deals"]})]})})]}),d&&d.totalTransactions>0&&e.jsx(fe,{className:"border-primary/30 bg-primary/5",children:e.jsxs(Ee,{className:"pt-4 flex items-center gap-4",children:[e.jsx("div",{className:"flex items-center justify-center h-10 w-10 rounded-full bg-primary/10",children:e.jsx(xo,{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:jc(d.totalVolume,!0)})]})]})}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Member Performance"})}),e.jsx(Ee,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Transactions"}),e.jsx(Tt,{className:"text-center",children:"B / S"}),e.jsx(Tt,{className:"text-right",children:"Volume"}),e.jsx(Tt,{className:"text-right",children:"Avg Price"}),e.jsx(Tt,{className:"text-right",children:"GCI"}),e.jsx(Tt,{className:"text-right"})]})}),e.jsx(da,{children:c.map((f,y)=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"relative",children:[y===0&&f.totalTransactions>0&&e.jsx(xo,{className:"absolute -top-2 -right-2 h-3.5 w-3.5 text-amber-500"}),e.jsxs(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:f.member.avatar_url||void 0}),e.jsx(ea,{className:"text-xs",children:CYs(f.member.name,f.member.email)})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:f.member.name||f.member.email}),f.member.name&&e.jsx("p",{className:"text-xs text-muted-foreground",children:f.member.email})]})]})}),e.jsx(ht,{className:"text-center font-semibold",children:f.totalTransactions}),e.jsxs(ht,{className:"text-center text-sm",children:[f.buyerCount," / ",f.sellerCount]}),e.jsx(ht,{className:"text-right font-medium",children:jc(f.totalVolume,!0)}),e.jsx(ht,{className:"text-right text-sm",children:jc(f.averagePrice,!0)}),e.jsx(ht,{className:"text-right font-medium",children:jc(f.totalGCI,!0)}),e.jsx(ht,{className:"text-right",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>i(`/mission-control/scorecard/${f.member.id}`),children:e.jsx(Sr,{className:"h-4 w-4"})})})]},f.member.id))})]})})})]}),e.jsxs(Fr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"transactions",children:[e.jsx(Sp,{className:"h-4 w-4 mr-1"}),"All Transactions"]}),e.jsxs(Zt,{value:"charts",children:[e.jsx(_o,{className:"h-4 w-4 mr-1"}),"Charts"]}),e.jsxs(Zt,{value:"map",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(is,{value:"transactions",children:e.jsx(WLe,{transactions:r||[],showCommission:!0,isLoading:a,agentNameMap:u,readOnly:!0})}),e.jsx(is,{value:"charts",children:h&&e.jsx(KLe,{stats:h,year:s})}),e.jsx(is,{value:"map",children:e.jsx(YLe,{transactions:r||[],isLoading:a})})]})]})}const Wme=new Date().getFullYear(),SQe=Array.from({length:10},(s,t)=>Wme-t),xG="all";function EYs(){var Z;const[s,t]=N.useState(Wme),n=s===null?xG:String(s),r=Y=>t(Y===xG?null:Number(Y)),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState("my"),{data:y}=Wv(),_=(y==null?void 0:y.role)==="team_leader",{data:v,isLoading:j}=s6e(s??void 0),{yearStats:w,lifetimeStats:S,isLoading:A,showCommission:E}=qmt(s??void 0),{data:O,isLoading:D}=Umt(s??Wme),{data:I}=Aye(),F=yrs(),z=()=>{if(!v||v.length===0)return;const Y=["Property Address","City","State","Zip","Transaction Type","Close Date","Sale Price",...E?["Commission"]:[],"Lead Source","Client Type","Contact Name","Is Win","Notes"],W=v.map(ce=>{var me,le;return[ce.property_address,ce.city||"",ce.state||"",ce.zip||"",ce.transaction_type,ce.close_date,ce.sale_price,...E?[ce.commission_amount||""]:[],((me=ce.lead_source)==null?void 0:me.name)||"",((le=ce.client_type)==null?void 0:le.name)||"",ce.contact?`${ce.contact.first_name} ${ce.contact.last_name||""}`.trim():"",ce.is_win?"Yes":"No",ce.notes||""]}),ee=[Y,...W].map(ce=>ce.map(me=>`"${String(me).replace(/"/g,'""')}"`).join(",")).join(` `),se=new Blob([ee],{type:"text/csv"}),oe=URL.createObjectURL(se),he=document.createElement("a");he.href=oe,he.download=s===null?"transactions-all.csv":`transactions-${s}.csv`,he.click(),URL.revokeObjectURL(oe)},H=!v||v.length===0;return e.jsxs(Cs,{title:"Scorecard",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Scorecard"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500/50 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),_&&e.jsxs("div",{className:"flex items-center gap-1 bg-muted rounded-lg p-1 w-fit",children:[e.jsx(B,{variant:p==="my"?"default":"ghost",size:"sm",onClick:()=>f("my"),className:"h-8",children:"My Scorecard"}),e.jsxs(B,{variant:p==="team"?"default":"ghost",size:"sm",onClick:()=>f("team"),className:"h-8",children:[e.jsx(An,{className:"h-4 w-4 mr-1.5"}),"Team"]})]}),p==="team"&&_?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-semibold text-foreground",children:"Team Performance"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Aggregate stats and member comparison"})]}),e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:xG,children:"All Years"}),SQe.map(Y=>e.jsx(Ze,{value:String(Y),children:Y},Y))]})]})]}),e.jsx(TYs,{year:s??void 0})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Business Scorecard"}),e.jsx("p",{className:"text-muted-foreground",children:"Track your transactions, goals, and performance"})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:xG,children:"All Years"}),SQe.map(Y=>e.jsx(Ze,{value:String(Y),children:Y},Y))]})]}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>h(!u),children:e.jsx(Ko,{className:"h-4 w-4"})})]})]}),u&&e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsx(Rt,{className:"text-lg",children:"Settings"})}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ne,{children:"Show Commission"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Display commission fields and include in stats"})]}),e.jsx(jn,{checked:(I==null?void 0:I.show_commission)??!0,onCheckedChange:Y=>F.mutate({show_commission:Y})})]})})]}),H&&!j?e.jsx(fe,{className:"py-12",children:e.jsxs(Ee,{className:"text-center space-y-4",children:[e.jsx("div",{className:"w-16 h-16 mx-auto rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(_o,{className:"h-8 w-8 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Start Tracking Your Success"}),e.jsx("p",{className:"text-muted-foreground max-w-md mx-auto mt-1",children:"Add your past transactions to see your performance metrics, track your goals, and celebrate your wins."})]}),e.jsxs("div",{className:"flex flex-wrap justify-center gap-2 pt-2",children:[e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Your First Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Import CSV"]})]}),e.jsxs("div",{className:"pt-4 border-t mt-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Need help formatting your data?"}),e.jsx(B,{variant:"link",className:"h-auto p-0",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Download CSV Template"]})})]})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Transaction"]}),e.jsxs(B,{variant:"outline",onClick:()=>d(!0),children:[e.jsx(Ac,{className:"h-4 w-4 mr-2"}),"Set Goals"]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!0),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Import"]}),e.jsxs(B,{variant:"outline",onClick:z,disabled:H,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Export"]}),e.jsx(B,{variant:"ghost",size:"sm",asChild:!0,children:e.jsxs("a",{href:"/templates/transaction-import-template.csv",download:!0,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"CSV Template"]})})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-7 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Or,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:w.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[S.totalTransactions," lifetime"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(An,{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:[w.buyerCount,"/",w.sellerCount]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"B/S split"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:jc(w.totalVolume,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[jc(S.totalVolume,!0)," lifetime"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(go,{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:jc(w.averagePrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fc,{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=w.topLeadSource)==null?void 0:Z.name)||"-"}),w.topLeadSource&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[w.topLeadSource.count," deals"]})]})}),E&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"GCI"})]}),e.jsx("p",{className:"text-2xl font-bold",children:jc(w.totalCommission,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[jc(S.totalCommission,!0)," lifetime"]})]})}),E&&w.totalNetToAgent>0&&w.totalNetToAgent!==w.totalCommission&&e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-teal-600 dark:text-teal-400 mb-1",children:[e.jsx(Yl,{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:jc(w.totalNetToAgent,!0)}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[jc(S.totalNetToAgent,!0)," lifetime"]})]})})]}),s!==null&&O&&e.jsx(Ejt,{goals:O,stats:w,year:s,showCommission:E}),e.jsxs(Fr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"transactions",children:"Transactions"}),e.jsx(Zt,{value:"charts",children:"Charts"}),e.jsxs(Zt,{value:"map",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(is,{value:"transactions",children:e.jsx(WLe,{transactions:v||[],showCommission:E,isLoading:j})}),e.jsx(is,{value:"charts",children:e.jsx(KLe,{stats:w,year:s??void 0})}),e.jsx(is,{value:"map",children:e.jsx(YLe,{transactions:v||[],isLoading:j})})]})]})]})]}),e.jsx(Tjt,{open:a,onOpenChange:i}),e.jsx(wYs,{open:l,onOpenChange:o}),e.jsx(NYs,{open:c,onOpenChange:d,year:s??Wme,existingGoals:O})]})}function Djt({open:s,onOpenChange:t,listingId:n,listingSlug:r,listingTitle:a}){const{user:i}=vs(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1);N.useEffect(()=>{(async()=>{if(!(!s||!i)){d(!0);try{const{data:v,error:j}=await q.from("listing_shares").select("id, share_token, click_count, lead_count").eq("listing_id",n).eq("sharing_agent_id",i.id).order("created_at",{ascending:!1}).limit(1).maybeSingle();if(j)throw j;if(v&&v.share_token)o(v);else if(v&&!v.share_token){const{data:w,error:S}=await q.from("listing_shares").update({share_type:"referral_link"}).eq("id",v.id).select("id, share_token, click_count, lead_count").single();if(S)throw S;o(w)}else{const{data:w,error:S}=await q.from("listing_shares").insert({listing_id:n,sharing_agent_id:i.id,share_type:"referral_link"}).select("id, share_token, click_count, lead_count").single();if(S)throw S;o(w)}}catch(v){console.error("Error creating share link:",v),ae.error("Failed to generate share link")}finally{d(!1)}}})()},[s,i,n]);const p=l!=null&&l.share_token?`https://listings.relevelup.com/${r||n}?ref=${l.share_token}`:"",f=async()=>{try{await navigator.clipboard.writeText(p),h(!0),ae.success("Link copied to clipboard!"),setTimeout(()=>h(!1),2e3)}catch{ae.error("Failed to copy link")}},y=_=>{const v=encodeURIComponent(p),j=encodeURIComponent(`Check out this listing: ${a}`);switch(_){case"email":window.open(`mailto:?subject=${j}&body=${v}`);break;case"text":window.open(`sms:?body=${j}%20${v}`);break;case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${v}`,"_blank");break}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Share & Earn Leads"]}),e.jsx(Jn,{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(ne,{children:"Your Referral Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:c?"Generating...":p,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:f,disabled:c||!p,variant:u?"default":"outline",children:u?e.jsx(Lr,{className:"h-4 w-4"}):e.jsx(Zr,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Share via"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>y("email"),disabled:c,children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Email"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>y("text"),disabled:c,children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:()=>y("facebook"),disabled:c,children:[e.jsx(Mh,{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(ne,{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(Sr,{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(An,{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 AYs={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"},MYs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},IYs={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function PYs({listing:s,onClick:t,onEdit:n,onDelete:r,onCreateMusicVideo:a,showActions:i}){var v,j;const{user:l}=vs(),{data:o}=Rmt(s.id),c=Dmt(),[d,u]=N.useState(!1),h=w=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(w),p=((v=s.photos)==null?void 0:v.find(w=>w.is_primary))||((j=s.photos)==null?void 0:j[0]),f=(l==null?void 0:l.id)===s.agent_id,y=async w=>{w.stopPropagation();try{const S=await c.mutateAsync(s.id);ae.success(S.saved?"Listing saved!":"Listing removed from saved")}catch{ae.error("Failed to save listing")}},_=w=>{if(w.stopPropagation(),l)u(!0);else{const S=`https://listings.relevelup.com/${s.slug||s.id}`;navigator.clipboard.writeText(S),ae.success("Link copied to clipboard!")}};return e.jsxs(fe,{className:"overflow-hidden hover:shadow-lg transition-shadow cursor-pointer group",onClick:t,children:[e.jsxs("div",{className:"relative aspect-[4/3] bg-muted",children:[p?e.jsx("img",{src:p.photo_url,alt:s.property_address||s.city,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:e.jsx(ay,{className:"h-12 w-12"})}),e.jsx(Ue,{className:`absolute top-2 left-2 ${AYs[s.status]} text-white border-0`,children:MYs[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(oa,{className:"h-4 w-4 text-white fill-white"})}),e.jsxs("div",{className:"absolute bottom-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(B,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:y,children:e.jsx(gi,{className:`h-4 w-4 ${o?"fill-pink-500 text-pink-500":""}`})}),e.jsx(B,{size:"icon",variant:"secondary",className:"h-8 w-8",onClick:_,title:f?"Copy link":"Share & earn leads",children:f?e.jsx(Vl,{className:"h-4 w-4"}):e.jsx(un,{className:"h-4 w-4 text-amber-500"})})]})]}),e.jsx(Djt,{open:d,onOpenChange:u,listingId:s.id,listingSlug:s.slug||null,listingTitle:s.property_address||`${s.city}, ${s.state}`}),e.jsxs(Ee,{className:"p-4 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xl font-bold text-primary",children:h(s.price)}),s.open_to_referrals&&e.jsxs(Ue,{variant:"outline",className:"text-xs",children:[e.jsx(An,{className:"h-3 w-3 mr-1"}),"Referrals"]})]}),e.jsxs("div",{children:[s.property_address&&e.jsx("p",{className:"font-medium truncate",children:s.property_address}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),s.city,", ",s.state,s.neighborhood&&` • ${s.neighborhood}`]})]}),e.jsxs("div",{className:"flex items-center gap-4 text-sm text-muted-foreground",children:[s.bedrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(J0,{className:"h-4 w-4"}),s.bedrooms," bd"]}),s.bathrooms&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(kp,{className:"h-4 w-4"}),s.bathrooms," ba"]}),s.square_footage&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ay,{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(Ue,{variant:"secondary",className:"text-xs",children:IYs[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(Sr,{className:"h-3 w-3"}),s.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vl,{className:"h-3 w-3"}),s.share_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gi,{className:"h-3 w-3"}),s.save_count]})]}),i&&(n||r||a)&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[a&&e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1 min-w-[140px] gap-1.5 border-violet-500/60 text-violet-600 hover:bg-violet-50",onClick:w=>{w.stopPropagation(),a()},children:[e.jsx(cL,{className:"h-4 w-4"}),"Music Video"]}),n&&e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1",onClick:w=>{w.stopPropagation(),n()},children:[e.jsx(wu,{className:"h-4 w-4 mr-2"}),"Edit"]}),r&&e.jsx(B,{variant:"destructive",size:"sm",onClick:w=>{w.stopPropagation(),r()},children:e.jsx(_n,{className:"h-4 w-4"})})]})]})]})}const ZLe="lu_listing_selection_v1",Mge=24,Ige=new Set;function Rjt(){try{return JSON.parse(sessionStorage.getItem(ZLe)||"{}")}catch{return{}}}function yNe(s){try{sessionStorage.setItem(ZLe,JSON.stringify(s))}catch{}Ige.forEach(t=>t())}let x2=Rjt();function LYs(){x2=Rjt(),Ige.forEach(s=>s())}typeof window<"u"&&window.addEventListener("storage",s=>{s.key===ZLe&&LYs()});const Xk={getSnapshot:()=>x2,subscribe(s){return Ige.add(s),()=>Ige.delete(s)},toggle(s){const t={...x2};if(t[s.mlsNumber])delete t[s.mlsNumber];else{if(Object.keys(t).length>=Mge)return!1;t[s.mlsNumber]=s}return x2=t,yNe(t),!0},remove(s){const t={...x2};delete t[s],x2=t,yNe(t)},clear(){x2={},yNe({})},has(s){return!!x2[s]},all(){return Object.values(x2)}};function Ojt(){const s=N.useSyncExternalStore(Xk.subscribe,Xk.getSnapshot,Xk.getSnapshot);return{selected:Object.values(s),selectedIds:new Set(Object.keys(s)),count:Object.keys(s).length,has:t=>!!s[t],toggle:Xk.toggle,remove:Xk.remove,clear:Xk.clear}}const DYs=new Set(["office_exclusive","coming_soon","pre_market"]);function RYs(s){const t=(s.photos??[]).slice().sort((i,l)=>(l.is_primary?1:0)-(i.is_primary?1:0)||(i.sort_order??0)-(l.sort_order??0)).map(i=>i.photo_url).filter(Boolean),n=s.status||"active",r=DYs.has(n);return{mlsNumber:`lx-${s.id}`,address:s.property_address||`${s.city??""}, ${s.state??""}`.trim(),city:s.city||"",state:s.state||"",zip:s.zip_code||s.zip||"",price:Number(s.price)||0,bedrooms:Number(s.bedrooms)||0,bathrooms:Number(s.bathrooms)||0,sqft:Number(s.square_footage)||0,lotSize:s.lot_size?String(s.lot_size):"",yearBuilt:s.year_built??null,propertyType:s.property_type||"",propertySubType:null,description:s.description||"",photos:t,status:n,listDate:s.created_at||new Date().toISOString(),soldDate:null,soldPrice:null,latitude:s.latitude??null,longitude:s.longitude??null,garageSpaces:null,stories:null,hoaFee:null,hoaFrequency:null,taxAmount:null,taxYear:null,heating:null,cooling:null,basement:null,pool:null,fireplace:null,virtualTourUrl:s.virtual_tour_url??null,features:[],appliances:[],flooring:[],parking:null,waterSource:null,sewer:null,externalUrl:r?null:`https://listings.relevelup.com/${s.slug||s.id}`,is_private:r}}function gG(s){const{has:t}=Ojt(),n=`lx-${s.listing.id}`,r=t(n);return e.jsxs("div",{className:"relative",children:[e.jsx(PYs,{...s}),e.jsx("button",{type:"button",onClick:a=>{a.stopPropagation(),Xk.toggle(RYs(s.listing))||ae.error(`You can select up to ${Mge} listings`)},title:r?"Remove from email":"Add to email",className:`absolute top-3 right-3 z-10 h-8 w-8 rounded-full flex items-center justify-center shadow-md border transition ${r?"bg-primary text-primary-foreground border-primary":"bg-white/95 text-foreground border-white hover:bg-white"}`,children:r?e.jsx(Lr,{className:"h-4 w-4"}):e.jsx(Gs,{className:"h-4 w-4"})})]})}function OYs({open:s,onOpenChange:t,listings:n}){const{user:r}=vs(),{leadSite:a}=Ap(),[i,l]=N.useState("grid"),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(new Set),[_,v]=N.useState(!1),[j,w]=N.useState(!1),{data:S}=d1e(),[A,E]=N.useState(!1);N.useEffect(()=>{!s||!(r!=null&&r.id)||q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle().then(({data:ee})=>w(!!(ee!=null&&ee.gmail_email)))},[s,r==null?void 0:r.id]),N.useEffect(()=>{if(s){if(!o){const ee=Array.from(new Set(n.map(oe=>oe.city).filter(Boolean))),se=ee.length===1?` in ${ee[0]}`:"";c(n.length===1?`New listing for you${se}`:`${n.length} hand-picked listings${se}`)}d||u(`Hi {{first_name}}, Thought of you — I just picked a few properties I think you'll love. Take a look and let me know if anything catches your eye. Happy to set up a private showing whenever works.`)}},[s]);const{data:O=[],isLoading:D}=dt({queryKey:["send-listings-contacts",r==null?void 0:r.id],queryFn:async()=>{const{data:ee}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, city").eq("owner_user_id",r.id).not("email","is",null).neq("email","").order("first_name");return ee||[]},enabled:!!(r!=null&&r.id)&&s}),{data:I}=dt({queryKey:["send-listings-suggestions",n.map(ee=>ee.mlsNumber).join(",")],queryFn:async()=>{const{data:ee,error:se}=await q.functions.invoke("listing-email-suggestions",{body:{listings:n.map(oe=>({mlsNumber:oe.mlsNumber,city:oe.city,state:oe.state,price:oe.price,bedrooms:oe.bedrooms,bathrooms:oe.bathrooms}))}});if(se)throw se;return ee},enabled:s&&n.length>0}),F=(I==null?void 0:I.suggestions)||[],z=N.useMemo(()=>{const ee=h.trim().toLowerCase();return ee?O.filter(se=>`${se.first_name??""} ${se.last_name??""} ${se.email} ${se.city??""}`.toLowerCase().includes(ee)):O},[O,h]),H=ee=>{y(se=>{const oe=new Set(se);return oe.has(ee)?oe.delete(ee):oe.add(ee),oe})},Z=()=>{y(ee=>{const se=new Set(ee);return F.forEach(oe=>se.add(oe.contact_id)),se})},Y=n.length>0&&n.every(ee=>ee.mlsNumber.startsWith("lx-")),W=async()=>{if(!Y&&!(a!=null&&a.id)){ae.error("You need an active lead site to send listings.");return}if(!o.trim())return ae.error("Subject is required");if(f.size===0)return ae.error("Pick at least one recipient");if(!j&&S&&!S.hasVerifiedSes){E(!0);return}const ee=O.filter(se=>f.has(se.id)).map(se=>({contact_id:se.id,email:se.email,first_name:se.first_name,last_name:se.last_name}));v(!0);try{const{data:se,error:oe}=await q.functions.invoke("listing-email-send",{body:{lead_site_id:(a==null?void 0:a.id)||null,layout:i,subject:o.trim(),intro_message:d.trim()||null,listings:n.map(he=>({mlsNumber:he.mlsNumber,address:he.address,city:he.city,state:he.state,zip:he.zip,price:he.price,bedrooms:he.bedrooms,bathrooms:he.bathrooms,sqft:he.sqft,status:he.status,photos:(he.photos||[]).slice(0,1),description:he.description||"",external_url:he.externalUrl||null,is_private:he.is_private===!0})),recipients:ee}});if(oe)throw oe;if(!(se!=null&&se.success))throw new Error((se==null?void 0:se.error)||"Send failed");ae.success(`Sent ${se.sent}/${ee.length} via ${j?"Gmail":"Amazon SES"}${se.failed?` · ${se.failed} failed`:""}`),Xk.clear(),y(new Set),t(!1)}catch(se){ae.error((se==null?void 0:se.message)||"Failed to send")}finally{v(!1)}};return e.jsxs(_s,{open:s,onOpenChange:t,children:[e.jsxs(bs,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0 flex flex-col",children:[e.jsxs(js,{className:"px-6 pt-6 pb-2",children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5 text-primary"}),"Email ",n.length," ",n.length===1?"Listing":"Listings"]}),e.jsx(Jn,{children:Y?"Send your Listing Exchange properties. Recipients land on listings.relevelup.com and clicks track back to the contact.":"Drive traffic to your site. Recipients land on your lead site and clicks show up on Mission Control."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-0 flex-1 overflow-hidden",children:[e.jsxs("div",{className:"overflow-y-auto px-6 pb-4 space-y-4 border-r",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Selected listings"}),e.jsx("div",{className:"mt-2 flex gap-2 overflow-x-auto pb-1",children:n.map(ee=>{var se;return e.jsxs("div",{className:"shrink-0 w-32 rounded-lg overflow-hidden border bg-muted",children:[e.jsx("div",{className:"h-20 w-full bg-muted",children:((se=ee.photos)==null?void 0:se[0])&&e.jsx("img",{src:ee.photos[0],alt:"",className:"h-full w-full object-cover"})}),e.jsxs("div",{className:"p-1.5",children:[e.jsxs("div",{className:"text-[11px] font-semibold truncate",children:["$",(ee.price/1e3).toFixed(0),"k"]}),e.jsxs("div",{className:"text-[10px] text-muted-foreground truncate",children:[ee.city,", ",ee.state]})]})]},ee.mlsNumber)})})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Layout"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-2",children:[e.jsxs("button",{type:"button",onClick:()=>l("grid"),className:`rounded-lg border p-3 text-left transition ${i==="grid"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(ff,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Magazine grid"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clean card stack"})]}),e.jsxs("button",{type:"button",onClick:()=>l("hero"),className:`rounded-lg border p-3 text-left transition ${i==="hero"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsx(Xo,{className:"h-4 w-4 mb-1.5"}),e.jsx("div",{className:"text-sm font-medium",children:"Hero + list"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"First listing gets spotlight"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"subject",children:"Subject"}),e.jsx(ye,{id:"subject",value:o,onChange:ee=>c(ee.target.value),placeholder:"Subject line",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"intro",children:"Personal message"}),e.jsx(Ms,{id:"intro",value:d,onChange:ee=>u(ee.target.value),placeholder:"Optional intro shown above the listings…",className:"mt-1 min-h-[120px]"}),e.jsxs("p",{className:"text-[11px] text-muted-foreground mt-1",children:["Use ",e.jsx("code",{className:"px-1 rounded bg-muted",children:"{{first_name}}"})," to personalize."]})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 text-xs text-muted-foreground",children:["Sending via"," ",e.jsx("span",{className:"font-medium text-foreground",children:j?"your connected Gmail":"Amazon SES"}),". Every click tracks back to the contact and triggers a buyer signal."]})]}),e.jsxs("div",{className:"flex flex-col overflow-hidden",children:[e.jsxs("div",{className:"px-6 pt-4 pb-2 space-y-3",children:[F.length>0&&e.jsxs(fe,{className:"p-3 bg-amber-50/50 border-amber-200",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-amber-600"}),e.jsxs("div",{className:"text-sm font-medium",children:[F.length," smart ",F.length===1?"match":"matches"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:Z,children:"Add all"})]}),e.jsx(di,{className:"max-h-32 mt-2",children:e.jsx("div",{className:"space-y-1",children:F.slice(0,12).map(ee=>{const se=f.has(ee.contact_id);return e.jsxs("label",{className:"flex items-start gap-2 text-xs py-1 cursor-pointer",children:[e.jsx(hi,{checked:se,onCheckedChange:()=>H(ee.contact_id),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[ee.first_name," ",ee.last_name??""," ",e.jsxs("span",{className:"text-muted-foreground font-normal",children:["· ",ee.email]})]}),e.jsx("div",{className:"text-muted-foreground truncate",children:ee.reason})]})]},ee.contact_id)})})})]}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:["All contacts (",z.length,")"]}),f.size>0&&e.jsxs(Ue,{variant:"secondary",children:[f.size," selected"]})]}),e.jsx(ye,{placeholder:"Search contacts…",value:h,onChange:ee=>p(ee.target.value)})]}),e.jsx("div",{className:"flex-1 overflow-hidden px-6 pb-2",children:e.jsx("div",{className:"border rounded-md h-full",children:e.jsx(di,{className:"h-full",children:D?e.jsx("div",{className:"p-4 text-sm text-muted-foreground",children:"Loading…"}):z.length===0?e.jsx("div",{className:"p-4 text-sm text-muted-foreground text-center",children:"No contacts found"}):e.jsx("div",{className:"divide-y",children:z.map(ee=>{const se=f.has(ee.id);return e.jsxs("label",{className:"flex items-center gap-2 px-3 py-2 cursor-pointer hover:bg-muted/40",children:[e.jsx(hi,{checked:se,onCheckedChange:()=>H(ee.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-sm font-medium truncate",children:[ee.first_name," ",ee.last_name??""]}),e.jsxs("div",{className:"text-xs text-muted-foreground truncate",children:[ee.email,ee.city&&e.jsxs(e.Fragment,{children:[" · ",ee.city]})]})]})]},ee.id)})})})})}),e.jsxs("div",{className:"px-6 py-2 text-xs text-muted-foreground border-t flex items-center justify-between",children:[e.jsxs("span",{children:[e.jsx("strong",{className:"text-foreground",children:f.size})," recipients"]}),f.size>0&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>y(new Set),children:[e.jsx($n,{className:"h-3 w-3 mr-1"}),"Clear"]})]})]})]}),e.jsxs(Xn,{className:"px-6 py-4 border-t bg-muted/30",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsx(B,{onClick:W,disabled:_||f.size===0,children:_?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Sending…"]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Send to ",f.size," ",f.size===1?"contact":"contacts"]})})]})]}),e.jsx(u1e,{open:A,onOpenChange:E,hasPending:!!(S!=null&&S.hasPendingSes),pendingEmails:S==null?void 0:S.pendingEmails})]})}function FYs(){const{selected:s,count:t,remove:n,clear:r}=Ojt(),[a,i]=N.useState(!1);return t===0?null:e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"fixed bottom-4 left-1/2 -translate-x-1/2 z-50 w-[min(96vw,820px)]",children:e.jsxs("div",{className:"rounded-2xl border bg-background/95 backdrop-blur shadow-2xl p-3 flex items-center gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2 px-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 text-primary flex items-center justify-center font-semibold",children:t}),e.jsxs("div",{className:"text-sm",children:[e.jsxs("div",{className:"font-medium leading-tight",children:[t," listing",t===1?"":"s"," selected"]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:t>=Mge?"Max reached":`Pick up to ${Mge}`})]})]}),e.jsx("div",{className:"flex-1 overflow-x-auto hidden sm:block",children:e.jsxs("div",{className:"flex items-center gap-2",children:[s.slice(0,6).map(l=>{var o;return e.jsxs("div",{className:"group relative shrink-0 h-12 w-16 rounded-md overflow-hidden border bg-muted",title:l.address,children:[(o=l.photos)!=null&&o[0]?e.jsx("img",{src:l.photos[0],alt:"",className:"h-full w-full object-cover"}):e.jsx("div",{className:"h-full w-full"}),e.jsx("button",{"aria-label":"Remove",onClick:()=>n(l.mlsNumber),className:"absolute inset-0 bg-black/50 opacity-0 group-hover:opacity-100 flex items-center justify-center transition",children:e.jsx($n,{className:"h-4 w-4 text-white"})})]},l.mlsNumber)}),t>6&&e.jsxs("div",{className:"shrink-0 h-12 w-12 rounded-md border bg-muted flex items-center justify-center text-xs font-medium text-muted-foreground",children:["+",t-6]})]})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(_n,{className:"h-4 w-4"})," Clear"]}),e.jsxs(B,{size:"sm",className:"gap-1.5",onClick:()=>i(!0),children:[e.jsx(lr,{className:"h-4 w-4"}),"Email these ",t===1?"listing":"listings"]})]})]})}),e.jsx(OYs,{open:a,onOpenChange:i,listings:s})]})}const zYs=[{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"}],BYs=[{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 $Ys({filters:s,onFiltersChange:t,onClose:n}){const r=()=>{t({sortBy:"newest"})};return e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between pb-3",children:[e.jsx(Rt,{className:"text-lg",children:"Filters"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:r,children:"Clear All"}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,children:e.jsx($n,{className:"h-4 w-4"})})]})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Status"}),e.jsxs(us,{value:s.status||"all",onValueChange:a=>t({...s,status:a==="all"?void 0:a}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"All statuses"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),zYs.map(a=>e.jsx(Ze,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Property Type"}),e.jsxs(us,{value:s.propertyType||"all",onValueChange:a=>t({...s,propertyType:a==="all"?void 0:a}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"All types"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),BYs.map(a=>e.jsx(Ze,{value:a.value,children:a.label},a.value))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Min Price"}),e.jsx(ye,{type:"number",placeholder:"No minimum",value:s.minPrice||"",onChange:a=>t({...s,minPrice:a.target.value?Number(a.target.value):void 0})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Max Price"}),e.jsx(ye,{type:"number",placeholder:"No maximum",value:s.maxPrice||"",onChange:a=>t({...s,maxPrice:a.target.value?Number(a.target.value):void 0})})]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4 pt-4 border-t",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Open to Referrals Only"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show only listings accepting buyer referrals"})]}),e.jsx(jn,{checked:s.openToReferrals||!1,onCheckedChange:a=>t({...s,openToReferrals:a||void 0})})]})]})]})}function UYs({leaderboard:s}){const t=r=>{switch(r){case 0:return e.jsx(xo,{className:"h-5 w-5 text-amber-500"});case 1:return e.jsx(K2,{className:"h-5 w-5 text-gray-400"});case 2:return e.jsx(fc,{className:"h-5 w-5 text-amber-700"});default:return e.jsx("span",{className:"text-sm font-medium text-muted-foreground w-5 text-center",children:r+1})}},n=(r,a)=>!r||r.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No data yet. Start sharing to climb the leaderboard!"}):e.jsx("div",{className:"space-y-2",children:r.map((i,l)=>e.jsxs("div",{className:`flex items-center gap-4 p-3 rounded-lg ${l===0?"bg-gradient-to-r from-amber-500/10 to-amber-500/5 border border-amber-500/20":"bg-muted/50"}`,children:[e.jsx("div",{className:"flex items-center justify-center w-8",children:t(l)}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsx("p",{className:"font-medium truncate",children:i.name})}),e.jsxs(Ue,{variant:l===0?"default":"secondary",children:[i.count," ",a]})]},i.agentId))});return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(xo,{className:"h-5 w-5 text-amber-500"}),"Community Badges"]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-emerald-500/10 to-emerald-500/5 border border-emerald-500/20",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-emerald-500/20 flex items-center justify-center",children:e.jsx(Vl,{className:"h-6 w-6 text-emerald-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Listing Amplifier"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Share 10+ listings"})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-sky-500/10 to-sky-500/5 border border-sky-500/20",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-sky-500/20 flex items-center justify-center",children:e.jsx(Or,{className:"h-6 w-6 text-sky-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Top Contributor"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add 5+ listings"})]}),e.jsxs("div",{className:"text-center p-4 rounded-lg bg-gradient-to-br from-purple-500/10 to-purple-500/5 border border-purple-500/20",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-2 rounded-full bg-purple-500/20 flex items-center justify-center",children:e.jsx(K2,{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(xo,{className:"h-6 w-6 text-amber-500"})}),e.jsx("p",{className:"font-medium text-sm",children:"Community MVP"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Top performer"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Community Leaderboard"})}),e.jsx(Ee,{children:e.jsxs(Fr,{defaultValue:"sharers",children:[e.jsxs(Rr,{className:"w-full",children:[e.jsxs(Zt,{value:"sharers",className:"flex-1",children:[e.jsx(Vl,{className:"h-4 w-4 mr-2"}),"Top Sharers"]}),e.jsxs(Zt,{value:"listers",className:"flex-1",children:[e.jsx(Or,{className:"h-4 w-4 mr-2"}),"Top Contributors"]})]}),e.jsx(is,{value:"sharers",className:"mt-4",children:n(s==null?void 0:s.topSharers,"shares")}),e.jsx(is,{value:"listers",className:"mt-4",children:n(s==null?void 0:s.topListers,"listings")})]})})]})]})}const CQe={coming_soon:"#F59E0B",office_exclusive:"#6366F1",pre_market:"#06B6D4",active:"#10B981",price_improvement:"#8B5CF6",under_contract:"#3B82F6",sold:"#A855F7"},TQe={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 qYs(s){return s>=1e6?`$${(s/1e6).toFixed(1)}M`:`$${(s/1e3).toFixed(0)}K`}function VYs({listings:s,isLoading:t}){const n=Ln(),r=N.useRef(null),a=N.useRef(null),i=N.useRef([]),{isAdmin:l}=vs(),[o,c]=N.useState(""),[d,u]=N.useState(!0),[h,p]=N.useState(!1),f=s.filter(_=>_.latitude!=null&&_.longitude!=null),y=s.filter(_=>(_.latitude==null||_.longitude==null)&&(_.property_address||_.city));return N.useEffect(()=>{(async()=>{u(!0);try{const{data:v}=await q.from("settings").select("value").eq("key","mapbox_public_token").maybeSingle();v!=null&&v.value&&c(v.value)}catch(v){console.error("Error fetching mapbox token:",v)}u(!1)})()},[]),N.useEffect(()=>{if(!o||y.length===0||h)return;(async()=>{var v;p(!0);for(const j of y){const w=[j.property_address,j.city,j.state].filter(Boolean).join(", ");if(w)try{const A=await(await fetch(`https://api.mapbox.com/geocoding/v5/mapbox.places/${encodeURIComponent(w)}.json?access_token=${o}&limit=1`)).json();if((v=A.features)!=null&&v[0]){const[E,O]=A.features[0].center;await q.from("listings").update({latitude:O,longitude:E}).eq("id",j.id),j.latitude=O,j.longitude=E}}catch(S){console.error("Geocode error:",S)}}p(!1)})()},[o,s]),N.useEffect(()=>{if(!r.current||!o||a.current)return;ul.accessToken=o;const _=s.filter(w=>w.latitude!=null&&w.longitude!=null);let v=[-98.5795,39.8283],j=4;if(_.length>0){const w=_.reduce((A,E)=>A+E.longitude,0)/_.length,S=_.reduce((A,E)=>A+E.latitude,0)/_.length;v=[w,S],j=_.length===1?12:10}return a.current=new ul.Map({container:r.current,style:"mapbox://styles/mapbox/light-v11",zoom:j,center:v}),a.current.addControl(new ul.NavigationControl,"top-right"),()=>{var w;(w=a.current)==null||w.remove(),a.current=null}},[o]),N.useEffect(()=>{if(!a.current||!o)return;i.current.forEach(v=>v.remove()),i.current=[];const _=s.filter(v=>v.latitude!=null&&v.longitude!=null);if(_.forEach(v=>{var O,D,I;const j=CQe[v.status]||"#10B981",w=((O=v.photos)==null?void 0:O.find(F=>F.is_primary))||((D=v.photos)==null?void 0:D[0]),S=document.createElement("div");S.className="cursor-pointer",S.innerHTML=`
`;const A=new ul.Popup({offset:25,closeButton:!0,maxWidth:"280px"}).setHTML(`
${w!=null&&w.photo_url?``:""}
${qYs(v.price)}
${v.property_address||""}
${v.city}, ${v.state}
${TQe[v.status]||v.status} ${v.bedrooms?`${v.bedrooms} bed`:""} ${v.bathrooms?`${v.bathrooms} bath`:""}
${(I=v.agent)!=null&&I.name?`
Listed by ${v.agent.name}
`:""}
Click to view details →
`),E=new ul.Marker(S).setLngLat([v.longitude,v.latitude]).setPopup(A).addTo(a.current);i.current.push(E)}),_.length>1){const v=new ul.LngLatBounds;_.forEach(j=>v.extend([j.longitude,j.latitude])),a.current.fitBounds(v,{padding:60,maxZoom:13})}else _.length===1&&a.current.flyTo({center:[_[0].longitude,_[0].latitude],zoom:12})},[s,o,h]),N.useEffect(()=>(window.__navigateToListing__=_=>{n(`/mission-control/listings/${_}`)},()=>{delete window.__navigateToListing__}),[n]),d||t?e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center h-[60vh]",children:e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-b-2 border-primary"})})}):o?s.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(ka,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"No Listings Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add listings to see them on the map."})]})]})}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-3 text-sm",children:[Object.entries(CQe).map(([_,v])=>e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("div",{className:"w-3 h-3 rounded-full border-2 border-white shadow",style:{background:v}}),e.jsx("span",{className:"text-xs",children:TQe[_]})]},_)),e.jsxs("span",{className:"text-muted-foreground ml-auto text-xs",children:[f.length," of ",s.length," mapped",h&&" · Geocoding..."]})]}),e.jsx("div",{ref:r,className:"w-full h-[60vh] rounded-lg shadow-lg border"})]}):e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center h-[60vh] text-center gap-3",children:[e.jsx(Bi,{className:"h-12 w-12 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:"Map Not Configured"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:l?"Set up your Mapbox token in Settings to enable maps.":"The map feature has not been configured yet. Please contact your administrator."})]})]})})}const tTe="homereel_mv_prefill",sTe="homereel_mv_badge_default";function Fjt(s){try{sessionStorage.setItem(tTe,JSON.stringify(s)),s.badge&&s.badge.type!=="none"&&sessionStorage.setItem(sTe,JSON.stringify(s.badge))}catch{}}function $fn(){try{const s=sessionStorage.getItem(tTe);return s?(sessionStorage.removeItem(tTe),JSON.parse(s)):null}catch{return null}}function Ufn(){try{const s=sessionStorage.getItem(sTe);return s?(sessionStorage.removeItem(sTe),JSON.parse(s)):null}catch{return null}}function zjt(s,t){switch(s){case"coming_soon":case"pre_market":return{type:"coming_soon"};case"price_improvement":return{type:"price_improvement",newPrice:t?String(t):""};case"active":return{type:"just_listed"};default:return{type:"none"}}}function HYs(){var F,z,H,Z,Y,W,ee,se;const s=Ln(),{brokerageId:t}=vs(),{data:n,isLoading:r}=Mmt(),[a,i]=N.useState("feed"),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState({sortBy:"newest"}),{data:p,isLoading:f}=Imt({...u,city:c||u.city}),{data:y,isLoading:_}=ers(),{data:v,isLoading:j}=Pmt(),{data:w,isLoading:S}=rrs(),{data:A,isLoading:E}=ors(),{data:O}=irs(),D=Lmt(),I=async oe=>{if(confirm("Are you sure you want to delete this listing? This action cannot be undone."))try{await D.mutateAsync(oe),ae.success("Listing deleted successfully")}catch{ae.error("Failed to delete listing")}};return r?e.jsx(Cs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})})}):n?e.jsxs(Cs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide px-1.5 py-0.5 rounded border border-amber-500 text-amber-600 dark:text-amber-400 bg-amber-500/10",children:"Beta"})]}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-primary/10 rounded-lg",children:e.jsx(Or,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(p==null?void 0:p.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active Listings"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-pink-500/10 rounded-lg",children:e.jsx(gi,{className:"h-5 w-5 text-pink-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(y==null?void 0:y.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Saved"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-emerald-500/10 rounded-lg",children:e.jsx(gA,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(v==null?void 0:v.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"My Listings"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 bg-sky-500/10 rounded-lg",children:e.jsx(An,{className:"h-5 w-5 text-sky-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:(((F=w==null?void 0:w.sent)==null?void 0:F.length)||0)+(((z=w==null?void 0:w.received)==null?void 0:z.length)||0)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Referrals"})]})]})})]}),e.jsxs(Fr,{value:a,onValueChange:i,children:[e.jsxs(Rr,{className:"w-full justify-start overflow-x-auto",children:[e.jsx(Zt,{value:"feed",children:"Community Feed"}),t&&e.jsx(Zt,{value:"brokerage",children:"Brokerage"}),e.jsx(Zt,{value:"my-listings",children:"My Listings"}),e.jsx(Zt,{value:"saved",children:"Saved"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"map",children:"Map"}),e.jsx(Zt,{value:"leaderboard",children:"Leaderboard"})]}),e.jsxs(is,{value:"feed",className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by city or neighborhood...",value:c,onChange:oe=>d(oe.target.value),className:"pl-9"})]}),e.jsxs(us,{value:u.sortBy,onValueChange:oe=>h({...u,sortBy:oe}),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"Sort by"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"newest",children:"Newest First"}),e.jsx(Ze,{value:"updated",children:"Recently Updated"}),e.jsx(Ze,{value:"price_asc",children:"Price: Low to High"}),e.jsx(Ze,{value:"price_desc",children:"Price: High to Low"})]})]}),e.jsxs(B,{variant:"outline",onClick:()=>o(!l),children:[e.jsx(Lv,{className:"h-4 w-4 mr-2"}),"Filters"]})]}),l&&e.jsx($Ys,{filters:u,onFiltersChange:h,onClose:()=>o(!1)}),f?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(6)].map((oe,he)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"}),e.jsx(Ws,{className:"h-4 w-1/4"})]})]},he))}):(p==null?void 0:p.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Or,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings found"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Be the first to share a listing with the community!"}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:p==null?void 0:p.map(oe=>e.jsx(gG,{listing:oe,onClick:()=>s(`/mission-control/listings/${oe.id}`)},oe.id))})]}),e.jsx(is,{value:"my-listings",className:"space-y-4",children:j?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,he)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},he))}):(v==null?void 0:v.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(gA,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Share your listings with the LevelUp community!"}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Your First Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v==null?void 0:v.map(oe=>e.jsx(gG,{listing:oe,showActions:!0,onClick:()=>s(`/mission-control/listings/${oe.id}`),onEdit:()=>s(`/mission-control/listings/${oe.id}/edit`),onDelete:()=>I(oe.id),onCreateMusicVideo:()=>{const he=(oe.photos??[]).slice().sort((ce,me)=>(me.is_primary?1:0)-(ce.is_primary?1:0)||(ce.sort_order??0)-(me.sort_order??0)).map(ce=>ce.photo_url).filter(Boolean);if(he.length===0){ae.error("Add photos to this listing first.");return}Fjt({photos:he,details:{address:oe.property_address||`${oe.city??""} ${oe.state??""}`.trim(),beds:oe.bedrooms?String(oe.bedrooms):"",baths:oe.bathrooms?String(oe.bathrooms):"",sqft:oe.square_footage?String(oe.square_footage):"",price:oe.price?String(oe.price):"",highlights:oe.description||""},sourceLabel:"My Listings",badge:zjt(oe.status,oe.price)}),s("/admin/beta/homereel?tab=music-video")}},oe.id))})}),e.jsx(is,{value:"saved",className:"space-y-4",children:_?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,he)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},he))}):(y==null?void 0:y.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(gi,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No saved listings"}),e.jsx("p",{className:"text-muted-foreground",children:"Save listings to quickly access them later"})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:y==null?void 0:y.map(oe=>e.jsx(gG,{listing:oe.listing,onClick:()=>s(`/mission-control/listings/${oe.listing.id}`)},oe.id))})}),e.jsx(is,{value:"referrals",className:"space-y-6",children:e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(Vl,{className:"h-4 w-4"}),"Referrals Sent (",((H=w==null?void 0:w.sent)==null?void 0:H.length)||0,")"]}),((Z=w==null?void 0:w.sent)==null?void 0:Z.length)===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center text-muted-foreground",children:"No referrals sent yet"})}):e.jsx("div",{className:"space-y-3",children:(Y=w==null?void 0:w.sent)==null?void 0:Y.map(oe=>{var he,ce;return e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:oe.buyer_name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:((he=oe.listing)==null?void 0:he.property_address)||((ce=oe.listing)==null?void 0:ce.city)})]}),e.jsx(Ue,{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(An,{className:"h-4 w-4"}),"Referrals Received (",((W=w==null?void 0:w.received)==null?void 0:W.length)||0,")"]}),((ee=w==null?void 0:w.received)==null?void 0:ee.length)===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center text-muted-foreground",children:"No referrals received yet"})}):e.jsx("div",{className:"space-y-3",children:(se=w==null?void 0:w.received)==null?void 0:se.map(oe=>{var he;return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:oe.buyer_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:["From: ",(he=oe.sender)==null?void 0:he.name]})]}),e.jsx(Ue,{variant:oe.status==="closed"?"default":"secondary",children:oe.status.replace("_"," ")})]}),e.jsx(B,{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(is,{value:"brokerage",className:"space-y-4",children:E?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[...Array(3)].map((oe,he)=>e.jsxs(fe,{children:[e.jsx(Ws,{className:"h-48 w-full"}),e.jsxs(Ee,{className:"p-4 space-y-2",children:[e.jsx(Ws,{className:"h-5 w-3/4"}),e.jsx(Ws,{className:"h-4 w-1/2"})]})]},he))}):(A==null?void 0:A.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(gA,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-medium mb-2",children:"No brokerage listings yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No agents in your brokerage have added listings yet."}),e.jsxs(B,{onClick:()=>s("/mission-control/listings/new"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add a Listing"]})]})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:A==null?void 0:A.map(oe=>e.jsx(gG,{listing:oe,onClick:()=>s(`/mission-control/listings/${oe.id}`)},oe.id))})}),e.jsx(is,{value:"map",children:e.jsx(VYs,{listings:p||[],isLoading:f})}),e.jsx(is,{value:"leaderboard",children:e.jsx(UYs,{leaderboard:O})})]})]}),e.jsx(FYs,{})]}):e.jsx(Cs,{title:"Listing Exchange",description:"Community-powered listing collaboration",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Or,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Coming Soon"}),e.jsx("p",{className:"text-muted-foreground",children:"Listing Exchange is currently in development. Check back soon!"})]})})})}function Bjt(s){return dt({queryKey:["listing-documents",s],queryFn:async()=>{const{data:t,error:n}=await q.from("listing_documents").select("*").eq("listing_id",s).order("sort_order",{ascending:!0}).order("created_at",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function GYs(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async({listingId:n,file:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s.id}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await q.storage.from("listing-documents").upload(i,r,{contentType:r.type||void 0});if(l)throw l;const{data:o,error:c}=await q.from("listing_documents").insert({listing_id:n,owner_user_id:s.id,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["listing-documents",r.listingId]})}})}function WYs(){const s=Kt();return yt({mutationFn:async({id:t,storage_path:n,listingId:r})=>{await q.storage.from("listing-documents").remove([n]);const{error:a}=await q.from("listing_documents").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}function KYs(){const s=Kt();return yt({mutationFn:async({id:t,visible:n,listingId:r})=>{const{error:a}=await q.from("listing_documents").update({visible_on_exchange:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["listing-documents",t]})}})}async function $jt(s){const{data:t,error:n}=await q.storage.from("listing-documents").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const YYs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function ZYs({listingId:s,ownerOnly:t=!1}){const{data:n=[]}=Bjt(s),r=t?n:n.filter(i=>i.visible_on_exchange);if(r.length===0)return null;const a=async i=>{try{const l=await $jt(i);window.open(l,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:[e.jsx(br,{className:"h-5 w-5"}),"Documents & Disclosures (",r.length,")"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-2",children:r.map(i=>e.jsxs("button",{onClick:()=>a(i.storage_path),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted transition-colors text-left group",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10 flex-shrink-0",children:e.jsx(br,{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:YYs(i.file_size)})]}),e.jsx(Ia,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary"})]},i.id))})})]})}const QYs=s=>{if(!s)return"";const t=s.replace(/\D/g,""),n=t.length===11&&t.startsWith("1")?t.slice(1):t;return n.length!==10?s:`${n.slice(0,3)}-${n.slice(3,6)}-${n.slice(6)}`},EQe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),c3="#D4AF37",AQe="#0F172A",MQe=async s=>new Promise((t,n)=>{const r=new Image;r.crossOrigin="anonymous",r.referrerPolicy="no-referrer",r.onload=()=>t(r),r.onerror=n,r.src=s}),IQe=(s,t,n,r,a,i)=>{const l=Math.max(a/t.naturalWidth,i/t.naturalHeight),o=a/l,c=i/l,d=(t.naturalWidth-o)/2,u=(t.naturalHeight-c)/2;s.drawImage(t,d,u,o,c,n,r,a,i)},y7=(s,t,n)=>{if(s.measureText(t).width<=n)return t;let r=t;for(;r.length>3&&s.measureText(`${r}…`).width>n;)r=r.slice(0,-1);return`${r.trim()}…`},XYs=(s,t,n,r)=>{const a=t.split(/\s+/).filter(Boolean),i=[];let l="";for(const o of a){const c=l?`${l} ${o}`:o;if(s.measureText(c).width<=n||!l)l=c;else if(i.push(l),l=o,i.length===r)break}return l&&i.length{let i=n;for(const l of t)s.fillText(l,i,r),i+=s.measureText(l).width+a},eZs=s=>s instanceof DOMException||s instanceof Error?s.name:null;function Ujt({listingId:s,open:t,onOpenChange:n}){var E,O;const{data:r}=e6e(s||""),[a,i]=N.useState(null),[l,o]=N.useState(!1),[c,d]=N.useState(null),[u,h]=N.useState(null),p=((r==null?void 0:r.photos)||[]).slice().sort((D,I)=>D.is_primary&&!I.is_primary?-1:!D.is_primary&&I.is_primary?1:(D.sort_order??0)-(I.sort_order??0));N.useEffect(()=>{var I;if(!t)return;const D=((I=p[0])==null?void 0:I.photo_url)||null;h(F=>F||D)},[t,r==null?void 0:r.id,p.length]),N.useEffect(()=>{let D=!1;if(!(!t||!(r!=null&&r.agent_id)))return(async()=>{var H,Z,Y,W;const{data:I}=await q.from("profiles").select("name, phone, phone_e164, avatar_url, brokerage:brokerages!profiles_brokerage_id_fkey(name)").eq("id",r.agent_id).maybeSingle();if(D)return;const F=I,z=((H=F==null?void 0:F.brokerage)==null?void 0:H.name)||((Y=(Z=r.agent)==null?void 0:Z.brokerage)==null?void 0:Y.name)||null;i({name:(F==null?void 0:F.name)||((W=r.agent)==null?void 0:W.name)||"Agent",phone:(F==null?void 0:F.phone)||(F==null?void 0:F.phone_e164)||null,avatar_url:(F==null?void 0:F.avatar_url)||null,brokerage:z})})(),()=>{D=!0}},[t,r==null?void 0:r.agent_id]),N.useEffect(()=>{if(!t){d(null),h(null);return}if(!r||!a)return;const D=setTimeout(()=>{f()},350);return()=>clearTimeout(D)},[t,r==null?void 0:r.id,a==null?void 0:a.name,u]);const f=async()=>{if(!(!r||!a)){o(!0);try{const D=document.createElement("canvas");D.width=1080,D.height=1080;const I=D.getContext("2d");if(!I)throw new Error("Canvas unavailable");if(I.fillStyle=AQe,I.fillRect(0,0,1080,1080),w){const W=await MQe(w);IQe(I,W,0,0,1080,1080)}const F=I.createLinearGradient(0,0,0,1080);F.addColorStop(0,"rgba(15,23,42,0.58)"),F.addColorStop(.34,"rgba(15,23,42,0.16)"),F.addColorStop(.62,"rgba(15,23,42,0.48)"),F.addColorStop(1,"rgba(15,23,42,0.98)"),I.fillStyle=F,I.fillRect(0,0,1080,1080),I.fillStyle=c3,I.fillRect(56,62,72,2),I.font="600 22px Arial, sans-serif",JYs(I,"JUST LISTED",146,72,8),I.save(),I.shadowColor="rgba(0,0,0,0.55)",I.shadowBlur=24,I.shadowOffsetY=4,I.fillStyle="#F8FAFC",I.font="600 64px Georgia, serif",I.textBaseline="top";const z=XYs(I,r.property_address||`${r.city||""}, ${r.state||""}`.trim(),952,2);let H=z.length>1?590:654;z.forEach(W=>{I.fillText(W,64,H),H+=70}),I.restore();const Z=[r.city,r.state].filter(Boolean).join(", ")+(r.neighborhood?` · ${r.neighborhood}`:"");I.fillStyle="rgba(248,250,252,0.9)",I.font="600 26px Arial, sans-serif",I.fillText(y7(I,Z.toUpperCase(),952),64,H+8),I.fillStyle=c3,I.font="700 56px Arial, sans-serif",I.fillText(EQe(r.price),64,H+58),A.length>0&&(I.fillStyle="rgba(248,250,252,0.86)",I.font="600 22px Arial, sans-serif",I.fillText(y7(I,A.join(" · "),430),360,H+78));const Y=I.createLinearGradient(0,880,0,1080);if(Y.addColorStop(0,"rgba(15,23,42,0.96)"),Y.addColorStop(1,"#0B1322"),I.fillStyle=Y,I.fillRect(0,880,1080,200),I.fillStyle=c3,I.fillRect(0,880,1080,2),I.save(),I.beginPath(),I.arc(124,980,60,0,Math.PI*2),I.closePath(),I.fillStyle="#1E293B",I.fill(),I.lineWidth=6,I.strokeStyle=c3,I.stroke(),I.clip(),a.avatar_url)try{const W=await MQe(a.avatar_url);IQe(I,W,64,920,120,120)}catch{I.fillStyle=c3,I.font="700 48px Arial, sans-serif",I.textAlign="center",I.textBaseline="middle",I.fillText(a.name.charAt(0).toUpperCase(),124,982)}else I.fillStyle=c3,I.font="700 48px Arial, sans-serif",I.textAlign="center",I.textBaseline="middle",I.fillText(a.name.charAt(0).toUpperCase(),124,982);I.restore(),I.textAlign="left",I.textBaseline="alphabetic",I.fillStyle="#F8FAFC",I.font="600 38px Georgia, serif",I.fillText(y7(I,a.name,S?430:820),212,970),a.brokerage&&(I.fillStyle=c3,I.font="600 20px Arial, sans-serif",I.fillText(y7(I,a.brokerage.toUpperCase(),S?430:820),212,1008)),S&&(I.textAlign="right",I.fillStyle="rgba(212,175,55,0.86)",I.font="600 16px Arial, sans-serif",I.fillText("CALL · TEXT",1016,958),I.fillStyle="#F8FAFC",I.font="600 38px Arial, sans-serif",I.fillText(S,1016,1008)),d(D.toDataURL("image/png"))}catch(D){console.error("Generate graphic error",D),ae.error("Could not generate graphic")}finally{o(!1)}}},y=async D=>(await fetch(D)).blob(),_=async()=>{if(!c)return;const D=document.createElement("a");D.href=c,D.download=`just-listed-${(r==null?void 0:r.slug)||(r==null?void 0:r.id)||"graphic"}.png`,D.click(),ae.success("Downloaded!")},v=async()=>{if(c)try{const D=await y(c);await navigator.clipboard.write([new ClipboardItem({"image/png":D})]),ae.success("Copied to clipboard")}catch{ae.error("Copy not supported in this browser")}},j=async()=>{if(c)try{const D=await y(c),I=new File([D],"just-listed.png",{type:"image/png"});navigator.canShare&&navigator.canShare({files:[I]})?await navigator.share({files:[I],title:"Just Listed"}):_()}catch(D){eZs(D)!=="AbortError"&&ae.error("Share failed")}},w=u||((E=p[0])==null?void 0:E.photo_url)||null,S=QYs(a==null?void 0:a.phone),A=[r!=null&&r.bedrooms?`${r.bedrooms} BD`:null,r!=null&&r.bathrooms?`${r.bathrooms} BA`:null,r!=null&&r.square_footage?`${r.square_footage.toLocaleString()} SF`:null].filter(Boolean);return e.jsx(_s,{open:t,onOpenChange:n,children:e.jsx(bs,{className:"!max-w-[480px] !w-[calc(100vw-2rem)] !p-0 !gap-0 !block overflow-hidden",style:{maxHeight:"calc(100vh - 2rem)"},children:e.jsxs("div",{className:"flex flex-col",style:{maxHeight:"calc(100vh - 2rem)"},children:[e.jsxs(js,{className:"px-5 pt-5 pb-3 shrink-0",children:[e.jsxs(ws,{className:"flex items-center gap-2 pr-8",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500 shrink-0"}),e.jsx("span",{className:"truncate",children:"Your Just Listed Graphic"})]}),e.jsx(Jn,{className:"text-xs",children:"Square 1080×1080 — perfect for Instagram, Facebook, LinkedIn."})]}),e.jsxs("div",{className:"flex-1 min-h-0 overflow-y-auto px-5 pb-3",children:[e.jsxs("div",{className:"relative mx-auto flex items-center justify-center rounded-lg overflow-hidden",style:{width:"280px",maxWidth:"100%",height:"280px",background:AQe},children:[w&&e.jsx("img",{src:w,alt:"Selected property",className:"absolute inset-0 h-full w-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-b from-slate-950/65 via-slate-950/25 to-slate-950"}),e.jsxs("div",{className:"absolute left-4 right-4 top-4 flex items-center gap-2",children:[e.jsx("span",{className:"h-px w-6 bg-amber-400"}),e.jsx("span",{className:"text-[9px] font-semibold uppercase tracking-[0.28em] text-amber-300",children:"Just Listed"})]}),e.jsxs("div",{className:"absolute left-4 right-4 bottom-[64px] text-white",children:[e.jsx("div",{className:"line-clamp-2 font-serif text-[18px] font-semibold leading-[1.05] drop-shadow-lg",children:(r==null?void 0:r.property_address)||`${(r==null?void 0:r.city)||""}, ${(r==null?void 0:r.state)||""}`}),e.jsxs("div",{className:"mt-1 truncate text-[9px] font-semibold uppercase tracking-[0.18em] text-white/85",children:[[r==null?void 0:r.city,r==null?void 0:r.state].filter(Boolean).join(", "),r!=null&&r.neighborhood?` · ${r.neighborhood}`:""]}),e.jsxs("div",{className:"mt-1.5 flex items-center gap-2",children:[e.jsx("span",{className:"text-[16px] font-bold text-amber-300",children:r?EQe(r.price):""}),A.length>0&&e.jsx("span",{className:"truncate text-[8px] font-semibold uppercase tracking-[0.14em] text-white/80",children:A.join(" · ")})]})]}),e.jsxs("div",{className:"absolute inset-x-0 bottom-0 flex h-[52px] items-center border-t border-amber-400 bg-slate-950/95 px-4",children:[e.jsx("div",{className:"flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-amber-400 bg-slate-800 text-xs font-bold text-amber-300",children:a!=null&&a.avatar_url?e.jsx("img",{src:a.avatar_url,alt:"",className:"h-full w-full object-cover"}):(O=a==null?void 0:a.name)==null?void 0:O.charAt(0).toUpperCase()}),e.jsxs("div",{className:"ml-2 min-w-0 flex-1",children:[e.jsx("div",{className:"truncate font-serif text-xs font-semibold text-white",children:a==null?void 0:a.name}),(a==null?void 0:a.brokerage)&&e.jsx("div",{className:"truncate text-[7px] font-semibold uppercase tracking-[0.18em] text-amber-300",children:a.brokerage})]}),S&&e.jsx("div",{className:"ml-2 shrink-0 text-[9px] font-semibold text-white",children:S})]}),l&&e.jsxs("div",{className:"absolute inset-0 flex flex-col items-center justify-center gap-2 bg-slate-950/80 text-white/85",children:[e.jsx(rs,{className:"h-7 w-7 animate-spin"}),e.jsx("p",{className:"text-xs",children:"Crafting your graphic…"})]})]}),p.length>1&&e.jsxs("div",{className:"mt-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"Choose photo"}),e.jsx("div",{className:"flex gap-2 pb-2",style:{overflowX:"auto",overflowY:"hidden",WebkitOverflowScrolling:"touch"},children:p.map(D=>{const I=u===D.photo_url;return e.jsx("button",{type:"button",onClick:()=>h(D.photo_url),className:`relative shrink-0 h-14 w-14 rounded-md overflow-hidden border-2 transition ${I?"border-amber-500 ring-2 ring-amber-500/30":"border-transparent hover:border-muted-foreground/40"}`,children:e.jsx("img",{src:D.photo_url,alt:"",className:"w-full h-full object-cover"})},D.id)})})]})]}),e.jsxs("div",{className:"px-5 pb-5 pt-2 shrink-0 border-t bg-background flex flex-wrap justify-end gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>void f(),disabled:l||!r||!a,children:"Regenerate"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:v,disabled:!c,className:"gap-1.5",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"})," Copy"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:j,disabled:!c,className:"gap-1.5",children:[e.jsx(Vl,{className:"h-3.5 w-3.5"})," Share"]}),e.jsxs(B,{size:"sm",onClick:_,disabled:!c,className:"gap-1.5",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Download"]})]})]})})})}function tZs(s){return new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s)}const sZs={single_family:"Single Family Home",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury Home",commercial:"Commercial",other:"Property"};function nZs({open:s,onOpenChange:t,listing:n}){const{user:r}=vs(),{data:a=[],isLoading:i}=ax(),{data:l=[]}=ky(),[o,c]=N.useState(""),[d,u]=N.useState("all"),[h,p]=N.useState(new Set),[f,y]=N.useState(!1),[_,v]=N.useState(null);N.useEffect(()=>{s||(c(""),u("all"),p(new Set),y(!1))},[s]),N.useEffect(()=>{!s||!r||(async()=>{const{data:I}=await q.from("gmail_integrations").select("gmail_email").eq("user_id",r.id).maybeSingle();v((I==null?void 0:I.gmail_email)||null)})()},[s,r]);const j=N.useMemo(()=>a.filter(I=>I.email),[a]),w=N.useMemo(()=>{let I=j;if(d!=="all"&&(I=I.filter(F=>{var z;return(z=F.tags)==null?void 0:z.some(H=>H.relationship_type_id===d)})),o.trim()){const F=o.toLowerCase();I=I.filter(z=>`${z.first_name||""} ${z.last_name||""}`.toLowerCase().includes(F)||(z.email||"").toLowerCase().includes(F))}return I},[j,o,d]),S=()=>{h.size===w.length?p(new Set):p(new Set(w.map(I=>I.id)))},A=I=>{const F=new Set(h);F.has(I)?F.delete(I):F.add(I),p(F)},E=N.useMemo(()=>j.filter(I=>h.has(I.id)).map(I=>({id:I.id,first_name:I.first_name||"there",last_name:I.last_name,email:I.email})),[j,h]),{defaultSubject:O,defaultBody:D}=N.useMemo(()=>{var le,ve,ge,Te;const I=n.property_address||`${n.city}, ${n.state}`,F=tZs(n.price),z=sZs[n.property_type]||"home",H=n.bedrooms?`${n.bedrooms} bed`:"",Z=n.bathrooms?`${n.bathrooms} bath`:"",Y=n.square_footage?`${n.square_footage.toLocaleString()} sqft`:"",W=[H,Z,Y].filter(Boolean).join(" • "),ee=`https://listings.relevelup.com/${n.slug||n.id}`,se=((ve=(le=n.photos)==null?void 0:le.find(Ie=>Ie.is_primary))==null?void 0:ve.photo_url)||((Te=(ge=n.photos)==null?void 0:ge[0])==null?void 0:Te.photo_url)||"",he={active:"Just Listed",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"}[n.status]||"New Listing",ce=`${he}: ${I} — ${F}`,me=`

Hi {{first_name}},

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

${se?` ${I} `:""}
${he}

${F}

${I}

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

${W?`

${W} • ${z}

`:""} View Photos & Details →

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

Talk soon,

`;return{defaultSubject:ce,defaultBody:me}},[n]);return f?e.jsx(Xv,{open:f,onOpenChange:I=>{y(I),I||t(!1)},bulkContacts:E,defaultSubject:O,defaultBody:D,gmailEmail:_}):e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[640px] max-h-[90vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-amber-500"}),"Email this listing to your sphere"]}),e.jsx(Jn,{children:"Pick which contacts should hear about this property. We'll personalize each email with their name."})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search contacts...",value:o,onChange:I=>c(I.target.value),className:"pl-9"})]}),e.jsxs(us,{value:d,onValueChange:u,children:[e.jsx(ls,{className:"sm:w-[180px]",children:e.jsx(hs,{placeholder:"Filter by tag"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All contacts"}),l.map(I=>e.jsx(Ze,{value:I.id,children:I.name},I.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-sm border-y py-2",children:[e.jsxs("button",{type:"button",onClick:S,className:"flex items-center gap-2 text-primary hover:underline",children:[e.jsx(hi,{checked:w.length>0&&h.size===w.length,className:"pointer-events-none"}),e.jsx("span",{children:h.size===w.length&&w.length>0?"Deselect all":`Select all (${w.length})`})]}),e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(An,{className:"h-3 w-3"}),h.size," selected"]})]}),e.jsx(di,{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(rs,{className:"h-5 w-5 animate-spin mr-2"}),"Loading your contacts..."]}):w.length===0?e.jsx("div",{className:"text-center py-12 text-muted-foreground text-sm",children:j.length===0?"No contacts with email addresses yet.":"No contacts match your search."}):e.jsx("div",{className:"space-y-1 py-2",children:w.map(I=>e.jsxs("label",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50 cursor-pointer",children:[e.jsx(hi,{checked:h.has(I.id),onCheckedChange:()=>A(I.id)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[I.first_name," ",I.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:I.email})]}),I.tags&&I.tags.length>0&&e.jsx("div",{className:"flex gap-1 flex-wrap justify-end max-w-[40%]",children:I.tags.slice(0,2).map(F=>{var z;return e.jsx(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:(z=F.relationship_type)==null?void 0:z.name},F.id)})})]},I.id))})}),e.jsx(al,{}),e.jsxs("div",{className:"flex justify-between items-center gap-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:_?`Sending from ${_}`:"Connect Gmail in Settings to send"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>y(!0),disabled:h.size===0,className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"}),"Compose Email (",h.size,")"]})]})]})]})})}function Sv(s){const t=s.expected_commission;if(!t)return null;if((s.commission_calc_method||"standard")==="referral_first"){let a=t;s.referral_fee_pct&&(a-=t*(s.referral_fee_pct/100));let i=a;return s.brokerage_split_pct&&(i-=a*(s.brokerage_split_pct/100)),s.team_split_pct&&(i-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(i-=t*(s.franchise_fee_pct/100)),s.transaction_fee&&(i-=s.transaction_fee),Math.max(0,i)}let r=t;return s.brokerage_split_pct&&(r-=t*(s.brokerage_split_pct/100)),s.team_split_pct&&(r-=t*(s.team_split_pct/100)),s.franchise_fee_pct&&(r-=t*(s.franchise_fee_pct/100)),s.referral_fee_pct&&(r-=t*(s.referral_fee_pct/100)),s.transaction_fee&&(r-=s.transaction_fee),Math.max(0,r)}function $1e(){const s=wa();return dt({queryKey:["deal-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function qjt(){const s=wa(),t=Kt();return yt({mutationFn:async()=>{if(!s)throw new Error("Not authenticated");const{error:n}=await q.rpc("initialize_deal_pipeline_stages",{p_user_id:s});if(n)throw n},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-stages"]})}})}function U1e(){const s=wa();return dt({queryKey:["deal-pipeline-deals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at) `).eq("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Vjt(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_pipeline").insert({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||null,contact_id:n.contact_id||null,listing_id:n.listing_id||null,property_address:n.property_address||null,city:n.city||null,state:n.state||null,zip_code:n.zip_code||null,expected_price:n.expected_price||null,expected_commission:n.expected_commission||null,commission_percentage:n.commission_percentage||3,target_close_date:n.target_close_date||null,contract_date:n.contract_date||null,listing_date:n.listing_date||null,priority:n.priority||"medium",probability:n.probability||50,notes:n.notes||null,owner_user_id:s}).select().single();if(a)throw a;return await q.from("deal_activities").insert([{deal_id:r.id,activity_type:"system",title:"Deal created",description:`Deal "${n.deal_name}" was created`}]),r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-pipeline-deals"]}),t.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function Hjt(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function rZs(){const s=Kt();return yt({mutationFn:async({dealId:t,stageId:n,stageName:r})=>{const{data:a,error:i}=await q.from("deal_pipeline").update({stage_id:n}).eq("id",t).select().single();if(i)throw i;return await q.from("deal_activities").insert({deal_id:t,activity_type:"stage_change",title:`Moved to ${r}`,metadata:{new_stage_id:n,new_stage_name:r}}),a},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-activities"]})}})}function aZs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("deal_pipeline").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-pipeline-stats"]})}})}function iZs(s){return dt({queryKey:["deal-activities",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_activities").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function oZs(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_activities").insert([{deal_id:t.deal_id,activity_type:t.activity_type,title:t.title,description:t.description||null}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-activities",n.deal_id]})}})}function lZs(s){return dt({queryKey:["deal-checklist",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_checklist_items").select("*").eq("deal_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function cZs(){const s=Kt();return yt({mutationFn:async({id:t,is_completed:n,deal_id:r})=>{const{data:a,error:i}=await q.from("deal_checklist_items").update({is_completed:n,completed_at:n?new Date().toISOString():null}).eq("id",t).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function dZs(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("deal_checklist_items").insert([{deal_id:t.deal_id,title:t.title,description:t.description||null,due_date:t.due_date||null,sort_order:t.sort_order||0}]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-checklist",n.deal_id]})}})}function uZs(){const s=wa();return dt({queryKey:["deal-pipeline-stats",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("deal_pipeline").select("*, deal_pipeline_stages(name, is_won_stage, is_lost_stage)").eq("owner_user_id",s);if(n)throw n;const r=(t==null?void 0:t.filter(o=>{var c,d,u;return!((c=o.deal_pipeline_stages)!=null&&c.is_won_stage)&&!((d=o.deal_pipeline_stages)!=null&&d.is_lost_stage)&&((u=o.deal_pipeline_stages)==null?void 0:u.name)!=="Cancelled"}))||[],a=(t==null?void 0:t.filter(o=>{var c;return(c=o.deal_pipeline_stages)==null?void 0:c.is_won_stage}))||[],i=new Date().getFullYear(),l=a.filter(o=>{const c=o.actual_close_date;return c?new Date(c).getFullYear()===i:!0});return{totalDeals:(t==null?void 0:t.length)||0,activeDeals:r.length,wonDeals:a.length,pipelineValue:r.reduce((o,c)=>o+(c.expected_price||0),0),expectedCommission:r.reduce((o,c)=>o+(c.expected_commission||0),0),expectedNetToAgent:r.reduce((o,c)=>o+(Sv(c)||0),0),wonValue:a.reduce((o,c)=>o+(c.expected_price||0),0),weightedGCI:r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(c.expected_commission||0)*d},0),weightedNet:r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Sv(c)||0)*d},0),ytdWonDeals:l.length,ytdWonGCI:l.reduce((o,c)=>o+(c.expected_commission||0),0),ytdWonNet:l.reduce((o,c)=>o+(Sv(c)||0),0),projectedAnnualNet:l.reduce((o,c)=>o+(Sv(c)||0),0)+r.reduce((o,c)=>{const d=(c.probability??50)/100;return o+(Sv(c)||0)*d},0)}},enabled:!!s})}function hZs(s){const t=wa();return dt({queryKey:["deal-by-listing",s,t],queryFn:async()=>{if(!t||!s)return null;const{data:n,error:r}=await q.from("deal_pipeline").select(` *, deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("listing_id",s).maybeSingle();if(r)throw r;return n},enabled:!!t&&!!s})}function mZs(){const s=Kt();return yt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:n}).eq("id",t).select().single();if(a)throw a;return await q.from("deal_activities").insert({deal_id:t,activity_type:"system",title:"Linked to Listing Exchange",description:"This deal is now synced with Listing Exchange",metadata:{listing_id:n}}),r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",n.listingId]})}})}function pZs(){const s=Kt();return yt({mutationFn:async({dealId:t,listingId:n})=>{const{data:r,error:a}=await q.from("deal_pipeline").update({listing_id:null}).eq("id",t).select().single();if(a)throw a;return{data:r,listingId:n}},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-pipeline-deals"]}),s.invalidateQueries({queryKey:["deal-by-listing",t.listingId]})}})}function fZs({listing:s}){const t=Ln(),[n,r]=N.useState(""),[a,i]=N.useState(!1),{data:l,isLoading:o}=hZs(s.id),{data:c,isLoading:d}=$1e(),{data:u,isLoading:h}=U1e(),p=qjt(),f=mZs(),y=pZs(),_=Vjt(),v=(u==null?void 0:u.filter(E=>!E.listing_id))||[],j=E=>{if(!(c!=null&&c.length))return null;switch(E){case"coming_soon":case"active":case"price_improvement":return c.find(O=>O.name==="Active");case"under_contract":return c.find(O=>O.name==="Under Contract");case"sold":return c.find(O=>O.is_won_stage);default:return c.find(O=>O.name==="Active")}},w=async()=>{i(!0);try{c!=null&&c.length||await p.mutateAsync();const E=j(s.status);await _.mutateAsync({deal_name:s.property_address?`${s.property_address}, ${s.city}`:`${s.city}, ${s.state}`,deal_type:"seller",stage_id:(E==null?void 0:E.id)||null,listing_id:s.id,property_address:s.property_address,city:s.city,state:s.state,expected_price:s.price,expected_commission:s.price*.03,commission_percentage:3,priority:"medium",probability:50}),ae.success("Deal created and linked to listing!")}catch(E){console.error("Failed to create deal:",E),ae.error("Failed to create deal")}finally{i(!1)}},S=async()=>{if(!n){ae.error("Please select a deal");return}try{await f.mutateAsync({dealId:n,listingId:s.id}),ae.success("Listing linked to deal!"),r("")}catch{ae.error("Failed to link listing")}},A=async()=>{if(l)try{await y.mutateAsync({dealId:l.id,listingId:s.id}),ae.success("Listing unlinked from deal")}catch{ae.error("Failed to unlink listing")}};return o||d?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2 text-base",children:[e.jsx(G2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})})})]}):l?e.jsxs(fe,{className:"border-primary/20 bg-primary/5",children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"flex items-center gap-2 text-base",children:[e.jsx(Tl,{className:"h-4 w-4 text-primary"}),"Linked to Pipeline"]})}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:l.deal_name}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:l.deal_pipeline_stages&&e.jsx(Ue,{variant:"secondary",className:"text-xs",style:{backgroundColor:`${l.deal_pipeline_stages.color}20`,color:l.deal_pipeline_stages.color},children:l.deal_pipeline_stages.name})})]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes sync automatically between the listing and pipeline."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1",onClick:()=>t("/mission-control/pipeline"),children:["View Pipeline",e.jsx(Oa,{className:"h-3 w-3 ml-1"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:A,disabled:y.isPending,children:y.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(OA,{className:"h-4 w-4"})})]})]})]}):e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsxs(Rt,{className:"flex items-center gap-2 text-base",children:[e.jsx(G2,{className:"h-4 w-4"}),"Deal Pipeline"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link this listing to your pipeline to track the deal and sync status changes."}),e.jsxs(B,{onClick:w,disabled:a||_.isPending,className:"w-full",size:"sm",children:[a||_.isPending?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create New Deal"]}),v.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"absolute inset-0 flex items-center",children:e.jsx("span",{className:"w-full border-t"})}),e.jsx("div",{className:"relative flex justify-center text-xs uppercase",children:e.jsx("span",{className:"bg-card px-2 text-muted-foreground",children:"or"})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"flex-1 text-sm",children:e.jsx(hs,{placeholder:"Link to existing deal..."})}),e.jsx(cs,{children:v.map(E=>e.jsx(Ze,{value:E.id,children:E.deal_name},E.id))})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:S,disabled:!n||f.isPending,children:f.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Tl,{className:"h-4 w-4"})})]})]})]})]})}const xZs={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"},gZs={active:"Active",coming_soon:"Coming Soon",office_exclusive:"Office Exclusive",pre_market:"Pre-Market",price_improvement:"Price Improvement",under_contract:"Under Contract",sold:"Sold"},PQe={single_family:"Single Family",condo:"Condo",townhouse:"Townhouse",land:"Land",multi_family:"Multi-Family",luxury:"Luxury",commercial:"Commercial",other:"Other"};function yZs(){var oe,he,ce,me,le,ve,ge,Te,Ie;const{listingId:s}=bi(),t=Ln(),{user:n}=vs(),{data:r,isLoading:a}=e6e(s||""),{data:i}=Rmt(s||""),{data:l}=srs(s||""),o=Dmt(),c=trs(),d=nrs(),u=Lmt(),h=ars(),[p,f]=N.useState(!1),[y,_]=N.useState(!1),[v,j]=N.useState(!1),[w,S]=N.useState(!1),[A,E]=N.useState(!1),[O,D]=N.useState(null),[I,F]=N.useState({buyerName:"",buyerType:"",notes:""}),z=(n==null?void 0:n.id)===(r==null?void 0:r.agent_id),H=Ce=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ce),Z=async Ce=>{const Me=`https://listings.relevelup.com/${(r==null?void 0:r.slug)||(r==null?void 0:r.id)}`,Pe=`Check out this listing: ${(r==null?void 0:r.property_address)||(r==null?void 0:r.city)}`;d.mutate({listingId:r.id,shareType:Ce});try{switch(Ce){case"facebook":window.open(`https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(Me)}`,"_blank");break;case"copy":await navigator.clipboard.writeText(Me),ae.success("Link copied to clipboard!");break;case"text":window.open(`sms:?body=${encodeURIComponent(`${Pe} ${Me}`)}`);break;case"email":window.open(`mailto:?subject=${encodeURIComponent(Pe)}&body=${encodeURIComponent(`Check out this listing: ${Me}`)}`);break}}catch(Re){console.error("Share error:",Re),ae.error("Failed to share")}},Y=async()=>{try{await u.mutateAsync(r.id),ae.success("Listing deleted"),t("/mission-control/listings")}catch{ae.error("Failed to delete listing")}},W=async()=>{if(!I.buyerName.trim()){ae.error("Please enter buyer name");return}try{await h.mutateAsync({listingId:r.id,listingAgentId:r.agent_id,buyerName:I.buyerName,buyerType:I.buyerType||void 0,notes:I.notes||void 0}),ae.success("Referral sent successfully!"),_(!1),F({buyerName:"",buyerType:"",notes:""})}catch{ae.error("Failed to send referral")}},ee=Ce=>{var Je,ke;const Me=(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`,Pe=H((r==null?void 0:r.price)||0),Re=r!=null&&r.bedrooms?`${r.bedrooms}BD`:"",Ae=r!=null&&r.bathrooms?`${r.bathrooms}BA`:"",Be=r!=null&&r.square_footage?`${r.square_footage.toLocaleString()}SF`:"",we=[Re,Ae,Be].filter(Boolean).join(" | ");switch(Ce){case"just_listed":return`🏡 JUST LISTED! ${Me} ${Pe} ${we} ${(r==null?void 0:r.description)||"Schedule your showing today!"} #JustListed #RealEstate #HomeForSale #${(Je=r==null?void 0:r.city)==null?void 0:Je.replace(/\s/g,"")}`;case"price_improvement":return`📣 PRICE IMPROVEMENT! ${Me} Now ${Pe}! ${we} Don't miss this opportunity! #PriceReduced #RealEstate #HomeForSale`;case"teaser":return`Looking for a ${PQe[(r==null?void 0:r.property_type)||"single_family"].toLowerCase()} in ${r==null?void 0:r.city}? 👀 I've got just the one for you! ${we} DM me for details! 📩 #ComingSoon #RealEstate #${(ke=r==null?void 0:r.city)==null?void 0:ke.replace(/\s/g,"")}`;default:return""}};if(a)return e.jsx(Cs,{title:"Listing",description:"",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-10 w-32"}),e.jsx(Ws,{className:"h-[400px] w-full"}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsx(Ws,{className:"h-48"}),e.jsx(Ws,{className:"h-48"}),e.jsx(Ws,{className:"h-48"})]})]})});if(!r)return e.jsx(Cs,{title:"Listing Not Found",description:"",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"This listing could not be found."}),e.jsx(B,{onClick:()=>t("/mission-control/listings"),children:"Back to Listings"})]})})});const se=((oe=r.photos)==null?void 0:oe.find(Ce=>Ce.is_primary))||((he=r.photos)==null?void 0:he[0]);return e.jsxs(Cs,{title:"",description:"",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs(B,{variant:"ghost",onClick:()=>t("/mission-control/listings"),children:[e.jsx(qr,{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:()=>se&&D(se.photo_url),children:se?e.jsx("img",{src:se.photo_url,alt:"Primary",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center text-muted-foreground",children:"No photos"})})}),e.jsx("div",{className:"grid grid-cols-2 gap-2",children:(ce=r.photos)==null?void 0:ce.slice(1,5).map((Ce,Me)=>e.jsx("div",{className:"aspect-square rounded-lg overflow-hidden bg-muted cursor-pointer",onClick:()=>D(Ce.photo_url),children:e.jsx("img",{src:Ce.photo_url,alt:`Photo ${Me+2}`,className:"w-full h-full object-cover"})},Ce.id))})]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6",children:[e.jsxs("div",{className:"flex flex-wrap items-start justify-between gap-4 mb-6",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ue,{className:`${xZs[r.status]} text-white border-0`,children:gZs[r.status]}),r.is_featured&&e.jsxs(Ue,{variant:"outline",className:"border-amber-500 text-amber-500",children:[e.jsx(oa,{className:"h-3 w-3 mr-1 fill-amber-500"}),"Featured"]}),r.open_to_referrals&&e.jsxs(Ue,{variant:"outline",children:[e.jsx(An,{className:"h-3 w-3 mr-1"}),"Open to Referrals"]})]}),e.jsx("h1",{className:"text-3xl font-bold text-primary mb-2",children:H(r.price)}),r.property_address&&e.jsx("p",{className:"text-xl font-medium",children:r.property_address}),e.jsxs("p",{className:"text-muted-foreground flex items-center gap-1",children:[e.jsx(ka,{className:"h-4 w-4"}),r.city,", ",r.state,r.neighborhood&&` • ${r.neighborhood}`]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>o.mutate(r.id),children:e.jsx(gi,{className:`h-4 w-4 ${i?"fill-pink-500 text-pink-500":""}`})}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>c.mutate(r.id),children:l?e.jsx(cw,{className:"h-4 w-4"}):e.jsx(nm,{className:"h-4 w-4"})}),!z&&e.jsxs(B,{variant:"outline",className:"border-amber-500 text-amber-600 hover:bg-amber-50",onClick:()=>j(!0),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Share & Earn Leads"]}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"outline",children:[e.jsx(Vl,{className:"h-4 w-4 mr-2"}),"Share"]})}),e.jsxs(gc,{children:[e.jsxs(Kr,{onClick:()=>Z("copy"),children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Copy Link"]}),e.jsxs(Kr,{onClick:()=>Z("facebook"),children:[e.jsx(Mh,{className:"h-4 w-4 mr-2"}),"Facebook"]}),e.jsxs(Kr,{onClick:()=>Z("text"),children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Text"]}),e.jsxs(Kr,{onClick:()=>Z("email"),children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Email"]})]})]}),z&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",onClick:()=>{const Ce=(r.photos??[]).slice().sort((Me,Pe)=>(Pe.is_primary?1:0)-(Me.is_primary?1:0)||(Me.sort_order??0)-(Pe.sort_order??0)).map(Me=>Me.photo_url).filter(Boolean);if(Ce.length===0){ae.error("Add photos to this listing first.");return}Fjt({photos:Ce,details:{address:r.property_address||`${r.city??""} ${r.state??""}`.trim(),beds:r.bedrooms?String(r.bedrooms):"",baths:r.bathrooms?String(r.bathrooms):"",sqft:r.square_footage?String(r.square_footage):"",price:r.price?String(r.price):"",highlights:r.description||""},sourceLabel:"Listing Exchange",badge:zjt(r.status,r.price)}),t("/admin/beta/homereel?tab=music-video")},className:"gap-2 border-violet-500/60 text-violet-600 hover:bg-violet-50",children:[e.jsx(cL,{className:"h-4 w-4"}),"Create Music Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>E(!0),className:"gap-2 border-amber-500/60 text-amber-600 hover:bg-amber-50",children:[e.jsx(un,{className:"h-4 w-4"}),"Just Listed Graphic"]}),e.jsxs(B,{variant:"outline",onClick:()=>S(!0),className:"gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"}),"Email My Sphere"]}),e.jsxs(B,{onClick:()=>t(`/mission-control/listings/${r.id}/customize`),className:"gap-2 bg-gradient-to-r from-primary to-primary/80 hover:opacity-95 text-primary-foreground shadow-md",children:[e.jsx(un,{className:"h-4 w-4"}),"Customize Public Page"]}),e.jsxs(B,{variant:"outline",onClick:()=>t(`/mission-control/listings/${r.id}/edit`),children:[e.jsx(wu,{className:"h-4 w-4 mr-2"}),"Edit"]}),e.jsx(B,{variant:"destructive",size:"icon",onClick:()=>f(!0),children:e.jsx(_n,{className:"h-4 w-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-4 gap-4 py-4 border-y",children:[r.bedrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(J0,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.bedrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Beds"})]}),r.bathrooms&&e.jsxs("div",{className:"text-center",children:[e.jsx(kp,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.bathrooms}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Baths"})]}),r.square_footage&&e.jsxs("div",{className:"text-center",children:[e.jsx(ay,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.square_footage.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Sq Ft"})]}),r.year_built&&e.jsxs("div",{className:"text-center",children:[e.jsx(yr,{className:"h-5 w-5 mx-auto mb-1 text-muted-foreground"}),e.jsx("p",{className:"font-semibold",children:r.year_built}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Built"})]})]}),e.jsxs("div",{className:"pt-4 space-y-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Ue,{variant:"secondary",children:[e.jsx(Ua,{className:"h-3 w-3 mr-1"}),PQe[r.property_type]]}),r.lot_size&&e.jsxs(Ue,{variant:"secondary",children:["Lot: ",r.lot_size]}),r.has_hoa&&e.jsx(Ue,{variant:"secondary",children:"HOA"})]}),r.description&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Description"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.description})]}),r.agent_notes&&r.agent_notes_public&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-medium mb-2",children:"Agent Notes"}),e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:r.agent_notes})]}),r.mls_link&&e.jsx(B,{variant:"outline",asChild:!0,children:e.jsxs("a",{href:r.mls_link,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"View on MLS"]})})]}),e.jsxs("div",{className:"flex items-center gap-4 pt-4 mt-4 border-t text-sm text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Sr,{className:"h-4 w-4"}),r.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Vl,{className:"h-4 w-4"}),r.share_count," shares"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(gi,{className:"h-4 w-4"}),r.save_count," saves"]})]})]})}),r.allow_sharing&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Share Content"})}),e.jsx(Ee,{className:"space-y-4",children:["just_listed","price_improvement","teaser"].map(Ce=>e.jsxs("div",{className:"p-3 bg-muted rounded-lg",children:[e.jsxs("div",{className:"flex justify-between items-start mb-2",children:[e.jsxs("p",{className:"font-medium text-sm capitalize",children:[Ce.replace("_"," ")," Caption"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(ee(Ce)),ae.success("Caption copied!")},children:e.jsx(Zr,{className:"h-3 w-3"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground whitespace-pre-wrap",children:ee(Ce)})]},Ce))})]}),e.jsx(ZYs,{listingId:r.id,ownerOnly:z})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Listing Agent"})}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"w-12 h-12 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx("span",{className:"text-lg font-semibold text-primary",children:((le=(me=r.agent)==null?void 0:me.name)==null?void 0:le.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((ve=r.agent)==null?void 0:ve.name)||"Unknown"}),((Te=(ge=r.agent)==null?void 0:ge.brokerage)==null?void 0:Te.name)&&e.jsx("p",{className:"text-sm text-muted-foreground",children:r.agent.brokerage.name})]})]}),!z&&e.jsx("div",{className:"space-y-2",children:((Ie=r.agent)==null?void 0:Ie.email)&&e.jsx(B,{variant:"outline",className:"w-full",asChild:!0,children:e.jsxs("a",{href:`mailto:${r.agent.email}`,children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Email Agent"]})})})]})]}),z&&e.jsx(fZs,{listing:r}),!z&&r.open_to_referrals&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"Send a Buyer"]})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Have a buyer interested in this property? Send a referral to the listing agent."}),e.jsx(B,{className:"w-full",onClick:()=>_(!0),children:"Send Referral"})]})]})]})]})]}),e.jsx(_s,{open:!!O,onOpenChange:()=>D(null),children:e.jsx(bs,{className:"max-w-4xl",children:e.jsx("img",{src:O||"",alt:"Full size",className:"w-full h-auto"})})}),e.jsx(_s,{open:p,onOpenChange:f,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Delete Listing"}),e.jsx(Jn,{children:"Are you sure you want to delete this listing? This action cannot be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Y,disabled:u.isPending,children:u.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(_s,{open:y,onOpenChange:_,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Send Buyer Referral"}),e.jsx(Jn,{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(ne,{children:"Buyer Name *"}),e.jsx(ye,{value:I.buyerName,onChange:Ce=>F({...I,buyerName:Ce.target.value}),placeholder:"Enter buyer's name"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Buyer Type"}),e.jsxs(us,{value:I.buyerType,onValueChange:Ce=>F({...I,buyerType:Ce}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select type"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"first_time",children:"First-Time Buyer"}),e.jsx(Ze,{value:"investor",children:"Investor"}),e.jsx(Ze,{value:"relocating",children:"Relocating"}),e.jsx(Ze,{value:"upgrade",children:"Upgrading"}),e.jsx(Ze,{value:"downsize",children:"Downsizing"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Notes"}),e.jsx(Ms,{value:I.notes,onChange:Ce=>F({...I,notes:Ce.target.value}),placeholder:"Any additional information..."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>_(!1),children:"Cancel"}),e.jsx(B,{onClick:W,disabled:h.isPending,children:h.isPending?"Sending...":"Send Referral"})]})]})}),e.jsx(Djt,{open:v,onOpenChange:j,listingId:(r==null?void 0:r.id)||"",listingSlug:(r==null?void 0:r.slug)||null,listingTitle:(r==null?void 0:r.property_address)||`${r==null?void 0:r.city}, ${r==null?void 0:r.state}`}),r&&e.jsx(nZs,{open:w,onOpenChange:S,listing:r}),e.jsx(Ujt,{listingId:(r==null?void 0:r.id)||null,open:A,onOpenChange:E})]})}function vZs({onImport:s}){const[t,n]=N.useState(""),[r,a]=N.useState([]),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(null),h=N.useRef(),p=N.useRef(null);N.useEffect(()=>{const w=S=>{p.current&&!p.current.contains(S.target)&&c(!1)};return document.addEventListener("mousedown",w),()=>document.removeEventListener("mousedown",w)},[]);const f=async w=>{if(w.trim().length<3){a([]),c(!1);return}l(!0);try{const{data:S,error:A}=await q.functions.invoke("mls-listing-search",{body:{query:w}});if(A)throw A;a((S==null?void 0:S.listings)||[]),c(!0)}catch(S){console.error("MLS search error:",S),a([])}finally{l(!1)}},y=w=>{n(w),h.current&&clearTimeout(h.current),h.current=setTimeout(()=>f(w),400)},_=w=>{u(w.mlsNumber),s(w),c(!1),n(`${w.address}, ${w.city}`),ae.success(`Imported: ${w.address}`,{description:"Property details and photos have been auto-filled."}),u(null)},v=w=>w?`$${w.toLocaleString()}`:"",j=w=>{const S=(w||"").toLowerCase();return S.includes("single")||S.includes("detached")?"Single Family":S.includes("condo")?"Condo":S.includes("town")?"Townhouse":S.includes("land")||S.includes("lot")?"Land":S.includes("multi")?"Multi-Family":S.includes("commercial")?"Commercial":w||"Other"};return e.jsxs(fe,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(It,{className:"pb-3",children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ia,{className:"h-4 w-4 text-primary"}),"Import from MLS"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Search by address to auto-fill property details and photos from MLS"})]}),e.jsx(Ee,{children:e.jsxs("div",{ref:p,className:"relative",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:t,onChange:w=>y(w.target.value),onFocus:()=>r.length>0&&c(!0),placeholder:"Start typing a property address...",className:"pl-9 pr-9"}),i&&e.jsx(rs,{className:"absolute right-3 top-1/2 -translate-y-1/2 h-4 w-4 animate-spin text-muted-foreground"}),t&&!i&&e.jsx("button",{type:"button",onClick:()=>{n(""),a([]),c(!1)},className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx($n,{className:"h-4 w-4"})})]}),o&&e.jsx("div",{className:"absolute z-50 w-full mt-1 bg-popover border rounded-lg shadow-lg max-h-[400px] overflow-y-auto",children:r.length===0&&!i?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No properties found. Try a different address."}):r.map(w=>e.jsxs("button",{type:"button",onClick:()=>_(w),disabled:d===w.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:[w.photos[0]?e.jsx("img",{src:w.photos[0],alt:"",className:"w-16 h-12 rounded object-cover flex-shrink-0"}):e.jsx("div",{className:"w-16 h-12 rounded bg-muted flex items-center justify-center flex-shrink-0",children:e.jsx(ka,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:w.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[w.city,", ",w.state," ",w.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-semibold text-foreground",children:v(w.price)}),w.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(J0,{className:"h-3 w-3"})," ",w.bedrooms]}),w.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(kp,{className:"h-3 w-3"})," ",w.bathrooms]}),w.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Z2,{className:"h-3 w-3"})," ",w.sqft.toLocaleString()]})]})]}),e.jsxs("div",{className:"flex-shrink-0 flex flex-col items-end gap-1",children:[e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:j(w.propertyType)}),w.photos.length>0&&e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[w.photos.length," photos"]})]})]},w.mlsNumber))})]})})]})}function bZs({photo:s,onRemove:t,onSetPrimary:n}){const{attributes:r,listeners:a,setNodeRef:i,transform:l,transition:o,isDragging:c}=gve({id:s.id}),d={transform:E4.Transform.toString(l),transition:o};return e.jsxs("div",{ref:i,style:d,className:Mt("relative aspect-square rounded-lg overflow-hidden bg-muted group",c&&"opacity-50 ring-2 ring-primary z-50"),children:[e.jsx("img",{src:s.photo_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...r,...a,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Pu,{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($n,{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(oa,{className:"h-2.5 w-2.5 fill-current"})," Primary"]}):e.jsx("button",{type:"button",onClick:()=>n(s.id),className:"absolute bottom-1 left-1 text-[10px] bg-black/60 text-white px-1.5 py-0.5 rounded opacity-0 group-hover:opacity-100 transition-opacity hover:bg-black/80",children:"Set as Primary"})]})}function _Zs({photos:s,uploading:t,onUpload:n,onRemove:r,onReorder:a,onSetPrimary:i}){const l=lve(A8(QD,{activationConstraint:{distance:5}})),o=[...s].sort((d,u)=>(d.sort_order??0)-(u.sort_order??0)),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const p=o.findIndex(j=>j.id===u.id),f=o.findIndex(j=>j.id===h.id),y=[...o],[_]=y.splice(p,1);y.splice(f,0,_);const v=y.map((j,w)=>({...j,sort_order:w}));a(v)};return e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. Hover to set primary."}),e.jsx(pve,{sensors:l,collisionDetection:cve,onDragEnd:c,children:e.jsx(xve,{items:o.map(d=>d.id),strategy:_U,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[o.map(d=>e.jsx(bZs,{photo:d,onRemove:r,onSetPrimary:i},d.id)),e.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[t?e.jsx(rs,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-8 w-8"}),e.jsx("span",{className:"text-xs",children:"Upload"})]}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:d=>n(d.target.files),disabled:t})]})]})})})]})}function wZs({selectedVideoId:s,onVideoSelect:t,listingId:n}){const r=Ln(),{user:a}=vs(),[i,l]=N.useState(!1),[o,c]=N.useState([]),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,y]=N.useState({});N.useEffect(()=>{s&&a?_():p(null)},[s,a]);const _=async()=>{if(!s)return;const{data:F,error:z}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("id",s).eq("is_deleted",!1).single();!z&&F&&(p(F),v(F))},v=async F=>{try{const{data:z,error:H}=await q.functions.invoke("bunny-upload",{body:{action:"asset-urls",videoId:F.bunny_video_id,isAgentVideo:!0}});!H&&(z!=null&&z.thumbnailUrl)&&y(Z=>({...Z,[F.id]:{thumbnailUrl:z.thumbnailUrl}}))}catch(z){console.warn("Failed to get signed URL",z)}},j=async()=>{if(a){u(!0);try{const{data:F,error:z}=await q.from("agent_videos").select("id, bunny_video_id, title, thumbnail_url, preview_url, playback_url, duration_seconds, status, created_at").eq("owner_user_id",a.id).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(z)throw z;c(F||[]),F!=null&&F.length&&w(F)}catch(F){console.error("Error fetching videos:",F),ae.error("Failed to load videos")}finally{u(!1)}}},w=async F=>{var z;try{const H=F.map(se=>se.bunny_video_id),{data:Z,error:Y}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:H,isAgentVideo:!0}});if(Y)throw Y;const W=(Z==null?void 0:Z.assets)||{},ee={};for(const se of F)(z=W[se.bunny_video_id])!=null&&z.thumbnailUrl&&(ee[se.id]={thumbnailUrl:W[se.bunny_video_id].thumbnailUrl});y(se=>({...se,...ee}))}catch(H){console.warn("Failed to bulk-fetch signed URLs",H)}},S=()=>{l(!0),j()},A=F=>{t(F.id),p(F),l(!1),ae.success("Video selected")},E=()=>{t(null),p(null)},O=()=>{const F=n?`/mission-control/listings/${n}/edit`:"/mission-control/listings/new";r(`/mission-control/video?returnUrl=${encodeURIComponent(F)}`)},D=F=>{if(!F)return"0:00";const z=Math.floor(F/60),H=F%60;return`${z}:${H.toString().padStart(2,"0")}`},I=F=>{var z;return((z=f[F.id])==null?void 0:z.thumbnailUrl)||F.thumbnail_url};return e.jsxs("div",{className:"space-y-3",children:[h?e.jsx(fe,{className:"overflow-hidden",children:e.jsx(Ee,{className:"p-0",children:e.jsxs("div",{className:"flex items-start gap-4 p-4",children:[e.jsxs("div",{className:"relative w-32 h-20 bg-muted rounded-lg overflow-hidden flex-shrink-0",children:[I(h)?e.jsx("img",{src:I(h),alt:h.title||"Video thumbnail",className:"w-full h-full object-cover"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(fr,{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(El,{className:"h-6 w-6 text-white fill-white"})}),h.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:D(h.duration_seconds)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.title||"Untitled Video"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Property Video Tour"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:S,children:"Change"}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:E,className:"text-destructive hover:text-destructive",children:e.jsx($n,{className:"h-4 w-4"})})]})]})})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ee,{className:"p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx(fr,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Add a video walkthrough to showcase this property"}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2 justify-center",children:[e.jsxs(B,{type:"button",variant:"outline",onClick:S,className:"gap-2",children:[e.jsx(qg,{className:"h-4 w-4"}),"Select from Library"]}),e.jsxs(B,{type:"button",variant:"outline",onClick:O,className:"gap-2",children:[e.jsx(Jf,{className:"h-4 w-4"}),"Record New Video"]})]})]})})}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{className:"max-w-2xl max-h-[80vh] overflow-hidden flex flex-col",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(qg,{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(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):o.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(fr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"No videos in your library yet"}),e.jsxs(B,{onClick:O,className:"gap-2",children:[e.jsx(Jf,{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:[I(F)?e.jsx("img",{src:I(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(fr,{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(El,{className:"h-8 w-8 text-white opacity-0 group-hover:opacity-100 transition-opacity"})}),F.duration_seconds&&e.jsx("div",{className:"absolute bottom-1 right-1 bg-black/70 text-white text-[10px] px-1.5 py-0.5 rounded",children:D(F.duration_seconds)})]}),e.jsx("div",{className:"p-2 bg-card",children:e.jsx("p",{className:"text-xs font-medium truncate",children:F.title||"Untitled Video"})})]},F.id))})}),e.jsxs("div",{className:"flex justify-between items-center pt-4 border-t",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:O,className:"gap-2",children:[e.jsx(Jf,{className:"h-4 w-4"}),"Record New Video"]}),e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"})]})]})})]})}const jZs=s=>s<1024?`${s} B`:s<1024*1024?`${(s/1024).toFixed(0)} KB`:`${(s/(1024*1024)).toFixed(1)} MB`;function NZs({listingId:s}){const t=N.useRef(null),{data:n=[],isLoading:r}=Bjt(s),a=GYs(),i=WYs(),l=KYs(),o=async d=>{if(!(!d||d.length===0)){for(const u of Array.from(d)){if(u.size>25*1024*1024){ae.error(`${u.name} exceeds 25MB limit`);continue}try{await a.mutateAsync({listingId:s,file:u})}catch(h){ae.error(`Failed to upload ${u.name}: ${h.message}`)}}t.current&&(t.current.value=""),ae.success("Documents uploaded")}},c=async d=>{try{const u=await $jt(d);window.open(u,"_blank")}catch{ae.error("Failed to open document")}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("input",{ref:t,type:"file",multiple:!0,accept:".pdf,application/pdf",className:"hidden",onChange:d=>o(d.target.files)}),e.jsxs(B,{type:"button",variant:"outline",onClick:()=>{var d;return(d=t.current)==null?void 0:d.click()},disabled:a.isPending,className:"w-full",children:[a.isPending?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Upload PDFs (disclosures, etc.)"]}),r?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."}):n.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No documents yet. Upload PDFs that other agents can download from your listing."}):e.jsx("div",{className:"space-y-2",children:n.map(d=>e.jsxs(fe,{className:"p-3 flex items-center gap-3",children:[e.jsx("div",{className:"p-2 rounded-md bg-primary/10",children:e.jsx(br,{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:jZs(d.file_size)})]}),e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[d.visible_on_exchange?e.jsx(Sr,{className:"h-3 w-3"}):e.jsx(mf,{className:"h-3 w-3"}),e.jsx("span",{className:"hidden sm:inline",children:d.visible_on_exchange?"Visible":"Hidden"}),e.jsx(jn,{checked:d.visible_on_exchange,onCheckedChange:u=>l.mutate({id:d.id,visible:u,listingId:s}),className:"ml-1"})]}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>c(d.storage_path),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(B,{type:"button",variant:"ghost",size:"icon",onClick:()=>{confirm(`Delete ${d.file_name}?`)&&i.mutate({id:d.id,storage_path:d.storage_path,listingId:s})},children:e.jsx($n,{className:"h-4 w-4 text-destructive"})})]},d.id))})]})}const kZs=[{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"}],SZs=[{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 CZs({id:s,url:t,index:n,onRemove:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=gve({id:s}),u={transform:E4.Transform.toString(o),transition:c};return e.jsxs("div",{ref:l,style:u,className:`relative aspect-square rounded-lg overflow-hidden bg-muted group ${d?"opacity-50 ring-2 ring-primary z-50":""}`,children:[e.jsx("img",{src:t,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{type:"button",...a,...i,className:"absolute top-1 left-1 p-1 bg-black/60 text-white rounded cursor-grab active:cursor-grabbing opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx(Pu,{className:"h-3.5 w-3.5"})}),e.jsx("button",{type:"button",onClick:()=>r(n),className:"absolute top-1 right-1 p-1 bg-destructive text-destructive-foreground rounded-full hover:bg-destructive/90 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx($n,{className:"h-3 w-3"})}),n===0&&e.jsxs("span",{className:"absolute bottom-1 left-1 text-[10px] bg-primary text-primary-foreground px-1.5 py-0.5 rounded flex items-center gap-0.5",children:[e.jsx(oa,{className:"h-2.5 w-2.5 fill-current"})," Primary"]})]})}function TZs({photoUrls:s,pendingPhotos:t,onRemove:n,onReorder:r,uploading:a,onUpload:i}){const l=lve(A8(QD,{activationConstraint:{distance:5}})),o=s.map((d,u)=>`pending-${u}`),c=d=>{const{active:u,over:h}=d;if(!h||u.id===h.id)return;const p=o.indexOf(u.id),f=o.indexOf(h.id),y=[...s],_=[...t],[v]=y.splice(p,1),[j]=_.splice(p,1);y.splice(f,0,v),_.splice(f,0,j),r(y,_)};return e.jsxs("div",{className:"space-y-2",children:[s.length>1&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Drag photos to reorder. First photo will be primary."}),e.jsx(pve,{sensors:l,collisionDetection:cve,onDragEnd:c,children:e.jsx(xve,{items:o,strategy:_U,children:e.jsxs("div",{className:"grid grid-cols-3 sm:grid-cols-4 gap-4",children:[s.map((d,u)=>e.jsx(CZs,{id:o[u],url:d,index:u,onRemove:n},o[u])),e.jsxs("label",{className:"aspect-square rounded-lg border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 cursor-pointer flex flex-col items-center justify-center gap-2 text-muted-foreground",children:[a?e.jsx(rs,{className:"h-8 w-8 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{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 LQe(){const{listingId:s}=bi(),[t]=xl(),n=t.get("brokerage"),r=Ln(),{user:a}=vs(),{hasLeadSite:i}=Ap(),l=!!s&&s!=="new",o=!!n&&!l,[c,d]=N.useState([]),[u,h]=N.useState({open:!1,listingId:null,nextPath:"/mission-control/listings"}),{data:p,isLoading:f}=e6e(l?s:""),y=Wns(),_=Kns(),v=Yns(),j=Zns(),w=Qns(),S=Xns(),A=Jns(),{data:E=[]}=dt({queryKey:["brokerage-agents",n],queryFn:async()=>{if(!n)return[];const{data:ge,error:Te}=await q.from("profiles").select("id, name, email").eq("brokerage_id",n).order("name");if(Te)throw Te;return ge||[]},enabled:o}),[O,D]=N.useState(""),[I,F]=N.useState(!1),[z,H]=N.useState([]),[Z,Y]=N.useState([]),[W,ee]=N.useState({property_address:"",city:"",state:"",neighborhood:"",price:"",property_type:"single_family",status:"active",bedrooms:"",bathrooms:"",square_footage:"",lot_size:"",year_built:"",has_hoa:!1,description:"",agent_notes:"",agent_notes_public:!1,mls_link:"",video_link:"",video_id:null,allow_sharing:!0,open_to_referrals:!0,open_to_social_promotion:!0,share_with_brokerage:!1,is_public:!0});N.useEffect(()=>{var ge,Te,Ie,Ce,Me;p&&l&&ee({property_address:p.property_address||"",city:p.city||"",state:p.state||"",neighborhood:p.neighborhood||"",price:((ge=p.price)==null?void 0:ge.toString())||"",property_type:p.property_type,status:p.status,bedrooms:((Te=p.bedrooms)==null?void 0:Te.toString())||"",bathrooms:((Ie=p.bathrooms)==null?void 0:Ie.toString())||"",square_footage:((Ce=p.square_footage)==null?void 0:Ce.toString())||"",lot_size:p.lot_size||"",year_built:((Me=p.year_built)==null?void 0:Me.toString())||"",has_hoa:p.has_hoa,description:p.description||"",agent_notes:p.agent_notes||"",agent_notes_public:p.agent_notes_public,mls_link:p.mls_link||"",video_link:p.video_link||"",video_id:p.video_id||null,allow_sharing:p.allow_sharing,open_to_referrals:p.open_to_referrals,open_to_social_promotion:p.open_to_social_promotion,share_with_brokerage:p.share_with_brokerage??!1,is_public:p.is_public})},[p,l]);const se=ge=>{var Me,Pe;const Te={"single family":"single_family",detached:"single_family",residential:"single_family",condo:"condo",condominium:"condo",apartment:"condo",townhouse:"townhouse",townhome:"townhouse",land:"land",lot:"land","lots and land":"land","multi-family":"multi_family","multi family":"multi_family",duplex:"multi_family",commercial:"commercial"},Ie=(ge.propertyType||"").toLowerCase(),Ce=((Me=Object.entries(Te).find(([Re])=>Ie.includes(Re)))==null?void 0:Me[1])||"other";ee(Re=>({...Re,property_address:ge.address||Re.property_address,city:ge.city||Re.city,state:ge.state||Re.state,price:ge.price?String(ge.price):Re.price,property_type:Ce,bedrooms:ge.bedrooms?String(ge.bedrooms):Re.bedrooms,bathrooms:ge.bathrooms?String(ge.bathrooms):Re.bathrooms,square_footage:ge.sqft?String(ge.sqft):Re.square_footage,lot_size:ge.lotSize?String(ge.lotSize):Re.lot_size,year_built:ge.yearBuilt?String(ge.yearBuilt):Re.year_built,description:ge.description||Re.description})),((Pe=ge.photos)==null?void 0:Pe.length)>0&&(d(ge.photos),Z.forEach(Re=>URL.revokeObjectURL(Re)),H([]),Y([]))},oe=ge=>{if(!ge)return;const Te=Array.from(ge);H(Ce=>[...Ce,...Te]);const Ie=Te.map(Ce=>URL.createObjectURL(Ce));Y(Ce=>[...Ce,...Ie])},he=ge=>{URL.revokeObjectURL(Z[ge]),H(Te=>Te.filter((Ie,Ce)=>Ce!==ge)),Y(Te=>Te.filter((Ie,Ce)=>Ce!==ge))},ce=async ge=>{var Te;if(!(!ge||!p)){F(!0);try{for(const Ie of Array.from(ge)){const Ce=Ie.name.split(".").pop(),Me=`${a==null?void 0:a.id}/${p.id}/${Date.now()}.${Ce}`,{error:Pe}=await q.storage.from("listing-photos").upload(Me,Ie);if(Pe)throw Pe;const{data:{publicUrl:Re}}=q.storage.from("listing-photos").getPublicUrl(Me);await j.mutateAsync({listingId:p.id,photoUrl:Re,isPrimary:!((Te=p.photos)!=null&&Te.length)})}ae.success("Photos uploaded!")}catch(Ie){console.error("Upload error:",Ie),ae.error("Failed to upload photos")}finally{F(!1)}}},me=async ge=>{for(let Te=0;Te{if(p)try{await w.mutateAsync({photoId:ge,listingId:p.id}),ae.success("Photo removed")}catch{ae.error("Failed to remove photo")}},ve=async ge=>{if(ge.preventDefault(),!W.city.trim()||!W.state.trim()||!W.price){ae.error("Please fill in required fields (City, State, Price)");return}if(o&&!O){ae.error("Please select an agent to assign this listing to");return}try{const Te={property_address:W.property_address||null,city:W.city,state:W.state,neighborhood:W.neighborhood||null,price:Number(W.price),property_type:W.property_type,status:W.status,bedrooms:W.bedrooms?Number(W.bedrooms):null,bathrooms:W.bathrooms?Number(W.bathrooms):null,square_footage:W.square_footage?Number(W.square_footage):null,lot_size:W.lot_size||null,year_built:W.year_built?Number(W.year_built):null,has_hoa:W.has_hoa,description:W.description||null,agent_notes:W.agent_notes||null,agent_notes_public:W.agent_notes_public,mls_link:W.mls_link||null,video_link:W.video_link||null,video_id:W.video_id||null,allow_sharing:W.allow_sharing,open_to_referrals:W.open_to_referrals,open_to_social_promotion:W.open_to_social_promotion,share_with_brokerage:W.share_with_brokerage,is_public:W.is_public};if(l)await v.mutateAsync({id:s,...Te}),ae.success("Listing updated!"),r(`/mission-control/listings/${s}`);else{F(!0);let Ie;if(o&&O?Ie=await _.mutateAsync({agentId:O,...Te}):Ie=await y.mutateAsync(Te),z.length>0)try{await me(Ie.id),Z.forEach(Me=>URL.revokeObjectURL(Me)),H([]),Y([])}catch(Me){console.error("Photo upload error:",Me),ae.error("Listing created but some photos failed to upload")}if(c.length>0)try{for(let Me=0;Mer(o?"/my-brokerage":"/mission-control/listings"),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"}),o?"Back to Brokerage":"Back to Listings"]}),e.jsxs("div",{className:"grid md:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"md:col-span-2 space-y-6",children:[o&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Assign to Agent *"})}),e.jsxs(Ee,{children:[e.jsxs(us,{value:O,onValueChange:D,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select an agent..."})}),e.jsx(cs,{children:E.map(ge=>e.jsx(Ze,{value:ge.id,children:ge.name||ge.email},ge.id))})]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:"This listing will appear on the selected agent's Listing Exchange."})]})]}),!l&&i&&!o&&e.jsx(vZs,{onImport:se}),c.length>0&&e.jsxs(fe,{className:"border-primary/30 bg-primary/5",children:[e.jsxs(It,{className:"pb-3",children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ia,{className:"h-4 w-4 text-primary"}),"MLS Photos (",c.length,")"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"These photos will be imported when you save the listing."})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"grid grid-cols-4 sm:grid-cols-6 gap-2",children:[c.slice(0,12).map((ge,Te)=>e.jsx("div",{className:"aspect-square rounded overflow-hidden bg-muted",children:e.jsx("img",{src:ge,alt:"",className:"w-full h-full object-cover"})},Te)),c.length>12&&e.jsxs("div",{className:"aspect-square rounded bg-muted flex items-center justify-center text-sm text-muted-foreground font-medium",children:["+",c.length-12]})]}),e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"mt-2 text-destructive",onClick:()=>d([]),children:[e.jsx($n,{className:"h-3 w-3 mr-1"})," Clear MLS photos"]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Property Details"})}),e.jsx(Ee,{className:"space-y-4",children:e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"sm:col-span-2 space-y-2",children:[e.jsx(ne,{children:"Property Address"}),e.jsx(ye,{value:W.property_address,onChange:ge=>ee({...W,property_address:ge.target.value}),placeholder:"123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"City *"}),e.jsx(ye,{value:W.city,onChange:ge=>ee({...W,city:ge.target.value}),placeholder:"City",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"State *"}),e.jsx(ye,{value:W.state,onChange:ge=>ee({...W,state:ge.target.value}),placeholder:"State",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Neighborhood"}),e.jsx(ye,{value:W.neighborhood,onChange:ge=>ee({...W,neighborhood:ge.target.value}),placeholder:"Neighborhood"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Price *"}),e.jsx(ye,{type:"number",value:W.price,onChange:ge=>ee({...W,price:ge.target.value}),placeholder:"500000",required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Property Type"}),e.jsxs(us,{value:W.property_type,onValueChange:ge=>ee({...W,property_type:ge}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:SZs.map(ge=>e.jsx(Ze,{value:ge.value,children:ge.label},ge.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Status"}),e.jsxs(us,{value:W.status,onValueChange:ge=>ee({...W,status:ge}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:kZs.map(ge=>e.jsx(Ze,{value:ge.value,children:ge.label},ge.value))})]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Property Specs (Optional)"})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Bedrooms"}),e.jsx(ye,{type:"number",value:W.bedrooms,onChange:ge=>ee({...W,bedrooms:ge.target.value}),placeholder:"3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Bathrooms"}),e.jsx(ye,{type:"number",step:"0.5",value:W.bathrooms,onChange:ge=>ee({...W,bathrooms:ge.target.value}),placeholder:"2"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Sq Ft"}),e.jsx(ye,{type:"number",value:W.square_footage,onChange:ge=>ee({...W,square_footage:ge.target.value}),placeholder:"2000"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Lot Size"}),e.jsx(ye,{value:W.lot_size,onChange:ge=>ee({...W,lot_size:ge.target.value}),placeholder:"0.25 acres"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Year Built"}),e.jsx(ye,{type:"number",value:W.year_built,onChange:ge=>ee({...W,year_built:ge.target.value}),placeholder:"2005"})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-6",children:[e.jsx(jn,{checked:W.has_hoa,onCheckedChange:ge=>ee({...W,has_hoa:ge})}),e.jsx(ne,{children:"Has HOA"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Description & Links"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{value:W.description,onChange:ge=>ee({...W,description:ge.target.value}),placeholder:"Tell the story of this property...",rows:4})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Agent Notes"}),e.jsx(Ms,{value:W.agent_notes,onChange:ge=>ee({...W,agent_notes:ge.target.value}),placeholder:"Notes for other agents...",rows:2}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:W.agent_notes_public,onCheckedChange:ge=>ee({...W,agent_notes_public:ge})}),e.jsx(ne,{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(ne,{children:"MLS Link"}),e.jsx(ye,{value:W.mls_link,onChange:ge=>ee({...W,mls_link:ge.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Video Link"}),e.jsx(ye,{value:W.video_link,onChange:ge=>ee({...W,video_link:ge.target.value}),placeholder:"YouTube or Vimeo URL"})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5"}),"Property Video"]})}),e.jsx(Ee,{children:e.jsx(wZs,{selectedVideoId:W.video_id,onVideoSelect:ge=>ee({...W,video_id:ge}),listingId:l?s:void 0})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Photos"})}),e.jsx(Ee,{children:l&&(p!=null&&p.photos)?e.jsx(_Zs,{photos:p.photos,uploading:I,onUpload:ge=>ce(ge),onRemove:ge=>le(ge),onReorder:ge=>{S.mutate({photos:ge.map(Te=>({id:Te.id,sort_order:Te.sort_order,is_primary:Te.is_primary}))})},onSetPrimary:ge=>{p&&A.mutate({photoId:ge,listingId:p.id})}}):e.jsx(TZs,{photoUrls:Z,onRemove:he,onReorder:(ge,Te)=>{Y(ge),H(Te)},pendingPhotos:z,uploading:I,onUpload:oe})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Ia,{className:"h-5 w-5"}),"Documents & Disclosures"]})}),e.jsx(Ee,{children:l&&s?e.jsx(NZs,{listingId:s}):e.jsx("p",{className:"text-sm text-muted-foreground",children:"Save the listing first, then you can upload PDFs (disclosures, floor plans, HOA docs, etc.) for other agents to download."})})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Sharing & Collaboration"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Allow Sharing"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Other agents can share this listing"})]}),e.jsx(jn,{checked:W.allow_sharing,onCheckedChange:ge=>ee({...W,allow_sharing:ge})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Open to Referrals"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Accept buyer referrals"})]}),e.jsx(jn,{checked:W.open_to_referrals,onCheckedChange:ge=>ee({...W,open_to_referrals:ge})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Social Promotion"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Can be promoted on social media"})]}),e.jsx(jn,{checked:W.open_to_social_promotion,onCheckedChange:ge=>ee({...W,open_to_social_promotion:ge})})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Share with Brokerage"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Visible to agents in your brokerage"})]}),e.jsx(jn,{checked:W.share_with_brokerage,onCheckedChange:ge=>ee({...W,share_with_brokerage:ge})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Make Public"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Publish on listings.relevelup.com to get leads"})]}),e.jsx(jn,{checked:W.is_public,onCheckedChange:ge=>ee({...W,is_public:ge})})]})]})]}),e.jsx(B,{type:"submit",className:"w-full",size:"lg",disabled:y.isPending||v.isPending,children:y.isPending||v.isPending?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Saving..."]}):l?"Update Listing":"Create Listing"})]})]})]}),e.jsx(Ujt,{listingId:u.listingId,open:u.open,onOpenChange:ge=>{if(!ge){const{nextPath:Te}=u;h({open:!1,listingId:null,nextPath:Te}),r(Te)}}})]})}const nTe=[{key:"stats",label:"Stats strip",hint:"Beds, baths, sqft, lot, year"},{key:"story",label:"The Story",hint:"Property description"},{key:"agent_note",label:"Agent note",hint:"Personal note callout"},{key:"gallery",label:"Photo gallery",hint:"Bento gallery + lightbox"},{key:"video",label:"Video tour",hint:"Uses the linked video"},{key:"map",label:"Location map",hint:"Neighborhood map"},{key:"payment",label:"Payment calc",hint:"Interactive mortgage estimator"},{key:"agent_card",label:"Agent card",hint:"Your info + contact form"}],Gjt=[{type:"extra_video",label:"Extra Video / Reel",icon:fr,desc:"Add a YouTube, Vimeo, or MP4 embed",accent:"from-rose-500/20 to-rose-500/5"},{type:"tour_3d",label:"3D Tour",icon:D7,desc:"Matterport, iGuide, or Kuula embed",accent:"from-indigo-500/20 to-indigo-500/5"},{type:"floor_plans",label:"Floor Plans",icon:Xo,desc:"Upload floor plan images",accent:"from-sky-500/20 to-sky-500/5"},{type:"testimonial",label:"Testimonial",icon:gw,desc:"A quote from a past client",accent:"from-amber-500/20 to-amber-500/5"},{type:"countdown",label:"Offer Countdown",icon:pr,desc:'"Offers due Friday 5pm"',accent:"from-emerald-500/20 to-emerald-500/5"},{type:"custom_cta",label:"Custom CTA Button",icon:Yo,desc:"Link to a brochure or booking page",accent:"from-violet-500/20 to-violet-500/5"}],EZs=["#0f172a","#406E71","#c9a84c","#b91c1c","#0d7a5f","#4f46e5","#e85d3a","#111827"],vNe={sections:Object.fromEntries(nTe.map(s=>[s.key,!0])),hero_style:"photo",accent_color:null,custom_note:"",addons:[]},AZs=()=>Math.random().toString(36).slice(2,10);function MZs(){const{listingId:s}=bi(),t=Ln(),{user:n}=vs(),r=Kt(),[a,i]=N.useState("desktop"),[l,o]=N.useState(vNe),[c,d]=N.useState(!1),[u,h]=N.useState(0),{data:p,isLoading:f}=dt({queryKey:["listing-customize",s],queryFn:async()=>{const{data:z,error:H}=await q.from("listings").select("id, agent_id, slug, property_address, city, state, price, page_config, page_theme").eq("id",s).single();if(H)throw H;return z},enabled:!!s});N.useEffect(()=>{var z,H;p!=null&&p.page_config&&o({...vNe,...p.page_config||{},sections:{...vNe.sections,...((z=p.page_config)==null?void 0:z.sections)||{}},addons:((H=p.page_config)==null?void 0:H.addons)||[]})},[p==null?void 0:p.id]);const y=!!n&&!!p&&n.id===p.agent_id,_=N.useMemo(()=>p?`/public/listing/${p.slug||p.id}?preview=1&t=${u}`:"",[p,u]),v=N.useMemo(()=>p?`https://listings.relevelup.com/${p.slug||p.id}`:"",[p]),j=yt({mutationFn:async()=>{const{error:z}=await q.from("listings").update({page_config:l}).eq("id",s);if(z)throw z},onSuccess:()=>{ae.success("Saved. Your public page is live."),d(!1),r.invalidateQueries({queryKey:["listing-customize",s]}),r.invalidateQueries({queryKey:["public-listing"]}),h(z=>z+1)},onError:z=>ae.error(`Save failed: ${z.message||"Try again"}`)}),w=z=>{o(H=>({...H,...z})),d(!0)},S=(z,H)=>w({sections:{...l.sections||{},[z]:H}}),A=z=>w({addons:[...l.addons||[],{id:AZs(),type:z,data:{}}]}),E=(z,H)=>w({addons:(l.addons||[]).map(Z=>Z.id===z?{...Z,data:{...Z.data,...H}}:Z)}),O=z=>w({addons:(l.addons||[]).filter(H=>H.id!==z)}),D=(z,H)=>{const Z=[...l.addons||[]],Y=Z.findIndex(ee=>ee.id===z);if(Y<0)return;const W=Y+H;W<0||W>=Z.length||([Z[Y],Z[W]]=[Z[W],Z[Y]],w({addons:Z}))};if(f)return e.jsx(Cs,{title:"",description:"",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading…"})});if(!p)return e.jsx(Cs,{title:"",description:"",children:e.jsx("div",{className:"p-8",children:"Listing not found."})});if(!y)return e.jsx(Cs,{title:"",description:"",children:e.jsxs("div",{className:"p-8",children:[e.jsx("p",{children:"You can only customize your own listing pages."}),e.jsx(B,{className:"mt-3",onClick:()=>t(`/mission-control/listings/${p.id}`),children:"Back"})]})});const I=(l.addons||[]).length,F=Object.values(l.sections||{}).filter(Boolean).length;return e.jsxs(Cs,{title:"",description:"",children:[e.jsxs("div",{className:"sticky top-0 z-30 -mx-4 sm:-mx-6 px-4 sm:px-6 py-3 bg-background/85 backdrop-blur border-b flex items-center gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t(`/mission-control/listings/${p.id}`),children:[e.jsx(qr,{className:"h-4 w-4 mr-1.5"})," Back"]}),e.jsxs("div",{className:"hidden md:flex flex-col leading-tight",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"Customize Public Page"}),e.jsx("p",{className:"text-sm font-medium truncate max-w-[420px]",children:p.property_address||`${p.city}, ${p.state}`})]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[c&&e.jsx("span",{className:"text-xs text-amber-600 hidden sm:inline",children:"Unsaved changes"}),e.jsxs("div",{className:"hidden md:inline-flex rounded-lg border bg-muted p-0.5",children:[e.jsxs("button",{onClick:()=>i("desktop"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="desktop"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx(mb,{className:"h-3.5 w-3.5"})," Desktop"]}),e.jsxs("button",{onClick:()=>i("mobile"),className:`h-8 px-2.5 rounded-md text-xs flex items-center gap-1.5 ${a==="mobile"?"bg-background shadow-sm":"text-muted-foreground"}`,children:[e.jsx(tg,{className:"h-3.5 w-3.5"})," Mobile"]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>h(z=>z+1),children:[e.jsx(Ei,{className:"h-3.5 w-3.5 mr-1.5"})," Refresh"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:v,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1.5"})," Open live"]})}),e.jsx(B,{size:"sm",onClick:()=>j.mutate(),disabled:!c||j.isPending,children:j.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Jo,{className:"h-3.5 w-3.5 mr-1.5"})," Save & Publish"]})})]})]}),e.jsxs("div",{className:"grid lg:grid-cols-[minmax(360px,440px)_1fr] gap-6 mt-4",children:[e.jsx(di,{className:"lg:h-[calc(100vh-140px)] pr-2",children:e.jsxs("div",{className:"space-y-6 pb-16",children:[e.jsx(EF,{icon:e.jsx(un,{className:"h-4 w-4"}),title:"Hero",desc:"What visitors see first",children:e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Hero style"}),e.jsx("div",{className:"mt-2 grid grid-cols-3 gap-2",children:["photo","video","slideshow"].map(z=>e.jsx("button",{onClick:()=>w({hero_style:z}),className:`text-xs rounded-lg border py-3 capitalize transition ${l.hero_style===z?"border-primary bg-primary/5 text-primary font-medium":"border-border hover:bg-muted"}`,children:z},z))})]})}),e.jsx(EF,{icon:e.jsx(pl,{className:"h-4 w-4"}),title:"Accent color",desc:"Highlights on the public page",children:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("button",{onClick:()=>w({accent_color:null}),className:`h-9 px-3 rounded-full text-xs border ${l.accent_color?"border-border hover:bg-muted":"border-primary bg-primary/5 text-primary"}`,children:"Default"}),EZs.map(z=>e.jsx("button",{onClick:()=>w({accent_color:z}),className:`h-9 w-9 rounded-full border-2 transition ${l.accent_color===z?"ring-2 ring-offset-2 ring-primary border-white":"border-white/20"}`,style:{background:z},"aria-label":z},z))]})}),e.jsx(EF,{icon:e.jsx(Im,{className:"h-4 w-4"}),title:"Personal note",desc:"Shows in a beautiful callout on the public page",children:e.jsx(Ms,{value:l.custom_note||"",onChange:z=>w({custom_note:z.target.value}),placeholder:"Why we love this home… (optional)",rows:3})}),e.jsx(EF,{icon:e.jsx(k2,{className:"h-4 w-4"}),title:"Page sections",desc:"Toggle any default section on or off",rightLabel:`${F} of ${nTe.length} on`,children:e.jsx("div",{className:"divide-y rounded-xl border",children:nTe.map(z=>{var Z;const H=((Z=l.sections)==null?void 0:Z[z.key])!==!1;return e.jsxs("div",{className:"flex items-center justify-between p-3.5",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:z.label}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:z.hint})]}),e.jsx(jn,{checked:H,onCheckedChange:Y=>S(z.key,Y)})]},z.key)})})}),e.jsxs(EF,{icon:e.jsx(Is,{className:"h-4 w-4"}),title:"Add-on modules",desc:"Drop in extras to make this page unique",rightLabel:I?`${I} added`:void 0,children:[e.jsx("div",{className:"grid grid-cols-2 gap-2",children:Gjt.map(z=>e.jsxs("button",{onClick:()=>A(z.type),className:`group text-left rounded-xl border p-3 hover:shadow-md transition bg-gradient-to-br ${z.accent}`,children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx("div",{className:"h-7 w-7 rounded-md bg-background border flex items-center justify-center",children:e.jsx(z.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-sm font-medium",children:z.label})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground leading-snug",children:z.desc})]},z.type))}),(l.addons||[]).length>0&&e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsx("p",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:"On this page · drag to reorder"}),(l.addons||[]).map((z,H)=>e.jsx(IZs,{addon:z,onChange:Z=>E(z.id,Z),onRemove:()=>O(z.id),onMoveUp:H>0?()=>D(z.id,-1):void 0,onMoveDown:HD(z.id,1):void 0},z.id))]})]}),e.jsx("div",{className:"lg:hidden",children:e.jsx(B,{className:"w-full",onClick:()=>j.mutate(),disabled:!c||j.isPending,children:j.isPending?"Saving…":e.jsxs(e.Fragment,{children:[e.jsx(Jo,{className:"h-4 w-4 mr-1.5"})," Save & Publish"]})})})]})}),e.jsx("div",{className:"lg:h-[calc(100vh-140px)]",children:e.jsxs(fe,{className:"h-full overflow-hidden bg-neutral-100 p-4 lg:p-6 border rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Sr,{className:"h-3.5 w-3.5"}),"Live preview",c&&e.jsx(Ue,{variant:"outline",className:"text-[10px] border-amber-400 text-amber-700 bg-amber-50 ml-1",children:"Save to update"}),!c&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-emerald-600 ml-1",children:[e.jsx(Lr,{className:"h-3 w-3"})," In sync"]})]}),e.jsxs("div",{className:"lg:hidden inline-flex rounded-lg border bg-background p-0.5",children:[e.jsx("button",{onClick:()=>i("desktop"),className:`h-7 px-2 rounded ${a==="desktop"?"bg-muted":""}`,children:e.jsx(mb,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:()=>i("mobile"),className:`h-7 px-2 rounded ${a==="mobile"?"bg-muted":""}`,children:e.jsx(tg,{className:"h-3.5 w-3.5"})})]})]}),e.jsx("div",{className:"h-[calc(100%-32px)] w-full flex items-start justify-center overflow-auto",children:e.jsx("div",{className:`bg-neutral-950 rounded-xl shadow-2xl overflow-hidden transition-all mx-auto ${a==="mobile"?"w-[390px] h-[800px]":"w-full h-full min-h-[720px]"}`,children:e.jsx("iframe",{src:_,title:"Preview",className:"w-full h-full border-0"},u)})})]})})]})]})}function EF({icon:s,title:t,desc:n,rightLabel:r,children:a}){return e.jsxs("div",{className:"rounded-2xl border bg-card p-5",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{className:"flex items-start gap-2.5",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 text-primary flex items-center justify-center shrink-0",children:s}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-sm font-semibold leading-tight",children:t}),n&&e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:n})]})]}),r&&e.jsx("span",{className:"text-[10px] uppercase tracking-widest text-muted-foreground",children:r})]}),e.jsx("div",{className:"space-y-3",children:a})]})}function IZs({addon:s,onChange:t,onRemove:n,onMoveUp:r,onMoveDown:a}){const i=Gjt.find(o=>o.type===s.type),l=i.icon;return e.jsxs("div",{className:"rounded-xl border bg-background p-3.5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:"flex flex-col -my-1",children:e.jsx("button",{onClick:r,disabled:!r,className:"text-muted-foreground/50 hover:text-foreground disabled:opacity-30 leading-none",children:e.jsx(Pu,{className:"h-3.5 w-3.5"})})}),e.jsx("div",{className:"h-7 w-7 rounded-md bg-primary/10 text-primary flex items-center justify-center",children:e.jsx(l,{className:"h-3.5 w-3.5"})}),e.jsx("p",{className:"text-sm font-medium flex-1",children:i.label}),e.jsxs("div",{className:"flex items-center gap-1",children:[a&&e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:a,"aria-label":"Move down",children:e.jsx(Pu,{className:"h-3.5 w-3.5 rotate-180"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive hover:text-destructive",onClick:n,"aria-label":"Remove",children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),s.type==="extra_video"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs",children:"Video URL"}),e.jsx(ye,{placeholder:"https://youtu.be/…",value:s.data.url||"",onChange:o=>t({url:o.target.value})}),e.jsx(ne,{className:"text-xs",children:"Title (optional)"}),e.jsx(ye,{placeholder:"e.g. Sunset drone flyover",value:s.data.title||"",onChange:o=>t({title:o.target.value})})]}),s.type==="tour_3d"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs",children:"3D tour embed URL"}),e.jsx(ye,{placeholder:"https://my.matterport.com/show/?m=…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]}),s.type==="floor_plans"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs",children:"Floor plan image URLs (one per line)"}),e.jsx(Ms,{rows:3,placeholder:`https://…/floor1.jpg https://…/floor2.jpg`,value:(s.data.urls||[]).join(` `),onChange:o=>t({urls:o.target.value.split(` `).map(c=>c.trim()).filter(Boolean)})})]}),s.type==="testimonial"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs",children:"Quote"}),e.jsx(Ms,{rows:3,placeholder:`"Best home-buying experience we've ever had."`,value:s.data.quote||"",onChange:o=>t({quote:o.target.value})}),e.jsx(ne,{className:"text-xs",children:"Attribution"}),e.jsx(ye,{placeholder:"Sarah & Mike, past clients",value:s.data.author||"",onChange:o=>t({author:o.target.value})})]}),s.type==="countdown"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs",children:"Headline"}),e.jsx(ye,{placeholder:"Offers due",value:s.data.headline||"",onChange:o=>t({headline:o.target.value})}),e.jsx(ne,{className:"text-xs",children:"Deadline (date & time)"}),e.jsx(ye,{type:"datetime-local",value:s.data.deadline||"",onChange:o=>t({deadline:o.target.value})})]}),s.type==="custom_cta"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs",children:"Button label"}),e.jsx(ye,{placeholder:"Download brochure",value:s.data.label||"",onChange:o=>t({label:o.target.value})}),e.jsx(ne,{className:"text-xs",children:"Link URL"}),e.jsx(ye,{placeholder:"https://…",value:s.data.url||"",onChange:o=>t({url:o.target.value})})]})]})}const Wjt="teleprompter_settings",bNe={scrollSpeed:30,fontSize:24,lineHeight:1.6,opacity:.85,position:"top",isMirrored:!1};function PZs(){try{const s=localStorage.getItem(Wjt);return s?{...bNe,...JSON.parse(s)}:bNe}catch{return bNe}}function LZs(s){try{localStorage.setItem(Wjt,JSON.stringify(s))}catch{}}function QLe({text:s,isVisible:t,onToggleVisibility:n,isRecording:r=!1,startCountdown:a=!1,onCountdownComplete:i,className:l}){const o=N.useRef(null),c=N.useRef(null),d=N.useRef(0),u=N.useRef(0),[h,p]=N.useState(PZs),{scrollSpeed:f,fontSize:y,lineHeight:_,opacity:v,position:j,isMirrored:w}=h,S=N.useCallback((Z,Y)=>{p(W=>{const ee={...W,[Z]:Y};return LZs(ee),ee})},[]),[A,E]=N.useState(!1),[O,D]=N.useState(null),I=N.useCallback(Z=>{if(!o.current)return;d.current===0&&(d.current=Z);const Y=Z-d.current;d.current=Z,u.current+=f*Y/1e3;const W=Math.floor(u.current);W>0&&(o.current.scrollTop+=W,u.current-=W);const{scrollTop:ee,scrollHeight:se,clientHeight:oe}=o.current;if(ee+oe>=se){E(!1);return}c.current=requestAnimationFrame(I)},[f]);N.useEffect(()=>(A?(d.current=0,u.current=0,c.current=requestAnimationFrame(I)):c.current&&cancelAnimationFrame(c.current),()=>{c.current&&cancelAnimationFrame(c.current)}),[A,I]),N.useEffect(()=>{if(r&&t)if(o.current&&(o.current.scrollTop=0),a){D(3);let Z=3;const Y=setInterval(()=>{Z-=1,Z<=0?(clearInterval(Y),D(null),i==null||i(),E(!0)):D(Z)},1e3);return()=>clearInterval(Y)}else setTimeout(()=>E(!0),100);else r||(E(!1),D(null))},[r,t,a,i]);const F=N.useCallback(()=>{o.current&&(o.current.scrollTop=0),E(!1)},[]),z=N.useCallback(()=>{E(Z=>!Z)},[]);if(!t)return e.jsx("div",{className:Mt("absolute top-4 right-4 pointer-events-auto z-10",l),children:e.jsxs(B,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Show Script"]})});const H={top:"top-0 pt-16",center:"top-1/2 -translate-y-1/2",bottom:"bottom-0 pb-24"};return e.jsxs("div",{className:Mt("absolute inset-0 pointer-events-none",l),children:[O!==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:O},O),e.jsx("p",{className:"text-white/80 text-lg font-medium drop-shadow-md",children:"Get ready…"})]})}),e.jsx("div",{className:Mt("absolute left-0 right-0 h-[60%] overflow-hidden pointer-events-auto",H[j],O!==null&&"opacity-30"),style:{opacity:O!==null?.3:v},children:e.jsxs("div",{ref:o,className:Mt("mx-auto max-w-2xl px-6 overflow-y-auto scrollbar-hide h-full",w&&"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:`${y}px`,lineHeight:_,textShadow:"0 2px 4px rgba(0,0,0,0.8)"},children:s}),e.jsx("div",{className:"h-full"})]})}),e.jsxs("div",{className:"absolute top-4 right-4 flex items-center gap-2 pointer-events-auto",children:[e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsx(B,{variant:"secondary",size:"icon",className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Ko,{className:"h-4 w-4"})})}),e.jsx(el,{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(ne,{className:"text-xs",children:"Scroll Speed"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:f})]}),e.jsx(jp,{value:[f],onValueChange:([Z])=>S("scrollSpeed",Z),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(ne,{className:"text-xs",children:"Font Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[y,"px"]})]}),e.jsx(jp,{value:[y],onValueChange:([Z])=>S("fontSize",Z),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(ne,{className:"text-xs",children:"Line Spacing"}),e.jsx("span",{className:"text-xs text-muted-foreground",children:_.toFixed(1)})]}),e.jsx(jp,{value:[_*10],onValueChange:([Z])=>S("lineHeight",Z/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(ne,{className:"text-xs",children:"Opacity"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[Math.round(v*100),"%"]})]}),e.jsx(jp,{value:[v*100],onValueChange:([Z])=>S("opacity",Z/100),min:30,max:100,step:5})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs",children:"Position"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:j==="top"?"default":"outline",size:"sm",onClick:()=>S("position","top"),children:e.jsx(ex,{className:"h-4 w-4"})}),e.jsx(B,{variant:j==="center"?"default":"outline",size:"sm",onClick:()=>S("position","center"),children:e.jsx(hb,{className:"h-4 w-4"})}),e.jsx(B,{variant:j==="bottom"?"default":"outline",size:"sm",onClick:()=>S("position","bottom"),children:e.jsx(ao,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-xs",children:"Mirror Mode"}),e.jsx(jn,{checked:w,onCheckedChange:Z=>S("isMirrored",Z)})]})]})})]}),e.jsx(B,{variant:"secondary",size:"icon",onClick:z,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:A?e.jsx(gf,{className:"h-4 w-4"}):e.jsx(El,{className:"h-4 w-4"})}),e.jsx(B,{variant:"secondary",size:"icon",onClick:F,className:"h-9 w-9 bg-black/50 hover:bg-black/70 text-white border-0",children:e.jsx(Bm,{className:"h-4 w-4"})}),e.jsxs(B,{variant:"secondary",size:"sm",onClick:n,className:"bg-black/50 hover:bg-black/70 text-white border-0",children:[e.jsx(mf,{className:"h-4 w-4 mr-2"}),"Hide"]})]})]})}function DZs({onSelectScript:s,onCreateNew:t,selectedScriptId:n,className:r}){const{toast:a}=Fa(),[i,l]=N.useState(""),[o,c]=N.useState(null),[d,u]=N.useState("levelup"),{data:h,isLoading:p}=ZHs(),{data:f,isLoading:y}=QHs(),{data:_,isLoading:v}=XHs(),j=JHs(),w=N.useMemo(()=>f?f.filter(D=>{const I=!i||D.title.toLowerCase().includes(i.toLowerCase())||D.script_text.toLowerCase().includes(i.toLowerCase())||D.tags.some(z=>z.toLowerCase().includes(i.toLowerCase())),F=!o||D.category_id===o;return I&&F}):[],[f,i,o]),S=N.useMemo(()=>_?_.filter(D=>!i||D.title.toLowerCase().includes(i.toLowerCase())||D.script_text.toLowerCase().includes(i.toLowerCase())):[],[_,i]),A=D=>{s({title:D.title,text:D.script_text})},E=async D=>{try{await j.mutateAsync(D),a({title:"Script saved to My Scripts"})}catch{a({title:"Failed to save script",variant:"destructive"})}},O=p||y||v;return e.jsxs("div",{className:Mt("flex flex-col h-full",r),children:[e.jsx("div",{className:"p-4 border-b",children:e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search scripts...",value:i,onChange:D=>l(D.target.value),className:"pl-9"})]})}),e.jsxs(Fr,{value:d,onValueChange:D=>u(D),className:"flex-1 flex flex-col",children:[e.jsxs(Rr,{className:"mx-4 mt-4 grid grid-cols-2",children:[e.jsxs(Zt,{value:"levelup",children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"LevelUp Scripts"]}),e.jsxs(Zt,{value:"my-scripts",children:[e.jsx(Pv,{className:"h-4 w-4 mr-2"}),"My Scripts"]})]}),e.jsxs(is,{value:"levelup",className:"flex-1 flex flex-col mt-0 p-4",children:[e.jsxs("div",{className:"flex flex-wrap gap-2 mb-4",children:[e.jsx(Ue,{variant:o?"outline":"default",className:"cursor-pointer",onClick:()=>c(null),children:"All"}),h==null?void 0:h.map(D=>e.jsx(Ue,{variant:o===D.id?"default":"outline",className:"cursor-pointer",onClick:()=>c(D.id),children:D.name},D.id))]}),e.jsx(di,{className:"flex-1 max-h-[50vh]",children:O?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(br,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No scripts found"})]}):e.jsx("div",{className:"space-y-2",children:w.map(D=>e.jsxs(fe,{className:Mt("cursor-pointer hover:bg-accent/50 transition-colors",n===D.id&&"ring-2 ring-primary"),onClick:()=>A(D),children:[e.jsx(It,{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(Rt,{className:"text-sm font-medium truncate",children:D.title}),D.category&&e.jsx(Ue,{variant:"secondary",className:"mt-1 text-xs",children:D.category.name})]}),e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:I=>{I.stopPropagation(),E(D)},children:e.jsx(Pv,{className:"h-4 w-4"})}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"})]})]})}),e.jsx(Ee,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:D.script_text})})]},D.id))})})]}),e.jsxs(is,{value:"my-scripts",className:"flex-1 flex flex-col mt-0 p-4",children:[t&&e.jsxs(B,{variant:"outline",className:"mb-4",onClick:t,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create New Script"]}),e.jsx(di,{className:"flex-1 max-h-[50vh]",children:v?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(rs,{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(Pv,{className:"h-12 w-12 mx-auto mb-2 opacity-50"}),e.jsx("p",{children:"No saved scripts"}),e.jsx("p",{className:"text-sm mt-1",children:"Save LevelUp scripts or create your own"})]}):e.jsx("div",{className:"space-y-2",children:S.map(D=>e.jsxs(fe,{className:Mt("cursor-pointer hover:bg-accent/50 transition-colors",n===D.id&&"ring-2 ring-primary"),onClick:()=>A(D),children:[e.jsx(It,{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(Rt,{className:"text-sm font-medium truncate",children:D.title}),e.jsx("div",{className:"flex items-center gap-2 mt-1",children:D.is_custom?e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Custom"}):e.jsx(Ue,{variant:"secondary",className:"text-xs",children:"Saved"})})]}),e.jsx(ga,{className:"h-4 w-4 text-muted-foreground ml-2"})]})}),e.jsx(Ee,{className:"p-3 pt-0",children:e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:D.script_text})})]},D.id))})})]})]})]})}function RZs({selectedTemplate:s,onSelect:t,contactName:n,saving:r=!1}){const[a,i]=N.useState(()=>{const o=SL(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(ne,{className:"text-sm font-medium",children:"Share Page Template"}),r&&e.jsx(rs,{className:"h-3 w-3 animate-spin text-muted-foreground"})]}),e.jsx("div",{className:"space-y-3",children:Qss.map(o=>{const c=Xss(o.id),d=a.has(o.id),u=c.some(h=>h.id===s);return e.jsxs(oy,{open:d,onOpenChange:()=>l(o.id),children:[e.jsxs(ly,{className:"flex items-center justify-between w-full p-2.5 rounded-lg bg-muted/50 hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium text-sm",children:o.name}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["(",c.length,")"]}),u&&!d&&e.jsx("span",{className:"text-xs bg-primary/10 text-primary px-1.5 py-0.5 rounded-full",children:"✓"})]}),e.jsx(ao,{className:Mt("h-4 w-4 text-muted-foreground transition-transform",d&&"rotate-180")})]}),e.jsx(cy,{className:"pt-2",children:e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2",children:c.map(h=>{const p=s===h.id;return e.jsxs("button",{type:"button",onClick:()=>t(h.id),disabled:r,className:Mt("relative rounded-lg border-2 p-2.5 text-left transition-all hover:shadow-sm disabled:opacity-50 disabled:cursor-not-allowed",p?"border-primary ring-1 ring-primary/20 bg-primary/5":"border-muted hover:border-muted-foreground/30"),children:[p&&e.jsx("div",{className:"absolute top-1 right-1 w-4 h-4 rounded-full bg-primary flex items-center justify-center",children:e.jsx(Lr,{className:"h-2.5 w-2.5 text-primary-foreground"})}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"opacity-70 shrink-0",children:h.icon}),e.jsx("span",{className:"text-sm font-medium truncate",children:h.name})]})]},h.id)})})})]},o.id)})}),n&&s!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Will show: "',SL(s).headerText(n),'"']})]})}function Kjt({open:s,onOpenChange:t,video:n,contactName:r,onTemplateUpdated:a}){const[i,l]=N.useState(n.page_template||"default"),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(n.page_template||"default"),[f,y]=N.useState([]),[_,v]=N.useState(n.contact_id&&r?{id:n.contact_id,name:r,email:null}:null),[j,w]=N.useState(!1),[S,A]=N.useState(!1),E=n.share_token?`https://video.relevelup.com/${n.share_token}`:"";N.useEffect(()=>{s&&f.length===0&&O()},[s]);const O=async()=>{A(!0);try{const{data:ee,error:se}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(se)throw se;const oe=(ee||[]).map(he=>({id:he.id,name:[he.first_name,he.last_name].filter(Boolean).join(" ")||"Unnamed",email:he.email||null}));y(oe)}catch(ee){console.error("Failed to fetch contacts:",ee)}finally{A(!1)}},D=async ee=>{v(ee),w(!1),c(!0);try{const{error:se}=await q.from("agent_videos").update({contact_id:(ee==null?void 0:ee.id)||null,recipient_name:(ee==null?void 0:ee.name)||null}).eq("id",n.id);if(se)throw se;ae.success(ee?`Assigned to ${ee.name}`:"Contact removed"),a==null||a()}catch(se){console.error("Failed to update contact:",se),ae.error("Failed to update contact")}finally{c(!1)}},I=async ee=>{l(ee),c(!0);try{const{error:se}=await q.from("agent_videos").update({page_template:ee}).eq("id",n.id);if(se)throw se;p(ee),ae.success("Template saved!"),a==null||a()}catch(se){console.error("Failed to save template:",se),ae.error("Failed to save template"),l(h)}finally{c(!1)}},F=(_==null?void 0:_.name)||null,z=()=>{const ee=n.title||"Video Message",se=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:n.thumbnail_url||"";return``},H=async()=>{if(!n.thumbnail_url){ae.error("Video thumbnail not available yet");return}const ee=z(),se=`Watch: ${n.title||"Video Message"} ${E}`;try{const oe=new Blob([ee],{type:"text/html"}),he=new Blob([se],{type:"text/plain"}),ce=new ClipboardItem({"text/html":oe,"text/plain":he});await navigator.clipboard.write([ce]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(se+` `+ee),ae.success("Copied! Paste into your email.")}},Z=async()=>{await navigator.clipboard.writeText(E),u(!0),ae.success("Share link copied!"),setTimeout(()=>u(!1),2e3)},Y=()=>{const se=SL(i).headerText(F),oe=i==="default"?`Check out this video: ${E}`:`${se} Check out this special video: ${E}`;window.open(`sms:?body=${encodeURIComponent(oe)}`,"_self")},W=()=>{const ee=SL(i),se=ee.headerText(F),oe=i==="default"?n.title||"Video Message":se,he=`${ee.subText} Watch the video: ${E}`,ce=_!=null&&_.email?encodeURIComponent(_.email):"";window.open(`mailto:${ce}?subject=${encodeURIComponent(oe)}&body=${encodeURIComponent(he)}`,"_self")};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Yo,{className:"h-5 w-5"}),"Share Video"]}),e.jsx(Jn,{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(ne,{className:"text-sm font-medium",children:"Personalize for Contact (Optional)"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(il,{open:j,onOpenChange:w,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":j,className:"flex-1 justify-between",disabled:o,children:[_?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Wi,{className:"h-4 w-4 text-muted-foreground"}),_.name]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx($g,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-[300px] p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search contacts..."}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:S?"Loading...":"No contacts found."}),e.jsx(Jg,{children:f.map(ee=>e.jsxs(Zf,{value:ee.name,onSelect:()=>D(ee),children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",(_==null?void 0:_.id)===ee.id?"opacity-100":"opacity-0")}),ee.name]},ee.id))})]})]})})]}),_&&e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>D(null),disabled:o,className:"shrink-0",children:e.jsx($n,{className:"h-4 w-4"})})]}),_&&i!=="default"&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:['Page will show: "',SL(i).headerText(_.name),'"']})]}),e.jsx(RZs,{selectedTemplate:i,onSelect:I,contactName:F,saving:o}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Share Link"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:E,readOnly:!0,className:"font-mono text-sm"}),e.jsx(B,{onClick:Z,variant:d?"default":"outline",className:"shrink-0 gap-2",children:d?e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-4 w-4"}),"Copied"]}):e.jsxs(e.Fragment,{children:[e.jsx(Zr,{className:"h-4 w-4"}),"Copy"]})})]})]}),n.thumbnail_url&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Share for Email"}),e.jsxs(B,{variant:"outline",className:"w-full gap-2",onClick:H,children:[e.jsx(Xo,{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(ne,{children:"Quick Share"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:Y,children:[e.jsx(Ai,{className:"h-4 w-4"}),"Text"]}),e.jsxs(B,{variant:"outline",className:"flex-1 gap-2",onClick:W,children:[e.jsx(Gs,{className:"h-4 w-4"}),"Email"]})]})]})]}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Done"})})]})})}function OZs(){var $e;const s=Ln(),[t]=xl(),{toast:n}=Fa(),r=t.get("contact_id"),a=t.get("task_id"),{canRecord:i,remainingMb:l,usagePercent:o,isNearLimit:c,storage:d}=m_t(),{data:u}=ax(),h=CN(),p=rGs(),[f,y]=N.useState("record"),[_,v]=N.useState(""),[j,w]=N.useState(!1),[S,A]=N.useState(!1),[E,O]=N.useState(!1),[D,I]=N.useState(null),[F,z]=N.useState(0),[H,Z]=N.useState(0),[Y,W]=N.useState(null),[ee,se]=N.useState(null),[oe,he]=N.useState(r||""),[ce,me]=N.useState(""),[le,ve]=N.useState(""),[ge,Te]=N.useState(null),[Ie,Ce]=N.useState(null),[Me,Pe]=N.useState(null),[Re,Ae]=N.useState(!1),Be=N.useCallback(async(Ke,Ge)=>{I(Ke),y("uploading");try{const{videoId:rt,uploadUrl:tt}=await t6(ce||"Quick Video Touch");W(rt);const{apiKey:at}=await s6(rt),Ye=new XMLHttpRequest;Ye.upload.onprogress=$t=>{$t.lengthComputable&&z($t.loaded/$t.total*100)},await new Promise(($t,Yt)=>{Ye.onload=()=>{Ye.status>=200&&Ye.status<300?$t():Yt(new Error(`Upload failed: ${Ye.status}`))},Ye.onerror=()=>Yt(new Error("Upload failed")),Ye.open("PUT",tt),Ye.setRequestHeader("AccessKey",at),Ye.send(Ke)}),y("processing");let ut=0;const _t=Date.now(),bt=90*1e3;for(;ut<4;){if(await new Promise(Yt=>setTimeout(Yt,3e3)),Date.now()-_t>bt){const Yt=Ke.size/1048576,Ds=`https://iframe.mediadelivery.net/play/${rt}/${rt}`;await h.mutateAsync({bunny_video_id:rt,playback_url:Ds,file_size_mb:Yt,title:ce||"Quick Video Touch",notes:le||void 0,contact_id:oe&&oe!=="none"?oe:void 0,status:"processing",touch_type:"video_touch"}),n({title:"Video saved — still processing",description:'Your video has been saved and will appear in your library with a "processing" badge. It will be ready to share once encoding completes (usually within a few minutes).',duration:8e3}),s("/mission-control/video-library");return}const $t=await Fw(rt);if(ut=$t.status,Z($t.encodeProgress||0),ut===4)se({playbackUrl:$t.directPlayUrl,thumbnailUrl:$t.thumbnailUrl,previewUrl:$t.previewUrl||null,duration:$t.length||Ge,fileSizeMb:($t.storageSize||Ke.size)/(1024*1024)});else if(ut===5||ut===6)throw new Error("Video processing failed")}y("details")}catch(rt){console.error("Upload error:",rt),n({title:"Upload failed",description:"Please try recording again.",variant:"destructive"}),y("record")}},[ce,n]),we=async()=>{if(!(!Y||!ee))try{const Ke=oe&&oe!=="none"?oe:null,Ge=await h.mutateAsync({bunny_video_id:Y,contact_id:Ke,playback_url:ee.playbackUrl,thumbnail_url:ee.thumbnailUrl,preview_url:ee.previewUrl,duration_seconds:ee.duration,file_size_mb:ee.fileSizeMb,title:ce||"Quick Video Touch",notes:le,task_id:a||null,status:"ready"});Te(Ge.id),Ce(Ge.share_token||null),Ke&&await p.mutateAsync({contactId:Ke,videoId:Ge.id,notes:le}),n({title:"Video saved successfully!"}),y("share")}catch(Ke){console.error("Save video error:",Ke),n({title:"Failed to save video",description:(Ke==null?void 0:Ke.message)||"Please try again.",variant:"destructive"})}},Je=(Ke,Ge)=>{navigator.clipboard.writeText(Ge),Pe(Ke),setTimeout(()=>Pe(null),2e3),n({title:"Copied to clipboard!"})},ke=()=>Ie?`https://video.relevelup.com/${Ie}`:(ee==null?void 0:ee.playbackUrl)||"",it=()=>{const Ke=u==null?void 0:u.find(Ye=>Ye.id===oe),Ge=Ke?`${Ke.first_name}`:"",rt=(Ke==null?void 0:Ke.phone)||"",tt=(Ke==null?void 0:Ke.email)||"",at=ke();return{text:`Hey${Ge?` ${Ge}`:""}! I recorded a quick video for you: ${at}`,link:at,contactPhone:rt,contactEmail:tt}},je=()=>{const{text:Ke,contactPhone:Ge}=it(),rt=Ge?`sms:${Ge}?body=${encodeURIComponent(Ke)}`:`sms:?body=${encodeURIComponent(Ke)}`;window.open(rt,"_self")},He=()=>{const{link:Ke,contactEmail:Ge}=it(),rt="Check out this video",tt=`I recorded a quick video for you: ${Ke}`,at=Ge?`mailto:${Ge}?subject=${encodeURIComponent(rt)}&body=${encodeURIComponent(tt)}`:`mailto:?subject=${encodeURIComponent(rt)}&body=${encodeURIComponent(tt)}`;window.open(at,"_self")};return i?e.jsx(Cs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s(-1),children:e.jsx(qr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"QuickVid"}),e.jsx("p",{className:"text-muted-foreground",children:"Record a personal video message"})]})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>s("/mission-control/video-library"),className:"gap-1.5",children:[e.jsx(br,{className:"h-4 w-4"}),"Video Library"]}),c&&e.jsxs("div",{className:"text-right",children:[e.jsxs("p",{className:"text-sm text-warning",children:["Storage: ",o.toFixed(0),"% used"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[l.toFixed(0)," MB remaining"]})]})]})]}),f==="record"&&e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2",children:[e.jsx(i6,{maxDurationSeconds:600,onRecordingComplete:Be,onRecordingStateChange:O,className:"w-full",teleprompterContent:j&&_&&e.jsx(QLe,{text:_,isVisible:j,onToggleVisibility:()=>w(!1),isRecording:E,startCountdown:!1})}),!j&&_&&e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>w(!0),children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"Show Teleprompter"]})]}),e.jsxs(fe,{className:"lg:col-span-1",children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-lg",children:"Teleprompter Script"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(Ms,{placeholder:"Type or paste your script here...",value:_,onChange:Ke=>v(Ke.target.value),rows:6}),e.jsxs(t0,{open:S,onOpenChange:A,children:[e.jsx(Y$,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:"w-full",children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"Browse Scripts"]})}),e.jsxs(og,{side:"right",className:"w-[400px] sm:w-[540px] p-0",children:[e.jsx(jy,{className:"p-4 border-b",children:e.jsx(Ny,{children:"Select a Script"})}),e.jsx(DZs,{onSelectScript:Ke=>{v(Ke.text),A(!1),w(!0)},className:"h-[calc(100vh-80px)]"})]})]}),_&&e.jsx(B,{className:"w-full",onClick:()=>w(!0),children:"Use Script"})]})]})]}),f==="uploading"&&e.jsx(fe,{className:"max-w-md mx-auto",children:e.jsxs(Ee,{className:"pt-6 text-center",children:[e.jsx(_a,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-pulse"}),e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Uploading Video..."}),e.jsx(fi,{value:F,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[F.toFixed(0),"%"]})]})}),f==="processing"&&e.jsx(fe,{className:"max-w-md mx-auto",children:e.jsxs(Ee,{className:"pt-6 text-center space-y-4",children:[e.jsx(rs,{className:"h-12 w-12 mx-auto mb-4 text-primary animate-spin"}),e.jsx("h2",{className:"text-lg font-semibold mb-2",children:"Processing Video..."}),e.jsx(fi,{value:H,className:"mb-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[H.toFixed(0),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:`This usually takes 30-60 seconds. If it takes longer, we'll auto-save your video and you can find it in your Video Library — look for the "processing" badge.`})]})}),f==="details"&&e.jsxs(fe,{className:"max-w-lg mx-auto",children:[e.jsx(It,{children:e.jsx(Rt,{children:"Video Details"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:ce,onChange:Ke=>me(Ke.target.value),placeholder:"Quick Video Touch"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Attach to Contact (Optional)"}),e.jsxs(us,{value:oe,onValueChange:he,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"No contact - use anywhere"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Yo,{className:"h-4 w-4"}),"No contact - use anywhere"]})}),u==null?void 0:u.map(Ke=>e.jsx(Ze,{value:Ke.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wi,{className:"h-4 w-4"}),Ke.first_name," ",Ke.last_name]})},Ke.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Notes"}),e.jsx(Ms,{value:le,onChange:Ke=>ve(Ke.target.value),placeholder:"Add notes about this video...",rows:3})]}),e.jsxs(B,{className:"w-full",onClick:we,disabled:h.isPending,children:[h.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Video"]})]})]}),f==="share"&&e.jsxs(fe,{className:"max-w-lg mx-auto",children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Lr,{className:"h-5 w-5 text-green-500"}),"Video Saved!"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:"Share your video with one click:"}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs(B,{variant:"outline",className:"justify-start",onClick:je,children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:He,children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Je("link",it().link),children:[e.jsx(Yo,{className:"h-4 w-4 mr-2"}),"Copy Video Link",Me==="link"&&e.jsx(Lr,{className:"h-4 w-4 ml-auto text-green-500"})]}),e.jsxs(B,{variant:"outline",className:"justify-start",onClick:()=>Ae(!0),children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]})]}),e.jsxs("div",{className:"flex gap-3 pt-4",children:[e.jsx(B,{variant:"outline",onClick:()=>s("/mission-control/video-library"),children:"View Library"}),e.jsx(B,{onClick:()=>{y("record"),I(null),W(null),se(null)},children:"Record Another"})]})]})]}),ge&&Ie&&e.jsx(Kjt,{open:Re,onOpenChange:Ae,video:{id:ge,share_token:Ie,title:ce||null,contact_id:oe||null,thumbnail_url:(ee==null?void 0:ee.thumbnailUrl)||null},contactName:(($e=u==null?void 0:u.find(Ke=>Ke.id===oe))==null?void 0:$e.first_name)||null})]})}):e.jsx(Cs,{title:"QuickVid",children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center py-12",children:[e.jsx(ic,{className:"h-16 w-16 text-destructive mx-auto mb-4"}),e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Storage Limit Reached"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"You've reached your video storage limit. Delete videos from your library to record more."}),e.jsx(B,{onClick:()=>s("/mission-control/video-library"),children:"Open Video Library"})]})})}function FZs({open:s,onOpenChange:t,video:n,gmailEmail:r,signedThumbnailUrl:a,onSendComplete:i}){const[l,o]=N.useState([]),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[y,_]=N.useState(""),[v,j]=N.useState(""),[w,S]=N.useState(""),[A,E]=N.useState(!1),O=o_t(),D=n.share_token?`https://video.relevelup.com/share/video/${n.share_token}`:"",I=n.share_token?`https://video.relevelup.com/thumb/${n.share_token}`:a||n.thumbnail_url||"",F=n.title||"Video Message";N.useEffect(()=>{s&&l.length===0&&z()},[s]),N.useEffect(()=>{if(s&&(j(`I recorded a video for you — ${F}`),S("Hey! I recorded a quick video just for you. Click below to watch it:"),d(null),_(""),n.contact_id)){const se=l.find(oe=>oe.id===n.contact_id);se&&(d(se),_(se.email||""))}},[s,n.contact_id,l]);const z=async()=>{f(!0);try{const{data:se,error:oe}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").order("first_name",{ascending:!0}).limit(500);if(oe)throw oe;o(se||[])}catch{console.error("Failed to fetch contacts")}finally{f(!1)}},H=se=>{d(se),h(!1),_(se.email||""),S(`Hey ${se.first_name}! I recorded a quick video just for you. Click below to watch it:`),j(`I recorded a video for you — ${F}`)},Z=()=>{d(null),_(""),S("Hey! I recorded a quick video just for you. Click below to watch it:")},Y=se=>`${se.first_name} ${se.last_name||""}`.trim(),W=se=>{const oe=w.split(/\n\n+/).map(me=>`

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

`).join(""),he=se?c_t(se):D,ce=se?``:"";return`
${oe}

▶ Watch Video

${ce}
`},ee=async()=>{var se;if(!y){ae.error("Please enter a recipient email");return}if(!D){ae.error("Video does not have a share link");return}E(!0);try{let oe;try{const ve=c?Y(c):y.split("@")[0];oe=(await O.mutateAsync({video_id:n.id,recipient_email:y,recipient_name:ve,contact_id:(c==null?void 0:c.id)||null,sent_via:"gmail"})).share_token}catch(ve){console.warn("Failed to create tracking record, sending without tracking:",ve)}const he=W(oe),{data:ce,error:me}=await q.functions.invoke("gmail-send",{body:{to:y,subject:v,body:he,contactId:(c==null?void 0:c.id)||null}});let le=null;if(me&&((se=me.context)!=null&&se.json))try{le=await me.context.json()}catch{}if((le==null?void 0:le.error)==="insufficient_scope"||(ce==null?void 0:ce.error)==="insufficient_scope"){ae.error((le==null?void 0:le.message)||"Gmail is missing send permission. Please disconnect and reconnect Gmail, allowing 'Send email on your behalf'.",{duration:1e4});return}if(me)throw new Error((le==null?void 0:le.message)||me.message);if(!(ce!=null&&ce.success))throw new Error((ce==null?void 0:ce.error)||"Failed to send");ae.success("Video email sent!"),t(!1),i==null||i()}catch(oe){console.error("Gmail send error:",oe),ae.error("Failed to send: "+(oe instanceof Error?oe.message:"Unknown error"))}finally{E(!1)}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[560px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5 text-red-500"}),"Send Video via Gmail"]}),r&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sending from ",e.jsx("span",{className:"font-medium",children:r})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Send to Contact"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(il,{open:u,onOpenChange:h,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"flex-1 justify-between",children:[c?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Wi,{className:"h-4 w-4 text-muted-foreground"}),Y(c),c.email&&e.jsxs("span",{className:"text-muted-foreground text-xs",children:["(",c.email,")"]})]}):e.jsx("span",{className:"text-muted-foreground",children:"Select a contact..."}),e.jsx($g,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-[350px] p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search contacts..."}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:p?"Loading...":"No contacts found."}),e.jsx(Jg,{children:l.filter(se=>se.email).map(se=>e.jsxs(Zf,{value:`${se.first_name} ${se.last_name||""} ${se.email||""}`,onSelect:()=>H(se),children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",(c==null?void 0:c.id)===se.id?"opacity-100":"opacity-0")}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:Y(se)}),e.jsx("div",{className:"text-xs text-muted-foreground",children:se.email})]})]},se.id))})]})]})})]}),c&&e.jsx(B,{variant:"ghost",size:"icon",onClick:Z,className:"shrink-0",children:e.jsx($n,{className:"h-4 w-4"})})]})]}),!c&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"video-to",children:"Or type email address"}),e.jsx(ye,{id:"video-to",value:y,onChange:se=>_(se.target.value),placeholder:"recipient@example.com",type:"email"})]}),e.jsx(al,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"video-subject",children:"Subject"}),e.jsx(ye,{id:"video-subject",value:v,onChange:se=>j(se.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"video-message",children:"Personal Message"}),e.jsx(Ms,{id:"video-message",value:w,onChange:se=>S(se.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(ne,{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:[I?e.jsx("img",{src:I,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(El,{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(El,{className:"h-5 w-5 text-primary ml-0.5"})})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Recipients will see the thumbnail with a play button. Clicking opens the video page."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:A,children:"Cancel"}),e.jsxs(B,{onClick:ee,disabled:A||!y||!v,className:"gap-2",children:[A?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"}),A?"Sending...":"Send Video Email"]})]})]})]})})}const zZs=()=>{const{user:s}=vs();return dt({queryKey:["team-videos",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_videos",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})};function BZs({recipient:s}){return s.watched_at?e.jsxs(Ue,{className:"bg-emerald-100 text-emerald-800 text-[10px]",children:[e.jsx(El,{className:"h-2.5 w-2.5 mr-0.5"}),"Watched"]}):s.clicked_at?e.jsxs(Ue,{className:"bg-blue-100 text-blue-800 text-[10px]",children:[e.jsx(Lm,{className:"h-2.5 w-2.5 mr-0.5"}),"Clicked"]}):s.opened_at?e.jsxs(Ue,{className:"bg-amber-100 text-amber-800 text-[10px]",children:[e.jsx(Sr,{className:"h-2.5 w-2.5 mr-0.5"}),"Opened"]}):e.jsxs(Ue,{variant:"outline",className:"text-[10px]",children:[e.jsx(lr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]})}function $Zs({open:s,onOpenChange:t,videoId:n,videoTitle:r}){const{data:a=[],isLoading:i}=PHs(n);return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl max-h-[80vh]",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(_o,{className:"h-5 w-5"}),"Send Analytics: ",r]})}),i?e.jsx("div",{className:"space-y-2",children:[...Array(3)].map((l,o)=>e.jsx(Ws,{className:"h-12 w-full"},o))}):a.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recipients tracked for this video yet."}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"grid grid-cols-3 gap-3 mb-4",children:[e.jsxs("div",{className:"text-center p-2 rounded-lg bg-muted/50",children:[e.jsx("div",{className:"text-lg font-bold",children:a.length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Sent"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-amber-50",children:[e.jsx("div",{className:"text-lg font-bold text-amber-700",children:a.filter(l=>l.opened_at).length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Opened"})]}),e.jsxs("div",{className:"text-center p-2 rounded-lg bg-blue-50",children:[e.jsx("div",{className:"text-lg font-bold text-blue-700",children:a.filter(l=>l.clicked_at).length}),e.jsx("div",{className:"text-[10px] text-muted-foreground",children:"Clicked"})]})]}),e.jsx(di,{className:"h-[400px]",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Recipient"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Sent"}),e.jsx(Tt,{children:"Last Activity"})]})}),e.jsx(da,{children:a.map(l=>e.jsxs(Hs,{children:[e.jsx(ht,{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(ht,{children:e.jsx(BZs,{recipient:l})}),e.jsx(ht,{className:"text-xs text-muted-foreground",children:Ss(new Date(l.sent_at),"MMM d, h:mm a")}),e.jsx(ht,{className:"text-xs text-muted-foreground",children:l.last_activity_at?Uo(new Date(l.last_activity_at),{addSuffix:!0}):"—"})]},l.id))})]})})]})]})})}function UZs(){const{data:s,isLoading:t}=LHs(),{data:n=[],isLoading:r}=DHs(),[a,i]=N.useState(null),l=t||r,o=n.reduce((c,d)=>{const u=d.agent_videos,h=(u==null?void 0:u.id)||d.video_id;return c[h]||(c[h]={videoId:h,title:(u==null?void 0:u.title)||"Untitled",thumbnailUrl:u==null?void 0:u.thumbnail_url,recipients:[]}),c[h].recipients.push(d),c},{});return l?e.jsx("div",{className:"space-y-4",children:e.jsx("div",{className:"grid gap-4 md:grid-cols-4",children:[...Array(4)].map((c,d)=>e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Ws,{className:"h-4 w-20"})}),e.jsx(Ee,{children:e.jsx(Ws,{className:"h-8 w-16"})})]},d))})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid gap-3 grid-cols-3",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Total Sent"}),e.jsx(lr,{className:"h-4 w-4 text-muted-foreground"})]}),e.jsx(Ee,{children:e.jsx("div",{className:"text-2xl font-bold",children:(s==null?void 0:s.totalSent)||0})})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Open Rate"}),e.jsx(Sr,{className:"h-4 w-4 text-amber-500"})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.openRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalOpened)||0," opened"]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Click Rate"}),e.jsx(Lm,{className:"h-4 w-4 text-blue-500"})]}),e.jsxs(Ee,{children:[e.jsxs("div",{className:"text-2xl font-bold",children:[(s==null?void 0:s.clickRate)||0,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(s==null?void 0:s.totalClicked)||0," clicked"]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{className:"text-sm font-medium",children:"Send History by Video"}),e.jsx(Vn,{children:"Click a video to see individual recipient tracking"})]}),e.jsx(Ee,{children:Object.keys(o).length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No tracked sends yet. Send a video via Gmail to start tracking."}):e.jsx("div",{className:"space-y-2",children:Object.values(o).map(c=>{const d=c.recipients.filter(h=>h.opened_at).length,u=c.recipients.filter(h=>h.clicked_at).length;return e.jsxs("button",{onClick:()=>i({id:c.videoId,title:c.title}),className:"w-full flex items-center gap-3 p-3 rounded-lg border hover:bg-muted/50 transition-colors text-left",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:c.thumbnailUrl?e.jsx("img",{src:c.thumbnailUrl,alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer",onError:h=>{const p=h.currentTarget;p.style.display="none",p.parentElement.innerHTML='
'}}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(fr,{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(lr,{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(Sr,{className:"h-3 w-3"})," ",d]}),e.jsxs("span",{className:"text-xs text-blue-600 flex items-center gap-1",children:[e.jsx(Lm,{className:"h-3 w-3"})," ",u]})]})]}),e.jsx(go,{className:"h-4 w-4 text-muted-foreground"})]},c.videoId)})})})]}),e.jsx($Zs,{open:!!a,onOpenChange:c=>!c&&i(null),videoId:(a==null?void 0:a.id)||null,videoTitle:(a==null?void 0:a.title)||""})]})}function qZs({previewSrc:s,thumbnailSrc:t,alt:n,isHovered:r}){const[a,i]=N.useState(!1),[l,o]=N.useState(!1),c=r&&s&&!a,d=t&&!l;return!d&&!c?e.jsx("div",{className:"w-full h-full flex items-center justify-center absolute inset-0 bg-muted",children:e.jsx(fr,{className:"h-12 w-12 text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[d&&e.jsx("img",{src:t,alt:n,loading:"lazy",className:`w-full h-full object-cover absolute inset-0 transition-opacity duration-200 ${c?"opacity-0":"opacity-100"}`,onError:()=>o(!0)}),c&&e.jsx("img",{src:s,alt:n,className:"w-full h-full object-cover absolute inset-0",onError:()=>i(!0)})]})}function VZs({video:s,previewSrc:t,thumbnailSrc:n,onOpen:r,onDelete:a,onRename:i,onNavigateToContact:l,onGetEmbedCode:o,onCopyEmailHtml:c,onEmbedToCrm:d,onShareWithTemplate:u,onSendViaGmail:h,isGmailConnected:p,getContactName:f,getShareUrl:y,copyToClipboard:_,formatDuration:v}){const[j,w]=N.useState(!1);return e.jsxs(fe,{className:"overflow-hidden group cursor-pointer",onClick:r,onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),children:[e.jsxs("div",{className:"relative aspect-video bg-muted overflow-hidden",children:[e.jsx(qZs,{previewSrc:t,thumbnailSrc:n,alt:s.title||"Video preview",isHovered:j}),e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/40 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx("div",{className:"w-12 h-12 rounded-full bg-white/90 flex items-center justify-center",children:e.jsx(El,{className:"h-6 w-6 text-primary ml-1"})})}),e.jsx("div",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:v(s.duration_seconds)}),s.status!=="ready"&&e.jsx(Ue,{variant:s.status==="processing"?"secondary":"destructive",className:"absolute top-2 left-2",children:s.status})]}),e.jsx(Ee,{className:"p-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("h3",{className:"font-medium truncate",children:s.title||"Untitled Video"}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-1",children:[e.jsx(Wi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),e.jsx("span",{children:Ss(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(Sr,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]}),p&&s.share_token&&e.jsxs(B,{variant:"outline",size:"sm",className:"mt-2 gap-1.5 text-xs h-7",onClick:S=>{S.stopPropagation(),h==null||h()},children:[e.jsx(Gs,{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(Wi,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f(s.contact_id)})]}),e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),e.jsx("span",{children:Ss(new Date(s.created_at),"MMM d, yyyy")})]}),(s.view_count??0)>0&&e.jsxs("div",{className:"flex items-center gap-1 text-primary",children:[e.jsx(Sr,{className:"h-3 w-3"}),e.jsxs("span",{children:[s.view_count," ",s.view_count===1?"view":"views"]})]})]})]}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:S=>S.stopPropagation(),children:e.jsx(Ag,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",className:"bg-popover",children:[e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),r()},children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"Watch"]}),e.jsx(Kg,{}),e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),u()},children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Share with Template"]}),e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),_(y(s),"Share link")},children:[e.jsx(Yo,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),o()},children:[e.jsx(vA,{className:"h-4 w-4 mr-2"}),"Get Embed Code"]}),e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),c()},children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),d()},children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),p&&s.share_token&&e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),h==null||h()},children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]}),e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),i()},children:[e.jsx(ya,{className:"h-4 w-4 mr-2"}),"Rename"]}),e.jsx(Kg,{}),s.contact_id&&e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),l()},children:[e.jsx(Wi,{className:"h-4 w-4 mr-2"}),"View Contact"]}),e.jsxs(Kr,{onClick:S=>{S.stopPropagation(),a()},className:"text-destructive",children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})]})})]})}function HZs(){var Ds,Ls;const s=Ln(),{data:t,isLoading:n,refetch:r}=eGs(),{data:a}=g1e(),{data:i}=ax(),l=nGs(),o=sGs(),{isGmailConnected:c,gmailEmail:d}=Dh(),{data:u}=Wv(),{data:h=[],isLoading:p}=zZs(),[f,y]=N.useState("my"),[_,v]=N.useState(""),[j,w]=N.useState(null),[S,A]=N.useState(!1),[E,O]=N.useState(!1),[D,I]=N.useState(!1),[F,z]=N.useState(!1),[H,Z]=N.useState(!1),[Y,W]=N.useState(""),[ee,se]=N.useState(!1),[oe,he]=N.useState(!1),[ce,me]=N.useState(!1),[le,ve]=N.useState(!1),[ge,Te]=N.useState(""),[Ie,Ce]=N.useState({}),Me=xs=>{if(!xs)return"Unassigned";const Lt=i==null?void 0:i.find(Jt=>Jt.id===xs);return Lt?`${Lt.first_name} ${Lt.last_name||""}`.trim():"Unknown"},Pe=xs=>{if(!xs)return"0:00";const Lt=Math.floor(xs/60),Jt=xs%60;return`${Lt}:${Jt.toString().padStart(2,"0")}`},[Re,Ae]=N.useState("all"),Be=t==null?void 0:t.filter(xs=>{const Lt=xs.category||"general";if(Re==="general"&&Lt!=="general"||Re==="open_house"&&Lt!=="open_house")return!1;if(!_)return!0;const Jt=Me(xs.contact_id).toLowerCase(),gt=(xs.title||"").toLowerCase(),zt=(xs.notes||"").toLowerCase();return Jt.includes(_.toLowerCase())||gt.includes(_.toLowerCase())||zt.includes(_.toLowerCase())}),we=(t==null?void 0:t.filter(xs=>(xs.category||"general")==="open_house").length)||0,Je=(t==null?void 0:t.filter(xs=>(xs.category||"general")==="general").length)||0,ke=(t||[]).filter(xs=>xs.status==="processing"&&xs.bunny_video_id).map(xs=>xs.id).join(",");N.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Lt=t.filter(gt=>gt.status==="processing"&>.bunny_video_id);if(!Lt.length)return;let Jt=!1;for(const gt of Lt)try{const{data:zt,error:As}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:gt.bunny_video_id,isAgentVideo:!0}});if(As||!zt)continue;zt.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:zt.directPlayUrl,thumbnail_url:zt.thumbnailUrl,preview_url:zt.previewUrl,duration_seconds:zt.length||gt.duration_seconds,updated_at:new Date().toISOString()}).eq("id",gt.id),Jt=!0)}catch(zt){console.warn("Reconcile check failed for video",gt.id,zt)}Jt&&r()})()},[ke,r]),N.useEffect(()=>{(async()=>{if(!(t!=null&&t.length))return;const Lt=t.filter(Xt=>(Xt==null?void 0:Xt.bunny_video_id)&&!Ie[Xt.id]);if(!Lt.length)return;const Jt=Lt.map(Xt=>Xt.bunny_video_id),{data:gt,error:zt}=await q.functions.invoke("bunny-upload",{body:{action:"bulk-asset-urls",videoIds:Jt,isAgentVideo:!0}});if(zt)throw zt;const As=(gt==null?void 0:gt.assets)||{};Ce(Xt=>{const Qs={...Xt};for(const ks of Lt)As[ks.bunny_video_id]&&(Qs[ks.id]={previewUrl:As[ks.bunny_video_id].previewUrl,thumbnailUrl:As[ks.bunny_video_id].thumbnailUrl});return Qs})})().catch(Lt=>console.warn("Failed to load signed Bunny asset URLs",Lt))},[t,Ie]);const it=(a==null?void 0:a.total_storage_mb)||0,je=(a==null?void 0:a.max_storage_mb)||1024,He=it/je*100,$e=He>=80,Ke=He>=100,Ge=async(xs,Lt)=>{await navigator.clipboard.writeText(xs),ae.success(`${Lt} copied to clipboard`)},rt=xs=>xs.share_token?`https://video.relevelup.com/${xs.share_token}`:xs.playback_url||"",tt=xs=>{const Lt=rt(xs),Jt=i==null?void 0:i.find(ks=>ks.id===xs.contact_id),gt=Me(xs.contact_id),zt=gt!=="Unassigned"?gt.split(" ")[0]:"",As=(Jt==null?void 0:Jt.phone)||"",Xt=`Hey${zt?` ${zt}`:""}! I recorded a quick video message for you. Check it out: ${Lt}`,Qs=As?`sms:${As}?body=${encodeURIComponent(Xt)}`:`sms:?body=${encodeURIComponent(Xt)}`;window.open(Qs,"_self")},at=xs=>{const Lt=i==null?void 0:i.find(Qs=>Qs.id===xs.contact_id),Jt=(Lt==null?void 0:Lt.email)||"",gt=rt(xs),zt="Check out this video",As=`I recorded a quick video for you: ${gt}`,Xt=Jt?`mailto:${Jt}?subject=${encodeURIComponent(zt)}&body=${encodeURIComponent(As)}`:`mailto:?subject=${encodeURIComponent(zt)}&body=${encodeURIComponent(As)}`;window.open(Xt,"_self")},Ye=xs=>{var zt;const Lt=rt(xs),Jt=xs.title||"Video Message",gt=xs.share_token?`https://video.relevelup.com/thumb/${xs.share_token}`:((zt=Ie[xs.id])==null?void 0:zt.thumbnailUrl)||xs.thumbnail_url||"";return``},ut=async xs=>{if(!xs.thumbnail_url&&!xs.share_token){ae.error("Video thumbnail not available yet");return}const Lt=Ye(xs),Jt=rt(xs),gt=`Watch: ${xs.title||"Video Message"} ${Jt}`;try{const zt=new Blob([Lt],{type:"text/html"}),As=new Blob([gt],{type:"text/plain"}),Xt=new ClipboardItem({"text/html":zt,"text/plain":As});await navigator.clipboard.write([Xt]),ae.success("Copied! Paste into Gmail - the thumbnail will appear after sending.")}catch{await navigator.clipboard.writeText(gt+` `+Lt),ae.success("Copied! Paste into your email.")}},_t=async xs=>{try{ae.loading("Preparing download...",{id:"download"});const{data:Lt,error:Jt}=await q.functions.invoke("bunny-upload",{body:{action:"download-url",videoId:xs.bunny_video_id,isAgentVideo:!0}});if(Jt||!(Lt!=null&&Lt.downloadUrl))throw new Error((Jt==null?void 0:Jt.message)||"Failed to get download URL");const zt=`${((xs.title||"video").toString().trim()||"video").replace(/[\\/:*?"<>|]+/g,"-")}.mp4`,As=await fetch(Lt.downloadUrl);if(!As.ok)throw new Error("Failed to fetch video file");const Xt=await As.blob(),Qs=URL.createObjectURL(Xt),ks=document.createElement("a");ks.href=Qs,ks.download=zt,ks.rel="noreferrer",document.body.appendChild(ks),ks.click(),ks.remove(),URL.revokeObjectURL(Qs),ae.success("Download started",{id:"download"})}catch(Lt){console.error("Download error:",Lt),ae.error("Could not force download (your browser may block it).",{id:"download"})}},bt=async xs=>{w(xs),se(!0),W(""),Z(!0);try{const{data:Lt,error:Jt}=await q.functions.invoke("bunny-upload",{body:{action:"crm-embed",videoId:xs.bunny_video_id,title:xs.title,isAgentVideo:!0,shareToken:xs.share_token}});if(Jt||!(Lt!=null&&Lt.html))throw new Error("Failed to generate CRM embed code");W(Lt.html)}catch(Lt){console.error("CRM embed error:",Lt),ae.error("Failed to generate CRM embed code"),Z(!1)}finally{se(!1)}},$t=xs=>{w(xs),A(!0)},Yt=async()=>{if(j)try{await l.mutateAsync({id:j.id,bunnyVideoId:j.bunny_video_id,hardDelete:!0}),O(!1),w(null),ae.success("Video deleted successfully")}catch{ae.error("Failed to delete video")}};return e.jsx(Cs,{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:()=>y("my"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${f==="my"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"My Videos"}),u&&((Ds=u.team)==null?void 0:Ds.shared_videos_enabled)&&e.jsxs("button",{onClick:()=>y("team"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="team"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"Team"]}),e.jsxs("button",{onClick:()=>y("analytics"),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors flex items-center gap-1.5 ${f==="analytics"?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[e.jsx(_o,{className:"h-3.5 w-3.5"}),"Analytics"]})]})]}),f==="my"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>I(!0),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Upload Video"]}),e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Record New Video"]})]})]}),f==="team"?e.jsx(GZs,{videos:h,isLoading:p,searchTerm:_,setSearchTerm:v}):f==="analytics"?e.jsx(UZs,{}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:$e?"border-amber-500":Ke?"border-destructive":"",children:e.jsxs(Ee,{className:"py-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(Z7,{className:`h-5 w-5 ${Ke?"text-destructive":$e?"text-amber-500":"text-muted-foreground"}`}),e.jsxs("div",{className:"flex-1",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx("span",{className:"text-sm font-medium",children:"Storage Used"}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[it.toFixed(1)," MB / ",je>=1024?`${(je/1024).toFixed(0)} GB`:`${je} MB`]})]}),e.jsx(fi,{value:Math.min(He,100),className:`h-2 ${Ke?"[&>div]:bg-destructive":$e?"[&>div]:bg-amber-500":""}`})]}),$e&&!Ke&&e.jsxs(Ue,{variant:"outline",className:"border-amber-500 text-amber-600",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"}),"Near Limit"]}),Ke&&e.jsxs(Ue,{variant:"destructive",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"}),"At Limit"]})]}),Ke&&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:Je},{id:"open_house",label:"Open House Tours",count:we}].map(xs=>e.jsxs("button",{onClick:()=>Ae(xs.id),className:`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${Re===xs.id?"bg-background text-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:[xs.label," ",e.jsx("span",{className:"ml-1 text-xs text-muted-foreground",children:xs.count})]},xs.id))}),e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos by contact, title, or notes...",value:_,onChange:xs=>v(xs.target.value),className:"pl-10"})]}),n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):(Be==null?void 0:Be.length)===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(fr,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("h3",{className:"font-semibold mb-2",children:"No videos yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Record your first video touch to get started"}),e.jsxs(B,{onClick:()=>s("/mission-control/video/record"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Record Video"]})]})}):e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-3 gap-4",children:Be==null?void 0:Be.map(xs=>{var Lt,Jt;return e.jsx(VZs,{video:xs,previewSrc:(Lt=Ie[xs.id])==null?void 0:Lt.previewUrl,thumbnailSrc:(Jt=Ie[xs.id])==null?void 0:Jt.thumbnailUrl,onOpen:()=>$t(xs),onDelete:()=>{w(xs),O(!0)},onRename:()=>{w(xs),Te(xs.title||""),ve(!0)},onNavigateToContact:()=>s(`/mission-control/contacts/${xs.contact_id}`),onGetEmbedCode:()=>{w(xs),z(!0)},onCopyEmailHtml:()=>ut(xs),onEmbedToCrm:()=>bt(xs),onShareWithTemplate:()=>{w(xs),he(!0)},onSendViaGmail:()=>{w(xs),me(!0)},isGmailConnected:c,getContactName:Me,getShareUrl:rt,copyToClipboard:Ge,formatDuration:Pe},xs.id)})}),e.jsx(_s,{open:S,onOpenChange:A,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsx(ws,{children:(j==null?void 0:j.title)||"Video Preview"}),e.jsx(Jn,{children:(j==null?void 0:j.contact_id)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wi,{className:"h-3 w-3"}),Me(j.contact_id)]})})]}),j&&e.jsxs("div",{className:"space-y-4",children:[j.status==="processing"?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6 bg-muted/50 rounded-lg border border-dashed border-border text-center space-y-4",children:[e.jsx("div",{className:"relative",children:e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center",children:e.jsx(rs,{className:"h-8 w-8 text-primary animate-spin"})})}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:"Video is still processing"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm",children:"Your video is being encoded and will be ready shortly. This usually takes 1–3 minutes. Check back soon!"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{A(!1),r()},children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"}),"Refresh Library"]})]}):e.jsx("div",{className:"relative w-full",style:{paddingBottom:"56.25%"},children:j.playback_url?(()=>{let xs=j.playback_url;return xs.includes("iframe.mediadelivery.net/play/")&&(xs=xs.replace("/play/","/embed/"),xs+=(xs.includes("?")?"&":"?")+"autoplay=false&responsive=true"),xs.includes("iframe.mediadelivery.net")?e.jsx("iframe",{src:xs,title:j.title||"Video preview",className:"absolute top-0 left-0 w-full h-full rounded-lg",style:{border:0},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0}):e.jsx("video",{src:j.playback_url,controls:!0,playsInline:!0,preload:"metadata",poster:j.thumbnail_url||void 0,className:"absolute top-0 left-0 w-full h-full rounded-lg object-cover",onError:()=>ae.error("Video preview failed to load")},j.playback_url)})():e.jsxs("div",{className:"absolute inset-0 flex items-center justify-center bg-muted rounded-lg",children:[e.jsx(fr,{className:"h-12 w-12 text-muted-foreground"}),e.jsx("p",{className:"text-muted-foreground ml-2",children:"Video not available"})]})}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>tt(j),children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"}),"Text Contact Video"]}),!c&&e.jsxs(B,{variant:"outline",onClick:()=>at(j),children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Email Contact Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>Ge(rt(j),"Share link"),children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Copy Share Link"]}),e.jsxs(B,{variant:"outline",onClick:()=>ut(j),children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Copy HTML for Email"]}),e.jsxs(B,{variant:"outline",onClick:()=>_t(j),children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Download Video"]}),e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),bt(j)},children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Embed to CRM"]}),e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),he(!0)},children:[e.jsx(pl,{className:"h-4 w-4 mr-2"}),"Send with Page Template"]}),c&&(j==null?void 0:j.share_token)&&e.jsxs(B,{variant:"outline",onClick:()=>{A(!1),me(!0)},children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Send via Gmail"]})]}),e.jsx("div",{className:"flex justify-end pt-2 border-t",children:e.jsxs(B,{variant:"destructive",onClick:()=>{A(!1),O(!0)},children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),"Delete Video"]})})]})]})}),e.jsx(_s,{open:E,onOpenChange:O,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Delete Video"}),e.jsx(Jn,{children:"Are you sure you want to delete this video? This action cannot be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>O(!1),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:Yt,disabled:l.isPending,children:l.isPending?"Deleting...":"Delete"})]})]})}),e.jsx(p_t,{open:D,onOpenChange:I}),e.jsx(_s,{open:F,onOpenChange:z,children:e.jsxs(bs,{className:"sm:max-w-lg",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Embed Video"}),e.jsx(Jn,{children:"Copy this code to embed the video on your website."})]}),j&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Embed Code"}),e.jsx(Ms,{readOnly:!0,rows:5,value:``,className:"font-mono text-xs"})]}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{className:"flex-1",onClick:()=>{const xs=``;Ge(xs,"Embed code")},children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Copy Embed Code"]})}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Paste this code into your website's HTML where you want the video to appear. The video will automatically resize to fit its container."})]})]})}),j&&e.jsx(Kjt,{open:oe,onOpenChange:he,video:j,contactName:Me(j.contact_id)}),j&&e.jsx(FZs,{open:ce,onOpenChange:me,video:j,gmailEmail:d,signedThumbnailUrl:(Ls=Ie[j.id])==null?void 0:Ls.thumbnailUrl}),e.jsx(_s,{open:le,onOpenChange:ve,children:e.jsxs(bs,{className:"max-w-sm",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Rename Video"}),e.jsx(Jn,{children:"Enter a new title for this video."})]}),e.jsx(ye,{value:ge,onChange:xs=>Te(xs.target.value),placeholder:"Video title",autoFocus:!0,onKeyDown:xs=>{xs.key==="Enter"&&ge.trim()&&o.mutate({id:j.id,title:ge.trim()},{onSuccess:()=>{ae.success("Video renamed"),ve(!1)}})}}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>ve(!1),children:"Cancel"}),e.jsx(B,{disabled:!ge.trim()||o.isPending,onClick:()=>{o.mutate({id:j.id,title:ge.trim()},{onSuccess:()=>{ae.success("Video renamed"),ve(!1)}})},children:o.isPending?"Saving...":"Save"})]})]})}),e.jsx(_s,{open:H,onOpenChange:Z,children:e.jsxs(bs,{className:"sm:max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(tr,{className:"h-5 w-5"}),"Embed to CRM"]}),e.jsx(Jn,{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."})]}),ee?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(rs,{className:"h-8 w-8 animate-spin text-muted-foreground"})}):Y?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"CRM Email HTML"}),e.jsx(Ms,{readOnly:!0,rows:12,value:Y,className:"font-mono text-xs"})]}),e.jsxs(B,{className:"w-full",onClick:()=>{Ge(Y,"CRM embed code")},children:[e.jsx(Zr,{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 GZs({videos:s,isLoading:t,searchTerm:n,setSearchTerm:r}){const a=N.useMemo(()=>{if(!n)return s;const o=n.toLowerCase();return s.filter(c=>(c.title||"").toLowerCase().includes(o)||(c.owner_name||"").toLowerCase().includes(o)||(c.recipient_name||"").toLowerCase().includes(o))},[s,n]),i=N.useMemo(()=>{const o=new Map;return a.forEach(c=>{const d=o.get(c.owner_user_id);d?d.videos.push(c):o.set(c.owner_user_id,{name:c.owner_name,avatar:c.owner_avatar_url,videos:[c]})}),Array.from(o.entries())},[a]),l=o=>{if(!o)return"0:00";const c=Math.floor(o/60),d=o%60;return`${c}:${d.toString().padStart(2,"0")}`};return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search team videos by title, owner, or recipient...",value:n,onChange:o=>r(o.target.value),className:"pl-10"})]}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-4 border-primary border-t-transparent rounded-full"})}):a.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(An,{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(Jr,{className:"h-7 w-7",children:[e.jsx(ti,{src:c.avatar||""}),e.jsx(ea,{children:(c.name||"?").charAt(0).toUpperCase()})]}),e.jsx("h3",{className:"font-semibold text-sm",children:c.name}),e.jsx(Ue,{variant:"secondary",className:"text-xs",children:c.videos.length})]}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3",children:c.videos.map(d=>e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"relative aspect-video bg-muted flex items-center justify-center",children:[d.thumbnail_url?e.jsx("img",{src:d.thumbnail_url,alt:d.title||"Video",className:"w-full h-full object-cover",referrerPolicy:"no-referrer",onError:u=>{u.target.style.display="none"}}):e.jsx(fr,{className:"h-10 w-10 text-muted-foreground"}),d.duration_seconds&&e.jsx("span",{className:"absolute bottom-2 right-2 bg-black/70 text-white text-xs px-1.5 py-0.5 rounded",children:l(d.duration_seconds)})]}),e.jsxs(Ee,{className:"p-3",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:d.title||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1 text-xs text-muted-foreground",children:[d.recipient_name&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Wi,{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(Sr,{className:"h-3 w-3"}),d.view_count]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),Ss(new Date(d.created_at),"MMM d")]})]})]})]},d.id))})]},o))})]})}const WZs=()=>{const{user:s}=vs();return dt({queryKey:["team-deals",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.rpc("get_team_deals",{_user_id:s.id});if(n)throw n;return t||[]},enabled:!!s})},DQe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function KZs({open:s,onOpenChange:t}){const{data:n,isLoading:r}=WZs(),[a,i]=N.useState(""),[l,o]=N.useState("all"),c=N.useMemo(()=>{if(!n)return new Map;const y=new Map;let _=0;return n.forEach(v=>{y.has(v.owner_user_id)||(y.set(v.owner_user_id,{name:v.owner_name||"Unknown",avatar:v.owner_avatar_url,color:DQe[_%DQe.length]}),_++)}),y},[n]),d=N.useMemo(()=>Array.from(c.entries()).map(([y,_])=>({id:y,..._})),[c]),u=N.useMemo(()=>{if(!n)return[];let y=n;if(l!=="all"&&(y=y.filter(_=>_.owner_user_id===l)),a.trim()){const _=a.toLowerCase();y=y.filter(v=>{var j,w,S,A;return v.deal_name.toLowerCase().includes(_)||((j=v.contact_name)==null?void 0:j.toLowerCase().includes(_))||((w=v.property_address)==null?void 0:w.toLowerCase().includes(_))||((S=v.city)==null?void 0:S.toLowerCase().includes(_))||((A=v.owner_name)==null?void 0:A.toLowerCase().includes(_))})}return y},[n,a,l]),h=N.useMemo(()=>{const y=new Map;return u.forEach(_=>{const v=_.stage_name||"Unknown";y.has(v)||y.set(v,{name:v,color:_.stage_color,icon:_.stage_icon,deals:[],totalValue:0});const j=y.get(v);j.deals.push(_),j.totalValue+=_.sale_price||0}),Array.from(y.values())},[u]),p=y=>y>=1e6?`$${(y/1e6).toFixed(1)}M`:y>=1e3?`$${(y/1e3).toFixed(0)}K`:`$${y.toFixed(0)}`,f=y=>y?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(y):null;return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-[95vw] w-full max-h-[90vh] flex flex-col",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"Team Pipeline"]})}),e.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[e.jsxs("div",{className:"relative flex-1 max-w-xs",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals...",value:a,onChange:y=>i(y.target.value),className:"pl-9"})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"All Members"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Members"}),d.map(y=>e.jsx(Ze,{value:y.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:y.color}}),y.name]})},y.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(y=>e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"h-2 w-2 rounded-full",style:{backgroundColor:y.color}}),y.name.split(" ")[0]]},y.id)),d.length>6&&e.jsxs("span",{children:["+",d.length-6," more"]})]})]}),e.jsx("div",{className:"flex-1 overflow-hidden mt-2",children:r?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map(y=>e.jsxs("div",{className:"min-w-[260px] flex-1",children:[e.jsx(Ws,{className:"h-12 w-full mb-2 rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full mb-2 rounded-lg"}),e.jsx(Ws,{className:"h-24 w-full rounded-lg"})]},y))}):h.length===0?e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:e.jsxs("div",{className:"text-center",children:[e.jsx(An,{className:"h-10 w-10 mx-auto mb-3 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No team deals found"}),e.jsx("p",{className:"text-sm",children:"Team members' deals will appear here."})]})}):e.jsx("div",{className:"flex gap-3 h-full overflow-x-auto pb-2",children:h.map(y=>{const _=y.icon&&m0e[y.icon]||am;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:y.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:y.color?`${y.color}20`:void 0},children:e.jsx(_,{className:"h-3.5 w-3.5",style:{color:y.color||void 0}})}),e.jsx("h3",{className:"font-semibold text-sm",children:y.name})]}),e.jsx(Ue,{variant:"secondary",className:"text-xs px-2",children:y.deals.length})]}),y.totalValue>0&&e.jsx("p",{className:"text-xs text-muted-foreground ml-8",children:p(y.totalValue)})]}),e.jsx(di,{className:"flex-1 p-2",children:e.jsx("div",{className:"space-y-2",children:y.deals.map(v=>{const j=c.get(v.owner_user_id);return e.jsx(YZs,{deal:v,ownerColor:(j==null?void 0:j.color)||"#888",ownerName:(j==null?void 0:j.name)||"Unknown",ownerAvatar:(j==null?void 0:j.avatar)||null,formatPrice:f},v.id)})})})]},y.name)})})}),e.jsxs("p",{className:"text-xs text-muted-foreground text-center pt-2 border-t shrink-0",children:[u.length," deal",u.length!==1?"s":""," across ",h.length," stage",h.length!==1?"s":""," from ",d.length," member",d.length!==1?"s":""]})]})})}function YZs({deal:s,ownerColor:t,ownerName:n,ownerAvatar:r,formatPrice:a}){const i={buyer:{label:"Buyer",className:"bg-blue-500/10 text-blue-600 border-blue-200"},seller:{label:"Seller",className:"bg-emerald-500/10 text-emerald-600 border-emerald-200"},dual:{label:"Dual",className:"bg-purple-500/10 text-purple-600 border-purple-200"},referral:{label:"Referral",className:"bg-orange-500/10 text-orange-600 border-orange-200"},lease:{label:"Lease",className:"bg-cyan-500/10 text-cyan-600 border-cyan-200"}},l=s.deal_type?i[s.deal_type]:null;return e.jsxs("div",{className:"rounded-lg border bg-card p-3 space-y-2 transition-all hover:shadow-sm",style:{borderLeftWidth:4,borderLeftColor:t},children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(Jr,{className:"h-4 w-4",children:[e.jsx(ti,{src:r||""}),e.jsx(ea,{className:"text-[8px] font-semibold text-white",style:{backgroundColor:t},children:n.charAt(0).toUpperCase()})]}),e.jsx("span",{className:"text-[10px] font-medium truncate",style:{color:t},children:n})]}),e.jsxs("div",{className:"flex items-start justify-between gap-1",children:[e.jsx("h4",{className:"font-medium text-sm leading-tight line-clamp-2",children:s.deal_name}),l&&e.jsx(Ue,{variant:"outline",className:Mt("text-[10px] px-1.5 py-0 shrink-0",l.className),children:l.label})]}),s.contact_name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:s.contact_name}),(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1 text-xs text-muted-foreground",children:[e.jsx(Or,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.property_address||`${s.city}, ${s.state}`})]}),s.sale_price&&e.jsxs("div",{className:"flex items-center gap-1 text-xs",children:[e.jsx(Yl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:a(s.sale_price)})]})]})}function ZZs({members:s,enabledMembers:t,onToggleMember:n,isOpen:r,onToggleOpen:a}){const i=t.size;return e.jsxs("div",{className:Mt("shrink-0 border-r border-border/50 bg-muted/20 transition-all duration-300 flex flex-col",r?"w-[220px]":"w-[48px]"),children:[e.jsx("div",{className:"p-2 border-b border-border/50 shrink-0",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start gap-2 px-2",onClick:a,children:[e.jsx(An,{className:"h-4 w-4 shrink-0 text-primary"}),r&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"text-xs font-semibold flex-1 text-left",children:"Team"}),i>0&&e.jsx("span",{className:"text-[10px] bg-primary text-primary-foreground rounded-full px-1.5 py-0.5",children:i}),e.jsx(ml,{className:"h-3 w-3 text-muted-foreground"})]}),!r&&i>0&&e.jsx("span",{className:"absolute -top-1 -right-1 text-[9px] bg-primary text-primary-foreground rounded-full w-4 h-4 flex items-center justify-center",children:i})]})}),r?e.jsxs(di,{className:"flex-1 p-2",children:[e.jsx("div",{className:"space-y-1",children:s.map(l=>{const o=t.has(l.id);return e.jsxs("button",{onClick:()=>n(l.id),className:Mt("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(Jr,{className:"h-7 w-7",children:[e.jsx(ti,{src:l.avatar_url||""}),e.jsx(ea,{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:Mt("text-xs truncate flex-1",o?"font-medium text-foreground":"text-muted-foreground"),children:l.name}),e.jsx(jn,{checked:o,onCheckedChange:()=>n(l.id),className:"scale-75",onClick:c=>c.stopPropagation()})]},l.id)})}),s.length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-4",children:"No team members"})]}):e.jsxs("div",{className:"flex-1 flex flex-col items-center pt-2 gap-2",children:[s.slice(0,5).map(l=>{const o=t.has(l.id);return e.jsx("button",{onClick:()=>n(l.id),className:"relative",title:l.name,children:e.jsxs(Jr,{className:Mt("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(ti,{src:l.avatar_url||""}),e.jsx(ea,{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 RQe=["#8B5CF6","#EC4899","#F59E0B","#10B981","#3B82F6","#EF4444","#06B6D4","#F97316"];function QZs(){const s=wa(),{data:t}=Wv(),n=(t==null?void 0:t.role)==="team_leader",r=t==null?void 0:t.teamId,a=dt({queryKey:["team-pipeline-members",r,s],queryFn:async()=>{const{data:i,error:l}=await q.from("team_members").select("user_id, role").eq("team_id",r).neq("user_id",s);if(l)throw l;if(!i||i.length===0)return[];const o=i.map(u=>u.user_id),{data:c,error:d}=await q.from("profiles").select("id, name, avatar_url").in("id",o);if(d)throw d;return(c||[]).map((u,h)=>({id:u.id,name:u.name||"Unknown",avatar_url:u.avatar_url,color:RQe[h%RQe.length]}))},enabled:!!r&&!!s&&n,staleTime:5*60*1e3});return{isTeamLeader:n,teamMembers:a.data||[],isLoadingMembers:a.isLoading}}function XZs(s){return dt({queryKey:["team-member-deals",s],queryFn:async()=>{if(s.length===0)return[];const{data:t,error:n}=await q.from("deal_pipeline").select(` *, contact:innercircle_contacts(id, first_name, last_name, email, phone), listing:listings(id, property_address, city, state, price, status, created_at), deal_pipeline_stages(name) `).in("owner_user_id",s).order("updated_at",{ascending:!1});if(n)throw n;return(t||[]).map(r=>{var a;return{...r,_stage_name:((a=r.deal_pipeline_stages)==null?void 0:a.name)||null}})},enabled:s.length>0})}function JZs(){const s=wa();return dt({queryKey:["all-deal-tags-map",s],queryFn:async()=>{if(!s)return{tags:[],byDeal:{},unique:[]};const{data:t,error:n}=await q.from("deal_tags").select("id, deal_id, tag").eq("owner_user_id",s);if(n)throw n;const r=t||[],a={},i=new Set;r.forEach(o=>{a[o.deal_id]||(a[o.deal_id]=[]),a[o.deal_id].push(o.tag),i.add(o.tag)});const l=Array.from(i).sort((o,c)=>o.localeCompare(c));return{tags:r,byDeal:a,unique:l}},enabled:!!s})}function Yjt({stages:s,currentStageId:t,onStageSelect:n,disabled:r}){const[a,i]=N.useState(!1),l=s.find(c=>c.id===t),o=c=>{c.id!==t&&n(c.id,c.name),i(!1)};return e.jsxs(Mc,{open:a,onOpenChange:i,children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs gap-1.5",disabled:r,onClick:c=>c.stopPropagation(),children:[l&&e.jsx("div",{className:"w-2 h-2 rounded-full shrink-0",style:{backgroundColor:l.color}}),e.jsx("span",{className:"max-w-[80px] truncate",children:(l==null?void 0:l.name)||"Move"}),e.jsx(ga,{className:"h-3 w-3 shrink-0"})]})}),e.jsx(gc,{align:"end",className:"w-48 z-50 bg-popover",onClick:c=>c.stopPropagation(),children:s.map(c=>{const d=c.icon&&m0e[c.icon]||am,u=c.id===t;return e.jsxs(Kr,{onClick:()=>o(c),className:Mt("flex items-center gap-2 cursor-pointer",u&&"bg-accent"),children:[e.jsx("div",{className:"w-5 h-5 rounded flex items-center justify-center shrink-0",style:{backgroundColor:`${c.color}20`},children:e.jsx(d,{className:"h-3 w-3",style:{color:c.color}})}),e.jsx("span",{className:"flex-1",children:c.name}),u&&e.jsx(Lr,{className:"h-4 w-4 text-primary"})]},c.id)})})]})}const eQs={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"}},tQs={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 Zjt({deal:s,onClick:t,isDragging:n,stages:r,onStageChange:a,showStagePicker:i=!1,isWonStage:l=!1,ownerInfo:o=null}){var w,S;const c=fR(),d=eQs[s.deal_type],u=tQs[s.priority],h=N.useMemo(()=>s.target_close_date?Vv(Ll(s.target_close_date),new Date):null,[s.target_close_date]),p=h!==null&&h<0,f=h!==null&&h<=7&&h>=0,y=N.useMemo(()=>{var O;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const A=((O=s.listing)==null?void 0:O.created_at)||s.listing_date;if(!A)return null;const E=s.contract_date?Ll(s.contract_date):new Date;return Vv(E,Ll(A))},[s]),_=l&&!s.scorecard_transaction_id,v=!!s.scorecard_transaction_id,j=A=>A?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(A):null;return e.jsx(fe,{className:Mt("cursor-pointer transition-all duration-200 hover:shadow-md hover:border-primary/30 group overflow-hidden",n&&"opacity-50 rotate-2 shadow-xl",p&&"border-red-200 bg-red-50/30",_&&"border-amber-300 bg-amber-50/30 dark:bg-amber-950/20"),onClick:t,style:o?{borderLeftWidth:4,borderLeftColor:o.color}:void 0,children:e.jsxs(Ee,{className:"p-3 space-y-2.5",children:[o&&e.jsxs("div",{className:"flex items-center gap-1.5 -mt-0.5 mb-1",children:[e.jsxs(Jr,{className:"h-4 w-4",children:[e.jsx(ti,{src:o.avatar_url||""}),e.jsx(ea,{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(Ue,{variant:"outline",className:Mt("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(Jr,{className:"h-5 w-5",children:e.jsxs(ea,{className:"text-[10px] bg-primary/10 text-primary",children:[(w=s.contact.first_name)==null?void 0:w[0],(S=s.contact.last_name)==null?void 0:S[0]]})}),e.jsxs("span",{className:"truncate",children:[s.contact.first_name," ",s.contact.last_name]})]}),s.listing&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(Tl,{className:"h-3 w-3 text-primary shrink-0"}),e.jsx("span",{className:"text-primary truncate",children:"Linked to Listing Exchange"})]}),_&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 px-2 py-1 rounded",children:[e.jsx(xo,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate font-medium",children:"Add to Scorecard"})]}),v&&l&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-green-600 dark:text-green-400",children:[e.jsx(vr,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:"Synced to Scorecard"})]}),y!==null&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(Xf,{className:"h-3 w-3 text-muted-foreground shrink-0"}),e.jsxs("span",{className:Mt("font-medium",y>90?"text-red-600":y>60?"text-amber-600":"text-muted-foreground"),children:[y," DOM"]}),s.contract_date&&e.jsx("span",{className:"text-muted-foreground",children:"(final)"})]}),!s.listing&&(s.property_address||s.city)&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Or,{className:"h-3 w-3 shrink-0"}),e.jsx("span",{className:"truncate",children:s.property_address||`${s.city}, ${s.state}`})]}),s.expected_price&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs",children:[e.jsx(Yl,{className:"h-3 w-3 text-emerald-500 shrink-0"}),e.jsx("span",{className:"font-semibold text-foreground",children:j(s.expected_price)}),s.expected_commission&&e.jsxs("span",{className:"text-muted-foreground",children:["• ",j(s.expected_commission)," GCI"]}),(()=>{const A=Sv(s);return A!==null&&A!==s.expected_commission?e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:["• ",j(A)," Net"]}):null})()]}),e.jsxs("div",{className:"flex items-center justify-between pt-1 border-t border-border/50",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:Mt("flex items-center gap-1 px-1.5 py-0.5 rounded text-[10px]",u.color),children:[e.jsx("div",{className:Mt("w-1.5 h-1.5 rounded-full",u.dot)}),e.jsx("span",{className:"capitalize",children:s.priority})]}),e.jsxs("span",{className:"text-[10px] text-muted-foreground",children:[s.probability,"%"]})]}),i&&c&&r&&a?e.jsx(Yjt,{stages:r,currentStageId:s.stage_id||"",onStageSelect:(A,E)=>a(s.id,A,E)}):s.target_close_date?e.jsxs("div",{className:Mt("flex items-center gap-1 text-[10px]",p&&"text-red-600",f&&!p&&"text-amber-600",!p&&!f&&"text-muted-foreground"),children:[p?e.jsx(Bi,{className:"h-3 w-3"}):e.jsx(yr,{className:"h-3 w-3"}),e.jsx("span",{children:p?`${Math.abs(h)}d overdue`:f?`${h}d left`:Ss(Ll(s.target_close_date),"MMM d")})]}):null]})]})})}function sQs({stage:s,deals:t,onDealClick:n,onAddDeal:r,onDragStart:a,onDragOver:i,onDrop:l,isDragOver:o,isWonStage:c=!1,getOwnerInfo:d}){const u=N.useRef(null),h=t.reduce((v,j)=>v+(j.expected_price||0),0),p=t.reduce((v,j)=>v+(j.expected_commission||0),0),f=t.reduce((v,j)=>v+(Sv(j)||0),0),y=v=>v>=1e6?`$${(v/1e6).toFixed(1)}M`:v>=1e3?`$${(v/1e3).toFixed(0)}K`:`$${v.toFixed(0)}`,_=s.icon&&m0e[s.icon]||am;return e.jsxs("div",{ref:u,className:Mt("flex flex-col h-full min-w-[280px] max-w-[320px] bg-muted/30 rounded-xl border border-border/50 transition-all duration-200",o&&"border-primary/50 bg-primary/5 ring-2 ring-primary/20"),onDragOver:v=>i(v,s.id),onDrop:v=>l(v,s.id),children:[e.jsxs("div",{className:"p-3 border-b border-border/50 shrink-0",style:{borderTopColor:s.color,borderTopWidth:3},children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-7 h-7 rounded-lg flex items-center justify-center",style:{backgroundColor:`${s.color}20`},children:e.jsx(_,{className:"h-4 w-4",style:{color:s.color}})}),e.jsx("div",{children:e.jsx("h3",{className:"font-semibold text-sm",children:s.name})})]}),e.jsx(Ue,{variant:"secondary",className:"text-xs font-medium px-2",children:t.length})]}),h>0&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-wrap",children:[e.jsx("span",{className:"font-medium text-foreground",children:y(h)}),e.jsx("span",{children:"•"}),e.jsxs("span",{children:[y(p)," GCI"]}),f>0&&f!==p&&e.jsxs(e.Fragment,{children:[e.jsx("span",{children:"•"}),e.jsxs("span",{className:"text-teal-600 dark:text-teal-400",children:[y(f)," Net"]})]})]})]}),e.jsx(di,{className:"flex-1 p-2",children:e.jsxs("div",{className:"space-y-2",children:[t.map(v=>e.jsx("div",{draggable:!0,onDragStart:j=>{j.dataTransfer.effectAllowed="move",a(v.id,s.id)},children:e.jsx(Zjt,{deal:v,onClick:()=>n(v),isWonStage:c,ownerInfo:(d==null?void 0:d(v))||null})},v.id)),t.length===0&&e.jsxs("div",{className:"py-8 px-4 text-center text-muted-foreground text-sm",children:[e.jsx("p",{className:"mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-xs",children:"Drag deals here or add new"})]})]})}),e.jsx("div",{className:"p-2 border-t border-border/50 shrink-0",children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-start text-muted-foreground hover:text-foreground",onClick:()=>r(s.id),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Deal"]})})]})}function nQs({stats:s,isLoading:t}){const n=a=>a>=1e6?`$${(a/1e6).toFixed(1)}M`:a>=1e3?`$${(a/1e3).toFixed(0)}K`:`$${a.toLocaleString()}`,r=[{label:"Active Deals",value:(s==null?void 0:s.activeDeals)||0,icon:Ac,color:"text-blue-500",bgColor:"bg-blue-500/10"},{label:"Weighted GCI",value:n((s==null?void 0:s.weightedGCI)||0),icon:p9,color:"text-indigo-500",bgColor:"bg-indigo-500/10",tooltip:"GCI adjusted by each deal's win probability"},{label:"Weighted Net",value:n((s==null?void 0:s.weightedNet)||0),icon:gL,color:"text-teal-500",bgColor:"bg-teal-500/10",tooltip:"Net to Agent adjusted by each deal's win probability"},{label:"YTD Closed Net",value:n((s==null?void 0:s.ytdWonNet)||0),icon:O7,color:"text-green-500",bgColor:"bg-green-500/10",subtitle:`${(s==null?void 0:s.ytdWonDeals)||0} deals`,tooltip:"Net commission from deals closed this year"},{label:"Projected Annual",value:n((s==null?void 0:s.projectedAnnualNet)||0),icon:go,color:"text-amber-500",bgColor:"bg-amber-500/10",tooltip:"YTD Closed Net + Weighted Active Net"}];return t?e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[1,2,3,4,5].map(a=>e.jsx(fe,{className:"animate-pulse",children:e.jsx(Ee,{className:"p-4",children:e.jsx("div",{className:"h-10 bg-muted rounded"})})},a))}):e.jsx(Vw,{children:e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:r.map(a=>{const i=e.jsx(fe,{className:"border-border/50 hover:shadow-sm transition-shadow",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Mt("p-2 rounded-lg",a.bgColor),children:e.jsx(a.icon,{className:Mt("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(Bc,{children:[e.jsx($c,{asChild:!0,children:i}),e.jsx(Nc,{children:e.jsx("p",{children:a.tooltip})})]},a.label):i})})})}function rQs({formData:s,onChange:t,isEditing:n}){const{isAdmin:r}=vs(),[a,i]=N.useState(s.portal_enabled);if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 opacity-60",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ue,{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(oy,{open:a,onOpenChange:i,children:e.jsxs("div",{className:"border rounded-lg",children:[e.jsxs(ly,{className:"w-full p-4 flex items-center justify-between hover:bg-muted/50 transition-colors rounded-t-lg",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("h4",{className:"font-medium text-sm",children:"Client Portal"}),s.portal_enabled&&e.jsx(Ue,{className:"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200",variant:"outline",children:"Enabled"})]}),e.jsx(ao,{className:Mt("h-4 w-4 text-muted-foreground transition-transform",a&&"rotate-180")})]}),e.jsx(cy,{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(ne,{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(jn,{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(ne,{className:"text-sm font-medium",children:"Portal Visibility"}),e.jsxs(ib,{value:s.visibility,onValueChange:o=>l({visibility:o}),className:"grid grid-cols-2 gap-3",children:[e.jsxs("label",{className:Mt("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(Ld,{value:"private"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Gc,{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:Mt("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(Ld,{value:"public"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(lc,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"text-sm font-medium",children:"Public"})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Shareable link"})]})]})]})]}),e.jsxs("div",{className:"flex items-start gap-3 p-3 rounded-lg bg-muted/30",children:[e.jsx(hi,{id:"require_onboarding",checked:s.require_onboarding,onCheckedChange:o=>l({require_onboarding:!!o}),className:"mt-0.5"}),e.jsxs("div",{children:[e.jsx(ne,{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(hi,{id:"allow_spouse",checked:s.allow_spouse,onCheckedChange:o=>l({allow_spouse:!!o})}),e.jsx(ne,{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(ne,{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(ne,{className:"text-xs text-muted-foreground",children:"Client Full Name"}),e.jsx(ye,{value:s.client_name,onChange:o=>l({client_name:o.target.value}),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Email"}),e.jsx(ye,{type:"email",value:s.client_email,onChange:o=>l({client_email:o.target.value}),placeholder:"jane@example.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Phone"}),e.jsx(ye,{type:"tel",value:s.client_phone,onChange:o=>l({client_phone:o.target.value}),placeholder:"(555) 123-4567"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Preferred Invite Method"}),e.jsxs(us,{value:s.invite_method,onValueChange:o=>l({invite_method:o}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"email",children:"Email"}),e.jsxs(Ze,{value:"sms",disabled:!s.client_phone,children:["SMS ",!s.client_phone&&"(add phone first)"]})]})]})]})]})]})]})]})})]})})}const aQs=[{value:"buyer",label:"Buyer"},{value:"seller",label:"Seller"},{value:"dual",label:"Dual Agency"},{value:"referral",label:"Referral"},{value:"lease",label:"Lease"}],iQs=[{value:"low",label:"Low"},{value:"medium",label:"Medium"},{value:"high",label:"High"},{value:"urgent",label:"Urgent"}];function oQs({open:s,onOpenChange:t,deal:n,defaultStageId:r}){const{data:a}=$1e(),{data:i}=ax(),{data:l}=Pmt(),o=Cye(),c=Vjt(),d=Hjt(),u=QPe(),[h,p]=N.useState({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"}),[f,y]=N.useState(""),[_,v]=N.useState(!1),[j,w]=N.useState(!1),[S,A]=N.useState({first_name:"",last_name:"",email:"",phone:""}),E=(l==null?void 0:l.filter(Y=>((n==null?void 0:n.listing_id)===Y.id,!0)))||[],[O,D]=N.useState({deal_name:"",deal_type:"buyer",stage_id:"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",team_split_pct:"",referral_fee_pct:"",franchise_fee_pct:"",transaction_fee:"",commission_calc_method:"standard",target_close_date:void 0,contract_date:void 0,listing_date:void 0,priority:"medium",probability:"50",notes:""});N.useEffect(()=>{var Y,W,ee,se,oe,he,ce,me;s&&(n?(D({deal_name:n.deal_name,deal_type:n.deal_type,stage_id:n.stage_id||"",contact_id:n.contact_id||"",listing_id:n.listing_id||"",property_address:n.property_address||"",city:n.city||"",state:n.state||"",zip_code:n.zip_code||"",expected_price:((Y=n.expected_price)==null?void 0:Y.toString())||"",commission_percentage:((W=n.commission_percentage)==null?void 0:W.toString())||"3",brokerage_split_pct:((ee=n.brokerage_split_pct)==null?void 0:ee.toString())||"",team_split_pct:((se=n.team_split_pct)==null?void 0:se.toString())||"",referral_fee_pct:((oe=n.referral_fee_pct)==null?void 0:oe.toString())||"",franchise_fee_pct:((he=n.franchise_fee_pct)==null?void 0:he.toString())||"",transaction_fee:((ce=n.transaction_fee)==null?void 0:ce.toString())||"",commission_calc_method:n.commission_calc_method||"standard",target_close_date:n.target_close_date?Ll(n.target_close_date):void 0,contract_date:n.contract_date?Ll(n.contract_date):void 0,listing_date:n.listing_date?Ll(n.listing_date):void 0,priority:n.priority,probability:n.probability.toString(),notes:n.notes||""}),n.contact&&y(`${n.contact.first_name} ${n.contact.last_name}`)):(D({deal_name:"",deal_type:"buyer",stage_id:r||((me=a==null?void 0:a[0])==null?void 0:me.id)||"",contact_id:"",listing_id:"",property_address:"",city:"",state:"",zip_code:"",expected_price:"",commission_percentage:"3",brokerage_split_pct:"",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:""}),y(""),p({portal_enabled:!1,visibility:"private",require_onboarding:!0,allow_spouse:!1,client_name:"",client_email:"",client_phone:"",invite_method:"email"})))},[s,n,r,a]);const I=i==null?void 0:i.filter(Y=>{var ve,ge,Te,Ie,Ce;const W=f.toLowerCase().trim();if(!W)return!0;const ee=((ve=Y.first_name)==null?void 0:ve.toLowerCase())||"",se=((ge=Y.last_name)==null?void 0:ge.toLowerCase())||"",oe=((Te=Y.email)==null?void 0:Te.toLowerCase())||"",he=((Ce=(Ie=Y.phone)==null?void 0:Ie.toLowerCase)==null?void 0:Ce.call(Ie))||"",ce=`${ee} ${se}`.trim(),me=`${se} ${ee}`.trim();if(ce.includes(W)||me.includes(W)||ee.includes(W)||se.includes(W)||oe.includes(W)||he.includes(W))return!0;const le=W.split(/\s+/).filter(Boolean);return le.length>1?le.every(Me=>ee.includes(Me)||se.includes(Me)||oe.includes(Me)||he.includes(Me)):!1}).slice(0,8),F=()=>{const Y=parseFloat(O.expected_price)||0,W=parseFloat(O.commission_percentage)||0;return Y*(W/100)},z=()=>{const Y=F();if(!Y)return null;const W=parseFloat(O.brokerage_split_pct)||0,ee=parseFloat(O.team_split_pct)||0,se=parseFloat(O.referral_fee_pct)||0,oe=parseFloat(O.franchise_fee_pct)||0,he=parseFloat(O.transaction_fee)||0;if(O.commission_calc_method==="referral_first"){let me=Y;se&&(me-=Y*se/100);let le=me;return W&&(le-=me*W/100),ee&&(le-=Y*ee/100),oe&&(le-=Y*oe/100),he&&(le-=he),Math.max(0,le)}let ce=Y;return W&&(ce=ce*((100-W)/100)),ee&&(ce=ce*((100-ee)/100)),se&&(ce=ce-Y*se/100),oe&&(ce=ce-Y*oe/100),he&&(ce=ce-he),Math.max(0,ce)},H=async Y=>{var W,ee,se;if(Y.preventDefault(),!O.deal_name.trim()){ae.error("Please enter a deal name");return}try{const oe={deal_name:O.deal_name,deal_type:O.deal_type,stage_id:O.stage_id||null,contact_id:O.contact_id||null,listing_id:O.listing_id||null,property_address:O.property_address||null,city:O.city||null,state:O.state||null,zip_code:O.zip_code||null,expected_price:O.expected_price?parseFloat(O.expected_price):null,expected_commission:F()||null,commission_percentage:O.commission_percentage?parseFloat(O.commission_percentage):3,brokerage_split_pct:O.brokerage_split_pct?parseFloat(O.brokerage_split_pct):null,team_split_pct:O.team_split_pct?parseFloat(O.team_split_pct):null,referral_fee_pct:O.referral_fee_pct?parseFloat(O.referral_fee_pct):null,franchise_fee_pct:O.franchise_fee_pct?parseFloat(O.franchise_fee_pct):null,transaction_fee:O.transaction_fee?parseFloat(O.transaction_fee):null,commission_calc_method:O.commission_calc_method,target_close_date:((W=O.target_close_date)==null?void 0:W.toISOString().split("T")[0])||null,contract_date:((ee=O.contract_date)==null?void 0:ee.toISOString().split("T")[0])||null,listing_date:((se=O.listing_date)==null?void 0:se.toISOString().split("T")[0])||null,priority:O.priority,probability:parseInt(O.probability)||50,notes:O.notes||null};if(n)await d.mutateAsync({id:n.id,...oe}),ae.success("Deal updated successfully");else{const he=await c.mutateAsync(oe);if(ae.success("Deal created successfully"),h.portal_enabled&&(he!=null&&he.id))try{await u.mutateAsync({deal_id:he.id,visibility:h.visibility,require_onboarding:h.require_onboarding,allow_spouse:h.allow_spouse,client_name:h.client_name||null,client_email:h.client_email||null,client_phone:h.client_phone||null,invite_method:h.invite_method}),ae.success("Client portal created!")}catch{ae.error("Deal created, but portal setup failed")}}t(!1)}catch{ae.error("Failed to save deal")}},Z=c.isPending||d.isPending;return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:n?"Edit Deal":"Add New Deal"}),e.jsx(Jn,{children:n?"Update the deal details below.":"Enter the details for your new deal."})]}),e.jsxs("form",{onSubmit:H,className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(ne,{htmlFor:"deal_name",children:"Deal Name *"}),e.jsx(ye,{id:"deal_name",value:O.deal_name,onChange:Y=>D(W=>({...W,deal_name:Y.target.value})),placeholder:"e.g., Smith Family - 123 Main St"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Deal Type"}),e.jsxs(us,{value:O.deal_type,onValueChange:Y=>D(W=>({...W,deal_type:Y})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:aQs.map(Y=>e.jsx(Ze,{value:Y.value,children:Y.label},Y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Stage"}),e.jsxs(us,{value:O.stage_id||"none",onValueChange:Y=>D(W=>({...W,stage_id:Y==="none"?"":Y})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select stage"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No Stage"}),a==null?void 0:a.map(Y=>e.jsx(Ze,{value:Y.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-2 h-2 rounded-full",style:{backgroundColor:Y.color}}),Y.name]})},Y.id))]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Link to Contact"}),e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:f,onChange:Y=>{y(Y.target.value),v(!0),w(!1),Y.target.value||D(W=>({...W,contact_id:""}))},onFocus:()=>v(!0),placeholder:"Search contacts...",className:"pl-9"}),_&&f&&e.jsxs("div",{className:"absolute z-10 w-full mt-1 bg-background border rounded-lg shadow-lg max-h-60 overflow-y-auto",children:[I&&I.length>0?I.map(Y=>e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2",onClick:()=>{D(W=>({...W,contact_id:Y.id})),y(`${Y.first_name} ${Y.last_name}`),v(!1)},children:[e.jsx(Wi,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:[Y.first_name," ",Y.last_name]}),Y.email&&e.jsx("span",{className:"text-xs text-muted-foreground ml-auto",children:Y.email})]},Y.id)):e.jsx("div",{className:"px-3 py-2 text-sm text-muted-foreground",children:"No contacts found"}),e.jsxs("button",{type:"button",className:"w-full px-3 py-2 text-left hover:bg-muted flex items-center gap-2 border-t text-primary font-medium",onClick:()=>{const Y=f.trim().split(/\s+/);A({first_name:Y[0]||"",last_name:Y.slice(1).join(" ")||"",email:"",phone:""}),w(!0),v(!1)},children:[e.jsx(Fo,{className:"h-4 w-4"}),e.jsxs("span",{children:['Create new contact "',f.trim(),'"']})]})]})]}),j&&e.jsxs("div",{className:"border rounded-lg p-3 space-y-3 bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm font-medium flex items-center gap-1.5",children:[e.jsx(Fo,{className:"h-3.5 w-3.5"}),"Quick Add Contact"]}),e.jsx(B,{type:"button",variant:"ghost",size:"sm",className:"h-6 px-2 text-xs",onClick:()=>w(!1),children:"Cancel"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{placeholder:"First name *",value:S.first_name,onChange:Y=>A(W=>({...W,first_name:Y.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Last name",value:S.last_name,onChange:Y=>A(W=>({...W,last_name:Y.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Email",type:"email",value:S.email,onChange:Y=>A(W=>({...W,email:Y.target.value})),className:"h-8 text-sm"}),e.jsx(ye,{placeholder:"Phone",type:"tel",value:S.phone,onChange:Y=>A(W=>({...W,phone:Y.target.value})),className:"h-8 text-sm"})]}),e.jsx(B,{type:"button",size:"sm",className:"w-full h-8",disabled:!S.first_name.trim()||o.isPending,onClick:async()=>{try{const Y=await o.mutateAsync({first_name:S.first_name.trim(),last_name:S.last_name.trim()||null,email:S.email.trim()||null,phone:S.phone.trim()||null});Y&&(D(W=>({...W,contact_id:Y.id})),y(`${Y.first_name} ${Y.last_name||""}`.trim()),w(!1))}catch{}},children:o.isPending?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-3.5 w-3.5 mr-1 animate-spin"})," Creating..."]}):e.jsxs(e.Fragment,{children:[e.jsx(Fo,{className:"h-3.5 w-3.5 mr-1"})," Add & Link Contact"]})})]})]}),E.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"flex items-center gap-2",children:[e.jsx(Tl,{className:"h-4 w-4"}),"Link to Listing Exchange"]}),e.jsxs(us,{value:O.listing_id||"none",onValueChange:Y=>{const W=Y==="none"?"":Y,ee=E.find(se=>se.id===W);D(ee?se=>{var oe;return{...se,listing_id:W,deal_type:"seller",property_address:ee.property_address||se.property_address,city:ee.city||se.city,state:ee.state||se.state,expected_price:((oe=ee.price)==null?void 0:oe.toString())||se.expected_price}}:se=>({...se,listing_id:W}))},children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a listing to sync status..."})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"None"}),E.map(Y=>e.jsx(Ze,{value:Y.id,children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{children:Y.property_address||`${Y.city}, ${Y.state}`}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:["$",(Y.price/1e3).toFixed(0),"K"]})]})},Y.id))]})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Status changes will sync automatically between the deal and listing."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Property Details"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"col-span-2 space-y-2",children:[e.jsx(ne,{htmlFor:"property_address",children:"Address"}),e.jsx(ye,{id:"property_address",value:O.property_address,onChange:Y=>D(W=>({...W,property_address:Y.target.value})),placeholder:"123 Main Street"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:O.city,onChange:Y=>D(W=>({...W,city:Y.target.value}))})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:O.state,onChange:Y=>D(W=>({...W,state:Y.target.value})),maxLength:2,placeholder:"TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"zip_code",children:"ZIP"}),e.jsx(ye,{id:"zip_code",value:O.zip_code,onChange:Y=>D(W=>({...W,zip_code:Y.target.value}))})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Financial Details"}),e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"expected_price",children:"Expected Price"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"$"}),e.jsx(ye,{id:"expected_price",type:"number",value:O.expected_price,onChange:Y=>D(W=>({...W,expected_price:Y.target.value})),className:"pl-7",placeholder:"500000"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"commission_percentage",children:"Commission %"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{id:"commission_percentage",type:"number",step:"0.1",value:O.commission_percentage,onChange:Y=>D(W=>({...W,commission_percentage:Y.target.value})),className:"pr-7"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Expected GCI"}),e.jsx(ye,{value:F()?`$${F().toLocaleString()}`:"-",disabled:!0,className:"bg-muted"})]})]}),e.jsxs("details",{className:"group",children:[e.jsxs("summary",{className:"text-xs font-medium text-muted-foreground cursor-pointer hover:text-foreground flex items-center gap-1 py-1",children:[e.jsx("span",{className:"group-open:rotate-90 transition-transform text-[10px]",children:"▶"}),"Commission Splits (optional)"]}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg bg-muted/50",children:[e.jsx(ne,{className:"text-xs whitespace-nowrap",children:"Calculation Method:"}),e.jsxs(us,{value:O.commission_calc_method,onValueChange:Y=>D(W=>({...W,commission_calc_method:Y})),children:[e.jsx(ls,{className:"h-7 text-xs",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"standard",children:"Standard (all splits on GCI)"}),e.jsx(Ze,{value:"referral_first",children:"Referral First (brokerage split after referral)"})]})]})]}),O.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(ne,{className:"text-xs",children:"Brokerage Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",step:"1",min:"0",max:"100",value:O.brokerage_split_pct,onChange:Y=>D(W=>({...W,brokerage_split_pct:Y.target.value})),className:"pr-7 h-8 text-sm",placeholder:"30"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"% that goes to brokerage"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Team Split"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",step:"1",min:"0",max:"100",value:O.team_split_pct,onChange:Y=>D(W=>({...W,team_split_pct:Y.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"% that goes to team lead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Referral Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",step:"1",min:"0",max:"100",value:O.referral_fee_pct,onChange:Y=>D(W=>({...W,referral_fee_pct:Y.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Franchise Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",step:"1",min:"0",max:"100",value:O.franchise_fee_pct,onChange:Y=>D(W=>({...W,franchise_fee_pct:Y.target.value})),className:"pr-7 h-8 text-sm",placeholder:"0"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"%"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Transaction Fee"}),e.jsxs("div",{className:"relative",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground text-xs",children:"$"}),e.jsx(ye,{type:"number",step:"1",min:"0",value:O.transaction_fee,onChange:Y=>D(W=>({...W,transaction_fee:Y.target.value})),className:"pl-7 h-8 text-sm",placeholder:"500"})]}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Flat fee deducted"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Net to Agent"}),e.jsx(ye,{value:z()?`$${Math.round(z()).toLocaleString()}`:"-",disabled:!0,className:"bg-muted h-8 text-sm font-semibold"})]})]})]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Dates & Status"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Target Close Date"}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!O.target_close_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),O.target_close_date?Ss(O.target_close_date,"PPP"):"Pick a date"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:O.target_close_date,onSelect:Y=>D(W=>({...W,target_close_date:Y})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Contract Date"}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!O.contract_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),O.contract_date?Ss(O.contract_date,"PPP"):"Pick a date"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:O.contract_date,onSelect:Y=>D(W=>({...W,contract_date:Y})),initialFocus:!0,className:"pointer-events-auto"})})]})]}),(O.deal_type==="seller"||O.deal_type==="dual")&&!O.listing_id&&e.jsxs("div",{className:"space-y-2 col-span-2",children:[e.jsx(ne,{children:"Listing Date (for Days on Market)"}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!O.listing_date&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),O.listing_date?Ss(O.listing_date,"PPP"):"Pick a date"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:O.listing_date,onSelect:Y=>D(W=>({...W,listing_date:Y})),initialFocus:!0,className:"pointer-events-auto"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Used to calculate Days on Market. Auto-filled for linked listings."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Priority"}),e.jsxs(us,{value:O.priority,onValueChange:Y=>D(W=>({...W,priority:Y})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:iQs.map(Y=>e.jsx(Ze,{value:Y.value,children:Y.label},Y.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Win Probability"}),e.jsxs("div",{className:"relative",children:[e.jsx(ye,{type:"number",min:"0",max:"100",value:O.probability,onChange:Y=>D(W=>({...W,probability:Y.target.value})),className:"pr-7"}),e.jsx("span",{className:"absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground",children:"%"})]})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"notes",children:"Notes"}),e.jsx(Ms,{id:"notes",value:O.notes,onChange:Y=>D(W=>({...W,notes:Y.target.value})),placeholder:"Add any additional notes about this deal...",rows:3})]}),!n&&e.jsx(rQs,{formData:h,onChange:p}),e.jsxs("div",{className:"flex justify-end gap-3 pt-4 border-t",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{type:"submit",disabled:Z,children:[Z&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),n?"Update Deal":"Create Deal"]})]})]})]})})}function lQs({dealId:s}){const t=wa(),n=Kt(),[r,a]=N.useState(""),[i,l]=N.useState(!1),{data:o=[]}=dt({queryKey:["deal-tags",s],queryFn:async()=>{const{data:y,error:_}=await q.from("deal_tags").select("*").eq("deal_id",s).order("created_at");if(_)throw _;return y},enabled:!!s}),{data:c=[]}=dt({queryKey:["all-deal-tags",t],queryFn:async()=>{if(!t)return[];const{data:y,error:_}=await q.from("deal_tags").select("tag").eq("owner_user_id",t);if(_)throw _;return[...new Set(y.map(j=>j.tag))].sort()},enabled:!!t}),d=yt({mutationFn:async y=>{if(!t)throw new Error("Not authenticated");const{error:_}=await q.from("deal_tags").insert({deal_id:s,owner_user_id:t,tag:y.trim()});if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]}),n.invalidateQueries({queryKey:["all-deal-tags"]}),a("")}}),u=yt({mutationFn:async y=>{const{error:_}=await q.from("deal_tags").delete().eq("id",y);if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["deal-tags",s]})}}),h=()=>{const y=r.trim();y&&(o.some(_=>_.tag.toLowerCase()===y.toLowerCase())||d.mutate(y))},p=o.map(y=>y.tag.toLowerCase()),f=c.filter(y=>y.toLowerCase().includes(r.toLowerCase())&&!p.includes(y.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(y=>e.jsxs(Ue,{variant:"secondary",className:"gap-1 text-xs",children:[y.tag,e.jsx("button",{type:"button",onClick:()=>u.mutate(y.id),className:"ml-0.5 hover:text-destructive",children:e.jsx($n,{className:"h-3 w-3"})})]},y.id)),!i&&e.jsxs("button",{type:"button",onClick:()=>l(!0),className:"flex items-center gap-1 text-xs text-muted-foreground hover:text-foreground px-2 py-0.5 rounded border border-dashed border-border hover:border-primary transition-colors",children:[e.jsx(Is,{className:"h-3 w-3"})," Add tag"]})]}),i&&e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"flex gap-1.5",children:[e.jsx(ye,{value:r,onChange:y=>a(y.target.value),onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),h()),y.key==="Escape"&&(l(!1),a(""))},placeholder:"Type tag name...",className:"h-8 text-xs flex-1",autoFocus:!0}),e.jsx("button",{type:"button",onClick:h,disabled:!r.trim()||d.isPending,className:"h-8 px-3 rounded-md bg-primary text-primary-foreground text-xs font-medium disabled:opacity-50 shrink-0",children:"Add"}),e.jsx("button",{type:"button",onClick:()=>{l(!1),a("")},className:"h-8 px-2 rounded-md bg-muted text-muted-foreground text-xs shrink-0",children:"Cancel"})]}),r&&f.length>0&&e.jsx("div",{className:"absolute z-20 w-full mt-1 bg-background border rounded shadow-lg max-h-32 overflow-y-auto",children:f.map(y=>e.jsx("button",{type:"button",className:"w-full px-3 py-2 text-left text-xs hover:bg-muted active:bg-muted",onClick:_=>{_.preventDefault(),d.mutate(y)},children:y},y))})]})]})}function cQs(s){return dt({queryKey:["deal-files",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_files").select("*").eq("deal_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function dQs(){const s=wa(),t=Kt();return yt({mutationFn:async({dealId:n,file:r})=>{if(!s)throw new Error("Not authenticated");const a=r.name.split(".").pop(),i=`${s}/${n}/${crypto.randomUUID()}.${a}`,{error:l}=await q.storage.from("deal-files").upload(i,r);if(l)throw l;const{data:o,error:c}=await q.from("deal_files").insert({deal_id:n,owner_user_id:s,file_name:r.name,file_size:r.size,file_type:r.type||null,storage_path:i}).select().single();if(c)throw c;return o},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["deal-files",r.dealId]})}})}function uQs(){const s=Kt();return yt({mutationFn:async({fileId:t,storagePath:n,dealId:r})=>{await q.storage.from("deal-files").remove([n]);const{error:a}=await q.from("deal_files").delete().eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}function hQs(){const s=Kt();return yt({mutationFn:async({fileId:t,visible:n,dealId:r})=>{const{error:a}=await q.from("deal_files").update({visible_on_portal:n}).eq("id",t);if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["deal-files",t]})}})}async function mQs(s){const{data:t,error:n}=await q.storage.from("deal-files").createSignedUrl(s,3600);if(n)throw n;return t.signedUrl}const OQe={text:"Short Text",textarea:"Long Text",dropdown:"Dropdown",toggle:"Yes / No"};function Qjt({open:s,onOpenChange:t}){const{data:n,isLoading:r}=zGs(),a=BGs(),i=$Gs(),l=UGs(),[o,c]=N.useState(!1),[d,u]=N.useState({question_text:"",field_type:"text",options:[],is_required:!1}),[h,p]=N.useState(""),f=async()=>{if(d.question_text.trim())try{await a.mutateAsync({question_text:d.question_text.trim(),field_type:d.field_type,options:d.field_type==="dropdown"?d.options:[],is_required:d.is_required,sort_order:((n==null?void 0:n.length)||0)+1}),u({question_text:"",field_type:"text",options:[],is_required:!1}),p(""),c(!1),ae.success("Question added")}catch{ae.error("Failed to add question")}},y=async w=>{try{await l.mutateAsync(w),ae.success("Question removed")}catch{ae.error("Failed to remove question")}},_=async(w,S)=>{try{await i.mutateAsync({id:w,is_required:S})}catch{ae.error("Failed to update question")}},v=()=>{h.trim()&&(u(w=>({...w,options:[...w.options,h.trim()]})),p(""))},j=w=>{u(S=>({...S,options:S.options.filter((A,E)=>E!==w)}))};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-md max-h-[85vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsx(ws,{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(di,{className:"flex-1",children:e.jsxs("div",{className:"space-y-3 pr-2",children:[r&&e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})}),n==null?void 0:n.map(w=>{var S;return e.jsx("div",{className:"border rounded-lg p-3 space-y-2",children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Pu,{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:w.question_text}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ue,{variant:"secondary",className:"text-xs",children:OQe[w.field_type]||w.field_type}),w.is_required&&e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Required"})]}),w.field_type==="dropdown"&&((S=w.options)==null?void 0:S.length)>0&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Options: ",w.options.join(", ")]})]}),e.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[e.jsx(jn,{checked:w.is_required,onCheckedChange:A=>_(w.id,A),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:()=>y(w.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})},w.id)}),!r&&(n==null?void 0:n.length)===0&&!o&&e.jsxs("div",{className:"text-center py-8 border border-dashed rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"No custom questions yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add questions that clients will answer during onboarding."})]}),o&&e.jsxs("div",{className:"border-2 border-primary/20 rounded-lg p-4 space-y-3 bg-primary/5",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Question"}),e.jsx(ye,{value:d.question_text,onChange:w=>u(S=>({...S,question_text:w.target.value})),className:"mt-1",placeholder:"e.g., Do you have a home to sell first?",autoFocus:!0})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Answer Type"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(OQe).map(([w,S])=>e.jsx("button",{type:"button",onClick:()=>u(A=>({...A,field_type:w,options:[]})),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${d.field_type===w?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:S},w))})]}),d.field_type==="dropdown"&&e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Options"}),e.jsxs("div",{className:"space-y-1.5 mt-1.5",children:[d.options.map((w,S)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"flex-1 text-sm bg-muted/50 rounded px-2 py-1",children:w}),e.jsx("button",{onClick:()=>j(S),className:"text-muted-foreground hover:text-destructive",children:e.jsx($n,{className:"h-3.5 w-3.5"})})]},S)),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:h,onChange:w=>p(w.target.value),onKeyDown:w=>w.key==="Enter"&&(w.preventDefault(),v()),placeholder:"Add option...",className:"h-8 text-sm"}),e.jsx(B,{variant:"outline",size:"sm",onClick:v,disabled:!h.trim(),className:"h-8",children:e.jsx(Is,{className:"h-3 w-3"})})]})]})]}),e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:d.is_required,onCheckedChange:w=>u(S=>({...S,is_required:w}))}),e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Required"})]})}),e.jsxs("div",{className:"flex gap-2 pt-1",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>c(!1),className:"flex-1",children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:f,disabled:!d.question_text.trim()||a.isPending,className:"flex-1",children:[a.isPending?e.jsx(rs,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Add Question"]})]})]})]})}),e.jsxs("div",{className:"flex justify-between pt-4 border-t shrink-0",children:[o?e.jsx("div",{}):e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Question"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t(!1),children:"Done"})]})]})})}function pQs({override:s,onChange:t}){const n=wa(),{data:r}=mht(),[a,i]=N.useState(null),l=d=>t({...s,...d}),o=async(d,u)=>{if(n){if(d.size>5*1024*1024){ae.error("Image must be under 5MB");return}i(u);try{const h=await pht(n,d,`${u}`);l(u==="logo"?{logo_url:h}:{cover_photo_url:h})}catch(h){ae.error(`Upload failed: ${h.message||h}`)}finally{i(null)}}},c=Object.values(s||{}).some(d=>d!=null&&d!=="");return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-2 p-3 rounded-md bg-primary/5 border border-primary/10",children:[e.jsx(un,{className:"h-4 w-4 text-primary shrink-0 mt-0.5"}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["These settings ",e.jsx("span",{className:"font-medium text-foreground",children:"override your global Portal Branding"})," for this deal only. Leave any field empty to use your global default."]})]}),e.jsx(FQe,{label:"Logo",value:s.logo_url??null,globalValue:(r==null?void 0:r.logo_url)??null,uploading:a==="logo",onUpload:d=>o(d,"logo"),onClear:()=>l({logo_url:null}),aspect:"square"}),e.jsx(FQe,{label:"Cover Photo",value:s.cover_photo_url??null,globalValue:(r==null?void 0:r.cover_photo_url)??null,uploading:a==="cover",onUpload:d=>o(d,"cover"),onClear:()=>l({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(zQe,{label:"Brand Color",value:s.brand_color??null,globalValue:(r==null?void 0:r.brand_color)??null,onChange:d=>l({brand_color:d})}),e.jsx(zQe,{label:"Accent Color",value:s.accent_color??null,globalValue:(r==null?void 0:r.accent_color)??null,onChange:d=>l({accent_color:d})})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Tagline"}),e.jsx(ye,{value:s.tagline||"",onChange:d=>l({tagline:d.target.value||null}),placeholder:(r==null?void 0:r.tagline)||"Your trusted real estate advisor",maxLength:80,className:"mt-1"})]}),c&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t({}),className:"text-xs text-muted-foreground hover:text-destructive",children:[e.jsx(_n,{className:"h-3 w-3 mr-1"}),"Clear all overrides"]})]})}function FQe({label:s,value:t,globalValue:n,uploading:r,onUpload:a,onClear:i,aspect:l}){const o=t||n,c=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:s}),c?e.jsx("span",{className:"text-[10px] font-medium text-primary",children:"Overridden"}):n?e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Using global"}):null]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Mt("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(Xo,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:d=>{var h;const u=(h=d.target.files)==null?void 0:h[0];u&&a(u),d.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[r?e.jsx(rs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(_a,{className:"h-3.5 w-3.5"}),t?"Replace":"Override"]})]}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]})}function zQe({label:s,value:t,globalValue:n,onChange:r}){const a=t||n||"#000000",i=!!t;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{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:Mt("mt-1 flex items-center gap-2 h-9 rounded-md border bg-background px-2",i?"border-primary":"border-input"),children:[e.jsx("input",{type:"color",value:a,onChange:l=>r(l.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(ye,{value:t||"",onChange:l=>r(l.target.value||null),placeholder:n||"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"}),t&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(null),className:"h-6 w-6 p-0 text-muted-foreground hover:text-destructive",children:e.jsx(_n,{className:"h-3 w-3"})})]})]})}function fQs({portalId:s,agentUserId:t}){const n=Kt(),{data:r,isLoading:a}=dt({queryKey:["portal-vendor-manage",s,t],queryFn:async()=>{const{data:h}=await q.from("profiles").select("brokerage_id").eq("id",t).maybeSingle(),p=h==null?void 0:h.brokerage_id,f=q.from("vendors").select("*").eq("is_active",!0),y=p?f.or(`and(owner_type.eq.agent,owner_user_id.eq.${t}),and(owner_type.eq.brokerage,owner_brokerage_id.eq.${p})`):f.eq("owner_type","agent").eq("owner_user_id",t),[{data:_,error:v},{data:j},{data:w}]=await Promise.all([y.order("sort_order",{ascending:!0}).order("name",{ascending:!0}),q.from("agent_vendor_selections").select("vendor_id, is_visible").eq("agent_user_id",t),q.from("portal_vendor_overrides").select("vendor_id, is_visible").eq("portal_id",s)]);if(v)throw v;const S=new Map;(j||[]).forEach(E=>S.set(E.vendor_id,E.is_visible));const A=new Map;return(w||[]).forEach(E=>A.set(E.vendor_id,E.is_visible)),{vendors:_||[],selMap:S,overrideMap:A}}}),i=yt({mutationFn:async({vendorId:h,isVisible:p})=>{const{data:f}=await q.from("portal_vendor_overrides").select("id").eq("portal_id",s).eq("vendor_id",h).maybeSingle();if(f){const{error:y}=await q.from("portal_vendor_overrides").update({is_visible:p}).eq("id",f.id);if(y)throw y}else{const{error:y}=await q.from("portal_vendor_overrides").insert({portal_id:s,vendor_id:h,is_visible:p});if(y)throw y}},onSuccess:()=>{n.invalidateQueries({queryKey:["portal-vendor-manage",s,t]}),n.invalidateQueries({queryKey:["portal-vendors",s]})},onError:h=>ae.error(h.message)});if(a)return e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(rs,{className:"w-5 h-5 animate-spin text-muted-foreground"})});const l=(r==null?void 0:r.vendors)||[],o=(r==null?void 0:r.selMap)||new Map,c=(r==null?void 0:r.overrideMap)||new Map;if(l.length===0)return e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-xl",children:[e.jsx(pw,{className:"w-10 h-10 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors in your library yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Add vendors in the Vendors tab of Client Portals, then toggle them here per portal."})]});const d=h=>{const p=c.get(h.id);if(p!==void 0)return p;if(h.is_required)return!0;const f=o.get(h.id);return f===void 0?!0:f!==!1},u=h=>{var p;return((p=$D.find(f=>f.value===h))==null?void 0:p.label)||h};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Choose which vendors from your library appear in ",e.jsx("em",{children:"this specific portal"}),". Changes here only affect this deal — your global vendor library and other portals are unaffected."]}),e.jsx(di,{className:"h-[400px] rounded-lg border",children:e.jsx("div",{className:"divide-y",children:l.map(h=>{const p=d(h);return e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-muted border flex items-center justify-center overflow-hidden shrink-0",children:h.logo_url?e.jsx("img",{src:h.logo_url,alt:h.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-sm font-semibold text-muted-foreground",children:h.name.charAt(0)})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:h.company||h.name}),e.jsx(Ue,{variant:"outline",className:"text-[10px] shrink-0",children:u(h.category)}),h.owner_type==="brokerage"&&e.jsx(Ue,{variant:"secondary",className:"text-[10px] shrink-0",children:"Brokerage"}),h.is_required&&e.jsx(Ue,{className:"text-[10px] shrink-0",children:"Required"})]}),h.company&&h.name&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:h.name})]}),e.jsx(jn,{checked:p,disabled:h.is_required||i.isPending,onCheckedChange:f=>i.mutate({vendorId:h.id,isVisible:f})})]},h.id)})})})]})}function xQs({portalId:s,ownerId:t,clientEmail:n,linkedPortalId:r,onLink:a}){const[i,l]=N.useState(""),[o,c]=N.useState(!1),{data:d,isLoading:u}=dt({queryKey:["all-owner-portals",t],queryFn:async()=>{const{data:y,error:_}=await q.from("client_portals").select(` id, slug, client_name, client_email, deal_id, archived_at, deal_pipeline (id, deal_name, deal_type, property_address) `).eq("owner_user_id",t).neq("id",s).is("archived_at",null).eq("is_enabled",!0);if(_)throw _;return y},enabled:o||!!r}),h=N.useMemo(()=>!r||!d?null:d.find(y=>y.id===r),[r,d]),p=N.useMemo(()=>!d||!n?[]:d.filter(y=>{var _;return((_=y.client_email)==null?void 0:_.toLowerCase())===n.toLowerCase()&&y.id!==s}),[d,n,s]),f=N.useMemo(()=>{if(!d||!i.trim())return[];const y=i.toLowerCase();return d.filter(_=>{var j,w,S,A;const v=_.deal_pipeline;return((j=_.client_name)==null?void 0:j.toLowerCase().includes(y))||((w=_.client_email)==null?void 0:w.toLowerCase().includes(y))||((S=v==null?void 0:v.deal_name)==null?void 0:S.toLowerCase().includes(y))||((A=v==null?void 0:v.property_address)==null?void 0:A.toLowerCase().includes(y))})},[d,i]);if(r){const y=h==null?void 0:h.deal_pipeline;return e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{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:(h==null?void 0:h.client_name)||(y==null?void 0:y.deal_name)||"Linked Portal"}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[(y==null?void 0:y.deal_type)==="listing"?"🏠 Listing":"🔑 Purchase"," · ",(y==null?void 0:y.property_address)||"No address"]})]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive shrink-0",onClick:()=>a(null),children:[e.jsx(OA,{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(ne,{className:"text-sm font-medium",children:"Link Another Transaction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Combine buy + sell into one portal"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"text-xs",onClick:()=>c(!o),children:[e.jsx(Tl,{className:"h-3 w-3 mr-1"}),o?"Cancel":"Link"]})]}),!o&&p.length>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("p",{className:"text-[11px] text-muted-foreground font-medium",children:"✨ Suggested match (same client email)"}),p.map(y=>{const _=y.deal_pipeline;return e.jsxs("button",{onClick:()=>a(y.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(Ue,{variant:"outline",className:"text-[10px] shrink-0 bg-amber-100 border-amber-300 text-amber-700",children:(_==null?void 0:_.deal_type)==="listing"?"Listing":"Purchase"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:(_==null?void 0:_.deal_name)||y.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:_==null?void 0:_.property_address})]}),e.jsx(Tl,{className:"h-3.5 w-3.5 text-amber-600 shrink-0"})]},y.id)})]}),o&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-2.5 top-1/2 -translate-y-1/2 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{value:i,onChange:y=>l(y.target.value),placeholder:"Search by name, email, or address...",className:"pl-8 h-8 text-xs",autoFocus:!0})]}),u&&e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(rs,{className:"h-4 w-4 animate-spin text-muted-foreground"})}),f.length>0&&e.jsx("div",{className:"space-y-1 max-h-[200px] overflow-y-auto",children:f.map(y=>{const _=y.deal_pipeline;return e.jsxs("button",{onClick:()=>{a(y.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(Ue,{variant:"outline",className:"text-[10px] shrink-0",children:(_==null?void 0:_.deal_type)==="listing"?"Listing":"Purchase"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-xs font-medium truncate",children:(_==null?void 0:_.deal_name)||y.client_name}),e.jsx("p",{className:"text-[11px] text-muted-foreground truncate",children:y.client_email})]})]},y.id)})}),i&&f.length===0&&!u&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-3",children:"No portals found"})]})]})}function XLe({contactId:s,onVideoReady:t}){const[n,r]=N.useState(!1),[a,i]=N.useState("record"),[l,o]=N.useState(0),[c,d]=N.useState(0),u=CN(),h=()=>{i("record"),o(0),d(0)},p=y=>{!y&&(a==="uploading"||a==="processing")||(r(y),y||h())},f=N.useCallback(async(y,_)=>{i("uploading");try{const v="Card Video",{videoId:j,libraryId:w}=await t6(v),{uploadUrl:S,apiKey:A}=await s6(j),E=new XMLHttpRequest;E.upload.onprogress=Z=>{Z.lengthComputable&&o(Z.loaded/Z.total*100)},await new Promise((Z,Y)=>{E.onload=()=>E.status>=200&&E.status<300?Z():Y(new Error("Upload failed")),E.onerror=()=>Y(new Error("Upload failed")),E.open("PUT",S),E.setRequestHeader("AccessKey",A),E.send(y)}),i("processing");let O=0;const D=Date.now(),I=9e4,F=`https://iframe.mediadelivery.net/embed/${w}/${j}`;for(;O<4;){if(await new Promise(Y=>setTimeout(Y,3e3)),Date.now()-D>I){const Y=y.size/1048576;await u.mutateAsync({bunny_video_id:j,playback_url:`https://iframe.mediadelivery.net/play/${w}/${j}`,file_size_mb:Y,title:v,contact_id:s||void 0,status:"processing",touch_type:"video"}),t(F),ae.success("Video saved — still encoding. It will be ready shortly."),i("done"),setTimeout(()=>{r(!1),h()},1500);return}const Z=await Fw(j);if(O=Z.status,d(Z.encodeProgress||0),O===5||O===6)throw new Error("Video processing failed")}const z=await Fw(j),H=(z.storageSize||y.size)/(1024*1024);await u.mutateAsync({bunny_video_id:j,contact_id:s||void 0,playback_url:z.directPlayUrl||F,thumbnail_url:z.thumbnailUrl,preview_url:z.previewUrl||null,duration_seconds:z.length||_,file_size_mb:H,title:v,status:"ready",touch_type:"video"}),t(F),ae.success("Video recorded & added to your library!"),i("done"),setTimeout(()=>{r(!1),h()},1500)}catch(v){console.error("Recording upload error:",v),ae.error("Failed to process video. Please try again."),i("record")}},[s,t,u]);return e.jsxs(_s,{open:n,onOpenChange:p,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 w-full",children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),"Record Video"]})}),e.jsxs(bs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Record a Video for Your Card"})}),a==="record"&&e.jsx(i6,{maxDurationSeconds:600,onRecordingComplete:f,onError:y=>ae.error(y)}),a==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(rs,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(fi,{value:l,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(l),"%"]})]}),a==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(rs,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(fi,{value:c,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(c),"%"]})]}),a==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Pi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your card!"})]})]})]})}const gQs=s=>`portal-settings-draft:${s}`;function JLe({open:s,onOpenChange:t,portal:n,dealOwnerId:r}){const a=xR(),[i,l]=N.useState(!1),o=N.useMemo(()=>gQs(n.id),[n.id]),[c,d]=N.useState(!1),[u,h]=N.useState(n.next_step_text||""),[p,f]=N.useState(n.next_step_video_url||""),[y,_]=N.useState(n.inspection_date||""),[v,j]=N.useState(n.appraisal_date||""),[w,S]=N.useState(n.welcome_message||""),[A,E]=N.useState(n.review_url||""),[O,D]=N.useState(n.show_post_close_tips),[I,F]=N.useState(n.notify_client),[z,H]=N.useState(n.require_onboarding),[Z,Y]=N.useState(n.allow_spouse),[W,ee]=N.useState(n.visibility),[se,oe]=N.useState(n.stage_mapping||[]),[he,ce]=N.useState(null),[me,le]=N.useState(n.linked_portal_id||null),[ve,ge]=N.useState(n.referral_enabled??!0),[Te,Ie]=N.useState(n.referral_reward_text||""),[Ce,Me]=N.useState(n.referral_cta_headline||""),[Pe,Re]=N.useState(n.homeowner_hub_video_url||""),[Ae,Be]=N.useState(n.branding_override||{}),we=()=>{h(n.next_step_text||""),f(n.next_step_video_url||""),_(n.inspection_date||""),j(n.appraisal_date||""),S(n.welcome_message||""),E(n.review_url||""),D(n.show_post_close_tips),F(n.notify_client),H(n.require_onboarding),Y(n.allow_spouse),ee(n.visibility),oe(n.stage_mapping||[]),le(n.linked_portal_id||null),ge(n.referral_enabled??!0),Ie(n.referral_reward_text||""),Me(n.referral_cta_headline||""),Re(n.homeowner_hub_video_url||""),Be(n.branding_override||{})};N.useEffect(()=>{d(!1);const Ke=localStorage.getItem(o);if(Ke)try{const Ge=JSON.parse(Ke);h(Ge.nextStepText||""),f(Ge.nextStepVideo||""),_(Ge.inspectionDate||""),j(Ge.appraisalDate||""),S(Ge.welcomeMessage||""),E(Ge.reviewUrl||""),D(!!Ge.showPostClose),F(!!Ge.notifyClient),H(!!Ge.requireOnboarding),Y(!!Ge.allowSpouse),ee(Ge.visibility||n.visibility),oe(Ge.stageMapping||[]),le(Ge.linkedPortalId??null),ge(Ge.referralEnabled??!0),Ie(Ge.referralRewardText||""),Me(Ge.referralCtaHeadline||""),Re(Ge.homeownerHubVideoUrl||""),Be(Ge.brandingOverride||{}),d(!0);return}catch{localStorage.removeItem(o)}we(),d(!0)},[o,n]),N.useEffect(()=>{if(!c)return;const Ke={nextStepText:u,nextStepVideo:p,inspectionDate:y,appraisalDate:v,welcomeMessage:w,reviewUrl:A,showPostClose:O,notifyClient:I,requireOnboarding:z,allowSpouse:Z,visibility:W,stageMapping:se,linkedPortalId:me,referralEnabled:ve,referralRewardText:Te,referralCtaHeadline:Ce,homeownerHubVideoUrl:Pe,brandingOverride:Ae};u!==(n.next_step_text||"")||p!==(n.next_step_video_url||"")||y!==(n.inspection_date||"")||v!==(n.appraisal_date||"")||w!==(n.welcome_message||"")||A!==(n.review_url||"")||O!==n.show_post_close_tips||I!==n.notify_client||z!==n.require_onboarding||Z!==n.allow_spouse||W!==n.visibility||JSON.stringify(se)!==JSON.stringify(n.stage_mapping||[])||me!==(n.linked_portal_id||null)||ve!==(n.referral_enabled??!0)||Te!==(n.referral_reward_text||"")||Ce!==(n.referral_cta_headline||"")||Pe!==(n.homeowner_hub_video_url||"")||JSON.stringify(Ae)!==JSON.stringify(n.branding_override||{})?localStorage.setItem(o,JSON.stringify(Ke)):localStorage.removeItem(o)},[u,p,y,v,w,A,O,I,z,Z,W,se,me,ve,Te,Ce,Pe,Ae,o,c,n]);const Je=()=>{localStorage.removeItem(o),we()},ke=async()=>{try{await a.mutateAsync({id:n.id,next_step_text:u||null,next_step_video_url:p||null,inspection_date:y||null,appraisal_date:v||null,welcome_message:w||null,review_url:A||null,show_post_close_tips:O,notify_client:I,require_onboarding:z,allow_spouse:Z,visibility:W,stage_mapping:se.length>0?se:null,linked_portal_id:me,referral_enabled:ve,referral_reward_text:Te||null,referral_cta_headline:Ce||null,homeowner_hub_video_url:Pe||null,branding_override:Object.values(Ae).some(Ge=>Ge!=null&&Ge!=="")?Ae:null});const Ke=n.linked_portal_id;me&&me!==Ke&&await q.from("client_portals").update({linked_portal_id:n.id}).eq("id",me),!me&&Ke&&await q.from("client_portals").update({linked_portal_id:null}).eq("id",Ke),localStorage.removeItem(o),ae.success("Portal settings saved"),t(!1)}catch{ae.error("Failed to save settings")}},it=()=>{oe([...se,{label:""}])},je=Ke=>{oe(se.filter((Ge,rt)=>rt!==Ke)),he===Ke&&ce(null)},He=(Ke,Ge,rt)=>{const tt=[...se];tt[Ke]={...tt[Ke],[Ge]:rt},oe(tt)},$e=()=>{const Ge=xye(null).map(rt=>({label:rt.label,description:rt.description,stageId:void 0}));oe(Ge)};return e.jsxs(e.Fragment,{children:[e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg max-h-[85vh] flex flex-col",children:[e.jsx(js,{children:e.jsx(ws,{children:"Portal Settings"})}),e.jsxs(Fr,{defaultValue:"general",className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Rr,{className:"grid grid-cols-5 shrink-0",children:[e.jsx(Zt,{value:"general",children:"General"}),e.jsx(Zt,{value:"timeline",children:"Timeline"}),e.jsx(Zt,{value:"content",children:"Content"}),e.jsx(Zt,{value:"vendors",children:"Vendors"}),e.jsx(Zt,{value:"branding",children:"Branding"})]}),e.jsxs("div",{className:"flex-1 overflow-y-auto mt-4 min-h-0",children:[e.jsxs(is,{value:"general",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{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(Ke=>e.jsx("button",{onClick:()=>ee(Ke),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${W===Ke?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:Ke.charAt(0).toUpperCase()+Ke.slice(1)},Ke))})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:z,onCheckedChange:H})]}),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(ne,{className:"text-sm font-medium",children:"Custom Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Manage intake form questions"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>l(!0),className:"text-xs",children:"Manage"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:Z,onCheckedChange:Y})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:O,onCheckedChange:D})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:I,onCheckedChange:F})]}),e.jsx("div",{className:"border-t pt-4",children:e.jsx(xQs,{portalId:n.id,ownerId:r,clientEmail:n.client_email,linkedPortalId:me,onLink:le})}),e.jsx("div",{children:e.jsx(ye,{type:"date",value:y,onChange:Ke=>_(Ke.target.value),className:"mt-1"})}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Appraisal Date"}),e.jsx(ye,{type:"date",value:v,onChange:Ke=>j(Ke.target.value),className:"mt-1"})]})]}),e.jsx(is,{value:"timeline",className:"space-y-4 mt-0 px-1",children:e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Client-Facing Stages"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Customize the client-friendly stage labels shown on the portal timeline"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:$e,className:"text-xs",children:"Auto-map"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground bg-muted/50 rounded-md p-2",children:'💡 These labels are what clients see. Click "More" on any stage to customize its description and add a video link. Internal pipeline stages are automatically translated to friendly names.'}),se.length===0&&e.jsxs("div",{className:"border border-dashed rounded-lg p-4 text-center",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-2",children:"No custom mapping — using default client-friendly journey stages"}),e.jsx(B,{variant:"outline",size:"sm",onClick:$e,children:"Customize journey labels"})]}),e.jsx("div",{className:"space-y-2 mt-2",children:se.map((Ke,Ge)=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pu,{className:"h-4 w-4 text-muted-foreground/50 flex-shrink-0"}),e.jsx(ye,{value:Ke.label,onChange:rt=>He(Ge,"label",rt.target.value),placeholder:`Stage ${Ge+1} label`,className:"flex-1 h-9 text-sm"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-9 px-2 text-xs text-muted-foreground hover:text-primary",onClick:()=>ce(he===Ge?null:Ge),children:he===Ge?"Less":"More"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-9 w-9 text-muted-foreground hover:text-destructive",onClick:()=>je(Ge),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}),he===Ge&&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(ne,{className:"text-xs text-muted-foreground",children:"Description"}),e.jsx("textarea",{value:Ke.description||"",onChange:rt=>He(Ge,"description",rt.target.value),placeholder:"e.g. Now it's time to start actively looking at homes",className:"mt-0.5 w-full rounded-md border border-input bg-background px-3 py-2 text-xs min-h-[50px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Video"}),Ke.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:Ke.video_url.length>40?Ke.video_url.slice(0,40)+"...":Ke.video_url}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive hover:text-destructive",onClick:()=>He(Ge,"video_url",""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(XLe,{onVideoReady:rt=>He(Ge,"video_url",rt)}),e.jsx(e6,{userId:r,onSelect:rt=>He(Ge,"video_url",rt),triggerSize:"sm",triggerClassName:"gap-1.5 shrink-0 flex-1"}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const rt=prompt("Paste a YouTube or Loom URL:");rt&&He(Ge,"video_url",rt)},children:[e.jsx(Yo,{className:"h-3 w-3"}),"Paste URL"]})]})]})]})]},Ge))}),se.length>0&&e.jsxs(B,{variant:"outline",size:"sm",onClick:it,className:"mt-2 text-xs w-full",children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add Stage"]})]})}),e.jsxs(is,{value:"content",className:"space-y-4 mt-0 px-1",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Welcome Message"}),e.jsx("textarea",{value:w,onChange:Ke=>S(Ke.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(ne,{className:"text-sm font-medium",children:"What's Next"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Tell your client what to expect next"}),e.jsx("textarea",{value:u,onChange:Ke=>h(Ke.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(ne,{className:"text-sm font-medium",children:"Next Step Video (optional)"}),e.jsx(ye,{value:p,onChange:Ke=>f(Ke.target.value),className:"mt-1",placeholder:"YouTube or Loom URL"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Review URL"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown after deal closes"}),e.jsx(ye,{value:A,onChange:Ke=>E(Ke.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(ne,{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(ne,{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(jn,{checked:ve,onCheckedChange:ge})]}),ve&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Headline"}),e.jsx(ye,{value:Ce,onChange:Ke=>Me(Ke.target.value),className:"mt-1",placeholder:"Know someone buying or selling?"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Reward (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"What the client gets for a successful referral"}),e.jsx(ye,{value:Te,onChange:Ke=>Ie(Ke.target.value),className:"mt-1",placeholder:"$250 gift card • Donation to your charity • Closing gift"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Personal Welcome Video URL (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:'A "welcome home" video shown above the referral card'}),e.jsx(ye,{value:Pe,onChange:Ke=>Re(Ke.target.value),className:"mt-1",placeholder:"YouTube, Loom, or direct video URL"})]})]})]})]}),e.jsx(is,{value:"vendors",className:"space-y-4 mt-0 px-1",children:e.jsx(fQs,{portalId:n.id,agentUserId:r})}),e.jsx(is,{value:"branding",className:"space-y-4 mt-0 px-1",children:e.jsx(pQs,{override:Ae,onChange:Be})})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"ghost",onClick:Je,children:"Reset Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:ke,disabled:a.isPending,children:[a.isPending?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Save Settings"]})]})]})]})}),e.jsx(Qjt,{open:i,onOpenChange:l})]})}const yQs=s=>`portal-update-draft:${s}`;function e8e({open:s,onOpenChange:t,portalId:n,portalSlug:r,notifyClient:a}){const i=N.useMemo(()=>yQs(n),[n]),[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState(!1),[y,_]=N.useState(a??!1),[v,j]=N.useState(!1),w=w_t();N.useEffect(()=>{j(!1);const E=localStorage.getItem(i);if(E)try{const O=JSON.parse(E);o(O.title||""),d(O.content||""),h(O.videoUrl||""),f(!!O.isStageChange),_(typeof O.sendNotification=="boolean"?O.sendNotification:a??!1),j(!0);return}catch{localStorage.removeItem(i)}o(""),d(""),h(""),f(!1),_(a??!1),j(!0)},[i,a]),N.useEffect(()=>{if(!v)return;const E={title:l,content:c,videoUrl:u,isStageChange:p,sendNotification:y};l.trim()||c.trim()||u.trim()||p||y!==(a??!1)?localStorage.setItem(i,JSON.stringify(E)):localStorage.removeItem(i)},[l,c,u,p,y,v,i,a]);const S=()=>{localStorage.removeItem(i),o(""),d(""),h(""),f(!1),_(a??!1)},A=async()=>{if(l.trim())try{if(await w.mutateAsync({portal_id:n,title:l.trim(),content:c.trim()||void 0,video_url:u.trim()||void 0,is_stage_change:p}),y&&r)try{const E=kw(r);await q.functions.invoke("send-portal-notification",{body:{portal_id:n,update_title:l.trim(),update_content:c.trim()||null,portal_url:E}}),ae.success("Update posted & client notified")}catch(E){console.error("Notification failed:",E),ae.success("Update posted (notification failed to send)")}else ae.success("Update posted to portal");S(),t(!1)}catch{ae.error("Failed to post update")}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Post Portal Update"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Title *"}),e.jsx(ye,{value:l,onChange:E=>o(E.target.value),className:"mt-1",placeholder:"Inspection cleared!"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Message"}),e.jsx("textarea",{value:c,onChange:E=>d(E.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(ne,{className:"text-sm font-medium",children:"Video URL (optional)"}),e.jsxs("div",{className:"relative mt-1",children:[e.jsx(ye,{value:u,onChange:E=>h(E.target.value),className:"pl-9",placeholder:"YouTube or Loom link"}),e.jsx(fr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"})]})]}),e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("button",{type:"button",onClick:()=>f(!p),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${p?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-background text-muted-foreground border-input"}`,children:"📊 Stage Change"}),e.jsxs("button",{type:"button",onClick:()=>_(!y),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors flex items-center gap-1.5 ${y?"bg-blue-500/10 text-blue-700 border-blue-200":"bg-background text-muted-foreground border-input"}`,children:[y?e.jsx(nm,{className:"h-3 w-3"}):e.jsx(cw,{className:"h-3 w-3"}),y?"Notify Client":"No Notification"]})]})]}),e.jsxs("div",{className:"flex justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",onClick:S,children:"Clear Draft"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Close"}),e.jsxs(B,{onClick:A,disabled:!l.trim()||w.isPending,children:[w.isPending?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Post Update"]})]})]})]})})}function t8e({open:s,onOpenChange:t,portal:n,dealName:r}){const a=xR(),{isGmailConnected:i,gmailEmail:l}=Dh(),[o,c]=N.useState(n.client_name||""),[d,u]=N.useState(n.client_email||""),[h,p]=N.useState(!1),[f,y]=N.useState(!1),_=kw(n.slug),v=o.split(" ")[0]||"there",j=`Your Transaction Portal – ${r}`,w=`Hi ${v}, I've set up a dedicated portal where you can track the progress of your transaction in real-time. Here's your link: ${_} You can view your timeline, key dates, documents, and any updates I post along the way. Let me know if you have any questions!`,S=()=>{navigator.clipboard.writeText(_),y(!0),setTimeout(()=>y(!1),2e3),ae.success("Portal link copied!")},A=async()=>{if(!d.trim()){ae.error("Please enter the client email");return}p(!0);try{await a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"});const{error:O}=await q.functions.invoke("gmail-send",{body:{to:d,subject:j,body:w.replace(/\n/g,"
")}});if(O){let D="";try{const I=O==null?void 0:O.context;if(I&&typeof I.json=="function"){const F=await I.json();D=(F==null?void 0:F.message)||(F==null?void 0:F.error)||""}}catch{}throw new Error(D||O.message||"Failed to send invite")}ae.success(`Invite sent to ${d}`),t(!1)}catch(O){ae.error(O.message||"Failed to send invite")}finally{p(!1)}},E=()=>{const O=encodeURIComponent(j),D=encodeURIComponent(w);window.open(`mailto:${d}?subject=${O}&body=${D}`,"_blank"),a.mutateAsync({id:n.id,client_name:o||null,client_email:d||null,invite_sent_at:new Date().toISOString(),invite_method:"email"}).catch(()=>{})};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Invite Client to Portal"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Client Name"}),e.jsx(ye,{value:o,onChange:O=>c(O.target.value),className:"mt-1",placeholder:"John Doe"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Client Email"}),e.jsx(ye,{type:"email",value:d,onChange:O=>u(O.target.value),className:"mt-1",placeholder:"john@example.com"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Portal Link"}),e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsx("div",{className:"flex-1 bg-muted/50 rounded-md px-3 py-2",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:_})}),e.jsx(B,{variant:"outline",size:"icon",onClick:S,className:"shrink-0",children:f?e.jsx(Lr,{className:"h-4 w-4 text-emerald-600"}):e.jsx(Zr,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{className:"space-y-2 pt-2 border-t",children:[i?e.jsxs(B,{onClick:A,disabled:h||!d.trim(),className:"w-full",children:[h?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Send via Gmail (",l,")"]}):e.jsxs(B,{onClick:E,disabled:!d.trim(),className:"w-full",variant:"outline",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Open in Email App"]}),e.jsxs(B,{variant:"ghost",onClick:S,className:"w-full text-muted-foreground",children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Just Copy Link"]})]})]})]})})}function vQs({deal:s}){const{isAdmin:t,user:n}=vs(),{data:r,isLoading:a}=OGs(s.id),i=QPe(),l=xR(),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,y]=N.useState(!1),_=`portal-management-ui:${s.id}`;if(N.useEffect(()=>{const O=sessionStorage.getItem(_);if(O)try{const D=JSON.parse(O);u(!!D.settingsOpen),p(!!D.composerOpen),y(!!D.inviteOpen)}catch{sessionStorage.removeItem(_)}},[_]),N.useEffect(()=>{d||h||f?sessionStorage.setItem(_,JSON.stringify({settingsOpen:d,composerOpen:h,inviteOpen:f})):sessionStorage.removeItem(_)},[d,h,f,_]),a)return e.jsx("div",{className:"border rounded-lg p-4",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(rs,{className:"h-3 w-3 animate-spin ml-auto"})]})});const v=async()=>{var O,D;c(!0);try{await i.mutateAsync({deal_id:s.id,visibility:"private",require_onboarding:!0,client_name:s.contact?`${s.contact.first_name} ${s.contact.last_name}`:void 0,client_email:((O=s.contact)==null?void 0:O.email)||void 0,client_phone:((D=s.contact)==null?void 0:D.phone)||void 0}),ae.success("Client portal enabled!")}catch{ae.error("Failed to create portal")}finally{c(!1)}},j=async O=>{if(r)try{await l.mutateAsync({id:r.id,is_enabled:O}),ae.success(O?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},w=()=>{if(!r)return;const O=kw(r.slug);navigator.clipboard.writeText(O),ae.success("Portal link copied!")},S=()=>{if(!r)return;const O=kw(r.slug);window.open(O,"_blank")};if(!r)return e.jsxs("div",{className:"border rounded-lg p-4 border-dashed",children:[e.jsx("div",{className:"flex items-center justify-between mb-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"})]})}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Create a beautiful portal so your client can track their deal progress in real-time."}),e.jsxs(B,{onClick:v,disabled:o,size:"sm",className:"w-full",children:[o?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(un,{className:"h-4 w-4 mr-2"}),"Enable Client Portal"]})]});const A=kw(r.slug),E=(n==null?void 0:n.id)||"";return e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"border rounded-lg p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-sm",children:"Client Portal"}),e.jsx(Ue,{variant:"outline",className:r.is_enabled?"text-xs bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-xs bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"})]}),e.jsx(jn,{checked:r.is_enabled,onCheckedChange:j})]}),e.jsxs("div",{className:"space-y-1.5 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Visibility:"}),e.jsx(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0",children:r.visibility==="private"?"Private":"Public"})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Onboarding:"}),e.jsx("span",{className:"text-foreground",children:r.require_onboarding?"Required":"Disabled"})]}),r.client_name&&e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{children:"Client:"}),e.jsx("span",{className:"text-foreground",children:r.client_name})]})]}),e.jsx("div",{className:"bg-muted/50 rounded-md p-2 mb-3",children:e.jsx("p",{className:"text-xs font-mono text-muted-foreground truncate",children:A})}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 mb-2 w-full",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:w,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(Zr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Copy"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:S,className:"text-xs w-full min-w-0 px-2",children:[e.jsx(tr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Preview"})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>y(!0),className:"text-xs w-full min-w-0 px-2",children:[e.jsx(lr,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Invite"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 w-full",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>p(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(X_,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Post Update"})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>u(!0),className:"text-xs text-muted-foreground w-full min-w-0 px-2",children:[e.jsx(Ko,{className:"h-3 w-3 mr-1 shrink-0"}),e.jsx("span",{className:"truncate",children:"Settings"})]})]}),e.jsxs(In,{to:"/mission-control/portal-referrals",className:"mt-2 flex items-center justify-center gap-1.5 text-[11px] text-muted-foreground hover:text-primary transition-colors py-1.5",children:[e.jsx(Oi,{className:"h-3 w-3"}),"View incoming referrals"]})]}),e.jsx(JLe,{open:d,onOpenChange:u,portal:r,dealOwnerId:E}),e.jsx(e8e,{open:h,onOpenChange:p,portalId:r.id,portalSlug:r.slug,notifyClient:r.notify_client}),e.jsx(t8e,{open:f,onOpenChange:y,portal:r,dealName:s.deal_name})]})}const bQs=["Client","Co-Buyer","Co-Seller","Spouse","Lender","Title Company","Inspector","Appraiser","Attorney","Contractor","Other"];function _Qs(s){return dt({queryKey:["deal-contacts",s],queryFn:async()=>{const{data:t,error:n}=await q.from("deal_contacts").select(` id, deal_id, contact_id, role, created_at, contact:innercircle_contacts(id, first_name, last_name, email, phone) `).eq("deal_id",s).order("created_at");if(n)throw n;return t||[]},enabled:!!s})}function wQs(){const s=Kt();return yt({mutationFn:async({dealId:t,contactId:n,role:r})=>{const{data:a,error:i}=await q.from("deal_contacts").insert({deal_id:t,contact_id:n,role:r}).select().single();if(i)throw i;return a},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact linked to deal")},onError:t=>{var n;(n=t.message)!=null&&n.includes("duplicate")?ae.error("This contact is already linked to this deal"):ae.error("Failed to link contact")}})}function jQs(){const s=Kt();return yt({mutationFn:async({id:t,dealId:n})=>{const{error:r}=await q.from("deal_contacts").delete().eq("id",t);if(r)throw r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["deal-contacts",n.dealId]}),ae.success("Contact removed from deal")},onError:()=>{ae.error("Failed to remove contact")}})}function NQs({dealId:s,primaryContactId:t}){const n=Ln(),{data:r,isLoading:a}=_Qs(s),{data:i}=ax(),l=wQs(),o=jQs(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState("Client"),y=new Set((r==null?void 0:r.map(S=>S.contact_id))||[]);t&&y.add(t);const _=i==null?void 0:i.filter(S=>{var E,O,D;if(y.has(S.id))return!1;if(!u.trim())return!0;const A=u.toLowerCase();return((E=S.first_name)==null?void 0:E.toLowerCase().includes(A))||((O=S.last_name)==null?void 0:O.toLowerCase().includes(A))||((D=S.email)==null?void 0:D.toLowerCase().includes(A))}).slice(0,8),v=S=>{l.mutate({dealId:s,contactId:S,role:p}),d(!1),h("")},j=S=>{o.mutate({id:S,dealId:s})},w={Client:"bg-primary/10 text-primary","Co-Buyer":"bg-blue-500/10 text-blue-600","Co-Seller":"bg-emerald-500/10 text-emerald-600",Spouse:"bg-pink-500/10 text-pink-600",Lender:"bg-amber-500/10 text-amber-600","Title Company":"bg-purple-500/10 text-purple-600",Inspector:"bg-orange-500/10 text-orange-600",Appraiser:"bg-cyan-500/10 text-cyan-600",Attorney:"bg-slate-500/10 text-slate-600",Contractor:"bg-lime-500/10 text-lime-600",Other:"bg-muted text-muted-foreground"};return!(r!=null&&r.length)&&!c?e.jsxs("div",{className:"space-y-2",children:[e.jsx("div",{className:"flex items-center justify-between",children:e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4"}),"Additional Contacts"]})}),e.jsxs(il,{open:c,onOpenChange:d,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"w-full text-muted-foreground",children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"}),"Link a contact (lender, spouse, vendor...)"]})}),e.jsx(el,{className:"w-80 p-3",align:"start",children:e.jsx(BQe,{search:u,setSearch:h,selectedRole:p,setSelectedRole:f,filteredContacts:_,onAdd:v})})]})]}):e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h4",{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4"}),"Linked Contacts",r&&r.length>0&&e.jsx(Ue,{variant:"secondary",className:"text-[10px] px-1.5",children:r.length})]}),e.jsxs(il,{open:c,onOpenChange:d,children:[e.jsx(ol,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 px-2",children:e.jsx(Is,{className:"h-3.5 w-3.5"})})}),e.jsx(el,{className:"w-80 p-3",align:"end",children:e.jsx(BQe,{search:u,setSearch:h,selectedRole:p,setSelectedRole:f,filteredContacts:_,onAdd:v})})]})]}),e.jsx("div",{className:"space-y-1.5",children:r==null?void 0:r.map(S=>{var A,E,O,D,I,F,z,H;return e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-md bg-muted/40 group",children:[e.jsx(Jr,{className:"h-7 w-7",children:e.jsxs(ea,{className:"text-[10px] bg-primary/10 text-primary",children:[(E=(A=S.contact)==null?void 0:A.first_name)==null?void 0:E[0],(D=(O=S.contact)==null?void 0:O.last_name)==null?void 0:D[0]]})}),e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("button",{onClick:()=>n(`/mission-control/contacts/${S.contact_id}`),className:"text-sm font-medium hover:underline text-primary truncate block",children:[(I=S.contact)==null?void 0:I.first_name," ",(F=S.contact)==null?void 0:F.last_name]})}),e.jsx(Ue,{variant:"outline",className:`text-[10px] px-1.5 py-0 shrink-0 ${w[S.role]||w.Other}`,children:S.role}),e.jsxs("div",{className:"flex gap-0.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[((z=S.contact)==null?void 0:z.phone)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`tel:${S.contact.phone}`,children:e.jsx(Cr,{className:"h-3 w-3"})})}),((H=S.contact)==null?void 0:H.email)&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",asChild:!0,children:e.jsx("a",{href:`mailto:${S.contact.email}`,children:e.jsx(Gs,{className:"h-3 w-3"})})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>j(S.id),children:e.jsx(_n,{className:"h-3 w-3"})})]})]},S.id)})})]})}function BQe({search:s,setSearch:t,selectedRole:n,setSelectedRole:r,filteredContacts:a,onAdd:i}){return e.jsxs("div",{className:"space-y-3",children:[e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"h-8 text-sm",children:e.jsx(hs,{placeholder:"Role"})}),e.jsx(cs,{children:bQs.map(l=>e.jsx(Ze,{value:l,children:l},l))})]}),e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-2 top-2.5 h-3.5 w-3.5 text-muted-foreground"}),e.jsx(ye,{value:s,onChange:l=>t(l.target.value),placeholder:"Search contacts...",className:"pl-7 h-8 text-sm",autoFocus:!0})]}),e.jsx(di,{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 kQs={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"}},SQs={note:Ai,call:Cr,email:Gs,meeting:yr,stage_change:tr,task_completed:vr,document:Or,system:pr};function CQs({deal:s,open:t,onOpenChange:n,onEdit:r,onAddToScorecard:a,isWonStage:i}){var Pe,Re;const l=Ln(),{data:o,isLoading:c}=iZs((s==null?void 0:s.id)||""),{data:d,isLoading:u}=lZs((s==null?void 0:s.id)||""),h=oZs(),p=dZs(),f=cZs(),y=aZs(),{data:_,isLoading:v}=cQs((s==null?void 0:s.id)||""),j=dQs(),w=uQs(),S=hQs(),A=N.useRef(null),[E,O]=N.useState(""),[D,I]=N.useState(""),[F,z]=N.useState(!1),[H,Z]=N.useState(!1);if(!s)return null;const Y=kQs[s.deal_type],W=(()=>{var we;if(s.deal_type!=="seller"&&s.deal_type!=="dual")return null;const Ae=((we=s.listing)==null?void 0:we.created_at)||s.listing_date;if(!Ae)return null;const Be=s.contract_date?Ll(s.contract_date):new Date;return Vv(Be,Ll(Ae))})(),ee=Ae=>Ae?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Ae):"-",se=async()=>{if(E.trim())try{await h.mutateAsync({deal_id:s.id,activity_type:"note",title:"Note added",description:E}),O(""),ae.success("Note added")}catch{ae.error("Failed to add note")}},oe=async()=>{if(D.trim())try{await p.mutateAsync({deal_id:s.id,title:D,sort_order:((d==null?void 0:d.length)||0)+1}),I(""),ae.success("Task added")}catch{ae.error("Failed to add task")}},he=async(Ae,Be)=>{try{await f.mutateAsync({id:Ae,is_completed:Be,deal_id:s.id})}catch{ae.error("Failed to update task")}},ce=async()=>{try{await y.mutateAsync(s.id),ae.success("Deal deleted"),n(!1)}catch{ae.error("Failed to delete deal")}},me=(d==null?void 0:d.filter(Ae=>Ae.is_completed).length)||0,le=(d==null?void 0:d.length)||0,ve=(_==null?void 0:_.length)||0,ge=Ae=>Ae<1024?`${Ae} B`:Ae<1024*1024?`${(Ae/1024).toFixed(1)} KB`:`${(Ae/(1024*1024)).toFixed(1)} MB`,Te=Ae=>Ae?Ae.startsWith("image/")?Xo:Ae.includes("pdf")?br:QP:QP,Ie=async Ae=>{const Be=Ae.target.files;if(!(!Be||!s)){Z(!0);try{for(const we of Array.from(Be)){if(we.size>20*1024*1024){ae.error(`${we.name} exceeds 20MB limit`);continue}await j.mutateAsync({dealId:s.id,file:we})}ae.success("File(s) uploaded")}catch{ae.error("Failed to upload file")}finally{Z(!1),A.current&&(A.current.value="")}}},Ce=async(Ae,Be)=>{if(s)try{await w.mutateAsync({fileId:Ae,storagePath:Be,dealId:s.id}),ae.success("File deleted")}catch{ae.error("Failed to delete file")}},Me=async(Ae,Be)=>{try{const we=await mQs(Ae),Je=document.createElement("a");Je.href=we,Je.download=Be,Je.target="_blank",document.body.appendChild(Je),Je.click(),document.body.removeChild(Je)}catch{ae.error("Failed to download file")}};return e.jsxs(e.Fragment,{children:[e.jsx(t0,{open:t,onOpenChange:n,children:e.jsxs(og,{className:"w-full sm:max-w-xl p-0 flex flex-col",children:[e.jsx(jy,{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(Ue,{variant:"outline",className:Mt("text-xs",Y.color),children:Y.label}),e.jsxs(Ue,{variant:"secondary",className:"text-xs capitalize",children:[s.priority," priority"]})]}),e.jsx(Ny,{className:"text-xl",children:s.deal_name}),e.jsx("div",{className:"mt-2",children:e.jsx(lQs,{dealId:s.id})})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>r(s),children:e.jsx(wu,{className:"h-4 w-4"})}),e.jsx(B,{variant:"outline",size:"icon",className:"text-destructive hover:bg-destructive/10",onClick:()=>z(!0),children:e.jsx(_n,{className:"h-4 w-4"})})]})]})}),e.jsx(di,{className:"flex-1 [&>[data-radix-scroll-area-viewport]>div]:!block [&>[data-radix-scroll-area-viewport]>div]:!w-full",children:e.jsxs("div",{className:"p-6 space-y-6 min-w-0",children:[s.contact&&e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsxs("button",{type:"button",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},className:"flex items-center gap-3 flex-1 min-w-0 text-left hover:opacity-80 transition-opacity group",children:[e.jsx(Jr,{className:"h-10 w-10",children:e.jsxs(ea,{className:"bg-primary/10 text-primary",children:[(Pe=s.contact.first_name)==null?void 0:Pe[0],(Re=s.contact.last_name)==null?void 0:Re[0]]})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:"font-medium group-hover:text-primary group-hover:underline truncate",children:[s.contact.first_name," ",s.contact.last_name]}),s.contact.email&&e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:s.contact.email})]})]}),e.jsxs("div",{className:"flex gap-2 shrink-0",children:[s.contact.phone&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`tel:${s.contact.phone}`,children:e.jsx(Cr,{className:"h-4 w-4"})})}),s.contact.email&&e.jsx(B,{variant:"outline",size:"icon",asChild:!0,children:e.jsx("a",{href:`mailto:${s.contact.email}`,children:e.jsx(Gs,{className:"h-4 w-4"})})}),e.jsx(B,{variant:"outline",size:"icon",title:"Open contact record",onClick:()=>{n(!1),l(`/mission-control/contacts/${s.contact_id}`)},children:e.jsx(tr,{className:"h-4 w-4"})})]})]}),e.jsx(NQs,{dealId:s.id,primaryContactId:s.contact_id}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[(s.property_address||s.city)&&e.jsxs("div",{className:"col-span-2 flex items-start gap-2 text-sm",children:[e.jsx(Or,{className:"h-4 w-4 text-muted-foreground mt-0.5"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:s.property_address||"Address TBD"}),e.jsx("p",{className:"text-muted-foreground",children:[s.city,s.state,s.zip_code].filter(Boolean).join(", ")})]})]}),e.jsxs("div",{className:"bg-muted/50 rounded-lg p-3",children:[e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Expected Price"}),e.jsx("p",{className:"text-lg font-bold",children:ee(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:ee(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?` (${ee(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:ee(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:ee(s.net_commission)})]})})})]}),i&&!s.scorecard_transaction_id&&a&&e.jsxs(B,{onClick:()=>a(s),className:"w-full bg-green-600 hover:bg-green-700",children:[e.jsx(xo,{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(vr,{className:"h-4 w-4 text-green-600"}),e.jsx("span",{children:"Synced to Scorecard"})]}),W!==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:Mt("text-lg font-bold",W>90?"text-red-600":W>60?"text-amber-600":"text-foreground"),children:[W," ",s.contract_date?"(final)":"days"]})]}),s.target_close_date&&e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("span",{children:["Close: ",Ss(Ll(s.target_close_date),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm",children:[e.jsx(Yl,{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(vQs,{deal:s}),e.jsxs(Fr,{defaultValue:"tasks",className:"w-full",children:[e.jsxs(Rr,{className:"w-full grid grid-cols-3",children:[e.jsxs(Zt,{value:"tasks",className:"gap-1",children:[e.jsx(vr,{className:"h-4 w-4"}),"Tasks ",le>0&&`(${me}/${le})`]}),e.jsxs(Zt,{value:"files",className:"gap-1",children:[e.jsx(YS,{className:"h-4 w-4"}),"Files ",ve>0&&`(${ve})`]}),e.jsxs(Zt,{value:"activity",className:"gap-1",children:[e.jsx(pr,{className:"h-4 w-4"}),"Activity"]})]}),e.jsxs(is,{value:"tasks",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Add a new task...",value:D,onChange:Ae=>I(Ae.target.value),onKeyDown:Ae=>Ae.key==="Enter"&&oe()}),e.jsx(B,{onClick:oe,disabled:!D.trim(),children:e.jsx(Is,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"space-y-2",children:[d==null?void 0:d.map(Ae=>e.jsxs("div",{className:Mt("flex items-center gap-3 p-3 rounded-lg border transition-colors",Ae.is_completed?"bg-muted/50 border-border":"bg-background"),children:[e.jsx(hi,{checked:Ae.is_completed,onCheckedChange:Be=>he(Ae.id,!!Be)}),e.jsx("span",{className:Mt("flex-1 text-sm",Ae.is_completed&&"line-through text-muted-foreground"),children:Ae.title}),Ae.due_date&&e.jsx("span",{className:"text-xs text-muted-foreground",children:Ss(new Date(Ae.due_date),"MMM d")})]},Ae.id)),(d==null?void 0:d.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No tasks yet. Add one above!"})]})]}),e.jsxs(is,{value:"files",className:"mt-4 space-y-3",children:[e.jsx("input",{type:"file",ref:A,className:"hidden",multiple:!0,onChange:Ie,accept:".pdf,.doc,.docx,.xls,.xlsx,.jpg,.jpeg,.png,.webp,.gif,.txt,.csv"}),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{var Ae;return(Ae=A.current)==null?void 0:Ae.click()},disabled:H,children:[H?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(_a,{className:"h-4 w-4 mr-2"}),H?"Uploading...":"Upload Files"]}),e.jsxs("div",{className:"space-y-2",children:[_==null?void 0:_.map(Ae=>{const Be=Te(Ae.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(Be,{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:Ae.file_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[ge(Ae.file_size)," · ",Ss(new Date(Ae.created_at),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Vw,{children:e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:`h-8 w-8 transition-colors ${Ae.visible_on_portal?"text-primary bg-primary/10 hover:bg-primary/20":"text-muted-foreground/40 hover:text-muted-foreground"}`,onClick:()=>S.mutate({fileId:Ae.id,visible:!Ae.visible_on_portal,dealId:s.id}),children:Ae.visible_on_portal?e.jsx(Sr,{className:"h-4 w-4"}):e.jsx(mf,{className:"h-4 w-4"})})}),e.jsx(Nc,{side:"top",children:Ae.visible_on_portal?"Visible on client portal":"Hidden from client portal"})]})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>Me(Ae.storage_path,Ae.file_name),children:e.jsx(Ia,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive hover:text-destructive",onClick:()=>Ce(Ae.id,Ae.storage_path),children:e.jsx($n,{className:"h-4 w-4"})})]})]},Ae.id)}),(_==null?void 0:_.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No files yet. Upload contracts, disclosures, or other documents."})]})]}),e.jsxs(is,{value:"activity",className:"mt-4 space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ms,{placeholder:"Add a note...",value:E,onChange:Ae=>O(Ae.target.value),rows:2}),e.jsxs(B,{onClick:se,disabled:!E.trim(),size:"sm",className:"w-full",children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Add Note"]})]}),e.jsxs("div",{className:"space-y-3",children:[o==null?void 0:o.map(Ae=>{const Be=SQs[Ae.activity_type]||pr;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(Be,{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:Ae.title}),Ae.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:Ae.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Uo(new Date(Ae.created_at),{addSuffix:!0})})]})]},Ae.id)}),(o==null?void 0:o.length)===0&&e.jsx("p",{className:"text-center text-muted-foreground text-sm py-4",children:"No activity yet"})]})]})]})]})})]})}),e.jsx(Oo,{open:F,onOpenChange:z,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Deal?"}),e.jsxs(Mo,{children:['This will permanently delete "',s.deal_name,'" and all associated data. This action cannot be undone.']})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:ce,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})})]})}function TQs({open:s,onOpenChange:t,deal:n,onComplete:r}){const a=Eye(),i=Hjt(),{data:l}=qD(),{data:o}=ky(),[c,d]=N.useState({property_address:"",city:"",state:"",zip:"",transaction_type:"buyer",close_date:Ss(new Date,"yyyy-MM-dd"),sale_price:0,commission_amount:0,lead_source_id:"",client_type_id:"",notes:""});N.useEffect(()=>{if(n&&s){const p=n.deal_type==="seller"?"seller":"buyer",f=n.expected_price||0,y=n.commission_percentage||3,_=n.expected_commission||f*y/100;d({property_address:n.property_address||n.deal_name||"",city:n.city||"",state:n.state||"",zip:n.zip_code||"",transaction_type:p,close_date:n.actual_close_date||n.target_close_date||Ss(new Date,"yyyy-MM-dd"),sale_price:f,commission_amount:_,lead_source_id:"",client_type_id:"",notes:n.notes||""})}},[n,s]);const u=async p=>{if(p.preventDefault(),!!n)try{const f=await a.mutateAsync({property_address:c.property_address,city:c.city||null,state:c.state||null,zip:c.zip||null,transaction_type:c.transaction_type,close_date:c.close_date,sale_price:c.sale_price,commission_amount:c.commission_amount||null,brokerage_split_pct:n.brokerage_split_pct||null,team_split_pct:n.team_split_pct||null,franchise_fee_pct:n.franchise_fee_pct||null,referral_fee_pct:n.referral_fee_pct||null,transaction_fee:n.transaction_fee||null,lead_source_id:c.lead_source_id||null,client_type_id:c.client_type_id||null,contact_id:n.contact_id||null,notes:c.notes||null,is_win:!0});await i.mutateAsync({id:n.id,scorecard_transaction_id:f.id,actual_close_date:c.close_date}),ae.success("Deal added to Scorecard! 🎉"),t(!1),r==null||r()}catch(f){console.error("Error syncing to scorecard:",f),ae.error("Failed to add to scorecard")}},h=p=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",minimumFractionDigits:0,maximumFractionDigits:0}).format(p);return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[550px] max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{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(xo,{className:"h-6 w-6 text-green-600 dark:text-green-400"})}),e.jsx(ws,{className:"text-center text-xl",children:"Congratulations on Closing! 🎉"}),e.jsx(Jn,{className:"text-center",children:"Review and confirm the details before adding this deal to your Scorecard."})]}),e.jsxs("form",{onSubmit:u,className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"property_address",className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4 text-muted-foreground"}),"Property Address *"]}),e.jsx(ye,{id:"property_address",value:c.property_address,onChange:p=>d(f=>({...f,property_address:p.target.value})),placeholder:"123 Main St",required:!0})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"city",children:"City"}),e.jsx(ye,{id:"city",value:c.city,onChange:p=>d(f=>({...f,city:p.target.value})),placeholder:"City"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"state",children:"State"}),e.jsx(ye,{id:"state",value:c.state,onChange:p=>d(f=>({...f,state:p.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"zip",children:"Zip"}),e.jsx(ye,{id:"zip",value:c.zip,onChange:p=>d(f=>({...f,zip:p.target.value})),placeholder:"75001"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Transaction Type *"}),e.jsxs(us,{value:c.transaction_type,onValueChange:p=>d(f=>({...f,transaction_type:p})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"close_date",className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),"Close Date *"]}),e.jsx(ye,{id:"close_date",type:"date",value:c.close_date,onChange:p=>d(f=>({...f,close_date:p.target.value})),required:!0})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"sale_price",className:"flex items-center gap-2",children:[e.jsx(Yl,{className:"h-4 w-4 text-muted-foreground"}),"Sale Price *"]}),e.jsx(ye,{id:"sale_price",type:"number",value:c.sale_price||"",onChange:p=>d(f=>({...f,sale_price:Number(p.target.value)})),placeholder:"450000",required:!0,min:0}),c.sale_price>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.sale_price)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"commission_amount",className:"flex items-center gap-2",children:[e.jsx(QS,{className:"h-4 w-4 text-muted-foreground"}),"GCI (Commission)"]}),e.jsx(ye,{id:"commission_amount",type:"number",value:c.commission_amount||"",onChange:p=>d(f=>({...f,commission_amount:Number(p.target.value)})),placeholder:"13500",min:0}),c.commission_amount>0&&e.jsx("p",{className:"text-xs text-muted-foreground",children:h(c.commission_amount)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Lead Source"}),e.jsxs(us,{value:c.lead_source_id,onValueChange:p=>d(f=>({...f,lead_source_id:p})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select source"})}),e.jsx(cs,{children:l==null?void 0:l.map(p=>e.jsx(Ze,{value:p.id,children:p.name},p.id))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Client Type"}),e.jsxs(us,{value:c.client_type_id,onValueChange:p=>d(f=>({...f,client_type_id:p})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select type"})}),e.jsx(cs,{children:o==null?void 0:o.map(p=>e.jsx(Ze,{value:p.id,children:p.name},p.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"notes",children:"Notes"}),e.jsx(Ms,{id:"notes",value:c.notes,onChange:p=>d(f=>({...f,notes:p.target.value})),placeholder:"Any additional notes about this transaction...",rows:2})]}),e.jsxs(Xn,{className:"gap-2 sm:gap-0 pt-4",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Skip for now"}),e.jsx(B,{type:"submit",disabled:a.isPending||i.isPending,className:"bg-green-600 hover:bg-green-700",children:a.isPending?"Adding...":e.jsxs(e.Fragment,{children:["Add to Scorecard",e.jsx(Oa,{className:"ml-2 h-4 w-4"})]})})]})]})]})})}const EQs={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"}},$Qe={urgent:0,high:1,medium:2,low:3};function AQs({deals:s,stages:t,onDealClick:n,onStageChange:r}){const[a,i]=N.useState("target_close_date"),[l,o]=N.useState("asc"),c=f=>{a===f?o(y=>y==="asc"?"desc":"asc"):(i(f),o("asc"))},d=N.useMemo(()=>[...s].sort((f,y)=>{var v,j;let _=0;switch(a){case"deal_name":_=f.deal_name.localeCompare(y.deal_name);break;case"stage":{const w=((v=t.find(A=>A.id===f.stage_id))==null?void 0:v.sort_order)||0,S=((j=t.find(A=>A.id===y.stage_id))==null?void 0:j.sort_order)||0;_=w-S;break}case"expected_price":_=(f.expected_price||0)-(y.expected_price||0);break;case"expected_commission":_=(f.expected_commission||0)-(y.expected_commission||0);break;case"target_close_date":{const w=f.target_close_date?Ll(f.target_close_date).getTime():1/0,S=y.target_close_date?Ll(y.target_close_date).getTime():1/0;_=w-S;break}case"priority":_=$Qe[f.priority]-$Qe[y.priority];break}return l==="asc"?_:-_}),[s,t,a,l]),u=f=>f?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(f):"—",h=f=>f?t.find(y=>y.id===f):null,p=({field:f,children:y})=>e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 -ml-3 font-medium",onClick:()=>c(f),children:[y,a===f?l==="asc"?e.jsx(Iu,{className:"ml-2 h-4 w-4"}):e.jsx(sm,{className:"ml-2 h-4 w-4"}):e.jsx(ah,{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(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{className:"bg-muted/50",children:[e.jsx(Tt,{className:"w-[250px]",children:e.jsx(p,{field:"deal_name",children:"Deal Name"})}),e.jsx(Tt,{className:"w-[150px]",children:e.jsx(p,{field:"stage",children:"Stage"})}),e.jsx(Tt,{className:"w-[100px]",children:"Type"}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(p,{field:"expected_price",children:"Price"})}),e.jsx(Tt,{className:"w-[120px]",children:e.jsx(p,{field:"expected_commission",children:"GCI"})}),e.jsx(Tt,{className:"w-[130px]",children:e.jsx(p,{field:"target_close_date",children:"Close Date"})}),e.jsx(Tt,{className:"w-[100px]",children:e.jsx(p,{field:"priority",children:"Priority"})})]})}),e.jsx(da,{children:d.map(f=>{h(f.stage_id);const y=EQs[f.deal_type],_=f.target_close_date?Vv(Ll(f.target_close_date),new Date):null,v=_!==null&&_<0,j=_!==null&&_<=7&&_>=0;return e.jsxs(Hs,{className:Mt("cursor-pointer hover:bg-muted/50 transition-colors",v&&"bg-red-50/50"),onClick:()=>n(f),children:[e.jsx(ht,{className:"font-medium",children:e.jsxs("div",{children:[e.jsx("p",{className:"truncate max-w-[230px]",children:f.deal_name}),f.contact&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[f.contact.first_name," ",f.contact.last_name]})]})}),e.jsx(ht,{onClick:w=>w.stopPropagation(),children:e.jsx(Yjt,{stages:t,currentStageId:f.stage_id||"",onStageSelect:(w,S)=>r(f.id,w,S)})}),e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",className:Mt("text-xs",y.color),children:y.label})}),e.jsx(ht,{children:e.jsx("span",{className:"font-medium",children:u(f.expected_price)})}),e.jsx(ht,{children:e.jsx("span",{className:"text-emerald-600",children:u(f.expected_commission)})}),e.jsx(ht,{children:f.target_close_date?e.jsxs("div",{className:Mt("flex items-center gap-1 text-sm",v&&"text-red-600",j&&!v&&"text-amber-600"),children:[v&&e.jsx(Bi,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:Ss(Ll(f.target_close_date),"MMM d, yyyy")})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",className:Mt("text-xs capitalize",f.priority==="urgent"&&"border-red-200 bg-red-50 text-red-700",f.priority==="high"&&"border-orange-200 bg-orange-50 text-orange-700",f.priority==="medium"&&"border-amber-200 bg-amber-50 text-amber-700",f.priority==="low"&&"border-slate-200 bg-slate-50 text-slate-600"),children:f.priority})})]},f.id)})})]})})}function MQs(){const s=wa();return dt({queryKey:["deal-tasks",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_tasks").select(` *, deal:deal_pipeline(id, deal_name, stage_id), contact:innercircle_contacts(id, first_name, last_name), stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function IQs(s){const t=wa();return dt({queryKey:["deal-tasks","deal",s,t],queryFn:async()=>{if(!t||!s)return[];const{data:n,error:r}=await q.from("deal_tasks").select(` *, stage:deal_pipeline_stages(id, name, color) `).eq("owner_user_id",t).eq("deal_id",s).order("sort_order",{ascending:!0});if(r)throw r;return n},enabled:!!t&&!!s})}function PQs(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_tasks").insert({owner_user_id:s,title:n.title,description:n.description||null,deal_id:n.deal_id||null,contact_id:n.contact_id||null,stage_id:n.stage_id||null,priority:n.priority||"medium",status:n.status||"todo",due_date:n.due_date||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}function LQs(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("deal_tasks").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function DQs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("deal_tasks").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function s8e(){const s=Kt();return yt({mutationFn:async({id:t,status:n})=>{const{data:r,error:a}=await q.from("deal_tasks").update({status:n,completed_at:n==="done"?new Date().toISOString():null}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function RQs(){const s=Kt();return yt({mutationFn:async t=>{if(t.length===0)return;const{error:n}=await q.from("deal_tasks").update({status:"done",completed_at:new Date().toISOString()}).in("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-tasks"]})}})}function OQs(s){const t=wa();return dt({queryKey:["deal-task-templates",t,s],queryFn:async()=>{if(!t)return[];let n=q.from("deal_task_templates").select("*").eq("owner_user_id",t).order("sort_order",{ascending:!0});s&&(n=n.eq("stage_id",s));const{data:r,error:a}=await n;if(a)throw a;return r},enabled:!!t})}function FQs(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("deal_task_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title,description:n.description||null,priority:n.priority||"medium",default_due_offset_days:n.default_due_offset_days||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-task-templates"]})}})}function zQs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("deal_task_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["deal-task-templates"]})}})}function BQs(){const s=wa(),t=Kt();return yt({mutationFn:async({dealId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("deal_task_templates").select("*").eq("owner_user_id",s).eq("stage_id",r).order("sort_order");if(i)throw i;if(!a||a.length===0)return[];const{data:l}=await q.from("deal_tasks").select("title, stage_id").eq("deal_id",n).eq("stage_id",r),o=new Set((l||[]).map(h=>h.title)),c=a.filter(h=>!o.has(h.title)).map((h,p)=>({owner_user_id:s,deal_id:n,stage_id:r,title:h.title,description:h.description,priority:h.priority,due_date:h.default_due_offset_days?new Date(Date.now()+h.default_due_offset_days*864e5).toISOString().split("T")[0]:null,sort_order:p,status:"todo"}));if(c.length===0)return[];const{data:d,error:u}=await q.from("deal_tasks").insert(c).select();if(u)throw u;return d},onSuccess:()=>{t.invalidateQueries({queryKey:["deal-tasks"]})}})}const $Qs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function UQs({open:s,onOpenChange:t,dealId:n,dealName:r,fromStageName:a,toStageName:i,toStageId:l,onConfirm:o}){const{data:c,isLoading:d}=IQs(s?n:void 0),u=RQs(),h=BQs(),[p,f]=N.useState(new Set),[y,_]=N.useState(!1),v=(c||[]).filter(A=>A.status!=="done");N.useEffect(()=>{v.length>0&&f(new Set(v.map(A=>A.id)))},[c]);const j=A=>{f(E=>{const O=new Set(E);return O.has(A)?O.delete(A):O.add(A),O})},w=async()=>{_(!0);try{const A=Array.from(p);A.length>0&&await u.mutateAsync(A),await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(A){console.error("Stage move failed:",A),ae.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{_(!1)}},S=async()=>{_(!0);try{await o(),await h.mutateAsync({dealId:n,stageId:l}),t(!1)}catch(A){console.error("Stage move (skip) failed:",A),ae.error((A==null?void 0:A.message)||"Failed to move deal. Please try again.")}finally{_(!1)}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[480px]",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Move Deal"}),e.jsxs(Jn,{children:["Moving ",e.jsx("span",{className:"font-medium text-foreground",children:r})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 py-2",children:[e.jsx(Ue,{variant:"outline",className:"text-sm",children:a}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(Ue,{className:"text-sm bg-primary",children:i})]}),d?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["You have ",e.jsx("span",{className:"font-medium text-foreground",children:v.length})," incomplete task",v.length!==1?"s":"",". Select which to mark as done:"]}),e.jsx(di,{className:"max-h-[250px]",children:e.jsx("div",{className:"space-y-1",children:v.map(A=>e.jsxs("label",{className:"flex items-center gap-3 px-3 py-2 rounded-lg hover:bg-muted/50 cursor-pointer transition-colors",children:[e.jsx(hi,{checked:p.has(A.id),onCheckedChange:()=>j(A.id)}),e.jsxs("span",{className:"text-sm flex-1",children:[$Qs[A.priority]," ",A.title]}),A.stage&&e.jsx("span",{className:"text-[10px] px-1.5 py-0.5 rounded-full",style:{backgroundColor:A.stage.color+"20",color:A.stage.color},children:A.stage.name})]},A.id))})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>{p.size===v.length?f(new Set):f(new Set(v.map(A=>A.id)))},children:p.size===v.length?"Deselect All":"Select All"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:S,disabled:y,children:"Skip"}),e.jsxs(B,{size:"sm",onClick:w,disabled:y,children:[y&&e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}),p.size>0?`Complete ${p.size} & Move`:"Move Deal"]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"text-center py-4",children:[e.jsx(vr,{className:"h-8 w-8 text-emerald-500 mx-auto mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"All tasks completed! Ready to move."})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:w,disabled:y,children:[y&&e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}),"Move to ",i]})]})]})]})})}const qQs=[{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 Xjt({open:s,onOpenChange:t}){const n=wa(),{data:r,isLoading:a}=mht(),i=oJt(),[l,o]=N.useState({logo_url:null,cover_photo_url:null,brand_color:null,accent_color:null,tagline:null,welcome_message:null}),[c,d]=N.useState(null);N.useEffect(()=>{s&&o({logo_url:(r==null?void 0:r.logo_url)??null,cover_photo_url:(r==null?void 0:r.cover_photo_url)??null,brand_color:(r==null?void 0:r.brand_color)??null,accent_color:(r==null?void 0:r.accent_color)??null,tagline:(r==null?void 0:r.tagline)??null,welcome_message:(r==null?void 0:r.welcome_message)??null})},[s,r]);const u=f=>o(y=>({...y,...f})),h=async(f,y)=>{if(n){if(f.size>5*1024*1024){ae.error("Image must be under 5MB");return}d(y);try{const _=await pht(n,f,y);u(y==="logo"?{logo_url:_}:{cover_photo_url:_})}catch(_){ae.error(`Upload failed: ${_.message||_}`)}finally{d(null)}}},p=async()=>{try{await i.mutateAsync(l),ae.success("Portal branding saved"),t(!1)}catch{ae.error("Failed to save branding")}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-5 w-5 text-primary"}),"Portal Branding"]}),e.jsx(Jn,{children:"Customize how your client portals look. These defaults apply to every portal — you can override them per deal."})]}),e.jsx(di,{className:"flex-1 pr-3 -mr-3",children:a?e.jsx("div",{className:"py-12 flex justify-center",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):e.jsxs("div",{className:"space-y-6 py-2",children:[e.jsx(VQs,{draft:l}),e.jsx(UQe,{label:"Logo",hint:"Shown above your name on the portal. PNG with transparent background works best.",value:l.logo_url,uploading:c==="logo",onUpload:f=>h(f,"logo"),onClear:()=>u({logo_url:null}),aspect:"square"}),e.jsx(UQe,{label:"Cover Photo",hint:"Hero background at the top of the portal. Wide landscape works best.",value:l.cover_photo_url,uploading:c==="cover",onUpload:f=>h(f,"cover"),onClear:()=>u({cover_photo_url:null}),aspect:"cover"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{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:qQs.map(f=>{const y=l.brand_color===f.brand&&l.accent_color===f.accent;return e.jsxs("button",{type:"button",onClick:()=>u({brand_color:f.brand,accent_color:f.accent}),className:Mt("group relative rounded-lg border-2 p-2 text-left transition-all",y?"border-primary ring-2 ring-primary/20":"border-input hover:border-primary/40"),children:[e.jsxs("div",{className:"flex h-6 rounded-md overflow-hidden",children:[e.jsx("div",{className:"flex-1",style:{background:f.brand}}),e.jsx("div",{className:"flex-1",style:{background:f.accent}})]}),e.jsx("div",{className:"text-[11px] mt-1.5 font-medium text-foreground",children:f.name})]},f.name)})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(qQe,{label:"Brand",value:l.brand_color,onChange:f=>u({brand_color:f})}),e.jsx(qQe,{label:"Accent",value:l.accent_color,onChange:f=>u({accent_color:f})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Tagline"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Short line shown under your name."}),e.jsx(ye,{value:l.tagline||"",onChange:f=>u({tagline:f.target.value}),placeholder:"Your trusted real estate advisor",maxLength:80})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Default Welcome Message"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Shown on the portal hero. Per-deal welcome messages override this."}),e.jsx("textarea",{value:l.welcome_message||"",onChange:f=>u({welcome_message:f.target.value}),placeholder:"Welcome! Here's everything you need for your transaction.",className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[70px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",maxLength:300})]})]})}),e.jsxs("div",{className:"flex justify-end gap-2 pt-4 border-t shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsxs(B,{onClick:p,disabled:i.isPending,children:[i.isPending?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),"Save Branding"]})]})]})})}function VQs({draft:s}){const t=s.brand_color||"#2a4c64",n=s.accent_color||"#406E71";return e.jsxs("div",{className:"rounded-xl overflow-hidden border border-input shadow-sm",children:[e.jsx("div",{className:"relative h-24 flex items-center justify-center text-white",style:{background:s.cover_photo_url?`linear-gradient(135deg, ${t}cc, ${n}cc), url(${s.cover_photo_url}) center/cover`:`linear-gradient(135deg, ${t}, ${n})`},children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:"logo",className:"h-12 w-12 rounded-full object-cover border-2 border-white/40 shadow"}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-white/20 border-2 border-white/40"})}),e.jsxs("div",{className:"bg-white p-3 text-center",children:[e.jsx("div",{className:"text-sm font-semibold text-slate-800",children:"Your Name"}),e.jsx("div",{className:"text-[11px] text-slate-500",children:s.tagline||"Your tagline appears here"})]})]})}function UQe({label:s,hint:t,value:n,uploading:r,onUpload:a,onClear:i,aspect:l}){return e.jsxs("div",{children:[e.jsx(ne,{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:Mt("rounded-lg border-2 border-dashed border-input flex items-center justify-center overflow-hidden bg-muted/30 shrink-0",l==="square"?"h-16 w-16":"h-16 w-32"),children:n?e.jsx("img",{src:n,alt:s,className:"h-full w-full object-cover"}):e.jsx(Xo,{className:"h-5 w-5 text-muted-foreground/40"})}),e.jsxs("div",{className:"flex-1 flex gap-2",children:[e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:o=>{var d;const c=(d=o.target.files)==null?void 0:d[0];c&&a(c),o.target.value=""}}),e.jsxs("span",{className:"inline-flex items-center gap-1.5 h-9 px-3 rounded-md border border-input bg-background hover:bg-accent text-sm font-medium",children:[r?e.jsx(rs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(_a,{className:"h-3.5 w-3.5"}),n?"Replace":"Upload"]})]}),n&&e.jsx(B,{variant:"ghost",size:"sm",onClick:i,className:"text-muted-foreground hover:text-destructive",children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]})}function qQe({label:s,value:t,onChange:n}){const r=t||"#000000";return e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:s}),e.jsxs("div",{className:"mt-1 flex items-center gap-2 h-9 rounded-md border border-input bg-background px-2",children:[e.jsx("input",{type:"color",value:r,onChange:a=>n(a.target.value),className:"h-6 w-8 rounded cursor-pointer border-0 bg-transparent"}),e.jsx(ye,{value:t||"",onChange:a=>n(a.target.value||null),placeholder:"#406E71",className:"border-0 h-7 px-1 focus-visible:ring-0 text-xs font-mono"})]})]})}function HQs(){const s=wa();return dt({queryKey:["all-client-portals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("client_portals").select("*").eq("owner_user_id",s);if(n)throw n;return t||[]},enabled:!!s})}function GQs({dealId:s,dealName:t,contactName:n,portal:r,onSettingsOpen:a,onComposerOpen:i,onInviteOpen:l,onDeleteConfirm:o}){const c=QPe(),d=xR(),u=v_t(),h=b_t(),[p,f]=N.useState(!1),y=!!(r!=null&&r.archived_at),_=async()=>{f(!0);try{await c.mutateAsync({deal_id:s,visibility:"private",require_onboarding:!0}),ae.success("Portal enabled!")}catch{ae.error("Failed to create portal")}finally{f(!1)}},v=async E=>{if(r)try{await d.mutateAsync({id:r.id,is_enabled:E}),ae.success(E?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update portal")}},j=()=>{r&&(navigator.clipboard.writeText(kw(r.slug)),ae.success("Link copied!"))},w=()=>{r&&window.open(kw(r.slug),"_blank")},S=async()=>{if(r)try{await u.mutateAsync(r.id),ae.success("Portal archived")}catch{ae.error("Failed to archive portal")}},A=async()=>{if(r)try{await h.mutateAsync(r.id),ae.success("Portal restored")}catch{ae.error("Failed to restore portal")}};return r?y?e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg opacity-60 bg-muted/30",children:[e.jsxs(In,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0 hover:opacity-80",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx(Ue,{variant:"outline",className:"text-[10px] bg-muted text-muted-foreground",children:"Archived"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:A,className:"text-xs gap-1",children:[e.jsx(HP,{className:"h-3.5 w-3.5"}),"Restore"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>o(r),className:"text-xs gap-1 text-destructive hover:text-destructive",children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Delete"]})]})]}):e.jsxs("div",{className:"flex items-center gap-4 p-4 border rounded-lg hover:border-primary/40 hover:bg-muted/30 transition-colors group",children:[e.jsxs(In,{to:`/mission-control/client-portals/${r.id}`,className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium text-sm truncate group-hover:text-primary transition-colors",children:t}),e.jsx(Ue,{variant:"outline",className:r.is_enabled?"text-[10px] bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-[10px] bg-muted text-muted-foreground",children:r.is_enabled?"Active":"Disabled"}),e.jsx(ga,{className:"h-3.5 w-3.5 text-muted-foreground opacity-0 group-hover:opacity-100 transition-opacity"})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.client_name||n||"No client name"})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:j,title:"Copy link",children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:w,title:"Preview",children:e.jsx(tr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(r,t),title:"Invite client",children:e.jsx(lr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>i(r),title:"Post update",children:e.jsx(X_,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>a(r),title:"Settings",children:e.jsx(Ko,{className:"h-3.5 w-3.5"})}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Kf,{className:"h-3.5 w-3.5"})})}),e.jsx(gc,{align:"end",children:e.jsxs(Kr,{onClick:S,children:[e.jsx(tm,{className:"h-4 w-4 mr-2"}),"Archive Portal"]})})]}),e.jsx(jn,{checked:r.is_enabled,onCheckedChange:v,className:"ml-1"})]})]}):e.jsxs("div",{className:"flex items-center justify-between p-4 border rounded-lg border-dashed bg-muted/20",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:t}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:n||"No contact"})]}),e.jsxs(B,{size:"sm",onClick:_,disabled:p,className:"shrink-0 ml-4",children:[p?e.jsx(rs,{className:"h-3 w-3 animate-spin mr-1"}):e.jsx(un,{className:"h-3 w-3 mr-1"}),"Enable Portal"]})]})}function Jjt(){const{data:s,isLoading:t}=U1e(),{data:n,isLoading:r}=HQs(),[a,i]=N.useState(""),[l,o]=N.useState("all"),c=__t(),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,y]=N.useState(null),[_,v]=N.useState(null),[j,w]=N.useState(!1),S=wa(),A=t||r,E=new Map;n==null||n.forEach(Z=>E.set(Z.deal_id,Z));const D=[...(s||[]).filter(Z=>{var oe,he,ce,me,le;const Y=E.get(Z.id),W=a.toLowerCase(),ee=!W||Z.deal_name.toLowerCase().includes(W)||((he=(oe=Z.contact)==null?void 0:oe.first_name)==null?void 0:he.toLowerCase().includes(W))||((me=(ce=Z.contact)==null?void 0:ce.last_name)==null?void 0:me.toLowerCase().includes(W))||((le=Y==null?void 0:Y.client_name)==null?void 0:le.toLowerCase().includes(W));let se=!0;return l==="active"?se=!!(Y!=null&&Y.is_enabled)&&!(Y!=null&&Y.archived_at):l==="disabled"?se=!!Y&&!Y.is_enabled&&!Y.archived_at:l==="archived"?se=!!(Y!=null&&Y.archived_at):l==="none"?se=!Y:l==="all"&&(se=!(Y!=null&&Y.archived_at)||!Y),ee&&se})].sort((Z,Y)=>{const W=E.get(Z.id),ee=E.get(Y.id);if(W!=null&&W.archived_at&&!(ee!=null&&ee.archived_at))return 1;if(!(W!=null&&W.archived_at)&&(ee!=null&&ee.archived_at)||W&&!ee)return-1;if(!W&&ee)return 1;if(W&&ee){if(W.is_enabled&&!ee.is_enabled)return-1;if(!W.is_enabled&&ee.is_enabled)return 1}return 0}),I=(n==null?void 0:n.filter(Z=>!Z.archived_at).length)||0,F=(n==null?void 0:n.filter(Z=>Z.is_enabled&&!Z.archived_at).length)||0,z=(n==null?void 0:n.filter(Z=>Z.archived_at).length)||0,H=async()=>{if(_)try{await c.mutateAsync({id:_.id,dealId:_.deal_id}),ae.success("Portal permanently deleted"),v(null)}catch{ae.error("Failed to delete portal")}};return A?e.jsx("div",{className:"flex items-center justify-center py-16",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4 text-sm",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsxs("span",{className:"font-medium",children:[I," Portals"]})]}),e.jsxs("span",{className:"text-muted-foreground",children:[F," active · ",I-F," disabled",z>0&&` · ${z} archived`]})]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>w(!0),className:"gap-1.5",children:[e.jsx(pl,{className:"h-3.5 w-3.5"}),"Portal Branding"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals or clients...",value:a,onChange:Z=>i(Z.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($n,{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(Z=>e.jsx(B,{variant:l===Z?"secondary":"ghost",size:"sm",onClick:()=>o(Z),className:"text-xs px-3 capitalize",children:Z==="none"?"No Portal":Z},Z))})]}),e.jsx(di,{className:"h-[calc(100vh-22rem)]",children:e.jsxs("div",{className:"space-y-2 pb-4",children:[D.map(Z=>{const Y=E.get(Z.id)||null,W=Z.contact?`${Z.contact.first_name||""} ${Z.contact.last_name||""}`.trim():"";return e.jsx(GQs,{dealId:Z.id,dealName:Z.deal_name,contactName:W,portal:Y,onSettingsOpen:u,onComposerOpen:ee=>p(ee),onInviteOpen:(ee,se)=>y({portal:ee,dealName:se}),onDeleteConfirm:v},Z.id)}),D.length===0&&e.jsxs("div",{className:"text-center py-12",children:[e.jsx("div",{className:"w-12 h-12 mx-auto mb-3 bg-muted rounded-full flex items-center justify-center",children:e.jsx(un,{className:"h-5 w-5 text-muted-foreground"})}),e.jsx("p",{className:"text-sm font-medium",children:"No matching deals"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Try adjusting your search or filters"})]})]})})]}),d&&e.jsx(JLe,{open:!!d,onOpenChange:Z=>!Z&&u(null),portal:d,dealOwnerId:S||""}),h&&e.jsx(e8e,{open:!!h,onOpenChange:Z=>!Z&&p(null),portalId:h.id,portalSlug:h.slug,notifyClient:h.notify_client}),f&&e.jsx(t8e,{open:!!f,onOpenChange:Z=>!Z&&y(null),portal:f.portal,dealName:f.dealName}),e.jsx(Xjt,{open:j,onOpenChange:w}),e.jsx(Oo,{open:!!_,onOpenChange:Z=>!Z&&v(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Permanently delete this portal?"}),e.jsx(Mo,{children:"This will permanently remove the portal and all its updates. The client will no longer be able to access their portal page. This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:H,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}class WQs extends N.Component{constructor(t){super(t),this.state={hasError:!1,error:null}}static getDerivedStateFromError(t){return{hasError:!0,error:t}}componentDidCatch(t,n){console.error("DealPipeline error:",t,n)}render(){return this.state.hasError?e.jsx(Cs,{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 AF="deal-pipeline-detail-sheet";function KQs(){var ks;const s=fR(),{data:t,isLoading:n}=$1e(),{data:r,isLoading:a,refetch:i}=U1e(),{data:l,isLoading:o}=uZs(),c=qjt(),d=rZs(),[u,h]=N.useState("board"),[p,f]=N.useState(!1),[y,_]=N.useState(!1),[v,j]=N.useState(null),[w,S]=N.useState(null),[A,E]=N.useState(null),[O,D]=N.useState(null),[I,F]=N.useState(!1),[z,H]=N.useState(null),[Z,Y]=N.useState(""),[W,ee]=N.useState("all"),[se,oe]=N.useState("all"),[he,ce]=N.useState("all"),{data:me}=JZs(),[le,ve]=N.useState(!1),[ge,Te]=N.useState(!1),[Ie,Ce]=N.useState(new Set),Me=N.useRef(!1),[Pe,Re]=N.useState(null),{data:Ae}=Wv(),{isTeamLeader:Be,teamMembers:we}=QZs(),Je=N.useMemo(()=>Array.from(Ie),[Ie]),{data:ke}=XZs(Je),it=N.useMemo(()=>{const $s=new Map;return we.forEach(an=>$s.set(an.id,{name:an.name,avatar_url:an.avatar_url,color:an.color})),$s},[we]),je=N.useCallback($s=>$s.owner_user_id&&it.get($s.owner_user_id)||null,[it]),He=N.useCallback($s=>{Ce(an=>{const tn=new Set(an);return tn.has($s)?tn.delete($s):tn.add($s),tn})},[]);N.useEffect(()=>{!n&&t&&t.length===0&&c.mutate()},[n,t]);const[$e,Ke]=xl(),Ge=N.useRef(!1);N.useEffect(()=>{const $s=$e.get("deal");if($s&&r&&r.length>0&&!Ge.current){const an=r.find(tn=>tn.id===$s);an&&(Ge.current=!0,j(an),_(!0),$e.delete("deal"),Ke($e,{replace:!0}))}},[r,$e]);const rt=N.useMemo(()=>{if(!ke||!t)return[];const $s=new Map(t.map(an=>[an.name,an.id]));return ke.map(an=>{const tn=an._stage_name&&$s.get(an._stage_name)||null;return{...an,stage_id:tn||an.stage_id}})},[ke,t]),tt=N.useMemo(()=>[...r||[],...rt],[r,rt]);N.useEffect(()=>{if(Me.current||tt.length===0)return;Me.current=!0;const $s=sessionStorage.getItem(AF);if($s)try{const an=JSON.parse($s);if(!an.open||!an.dealId)return;const tn=tt.find(er=>er.id===an.dealId);tn&&(j(tn),_(!0))}catch{sessionStorage.removeItem(AF)}},[tt]),N.useEffect(()=>{y&&(v!=null&&v.id)?sessionStorage.setItem(AF,JSON.stringify({dealId:v.id,open:!0})):sessionStorage.removeItem(AF)},[y,v==null?void 0:v.id]);const at=(me==null?void 0:me.byDeal)||{},Ye=(me==null?void 0:me.unique)||[],ut=tt.filter($s=>{var Es,mi,Ar,Hn,Ts,Un;const an=Z.toLowerCase(),tn=at[$s.id]||[],er=!an||$s.deal_name.toLowerCase().includes(an)||((mi=(Es=$s.contact)==null?void 0:Es.first_name)==null?void 0:mi.toLowerCase().includes(an))||((Hn=(Ar=$s.contact)==null?void 0:Ar.last_name)==null?void 0:Hn.toLowerCase().includes(an))||((Ts=$s.property_address)==null?void 0:Ts.toLowerCase().includes(an))||((Un=$s.city)==null?void 0:Un.toLowerCase().includes(an))||tn.some(ir=>ir.toLowerCase().includes(an)),xn=W==="all"||$s.deal_type===W,Pn=se==="all"||tn.includes(se),Qn=$s.actual_close_date||$s.target_close_date||$s.contract_date||$s.created_at,sa=Qn?String(Qn).slice(0,4):null;return er&&xn&&Pn&&(he==="all"||sa===he)}),_t=N.useMemo(()=>{const $s=new Set;return $s.add(String(new Date().getFullYear())),tt.forEach(an=>{const tn=an.actual_close_date||an.target_close_date||an.contract_date||an.created_at;tn&&$s.add(String(tn).slice(0,4))}),Array.from($s).sort((an,tn)=>Number(tn)-Number(an))},[tt]),bt=N.useMemo(()=>{if(!t)return l||null;const $s=new Set(t.filter(Qn=>Qn.is_won_stage).map(Qn=>Qn.id)),an=new Set(t.filter(Qn=>Qn.is_lost_stage).map(Qn=>Qn.id)),tn=tt.filter(Qn=>Qn.stage_id&&!$s.has(Qn.stage_id)&&!an.has(Qn.stage_id)),er=tt.filter(Qn=>Qn.stage_id&&$s.has(Qn.stage_id)),xn=new Date().getFullYear(),Pn=er.filter(Qn=>Qn.actual_close_date?new Date(Qn.actual_close_date).getFullYear()===xn:!0);return{totalDeals:tt.length,activeDeals:tn.length,wonDeals:er.length,pipelineValue:tn.reduce((Qn,sa)=>Qn+(sa.expected_price||0),0),expectedCommission:tn.reduce((Qn,sa)=>Qn+(sa.expected_commission||0),0),expectedNetToAgent:tn.reduce((Qn,sa)=>Qn+(Sv(sa)||0),0),wonValue:er.reduce((Qn,sa)=>Qn+(sa.expected_price||0),0),weightedGCI:tn.reduce((Qn,sa)=>Qn+(sa.expected_commission||0)*((sa.probability??50)/100),0),weightedNet:tn.reduce((Qn,sa)=>Qn+(Sv(sa)||0)*((sa.probability??50)/100),0),ytdWonDeals:Pn.length,ytdWonGCI:Pn.reduce((Qn,sa)=>Qn+(sa.expected_commission||0),0),ytdWonNet:Pn.reduce((Qn,sa)=>Qn+(Sv(sa)||0),0),projectedAnnualNet:Pn.reduce((Qn,sa)=>Qn+(Sv(sa)||0),0)+tn.reduce((Qn,sa)=>Qn+(Sv(sa)||0)*((sa.probability??50)/100),0)}},[tt,t,l]),$t=$s=>{j($s),_(!0)},Yt=$s=>{S($s||null),j(null),f(!0)},Ds=$s=>{j($s),_(!1),f(!0)},Ls=$s=>{_($s),$s||sessionStorage.removeItem(AF)},xs=($s,an)=>{E($s)},Lt=($s,an)=>{$s.preventDefault(),$s.dataTransfer.dropEffect="move",D(an)},Jt=async($s,an)=>{if($s.preventDefault(),D(null),!A)return;const tn=r==null?void 0:r.find(Pn=>Pn.id===A),er=t==null?void 0:t.find(Pn=>Pn.id===an),xn=t==null?void 0:t.find(Pn=>Pn.id===(tn==null?void 0:tn.stage_id));if(!tn||!er||tn.stage_id===an){E(null);return}Re({dealId:A,dealName:tn.deal_name,fromStageName:(xn==null?void 0:xn.name)||"Unknown",toStageName:er.name,toStageId:an,isWonStage:er.is_won_stage,deal:tn}),E(null)},gt=async()=>{if(!Pe)return;const{dealId:$s,toStageId:an,toStageName:tn,isWonStage:er,deal:xn}=Pe;if(await d.mutateAsync({dealId:$s,stageId:an,stageName:tn}),ae.success(`Moved to ${tn}`),er&&!xn.scorecard_transaction_id){const Pn={...xn,stage_id:an};H(Pn),F(!0)}},zt=N.useCallback(async($s,an,tn)=>{const er=r==null?void 0:r.find(Qn=>Qn.id===$s),xn=t==null?void 0:t.find(Qn=>Qn.id===an),Pn=t==null?void 0:t.find(Qn=>Qn.id===(er==null?void 0:er.stage_id));!er||!xn||er.stage_id===an||Re({dealId:$s,dealName:er.deal_name,fromStageName:(Pn==null?void 0:Pn.name)||"Unknown",toStageName:tn,toStageId:an,isWonStage:xn.is_won_stage,deal:er})},[r,t]),As=$s=>ut.filter(an=>an.stage_id===$s),Xt=n||a,Qs=s?"list":u;return e.jsxs(Cs,{children:[e.jsxs("div",{className:"flex flex-col h-[calc(100vh-4rem)]",children:[e.jsxs("div",{className:"shrink-0 p-4 md:p-6 pb-0 space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Deal Pipeline"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Track and manage your active deals"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>i(),className:"shrink-0",children:e.jsx(Ei,{className:"h-4 w-4"})}),!s&&e.jsx(Vw,{children:e.jsxs("div",{className:"flex bg-muted rounded-lg p-1 gap-0.5",children:[e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsxs(B,{variant:u==="board"?"secondary":"ghost",size:"sm",onClick:()=>h("board"),className:"px-3 gap-1.5",children:[e.jsx(ff,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Board"})]})}),e.jsx(Nc,{children:"Kanban board view"})]}),e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsxs(B,{variant:u==="list"?"secondary":"ghost",size:"sm",onClick:()=>h("list"),className:"px-3 gap-1.5",children:[e.jsx(Sp,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"List"})]})}),e.jsx(Nc,{children:"Grouped list view"})]}),e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsxs(B,{variant:u==="table"?"secondary":"ghost",size:"sm",onClick:()=>h("table"),className:"px-3 gap-1.5",children:[e.jsx(hL,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Table"})]})}),e.jsx(Nc,{children:"Sortable table view"})]}),e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsxs(B,{variant:u==="portals"?"secondary":"ghost",size:"sm",onClick:()=>h("portals"),className:"px-3 gap-1.5",children:[e.jsx(un,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden sm:inline text-xs",children:"Portals"})]})}),e.jsx(Nc,{children:"Client portal management"})]})]})}),Ae&&!Be&&e.jsxs(B,{variant:"outline",onClick:()=>ve(!0),children:[e.jsx(An,{className:"h-4 w-4 mr-2"}),"Team"]}),e.jsxs(B,{onClick:()=>Yt(),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Deal"]})]})]}),Qs!=="portals"&&e.jsx(nQs,{stats:bt,isLoading:o}),Qs!=="portals"&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search deals, contacts, addresses, tags...",value:Z,onChange:$s=>Y($s.target.value),className:"pl-9 pr-8"}),Z&&e.jsx("button",{onClick:()=>Y(""),className:"absolute right-2 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground",children:e.jsx($n,{className:"h-4 w-4"})})]}),e.jsxs(us,{value:W,onValueChange:ee,children:[e.jsx(ls,{className:"w-[140px]",children:e.jsx(hs,{placeholder:"All Types"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"}),e.jsx(Ze,{value:"dual",children:"Dual"}),e.jsx(Ze,{value:"referral",children:"Referral"}),e.jsx(Ze,{value:"lease",children:"Lease"})]})]}),e.jsxs(us,{value:he,onValueChange:ce,children:[e.jsx(ls,{className:"w-[120px]",children:e.jsx(hs,{placeholder:"Year"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Years"}),_t.map($s=>e.jsx(Ze,{value:$s,children:$s},$s))]})]}),e.jsxs(us,{value:se,onValueChange:oe,children:[e.jsxs(ls,{className:"w-[160px]",children:[e.jsx(oh,{className:"h-3.5 w-3.5 mr-1.5 text-muted-foreground"}),e.jsx(hs,{placeholder:"All Tags"})]}),e.jsxs(cs,{className:"max-h-[300px]",children:[e.jsx(Ze,{value:"all",children:"All Tags"}),Ye.length===0&&e.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No tags yet"}),Ye.map($s=>e.jsx(Ze,{value:$s,children:$s},$s))]})]}),se!=="all"&&e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(oh,{className:"h-3 w-3"}),se,e.jsx("button",{onClick:()=>oe("all"),className:"ml-1 hover:text-foreground","aria-label":"Clear tag filter",children:e.jsx($n,{className:"h-3 w-3"})})]}),(Z||W!=="all"||se!=="all"||he!=="all")&&e.jsxs("span",{className:"text-xs text-muted-foreground whitespace-nowrap",children:[ut.length," of ",(r==null?void 0:r.length)||0," deals"]})]})]}),e.jsxs("div",{className:"flex-1 min-h-0 flex",children:[Be&&!s&&we.length>0&&e.jsx(ZZs,{members:we,enabledMembers:Ie,onToggleMember:He,isOpen:ge,onToggleOpen:()=>Te($s=>!$s)}),e.jsx("div",{className:"flex-1 min-w-0 min-h-0 p-4 md:p-6 pt-4",children:Xt?e.jsx("div",{className:"flex gap-4 h-full",children:[1,2,3,4].map($s=>e.jsx("div",{className:"min-w-[280px] max-w-[320px] flex-shrink-0",children:e.jsx(Ws,{className:"h-full rounded-xl"})},$s))}):Qs==="board"?e.jsxs(di,{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($s=>e.jsx(sQs,{stage:$s,deals:As($s.id),onDealClick:$t,onAddDeal:Yt,onDragStart:xs,onDragOver:Lt,onDrop:Jt,isDragOver:O===$s.id,isWonStage:$s.is_won_stage,getOwnerInfo:je},$s.id))}),e.jsx(Q$,{orientation:"horizontal"})]}):Qs==="table"?e.jsx(di,{className:"h-full",children:e.jsx(AQs,{deals:ut,stages:t||[],onDealClick:$t,onStageChange:zt})}):Qs==="portals"?e.jsx(Jjt,{}):e.jsx(di,{className:"h-full",children:e.jsxs("div",{className:"space-y-6",children:[t==null?void 0:t.map($s=>{const an=As($s.id);return an.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:$s.color}}),e.jsx("h3",{className:"font-semibold",children:$s.name}),e.jsxs("span",{className:"text-muted-foreground text-sm",children:["(",an.length,")"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-3",children:an.map(tn=>e.jsx(Zjt,{deal:tn,onClick:()=>$t(tn),stages:t,onStageChange:zt,showStagePicker:!0,isWonStage:$s.is_won_stage,ownerInfo:je(tn)},tn.id))})]},$s.id)}),(r==null?void 0:r.length)===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(ff,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No deals yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start tracking your opportunities by adding your first deal"}),e.jsxs(B,{onClick:()=>Yt(),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Your First Deal"]})]}),((r==null?void 0:r.length)||0)>0&&ut.length===0&&e.jsxs("div",{className:"text-center py-16",children:[e.jsx("div",{className:"w-16 h-16 mx-auto mb-4 bg-muted rounded-full flex items-center justify-center",children:e.jsx(gr,{className:"h-8 w-8 text-muted-foreground"})}),e.jsx("h3",{className:"font-semibold text-lg mb-2",children:"No matching deals"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Try adjusting your search or filters"}),e.jsx(B,{variant:"outline",onClick:()=>{Y(""),ee("all"),oe("all"),ce("all")},children:"Clear Filters"})]})]})})})]})]}),e.jsx(oQs,{open:p,onOpenChange:f,deal:v,defaultStageId:w}),e.jsx(CQs,{deal:v,open:y,onOpenChange:Ls,onEdit:Ds,isWonStage:v?(ks=t==null?void 0:t.find($s=>$s.id===v.stage_id))==null?void 0:ks.is_won_stage:!1,onAddToScorecard:$s=>{H($s),F(!0),_(!1)}}),e.jsx(TQs,{open:I,onOpenChange:F,deal:z,onComplete:()=>{i(),H(null)}}),Pe&&e.jsx(UQs,{open:!!Pe,onOpenChange:$s=>{$s||Re(null)},dealId:Pe.dealId,dealName:Pe.dealName,fromStageName:Pe.fromStageName,toStageName:Pe.toStageName,toStageId:Pe.toStageId,onConfirm:gt}),e.jsx(KZs,{open:le,onOpenChange:ve})]})}function YQs(){return e.jsx(WQs,{children:e.jsx(KQs,{})})}function e2t({open:s,onOpenChange:t,editTask:n,defaultDealId:r,defaultStageId:a}){var Y;const i=PQs(),l=LQs(),{data:o}=U1e(),c=wa(),{data:d}=dt({queryKey:["contacts-for-tasks",c],queryFn:async()=>{if(!c)return[];const{data:W,error:ee}=await q.from("innercircle_contacts").select("id, first_name, last_name").eq("owner_user_id",c).order("first_name").limit(500);if(ee)throw ee;return W},enabled:!!c&&s}),[u,h]=N.useState(""),[p,f]=N.useState(""),[y,_]=N.useState("none"),[v,j]=N.useState("none"),[w,S]=N.useState("medium"),[A,E]=N.useState("todo"),[O,D]=N.useState(),[I,F]=N.useState(!1),[z,H]=N.useState(!1);N.useEffect(()=>{n?(h(n.title),f(n.description||""),_(n.deal_id||"none"),j(n.contact_id||"none"),S(n.priority),E(n.status),D(n.due_date?Zh(n.due_date):void 0)):(h(""),f(""),_(r||"none"),j("none"),S("medium"),E("todo"),D(void 0))},[n,s,r]);const Z=async()=>{if(!u.trim()){ae.error("Task title is required");return}try{const W={title:u.trim(),description:p.trim()||null,deal_id:y==="none"?null:y,contact_id:v==="none"?null:v,stage_id:a||null,priority:w,status:A,due_date:O?Ss(O,"yyyy-MM-dd"):null};n?(await l.mutateAsync({id:n.id,...W}),ae.success("Task updated")):(await i.mutateAsync(W),ae.success("Task created")),t(!1)}catch{ae.error("Failed to save task")}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[480px]",children:[e.jsx(js,{children:e.jsx(ws,{children:n?"Edit Task":"New Task"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title *"}),e.jsx(ye,{value:u,onChange:W=>h(W.target.value),placeholder:"e.g., Send inspection report"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{value:p,onChange:W=>f(W.target.value),placeholder:"Optional details...",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Priority"}),e.jsxs(us,{value:w,onValueChange:W=>S(W),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"low",children:"🟢 Low"}),e.jsx(Ze,{value:"medium",children:"🟡 Medium"}),e.jsx(Ze,{value:"high",children:"🟠 High"}),e.jsx(Ze,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Status"}),e.jsxs(us,{value:A,onValueChange:W=>E(W),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"todo",children:"To Do"}),e.jsx(Ze,{value:"in_progress",children:"In Progress"}),e.jsx(Ze,{value:"done",children:"Done"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Due Date"}),e.jsxs(il,{children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",className:Mt("w-full justify-start text-left font-normal",!O&&"text-muted-foreground"),children:[e.jsx(yr,{className:"mr-2 h-4 w-4"}),O?Ss(O,"PPP"):"Pick a date"]})}),e.jsx(el,{className:"w-auto p-0",align:"start",children:e.jsx(Gg,{mode:"single",selected:O,onSelect:D,initialFocus:!0,className:"p-3 pointer-events-auto"})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Link to Deal"}),e.jsxs(il,{open:I,onOpenChange:F,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Ua,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),y!=="none"?((Y=o==null?void 0:o.find(W=>W.id===y))==null?void 0:Y.deal_name)||"Select deal":"No Deal"]}),e.jsx($g,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search deals..."}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:"No deals found."}),e.jsxs(Jg,{children:[e.jsxs(Zf,{value:"no-deal",onSelect:()=>{_("none"),F(!1)},children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",y==="none"?"opacity-100":"opacity-0")}),"No Deal"]}),o==null?void 0:o.map(W=>e.jsxs(Zf,{value:W.deal_name,onSelect:()=>{_(W.id),F(!1)},children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",y===W.id?"opacity-100":"opacity-0")}),W.deal_name]},W.id))]})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Link to Contact"}),e.jsxs(il,{open:z,onOpenChange:H,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between font-normal",children:[e.jsxs("span",{className:"flex items-center gap-2 truncate",children:[e.jsx(Wi,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),v!=="none"?(()=>{const W=d==null?void 0:d.find(ee=>ee.id===v);return W?`${W.first_name} ${W.last_name}`:"Select contact"})():"No Contact"]}),e.jsx($g,{className:"h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search contacts..."}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:"No contacts found."}),e.jsxs(Jg,{children:[e.jsxs(Zf,{value:"no-contact",onSelect:()=>{j("none"),H(!1)},children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",v==="none"?"opacity-100":"opacity-0")}),"No Contact"]}),d==null?void 0:d.map(W=>e.jsxs(Zf,{value:`${W.first_name} ${W.last_name}`,onSelect:()=>{j(W.id),H(!1)},children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",v===W.id?"opacity-100":"opacity-0")}),W.first_name," ",W.last_name]},W.id))]})]})]})})]})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:Z,disabled:i.isPending||l.isPending,children:n?"Save Changes":"Create Task"})]})]})]})})}const ZQs={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 QQs({tasks:s}){const t=s8e(),n=DQs(),r=Ln(),[a,i]=N.useState(null),l=async u=>{const h=u.status==="done"?"todo":"done";try{await t.mutateAsync({id:u.id,status:h})}catch{ae.error("Failed to update task")}},o=async u=>{try{await n.mutateAsync(u),ae.success("Task deleted")}catch{ae.error("Failed to delete task")}};if(s.length===0)return e.jsxs("div",{className:"flex flex-col items-center justify-center py-20 text-center",children:[e.jsx(vr,{className:"h-12 w-12 text-muted-foreground/30 mb-3"}),e.jsx("p",{className:"text-muted-foreground font-medium",children:"No tasks found"}),e.jsx("p",{className:"text-muted-foreground/60 text-sm",children:"Create a new task to get started"})]});const c=new Map,d=[];return s.forEach(u=>{if(u.deal){const h=c.get(u.deal.id)||{dealName:u.deal.deal_name,tasks:[]};h.tasks.push(u),c.set(u.deal.id,h)}else d.push(u)}),e.jsxs("div",{className:"space-y-4",children:[d.length>0&&e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 px-4 py-2 border-b",children:e.jsx("h3",{className:"font-medium text-sm text-muted-foreground",children:"General Tasks"})}),d.map(u=>e.jsx(VQe,{task:u,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:h=>r(`/mission-control/pipeline?deal=${h}`)},u.id))]}),Array.from(c.entries()).map(([u,h])=>e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>r(`/mission-control/pipeline?deal=${u}`),className:"w-full bg-muted/30 px-4 py-2 border-b flex items-center gap-2 hover:bg-muted/50 transition-colors text-left",children:[e.jsx(Ua,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("h3",{className:"font-medium text-sm",children:h.dealName}),e.jsxs(Ue,{variant:"secondary",className:"ml-auto text-xs",children:[h.tasks.filter(p=>p.status==="done").length,"/",h.tasks.length]}),e.jsx(ga,{className:"h-3.5 w-3.5 text-muted-foreground"})]}),h.tasks.map(p=>e.jsx(VQe,{task:p,onToggle:l,onDelete:o,onEdit:i,onNavigateDeal:f=>r(`/mission-control/pipeline?deal=${f}`)},p.id))]},u)),a&&e.jsx(e2t,{open:!!a,onOpenChange:()=>i(null),editTask:a})]})}function VQe({task:s,onToggle:t,onDelete:n,onEdit:r,onNavigateDeal:a}){const i=s.status==="done",l=!i&&s.due_date&&vw(Zh(s.due_date))&&!of(Zh(s.due_date)),o=!i&&s.due_date&&of(Zh(s.due_date)),c=ZQs[s.priority];return e.jsxs("div",{className:Mt("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(vr,{className:"h-5 w-5 text-emerald-500"}):e.jsx(am,{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:Mt("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(Wi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]})]}),e.jsxs(Ue,{variant:"outline",className:Mt("text-[10px] shrink-0",c.color),children:[c.dot," ",c.label]}),s.due_date&&e.jsxs("span",{className:Mt("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(pr,{className:"h-3 w-3"}),Ss(Zh(s.due_date),"MMM d")]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx("button",{onClick:()=>r(s),className:"p-1 hover:bg-muted rounded",children:e.jsx(wu,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsx("button",{onClick:()=>n(s.id),className:"p-1 hover:bg-destructive/10 rounded",children:e.jsx(_n,{className:"h-3.5 w-3.5 text-destructive"})})]})]})}const XQs=[{status:"todo",label:"To Do",icon:am,color:"border-t-slate-400"},{status:"in_progress",label:"In Progress",icon:jh,color:"border-t-blue-500"},{status:"done",label:"Done",icon:vr,color:"border-t-emerald-500"}],JQs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function eXs({tasks:s}){const t=s8e(),n=N.useMemo(()=>{const i={todo:[],in_progress:[],done:[]};return s.forEach(l=>i[l.status].push(l)),i},[s]),r=(i,l)=>{i.dataTransfer.setData("taskId",l)},a=async(i,l)=>{i.preventDefault();const o=i.dataTransfer.getData("taskId");if(!o)return;const c=s.find(d=>d.id===o);if(!(!c||c.status===l))try{await t.mutateAsync({id:o,status:l})}catch{ae.error("Failed to move task")}};return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:XQs.map(i=>e.jsxs("div",{className:Mt("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(Ue,{variant:"secondary",className:"ml-auto text-xs",children:n[i.status].length})]}),e.jsxs("div",{className:"p-2 space-y-2 min-h-[200px]",children:[n[i.status].map(l=>e.jsx(tXs,{task:l,onDragStart:r},l.id)),n[i.status].length===0&&e.jsx("p",{className:"text-xs text-muted-foreground text-center py-8",children:"Drag tasks here"})]})]},i.status))})}function tXs({task:s,onDragStart:t}){const n=s.status==="done",r=!n&&s.due_date&&vw(Zh(s.due_date))&&!of(Zh(s.due_date)),a=!n&&s.due_date&&of(Zh(s.due_date));return e.jsx("div",{draggable:!0,onDragStart:i=>t(i,s.id),className:Mt("bg-background border rounded-lg p-3 cursor-grab active:cursor-grabbing shadow-sm hover:shadow-md transition-shadow",r&&"border-destructive/50"),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx("span",{className:"text-xs mt-0.5",children:JQs[s.priority]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:Mt("text-sm font-medium",n&&"line-through text-muted-foreground"),children:s.title}),e.jsxs("div",{className:"flex items-center gap-2 mt-1.5 flex-wrap",children:[s.deal&&e.jsxs("span",{className:"text-[10px] text-muted-foreground flex items-center gap-0.5",children:[e.jsx(Ua,{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(Wi,{className:"h-2.5 w-2.5"}),s.contact.first_name," ",s.contact.last_name]})]}),s.due_date&&e.jsxs("div",{className:Mt("text-[10px] mt-1.5 flex items-center gap-1",r&&"text-destructive font-medium",a&&"text-amber-600 font-medium",!r&&!a&&"text-muted-foreground"),children:[e.jsx(pr,{className:"h-2.5 w-2.5"}),r?"Overdue — ":a?"Due today — ":"",Ss(Zh(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 HQe={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function sXs({tasks:s}){const[t,n]=N.useState(new Date),r=s8e(),a=Rd(t),i=$0(t),l=Vm(a),o=x8(i),c=x4e({start:l,end:o}),d=N.useMemo(()=>{const p=new Map;return s.forEach(f=>{if(!f.due_date)return;const y=f.due_date,_=p.get(y)||[];_.push(f),p.set(y,_)}),p},[s]),u=N.useMemo(()=>s.filter(p=>!p.due_date),[s]),h=async p=>{const f=p.status==="done"?"todo":"done";try{await r.mutateAsync({id:p.id,status:f})}catch{ae.error("Failed to update task")}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(BE(t,1)),children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx("h3",{className:"font-semibold",children:Ss(t,"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>n(_f(t,1)),children:e.jsx(ga,{className:"h-4 w-4"})})]}),e.jsx("div",{className:"grid grid-cols-7 text-center",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(p=>e.jsx("div",{className:"text-xs font-medium text-muted-foreground py-2",children:p},p))}),e.jsx("div",{className:"grid grid-cols-7 border-l border-t",children:c.map(p=>{const f=Ss(p,"yyyy-MM-dd"),y=d.get(f)||[],_=W$(p,t),v=of(p);return e.jsxs("div",{className:Mt("border-r border-b min-h-[100px] p-1",!_&&"bg-muted/30",v&&"bg-primary/5"),children:[e.jsx("div",{className:Mt("text-xs font-medium mb-1 text-right px-1",!_&&"text-muted-foreground/40",v&&"text-primary font-bold"),children:Ss(p,"d")}),e.jsxs("div",{className:"space-y-0.5",children:[y.slice(0,3).map(j=>e.jsxs("button",{onClick:()=>h(j),className:Mt("w-full text-left text-[10px] px-1 py-0.5 rounded truncate flex items-center gap-0.5 hover:bg-muted transition-colors",j.status==="done"?"text-muted-foreground line-through":"text-foreground"),children:[j.status==="done"?e.jsx(vr,{className:"h-2.5 w-2.5 text-emerald-500 shrink-0"}):e.jsx(am,{className:"h-2.5 w-2.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[HQe[j.priority]," ",j.title]})]},j.id)),y.length>3&&e.jsxs("p",{className:"text-[9px] text-muted-foreground text-center",children:["+",y.length-3," more"]})]})]},f)})}),u.length>0&&e.jsxs("div",{className:"border rounded-lg p-3",children:[e.jsxs("h4",{className:"text-sm font-medium text-muted-foreground mb-2",children:["No Due Date (",u.length,")"]}),e.jsx("div",{className:"space-y-1",children:u.map(p=>e.jsxs("button",{onClick:()=>h(p),className:Mt("w-full text-left text-xs px-2 py-1.5 rounded flex items-center gap-2 hover:bg-muted transition-colors",p.status==="done"&&"opacity-50 line-through"),children:[p.status==="done"?e.jsx(vr,{className:"h-3.5 w-3.5 text-emerald-500 shrink-0"}):e.jsx(am,{className:"h-3.5 w-3.5 shrink-0"}),e.jsxs("span",{className:"truncate",children:[HQe[p.priority]," ",p.title]}),p.deal&&e.jsxs("span",{className:"text-muted-foreground ml-auto shrink-0",children:["• ",p.deal.deal_name]})]},p.id))})]})]})}const nXs={urgent:"🔴",high:"🟠",medium:"🟡",low:"🟢"};function rXs({open:s,onOpenChange:t,stages:n}){var j;const[r,a]=N.useState(((j=n[0])==null?void 0:j.id)||""),{data:i,isLoading:l}=OQs(r||void 0),o=FQs(),c=zQs(),[d,u]=N.useState(""),[h,p]=N.useState("medium"),[f,y]=N.useState(""),_=async()=>{if(!(!d.trim()||!r))try{await o.mutateAsync({stage_id:r,title:d.trim(),priority:h,default_due_offset_days:f?parseInt(f):null,sort_order:((i==null?void 0:i.length)||0)+1}),u(""),y(""),ae.success("Template added")}catch{ae.error("Failed to add template")}},v=async w=>{try{await c.mutateAsync(w),ae.success("Template deleted")}catch{ae.error("Failed to delete template")}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[560px]",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(H7,{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(ne,{children:"Pipeline Stage"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:n.filter(w=>!w.is_won_stage&&!w.is_lost_stage).map(w=>e.jsx("button",{onClick:()=>a(w.id),className:Mt("px-3 py-1.5 rounded-full text-xs font-medium border transition-colors",r===w.id?"border-primary bg-primary/10 text-primary":"border-border hover:bg-muted"),children:w.name},w.id))})]}),e.jsx(di,{className:"max-h-[250px]",children:e.jsxs("div",{className:"space-y-1.5",children:[i==null?void 0:i.map((w,S)=>e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border rounded-lg group",children:[e.jsx("span",{className:"text-xs",children:nXs[w.priority]}),e.jsx("span",{className:"text-sm flex-1 truncate",children:w.title}),w.default_due_offset_days&&e.jsxs(Ue,{variant:"outline",className:"text-[10px]",children:["+",w.default_due_offset_days,"d"]}),e.jsx("button",{onClick:()=>v(w.id),className:"opacity-0 group-hover:opacity-100 p-1 hover:bg-destructive/10 rounded transition-opacity",children:e.jsx(_n,{className:"h-3.5 w-3.5 text-destructive"})})]},w.id)),(i==null?void 0:i.length)===0&&r&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No templates for this stage yet"})]})}),r&&e.jsxs("div",{className:"space-y-3 border-t pt-3",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Add Template Task"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Task title...",value:d,onChange:w=>u(w.target.value),className:"flex-1",onKeyDown:w=>w.key==="Enter"&&_()}),e.jsxs(us,{value:h,onValueChange:w=>p(w),children:[e.jsx(ls,{className:"w-[100px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"low",children:"🟢 Low"}),e.jsx(Ze,{value:"medium",children:"🟡 Med"}),e.jsx(Ze,{value:"high",children:"🟠 High"}),e.jsx(Ze,{value:"urgent",children:"🔴 Urgent"})]})]})]}),e.jsxs("div",{className:"flex gap-2 items-end",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{className:"text-xs",children:"Due offset (days from entering stage)"}),e.jsx(ye,{type:"number",placeholder:"e.g., 7",value:f,onChange:w=>y(w.target.value)})]}),e.jsxs(B,{onClick:_,disabled:!d.trim()||o.isPending,children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"Add"]})]})]})]})})}function aXs(){const{data:s,isLoading:t}=MQs(),{data:n}=$1e(),[r,a]=N.useState("list"),[i,l]=N.useState(""),[o,c]=N.useState("active"),[d,u]=N.useState("all"),[h,p]=N.useState("all"),[f,y]=N.useState(!1),[_,v]=N.useState(!1),j=N.useMemo(()=>{if(!s)return[];const A=new Map;return s.forEach(E=>{E.deal&&A.set(E.deal.id,E.deal.deal_name)}),Array.from(A,([E,O])=>({id:E,name:O}))},[s]),w=N.useMemo(()=>s?s.filter(A=>{var z,H,Z,Y;const E=i.toLowerCase(),O=!E||A.title.toLowerCase().includes(E)||((H=(z=A.deal)==null?void 0:z.deal_name)==null?void 0:H.toLowerCase().includes(E))||`${((Z=A.contact)==null?void 0:Z.first_name)||""} ${((Y=A.contact)==null?void 0:Y.last_name)||""}`.toLowerCase().includes(E),D=o==="all"||o==="active"&&A.status!=="done"||o==="todo"&&A.status==="todo"||o==="in_progress"&&A.status==="in_progress"||o==="done"&&A.status==="done"||o==="overdue"&&A.status!=="done"&&A.due_date&&vw(Zh(A.due_date))&&!of(Zh(A.due_date)),I=d==="all"||A.priority===d,F=h==="all"||h==="no_deal"&&!A.deal_id||A.deal_id===h;return O&&D&&I&&F}):[],[s,i,o,d,h]),S=N.useMemo(()=>{if(!s)return{total:0,overdue:0,dueToday:0,dueThisWeek:0,completed:0};const A=s.filter(E=>E.status!=="done");return{total:A.length,overdue:A.filter(E=>E.due_date&&vw(Zh(E.due_date))&&!of(Zh(E.due_date))).length,dueToday:A.filter(E=>E.due_date&&of(Zh(E.due_date))).length,dueThisWeek:A.filter(E=>E.due_date&&lUt(Zh(E.due_date))).length,completed:s.filter(E=>E.status==="done").length}},[s]);return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-6 max-w-[1600px] mx-auto",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Tasks"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Manage tasks across deals and contacts"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>v(!0),children:[e.jsx(Lv,{className:"h-4 w-4 mr-1"}),"Templates"]}),e.jsxs(B,{size:"sm",onClick:()=>y(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"}),"New Task"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsxs("button",{onClick:()=>c("active"),className:`p-3 rounded-lg border text-left transition-colors ${o==="active"?"border-primary bg-primary/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground text-xs font-medium",children:[e.jsx(Sp,{className:"h-3.5 w-3.5"}),"Active"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.total})]}),e.jsxs("button",{onClick:()=>c("overdue"),className:`p-3 rounded-lg border text-left transition-colors ${o==="overdue"?"border-destructive bg-destructive/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-destructive text-xs font-medium",children:[e.jsx(ic,{className:"h-3.5 w-3.5"}),"Overdue"]}),e.jsx("p",{className:"text-xl font-bold mt-1 text-destructive",children:S.overdue})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-xs font-medium",children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),"Due Today"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.dueToday})]}),e.jsxs("button",{onClick:()=>{c("active")},className:"p-3 rounded-lg border text-left hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 text-blue-600 text-xs font-medium",children:[e.jsx(Cl,{className:"h-3.5 w-3.5"}),"This Week"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.dueThisWeek})]}),e.jsxs("button",{onClick:()=>c("done"),className:`p-3 rounded-lg border text-left transition-colors ${o==="done"?"border-emerald-500 bg-emerald-500/5":"hover:bg-muted/50"}`,children:[e.jsxs("div",{className:"flex items-center gap-2 text-emerald-600 text-xs font-medium",children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),"Completed"]}),e.jsx("p",{className:"text-xl font-bold mt-1",children:S.completed})]})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3 items-start md:items-center",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search tasks...",value:i,onChange:A=>l(A.target.value),className:"pl-9"})]}),e.jsxs(us,{value:d,onValueChange:u,children:[e.jsx(ls,{className:"w-[130px]",children:e.jsx(hs,{placeholder:"Priority"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Priorities"}),e.jsx(Ze,{value:"urgent",children:"🔴 Urgent"}),e.jsx(Ze,{value:"high",children:"🟠 High"}),e.jsx(Ze,{value:"medium",children:"🟡 Medium"}),e.jsx(Ze,{value:"low",children:"🟢 Low"})]})]}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(ls,{className:"w-[160px]",children:e.jsx(hs,{placeholder:"Deal"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Deals"}),e.jsx(Ze,{value:"no_deal",children:"No Deal"}),j.map(A=>e.jsx(Ze,{value:A.id,children:A.name},A.id))]})]}),e.jsxs("div",{className:"flex items-center border rounded-lg p-0.5 ml-auto",children:[e.jsx("button",{onClick:()=>a("list"),className:`p-1.5 rounded-md transition-colors ${r==="list"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(Sp,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("kanban"),className:`p-1.5 rounded-md transition-colors ${r==="kanban"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(G2,{className:"h-4 w-4"})}),e.jsx("button",{onClick:()=>a("calendar"),className:`p-1.5 rounded-md transition-colors ${r==="calendar"?"bg-primary text-primary-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(Cl,{className:"h-4 w-4"})})]})]}),t?e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"animate-spin h-8 w-8 border-2 border-primary border-t-transparent rounded-full"})}):e.jsxs(e.Fragment,{children:[r==="list"&&e.jsx(QQs,{tasks:w}),r==="kanban"&&e.jsx(eXs,{tasks:w}),r==="calendar"&&e.jsx(sXs,{tasks:w})]}),e.jsx(e2t,{open:f,onOpenChange:y}),e.jsx(rXs,{open:_,onOpenChange:v,stages:n||[]})]})})}function t2t(){const s=wa();return dt({queryKey:["portal-referrals",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("portal_referrals").select("*, client_portals!inner(slug, client_name, deal_id)").eq("owner_user_id",s).order("created_at",{ascending:!1});if(n)throw n;return t||[]},enabled:!!s})}function iXs(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("portal_referrals").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}function oXs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("portal_referrals").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["portal-referrals"]})}})}const lXs=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s)),_Ne=[{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"}],cXs={buying:"Buying",selling:"Selling",both:"Buying & Selling",unsure:"Not sure yet"};function s2t(){const{data:s=[],isLoading:t}=t2t(),n=iXs(),r=oXs(),[a,i]=N.useState("all"),[l,o]=N.useState({}),c=N.useMemo(()=>a==="all"?s:s.filter(f=>f.status===a),[s,a]),d=N.useMemo(()=>({total:s.length,new:s.filter(f=>f.status==="new").length,converted:s.filter(f=>f.status==="converted").length}),[s]),u=(f,y)=>{n.mutate({id:f.id,status:y}),ae.success("Status updated")},h=f=>{const y=l[f.id];n.mutate({id:f.id,agent_notes:y}),o(_=>{const{[f.id]:v,...j}=_;return j}),ae.success("Notes saved")},p=f=>{confirm(`Delete referral for ${f.friend_name}?`)&&r.mutate(f.id)};return e.jsxs("div",{className:"container max-w-5xl py-6 px-4",children:[e.jsx(Zo,{children:e.jsx("title",{children:"Client Portal Referrals"})}),e.jsxs("div",{className:"flex items-start justify-between mb-6 flex-wrap gap-3",children:[e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(Oi,{className:"h-6 w-6 text-primary"}),"Portal Referrals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Referrals sent in by happy clients via their post-close portal."})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:d.total}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Total"})]}),e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-blue-600",children:d.new}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"New"})]}),e.jsxs("div",{className:"bg-card border rounded-lg px-4 py-2 text-center",children:[e.jsx("div",{className:"text-2xl font-bold text-emerald-600",children:d.converted}),e.jsx("div",{className:"text-[10px] uppercase tracking-wide text-muted-foreground",children:"Closed"})]})]})]}),e.jsx("div",{className:"flex flex-wrap gap-2 mb-4",children:[{v:"all",l:"All"},..._Ne.map(f=>({v:f.value,l:f.label}))].map(f=>e.jsx("button",{onClick:()=>i(f.v),className:`px-3 py-1.5 rounded-full text-xs font-medium border transition-colors ${a===f.v?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:f.l},f.v))}),t?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):c.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center",children:[e.jsx(Oi,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once your closed clients refer friends from their portal, they'll show up here."})]})}):e.jsx("div",{className:"space-y-3",children:c.map(f=>{var j,w;const y=_Ne.find(S=>S.value===f.status),_=(j=f.client_portals)==null?void 0:j.slug,v=f.referrer_name||((w=f.client_portals)==null?void 0:w.client_name)||"Anonymous client";return e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between flex-wrap gap-2",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:f.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-3 w-3"}),"Referred by ",e.jsx("span",{className:"font-medium text-foreground",children:v})," ·"," ",lXs(f.created_at)]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{variant:"outline",className:y==null?void 0:y.className,children:(y==null?void 0:y.label)||f.status}),e.jsxs(us,{value:f.status,onValueChange:S=>u(f,S),children:[e.jsx(ls,{className:"h-8 w-[130px] text-xs",children:e.jsx(hs,{})}),e.jsx(cs,{children:_Ne.map(S=>e.jsx(Ze,{value:S.value,className:"text-xs",children:S.label},S.value))})]})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[f.friend_interest&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:cXs[f.friend_interest]||f.friend_interest}),f.friend_email&&e.jsxs("a",{href:`mailto:${f.friend_email}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Gs,{className:"h-3 w-3"}),f.friend_email]}),f.friend_phone&&e.jsxs(e.Fragment,{children:[e.jsxs("a",{href:`tel:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Cr,{className:"h-3 w-3"}),f.friend_phone]}),e.jsxs("a",{href:`sms:${f.friend_phone}`,className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:[e.jsx(Zl,{className:"h-3 w-3"}),"Text"]})]})]}),f.friend_message&&e.jsxs("div",{className:"bg-muted/50 rounded-md p-3 text-sm",children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Note from referrer"}),e.jsxs("p",{className:"italic text-foreground",children:['"',f.friend_message,'"']})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[11px] uppercase tracking-wide text-muted-foreground mb-1",children:"Your notes"}),l[f.id]!==void 0?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ms,{value:l[f.id],onChange:S=>o(A=>({...A,[f.id]:S.target.value})),rows:3,className:"text-sm"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",onClick:()=>h(f),children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>o(S=>{const{[f.id]:A,...E}=S;return E}),children:"Cancel"})]})]}):e.jsx("button",{onClick:()=>o(S=>({...S,[f.id]:f.agent_notes||""})),className:"text-sm text-left w-full p-2 rounded border border-dashed border-input hover:border-primary/50 hover:bg-muted/30 transition-colors",children:f.agent_notes||e.jsx("span",{className:"text-muted-foreground italic",children:"Click to add notes..."})})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-3",children:[_&&e.jsxs("a",{href:`/portal/${_}`,target:"_blank",rel:"noopener noreferrer",className:"text-xs text-muted-foreground hover:text-primary inline-flex items-center gap-1",children:[e.jsx(tr,{className:"h-3 w-3"}),"View source portal"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>p(f),className:"text-destructive hover:text-destructive ml-auto h-8",children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]},f.id)})})]})}function n2t({vendor:s,onEdit:t,onDelete:n,onToggleVisible:r,isVisible:a,showOwnerBadge:i,clickCount:l}){var c;const o=((c=$D.find(d=>d.value===s.category))==null?void 0:c.label)||s.category;return e.jsxs(fe,{className:"p-4 flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-12 h-12 rounded-lg bg-muted flex items-center justify-center overflow-hidden shrink-0",children:s.logo_url?e.jsx("img",{src:s.logo_url,alt:s.name,className:"w-full h-full object-cover"}):e.jsx("span",{className:"text-lg font-semibold text-muted-foreground",children:s.name.charAt(0).toUpperCase()})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-1.5 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:s.name}),s.is_required&&e.jsx(Gc,{className:"w-3.5 h-3.5 text-amber-600","aria-label":"Required"}),s.is_featured&&e.jsx(oa,{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(Ue,{variant:"secondary",className:"text-[10px]",children:o}),i==="brokerage"&&e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:"Brokerage"}),i==="agent"&&e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:"Personal"}),!s.is_active&&e.jsx(Ue,{variant:"destructive",className:"text-[10px]",children:"Inactive"}),typeof l=="number"&&l>0&&e.jsxs(Ue,{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(Cr,{className:"w-3 h-3"}),s.phone]}),s.email&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Gs,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.email})]}),s.website&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(lc,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.website})]}),s.booking_url&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(yr,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:"Booking link"})]}),s.address&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(ka,{className:"w-3 h-3"}),e.jsx("span",{className:"truncate",children:s.address})]})]}),e.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t",children:[r&&e.jsxs(B,{size:"sm",variant:a?"default":"outline",onClick:()=>r(!a),disabled:s.is_required&&!a,className:"flex-1",children:[a?e.jsx(Sr,{className:"w-3.5 h-3.5 mr-1.5"}):e.jsx(mf,{className:"w-3.5 h-3.5 mr-1.5"}),a?"Showing in portals":"Hidden"]}),t&&e.jsx(B,{size:"sm",variant:"ghost",onClick:t,children:e.jsx(wu,{className:"w-3.5 h-3.5"})}),n&&e.jsx(B,{size:"sm",variant:"ghost",onClick:n,className:"text-destructive",children:e.jsx(_n,{className:"w-3.5 h-3.5"})})]})]})}function r2t({open:s,onOpenChange:t,vendor:n,ownerType:r,brokerageId:a,agentUserId:i,showBrokerageOnlyFields:l}){const o=YXt(),[c,d]=N.useState({}),[u,h]=N.useState(!1),p=N.useRef(null),f=async v=>{if(!v.type.startsWith("image/")){ae.error("Please select an image");return}if(v.size>5*1024*1024){ae.error("Image must be under 5MB");return}h(!0);try{const j=v.name.split(".").pop()||"png",w=`${r}/${a||i||"misc"}/${Date.now()}.${j}`,{error:S}=await q.storage.from("vendor-logos").upload(w,v,{upsert:!0,contentType:v.type});if(S)throw S;const{data:A}=q.storage.from("vendor-logos").getPublicUrl(w);d(E=>({...E,logo_url:A.publicUrl})),ae.success("Logo uploaded")}catch(j){ae.error(j.message||"Upload failed")}finally{h(!1)}};N.useEffect(()=>{s&&d(n||{owner_type:r,owner_brokerage_id:r==="brokerage"&&a||null,owner_user_id:r==="agent"&&i||null,category:"other",action_type:"call",is_active:!0,is_featured:!1,is_required:!1})},[s,n,r,a,i]);const y=(v,j)=>d(w=>({...w,[v]:j})),_=async()=>{var v;if(!((v=c.name)!=null&&v.trim())){ae.error("Name is required");return}try{await o.mutateAsync(c),ae.success(n?"Vendor updated":"Vendor added"),t(!1)}catch(j){ae.error(j.message||"Failed to save vendor")}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:n?"Edit Vendor":"Add Vendor"})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Contact Name *"}),e.jsx(ye,{value:c.name||"",onChange:v=>y("name",v.target.value),placeholder:"Bob Smith"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Company"}),e.jsx(ye,{value:c.company||"",onChange:v=>y("company",v.target.value),placeholder:"Smith Inspections"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Category"}),e.jsxs(us,{value:c.category,onValueChange:v=>y("category",v),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:$D.map(v=>e.jsx(Ze,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Phone"}),e.jsx(ye,{value:c.phone||"",onChange:v=>y("phone",v.target.value),placeholder:"(555) 123-4567"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Email"}),e.jsx(ye,{type:"email",value:c.email||"",onChange:v=>y("email",v.target.value),placeholder:"bob@smithinsp.com"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Website"}),e.jsx(ye,{value:c.website||"",onChange:v=>y("website",v.target.value),placeholder:"https://..."})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Logo"}),e.jsx("input",{ref:p,type:"file",accept:"image/*",className:"hidden",onChange:v=>{var w;const j=(w=v.target.files)==null?void 0:w[0];j&&f(j),v.target.value=""}}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[c.logo_url?e.jsxs("div",{className:"relative",children:[e.jsx("img",{src:c.logo_url,alt:"Vendor logo",className:"h-14 w-14 rounded-md object-cover border"}),e.jsx("button",{type:"button",onClick:()=>y("logo_url",""),className:"absolute -top-2 -right-2 bg-background border rounded-full p-0.5 shadow","aria-label":"Remove logo",children:e.jsx($n,{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(_a,{className:"h-5 w-5"})}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",onClick:()=>{var v;return(v=p.current)==null?void 0:v.click()},disabled:u,children:[u?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(_a,{className:"h-4 w-4 mr-2"}),c.logo_url?"Replace":"Upload Logo"]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Address"}),e.jsx(ye,{value:c.address||"",onChange:v=>y("address",v.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{rows:3,value:c.description||"",onChange:v=>y("description",v.target.value),placeholder:"Why your clients should use this vendor..."})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Primary Action"}),e.jsxs(us,{value:c.action_type,onValueChange:v=>y("action_type",v),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:GXt.map(v=>e.jsx(Ze,{value:v.value,children:v.label},v.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Booking URL (Calendly etc.)"}),e.jsx(ye,{value:c.booking_url||"",onChange:v=>y("booking_url",v.target.value),placeholder:"https://calendly.com/..."})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Compliance Disclosure (optional)"}),e.jsx(Ms,{rows:2,value:c.disclosure_text||"",onChange:v=>y("disclosure_text",v.target.value),placeholder:"e.g. Agent receives no compensation for this referral."})]}),e.jsxs("div",{className:"flex items-center justify-between md:col-span-2 border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"font-medium",children:"Active"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Show this vendor in client portals"})]}),e.jsx(jn,{checked:!!c.is_active,onCheckedChange:v=>y("is_active",v)})]}),l&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"font-medium",children:"Featured"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highlight in agent library"})]}),e.jsx(jn,{checked:!!c.is_featured,onCheckedChange:v=>y("is_featured",v)})]}),e.jsxs("div",{className:"flex items-center justify-between border rounded-lg p-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"font-medium",children:"Required"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents cannot hide"})]}),e.jsx(jn,{checked:!!c.is_required,onCheckedChange:v=>y("is_required",v)})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{onClick:_,disabled:o.isPending,children:o.isPending?"Saving...":"Save Vendor"})]})]})})}function a2t({embedded:s=!1}={}){const t=wa(),{brokerageId:n}=vs(),{data:r,isLoading:a}=KXt(),{data:i={}}=cht("agent",t),l=oht(),o=ZXt(),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[y,_]=N.useState("all"),v=(r==null?void 0:r.vendors)||[],j=(r==null?void 0:r.selections)||[],w=N.useMemo(()=>{const z=new Map;return j.forEach(H=>z.set(H.vendor_id,H.is_visible)),z},[j]),S=N.useMemo(()=>v.filter(z=>!(y!=="all"&&z.category!==y||p&&!`${z.name} ${z.company||""}`.toLowerCase().includes(p.toLowerCase()))),[v,p,y]),A=S.filter(z=>z.owner_type==="agent"),E=S.filter(z=>z.owner_type==="brokerage"),O=async z=>{if(confirm("Delete this vendor?"))try{await l.mutateAsync(z),ae.success("Vendor deleted")}catch(H){ae.error(H.message)}},D=async(z,H)=>{try{await o.mutateAsync({vendorId:z,isVisible:H})}catch(Z){ae.error(Z.message)}},I=z=>z.is_required?!0:w.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(zm,{className:"w-6 h-6 text-primary"}),"My Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Curate trusted partners that show up in your client portals — inspector, lender, movers and more."})]}),e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(Is,{className:"w-4 h-4 mr-2"})," Add Personal Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(gr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search vendors...",value:p,onChange:z=>f(z.target.value)})]}),e.jsxs("select",{value:y,onChange:z=>_(z.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),$D.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(Fr,{defaultValue:n?"all":"personal",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"all",children:["All (",S.length,")"]}),n&&e.jsxs(Zt,{value:"brokerage",children:["From Brokerage (",E.length,")"]}),e.jsxs(Zt,{value:"personal",children:["My Personal (",A.length,")"]})]}),e.jsx(is,{value:"all",className:"mt-4",children:e.jsx(wNe,{vendors:S,isVisibleInPortals:I,onToggle:D,onEdit:z=>{d(z),h(!0)},onDelete:O,userId:t,clicks:i})}),n&&e.jsx(is,{value:"brokerage",className:"mt-4",children:E.length===0?e.jsx(GQe,{icon:e.jsx(un,{className:"w-12 h-12"}),title:"No brokerage vendors yet",desc:"Your brokerage hasn't added any vendors. Ask your manager to set them up."}):e.jsx(wNe,{vendors:E,isVisibleInPortals:I,onToggle:D,userId:t,clicks:i})}),e.jsx(is,{value:"personal",className:"mt-4",children:A.length===0?e.jsx(GQe,{icon:e.jsx(zm,{className:"w-12 h-12"}),title:"No personal vendors yet",desc:"Add your trusted inspector, lender, mover — they'll show in every client portal you create.",action:e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(Is,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})}):e.jsx(wNe,{vendors:A,isVisibleInPortals:I,onToggle:D,onEdit:z=>{d(z),h(!0)},onDelete:O,userId:t,clicks:i})})]}),e.jsx(r2t,{open:u,onOpenChange:h,vendor:c,ownerType:"agent",agentUserId:t})]});return s?F:e.jsx(Cs,{children:F})}function wNe({vendors:s,isVisibleInPortals:t,onToggle:n,onEdit:r,onDelete:a,userId:i,clicks:l}){return e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:s.map(o=>e.jsx(n2t,{vendor:o,isVisible:t(o),onToggleVisible:c=>n(o.id,c),onEdit:o.owner_type==="agent"&&o.owner_user_id===i?()=>r==null?void 0:r(o):void 0,onDelete:o.owner_type==="agent"&&o.owner_user_id===i?()=>a==null?void 0:a(o.id):void 0,showOwnerBadge:o.owner_type,clickCount:l[o.id]},o.id))})}function GQe({icon:s,title:t,desc:n,action:r}){return e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx("div",{className:"text-muted-foreground inline-block mb-3",children:s}),e.jsx("h3",{className:"font-semibold",children:t}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-md mx-auto",children:n}),r]})}function dXs(){const{brokerageId:s,isBrokerageManager:t,isAdmin:n,loading:r}=vs(),{data:a=[],isLoading:i}=WXt(s),{data:l={}}=cht("brokerage",s),o=oht(),[c,d]=N.useState(null),[u,h]=N.useState(!1),[p,f]=N.useState(""),[y,_]=N.useState("all");if(r)return e.jsx(Cs,{children:e.jsx("div",{className:"p-8",children:"Loading..."})});if(!t&&!n)return e.jsx(Cs,{children:e.jsx("div",{className:"p-8 text-center",children:e.jsx("h2",{className:"text-xl font-semibold",children:"Brokerage managers only"})})});const v=a.filter(w=>!(y!=="all"&&w.category!==y||p&&!`${w.name} ${w.company||""}`.toLowerCase().includes(p.toLowerCase()))),j=async w=>{if(confirm("Delete this vendor? This will remove it from all agent libraries."))try{await o.mutateAsync(w),ae.success("Vendor deleted")}catch(S){ae.error(S.message)}};return e.jsx(Cs,{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(Ua,{className:"w-6 h-6 text-primary"}),"Brokerage Vendor Library"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Manage preferred vendors that all agents in your brokerage can offer to their clients."})]}),e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(Is,{className:"w-4 h-4 mr-2"})," Add Vendor"]})]}),e.jsxs("div",{className:"flex gap-2 items-center flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[200px]",children:[e.jsx(gr,{className:"w-4 h-4 absolute left-3 top-1/2 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{className:"pl-9",placeholder:"Search vendors...",value:p,onChange:w=>f(w.target.value)})]}),e.jsxs("select",{value:y,onChange:w=>_(w.target.value),className:"border rounded-md px-3 py-2 text-sm bg-background",children:[e.jsx("option",{value:"all",children:"All categories"}),$D.map(w=>e.jsx("option",{value:w.value,children:w.label},w.value))]})]}),i?e.jsx("div",{className:"text-center text-muted-foreground py-12",children:"Loading vendors..."}):v.length===0?e.jsxs("div",{className:"text-center py-16 border-2 border-dashed rounded-xl",children:[e.jsx(Ua,{className:"w-12 h-12 text-muted-foreground mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold",children:"No vendors yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4",children:"Add preferred lenders, inspectors, title companies, and more."}),e.jsxs(B,{onClick:()=>{d(null),h(!0)},children:[e.jsx(Is,{className:"w-4 h-4 mr-2"})," Add Your First Vendor"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(w=>e.jsx(n2t,{vendor:w,onEdit:()=>{d(w),h(!0)},onDelete:()=>j(w.id),clickCount:l[w.id]},w.id))}),e.jsx(r2t,{open:u,onOpenChange:h,vendor:c,ownerType:"brokerage",brokerageId:s,showBrokerageOnlyFields:!0})]})})}const uXs=[{value:"overview",label:"Portals",icon:ff},{value:"vendors",label:"Vendors",icon:pw},{value:"referrals",label:"Referrals",icon:Oi},{value:"branding",label:"Branding",icon:pl},{value:"questions",label:"Onboarding",icon:lu}];function hXs(){const[s,t]=xl(),n=s.get("tab")||"overview",[r,a]=N.useState(n),[i,l]=N.useState(!1),[o,c]=N.useState(!1);return N.useEffect(()=>{t(d=>{const u=new URLSearchParams(d);return u.set("tab",r),u},{replace:!0})},[r,t]),e.jsxs(Cs,{children:[e.jsx(Zo,{children:e.jsx("title",{children:"Client Portals"})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{className:"flex items-start justify-between flex-wrap gap-4",children:e.jsxs("div",{children:[e.jsxs("h1",{className:"text-2xl font-bold flex items-center gap-2",children:[e.jsx(un,{className:"w-6 h-6 text-primary"}),"Client Portals"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-2xl",children:"Your central hub for everything client-facing — manage active portals, curate trusted vendors, tune branding, and inbox referrals from happy clients."})]})}),e.jsx("div",{className:"border rounded-xl p-5 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(I9,{className:"w-5 h-5 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-base font-semibold",children:"Create portals from Deal Pipeline"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 max-w-3xl",children:"This page is for managing portals after they’ve been created. To create a new client portal, open the deal inside Deal Pipeline and enable the portal from that deal."})]}),e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"shrink-0",children:e.jsx(In,{to:"/mission-control/pipeline",children:"Open Deal Pipeline"})})]})}),e.jsxs(Fr,{value:r,onValueChange:a,className:"w-full",children:[e.jsx(Rr,{className:"w-full justify-start overflow-x-auto h-auto flex-wrap",children:uXs.map(d=>e.jsxs(Zt,{value:d.value,className:"gap-2",children:[e.jsx(d.icon,{className:"w-4 h-4"}),d.label]},d.value))}),e.jsx(is,{value:"overview",className:"mt-6",children:e.jsx(Jjt,{})}),e.jsx(is,{value:"vendors",className:"mt-6",children:e.jsx(mXs,{})}),e.jsx(is,{value:"referrals",className:"mt-6",children:e.jsx(pXs,{})}),e.jsx(is,{value:"branding",className:"mt-6",children:e.jsx("div",{className:"border rounded-xl p-8 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(pl,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Portal Branding Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Set the default logo, colors, cover photo and welcome message that appear at the top of every client portal you create. You can still override per-portal in any deal's settings."}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(Ko,{className:"w-4 h-4 mr-2"}),"Edit Branding Defaults"]})]})]})})}),e.jsx(is,{value:"questions",className:"mt-6",children:e.jsx("div",{className:"border rounded-xl p-8 bg-card",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(lu,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Custom Onboarding Questions"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1 mb-4 max-w-xl",children:"Questions you want every new client to answer when they first open their portal — preferred contact times, kids/pets, must-have features, and anything else that helps you serve them better."}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(Ko,{className:"w-4 h-4 mr-2"}),"Manage Questions"]})]})]})})})]})]}),e.jsx(Xjt,{open:i,onOpenChange:l}),e.jsx(Qjt,{open:o,onOpenChange:c})]})}function mXs(){return e.jsx(a2t,{embedded:!0})}function pXs(){return e.jsx(s2t,{})}const RI=s=>new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(s));function fXs(s){return dt({queryKey:["client-portal-by-id",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("client_portals").select("*").eq("id",s).maybeSingle();if(n)throw n;if(!t)return{portal:null,deal:null};const{data:r,error:a}=await q.from("deal_pipeline").select("deal_name, contact_id").eq("id",t.deal_id).maybeSingle();if(a)throw a;let i=null;if(r!=null&&r.contact_id){const{data:l,error:o}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",r.contact_id).maybeSingle();if(o)throw o;i=l}return{portal:t,deal:r?{deal_name:r.deal_name,contact_id:r.contact_id,contact:i}:null}},enabled:!!s})}function xXs(){const{portalId:s}=bi(),t=Ln(),n=wa(),{data:r,isLoading:a}=fXs(s),{data:i=[]}=FGs(s),{data:l=[]}=t2t(),o=xR(),c=v_t(),d=b_t(),u=__t(),[h,p]=N.useState(!1),[f,y]=N.useState(!1),[_,v]=N.useState(!1),[j,w]=N.useState(!1),S=(r==null?void 0:r.portal)??null,A=(r==null?void 0:r.deal)??null,E=N.useMemo(()=>S?l.filter(se=>se.portal_id===S.id):[],[l,S==null?void 0:S.id]);if(a)return e.jsx(Cs,{children:e.jsx("div",{className:"flex items-center justify-center py-24",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})})});if(!S)return e.jsx(Cs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto p-8 text-center",children:[e.jsx("h1",{className:"text-xl font-semibold mb-2",children:"Portal not found"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"This portal may have been deleted or you don't have access to it."}),e.jsx(B,{asChild:!0,variant:"outline",children:e.jsxs(In,{to:"/mission-control/client-portals",children:[e.jsx(qr,{className:"w-4 h-4 mr-2"}),"Back to Portals"]})})]})});const O=kw(S.slug),D=(A==null?void 0:A.deal_name)||"Untitled deal",I=A==null?void 0:A.contact,F=I?`${I.first_name||""} ${I.last_name||""}`.trim():"",z=!!S.archived_at,H=()=>{navigator.clipboard.writeText(O),ae.success("Portal link copied!")},Z=async se=>{try{await o.mutateAsync({id:S.id,is_enabled:se}),ae.success(se?"Portal enabled":"Portal disabled")}catch{ae.error("Failed to update")}},Y=async()=>{try{await c.mutateAsync(S.id),ae.success("Portal archived")}catch{ae.error("Failed to archive")}},W=async()=>{try{await d.mutateAsync(S.id),ae.success("Portal restored")}catch{ae.error("Failed to restore")}},ee=async()=>{try{await u.mutateAsync({id:S.id,dealId:S.deal_id}),ae.success("Portal deleted"),t("/mission-control/client-portals")}catch{ae.error("Failed to delete")}};return e.jsxs(Cs,{children:[e.jsx(Zo,{children:e.jsxs("title",{children:[D," — Client Portal"]})}),e.jsxs("div",{className:"max-w-6xl mx-auto p-4 md:p-8 space-y-6",children:[e.jsx("div",{children:e.jsx(B,{asChild:!0,variant:"ghost",size:"sm",className:"-ml-2 text-muted-foreground",children:e.jsxs(In,{to:"/mission-control/client-portals?tab=overview",children:[e.jsx(qr,{className:"w-4 h-4 mr-1"})," All Client Portals"]})})}),e.jsxs("div",{className:"border rounded-xl p-6 bg-gradient-to-br from-card to-muted/30",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2 flex-wrap",children:[e.jsx(un,{className:"w-5 h-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold truncate",children:D}),e.jsx(Ue,{variant:"outline",className:z?"bg-muted text-muted-foreground":S.is_enabled?"bg-emerald-500/10 text-emerald-700 border-emerald-200":"bg-muted text-muted-foreground",children:z?"Archived":S.is_enabled?"Active":"Disabled"}),e.jsx(Ue,{variant:"outline",className:"capitalize text-xs",children:S.visibility})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-2 flex-wrap",children:[e.jsx(Wi,{className:"w-3.5 h-3.5"}),S.client_name||F||"No client name set",(I==null?void 0:I.email)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Gs,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"truncate",children:I.email})]}),(I==null?void 0:I.phone)&&e.jsxs(e.Fragment,{children:["· ",e.jsx(Cr,{className:"w-3.5 h-3.5"}),I.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:O})})]}),!z&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Live"}),e.jsx(jn,{checked:S.is_enabled,onCheckedChange:Z})]})]}),e.jsxs("div",{className:"mt-5 flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{onClick:H,variant:"outline",size:"sm",children:[e.jsx(Zr,{className:"w-4 h-4 mr-1.5"})," Copy Link"]}),e.jsxs(B,{onClick:()=>window.open(O,"_blank"),variant:"outline",size:"sm",children:[e.jsx(tr,{className:"w-4 h-4 mr-1.5"})," Preview"]}),e.jsxs(B,{onClick:()=>v(!0),size:"sm",children:[e.jsx(lr,{className:"w-4 h-4 mr-1.5"})," Invite Client"]}),e.jsxs(B,{onClick:()=>y(!0),variant:"outline",size:"sm",children:[e.jsx(X_,{className:"w-4 h-4 mr-1.5"})," Post Update"]}),e.jsxs(B,{onClick:()=>p(!0),variant:"outline",size:"sm",children:[e.jsx(Ko,{className:"w-4 h-4 mr-1.5"})," Settings"]}),e.jsxs("div",{className:"ml-auto flex items-center gap-2",children:[z?e.jsxs(B,{onClick:W,variant:"outline",size:"sm",children:[e.jsx(HP,{className:"w-4 h-4 mr-1.5"})," Restore"]}):e.jsxs(B,{onClick:Y,variant:"ghost",size:"sm",children:[e.jsx(tm,{className:"w-4 h-4 mr-1.5"})," Archive"]}),e.jsx(B,{onClick:()=>w(!0),variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"w-4 h-4"})})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:[e.jsx(yG,{icon:X_,label:"Updates Posted",value:i.length}),e.jsx(yG,{icon:Oi,label:"Referrals",value:E.length}),e.jsx(yG,{icon:yr,label:"Inspection",value:S.inspection_date?RI(S.inspection_date):"—"}),e.jsx(yG,{icon:yr,label:"Appraisal",value:S.appraisal_date?RI(S.appraisal_date):"—"})]}),e.jsxs(Fr,{defaultValue:"updates",className:"w-full",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"updates",children:["Updates (",i.length,")"]}),e.jsxs(Zt,{value:"referrals",children:["Referrals (",E.length,")"]}),e.jsx(Zt,{value:"branding",children:"Branding"}),e.jsx(Zt,{value:"details",children:"Details"})]}),e.jsx(is,{value:"updates",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold",children:"Portal Update Feed"}),e.jsxs(B,{size:"sm",onClick:()=>y(!0),children:[e.jsx(X_,{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(X_,{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(se=>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:se.title}),se.is_stage_change&&e.jsx(Ue,{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:RI(se.created_at)}),se.content&&e.jsx("p",{className:"text-sm text-muted-foreground mt-2 whitespace-pre-wrap",children:se.content}),se.video_url&&e.jsxs("a",{href:se.video_url,target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline mt-2",children:[e.jsx(fr,{className:"w-3 h-3"})," View video"]})]})})},se.id))})]})})}),e.jsx(is,{value:"referrals",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-4",children:"Referrals from this Portal"}),E.length===0?e.jsxs("div",{className:"text-center py-12 border-2 border-dashed rounded-lg",children:[e.jsx(Oi,{className:"w-10 h-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium",children:"No referrals yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"When your client refers a friend, they'll show up here."})]}):e.jsx("div",{className:"space-y-2",children:E.map(se=>e.jsx(In,{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:se.friend_name}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[se.friend_email||se.friend_phone||"No contact info"," · ",RI(se.created_at)]})]}),e.jsx(Ue,{variant:"outline",className:"text-xs capitalize",children:se.status})]})},se.id))})]})})}),e.jsx(is,{value:"branding",className:"mt-4",children:e.jsx(fe,{children:e.jsx(Ee,{className:"p-6",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"rounded-lg bg-primary/10 p-3",children:e.jsx(pl,{className:"w-6 h-6 text-primary"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold mb-1",children:"Portal Branding"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4 max-w-xl",children:"Override your default branding for this specific portal — custom logo, colors, cover photo, and welcome message just for this client."}),e.jsxs(B,{onClick:()=>p(!0),children:[e.jsx(Ko,{className:"w-4 h-4 mr-2"}),"Edit Branding (in Settings)"]})]})]})})})}),e.jsx(is,{value:"details",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsx(Sk,{label:"Visibility",value:S.visibility}),e.jsx(Sk,{label:"Onboarding Required",value:S.require_onboarding?"Yes":"No"}),e.jsx(Sk,{label:"Allow Spouse",value:S.allow_spouse?"Yes":"No"}),e.jsx(Sk,{label:"Notify Client on Updates",value:S.notify_client?"Yes":"No"}),e.jsx(Sk,{label:"Show Post-Close Tips",value:S.show_post_close_tips?"Yes":"No"}),e.jsx(Sk,{label:"Slug",value:S.slug,mono:!0}),e.jsx(Sk,{label:"Created",value:RI(S.created_at)}),e.jsx(Sk,{label:"Last Updated",value:RI(S.updated_at)}),e.jsx("div",{className:"pt-2",children:e.jsxs(B,{variant:"outline",onClick:()=>p(!0),children:[e.jsx(Ko,{className:"w-4 h-4 mr-2"})," Edit All Settings"]})})]})})})]})]}),e.jsx(JLe,{open:h,onOpenChange:p,portal:S,dealOwnerId:n||""}),e.jsx(e8e,{open:f,onOpenChange:y,portalId:S.id,portalSlug:S.slug,notifyClient:S.notify_client}),e.jsx(t8e,{open:_,onOpenChange:v,portal:S,dealName:D}),e.jsx(Oo,{open:j,onOpenChange:w,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Permanently delete this portal?"}),e.jsx(Mo,{children:"This removes the portal and all its updates. The client will lose access. This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:ee,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete Permanently"})]})]})})]})}function yG({icon:s,label:t,value:n}){return e.jsxs("div",{className:"border rounded-lg p-4 bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(s,{className:"w-3.5 h-3.5"}),e.jsx("span",{className:"text-[11px] uppercase tracking-wide",children:t})]}),e.jsx("p",{className:"text-xl font-semibold truncate",children:n})]})}function Sk({label:s,value:t,mono:n}){return e.jsxs("div",{className:"flex items-center justify-between gap-4 border-b pb-2 last:border-b-0 last:pb-0",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:s}),e.jsx("span",{className:`text-sm ${n?"font-mono text-xs":""} text-right truncate`,children:t})]})}const rTe=[{value:"video_intro",label:"Video Intro",icon:fr,description:"Add an intro video"},{value:"testimonials",label:"Testimonials",icon:xw,description:"Client testimonials carousel"},{value:"specialties",label:"Specialties",icon:oh,description:"Tags for your specialties"},{value:"custom_links",label:"Custom Links",icon:Tl,description:"Custom CTA buttons"},{value:"social_media",label:"Social Media",icon:Vl,description:"Links to your social profiles"}],gXs=["First-Time Buyers","Luxury Homes","Investment Properties","Relocation","New Construction","Condos & Townhomes","Waterfront","Commercial","Land & Lots","Senior Living","Military/VA","Short Sales & Foreclosures"],yXs={video_intro:{video_url:""},testimonials:{testimonials:[{name:"",quote:"",role:""}]},specialties:{tags:[]},custom_links:{links:[{label:"",url:""}]},social_media:{platforms:[]}};function i2t({cardId:s}){const{data:t,isLoading:n}=Z9t(s),r=Q9t(),a=X9t(),i=J9t(),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState(null);if(n)return e.jsxs("div",{className:"space-y-3",children:[e.jsx(Ws,{className:"h-16 w-full"}),e.jsx(Ws,{className:"h-16 w-full"})]});const p=()=>{c&&r.mutate({card_id:s,block_type:c,sort_order:(t==null?void 0:t.length)||0,config:yXs[c]||{}},{onSuccess:()=>{o(!1),d("")}})},f=w=>{a.mutate({id:w.id,is_visible:!w.is_visible})},y=(w,S)=>{if(!t)return;const A=t.findIndex(D=>D.id===w.id),E=S==="up"?A-1:A+1;if(E<0||E>=t.length)return;const O=t[E];a.mutate({id:w.id,sort_order:O.sort_order}),a.mutate({id:O.id,sort_order:w.sort_order})},_=w=>{confirm("Remove this block from this card?")&&i.mutate(w.id)},v=(w,S)=>{a.mutate({id:w.id,config:S},{onSuccess:()=>h(null)})},j=w=>rTe.find(S=>S.value===w);return e.jsxs("div",{className:"space-y-3",children:[!t||t.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx("p",{className:"text-muted-foreground mb-4 text-sm",children:"No blocks yet. Add a block to customize this card."}),e.jsxs(B,{size:"sm",onClick:()=>o(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Block"]})]}):e.jsxs(e.Fragment,{children:[t.map((w,S)=>{const A=j(w.block_type),E=(A==null?void 0:A.icon)||oh;return e.jsx(fe,{className:w.is_visible?"":"opacity-50",children:e.jsx(Ee,{className:"p-3",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Pu,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),e.jsx(E,{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)||w.block_type}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:vXs(w)})]}),e.jsxs("div",{className:"flex items-center gap-0.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(w,"up"),disabled:S===0,children:e.jsx(Iu,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>y(w,"down"),disabled:S===t.length-1,children:e.jsx(sm,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>f(w),children:w.is_visible?e.jsx(Sr,{className:"h-3 w-3"}):e.jsx(mf,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>h(w),children:"Edit"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-destructive",onClick:()=>_(w),children:e.jsx(_n,{className:"h-3 w-3"})})]})]})})},w.id)}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>o(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Block"]})]}),e.jsx(_s,{open:l,onOpenChange:o,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Add Block"})}),e.jsx("div",{className:"grid gap-3",children:rTe.map(w=>{const S=w.icon;return e.jsxs("button",{onClick:()=>d(w.value),className:`flex items-center gap-3 p-3 rounded-lg border text-left transition-colors ${c===w.value?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[e.jsx(S,{className:"h-5 w-5 text-primary flex-shrink-0"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:w.label}),e.jsx("p",{className:"text-xs text-muted-foreground",children:w.description})]})]},w.value)})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>o(!1),children:"Cancel"}),e.jsx(B,{onClick:p,disabled:!c||r.isPending,children:"Add Block"})]})]})}),u&&e.jsx(bXs,{block:u,onSave:w=>v(u,w),onClose:()=>h(null)})]})}function vXs(s){var n;const t=s.config;switch(s.block_type){case"video_intro":return t.video_url?"Video configured":"No video set";case"testimonials":{const r=((n=t.testimonials)==null?void 0:n.length)||0;return`${r} testimonial${r!==1?"s":""}`}case"specialties":{const r=t.tags||[];return r.length?r.slice(0,3).join(", ")+(r.length>3?"...":""):"No tags"}case"custom_links":{const r=t.links||[];return`${r.length} link${r.length!==1?"s":""}`}case"social_media":{const r=t.platforms||[];return r.length?r.map(a=>a.platform).join(", "):"No platforms"}default:return""}}function bXs({block:s,onSave:t,onClose:n}){const[r,a]=N.useState(s.config),i=rTe.find(l=>l.value===s.block_type);return e.jsx(_s,{open:!0,onOpenChange:n,children:e.jsxs(bs,{className:"max-w-lg max-h-[80vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(ws,{children:["Edit ",i==null?void 0:i.label]})}),s.block_type==="video_intro"&&e.jsx(_Xs,{config:r,onChange:a,cardId:s.card_id}),s.block_type==="testimonials"&&e.jsx(wXs,{config:r,onChange:a}),s.block_type==="specialties"&&e.jsx(jXs,{config:r,onChange:a}),s.block_type==="custom_links"&&e.jsx(NXs,{config:r,onChange:a}),s.block_type==="social_media"&&e.jsx(kXs,{config:r,onChange:a}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:n,children:"Cancel"}),e.jsx(B,{onClick:()=>t(r),children:"Save"})]})]})})}function _Xs({config:s,onChange:t,cardId:n}){var f,y;const[r,a]=N.useState(""),[i,l]=N.useState((f=s.video_url)!=null&&f.includes("youtube")||(y=s.video_url)!=null&&y.includes("youtu.be")?"youtube":"library"),{data:o}=dt({queryKey:["card-owner",n],queryFn:async()=>{const{data:_}=await q.from("agent_cards").select("user_id").eq("id",n).single();return _==null?void 0:_.user_id},enabled:!!n}),{data:c,isLoading:d}=dt({queryKey:["agent-videos-library",o],queryFn:async()=>{const{data:_,error:v}=await q.from("agent_videos").select("id, title, bunny_video_id, thumbnail_url, playback_url, created_at").eq("owner_user_id",o).eq("is_deleted",!1).eq("status","ready").order("created_at",{ascending:!1});if(v)throw v;return _||[]},enabled:!!o}),u=(c==null?void 0:c.filter(_=>!r||(_.title||"").toLowerCase().includes(r.toLowerCase())))||[],h=s.bunny_video_id,p=_=>{var S;const v=(S=_.playback_url)==null?void 0:S.match(/\/(?:play|embed)\/(\d+)\//),w=`https://iframe.mediadelivery.net/embed/${v?v[1]:"570924"}/${_.bunny_video_id}?autoplay=false&responsive=true`;t({...s,video_url:w,bunny_video_id:_.bunny_video_id,video_source:"library"})};return e.jsx("div",{className:"space-y-4",children:e.jsxs(Fr,{value:i,onValueChange:l,children:[e.jsxs(Rr,{className:"w-full",children:[e.jsx(Zt,{value:"library",className:"flex-1",children:"Video Library"}),e.jsx(Zt,{value:"youtube",className:"flex-1",children:"YouTube URL"})]}),e.jsxs(is,{value:"library",className:"space-y-3 mt-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search videos...",value:r,onChange:_=>a(_.target.value),className:"pl-9"})]}),e.jsx(di,{className:"h-[240px]",children:d?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ws,{className:"h-14 w-full"}),e.jsx(Ws,{className:"h-14 w-full"})]}):u.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:(c==null?void 0:c.length)===0?"No videos in library yet":"No matching videos"}):e.jsx("div",{className:"space-y-1.5 pr-3",children:u.map(_=>e.jsxs("button",{onClick:()=>p(_),className:`w-full flex items-center gap-3 p-2 rounded-lg border text-left transition-colors ${h===_.bunny_video_id?"border-primary bg-primary/5":"border-border hover:bg-muted"}`,children:[_.thumbnail_url?e.jsx("img",{src:_.thumbnail_url,alt:"",className:"h-10 w-16 rounded object-cover flex-shrink-0 bg-muted",onError:v=>{var j;v.currentTarget.style.display="none",(j=v.currentTarget.nextElementSibling)==null||j.classList.remove("hidden")}}):null,e.jsx("div",{className:`h-10 w-16 rounded bg-muted flex items-center justify-center flex-shrink-0 ${_.thumbnail_url?"hidden":""}`,children:e.jsx(fr,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{className:"text-sm font-medium truncate flex-1",children:_.title||"Untitled Video"}),h===_.bunny_video_id&&e.jsx(Lr,{className:"h-4 w-4 text-primary flex-shrink-0"})]},_.id))})})]}),e.jsx(is,{value:"youtube",className:"space-y-3 mt-3",children:e.jsxs("div",{children:[e.jsx(ne,{children:"YouTube URL"}),e.jsx(ye,{placeholder:"https://www.youtube.com/watch?v=...",value:s.video_source==="youtube"&&s.video_url||"",onChange:_=>t({...s,video_url:_.target.value,bunny_video_id:null,video_source:"youtube"})}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Paste a YouTube video link"})]})})]})})}function wXs({config:s,onChange:t}){const n=s.testimonials||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,testimonials:d})},a=()=>t({...s,testimonials:[...n,{name:"",quote:"",role:""}]}),i=l=>t({...s,testimonials:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-4",children:[n.map((l,o)=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ne,{className:"text-xs font-medium",children:["Testimonial ",o+1]}),n.length>1&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-destructive",onClick:()=>i(o),children:e.jsx(_n,{className:"h-3 w-3"})})]}),e.jsx(ye,{placeholder:"Client name",value:l.name,onChange:c=>r(o,"name",c.target.value)}),e.jsx(ye,{placeholder:"Role/title (optional)",value:l.role||"",onChange:c=>r(o,"role",c.target.value)}),e.jsx("textarea",{className:"w-full min-h-[60px] rounded-md border border-input bg-background px-3 py-2 text-sm",placeholder:"Their testimonial quote...",value:l.quote,onChange:c=>r(o,"quote",c.target.value)})]})},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Testimonial"]})]})}function jXs({config:s,onChange:t}){const n=s.tags||[],[r,a]=N.useState(""),i=o=>{t({...s,tags:n.includes(o)?n.filter(c=>c!==o):[...n,o]})},l=()=>{r.trim()&&!n.includes(r.trim())&&(t({...s,tags:[...n,r.trim()]}),a(""))};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm mb-2 block",children:"Preset Specialties"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:gXs.map(o=>e.jsx("button",{onClick:()=>i(o),className:`px-3 py-1.5 text-xs rounded-full border transition-colors ${n.includes(o)?"bg-primary text-primary-foreground border-primary":"bg-muted border-border hover:bg-muted/80"}`,children:o},o))})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm mb-2 block",children:"Custom Tag"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Add your own...",value:r,onChange:o=>a(o.target.value),onKeyDown:o=>o.key==="Enter"&&(o.preventDefault(),l())}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:"Add"})]})]}),n.length>0&&e.jsxs("div",{children:[e.jsxs(ne,{className:"text-xs text-muted-foreground mb-1 block",children:["Selected (",n.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-1.5",children:n.map(o=>e.jsxs("span",{className:"inline-flex items-center gap-1 px-2 py-1 text-xs bg-primary/10 text-primary rounded-full",children:[o,e.jsx("button",{onClick:()=>i(o),className:"hover:text-destructive",children:"×"})]},o))})]})]})}function NXs({config:s,onChange:t}){const n=s.links||[],r=(l,o,c)=>{const d=[...n];d[l]={...d[l],[o]:c},t({...s,links:d})},a=()=>t({...s,links:[...n,{label:"",url:""}]}),i=l=>t({...s,links:n.filter((o,c)=>c!==l)});return e.jsxs("div",{className:"space-y-3",children:[n.map((l,o)=>e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ye,{placeholder:"Button label",value:l.label,onChange:c=>r(o,"label",c.target.value)}),e.jsx(ye,{placeholder:"https://...",value:l.url,onChange:c=>r(o,"url",c.target.value)})]}),n.length>1&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 mt-1 text-destructive",onClick:()=>i(o),children:e.jsx(_n,{className:"h-3 w-3"})})]},o)),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"w-full",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Link"]})]})}const WQe=[{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 kXs({config:s,onChange:t}){const n=s.platforms||[],r=c=>{n.find(d=>d.platform===c)||t({...s,platforms:[...n,{platform:c,url:""}]})},a=(c,d)=>{const u=[...n];u[c]={...u[c],url:d},t({...s,platforms:u})},i=c=>{t({...s,platforms:n.filter((d,u)=>u!==c)})},l=WQe.filter(c=>!n.find(d=>d.platform===c.value)),o=c=>{const d=p4e[c],u=WQe.find(h=>h.value===c);return{label:(u==null?void 0:u.label)||c,color:(d==null?void 0:d.color)||"#666",iconPath:d==null?void 0:d.icon}};return e.jsxs("div",{className:"space-y-4",children:[n.length>0&&e.jsx("div",{className:"space-y-3",children:n.map((c,d)=>{const u=o(c.platform);return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg flex items-center justify-center flex-shrink-0 border",style:{borderColor:u.color+"30",backgroundColor:u.color+"10"},children:u.iconPath&&e.jsx("svg",{viewBox:"0 0 24 24",width:16,height:16,fill:u.color,children:e.jsx("path",{d:u.iconPath})})}),e.jsx("div",{className:"flex-1",children:e.jsx(ye,{placeholder:`Your ${u.label} profile URL`,value:c.url,onChange:h=>a(d,h.target.value)})}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8 text-destructive flex-shrink-0",onClick:()=>i(d),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]},d)})}),l.length>0&&e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground mb-2 block",children:"Add a platform"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:l.map(c=>{const d=p4e[c.value];return e.jsxs("button",{onClick:()=>r(c.value),className:"inline-flex items-center gap-1.5 px-3 py-1.5 text-xs rounded-full border border-border bg-muted hover:bg-muted/80 transition-colors",children:[(d==null?void 0:d.icon)&&e.jsx("svg",{viewBox:"0 0 24 24",width:12,height:12,fill:d.color,children:e.jsx("path",{d:d.icon})}),c.label]},c.value)})})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"Tap a platform above to add your social media profile."})]})}var SXs=Object.defineProperty,Pge=Object.getOwnPropertySymbols,o2t=Object.prototype.hasOwnProperty,l2t=Object.prototype.propertyIsEnumerable,KQe=(s,t,n)=>t in s?SXs(s,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):s[t]=n,aTe=(s,t)=>{for(var n in t||(t={}))o2t.call(t,n)&&KQe(s,n,t[n]);if(Pge)for(var n of Pge(t))l2t.call(t,n)&&KQe(s,n,t[n]);return s},iTe=(s,t)=>{var n={};for(var r in s)o2t.call(s,r)&&t.indexOf(r)<0&&(n[r]=s[r]);if(s!=null&&Pge)for(var r of Pge(s))t.indexOf(r)<0&&l2t.call(s,r)&&(n[r]=s[r]);return n};/** * @license QR Code generator library (TypeScript) * Copyright (c) Project Nayuki. * SPDX-License-Identifier: MIT */var PM;(s=>{const t=class dl{constructor(c,d,u,h){if(this.version=c,this.errorCorrectionLevel=d,this.modules=[],this.isFunction=[],cdl.MAX_VERSION)throw new RangeError("Version value out of range");if(h<-1||h>7)throw new RangeError("Mask value out of range");this.size=c*4+17;let p=[];for(let y=0;y7)throw new RangeError("Invalid value");let y,_;for(y=u;;y++){const S=dl.getNumDataCodewords(y,d)*8,A=l.getTotalBits(c,y);if(A<=S){_=A;break}if(y>=h)throw new RangeError("Data too long")}for(const S of[dl.Ecc.MEDIUM,dl.Ecc.QUARTILE,dl.Ecc.HIGH])f&&_<=dl.getNumDataCodewords(y,S)*8&&(d=S);let v=[];for(const S of c){n(S.mode.modeBits,4,v),n(S.numChars,S.mode.numCharCountBits(y),v);for(const A of S.getData())v.push(A)}a(v.length==_);const j=dl.getNumDataCodewords(y,d)*8;a(v.length<=j),n(0,Math.min(4,j-v.length),v),n(0,(8-v.length%8)%8,v),a(v.length%8==0);for(let S=236;v.lengthw[A>>>3]|=S<<7-(A&7)),new dl(y,d,w,p)}getModule(c,d){return 0<=c&&c>>9)*1335;const h=(d<<10|u)^21522;a(h>>>15==0);for(let p=0;p<=5;p++)this.setFunctionModule(8,p,r(h,p));this.setFunctionModule(8,7,r(h,6)),this.setFunctionModule(8,8,r(h,7)),this.setFunctionModule(7,8,r(h,8));for(let p=9;p<15;p++)this.setFunctionModule(14-p,8,r(h,p));for(let p=0;p<8;p++)this.setFunctionModule(this.size-1-p,8,r(h,p));for(let p=8;p<15;p++)this.setFunctionModule(8,this.size-15+p,r(h,p));this.setFunctionModule(8,this.size-8,!0)}drawVersion(){if(this.version<7)return;let c=this.version;for(let u=0;u<12;u++)c=c<<1^(c>>>11)*7973;const d=this.version<<12|c;a(d>>>18==0);for(let u=0;u<18;u++){const h=r(d,u),p=this.size-11+u%3,f=Math.floor(u/3);this.setFunctionModule(p,f,h),this.setFunctionModule(f,p,h)}}drawFinderPattern(c,d){for(let u=-4;u<=4;u++)for(let h=-4;h<=4;h++){const p=Math.max(Math.abs(h),Math.abs(u)),f=c+h,y=d+u;0<=f&&f{(S!=_-p||E>=y)&&w.push(A[S])});return a(w.length==f),w}drawCodewords(c){if(c.length!=Math.floor(dl.getNumRawDataModules(this.version)/8))throw new RangeError("Invalid argument");let d=0;for(let u=this.size-1;u>=1;u-=2){u==6&&(u=5);for(let h=0;h>>3],7-(d&7)),d++)}}a(d==c.length*8)}applyMask(c){if(c<0||c>7)throw new RangeError("Mask value out of range");for(let d=0;d5&&c++):(this.finderPenaltyAddHistory(y,_),f||(c+=this.finderPenaltyCountPatterns(_)*dl.PENALTY_N3),f=this.modules[p][v],y=1);c+=this.finderPenaltyTerminateAndCount(f,y,_)*dl.PENALTY_N3}for(let p=0;p5&&c++):(this.finderPenaltyAddHistory(y,_),f||(c+=this.finderPenaltyCountPatterns(_)*dl.PENALTY_N3),f=this.modules[v][p],y=1);c+=this.finderPenaltyTerminateAndCount(f,y,_)*dl.PENALTY_N3}for(let p=0;pf+(y?1:0),d);const u=this.size*this.size,h=Math.ceil(Math.abs(d*20-u*10)/u)-1;return a(0<=h&&h<=9),c+=h*dl.PENALTY_N4,a(0<=c&&c<=2568888),c}getAlignmentPatternPositions(){if(this.version==1)return[];{const c=Math.floor(this.version/7)+2,d=this.version==32?26:Math.ceil((this.version*4+4)/(c*2-2))*2;let u=[6];for(let h=this.size-7;u.lengthdl.MAX_VERSION)throw new RangeError("Version number out of range");let d=(16*c+128)*c+64;if(c>=2){const u=Math.floor(c/7)+2;d-=(25*u-10)*u-55,c>=7&&(d-=36)}return a(208<=d&&d<=29648),d}static getNumDataCodewords(c,d){return Math.floor(dl.getNumRawDataModules(c)/8)-dl.ECC_CODEWORDS_PER_BLOCK[d.ordinal][c]*dl.NUM_ERROR_CORRECTION_BLOCKS[d.ordinal][c]}static reedSolomonComputeDivisor(c){if(c<1||c>255)throw new RangeError("Degree out of range");let d=[];for(let h=0;h0);for(const h of c){const p=h^u.shift();u.push(0),d.forEach((f,y)=>u[y]^=dl.reedSolomonMultiply(f,p))}return u}static reedSolomonMultiply(c,d){if(c>>>8||d>>>8)throw new RangeError("Byte out of range");let u=0;for(let h=7;h>=0;h--)u=u<<1^(u>>>7)*285,u^=(d>>>h&1)*c;return a(u>>>8==0),u}finderPenaltyCountPatterns(c){const d=c[1];a(d<=this.size*3);const u=d>0&&c[2]==d&&c[3]==d*3&&c[4]==d&&c[5]==d;return(u&&c[0]>=d*4&&c[6]>=d?1:0)+(u&&c[6]>=d*4&&c[0]>=d?1:0)}finderPenaltyTerminateAndCount(c,d,u){return c&&(this.finderPenaltyAddHistory(d,u),d=0),d+=this.size,this.finderPenaltyAddHistory(d,u),this.finderPenaltyCountPatterns(u)}finderPenaltyAddHistory(c,d){d[0]==0&&(c+=this.size),d.pop(),d.unshift(c)}};t.MIN_VERSION=1,t.MAX_VERSION=40,t.PENALTY_N1=3,t.PENALTY_N2=3,t.PENALTY_N3=40,t.PENALTY_N4=10,t.ECC_CODEWORDS_PER_BLOCK=[[-1,7,10,15,20,26,18,20,24,30,18,20,24,26,30,22,24,28,30,28,28,28,28,30,30,26,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,10,16,26,18,24,16,18,22,22,26,30,22,22,24,24,28,28,26,26,26,26,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28,28],[-1,13,22,18,26,18,24,18,22,20,24,28,26,24,20,30,24,28,28,26,30,28,30,30,30,30,28,30,30,30,30,30,30,30,30,30,30,30,30,30,30],[-1,17,28,22,16,22,28,26,26,24,28,24,28,22,24,24,30,28,28,26,28,30,24,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30,30]],t.NUM_ERROR_CORRECTION_BLOCKS=[[-1,1,1,1,1,1,2,2,2,2,4,4,4,4,4,6,6,6,6,7,8,8,9,9,10,12,12,12,13,14,15,16,17,18,19,19,20,21,22,24,25],[-1,1,1,1,2,2,4,4,4,5,5,5,8,9,9,10,10,11,13,14,16,17,17,18,20,21,23,25,26,28,29,31,33,35,37,38,40,43,45,47,49],[-1,1,1,2,2,4,4,6,6,8,8,8,10,12,16,12,17,16,18,21,20,23,23,25,27,29,34,34,35,38,40,43,45,48,51,53,56,59,62,65,68],[-1,1,1,2,4,4,4,5,6,8,8,11,11,16,16,18,16,19,21,25,25,25,34,30,32,35,37,40,42,45,48,51,54,57,60,63,66,70,74,77,81]],s.QrCode=t;function n(o,c,d){if(c<0||c>31||o>>>c)throw new RangeError("Value out of range");for(let u=c-1;u>=0;u--)d.push(o>>>u&1)}function r(o,c){return(o>>>c&1)!=0}function a(o){if(!o)throw new Error("Assertion error")}const i=class Zu{constructor(c,d,u){if(this.mode=c,this.numChars=d,this.bitData=u,d<0)throw new RangeError("Invalid argument");this.bitData=u.slice()}static makeBytes(c){let d=[];for(const u of c)n(u,8,d);return new Zu(Zu.Mode.BYTE,c.length,d)}static makeNumeric(c){if(!Zu.isNumeric(c))throw new RangeError("String contains non-numeric characters");let d=[];for(let u=0;u=1<{(t=>{const n=class{constructor(a,i){this.ordinal=a,this.formatBits=i}};n.LOW=new n(0,1),n.MEDIUM=new n(1,0),n.QUARTILE=new n(2,3),n.HIGH=new n(3,2),t.Ecc=n})(s.QrCode||(s.QrCode={}))})(PM||(PM={}));(s=>{(t=>{const n=class{constructor(a,i){this.modeBits=a,this.numBitsCharCount=i}numCharCountBits(a){return this.numBitsCharCount[Math.floor((a+7)/17)]}};n.NUMERIC=new n(1,[10,12,14]),n.ALPHANUMERIC=new n(2,[9,11,13]),n.BYTE=new n(4,[8,16,16]),n.KANJI=new n(8,[8,10,12]),n.ECI=new n(7,[0,0,0]),t.Mode=n})(s.QrSegment||(s.QrSegment={}))})(PM||(PM={}));var DP=PM;/** * @license qrcode.react * Copyright (c) Paul O'Shannessy * SPDX-License-Identifier: ISC */var CXs={L:DP.QrCode.Ecc.LOW,M:DP.QrCode.Ecc.MEDIUM,Q:DP.QrCode.Ecc.QUARTILE,H:DP.QrCode.Ecc.HIGH},c2t=128,d2t="L",u2t="#FFFFFF",h2t="#000000",m2t=!1,p2t=1,TXs=4,EXs=0,AXs=.1;function f2t(s,t=0){const n=[];return s.forEach(function(r,a){let i=null;r.forEach(function(l,o){if(!l&&i!==null){n.push(`M${i+t} ${a+t}h${o-i}v1H${i+t}z`),i=null;return}if(o===r.length-1){if(!l)return;i===null?n.push(`M${o+t},${a+t} h1v1H${o+t}z`):n.push(`M${i+t},${a+t} h${o+1-i}v1H${i+t}z`);return}l&&i===null&&(i=o)})}),n.join("")}function x2t(s,t){return s.slice().map((n,r)=>r=t.y+t.h?n:n.map((a,i)=>i=t.x+t.w?a:!1))}function MXs(s,t,n,r){if(r==null)return null;const a=s.length+n*2,i=Math.floor(t*AXs),l=a/t,o=(r.width||i)*l,c=(r.height||i)*l,d=r.x==null?s.length/2-o/2:r.x*l,u=r.y==null?s.length/2-c/2:r.y*l,h=r.opacity==null?1:r.opacity;let p=null;if(r.excavate){let y=Math.floor(d),_=Math.floor(u),v=Math.ceil(o+d-y),j=Math.ceil(c+u-_);p={x:y,y:_,w:v,h:j}}const f=r.crossOrigin;return{x:d,y:u,h:c,w:o,excavation:p,opacity:h,crossOrigin:f}}function IXs(s,t){return t!=null?Math.max(Math.floor(t),0):s?TXs:EXs}function g2t({value:s,level:t,minVersion:n,includeMargin:r,marginSize:a,imageSettings:i,size:l,boostLevel:o}){let c=Ct.useMemo(()=>{const y=(Array.isArray(s)?s:[s]).reduce((_,v)=>(_.push(...DP.QrSegment.makeSegments(v)),_),[]);return DP.QrCode.encodeSegments(y,CXs[t],n,void 0,void 0,o)},[s,t,n,o]);const{cells:d,margin:u,numCells:h,calculatedImageSettings:p}=Ct.useMemo(()=>{let f=c.getModules();const y=IXs(r,a),_=f.length+y*2,v=MXs(f,l,y,i);return{cells:f,margin:y,numCells:_,calculatedImageSettings:v}},[c,l,i,r,a]);return{qrcode:c,margin:u,cells:d,numCells:h,calculatedImageSettings:p}}var PXs=function(){try{new Path2D().addPath(new Path2D)}catch{return!1}return!0}(),LXs=Ct.forwardRef(function(t,n){const r=t,{value:a,size:i=c2t,level:l=d2t,bgColor:o=u2t,fgColor:c=h2t,includeMargin:d=m2t,minVersion:u=p2t,boostLevel:h,marginSize:p,imageSettings:f}=r,_=iTe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","marginSize","imageSettings"]),{style:v}=_,j=iTe(_,["style"]),w=f==null?void 0:f.src,S=Ct.useRef(null),A=Ct.useRef(null),E=Ct.useCallback(W=>{S.current=W,typeof n=="function"?n(W):n&&(n.current=W)},[n]),[O,D]=Ct.useState(!1),{margin:I,cells:F,numCells:z,calculatedImageSettings:H}=g2t({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:p,imageSettings:f,size:i});Ct.useEffect(()=>{if(S.current!=null){const W=S.current,ee=W.getContext("2d");if(!ee)return;let se=F;const oe=A.current,he=H!=null&&oe!==null&&oe.complete&&oe.naturalHeight!==0&&oe.naturalWidth!==0;he&&H.excavation!=null&&(se=x2t(F,H.excavation));const ce=window.devicePixelRatio||1;W.height=W.width=i*ce;const me=i/z*ce;ee.scale(me,me),ee.fillStyle=o,ee.fillRect(0,0,z,z),ee.fillStyle=c,PXs?ee.fill(new Path2D(f2t(se,I))):F.forEach(function(le,ve){le.forEach(function(ge,Te){ge&&ee.fillRect(Te+I,ve+I,1,1)})}),H&&(ee.globalAlpha=H.opacity),he&&ee.drawImage(oe,H.x+I,H.y+I,H.w,H.h)}}),Ct.useEffect(()=>{D(!1)},[w]);const Z=aTe({height:i,width:i},v);let Y=null;return w!=null&&(Y=Ct.createElement("img",{src:w,key:w,style:{display:"none"},onLoad:()=>{D(!0)},ref:A,crossOrigin:H==null?void 0:H.crossOrigin})),Ct.createElement(Ct.Fragment,null,Ct.createElement("canvas",aTe({style:Z,height:i,width:i,ref:E,role:"img"},j)),Y)});LXs.displayName="QRCodeCanvas";var zU=Ct.forwardRef(function(t,n){const r=t,{value:a,size:i=c2t,level:l=d2t,bgColor:o=u2t,fgColor:c=h2t,includeMargin:d=m2t,minVersion:u=p2t,boostLevel:h,title:p,marginSize:f,imageSettings:y}=r,_=iTe(r,["value","size","level","bgColor","fgColor","includeMargin","minVersion","boostLevel","title","marginSize","imageSettings"]),{margin:v,cells:j,numCells:w,calculatedImageSettings:S}=g2t({value:a,level:l,minVersion:u,boostLevel:h,includeMargin:d,marginSize:f,imageSettings:y,size:i});let A=j,E=null;y!=null&&S!=null&&(S.excavation!=null&&(A=x2t(j,S.excavation)),E=Ct.createElement("image",{href:y.src,height:S.h,width:S.w,x:S.x+v,y:S.y+v,preserveAspectRatio:"none",opacity:S.opacity,crossOrigin:S.crossOrigin}));const O=f2t(A,v);return Ct.createElement("svg",aTe({height:i,width:i,viewBox:`0 0 ${w} ${w}`,ref:n,role:"img"},_),!!p&&Ct.createElement("title",null,p),Ct.createElement("path",{fill:o,d:`M0,0 h${w}v${w}H0z`,shapeRendering:"crispEdges"}),Ct.createElement("path",{fill:c,d:O,shapeRendering:"crispEdges"}),E)});zU.displayName="QRCodeSVG";function DXs({slug:s,agentName:t}){const n=N.useRef(null),r=`https://cards.relevelup.com/${s}`,a=N.useCallback(()=>{var h;const i=(h=n.current)==null?void 0:h.querySelector("svg");if(!i)return;const l=document.createElement("canvas"),o=1024;l.width=o,l.height=o;const c=l.getContext("2d");if(!c)return;const d=new XMLSerializer().serializeToString(i),u=new Image;u.onload=()=>{c.fillStyle="#ffffff",c.fillRect(0,0,o,o),c.drawImage(u,0,0,o,o);const p=document.createElement("a");p.download=`${s}-qr-code.png`,p.href=l.toDataURL("image/png"),p.click(),ae.success("QR code downloaded!")},u.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(d)))},[s]);return e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{className:"text-sm font-medium",children:"QR Code"}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{ref:n,className:"bg-white p-3 rounded-lg border shadow-sm shrink-0",children:e.jsx(zU,{value:r,size:120,level:"H",bgColor:"#ffffff",fgColor:"#000000"})}),e.jsxs("div",{className:"space-y-2 min-w-0",children:[e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"Download this QR code to use on business cards, flyers, signs, or any print materials. Scanning it opens your digital card instantly."}),e.jsxs(B,{variant:"outline",size:"sm",onClick:a,className:"gap-1.5",children:[e.jsx(Ia,{className:"h-3.5 w-3.5"}),"Download PNG"]})]})]})]})}function jNe(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 RXs(){const{user:s}=vs(),{data:t,isLoading:n}=W9t(s==null?void 0:s.id),r=fR(),[a,i]=N.useState(null),l=N.useMemo(()=>a||(t?jNe(t):null),[a,t]);if(n)return e.jsx(Cs,{children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 space-y-4",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-32 w-full"}),e.jsx(Ws,{className:"h-32 w-full"})]})});if(!t)return e.jsx(Cs,{children:e.jsx(FXs,{userId:s==null?void 0:s.id})});const o=l||jNe(t),c=d=>{i(u=>{const h=u||jNe(t);return typeof d=="function"?d(h):d})};return e.jsx(Cs,{children:e.jsxs("div",{className:"flex gap-6 items-start",children:[e.jsxs("div",{className:`${r?"w-full":"flex-1 min-w-0"} max-w-2xl p-4 space-y-6 animate-fade-in`,children:[e.jsx(zXs,{card:t}),e.jsx(qXs,{card:t,form:o,setForm:c})]}),!r&&e.jsx("div",{className:"w-[400px] shrink-0","aria-hidden":"true"}),!r&&e.jsx("div",{className:"fixed right-8 top-[5.5rem] w-[400px] z-30",style:{height:"calc(100vh - 6.5rem)"},children:e.jsxs("div",{className:"rounded-xl border bg-muted/30 overflow-hidden h-full flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 px-4 py-2.5 border-b bg-card shrink-0",children:[e.jsx(mb,{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(OXs,{card:t,form:o})})]})})]})})}function OXs({card:s,form:t}){const{data:n}=dt({queryKey:["card-preview-profile",s.user_id],queryFn:async()=>{const{data:a}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage_id").eq("id",s.user_id).single();let i=(a==null?void 0:a.avatar_url)||null;if(!i){const{data:l}=await q.storage.from("avatars").list(`${s.user_id}`);if(l&&l.length>0){const{data:o}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${l[0].name}`);i=`${o.publicUrl}?t=${Date.now()}`}}return{...a,avatar_url:i}}}),r=N.useMemo(()=>({...s,is_published:t.is_published,theme:t.theme,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,custom_cta_url:s.custom_cta_url,show_photo:t.show_photo,show_bio:t.show_bio,show_video:s.show_video,show_credentials:t.show_credentials,show_social_links:t.show_social_links,show_save_contact:t.show_save_contact,show_leave_review:t.show_leave_review,show_refer_friend:t.show_refer_friend,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,display_email:t.display_email||null,social_links:s.social_links||[],profile:{name:(n==null?void 0:n.name)||null,email:t.display_email||(n==null?void 0:n.email)||null,phone:(n==null?void 0:n.phone)||null,brokerage_id:(n==null?void 0:n.brokerage_id)||null},brokerage_name:t.brokerage_display_name||null,avatar_url:(n==null?void 0:n.avatar_url)||null}),[s,t,n]);return e.jsx("div",{className:"transform scale-[0.85] origin-top",children:e.jsx(DAe,{card:r})})}function FXs({userId:s}){var c;const[t,n]=N.useState(""),r=Glt(),{data:a}=dt({queryKey:["my-profile-for-card",s],queryFn:async()=>{if(!s)return null;const{data:d}=await q.from("profiles").select("name").eq("id",s).single();return d},enabled:!!s}),i=((c=a==null?void 0:a.name)==null?void 0:c.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||"",l=()=>{if(!s)return;const d=(t.trim()||i).toLowerCase().replace(/[^a-z0-9-]/g,"-");if(!d){ae.error("Please enter a URL slug for your card");return}r.mutate({user_id:s,slug:d,is_published:!0},{onSuccess:()=>ae.success("Your digital card has been created!")})},o=[{icon:lc,title:"Shareable Link",desc:"One link that works everywhere"},{icon:im,title:"Lead Capture",desc:"Collect leads automatically"},{icon:Ih,title:"Always Up-to-Date",desc:"Edit anytime, changes are instant"},{icon:pl,title:"Fully Customizable",desc:"Themes, colors, and content blocks"}];return e.jsxs("div",{className:"max-w-2xl mx-auto p-4 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-2xl bg-gradient-to-br from-primary/90 via-primary to-primary/80 p-8 md:p-12 mb-8 text-primary-foreground",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_30%_20%,rgba(255,255,255,0.15),transparent_50%)]"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_80%_80%,rgba(0,0,0,0.1),transparent_50%)]"}),e.jsxs("div",{className:"relative z-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-white/20 backdrop-blur-sm text-sm font-medium mb-4",children:[e.jsx(un,{className:"h-3.5 w-3.5"}),"New Feature"]}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold mb-3 tracking-tight",children:"Your Digital Business Card"}),e.jsx("p",{className:"text-primary-foreground/80 text-lg max-w-md leading-relaxed",children:"Ditch the paper. Share a beautiful, interactive card that captures leads and makes a lasting impression."})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3 mb-8",children:o.map(d=>e.jsxs("div",{className:"flex items-start gap-3 p-4 rounded-xl border bg-card hover:shadow-md transition-shadow",children:[e.jsx("div",{className:"mt-0.5 p-2 rounded-lg bg-primary/10 shrink-0",children:e.jsx(d.icon,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:d.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.desc})]})]},d.title))}),e.jsxs(fe,{className:"shadow-lg border-2",children:[e.jsxs(It,{className:"text-center pb-2",children:[e.jsx(Rt,{className:"text-xl",children:"Set Up Your Card"}),e.jsx(Vn,{children:"Choose a URL slug — this is the link you'll share with clients"})]}),e.jsxs(Ee,{className:"p-6 pt-2 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Your Card URL"}),e.jsxs("div",{className:"flex items-center gap-0 mt-1.5",children:[e.jsx("span",{className:"inline-flex items-center px-3 h-10 rounded-l-md border border-r-0 bg-muted text-sm text-muted-foreground whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ye,{value:t||i,onChange:d=>n(d.target.value),placeholder:"your-name",className:"rounded-l-none"})]})]}),e.jsxs(B,{onClick:l,disabled:r.isPending,className:"w-full h-11 text-base font-semibold",size:"lg",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),r.isPending?"Creating...":"Create My Card"]})]})]})]})}function zXs({card:s}){const n=`https://cards.relevelup.com/${s.slug}`,r=()=>{navigator.clipboard.writeText(n),ae.success("Card link copied!")};return e.jsx("div",{className:"rounded-xl border bg-card p-5",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-xl font-bold",children:"My Digital Card"}),e.jsx(Ue,{variant:s.is_published?"default":"secondary",className:"text-[10px] uppercase tracking-wider",children:s.is_published?"Live":"Draft"})]}),e.jsxs("p",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(lc,{className:"h-3.5 w-3.5"}),"cards.relevelup.com/",s.slug]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:r,className:"gap-1.5",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"})," Copy Link"]}),e.jsx(B,{size:"sm",asChild:!0,className:"gap-1.5",children:e.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5"})," Preview"]})})]})]})})}function BXs({userId:s}){const t=Kt(),n=N.useRef(null),[r,a]=N.useState(!1),[i,l]=N.useState(""),{data:o,isLoading:c}=dt({queryKey:["card-editor-profile",s],queryFn:async()=>{const{data:H}=await q.from("profiles").select("name, email, phone, avatar_url").eq("id",s).single();let Z=(H==null?void 0:H.avatar_url)||null;if(!Z){const{data:Y}=await q.storage.from("avatars").list(`${s}`);if(Y&&Y.length>0){const{data:W}=q.storage.from("avatars").getPublicUrl(`${s}/${Y[0].name}`);Z=`${W.publicUrl}?t=${Date.now()}`,await q.from("profiles").update({avatar_url:Z}).eq("id",s)}}return{...H,avatar_url:Z}}}),[d,u]=N.useState(null),[h,p]=N.useState(null),[f,y]=N.useState(null),[_,v]=N.useState(!1),j=d??(o==null?void 0:o.name)??"",w=h??(o==null?void 0:o.phone)??"",S=f??(o==null?void 0:o.email)??"",A=o==null?void 0:o.avatar_url,E=((o==null?void 0:o.name)||"A").split(" ").map(H=>H[0]).join("").toUpperCase().slice(0,2),O=!(o!=null&&o.avatar_url)||!(o!=null&&o.phone),D=yt({mutationFn:async H=>{const{error:Z}=await q.from("profiles").update(H).eq("id",s);if(Z)throw Z},onSuccess:()=>{t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Profile updated!")},onError:()=>ae.error("Failed to update profile")}),I=()=>{const H={};if(d!==null&&d!==(o==null?void 0:o.name)&&(H.name=d),h!==null&&h!==(o==null?void 0:o.phone)&&(H.phone=h||null),f!==null&&f!==(o==null?void 0:o.email)&&(H.email=f),Object.keys(H).length===0){ae.info("No changes to save");return}D.mutate(H)},F=H=>{var W;const Z=(W=H.target.files)==null?void 0:W[0];if(!Z)return;if(!Z.type.startsWith("image/")){ae.error("Please select an image file");return}const Y=new FileReader;Y.onloadend=()=>{l(Y.result),a(!0)},Y.readAsDataURL(Z),H.target.value=""},z=async H=>{v(!0);try{const{data:Z}=await q.storage.from("avatars").list(`${s}`);Z&&Z.length>0&&await q.storage.from("avatars").remove(Z.map(oe=>`${s}/${oe.name}`));const Y=`${s}/avatar.jpg`,{error:W}=await q.storage.from("avatars").upload(Y,H,{upsert:!0,contentType:"image/jpeg"});if(W)throw W;const{data:ee}=q.storage.from("avatars").getPublicUrl(Y),se=ee.publicUrl+"?t="+Date.now();await q.from("profiles").update({avatar_url:se}).eq("id",s),t.invalidateQueries({queryKey:["card-editor-profile",s]}),t.invalidateQueries({queryKey:["card-preview-profile",s]}),t.invalidateQueries({queryKey:["agent-card-user"]}),ae.success("Photo updated!")}catch{ae.error("Failed to upload photo")}finally{v(!1)}};return c?e.jsx(Ws,{className:"h-32 w-full rounded-xl"}):e.jsxs(e.Fragment,{children:[e.jsx(fe,{className:O?"border-amber-300 dark:border-amber-700":"",children:e.jsxs(Ee,{className:"p-5 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsx(ne,{className:"text-sm font-semibold",children:"Profile Info"}),O&&e.jsxs("span",{className:"inline-flex items-center gap-1 text-xs text-amber-600 dark:text-amber-400 font-medium",children:[e.jsx(Bi,{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 H;return(H=n.current)==null?void 0:H.click()},children:[e.jsxs(Jr,{className:"h-16 w-16 ring-2 ring-muted",children:[e.jsx(ti,{src:A||void 0,alt:j}),e.jsx(ea,{className:"text-lg font-semibold bg-primary/10 text-primary",children:E})]}),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(Jf,{className:"h-5 w-5 text-white"})}),e.jsx("input",{ref:n,type:"file",accept:"image/*",className:"hidden",onChange:F})]}),e.jsxs("div",{className:"flex-1 space-y-0.5",children:[e.jsx("p",{className:"text-sm font-medium",children:_?"Uploading...":A?"Tap to change photo":"Add a profile photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"This photo appears on your card, profile, and community posts"})]})]}),e.jsxs("div",{className:"grid gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Full Name"}),e.jsx(ye,{value:j,onChange:H=>u(H.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(ne,{className:"text-xs font-medium text-muted-foreground",children:"Phone Number"}),e.jsx(ye,{value:w,onChange:H=>p(H.target.value),placeholder:"(555) 123-4567",className:"h-10",type:"tel"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Email"}),e.jsx(ye,{value:S,onChange:H=>y(H.target.value),placeholder:"you@example.com",className:"h-10",type:"email"})]})]})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:I,disabled:D.isPending,className:"w-full",children:D.isPending?"Saving...":"Update Profile Info"})]})}),e.jsx(G6e,{open:r,onClose:()=>a(!1),imageSrc:i,onCropComplete:z,aspectRatio:1})]})}function $Xs({form:s,setForm:t,userId:n}){const[r,a]=N.useState(null),[i,l]=N.useState(s.brokerage_logo_url?"logo":"name"),[o,c]=N.useState(s.team_logo_url?"logo":"name"),d=f=>{l(f),t(f==="name"?y=>({...y,brokerage_logo_url:""}):y=>({...y,brokerage_display_name:""}))},u=f=>{c(f),t(f==="name"?y=>({...y,team_logo_url:""}):y=>({...y,team_name:""}))},h=async(f,y)=>{var v;const _=(v=f.target.files)==null?void 0:v[0];if(_){if(!_.type.startsWith("image/")){ae.error("Please select an image file");return}a(y);try{const j=_.name.split(".").pop()||"png",S=`${n}/${y==="brokerage_logo_url"?"brokerage-logo":"team-logo"}.${j}`,{error:A}=await q.storage.from("card-logos").upload(S,_,{upsert:!0});if(A)throw A;const{data:E}=q.storage.from("card-logos").getPublicUrl(S),O=E.publicUrl+"?t="+Date.now();t(y==="brokerage_logo_url"?D=>({...D,[y]:O,brokerage_display_name:""}):D=>({...D,[y]:O,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{a(null),f.target.value=""}}},p=f=>{t(y=>({...y,[f]:""}))};return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5 space-y-5",children:[e.jsxs("div",{children:[e.jsx(ne,{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(ne,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:i==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("name"),children:"Use Name"}),e.jsx(B,{type:"button",variant:i==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>d("logo"),children:"Use Logo"})]}),i==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Name"}),e.jsx(ye,{value:s.brokerage_display_name,onChange:f=>t(y=>({...y,brokerage_display_name:f.target.value})),placeholder:"e.g. Keller Williams Realty",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.brokerage_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${s.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>p("brokerage_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Jf,{className:"h-3.5 w-3.5"}),r==="brokerage_logo_url"?"Uploading...":s.brokerage_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"brokerage_logo_url"),disabled:r!==null})]})]}),s.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{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(jp,{value:[s.brokerage_logo_size||56],onValueChange:([f])=>t(y=>({...y,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(ne,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{type:"button",variant:o==="name"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("name"),children:"Use Name"}),e.jsx(B,{type:"button",variant:o==="logo"?"default":"outline",size:"sm",className:"text-xs",onClick:()=>u("logo"),children:"Use Logo"})]}),o==="name"?e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Team Name"}),e.jsx(ye,{value:s.team_name,onChange:f=>t(y=>({...y,team_name:f.target.value})),placeholder:"e.g. The Smith Group",className:"h-10"})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Team Logo"}),e.jsxs("div",{className:"flex items-center gap-3",children:[s.team_logo_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:s.team_logo_url,alt:"Team logo",style:{height:`${s.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>p("team_logo_url"),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}):null,e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(Jf,{className:"h-3.5 w-3.5"}),r==="team_logo_url"?"Uploading...":s.team_logo_url?"Change":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:f=>h(f,"team_logo_url"),disabled:r!==null})]})]}),s.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{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(jp,{value:[s.team_logo_size||56],onValueChange:([f])=>t(y=>({...y,team_logo_size:f})),min:24,max:120,step:4})]})]})]})]})})}function UXs({form:s,setForm:t}){const n={accent:"#ff5722",dark:"#1a1a2e",button:"#ff5722"},r=s.bold_theme_colors||n,a=(o,c)=>{t(d=>({...d,bold_theme_colors:{...n,...d.bold_theme_colors,[o]:c}}))},i=()=>{t(o=>({...o,bold_theme_colors:null}))},l=[{key:"accent",label:"Accent Color",desc:"Page background, icons, highlights"},{key:"dark",label:"Dark Color",desc:"Header background, action buttons, social icons"},{key:"button",label:"CTA Button Color",desc:"Main call-to-action button"}];return e.jsxs("div",{className:"space-y-3 p-4 rounded-xl border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(ne,{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(pl,{className:"h-4 w-4"})," Brand Colors"]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:"Customize colors to match your brand"})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-xs h-7",onClick:i,children:"Reset to Default"})]}),e.jsx("div",{className:"grid gap-3",children:l.map(({key:o,label:c,desc:d})=>e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("label",{className:"relative shrink-0",children:[e.jsx("input",{type:"color",value:r[o],onChange:u=>a(o,u.target.value),className:"sr-only"}),e.jsx("div",{className:"h-10 w-10 rounded-lg border-2 border-border cursor-pointer shadow-sm hover:scale-105 transition-transform",style:{backgroundColor:r[o]}})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-medium",children:c}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsx(ye,{value:r[o],onChange:u=>{const h=u.target.value;/^#[0-9a-fA-F]{0,6}$/.test(h)&&a(o,h)},className:"w-24 h-8 text-xs font-mono",placeholder:"#ff5722"})]},o))}),e.jsxs("div",{className:"flex items-center gap-2 pt-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Preview:"}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.accent}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.dark}}),e.jsx("div",{className:"h-6 w-12 rounded",style:{backgroundColor:r.button}})]})]})]})}function qXs({card:s,form:t,setForm:n}){var _;const r=Wlt(),a=Kt(),{data:i}=Klt(s.id),[l,o]=N.useState(s.slug),[c,d]=N.useState(!1),[u,h]=N.useState("idle"),p=N.useRef(JSON.stringify(t)),f=N.useRef(null);N.useEffect(()=>{const v=JSON.stringify(t);if(v!==p.current)return f.current&&clearTimeout(f.current),f.current=setTimeout(()=>{h("saving"),r.mutate({id:s.id,...t,is_published:!0,title:t.title||null,positioning_statement:t.positioning_statement||null,bio:t.bio||null,review_snippet:t.review_snippet||null,review_source_url:t.review_source_url||null,booking_url:t.booking_url||null,custom_cta_label:t.custom_cta_label||null,brokerage_display_name:t.brokerage_display_name||null,brokerage_logo_url:t.brokerage_logo_url||null,brokerage_logo_size:t.brokerage_logo_size,team_name:t.team_name||null,team_logo_url:t.team_logo_url||null,team_logo_size:t.team_logo_size,bold_theme_colors:t.bold_theme_colors||null,display_email:t.display_email||null},{onSuccess:()=>{p.current=v,h("saved"),setTimeout(()=>h("idle"),2e3)},onError:()=>h("idle")})},1500),()=>{f.current&&clearTimeout(f.current)}},[t]);const y=async()=>{const v=l.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!v){ae.error("Please enter a valid URL");return}if(v===s.slug){ae.info("No changes to save");return}d(!0);try{const{data:j}=await q.from("agent_cards").select("id").eq("slug",v).neq("id",s.id).maybeSingle();if(j){ae.error("This URL is already taken. Try another one.");return}const{error:w}=await q.from("agent_cards").update({slug:v}).eq("id",s.id);if(w)throw w;o(v),a.invalidateQueries({queryKey:["agent-card"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{d(!1)}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs(Fr,{defaultValue:"content",children:[e.jsxs(Rr,{className:"w-full h-11 p-1",children:[e.jsxs(Zt,{value:"content",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(uf,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Content"]}),e.jsxs(Zt,{value:"sections",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(Sr,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Sections"]}),e.jsxs(Zt,{value:"blocks",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(im,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Blocks"]}),e.jsxs(Zt,{value:"qrcode",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(ry,{className:"h-3.5 w-3.5 hidden sm:inline"}),"QR Code"]}),e.jsxs(Zt,{value:"analytics",className:"flex-1 gap-1.5 data-[state=active]:shadow-sm",children:[e.jsx(oc,{className:"h-3.5 w-3.5 hidden sm:inline"}),"Analytics"]})]}),e.jsxs(is,{value:"content",className:"mt-4 space-y-4",children:[e.jsx(BXs,{userId:s.user_id}),e.jsx($Xs,{form:t,setForm:n,userId:s.user_id}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-5 space-y-5",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:t.is_published,onCheckedChange:v=>n(j=>({...j,is_published:v}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ye,{value:l,onChange:v=>o(v.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"your-name",className:"rounded-l-none h-10"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:y,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(ne,{className:"text-sm font-medium",children:"Card Email (Override)"}),e.jsx(ye,{value:t.display_email,onChange:v=>n(j=>({...j,display_email:v.target.value})),placeholder:"you@yourbusiness.com",className:"h-11",type:"email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Optional — use a different email on your card instead of your sign-in email."})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Theme"}),e.jsxs(us,{value:t.theme,onValueChange:v=>n(j=>({...j,theme:v})),children:[e.jsx(ls,{className:"h-11",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"standard",children:"✨ Standard — Modern & Clean"}),e.jsx(Ze,{value:"luxury",children:"🌙 Luxury — Dark & Gold"}),e.jsx(Ze,{value:"bold",children:"🔥 Bold — Vibrant & Punchy"}),e.jsx(Ze,{value:"classic",children:"📋 Classic — Professional"})]})]})]}),t.theme==="bold"&&e.jsx(UXs,{form:t,setForm:n}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Title / Tagline"}),e.jsx(ye,{value:t.title,onChange:v=>n(j=>({...j,title:v.target.value})),placeholder:"e.g. Luxury Real Estate Specialist",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown below your name on the card"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Positioning Statement"}),e.jsx(ye,{value:t.positioning_statement,onChange:v=>n(j=>({...j,positioning_statement:v.target.value})),placeholder:"Your home journey, handled with care.",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Bio"}),e.jsx(Ms,{value:t.bio,onChange:v=>n(j=>({...j,bio:v.target.value})),placeholder:"A short intro about you and what makes you different...",rows:3})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Review Snippet"}),e.jsx(ye,{value:t.review_snippet,onChange:v=>n(j=>({...j,review_snippet:v.target.value})),placeholder:"Best agent we've ever worked with...",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Review Source URL"}),e.jsx(ye,{value:t.review_source_url,onChange:v=>n(j=>({...j,review_source_url:v.target.value})),placeholder:"https://g.page/your-business/review",className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Booking URL"}),e.jsx(ye,{value:t.booking_url,onChange:v=>n(j=>({...j,booking_url:v.target.value})),placeholder:"https://calendly.com/your-link",className:"h-11"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Leave empty to show a built-in lead form instead"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Custom CTA Label"}),e.jsx(ye,{value:t.custom_cta_label,onChange:v=>n(j=>({...j,custom_cta_label:v.target.value})),placeholder:"Book a Call",className:"h-11"})]})]})})]}),e.jsx(is,{value:"sections",className:"mt-4",children:e.jsx(fe,{children:e.jsx(Ee,{className:"p-5 divide-y",children:[{key:"show_photo",label:"Photo",desc:"Uses the photo from your Profile Info above"},{key:"show_bio",label:"Bio Section",desc:"Display your bio on the card"},{key:"show_credentials",label:"Credentials",desc:"Show star rating and reviews"},{key:"show_social_links",label:"Social Links",desc:"Display your social media links"},{key:"show_save_contact",label:"Save Contact",desc:"Let visitors save you as a contact"},{key:"show_leave_review",label:"Leave Review",desc:"Link to your review page"},{key:"show_refer_friend",label:"Refer a Friend",desc:"Enable referral submissions"}].map(({key:v,label:j,desc:w})=>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(ne,{className:"text-sm font-medium",children:j}),e.jsx("p",{className:"text-xs text-muted-foreground",children:w})]}),e.jsx(jn,{checked:t[v],onCheckedChange:S=>n(A=>({...A,[v]:S}))})]},v))})})}),e.jsx(is,{value:"blocks",className:"mt-4",children:e.jsx(i2t,{cardId:s.id})}),e.jsx(is,{value:"analytics",className:"mt-4",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-3",children:[{label:"Views",value:(i==null?void 0:i.views)??0,icon:Sr,color:"text-blue-600 bg-blue-100 dark:text-blue-400 dark:bg-blue-900/30"},{label:"Clicks",value:(i==null?void 0:i.clicks)??0,icon:oc,color:"text-amber-600 bg-amber-100 dark:text-amber-400 dark:bg-amber-900/30"},{label:"Leads",value:((_=i==null?void 0:i.leads)==null?void 0:_.length)??0,icon:Fo,color:"text-emerald-600 bg-emerald-100 dark:text-emerald-400 dark:bg-emerald-900/30"}].map(v=>e.jsx(fe,{className:"overflow-hidden",children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx("div",{className:`p-1.5 rounded-md ${v.color}`,children:e.jsx(v.icon,{className:"h-3.5 w-3.5"})}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:v.label})]}),e.jsx("div",{className:"text-2xl font-bold",children:v.value})]})},v.label))}),i&&i.leads.length>0&&e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsx(Rt,{className:"text-base",children:"Recent Leads"})}),e.jsx(Ee,{className:"pt-0 space-y-2",children:i.leads.slice(0,5).map(v=>e.jsxs("div",{className:"flex items-center justify-between text-sm p-3 rounded-lg bg-muted/50",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:v.name}),v.phone&&e.jsx("span",{className:"text-muted-foreground ml-2",children:v.phone})]}),v.intent&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:v.intent})]},v.id))})]}),(!i||i.leads.length===0)&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-8 text-center",children:[e.jsx(oc,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"font-medium text-muted-foreground",children:"No analytics data yet"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Share your card link to start tracking"})]})})]})}),e.jsx(is,{value:"qrcode",className:"mt-4 space-y-4",children:e.jsx(fe,{children:e.jsx(Ee,{className:"p-6",children:e.jsx(DXs,{slug:s.slug})})})})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 py-2 text-sm text-muted-foreground",children:[u==="saving"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-amber-400 animate-pulse"})," Saving..."]}),u==="saved"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-green-500"})," All changes saved"]}),u==="idle"&&e.jsxs(e.Fragment,{children:[e.jsx("span",{className:"h-2 w-2 rounded-full bg-muted-foreground/30"})," Changes auto-save"]})]})]})}function VXs(){const s=Kt(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,y]=N.useState(null),[_,v]=N.useState(null),[j,w]=N.useState(0),[S,A]=N.useState(""),[E,O]=N.useState(!1),{data:D,isLoading:I}=dt({queryKey:["boldtrail-status"],queryFn:async()=>{const{data:ce,error:me}=await q.functions.invoke("boldtrail-sync",{body:{action:"status"}});if(me)throw me;return ce}}),F=yt({mutationFn:async ce=>{const{data:me,error:le}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_token",api_token:ce}});if(le)throw le;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),n(""),ae.success("BoldTrail connected successfully!")},onError:ce=>{ae.error(ce.message||"Failed to connect BoldTrail")}}),z=yt({mutationFn:async()=>{const{data:ce,error:me}=await q.functions.invoke("boldtrail-sync",{body:{action:"disconnect"}});if(me)throw me;return ce},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("BoldTrail disconnected")},onError:()=>ae.error("Failed to disconnect")}),H=yt({mutationFn:async ce=>{const{data:me,error:le}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_direction",sync_direction:ce}});if(le)throw le;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Sync direction saved")},onError:ce=>{ae.error(ce.message||"Failed to save sync direction")}}),Z=yt({mutationFn:async()=>{const{data:ce,error:me}=await q.functions.invoke("boldtrail-sync",{body:{action:"detect_owner"}});if(me)throw me;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{if(s.invalidateQueries({queryKey:["boldtrail-status"]}),ce.kvcore_user_id){const me=ce.detected_name||ce.detected_email||`ID ${ce.kvcore_user_id}`;ae.success(`Detected your BoldTrail account: ${me}`)}else if(ce.candidates&&ce.candidates.length>0){const me=ce.candidates.slice(0,5).map(le=>`${le.id} (${le.count} contacts)`).join(", ");ae.warning(`Couldn't auto-detect your ID. Owner IDs found in your contacts: ${me}. Pick yours and enter it below.`,{duration:12e3}),O(!0)}else ae.warning("Couldn't auto-detect your BoldTrail user ID. Please find it in BoldTrail (My Profile URL) and enter it manually."),O(!0)},onError:ce=>ae.error(ce.message||"Detection failed")}),Y=yt({mutationFn:async ce=>{const{data:me,error:le}=await q.functions.invoke("boldtrail-sync",{body:{action:"save_owner_settings",...ce}});if(le)throw le;if(me!=null&&me.error)throw new Error(me.error);return me},onSuccess:()=>{s.invalidateQueries({queryKey:["boldtrail-status"]}),ae.success("Settings saved"),O(!1)},onError:ce=>ae.error(ce.message||"Failed to save settings")}),W=yt({mutationFn:async()=>{const{data:ce,error:me}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync_preview"}});if(me)throw me;if(ce!=null&&ce.error)throw new Error(ce.error);return ce},onSuccess:ce=>{y(null),c(ce),a(!0)},onError:ce=>{ae.error(ce.message||"Failed to generate sync preview")}}),ee=yt({mutationFn:async()=>{v("Initializing sync..."),w(5);const{data:ce,error:me}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"init",sync_direction:he}});if(me)throw me;if(ce!=null&&ce.error)throw new Error(ce.error);const le=ce;let ve=le.sync_log_id,ge=le.next_phase,Te=le.next_offset,Ie=le.push_total||0,Ce=le.pull_total||0,Me=0,Pe=0;for(;ge!=="finalize";){const Be=Ie+Ce;ge==="fetch_bt"?v("Fetching BoldTrail contacts..."):ge==="analyze"?(v("Analyzing contacts..."),w(15)):ge==="push"?(v(`Pushing contacts to BoldTrail... (${Me}/${Ie})`),w(Be>0?Me/Be*100:0)):ge==="pull"&&(v(`Pulling contacts from BoldTrail... (${Pe}/${Ce})`),w(Be>0?(Ie+Pe)/Be*100:0));const{data:we,error:Je}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:ge,offset:Te,sync_log_id:ve,sync_direction:he}});if(Je)throw Je;if(we!=null&&we.error)throw new Error(we.error);const ke=we;Me+=ke.chunk_pushed||0,Pe+=ke.chunk_pulled||0,ke.push_total!==void 0&&(Ie=ke.push_total||0),ke.pull_total!==void 0&&(Ce=ke.pull_total||0),ke.progress&&v(ke.progress),ge==="pull"&&Ce>0?w(Math.min(95,Pe/Ce*100)):ge==="push"&&Ie>0&&w(Math.min(95,Me/Ie*100)),ge=ke.next_phase,Te=ke.next_offset}v("Finalizing sync..."),w(95);const{data:Re,error:Ae}=await q.functions.invoke("boldtrail-sync",{body:{action:"sync",phase:"finalize",sync_log_id:ve,sync_direction:he}});if(Ae)throw Ae;return w(100),Re},onSuccess:ce=>{v(null),w(0),a(!1),s.invalidateQueries({queryKey:["boldtrail-status"]}),s.invalidateQueries({queryKey:["contacts"]}),s.invalidateQueries({queryKey:["innercircle-contacts"]}),s.invalidateQueries({queryKey:["innercircle-contact-counts"]}),s.invalidateQueries({queryKey:["contacts-last-touch"]}),ae.success(`Sync complete! Pushed ${ce.contacts_pushed||0}, pulled ${ce.contacts_pulled||0}, skipped ${ce.contacts_skipped||0} duplicates.`)},onError:ce=>{v(null),w(0),ae.error(ce.message||"Sync failed")}}),se=D==null?void 0:D.connected,oe=(D==null?void 0:D.sync_direction)||"bidirectional",he=f??oe;return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(It,{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(ah,{className:"h-5 w-5 text-emerald-600"})}),e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:["BoldTrail",se&&e.jsx(Ue,{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(jh,{className:"h-3.5 w-3.5"}),"Learn More"]})]}),e.jsx(Vn,{children:"Sync contacts bidirectionally between Agent OS and your BoldTrail (kvCORE) CRM."})]})]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Pi,{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(Pi,{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(Pi,{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"})]}),se?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsx("div",{className:"rounded-lg border p-3 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:"BoldTrail Connected"}),(D==null?void 0:D.last_sync_at)&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Last sync: ",new Date(D.last_sync_at).toLocaleString(),D.last_sync_status&&e.jsx(Ue,{variant:D.last_sync_status==="success"?"default":"secondary",className:"ml-2 text-[10px]",children:D.last_sync_status})]}),(D==null?void 0:D.boldtrail_contact_count)!=null&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[D.boldtrail_contact_count," contacts in BoldTrail"]}),(D==null?void 0:D.last_sync_message)&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:D.last_sync_message})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect BoldTrail?"}),e.jsx(Mo,{children:"This will remove your API token. Previously synced contacts will remain in both systems."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{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(xb,{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(jn,{checked:!!(D!=null&&D.sync_only_owned),onCheckedChange:ce=>Y.mutate({sync_only_owned:ce}),disabled:Y.isPending})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"Your BoldTrail Agent ID"}),E?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",placeholder:"e.g. 12345",value:S,onChange:ce=>A(ce.target.value),className:"h-8 text-sm"}),e.jsx(B,{size:"sm",onClick:()=>{const ce=S.trim()===""?null:Number(S);Y.mutate({kvcore_user_id:ce})},disabled:Y.isPending,children:"Save"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>O(!1),children:"Cancel"})]}):e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"text-sm font-mono",children:(D==null?void 0:D.kvcore_user_id)??e.jsx("span",{className:"text-muted-foreground",children:"Not set"})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>Z.mutate(),disabled:Z.isPending,children:[Z.isPending?e.jsx(Ei,{className:"h-3 w-3 mr-1 animate-spin"}):null,"Auto-detect"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{var ce;A(((ce=D==null?void 0:D.kvcore_user_id)==null?void 0:ce.toString())??""),O(!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(P5e,{value:oe,onChange:ce=>H.mutate(ce)})}),e.jsx("div",{className:"flex gap-2",children:e.jsxs(B,{onClick:()=>W.mutate(),disabled:W.isPending||ee.isPending,variant:"outline",className:"gap-2",children:[W.isPending?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(Sr,{className:"h-4 w-4"}),"Preview Sync"]})})]}):e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{type:"password",placeholder:"Paste your BoldTrail API token",value:t,onChange:ce=>n(ce.target.value),className:"flex-1"}),e.jsxs(B,{onClick:()=>F.mutate(t),disabled:!t||t.length<10||F.isPending,children:[F.isPending?e.jsx(Ei,{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(_s,{open:r,onOpenChange:ce=>{ee.isPending||a(ce)},children:e.jsxs(bs,{className:"sm:max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(ah,{className:"h-5 w-5 text-emerald-600"}),"Sync Preview"]}),e.jsx(Jn,{children:"Review what will happen when you sync your contacts."})]}),o&&(()=>{const ce=he==="pull_only"?0:o.to_push,me=he==="push_only"?0:o.to_pull;return e.jsxs("div",{className:"space-y-4",children:[e.jsx(P5e,{value:he,onChange:y,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(xb,{className:"h-3.5 w-3.5 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Owner filter is on. Only contacts assigned to your BoldTrail account",o.kvcore_user_id?` (ID ${o.kvcore_user_id})`:""," will be synced.",o.boldtrail_total_brokerage!=null&&e.jsxs(e.Fragment,{children:[" Brokerage total: ",e.jsx("strong",{children:o.boldtrail_total_brokerage.toLocaleString()}),"."]})]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{className:`rounded-lg border p-3 text-center ${he==="pull_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-emerald-600",children:ce}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(Iu,{className:"h-3 w-3"})," Push to BoldTrail"]})]}),e.jsxs("div",{className:`rounded-lg border p-3 text-center ${he==="push_only"?"opacity-40":""}`,children:[e.jsx("p",{className:"text-2xl font-bold text-blue-600",children:me}),e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center justify-center gap-1",children:[e.jsx(sm,{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(An,{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"]}),ee.isPending&&e.jsxs("div",{className:"space-y-2 py-2",children:[e.jsx(fi,{value:j||10,className:"h-2"}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:_||"Sync in progress..."})]}),ce>0&&e.jsxs(oy,{open:d,onOpenChange:u,children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Iu,{className:"h-3 w-3 text-emerald-600"}),ce," contacts to push to BoldTrail"]}),e.jsx(ao,{className:`h-3 w-3 transition-transform ${d?"rotate-180":""}`})]})}),e.jsx(cy,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.push_preview.map((le,ve)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:le.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:le.email})]},ve)),o.to_push>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_push-20," more"]})]})})]}),me>0&&e.jsxs(oy,{open:h,onOpenChange:p,children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(sm,{className:"h-3 w-3 text-blue-600"}),me," contacts to pull from BoldTrail"]}),e.jsx(ao,{className:`h-3 w-3 transition-transform ${h?"rotate-180":""}`})]})}),e.jsx(cy,{children:e.jsxs("div",{className:"rounded border divide-y max-h-40 overflow-y-auto",children:[o.pull_preview.map((le,ve)=>e.jsxs("div",{className:"px-3 py-1.5 text-xs flex justify-between",children:[e.jsx("span",{className:"font-medium",children:le.name||"No name"}),e.jsx("span",{className:"text-muted-foreground",children:le.email})]},ve)),o.to_pull>20&&e.jsxs("div",{className:"px-3 py-1.5 text-xs text-muted-foreground text-center",children:["...and ",o.to_pull-20," more"]})]})})]}),ce===0&&me===0&&e.jsx("div",{className:"text-center py-4 text-sm text-muted-foreground",children:"✅ Everything is already in sync! No contacts to transfer."}),e.jsxs("div",{className:"flex gap-2 justify-end pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),disabled:ee.isPending,children:"Cancel"}),e.jsxs(B,{onClick:()=>ee.mutate(),disabled:ee.isPending||ce===0&&me===0,className:"gap-2",children:[ee.isPending?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(ah,{className:"h-4 w-4"}),ee.isPending?"Syncing...":"Sync Now"]})]})]})})()]})}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{className:"sm:max-w-2xl p-0 overflow-hidden",children:[e.jsx(js,{className:"p-6 pb-0",children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(ah,{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 HXs(){const s=Kt(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(null),{data:d,isLoading:u}=dt({queryKey:["fub-status"],queryFn:async()=>{const{data:_,error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"status"}});if(v)throw v;return _}}),h=yt({mutationFn:async _=>{const{data:v,error:j}=await q.functions.invoke("followupboss-sync",{body:{action:"save_token",api_key:_}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ae.success("Connected to Follow Up Boss"),n(""),s.invalidateQueries({queryKey:["fub-status"]})},onError:_=>ae.error(_.message)}),p=yt({mutationFn:async()=>{const{error:_}=await q.functions.invoke("followupboss-sync",{body:{action:"disconnect"}});if(_)throw _},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["fub-status"]})}}),f=yt({mutationFn:async _=>{const{error:v}=await q.functions.invoke("followupboss-sync",{body:{action:"set_direction",sync_direction:_}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["fub-status"]})}),y=async()=>{a(!0),l(0),c("Pulling from FUB…");let _=0,v=0,j=0,w=0;try{for(;;){const{data:O,error:D}=await q.functions.invoke("followupboss-sync",{body:{action:"sync",offset:_}});if(D)throw D;if(O!=null&&O.error)throw new Error(O.error);v+=O.chunk_created||0,j+=O.chunk_updated||0,w+=O.chunk_skipped||0,_=O.next_offset;const I=O.total?Math.min(100,Math.round(_/O.total*100)):100;if(l(I),c(`Pulling · ${_} / ${O.total||"?"}`),O.done)break;await new Promise(F=>setTimeout(F,400))}let S=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let O=0;for(l(0),c("Pushing to FUB…");;){const{data:D,error:I}=await q.functions.invoke("followupboss-sync",{body:{action:"push",offset:O}});if(I)throw I;if(D!=null&&D.error)throw new Error(D.error);S+=D.chunk_pushed||0,A+=D.chunk_failed||0,O=D.next_offset;const F=D.total?Math.min(100,Math.round(O/D.total*100)):100;if(l(F),c(`Pushing · ${O} / ${D.total||"?"}`),D.done)break;await new Promise(z=>setTimeout(z,400))}}const E=S||A?` · pushed ${S}${A?`, ${A} failed`:""}`:"";ae.success(`Sync complete · ${v} new, ${j} updated${w?`, ${w} skipped`:""}${E}`),s.invalidateQueries({queryKey:["fub-status"]})}catch(S){ae.error(S.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Y2,{className:"h-5 w-5 text-primary"}),"Follow Up Boss",(d==null?void 0:d.connected)&&e.jsxs(Ue,{variant:"default",className:"ml-1",children:[e.jsx(Pi,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync your Follow Up Boss contacts into Agent OS."})]})})}),e.jsx(Ee,{className:"space-y-4",children:u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):d!=null&&d.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:d.last_sync_at?new Date(d.last_sync_at).toLocaleString():"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"FUB contacts"}),e.jsx("p",{className:"font-medium",children:d.fub_contact_count??"—"})]})]}),d.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:d.last_sync_message}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off = pull from FUB only. On = also push new Agent OS contacts to FUB."})]}),e.jsx(jn,{checked:d.sync_direction==="bidirectional",onCheckedChange:_=>f.mutate(_?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(fi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:y,disabled:r,children:[e.jsx(Ei,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(_n,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Follow Up Boss?"}),e.jsx(Mo,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>p.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"fub-key",children:"Follow Up Boss API Key"}),e.jsx(ye,{id:"fub-key",type:"password",placeholder:"fka_live_...",value:t,onChange:_=>n(_.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Find your key in FUB → Admin → API.",e.jsxs("a",{href:"https://app.followupboss.com/2/api",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(tr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function GXs(){var W;const s=Kt(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState(!1),[o,c]=N.useState(0),[d,u]=N.useState(null),[h,p]=N.useState(!1),[f,y]=N.useState(null),[_,v]=N.useState(!1),[j,w]=N.useState(new Set),{data:S,isLoading:A}=dt({queryKey:["cloze-status"],queryFn:async()=>{const{data:ee,error:se}=await q.functions.invoke("cloze-sync",{body:{action:"status"}});if(se)throw se;return ee}}),E=yt({mutationFn:async()=>{const{data:ee,error:se}=await q.functions.invoke("cloze-sync",{body:{action:"save_token",api_key:t.trim(),account_email:r.trim()}});if(se)throw se;if(ee!=null&&ee.error)throw new Error(ee.error);return ee},onSuccess:()=>{ae.success("Connected to Cloze"),n(""),a(""),s.invalidateQueries({queryKey:["cloze-status"]})},onError:ee=>ae.error(ee.message)}),O=yt({mutationFn:async()=>{const{error:ee}=await q.functions.invoke("cloze-sync",{body:{action:"disconnect"}});if(ee)throw ee},onSuccess:()=>{ae.success("Cloze disconnected"),s.invalidateQueries({queryKey:["cloze-status"]})}}),D=yt({mutationFn:async ee=>{const{error:se}=await q.functions.invoke("cloze-sync",{body:{action:"set_direction",sync_direction:ee}});if(se)throw se},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),I=yt({mutationFn:async ee=>{const{error:se}=await q.functions.invoke("cloze-sync",{body:{action:"set_scope",...ee}});if(se)throw se},onSuccess:()=>s.invalidateQueries({queryKey:["cloze-status"]})}),F=async()=>{v(!0);try{const{data:ee,error:se}=await q.functions.invoke("cloze-sync",{body:{action:"list_segments"}});if(se)throw se;if(ee!=null&&ee.error)throw new Error(ee.error);y(ee.segments||[]),w(new Set((S==null?void 0:S.selected_segments)||[])),p(!0)}catch(ee){ae.error(ee.message||"Failed to load segments")}finally{v(!1)}},z=async()=>{const ee=Array.from(j);await I.mutateAsync({sync_scope:"segments",selected_segments:ee}),ae.success(`Saved · ${ee.length} segment(s) selected`),p(!1)},H=async()=>{const ee=(S==null?void 0:S.sync_direction)||"pull_only";l(!0),c(0);try{if(ee==="pull_only"||ee==="bidirectional"){u("Pulling from Cloze…");let se=0,oe=0,he=0;for(;;){const{data:ce,error:me}=await q.functions.invoke("cloze-sync",{body:{action:"sync",offset:se}});if(me)throw me;if(ce!=null&&ce.error)throw new Error(ce.error);if(oe+=ce.chunk_created||0,he+=ce.chunk_updated||0,se=ce.next_offset,u(`Pulling · ${oe+he} contacts processed`),c(ce.done?100:Math.min(95,(oe+he)%200/2)),ce.done)break;await new Promise(le=>setTimeout(le,300))}ae.success(`Pulled · ${oe} new, ${he} updated`)}if(ee==="push_only"||ee==="bidirectional"){c(0),u("Pushing to Cloze…");let se=0,oe=0,he=0;for(;;){const{data:ce,error:me}=await q.functions.invoke("cloze-sync",{body:{action:"push",offset:se}});if(me)throw me;if(ce!=null&&ce.error)throw new Error(ce.error);oe+=ce.chunk_pushed||0,he+=ce.chunk_failed||0,se=ce.next_offset;const le=ce.total?Math.min(100,Math.round(se/ce.total*100)):100;if(c(le),u(`Pushing · ${se} / ${ce.total||"?"}`),ce.done)break;await new Promise(ve=>setTimeout(ve,300))}ae.success(`Pushed · ${oe}${he?`, ${he} failed`:""}`)}s.invalidateQueries({queryKey:["cloze-status"]})}catch(se){ae.error(se.message||"Sync failed")}finally{l(!1),setTimeout(()=>{c(0),u(null)},2e3)}},Z=(S==null?void 0:S.sync_scope)||"all",Y=((W=S==null?void 0:S.selected_segments)==null?void 0:W.length)||0;return e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Y2,{className:"h-5 w-5 text-primary"}),"Cloze",(S==null?void 0:S.connected)&&e.jsxs(Ue,{variant:"default",className:"ml-1",children:[e.jsx(Pi,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync contacts between Cloze and Agent OS using your personal Cloze API key."})]})})}),e.jsx(Ee,{className:"space-y-4",children:A?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):S!=null&&S.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Account"}),e.jsx("p",{className:"font-medium break-all",children:S.account_email})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:S.last_sync_at?new Date(S.last_sync_at).toLocaleString():"Never"})]})]}),S.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:S.last_sync_message}),e.jsx("div",{className:"rounded-lg border px-3 py-2 space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sync direction"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Choose which way contacts should flow."})]}),e.jsxs(us,{value:S.sync_direction||"pull_only",onValueChange:ee=>D.mutate(ee),disabled:i||D.isPending,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"pull_only",children:"Pull from Cloze"}),e.jsx(Ze,{value:"push_only",children:"Push to Cloze"}),e.jsx(Ze,{value:"bidirectional",children:"Two-way sync"})]})]})]})}),e.jsxs("div",{className:"rounded-lg border px-3 py-2 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"What to sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Z==="all"?"All Cloze contacts.":`${Y} segment${Y===1?"":"s"} selected.`})]}),e.jsxs(us,{value:Z,onValueChange:ee=>{ee==="all"?I.mutate({sync_scope:"all",selected_segments:[]}):(I.mutate({sync_scope:"segments",selected_segments:S.selected_segments||[]}),F())},disabled:i||I.isPending,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All contacts"}),e.jsx(Ze,{value:"segments",children:"Selected segments"})]})]})]}),Z==="segments"&&e.jsxs("div",{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:F,disabled:_,children:[e.jsx(w9,{className:"h-4 w-4 mr-2"}),_?"Loading segments…":"Choose segments"]}),h&&f&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"max-h-96 overflow-y-auto rounded-md border divide-y",children:[f.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground p-3",children:"No segments found in your Cloze account."}),f.map(ee=>{const se=j.has(ee.id);return e.jsxs("label",{className:"flex items-center gap-3 p-2 cursor-pointer hover:bg-muted/50",children:[e.jsx(hi,{checked:se,onCheckedChange:oe=>{const he=new Set(j);oe?he.add(ee.id):he.delete(ee.id),w(he)}}),e.jsx("span",{className:"flex-1 text-sm",children:ee.name}),ee.count!=null&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:ee.count})]},ee.id)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:z,disabled:I.isPending,children:["Save selection (",j.size,")"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(!1),children:"Cancel"})]})]})]})]}),d&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(fi,{value:o}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsxs(B,{disabled:i,children:[e.jsx(Ei,{className:`h-4 w-4 mr-2 ${i?"animate-spin":""}`}),i?"Syncing…":"Sync Now"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Preview sync"}),e.jsx(Mo,{asChild:!0,children:e.jsx(WXs,{segments:f})})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:H,children:"Start Sync"})]})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:i,children:[e.jsx(_n,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Cloze?"}),e.jsx(Mo,{children:"Your API key will be removed. Contacts already synced will remain."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>O.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"cloze-email",children:"Cloze Account Email"}),e.jsx(ye,{id:"cloze-email",type:"email",placeholder:"you@example.com",value:r,onChange:ee=>a(ee.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"cloze-key",children:"Cloze API Key"}),e.jsx(ye,{id:"cloze-key",type:"password",placeholder:"Your personal Cloze API key",value:t,onChange:ee=>n(ee.target.value)}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 flex items-center gap-1",children:["Generate one in Cloze → Settings → API Keys.",e.jsxs("a",{href:"https://app.cloze.com/app/#/settings/apikeys",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-0.5 text-primary hover:underline",children:["Open ",e.jsx(tr,{className:"h-3 w-3"})]})]})]}),e.jsx(B,{onClick:()=>E.mutate(),disabled:!t.trim()||!r.trim()||E.isPending,children:E.isPending?"Connecting…":"Connect Cloze"})]})})]})}function WXs({segments:s}){var h;const[t,n]=N.useState(!0),[r,a]=N.useState(null),[i,l]=N.useState(null);if(N.useEffect(()=>{(async()=>{try{const{data:p,error:f}=await q.functions.invoke("cloze-sync",{body:{action:"preview"}});if(f)throw f;if(p!=null&&p.error)throw new Error(p.error);a(p)}catch(p){l(p.message||"Could not load preview")}finally{n(!1)}})()},[]),t)return e.jsx("span",{className:"text-sm",children:"Calculating…"});if(i)return e.jsx("span",{className:"text-sm text-destructive",children:i});const o=new Map((s||[]).map(p=>[p.id,p.name])),c=r.total_incoming??0,d=r.already_synced??0,u=Math.max(0,c-d);return e.jsxs("div",{className:"space-y-3 text-sm text-foreground",children:[e.jsxs("div",{className:"rounded-md border p-3 space-y-1",children:[e.jsxs("div",{className:"flex justify-between",children:[e.jsxs("span",{children:["Contacts in Cloze (",r.scope==="segments"?"selected segments":"all",")"]}),e.jsx("strong",{children:c.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between text-muted-foreground",children:[e.jsx("span",{children:"Already linked to Cloze in your CRM"}),e.jsx("span",{children:d.toLocaleString()})]}),e.jsxs("div",{className:"flex justify-between",children:[e.jsx("span",{children:"Estimated new contacts"}),e.jsxs("strong",{children:["~",u.toLocaleString()]})]})]}),r.scope==="segments"&&((h=r.segment_counts)==null?void 0:h.length)>0&&e.jsx("div",{className:"rounded-md border p-3 space-y-1 max-h-40 overflow-auto",children:r.segment_counts.map(p=>e.jsxs("div",{className:"flex justify-between text-xs",children:[e.jsx("span",{children:o.get(p.id)||p.id}),e.jsx("span",{className:"text-muted-foreground",children:p.total})]},p.id))}),e.jsx("p",{className:"text-xs text-muted-foreground",children:r.note})]})}function KXs(){const s=Kt(),[t,n]=N.useState(""),[r,a]=N.useState(!1),[i,l]=N.useState(0),[o,c]=N.useState(null),{data:d,isLoading:u}=dt({queryKey:["boomtown-status"],queryFn:async()=>{const{data:_,error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"status"}});if(v)throw v;return _}}),h=yt({mutationFn:async _=>{const{data:v,error:j}=await q.functions.invoke("boomtown-sync",{body:{action:"save_token",api_key:_}});if(j)throw j;if(v!=null&&v.error)throw new Error(v.error);return v},onSuccess:()=>{ae.success("Connected to Boomtown"),n(""),s.invalidateQueries({queryKey:["boomtown-status"]})},onError:_=>ae.error(_.message)}),p=yt({mutationFn:async()=>{const{error:_}=await q.functions.invoke("boomtown-sync",{body:{action:"disconnect"}});if(_)throw _},onSuccess:()=>{ae.success("Disconnected"),s.invalidateQueries({queryKey:["boomtown-status"]})}}),f=yt({mutationFn:async _=>{const{error:v}=await q.functions.invoke("boomtown-sync",{body:{action:"set_direction",sync_direction:_}});if(v)throw v},onSuccess:()=>s.invalidateQueries({queryKey:["boomtown-status"]})}),y=async()=>{a(!0),l(0),c("Pulling from Boomtown…");let _=0,v=0,j=0,w=0;try{for(;;){const{data:O,error:D}=await q.functions.invoke("boomtown-sync",{body:{action:"sync",offset:_}});if(D)throw D;if(O!=null&&O.error)throw new Error(O.error);v+=O.chunk_created||0,j+=O.chunk_updated||0,w+=O.chunk_skipped||0,_=O.next_offset;const I=O.total?Math.min(100,Math.round(_/O.total*100)):100;if(l(I),c(`Pulling · ${_} / ${O.total||"?"}`),O.done)break;await new Promise(F=>setTimeout(F,400))}let S=0,A=0;if((d==null?void 0:d.sync_direction)==="bidirectional"){let O=0;for(l(0),c("Pushing to Boomtown…");;){const{data:D,error:I}=await q.functions.invoke("boomtown-sync",{body:{action:"push",offset:O}});if(I)throw I;if(D!=null&&D.error)throw new Error(D.error);S+=D.chunk_pushed||0,A+=D.chunk_failed||0,O=D.next_offset;const F=D.total?Math.min(100,Math.round(O/D.total*100)):100;if(l(F),c(`Pushing · ${O} / ${D.total||"?"}`),D.done)break;await new Promise(z=>setTimeout(z,400))}}const E=S||A?` · pushed ${S}${A?`, ${A} failed`:""}`:"";ae.success(`Sync complete · ${v} new, ${j} updated${w?`, ${w} skipped`:""}${E}`),s.invalidateQueries({queryKey:["boomtown-status"]})}catch(S){ae.error(S.message||"Sync failed")}finally{a(!1),setTimeout(()=>{l(0),c(null)},2500)}};return e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx("div",{className:"flex items-start justify-between gap-3",children:e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Y2,{className:"h-5 w-5 text-primary"}),"Boomtown",(d==null?void 0:d.connected)&&e.jsxs(Ue,{variant:"default",className:"ml-1",children:[e.jsx(Pi,{className:"h-3 w-3 mr-1"})," Connected"]})]}),e.jsx(Vn,{children:"Sync your Boomtown contacts into Agent OS."})]})})}),e.jsx(Ee,{className:"space-y-4",children:u?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading…"}):d!=null&&d.connected?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3 text-sm",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Last sync"}),e.jsx("p",{className:"font-medium",children:d.last_sync_at?new Date(d.last_sync_at).toLocaleString():"Never"})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-muted-foreground",children:"Boomtown contacts"}),e.jsx("p",{className:"font-medium",children:d.boomtown_contact_count??"—"})]})]}),d.last_sync_status==="error"&&e.jsx("p",{className:"text-sm text-destructive",children:d.last_sync_message}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border px-3 py-2",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Two-way sync"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Off = pull from Boomtown only. On = also push new Agent OS contacts to Boomtown."})]}),e.jsx(jn,{checked:d.sync_direction==="bidirectional",onCheckedChange:_=>f.mutate(_?"bidirectional":"pull_only"),disabled:r||f.isPending})]}),o&&e.jsxs("div",{className:"space-y-1",children:[e.jsx(fi,{value:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:o})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{onClick:y,disabled:r,children:[e.jsx(Ei,{className:`h-4 w-4 mr-2 ${r?"animate-spin":""}`}),r?"Syncing…":"Sync Now"]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsxs(B,{variant:"outline",disabled:r,children:[e.jsx(_n,{className:"h-4 w-4 mr-2"})," Disconnect"]})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Boomtown?"}),e.jsx(Mo,{children:"Your API key will be removed. Synced contacts stay in Agent OS."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>p.mutate(),children:"Disconnect"})]})]})]})]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{htmlFor:"boomtown-key",children:"Boomtown API Key"}),e.jsx(ye,{id:"boomtown-key",type:"password",placeholder:"Paste your Boomtown Ambassador API key",value:t,onChange:_=>n(_.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Requires a Boomtown Ambassador/Partner API key with contact access."})]}),e.jsxs("div",{className:"rounded-lg border bg-muted/40 p-3 space-y-2",children:[e.jsx("p",{className:"text-sm font-medium",children:"How to get your API key"}),e.jsxs("ol",{className:"text-xs text-muted-foreground space-y-1 list-decimal list-inside",children:[e.jsx("li",{children:"Log in to Boomtown as an admin or manager."}),e.jsxs("li",{children:["Go to ",e.jsx("strong",{children:"Settings → Integrations → API Keys"}),"."]}),e.jsxs("li",{children:["Generate a key with ",e.jsx("strong",{children:"Contact read/write"})," scope."]}),e.jsx("li",{children:"Copy the key and paste it above, then click Connect."})]}),e.jsxs("a",{href:"https://backoffice.boomtownroi.com/#/settings/integrations",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs text-primary hover:underline",children:["Open Boomtown settings ",e.jsx(tr,{className:"h-3 w-3"})]})]}),e.jsx(B,{onClick:()=>h.mutate(t),disabled:!t.trim()||h.isPending,children:h.isPending?"Connecting…":"Connect"})]})})]})}function y2t(){const s=Ln(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState("Test from ReLevelUp"),[o,c]=N.useState(!1),{data:d,isLoading:u}=dt({queryKey:["ses-config"],queryFn:async()=>{const{data:{session:f}}=await q.auth.getSession();if(!f)throw new Error("Not authenticated");return(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f.access_token}`},body:JSON.stringify({action:"check_config"})})).json()}}),h=async()=>{if(!t||!r){ae.error("Please fill in From and To email addresses");return}c(!0);try{const{data:{session:f}}=await q.auth.getSession();if(!f)throw new Error("Not authenticated");const _=await(await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-send-campaign",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${f.access_token}`},body:JSON.stringify({action:"test_send",to:t,from_email:r,subject:i,body_html:"

Test Email

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

If you received this, SES is configured correctly! 🎉

"})})).json();_.success?ae.success(`Test email sent! Message ID: ${_.messageId}`):ae.error(_.error||"Failed to send test email")}catch(f){ae.error(f.message||"Failed to send test email")}finally{c(!1)}},p=(d==null?void 0:d.configured)===!0;return e.jsxs(fe,{children:[e.jsx(It,{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(Gs,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:"Amazon SES — Mass Email"}),e.jsx(Vn,{children:"Send bulk email campaigns via Amazon SES"})]})]}),e.jsx(Ue,{variant:p?"default":"secondary",children:u?"Checking...":p?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Pi,{className:"h-3 w-3"})," Connected"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Bi,{className:"h-3 w-3"})," Not Configured"]})})]})}),p&&e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-lg border p-4 space-y-3",children:[e.jsx("h4",{className:"font-medium text-sm",children:"Send Test Email"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:'Verify your SES setup by sending a test email. The "From" address must be verified in SES or belong to a verified domain.'}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"From Email"}),e.jsx(ye,{placeholder:"notifications@mail.relevelup.com",value:r,onChange:f=>a(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"To Email"}),e.jsx(ye,{placeholder:"your@email.com",value:t,onChange:f=>n(f.target.value),className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"Subject"}),e.jsx(ye,{value:i,onChange:f=>l(f.target.value),className:"text-sm"})]})]}),e.jsxs(B,{onClick:h,disabled:o,size:"sm",children:[o?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Send Test"]})]}),e.jsxs(B,{onClick:()=>s("/admin/email-campaigns"),className:"w-full",children:[e.jsx(zd,{className:"h-4 w-4 mr-2"})," Launch Campaign Composer"]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-1",children:[e.jsxs("p",{children:[e.jsx("strong",{children:"Region:"})," ",d==null?void 0:d.region]}),e.jsxs("p",{children:[e.jsx("strong",{children:"Domain:"})," send.relevelup.com (verified)"]})]})]}),!p&&!u&&e.jsx(Ee,{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:["AWS SES credentials are not configured. Add ",e.jsx("code",{children:"AWS_SES_ACCESS_KEY_ID"}),", ",e.jsx("code",{children:"AWS_SES_SECRET_ACCESS_KEY"}),", and ",e.jsx("code",{children:"AWS_SES_REGION"})," as secrets to enable."]})})]})}async function NNe(s){const{data:{session:t}}=await q.auth.getSession();if(!t)throw new Error("Not authenticated");const n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function YXs({status:s}){return s==="verified"?e.jsxs(Ue,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Ue,{variant:"secondary",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Ue,{variant:"destructive",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Ue,{variant:"outline",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"})," Not started"]})}function v2t({brokerageId:s,onVerifiedSelect:t}){const n=Kt(),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),{data:f,isLoading:y}=dt({queryKey:["brokerage-verified-senders",s],queryFn:async()=>{const{data:w,error:S}=await q.from("brokerage_verified_senders").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(S)throw S;return w||[]}}),_=yt({mutationFn:async()=>NNe({action:"request_verification",brokerage_id:s,email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:w=>ae.error(w.message)}),v=async w=>{var S,A;u(w.id);try{const E=await NNe({action:"check_status",sender_id:w.id});n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),((S=E.sender)==null?void 0:S.status)==="verified"?ae.success(`${w.email} is verified! 🎉`):ae.info(`Status: ${((A=E.sender)==null?void 0:A.status)||"unknown"}`)}catch(E){ae.error(E.message)}finally{u(null)}},j=yt({mutationFn:async w=>NNe({action:"delete",sender_id:w}),onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-verified-senders",s]}),ae.success("Sender removed"),p(null)},onError:w=>ae.error(w.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."})]}),y?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(w=>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(Gs,{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:w.email}),e.jsx(YXs,{status:w.status})]}),w.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',w.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[w.status==="verified"&&t&&e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(w.email),children:"Use"}),w.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>v(w),disabled:d===w.id,title:"Refresh status from AWS",children:d===w.id?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Ei,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(w),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})]},w.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(ne,{className:"text-xs",children:"Email Address *"}),e.jsx(ye,{type:"email",value:r,onChange:w=>a(w.target.value),placeholder:"broker@yourbrokerage.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ye,{value:i,onChange:w=>l(w.target.value),placeholder:"John at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask AWS to send a verification email to this address. The owner must click the link before this sender can be used."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>_.mutate(),disabled:!r.trim()||_.isPending,children:[_.isPending?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Oo,{open:!!h,onOpenChange:w=>!w&&p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove this sender?"}),e.jsxs(Mo,{children:['"',h==null?void 0:h.email,`" will be removed from your verified senders and from Amazon SES. You'd need to verify it again to use it.`]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>h&&j.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}async function kNe(s){const{data:{session:t}}=await q.auth.getSession();if(!t)throw new Error("Not authenticated");const n=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/ses-verify-sender",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${t.access_token}`},body:JSON.stringify(s)}),r=await n.json();if(!n.ok)throw new Error(r.error||"Request failed");return r}function ZXs({status:s}){return s==="verified"?e.jsxs(Ue,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-green-500/20",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"})," Verified"]}):s==="pending"?e.jsxs(Ue,{variant:"secondary",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"})," Pending — check inbox"]}):s==="failed"||s==="temporary_failure"?e.jsxs(Ue,{variant:"destructive",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"})," Failed"]}):e.jsxs(Ue,{variant:"outline",children:[e.jsx(Bi,{className:"h-3 w-3 mr-1"})," Not started"]})}function QXs({userId:s,onVerifiedSelect:t}){const n=Kt(),[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(null),{data:f,isLoading:y}=dt({queryKey:["user-verified-senders",s],queryFn:async()=>{const{data:w,error:S}=await q.from("user_verified_senders").select("*").eq("user_id",s).order("created_at",{ascending:!1});if(S)throw S;return w||[]}}),_=yt({mutationFn:async()=>kNe({action:"request_verification",scope:"user",email:r,display_name:i||void 0}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Verification email sent",{description:`Check ${r} and click the AWS verification link.`}),a(""),l(""),c(!1)},onError:w=>ae.error(w.message)}),v=async w=>{var S,A;u(w.id);try{const E=await kNe({action:"check_status",sender_id:w.id});n.invalidateQueries({queryKey:["user-verified-senders",s]}),((S=E.sender)==null?void 0:S.status)==="verified"?ae.success(`${w.email} is verified! 🎉`):ae.info(`Status: ${((A=E.sender)==null?void 0:A.status)||"unknown"}`)}catch(E){ae.error(E.message)}finally{u(null)}},j=yt({mutationFn:async w=>kNe({action:"delete",sender_id:w}),onSuccess:()=>{n.invalidateQueries({queryKey:["user-verified-senders",s]}),ae.success("Sender removed"),p(null)},onError:w=>ae.error(w.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."]})]}),y?e.jsx("div",{className:"text-xs text-muted-foreground py-3",children:"Loading…"}):f&&f.length>0?e.jsx("div",{className:"space-y-2",children:f.map(w=>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(Gs,{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:w.email}),e.jsx(ZXs,{status:w.status})]}),w.display_name&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:['"',w.display_name,'"']})]})]}),e.jsxs("div",{className:"flex items-center gap-1 shrink-0",children:[w.status==="verified"&&t&&e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(w.email),children:"Use"}),w.status!=="verified"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>v(w),disabled:d===w.id,title:"Refresh status from AWS",children:d===w.id?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(Ei,{className:"h-4 w-4"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>p(w),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})]},w.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(ne,{className:"text-xs",children:"Email Address *"}),e.jsx(ye,{type:"email",value:r,onChange:w=>a(w.target.value),placeholder:"you@yourdomain.com",className:"text-sm"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"Display Name (optional)"}),e.jsx(ye,{value:i,onChange:w=>l(w.target.value),placeholder:"Jane at Acme Realty",className:"text-sm"})]})]}),e.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:"We'll ask Amazon to send a verification email to this address. You must click the link before this sender can be used in a campaign."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>_.mutate(),disabled:!r.trim()||_.isPending,children:[_.isPending?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Send Verification Email"]}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{c(!1),a(""),l("")},children:"Cancel"})]})]}):e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Sender Address"]}),e.jsx(Oo,{open:!!h,onOpenChange:w=>!w&&p(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Remove this sender?"}),e.jsxs(Mo,{children:['"',h==null?void 0:h.email,`" will be removed from your verified senders and from Amazon. You'd need to verify it again to use it.`]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>h&&j.mutate(h.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Remove"})]})]})})]})}function XXs(){var A,E,O,D,I;const{user:s,isBrokerageManager:t,isAdmin:n,managedBrokerages:r,selectedBrokerageId:a}=vs(),i=a||((A=r==null?void 0:r[0])==null?void 0:A.id)||null,l=(t||n)&&!!i,o=Kt(),[c,d]=N.useState(!1),[u,h]=N.useState(""),[p,f]=N.useState(""),{data:y}=dt({queryKey:["mass-email-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:z}=await q.from("mass_email_settings").select("*").eq("user_id",s.id).maybeSingle();if(z)throw z;return F}}),{data:_}=dt({queryKey:["agent-profile-email",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:F,error:z}=await q.from("profiles").select("email, name").eq("id",s.id).single();if(z)throw z;return F}}),v=((E=y==null?void 0:y.reply_to_email)==null?void 0:E.trim())||((O=_==null?void 0:_.email)==null?void 0:O.trim())||"",j=((D=y==null?void 0:y.display_name)==null?void 0:D.trim())||((I=_==null?void 0:_.name)==null?void 0:I.trim())||"";N.useEffect(()=>{c||(h(v),f(j))},[c,v,j]);const w=yt({mutationFn:async()=>{if(!s||!u.trim())throw new Error("Please enter a reply-to email");const F={reply_to_email:u.trim(),display_name:p.trim()||null,updated_at:new Date().toISOString()};if(y){const{error:z}=await q.from("mass_email_settings").update(F).eq("user_id",s.id);if(z)throw z}else{const{error:z}=await q.from("mass_email_settings").insert({user_id:s.id,...F});if(z)throw z}},onSuccess:()=>{o.invalidateQueries({queryKey:["mass-email-settings",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-ready",s==null?void 0:s.id]}),o.invalidateQueries({queryKey:["mass-email-settings-check",s==null?void 0:s.id]}),ae.success("Reply-to email saved!"),d(!1)},onError:F=>ae.error(F.message)}),S=!!v;return e.jsxs(fe,{children:[e.jsx(It,{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(lr,{className:"h-5 w-5 text-orange-600"})}),e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:["Mass Email",S?e.jsxs(Ue,{variant:"default",className:"text-xs bg-green-600",children:[e.jsx(Pi,{className:"h-3 w-3 mr-1"})," Set Up"]}):e.jsx(Ue,{variant:"secondary",className:"text-xs",children:"Setup Required"})]}),e.jsx(Vn,{children:"Set the email address where replies from your campaigns will be sent. If you haven't customized it yet, we'll use your profile email."})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[S&&!c?e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:j||"No display name"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:v})]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>d(!0),children:[e.jsx(ya,{className:"h-3 w-3 mr-1"})," Edit"]})]}):e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"Display Name"}),e.jsx(ye,{placeholder:"e.g. 🏡 Karen Hall",value:p,onChange:F=>f(F.target.value)}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"How your name appears in the recipient's inbox"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"Reply-To Email *"}),e.jsx(ye,{type:"email",placeholder:"your@email.com",value:u,onChange:F=>h(F.target.value)})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{size:"sm",onClick:()=>w.mutate(),disabled:w.isPending||!u.trim(),children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save"]}),c&&e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{d(!1),h(v),f(j)},children:[e.jsx($n,{className:"h-4 w-4 mr-1"})," Cancel"]})]})]}),s&&e.jsxs(e.Fragment,{children:[e.jsx(al,{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(eg,{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(QXs,{userId:s.id,onVerifiedSelect:F=>{h(F),d(!0)}})]})]}),l&&e.jsxs(e.Fragment,{children:[e.jsx(al,{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(eg,{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(v2t,{brokerageId:i})]})]})]})]})}function JXs(){const s=Ln(),{isAdmin:t}=vs(),n=Kt(),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(!1),{data:d,isLoading:u}=dt({queryKey:["gmail-integration"],queryFn:async()=>{const{data:E,error:O}=await q.from("gmail_integrations").select("*").maybeSingle();if(O)throw O;return E}}),{data:h}=dt({queryKey:["social-accounts"],queryFn:async()=>{const{data:{user:E}}=await q.auth.getUser();if(!E)return[];const{data:O,error:D}=await q.from("social_accounts").select("*").eq("user_id",E.id).order("created_at",{ascending:!1});if(D)throw D;return O}}),p=async()=>{a(!0);try{const{data:E,error:O}=await q.functions.invoke("gmail-oauth",{body:{action:"get_auth_url"}});if(O)throw O;if(E!=null&&E.authUrl)window.location.href=E.authUrl;else throw new Error("Failed to get authorization URL")}catch(E){console.error("Gmail OAuth error:",E),ae.error("Failed to start Gmail connection"),a(!1)}},f=async E=>{l(!0);try{const{data:O,error:D}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:E}});if(D)throw D;if(O!=null&&O.authUrl)window.location.href=O.authUrl;else throw new Error("Failed to get authorization URL")}catch(O){console.error("Meta OAuth error:",O),ae.error("Failed to start connection. Make sure Meta App credentials are configured."),l(!1)}},y=async()=>{c(!0);try{const{data:E,error:O}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(O)throw O;if(E!=null&&E.authUrl)window.location.href=E.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(E){console.error("LinkedIn OAuth error:",E),ae.error("Failed to start LinkedIn connection. Please try again."),c(!1)}},_=yt({mutationFn:async E=>{const{error:O}=await q.from("gmail_integrations").delete().eq("id",E);if(O)throw O},onSuccess:()=>{n.invalidateQueries({queryKey:["gmail-integration"]}),ae.success("Gmail disconnected")},onError:()=>{ae.error("Failed to disconnect Gmail")}}),v=yt({mutationFn:async E=>{const{error:O}=await q.from("social_accounts").delete().eq("id",E);if(O)throw O},onSuccess:()=>{n.invalidateQueries({queryKey:["social-accounts"]}),ae.success("Account disconnected")},onError:()=>{ae.error("Failed to disconnect account")}}),j=!!(d!=null&&d.is_active),w=(h==null?void 0:h.filter(E=>E.platform==="facebook"))||[],S=(h==null?void 0:h.filter(E=>E.platform==="instagram"))||[],A=(h==null?void 0:h.filter(E=>E.platform==="linkedin"))||[];return e.jsx(Cs,{children:e.jsxs("div",{className:"max-w-3xl mx-auto space-y-6 animate-fade-in",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold tracking-tight",children:"Integrations"}),e.jsx("p",{className:"text-muted-foreground",children:"Connect third-party services to supercharge your Agent OS workflow."})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-primary/10 flex items-center justify-center",children:e.jsx(US,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:"ChatGPT"}),e.jsx(Vn,{children:"Connect ChatGPT to LevelUp so it can use LevelUp tools on your behalf."})]})]})}),e.jsx(Ee,{children:e.jsxs(B,{variant:"outline",onClick:()=>s("/connect-chatgpt"),children:["View connection instructions ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{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(Gs,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:["Gmail",j&&e.jsx(Ue,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Vn,{children:"Send emails directly from your contact pages and auto-log them as touchpoints."})]})]})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Pi,{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(Pi,{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(Pi,{className:"h-4 w-4 mt-0.5 text-green-500 shrink-0"}),e.jsx("span",{children:"Quick compose from any contact detail page"})]}),j?e.jsxs("div",{className:"flex items-center justify-between mt-4 p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:d.gmail_email}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Gmail account"})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Gmail?"}),e.jsx(Mo,{children:"This will remove your Gmail connection. You'll need to reconnect to send emails."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>_.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:p,disabled:r||u,children:[r?e.jsx(Ei,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Gs,{className:"h-4 w-4 mr-2"}),"Connect Gmail",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{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(Mh,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:["Facebook",w.length>0&&e.jsx(Ue,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Vn,{children:"Connect Facebook Pages to post content and reach your audience."})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[w.length>0&&e.jsx("div",{className:"space-y-2",children:w.map(E=>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(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:E.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(Mh,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:E.page_name||E.platform_username||"Facebook Page"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Facebook Page"})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Facebook?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>v.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(B,{onClick:()=>f("facebook"),disabled:i,variant:"outline",className:"gap-2",children:[i?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),"Connect Facebook Page"]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{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(ou,{className:"h-5 w-5 text-pink-600"})}),e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:["Instagram",S.length>0&&e.jsx(Ue,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Vn,{children:"Connect an Instagram Business or Creator account to schedule and publish posts. Personal accounts are not supported by Meta's API."})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[S.length>0&&e.jsx("div",{className:"space-y-2",children:S.map(E=>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(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:E.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(ou,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium text-sm",children:["@",E.platform_username||"Instagram Account"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected Instagram account"})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Instagram?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>v.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(B,{onClick:()=>f("instagram"),disabled:i,variant:"outline",className:"gap-2",children:[i?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Uses Instagram's professional login for Business or Creator accounts. Personal accounts cannot post via Meta's API — convert your account in the Instagram app (Profile → Menu → Settings → Account type → Switch to Professional)."})]})]}),e.jsxs(fe,{children:[e.jsx(It,{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(xf,{className:"h-5 w-5 text-blue-700"})}),e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:["LinkedIn",A.length>0&&e.jsx(Ue,{variant:"default",className:"text-xs bg-green-600",children:"Connected"})]}),e.jsx(Vn,{children:"Connect your LinkedIn profile to share content and grow your professional network."})]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[A.length>0&&e.jsx("div",{className:"space-y-2",children:A.map(E=>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(Jr,{className:"h-8 w-8",children:[e.jsx(ti,{src:E.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(xf,{className:"h-4 w-4"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:E.platform_username||"LinkedIn Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Connected LinkedIn profile"})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect LinkedIn?"}),e.jsx(Mo,{children:"This will remove your LinkedIn connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>v.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}),e.jsxs(B,{onClick:y,disabled:o,variant:"outline",className:"gap-2",children:[o?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),"Connect LinkedIn"]})]})]}),e.jsx(VXs,{}),e.jsx(HXs,{}),e.jsx(GXs,{}),e.jsx(KXs,{}),e.jsx(XXs,{}),t&&e.jsx(y2t,{})]})})}const eJs="https://chromewebstore.google.com/detail/levelup-companion/lppakdeaencigddecnkcifdcemlfpkkk";function tJs(){const[s,t]=N.useState(null),[n,r]=N.useState(!1),[a,i]=N.useState(0),[l,o]=N.useState(!1),c="/levelup-extension.zip",d="https://tile-portal.lovable.app/levelup-extension.zip",u=window.location.hostname.startsWith("id-preview--"),h=async v=>{const j=new Uint8Array(await v.slice(0,4).arrayBuffer());return j[0]===80&&j[1]===75&&j[2]===3&&j[3]===4||j[0]===80&&j[1]===75&&j[2]===5&&j[3]===6||j[0]===80&&j[1]===75&&j[2]===7&&j[3]===8},p=v=>{const j=document.createElement("a");j.href=v,j.download="levelup-extension.zip",j.rel="noopener noreferrer",j.target="_blank",document.body.appendChild(j),j.click(),j.remove()},f=async()=>{o(!0);try{if(u){p(`${d}?v=${Date.now()}`);return}const v=await fetch(`${c}?v=${Date.now()}`,{cache:"no-store"});if(!v.ok)throw new Error(`Download failed (${v.status})`);const j=await v.blob();if(!await h(j)){p(`${d}?v=${Date.now()}`);return}const w=new Blob([j],{type:"application/zip"}),S=URL.createObjectURL(w),A=document.createElement("a");A.href=S,A.download="levelup-extension.zip",document.body.appendChild(A),A.click(),A.remove(),setTimeout(()=>URL.revokeObjectURL(S),1e3)}catch(v){ae.error(v.message||"Download failed")}finally{o(!1)}},y=async()=>{r(!0);try{await q.auth.refreshSession();const{data:v}=await q.auth.getSession();if(!v.session){ae.error("Your session has expired. Please sign in again.");return}const{data:j,error:w}=await q.functions.invoke("extension-pair-start",{headers:{Authorization:`Bearer ${v.session.access_token}`}});if(w)throw w;t(j.code),i(j.expires_in||300);const S=setInterval(()=>{i(A=>A<=1?(clearInterval(S),t(null),0):A-1)},1e3)}catch(v){console.error("generateCode error",v),ae.error("We couldn't generate a pairing code",{description:"Please refresh the page and try again. If it still fails, sign out and sign back in, then click Generate pairing code.",duration:8e3})}finally{r(!1)}},_=()=>{s&&(navigator.clipboard.writeText(s),ae.success("Copied"))};return e.jsx(Cs,{title:"Browser Extension",children:e.jsxs("div",{className:"container max-w-3xl mx-auto py-8 px-4 space-y-6",children:[e.jsxs(Zo,{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(yA,{className:"w-6 h-6"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Browser Extension"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Add contacts and import listings from anywhere on the web."})]})]})}),e.jsxs(fe,{className:"p-6 space-y-4 border-2 border-primary/20",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"1"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Install from the Chrome Web Store"})]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"Quick-add contacts from any webpage with one click or right-click"}),e.jsx("li",{children:"Import listings from Zillow, Realtor.com, and Redfin as drafts"}),e.jsx("li",{children:'"Add to LevelUp" button on Gmail threads and LinkedIn profiles'}),e.jsx("li",{children:"Toolbar launcher with shortcuts to Dashboard, ReelFlow, Card Studio, and more"})]}),e.jsxs(B,{size:"lg",className:"w-full",onClick:()=>window.open(eJs,"_blank","noopener,noreferrer"),children:[e.jsx(yA,{className:"w-4 h-4 mr-2"}),"Add to Chrome",e.jsx(tr,{className:"w-3.5 h-3.5 ml-2 opacity-70"})]}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Works in Chrome, Edge, Brave, and Arc. Free to install."})]}),e.jsxs(fe,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"w-6 h-6 rounded-full bg-primary text-primary-foreground flex items-center justify-center text-xs font-bold",children:"2"}),e.jsx("h2",{className:"text-lg font-semibold",children:"Pair the extension"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Generate a one-time pairing code, then enter it inside the extension popup."}),s?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"bg-muted rounded-xl p-6 text-center",children:[e.jsx("div",{className:"text-4xl font-mono font-bold tracking-[0.4em] text-primary",children:s}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-3",children:["Expires in ",Math.floor(a/60),":",String(a%60).padStart(2,"0")]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{onClick:_,variant:"outline",className:"flex-1",children:[e.jsx(Zr,{className:"w-4 h-4 mr-2"})," Copy"]}),e.jsxs(B,{onClick:y,variant:"outline",className:"flex-1",children:[e.jsx(Ei,{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(Lr,{className:"w-4 h-4 mt-0.5 text-primary"}),e.jsx("span",{children:"Click the LevelUp icon in your browser toolbar and paste this code. You only need to do this once per browser."})]})]}):e.jsx(B,{onClick:y,disabled:n,size:"lg",className:"w-full",children:n?e.jsxs(e.Fragment,{children:[e.jsx(Ei,{className:"w-4 h-4 mr-2 animate-spin"}),"Generating…"]}):"Generate pairing code"})]}),e.jsxs(fe,{className:"p-6 space-y-4 bg-muted/30 border-dashed",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ec,{className:"w-5 h-5 text-muted-foreground"}),e.jsx("h2",{className:"text-base font-semibold text-muted-foreground",children:"Manual install (advanced)"})]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you prefer to load the extension unpacked, or the Web Store is unavailable, download the ZIP below."}),e.jsxs("ol",{className:"text-sm space-y-2 list-decimal list-inside text-muted-foreground",children:[e.jsx("li",{children:e.jsx(B,{variant:"link",className:"h-auto p-0 text-sm",onClick:f,disabled:l,children:"Download the extension ZIP"})}),e.jsx("li",{children:"Unzip the downloaded file"}),e.jsxs("li",{children:["Open"," ",e.jsx("code",{className:"px-1.5 py-0.5 rounded bg-muted text-foreground",children:"chrome://extensions"})," ","in Chrome, Edge, Brave, or Arc"]}),e.jsxs("li",{children:["Turn on ",e.jsx("b",{className:"text-foreground",children:"Developer mode"})," (top-right toggle)"]}),e.jsxs("li",{children:["Click ",e.jsx("b",{className:"text-foreground",children:"Load unpacked"})," and pick the unzipped folder"]}),e.jsx("li",{children:"Pin the LevelUp icon to your toolbar"})]})]})]})})}function sJs(){const[s]=xl(),t=Ln(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your Gmail account...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:p}=await q.functions.invoke("gmail-oauth",{body:{action:"exchange_code",code:o,state:u}});if(p)throw p;if(h!=null&&h.success)r("success"),i(h.message||"Gmail connected successfully!"),ae.success("Gmail connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Gmail OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Gmail"),ae.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{className:"text-center",children:[n==="loading"&&e.jsx(rs,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Pi,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Uc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Rt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"Back to Integrations":"Try Again"})})]})})}function nJs(){const s=Ln();return N.useEffect(()=>{const t=setTimeout(()=>{s("/mission-control/integrations",{replace:!0})},1500);return()=>clearTimeout(t)},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"h-10 w-10 animate-spin rounded-full border-4 border-primary border-t-transparent mx-auto"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Finishing Canva connection…"})]})})}function rJs(){const[s]=xl(),t=Ln(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing your connection...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/mission-control/integrations/meta/callback"}});if(p&&p.success===!1)throw new Error(p.error||"Failed to connect accounts");if(f){let y=f.message||"Failed to connect accounts";try{const _=f.context;if(_&&typeof _.json=="function"){const v=await _.json();v!=null&&v.error&&(y=v.error)}}catch{}throw new Error(y)}if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{className:"text-center",children:[n==="loading"&&e.jsx(rs,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Pi,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Uc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Rt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Integrations":"Try Again"})})]})})}const b2t=new Date().getFullYear(),aJs=Array.from({length:5},(s,t)=>b2t-t);function iJs(){const[s,t]=N.useState(b2t),n=Ln(),{data:r,isLoading:a}=vrs();return a?e.jsx(Cs,{title:"Scorecard Admin",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(i=>e.jsx(Ws,{className:"h-24"},i))}),e.jsx(Ws,{className:"h-96"})]})}):e.jsx(Cs,{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(us,{value:String(s),onValueChange:i=>t(Number(i)),children:[e.jsx(ls,{className:"w-[120px]",children:e.jsx(hs,{})}),e.jsx(cs,{children:aJs.map(i=>e.jsx(Ze,{value:String(i),children:i},i))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(An,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Agents Tracking"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(_o,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Agents"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(r==null?void 0:r.length)||0}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with transactions"})]})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Agents with Scorecards"}),e.jsx(Vn,{children:"Click to view individual agent scorecards"})]}),e.jsx(Ee,{children:!r||r.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(_o,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents have added transactions yet"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:r.map(i=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:i.name}),e.jsx(ht,{className:"text-muted-foreground",children:i.email}),e.jsx(ht,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n(`/admin/scorecard/${i.id}`),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"View Scorecard"]})})]},i.id))})]})})]})]})})}const _2t=new Date().getFullYear(),oJs=Array.from({length:10},(s,t)=>_2t-t);function YQe(){var _;const{userId:s}=bi(),t=Ln(),r=Xl().pathname.startsWith("/mission-control"),[a,i]=N.useState(_2t),{data:l,isLoading:o}=dt({queryKey:["agent-profile",s],queryFn:async()=>{const{data:v,error:j}=await q.from("profiles").select("id, name, email").eq("id",s).single();if(j)throw j;return v},enabled:!!s}),{data:c,isLoading:d}=s6e(a,s),{yearStats:u,lifetimeStats:h,isLoading:p,showCommission:f}=qmt(a,s),{data:y}=Umt(a,s);return o?e.jsx(Cs,{title:"Agent Scorecard",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-4 gap-4",children:[1,2,3,4].map(v=>e.jsx(Ws,{className:"h-24"},v))})]})}):e.jsx(Cs,{title:`${l==null?void 0:l.name}'s Scorecard`,children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center sm:justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t(r?"/mission-control/scorecard":"/admin/scorecard"),children:e.jsx(qr,{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(us,{value:String(a),onValueChange:v=>i(Number(v)),children:[e.jsx(ls,{className:"w-[120px]",children:e.jsx(hs,{})}),e.jsx(cs,{children:oJs.map(v=>e.jsx(Ze,{value:String(v),children:v},v))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 lg:grid-cols-5 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Or,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Transactions"})]}),e.jsx("p",{className:"text-2xl font-bold",children:u.totalTransactions}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[h.totalTransactions," lifetime"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(An,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Buyer/Seller"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[u.buyerCount,"/",u.sellerCount]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Yl,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Volume"})]}),e.jsx("p",{className:"text-2xl font-bold",children:jc(u.totalVolume,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(go,{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:jc(u.averagePrice,!0)})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(fc,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Top Source"})]}),e.jsx("p",{className:"text-lg font-bold truncate",children:((_=u.topLeadSource)==null?void 0:_.name)||"-"})]})})]}),y&&e.jsx(Ejt,{goals:y,stats:u,year:a,showCommission:f}),e.jsxs(Fr,{defaultValue:"transactions",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"transactions",children:"Transactions"}),e.jsx(Zt,{value:"charts",children:"Charts"}),e.jsxs(Zt,{value:"map",children:[e.jsx(ka,{className:"h-4 w-4 mr-1"}),"Map"]})]}),e.jsx(is,{value:"transactions",children:e.jsx(WLe,{transactions:c||[],showCommission:f,isLoading:d})}),e.jsx(is,{value:"charts",children:e.jsx(KLe,{stats:u,year:a})}),e.jsx(is,{value:"map",children:e.jsx(YLe,{transactions:c||[],isLoading:d})})]})]})})}function lJs(){const s=Kt(),[t,n]=N.useState(""),[r,a]=N.useState("all"),[i,l]=N.useState(null);wht();const{data:o,refetch:c}=dt({queryKey:["listing-exchange-flag"],queryFn:async()=>{const{data:F}=await q.from("feature_flags").select("enabled").eq("key","listing_exchange_enabled").single();return(F==null?void 0:F.enabled)??!1}}),{data:d,isLoading:u}=dt({queryKey:["admin-listings"],queryFn:async()=>{const{data:F,error:z}=await q.from("listings").select(` *, agent:profiles!listings_agent_id_fkey(id, name, email), photos:listing_photos(id, photo_url, is_primary) `).order("created_at",{ascending:!1});if(z)throw z;return F}}),{data:h}=dt({queryKey:["admin-listing-stats"],queryFn:async()=>{const{data:F}=await q.from("listings").select("id, is_approved, status"),{data:z}=await q.from("listing_shares").select("id"),{data:H}=await q.from("listing_views").select("id"),{count:Z}=await q.from("listing_leads").select("id",{count:"exact",head:!0}),Y=new Date(Date.now()-7*24*60*60*1e3).toISOString(),{count:W}=await q.from("listing_leads").select("id",{count:"exact",head:!0}).gte("created_at",Y);return{total:(F==null?void 0:F.length)||0,pending:(F==null?void 0:F.filter(ee=>!ee.is_approved).length)||0,active:(F==null?void 0:F.filter(ee=>ee.status==="active").length)||0,totalShares:(z==null?void 0:z.length)||0,totalViews:(H==null?void 0:H.length)||0,totalLeads:Z||0,leadsLast7:W||0}}}),{data:p}=dt({queryKey:["admin-listing-lead-counts"],queryFn:async()=>{const F={};let z=0;const H=1e3;for(;;){const{data:Z,error:Y}=await q.from("listing_leads").select("listing_id").range(z,z+H-1);if(Y)throw Y;if(!Z||Z.length===0)break;for(const W of Z)W.listing_id&&(F[W.listing_id]=(F[W.listing_id]||0)+1);if(Z.length{const{data:F,error:z}=await q.from("listing_leads").select("*").eq("listing_id",i.listingId).order("created_at",{ascending:!1});if(z)throw z;return F}}),_=async(F,z,H="submit_url")=>{try{const{data:{session:Z}}=await q.auth.getSession();if(!Z)return;const{data:Y,error:W}=await q.functions.invoke("google-indexing",{body:{action:H,listing_id:F,listing_slug:z}});if(W)throw W;if((Y==null?void 0:Y.configured)===!1)return;Y!=null&&Y.success&&ae.success("Submitted to Google for indexing")}catch(Z){console.error("Google indexing submission failed:",Z)}},v=yt({mutationFn:async()=>{const{data:{session:F}}=await q.auth.getSession();if(!F)throw new Error("Not authenticated");const{data:z,error:H}=await q.functions.invoke("google-indexing",{body:{action:"submit_all"}});if(H)throw H;return z},onSuccess:F=>{if((F==null?void 0:F.configured)===!1){ae.error("Google Indexing API not configured. Add the GOOGLE_INDEXING_SERVICE_ACCOUNT secret.");return}ae.success(`Submitted ${(F==null?void 0:F.succeeded)||0} URLs to Google (${(F==null?void 0:F.failed)||0} failed)`)},onError:F=>{ae.error("Failed to submit to Google"),console.error(F)}}),j=yt({mutationFn:async({id:F,approved:z,slug:H})=>{const{error:Z}=await q.from("listings").update({is_approved:z}).eq("id",F);if(Z)throw Z;return{id:F,approved:z,slug:H}},onSuccess:F=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success(F.approved?"Listing approved":"Listing unapproved"),F.approved?_(F.id,F.slug||null,"submit_url"):_(F.id,F.slug||null,"remove_url")}}),w=yt({mutationFn:async({id:F,featured:z})=>{const{error:H}=await q.from("listings").update({is_featured:z}).eq("id",F);if(H)throw H},onSuccess:(F,{featured:z})=>{s.invalidateQueries({queryKey:["admin-listings"]}),ae.success(z?"Listing featured":"Listing unfeatured")}}),S=yt({mutationFn:async F=>{const{error:z}=await q.from("listings").delete().eq("id",F);if(z)throw z},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-listings"]}),s.invalidateQueries({queryKey:["admin-listing-stats"]}),ae.success("Listing deleted")}}),A=yt({mutationFn:async F=>{const{error:z}=await q.from("feature_flags").update({enabled:F}).eq("key","listing_exchange_enabled");if(z)throw z},onSuccess:()=>{c(),ae.success("Feature flag updated")}}),E=o??!1,O=d==null?void 0:d.filter(F=>{var Z,Y,W,ee;const z=((Z=F.city)==null?void 0:Z.toLowerCase().includes(t.toLowerCase()))||((W=(Y=F.agent)==null?void 0:Y.name)==null?void 0:W.toLowerCase().includes(t.toLowerCase()))||((ee=F.property_address)==null?void 0:ee.toLowerCase().includes(t.toLowerCase())),H=r==="all"||r==="pending"&&!F.is_approved||r==="approved"&&F.is_approved;return z&&H}),D=F=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(F),I=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(Cs,{title:"Listing Exchange Admin",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Exchange"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage community listings"})]}),e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>v.mutate(),disabled:v.isPending,className:"gap-2",children:[v.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lc,{className:"h-4 w-4"}),"Submit All to Google"]}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Feature visible to agents"}),e.jsx(jn,{checked:E,onCheckedChange:F=>A.mutate(F)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Listings"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.total)||0})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(go,{className:"h-4 w-4 text-green-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Active"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.active)||0})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4 text-amber-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Pending Review"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.pending)||0})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Sr,{className:"h-4 w-4 text-blue-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Views"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalViews)||0})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Vl,{className:"h-4 w-4 text-purple-500"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Shares"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalShares)||0})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:(h==null?void 0:h.totalLeads)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[(h==null?void 0:h.leadsLast7)||0," in last 7 days"]})]})})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by city, address, or agent...",value:t,onChange:F=>n(F.target.value),className:"pl-9"})]}),e.jsx(Fr,{value:r,onValueChange:F=>a(F),children:e.jsxs(Rr,{children:[e.jsx(Zt,{value:"all",children:"All"}),e.jsx(Zt,{value:"pending",children:"Pending"}),e.jsx(Zt,{value:"approved",children:"Approved"})]})})]})})}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{children:["Listings (",(O==null?void 0:O.length)||0,")"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Price"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-center",children:"Approved"}),e.jsx(Tt,{className:"text-center",children:"Featured"}),e.jsx(Tt,{children:"Views"}),e.jsx(Tt,{children:"Shares"}),e.jsx(Tt,{children:"Leads"}),e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{})]})}),e.jsx(da,{children:u?e.jsx(Hs,{children:e.jsx(ht,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):(O==null?void 0:O.length)===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:11,className:"text-center py-8 text-muted-foreground",children:"No listings found"})}):O==null?void 0:O.map(F=>{var z,H,Z,Y,W;return e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[(H=(z=F.photos)==null?void 0:z[0])!=null&&H.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(Ua,{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:(Z=F.property_type)==null?void 0:Z.replace("_"," ")})]})]})}),e.jsx(ht,{children:e.jsx("p",{className:"text-sm",children:((Y=F.agent)==null?void 0:Y.name)||"Unknown"})}),e.jsx(ht,{className:"font-medium",children:D(F.price)}),e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",className:I(F.status),children:(W=F.status)==null?void 0:W.replace("_"," ")})}),e.jsx(ht,{className:"text-center",children:e.jsx(jn,{checked:F.is_approved??!1,onCheckedChange:ee=>j.mutate({id:F.id,approved:ee,slug:F.slug})})}),e.jsx(ht,{className:"text-center",children:e.jsx(jn,{checked:F.is_featured??!1,onCheckedChange:ee=>w.mutate({id:F.id,featured:ee})})}),e.jsx(ht,{children:F.view_count||0}),e.jsx(ht,{children:F.share_count||0}),e.jsx(ht,{children:((p==null?void 0:p[F.id])??0)>0?e.jsx(B,{variant:"link",size:"sm",className:"px-0 h-auto font-semibold text-teal-600",onClick:()=>l({listingId:F.id,label:F.property_address||`${F.city}, ${F.state}`}),children:p==null?void 0:p[F.id]}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Ss(new Date(F.created_at),"MMM d, yyyy")}),e.jsx(ht,{children:e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",children:e.jsx(Kf,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",children:[e.jsxs(Kr,{onClick:()=>window.open(`/mission-control/listings/${F.id}`,"_blank"),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),"View Listing"]}),e.jsxs(Kr,{onClick:()=>w.mutate({id:F.id,featured:!F.is_featured}),children:[e.jsx(oa,{className:"h-4 w-4 mr-2"}),F.is_featured?"Unfeature":"Feature"]}),e.jsxs(Kr,{className:"text-destructive",onClick:()=>{confirm("Are you sure you want to delete this listing?")&&S.mutate(F.id)},children:[e.jsx($n,{className:"h-4 w-4 mr-2"}),"Delete"]})]})]})})]},F.id)})})]})})})]})]}),e.jsx(_s,{open:!!i,onOpenChange:F=>!F&&l(null),children:e.jsxs(bs,{className:"max-w-3xl max-h-[80vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Leads from listing"}),e.jsx(Jn,{children:i==null?void 0:i.label})]}),y?e.jsxs("div",{className:"py-8 text-center text-muted-foreground",children:[e.jsx(rs,{className:"h-5 w-5 animate-spin inline mr-2"}),"Loading leads..."]}):!f||f.length===0?e.jsx("div",{className:"py-8 text-center text-muted-foreground",children:"No leads yet."}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Phone"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Captured"})]})}),e.jsx(da,{children:f.map(F=>{var z;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:[F.first_name,F.last_name].filter(Boolean).join(" ")||"—"}),e.jsx(ht,{children:F.email}),e.jsx(ht,{children:F.phone||"—"}),e.jsx(ht,{children:e.jsx(Ue,{variant:"outline",children:(z=F.lead_type)==null?void 0:z.replace("_"," ")})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Ss(new Date(F.created_at),"MMM d, yyyy h:mm a")})]},F.id)})})]})]})})]})}function cJs(s){return s?new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s):"—"}function dJs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),{data:l,isLoading:o}=dt({queryKey:["admin-all-listing-leads"],queryFn:async()=>{const h=[];let p=0;const f=1e3;for(;;){const{data:y,error:_}=await q.from("listing_leads").select(` id, listing_id, agent_id, referred_by_agent_id, first_name, last_name, email, phone, lead_type, showing_mode, preferred_date, preferred_time, message, created_at, listing:listings!listing_leads_listing_id_fkey(id, slug, property_address, city, state, price), agent:profiles!listing_leads_agent_id_fkey(id, name, email), referrer:profiles!listing_leads_referred_by_agent_id_fkey(id, name, email) `).order("created_at",{ascending:!1}).range(p,p+f-1);if(_)throw _;if(!y||y.length===0||(h.push(...y),y.length{if(!l)return[];const h=n==="all"?0:Date.now()-parseInt(n)*24*60*60*1e3,p=s.trim().toLowerCase();return l.filter(f=>{var _,v,j,w,S,A;return h&&new Date(f.created_at).getTime(){const h=c.length,p=c.filter(_=>_.lead_type==="showing_request").length,f=new Set(c.map(_=>_.agent_id)).size,y=new Set(c.map(_=>_.listing_id)).size;return{total:h,showings:p,uniqueAgents:f,uniqueListings:y}},[c]),u=()=>{const p=[["Date","Name","Email","Phone","Type","Showing Date","Property","City","Price","Assigned Agent","Agent Email","Referred By","Message"],...c.map(v=>{var j,w,S,A,E,O;return[Ss(new Date(v.created_at),"yyyy-MM-dd HH:mm"),`${v.first_name||""} ${v.last_name||""}`.trim(),v.email,v.phone||"",v.lead_type,v.preferred_date?`${v.preferred_date} ${v.preferred_time||""}`:"",((j=v.listing)==null?void 0:j.property_address)||"",((w=v.listing)==null?void 0:w.city)||"",(S=v.listing)!=null&&S.price?String(v.listing.price):"",((A=v.agent)==null?void 0:A.name)||"",((E=v.agent)==null?void 0:E.email)||"",((O=v.referrer)==null?void 0:O.name)||"",(v.message||"").replace(/[\r\n]+/g," ")]})].map(v=>v.map(j=>`"${String(j).replace(/"/g,'""')}"`).join(",")).join(` `),f=new Blob([p],{type:"text/csv"}),y=URL.createObjectURL(f),_=document.createElement("a");_.href=y,_.download=`listing-leads-${Ss(new Date,"yyyy-MM-dd")}.csv`,_.click(),URL.revokeObjectURL(y)};return e.jsx(Cs,{title:"Listing Leads",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-center justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Listing Leads"}),e.jsx("p",{className:"text-muted-foreground",children:"All leads submitted through the public listings site"})]}),e.jsxs(B,{variant:"outline",onClick:u,disabled:!c.length,className:"gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"}),"Export CSV"]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-teal-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Total Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.total})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-purple-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Showing Requests"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.showings})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4 text-blue-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Properties"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueListings})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-amber-600"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"Agents w/ Leads"})]}),e.jsx("p",{className:"text-2xl font-bold mt-1",children:d.uniqueAgents})]})})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search name, email, property, agent...",value:s,onChange:h=>t(h.target.value),className:"pl-9"})]}),e.jsxs(us,{value:a,onValueChange:h=>i(h),children:[e.jsx(ls,{className:"w-full sm:w-48",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Types"}),e.jsx(Ze,{value:"info_request",children:"Info Request"}),e.jsx(Ze,{value:"showing_request",children:"Showing Request"})]})]}),e.jsxs(us,{value:n,onValueChange:h=>r(h),children:[e.jsx(ls,{className:"w-full sm:w-40",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Time"}),e.jsx(Ze,{value:"7",children:"Last 7 days"}),e.jsx(Ze,{value:"30",children:"Last 30 days"}),e.jsx(Ze,{value:"90",children:"Last 90 days"})]})]})]})})}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{children:["Leads (",c.length,")"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Lead"}),e.jsx(Tt,{children:"Contact"}),e.jsx(Tt,{children:"Property"}),e.jsx(Tt,{children:"Type"}),e.jsx(Tt,{children:"Assigned To"}),e.jsx(Tt,{children:"Referred By"}),e.jsx(Tt,{children:"Message"})]})}),e.jsx(da,{children:o?e.jsx(Hs,{children:e.jsx(ht,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):c.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:8,className:"text-center py-8 text-muted-foreground",children:"No leads found"})}):c.map(h=>{var p,f;return e.jsxs(Hs,{children:[e.jsxs(ht,{className:"whitespace-nowrap text-sm",children:[Ss(new Date(h.created_at),"MMM d, yyyy"),e.jsx("div",{className:"text-xs text-muted-foreground",children:Ss(new Date(h.created_at),"h:mm a")})]}),e.jsx(ht,{children:e.jsx("div",{className:"font-medium",children:`${h.first_name||""} ${h.last_name||""}`.trim()||"—"})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex flex-col gap-1 text-sm",children:[e.jsxs("a",{href:`mailto:${h.email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Gs,{className:"h-3 w-3"}),h.email]}),h.phone&&e.jsxs("a",{href:`tel:${h.phone}`,className:"flex items-center gap-1 text-muted-foreground hover:underline",children:[e.jsx(Cr,{className:"h-3 w-3"}),h.phone]})]})}),e.jsx(ht,{children:h.listing?e.jsxs(In,{to:`/public/listing/${h.listing.slug||h.listing.id}`,target:"_blank",className:"group",children:[e.jsxs("div",{className:"font-medium text-sm group-hover:underline flex items-center gap-1",children:[h.listing.property_address||"Untitled",e.jsx(tr,{className:"h-3 w-3 opacity-60"})]}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:[[h.listing.city,h.listing.state].filter(Boolean).join(", ")," · ",cJs(h.listing.price)]})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})}),e.jsxs(ht,{children:[e.jsx(Ue,{variant:h.lead_type==="showing_request"?"default":"secondary",className:"text-xs",children:h.lead_type==="showing_request"?"Showing":"Info"}),h.preferred_date&&e.jsxs("div",{className:"text-xs text-muted-foreground mt-1",children:[h.preferred_date," ",h.preferred_time||""]}),h.showing_mode&&e.jsx("div",{className:"text-xs text-muted-foreground capitalize",children:h.showing_mode.replace("_"," ")})]}),e.jsxs(ht,{children:[e.jsx("div",{className:"text-sm font-medium",children:((p=h.agent)==null?void 0:p.name)||"—"}),((f=h.agent)==null?void 0:f.email)&&e.jsx("div",{className:"text-xs text-muted-foreground",children:h.agent.email})]}),e.jsx(ht,{children:h.referrer?e.jsxs("div",{children:[e.jsx("div",{className:"text-sm",children:h.referrer.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:h.referrer.email})]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"Direct"})}),e.jsx(ht,{className:"max-w-xs",children:h.message?e.jsxs("div",{className:"text-xs text-muted-foreground line-clamp-3 flex items-start gap-1",children:[e.jsx(Ai,{className:"h-3 w-3 mt-0.5 shrink-0"}),h.message]}):e.jsx("span",{className:"text-muted-foreground text-sm",children:"—"})})]},h.id)})})]})})})]})]})})}const OI={new_listing_alerts:{label:"New Listing Alerts",icon:nm,color:"bg-amber-100 text-amber-800"},exit_intent:{label:"Exit Intent",icon:TA,color:"bg-rose-100 text-rose-800"},saved_listing:{label:"Saved Home",icon:gi,color:"bg-pink-100 text-pink-800"},saved_search:{label:"Saved Search",icon:gr,color:"bg-blue-100 text-blue-800"},buyer_guide:{label:"Buyer's Guide",icon:rm,color:"bg-emerald-100 text-emerald-800"}},ZQe=[{key:"24h",label:"Last 24h",days:1},{key:"7d",label:"Last 7 days",days:7},{key:"30d",label:"Last 30 days",days:30},{key:"all",label:"All time",days:0}];function QQe(s){return new Date(s).toLocaleString("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric",hour:"numeric",minute:"2-digit"})}function uJs(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState("30d"),[l,o]=N.useState("all"),[c,d]=N.useState("");N.useEffect(()=>{let f=!1;return(async()=>{r(!0);let y=q.from("public_site_leads").select("*").order("created_at",{ascending:!1}).limit(2e3);const _=ZQe.find(w=>w.key===a);if(_&&_.days>0){const w=new Date(Date.now()-_.days*864e5).toISOString();y=y.gte("created_at",w)}const{data:v,error:j}=await y;f||(j?(console.error(j),t([])):t(v||[]),r(!1))})(),()=>{f=!0}},[a]);const u=N.useMemo(()=>s.filter(f=>{if(l!=="all"&&f.lead_type!==l)return!1;if(c){const y=c.toLowerCase();if(![f.email,f.first_name,f.last_name,f.phone,f.source_page,f.referrer].filter(Boolean).join(" ").toLowerCase().includes(y))return!1}return!0}),[s,l,c]),h=N.useMemo(()=>{const f=u.length,y=new Set(u.map(v=>v.email.toLowerCase())).size,_={};return u.forEach(v=>{_[v.lead_type]=(_[v.lead_type]||0)+1}),{total:f,uniqueEmails:y,byType:_}},[u]),p=()=>{const y=[["Date (ET)","Type","Email","First","Last","Phone","Listing ID","Source Page","Referrer","Criteria"].join(",")];u.forEach(w=>{var A;const S=[QQe(w.created_at),((A=OI[w.lead_type])==null?void 0:A.label)||w.lead_type,w.email,w.first_name||"",w.last_name||"",w.phone||"",w.listing_id||"",w.source_page||"",w.referrer||"",w.criteria?JSON.stringify(w.criteria):""].map(E=>`"${String(E).replace(/"/g,'""')}"`);y.push(S.join(","))});const _=new Blob([y.join(` `)],{type:"text/csv"}),v=URL.createObjectURL(_),j=document.createElement("a");j.href=v,j.download=`public-site-leads-${new Date().toISOString().slice(0,10)}.csv`,j.click(),URL.revokeObjectURL(v)};return e.jsxs("div",{className:"min-h-screen bg-slate-50",children:[e.jsx(Zo,{children:e.jsx("title",{children:"Public Site Leads — Admin"})}),e.jsx("div",{className:"border-b bg-white",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-4 flex items-center justify-between gap-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(In,{to:"/admin",children:e.jsxs(B,{variant:"ghost",size:"sm",children:[e.jsx(qr,{className:"h-4 w-4 mr-1"}),"Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-lg font-semibold",children:"Public Site Leads"}),e.jsx("p",{className:"text-xs text-slate-500",children:"listings.relevelup.com — alerts, exit intent & saved homes"})]})]}),e.jsxs(B,{onClick:p,variant:"outline",size:"sm",children:[e.jsx(Ia,{className:"h-4 w-4 mr-1"})," Export CSV"]})]})}),e.jsxs("div",{className:"max-w-7xl mx-auto px-6 py-6 space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-xs text-slate-500 uppercase tracking-wide",children:"Total Leads"}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.total}),e.jsxs("div",{className:"text-xs text-slate-500 mt-1",children:[h.uniqueEmails," unique"]})]})}),Object.keys(OI).map(f=>{const y=OI[f],_=y.icon;return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-slate-500 uppercase tracking-wide",children:[e.jsx(_,{className:"h-3.5 w-3.5"}),y.label]}),e.jsx("div",{className:"text-2xl font-bold mt-1",children:h.byType[f]||0})]})},f)})]}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsxs(us,{value:a,onValueChange:f=>i(f),children:[e.jsx(ls,{className:"w-[160px] bg-white",children:e.jsx(hs,{})}),e.jsx(cs,{children:ZQe.map(f=>e.jsx(Ze,{value:f.key,children:f.label},f.key))})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-[200px] bg-white",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All lead types"}),Object.keys(OI).map(f=>e.jsx(Ze,{value:f,children:OI[f].label},f))]})]}),e.jsxs("div",{className:"relative flex-1 min-w-[200px] max-w-md",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{placeholder:"Search name, email, phone…",value:c,onChange:f=>d(f.target.value),className:"pl-9 bg-white"})]}),e.jsxs("div",{className:"ml-auto text-sm text-slate-500",children:[u.length," ",u.length===1?"lead":"leads"]})]}),e.jsx(fe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-slate-50 text-left text-xs uppercase tracking-wide text-slate-500",children:[e.jsx("th",{className:"px-4 py-3",children:"Date"}),e.jsx("th",{className:"px-4 py-3",children:"Type"}),e.jsx("th",{className:"px-4 py-3",children:"Contact"}),e.jsx("th",{className:"px-4 py-3",children:"Phone"}),e.jsx("th",{className:"px-4 py-3",children:"Details"}),e.jsx("th",{className:"px-4 py-3",children:"Source"})]})}),e.jsx("tbody",{children:n?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"Loading…"})}):u.length===0?e.jsx("tr",{children:e.jsx("td",{colSpan:6,className:"px-4 py-12 text-center text-slate-500",children:"No leads yet in this range."})}):u.map(f=>{const y=OI[f.lead_type],_=y==null?void 0:y.icon,v=[f.first_name,f.last_name].filter(Boolean).join(" ")||"—";return e.jsxs("tr",{className:"border-b hover:bg-slate-50/60",children:[e.jsx("td",{className:"px-4 py-3 whitespace-nowrap text-slate-600 text-xs",children:QQe(f.created_at)}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:e.jsxs(Ue,{className:`${(y==null?void 0:y.color)||""} font-normal`,variant:"secondary",children:[_?e.jsx(_,{className:"h-3 w-3 mr-1"}):null,(y==null?void 0:y.label)||f.lead_type]})}),e.jsxs("td",{className:"px-4 py-3",children:[e.jsx("div",{className:"font-medium text-slate-900",children:v}),e.jsxs("a",{href:`mailto:${f.email}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Gs,{className:"h-3 w-3"}),f.email]})]}),e.jsx("td",{className:"px-4 py-3 whitespace-nowrap",children:f.phone?e.jsxs("a",{href:`tel:${f.phone}`,className:"text-xs text-blue-600 hover:underline inline-flex items-center gap-1",children:[e.jsx(Cr,{className:"h-3 w-3"}),f.phone]}):e.jsx("span",{className:"text-slate-400 text-xs",children:"—"})}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-600 max-w-xs",children:[f.listing_id&&e.jsxs("div",{className:"mb-0.5",children:["Listing: ",e.jsxs("span",{className:"font-mono text-[10px]",children:[f.listing_id.slice(0,8),"…"]})]}),f.criteria&&Object.keys(f.criteria).length>0&&e.jsx("div",{className:"text-slate-500 line-clamp-2",children:Object.entries(f.criteria).map(([j,w])=>`${j}: ${w}`).join(" · ")})]}),e.jsxs("td",{className:"px-4 py-3 text-xs text-slate-500 max-w-xs truncate",children:[f.source_page&&e.jsxs("div",{className:"inline-flex items-center gap-1",children:[e.jsx(tr,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:f.source_page})]}),f.referrer&&e.jsxs("div",{className:"text-slate-400 truncate",children:["from ",f.referrer]})]})]},f.id)})})]})})})]})]})}const hJs=()=>{var h,p;const[s,t]=N.useState(""),[n,r]=N.useState(null),{data:a,isLoading:i}=dt({queryKey:["membership-reviews"],queryFn:async()=>{const{data:f,error:y}=await q.from("membership_reviews").select("*").order("created_at",{ascending:!1});if(y)throw y;const _=(f==null?void 0:f.map(w=>w.user_id))||[],{data:v}=await q.from("profiles").select("id, name, email").in("id",_);return f==null?void 0:f.map(w=>({...w,profiles:(v==null?void 0:v.find(S=>S.id===w.user_id))||null}))}}),l=a==null?void 0:a.filter(f=>{var _,v,j,w,S;const y=s.toLowerCase();return((v=(_=f.profiles)==null?void 0:_.name)==null?void 0:v.toLowerCase().includes(y))||((w=(j=f.profiles)==null?void 0:j.email)==null?void 0:w.toLowerCase().includes(y))||((S=f.review_text)==null?void 0:S.toLowerCase().includes(y))}),o=a!=null&&a.length?(a.reduce((f,y)=>f+y.rating,0)/a.length).toFixed(1):"0.0",c=a==null?void 0:a.reduce((f,y)=>(f[y.rating]=(f[y.rating]||0)+1,f),{}),d=(a==null?void 0:a.filter(f=>f.posted_to_google).length)||0,u=f=>e.jsx("div",{className:"flex gap-0.5",children:[1,2,3,4,5].map(y=>e.jsx(oa,{className:Mt("h-4 w-4",f>=y?"fill-yellow-400 text-yellow-400":"text-muted-foreground")},y))});return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Membership Reviews",description:"View and manage feedback from LevelUp members"}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-4",children:[e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"Total Reviews"}),e.jsx(Rt,{className:"text-3xl",children:(a==null?void 0:a.length)||0})]})}),e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"Average Rating"}),e.jsxs(Rt,{className:"flex items-center gap-2 text-3xl",children:[o,e.jsx(oa,{className:"h-6 w-6 fill-yellow-400 text-yellow-400"})]})]})}),e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"5-Star Reviews"}),e.jsx(Rt,{className:"text-3xl",children:(c==null?void 0:c[5])||0})]})}),e.jsx(fe,{children:e.jsxs(It,{className:"pb-2",children:[e.jsx(Vn,{children:"Posted to Google"}),e.jsxs(Rt,{className:"flex items-center gap-2 text-3xl",children:[d,e.jsx(tr,{className:"h-5 w-5 text-muted-foreground"})]})]})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or review...",value:s,onChange:f=>t(f.target.value),className:"pl-9"})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Member"}),e.jsx(Tt,{children:"Rating"}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Review"}),e.jsx(Tt,{children:"Google"}),e.jsx(Tt,{children:"Date"})]})}),e.jsx(da,{children:i?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8",children:"Loading reviews..."})}):(l==null?void 0:l.length)===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No reviews found"})}):l==null?void 0:l.map(f=>{var y,_;return e.jsxs(Hs,{className:"cursor-pointer hover:bg-muted/50",onClick:()=>r(f),children:[e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:((y=f.profiles)==null?void 0:y.name)||"Unknown"}),e.jsx("div",{className:"text-sm text-muted-foreground",children:(_=f.profiles)==null?void 0:_.email})]})}),e.jsx(ht,{children:u(f.rating)}),e.jsx(ht,{className:"hidden md:table-cell max-w-xs",children:e.jsx("p",{className:"truncate text-sm text-muted-foreground",children:f.review_text||"-"})}),e.jsx(ht,{children:f.posted_to_google?e.jsx(Ue,{variant:"secondary",className:"bg-green-100 text-green-800",children:"Posted"}):e.jsx(Ue,{variant:"outline",children:"No"})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:Ss(new Date(f.created_at),"MMM d, yyyy")})]},f.id)})})]})})}),e.jsx(_s,{open:!!n,onOpenChange:()=>r(null),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(ws,{children:"Review Details"})}),n&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-start gap-4 p-4 bg-muted/50 rounded-lg",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx("h3",{className:"font-semibold text-lg",children:((h=n.profiles)==null?void 0:h.name)||"Unknown Member"}),((p=n.profiles)==null?void 0:p.email)&&e.jsxs("a",{href:`mailto:${n.profiles.email}`,className:"flex items-center gap-1 text-sm text-muted-foreground hover:text-primary",children:[e.jsx(Gs,{className:"h-3 w-3"}),n.profiles.email]})]}),e.jsxs("div",{className:"text-right",children:[u(n.rating),e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:[n.rating," out of 5 stars"]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-medium mb-2",children:"Review"}),e.jsx("p",{className:"text-sm text-muted-foreground whitespace-pre-wrap",children:n.review_text||"No written review provided."})]}),e.jsxs("div",{className:"flex items-center justify-between pt-4 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(yr,{className:"h-4 w-4"}),Ss(new Date(n.created_at),"MMMM d, yyyy 'at' h:mm a")]}),n.posted_to_google?e.jsxs(Ue,{variant:"secondary",className:"bg-green-100 text-green-800",children:[e.jsx(tr,{className:"h-3 w-3 mr-1"}),"Posted to Google"]}):e.jsx(Ue,{variant:"outline",children:"Not posted to Google"})]})]})]})})]})})},XQe={agent_card:"Agent Card",listing:"Listing",lead_site:"Lead Site",guest_book:"Guest Book",landing_page:"Landing Page",connect_page:"Connect Page",booking:"Booking"},mJs={sent:"bg-green-100 text-green-800",backfilled:"bg-blue-100 text-blue-800",failed:"bg-red-100 text-red-800",pending:"bg-yellow-100 text-yellow-800"};function pJs(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),[a,i]=N.useState("all"),[l,o]=N.useState("7"),{data:c,isLoading:d}=dt({queryKey:["lead-notification-log",l],queryFn:async()=>{const p=new Date(Date.now()-Number(l)*864e5).toISOString(),{data:f,error:y}=await q.from("lead_notification_log").select("*").gte("created_at",p).order("created_at",{ascending:!1}).limit(2e3);if(y)throw y;return f||[]}}),u=N.useMemo(()=>{const p=s.trim().toLowerCase();return(c||[]).filter(f=>n!=="all"&&f.source!==n||a!=="all"&&f.status!==a?!1:p?[f.agent_name,f.agent_email,f.lead_name,f.lead_email,f.lead_phone,f.subject].some(y=>(y||"").toLowerCase().includes(p)):!0)},[c,s,n,a]),h=N.useMemo(()=>{const p=u.length,f=u.filter(v=>v.status==="sent"||v.status==="backfilled").length,y=u.filter(v=>v.status==="failed").length,_=new Set(u.map(v=>v.agent_user_id).filter(Boolean)).size;return{total:p,sent:f,failed:y,agents:_}},[u]);return e.jsx(Cs,{children:e.jsxs("div",{className:"container mx-auto py-6 space-y-6",children:[e.jsx(Bd,{title:"Lead Notifications",description:"Every new-lead notification sent to agents — agent cards, listings, lead sites, guest book sign-ins, landing pages, connect pages, and bookings."}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Total"}),e.jsx("div",{className:"text-2xl font-bold",children:h.total})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Sent"}),e.jsx("div",{className:"text-2xl font-bold text-green-600",children:h.sent})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Failed"}),e.jsx("div",{className:"text-2xl font-bold text-red-600",children:h.failed})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"text-sm text-muted-foreground",children:"Unique Agents"}),e.jsx("div",{className:"text-2xl font-bold",children:h.agents})]})})]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agent or lead name, email, phone…",value:s,onChange:p=>t(p.target.value),className:"pl-9"})]}),e.jsxs(us,{value:n,onValueChange:r,children:[e.jsx(ls,{className:"w-full md:w-48",children:e.jsx(hs,{placeholder:"Source"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Sources"}),Object.entries(XQe).map(([p,f])=>e.jsx(Ze,{value:p,children:f},p))]})]}),e.jsxs(us,{value:a,onValueChange:i,children:[e.jsx(ls,{className:"w-full md:w-40",children:e.jsx(hs,{placeholder:"Status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Statuses"}),e.jsx(Ze,{value:"sent",children:"Sent"}),e.jsx(Ze,{value:"backfilled",children:"Backfilled"}),e.jsx(Ze,{value:"failed",children:"Failed"})]})]}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"w-full md:w-36",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"1",children:"Last 24h"}),e.jsx(Ze,{value:"7",children:"Last 7 days"}),e.jsx(Ze,{value:"14",children:"Last 14 days"}),e.jsx(Ze,{value:"30",children:"Last 30 days"})]})]})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"When"}),e.jsx(Tt,{children:"Source"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Lead"}),e.jsx(Tt,{children:"Status"})]})}),e.jsx(da,{children:d?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"Loading…"})}):u.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center py-8 text-muted-foreground",children:"No notifications match the current filters."})}):u.map(p=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"whitespace-nowrap text-sm",children:Ss(new Date(p.created_at),"MMM d, yyyy h:mm a")}),e.jsx(ht,{children:e.jsx(Ue,{variant:"secondary",children:XQe[p.source]||p.source})}),e.jsxs(ht,{children:[e.jsx("div",{className:"font-medium",children:p.agent_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.agent_email||"—"})]}),e.jsxs(ht,{children:[e.jsx("div",{className:"font-medium",children:p.lead_name||"—"}),e.jsxs("div",{className:"text-xs text-muted-foreground flex flex-wrap gap-x-3 gap-y-1",children:[p.lead_email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gs,{className:"h-3 w-3"}),p.lead_email]}),p.lead_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Cr,{className:"h-3 w-3"}),p.lead_phone]})]})]}),e.jsxs(ht,{children:[e.jsx(Ue,{className:mJs[p.status]||"",children:p.status}),p.error_message&&e.jsx("div",{className:"text-xs text-red-600 mt-1 max-w-[220px] truncate",title:p.error_message,children:p.error_message})]})]},p.id))})]})})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Historical entries (before this feature was enabled) are marked as ",e.jsx("em",{children:"backfilled"})," and reconstructed from the underlying lead records. New leads are logged automatically going forward."]})]})})}const fJs=[{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"}],xJs=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 gJs(){const s=Kt(),{user:t}=vs(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),{data:c,isLoading:d}=dt({queryKey:["weekly-digest-settings"],queryFn:async()=>{const{data:I,error:F}=await q.from("weekly_digest_settings").select("*").single();if(F)throw F;return I}}),{data:u,isLoading:h}=dt({queryKey:["weekly-digest-logs"],queryFn:async()=>{const{data:I,error:F}=await q.from("weekly_digest_logs").select("*").order("sent_at",{ascending:!1}).limit(100);if(F)throw F;return I}}),{data:p}=dt({queryKey:["digest-subscriber-count"],queryFn:async()=>{const{count:I,error:F}=await q.from("profiles").select("id",{count:"exact",head:!0}).eq("digest_opt_out",!1).not("email","is",null);if(F)throw F;return I||0}}),{data:f,refetch:y}=dt({queryKey:["digest-queue-status"],queryFn:async()=>{const I=new Date;I.setUTCHours(0,0,0,0);const[F,z,H,Z]=await Promise.all([q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","pending").gte("created_at",I.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","processing").gte("created_at",I.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","sent").gte("created_at",I.toISOString()),q.from("weekly_digest_send_queue").select("id",{count:"exact",head:!0}).eq("status","failed").gte("created_at",I.toISOString())]);return{pending:F.count||0,processing:z.count||0,sent:H.count||0,failed:Z.count||0,total:(F.count||0)+(z.count||0)+(H.count||0)+(Z.count||0)}},refetchInterval:5e3});N.useEffect(()=>{if(f&&(f.pending>0||f.processing>0)){const I=setInterval(()=>{y(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})},5e3);return()=>clearInterval(I)}},[f,y,s]);const{data:_=0}=dt({queryKey:["digest-today-failed-count"],queryFn:async()=>{const I=new Date;I.setUTCHours(0,0,0,0);const{count:F,error:z}=await q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",I.toISOString());if(z)throw z;return F||0}}),v=yt({mutationFn:async I=>{const{error:F}=await q.from("weekly_digest_settings").update(I).eq("id",c==null?void 0:c.id);if(F)throw F},onSuccess:()=>{s.invalidateQueries({queryKey:["weekly-digest-settings"]}),ae.success("Settings updated")},onError:I=>{ae.error("Failed to update settings: "+I.message)}}),j=async()=>{r(!0);try{const{data:I,error:F}=await q.functions.invoke("send-weekly-digest",{body:{manual:!0}});if(F)throw F;I.queued?ae.success(`${I.queued.toLocaleString()} emails queued! They'll be sent automatically (~80/minute).`):I.sent!==void 0&&ae.success(`Digest sent! ${I.sent} emails delivered, ${I.failed} failed`),y(),s.invalidateQueries({queryKey:["weekly-digest-logs"]})}catch(I){ae.error("Failed to send digest: "+I.message)}finally{r(!1)}},w=async()=>{var I,F,z,H,Z,Y;if(!(t!=null&&t.email)){ae.error("No email found for your account");return}i(!0);try{const{data:W,error:ee}=await q.functions.invoke("send-weekly-digest",{body:{preview:!0,previewEmail:t.email}});if(ee)throw ee;const se=W==null?void 0:W.resendId,oe=W==null?void 0:W.resendDetails,he=oe==null?void 0:oe.status,ce=((I=oe==null?void 0:oe.body)==null?void 0:I.status)||((z=(F=oe==null?void 0:oe.body)==null?void 0:F.data)==null?void 0:z.status),me=((Z=(H=oe==null?void 0:oe.body)==null?void 0:H.error)==null?void 0:Z.message)||((Y=oe==null?void 0:oe.body)==null?void 0:Y.message);ae.success(se?`Preview accepted by email provider (id: ${se})${he?`, status check: ${he}`:""}${ce?`, provider: ${ce}`:""}${me?` (${me})`:""}. Check spam/promotions—delivery can take a few minutes.`:"Preview accepted by email provider. Check spam/promotions—delivery can take a few minutes.")}catch(W){ae.error("Failed to send preview: "+W.message)}finally{i(!1)}},S=async()=>{o(!0);try{const{data:I,error:F}=await q.functions.invoke("send-weekly-digest",{body:{retryFailed:!0}});if(F)throw F;I.queued===0||I.sent===0&&I.failed===0&&!I.queued?ae.info("No failed emails to retry"):I.queued?ae.success(`${I.queued} emails queued for retry!`):ae.success(`Retry complete! ${I.sent} emails delivered, ${I.failed} failed`),y(),s.invalidateQueries({queryKey:["weekly-digest-logs"]}),s.invalidateQueries({queryKey:["digest-today-failed-count"]}),s.invalidateQueries({queryKey:["digest-today-missing-count"]})}catch(I){ae.error("Failed to retry: "+I.message)}finally{o(!1)}},A=f!=null&&f.total?Math.round((f.sent+f.failed)/f.total*100):0,E=((f==null?void 0:f.pending)||0)>0||((f==null?void 0:f.processing)||0)>0,{data:O}=dt({queryKey:["digest-delivery-stats"],queryFn:async()=>{var Y,W;const I=new Date;I.setUTCHours(0,0,0,0);const[F,z,H,Z]=await Promise.all([q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","sent").gte("sent_at",I.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("delivery_status","failed").gte("sent_at",I.toISOString()),q.from("weekly_digest_logs").select("id",{count:"exact",head:!0}).eq("has_agent_os_activity",!0).gte("sent_at",I.toISOString()),q.from("weekly_digest_logs").select("sent_at").order("sent_at",{ascending:!1}).limit(1)]);return{totalSent:F.count||0,totalFailed:z.count||0,agentOsEngaged:H.count||0,lastSent:((W=(Y=Z.data)==null?void 0:Y[0])==null?void 0:W.sent_at)||null}},refetchInterval:E?5e3:!1}),D={totalSent:(O==null?void 0:O.totalSent)||0,totalFailed:(O==null?void 0:O.totalFailed)||0,lastSent:O==null?void 0:O.lastSent,agentOsEngaged:(O==null?void 0:O.agentOsEngaged)||0};return d?e.jsx(Cs,{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(Cs,{title:"Weekly Digest",description:"Configure and manage automated weekly email digests for members",children:e.jsxs(Fr,{defaultValue:"settings",className:"space-y-6",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"settings",className:"flex items-center gap-2",children:[e.jsx(Ko,{className:"h-4 w-4"}),"Settings"]}),e.jsxs(Zt,{value:"stats",className:"flex items-center gap-2",children:[e.jsx(_o,{className:"h-4 w-4"}),"Delivery Stats"]})]}),e.jsxs(is,{value:"settings",className:"space-y-6",children:[E&&f&&e.jsx(fe,{className:"border-primary/50 bg-primary/5",children:e.jsxs(Ee,{className:"pt-6",children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[e.jsx(rs,{className:"h-5 w-5 animate-spin text-primary"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:"Sending emails..."}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[f.sent.toLocaleString()," sent, ",f.pending.toLocaleString()," pending",f.failed>0&&`, ${f.failed} failed`]})]}),e.jsxs("span",{className:"text-sm font-medium",children:[A,"%"]})]}),e.jsx(fi,{value:A,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-2",children:["Processing ~80 emails per minute. Estimated time remaining: ~",Math.ceil(f.pending/80)," min"]})]})}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(An,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:p}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Subscribers"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-emerald-500/10",children:e.jsx(vr,{className:"h-5 w-5 text-emerald-500"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:D.totalSent}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Delivered"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-destructive/10",children:e.jsx(Uc,{className:"h-5 w-5 text-destructive"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:D.totalFailed}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Failed"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-full bg-primary/10",children:e.jsx(pr,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:D.lastSent?Ss(new Date(D.lastSent),"MMM d"):"Never"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Last Sent"})]})]})})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Schedule"]}),e.jsx(Vn,{children:"Configure when the digest is sent"})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Enable Weekly Digest"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Send automated weekly emails to members"})]}),e.jsx(jn,{checked:c==null?void 0:c.is_enabled,onCheckedChange:I=>v.mutate({is_enabled:I})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Cron Frequency"}),e.jsxs(us,{value:(c==null?void 0:c.cron_frequency)||"daily",onValueChange:I=>v.mutate({cron_frequency:I}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"daily",children:"Daily (runs once at selected time)"}),e.jsx(Ze,{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(ne,{children:"Day of Week"}),e.jsxs(us,{value:String(c==null?void 0:c.send_day),onValueChange:I=>v.mutate({send_day:parseInt(I)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:fJs.map(I=>e.jsx(Ze,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Time (UTC)"}),e.jsxs(us,{value:String(c==null?void 0:c.send_hour),onValueChange:I=>v.mutate({send_hour:parseInt(I)}),disabled:(c==null?void 0:c.cron_frequency)==="daily",children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:xJs.map(I=>e.jsx(Ze,{value:I.value,children:I.label},I.value))})]})]})]}),e.jsxs("div",{className:"flex flex-col gap-2",children:[e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{onClick:w,disabled:a,variant:"outline",className:"flex-1",children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),a?"Sending...":"Send Preview to Me"]}),e.jsxs(B,{onClick:j,disabled:n,className:"flex-1",children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),n?"Sending...":"Send to All"]})]}),_>0&&e.jsxs(B,{onClick:S,disabled:l,variant:"outline",className:"w-full",children:[e.jsx(Ei,{className:`h-4 w-4 mr-2 ${l?"animate-spin":""}`}),l?"Retrying...":`Retry ${_} Failed`]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(br,{className:"h-5 w-5"}),"Content Sections"]}),e.jsx(Vn,{children:"Choose what to include in the digest"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(br,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ne,{children:"New Resources"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_new_resources,onCheckedChange:I=>v.mutate({include_new_resources:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ne,{children:"Community Highlights"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_community_posts,onCheckedChange:I=>v.mutate({include_community_posts:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(_o,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ne,{children:"Agent OS Stats"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_agent_os_stats,onCheckedChange:I=>v.mutate({include_agent_os_stats:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ne,{children:"Upcoming Events"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_upcoming_events,onCheckedChange:I=>v.mutate({include_upcoming_events:I})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ac,{className:"h-4 w-4 text-muted-foreground"}),e.jsx(ne,{children:"Goals Progress"})]}),e.jsx(jn,{checked:c==null?void 0:c.include_goals_progress,onCheckedChange:I=>v.mutate({include_goals_progress:I})})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Custom Introduction"}),e.jsx(Vn,{children:"Personalize the intro message (optional)"})]}),e.jsx(Ee,{children:e.jsx(Ms,{placeholder:"Here's what's new this week to help you grow your business...",value:(c==null?void 0:c.custom_intro_text)||"",onChange:I=>v.mutate({custom_intro_text:I.target.value||null}),rows:3})})]})]}),e.jsx(is,{value:"stats",children:e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5"}),"Delivery History"]}),e.jsx(Vn,{children:"Recent digest emails sent to members"})]}),e.jsx(Ee,{children:h?e.jsx("div",{className:"animate-pulse space-y-2",children:[1,2,3,4,5].map(I=>e.jsx("div",{className:"h-12 bg-muted rounded"},I))}):u&&u.length>0?e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Email"}),e.jsx(Tt,{children:"Sent At"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Resources"}),e.jsx(Tt,{children:"Agent OS"})]})}),e.jsx(da,{children:u.map(I=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:I.email_sent_to}),e.jsx(ht,{children:Ss(new Date(I.sent_at),"MMM d, yyyy h:mm a")}),e.jsx(ht,{children:e.jsx(Ue,{variant:I.delivery_status==="sent"?"default":"destructive",children:I.delivery_status})}),e.jsx(ht,{children:I.resources_count}),e.jsx(ht,{children:I.has_agent_os_activity?e.jsx(Ue,{variant:"secondary",children:"Active"}):e.jsx(Ue,{variant:"outline",children:"Not Started"})})]},I.id))})]}):e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Gs,{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 yJs={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 vJs(){var ve,ge,Te;const s=Kt(),[t,n]=N.useState(""),[r,a]=N.useState(null),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(!0),[_,v]=N.useState(!1),[j,w]=N.useState(""),[S,A]=N.useState(null),{data:E,isLoading:O}=dt({queryKey:["admin-agent-points"],queryFn:async()=>{const{data:Ie,error:Ce}=await q.from("agent_attendance_stats").select("*").order("total_points",{ascending:!1});if(Ce)throw Ce;const Me=(Ie==null?void 0:Ie.map(Ae=>Ae.user_id))||[],{data:Pe}=await q.from("profiles").select("id, name, email").in("id",Me),Re=new Map((Pe==null?void 0:Pe.map(Ae=>[Ae.id,{name:Ae.name,email:Ae.email}]))||[]);return Ie==null?void 0:Ie.map(Ae=>({...Ae,profile:Re.get(Ae.user_id)||null}))}}),{data:D}=dt({queryKey:["all-profiles-for-points",E],queryFn:async()=>{const Ce=[];let Me=0;for(;;){const{data:Pe,error:Re}=await q.from("profiles").select("id, name, email").order("name").range(Me,Me+1e3-1);if(Re)throw Re;if(Ce.push(...Pe),!Pe||Pe.length<1e3)break;Me+=1e3}return Ce}}),F=((D==null?void 0:D.filter(Ie=>!(E!=null&&E.some(Ce=>Ce.user_id===Ie.id))))||[]).filter(Ie=>{var Me,Pe;if(!j)return!0;const Ce=j.toLowerCase();return((Me=Ie.name)==null?void 0:Me.toLowerCase().includes(Ce))||((Pe=Ie.email)==null?void 0:Pe.toLowerCase().includes(Ce))}),{data:z,isLoading:H}=dt({queryKey:["agent-point-history",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:Ie,error:Ce}=await q.from("agent_points").select("*").eq("user_id",r.user_id).order("created_at",{ascending:!1});if(Ce)throw Ce;return Ie},enabled:!!(r!=null&&r.user_id)&&o}),{data:Z}=dt({queryKey:["agent-badges",r==null?void 0:r.user_id],queryFn:async()=>{if(!(r!=null&&r.user_id))return[];const{data:Ie,error:Ce}=await q.from("agent_badges").select("*").eq("user_id",r.user_id).order("earned_at",{ascending:!1});if(Ce)throw Ce;return Ie},enabled:!!(r!=null&&r.user_id)}),Y=yt({mutationFn:async({userId:Ie,points:Ce,reason:Me})=>{const{error:Pe}=await q.from("agent_points").insert({user_id:Ie,points:Ce,reason:Me});if(Pe)throw Pe;const{data:Re}=await q.from("agent_attendance_stats").select("total_points, spendable_points").eq("user_id",Ie).maybeSingle(),Ae=((Re==null?void 0:Re.total_points)||0)+Ce,Be=((Re==null?void 0:Re.spendable_points)||0)+Ce,{error:we}=await q.from("agent_attendance_stats").upsert({user_id:Ie,total_points:Math.max(0,Ae),spendable_points:Math.max(0,Be),updated_at:new Date().toISOString()},{onConflict:"user_id"});if(we)throw we},onSuccess:()=>{s.invalidateQueries({queryKey:["admin-agent-points"]}),s.invalidateQueries({queryKey:["agent-point-history"]}),l(!1),u(""),p(""),ae.success(f?"Points awarded successfully!":"Points deducted successfully!")},onError:Ie=>{console.error("Error modifying points:",Ie),ae.error("Failed to modify points")}}),W=()=>{if(!r||!d||!h){ae.error("Please fill in all fields");return}const Ie=parseInt(d);if(isNaN(Ie)||Ie<=0){ae.error("Please enter a valid positive number");return}Y.mutate({userId:r.user_id,points:f?Ie:-Ie,reason:h})},ee=()=>{if(!S||!d||!h){ae.error("Please fill in all fields");return}const Ie=parseInt(d);if(isNaN(Ie)||Ie<=0){ae.error("Please enter a valid positive number");return}Y.mutate({userId:S.id,points:Ie,reason:h},{onSuccess:()=>{v(!1),A(null),w("")}})},se=(Ie,Ce)=>{a(Ie),y(Ce),l(!0)},oe=Ie=>{a(Ie),c(!0)},he=E==null?void 0:E.filter(Ie=>{var Re,Ae,Be,we;const Ce=((Ae=(Re=Ie.profile)==null?void 0:Re.name)==null?void 0:Ae.toLowerCase())||"",Me=((we=(Be=Ie.profile)==null?void 0:Be.email)==null?void 0:we.toLowerCase())||"",Pe=t.toLowerCase();return Ce.includes(Pe)||Me.includes(Pe)}),ce=(E==null?void 0:E.reduce((Ie,Ce)=>Ie+Ce.total_points,0))||0,me=(E==null?void 0:E.length)||0,le=me>0?Math.round(ce/me):0;return O?e.jsx(Cs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx("div",{className:"grid grid-cols-3 gap-4",children:[1,2,3].map(Ie=>e.jsx(Ws,{className:"h-24"},Ie))}),e.jsx(Ws,{className:"h-96"})]})}):e.jsx(Cs,{title:"Agent Points",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Agent Points Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Track, view, and manage agent gamification points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(An,{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:me}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with points tracked"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(xo,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:ce.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"awarded across all agents"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(go,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Average Points"})]}),e.jsx("p",{className:"text-2xl font-bold",children:le}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"per agent"})]})})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-4 items-start sm:items-center justify-between",children:[e.jsxs("div",{className:"relative max-w-sm w-full",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search agents...",value:t,onChange:Ie=>n(Ie.target.value),className:"pl-10"})]}),e.jsxs(B,{onClick:()=>v(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Award Points to New Agent"]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Agent Leaderboard"}),e.jsx(Vn,{children:"All agents with their points, events, and streaks"})]}),e.jsx(Ee,{children:!he||he.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(xo,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No agents with points yet"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-12",children:"#"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Total Points"}),e.jsx(Tt,{className:"text-center",children:"Spendable"}),e.jsx(Tt,{className:"text-center",children:"Events"}),e.jsx(Tt,{className:"text-center",children:"Streak"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:he.map((Ie,Ce)=>{var Me,Pe,Re,Ae;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:Ce<3?e.jsx("div",{className:`w-6 h-6 rounded-full flex items-center justify-center ${Ce===0?"bg-yellow-100 text-yellow-700":Ce===1?"bg-gray-100 text-gray-600":"bg-amber-100 text-amber-700"}`,children:Ce+1}):e.jsx("span",{className:"text-muted-foreground",children:Ce+1})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(Jr,{className:"h-8 w-8",children:e.jsx(ea,{children:((Pe=(Me=Ie.profile)==null?void 0:Me.name)==null?void 0:Pe.charAt(0))||"?"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((Re=Ie.profile)==null?void 0:Re.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(Ae=Ie.profile)==null?void 0:Ae.email})]})]})}),e.jsx(ht,{className:"text-center",children:e.jsxs(Ue,{variant:"secondary",className:"font-bold",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),Ie.total_points]})}),e.jsx(ht,{className:"text-center",children:e.jsxs(Ue,{variant:"outline",className:"font-bold text-primary",children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"}),Ie.spendable_points||0]})}),e.jsx(ht,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3 text-muted-foreground"}),Ie.total_events_attended]})}),e.jsx(ht,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Hc,{className:"h-3 w-3 text-orange-500"}),Ie.current_streak]})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>se(Ie,!0),title:"Award points",children:e.jsx(Is,{className:"h-4 w-4 text-green-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>se(Ie,!1),title:"Deduct points",children:e.jsx(hb,{className:"h-4 w-4 text-red-600"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>oe(Ie),title:"View history",children:e.jsx(kA,{className:"h-4 w-4"})})]})})]},Ie.user_id)})})]})})]}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:f?"Award Points":"Deduct Points"}),e.jsxs(Jn,{children:[f?"Award":"Deduct"," points ",f?"to":"from"," ",((ve=r==null?void 0:r.profile)==null?void 0:ve.name)||"this agent"]})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"points",children:"Points Amount"}),e.jsx(ye,{id:"points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Ie=>u(Ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"reason",children:"Reason"}),e.jsx(Ms,{id:"reason",placeholder:"Enter reason for this adjustment...",value:h,onChange:Ie=>p(Ie.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:W,disabled:Y.isPending,className:f?"bg-green-600 hover:bg-green-700":"bg-red-600 hover:bg-red-700",children:Y.isPending?"Saving...":f?"Award Points":"Deduct Points"})]})]})}),e.jsx(_s,{open:o,onOpenChange:c,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsxs(js,{children:[e.jsxs(ws,{children:["Point History: ",(ge=r==null?void 0:r.profile)==null?void 0:ge.name]}),e.jsx(Jn,{children:"View all point transactions and badges for this agent"})]}),e.jsxs(Fr,{defaultValue:"history",className:"w-full",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-2",children:[e.jsx(Zt,{value:"history",children:"Point History"}),e.jsx(Zt,{value:"badges",children:"Badges"})]}),e.jsx(is,{value:"history",className:"mt-4",children:H?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(Ie=>e.jsx(Ws,{className:"h-12"},Ie))}):!z||z.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(kA,{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(Ie=>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:Ie.reason}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Ss(new Date(Ie.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(Ue,{variant:Ie.points>=0?"default":"destructive",className:Ie.points>=0?"bg-green-100 text-green-800":"",children:[Ie.points>=0?"+":"",Ie.points]})]},Ie.id))})}),e.jsx(is,{value:"badges",className:"mt-4",children:!Z||Z.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(fc,{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:Z.map(Ie=>e.jsxs("div",{className:`p-3 rounded-lg ${yJs[Ie.badge_type]||"bg-gray-100"}`,children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(fc,{className:"h-5 w-5"}),e.jsx("span",{className:"font-medium",children:Ie.badge_name})]}),Ie.badge_description&&e.jsx("p",{className:"text-xs mt-1 opacity-80",children:Ie.badge_description}),e.jsxs("p",{className:"text-xs mt-1 opacity-60",children:["Earned ",Ss(new Date(Ie.earned_at),"MMM d, yyyy")]})]},Ie.id))})})]})]})}),e.jsx(_s,{open:_,onOpenChange:Ie=>{v(Ie),Ie||(A(null),w(""),u(""),p(""))},children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Award Points to New Agent"}),e.jsx(Jn,{children:"Select an agent who doesn't have points yet and award them points"})]}),e.jsx("div",{className:"space-y-4 py-4",children:S?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-3 p-3 bg-muted/50 rounded-lg",children:[e.jsx(Jr,{className:"h-10 w-10",children:e.jsx(ea,{children:((Te=S.name)==null?void 0:Te.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-medium",children:S.name||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:S.email})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>A(null),children:"Change"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"new-points",children:"Points Amount"}),e.jsx(ye,{id:"new-points",type:"number",min:"1",placeholder:"Enter points...",value:d,onChange:Ie=>u(Ie.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"new-reason",children:"Reason"}),e.jsx(Ms,{id:"new-reason",placeholder:"Enter reason for awarding points...",value:h,onChange:Ie=>p(Ie.target.value)})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Search Agent"}),e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:j,onChange:Ie=>w(Ie.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(An,{className:"h-6 w-6 mx-auto mb-2 opacity-50"}),e.jsx("p",{className:"text-sm",children:j?"No matching agents found":"All agents already have points"})]}):F.slice(0,20).map(Ie=>{var Ce;return e.jsxs("button",{onClick:()=>A(Ie),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(Jr,{className:"h-8 w-8",children:e.jsx(ea,{children:((Ce=Ie.name)==null?void 0:Ce.charAt(0))||"?"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium truncate",children:Ie.name||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ie.email})]})]},Ie.id)})})]})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),S&&e.jsxs(B,{onClick:ee,disabled:Y.isPending,className:"bg-green-600 hover:bg-green-700",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Award Points"]})]})]})})]})})}function bJs(){const{data:s,isLoading:t}=G9t(),[n,r]=N.useState(null),[a,i]=N.useState(!1),[l,o]=N.useState(""),[c,d]=N.useState("all"),[u,h]=N.useState("newest"),[p,f]=N.useState("table"),y=N.useMemo(()=>(s==null?void 0:s.map(S=>S.user_id))||[],[s]),_=N.useMemo(()=>(s==null?void 0:s.map(S=>S.id))||[],[s]),{data:v}=dt({queryKey:["card-profiles-lookup",y],queryFn:async()=>{if(y.length===0)return{};const{data:S}=await q.from("profiles").select("id, name, email").in("id",y),A={};return S==null||S.forEach(E=>{A[E.id]={name:E.name||"",email:E.email||""}}),A},enabled:y.length>0}),{data:j}=dt({queryKey:["card-stats-all",_],queryFn:async()=>{if(_.length===0)return{};const S={};_.forEach(O=>{S[O]={views:0,leads:0}});const{data:A}=await q.from("agent_card_interactions").select("card_id").in("card_id",_).eq("interaction_type","card_view");A==null||A.forEach(O=>{S[O.card_id]&&S[O.card_id].views++});const{data:E}=await q.from("agent_card_leads").select("card_id").in("card_id",_);return E==null||E.forEach(O=>{S[O.card_id]&&S[O.card_id].leads++}),S},enabled:_.length>0}),w=N.useMemo(()=>{if(!s)return[];let S=[...s];if(c==="live"?S=S.filter(A=>A.is_published):c==="draft"&&(S=S.filter(A=>!A.is_published)),l.trim()){const A=l.toLowerCase();S=S.filter(E=>{var D,I;const O=v==null?void 0:v[E.user_id];return E.slug.toLowerCase().includes(A)||((D=O==null?void 0:O.name)==null?void 0:D.toLowerCase().includes(A))||((I=O==null?void 0:O.email)==null?void 0:I.toLowerCase().includes(A))})}return u==="newest"?S.sort((A,E)=>new Date(E.created_at).getTime()-new Date(A.created_at).getTime()):u==="oldest"?S.sort((A,E)=>new Date(A.created_at).getTime()-new Date(E.created_at).getTime()):u==="name"?S.sort((A,E)=>{var O,D;return(((O=v==null?void 0:v[A.user_id])==null?void 0:O.name)||"").localeCompare(((D=v==null?void 0:v[E.user_id])==null?void 0:D.name)||"")}):u==="slug"?S.sort((A,E)=>A.slug.localeCompare(E.slug)):u==="views_desc"?S.sort((A,E)=>{var O,D;return(((O=j==null?void 0:j[E.id])==null?void 0:O.views)||0)-(((D=j==null?void 0:j[A.id])==null?void 0:D.views)||0)}):u==="views_asc"?S.sort((A,E)=>{var O,D;return(((O=j==null?void 0:j[A.id])==null?void 0:O.views)||0)-(((D=j==null?void 0:j[E.id])==null?void 0:D.views)||0)}):u==="leads_desc"?S.sort((A,E)=>{var O,D;return(((O=j==null?void 0:j[E.id])==null?void 0:O.leads)||0)-(((D=j==null?void 0:j[A.id])==null?void 0:D.leads)||0)}):u==="leads_asc"&&S.sort((A,E)=>{var O,D;return(((O=j==null?void 0:j[A.id])==null?void 0:O.leads)||0)-(((D=j==null?void 0:j[E.id])==null?void 0:D.leads)||0)}),S},[s,c,l,u,v]);return e.jsxs(Cs,{title:"Digital Agent Cards",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Digital Agent Cards"}),e.jsx("p",{className:"text-muted-foreground",children:"Create and manage agent digital business cards"})]}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create Card"]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name, email, or slug...",value:l,onChange:S=>o(S.target.value),className:"pl-9"})]}),e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(ls,{className:"w-full sm:w-36",children:e.jsx(hs,{placeholder:"Status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All Status"}),e.jsx(Ze,{value:"live",children:"Live"}),e.jsx(Ze,{value:"draft",children:"Draft"})]})]}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(ls,{className:"w-full sm:w-44",children:e.jsx(hs,{placeholder:"Sort by"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"newest",children:"Newest First"}),e.jsx(Ze,{value:"oldest",children:"Oldest First"}),e.jsx(Ze,{value:"name",children:"Name A–Z"}),e.jsx(Ze,{value:"slug",children:"Slug A–Z"}),e.jsx(Ze,{value:"views_desc",children:"Most Views"}),e.jsx(Ze,{value:"views_asc",children:"Fewest Views"}),e.jsx(Ze,{value:"leads_desc",children:"Most Leads"}),e.jsx(Ze,{value:"leads_asc",children:"Fewest Leads"})]})]}),e.jsxs("div",{className:"flex border rounded-md",children:[e.jsx(B,{variant:p==="table"?"default":"ghost",size:"sm",onClick:()=>f("table"),className:"rounded-r-none",children:e.jsx(hL,{className:"h-4 w-4"})}),e.jsx(B,{variant:p==="grid"?"default":"ghost",size:"sm",onClick:()=>f("grid"),className:"rounded-l-none",children:e.jsx(ff,{className:"h-4 w-4"})})]})]}),!t&&s&&s.length>0&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Showing ",w.length," of ",s.length," cards"]}),t?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(S=>e.jsx(Ws,{className:"h-48"},S))}):w.length>0?p==="table"?e.jsx(_Js,{cards:w,cardProfiles:v,cardStats:j,onEdit:r,sortBy:u,setSortBy:h}):e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:w.map(S=>e.jsx(wJs,{card:S,onEdit:()=>r(S),stats:j==null?void 0:j[S.id]},S.id))}):s&&s.length>0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(gr,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No matching cards"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Try adjusting your search or filters"})]})}):e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12",children:[e.jsx(An,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No cards yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first digital agent card"}),e.jsxs(B,{onClick:()=>i(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create Card"]})]})})]}),e.jsx(jJs,{open:a,onOpenChange:i}),n&&e.jsx(NJs,{card:n,open:!!n,onOpenChange:S=>!S&&r(null)})]})}function _Js({cards:s,cardProfiles:t,cardStats:n,onEdit:r,sortBy:a,setSortBy:i}){const l=c=>{a===`${c}_desc`?i(`${c}_asc`):i(`${c}_desc`)},o=({field:c})=>a===`${c}_desc`?e.jsx(sm,{className:"h-3 w-3"}):a===`${c}_asc`?e.jsx(Iu,{className:"h-3 w-3"}):e.jsx(ah,{className:"h-3 w-3 opacity-40"});return e.jsx(fe,{children:e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b bg-muted/50",children:[e.jsx("th",{className:"text-left p-3 font-medium",children:e.jsxs("button",{onClick:()=>{i(a==="name"?"newest":"name")},className:"flex items-center gap-1 hover:text-foreground text-muted-foreground",children:["Agent ",a==="name"&&e.jsx(Iu,{className:"h-3 w-3"})]})}),e.jsx("th",{className:"text-left p-3 font-medium text-muted-foreground hidden md:table-cell",children:"Slug"}),e.jsx("th",{className:"text-center p-3 font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("views"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Views ",e.jsx(o,{field:"views"})]})}),e.jsx("th",{className:"text-right p-3 font-medium",children:e.jsxs("button",{onClick:()=>l("leads"),className:"flex items-center gap-1 ml-auto hover:text-foreground text-muted-foreground",children:["Leads ",e.jsx(o,{field:"leads"})]})}),e.jsx("th",{className:"text-right p-3 font-medium text-muted-foreground",children:"Actions"})]})}),e.jsx("tbody",{children:s.map(c=>{const d=t==null?void 0:t[c.user_id],u=n==null?void 0:n[c.id],h=`https://cards.relevelup.com/${c.slug}`;return e.jsxs("tr",{className:"border-b last:border-0 hover:bg-muted/30 transition-colors",children:[e.jsx("td",{className:"p-3",children:e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:(d==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:(d==null?void 0:d.email)||""})]})}),e.jsx("td",{className:"p-3 hidden md:table-cell",children:e.jsxs("span",{className:"text-xs text-muted-foreground font-mono",children:["/",c.slug]})}),e.jsx("td",{className:"p-3 text-center",children:e.jsx(Ue,{variant:c.is_published?"default":"secondary",className:"text-xs",children:c.is_published?"Live":"Draft"})}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.views)??0}),e.jsx("td",{className:"p-3 text-right tabular-nums font-medium",children:(u==null?void 0:u.leads)??0}),e.jsx("td",{className:"p-3",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(c),className:"h-8 w-8 p-0",children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{navigator.clipboard.writeText(h),ae.success("Link copied!")},children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",asChild:!0,children:e.jsx("a",{href:h,target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})})]})})]},c.id)})})]})})})}function wJs({card:s,onEdit:t,stats:n}){const[r,a]=N.useState(null);N.useEffect(()=>{(async()=>{const{data:c}=await q.from("profiles").select("name").eq("id",s.user_id).single();let d=null;try{const{data:u}=await q.storage.from("avatars").list(`${s.user_id}`);if(u&&u.length>0){const{data:h}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${u[0].name}`);d=h.publicUrl}}catch{}a({name:(c==null?void 0:c.name)||"Unknown",avatar_url:d})})()},[s.user_id]);const i=`https://cards.relevelup.com/${s.slug}`,l=()=>{navigator.clipboard.writeText(i),ae.success("Link copied!")};return e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start gap-3 mb-3",children:[e.jsxs(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:(r==null?void 0:r.avatar_url)||void 0}),e.jsx(ea,{children:((r==null?void 0:r.name)||"U")[0]})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold truncate",children:(r==null?void 0:r.name)||"Loading..."}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:["/card/",s.slug]})]}),e.jsx(Ue,{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(Sr,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.views)??0," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(An,{className:"h-3.5 w-3.5"}),(n==null?void 0:n.leads)??0," leads"]})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:t,className:"flex-1",children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:l,children:e.jsx(Zr,{className:"h-3 w-3"})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx("a",{href:i,target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3 w-3"})})})]})]})})}function jJs({open:s,onOpenChange:t}){const[n,r]=N.useState(""),[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState(!1),u=Glt(),h=l.trim(),{data:p}=dt({queryKey:["profiles-search-for-cards",h],queryFn:async()=>{let w=q.from("profiles").select("id, name, email").order("name").limit(50);h.length>=2&&(w=w.or(`name.ilike.%${h}%,email.ilike.%${h}%`));const{data:S}=await w;return S||[]},enabled:s}),[f,y]=N.useState(null),_=(p==null?void 0:p.find(w=>w.id===n))||f,v=()=>{if(!n||!a.trim()){ae.error("Select an agent and enter a slug");return}u.mutate({user_id:n,slug:a.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-"),is_published:!0},{onSuccess:()=>{t(!1),r(""),i(""),o("")}})},j=w=>{var A;r(w),d(!1);const S=p==null?void 0:p.find(E=>E.id===w);S&&(y(S),i(((A=S.name)==null?void 0:A.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""))||""))};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create Agent Card"}),e.jsx(Jn,{children:"Select an agent and set their card URL slug."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Agent"}),e.jsxs(il,{open:c,onOpenChange:d,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox","aria-expanded":c,className:"w-full justify-between font-normal",children:[_?`${_.name} (${_.email})`:"Search for an agent...",e.jsx($g,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-[--radix-popover-trigger-width] p-0",align:"start",children:e.jsxs(Yg,{shouldFilter:!1,children:[e.jsx(Zg,{placeholder:"Search by name or email...",value:l,onValueChange:o}),e.jsxs(Qg,{children:[e.jsx(Xg,{children:"No agents found."}),e.jsx(Jg,{children:(p||[]).map(w=>e.jsxs(Zf,{value:w.id,onSelect:j,children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4",n===w.id?"opacity-100":"opacity-0")}),w.name," (",w.email,")"]},w.id))})]})]})})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"URL Slug"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"/card/"}),e.jsx(ye,{value:a,onChange:w=>i(w.target.value),placeholder:"john-doe"})]})]}),e.jsx(B,{onClick:v,disabled:u.isPending,className:"w-full",children:u.isPending?"Creating...":"Create Card"})]})]})})}function NJs({card:s,open:t,onOpenChange:n}){const r=Wlt(),{data:a}=Klt(s.id),i=Kt(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState(""),[y,_]=N.useState(s.slug),[v,j]=N.useState(!1),[w,S]=N.useState({is_published:s.is_published,theme:s.theme,title:s.title||"",positioning_statement:s.positioning_statement||"",bio:s.bio||"",review_snippet:s.review_snippet||"",review_source_url:s.review_source_url||"",booking_url:s.booking_url||"",custom_cta_label:s.custom_cta_label||"",custom_cta_url:s.custom_cta_url||"",show_photo:s.show_photo,show_bio:s.show_bio,show_credentials:s.show_credentials,show_social_links:s.show_social_links,show_save_contact:s.show_save_contact,show_leave_review:s.show_leave_review,show_refer_friend:s.show_refer_friend,brokerage_display_name:s.brokerage_display_name||"",brokerage_logo_url:s.brokerage_logo_url||"",brokerage_logo_size:s.brokerage_logo_size||56,team_name:s.team_name||"",team_logo_url:s.team_logo_url||"",team_logo_size:s.team_logo_size||56});N.useEffect(()=>{t&&(async()=>{try{const{data:z}=await q.storage.from("avatars").list(`${s.user_id}`);if(z&&z.length>0){const{data:H}=q.storage.from("avatars").getPublicUrl(`${s.user_id}/${z[0].name}`);o(`${H.publicUrl}?t=${Date.now()}`)}}catch{}})()},[s.user_id,t]);const A=F=>{var Z;const z=(Z=F.target.files)==null?void 0:Z[0];if(!z)return;if(!z.type.startsWith("image/")){ae.error("Please select an image file");return}if(z.size>5*1024*1024){ae.error("Image must be under 5MB");return}const H=new FileReader;H.onloadend=()=>{f(H.result),h(!0)},H.readAsDataURL(z),F.target.value=""},E=async F=>{d(!0);try{const{data:z}=await q.storage.from("avatars").list(`${s.user_id}`);z&&z.length>0&&await q.storage.from("avatars").remove(z.map(ee=>`${s.user_id}/${ee.name}`));const H=`${s.user_id}/avatar.jpg`,{error:Z}=await q.storage.from("avatars").upload(H,F,{upsert:!0,contentType:"image/jpeg"});if(Z)throw Z;const{data:Y}=q.storage.from("avatars").getPublicUrl(H),W=`${Y.publicUrl}?t=${Date.now()}`;o(W),await q.from("profiles").update({avatar_url:W}).eq("id",s.user_id),i.invalidateQueries({queryKey:["agent-card-public"]}),ae.success("Photo updated!")}catch(z){ae.error(z.message||"Upload failed")}finally{d(!1)}},O=async()=>{const F=y.trim().toLowerCase().replace(/[^a-z0-9-]/g,"-").replace(/-+/g,"-").replace(/(^-|-$)/g,"");if(!F){ae.error("Please enter a valid URL");return}if(F===s.slug){ae.info("No changes to save");return}j(!0);try{const{data:z}=await q.from("agent_cards").select("id").eq("slug",F).neq("id",s.id).maybeSingle();if(z){ae.error("This URL is already taken. Try another one.");return}const{error:H}=await q.from("agent_cards").update({slug:F}).eq("id",s.id);if(H)throw H;_(F),i.invalidateQueries({queryKey:["agent-cards-admin"]}),ae.success("Card address updated!")}catch{ae.error("Failed to update card address")}finally{j(!1)}},D=async(F,z)=>{var Z;const H=(Z=F.target.files)==null?void 0:Z[0];if(H){if(!H.type.startsWith("image/")){ae.error("Please select an image file");return}try{const Y=H.name.split(".").pop()||"png",W=z==="brokerage_logo_url"?"brokerage-logo":"team-logo",ee=`${s.user_id}/${W}.${Y}`,{error:se}=await q.storage.from("card-logos").upload(ee,H,{upsert:!0});if(se)throw se;const{data:oe}=q.storage.from("card-logos").getPublicUrl(ee),he=oe.publicUrl+"?t="+Date.now();S(z==="brokerage_logo_url"?ce=>({...ce,[z]:he,brokerage_display_name:""}):ce=>({...ce,[z]:he,team_name:""})),ae.success("Logo uploaded!")}catch{ae.error("Failed to upload logo")}finally{F.target.value=""}}},I=()=>{r.mutate({id:s.id,...w,title:w.title||null,positioning_statement:w.positioning_statement||null,bio:w.bio||null,review_snippet:w.review_snippet||null,review_source_url:w.review_source_url||null,booking_url:w.booking_url||null,custom_cta_label:w.custom_cta_label||null,custom_cta_url:w.custom_cta_url||null,brokerage_display_name:w.brokerage_display_name||null,brokerage_logo_url:w.brokerage_logo_url||null,brokerage_logo_size:w.brokerage_logo_size,team_name:w.team_name||null,team_logo_url:w.team_logo_url||null,team_logo_size:w.team_logo_size},{onSuccess:()=>n(!1)})};return e.jsxs(e.Fragment,{children:[e.jsx(_s,{open:t,onOpenChange:n,children:e.jsxs(bs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Edit Agent Card"}),e.jsxs(Jn,{children:["/card/",s.slug]})]}),e.jsxs(Fr,{defaultValue:"content",children:[e.jsxs(Rr,{className:"w-full",children:[e.jsx(Zt,{value:"content",className:"flex-1",children:"Content"}),e.jsx(Zt,{value:"sections",className:"flex-1",children:"Sections"}),e.jsx(Zt,{value:"blocks",className:"flex-1",children:"Blocks"}),e.jsx(Zt,{value:"analytics",className:"flex-1",children:"Analytics"})]}),e.jsxs(is,{value:"content",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Published"}),e.jsx(jn,{checked:w.is_published,onCheckedChange:F=>S(z=>({...z,is_published:F}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-4 mt-1",children:[e.jsxs(Jr,{className:"h-16 w-16",children:[e.jsx(ti,{src:l||void 0}),e.jsx(ea,{children:"?"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:A,disabled:c}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:c,children:e.jsx("span",{children:c?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-3 w-3 mr-1 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-3 w-3 mr-1"}),"Change Photo"]})})})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Card Address"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsxs("div",{className:"flex flex-1",children:[e.jsx("span",{className:"inline-flex items-center px-3 rounded-l-md border border-r-0 bg-muted text-muted-foreground text-xs whitespace-nowrap",children:"cards.relevelup.com/"}),e.jsx(ye,{value:y,onChange:F=>_(F.target.value.toLowerCase().replace(/[^a-z0-9-]/g,"-")),placeholder:"agent-name",className:"rounded-l-none"})]}),e.jsx(B,{variant:"outline",size:"sm",onClick:O,disabled:v||y===s.slug,className:"shrink-0",children:v?"Saving...":"Update"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Theme"}),e.jsxs(us,{value:w.theme,onValueChange:F=>S(z=>({...z,theme:F})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"standard",children:"✨ Standard (Modern Clean)"}),e.jsx(Ze,{value:"luxury",children:"🌙 Luxury (Dark & Gold)"}),e.jsx(Ze,{value:"bold",children:"🔥 Bold (Vibrant & Punchy)"}),e.jsx(Ze,{value:"classic",children:"📋 Classic (Professional)"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Title / Tagline"}),e.jsx(ye,{value:w.title,onChange:F=>S(z=>({...z,title:F.target.value})),placeholder:"e.g. Luxury Real Estate Specialist"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Shown below the agent's name on the card"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Positioning Statement"}),e.jsx(ye,{value:w.positioning_statement,onChange:F=>S(z=>({...z,positioning_statement:F.target.value})),placeholder:"Your home journey, handled with care."})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Bio"}),e.jsx(Ms,{value:w.bio,onChange:F=>S(z=>({...z,bio:F.target.value})),placeholder:"Short about me...",rows:3})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Review Snippet"}),e.jsx(ye,{value:w.review_snippet,onChange:F=>S(z=>({...z,review_snippet:F.target.value})),placeholder:"Best agent we've ever worked with..."})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Review Source URL"}),e.jsx(ye,{value:w.review_source_url,onChange:F=>S(z=>({...z,review_source_url:F.target.value})),placeholder:"https://g.page/your-business/review"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Booking URL (optional — if empty, shows lead form)"}),e.jsx(ye,{value:w.booking_url,onChange:F=>S(z=>({...z,booking_url:F.target.value})),placeholder:"https://calendly.com/your-link"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Custom CTA Label (optional)"}),e.jsx(ye,{value:w.custom_cta_label,onChange:F=>S(z=>({...z,custom_cta_label:F.target.value})),placeholder:"Book a Call"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Custom CTA URL (optional)"}),e.jsx(ye,{value:w.custom_cta_url,onChange:F=>S(z=>({...z,custom_cta_url:F.target.value})),placeholder:"https://example.com/landing"})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ne,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Brokerage Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ye,{value:w.brokerage_display_name,onChange:F=>S(z=>({...z,brokerage_display_name:F.target.value,brokerage_logo_url:""})),placeholder:"Brokerage name (or upload logo below)",disabled:!!w.brokerage_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[w.brokerage_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:w.brokerage_logo_url,alt:"Brokerage logo",style:{height:`${w.brokerage_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>S(F=>({...F,brokerage_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(_a,{className:"h-3.5 w-3.5"}),w.brokerage_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>D(F,"brokerage_logo_url")})]})]}),w.brokerage_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[w.brokerage_logo_size||56,"px"]})]}),e.jsx(jp,{value:[w.brokerage_logo_size||56],onValueChange:([F])=>S(z=>({...z,brokerage_logo_size:F})),min:24,max:120,step:4})]})]})]}),e.jsxs("div",{className:"space-y-3 p-3 rounded-lg bg-muted/30 border",children:[e.jsx(ne,{className:"text-xs font-semibold uppercase tracking-wider text-muted-foreground",children:"Team Branding"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ye,{value:w.team_name,onChange:F=>S(z=>({...z,team_name:F.target.value,team_logo_url:""})),placeholder:"Team name (or upload logo below)",disabled:!!w.team_logo_url}),e.jsxs("div",{className:"flex items-center gap-3",children:[w.team_logo_url&&e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:w.team_logo_url,alt:"Team logo",style:{height:`${w.team_logo_size||56}px`},className:"max-w-[200px] object-contain rounded border bg-white p-1"}),e.jsx("button",{onClick:()=>S(F=>({...F,team_logo_url:""})),className:"absolute -top-1.5 -right-1.5 h-5 w-5 rounded-full bg-destructive text-destructive-foreground text-xs flex items-center justify-center opacity-0 group-hover:opacity-100 transition-opacity",children:"×"})]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-md border text-xs font-medium hover:bg-muted transition-colors",children:[e.jsx(_a,{className:"h-3.5 w-3.5"}),w.team_logo_url?"Change Logo":"Upload Logo"]}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:F=>D(F,"team_logo_url")})]})]}),w.team_logo_url&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Logo Size"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[w.team_logo_size||56,"px"]})]}),e.jsx(jp,{value:[w.team_logo_size||56],onValueChange:([F])=>S(z=>({...z,team_logo_size:F})),min:24,max:120,step:4})]})]})]})]}),e.jsx(is,{value:"sections",className:"space-y-4 mt-4",children:[{key:"show_photo",label:"Show Photo",hint:"Photo is pulled from the agent's profile."},{key:"show_bio",label:"Show Bio"},{key:"show_credentials",label:"Show Credentials"},{key:"show_social_links",label:"Show Social Links"},{key:"show_save_contact",label:"Save Contact Button"},{key:"show_leave_review",label:"Leave Review Button"},{key:"show_refer_friend",label:"Refer a Friend Button"}].map(({key:F,label:z,hint:H})=>e.jsxs("div",{className:"flex items-center justify-between py-2",children:[e.jsxs("div",{children:[e.jsx(ne,{children:z}),H&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[H," ",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(jn,{checked:w[F],onCheckedChange:Z=>S(Y=>({...Y,[F]:Z}))})]},F))}),e.jsx(is,{value:"blocks",className:"mt-4",children:e.jsx(i2t,{cardId:s.id})}),e.jsx(is,{value:"analytics",className:"mt-4",children:a?e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-3 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.views}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Views"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.clicks}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Clicks"})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 text-center",children:[e.jsx("div",{className:"text-2xl font-bold",children:a.leads.length}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Leads"})]})})]}),a.leads.length>0&&e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold mb-2",children:"Recent Leads"}),e.jsx("div",{className:"space-y-2",children:a.leads.slice(0,5).map(F=>e.jsxs("div",{className:"text-sm p-2 bg-muted/50 rounded-lg",children:[e.jsx("span",{className:"font-medium",children:F.name}),F.phone&&e.jsxs("span",{className:"text-muted-foreground",children:[" · ",F.phone]}),F.intent&&e.jsx(Ue,{variant:"secondary",className:"ml-2 text-xs",children:F.intent})]},F.id))})]})]}):e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No analytics data yet"})})]}),e.jsx(B,{onClick:I,disabled:r.isPending,className:"w-full mt-4",children:r.isPending?"Saving...":"Save Changes"})]})}),e.jsx(G6e,{open:u,onClose:()=>h(!1),imageSrc:p,onCropComplete:E,aspectRatio:1})]})}const zL={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"},n8e={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 r8e(s=!0){return dt({queryKey:["marketplace-categories",s],queryFn:async()=>{let t=q.from("marketplace_categories").select("*").order("sort_order",{ascending:!0});s&&(t=t.eq("is_active",!0));const{data:n,error:r}=await t;if(r)throw r;return n}})}function kJs(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category created successfully")},onError:t=>{ae.error("Failed to create category: "+t.message)}})}function SJs(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category updated successfully")},onError:t=>{ae.error("Failed to update category: "+t.message)}})}function CJs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("marketplace_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-categories"]}),ae.success("Category deleted successfully")},onError:t=>{ae.error("Failed to delete category: "+t.message)}})}function w2t(s,t=!0){return dt({queryKey:["marketplace-products",s,t],queryFn:async()=>{let n=q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).order("sort_order",{ascending:!0});s&&(n=n.eq("category_id",s)),t&&(n=n.eq("is_active",!0));const{data:r,error:a}=await n;if(a)throw a;return r}})}function TJs(s){return dt({queryKey:["marketplace-product",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_products").select(` *, category:marketplace_categories(*), images:marketplace_product_images(*), video:marketplace_product_videos(*), variants:marketplace_product_variants(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function EJs(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_products").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product created successfully")},onError:t=>{ae.error("Failed to create product: "+t.message)}})}function AJs(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("marketplace_products").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.id]}),ae.success("Product updated successfully")},onError:t=>{ae.error("Failed to update product: "+t.message)}})}function MJs(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("marketplace_products").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["marketplace-products"]}),ae.success("Product deleted successfully")},onError:t=>{ae.error("Failed to delete product: "+t.message)}})}function IJs(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_images").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]})}})}function PJs(){const s=Kt();return yt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Image deleted successfully")},onError:t=>{ae.error("Failed to delete image: "+t.message)}})}function LJs(){const s=Kt();return yt({mutationFn:async({imageId:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_images").update({is_primary:!1}).eq("product_id",n);if(r)throw r;const{error:a}=await q.from("marketplace_product_images").update({is_primary:!0}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Primary image updated")},onError:t=>{ae.error("Failed to set primary image: "+t.message)}})}function DJs(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("marketplace_product_variants").insert([t]).select().single();if(r)throw r;return n},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.product_id]}),ae.success("Variant added successfully")}})}function RJs(){const s=Kt();return yt({mutationFn:async({id:t,productId:n})=>{const{error:r}=await q.from("marketplace_product_variants").delete().eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",t]}),ae.success("Variant deleted successfully")}})}function OJs(){const s=Kt();return yt({mutationFn:async({productId:t,videoUrl:n})=>{await q.from("marketplace_product_videos").delete().eq("product_id",t);const{data:r,error:a}=await q.from("marketplace_product_videos").insert({product_id:t,video_url:n}).select().single();if(a)throw a;return r},onSuccess:(t,n)=>{s.invalidateQueries({queryKey:["marketplace-products"]}),s.invalidateQueries({queryKey:["marketplace-product",n.productId]}),ae.success("Video updated successfully")}})}function FJs(s){const{isAdmin:t}=vs();return dt({queryKey:["marketplace-orders",s,t],queryFn:async()=>{let n=q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).order("created_at",{ascending:!1});const{data:r,error:a}=await n;if(a)throw a;if(t&&r){const i=[...new Set(r.map(c=>c.user_id))],{data:l}=await q.from("profiles").select("id, name, email").in("id",i),o=new Map((l==null?void 0:l.map(c=>[c.id,c]))||[]);return r.map(c=>({...c,user:o.get(c.user_id)}))}return r}})}function zJs(){const{user:s}=vs();return dt({queryKey:["my-marketplace-orders",s==null?void 0:s.id],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("user_id",s.id).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!(s!=null&&s.id)})}function BJs(s){return dt({queryKey:["marketplace-order",s],queryFn:async()=>{const{data:t,error:n}=await q.from("marketplace_orders").select(` *, items:marketplace_order_items(*), status_history:marketplace_order_status_history(*) `).eq("id",s).single();if(n)throw n;return t},enabled:!!s})}function $Js(){const s=Kt(),{user:t}=vs();return yt({mutationFn:async({orderId:n,status:r,notes:a,trackingNumber:i,trackingUrl:l,previousStatus:o})=>{const c={status:r};i!==void 0&&(c.tracking_number=i),l!==void 0&&(c.tracking_url=l);const{error:d}=await q.from("marketplace_orders").update(c).eq("id",n);if(d)throw d;const{error:u}=await q.from("marketplace_order_status_history").insert({order_id:n,status:r,notes:a,created_by:t==null?void 0:t.id});if(u)throw u;if(["shipped","in_production","processing","completed"].includes(r)&&r!==o)try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:n,notificationType:r==="shipped"?"shipped":"status_update",newStatus:r,trackingNumber:i,trackingUrl:l}})}catch(p){console.error("Failed to send notification email:",p)}},onSuccess:(n,r)=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",r.orderId]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Order status updated")},onError:n=>{ae.error("Failed to update order: "+n.message)}})}function UJs(){const s=Kt();return yt({mutationFn:async({itemId:t,proofUrl:n,proofNotes:r,orderId:a})=>{const{error:i}=await q.from("marketplace_order_items").update({proof_url:n,proof_notes:r,proof_status:"pending"}).eq("id",t);if(i)throw i;await q.from("marketplace_orders").update({status:"awaiting_proof_approval"}).eq("id",a);try{await q.functions.invoke("marketplace-order-notify",{body:{orderId:a,notificationType:"proof_ready"}})}catch(l){console.error("Failed to send proof notification:",l)}return a},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof uploaded & customer notified")}})}function qJs(){const s=Kt();return yt({mutationFn:async({itemId:t,orderId:n})=>{const{error:r}=await q.from("marketplace_order_items").update({proof_status:"approved"}).eq("id",t);if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof approved")}})}function VJs(){const s=Kt();return yt({mutationFn:async({itemId:t,orderId:n,reason:r})=>{const{error:a}=await q.from("marketplace_order_items").update({proof_status:"rejected",proof_notes:r}).eq("id",t);if(a)throw a;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["marketplace-orders"]}),s.invalidateQueries({queryKey:["marketplace-order",t]}),s.invalidateQueries({queryKey:["my-marketplace-orders"]}),ae.success("Proof rejected - please upload a new proof")}})}function HJs(){const{data:s,isLoading:t}=r8e(!1),n=kJs(),r=SJs(),a=CJs(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),h=()=>{u({name:"",description:"",image_url:"",sort_order:0,is_active:!0}),c(null)},p=_=>{c(_),u({name:_.name,description:_.description||"",image_url:_.image_url||"",sort_order:_.sort_order,is_active:_.is_active}),l(!0)},f=async _=>{_.preventDefault(),o?await r.mutateAsync({id:o.id,...d}):await n.mutateAsync(d),l(!1),h()},y=async _=>{confirm("Are you sure you want to delete this category?")&&await a.mutateAsync(_)};return t?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(_=>e.jsx(Ws,{className:"h-12 w-full"},_))})})]}):e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsx(Rt,{children:"Categories"}),e.jsxs(_s,{open:i,onOpenChange:_=>{l(_),_||h()},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Category"]})}),e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:o?"Edit Category":"Add Category"})}),e.jsxs("form",{onSubmit:f,className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"name",children:"Name"}),e.jsx(ye,{id:"name",value:d.name,onChange:_=>u({...d,name:_.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",value:d.description,onChange:_=>u({...d,description:_.target.value})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"image_url",children:"Image URL"}),e.jsx(ye,{id:"image_url",value:d.image_url,onChange:_=>u({...d,image_url:_.target.value}),placeholder:"https://..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(ye,{id:"sort_order",type:"number",value:d.sort_order,onChange:_=>u({...d,sort_order:parseInt(_.target.value)||0})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{id:"is_active",checked:d.is_active,onCheckedChange:_=>u({...d,is_active:_})}),e.jsx(ne,{htmlFor:"is_active",children:"Active"})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:n.isPending||r.isPending,children:o?"Update Category":"Create Category"})]})]})]})]}),e.jsx(Ee,{children:s&&s.length>0?e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{children:"Sort Order"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:s.map(_=>e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium",children:_.name}),e.jsx(ht,{className:"max-w-xs truncate",children:_.description}),e.jsx(ht,{children:_.sort_order}),e.jsx(ht,{children:e.jsx("span",{className:`px-2 py-1 rounded-full text-xs ${_.is_active?"bg-green-100 text-green-800":"bg-gray-100 text-gray-800"}`,children:_.is_active?"Active":"Inactive"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>p(_),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>y(_.id),disabled:a.isPending,children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},_.id))})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No categories yet. Create your first category to get started."})})]})}function GJs(){var le,ve;const{data:s,isLoading:t}=w2t(void 0,!1),{data:n}=r8e(!1),r=EJs(),a=AJs(),i=MJs(),l=IJs(),o=PJs(),c=LJs(),d=DJs(),u=RJs(),h=OJs(),[p,f]=N.useState(!1),[y,_]=N.useState(!1),[v,j]=N.useState(!1),[w,S]=N.useState(null),[A,E]=N.useState(null),[O,D]=N.useState(!1),[I,F]=N.useState({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),[z,H]=N.useState({name:"",price_adjustment:0}),[Z,Y]=N.useState(""),W=()=>{F({name:"",description:"",base_price:0,shipping_fee:0,category_id:"",allow_artwork_upload:!1,requires_proof_approval:!1,is_active:!0,sort_order:0}),S(null)},ee=ge=>{S(ge),F({name:ge.name,description:ge.description||"",base_price:Number(ge.base_price),shipping_fee:Number(ge.shipping_fee),category_id:ge.category_id||"",allow_artwork_upload:ge.allow_artwork_upload,requires_proof_approval:ge.requires_proof_approval,is_active:ge.is_active,sort_order:ge.sort_order}),f(!0)},se=async ge=>{ge.preventDefault();const Te={...I,category_id:I.category_id||null};w?await a.mutateAsync({id:w.id,...Te}):await r.mutateAsync(Te),f(!1),W()},oe=async ge=>{confirm("Are you sure you want to delete this product?")&&await i.mutateAsync(ge)},he=async ge=>{if(!A||!ge.target.files||ge.target.files.length===0)return;D(!0);const Te=ge.target.files[0],Ie=Te.name.split(".").pop(),Ce=`products/${A.id}/${Date.now()}.${Ie}`;try{const{error:Me}=await q.storage.from("marketplace").upload(Ce,Te);if(Me)throw Me;const{data:{publicUrl:Pe}}=q.storage.from("marketplace").getPublicUrl(Ce);await l.mutateAsync({product_id:A.id,image_url:Pe,is_primary:!A.images||A.images.length===0}),ae.success("Image uploaded successfully")}catch(Me){ae.error("Failed to upload image: "+Me.message)}finally{D(!1)}},ce=async ge=>{ge.preventDefault(),A&&(await d.mutateAsync({product_id:A.id,name:z.name,price_adjustment:z.price_adjustment}),H({name:"",price_adjustment:0}))},me=async()=>{!A||!Z||(await h.mutateAsync({productId:A.id,videoUrl:Z}),Y(""))};return t?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ee,{children:e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(ge=>e.jsx(Ws,{className:"h-64 w-full"},ge))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsx(Rt,{children:"Products"}),e.jsxs(_s,{open:p,onOpenChange:ge=>{f(ge),ge||W()},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Product"]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:w?"Edit Product":"Add Product"})}),e.jsxs("form",{onSubmit:se,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(ne,{htmlFor:"name",children:"Product Name"}),e.jsx(ye,{id:"name",value:I.name,onChange:ge=>F({...I,name:ge.target.value}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"category",children:"Category"}),e.jsxs(us,{value:I.category_id,onValueChange:ge=>F({...I,category_id:ge}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select category"})}),e.jsx(cs,{children:n==null?void 0:n.map(ge=>e.jsx(Ze,{value:ge.id,children:ge.name},ge.id))})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"description",children:"Description"}),e.jsx(Ms,{id:"description",value:I.description,onChange:ge=>F({...I,description:ge.target.value}),rows:4})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"base_price",children:"Base Price ($)"}),e.jsx(ye,{id:"base_price",type:"number",step:"0.01",min:"0",value:I.base_price,onChange:ge=>F({...I,base_price:parseFloat(ge.target.value)||0}),required:!0})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"shipping_fee",children:"Shipping Fee ($)"}),e.jsx(ye,{id:"shipping_fee",type:"number",step:"0.01",min:"0",value:I.shipping_fee,onChange:ge=>F({...I,shipping_fee:parseFloat(ge.target.value)||0})})]})]}),e.jsx("div",{className:"grid grid-cols-2 gap-4",children:e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"sort_order",children:"Sort Order"}),e.jsx(ye,{id:"sort_order",type:"number",value:I.sort_order,onChange:ge=>F({...I,sort_order:parseInt(ge.target.value)||0})})]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{id:"allow_artwork_upload",checked:I.allow_artwork_upload,onCheckedChange:ge=>F({...I,allow_artwork_upload:ge})}),e.jsx(ne,{htmlFor:"allow_artwork_upload",children:"Allow customer to upload artwork"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{id:"requires_proof_approval",checked:I.requires_proof_approval,onCheckedChange:ge=>F({...I,requires_proof_approval:ge})}),e.jsx(ne,{htmlFor:"requires_proof_approval",children:"Requires proof approval"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{id:"is_active",checked:I.is_active,onCheckedChange:ge=>F({...I,is_active:ge})}),e.jsx(ne,{htmlFor:"is_active",children:"Active"})]})]}),e.jsx(B,{type:"submit",className:"w-full",disabled:r.isPending||a.isPending,children:w?"Update Product":"Create Product"})]})]})]})]}),e.jsx(Ee,{children:s&&s.length>0?e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:s.map(ge=>{var Te,Ie;return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"aspect-video bg-muted relative",children:[ge.images&&ge.images.length>0?e.jsx("img",{src:((Te=ge.images.find(Ce=>Ce.is_primary))==null?void 0:Te.image_url)||ge.images[0].image_url,alt:ge.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full text-muted-foreground",children:"No image"}),!ge.is_active&&e.jsx(Ue,{variant:"secondary",className:"absolute top-2 right-2",children:"Inactive"})]}),e.jsxs(Ee,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1",children:ge.name}),e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:((Ie=ge.category)==null?void 0:Ie.name)||"No category"}),e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("span",{className:"font-bold",children:["$",Number(ge.base_price).toFixed(2)]}),Number(ge.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground",children:["+$",Number(ge.shipping_fee).toFixed(2)," shipping"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-1 mb-3",children:[ge.allow_artwork_upload&&e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Artwork Upload"}),ge.requires_proof_approval&&e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Proof Required"}),ge.variants&&ge.variants.length>0&&e.jsxs(Ue,{variant:"outline",className:"text-xs",children:[ge.variants.length," Variants"]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ee(ge),children:[e.jsx(ya,{className:"h-3 w-3 mr-1"}),"Edit"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{E(ge),_(!0)},children:[e.jsx(ty,{className:"h-3 w-3 mr-1"}),"Images"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{E(ge),j(!0)},children:[e.jsx(oh,{className:"h-3 w-3 mr-1"}),"Variants"]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>oe(ge.id),children:e.jsx(_n,{className:"h-3 w-3 text-destructive"})})]})]})]},ge.id)})}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No products yet. Create your first product to get started."})})]}),e.jsx(_s,{open:y,onOpenChange:_,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(ws,{children:["Manage Images - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-3 gap-4",children:(le=A==null?void 0:A.images)==null?void 0:le.map(ge=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:ge.image_url,alt:"",className:"w-full aspect-square object-cover rounded-lg"}),ge.is_primary&&e.jsx(Ue,{className:"absolute top-2 left-2",variant:"default",children:"Primary"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[!ge.is_primary&&e.jsx(B,{variant:"secondary",size:"icon",onClick:async()=>{var Te;await c.mutateAsync({imageId:ge.id,productId:A.id}),E({...A,images:(Te=A.images)==null?void 0:Te.map(Ie=>({...Ie,is_primary:Ie.id===ge.id}))})},disabled:c.isPending,title:"Set as primary",children:e.jsx(oa,{className:"h-4 w-4"})}),e.jsx(B,{variant:"destructive",size:"icon",onClick:async()=>{var Ie;await o.mutateAsync({id:ge.id,productId:A.id});const Te=s==null?void 0:s.find(Ce=>Ce.id===A.id);Te&&E({...Te,images:(Ie=Te.images)==null?void 0:Ie.filter(Ce=>Ce.id!==ge.id)})},disabled:o.isPending,children:e.jsx(_n,{className:"h-4 w-4"})})]})]},ge.id))}),e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6 text-center",children:[e.jsx("input",{type:"file",accept:"image/*",onChange:he,className:"hidden",id:"image-upload",disabled:O}),e.jsxs("label",{htmlFor:"image-upload",className:"cursor-pointer",children:[e.jsx(ty,{className:"h-8 w-8 mx-auto mb-2 text-muted-foreground"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:O?"Uploading...":"Click to upload an image"})]})]}),e.jsxs("div",{className:"border-t pt-4 mt-4",children:[e.jsx(ne,{children:"Product Video (optional)"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(ye,{placeholder:"Enter video URL (YouTube, Vimeo, etc.)",value:Z,onChange:ge=>Y(ge.target.value)}),e.jsxs(B,{onClick:me,disabled:!Z,children:[e.jsx(fr,{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(_s,{open:v,onOpenChange:j,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsxs(ws,{children:["Manage Variants - ",A==null?void 0:A.name]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("form",{onSubmit:ce,className:"flex gap-2",children:[e.jsx(ye,{placeholder:"Variant name (e.g., 500 count)",value:z.name,onChange:ge=>H({...z,name:ge.target.value}),required:!0}),e.jsx(ye,{type:"number",step:"0.01",placeholder:"Price adj.",value:z.price_adjustment,onChange:ge=>H({...z,price_adjustment:parseFloat(ge.target.value)||0}),className:"w-32"}),e.jsx(B,{type:"submit",children:"Add"})]}),e.jsxs("div",{className:"space-y-2",children:[(ve=A==null?void 0:A.variants)==null?void 0:ve.map(ge=>e.jsxs("div",{className:"flex items-center justify-between p-3 bg-muted rounded-lg",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-medium",children:ge.name}),e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:[Number(ge.price_adjustment)>=0?"+":"","$",Number(ge.price_adjustment).toFixed(2)]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>u.mutateAsync({id:ge.id,productId:A.id}),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]},ge.id)),(!(A!=null&&A.variants)||A.variants.length===0)&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:'No variants yet. Add variants like "250 count", "500 count", etc.'})]})]})]})})]})}const WJs=["pending_payment","order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed","cancelled","refunded"];function KJs(){var _,v,j;const{data:s,isLoading:t}=FJs(),n=$Js(),r=UJs(),[a,i]=N.useState(null),[l,o]=N.useState(!1),[c,d]=N.useState({status:"",notes:"",trackingNumber:"",trackingUrl:""}),[u,h]=N.useState(!1),p=w=>{i(w),d({status:w.status,notes:"",trackingNumber:w.tracking_number||"",trackingUrl:w.tracking_url||""}),o(!0)},f=async()=>{a&&(await n.mutateAsync({orderId:a.id,status:c.status,notes:c.notes,trackingNumber:c.trackingNumber,trackingUrl:c.trackingUrl,previousStatus:a.status}),o(!1))},y=async(w,S)=>{if(!a||!w.target.files||w.target.files.length===0)return;h(!0);const A=w.target.files[0],E=A.name.split(".").pop(),O=`proofs/${a.id}/${S}/${Date.now()}.${E}`;try{const{error:D}=await q.storage.from("marketplace").upload(O,A);if(D)throw D;const{data:{publicUrl:I}}=q.storage.from("marketplace").getPublicUrl(O);await r.mutateAsync({itemId:S,proofUrl:I,orderId:a.id}),ae.success("Proof uploaded successfully")}catch(D){ae.error("Failed to upload proof: "+D.message)}finally{h(!1)}};return t?e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Ws,{className:"h-8 w-48"})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(w=>e.jsx(Ws,{className:"h-16 w-full"},w))})})]}):e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Orders"})}),e.jsx(Ee,{children:s&&s.length>0?e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Order #"}),e.jsx(Tt,{children:"Customer"}),e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Total"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:s.map(w=>{var S,A;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-mono",children:w.order_number}),e.jsx(ht,{children:e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((S=w.user)==null?void 0:S.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(A=w.user)==null?void 0:A.email})]})}),e.jsx(ht,{children:Ss(new Date(w.created_at),"MMM d, yyyy")}),e.jsxs(ht,{className:"font-bold",children:["$",Number(w.total).toFixed(2)]}),e.jsx(ht,{children:e.jsx(Ue,{className:n8e[w.status],children:zL[w.status]})}),e.jsx(ht,{className:"text-right",children:e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>p(w),children:[e.jsx(Sr,{className:"h-4 w-4 mr-1"}),"View"]})})]},w.id)})})]}):e.jsx("div",{className:"text-center py-8 text-muted-foreground",children:"No orders yet."})})]}),e.jsx(_s,{open:l,onOpenChange:o,children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(ws,{children:["Order ",a==null?void 0:a.order_number]})}),a&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Customer"}),e.jsx("p",{children:(_=a.user)==null?void 0:_.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(v=a.user)==null?void 0:v.email})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Shipping Address"}),e.jsx("p",{children:a.shipping_name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[a.shipping_address,e.jsx("br",{}),a.shipping_city,", ",a.shipping_state," ",a.shipping_zip]})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-medium mb-2",children:"Order Items"}),e.jsx("div",{className:"space-y-3",children:(j=a.items)==null?void 0:j.map(w=>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:w.product_name}),w.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:w.variant_name})]}),e.jsxs("p",{className:"font-bold",children:["$",Number(w.unit_price).toFixed(2)," x ",w.quantity]})]}),w.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:w.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(Ue,{variant:w.proof_status==="approved"?"default":"secondary",children:w.proof_status||"No proof yet"})]}),w.proof_url?e.jsx("a",{href:w.proof_url,target:"_blank",rel:"noopener noreferrer",className:"text-primary hover:underline text-sm",children:"View Proof"}):e.jsxs("div",{children:[e.jsx("input",{type:"file",accept:"image/*,.pdf",onChange:S=>y(S,w.id),className:"hidden",id:`proof-${w.id}`,disabled:u}),e.jsx("label",{htmlFor:`proof-${w.id}`,children:e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-4 w-4 mr-1"}),u?"Uploading...":"Upload Proof"]})})})]})]})})]},w.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(ne,{children:"Status"}),e.jsxs(us,{value:c.status,onValueChange:w=>d({...c,status:w}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:WJs.map(w=>e.jsx(Ze,{value:w,children:zL[w]},w))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Tracking Number"}),e.jsx(ye,{value:c.trackingNumber,onChange:w=>d({...c,trackingNumber:w.target.value}),placeholder:"Enter tracking number"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Tracking URL"}),e.jsx(ye,{value:c.trackingUrl,onChange:w=>d({...c,trackingUrl:w.target.value}),placeholder:"https://..."})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Notes (optional)"}),e.jsx(Ms,{value:c.notes,onChange:w=>d({...c,notes:w.target.value}),placeholder:"Add a note about this status change..."})]}),e.jsxs(B,{onClick:f,disabled:n.isPending,className:"w-full",children:[e.jsx(Ec,{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(w=>e.jsxs("div",{className:"flex justify-between text-sm p-2 bg-muted rounded",children:[e.jsxs("div",{children:[e.jsx(Ue,{variant:"outline",children:zL[w.status]}),w.notes&&e.jsx("p",{className:"text-muted-foreground mt-1",children:w.notes})]}),e.jsx("span",{className:"text-muted-foreground",children:Ss(new Date(w.created_at),"MMM d, h:mm a")})]},w.id))})]})]})]})})]})}function YJs(){const[s,t]=N.useState("products"),n=Ln();return e.jsx(Cs,{title:"Marketplace Management",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Marketplace Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage products, categories, and orders"})]}),e.jsxs(B,{variant:"outline",onClick:()=>n("/marketplace"),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"View Store"]})]}),e.jsxs(Fr,{value:s,onValueChange:t,children:[e.jsxs(Rr,{className:"grid w-full grid-cols-3",children:[e.jsxs(Zt,{value:"products",className:"flex items-center gap-2",children:[e.jsx(Ec,{className:"h-4 w-4"}),"Products"]}),e.jsxs(Zt,{value:"categories",className:"flex items-center gap-2",children:[e.jsx(pf,{className:"h-4 w-4"}),"Categories"]}),e.jsxs(Zt,{value:"orders",className:"flex items-center gap-2",children:[e.jsx(Dg,{className:"h-4 w-4"}),"Orders"]})]}),e.jsx(is,{value:"products",children:e.jsx(GJs,{})}),e.jsx(is,{value:"categories",children:e.jsx(HJs,{})}),e.jsx(is,{value:"orders",children:e.jsx(KJs,{})})]})]})})}function j2t(){return dt({queryKey:["reward-categories"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_categories").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s}})}function ZJs(s){return dt({queryKey:["reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).order("created_at",{ascending:!1});const{data:n,error:r}=await t;if(r)throw r;return n}})}function QJs(s){return dt({queryKey:["active-reward-items",s],queryFn:async()=>{let t=q.from("reward_store_items").select(` *, category:reward_store_categories(*) `).eq("is_active",!0).order("created_at",{ascending:!1});s&&(t=t.eq("category_id",s));const{data:n,error:r}=await t;if(r)throw r;return n}})}function XJs(s){return dt({queryKey:["user-purchases",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).eq("user_id",s).order("purchased_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function JJs(){return dt({queryKey:["all-reward-purchases"],queryFn:async()=>{const{data:s,error:t}=await q.from("reward_store_purchases").select(` *, item:reward_store_items(*) `).order("purchased_at",{ascending:!1});if(t)throw t;if(!s||s.length===0)return[];const n=[...new Set(s.map(l=>l.user_id))],{data:r,error:a}=await q.from("profiles").select("id, name, email").in("id",n);if(a)throw a;const i=new Map((r==null?void 0:r.map(l=>[l.id,l]))||[]);return s.map(l=>({...l,user:i.get(l.user_id)||null}))}})}function een(s){return dt({queryKey:["spendable-points",s],queryFn:async()=>{if(!s)return 0;const{data:t,error:n}=await q.from("agent_attendance_stats").select("spendable_points").eq("user_id",s).single();if(n&&n.code!=="PGRST116")throw n;return(t==null?void 0:t.spendable_points)||0},enabled:!!s})}function ten(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("purchase_reward_item",{p_item_id:t});if(r)throw r;const a=n;if(!a.success)throw new Error(a.error||"Purchase failed");return a},onSuccess:()=>{s.invalidateQueries({queryKey:["user-purchases"]}),s.invalidateQueries({queryKey:["spendable-points"]}),s.invalidateQueries({queryKey:["active-reward-items"]}),s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["homereel-credits"]})}})}function sen(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_categories").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function nen(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_categories").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function ren(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("reward_store_categories").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-categories"]})}})}function aen(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("reward_store_items").insert([t]).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function ien(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("reward_store_items").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function oen(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("reward_store_items").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["reward-items"]}),s.invalidateQueries({queryKey:["active-reward-items"]})}})}function len(s){const t=s.match(/\/storage\/v1\/object\/public\/([^/]+)\/(.+)$/);return t?{bucket:t[1],path:t[2]}:null}async function SNe(s,t){const n=len(s);if(n)try{const{data:r,error:a}=await q.storage.from(n.bucket).download(n.path);if(a){console.error("Error downloading file:",a),ae.error("Failed to download file");return}const i=URL.createObjectURL(r),l=document.createElement("a");l.href=i,l.download=t||n.path.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("Download error:",r),ae.error("Failed to download file")}else try{const a=await(await fetch(s)).blob(),i=URL.createObjectURL(a),l=document.createElement("a");l.href=i,l.download=t||s.split("/").pop()||"download",document.body.appendChild(l),l.click(),document.body.removeChild(l),setTimeout(()=>URL.revokeObjectURL(i),100)}catch(r){console.error("External download error:",r),ae.error("Failed to download file")}}function N2t(){return dt({queryKey:["point-reward-settings"],queryFn:async()=>{const{data:s,error:t}=await q.from("point_reward_settings").select("*").order("action_name");if(t)throw t;return s}})}function cen(){const s=Kt();return yt({mutationFn:async({id:t,points:n,is_active:r})=>{const a={points:n};r!==void 0&&(a.is_active=r);const{data:i,error:l}=await q.from("point_reward_settings").update(a).eq("id",t).select().single();if(l)throw l;return i},onSuccess:()=>{s.invalidateQueries({queryKey:["point-reward-settings"]})}})}function den(){const{user:s}=vs(),[t,n]=N.useState("items"),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(null),[_,v]=N.useState(!1),[j,w]=N.useState(null),[S,A]=N.useState(""),[E,O]=N.useState(""),[D,I]=N.useState(null),[F,z]=N.useState(""),[H,Z]=N.useState("file"),[Y,W]=N.useState(""),[ee,se]=N.useState(""),[oe,he]=N.useState(""),[ce,me]=N.useState(!0),[le,ve]=N.useState(null),[ge,Te]=N.useState(!1),[Ie,Ce]=N.useState(!1),Me=N.useRef(null),Pe=N.useRef(null),{data:Re,isLoading:Ae}=j2t(),{data:Be,isLoading:we}=ZJs(),{data:Je,isLoading:ke}=JJs(),{data:it,isLoading:je}=N2t(),He=sen(),$e=nen(),Ke=ren(),Ge=aen(),rt=ien(),tt=oen(),at=cen(),[Ye,ut]=N.useState({}),_t=gt=>{gt?(l(gt),c(gt.name),u(gt.description||""),p(gt.icon||"")):(l(null),c(""),u(""),p("")),a(!0)},bt=async()=>{if(!o.trim()){ae.error("Please enter a category name");return}try{i?(await $e.mutateAsync({id:i.id,name:o,description:d||null,icon:h||null}),ae.success("Category updated successfully")):(await He.mutateAsync({name:o,description:d||null,icon:h||null,sort_order:((Re==null?void 0:Re.length)||0)+1}),ae.success("Category created successfully")),a(!1)}catch(gt){console.error("Error saving category:",gt),ae.error("Failed to save category")}},$t=async()=>{if(f)try{await Ke.mutateAsync(f),ae.success("Category deleted successfully"),y(null)}catch(gt){console.error("Error deleting category:",gt),ae.error("Failed to delete category")}},Yt=gt=>{var zt;gt?(w(gt),A(gt.name),O(gt.description||""),I(gt.category_id),z(gt.points_cost.toString()),Z(gt.item_type),W(gt.file_url||""),se(gt.preview_image_url||""),he(((zt=gt.max_quantity)==null?void 0:zt.toString())||""),me(gt.is_active)):(w(null),A(""),O(""),I(null),z(""),Z("file"),W(""),se(""),he(""),me(!0)),v(!0)},Ds=async(gt,zt)=>{zt==="file"?Te(!0):Ce(!0);try{const As=gt.name.split(".").pop(),Xt=`${Date.now()}-${Math.random().toString(36).substring(7)}.${As}`,Qs=`${zt==="file"?"items":"previews"}/${Xt}`,{error:ks}=await q.storage.from("reward-store").upload(Qs,gt);if(ks)throw ks;const{data:{publicUrl:$s}}=q.storage.from("reward-store").getPublicUrl(Qs);zt==="file"?W($s):se($s),ae.success("File uploaded successfully")}catch(As){console.error("Error uploading file:",As),ae.error("Failed to upload file")}finally{zt==="file"?Te(!1):Ce(!1)}},Ls=async()=>{if(!S.trim()){ae.error("Please enter an item name");return}if(!F||parseInt(F)<0){ae.error("Please enter a valid points cost");return}try{const gt={name:S,description:E||null,category_id:D,points_cost:parseInt(F),item_type:H,file_url:Y||null,preview_image_url:ee||null,max_quantity:oe?parseInt(oe):null,current_quantity:oe?parseInt(oe):null,is_active:ce,created_by:s==null?void 0:s.id};j?(await rt.mutateAsync({id:j.id,...gt,current_quantity:j.max_quantity!==(oe?parseInt(oe):null)?oe?parseInt(oe):null:j.current_quantity}),ae.success("Item updated successfully")):(await Ge.mutateAsync(gt),ae.success("Item created successfully")),v(!1)}catch(gt){console.error("Error saving item:",gt),ae.error("Failed to save item")}},xs=async()=>{if(le)try{await tt.mutateAsync(le),ae.success("Item deleted successfully"),ve(null)}catch(gt){console.error("Error deleting item:",gt),ae.error("Failed to delete item")}},Lt=async(gt,zt)=>{const As=Ye[gt];if(As===void 0||As===zt.toString())return;const Xt=parseInt(As);if(isNaN(Xt)||Xt<0){ae.error("Please enter a valid positive number");return}try{await at.mutateAsync({id:gt,points:Xt}),ae.success("Points updated successfully"),ut(Qs=>{const ks={...Qs};return delete ks[gt],ks})}catch(Qs){console.error("Error updating points:",Qs),ae.error("Failed to update points")}};return Ae||we||ke||je?e.jsx(Cs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-8 w-64"}),e.jsx(Ws,{className:"h-96"})]})}):e.jsxs(Cs,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Reward Store Management"}),e.jsx("p",{className:"text-muted-foreground",children:"Manage store items that agents can purchase with their points"})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(Ec,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Total Items"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Be==null?void 0:Be.length)||0}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Be==null?void 0:Be.filter(gt=>gt.is_active).length)||0," active"]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(pf,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Categories"})]}),e.jsx("p",{className:"text-2xl font-bold",children:(Re==null?void 0:Re.length)||0})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground mb-1",children:[e.jsx(oa,{className:"h-4 w-4"}),e.jsx("span",{className:"text-xs font-medium",children:"Avg. Cost"})]}),e.jsxs("p",{className:"text-2xl font-bold",children:[Be&&Be.length>0?Math.round(Be.reduce((gt,zt)=>gt+zt.points_cost,0)/Be.length):0," pts"]})]})})]}),e.jsxs(Fr,{value:t,onValueChange:n,children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"items",children:"Items"}),e.jsx(Zt,{value:"categories",children:"Categories"}),e.jsx(Zt,{value:"purchases",children:"Purchases"}),e.jsx(Zt,{value:"point-settings",children:"Point Settings"})]}),e.jsx(is,{value:"items",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Store Items"}),e.jsx(Vn,{children:"Manage rewards that agents can purchase"})]}),e.jsxs(B,{onClick:()=>Yt(),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Item"]})]}),e.jsx(Ee,{children:!Be||Be.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Oi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No items yet. Add your first reward item!"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Item"}),e.jsx(Tt,{children:"Category"}),e.jsx(Tt,{className:"text-center",children:"Cost"}),e.jsx(Tt,{className:"text-center",children:"Type"}),e.jsx(Tt,{className:"text-center",children:"Quantity"}),e.jsx(Tt,{className:"text-center",children:"Status"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:Be.map(gt=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[gt.preview_image_url?e.jsx("img",{src:gt.preview_image_url,alt:gt.name,className:"h-10 w-10 rounded object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded bg-muted flex items-center justify-center",children:e.jsx(Oi,{className:"h-5 w-5 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:gt.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-1",children:gt.description||"No description"})]})]})}),e.jsx(ht,{children:gt.category?e.jsx(Ue,{variant:"outline",children:gt.category.name}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ht,{className:"text-center",children:e.jsxs(Ue,{variant:"secondary",className:"font-bold",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),gt.points_cost]})}),e.jsx(ht,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[gt.item_type==="file"?e.jsx(br,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(Yo,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-xs capitalize",children:gt.item_type})]})}),e.jsx(ht,{className:"text-center",children:gt.max_quantity!==null?e.jsxs("span",{className:gt.current_quantity===0?"text-red-500":"",children:[gt.current_quantity,"/",gt.max_quantity]}):e.jsx("span",{className:"text-muted-foreground",children:"Unlimited"})}),e.jsx(ht,{className:"text-center",children:e.jsx(Ue,{variant:gt.is_active?"default":"secondary",children:gt.is_active?"Active":"Inactive"})}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>Yt(gt),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>ve(gt.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},gt.id))})]})})]})}),e.jsx(is,{value:"categories",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Categories"}),e.jsx(Vn,{children:"Organize your store items into categories"})]}),e.jsxs(B,{onClick:()=>_t(),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add Category"]})]}),e.jsx(Ee,{children:!Re||Re.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(pf,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No categories yet. Add your first category!"})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Name"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"text-center",children:"Items"}),e.jsx(Tt,{className:"text-right",children:"Actions"})]})}),e.jsx(da,{children:Re.map(gt=>e.jsxs(Hs,{children:[e.jsxs(ht,{className:"font-medium",children:[gt.icon&&e.jsx("span",{className:"mr-2",children:gt.icon}),gt.name]}),e.jsx(ht,{className:"text-muted-foreground",children:gt.description||"—"}),e.jsx(ht,{className:"text-center",children:(Be==null?void 0:Be.filter(zt=>zt.category_id===gt.id).length)||0}),e.jsx(ht,{className:"text-right",children:e.jsxs("div",{className:"flex items-center justify-end gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>_t(gt),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>y(gt.id),children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})})]})})]},gt.id))})]})})]})}),e.jsx(is,{value:"purchases",className:"mt-4",children:e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Dg,{className:"h-5 w-5"}),"Purchase History"]}),e.jsx(Vn,{children:"View all reward redemptions by agents"})]}),e.jsx(Ee,{children:!Je||Je.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Dg,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No purchases yet."})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Date"}),e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{children:"Item"}),e.jsx(Tt,{className:"text-center",children:"Points Spent"})]})}),e.jsx(da,{children:Je.map(gt=>{var zt,As,Xt,Qs;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"text-muted-foreground",children:Ss(new Date(gt.purchased_at),"MMM d, yyyy 'at' h:mm a")}),e.jsx(ht,{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(Wi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:((zt=gt.user)==null?void 0:zt.name)||"Unknown"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:((As=gt.user)==null?void 0:As.email)||"—"})]})]})}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[(Xt=gt.item)!=null&&Xt.preview_image_url?e.jsx("img",{src:gt.item.preview_image_url,alt:gt.item.name,className:"h-8 w-8 rounded object-cover"}):e.jsx("div",{className:"h-8 w-8 rounded bg-muted flex items-center justify-center",children:e.jsx(Oi,{className:"h-4 w-4 text-muted-foreground"})}),e.jsx("span",{children:((Qs=gt.item)==null?void 0:Qs.name)||"Deleted item"})]})}),e.jsx(ht,{className:"text-center",children:e.jsxs(Ue,{variant:"secondary",className:"font-bold",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),gt.points_spent]})})]},gt.id)})})]})})]})})]})]}),e.jsx(_s,{open:r,onOpenChange:a,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:i?"Edit Category":"Add Category"}),e.jsx(Jn,{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(ne,{htmlFor:"categoryName",children:"Name"}),e.jsx(ye,{id:"categoryName",value:o,onChange:gt=>c(gt.target.value),placeholder:"e.g., Templates, Resources"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"categoryDescription",children:"Description"}),e.jsx(Ms,{id:"categoryDescription",value:d,onChange:gt=>u(gt.target.value),placeholder:"Optional description..."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"categoryIcon",children:"Icon (emoji)"}),e.jsx(ye,{id:"categoryIcon",value:h,onChange:gt=>p(gt.target.value),placeholder:"e.g., 📄, 🎁"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{onClick:bt,disabled:He.isPending||$e.isPending,children:He.isPending||$e.isPending?"Saving...":"Save"})]})]})}),e.jsx(_s,{open:_,onOpenChange:v,children:e.jsxs(bs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:j?"Edit Item":"Add Item"}),e.jsx(Jn,{children:j?"Update the item details":"Create a new reward item for agents to purchase"})]}),e.jsxs("div",{className:"space-y-4 py-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"itemName",children:"Name *"}),e.jsx(ye,{id:"itemName",value:S,onChange:gt=>A(gt.target.value),placeholder:"e.g., Premium Template Pack"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"itemDescription",children:"Description"}),e.jsx(Ms,{id:"itemDescription",value:E,onChange:gt=>O(gt.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(ne,{htmlFor:"itemCategory",children:"Category"}),e.jsxs(us,{value:D||"none",onValueChange:gt=>I(gt==="none"?null:gt),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select category"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No category"}),Re==null?void 0:Re.map(gt=>e.jsxs(Ze,{value:gt.id,children:[gt.icon&&`${gt.icon} `,gt.name]},gt.id))]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"itemPointsCost",children:"Points Cost *"}),e.jsx(ye,{id:"itemPointsCost",type:"number",min:"0",value:F,onChange:gt=>z(gt.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(ne,{htmlFor:"itemType",children:"Type"}),e.jsxs(us,{value:H,onValueChange:Z,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"file",children:"File Download"}),e.jsx(Ze,{value:"link",children:"External Link"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"itemMaxQuantity",children:"Max Quantity"}),e.jsx(ye,{id:"itemMaxQuantity",type:"number",min:"1",value:oe,onChange:gt=>he(gt.target.value),placeholder:"Leave empty for unlimited"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"File / Link URL"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:Y,onChange:gt=>W(gt.target.value),placeholder:H==="file"?"Upload a file or paste URL":"Paste external link"}),H==="file"&&e.jsxs(e.Fragment,{children:[e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var gt;return(gt=Me.current)==null?void 0:gt.click()},disabled:ge,children:e.jsx(_a,{className:"h-4 w-4"})}),e.jsx("input",{ref:Me,type:"file",className:"hidden",onChange:gt=>{var As;const zt=(As=gt.target.files)==null?void 0:As[0];zt&&Ds(zt,"file")}})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Preview Image"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:ee,onChange:gt=>se(gt.target.value),placeholder:"Upload an image or paste URL"}),e.jsx(B,{type:"button",variant:"outline",size:"icon",onClick:()=>{var gt;return(gt=Pe.current)==null?void 0:gt.click()},disabled:Ie,children:e.jsx(Xo,{className:"h-4 w-4"})}),e.jsx("input",{ref:Pe,type:"file",accept:"image/*",className:"hidden",onChange:gt=>{var As;const zt=(As=gt.target.files)==null?void 0:As[0];zt&&Ds(zt,"preview")}})]}),ee&&e.jsx("img",{src:ee,alt:"Preview",className:"mt-2 h-24 rounded object-cover"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{id:"itemIsActive",checked:ce,onCheckedChange:me}),e.jsx(ne,{htmlFor:"itemIsActive",children:"Active (visible to agents)"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>v(!1),children:"Cancel"}),e.jsx(B,{onClick:Ls,disabled:Ge.isPending||rt.isPending,children:Ge.isPending||rt.isPending?"Saving...":"Save"})]})]})}),e.jsx(Oo,{open:!!f,onOpenChange:()=>y(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Category"}),e.jsx(Mo,{children:"Are you sure you want to delete this category? Items in this category will become uncategorized."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:$t,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),e.jsx(Oo,{open:!!le,onOpenChange:()=>ve(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Item"}),e.jsx(Mo,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:xs,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Delete"})]})]})}),t==="point-settings"&&e.jsxs(fe,{className:"mt-4",children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ko,{className:"h-5 w-5"}),e.jsxs("div",{children:[e.jsx(Rt,{children:"Point Reward Settings"}),e.jsx(Vn,{children:"Configure how many points agents earn for various actions. Adjust these values to run double-points promotions."})]})]})}),e.jsx(Ee,{children:!it||it.length===0?e.jsxs("div",{className:"text-center py-8 text-muted-foreground",children:[e.jsx(Ko,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No point settings configured."})]}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Action"}),e.jsx(Tt,{children:"Description"}),e.jsx(Tt,{className:"text-center w-32",children:"Points"}),e.jsx(Tt,{className:"text-right w-24",children:"Save"})]})}),e.jsx(da,{children:it.map(gt=>e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsx("p",{className:"font-medium",children:gt.action_name})}),e.jsx(ht,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:gt.description})}),e.jsx(ht,{className:"text-center",children:e.jsx(ye,{type:"number",min:"0",className:"w-20 mx-auto text-center",value:Ye[gt.id]??gt.points.toString(),onChange:zt=>ut(As=>({...As,[gt.id]:zt.target.value}))})}),e.jsx(ht,{className:"text-right",children:e.jsx(B,{size:"sm",variant:"outline",disabled:Ye[gt.id]===void 0||Ye[gt.id]===gt.points.toString()||at.isPending,onClick:()=>Lt(gt.id,gt.points),children:e.jsx(Jo,{className:"h-4 w-4"})})})]},gt.id))})]})})]})]})}const JQe=()=>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"})]}),eXe=[{value:"template",label:"Templates"},{value:"brand",label:"Brand Assets"},{value:"listing",label:"Listing Assets"},{value:"social",label:"Social Media"},{value:"general",label:"General"}];function uen(){const s=Kt(),[t,n]=N.useState(!1),[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""}),{data:d,isLoading:u}=dt({queryKey:["canva-integration"],queryFn:async()=>{const{data:w,error:S}=await q.from("canva_integration").select("*").eq("is_active",!0).maybeSingle();if(S)throw S;return w}}),{data:h}=dt({queryKey:["brokerages-list"],queryFn:async()=>{const{data:w,error:S}=await q.from("brokerages").select("id, name").order("name");if(S)throw S;return w}}),{data:p}=dt({queryKey:["canva-brokerage-folders"],queryFn:async()=>{const{data:w,error:S}=await q.from("canva_brokerage_folders").select("*, brokerages(name)").order("sort_order");if(S)throw S;return w}}),f=async()=>{var w;n(!0);try{const{data:S}=await q.auth.getSession(),A=(w=S==null?void 0:S.session)==null?void 0:w.access_token;if(!A)throw new Error("Not authenticated");const D=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"get_auth_url"})}),I=await D.json();if(!D.ok||I!=null&&I.error)throw new Error((I==null?void 0:I.error)||"Failed to get authorization URL");if(I!=null&&I.authUrl){localStorage.setItem("canva_code_verifier",I.codeVerifier),localStorage.setItem("canva_oauth_state",I.state);const F=window.open(I.authUrl,"canva-oauth","width=600,height=700,scrollbars=yes,resizable=yes");if(!F){ae.error("Popup was blocked. Please allow popups for this site and try again."),n(!1);return}const z=Z=>{var Y,W;Z.origin===window.location.origin&&(((Y=Z.data)==null?void 0:Y.type)==="canva-oauth-success"?(window.removeEventListener("message",z),ae.success("Canva connected successfully!"),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1)):((W=Z.data)==null?void 0:W.type)==="canva-oauth-error"&&(window.removeEventListener("message",z),ae.error("Canva connection failed: "+(Z.data.error||"Unknown error")),n(!1)))};window.addEventListener("message",z);const H=setInterval(()=>{F.closed&&(clearInterval(H),window.removeEventListener("message",z),s.invalidateQueries({queryKey:["canva-integration"]}),n(!1))},500)}else throw new Error("Failed to get authorization URL")}catch(S){console.error("Canva connect error:",S);const A=(S==null?void 0:S.message)||"";A.includes("CANVA_CLIENT_ID")?ae.error("Canva app credentials not configured yet."):ae.error(A||"Failed to start Canva connection"),n(!1)}},y=yt({mutationFn:async w=>{var F;const{data:S}=await q.auth.getSession(),A=(F=S==null?void 0:S.session)==null?void 0:F.access_token;if(!A)throw new Error("Not authenticated");const D=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/canva-oauth",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${A}`,apikey:"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJzdXBhYmFzZSIsInJlZiI6InJlbHplamlzd25vdGlramd2amh6Iiwicm9sZSI6ImFub24iLCJpYXQiOjE3NjE5NTAzNDQsImV4cCI6MjA3NzUyNjM0NH0.dzIkIr_oFSbFE3oWS0ktIr83iKHHkZxt40Gc7SpC_mM"},body:JSON.stringify({action:"disconnect",integrationId:w})}),I=await D.json();if(!D.ok||I!=null&&I.error)throw new Error((I==null?void 0:I.error)||"Failed to disconnect")},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-integration"]}),ae.success("Canva disconnected")},onError:w=>{ae.error(w.message||"Failed to disconnect Canva")}}),_=yt({mutationFn:async w=>{const{error:S}=await q.from("canva_brokerage_folders").insert({brokerage_id:w.brokerage_id,folder_id:w.folder_id.trim(),folder_name:w.folder_name.trim(),folder_type:w.folder_type,description:w.description.trim()||null,sort_order:(p==null?void 0:p.length)||0});if(S)throw S},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder added"),l(!1),c({brokerage_id:"",folder_id:"",folder_name:"",folder_type:"template",description:""})},onError:()=>ae.error("Failed to add folder")}),v=yt({mutationFn:async w=>{const{error:S}=await q.from("canva_brokerage_folders").delete().eq("id",w);if(S)throw S},onSuccess:()=>{s.invalidateQueries({queryKey:["canva-brokerage-folders"]}),ae.success("Folder removed")},onError:()=>ae.error("Failed to remove folder")}),j=!!d;return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsx(It,{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(JQe,{})}),e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-lg flex items-center gap-2",children:["Canva Connect",j&&e.jsx(Ue,{variant:"default",className:"text-xs",children:"Connected"}),e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Admin Only"})]}),e.jsx(Vn,{children:"Auto-share brokerage asset folders with agents when they connect their Canva accounts."})]})]})})}),e.jsx(Ee,{children:e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-start gap-2 text-sm text-muted-foreground",children:[e.jsx(Pi,{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(Pi,{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(Pi,{className:"h-4 w-4 mt-0.5 text-primary shrink-0"}),e.jsx("span",{children:"Multiple folders per brokerage (templates, brand assets, listings)"})]}),e.jsxs("div",{className:"mt-4 p-3 rounded-lg bg-muted border border-dashed",children:[e.jsx("p",{className:"text-xs font-medium text-foreground mb-1",children:"Canva App Redirect URL"}),e.jsx("code",{className:"text-xs text-muted-foreground break-all select-all",children:"https://dashboard.relevelup.com/canva-callback.html"})]}),j?e.jsxs("div",{className:"space-y-3 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border",children:[e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:d.canva_team_id?`Team: ${d.canva_team_id}`:"Canva Account"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:d.expires_at?`Token expires ${new Date(d.expires_at).toLocaleDateString()}`:"Platform integration active"})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Canva?"}),e.jsx(Mo,{children:"This will remove the Canva platform integration. Agents who have already connected will not be affected, but new folder sharing will stop."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>y.mutate(d.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]}),e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-center justify-between p-3 text-sm font-medium hover:bg-muted transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pf,{className:"h-4 w-4 text-primary"}),"Brokerage Folder Mappings",p&&p.length>0&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:p.length})]}),r?e.jsx(ex,{className:"h-4 w-4"}):e.jsx(ao,{className:"h-4 w-4"})]}),r&&e.jsxs("div",{className:"border-t p-3 space-y-2",children:[p&&p.length>0?p.map(w=>{var S,A;return e.jsxs("div",{className:"flex items-center justify-between p-2 rounded-md bg-muted/50 text-sm",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-medium truncate",children:w.folder_name}),e.jsx(Ue,{variant:"outline",className:"text-xs shrink-0",children:((S=eXe.find(E=>E.value===w.folder_type))==null?void 0:S.label)||w.folder_type})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(A=w.brokerages)==null?void 0:A.name," · ID: ",e.jsx("span",{className:"font-mono",children:w.folder_id})]})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive shrink-0 ml-2",onClick:()=>v.mutate(w.id),children:e.jsx($n,{className:"h-3.5 w-3.5"})})]},w.id)}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-2",children:"No folders mapped yet"}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5 mt-1",onClick:()=>l(!0),children:[e.jsx(Is,{className:"h-3.5 w-3.5"}),"Add Folder Mapping"]})]})]})]}):e.jsxs(B,{className:"mt-4",onClick:f,disabled:t||u,children:[t?e.jsx(Ei,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx("div",{className:"mr-2",children:e.jsx(JQe,{})}),"Connect Canva",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]})]})})]}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{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(ne,{children:"Brokerage"}),e.jsxs(us,{value:o.brokerage_id,onValueChange:w=>c(S=>({...S,brokerage_id:w})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a brokerage…"})}),e.jsx(cs,{children:h==null?void 0:h.map(w=>e.jsx(Ze,{value:w.id,children:w.name},w.id))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Canva Folder ID"}),e.jsx(ye,{placeholder:"e.g. FABCdef123456",value:o.folder_id,onChange:w=>c(S=>({...S,folder_id:w.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(ne,{children:"Folder Display Name"}),e.jsx(ye,{placeholder:"e.g. Brand Templates 2024",value:o.folder_name,onChange:w=>c(S=>({...S,folder_name:w.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Folder Type"}),e.jsxs(us,{value:o.folder_type,onValueChange:w=>c(S=>({...S,folder_type:w})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:eXe.map(w=>e.jsx(Ze,{value:w.value,children:w.label},w.value))})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ne,{children:["Description ",e.jsx("span",{className:"text-muted-foreground",children:"(optional)"})]}),e.jsx(ye,{placeholder:"What's in this folder?",value:o.description,onChange:w=>c(S=>({...S,description:w.target.value}))})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>_.mutate(o),disabled:!o.brokerage_id||!o.folder_id||!o.folder_name||_.isPending,children:[_.isPending?e.jsx(Ei,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Add Folder"]})]})]})})]})}function hen(){const s=Ln();return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Bd,{title:"Integrations",description:"Manage platform-level service connections"}),e.jsxs(fe,{className:"p-6 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"p-3 rounded-lg bg-primary/10",children:e.jsx(Vl,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold",children:"User Social Connections"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"See which agents have connected Facebook, Instagram, LinkedIn, and Google."})]})]}),e.jsxs(B,{onClick:()=>s("/admin/social-connections"),children:["View ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})]}),e.jsx(uen,{}),e.jsx(y2t,{})]})})}const tXe=s=>{const t="h-4 w-4";return s==="facebook"?e.jsx(Mh,{className:t}):s==="instagram"?e.jsx(ou,{className:t}):s==="linkedin"?e.jsx(xf,{className:t}):s==="google"?e.jsx(Gs,{className:t}):null},men=s=>s?new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",year:"numeric",month:"short",day:"numeric"}).format(new Date(s)):"—";function pen(){const[s,t]=N.useState([]),[n,r]=N.useState(!0),[a,i]=N.useState(""),[l,o]=N.useState("all");N.useEffect(()=>{(async()=>{r(!0);const{data:p,error:f}=await q.rpc("admin_get_social_connections");if(f){ae.error(f.message),r(!1);return}t(p||[]),r(!1)})()},[]);const c=N.useMemo(()=>{const p=a.trim().toLowerCase();return s.filter(f=>l!=="all"&&f.platform!==l?!1:p?(f.user_name||"").toLowerCase().includes(p)||(f.user_email||"").toLowerCase().includes(p)||(f.page_name||"").toLowerCase().includes(p)||(f.platform_username||"").toLowerCase().includes(p):!0)},[s,a,l]),d=N.useMemo(()=>{const p=new Map;return s.forEach(f=>{const y=p.get(f.user_id)||{name:f.user_name,email:f.user_email,platforms:new Set,count:0};y.platforms.add(f.platform),y.count+=1,p.set(f.user_id,y)}),Array.from(p.entries()).map(([f,y])=>({user_id:f,...y}))},[s]),u=N.useMemo(()=>{const p=new Map;return s.forEach(f=>p.set(f.platform,(p.get(f.platform)||0)+1)),{uniqueUsers:d.length,totalConnections:s.length,byPlatform:Array.from(p.entries())}},[s,d]),h=p=>p&&new Date(p).getTime()e.jsxs(fe,{className:"p-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground capitalize flex items-center gap-2",children:[tXe(p)," ",p]}),e.jsx("div",{className:"text-2xl font-bold",children:f})]},p))]}),e.jsxs("div",{className:"flex flex-col md:flex-row gap-3",children:[e.jsx(ye,{placeholder:"Search by user, email, page, or handle…",value:a,onChange:p=>i(p.target.value),className:"md:max-w-md"}),e.jsxs(us,{value:l,onValueChange:o,children:[e.jsx(ls,{className:"md:w-48",children:e.jsx(hs,{placeholder:"All platforms"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All platforms"}),e.jsx(Ze,{value:"facebook",children:"Facebook"}),e.jsx(Ze,{value:"instagram",children:"Instagram"}),e.jsx(Ze,{value:"linkedin",children:"LinkedIn"}),e.jsx(Ze,{value:"google",children:"Google"})]})]})]}),e.jsx(fe,{children:n?e.jsx("div",{className:"flex items-center justify-center p-12",children:e.jsx(rs,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"User"}),e.jsx(Tt,{children:"Platform"}),e.jsx(Tt,{children:"Page / Account"}),e.jsx(Tt,{children:"Status"}),e.jsx(Tt,{children:"Connected"})]})}),e.jsx(da,{children:c.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:5,className:"text-center text-muted-foreground py-8",children:"No connections found."})}):c.map(p=>{const f=h(p.token_expires_at);return e.jsxs(Hs,{children:[e.jsxs(ht,{children:[e.jsx("div",{className:"font-medium",children:p.user_name||"—"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:p.user_email})]}),e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-2 capitalize",children:[tXe(p.platform)," ",p.platform]})}),e.jsxs(ht,{children:[e.jsx("div",{className:"font-medium",children:p.page_name||p.platform_username||"—"}),p.instagram_business_id&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["IG Business: ",p.instagram_business_id]})]}),e.jsx(ht,{children:p.is_active?f?e.jsxs(Ue,{variant:"destructive",className:"gap-1",children:[e.jsx(Bi,{className:"h-3 w-3"})," Expired"]}):e.jsx(Ue,{children:"Active"}):e.jsx(Ue,{variant:"secondary",children:"Inactive"})}),e.jsx(ht,{className:"text-sm text-muted-foreground",children:men(p.created_at)})]},p.id)})})]})})]})})}const fen={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 MF(s,t=18,n=10){return s.length<=t+n+3?s:`${s.slice(0,t)}…${s.slice(-n)}`}function xen(){var H,Z,Y,W,ee;const s=Kt(),[t,n]=N.useState("Test Push"),[r,a]=N.useState("Testing web push notification"),[i,l]=N.useState("/community"),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState({isSupported:typeof window<"u"&&"serviceWorker"in navigator&&"PushManager"in window}),[f,y]=N.useState(null),[_,v]=N.useState(null),{data:j,isLoading:w}=dt({queryKey:["push-notification-settings"],queryFn:async()=>{const{data:se,error:oe}=await q.from("push_notification_settings").select("*").order("setting_key");if(oe)throw oe;return se}}),{data:S,isLoading:A}=dt({queryKey:["push-subscription-stats"],queryFn:async()=>{const{count:se,error:oe}=await q.from("push_subscriptions").select("*",{count:"exact",head:!0});if(oe)throw oe;return{totalSubscriptions:se||0}}}),E=yt({mutationFn:async({settingKey:se,isEnabled:oe})=>{const{error:he}=await q.from("push_notification_settings").update({is_enabled:oe}).eq("setting_key",se);if(he)throw he},onSuccess:()=>{s.invalidateQueries({queryKey:["push-notification-settings"]}),ae.success("Notification setting updated")},onError:se=>{ae.error("Failed to update setting: "+se.message)}}),O=N.useMemo(()=>{var se,oe;return h.isSupported?`perm=${h.permission??"unknown"} · controller=${h.controllerPresent?"yes":"no"} · sw=${((se=h.serviceWorker)==null?void 0:se.activeState)??"unknown"} · sub=${(oe=h.subscription)!=null&&oe.endpoint?"yes":"no"}`:"Push not supported in this browser."},[h]);N.useEffect(()=>{let se=!0;const oe=async()=>{var le,ve,ge,Te,Ie,Ce,Me;const ce="serviceWorker"in navigator&&"PushManager"in window,me={isSupported:ce,permission:typeof Notification<"u"?Notification.permission:void 0,controllerPresent:!!((le=navigator.serviceWorker)!=null&&le.controller)};if(!ce){se&&p(me);return}try{const{data:Pe,error:Re}=await q.functions.invoke("get-vapid-public-key",{body:{}});if(Re)throw Re;me.vapidPublicKey=Pe==null?void 0:Pe.vapidPublicKey;const Be=(await navigator.serviceWorker.getRegistrations()).find(we=>{var ke,it,je;return(((ke=we.active)==null?void 0:ke.scriptURL)||((it=we.waiting)==null?void 0:it.scriptURL)||((je=we.installing)==null?void 0:je.scriptURL)||"").includes("/sw.js")});if(Be){me.pushWorkerScriptUrl=((ve=Be.active)==null?void 0:ve.scriptURL)||((ge=Be.waiting)==null?void 0:ge.scriptURL)||((Te=Be.installing)==null?void 0:Te.scriptURL),me.serviceWorker={scope:Be.scope,activeState:(Ie=Be.active)==null?void 0:Ie.state};const we=await Be.pushManager.getSubscription();if(we){const Je=we.toJSON();me.subscription={endpoint:Je.endpoint,p256dh:(Ce=Je.keys)==null?void 0:Ce.p256dh,auth:(Me=Je.keys)==null?void 0:Me.auth}}}}catch(Pe){me.error=(Pe==null?void 0:Pe.message)||String(Pe)}se&&p(me)};oe();const he=window.setInterval(oe,4e3);return()=>{se=!1,window.clearInterval(he)}},[]);const D=async()=>{if(typeof Notification>"u"){ae.error("Notifications API not available in this browser.");return}try{if(Notification.permission!=="granted"&&await Notification.requestPermission()!=="granted"){ae.error("Notification permission not granted.");return}new Notification("Local notification test",{body:"If you see this, OS/browser notifications can display."}),ae.success("Triggered a local notification (not push).")}catch(se){ae.error(`Local notification failed: ${(se==null?void 0:se.message)||String(se)}`)}},I=async()=>{c(!0),y(null);try{const{data:se,error:oe}=await q.functions.invoke("send-push-notification",{body:{title:t,body:r,url:i}});if(oe)throw oe;y({sent:se==null?void 0:se.sent,failed:se==null?void 0:se.failed,expiredCleaned:se==null?void 0:se.expiredCleaned,vapidPublicKey:se==null?void 0:se.vapidPublicKey}),(se==null?void 0:se.sent)>0?ae.success(`Test notification sent to ${se.sent} subscriber(s)`):(se==null?void 0:se.failed)>0?ae.warning(`Notification failed for ${se.failed} subscriber(s). ${se.expired||0} expired subscriptions cleaned up.`):ae.info("No active subscriptions to send to")}catch(se){console.error("Error sending test notification:",se),y({error:(se==null?void 0:se.message)||String(se)}),ae.error("Failed to send test notification: "+(se.message||"Unknown error"))}finally{c(!1)}},F=async()=>{u(!0),v(null);try{const{data:se,error:oe}=await q.functions.invoke("generate-vapid-keys",{body:{}});if(oe)throw oe;const he=se==null?void 0:se.publicKey,ce=se==null?void 0:se.privateKey;if(!he||!ce)throw new Error("generate-vapid-keys did not return keys");v({publicKey:he,privateKey:ce}),ae.success("Generated new VAPID keys. Update backend secrets, then clear + re-subscribe.")}catch(se){console.error("Error generating VAPID keys:",se),ae.error("Failed to generate VAPID keys: "+((se==null?void 0:se.message)||"Unknown error"))}finally{u(!1)}},z=yt({mutationFn:async()=>{const{error:se}=await q.from("push_subscriptions").delete().neq("id","00000000-0000-0000-0000-000000000000");if(se)throw se},onSuccess:()=>{ae.success("All subscriptions cleared. Users will need to re-enable notifications."),s.invalidateQueries({queryKey:["push-subscription-stats"]})},onError:se=>{ae.error("Failed to clear subscriptions: "+se.message)}});return e.jsx(Cs,{title:"Notification Settings",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Notification Settings",description:"Manage push notifications and test the notification system"}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-5 w-5"}),"Push Notification Subscribers"]}),e.jsx(Vn,{children:"Current active push notification subscriptions"})]}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"text-4xl font-bold",children:A?"...":(S==null?void 0:S.totalSubscriptions)||0}),e.jsx("div",{className:"text-sm text-muted-foreground",children:"active subscriptions"})]})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Ko,{className:"h-5 w-5"}),"Notification Types"]}),e.jsx(Vn,{children:"Control which types of push notifications are sent to users"})]}),e.jsx(Ee,{children:w?e.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading settings..."}):e.jsx("div",{className:"space-y-4",children:j==null?void 0:j.map(se=>{const oe=fen[se.setting_key]||{label:se.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:se.description})]})]}),e.jsx(jn,{checked:se.is_enabled,onCheckedChange:he=>E.mutate({settingKey:se.setting_key,isEnabled:he}),disabled:E.isPending})]},se.id)})})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(nm,{className:"h-5 w-5"}),"Send Test Notification"]}),e.jsx(Vn,{children:"Send a test push notification to all subscribed users"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Client push debug"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:O}),h.error&&e.jsx("div",{className:"mt-2 text-destructive",children:h.error}),e.jsxs("div",{className:"mt-2 grid gap-2 sm:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Backend VAPID public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:h.vapidPublicKey?MF(h.vapidPublicKey):"(not loaded)"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Service worker"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["scope: ",(H=h.serviceWorker)!=null&&H.scope?MF(h.serviceWorker.scope,24,8):"none"]}),e.jsxs("div",{children:["active: ",((Z=h.serviceWorker)==null?void 0:Z.activeState)??"none"]})]})]}),e.jsxs("div",{className:"space-y-1 sm:col-span-2",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Current browser subscription"}),e.jsxs("div",{className:"rounded-md border bg-background p-2 font-mono text-xs",children:[e.jsxs("div",{children:["endpoint: ",(Y=h.subscription)!=null&&Y.endpoint?MF(h.subscription.endpoint,40,12):"none"]}),e.jsxs("div",{children:["p256dh: ",(W=h.subscription)!=null&&W.p256dh?MF(h.subscription.p256dh,22,10):"none"]}),e.jsxs("div",{children:["auth: ",(ee=h.subscription)!=null&&ee.auth?MF(h.subscription.auth,22,10):"none"]})]})]})]}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2",children:[e.jsx(B,{variant:"outline",onClick:D,children:"Local notification test"}),e.jsx(B,{variant:"outline",onClick:()=>window.location.reload(),children:"Reload page"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"test-title",children:"Notification Title"}),e.jsx(ye,{id:"test-title",value:t,onChange:se=>n(se.target.value),placeholder:"Enter notification title"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"test-body",children:"Notification Body"}),e.jsx(Ms,{id:"test-body",value:r,onChange:se=>a(se.target.value),placeholder:"Enter notification message",rows:3})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"test-url",children:"Click URL (optional)"}),e.jsx(ye,{id:"test-url",value:i,onChange:se=>l(se.target.value),placeholder:"/community or full URL"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Where users will be taken when they click the notification"})]}),e.jsxs(B,{onClick:I,disabled:o||!t||!r,className:"w-full sm:w-auto",children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),o?"Sending...":"Send Test Notification"]}),f&&e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"Last send debug"}),f.error?e.jsxs("div",{className:"mt-1 text-destructive",children:["Error: ",f.error]}):e.jsxs("div",{className:"mt-1 space-y-1 text-muted-foreground",children:[e.jsxs("div",{children:["Result: ",f.sent??0," sent, ",f.failed??0," failed, ",f.expiredCleaned??0," expired cleaned"]}),f.vapidPublicKey?e.jsxs("div",{className:"break-all",children:["Backend VAPID public key: ",e.jsx("span",{className:"font-mono",children:f.vapidPublicKey})]}):e.jsx("div",{children:"Backend VAPID public key: (not returned)"})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2 text-destructive",children:[e.jsx(_n,{className:"h-5 w-5"}),"Subscription Maintenance"]}),e.jsx(Vn,{children:"Clear all push subscriptions if VAPID keys were changed or subscriptions are invalid"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"If you've recently updated the VAPID keys, existing subscriptions will no longer work. Use this to clear all subscriptions so users can re-subscribe with the new keys."}),e.jsxs(B,{variant:"destructive",onClick:()=>z.mutate(),disabled:z.isPending,children:[e.jsx(_n,{className:"h-4 w-4 mr-2"}),z.isPending?"Clearing...":"Clear All Subscriptions"]}),e.jsxs("div",{className:"rounded-md border bg-muted/30 p-3 text-sm",children:[e.jsx("div",{className:"font-medium",children:"VAPID key rotation helper"}),e.jsx("div",{className:"mt-1 text-muted-foreground",children:"If you suspect the backend public/private keys don’t match, generate a fresh pair, update backend secrets, then clear subscriptions and have users re-enable push."}),e.jsx("div",{className:"mt-3 flex flex-wrap gap-2",children:e.jsx(B,{variant:"outline",onClick:F,disabled:d,children:d?"Generating…":"Generate VAPID keys"})}),_&&e.jsxs("div",{className:"mt-3 space-y-2",children:[e.jsxs("div",{className:"text-muted-foreground",children:["Copy these into backend secrets ",e.jsx("span",{className:"font-mono",children:"VAPID_PUBLIC_KEY"})," and ",e.jsx("span",{className:"font-mono",children:"VAPID_PRIVATE_KEY"}),"."]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Public key"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:_.publicKey})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Private key (keep secret)"}),e.jsx("div",{className:"break-all rounded-md border bg-background p-2 font-mono text-xs",children:_.privateKey})]})]})]})]})]})]})})}function gen(){const{toast:s}=Fa(),[t,n]=N.useState([]),[r,a]=N.useState({totalPresentations:0,totalViews:0,totalLeads:0,totalCtaClicks:0,agentsUsing:0}),[i,l]=N.useState(!0),{sortKey:o,sortDirection:c,handleSort:d,sortData:u}=xU("presentation_count","desc"),h=u(t,{name:y=>{var _;return((_=y.name)==null?void 0:_.toLowerCase())||""},presentations:y=>y.presentation_count,views:y=>y.total_views,leads:y=>y.total_leads,cta_clicks:y=>y.total_cta_clicks,conversion:y=>y.total_views>0?y.total_leads/y.total_views*100:0});N.useEffect(()=>{p()},[]);const p=async()=>{try{l(!0);const{data:y,error:_}=await q.rpc("get_admin_presentation_stats");if(_)throw _;if(!y||y.length===0){l(!1);return}const v=y.map(E=>E.owner_user_id),{data:j,error:w}=await q.from("profiles").select("id, name, email, avatar_url").in("id",v);if(w)throw w;const S=new Map((j==null?void 0:j.map(E=>[E.id,E]))||[]),A=y.map(E=>{const O=S.get(E.owner_user_id);return{owner_user_id:E.owner_user_id,name:(O==null?void 0:O.name)||"Unknown",email:(O==null?void 0:O.email)||"",avatar_url:(O==null?void 0:O.avatar_url)||null,presentation_count:Number(E.presentation_count),total_views:Number(E.total_views),total_leads:Number(E.total_leads),total_cta_clicks:Number(E.total_cta_clicks)}});n(A),n(A),a({totalPresentations:A.reduce((E,O)=>E+O.presentation_count,0),totalViews:A.reduce((E,O)=>E+O.total_views,0),totalLeads:A.reduce((E,O)=>E+O.total_leads,0),totalCtaClicks:A.reduce((E,O)=>E+O.total_cta_clicks,0),agentsUsing:A.length})}catch(y){console.error("Error loading presentation stats:",y),s({title:"Error",description:"Failed to load presentation analytics",variant:"destructive"})}finally{l(!1)}},f=[{label:"Agents Using",value:r.agentsUsing,icon:An,color:"text-blue-600"},{label:"Total Presentations",value:r.totalPresentations,icon:ny,color:"text-violet-600"},{label:"Total Views",value:r.totalViews,icon:Sr,color:"text-emerald-600"},{label:"Total Leads",value:r.totalLeads,icon:Fo,color:"text-amber-600"},{label:"CTA Clicks",value:r.totalCtaClicks,icon:oc,color:"text-rose-600"}];return e.jsx(Cs,{title:"Presentation Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Presentation Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track Smart Presentations usage and engagement across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:f.map(y=>e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:y.label}),e.jsx(y.icon,{className:`h-4 w-4 ${y.color}`})]}),e.jsx(Ee,{children:i?e.jsx(Ws,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:y.value.toLocaleString()})})]},y.label))}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(go,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ee,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((y,_)=>e.jsx(Ws,{className:"h-12 w-full"},_))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No presentations created yet."}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Sc,{sortKey:"name",currentSortKey:o,currentDirection:c,onSort:d,children:"Agent"}),e.jsx(Sc,{sortKey:"presentations",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Presentations"}),e.jsx(Sc,{sortKey:"views",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Views"}),e.jsx(Sc,{sortKey:"leads",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Leads"}),e.jsx(Sc,{sortKey:"cta_clicks",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"CTA Clicks"}),e.jsx(Sc,{sortKey:"conversion",currentSortKey:o,currentDirection:c,onSort:d,className:"text-center",children:"Conversion"})]})}),e.jsx(da,{children:h.map(y=>{var v,j;const _=y.total_views>0?(y.total_leads/y.total_views*100).toFixed(1):"0.0";return e.jsxs(Hs,{children:[e.jsx(ht,{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:y.avatar_url?e.jsx("img",{src:y.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((j=(v=y.name)==null?void 0:v.charAt(0))==null?void 0:j.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:y.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:y.email})]})]})}),e.jsx(ht,{className:"text-center font-medium",children:y.presentation_count}),e.jsx(ht,{className:"text-center",children:y.total_views.toLocaleString()}),e.jsx(ht,{className:"text-center",children:y.total_leads>0?e.jsx(Ue,{variant:"secondary",children:y.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ht,{className:"text-center",children:y.total_cta_clicks}),e.jsx(ht,{className:"text-center",children:e.jsxs("span",{className:Number(_)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[_,"%"]})})]},y.owner_user_id)})})]})})]})]})})}function yen(){const{toast:s}=Fa(),[t,n]=N.useState([]),[r,a]=N.useState({totalOpenHouses:0,totalVisitors:0,totalLeads:0,activeOpenHouses:0,agentsUsing:0}),[i,l]=N.useState(!0);N.useEffect(()=>{o()},[]);const o=async()=>{try{l(!0);const{data:d,error:u}=await q.rpc("get_admin_guest_book_stats");if(u)throw u;if(!d||d.length===0){l(!1);return}const h=d.map(v=>v.agent_id),{data:p,error:f}=await q.from("profiles").select("id, name, email, avatar_url").in("id",h);if(f)throw f;const y=new Map((p==null?void 0:p.map(v=>[v.id,v]))||[]),_=d.map(v=>{const j=y.get(v.agent_id);return{agent_id:v.agent_id,name:(j==null?void 0:j.name)||"Unknown",email:(j==null?void 0:j.email)||"",avatar_url:(j==null?void 0:j.avatar_url)||null,open_house_count:Number(v.open_house_count),total_visitors:Number(v.total_visitors),total_leads:Number(v.total_leads),active_count:Number(v.active_count)}});_.sort((v,j)=>j.total_visitors-v.total_visitors),n(_),a({totalOpenHouses:_.reduce((v,j)=>v+j.open_house_count,0),totalVisitors:_.reduce((v,j)=>v+j.total_visitors,0),totalLeads:_.reduce((v,j)=>v+j.total_leads,0),activeOpenHouses:_.reduce((v,j)=>v+j.active_count,0),agentsUsing:_.length})}catch(d){console.error("Error loading guest book stats:",d),s({title:"Error",description:"Failed to load guest book analytics",variant:"destructive"})}finally{l(!1)}},c=[{label:"Agents Using",value:r.agentsUsing,icon:An,color:"text-blue-600"},{label:"Total Open Houses",value:r.totalOpenHouses,icon:Or,color:"text-violet-600"},{label:"Active Now",value:r.activeOpenHouses,icon:Pi,color:"text-emerald-600"},{label:"Total Visitors",value:r.totalVisitors,icon:Sr,color:"text-amber-600"},{label:"Leads Created",value:r.totalLeads,icon:Fo,color:"text-rose-600"}];return e.jsx(Cs,{title:"Guest Book Analytics",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"Guest Book Analytics"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Track open house sign-in usage and lead generation across all agents"})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 lg:grid-cols-5 gap-4",children:c.map(d=>e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between space-y-0 pb-2",children:[e.jsx(Rt,{className:"text-sm font-medium",children:d.label}),e.jsx(d.icon,{className:`h-4 w-4 ${d.color}`})]}),e.jsx(Ee,{children:i?e.jsx(Ws,{className:"h-8 w-16"}):e.jsx("div",{className:"text-2xl font-bold",children:d.value.toLocaleString()})})]},d.label))}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(go,{className:"h-5 w-5"}),"Agent Breakdown"]})}),e.jsx(Ee,{children:i?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((d,u)=>e.jsx(Ws,{className:"h-12 w-full"},u))}):t.length===0?e.jsx("p",{className:"text-muted-foreground text-center py-8",children:"No open houses created yet."}):e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Agent"}),e.jsx(Tt,{className:"text-center",children:"Open Houses"}),e.jsx(Tt,{className:"text-center",children:"Active"}),e.jsx(Tt,{className:"text-center",children:"Visitors"}),e.jsx(Tt,{className:"text-center",children:"Leads"}),e.jsx(Tt,{className:"text-center",children:"Conversion"})]})}),e.jsx(da,{children:t.map(d=>{var h,p;const u=d.total_visitors>0?(d.total_leads/d.total_visitors*100).toFixed(1):"0.0";return e.jsxs(Hs,{children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-muted flex items-center justify-center overflow-hidden",children:d.avatar_url?e.jsx("img",{src:d.avatar_url,alt:"",className:"h-full w-full object-cover"}):e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:((p=(h=d.name)==null?void 0:h.charAt(0))==null?void 0:p.toUpperCase())||"?"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium text-sm",children:d.name}),e.jsx("div",{className:"text-xs text-muted-foreground",children:d.email})]})]})}),e.jsx(ht,{className:"text-center font-medium",children:d.open_house_count}),e.jsx(ht,{className:"text-center",children:d.active_count>0?e.jsx(Ue,{variant:"secondary",className:"bg-emerald-100 text-emerald-700",children:d.active_count}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ht,{className:"text-center",children:d.total_visitors.toLocaleString()}),e.jsx(ht,{className:"text-center",children:d.total_leads>0?e.jsx(Ue,{variant:"secondary",children:d.total_leads}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ht,{className:"text-center",children:e.jsxs("span",{className:Number(u)>0?"text-emerald-600 font-medium":"text-muted-foreground",children:[u,"%"]})})]},d.agent_id)})})]})})]})]})})}function ven(){const[s]=xl(),t=Ln(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing connection...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Failed to connect: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("Failed to connect: No authorization code");return}try{const{data:h,error:p}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u}});if(h&&h.success===!1)throw new Error(h.error||"Failed to connect accounts");if(p){let f=p.message||"Failed to connect accounts";try{const y=p.context;if(y&&typeof y.json=="function"){const _=await y.json();_!=null&&_.error&&(f=_.error)}}catch{}throw new Error(f)}if(h!=null&&h.success)r("success"),i(h.message||"Accounts connected successfully!"),ae.success(h.message||"Social accounts connected!");else throw new Error((h==null?void 0:h.error)||"Failed to connect accounts")}catch(h){console.error("Callback error:",h),r("error"),i(h.message||"Failed to complete connection"),ae.error(h.message||"Failed to connect accounts")}})()},[s]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4",children:[n==="loading"&&e.jsx(rs,{className:"h-12 w-12 animate-spin text-primary"}),n==="success"&&e.jsx(Pi,{className:"h-12 w-12 text-green-500"}),n==="error"&&e.jsx(Uc,{className:"h-12 w-12 text-destructive"})]}),e.jsxs(Rt,{children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/admin/integrations"),children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function ben(){const s=Kt(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState([]),o=N.useRef(null),{data:c,isLoading:d}=dt({queryKey:["prospect-emails"],queryFn:async()=>{const{data:w,error:S}=await q.from("prospect_emails").select("*").order("sent_at",{ascending:!1});if(S)throw S;return w}}),u=(c==null?void 0:c.filter(w=>w.status==="live_lead"))||[],h={total:(c==null?void 0:c.length)||0,sent:(c==null?void 0:c.filter(w=>w.status==="sent").length)||0,converted:(c==null?void 0:c.filter(w=>w.status==="converted").length)||0,liveLeads:u.length,conversionRate:c!=null&&c.length?Math.round(c.filter(w=>w.status==="converted").length/c.length*100):0},p=yt({mutationFn:async w=>{const{data:S,error:A}=await q.functions.invoke("send-prospect-email",{body:{emails:w}});if(A)throw A;return S},onSuccess:w=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ae.success(`${w.sent} email${w.sent>1?"s":""} sent successfully!`),n(""),a(""),l([])},onError:w=>{ae.error("Failed to send: "+w.message)}}),f=yt({mutationFn:async()=>{var E,O;const{data:{user:w}}=await q.auth.getUser();if(!(w!=null&&w.email))throw new Error("Could not get your email");const{data:S,error:A}=await q.functions.invoke("send-prospect-email",{body:{emails:[{email:w.email,first_name:(O=(E=w.user_metadata)==null?void 0:E.name)==null?void 0:O.split(" ")[0]}],test_mode:!0}});if(A)throw A;return S},onSuccess:()=>{ae.success("Test email sent to your inbox!")},onError:w=>{ae.error("Failed to send test: "+w.message)}}),y=yt({mutationFn:async()=>{const{data:w,error:S}=await q.functions.invoke("send-prospect-email",{body:{mode:"live_leads"}});if(S)throw S;return w},onSuccess:w=>{s.invalidateQueries({queryKey:["prospect-emails"]}),ae.success(`${w.sent} live lead invite${w.sent===1?"":"s"} sent!`)},onError:w=>{ae.error("Failed to send live lead invites: "+w.message)}}),_=()=>{if(!t.trim()){ae.error("Please enter an email address");return}if(c==null?void 0:c.find(S=>S.email.toLowerCase()===t.trim().toLowerCase())){ae.error("This email has already been prospected");return}p.mutate([{email:t.trim(),first_name:r.trim()||void 0}])},v=w=>{var E;const S=(E=w.target.files)==null?void 0:E[0];if(!S)return;const A=new FileReader;A.onload=O=>{var H,Z;const I=((H=O.target)==null?void 0:H.result).split(` `).filter(Y=>Y.trim()),F=[],z=(Z=I[0])!=null&&Z.toLowerCase().includes("email")?1:0;for(let Y=z;Yoe.trim().replace(/"/g,"")),ee=W[0],se=W[1];ee&&ee.includes("@")&&F.push({email:ee,first_name:se||void 0})}l(F),ae.success(`${F.length} entries loaded from CSV`)},A.readAsText(S),o.current&&(o.current.value="")},j=()=>{if(i.length===0){ae.error("No entries to send");return}const w=new Set((c==null?void 0:c.map(A=>A.email.toLowerCase()))||[]),S=i.filter(A=>!w.has(A.email.toLowerCase()));if(S.length===0){ae.error("All emails have already been prospected");return}S.length0&&e.jsxs(fe,{className:"border-red-200/50 bg-red-500/[0.02]",children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(yf,{className:"h-5 w-5 text-red-600"}),"Live Event Leads",e.jsx(Ue,{variant:"secondary",className:"ml-2",children:h.liveLeads})]}),e.jsx(Vn,{children:"These agents registered on a LevelUp Live page but haven't received a free trial invite yet."})]}),e.jsx(Ee,{children:e.jsxs(B,{onClick:()=>y.mutate(),disabled:y.isPending,className:"gap-2",children:[y.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"}),"Send free trial invite to all live leads"]})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Ac,{className:"h-5 w-5"}),"Send Prospect Email"]}),e.jsxs(Vn,{className:"flex items-center justify-between",children:[e.jsx("span",{children:"Send a beautiful free trial invitation email to potential members"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f.mutate(),disabled:f.isPending,className:"gap-2 ml-4 shrink-0",children:[f.isPending?e.jsx(rs,{className:"h-3 w-3 animate-spin"}):e.jsx(Gs,{className:"h-3 w-3"}),"Send Test to Me"]})]})]}),e.jsx(Ee,{children:e.jsxs(Fr,{defaultValue:"single",children:[e.jsxs(Rr,{className:"mb-4",children:[e.jsxs(Zt,{value:"single",children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Single Send"]}),e.jsxs(Zt,{value:"bulk",children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Bulk CSV"]})]}),e.jsx(is,{value:"single",children:e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{htmlFor:"prospect-email",className:"sr-only",children:"Email"}),e.jsx(ye,{id:"prospect-email",type:"email",placeholder:"agent@example.com",value:t,onChange:w=>n(w.target.value),onKeyDown:w=>w.key==="Enter"&&_()})]}),e.jsxs("div",{className:"w-full sm:w-48",children:[e.jsx(ne,{htmlFor:"prospect-name",className:"sr-only",children:"First Name"}),e.jsx(ye,{id:"prospect-name",placeholder:"First name (optional)",value:r,onChange:w=>a(w.target.value),onKeyDown:w=>w.key==="Enter"&&_()})]}),e.jsxs(B,{onClick:_,disabled:p.isPending,className:"gap-2",children:[p.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"}),"Send Invite"]})]})}),e.jsx(is,{value:"bulk",children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("input",{ref:o,type:"file",accept:".csv",onChange:v,className:"hidden"}),e.jsxs(B,{variant:"outline",onClick:()=>{var w;return(w=o.current)==null?void 0:w.click()},className:"gap-2",children:[e.jsx(br,{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(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(An,{className:"h-3 w-3"}),i.length," entries ready"]}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>l([]),children:[e.jsx($n,{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((w,S)=>e.jsxs("div",{className:"text-muted-foreground",children:[w.email,w.first_name?` — ${w.first_name}`:""]},S)),i.length>20&&e.jsxs("div",{className:"text-muted-foreground/60",children:["...and ",i.length-20," more"]})]}),e.jsxs(B,{onClick:j,disabled:p.isPending,className:"gap-2",children:[p.isPending?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"}),"Send ",i.length," Invites"]})]})]})})]})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5"}),"Prospect Log"]}),e.jsx(Vn,{children:"Track all sent invitations and their conversion status"})]}),e.jsx(Ee,{children:d?e.jsx("div",{className:"space-y-3",children:[...Array(5)].map((w,S)=>e.jsx(Ws,{className:"h-12 w-full"},S))}):c&&c.length>0?e.jsx("div",{className:"overflow-x-auto",children:e.jsxs("table",{className:"w-full",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"border-b",children:[e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Email"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Name"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Sent"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Status"}),e.jsx("th",{className:"text-left py-3 px-4 text-sm font-medium text-muted-foreground",children:"Converted"})]})}),e.jsx("tbody",{children:c.map(w=>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:w.email}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:w.first_name||"—"}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:Ss(new Date(w.sent_at),"MMM d, yyyy")}),e.jsx("td",{className:"py-3 px-4",children:w.status==="converted"?e.jsxs(Ue,{className:"bg-green-500/10 text-green-700 hover:bg-green-500/20 border-0",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"}),"Converted"]}):w.status==="live_lead"?e.jsxs(Ue,{className:"bg-red-500/10 text-red-700 hover:bg-red-500/20 border-0 gap-1",children:[e.jsx(yf,{className:"h-3 w-3"}),"Live lead"]}):e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),"Sent"]})}),e.jsx("td",{className:"py-3 px-4 text-sm text-muted-foreground",children:w.converted_at?Ss(new Date(w.converted_at),"MMM d, yyyy"):"—"})]},w.id))})]})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ac,{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 BU(s){const t=Kt(),{toast:n}=Fa(),r=dt({queryKey:["recruit-stages",s],queryFn:async()=>{if(!s)return[];const{data:c,error:d}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(d)throw d;return c},enabled:!!s}),a=dt({queryKey:["recruit-prospects",s],queryFn:async()=>{if(!s)return[];const c=1e3;let d=[],u=0,h=!0;for(;h;){const{data:p,error:f}=await q.from("recruit_prospects").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).range(u,u+c-1);if(f)throw f;d=d.concat(p),h=p.length===c,u+=c}return d},enabled:!!s}),i=yt({mutationFn:async c=>{const{data:{user:d}}=await q.auth.getUser();if(!d)throw new Error("Not authenticated");const u={first_name:c.first_name||"",last_name:c.last_name||null,email:c.email||null,phone:c.phone||null,current_brokerage:c.current_brokerage||null,license_number:c.license_number||null,experience_years:c.experience_years??null,annual_production:c.annual_production||null,source:c.source||"manual",notes:c.notes||null,stage_id:c.stage_id||null,brokerage_id:s,created_by:d.id,address:c.address||null,city:c.city||null,state:c.state||null,zip_code:c.zip_code||null,last_year_volume:c.last_year_volume||null,last_year_transactions:c.last_year_transactions??null,avg_sale_price:c.avg_sale_price||null,specialties:c.specialties||null,linkedin_url:c.linkedin_url||null,website_url:c.website_url||null,instagram_handle:c.instagram_handle||null,facebook_url:c.facebook_url||null,birthday:c.birthday||null,spouse_name:c.spouse_name||null,interests:c.interests||null,referred_by:c.referred_by||null},{data:h,error:p}=await q.from("recruit_prospects").insert(u).select().single();if(p)throw p;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect added"})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),l=yt({mutationFn:async({id:c,...d})=>{const{data:u,error:h}=await q.from("recruit_prospects").update({...d,updated_at:new Date().toISOString()}).eq("id",c).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]})},onError:c=>n({title:"Error",description:c.message,variant:"destructive"})}),o=yt({mutationFn:async c=>{const{error:d}=await q.from("recruit_prospects").delete().eq("id",c);if(d)throw d},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-prospects",s]}),n({title:"Prospect removed"})}});return{stages:r.data||[],prospects:a.data||[],isLoading:r.isLoading||a.isLoading,addProspect:i,updateProspect:l,deleteProspect:o}}function _en(s){const t=Kt(),{toast:n}=Fa(),r=dt({queryKey:["recruit-activities",s],queryFn:async()=>{if(!s)return[];const{data:i,error:l}=await q.from("recruit_activities").select("*").eq("prospect_id",s).order("created_at",{ascending:!1});if(l)throw l;return i},enabled:!!s}),a=yt({mutationFn:async i=>{const{data:{user:l}}=await q.auth.getUser();if(!l)throw new Error("Not authenticated");const{data:o,error:c}=await q.from("recruit_activities").insert({...i,created_by:l.id}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["recruit-activities",s]}),n({title:"Activity logged"})},onError:i=>n({title:"Error",description:i.message,variant:"destructive"})});return{activities:r.data||[],isLoading:r.isLoading,addActivity:a}}const sXe=(s,t)=>{var n;return{first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",license_number:"",experience_years:"",annual_production:"",source:"manual",notes:"",stage_id:s||((n=t==null?void 0:t[0])==null?void 0:n.id)||"",address:"",city:"",state:"",zip_code:"",last_year_volume:"",last_year_transactions:"",avg_sale_price:"",specialties:"",linkedin_url:"",website_url:"",instagram_handle:"",facebook_url:"",birthday:"",spouse_name:"",interests:"",referred_by:""}};function k2t({open:s,onOpenChange:t,stages:n,defaultStageId:r,onSubmit:a,isSubmitting:i}){const[l,o]=N.useState(sXe(r,n)),c=u=>h=>o(p=>({...p,[u]:h.target.value})),d=u=>{u.preventDefault(),a({...l,experience_years:l.experience_years?parseInt(l.experience_years):null,last_year_transactions:l.last_year_transactions?parseInt(l.last_year_transactions):null,stage_id:l.stage_id||null}),o(sXe(r,n)),t(!1)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Add Recruit Prospect"})}),e.jsxs("form",{onSubmit:d,className:"space-y-4",children:[e.jsxs(Fr,{defaultValue:"basic",className:"w-full",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-4",children:[e.jsx(Zt,{value:"basic",children:"Basic Info"}),e.jsx(Zt,{value:"production",children:"Production"}),e.jsx(Zt,{value:"social",children:"Social & Web"}),e.jsx(Zt,{value:"personal",children:"Personal"})]}),e.jsxs(is,{value:"basic",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"First Name *"}),e.jsx(ye,{required:!0,value:l.first_name,onChange:c("first_name")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Last Name"}),e.jsx(ye,{value:l.last_name,onChange:c("last_name")})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Email"}),e.jsx(ye,{type:"email",value:l.email,onChange:c("email")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Phone"}),e.jsx(ye,{value:l.phone,onChange:c("phone")})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Current Brokerage"}),e.jsx(ye,{value:l.current_brokerage,onChange:c("current_brokerage")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"License #"}),e.jsx(ye,{value:l.license_number,onChange:c("license_number")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Experience (years)"}),e.jsx(ye,{type:"number",min:"0",value:l.experience_years,onChange:c("experience_years")})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Address"}),e.jsx(ye,{placeholder:"Street address",value:l.address,onChange:c("address")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"City"}),e.jsx(ye,{value:l.city,onChange:c("city")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"State"}),e.jsx(ye,{value:l.state,onChange:c("state")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Zip"}),e.jsx(ye,{value:l.zip_code,onChange:c("zip_code")})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Pipeline Stage"}),e.jsxs(us,{value:l.stage_id,onValueChange:u=>o(h=>({...h,stage_id:u})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:n.map(u=>e.jsx(Ze,{value:u.id,children:u.name},u.id))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Referred By"}),e.jsx(ye,{placeholder:"Who referred this prospect?",value:l.referred_by,onChange:c("referred_by")})]})]}),e.jsxs(is,{value:"production",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Annual Production Volume"}),e.jsx(ye,{placeholder:"e.g. $5M, 20 transactions",value:l.annual_production,onChange:c("annual_production")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Last Year Volume"}),e.jsx(ye,{placeholder:"e.g. $8.2M",value:l.last_year_volume,onChange:c("last_year_volume")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Last Year Transactions"}),e.jsx(ye,{type:"number",min:"0",placeholder:"e.g. 24",value:l.last_year_transactions,onChange:c("last_year_transactions")})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Avg Sale Price"}),e.jsx(ye,{placeholder:"e.g. $350K",value:l.avg_sale_price,onChange:c("avg_sale_price")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Specialties / Niche"}),e.jsx(ye,{placeholder:"e.g. Luxury, First-time buyers, Investment",value:l.specialties,onChange:c("specialties")})]})]}),e.jsxs(is,{value:"social",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"LinkedIn URL"}),e.jsx(ye,{type:"url",placeholder:"https://linkedin.com/in/...",value:l.linkedin_url,onChange:c("linkedin_url")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Website URL"}),e.jsx(ye,{type:"url",placeholder:"https://...",value:l.website_url,onChange:c("website_url")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Instagram Handle"}),e.jsx(ye,{placeholder:"@handle",value:l.instagram_handle,onChange:c("instagram_handle")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Facebook URL"}),e.jsx(ye,{type:"url",placeholder:"https://facebook.com/...",value:l.facebook_url,onChange:c("facebook_url")})]})]}),e.jsxs(is,{value:"personal",className:"space-y-4 mt-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Birthday"}),e.jsx(ye,{type:"date",value:l.birthday,onChange:c("birthday")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Spouse / Partner Name"}),e.jsx(ye,{value:l.spouse_name,onChange:c("spouse_name")})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Interests / Hobbies"}),e.jsx(ye,{placeholder:"Golf, travel, community events...",value:l.interests,onChange:c("interests")})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Notes"}),e.jsx(Ms,{value:l.notes,onChange:c("notes"),rows:3})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:i,children:"Add Prospect"})]})]})]})})}function q1e(){const{user:s}=vs();return dt({queryKey:["recruit-email-senders",s==null?void 0:s.id],enabled:!!s,staleTime:6e4,queryFn:async()=>{const[t,n]=await Promise.all([q.from("user_verified_senders").select("email, display_name, status").eq("user_id",s.id).eq("status","verified").limit(1).maybeSingle(),q.from("gmail_integrations").select("gmail_email, is_active").eq("user_id",s.id).eq("is_active",!0).maybeSingle()]);return{massEmail:t.data?{email:t.data.email,displayName:t.data.display_name}:null,gmail:n.data?{email:n.data.gmail_email}:null}}})}function a8e({value:s,onChange:t}){const{data:n,isLoading:r}=q1e();return e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Send from"}),e.jsxs(us,{value:s,onValueChange:a=>t(a),disabled:r,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"default",children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-3.5 w-3.5"})," Brokerage default sender"]})}),e.jsx(Ze,{value:"mass_email",disabled:!(n!=null&&n.massEmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(H2,{className:"h-3.5 w-3.5"}),"Mass Email",n!=null&&n.massEmail?` (${n.massEmail.email})`:" — not configured"]})}),e.jsx(Ze,{value:"gmail",disabled:!(n!=null&&n.gmail),children:e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-3.5 w-3.5"}),"Gmail",n!=null&&n.gmail?` (${n.gmail.email})`:" — not connected"]})})]})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Mass Email and Gmail use your own verified sender. Configure them under Integrations."})]})}function S2t({open:s,onOpenChange:t,recruitVideoId:n,brokerageId:r,prospectName:a,prospectEmail:i,videoTitle:l,defaultMessage:o}){const c=(a||"").split(" ")[0]||"there",[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState("default"),[_,v]=N.useState(!1),j=Kt(),{data:w}=q1e();N.useEffect(()=>{s&&(u(`${c}, I made you a quick video 🎥`),p(o||""),y(w!=null&&w.massEmail?"mass_email":w!=null&&w.gmail?"gmail":"default"))},[s,c,o,w==null?void 0:w.massEmail,w==null?void 0:w.gmail]);const S=async()=>{var A,E;if(!i){ae.error("This prospect has no email address on file.");return}v(!0);try{const{data:O,error:D}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[n],brokerage_id:r,subject_override:d.trim()||void 0,message_override:h.trim()||void 0,send_via:f}});if(D)throw D;if(((O==null?void 0:O.sent)??0)>0)ae.success(`Email sent to ${i}`),j.invalidateQueries({queryKey:["recruit-videos"]}),j.invalidateQueries({queryKey:["recruit-videos-prospect"]}),t(!1);else{const F=((E=(A=O==null?void 0:O.results)==null?void 0:A[0])==null?void 0:E.error)||"Failed to send";ae.error(F)}}catch(O){ae.error((O==null?void 0:O.message)||"Failed to send email")}finally{v(!1)}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5"})," Email video to ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"To"}),e.jsx(ye,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(a8e,{value:f,onChange:y}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Subject"}),e.jsx(ye,{value:d,onChange:A=>u(A.target.value),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Personal message (optional)"}),e.jsx(Ms,{value:h,onChange:A=>p(A.target.value),rows:5,placeholder:`Hi ${c}, wanted to share a quick video...`,className:"mt-1"})]}),l&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Video: ",e.jsx("span",{className:"font-medium",children:l})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:_,children:"Cancel"}),e.jsxs(B,{onClick:S,disabled:_||!i,children:[_?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function nw(s){return s?s.share_token?`https://video.relevelup.com/thumb/${s.share_token}`:s.thumbnail_url||s.preview_url||null:null}const oTe=[{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 wen(s){return dt({queryKey:["recruit-videos",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("brokerage_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function jen(s){return dt({queryKey:["recruit-videos-prospect",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_videos").select(` *, video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token) `).eq("prospect_id",s).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function C2t(){const s=Kt(),{toast:t}=Fa();return yt({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_videos").insert({prospect_id:n.prospect_id,video_id:n.video_id,brokerage_id:n.brokerage_id,message:n.message||null,created_by:r.id}).select("*, prospect:recruit_prospects(id, first_name, last_name, email, phone, current_brokerage), video:agent_videos(id, title, thumbnail_url, playback_url, preview_url, duration_seconds, status, share_token)").single();if(i)throw i;return a},onSuccess:n=>{s.invalidateQueries({queryKey:["recruit-videos"]}),s.invalidateQueries({queryKey:["recruit-videos-prospect",n.prospect_id]}),t({title:"Video linked to prospect"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function T2t(){const s=Kt();return yt({mutationFn:async({id:t,sent_via:n})=>{const{error:r}=await q.from("recruit_videos").update({sent_at:new Date().toISOString(),sent_via:n,updated_at:new Date().toISOString()}).eq("id",t);if(r)throw r},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-videos"]})}})}function E2t(s){return dt({queryKey:["recruit-video-scripts",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_video_scripts").select("*").or(`brokerage_id.eq.${s},is_global.eq.true`).order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}function Nen(){const s=Kt(),{toast:t}=Fa();return yt({mutationFn:async n=>{const{data:{user:r}}=await q.auth.getUser();if(!r)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("recruit_video_scripts").insert({...n,created_by:r.id}).select().single();if(i)throw i;return a},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]}),t({title:"Script saved"})},onError:n=>t({title:"Error",description:n.message,variant:"destructive"})})}function ken(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("recruit_video_scripts").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["recruit-video-scripts"]})}})}function Sen({prospectId:s,prospectName:t,prospectEmail:n,brokerageId:r}){var ee;const{data:a=[],isLoading:i}=jen(s),{data:l=[]}=E2t(r),o=C2t(),c=CN();T2t();const[d,u]=N.useState("idle"),[h,p]=N.useState(0),[f,y]=N.useState(0),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState(!1),[E,O]=N.useState(null),[D,I]=N.useState(null),[F,z]=N.useState(null),H=((ee=l.find(se=>se.id===_))==null?void 0:ee.script_text)||"",Z=()=>{u("idle"),p(0),y(0),v(""),w("")},Y=N.useCallback(async(se,oe)=>{u("uploading");try{const he=`Recruiting: ${t}`,{videoId:ce,libraryId:me}=await t6(he),{uploadUrl:le,apiKey:ve}=await s6(ce),ge=new XMLHttpRequest;ge.upload.onprogress=Be=>{Be.lengthComputable&&p(Be.loaded/Be.total*100)},await new Promise((Be,we)=>{ge.onload=()=>ge.status>=200&&ge.status<300?Be():we(new Error("Upload failed")),ge.onerror=()=>we(new Error("Upload failed")),ge.open("PUT",le),ge.setRequestHeader("AccessKey",ve),ge.send(se)}),u("processing");let Te=0;const Ie=Date.now(),Ce=9e4,Me=`https://iframe.mediadelivery.net/embed/${me}/${ce}`;for(;Te<4&&(await new Promise(we=>setTimeout(we,3e3)),!(Date.now()-Ie>Ce));){const Be=await Fw(ce);if(Te=Be.status,y(Be.encodeProgress||0),Te===5||Te===6)throw new Error("Video processing failed")}const Pe=await Fw(ce),Re=(Pe.storageSize||se.size)/(1024*1024),Ae=await c.mutateAsync({bunny_video_id:ce,playback_url:Pe.directPlayUrl||Me,thumbnail_url:Pe.thumbnailUrl,preview_url:Pe.previewUrl||null,duration_seconds:Pe.length||oe,file_size_mb:Re,title:he,status:Te>=4?"ready":"processing",touch_type:"recruiting"});await o.mutateAsync({prospect_id:s,video_id:Ae.id,brokerage_id:r,message:j||void 0}),u("done"),ae.success("Video recorded and linked to prospect!"),setTimeout(()=>{A(!1),Z()},1500)}catch(he){ae.error(he.message||"Failed to upload video"),u("record")}},[s,t,r,j,c,o]),W=se=>{se&&(navigator.clipboard.writeText(`${window.location.origin}/recruit-video/${se}`),ae.success("Share link copied"))};return e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-1.5",children:[e.jsx(fr,{className:"h-4 w-4"})," Video Outreach"]}),e.jsxs(_s,{open:S,onOpenChange:se=>{!se&&(d==="uploading"||d==="processing")||(A(se),se||Z())},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>u("script"),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Record Video"]})}),e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsxs(ws,{children:["Record Video for ",t]})}),d==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Choose a Script (optional)"}),e.jsxs(us,{value:_,onValueChange:v,children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{placeholder:"No script — speak freely"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No script"}),l.map(se=>{var oe;return e.jsx(Ze,{value:se.id,children:e.jsxs("span",{className:"flex items-center gap-2",children:[se.title,e.jsx(Ue,{variant:"outline",className:"text-[9px] ml-1",children:(oe=oTe.find(he=>he.value===se.category))==null?void 0:oe.label})]})},se.id)})]})]}),H&&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:H})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Personal Message (shown on landing page)"}),e.jsx(Ms,{value:j,onChange:se=>w(se.target.value),placeholder:`Hi ${t.split(" ")[0]}, I'd love to chat about what we're building here...`,rows:3,className:"mt-1"})]}),e.jsxs(B,{onClick:()=>u("record"),className:"w-full",children:[e.jsx(fr,{className:"h-4 w-4 mr-2"})," Start Recording"]})]}),d==="record"&&e.jsx(i6,{maxDurationSeconds:600,onRecordingComplete:Y,teleprompterContent:H||void 0}),d==="uploading"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Uploading video…"}),e.jsx(fi,{value:h,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(h),"%"]})]}),d==="processing"&&e.jsxs("div",{className:"py-8 space-y-4 text-center",children:[e.jsx("p",{className:"font-medium",children:"Processing video…"}),e.jsx(fi,{value:f,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(f),"%"]})]}),d==="done"&&e.jsxs("div",{className:"py-8 text-center",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-emerald-100 flex items-center justify-center mx-auto mb-3",children:e.jsx(El,{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(se=>{var oe;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:nw(se.video)?e.jsx("img",{src:nw(se.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(fr,{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:((oe=se.video)==null?void 0:oe.title)||"Untitled"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[se.view_count>0?e.jsxs(Ue,{variant:"secondary",className:"text-[9px] h-4",children:[e.jsx(Sr,{className:"h-2.5 w-2.5 mr-0.5"}),se.view_count]}):se.sent_at?e.jsxs(Ue,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(lr,{className:"h-2.5 w-2.5 mr-0.5"}),"Sent"]}):e.jsxs(Ue,{variant:"outline",className:"text-[9px] h-4",children:[e.jsx(pr,{className:"h-2.5 w-2.5 mr-0.5"}),"Draft"]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:Ss(new Date(se.created_at),"MMM d")})]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>W(se.share_token),title:"Copy link",children:e.jsx(Zr,{className:"h-3 w-3"})}),e.jsxs(B,{variant:se.sent_at?"ghost":"default",size:"sm",className:"h-7 gap-1",disabled:!n,onClick:()=>{var he;O(se.id),I(((he=se.video)==null?void 0:he.title)||null),z(se.message||null)},title:n?"Email video to prospect":"No email on file",children:[e.jsx(Gs,{className:"h-3 w-3"}),e.jsx("span",{className:"text-[10px]",children:se.sent_at?"Resend":"Email"})]})]})]},se.id)})}),E&&e.jsx(S2t,{open:!!E,onOpenChange:se=>{se||O(null)},recruitVideoId:E,brokerageId:r,prospectName:t,prospectEmail:n,videoTitle:D,defaultMessage:F})]})}function Cen({brokerageId:s,onSelect:t}){const{data:n=[],isLoading:r}=dt({queryKey:["recruit-email-templates",s??"global-only"],queryFn:async()=>{let i=q.from("recruit_email_templates").select("id,brokerage_id,category,title,subject,body,sort_order").eq("is_active",!0).order("sort_order");s?i=i.or(`brokerage_id.is.null,brokerage_id.eq.${s}`):i=i.is("brokerage_id",null);const{data:l,error:o}=await i;if(o)throw o;return l}}),a=n.reduce((i,l)=>{var o;return(i[o=l.category]||(i[o]=[])).push(l),i},{});return e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-2",type:"button",children:[e.jsx(br,{className:"h-4 w-4"}),"Use Template",e.jsx(ao,{className:"h-3.5 w-3.5 opacity-60"})]})}),e.jsx(gc,{align:"end",className:"w-80 max-h-[420px] overflow-y-auto",children:r?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(rs,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):n.length===0?e.jsx("div",{className:"px-3 py-4 text-xs text-muted-foreground text-center",children:"No templates available."}):Object.entries(a).map(([i,l],o)=>e.jsxs("div",{children:[o>0&&e.jsx(Kg,{}),e.jsx(cM,{className:"text-[11px] uppercase tracking-wide text-muted-foreground",children:i}),l.map(c=>e.jsxs(Kr,{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(Ue,{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 Ten({open:s,onOpenChange:t,prospectId:n,brokerageId:r,prospectName:a,prospectEmail:i}){const{user:l}=vs(),o=(a||"").split(" ")[0]||"there",[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("default"),[y,_]=N.useState(!1),[v,j]=N.useState(null),[w,S]=N.useState(!1),A=Kt(),{data:E}=q1e();N.useEffect(()=>{if(s){d(`Hi ${o}`),h("");const H=E!=null&&E.massEmail?"mass_email":E!=null&&E.gmail?"gmail":"default";f(H),j(null),S(!1)}},[s,o,E==null?void 0:E.massEmail,E==null?void 0:E.gmail]);const{data:O=[],isLoading:D}=dt({queryKey:["prospect-email-video-library",l==null?void 0:l.id],queryFn:async()=>{const{data:H,error:Z}=await q.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, touch_type, created_at, share_token").eq("owner_user_id",l.id).eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Z)throw Z;return H??[]},enabled:s&&!!(l!=null&&l.id)}),I=O.find(H=>H.id===v)||null,F=async()=>{var H,Z;if(!i){ae.error("This prospect has no email address on file.");return}if(!c.trim()||!u.trim()){ae.error("Subject and message are required.");return}_(!0);try{if(v){const{data:Y}=await q.from("recruit_videos").select("id").eq("prospect_id",n).eq("video_id",v).maybeSingle();let W=Y==null?void 0:Y.id;if(!W){const{data:he,error:ce}=await q.from("recruit_videos").insert({prospect_id:n,video_id:v,brokerage_id:r,message:u.trim(),created_by:l.id}).select("id").single();if(ce)throw ce;W=he.id}const{data:ee,error:se}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:[W],brokerage_id:r,subject_override:c.trim(),message_override:u.trim(),send_via:p}});if(se)throw se;if(((ee==null?void 0:ee.sent)??0)>0)ae.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-videos"]}),A.invalidateQueries({queryKey:["recruit-videos-prospect",n]}),A.invalidateQueries({queryKey:["recruit-activities",n]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1);else{const he=((Z=(H=ee==null?void 0:ee.results)==null?void 0:H[0])==null?void 0:Z.error)||"Failed to send";ae.error(he)}}else{const{data:Y,error:W}=await q.functions.invoke("send-recruit-prospect-email",{body:{prospect_id:n,brokerage_id:r,subject:c.trim(),message:u.trim(),send_via:p}});if(W)throw W;Y!=null&&Y.success?(ae.success(`Email sent to ${i}`),A.invalidateQueries({queryKey:["recruit-activities",n]}),A.invalidateQueries({queryKey:["recruit-sent-emails"]}),t(!1)):ae.error((Y==null?void 0:Y.error)||"Failed to send")}}catch(Y){ae.error((Y==null?void 0:Y.message)||"Failed to send email")}finally{_(!1)}},z=H=>{const Z=Y=>Y.replace(/\[First Name\]/gi,o);d(Z(H.subject)),h(Z(H.body)),ae.success(`Loaded "${H.title}"`)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5"})," Email ",a]})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"To"}),e.jsx(ye,{value:i||"— no email on file —",disabled:!0,className:"mt-1"})]}),e.jsx(a8e,{value:p,onChange:f}),e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx(ne,{className:"text-xs",children:"Subject"}),e.jsx(Cen,{brokerageId:r,onSelect:z})]}),e.jsx(ye,{value:c,onChange:H=>d(H.target.value)}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Message"}),e.jsx(Ms,{value:u,onChange:H=>h(H.target.value),rows:8,placeholder:`Hi ${o}, wanted to reach out…`,className:"mt-1"})]}),e.jsxs("div",{className:"rounded-md border p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ne,{className:"text-xs flex items-center gap-1.5",children:[e.jsx(fr,{className:"h-3.5 w-3.5"})," Include a video"]}),I?e.jsxs(B,{type:"button",variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>{j(null),S(!1)},children:[e.jsx($n,{className:"h-3 w-3 mr-1"})," Remove"]}):e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>S(H=>!H),children:w?"Hide library":"Pick from library"})]}),I&&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:nw(I)?e.jsx("img",{src:nw(I),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(fr,{className:"h-4 w-4 text-muted-foreground"})})}),e.jsx("p",{className:"text-xs font-medium truncate flex-1",children:I.title||"Untitled video"})]}),!I&&w&&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(rs,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):O.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."}):O.map(H=>e.jsxs("button",{type:"button",onClick:()=>{j(H.id),S(!1)},className:"w-full flex items-center gap-3 p-2 rounded hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-10 w-16 rounded bg-muted overflow-hidden flex-shrink-0",children:nw(H)?e.jsx("img",{src:nw(H),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(fr,{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:H.title||"Untitled video"}),H.duration_seconds&&e.jsxs("p",{className:"text-[10px] text-muted-foreground",children:[Math.floor(H.duration_seconds/60),":",String(Math.floor(H.duration_seconds%60)).padStart(2,"0")]})]})]},H.id))}),I&&e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"A tracked share link with thumbnail will be added to the email automatically."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),disabled:y,children:"Cancel"}),e.jsxs(B,{onClick:F,disabled:y||!i,children:[y?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(lr,{className:"h-4 w-4 mr-2"}),"Send Email"]})]})]})})}function Een(s){return dt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, email_number, status, sent_at, opened_at, clicked_at, error_message, created_at").eq("prospect_id",s).neq("status","failed").order("created_at",{ascending:!1});if(n)throw n;return t},enabled:!!s})}const nXe=[{value:"call",label:"Phone Call",icon:Cr},{value:"email",label:"Email",icon:Gs},{value:"text",label:"Text Message",icon:Ai},{value:"meeting",label:"Meeting",icon:yr},{value:"note",label:"Note",icon:br},{value:"campaign_email",label:"Campaign Email",icon:lr}];function I0({label:s,value:t,icon:n}){return t?e.jsxs("div",{children:[e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[n&&e.jsx(n,{className:"h-3 w-3"})," ",s]}),e.jsx("p",{className:"font-medium text-sm",children:t})]}):null}function vG({label:s,url:t,icon:n}){return t?e.jsxs("a",{href:t.startsWith("http")?t:`https://${t}`,target:"_blank",rel:"noopener noreferrer",className:"flex items-center gap-2 text-sm text-primary hover:underline",children:[e.jsx(n,{className:"h-3.5 w-3.5"})," ",s," ",e.jsx(tr,{className:"h-3 w-3 opacity-50"})]}):null}function Ad({label:s,value:t,onChange:n,type:r="text",placeholder:a}){return e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:s}),e.jsx(ye,{type:r,value:t,onChange:i=>n(i.target.value),placeholder:a,className:"mt-1 h-8 text-sm"})]})}function A2t({prospect:s,stages:t,brokerageId:n,open:r,onOpenChange:a,onUpdate:i,onDelete:l}){const{activities:o,addActivity:c}=_en((s==null?void 0:s.id)||null),{data:d=[]}=Een((s==null?void 0:s.id)||null),[u,h]=N.useState({type:"note",title:"",description:""}),[p,f]=N.useState(!1),[y,_]=N.useState(!1),[v,j]=N.useState({}),[w,S]=N.useState(!1);if(!s)return null;const A=()=>{var W,ee;j({first_name:s.first_name||"",last_name:s.last_name||"",email:s.email||"",phone:s.phone||"",current_brokerage:s.current_brokerage||"",license_number:s.license_number||"",experience_years:((W=s.experience_years)==null?void 0:W.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:((ee=s.last_year_transactions)==null?void 0:ee.toString())||"",avg_sale_price:s.avg_sale_price||"",specialties:s.specialties||"",annual_production:s.annual_production||"",linkedin_url:s.linkedin_url||"",website_url:s.website_url||"",instagram_handle:s.instagram_handle||"",facebook_url:s.facebook_url||"",birthday:s.birthday||"",spouse_name:s.spouse_name||"",interests:s.interests||"",referred_by:s.referred_by||""}),_(!0)},E=()=>{const W={id:s.id};for(const[ee,se]of Object.entries(v))ee==="experience_years"||ee==="last_year_transactions"?W[ee]=se?parseInt(se):null:W[ee]=se||null;i(W),_(!1)},O=()=>_(!1),D=W=>ee=>j(se=>({...se,[W]:ee})),I=()=>{u.title.trim()&&(c.mutate({prospect_id:s.id,activity_type:u.type,title:u.title,description:u.description||null}),h({type:"note",title:"",description:""}),f(!1))},F=t.find(W=>W.id===s.stage_id),z=s.address||s.city||s.state,H=s.last_year_volume||s.last_year_transactions||s.avg_sale_price||s.specialties||s.annual_production,Z=s.linkedin_url||s.website_url||s.instagram_handle||s.facebook_url,Y=s.birthday||s.spouse_name||s.interests||s.referred_by;return e.jsxs(t0,{open:r,onOpenChange:W=>{W||_(!1),a(W)},children:[e.jsx(og,{className:"w-full sm:max-w-lg p-0",children:e.jsx(di,{className:"h-full",children:e.jsxs("div",{className:"p-6 space-y-5",children:[e.jsx(jy,{children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs(Ny,{className:"text-xl",children:[s.first_name," ",s.last_name]}),F&&e.jsx(Ue,{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:[y?e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:O,children:e.jsx($n,{className:"h-4 w-4"})}),e.jsx(B,{variant:"default",size:"icon",onClick:E,children:e.jsx(Jo,{className:"h-4 w-4"})})]}):e.jsx(B,{variant:"ghost",size:"icon",onClick:A,title:"Edit prospect",children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete prospect?"}),e.jsx(Mo,{children:"This will permanently remove this prospect and all their activity history."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>{l(s.id),a(!1)},children:"Delete"})]})]})]})]})]})}),!y&&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(Gs,{className:"h-3.5 w-3.5 flex-shrink-0"}),e.jsx("span",{className:"truncate",children:s.email})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 gap-1.5 flex-shrink-0",onClick:()=>S(!0),children:[e.jsx(Gs,{className:"h-3 w-3"})," Email"]})]}),s.phone&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(Cr,{className:"h-3.5 w-3.5"})," ",s.phone]}),z&&e.jsxs("div",{className:"flex items-center gap-2 text-muted-foreground",children:[e.jsx(ka,{className:"h-3.5 w-3.5"}),[s.address,s.city,s.state,s.zip_code].filter(Boolean).join(", ")]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Move to Stage"}),e.jsxs(us,{value:s.stage_id||"",onValueChange:W=>i({id:s.id,stage_id:W}),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(cs,{children:t.map(W=>e.jsx(Ze,{value:W.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:W.color}}),W.name]})},W.id))})]})]}),e.jsxs(Fr,{defaultValue:"details",className:"w-full",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-4 h-8 text-xs",children:[e.jsx(Zt,{value:"details",className:"text-xs",children:"Details"}),e.jsx(Zt,{value:"production",className:"text-xs",children:"Production"}),e.jsx(Zt,{value:"social",className:"text-xs",children:"Social"}),e.jsx(Zt,{value:"personal",className:"text-xs",children:"Personal"})]}),y?e.jsxs(e.Fragment,{children:[e.jsxs(is,{value:"details",className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ad,{label:"First Name",value:v.first_name,onChange:D("first_name")}),e.jsx(Ad,{label:"Last Name",value:v.last_name,onChange:D("last_name")})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ad,{label:"Email",value:v.email,onChange:D("email"),type:"email"}),e.jsx(Ad,{label:"Phone",value:v.phone,onChange:D("phone")})]}),e.jsx(Ad,{label:"Current Brokerage",value:v.current_brokerage,onChange:D("current_brokerage")}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ad,{label:"License #",value:v.license_number,onChange:D("license_number")}),e.jsx(Ad,{label:"Experience (years)",value:v.experience_years,onChange:D("experience_years"),type:"number"})]}),e.jsx(Ad,{label:"Address",value:v.address,onChange:D("address"),placeholder:"Street address"}),e.jsxs("div",{className:"grid grid-cols-3 gap-3",children:[e.jsx(Ad,{label:"City",value:v.city,onChange:D("city")}),e.jsx(Ad,{label:"State",value:v.state,onChange:D("state")}),e.jsx(Ad,{label:"Zip",value:v.zip_code,onChange:D("zip_code")})]}),e.jsx(Ad,{label:"Source",value:v.source,onChange:D("source")}),e.jsx(Ad,{label:"Referred By",value:v.referred_by,onChange:D("referred_by")}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Notes"}),e.jsx(Ms,{value:v.notes,onChange:W=>j(ee=>({...ee,notes:W.target.value})),rows:3,className:"mt-1 text-sm"})]})]}),e.jsxs(is,{value:"production",className:"mt-3 space-y-3",children:[e.jsx(Ad,{label:"Annual Production",value:v.annual_production,onChange:D("annual_production"),placeholder:"e.g. $5M"}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(Ad,{label:"Last Year Volume",value:v.last_year_volume,onChange:D("last_year_volume"),placeholder:"e.g. $8.2M"}),e.jsx(Ad,{label:"Last Year Transactions",value:v.last_year_transactions,onChange:D("last_year_transactions"),type:"number",placeholder:"e.g. 24"})]}),e.jsx(Ad,{label:"Avg Sale Price",value:v.avg_sale_price,onChange:D("avg_sale_price"),placeholder:"e.g. $350K"}),e.jsx(Ad,{label:"Specialties / Niche",value:v.specialties,onChange:D("specialties"),placeholder:"e.g. Luxury, Investment"})]}),e.jsxs(is,{value:"social",className:"mt-3 space-y-3",children:[e.jsx(Ad,{label:"LinkedIn URL",value:v.linkedin_url,onChange:D("linkedin_url"),type:"url",placeholder:"https://linkedin.com/in/..."}),e.jsx(Ad,{label:"Website URL",value:v.website_url,onChange:D("website_url"),type:"url",placeholder:"https://..."}),e.jsx(Ad,{label:"Instagram Handle",value:v.instagram_handle,onChange:D("instagram_handle"),placeholder:"@handle"}),e.jsx(Ad,{label:"Facebook URL",value:v.facebook_url,onChange:D("facebook_url"),type:"url",placeholder:"https://facebook.com/..."})]}),e.jsxs(is,{value:"personal",className:"mt-3 space-y-3",children:[e.jsx(Ad,{label:"Birthday",value:v.birthday,onChange:D("birthday"),type:"date"}),e.jsx(Ad,{label:"Spouse / Partner",value:v.spouse_name,onChange:D("spouse_name")}),e.jsx(Ad,{label:"Interests / Hobbies",value:v.interests,onChange:D("interests"),placeholder:"Golf, travel, community events..."})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(is,{value:"details",className:"mt-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(I0,{label:"Current Brokerage",value:s.current_brokerage}),e.jsx(I0,{label:"License #",value:s.license_number}),e.jsx(I0,{label:"Experience",value:s.experience_years!=null?`${s.experience_years} years`:null}),e.jsx(I0,{label:"Referred By",value:s.referred_by}),e.jsx(I0,{label:"Source",value:s.source})]}),s.notes&&e.jsxs("div",{className:"mt-3",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Notes"}),e.jsx("p",{className:"text-sm mt-1 whitespace-pre-wrap",children:s.notes})]})]}),e.jsx(is,{value:"production",className:"mt-3",children:H?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(I0,{label:"Annual Production",value:s.annual_production}),e.jsx(I0,{label:"Last Year Volume",value:s.last_year_volume}),e.jsx(I0,{label:"Last Year Transactions",value:s.last_year_transactions}),e.jsx(I0,{label:"Avg Sale Price",value:s.avg_sale_price}),e.jsx(I0,{label:"Specialties / Niche",value:s.specialties})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No production data added yet"})}),e.jsx(is,{value:"social",className:"mt-3",children:Z?e.jsxs("div",{className:"space-y-2",children:[e.jsx(vG,{label:"LinkedIn",url:s.linkedin_url,icon:xf}),e.jsx(vG,{label:"Website",url:s.website_url,icon:lc}),s.instagram_handle&&e.jsx(vG,{label:s.instagram_handle,url:`https://instagram.com/${s.instagram_handle.replace("@","")}`,icon:ou}),e.jsx(vG,{label:"Facebook",url:s.facebook_url,icon:Mh})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No social profiles added yet"})}),e.jsx(is,{value:"personal",className:"mt-3",children:Y?e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsx(I0,{label:"Birthday",value:s.birthday?Ss(new Date(s.birthday+"T00:00:00"),"MMMM d, yyyy"):null,icon:Oi}),e.jsx(I0,{label:"Spouse / Partner",value:s.spouse_name,icon:gi}),e.jsx("div",{className:"col-span-2",children:e.jsx(I0,{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(Sen,{prospectId:s.id,prospectName:`${s.first_name} ${s.last_name||""}`,prospectEmail:s.email,brokerageId:n}),e.jsx(al,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Activity Log"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>f(!p),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Log Activity"]})]}),p&&e.jsxs("div",{className:"border rounded-lg p-3 mb-4 space-y-3 bg-muted/30",children:[e.jsxs(us,{value:u.type,onValueChange:W=>h(ee=>({...ee,type:W})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:nXe.map(W=>e.jsx(Ze,{value:W.value,children:W.label},W.value))})]}),e.jsx(ye,{placeholder:"Subject / Title",value:u.title,onChange:W=>h(ee=>({...ee,title:W.target.value}))}),e.jsx(Ms,{placeholder:"Details (optional)",value:u.description,onChange:W=>h(ee=>({...ee,description:W.target.value})),rows:2}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>f(!1),children:"Cancel"}),e.jsx(B,{size:"sm",onClick:I,disabled:!u.title.trim(),children:"Save"})]})]}),e.jsx("div",{className:"space-y-3",children:(()=>{const W=[...o.map(ee=>({type:"manual",data:ee,date:ee.created_at})),...d.map(ee=>({type:"campaign_email",data:ee,date:ee.sent_at||ee.created_at}))].sort((ee,se)=>new Date(se.date).getTime()-new Date(ee.date).getTime());return W.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No activity logged yet"}):W.map(ee=>{if(ee.type==="manual"){const oe=ee.data,he=nXe.find(me=>me.value===oe.activity_type),ce=(he==null?void 0:he.icon)||br;return e.jsxs("div",{className:"flex gap-3 text-sm",children:[e.jsx("div",{className:"mt-0.5",children:e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center",children:e.jsx(ce,{className:"h-3.5 w-3.5 text-muted-foreground"})})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children: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:Ss(new Date(oe.created_at),"MMM d, yyyy h:mm a")})]})]},`activity-${oe.id}`)}const se=ee.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(lr,{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 #",se.email_number]}),e.jsx("p",{className:"text-muted-foreground text-xs mt-0.5",children:se.subject}),e.jsxs("div",{className:"flex flex-wrap items-center gap-1.5 mt-1.5",children:[se.status==="failed"?e.jsx(Ue,{variant:"destructive",className:"text-[10px] px-1.5 py-0 h-4",children:"Failed"}):e.jsxs(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-green-500 text-green-600",children:[e.jsx(lr,{className:"h-2.5 w-2.5 mr-0.5"})," Sent"]}),se.opened_at?e.jsxs(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-blue-500 text-blue-600",children:[e.jsx(Sr,{className:"h-2.5 w-2.5 mr-0.5"})," Opened ",Ss(new Date(se.opened_at),"MMM d, h:mm a")]}):se.status!=="failed"?e.jsx(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 text-muted-foreground",children:"Not opened"}):null,se.clicked_at&&e.jsxs(Ue,{variant:"outline",className:"text-[10px] px-1.5 py-0 h-4 border-purple-500 text-purple-600",children:[e.jsx(Lm,{className:"h-2.5 w-2.5 mr-0.5"})," Clicked ",Ss(new Date(se.clicked_at),"MMM d, h:mm a")]})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:Ss(new Date(se.sent_at||se.created_at),"MMM d, yyyy h:mm a")})]})]},`send-${se.id}`)})})()})]})]})})}),e.jsx(Ten,{open:w,onOpenChange:S,prospectId:s.id,brokerageId:s.brokerage_id,prospectName:`${s.first_name} ${s.last_name??""}`.trim(),prospectEmail:s.email})]})}const Aen=["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 M2t({open:s,onOpenChange:t,brokerageId:n,stages:r}){var z;const{toast:a}=Fa(),i=Kt(),l=N.useRef(null),[o,c]=N.useState([]),[d,u]=N.useState([]),[h,p]=N.useState({}),[f,y]=N.useState(((z=r[0])==null?void 0:z.id)||""),[_,v]=N.useState(!1),[j,w]=N.useState("upload"),[S,A]=N.useState(0),E=()=>{c([]),u([]),p({}),w("upload"),A(0)},O=H=>{var W;const Z=(W=H.target.files)==null?void 0:W[0];if(!Z)return;const Y=new FileReader;Y.onload=ee=>{var ve;const oe=((ve=ee.target)==null?void 0:ve.result).split(/\r?\n/).filter(ge=>ge.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 he=D(oe[0]);u(he);const ce={},me=new Set;he.forEach((ge,Te)=>{const Ie=ge.toLowerCase().replace(/[^a-z0-9]/g,"");let Ce=null;/^firstname$/.test(Ie)||Ie==="first"?Ce="first_name":/^lastname$/.test(Ie)||Ie==="last"?Ce="last_name":/^email$/.test(Ie)||Ie==="emailaddress"?Ce="email":/^mobile$|^phone$|^cellphone$|^mobilephone$/.test(Ie)?Ce="phone":/officename|currentbrokerage|brokerage|company/.test(Ie)?Ce="current_brokerage":/membernumber|licensenumber|license/.test(Ie)?Ce="license_number":/experienceyears|yearsexperience/.test(Ie)?Ce="experience_years":/^totalvolume$|annualproduction/.test(Ie)?Ce="annual_production":/^address$/.test(Ie)?Ce="address":/^city$/.test(Ie)?Ce="city":/^state$/.test(Ie)?Ce="state":/^postalcode$|^zip$|^zipcode$/.test(Ie)?Ce="zip_code":/listsidevolume|lastyearvolume/.test(Ie)?Ce="last_year_volume":/^totalcount$|lastyeartransactions/.test(Ie)?Ce="last_year_transactions":/avgsaleprice|averageprice/.test(Ie)?Ce="avg_sale_price":/linkedin/.test(Ie)?Ce="linkedin_url":/website/.test(Ie)?Ce="website_url":/specialt/.test(Ie)?Ce="specialties":/referr/.test(Ie)?Ce="referred_by":/^notes$|^note$/.test(Ie)&&(Ce="notes"),Ce&&!me.has(Ce)&&(ce[String(Te)]=Ce,me.add(Ce))}),p(ce);const le=oe.slice(1).map(ge=>{const Te=D(ge),Ie={};return he.forEach((Ce,Me)=>{Ie[String(Me)]=Te[Me]||""}),Ie});c(le),w("map")},Y.readAsText(Z)},D=H=>{const Z=[];let Y="",W=!1;for(const ee of H)ee==='"'?W=!W:ee===","&&!W?(Z.push(Y.trim()),Y=""):Y+=ee;return Z.push(Y.trim()),Z},I=async()=>{v(!0);try{const{data:{user:H}}=await q.auth.getUser();if(!H)throw new Error("Not authenticated");const Z=o.map(W=>{const ee={brokerage_id:n,created_by:H.id,stage_id:f,source:"csv_import",first_name:"Unknown"},se=ee;return Object.entries(h).forEach(([oe,he])=>{var me;const ce=(me=W[oe])==null?void 0:me.trim();ce&&(he==="experience_years"||he==="last_year_transactions"?se[he]=parseInt(ce.replace(/[^0-9.-]/g,""))||null:he==="annual_production"||he==="last_year_volume"||he==="avg_sale_price"?se[he]=ce.replace(/[^0-9.$,.-]/g,""):se[he]=ce)}),ee});let Y=0;for(let W=0;W{const H=`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`,Z=new Blob([H],{type:"text/csv"}),Y=URL.createObjectURL(Z),W=document.createElement("a");W.href=Y,W.download="recruit-prospects-template.csv",W.click(),URL.revokeObjectURL(Y)};return e.jsx(_s,{open:s,onOpenChange:H=>{H||E(),t(H)},children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Import Prospects from CSV"})}),j==="upload"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-8 text-center",children:[e.jsx(mw,{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:O}),e.jsxs(B,{onClick:()=>{var H;return(H=l.current)==null?void 0:H.click()},children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Choose File"]})]}),e.jsx(B,{variant:"link",className:"text-xs",onClick:F,children:"Download CSV template"})]}),j==="map"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," rows found"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"text-sm",children:"Import to stage:"}),e.jsxs(us,{value:f,onValueChange:y,children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{})}),e.jsx(cs,{children:r.map(H=>e.jsx(Ze,{value:H.id,children:H.name},H.id))})]})]})]}),e.jsx("div",{className:"border rounded-lg overflow-hidden",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-[140px]",children:"CSV Column"}),e.jsx(Tt,{className:"w-[160px]",children:"Map To"}),e.jsx(Tt,{children:"Preview"})]})}),e.jsx(da,{children:d.map((H,Z)=>{var Y;return e.jsxs(Hs,{children:[e.jsx(ht,{className:"font-medium text-xs",children:H}),e.jsx(ht,{children:e.jsxs(us,{value:h[String(Z)]||"skip",onValueChange:W=>p(ee=>({...ee,[String(Z)]:W==="skip"?"":W})),children:[e.jsx(ls,{className:"h-8 text-xs",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"skip",children:"— Skip —"}),Aen.map(W=>e.jsx(Ze,{value:W,children:W.replace(/_/g," ")},W))]})]})}),e.jsx(ht,{className:"text-xs text-muted-foreground truncate max-w-[200px]",children:((Y=o[0])==null?void 0:Y[String(Z)])||"—"})]},Z)})})]})}),!Object.values(h).includes("first_name")&&e.jsxs("div",{className:"flex items-center gap-2 text-amber-600 text-sm",children:[e.jsx(Bi,{className:"h-4 w-4"}),' Map at least "first name" to proceed']}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>{E()},children:"Back"}),e.jsx(B,{onClick:I,disabled:_||!Object.values(h).includes("first_name"),children:_?"Importing...":`Import ${o.length} Prospects`})]})]}),j==="done"&&e.jsxs("div",{className:"text-center py-6 space-y-3",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-green-500/10 flex items-center justify-center mx-auto",children:e.jsx(Lr,{className:"h-6 w-6 text-green-600"})}),e.jsxs("p",{className:"font-semibold",children:[S," prospects imported successfully!"]}),e.jsx(B,{onClick:()=>{E(),t(!1)},children:"Close"})]})]})})}function I2t({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=BU(s),[o,c]=N.useState(!1),[d,u]=N.useState(),[h,p]=N.useState(null),[f,y]=N.useState(!1),[_,v]=N.useState(!1),[j,w]=N.useState(null);if(r)return e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const S=F=>n.filter(z=>z.stage_id===F),A=(F,z)=>{w(z),F.dataTransfer.effectAllowed="move"},E=F=>{F.preventDefault(),F.dataTransfer.dropEffect="move"},O=(F,z)=>{F.preventDefault(),j&&(i.mutate({id:j,stage_id:z}),w(null))},D=F=>{u(F),c(!0)},I=F=>{p(F),y(!0)};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{children:e.jsxs("p",{className:"text-sm text-muted-foreground",children:[n.length," prospect",n.length!==1?"s":""]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>{u(void 0),c(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs(di,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:t.length*300},children:t.map(F=>{const z=S(F.id);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:E,onDrop:H=>O(H,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(Ue,{variant:"secondary",className:"text-xs h-5 px-1.5",children:z.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>D(F.id),children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]}),e.jsx("div",{className:"space-y-2 min-h-[200px] bg-muted/30 rounded-lg p-2",children:z.map(H=>e.jsx(fe,{className:"p-3 cursor-pointer hover:shadow-md transition-shadow border-l-4 group",style:{borderLeftColor:F.color},draggable:!0,onDragStart:Z=>A(Z,H.id),onClick:()=>I(H),children:e.jsxs("div",{className:"flex items-start gap-2",children:[e.jsx(Pu,{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(Wi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsxs("span",{className:"font-medium text-sm truncate",children:[H.first_name," ",H.last_name]})]}),H.current_brokerage&&e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground",children:[e.jsx(Ua,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:H.current_brokerage})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[H.email&&e.jsx(Gs,{className:"h-3 w-3 text-muted-foreground"}),H.phone&&e.jsx(Cr,{className:"h-3 w-3 text-muted-foreground"}),H.experience_years!=null&&e.jsxs(Ue,{variant:"secondary",className:"text-[10px] h-4 px-1",children:[H.experience_years,"yr"]})]})]})]})},H.id))})]},F.id)})}),e.jsx(Q$,{orientation:"horizontal"})]}),e.jsx(k2t,{open:o,onOpenChange:c,stages:t,defaultStageId:d,onSubmit:F=>a.mutate(F),isSubmitting:a.isPending}),e.jsx(A2t,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:y,onUpdate:F=>{i.mutate(F),p(z=>z?{...z,...F}:null)},onDelete:F=>l.mutate(F)}),e.jsx(M2t,{open:_,onOpenChange:v,brokerageId:s,stages:t})]})}function Lge({brokerageId:s}){const{stages:t,prospects:n,isLoading:r,addProspect:a,updateProspect:i,deleteProspect:l}=BU(s),{user:o}=vs(),c=Kt(),[d,u]=N.useState(!1),[h,p]=N.useState(null),[f,y]=N.useState(!1),[_,v]=N.useState(!1),[j,w]=N.useState(""),[S,A]=N.useState("all"),[E,O]=N.useState("all"),[D,I]=N.useState("all"),[F,z]=N.useState(null),[H,Z]=N.useState("asc"),[Y,W]=N.useState(new Set),[ee,se]=N.useState(!1),[oe,he]=N.useState(""),ce=N.useMemo(()=>{const we=new Set;return n.forEach(Je=>{Je.current_brokerage&&we.add(Je.current_brokerage)}),Array.from(we).sort()},[n]),{data:me=[]}=dt({queryKey:["recruit-campaigns-list",s],queryFn:async()=>{const{data:we,error:Je}=await q.from("recruit_campaigns").select("id, name, warmth_level").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("name");if(Je)throw Je;return we}}),{data:le=[]}=dt({queryKey:["recruit-campaign-assignments-lookup",s],queryFn:async()=>{let Je=[],ke=0;for(;;){const{data:it,error:je}=await q.from("recruit_campaign_assignments").select("prospect_id, campaign_id, status").eq("brokerage_id",s).range(ke,ke+1e3-1);if(je)throw je;if(Je=Je.concat(it??[]),!it||it.length<1e3)break;ke+=1e3}return Je}}),ve=N.useMemo(()=>{const we=new Map;return le.forEach(Je=>{we.has(Je.prospect_id)||we.set(Je.prospect_id,new Set),we.get(Je.prospect_id).add(Je.campaign_id)}),we},[le]),ge=we=>{F===we?Z(Je=>Je==="asc"?"desc":"asc"):(z(we),Z("asc"))},Te=({column:we})=>F!==we?e.jsx(ah,{className:"h-3.5 w-3.5 ml-1 text-muted-foreground/50"}):H==="asc"?e.jsx(Iu,{className:"h-3.5 w-3.5 ml-1 text-primary"}):e.jsx(sm,{className:"h-3.5 w-3.5 ml-1 text-primary"}),Ie=we=>t.find(Je=>Je.id===we),Ce=N.useMemo(()=>{let we=n.filter(Je=>{var $e,Ke,Ge;const ke=!j||`${Je.first_name} ${Je.last_name}`.toLowerCase().includes(j.toLowerCase())||(($e=Je.email)==null?void 0:$e.toLowerCase().includes(j.toLowerCase()))||((Ke=Je.current_brokerage)==null?void 0:Ke.toLowerCase().includes(j.toLowerCase())),it=S==="all"||Je.stage_id===S,je=E==="all"||Je.current_brokerage===E;let He=!0;return D==="in_campaign"?He=ve.has(Je.id):D==="not_in_campaign"?He=!ve.has(Je.id):D!=="all"&&(He=((Ge=ve.get(Je.id))==null?void 0:Ge.has(D))??!1),ke&&it&&je&&He});return F&&(we=[...we].sort((Je,ke)=>{var $e,Ke;let it=null,je=null;switch(F){case"name":it=`${Je.first_name} ${Je.last_name||""}`.toLowerCase(),je=`${ke.first_name} ${ke.last_name||""}`.toLowerCase();break;case"stage":it=(($e=Ie(Je.stage_id))==null?void 0:$e.sort_order)??999,je=((Ke=Ie(ke.stage_id))==null?void 0:Ke.sort_order)??999;break;case"brokerage":it=(Je.current_brokerage||"").toLowerCase(),je=(ke.current_brokerage||"").toLowerCase();break;case"experience":it=Je.experience_years??-1,je=ke.experience_years??-1;break;case"production":it=(Je.annual_production||"").toLowerCase(),je=(ke.annual_production||"").toLowerCase();break;case"source":it=(Je.source||"").toLowerCase(),je=(ke.source||"").toLowerCase();break;default:return 0}if(it===je)return 0;if(it==null)return 1;if(je==null)return-1;const He=it0&&Ce.every(we=>Y.has(we.id)),Pe=Ce.some(we=>Y.has(we.id)),Re=()=>{W(Me?new Set:new Set(Ce.map(we=>we.id)))},Ae=we=>{W(Je=>{const ke=new Set(Je);return ke.has(we)?ke.delete(we):ke.add(we),ke})},Be=yt({mutationFn:async()=>{if(!oe||!(o!=null&&o.id))throw new Error("Select a campaign");const we=new Set(le.filter(it=>it.campaign_id===oe).map(it=>it.prospect_id)),Je=Array.from(Y).filter(it=>!we.has(it)).map(it=>({prospect_id:it,campaign_id:oe,brokerage_id:s,assigned_by:o.id,status:"active",current_email_number:0}));if(Je.length===0)throw new Error("All selected prospects are already in this campaign");const{error:ke}=await q.from("recruit_campaign_assignments").insert(Je);if(ke)throw ke;return Je.length},onSuccess:we=>{ae.success(`${we} prospect(s) added to campaign`),se(!1),W(new Set),he(""),c.invalidateQueries({queryKey:["recruit-campaign-assignments-lookup"]})},onError:we=>ae.error(we.message)});return r?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 max-w-sm min-w-[200px]",children:[e.jsx(gr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search prospects...",value:j,onChange:we=>w(we.target.value),className:"pl-8"})]}),e.jsxs("div",{className:"flex gap-2",children:[Y.size>0&&e.jsxs(B,{variant:"secondary",onClick:()=>se(!0),className:"gap-1.5",children:[e.jsx(lr,{className:"h-4 w-4"})," Add ",Y.size," to Campaign"]}),e.jsxs(B,{variant:"outline",onClick:()=>v(!0),children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Import CSV"]}),e.jsxs(B,{onClick:()=>u(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Add Prospect"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Lv,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs(us,{value:S,onValueChange:A,children:[e.jsx(ls,{className:"w-[160px] h-8 text-xs",children:e.jsx(hs,{placeholder:"All stages"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All stages"}),t.map(we=>e.jsx(Ze,{value:we.id,children:we.name},we.id))]})]}),e.jsxs(us,{value:E,onValueChange:O,children:[e.jsxs(ls,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Ua,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(hs,{placeholder:"All brokerages"})]}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All brokerages"}),ce.map(we=>e.jsx(Ze,{value:we,children:we},we))]})]}),e.jsxs(us,{value:D,onValueChange:I,children:[e.jsxs(ls,{className:"w-[200px] h-8 text-xs",children:[e.jsx(Gs,{className:"h-3.5 w-3.5 mr-1.5"}),e.jsx(hs,{placeholder:"Campaign status"})]}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All contacts"}),e.jsx(Ze,{value:"in_campaign",children:"In any campaign"}),e.jsx(Ze,{value:"not_in_campaign",children:"Not in any campaign"}),me.map(we=>e.jsxs(Ze,{value:we.id,children:["In: ",we.name]},we.id))]})]}),(S!=="all"||E!=="all"||D!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs text-muted-foreground",onClick:()=>{A("all"),O("all"),I("all")},children:"Clear filters"})]}),e.jsx("div",{className:"rounded-md border",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{className:"w-[40px]",children:e.jsx(hi,{checked:Me,onCheckedChange:Re,"aria-label":"Select all",...Pe&&!Me?{"data-state":"indeterminate"}:{}})}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>ge("name"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Name ",e.jsx(Te,{column:"name"})]})}),e.jsx(Tt,{className:"cursor-pointer select-none",onClick:()=>ge("stage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Stage ",e.jsx(Te,{column:"stage"})]})}),e.jsx(Tt,{className:"hidden md:table-cell cursor-pointer select-none",onClick:()=>ge("brokerage"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Brokerage ",e.jsx(Te,{column:"brokerage"})]})}),e.jsx(Tt,{className:"hidden md:table-cell",children:"Contact"}),e.jsx(Tt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ge("experience"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Experience ",e.jsx(Te,{column:"experience"})]})}),e.jsx(Tt,{className:"hidden lg:table-cell cursor-pointer select-none",onClick:()=>ge("production"),children:e.jsxs("span",{className:"inline-flex items-center",children:["Production ",e.jsx(Te,{column:"production"})]})}),e.jsx(Tt,{className:"hidden lg:table-cell",children:"Campaigns"}),e.jsx(Tt,{className:"w-[50px]"})]})}),e.jsx(da,{children:Ce.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:9,className:"text-center text-muted-foreground py-8",children:"No prospects found"})}):Ce.map(we=>{const Je=Ie(we.stage_id),ke=ve.get(we.id),it=(ke==null?void 0:ke.size)??0;return e.jsxs(Hs,{className:"cursor-pointer",onClick:()=>{p(we),y(!0)},children:[e.jsx(ht,{onClick:je=>je.stopPropagation(),children:e.jsx(hi,{checked:Y.has(we.id),onCheckedChange:()=>Ae(we.id),"aria-label":`Select ${we.first_name}`})}),e.jsxs(ht,{className:"font-medium",children:[we.first_name," ",we.last_name]}),e.jsx(ht,{children:Je?e.jsxs(Ue,{variant:"outline",className:"text-xs gap-1 whitespace-nowrap",style:{borderColor:Je.color,color:Je.color,backgroundColor:`${Je.color}10`},children:[e.jsx("span",{className:"h-1.5 w-1.5 rounded-full inline-block",style:{backgroundColor:Je.color}}),Je.name]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"—"})}),e.jsx(ht,{className:"hidden md:table-cell",children:we.current_brokerage?e.jsxs("div",{className:"flex items-center gap-1.5 text-sm",children:[e.jsx(Ua,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"truncate max-w-[150px]",children:we.current_brokerage})]}):e.jsx("span",{className:"text-muted-foreground",children:"—"})}),e.jsx(ht,{className:"hidden md:table-cell",children:e.jsxs("div",{className:"flex items-center gap-2",children:[we.email&&e.jsx(Gs,{className:"h-3.5 w-3.5 text-muted-foreground"}),we.phone&&e.jsx(Cr,{className:"h-3.5 w-3.5 text-muted-foreground"}),!we.email&&!we.phone&&e.jsx("span",{className:"text-muted-foreground",children:"—"})]})}),e.jsx(ht,{className:"hidden lg:table-cell",children:we.experience_years!=null?`${we.experience_years} yr`:"—"}),e.jsx(ht,{className:"hidden lg:table-cell",children:we.annual_production||"—"}),e.jsx(ht,{className:"hidden lg:table-cell",children:it>0?e.jsxs(Ue,{variant:"secondary",className:"text-xs",children:[it," campaign",it>1?"s":""]}):e.jsx("span",{className:"text-muted-foreground text-xs",children:"None"})}),e.jsx(ht,{children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:je=>{je.stopPropagation(),l.mutate(we.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})})]},we.id)})})]})}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Y.size>0&&e.jsxs("span",{className:"font-medium text-foreground",children:[Y.size," selected · "]}),Ce.length," of ",n.length," prospects"]}),e.jsx(_s,{open:ee,onOpenChange:se,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsx(js,{children:e.jsx(ws,{children:"Add to Campaign"})}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:["Add ",e.jsx("span",{className:"font-medium text-foreground",children:Y.size})," selected prospect(s) to a recruiting campaign drip."]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Campaign"}),e.jsxs(us,{value:oe,onValueChange:he,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a campaign..."})}),e.jsx(cs,{children:me.map(we=>e.jsxs(Ze,{value:we.id,children:[we.name," ",e.jsxs("span",{className:"text-muted-foreground ml-1",children:["(",we.warmth_level,")"]})]},we.id))})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>se(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>Be.mutate(),disabled:!oe||Be.isPending,children:Be.isPending?"Adding...":"Add to Campaign"})]})]})}),e.jsx(k2t,{open:d,onOpenChange:u,stages:t,onSubmit:we=>a.mutate(we),isSubmitting:a.isPending}),e.jsx(A2t,{prospect:h,stages:t,brokerageId:s,open:f,onOpenChange:y,onUpdate:we=>{i.mutate(we),p(Je=>Je?{...Je,...we}:null)},onDelete:we=>l.mutate(we)}),e.jsx(M2t,{open:_,onOpenChange:v,brokerageId:s,stages:t})]})}function P2t({brokerageId:s}){const{stages:t,prospects:n,isLoading:r}=BU(s),a=N.useMemo(()=>{if(!t.length||!n.length)return null;const i=n.length,l=t.find(j=>j.name==="Signed"),o=t.find(j=>j.name==="Onboarded"),c=n.filter(j=>j.stage_id===(l==null?void 0:l.id)||j.stage_id===(o==null?void 0:o.id)).length,d=i>0?(c/i*100).toFixed(1):"0",u=new Date,h=i>0?Math.round(n.reduce((j,w)=>j+Vv(u,new Date(w.created_at)),0)/i):0,p=t.map(j=>({...j,count:n.filter(w=>w.stage_id===j.id).length})),f={};n.forEach(j=>{const w=j.source||"unknown";f[w]=(f[w]||0)+1});const y=Object.entries(f).sort((j,w)=>w[1]-j[1]),_=new Date;_.setDate(_.getDate()-30);const v=n.filter(j=>new Date(j.created_at)>=_).length;return{total:i,signed:c,conversionRate:d,avgDays:h,byStage:p,bySrc:y,recentCount:v}},[t,n]);return r?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):a?e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-blue-500/10 flex items-center justify-center",children:e.jsx(An,{className:"h-5 w-5 text-blue-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.total}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Total Prospects"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-green-500/10 flex items-center justify-center",children:e.jsx(go,{className:"h-5 w-5 text-green-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.conversionRate,"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Conversion Rate"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-amber-500/10 flex items-center justify-center",children:e.jsx(pr,{className:"h-5 w-5 text-amber-600"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-2xl font-bold",children:[a.avgDays,"d"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Avg Days in Pipeline"})]})]})})}),e.jsx(fe,{children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-lg bg-violet-500/10 flex items-center justify-center",children:e.jsx(Ac,{className:"h-5 w-5 text-violet-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.recentCount}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Added (30 days)"})]})]})})})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-6",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Pipeline Breakdown"})}),e.jsx(Ee,{className:"space-y-3",children:a.byStage.map(i=>{const l=a.total>0?i.count/a.total*100:0;return e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-2.5 w-2.5 rounded-full",style:{backgroundColor:i.color}}),e.jsx("span",{children:i.name})]}),e.jsx("span",{className:"font-medium",children:i.count})]}),e.jsx("div",{className:"h-2 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full transition-all",style:{width:`${l}%`,backgroundColor:i.color}})})]},i.id)})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Lead Sources"})}),e.jsxs(Ee,{className:"space-y-3",children:[a.bySrc.map(([i,l])=>e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Ue,{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 Men=["Outreach","Follow-up","Interview","Offer","Referral","Other"];function L2t({brokerageId:s}){const{toast:t}=Fa(),{user:n}=vs(),r=Kt(),[a,i]=N.useState(null),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),{data:p=[],isLoading:f}=dt({queryKey:["recruit-email-templates-manage",s],queryFn:async()=>{const{data:A,error:E}=await q.from("recruit_email_templates").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(E)throw E;return A}}),y=yt({mutationFn:async A=>{if(A.id){const{error:E}=await q.from("recruit_email_templates").update({category:A.category,title:A.title,subject:A.subject,body:A.body}).eq("id",A.id);if(E)throw E}else{const{error:E}=await q.from("recruit_email_templates").insert({brokerage_id:s,category:A.category||"Outreach",title:A.title,subject:A.subject,body:A.body,created_by:n==null?void 0:n.id,sort_order:100});if(E)throw E}},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template saved"}),d(!1),h(null)},onError:A=>t({title:"Save failed",description:A.message,variant:"destructive"})}),_=yt({mutationFn:async A=>{const{error:E}=await q.from("recruit_email_templates").delete().eq("id",A);if(E)throw E},onSuccess:()=>{r.invalidateQueries({queryKey:["recruit-email-templates-manage",s]}),r.invalidateQueries({queryKey:["recruit-email-templates"]}),t({title:"Template deleted"})},onError:A=>t({title:"Delete failed",description:A.message,variant:"destructive"})}),v=(A,E)=>{navigator.clipboard.writeText(A),i(E),t({title:"Copied to clipboard!"}),setTimeout(()=>i(null),2e3)},j=()=>{h({category:"Outreach",title:"",subject:"",body:""}),d(!0)},w=A=>{h(A),d(!0)},S=Array.from(new Set(p.map(A=>A.category)));return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pre-built and custom recruiting templates. Built-in templates are global; your custom ones are private to this brokerage."}),e.jsxs(B,{onClick:j,size:"sm",className:"gap-1.5",children:[e.jsx(Is,{className:"h-4 w-4"})," New Template"]})]}),f?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(rs,{className:"h-5 w-5 animate-spin text-muted-foreground"})}):S.map(A=>e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"font-semibold text-sm flex items-center gap-2",children:[e.jsx(Gs,{className:"h-4 w-4"})," ",A]}),p.filter(E=>E.category===A).map(E=>{const O=E.brokerage_id!==null;return e.jsxs(fe,{className:`transition-all ${l===E.id?"ring-2 ring-primary/20":"hover:shadow-sm"}`,children:[e.jsx(It,{className:"pb-2 cursor-pointer",onClick:()=>o(l===E.id?null:E.id),children:e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs(Rt,{className:"text-sm flex items-center gap-2",children:[e.jsx("span",{className:"truncate",children:E.title}),!O&&e.jsx(Ue,{variant:"secondary",className:"text-[10px] shrink-0",children:"Built-in"}),O&&e.jsx(Ue,{className:"text-[10px] shrink-0",children:"Custom"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:["Subject: ",E.subject]})]}),e.jsx(Ue,{variant:"outline",className:"text-[10px] shrink-0",children:E.category})]})}),l===E.id&&e.jsxs(Ee,{className:"pt-0 space-y-3",children:[e.jsxs("div",{className:"bg-muted/50 rounded-lg p-4",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground mb-1",children:"Subject Line:"}),e.jsx("p",{className:"text-sm mb-3",children:E.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:E.body})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>v(E.subject,E.id+"-s"),children:[a===E.id+"-s"?e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Copy Subject"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>v(E.body,E.id+"-b"),children:[a===E.id+"-b"?e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Copy Body"]}),O&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>w(E),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"text-destructive hover:text-destructive",onClick:()=>{confirm("Delete this template?")&&_.mutate(E.id)},children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1"})," Delete"]})]})]})]})]},E.id)})]},A)),e.jsx(_s,{open:c,onOpenChange:d,children:e.jsxs(bs,{className:"max-w-2xl",children:[e.jsx(js,{children:e.jsx(ws,{children:u!=null&&u.id?"Edit Template":"New Template"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Title"}),e.jsx(ye,{value:(u==null?void 0:u.title)||"",onChange:A=>h(E=>({...E,title:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Category"}),e.jsx("select",{value:(u==null?void 0:u.category)||"Outreach",onChange:A=>h(E=>({...E,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:Men.map(A=>e.jsx("option",{value:A,children:A},A))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Subject"}),e.jsx(ye,{value:(u==null?void 0:u.subject)||"",onChange:A=>h(E=>({...E,subject:A.target.value})),className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Body"}),e.jsx(Ms,{value:(u==null?void 0:u.body)||"",onChange:A=>h(E=>({...E,body:A.target.value})),rows:12,className:"mt-1 font-sans",placeholder:`Hi [First Name], ... Best, [Your Name]`}),e.jsx("p",{className:"text-[11px] text-muted-foreground mt-1",children:"Available placeholders: [First Name], [Your Name], [Brokerage Name]"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>y.mutate(u||{}),disabled:y.isPending||!(u!=null&&u.title)||!(u!=null&&u.subject)||!(u!=null&&u.body),children:[y.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Save Template"]})]})]})})]})}const rXe={call:Cr,email:Gs,text:Ai,meeting:yr,note:br};function D2t({brokerageId:s}){const{data:t,isLoading:n}=dt({queryKey:["recruit-activity-report",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, created_by").eq("brokerage_id",s);if(a)throw a;const i=(r==null?void 0:r.map(f=>f.id))||[];if(i.length===0)return{recruiters:[],recentActivities:[]};const{data:l,error:o}=await q.from("recruit_activities").select("*").in("prospect_id",i).order("created_at",{ascending:!1});if(o)throw o;const c=[...new Set([...r.map(f=>f.created_by),...(l||[]).map(f=>f.created_by)])],{data:d}=await q.from("profiles").select("id, name, email").in("id",c),u=Object.fromEntries((d||[]).map(f=>[f.id,f])),h=R9(new Date,30);return{recruiters:c.map(f=>{var w,S;const y=(l||[]).filter(A=>A.created_by===f),_=y.filter(A=>new Date(A.created_at)>=h),v={};_.forEach(A=>{v[A.activity_type]=(v[A.activity_type]||0)+1});const j=r.filter(A=>A.created_by===f).length;return{id:f,name:((w=u[f])==null?void 0:w.name)||"Unknown",email:((S=u[f])==null?void 0:S.email)||"",totalActivities:y.length,recentActivities:_.length,byType:v,prospectsCreated:j}}).sort((f,y)=>y.recentActivities-f.recentActivities),recentActivities:(l||[]).slice(0,20)}},enabled:!!s});return n?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t!=null&&t.recruiters.length?e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Recruiter Leaderboard (Last 30 Days)"})}),e.jsx(Ee,{className:"space-y-4",children:t.recruiters.map((r,a)=>e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-lg bg-muted/30",children:[e.jsx("div",{className:"flex items-center justify-center h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-sm",children:a+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wi,{className:"h-3.5 w-3.5 text-muted-foreground"}),e.jsx("span",{className:"font-medium text-sm",children:r.name})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1.5",children:Object.entries(r.byType).map(([i,l])=>{const o=rXe[i]||br;return e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(o,{className:"h-2.5 w-2.5"})," ",l," ",i,l!==1?"s":""]},i)})})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.recentActivities}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"activities"})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("p",{className:"text-lg font-bold",children:r.prospectsCreated}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"prospects"})]})]},r.id))})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Recent Activity"})}),e.jsx(Ee,{className:"space-y-3",children:t.recentActivities.map(r=>{const a=rXe[r.activity_type]||br;return e.jsxs("div",{className:"flex items-start gap-3 text-sm",children:[e.jsx("div",{className:"h-7 w-7 rounded-full bg-muted flex items-center justify-center flex-shrink-0 mt-0.5",children:e.jsx(a,{className:"h-3.5 w-3.5 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium",children:r.title}),r.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:r.description}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5",children:Ss(new Date(r.created_at),"MMM d, h:mm a")})]})]},r.id)})})]})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No recruiter activity yet."})}function R2t({brokerageId:s}){const{toast:t}=Fa(),n=Kt(),[r,a]=N.useState(!1),[i,l]=N.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),{data:o=[],isLoading:c}=dt({queryKey:["recruit-referrals",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_referrals").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(j)throw j;return v}}),d=[...new Set(o.map(v=>v.referred_by))],{data:u=[]}=dt({queryKey:["referral-profiles",d],queryFn:async()=>{if(!d.length)return[];const{data:v}=await q.from("profiles").select("id, name, email").in("id",d);return v||[]},enabled:d.length>0}),h=Object.fromEntries(u.map(v=>[v.id,v])),p=yt({mutationFn:async v=>{const{data:{user:j}}=await q.auth.getUser();if(!j)throw new Error("Not authenticated");const{error:w}=await q.from("recruit_referrals").insert({brokerage_id:s,referred_by:j.id,referee_first_name:v.first_name,referee_last_name:v.last_name||null,referee_email:v.email||null,referee_phone:v.phone||null,referee_current_brokerage:v.current_brokerage||null,notes:v.notes||null});if(w)throw w},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-referrals",s]}),t({title:"Referral submitted!"}),l({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",notes:""}),a(!1)},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),f=yt({mutationFn:async({id:v,status:j,incentive_status:w})=>{const S={updated_at:new Date().toISOString()};j&&(S.status=j),w&&(S.incentive_status=w);const{error:A}=await q.from("recruit_referrals").update(S).eq("id",v);if(A)throw A},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-referrals",s]})}),y=v=>v==="approved"||v==="signed"?e.jsx(Lr,{className:"h-3 w-3"}):v==="rejected"?e.jsx(Uc,{className:"h-3 w-3"}):e.jsx(pr,{className:"h-3 w-3"}),_=v=>v==="approved"||v==="signed"||v==="paid"?"bg-green-500/10 text-green-600 border-green-200":v==="rejected"?"bg-red-500/10 text-red-600 border-red-200":"bg-amber-500/10 text-amber-600 border-amber-200";return c?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[o.length," referral",o.length!==1?"s":""]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Submit Referral"]})]}),o.length===0?e.jsxs(fe,{className:"py-12 text-center",children:[e.jsx(Fo,{className:"h-10 w-10 mx-auto text-muted-foreground mb-3"}),e.jsx("p",{className:"text-muted-foreground",children:"No referrals yet. Agents can refer potential recruits here."})]}):e.jsx("div",{className:"space-y-3",children:o.map(v=>{var j;return e.jsx(fe,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium",children:[v.referee_first_name," ",v.referee_last_name]}),e.jsxs(Ue,{variant:"outline",className:_(v.status),children:[y(v.status)," ",v.status]}),v.incentive_status&&e.jsxs(Ue,{variant:"outline",className:_(v.incentive_status),children:[e.jsx(Oi,{className:"h-3 w-3 mr-1"})," ",v.incentive_status]})]}),e.jsxs("div",{className:"text-xs text-muted-foreground space-y-0.5",children:[v.referee_email&&e.jsx("p",{children:v.referee_email}),v.referee_phone&&e.jsx("p",{children:v.referee_phone}),v.referee_current_brokerage&&e.jsxs("p",{children:["Currently at: ",v.referee_current_brokerage]}),e.jsxs("p",{children:["Referred by: ",((j=h[v.referred_by])==null?void 0:j.name)||"Unknown"," • ",Ss(new Date(v.created_at),"MMM d, yyyy")]})]}),v.notes&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1 italic",children:v.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsxs(us,{value:v.status,onValueChange:w=>f.mutate({id:v.id,status:w}),children:[e.jsx(ls,{className:"h-7 text-xs w-[110px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"pending",children:"Pending"}),e.jsx(Ze,{value:"contacted",children:"Contacted"}),e.jsx(Ze,{value:"approved",children:"Approved"}),e.jsx(Ze,{value:"signed",children:"Signed"}),e.jsx(Ze,{value:"rejected",children:"Rejected"})]})]}),e.jsxs(us,{value:v.incentive_status||"pending",onValueChange:w=>f.mutate({id:v.id,incentive_status:w}),children:[e.jsx(ls,{className:"h-7 text-xs w-[100px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"pending",children:"Unpaid"}),e.jsx(Ze,{value:"paid",children:"Paid"}),e.jsx(Ze,{value:"n/a",children:"N/A"})]})]})]})]})},v.id)})}),e.jsx(_s,{open:r,onOpenChange:a,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Submit a Recruit Referral"})}),e.jsxs("form",{onSubmit:v=>{v.preventDefault(),p.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"First Name *"}),e.jsx(ye,{required:!0,value:i.first_name,onChange:v=>l(j=>({...j,first_name:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Last Name"}),e.jsx(ye,{value:i.last_name,onChange:v=>l(j=>({...j,last_name:v.target.value}))})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Email"}),e.jsx(ye,{type:"email",value:i.email,onChange:v=>l(j=>({...j,email:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Phone"}),e.jsx(ye,{value:i.phone,onChange:v=>l(j=>({...j,phone:v.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Current Brokerage"}),e.jsx(ye,{value:i.current_brokerage,onChange:v=>l(j=>({...j,current_brokerage:v.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Notes"}),e.jsx(Ms,{value:i.notes,onChange:v=>l(j=>({...j,notes:v.target.value})),rows:2})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:p.isPending,children:"Submit"})]})]})]})})]})}function O2t({brokerageId:s}){const{toast:t}=Fa(),n=Kt(),[r,a]=N.useState(!1),{data:i}=dt({queryKey:["brokerage-recruit-form",s],queryFn:async()=>{const{data:p,error:f}=await q.from("brokerages").select("id, name, recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(f)throw f;return p}}),{data:l=[]}=dt({queryKey:["recruit-interest-submissions",s],queryFn:async()=>{const{data:p,error:f}=await q.from("recruit_interest_submissions").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1});if(f)throw f;return p}}),o=yt({mutationFn:async p=>{const{error:f}=await q.from("brokerages").update({recruit_form_enabled:p}).eq("id",s);if(f)throw f},onSuccess:()=>{n.invalidateQueries({queryKey:["brokerage-recruit-form",s]}),t({title:i!=null&&i.recruit_form_enabled?"Form disabled":"Form enabled"})}}),c=yt({mutationFn:async({id:p,status:f})=>{const{error:y}=await q.from("recruit_interest_submissions").update({status:f}).eq("id",p);if(y)throw y},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-interest-submissions",s]})}),d=`https://bestbrokerage.relevelup.com/join-brokerage/${(i==null?void 0:i.recruit_form_slug)||""}`,u=()=>{navigator.clipboard.writeText(d),a(!0),t({title:"Link copied!"}),setTimeout(()=>a(!1),2e3)},h=p=>p==="contacted"||p==="converted"?"bg-green-500/10 text-green-600":p==="dismissed"?"bg-red-500/10 text-red-600":"bg-blue-500/10 text-blue-600";return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Public Interest Form"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:(i==null?void 0:i.recruit_form_enabled)||!1,onCheckedChange:p=>o.mutate(p)})]}),(i==null?void 0:i.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg",children:[e.jsx("code",{className:"text-xs flex-1 truncate",children:d}),e.jsx(B,{size:"sm",variant:"outline",onClick:u,children:r?e.jsx(Lr,{className:"h-3.5 w-3.5"}):e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:d,target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-base",children:["Interest Submissions (",l.length,")"]})}),e.jsx(Ee,{children:l.length===0?e.jsxs("div",{className:"text-center py-8",children:[e.jsx(Fo,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No submissions yet"})]}):e.jsx("div",{className:"space-y-3",children:l.map(p=>e.jsxs("div",{className:"flex items-start justify-between gap-4 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1",children:[e.jsxs("span",{className:"font-medium text-sm",children:[p.first_name," ",p.last_name]}),e.jsx(Ue,{variant:"outline",className:h(p.status),children:p.status})]}),e.jsxs("div",{className:"flex flex-wrap gap-3 text-xs text-muted-foreground",children:[p.email&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gs,{className:"h-3 w-3"}),p.email]}),p.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Cr,{className:"h-3 w-3"}),p.phone]}),p.current_brokerage&&e.jsxs("span",{children:["From: ",p.current_brokerage]}),p.experience_years&&e.jsxs("span",{children:[p.experience_years,"yr exp"]})]}),p.why_interested&&e.jsxs("p",{className:"text-xs text-muted-foreground mt-1 italic",children:['"',p.why_interested,'"']}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:Ss(new Date(p.created_at),"MMM d, yyyy h:mm a")})]}),e.jsxs(us,{value:p.status,onValueChange:f=>c.mutate({id:p.id,status:f}),children:[e.jsx(ls,{className:"h-7 text-xs w-[110px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"new",children:"New"}),e.jsx(Ze,{value:"contacted",children:"Contacted"}),e.jsx(Ze,{value:"converted",children:"Converted"}),e.jsx(Ze,{value:"dismissed",children:"Dismissed"})]})]})]},p.id))})})]})]})}function F2t({brokerageId:s}){const{toast:t}=Fa(),n=Kt(),[r,a]=N.useState(!1),[i,l]=N.useState({prospect_id:"",title:"",description:"",due_date:Ss(Bl(new Date,1),"yyyy-MM-dd'T'HH:mm")}),[o,c]=N.useState("pending"),{data:d=[]}=dt({queryKey:["recruit-prospects-list",s],queryFn:async()=>{const{data:E,error:O}=await q.from("recruit_prospects").select("id, first_name, last_name").eq("brokerage_id",s).order("first_name");if(O)throw O;return E}}),{data:u=[],isLoading:h}=dt({queryKey:["recruit-follow-ups",s],queryFn:async()=>{const E=d.map(I=>I.id);if(!E.length)return[];const{data:O,error:D}=await q.from("recruit_follow_ups").select("*").in("prospect_id",E).order("due_date");if(D)throw D;return O},enabled:d.length>0}),p=Object.fromEntries(d.map(E=>[E.id,E])),f=yt({mutationFn:async E=>{const{data:{user:O}}=await q.auth.getUser();if(!O)throw new Error("Not authenticated");const{error:D}=await q.from("recruit_follow_ups").insert({prospect_id:E.prospect_id,assigned_to:O.id,title:E.title,description:E.description||null,due_date:new Date(E.due_date).toISOString()});if(D)throw D},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-follow-ups",s]}),t({title:"Follow-up scheduled"}),l({prospect_id:"",title:"",description:"",due_date:Ss(Bl(new Date,1),"yyyy-MM-dd'T'HH:mm")}),a(!1)},onError:E=>t({title:"Error",description:E.message,variant:"destructive"})}),y=yt({mutationFn:async({id:E,completed:O})=>{const{error:D}=await q.from("recruit_follow_ups").update({completed_at:O?new Date().toISOString():null}).eq("id",E);if(D)throw D},onSuccess:()=>n.invalidateQueries({queryKey:["recruit-follow-ups",s]})}),_=u.filter(E=>o==="pending"?!E.completed_at:o==="completed"?!!E.completed_at:!0),v=_.filter(E=>!E.completed_at&&vw(new Date(E.due_date))&&!of(new Date(E.due_date))),j=_.filter(E=>!E.completed_at&&of(new Date(E.due_date))),w=_.filter(E=>!E.completed_at&&!vw(new Date(E.due_date))&&!of(new Date(E.due_date))),S=_.filter(E=>!!E.completed_at),A=E=>{const O=p[E.prospect_id],D=!E.completed_at&&vw(new Date(E.due_date))&&!of(new Date(E.due_date));return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(hi,{checked:!!E.completed_at,onCheckedChange:I=>y.mutate({id:E.id,completed:I}),className:"mt-0.5"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:`text-sm font-medium ${E.completed_at?"line-through text-muted-foreground":""}`,children:E.title}),E.description&&e.jsx("p",{className:"text-xs text-muted-foreground",children:E.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-1 text-xs text-muted-foreground",children:[O&&e.jsxs(Ue,{variant:"secondary",className:"text-[10px]",children:[O.first_name," ",O.last_name]}),e.jsxs("span",{className:`flex items-center gap-1 ${D?"text-destructive font-medium":""}`,children:[D?e.jsx(Bi,{className:"h-3 w-3"}):e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(E.due_date),"MMM d, h:mm a")]}),E.is_automated&&e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:"Auto"})]})]})]},E.id)};return h?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"flex gap-2",children:["pending","completed","all"].map(E=>e.jsxs(B,{size:"sm",variant:o===E?"default":"outline",onClick:()=>c(E),className:"capitalize text-xs",children:[E," ",E==="pending"&&v.length+j.length+w.length>0&&`(${v.length+j.length+w.length})`]},E))}),e.jsxs(B,{size:"sm",onClick:()=>a(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Follow-up"]})]}),o!=="completed"&&v.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-destructive flex items-center gap-1",children:[e.jsx(Bi,{className:"h-3.5 w-3.5"})," Overdue (",v.length,")"]}),v.map(A)]}),o!=="completed"&&j.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-amber-600 flex items-center gap-1",children:[e.jsx(pr,{className:"h-3.5 w-3.5"})," Today (",j.length,")"]}),j.map(A)]}),o!=="completed"&&w.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(yr,{className:"h-3.5 w-3.5"})," Upcoming (",w.length,")"]}),w.map(A)]}),o!=="pending"&&S.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-xs font-semibold text-muted-foreground flex items-center gap-1",children:[e.jsx(Lr,{className:"h-3.5 w-3.5"})," Completed (",S.length,")"]}),S.map(A)]}),_.length===0&&e.jsxs("p",{className:"text-sm text-muted-foreground text-center py-8",children:["No follow-ups ",o!=="all"?`(${o})`:""]}),e.jsx(_s,{open:r,onOpenChange:a,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Schedule Follow-up"})}),e.jsxs("form",{onSubmit:E=>{E.preventDefault(),f.mutate(i)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{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:E=>l(O=>({...O,prospect_id:E.target.value})),children:[e.jsx("option",{value:"",children:"Select prospect..."}),d.map(E=>e.jsxs("option",{value:E.id,children:[E.first_name," ",E.last_name]},E.id))]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Task *"}),e.jsx(ye,{required:!0,value:i.title,onChange:E=>l(O=>({...O,title:E.target.value})),placeholder:"e.g. Follow-up call"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Details"}),e.jsx(Ms,{value:i.description,onChange:E=>l(O=>({...O,description:E.target.value})),rows:2})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Due Date *"}),e.jsx(ye,{type:"datetime-local",required:!0,value:i.due_date,onChange:E=>l(O=>({...O,due_date:E.target.value}))})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:f.isPending,children:"Schedule"})]})]})]})})]})}const Ien=[{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 z2t({brokerageId:s}){const{toast:t}=Fa(),n=Kt(),[r,a]=N.useState(null),{data:i,isLoading:l}=dt({queryKey:["recruit-landing-settings",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",s).maybeSingle();if(j)throw j;return v}}),[o,c]=N.useState({brokerage_id:s,hero_headline:"Join Our Team",hero_subtext:"Take your real estate career to the next level.",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",benefits:Ien,testimonials:[],gallery_images:[],calculator_enabled:!1,calculator_config:{headline:"See What You Could Earn With Us",subtext:"Confidential 60-second calculator — no signup required.",commission_split_pct:80,cap_amount:16e3,post_cap_split_pct:100,monthly_fee:99,transaction_fee:0,show_email_capture:!0,email_capture_label:"Want the full breakdown? Enter your email."},lead_magnet_enabled:!1,lead_magnet_config:{title:"Get the Full Comp Plan PDF",description:"See exactly how splits, caps, and fees work — no call required.",button_text:"Email Me the PDF",pdf_url:null},form_style:"classic",confidential_messaging:!0});N.useEffect(()=>{i&&c({id:i.id,brokerage_id:i.brokerage_id,hero_headline:i.hero_headline,hero_subtext:i.hero_subtext||"",hero_image_url:i.hero_image_url,logo_url:i.logo_url,primary_color:i.primary_color,accent_color:i.accent_color,benefits:i.benefits||[],testimonials:i.testimonials||[],gallery_images:i.gallery_images||[],calculator_enabled:i.calculator_enabled??!1,calculator_config:i.calculator_config||{},lead_magnet_enabled:i.lead_magnet_enabled??!1,lead_magnet_config:i.lead_magnet_config||{},form_style:i.form_style||"classic",confidential_messaging:i.confidential_messaging??!0})},[i]);const d=yt({mutationFn:async()=>{const v={brokerage_id:s,hero_headline:o.hero_headline,hero_subtext:o.hero_subtext,hero_image_url:o.hero_image_url,logo_url:o.logo_url,primary_color:o.primary_color,accent_color:o.accent_color,benefits:JSON.parse(JSON.stringify(o.benefits)),testimonials:JSON.parse(JSON.stringify(o.testimonials)),gallery_images:JSON.parse(JSON.stringify(o.gallery_images)),calculator_enabled:o.calculator_enabled,calculator_config:JSON.parse(JSON.stringify(o.calculator_config)),lead_magnet_enabled:o.lead_magnet_enabled,lead_magnet_config:JSON.parse(JSON.stringify(o.lead_magnet_config)),form_style:o.form_style,confidential_messaging:o.confidential_messaging,updated_at:new Date().toISOString()};if(o.id){const{error:j}=await q.from("recruit_landing_page_settings").update(v).eq("id",o.id);if(j)throw j}else{const{error:j}=await q.from("recruit_landing_page_settings").insert(v);if(j)throw j}},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-landing-settings",s]}),t({title:"Landing page saved!"})},onError:v=>t({title:"Error",description:v.message,variant:"destructive"})}),u=async(v,j)=>{const w=v.name.split(".").pop(),S=`${s}/${j}-${Date.now()}.${w}`,{error:A}=await q.storage.from("recruit-landing").upload(S,v);if(A)throw A;const{data:{publicUrl:E}}=q.storage.from("recruit-landing").getPublicUrl(S);return E},h=async(v,j)=>{var S;const w=(S=v.target.files)==null?void 0:S[0];if(w){a(j);try{const A=await u(w,j);c(E=>({...E,[j]:A})),t({title:"Image uploaded!"})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},p=async v=>{var w;const j=(w=v.target.files)==null?void 0:w[0];if(j){a("gallery");try{const S=await u(j,"gallery");c(A=>({...A,gallery_images:[...A.gallery_images,S]})),t({title:"Gallery image added!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}},f=async(v,j)=>{var S;const w=(S=v.target.files)==null?void 0:S[0];if(w){a(`testimonial-${j}`);try{const A=await u(w,`testimonial-${j}`);c(E=>{const O=[...E.testimonials];return O[j]={...O[j],photo_url:A},{...E,testimonials:O}})}catch(A){t({title:"Upload failed",description:A.message,variant:"destructive"})}finally{a(null)}}},{data:y}=dt({queryKey:["brokerage-slug-for-landing",s],queryFn:async()=>{const{data:v,error:j}=await q.from("brokerages").select("recruit_form_slug, recruit_form_enabled").eq("id",s).single();if(j)throw j;return v}}),_=`https://bestbrokerage.relevelup.com/join-brokerage/${(y==null?void 0:y.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:[(y==null?void 0:y.recruit_form_enabled)&&e.jsxs("div",{className:"flex items-center gap-2 p-3 bg-muted/50 rounded-lg border",children:[e.jsx("span",{className:"text-sm text-muted-foreground",children:"Live page:"}),e.jsx("code",{className:"text-xs flex-1 truncate",children:_}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:_,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Branding"})}),e.jsx(Ee,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.logo_url&&e.jsx("img",{src:o.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="logo_url",children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),r==="logo_url"?"Uploading...":"Upload Logo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:v=>h(v,"logo_url")})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.primary_color,onChange:v=>c(j=>({...j,primary_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:o.primary_color,onChange:v=>c(j=>({...j,primary_color:v.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:o.accent_color,onChange:v=>c(j=>({...j,accent_color:v.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:o.accent_color,onChange:v=>c(j=>({...j,accent_color:v.target.value})),className:"font-mono text-xs"})]})]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Headline"}),e.jsx(ye,{value:o.hero_headline,onChange:v=>c(j=>({...j,hero_headline:v.target.value})),placeholder:"Join Our Team"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Subtext"}),e.jsx(Ms,{value:o.hero_subtext,onChange:v=>c(j=>({...j,hero_subtext:v.target.value})),rows:2,placeholder:"Take your career to the next level..."})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Background Image"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[o.hero_image_url&&e.jsx("img",{src:o.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),r==="hero_image_url"?"Uploading...":"Upload Image"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:v=>h(v,"hero_image_url")})]}),o.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(v=>({...v,hero_image_url:null})),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsx(Rt,{className:"text-base",children:"Benefits / Why Join Us"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,benefits:[...v.benefits,{title:"",description:"",icon:"✨"}]})),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ee,{className:"space-y-3",children:[o.benefits.map((v,j)=>e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsx(Pu,{className:"h-4 w-4 mt-2 text-muted-foreground"}),e.jsx(ye,{value:v.icon,onChange:w=>{const S=[...o.benefits];S[j]={...v,icon:w.target.value},c(A=>({...A,benefits:S}))},className:"w-14 text-center"}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsx(ye,{value:v.title,onChange:w=>{const S=[...o.benefits];S[j]={...v,title:w.target.value},c(A=>({...A,benefits:S}))},placeholder:"Benefit title"}),e.jsx(ye,{value:v.description,onChange:w=>{const S=[...o.benefits];S[j]={...v,description:w.target.value},c(A=>({...A,benefits:S}))},placeholder:"Short description"})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(w=>({...w,benefits:w.benefits.filter((S,A)=>A!==j)})),children:e.jsx(_n,{className:"h-3.5 w-3.5 text-destructive"})})]},j)),o.benefits.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No benefits added yet"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsx(Rt,{className:"text-base",children:"Testimonials"}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>c(v=>({...v,testimonials:[...v.testimonials,{name:"",role:"",quote:""}]})),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add"]})]}),e.jsxs(Ee,{className:"space-y-3",children:[o.testimonials.map((v,j)=>{var w;return e.jsxs("div",{className:"flex items-start gap-3 p-3 border rounded-lg",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1",children:[v.photo_url?e.jsx("img",{src:v.photo_url,alt:v.name,className:"h-10 w-10 rounded-full object-cover"}):e.jsx("div",{className:"h-10 w-10 rounded-full bg-muted flex items-center justify-center text-xs text-muted-foreground",children:((w=v.name)==null?void 0:w[0])||"?"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx("span",{className:"text-[10px] text-primary hover:underline",children:r===`testimonial-${j}`?"...":"Photo"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:S=>f(S,j)})]})]}),e.jsxs("div",{className:"flex-1 space-y-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsx(ye,{value:v.name,onChange:S=>{const A=[...o.testimonials];A[j]={...v,name:S.target.value},c(E=>({...E,testimonials:A}))},placeholder:"Name"}),e.jsx(ye,{value:v.role,onChange:S=>{const A=[...o.testimonials];A[j]={...v,role:S.target.value},c(E=>({...E,testimonials:A}))},placeholder:"Role / Title"})]}),e.jsx(Ms,{value:v.quote,onChange:S=>{const A=[...o.testimonials];A[j]={...v,quote:S.target.value},c(E=>({...E,testimonials:A}))},placeholder:"What they say about working here...",rows:2})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(S=>({...S,testimonials:S.testimonials.filter((A,E)=>E!==j)})),children:e.jsx(_n,{className:"h-3.5 w-3.5 text-destructive"})})]},j)}),o.testimonials.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No testimonials added yet"})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsx(Rt,{className:"text-base",children:"Team & Culture Gallery"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{size:"sm",variant:"outline",asChild:!0,disabled:r==="gallery",children:e.jsxs("span",{children:[e.jsx(Xo,{className:"h-3.5 w-3.5 mr-1"}),r==="gallery"?"Uploading...":"Add Photo"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:p})]})]}),e.jsx(Ee,{children:o.gallery_images.length>0?e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:o.gallery_images.map((v,j)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:v,alt:`Gallery ${j+1}`,className:"h-24 w-full object-cover rounded-lg"}),e.jsx(B,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>c(w=>({...w,gallery_images:w.gallery_images.filter((S,A)=>A!==j)})),children:e.jsx(_n,{className:"h-3 w-3"})})]},j))}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No gallery images added yet"})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," Form Style & Trust"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Application Form Style"}),e.jsxs(us,{value:o.form_style,onValueChange:v=>c(j=>({...j,form_style:v})),children:[e.jsx(ls,{className:"mt-1.5",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"classic",children:"Classic — single-page form (all fields visible)"}),e.jsx(Ze,{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(Gc,{className:"h-4 w-4 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:o.confidential_messaging,onCheckedChange:v=>c(j=>({...j,confidential_messaging:v}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(dw,{className:"h-4 w-4 text-primary"})," Split & Income Calculator"]}),e.jsx(jn,{checked:o.calculator_enabled,onCheckedChange:v=>c(j=>({...j,calculator_enabled:v}))})]}),o.calculator_enabled&&e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Highest-converting recruiting tool. Agents enter their GCI and instantly see what they'd earn at your brokerage."}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Calculator Headline"}),e.jsx(ye,{value:o.calculator_config.headline||"",onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,headline:v.target.value}})),placeholder:"See What You Could Earn With Us"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Subtext"}),e.jsx(ye,{value:o.calculator_config.subtext||"",onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,subtext:v.target.value}})),placeholder:"Confidential 60-second calculator"})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Pre-Cap Split % (agent keeps)"}),e.jsx(ye,{type:"number",value:o.calculator_config.commission_split_pct??80,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,commission_split_pct:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 80 for an 80/20"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Cap Amount ($)"}),e.jsx(ye,{type:"number",value:o.calculator_config.cap_amount??16e3,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,cap_amount:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Annual cap to brokerage"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Post-Cap Split % (agent keeps)"}),e.jsx(ye,{type:"number",value:o.calculator_config.post_cap_split_pct??100,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,post_cap_split_pct:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"e.g. 95 for 95/5 after cap, 100 for 100%"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Monthly Fee ($)"}),e.jsx(ye,{type:"number",value:o.calculator_config.monthly_fee??99,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,monthly_fee:parseFloat(v.target.value)||0}}))})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Per-Transaction Fee ($)"}),e.jsx(ye,{type:"number",value:o.calculator_config.transaction_fee??0,onChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,transaction_fee:parseFloat(v.target.value)||0}}))}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:"Multiplied by # of transactions"})]})]}),e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{children:[e.jsx(ne,{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(jn,{checked:o.calculator_config.show_email_capture!==!1,onCheckedChange:v=>c(j=>({...j,calculator_config:{...j.calculator_config,show_email_capture:v}}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(_A,{className:"h-4 w-4 text-primary"})," Lead Magnet (Gated PDF)"]}),e.jsx(jn,{checked:o.lead_magnet_enabled,onCheckedChange:v=>c(j=>({...j,lead_magnet_enabled:v}))})]}),o.lead_magnet_enabled&&e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Captures emails from agents not ready to talk. Offer a comp plan PDF, recruiting deck, or guide."}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Title"}),e.jsx(ye,{value:o.lead_magnet_config.title||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,title:v.target.value}})),placeholder:"Get the Full Comp Plan PDF"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Description"}),e.jsx(Ms,{rows:2,value:o.lead_magnet_config.description||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,description:v.target.value}})),placeholder:"See exactly how splits, caps, and fees work..."})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Button Text"}),e.jsx(ye,{value:o.lead_magnet_config.button_text||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,button_text:v.target.value}})),placeholder:"Email Me the PDF"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"PDF / File URL"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ye,{value:o.lead_magnet_config.pdf_url||"",onChange:v=>c(j=>({...j,lead_magnet_config:{...j.lead_magnet_config,pdf_url:v.target.value||null}})),placeholder:"https://...",className:"flex-1"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:r==="lead_magnet_pdf",children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),r==="lead_magnet_pdf"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"application/pdf,.pdf,.doc,.docx",className:"hidden",onChange:async v=>{var w;const j=(w=v.target.files)==null?void 0:w[0];if(j){a("lead_magnet_pdf");try{const S=await u(j,"lead-magnet");c(A=>({...A,lead_magnet_config:{...A.lead_magnet_config,pdf_url:S}})),t({title:"PDF uploaded!"})}catch(S){t({title:"Upload failed",description:S.message,variant:"destructive"})}finally{a(null)}}}})]})]})]})]})]})]}),e.jsx(Pen,{brokerageId:s}),e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{onClick:()=>d.mutate(),disabled:d.isPending,size:"lg",children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),d.isPending?"Saving...":"Save Landing Page"]})})]})}function Pen({brokerageId:s}){const{data:t=[]}=dt({queryKey:["lead-magnet-downloads",s],queryFn:async()=>{const{data:n,error:r}=await q.from("recruit_lead_magnet_downloads").select("*").eq("brokerage_id",s).order("created_at",{ascending:!1}).limit(100);if(r)throw r;return n}});return t.length===0?null:e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ia,{className:"h-4 w-4 text-primary"})," Lead Magnet Downloads (",t.length,")"]})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-2 max-h-80 overflow-y-auto",children:t.map(n=>e.jsx("div",{className:"flex items-center justify-between gap-3 p-2.5 border rounded-lg text-sm",children:e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"font-medium truncate",children:[n.first_name||"—"," · ",n.email]}),e.jsxs("div",{className:"text-[11px] text-muted-foreground",children:[Ss(new Date(n.created_at),"MMM d, yyyy h:mm a")," · via ",n.source]})]})},n.id))})})]})}function B2t({brokerageId:s,trigger:t,initialProspectId:n,open:r,onOpenChange:a}){const[i,l]=N.useState(!1),o=r??i,c=a??l,[d,u]=N.useState("pick-recipients"),[h,p]=N.useState(new Set(n?[n]:[])),[f,y]=N.useState("all"),[_,v]=N.useState(""),[j,w]=N.useState(null),[S,A]=N.useState(""),[E,O]=N.useState(0),[D,I]=N.useState(0),[F,z]=N.useState(""),[H,Z]=N.useState(""),{data:Y}=q1e(),[W,ee]=N.useState("default");N.useEffect(()=>{ee(Y!=null&&Y.massEmail?"mass_email":Y!=null&&Y.gmail?"gmail":"default")},[Y==null?void 0:Y.massEmail,Y==null?void 0:Y.gmail]);const[se,oe]=N.useState(null),{prospects:he,stages:ce}=BU(s),me=C2t(),le=CN(),{data:ve=[]}=dt({queryKey:["brokerage-recruit-video-pool",s],queryFn:async()=>{const{data:we,error:Je}=await q.from("agent_videos").select("id, title, thumbnail_url, duration_seconds, created_at, owner_user_id, share_token").eq("touch_type","recruiting").eq("status","ready").eq("is_deleted",!1).order("created_at",{ascending:!1}).limit(50);if(Je)throw Je;return we??[]},enabled:o&&d==="pick-video"}),ge=N.useCallback(()=>{u("pick-recipients"),p(new Set(n?[n]:[])),y("all"),v(""),w(null),A(""),O(0),I(0),z(""),Z(""),ee("default"),oe(null)},[n]),Te=we=>{!we&&(d==="uploading"||d==="processing"||d==="sending")||(c(we),we||setTimeout(ge,200))},Ie=N.useMemo(()=>he.filter(we=>{if(!we.email||f!=="all"&&we.stage_id!==f)return!1;if(_){const Je=_.toLowerCase();if(!`${we.first_name} ${we.last_name??""}`.toLowerCase().includes(Je)&&!we.email.toLowerCase().includes(Je))return!1}return!0}),[he,f,_]),Ce=we=>{p(Je=>{const ke=new Set(Je);return ke.has(we)?ke.delete(we):ke.add(we),ke})},Me=()=>{h.size===Ie.length?p(new Set):p(new Set(Ie.map(we=>we.id)))},Pe=N.useCallback(async(we,Je)=>{u("uploading");try{const ke=`Recruiting blast (${h.size} recipients)`,{videoId:it,libraryId:je}=await t6(ke),{uploadUrl:He,apiKey:$e}=await s6(it),Ke=new XMLHttpRequest;Ke.upload.onprogress=bt=>{bt.lengthComputable&&O(bt.loaded/bt.total*100)},await new Promise((bt,$t)=>{Ke.onload=()=>Ke.status>=200&&Ke.status<300?bt():$t(new Error("Upload failed")),Ke.onerror=()=>$t(new Error("Upload failed")),Ke.open("PUT",He),Ke.setRequestHeader("AccessKey",$e),Ke.send(we)}),u("processing");const Ge=`https://iframe.mediadelivery.net/embed/${je}/${it}`;let rt=0;const tt=Date.now(),at=9e4;for(;rt<4&&(await new Promise($t=>setTimeout($t,3e3)),!(Date.now()-tt>at));){const bt=await Fw(it);if(rt=bt.status,I(bt.encodeProgress||0),rt===5||rt===6)throw new Error("Video processing failed")}const Ye=await Fw(it),ut=(Ye.storageSize||we.size)/(1024*1024),_t=await le.mutateAsync({bunny_video_id:it,playback_url:Ye.directPlayUrl||Ge,thumbnail_url:Ye.thumbnailUrl,preview_url:Ye.previewUrl||null,duration_seconds:Ye.length||Je,file_size_mb:ut,title:ke,status:rt>=4?"ready":"processing",touch_type:"recruiting"});w(_t.id),A(ke),u("compose")}catch(ke){ae.error((ke==null?void 0:ke.message)||"Failed to upload video"),u("pick-video")}},[h.size,le]),Re=N.useCallback(async()=>{if(!(!j||h.size===0)){u("sending");try{const we=[];for(const it of h){const je=await me.mutateAsync({prospect_id:it,video_id:j,brokerage_id:s,message:H||void 0});we.push(je.id)}const{data:Je,error:ke}=await q.functions.invoke("send-recruit-video-email",{body:{recruit_video_ids:we,brokerage_id:s,subject_override:F||void 0,message_override:H||void 0,send_via:W}});if(ke)throw new Error(ke.message);oe({sent:(Je==null?void 0:Je.sent)??0,total:(Je==null?void 0:Je.total)??we.length}),u("done"),ae.success(`Sent ${(Je==null?void 0:Je.sent)??0} of ${(Je==null?void 0:Je.total)??we.length} videos`)}catch(we){ae.error((we==null?void 0:we.message)||"Failed to send"),u("compose")}}},[j,h,s,H,F,W,me]),Ae=h.size,Be=he.filter(we=>!we.email).length;return e.jsxs(_s,{open:o,onOpenChange:Te,children:[t&&e.jsx(ki,{asChild:!0,children:t}),e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-hidden flex flex-col",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(fr,{className:"h-5 w-5 text-primary"}),"Send Recruiting Video",Ae>0&&e.jsxs(Ue,{variant:"secondary",className:"ml-2",children:[e.jsx(An,{className:"h-3 w-3 mr-1"}),Ae," ",Ae===1?"recipient":"recipients"]})]})}),d==="pick-recipients"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col gap-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search prospects...",value:_,onChange:we=>v(we.target.value),className:"pl-9"})]}),e.jsxs(us,{value:f,onValueChange:y,children:[e.jsx(ls,{className:"w-48",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All stages"}),ce.map(we=>e.jsx(Ze,{value:we.id,children:we.name},we.id))]})]})]}),e.jsxs("div",{className:"flex items-center justify-between text-xs text-muted-foreground",children:[e.jsxs("button",{onClick:Me,className:"hover:underline",children:[h.size===Ie.length&&Ie.length>0?"Deselect all":"Select all"," ","(",Ie.length,")"]}),Be>0&&e.jsxs("span",{children:[Be," prospect(s) hidden — no email on file"]})]}),e.jsx(di,{className:"flex-1 border rounded-md",children:Ie.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:Ie.map(we=>{const Je=h.has(we.id),ke=ce.find(it=>it.id===we.stage_id);return e.jsxs("label",{className:"flex items-center gap-3 p-3 hover:bg-muted/30 cursor-pointer",children:[e.jsx(hi,{checked:Je,onCheckedChange:()=>Ce(we.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:[we.first_name," ",we.last_name]}),ke&&e.jsx(Ue,{variant:"outline",className:"text-[10px]",style:{borderColor:ke.color,color:ke.color},children:ke.name})]}),e.jsxs("p",{className:"text-xs text-muted-foreground truncate",children:[we.email," ",we.current_brokerage&&`· ${we.current_brokerage}`]})]})]},we.id)})})}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Te(!1),children:"Cancel"}),e.jsx(B,{disabled:Ae===0,onClick:()=>u("pick-video"),children:"Next: Choose Video"})]})]}),d==="pick-video"&&e.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[e.jsxs(Fr,{defaultValue:"record",className:"flex-1 flex flex-col overflow-hidden",children:[e.jsxs(Rr,{className:"self-start",children:[e.jsxs(Zt,{value:"record",children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"}),"Record New"]}),e.jsxs(Zt,{value:"library",children:[e.jsx(qg,{className:"h-3.5 w-3.5 mr-1"}),"Use Existing"]})]}),e.jsx(is,{value:"record",className:"flex-1 overflow-auto",children:e.jsxs("div",{className:"text-center py-8 space-y-4",children:[e.jsx(Sh,{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 ",Ae," ",Ae===1?"recipient":"recipients"," — each gets their own tracked link."]})]}),e.jsxs(B,{onClick:()=>u("record"),children:[e.jsx(fr,{className:"h-4 w-4 mr-2"}),"Start Recording"]})]})}),e.jsx(is,{value:"library",className:"flex-1 overflow-auto",children:ve.length===0?e.jsx("div",{className:"text-center py-8 text-sm text-muted-foreground",children:"No recruiting videos in library yet."}):e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 p-1",children:ve.map(we=>e.jsxs("button",{onClick:()=>{w(we.id),A(we.title||"Untitled"),u("compose")},className:"text-left group rounded-md border overflow-hidden hover:border-primary transition-colors",children:[e.jsx("div",{className:"aspect-video bg-muted relative",children:nw(we)?e.jsx("img",{src:nw(we),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(fr,{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:we.title||"Untitled"})})]},we.id))})})]}),e.jsx(Xn,{children:e.jsx(B,{variant:"outline",onClick:()=>u("pick-recipients"),children:"Back"})})]}),d==="record"&&e.jsxs("div",{className:"flex-1 overflow-auto",children:[e.jsx(i6,{maxDurationSeconds:600,onRecordingComplete:Pe}),e.jsx("div",{className:"mt-2 flex justify-start",children:e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>u("pick-video"),children:"← Back"})})]}),(d==="uploading"||d==="processing")&&e.jsxs("div",{className:"py-12 space-y-4 text-center",children:[e.jsx(rs,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsx("p",{className:"font-medium",children:d==="uploading"?"Uploading video…":"Processing video…"}),e.jsx(fi,{value:d==="uploading"?E:D,className:"mx-auto max-w-sm"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[Math.round(d==="uploading"?E:D),"%"]})]}),d==="compose"&&e.jsxs("div",{className:"flex-1 overflow-auto space-y-4",children:[e.jsxs("div",{className:"rounded-md border p-3 bg-muted/30 flex items-center gap-3",children:[e.jsx(vr,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"flex-1 text-sm",children:[e.jsx("span",{className:"font-medium",children:S})," selected · sending to ",e.jsx("strong",{children:Ae})," recipient",Ae===1?"":"s"]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Subject (optional override)"}),e.jsx(ye,{value:F,onChange:we=>z(we.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(ne,{className:"text-xs",children:"Personal message shown in the email & on the landing page"}),e.jsx(Ms,{value:H,onChange:we=>Z(we.target.value),placeholder:"Hey there — wanted to share a quick thought on what we're building here...",rows:5,className:"mt-1"})]}),e.jsx(a8e,{value:W,onChange:ee}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>u("pick-video"),children:"Back"}),e.jsxs(B,{onClick:Re,disabled:!j||Ae===0,children:[e.jsx(lr,{className:"h-4 w-4 mr-2"})," Send to ",Ae," ",Ae===1?"prospect":"prospects"]})]})]}),d==="sending"&&e.jsxs("div",{className:"py-12 text-center space-y-3",children:[e.jsx(rs,{className:"h-8 w-8 animate-spin mx-auto text-primary"}),e.jsxs("p",{className:"font-medium",children:["Sending to ",Ae," recipient",Ae===1?"":"s","…"]}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Each prospect gets their own tracked share link."})]}),d==="done"&&se&&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 ${se.sent===se.total?"bg-primary/10":"bg-muted"}`,children:se.sent===se.total?e.jsx(vr,{className:"h-8 w-8 text-primary"}):e.jsx(Bi,{className:"h-8 w-8 text-muted-foreground"})}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-semibold text-lg",children:[se.sent," of ",se.total," sent"]}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"View engagement under the Video Outreach tab."})]}),e.jsx(B,{onClick:()=>Te(!1),children:"Done"})]})]})]})}function Len(s){if(!s)return"—";const t=Math.floor(s/60),n=s%60;return t>0?`${t}m ${n}s`:`${n}s`}function Den({video:s}){return s.cta_clicked_at?e.jsx(Ue,{className:"bg-emerald-500/10 text-emerald-600 border-emerald-200",children:"CTA Clicked"}):s.view_count>0?e.jsxs(Ue,{className:"bg-blue-500/10 text-blue-600 border-blue-200",children:[e.jsx(Sr,{className:"h-3 w-3 mr-1"}),s.view_count," views"]}):s.sent_at?e.jsxs(Ue,{variant:"secondary",children:[e.jsx(lr,{className:"h-3 w-3 mr-1"}),"Sent"]}):e.jsxs(Ue,{variant:"outline",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"}),"Draft"]})}function $2t({brokerageId:s}){var S,A,E,O;const{data:t=[],isLoading:n}=wen(s),{data:r=[]}=E2t(s),a=Nen(),i=ken(),l=T2t(),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState({title:"",script_text:"",category:"general"}),[f,y]=N.useState(null),_=t.filter(D=>{var F,z,H,Z;return o?`${((F=D.prospect)==null?void 0:F.first_name)||""} ${((z=D.prospect)==null?void 0:z.last_name)||""}`.toLowerCase().includes(o.toLowerCase())||((Z=(H=D.video)==null?void 0:H.title)==null?void 0:Z.toLowerCase().includes(o.toLowerCase())):!0}),v={total:t.length,sent:t.filter(D=>D.sent_at).length,viewed:t.filter(D=>D.view_count>0).length,ctaClicked:t.filter(D=>D.cta_clicked_at).length},j=N.useCallback(D=>{if(!D)return;const I=`${window.location.origin}/recruit-video/${D}`;navigator.clipboard.writeText(I),ae.success("Share link copied")},[]);N.useCallback((D,I)=>{l.mutate({id:D,sent_via:I})},[l]);const w=()=>{!h.title.trim()||!h.script_text.trim()||a.mutate({brokerage_id:s,...h},{onSuccess:()=>{p({title:"",script_text:"",category:"general"}),u(!1)}})};return e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Total Videos",value:v.total,icon:fr,color:"text-primary"},{label:"Sent",value:v.sent,icon:lr,color:"text-blue-500"},{label:"Viewed",value:v.viewed,icon:Sr,color:"text-amber-500"},{label:"CTA Clicked",value:v.ctaClicked,icon:vr,color:"text-emerald-500"}].map(D=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx("div",{className:`h-10 w-10 rounded-lg bg-muted flex items-center justify-center ${D.color}`,children:e.jsx(D.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-2xl font-bold",children:D.value}),e.jsx("p",{className:"text-xs text-muted-foreground",children:D.label})]})]})},D.label))}),e.jsxs(Fr,{defaultValue:"videos",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"videos",children:[e.jsx(fr,{className:"h-4 w-4 mr-1.5"}),"All Videos"]}),e.jsxs(Zt,{value:"scripts",children:[e.jsx(br,{className:"h-4 w-4 mr-1.5"}),"Script Library"]}),e.jsxs(Zt,{value:"analytics",children:[e.jsx(_o,{className:"h-4 w-4 mr-1.5"}),"Engagement"]})]}),e.jsx(is,{value:"videos",children:e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Rt,{className:"text-lg",children:"Video Outreach"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative w-64",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or title...",value:o,onChange:D=>c(D.target.value),className:"pl-9"})]}),e.jsx(B2t,{brokerageId:s,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(Gs,{className:"h-4 w-4"})," Send Video Email"]})})]})]})}),e.jsx(Ee,{children:n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):_.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(fr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No video outreach yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Record a personalized video from any prospect's profile card"})]}):e.jsx("div",{className:"space-y-3",children:_.map(D=>{var I,F,z,H,Z,Y,W;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:[nw(D.video)?e.jsx("img",{src:nw(D.video),alt:"",className:"h-full w-full object-cover",referrerPolicy:"no-referrer"}):e.jsx("div",{className:"h-full w-full flex items-center justify-center",children:e.jsx(fr,{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:Len(((I=D.video)==null?void 0:I.duration_seconds)??null)})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium truncate",children:[(F=D.prospect)==null?void 0:F.first_name," ",(z=D.prospect)==null?void 0:z.last_name]}),e.jsx(Den,{video:D})]}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:((H=D.video)==null?void 0:H.title)||"Untitled video"}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ss(new Date(D.created_at),"MMM d, yyyy"),((Z=D.prospect)==null?void 0:Z.current_brokerage)&&` · ${D.prospect.current_brokerage}`]})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>j(D.share_token),title:"Copy share link",children:e.jsx(Zr,{className:"h-4 w-4"})}),e.jsxs(B,{variant:D.sent_at?"ghost":"default",size:"sm",className:"h-8 gap-1.5",onClick:()=>y(D),disabled:!((Y=D.prospect)!=null&&Y.email),title:(W=D.prospect)!=null&&W.email?"Email this video to the prospect":"Prospect has no email",children:[e.jsx(Gs,{className:"h-4 w-4"}),D.sent_at?"Resend":"Email"]}),D.share_token&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>window.open(`/recruit-video/${D.share_token}`,"_blank"),title:"Preview landing page",children:e.jsx(tr,{className:"h-4 w-4"})})]})]},D.id)})})})]})}),e.jsx(is,{value:"scripts",children:e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(Rt,{className:"text-lg",children:"Recruiting Scripts"}),e.jsxs(_s,{open:d,onOpenChange:u,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"}),"New Script"]})}),e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Create Recruiting Script"})}),e.jsxs("div",{className:"space-y-4 mt-2",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:h.title,onChange:D=>p(I=>({...I,title:D.target.value})),placeholder:"e.g., Why Switch to Our Brokerage"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Category"}),e.jsxs(us,{value:h.category,onValueChange:D=>p(I=>({...I,category:D})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:oTe.map(D=>e.jsx(Ze,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Script"}),e.jsx(Ms,{value:h.script_text,onChange:D=>p(I=>({...I,script_text:D.target.value})),placeholder:"Hi [Name], I noticed you've been doing great work at [Brokerage]...",rows:8})]}),e.jsx(B,{onClick:w,disabled:!h.title.trim()||!h.script_text.trim(),className:"w-full",children:"Save Script"})]})]})]})]})}),e.jsx(Ee,{children:r.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(br,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No scripts yet"}),e.jsx("p",{className:"text-sm mt-1",children:"Create teleprompter scripts for common recruiting conversations"})]}):e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:r.map(D=>{var F;const I=((F=oTe.find(z=>z.value===D.category))==null?void 0:F.label)||D.category;return e.jsx(fe,{className:"relative group",children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Ue,{variant:"outline",className:"text-[10px] mb-2",children:I}),e.jsx("h4",{className:"font-medium text-sm",children:D.title})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity text-destructive",onClick:()=>i.mutate(D.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2 line-clamp-3",children:D.script_text}),D.is_global&&e.jsx(Ue,{variant:"secondary",className:"mt-2 text-[10px]",children:"Template"})]})},D.id)})})})]})}),e.jsx(is,{value:"analytics",children:e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"Engagement Funnel"})}),e.jsxs(Ee,{children:[e.jsx("div",{className:"space-y-4",children:[{label:"Videos Created",count:v.total,pct:100,color:"bg-primary"},{label:"Sent to Prospects",count:v.sent,pct:v.total?Math.round(v.sent/v.total*100):0,color:"bg-blue-500"},{label:"Viewed by Prospect",count:v.viewed,pct:v.sent?Math.round(v.viewed/v.sent*100):0,color:"bg-amber-500"},{label:"CTA Clicked",count:v.ctaClicked,pct:v.viewed?Math.round(v.ctaClicked/v.viewed*100):0,color:"bg-emerald-500"}].map(D=>e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:D.label}),e.jsxs("span",{className:"font-medium",children:[D.count," (",D.pct,"%)"]})]}),e.jsx("div",{className:"h-3 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:`h-full ${D.color} rounded-full transition-all`,style:{width:`${D.pct}%`}})})]},D.label))}),t.filter(D=>D.view_count>0).length>0&&e.jsxs("div",{className:"mt-8",children:[e.jsx("h4",{className:"font-medium text-sm mb-3",children:"Most Engaged Prospects"}),e.jsx("div",{className:"space-y-2",children:t.filter(D=>D.view_count>0).sort((D,I)=>I.view_count-D.view_count).slice(0,5).map(D=>{var I,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:[(I=D.prospect)==null?void 0:I.first_name," ",(F=D.prospect)==null?void 0:F.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Sr,{className:"h-3.5 w-3.5"})," ",D.view_count]}),D.cta_clicked_at&&e.jsx(vr,{className:"h-4 w-4 text-emerald-500"})]})]},D.id)})})]})]})]})})]}),f&&e.jsx(S2t,{open:!!f,onOpenChange:D=>{D||y(null)},recruitVideoId:f.id,brokerageId:s,prospectName:`${((S=f.prospect)==null?void 0:S.first_name)||""} ${((A=f.prospect)==null?void 0:A.last_name)||""}`.trim(),prospectEmail:(E=f.prospect)==null?void 0:E.email,videoTitle:(O=f.video)==null?void 0:O.title,defaultMessage:f.message})]})}function U2t({brokerageId:s}){const{toast:t}=Fa(),n=Kt(),{stages:r,prospects:a}=BU(s),[i,l]=N.useState(!1),[o,c]=N.useState({title:"",target_count:"10",target_stage_id:"",period_start:Ss(new Date,"yyyy-MM-dd"),period_end:Ss(new Date(new Date().getFullYear(),new Date().getMonth()+3,0),"yyyy-MM-dd")}),{data:d=[],isLoading:u}=dt({queryKey:["recruit-goals",s],queryFn:async()=>{const{data:y,error:_}=await q.from("recruit_goals").select("*").eq("brokerage_id",s).order("period_end",{ascending:!1});if(_)throw _;return y}}),h=yt({mutationFn:async y=>{const{data:{user:_}}=await q.auth.getUser();if(!_)throw new Error("Not authenticated");const{error:v}=await q.from("recruit_goals").insert({brokerage_id:s,title:y.title,target_count:parseInt(y.target_count),target_stage_id:y.target_stage_id||null,period_start:y.period_start,period_end:y.period_end,created_by:_.id});if(v)throw v},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal created"}),l(!1)},onError:y=>t({title:"Error",description:y.message,variant:"destructive"})}),p=yt({mutationFn:async y=>{const{error:_}=await q.from("recruit_goals").delete().eq("id",y);if(_)throw _},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-goals",s]}),t({title:"Goal removed"})}}),f=y=>{const _=r.find(j=>j.id===y.target_stage_id);return{count:a.filter(j=>W1(new Date(j.created_at),{start:new Date(y.period_start),end:new Date(y.period_end)})?y.target_stage_id?j.stage_id===y.target_stage_id:!0:!1).length,stage:_}};return u?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:[d.length," goal",d.length!==1?"s":""]}),e.jsxs(B,{size:"sm",onClick:()=>l(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," New Goal"]})]}),d.length===0?e.jsxs(fe,{className:"py-12 text-center",children:[e.jsx(Ac,{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(y=>{const{count:_,stage:v}=f(y),j=Math.min(100,_/y.target_count*100),w=W1(new Date,{start:new Date(y.period_start),end:new Date(y.period_end)});return e.jsxs(fe,{className:w?"":"opacity-60",children:[e.jsx(It,{className:"pb-2",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{className:"text-sm",children:y.title}),e.jsxs("p",{className:"text-xs text-muted-foreground mt-0.5",children:[Ss(new Date(y.period_start),"MMM d")," – ",Ss(new Date(y.period_end),"MMM d, yyyy")]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[w?e.jsx(Ue,{className:"text-[10px]",children:"Active"}):e.jsx(Ue,{variant:"secondary",className:"text-[10px]",children:"Ended"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 text-muted-foreground",onClick:()=>p.mutate(y.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})}),e.jsxs(Ee,{className:"space-y-2",children:[v&&e.jsxs(Ue,{variant:"outline",className:"text-[10px]",style:{borderColor:v.color,color:v.color},children:["Stage: ",v.name]}),e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"font-bold text-lg",children:_}),e.jsxs("span",{className:"text-muted-foreground",children:["/ ",y.target_count]})]}),e.jsx(fi,{value:j,className:"h-2"}),e.jsxs("p",{className:"text-xs text-muted-foreground text-right",children:[j.toFixed(0),"% complete"]})]})]},y.id)})}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Create Recruiting Goal"})}),e.jsxs("form",{onSubmit:y=>{y.preventDefault(),h.mutate(o)},className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Goal Title *"}),e.jsx(ye,{required:!0,value:o.title,onChange:y=>c(_=>({..._,title:y.target.value})),placeholder:"e.g. Q2 Recruiting Target"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Target Count *"}),e.jsx(ye,{type:"number",min:"1",required:!0,value:o.target_count,onChange:y=>c(_=>({..._,target_count:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{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:y=>c(_=>({..._,target_stage_id:y.target.value})),children:[e.jsx("option",{value:"",children:"All stages (total prospects)"}),r.map(y=>e.jsx("option",{value:y.id,children:y.name},y.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(ne,{children:"Start Date"}),e.jsx(ye,{type:"date",required:!0,value:o.period_start,onChange:y=>c(_=>({..._,period_start:y.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"End Date"}),e.jsx(ye,{type:"date",required:!0,value:o.period_end,onChange:y=>c(_=>({..._,period_end:y.target.value}))})]})]}),e.jsxs("div",{className:"flex justify-end gap-2",children:[e.jsx(B,{type:"button",variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{type:"submit",disabled:h.isPending,children:"Create Goal"})]})]})]})})]})}const Ren={first_name:"Sarah",brokerage_name:"ABC Realty",city:"Austin",sender_name:"Jeremy"};function q2t({email:s,mergeValues:t=Ren,selectedSubjectIndex:n,onClose:r}){var c;const a=d=>d.replace(/\{\{first_name\}\}/g,t.first_name).replace(/\{\{brokerage_name\}\}/g,t.brokerage_name).replace(/\{\{city\}\}/g,t.city).replace(/\{\{sender_name\}\}/g,t.sender_name).replace(/\{\{landing_page_link\}\}/g,"https://bestbrokerage.relevelup.com/join-brokerage/your-slug"),i=((c=s.subject_line_options)==null?void 0:c.length)>0?s.subject_line_options:[s.subject_line],l=n??0,o=i[l]||s.subject_line;return e.jsx(_s,{open:!0,onOpenChange:()=>r(),children:e.jsxs(bs,{className:"max-w-2xl max-h-[85vh] overflow-y-auto p-0",children:[e.jsxs(js,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(ws,{className:"text-base",children:["Email #",s.email_number," — ",s.title]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2",children:[e.jsxs(Ue,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),s.email_number===1?"Sent immediately":`Day ${s.delay_days}`]}),i.length>1&&e.jsxs(Ue,{variant:"secondary",className:"text-xs",children:[i.length," subject variants"]})]})]}),e.jsxs("div",{className:"space-y-0",children:[i.length>1&&e.jsxs("div",{className:"px-6 py-3 border-b bg-muted/20",children:[e.jsx("p",{className:"text-[10px] font-medium text-muted-foreground uppercase tracking-wider mb-2",children:"Subject Line Options"}),e.jsx("div",{className:"flex flex-col gap-1.5",children:i.map((d,u)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:`text-[10px] font-bold uppercase px-1.5 py-0.5 rounded ${u===l?"bg-primary/10 text-primary":"bg-muted text-muted-foreground"}`,children:u===l?"Selected":u===0?"Primary":`Alt ${u}`}),e.jsx("span",{className:"text-sm",children:a(d)})]},u))})]}),e.jsxs("div",{className:"border-b",children:[e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-14",children:"From:"}),e.jsxs("span",{children:[t.sender_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs text-muted-foreground border-t",children:[e.jsx("span",{className:"font-medium w-14",children:"To:"}),e.jsxs("span",{children:[t.first_name," "]})]}),e.jsxs("div",{className:"px-6 py-2 flex items-center gap-2 text-xs border-t",children:[e.jsx("span",{className:"font-medium w-14 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:a(o)})]})]}),e.jsx("div",{className:"bg-white px-8 py-6",children:e.jsx("div",{className:"prose prose-sm max-w-none [&_p]:my-3 [&_p+p]:mt-4 [&_br]:block [&_br]:mt-2",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:a(s.body_html)}})})]})]})})}function i8e({brokerageId:s}){const t=Kt(),{user:n}=vs(),[r,a]=N.useState(""),[i,l]=N.useState(!1),[o,c]=N.useState({brokerage_id:s,sender_name:"LevelUp",sender_email:"recruiting@relevelup.com",reply_to_email:"",merge_fields:{city:"",broker_name:""}}),{data:d}=dt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:y,error:_}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(_)throw _;return y}}),{data:u}=dt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:y,error:_}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(_)throw _;return y}});N.useEffect(()=>{d?c({...d,merge_fields:d.merge_fields||{city:"",broker_name:""}}):u&&c(y=>({...y,merge_fields:{...y.merge_fields,brokerage_name:u.name,city:u.city||""}}))},[d,u]),N.useEffect(()=>{n!=null&&n.id&&q.from("profiles").select("recruit_cta_url").eq("id",n.id).single().then(({data:y})=>a((y==null?void 0:y.recruit_cta_url)||""))},[n==null?void 0:n.id]);const h=async()=>{if(!(n!=null&&n.id))return;l(!0);const{error:y}=await q.from("profiles").update({recruit_cta_url:r.trim()||null}).eq("id",n.id);l(!1),y?ae.error(y.message):ae.success("Scheduling link saved!")},p=yt({mutationFn:async()=>{const y={brokerage_id:s,sender_name:o.sender_name,sender_email:o.sender_email,reply_to_email:o.reply_to_email||null,merge_fields:o.merge_fields,updated_at:new Date().toISOString()};if(d!=null&&d.id){const{error:_}=await q.from("brokerage_recruit_settings").update(y).eq("id",d.id);if(_)throw _}else{const{error:_}=await q.from("brokerage_recruit_settings").insert(y);if(_)throw _}},onSuccess:()=>{t.invalidateQueries({queryKey:["brokerage-recruit-settings",s]}),ae.success("Recruiting email settings saved!")},onError:y=>ae.error(y.message)}),f=(y,_)=>{c(v=>({...v,merge_fields:{...v.merge_fields,[y]:_}}))};return e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the sender identity and merge fields for recruiting emails sent to this brokerage's prospects."}),e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-4 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(yr,{className:"h-4 w-4 text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Your Scheduling Link"})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["This URL powers the ",e.jsx("strong",{children:'"Schedule a Conversation"'})," button on every recruiting video page you send. Paste your Calendly, HubSpot Meetings, Google Calendar booking link, etc."]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:r,onChange:y=>a(y.target.value),placeholder:"https://calendly.com/your-name/intro"}),e.jsxs(B,{onClick:h,disabled:i,size:"sm",children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save"]})]}),!r&&e.jsx("p",{className:"text-xs text-amber-600",children:"⚠️ No link set — the CTA button will be hidden on your video pages until you add one."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"Sender Display Name"}),e.jsx(ye,{value:o.sender_name,onChange:y=>c({...o,sender_name:y.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"Sender Email Address"}),e.jsx(ye,{value:o.sender_email,onChange:y=>c({...o,sender_email:y.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(ne,{className:"text-xs",children:"Reply-To Email (optional)"}),e.jsx(ye,{value:o.reply_to_email,onChange:y=>c({...o,reply_to_email:y.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(eg,{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(v2t,{brokerageId:s,onVerifiedSelect:y=>{c(_=>({..._,sender_email:y})),ae.success(`Sender set to ${y}`)}})]}),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(ne,{className:"text-xs",children:"{{brokerage_name}}"}),e.jsx(ye,{value:o.merge_fields.brokerage_name||"",onChange:y=>f("brokerage_name",y.target.value),placeholder:(u==null?void 0:u.name)||"Brokerage Name"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"{{city}}"}),e.jsx(ye,{value:o.merge_fields.city||"",onChange:y=>f("city",y.target.value),placeholder:"e.g. Austin"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs",children:"{{sender_name}}"}),e.jsx(ye,{value:o.merge_fields.sender_name||"",onChange:y=>f("sender_name",y.target.value),placeholder:"e.g. Jeremy"})]})]})]}),e.jsxs(B,{onClick:()=>p.mutate(),disabled:p.isPending,className:"w-full",children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save Settings"]})]})}const Oen=kb.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",du(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()}}}),aXe=[{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 Yp({onClick:s,active:t,disabled:n,icon:r,tooltip:a}){return e.jsxs(Bc,{children:[e.jsx($c,{asChild:!0,children:e.jsx(B,{type:"button",variant:"ghost",size:"sm",onClick:s,disabled:n,className:`h-8 w-8 p-0 ${t?"bg-accent text-accent-foreground":"text-muted-foreground hover:text-foreground"}`,children:e.jsx(r,{className:"h-4 w-4"})})}),e.jsx(Nc,{side:"bottom",className:"text-xs",children:a})]})}function Fen({content:s,onChange:t}){const n=A6e({extensions:[I6e.configure({heading:{levels:[1,2,3]}}),Oen,U6e.configure({openOnClick:!1,HTMLAttributes:{class:"text-primary underline cursor-pointer"}}),q6e.configure({types:["heading","paragraph"]}),V6e,Xbt],content:s,editorProps:{attributes:{class:"prose prose-sm max-w-none focus:outline-none min-h-[350px] px-5 py-4",style:"font-size: 15px; line-height: 1.75; color: #1a1a1a;"}},onUpdate:({editor:i})=>{t(i.getHTML())}});N.useEffect(()=>{n&&s!==n.getHTML()&&n.commands.setContent(s)},[s,n]);const r=N.useCallback(()=>{if(!n)return;const i=n.getAttributes("link").href,l=window.prompt("Enter URL",i);if(l!==null){if(l===""){n.chain().focus().extendMarkRange("link").unsetLink().run();return}n.chain().focus().extendMarkRange("link").setLink({href:l}).run()}},[n]),a=N.useCallback(i=>{n&&n.chain().focus().insertContent(`{{${i}}}`).run()},[n]);return n?e.jsx(Vw,{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(Yp,{onClick:()=>n.chain().focus().toggleBold().run(),active:n.isActive("bold"),icon:$S,tooltip:"Bold"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleItalic().run(),active:n.isActive("italic"),icon:HS,tooltip:"Italic"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleUnderline().run(),active:n.isActive("underline"),icon:fL,tooltip:"Underline"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleStrike().run(),active:n.isActive("strike"),icon:_9,tooltip:"Strikethrough"}),e.jsx(al,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleHeading({level:1}).run(),active:n.isActive("heading",{level:1}),icon:XP,tooltip:"Heading 1"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleHeading({level:2}).run(),active:n.isActive("heading",{level:2}),icon:JP,tooltip:"Heading 2"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleHeading({level:3}).run(),active:n.isActive("heading",{level:3}),icon:Q7,tooltip:"Heading 3"}),e.jsx(al,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleBulletList().run(),active:n.isActive("bulletList"),icon:Sp,tooltip:"Bullet List"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleOrderedList().run(),active:n.isActive("orderedList"),icon:ub,tooltip:"Numbered List"}),e.jsx(Yp,{onClick:()=>n.chain().focus().toggleBlockquote().run(),active:n.isActive("blockquote"),icon:gw,tooltip:"Blockquote"}),e.jsx(Yp,{onClick:()=>n.chain().focus().setHorizontalRule().run(),icon:hb,tooltip:"Divider"}),e.jsx(al,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Yp,{onClick:()=>n.chain().focus().setTextAlign("left").run(),active:n.isActive({textAlign:"left"}),icon:fA,tooltip:"Align Left"}),e.jsx(Yp,{onClick:()=>n.chain().focus().setTextAlign("center").run(),active:n.isActive({textAlign:"center"}),icon:pA,tooltip:"Align Center"}),e.jsx(Yp,{onClick:()=>n.chain().focus().setTextAlign("right").run(),active:n.isActive({textAlign:"right"}),icon:xA,tooltip:"Align Right"}),e.jsx(al,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Yp,{onClick:r,active:n.isActive("link"),icon:Yo,tooltip:"Insert Link"}),e.jsx(al,{orientation:"vertical",className:"mx-1 h-6"}),e.jsx(Yp,{onClick:()=>n.chain().focus().undo().run(),disabled:!n.can().undo(),icon:n4,tooltip:"Undo"}),e.jsx(Yp,{onClick:()=>n.chain().focus().redo().run(),disabled:!n.can().redo(),icon:JS,tooltip:"Redo"}),e.jsx("div",{className:"flex-1"}),e.jsx(B,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",onClick:()=>{n&&n.chain().focus().insertContent('

Learn More About Us

').run()},children:"🔘 CTA Button"}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"h-8 gap-1.5 text-xs font-medium",children:[e.jsx(xL,{className:"h-3.5 w-3.5"}),"Merge Tags"]})}),e.jsx(gc,{align:"end",className:"w-56",children:aXe.map(i=>e.jsxs(Kr,{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(T6e,{editor:n,className:"[&_.ProseMirror]:outline-none [&_.ProseMirror]:min-h-[350px] [&_.ProseMirror_p]:my-3 [&_.ProseMirror_ul]:my-3 [&_.ProseMirror_ol]:my-3 [&_.ProseMirror_blockquote]:my-3 [&_.ProseMirror_h1]:my-4 [&_.ProseMirror_h2]:my-3 [&_.ProseMirror_h3]:my-2"})}),e.jsx("div",{className:"border-t px-4 py-2.5 bg-muted/20",children:e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground font-medium",children:"Tags:"}),aXe.map(i=>e.jsx(Ue,{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 zen({open:s,onClose:t,campaignName:n,stat:r}){return e.jsx(_s,{open:s,onOpenChange:a=>!a&&t(),children:e.jsxs(bs,{className:"max-w-3xl max-h-[85vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(go,{className:"h-5 w-5 text-primary"}),n," — Engagement Stats"]}),e.jsx(Jn,{children:"Per-email breakdown of sends, opens, and clicks for this campaign at your brokerage."})]}),!r||r.sent===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(lr,{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(bG,{icon:Gs,color:"text-blue-500",label:"Total Sent",value:r.sent.toLocaleString()}),e.jsx(bG,{icon:Sr,color:"text-amber-500",label:"Opens",value:`${r.opened.toLocaleString()}`,sub:`${r.openRate.toFixed(1)}% open rate`}),e.jsx(bG,{icon:oc,color:"text-green-500",label:"Clicks",value:`${r.clicked.toLocaleString()}`,sub:`${r.clickRate.toFixed(1)}% click rate`}),e.jsx(bG,{icon:ic,color:"text-destructive",label:"Failed",value:r.failed.toLocaleString()})]}),r.lastSentAt&&e.jsxs("p",{className:"text-xs text-muted-foreground flex items-center gap-1.5",children:[e.jsx(pr,{className:"h-3 w-3"})," Last sent: ",Ss(new Date(r.lastSentAt),"MMM d, yyyy h:mm a")]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-sm font-semibold mb-2 mt-4",children:"Per-Email Performance"}),e.jsx("div",{className:"space-y-2",children:r.byEmail.map(a=>{const i=a.sent_count>0?a.opened_count/a.sent_count*100:0,l=a.sent_count>0?a.clicked_count/a.sent_count*100:0;return e.jsx(fe,{className:"overflow-hidden",children:e.jsxs(Ee,{className:"py-3",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsxs("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary font-bold text-xs flex items-center justify-center shrink-0",children:["#",a.email_number]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:a.title}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 mt-1",children:[e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(Gs,{className:"h-2.5 w-2.5"})," ",a.sent_count.toLocaleString()," sent"]}),e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600",children:[e.jsx(Sr,{className:"h-2.5 w-2.5"})," ",a.opened_count.toLocaleString()," (",i.toFixed(1),"%)"]}),e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600",children:[e.jsx(oc,{className:"h-2.5 w-2.5"})," ",a.clicked_count.toLocaleString()," (",l.toFixed(1),"%)"]}),a.failed_count>0&&e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1 border-destructive/30 text-destructive",children:[e.jsx(ic,{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 bG({icon:s,color:t,label:n,value:r,sub:a}){return e.jsx(fe,{children:e.jsx(Ee,{className:"pt-4 pb-3",children:e.jsxs("div",{className:"flex items-center gap-2.5",children:[e.jsx(s,{className:`h-6 w-6 ${t}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"text-xl font-bold leading-none",children:r}),e.jsx("p",{className:"text-[10px] text-muted-foreground mt-1",children:n}),a&&e.jsx("p",{className:"text-[10px] text-muted-foreground",children:a})]})]})})})}function V2t(s){return dt({queryKey:["recruit-campaign-stats",s],enabled:!!s,staleTime:6e4,queryFn:async()=>{const{data:t,error:n}=await q.from("recruit_campaign_email_stats").select("*").eq("brokerage_id",s);if(n)throw n;const r=t??[],a={};for(const i of r){a[i.campaign_id]||(a[i.campaign_id]={campaign_id:i.campaign_id,sent:0,opened:0,clicked:0,failed:0,openRate:0,clickRate:0,byEmail:[],lastSentAt:null});const l=a[i.campaign_id];l.sent+=i.sent_count,l.opened+=i.opened_count,l.clicked+=i.clicked_count,l.failed+=i.failed_count,l.byEmail.push(i),i.last_sent_at&&(!l.lastSentAt||i.last_sent_at>l.lastSentAt)&&(l.lastSentAt=i.last_sent_at)}return Object.values(a).forEach(i=>{i.openRate=i.sent>0?i.opened/i.sent*100:0,i.clickRate=i.sent>0?i.clicked/i.sent*100:0,i.byEmail.sort((l,o)=>l.email_number-o.email_number)}),a}})}const iXe={cold:{icon:Tv,color:"text-blue-500",bg:"bg-blue-50 dark:bg-blue-950/30",label:"Cold — Curiosity"},warm:{icon:pb,color:"text-amber-500",bg:"bg-amber-50 dark:bg-amber-950/30",label:"Warm — Growth"},hot:{icon:Hc,color:"text-red-500",bg:"bg-red-50 dark:bg-red-950/30",label:"Hot — Private Invite"}};function H2t({brokerageId:s}){var Me,Pe,Re,Ae;const{user:t}=vs(),n=Kt(),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,y]=N.useState("editor"),[_,v]=N.useState(null),[j,w]=N.useState(null),{data:S={}}=V2t(s),[A,E]=N.useState({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""}),{data:O}=dt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:Be,error:we}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(we)throw we;return Be}}),{data:D}=dt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:Be,error:we}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(we)throw we;return Be}}),I={first_name:"Sarah",brokerage_name:((Me=D==null?void 0:D.merge_fields)==null?void 0:Me.brokerage_name)||(O==null?void 0:O.name)||"Your Brokerage",city:((Pe=D==null?void 0:D.merge_fields)==null?void 0:Pe.city)||(O==null?void 0:O.city)||"Your City",sender_name:((Re=D==null?void 0:D.merge_fields)==null?void 0:Re.sender_name)||(D==null?void 0:D.sender_name)||"Your Name"},F=Be=>Be.replace(/\{\{first_name\}\}/g,I.first_name).replace(/\{\{brokerage_name\}\}/g,I.brokerage_name).replace(/\{\{city\}\}/g,I.city).replace(/\{\{sender_name\}\}/g,I.sender_name),{data:z=[],isLoading:H}=dt({queryKey:["recruit-campaigns",s],queryFn:async()=>{const{data:Be,error:we}=await q.from("recruit_campaigns").select("*").or(`brokerage_id.is.null,brokerage_id.eq.${s}`).order("sort_order");if(we)throw we;return Be}}),{data:Z={}}=dt({queryKey:["recruit-campaign-emails",s],enabled:z.length>0,queryFn:async()=>{const Be=z.map(it=>it.id),{data:we,error:Je}=await q.from("recruit_campaign_emails").select("*").in("campaign_id",Be).order("email_number");if(Je)throw Je;const ke={};return we.forEach(it=>{ke[it.campaign_id]||(ke[it.campaign_id]=[]),ke[it.campaign_id].push(it)}),ke}}),Y=Object.values(Z).flat().map(Be=>Be.id),{data:W=[]}=dt({queryKey:["recruit-subject-overrides",s],enabled:Y.length>0,queryFn:async()=>{const{data:Be,error:we}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(we)throw we;return Be}}),ee={};W.forEach(Be=>{ee[Be.campaign_email_id]=Be.selected_subject_index});const se=yt({mutationFn:async({campaignEmailId:Be,selectedIndex:we})=>{const{error:Je}=await q.from("recruit_brokerage_subject_overrides").upsert({brokerage_id:s,campaign_email_id:Be,selected_subject_index:we,updated_at:new Date().toISOString()},{onConflict:"brokerage_id,campaign_email_id"});if(Je)throw Je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-subject-overrides",s]}),ae.success("Subject line updated for your brokerage")},onError:Be=>ae.error(Be.message)}),oe=yt({mutationFn:async Be=>{const{error:we}=await q.from("recruit_campaign_emails").update({title:Be.title,subject_line:Be.subject_line,subject_line_options:Be.subject_line_options,body_html:Be.body_html,body_text:Be.body_text,delay_days:Be.delay_days,updated_at:new Date().toISOString()}).eq("id",Be.id);if(we)throw we},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email template saved!"),l(null)},onError:Be=>ae.error(Be.message)}),he=yt({mutationFn:async()=>{const Be=A.name.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,""),{data:we,error:Je}=await q.from("recruit_campaigns").insert({name:A.name,slug:Be,description:A.description||null,theme:A.theme||null,goal:A.goal||null,primary_cta:A.primary_cta||"Learn more",warmth_level:A.warmth_level,brokerage_id:s,created_by:t==null?void 0:t.id,sender_name:A.sender_name||null,sender_email:A.sender_email||null,reply_to_email:A.reply_to_email||null,is_active:!0,sort_order:z.length+1}).select().single();if(Je)throw Je;const ke=[{email_number:1,title:"Introduction",subject_line:"Hey {{first_name}}, quick question",delay_days:0},{email_number:2,title:"Follow Up",subject_line:"Following up, {{first_name}}",delay_days:7},{email_number:3,title:"Value Add",subject_line:"{{first_name}}, thought you'd want to see this",delay_days:14},{email_number:4,title:"Final Touch",subject_line:"Last note, {{first_name}}",delay_days:21}],{error:it}=await q.from("recruit_campaign_emails").insert(ke.map(je=>({campaign_id:we.id,...je,body_html:"

Hi {{first_name}},

Write your message here...

Best,
{{sender_name}}

",body_text:"",subject_line_options:[],is_active:!0})));if(it)throw it;return we},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign created with 4 starter emails!"),p(!1),E({name:"",description:"",theme:"",goal:"",primary_cta:"Learn more",warmth_level:"warm",sender_name:"",sender_email:"",reply_to_email:""})},onError:Be=>ae.error(Be.message)}),ce=yt({mutationFn:async Be=>{const{error:we}=await q.from("recruit_campaigns").update({name:Be.name,description:Be.description,theme:Be.theme,goal:Be.goal,primary_cta:Be.primary_cta,warmth_level:Be.warmth_level,sender_name:Be.sender_name,sender_email:Be.sender_email,reply_to_email:Be.reply_to_email,updated_at:new Date().toISOString()}).eq("id",Be.id);if(we)throw we},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),ae.success("Campaign settings saved!"),v(null)},onError:Be=>ae.error(Be.message)}),me=yt({mutationFn:async Be=>{var He,$e;const{data:we}=await q.from("recruit_campaign_emails").select("email_number, delay_days").eq("campaign_id",Be).order("email_number",{ascending:!1}).limit(1),Je=((He=we==null?void 0:we[0])==null?void 0:He.email_number)??0,ke=(($e=we==null?void 0:we[0])==null?void 0:$e.delay_days)??0,it=Je+1,{error:je}=await q.from("recruit_campaign_emails").insert({campaign_id:Be,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:ke+7,is_active:!0});if(je)throw je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email added to campaign!")},onError:Be=>ae.error(Be.message)}),le=yt({mutationFn:async Be=>{const{error:we}=await q.from("recruit_campaigns").delete().eq("id",Be);if(we)throw we},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaigns"]}),n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Campaign deleted")},onError:Be=>ae.error(Be.message)}),ve=yt({mutationFn:async Be=>{const{error:we}=await q.from("recruit_campaign_emails").delete().eq("id",Be);if(we)throw we},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Email removed from campaign")},onError:Be=>ae.error(Be.message)}),ge=yt({mutationFn:async({emailId:Be,delay_days:we})=>{const{error:Je}=await q.from("recruit_campaign_emails").update({delay_days:we,updated_at:new Date().toISOString()}).eq("id",Be);if(Je)throw Je},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-emails"]}),ae.success("Send delay updated")},onError:Be=>ae.error(Be.message)});if(H)return e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});const Te=z.filter(Be=>!Be.brokerage_id),Ie=z.filter(Be=>Be.brokerage_id===s);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Recruiting Campaigns"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"System campaigns + custom campaigns · Each can have its own email settings"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>u(!0),className:"gap-1.5",children:[e.jsx(Ko,{className:"h-4 w-4"})," Default Settings"]}),e.jsxs(B,{size:"sm",onClick:()=>p(!0),className:"gap-1.5",children:[e.jsx(Is,{className:"h-4 w-4"})," New Campaign"]})]})]}),e.jsx(fe,{className:"border-primary/20 bg-primary/5",children:e.jsx(Ee,{className:"py-3",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(un,{className:"h-5 w-5 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm",children:[e.jsx("p",{className:"font-semibold",children:"Per-Campaign Email Settings"}),e.jsxs("p",{className:"text-muted-foreground",children:["Each campaign can override the default sender name, email, and reply-to. Click the ",e.jsx(Ko,{className:"inline h-3.5 w-3.5"})," icon on any campaign to customize."]})]})]})})}),Ie.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(e9,{className:"h-4 w-4"})," Your Custom Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Ie.map(Be=>Ce(Be,!0))})]}),Te.length>0&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("h3",{className:"text-sm font-semibold text-muted-foreground uppercase tracking-wider flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4"})," System Campaigns"]}),e.jsx("div",{className:"space-y-3",children:Te.map(Be=>Ce(Be,!1))})]}),z.length===0&&e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Gs,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No campaigns yet. Create your first campaign to start automated outreach."}),e.jsxs(B,{className:"mt-4",onClick:()=>p(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})}),e.jsx(zen,{open:!!j,onClose:()=>w(null),campaignName:(j==null?void 0:j.name)||"",stat:j&&S[j.id]||null}),o&&e.jsx(q2t,{email:o,mergeValues:I,selectedSubjectIndex:ee[o.id],onClose:()=>c(null)}),e.jsx(_s,{open:!!i,onOpenChange:Be=>!Be&&l(null),children:e.jsxs(bs,{className:"max-w-4xl max-h-[90vh] overflow-y-auto p-0",children:[e.jsxs(js,{className:"px-6 pt-6 pb-4 border-b",children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(VS,{className:"h-5 w-5 text-primary"}),"Edit Email #",i==null?void 0:i.email_number]}),e.jsx(Jn,{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(ne,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Title"}),e.jsx(ye,{value:i.title,onChange:Be=>l({...i,title:Be.target.value}),className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Delay (days after previous)"}),e.jsx(ye,{type:"number",min:0,max:90,value:i.delay_days,onChange:Be=>l({...i,delay_days:parseInt(Be.target.value)||7}),className:"h-9"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Subject Line"}),e.jsx(ye,{value:i.subject_line,onChange:Be=>l({...i,subject_line:Be.target.value}),placeholder:"e.g. Hey {{first_name}}, quick question...",className:"h-9"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs(ne,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:["Alternative Subject Lines ",e.jsx("span",{className:"text-muted-foreground font-normal normal-case",children:"(one per line, for A/B testing)"})]}),e.jsx(Ms,{value:((Ae=i.subject_line_options)==null?void 0:Ae.join(` `))||"",onChange:Be=>l({...i,subject_line_options:Be.target.value.split(` `).filter(Boolean)}),rows:2,className:"text-sm resize-none"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Email Body"}),e.jsx(Fr,{value:f,onValueChange:Be=>y(Be),children:e.jsxs(Rr,{className:"h-7",children:[e.jsx(Zt,{value:"editor",className:"text-xs px-3 h-6",children:"Editor"}),e.jsx(Zt,{value:"preview",className:"text-xs px-3 h-6",children:"Preview"})]})})]}),f==="editor"?e.jsx(Fen,{content:i.body_html,onChange:Be=>l({...i,body_html:Be})}):e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("div",{className:"bg-muted/50 px-4 py-2 border-b space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("span",{className:"font-medium w-12",children:"From:"}),e.jsxs("span",{children:[I.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:[I.first_name," "]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"font-medium w-12 text-muted-foreground",children:"Subject:"}),e.jsx("span",{className:"font-medium",children:F(i.subject_line)})]})]}),e.jsx("div",{className:"bg-white p-6",children:e.jsx("div",{className:"prose prose-sm max-w-none",style:{fontSize:"15px",lineHeight:"1.75",color:"#1a1a1a"},dangerouslySetInnerHTML:{__html:F(i.body_html)}})})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Changes are saved to this campaign's templates"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>l(null),children:"Cancel"}),e.jsxs(B,{size:"sm",onClick:()=>oe.mutate(i),disabled:oe.isPending,className:"gap-1.5",children:[e.jsx(Jo,{className:"h-3.5 w-3.5"})," Save Changes"]})]})]})]})]})}),e.jsx(_s,{open:h,onOpenChange:p,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Is,{className:"h-5 w-5 text-primary"})," Create Custom Campaign"]}),e.jsx(Jn,{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(ne,{className:"text-xs font-medium",children:"Campaign Name *"}),e.jsx(ye,{value:A.name,onChange:Be=>E({...A,name:Be.target.value}),placeholder:"e.g. Q2 Agent Outreach"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(us,{value:A.warmth_level,onValueChange:Be=>E({...A,warmth_level:Be}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"cold",children:"❄️ Cold — Curiosity"}),e.jsx(Ze,{value:"warm",children:"☀️ Warm — Growth"}),e.jsx(Ze,{value:"hot",children:"🔥 Hot — Private Invite"})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Primary CTA"}),e.jsx(ye,{value:A.primary_cta,onChange:Be=>E({...A,primary_cta:Be.target.value}),placeholder:"Learn more"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Description"}),e.jsx(Ms,{value:A.description,onChange:Be=>E({...A,description:Be.target.value}),placeholder:"What is this campaign about?",rows:2})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Goal"}),e.jsx(ye,{value:A.goal,onChange:Be=>E({...A,goal:Be.target.value}),placeholder:"e.g. Convert warm leads to meetings"})]}),e.jsxs(oy,{children:[e.jsx(ly,{asChild:!0,children:e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full justify-between text-xs font-medium text-muted-foreground hover:text-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(Gs,{className:"h-3.5 w-3.5"})," Email Settings Override"]}),e.jsx(ao,{className:"h-3.5 w-3.5"})]})}),e.jsxs(cy,{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(ne,{className:"text-xs",children:"Sender Name"}),e.jsx(ye,{value:A.sender_name,onChange:Be=>E({...A,sender_name:Be.target.value}),placeholder:"e.g. Jeremy at LevelUp"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Sender Email"}),e.jsx(ye,{value:A.sender_email,onChange:Be=>E({...A,sender_email:Be.target.value}),placeholder:"e.g. recruiting@send.relevelup.com"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Reply-To Email"}),e.jsx(ye,{value:A.reply_to_email,onChange:Be=>E({...A,reply_to_email:Be.target.value}),placeholder:"e.g. jeremy@mybrokerage.com"})]})]})]}),e.jsxs(B,{className:"w-full",disabled:!A.name.trim()||he.isPending,onClick:()=>he.mutate(),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Create Campaign"]})]})]})}),e.jsx(_s,{open:!!_,onOpenChange:Be=>!Be&&v(null),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Ko,{className:"h-5 w-5 text-primary"})," Campaign Email Settings"]}),e.jsx(Jn,{children:"Override the default sender for this campaign. Leave blank to use brokerage defaults."})]}),_&&e.jsxs("div",{className:"space-y-4 pt-2",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Campaign Name"}),e.jsx(ye,{value:_.name,onChange:Be=>v({..._,name:Be.target.value})})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Warmth Level"}),e.jsxs(us,{value:_.warmth_level,onValueChange:Be=>v({..._,warmth_level:Be}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"cold",children:"❄️ Cold"}),e.jsx(Ze,{value:"warm",children:"☀️ Warm"}),e.jsx(Ze,{value:"hot",children:"🔥 Hot"})]})]})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Goal"}),e.jsx(ye,{value:_.goal||"",onChange:Be=>v({..._,goal:Be.target.value})})]}),e.jsxs("div",{className:"border-t pt-4 space-y-3",children:[e.jsxs("p",{className:"text-sm font-semibold flex items-center gap-1.5",children:[e.jsx(Gs,{className:"h-4 w-4 text-primary"})," Email Sender Override"]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Sender Name"}),e.jsx(ye,{value:_.sender_name||"",onChange:Be=>v({..._,sender_name:Be.target.value}),placeholder:"Uses brokerage default"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Sender Email"}),e.jsx(ye,{value:_.sender_email||"",onChange:Be=>v({..._,sender_email:Be.target.value}),placeholder:"Uses brokerage default"}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Must be a verified sending domain"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs",children:"Reply-To Email"}),e.jsx(ye,{value:_.reply_to_email||"",onChange:Be=>v({..._,reply_to_email:Be.target.value}),placeholder:"Uses brokerage default"})]})]}),e.jsxs(B,{className:"w-full",onClick:()=>ce.mutate(_),disabled:ce.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-1"})," Save Campaign Settings"]})]})]})}),e.jsx(_s,{open:d,onOpenChange:u,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Default Recruiting Email Settings"}),e.jsx(Jn,{children:"These defaults apply to campaigns without their own overrides."})]}),e.jsx(i8e,{brokerageId:s})]})})]});function Ce(Be,we){const Je=iXe[Be.warmth_level]||iXe.cold,ke=Je.icon,it=Z[Be.id]||[],je=r===Be.id,He=!!(Be.sender_name||Be.sender_email||Be.reply_to_email),$e=S[Be.id];return e.jsxs(fe,{className:"overflow-hidden transition-shadow hover:shadow-md",children:[e.jsx(It,{className:"cursor-pointer hover:bg-muted/40 transition-colors py-4",onClick:()=>a(je?null:Be.id),children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl ${Je.bg} flex items-center justify-center`,children:e.jsx(ke,{className:`h-5 w-5 ${Je.color}`})}),e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[Be.name,e.jsx(Ue,{variant:Be.is_active?"default":"secondary",className:"text-[10px] px-1.5",children:Be.is_active?"Active":"Draft"}),we&&e.jsx(Ue,{variant:"outline",className:"text-[10px] px-1.5",children:"Custom"}),He&&e.jsxs(Ue,{variant:"outline",className:"text-[10px] px-1.5 border-primary/30 text-primary",children:[e.jsx(Gs,{className:"h-2.5 w-2.5 mr-0.5"})," Custom Sender"]})]}),e.jsx(Vn,{className:"text-xs mt-0.5",children:Be.theme||Be.description})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:Ke=>{Ke.stopPropagation(),v({...Be})},children:e.jsx(Ko,{className:"h-4 w-4 text-muted-foreground"})}),we&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:Ke=>{Ke.stopPropagation(),confirm("Delete this campaign and all its emails? This cannot be undone.")&&le.mutate(Be.id)},children:e.jsx(_n,{className:"h-4 w-4"})}),$e&&$e.sent>0&&e.jsxs("div",{className:"hidden md:flex items-center gap-1.5",children:[e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1 font-medium",title:"Total emails sent",children:[e.jsx(Gs,{className:"h-2.5 w-2.5"})," ",$e.sent.toLocaleString()]}),e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1 border-amber-500/30 text-amber-600 font-medium",title:`${$e.openRate.toFixed(1)}% open rate`,children:[e.jsx(Sr,{className:"h-2.5 w-2.5"})," ",$e.opened.toLocaleString()," (",$e.openRate.toFixed(0),"%)"]}),e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1 border-green-500/30 text-green-600 font-medium",title:`${$e.clickRate.toFixed(1)}% click rate`,children:[e.jsx(oc,{className:"h-2.5 w-2.5"})," ",$e.clicked.toLocaleString()," (",$e.clickRate.toFixed(1),"%)"]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 px-2 gap-1 text-xs",onClick:Ke=>{Ke.stopPropagation(),w(Be)},title:"View detailed engagement stats",children:[e.jsx(_o,{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(Gs,{className:"h-3.5 w-3.5"}),e.jsxs("span",{children:[it.length," emails"]})]}),e.jsx("div",{className:"h-7 w-7 rounded-md flex items-center justify-center",children:je?e.jsx(ex,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ao,{className:"h-4 w-4 text-muted-foreground"})})]})]})}),je&&e.jsxs(Ee,{className:"pt-0 pb-4 space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4 p-3 rounded-lg bg-muted/40 text-sm",children:[e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Goal"}),e.jsx("p",{className:"mt-0.5",children:Be.goal||"—"})]}),e.jsxs("div",{children:[e.jsx("span",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wider",children:"Primary CTA"}),e.jsx("p",{className:"mt-0.5",children:Be.primary_cta||"—"})]})]}),He&&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(Gs,{className:"h-3 w-3"})," Campaign Sender Override"]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-xs text-muted-foreground",children:[Be.sender_name&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Name:"})," ",Be.sender_name]}),Be.sender_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Email:"})," ",Be.sender_email]}),Be.reply_to_email&&e.jsxs("p",{children:[e.jsx("span",{className:"font-medium",children:"Reply-To:"})," ",Be.reply_to_email]})]})]}),e.jsx("div",{className:"relative",children:it.map((Ke,Ge)=>{var rt,tt;return e.jsxs("div",{className:"relative flex gap-4 pb-4 last:pb-0",children:[Geat.stopPropagation(),onBlur:at=>{const Ye=parseInt(at.target.value)||0;Ye!==Ke.delay_days&&ge.mutate({emailId:Ke.id,delay_days:Ye})},onKeyDown:at=>{at.key==="Enter"&&at.target.blur()}}),"days"]})]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),Ke.email_number===1?"Sent immediately":`Day ${Ke.delay_days}`]}),e.jsx("span",{className:"text-border",children:"•"}),e.jsxs("span",{className:"truncate",children:["Subject: ",F(((rt=Ke.subject_line_options)==null?void 0:rt.length)>0&&Ke.subject_line_options[ee[Ke.id]??0]||Ke.subject_line)]})]}),((tt=Ke.subject_line_options)==null?void 0:tt.length)>1&&e.jsx("div",{className:"mt-2",children:e.jsxs(us,{value:String(ee[Ke.id]??0),onValueChange:at=>se.mutate({campaignEmailId:Ke.id,selectedIndex:parseInt(at)}),children:[e.jsx(ls,{className:"h-7 text-xs w-full max-w-sm",children:e.jsx(hs,{placeholder:"Choose subject line"})}),e.jsx(cs,{children:Ke.subject_line_options.map((at,Ye)=>e.jsxs(Ze,{value:String(Ye),className:"text-xs",children:[e.jsxs("span",{className:"font-medium mr-1.5",children:[Ye===0?"Primary":`Alt ${Ye}`,":"]}),F(at)]},Ye))})]})})]}),e.jsxs("div",{className:"flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity shrink-0",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>c(Ke),children:e.jsx(Sr,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>{l({...Ke}),y("editor")},children:e.jsx(ya,{className:"h-4 w-4"})}),we&&it.length>1&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-destructive hover:text-destructive hover:bg-destructive/10",onClick:()=>{confirm("Delete this email from the sequence?")&&ve.mutate(Ke.id)},children:e.jsx(_n,{className:"h-4 w-4"})})]})]})})]},Ke.id)})}),we&&e.jsxs(B,{variant:"outline",size:"sm",className:"w-full gap-1.5",onClick:()=>me.mutate(Be.id),disabled:me.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5"})," Add Email to Sequence"]})]})]},Be.id)}}const oXe={active:{icon:El,color:"bg-green-500/10 text-green-600",label:"Active"},paused:{icon:gf,color:"bg-amber-500/10 text-amber-600",label:"Paused"},completed:{icon:Pi,color:"bg-blue-500/10 text-blue-600",label:"Completed"},cancelled:{icon:Uc,color:"bg-red-500/10 text-red-600",label:"Cancelled"}},lXe={sent:{icon:Gs,color:"text-blue-500"},opened:{icon:Sr,color:"text-amber-500"},clicked:{icon:oc,color:"text-green-500"},failed:{icon:ic,color:"text-destructive"}};function G2t({brokerageId:s}){var Ae,Be,we,Je,ke;const{user:t}=vs(),n=Kt(),[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(new Set),[d,u]=N.useState("assignments"),[h,p]=N.useState(null),[f,y]=N.useState(""),[_,v]=N.useState("all"),[j,w]=N.useState("all"),[S,A]=N.useState(!1),{data:E}=d1e(),{data:O={}}=dt({queryKey:["recruit-campaign-emails-for-preview",s],queryFn:async()=>{const{data:it,error:je}=await q.from("recruit_campaign_emails").select("*").order("email_number");if(je)throw je;const He={};return(it??[]).forEach($e=>{He[$e.campaign_id]||(He[$e.campaign_id]=[]),He[$e.campaign_id].push($e)}),He}}),{data:D}=dt({queryKey:["brokerage-detail",s],queryFn:async()=>{const{data:it,error:je}=await q.from("brokerages").select("name, city, state").eq("id",s).single();if(je)throw je;return it}}),{data:I}=dt({queryKey:["brokerage-recruit-settings",s],queryFn:async()=>{const{data:it,error:je}=await q.from("brokerage_recruit_settings").select("*").eq("brokerage_id",s).maybeSingle();if(je)throw je;return it}}),{data:F=[]}=dt({queryKey:["recruit-subject-overrides",s],queryFn:async()=>{const{data:it,error:je}=await q.from("recruit_brokerage_subject_overrides").select("*").eq("brokerage_id",s);if(je)throw je;return it}}),z={};F.forEach(it=>{z[it.campaign_email_id]=it.selected_subject_index});const H={first_name:((Ae=h==null?void 0:h.prospect)==null?void 0:Ae.first_name)||"Sarah",brokerage_name:((Be=I==null?void 0:I.merge_fields)==null?void 0:Be.brokerage_name)||(D==null?void 0:D.name)||"Your Brokerage",city:((we=I==null?void 0:I.merge_fields)==null?void 0:we.city)||(D==null?void 0:D.city)||"Your City",sender_name:((Je=I==null?void 0:I.merge_fields)==null?void 0:Je.sender_name)||(I==null?void 0:I.sender_name)||"Your Name"},Z=it=>{const je=O[it.campaign_id]||[],He=it.current_email_number+1;return je.find($e=>$e.email_number===He)||null},{data:Y=[],isLoading:W}=dt({queryKey:["recruit-campaign-assignments",s],queryFn:async()=>{let je=[],He=0;for(;;){const{data:$e,error:Ke}=await q.from("recruit_campaign_assignments").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign:recruit_campaigns(name, warmth_level) `).eq("brokerage_id",s).order("created_at",{ascending:!1}).range(He,He+1e3-1);if(Ke)throw Ke;if(je=je.concat($e??[]),!$e||$e.length<1e3)break;He+=1e3}return je}}),{data:ee=[]}=dt({queryKey:["recruit-campaign-sends",s],queryFn:async()=>{const{data:it,error:je}=await q.from("recruit_campaign_sends").select(` *, prospect:recruit_prospects(first_name, last_name, email), campaign_email:recruit_campaign_emails(title, campaign_id) `).eq("brokerage_id",s).neq("status","failed").order("sent_at",{ascending:!1}).limit(500);if(je)throw je;return it}}),{data:se=[]}=dt({queryKey:["recruit-campaigns"],queryFn:async()=>{const{data:it,error:je}=await q.from("recruit_campaigns").select("id, name, warmth_level").eq("is_active",!0).order("sort_order");if(je)throw je;return it}}),{data:oe=[]}=dt({queryKey:["recruit-prospects-for-assign",s],queryFn:async()=>{let je=[],He=0;for(;;){const{data:$e,error:Ke}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s).order("first_name").range(He,He+1e3-1);if(Ke)throw Ke;if(je=je.concat($e??[]),!$e||$e.length<1e3)break;He+=1e3}return je}}),he=new Set(Y.map(it=>`${it.prospect_id}-${it.campaign_id}`)),ce=yt({mutationFn:async()=>{if(!i||o.size===0)throw new Error("Select a campaign and at least one prospect");const it=new Date,je=Array.from(o).filter($e=>!he.has(`${$e}-${i}`)).map($e=>({prospect_id:$e,campaign_id:i,brokerage_id:s,assigned_by:t.id,status:"active",current_email_number:0,next_send_at:it.toISOString(),started_at:it.toISOString()}));if(je.length===0)throw new Error("All selected prospects are already assigned to this campaign");const{error:He}=await q.from("recruit_campaign_assignments").insert(je);if(He)throw He},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success(`Campaign assigned to ${o.size} prospect(s)!`),a(!1),l(""),c(new Set)},onError:it=>ae.error(it.message)}),me=yt({mutationFn:async({id:it,newStatus:je})=>{const{error:He}=await q.from("recruit_campaign_assignments").update({status:je,updated_at:new Date().toISOString()}).eq("id",it);if(He)throw He},onSuccess:()=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),ae.success("Assignment updated")}}),le=yt({mutationFn:async()=>{const{data:it,error:je}=await q.functions.invoke("ses-recruit-drip",{body:{action:"process_drips"}});if(je)throw je;return it},onSuccess:it=>{n.invalidateQueries({queryKey:["recruit-campaign-assignments",s]}),n.invalidateQueries({queryKey:["recruit-campaign-sends",s]}),ae.success(`Wave sent! ${it.sent} emails delivered, ${it.skipped} skipped, ${it.failed} failed`)},onError:it=>ae.error(`Send failed: ${it.message}`)}),ve=Y.filter(it=>it.status==="active").length;Y.filter(it=>it.status==="completed").length;const ge=Y.filter(it=>it.status==="active"&&it.next_send_at&&new Date(it.next_send_at)<=new Date).length,{data:Te={}}=V2t(s),Ie=Y.reduce((it,je)=>it+Math.max(0,je.current_email_number||0),0),Ce=Object.values(Te).reduce((it,je)=>it+je.opened,0),Me=Object.values(Te).reduce((it,je)=>it+je.clicked,0);Object.values(Te).reduce((it,je)=>it+je.failed,0);const Pe=Ie>0?Math.round(Ce/Ie*100):0,Re=Ie>0?Me/Ie*100:0;return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-xl font-bold",children:"Campaign Assignments"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Assign recruiting campaigns to prospects — emails auto-send weekly via SES"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[ge>0&&e.jsxs(B,{variant:"outline",onClick:()=>{le.mutate()},disabled:le.isPending,className:"border-amber-500/50 text-amber-600 hover:bg-amber-500/10",children:[e.jsx(im,{className:"h-4 w-4 mr-1"}),le.isPending?"Sending...":`Send Next Wave (${ge})`]}),e.jsxs(B,{onClick:()=>a(!0),children:[e.jsx(lr,{className:"h-4 w-4 mr-1"})," Assign Campaign"]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(An,{className:"h-7 w-7 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:Y.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Assigned"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(El,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:ve}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Active"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Gs,{className:"h-7 w-7 text-blue-500"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold",children:Ie.toLocaleString()}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Emails Sent"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(Sr,{className:"h-7 w-7 text-amber-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Pe,"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Open Rate (",Ce.toLocaleString(),")"]})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-3 pb-2 flex items-center gap-3",children:[e.jsx(oc,{className:"h-7 w-7 text-green-500"}),e.jsxs("div",{children:[e.jsxs("p",{className:"text-xl font-bold",children:[Re.toFixed(1),"%"]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Click Rate (",Me.toLocaleString(),")"]})]})]})})]}),e.jsxs(Fr,{value:d,onValueChange:u,children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"assignments",children:["Active Drips (",ve,")"]}),e.jsxs(Zt,{value:"history",children:["Send History (",Ie.toLocaleString(),")"]})]}),e.jsx(is,{value:"assignments",className:"mt-4",children:W?e.jsx("div",{className:"flex justify-center py-8",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):Y.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(lr,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No campaigns assigned yet"}),e.jsx("p",{className:"text-sm",children:"Assign a recruiting campaign to your prospects to start automated outreach"})]})}):e.jsx("div",{className:"space-y-2",children:Y.map(it=>{var rt,tt,at,Ye;const je=oXe[it.status]||oXe.active,He=je.icon,Ke=(O[it.campaign_id]||[]).length||4,Ge=Z(it);return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsxs(Ue,{className:`text-xs ${je.color} border-0`,children:[e.jsx(He,{className:"h-3 w-3 mr-1"}),je.label]}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm",children:[(rt=it.prospect)==null?void 0:rt.first_name," ",(tt=it.prospect)==null?void 0:tt.last_name,e.jsx("span",{className:"text-muted-foreground font-normal ml-2",children:(at=it.prospect)==null?void 0:at.email})]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[(Ye=it.campaign)==null?void 0:Ye.name," · Email ",it.current_email_number,"/",Ke,it.next_send_at&&it.status==="active"&&e.jsxs(e.Fragment,{children:[" ","· ",e.jsx(pr,{className:"h-3 w-3 inline"})," Next: ",Ss(new Date(it.next_send_at),"MMM d, h:mm a"),new Date(it.next_send_at)<=new Date&&e.jsx(Ue,{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:[Ge&&e.jsx(B,{variant:"ghost",size:"sm",title:"Preview next email",onClick:()=>p(it),children:e.jsx(Sr,{className:"h-3.5 w-3.5"})}),it.status==="active"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>me.mutate({id:it.id,newStatus:"paused"}),children:e.jsx(gf,{className:"h-3.5 w-3.5"})}),it.status==="paused"&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>me.mutate({id:it.id,newStatus:"active"}),children:e.jsx(El,{className:"h-3.5 w-3.5"})}),(it.status==="active"||it.status==="paused")&&e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive",onClick:()=>me.mutate({id:it.id,newStatus:"cancelled"}),children:e.jsx(Uc,{className:"h-3.5 w-3.5"})})]})]},it.id)})})}),e.jsxs(is,{value:"history",className:"mt-4 space-y-3",children:[e.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[e.jsx("span",{className:"text-xs text-muted-foreground",children:"Filter:"}),e.jsxs(us,{value:_,onValueChange:v,children:[e.jsx(ls,{className:"w-[220px] h-8 text-xs",children:e.jsx(hs,{placeholder:"All campaigns"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All campaigns"}),se.map(it=>e.jsx(Ze,{value:it.id,children:it.name},it.id))]})]}),e.jsxs(us,{value:j,onValueChange:w,children:[e.jsx(ls,{className:"w-[160px] h-8 text-xs",children:e.jsx(hs,{placeholder:"All statuses"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All statuses"}),e.jsx(Ze,{value:"sent",children:"Sent (no engagement)"}),e.jsx(Ze,{value:"opened",children:"Opened"}),e.jsx(Ze,{value:"clicked",children:"Clicked"})]})]}),(_!=="all"||j!=="all")&&e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 text-xs",onClick:()=>{v("all"),w("all")},children:"Clear"})]}),(()=>{var je;const it=ee.filter(He=>{var $e;return!(_!=="all"&&(($e=He.campaign_email)==null?void 0:$e.campaign_id)!==_||j==="opened"&&!He.opened_at||j==="clicked"&&!He.clicked_at||j==="sent"&&(He.opened_at||He.clicked_at))});return it.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(Gs,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:ee.length===0?"No emails sent yet":"No emails match these filters"}),e.jsx("p",{className:"text-sm",children:ee.length===0?"Emails will appear here once campaigns start sending":"Try clearing the filters above"})]})}):e.jsxs(e.Fragment,{children:[e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Showing ",it.length," of ",ee.length," recent sends",_!=="all"&&` · ${(je=se.find(He=>He.id===_))==null?void 0:je.name}`]}),e.jsx("div",{className:"space-y-1",children:it.map(He=>{var rt,tt,at;const $e=lXe[He.status]||lXe.sent,Ke=$e.icon,Ge=(rt=se.find(Ye=>{var ut;return Ye.id===((ut=He.campaign_email)==null?void 0:ut.campaign_id)}))==null?void 0:rt.name;return e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3 min-w-0",children:[e.jsx(Ke,{className:`h-4 w-4 flex-shrink-0 ${$e.color}`}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(tt=He.prospect)==null?void 0:tt.first_name," ",(at=He.prospect)==null?void 0:at.last_name,e.jsxs("span",{className:"text-muted-foreground font-normal ml-2",children:["Email #",He.email_number]}),Ge&&e.jsx(Ue,{variant:"outline",className:"ml-2 text-[10px] px-1.5 py-0 font-normal",children:Ge})]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:He.subject})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground flex-shrink-0",children:[He.opened_at&&e.jsxs("span",{className:"flex items-center gap-1 text-amber-500",children:[e.jsx(Sr,{className:"h-3 w-3"})," ",Ss(new Date(He.opened_at),"MMM d")]}),He.clicked_at&&e.jsxs("span",{className:"flex items-center gap-1 text-green-500",children:[e.jsx(oc,{className:"h-3 w-3"})," ",Ss(new Date(He.clicked_at),"MMM d")]}),e.jsx("span",{children:Ss(new Date(He.sent_at),"MMM d, h:mm a")})]})]},He.id)})})]})})()]})]}),e.jsx(_s,{open:r,onOpenChange:it=>{a(it),it||(y(""),c(new Set),l(""))},children:e.jsxs(bs,{className:"max-w-lg max-h-[85vh] flex flex-col p-0",children:[e.jsxs(js,{className:"px-6 pt-6 pb-4",children:[e.jsx(ws,{children:"Assign Campaign to Prospects"}),e.jsx(Jn,{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(ne,{className:"text-sm font-medium",children:"1. Select Campaign"}),e.jsxs(us,{value:i,onValueChange:l,children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Choose a campaign..."})}),e.jsx(cs,{children:se.map(it=>e.jsx(Ze,{value:it.id,children:it.name},it.id))})]})]}),i&&(()=>{const it=f.toLowerCase(),je=oe.filter(Ke=>`${Ke.first_name} ${Ke.last_name}`.toLowerCase().includes(it)||Ke.email.toLowerCase().includes(it)),He=je.filter(Ke=>!he.has(`${Ke.id}-${i}`)),$e=He.length>0&&He.every(Ke=>o.has(Ke.id));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{className:"text-sm font-medium",children:"2. Select Prospects"}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[o.size," selected"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1",children:[e.jsx(gr,{className:"absolute left-2.5 top-2.5 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:f,onChange:Ke=>y(Ke.target.value),className:"pl-9 h-9"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-9 whitespace-nowrap",onClick:()=>{if($e){const Ke=new Set(o);He.forEach(Ge=>Ke.delete(Ge.id)),c(Ke)}else{const Ke=new Set(o);He.forEach(Ge=>Ke.add(Ge.id)),c(Ke)}},children:[e.jsx(B7,{className:"h-3.5 w-3.5 mr-1"}),$e?"Deselect All":`Select All (${He.length})`]})]}),e.jsx("div",{className:"border rounded-lg max-h-60 overflow-y-auto divide-y",children:je.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:f?"No prospects match your search":"No prospects found for this brokerage"}):je.map(Ke=>{const Ge=he.has(`${Ke.id}-${i}`);return e.jsxs("label",{className:`flex items-center gap-3 p-2.5 hover:bg-muted/50 cursor-pointer ${Ge?"opacity-40":""}`,children:[e.jsx(hi,{checked:o.has(Ke.id),disabled:Ge,onCheckedChange:rt=>{const tt=new Set(o);rt?tt.add(Ke.id):tt.delete(Ke.id),c(tt)}}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Ke.first_name," ",Ke.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ke.email})]}),Ge&&e.jsx(Ue,{variant:"outline",className:"text-[10px] shrink-0",children:"Already assigned"})]},Ke.id)})}),je.length>0&&e.jsxs("p",{className:"text-[11px] text-muted-foreground",children:["Showing ",je.length," of ",oe.length," prospects",He.length0&&e.jsx(fe,{className:"bg-primary/5 border-primary/20",children:e.jsxs(Ee,{className:"pt-3 pb-2 text-sm space-y-1",children:[e.jsxs("p",{className:"font-medium text-primary",children:["✅ Ready to assign ",o.size," prospect",o.size>1?"s":""]}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["• Campaign: ",e.jsx("strong",{children:(ke=se.find(it=>it.id===i))==null?void 0:ke.name})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• First email sends immediately · follow-ups every 7 days"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"• You can pause or cancel any assignment at any time"})]})})]}),e.jsxs(Xn,{className:"px-6 py-4 border-t",children:[e.jsx(B,{variant:"outline",onClick:()=>a(!1),children:"Cancel"}),e.jsxs(B,{onClick:()=>{ce.mutate()},disabled:ce.isPending||!i||o.size===0,children:[e.jsx(lr,{className:"h-4 w-4 mr-1"}),ce.isPending?"Assigning...":`Assign & Start (${o.size})`]})]})]})}),h&&(()=>{const it=Z(h);return it?e.jsx(q2t,{email:it,mergeValues:H,selectedSubjectIndex:z[it.id],onClose:()=>p(null)}):null})(),e.jsx(u1e,{open:S,onOpenChange:A,hasPending:E==null?void 0:E.hasPendingSes,pendingEmails:E==null?void 0:E.pendingEmails})]})}function W2t({brokerageId:s}){const t=Kt(),[n,r]=N.useState([]),[a,i]=N.useState([]),[l,o]=N.useState(!1),c=N.useRef(!1),{data:d,isLoading:u}=dt({queryKey:["recruit-stages-editor",s],queryFn:async()=>{const{data:v,error:j}=await q.from("recruit_pipeline_stages").select("*").eq("brokerage_id",s).order("sort_order");if(j)throw j;return v},enabled:!!s});N.useEffect(()=>{if(d){if(c.current){c.current=!1;return}r(d.map(v=>({id:v.id,name:v.name,color:v.color,sort_order:v.sort_order}))),i([]),o(!1)}},[d]);const h=yt({mutationFn:async()=>{for(const w of a){const{error:S}=await q.from("recruit_pipeline_stages").delete().eq("id",w);if(S)throw S}const v=n.filter(w=>w.id&&!w.isNew),j=n.filter(w=>!w.id||w.isNew);for(const w of v){const{error:S}=await q.from("recruit_pipeline_stages").update({name:w.name,color:w.color,sort_order:w.sort_order}).eq("id",w.id);if(S)throw S}if(j.length>0){const{error:w}=await q.from("recruit_pipeline_stages").insert(j.map(S=>({brokerage_id:s,name:S.name,color:S.color,sort_order:S.sort_order})));if(w)throw w}},onSuccess:()=>{i([]),t.invalidateQueries({queryKey:["recruit-stages-editor",s]}),t.invalidateQueries({queryKey:["recruit-stages",s]}),ae.success("Pipeline stages saved!"),o(!1)},onError:v=>ae.error(v.message)}),p=(v,j,w)=>{r(S=>S.map((A,E)=>E===v?{...A,[j]:w}:A)),o(!0)},f=()=>{const v=n.length>0?Math.max(...n.map(j=>j.sort_order)):0;r(j=>[...j,{name:"",color:"#6366f1",sort_order:v+1,isNew:!0}]),o(!0)},y=v=>{const j=n[v];j.id&&!j.isNew&&i(w=>[...w,j.id]),r(w=>w.filter((S,A)=>A!==v)),o(!0)},_=(v,j)=>{const w=v+j;if(w<0||w>=n.length)return;const S=[...n];[S[v],S[w]]=[S[w],S[v]],S.forEach((A,E)=>A.sort_order=E+1),r(S),o(!0)};return u?e.jsx("div",{className:"text-sm text-muted-foreground py-8 text-center",children:"Loading stages…"}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Customize the recruiting pipeline stages for this brokerage. Changes will apply to the Kanban board and all prospect tracking."})]}),e.jsx("div",{className:"space-y-2",children:n.map((v,j)=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border bg-card",children:[e.jsxs("div",{className:"flex flex-col gap-0.5",children:[e.jsx("button",{type:"button",onClick:()=>_(j,-1),disabled:j===0,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▲"}),e.jsx("button",{type:"button",onClick:()=>_(j,1),disabled:j===n.length-1,className:"text-muted-foreground hover:text-foreground disabled:opacity-30 text-xs",children:"▼"})]}),e.jsx(Pu,{className:"h-4 w-4 text-muted-foreground/50 shrink-0"}),e.jsx("input",{type:"color",value:v.color,onChange:w=>p(j,"color",w.target.value),className:"h-8 w-8 rounded cursor-pointer border-0 p-0 shrink-0"}),e.jsx(ye,{value:v.name,onChange:w=>p(j,"name",w.target.value),placeholder:"Stage name…",className:"flex-1"}),e.jsx("span",{className:"text-xs text-muted-foreground w-6 text-center shrink-0",children:j+1}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>y(j),className:"text-destructive hover:text-destructive shrink-0 h-8 w-8",children:e.jsx(_n,{className:"h-4 w-4"})})]},v.id||`new-${j}`))}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:f,className:"gap-1",children:[e.jsx(Is,{className:"h-4 w-4"})," Add Stage"]}),l&&e.jsxs(B,{size:"sm",onClick:()=>h.mutate(),disabled:h.isPending,className:"gap-1",children:[e.jsx(Jo,{className:"h-4 w-4"})," Save Changes"]})]}),n.length===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No stages configured. Add stages to build your recruiting pipeline."})]})}function Ben({brokerageId:s}){const{data:t=[],isLoading:n}=dt({queryKey:["recruit-unsubscribed",s],queryFn:async()=>{const{data:r,error:a}=await q.from("recruit_prospects").select("id, first_name, last_name, email, unsubscribed_at, unsubscribe_reason, current_brokerage").eq("brokerage_id",s).not("unsubscribed_at","is",null).order("unsubscribed_at",{ascending:!1}).limit(500);if(a)throw a;return r||[]},enabled:!!s});return n?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-6 w-6 animate-spin rounded-full border-2 border-primary border-t-transparent"})}):e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs("h3",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(LA,{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(Ue,{variant:"secondary",className:"text-base px-3 py-1",children:[t.length," total"]})]}),t.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"py-12 text-center text-muted-foreground",children:[e.jsx(LA,{className:"h-10 w-10 mx-auto mb-3 opacity-40"}),e.jsx("p",{className:"text-sm",children:"No prospects have unsubscribed. Nice work!"})]})}):e.jsx("div",{className:"grid gap-3",children:t.map(r=>e.jsxs(fe,{className:"hover:shadow-sm transition-shadow",children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"text-base",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-1",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gs,{className:"h-3 w-3"}),r.email]}),r.current_brokerage&&e.jsxs("span",{children:["· ",r.current_brokerage]})]})]}),e.jsxs("div",{className:"flex items-center gap-1.5 text-xs text-muted-foreground whitespace-nowrap",children:[e.jsx(yr,{className:"h-3 w-3"}),r.unsubscribed_at&&Ss(new Date(r.unsubscribed_at),"MMM d, yyyy")]})]})}),r.unsubscribe_reason&&e.jsx(Ee,{className:"pt-0",children:e.jsxs("div",{className:"text-sm bg-muted/40 rounded-md px-3 py-2 italic text-muted-foreground",children:['"',r.unsubscribe_reason,'"']})})]},r.id))})]})}function $en(){var o;const[s,t]=N.useState(""),[n,r]=N.useState("board"),{data:a=[],isLoading:i}=dt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:c,error:d}=await q.from("brokerages").select("id, name").order("name");if(d)throw d;return c}}),l=s||((o=a[0])==null?void 0:o.id)||"";return i?e.jsx(Cs,{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(Cs,{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(us,{value:l,onValueChange:t,children:[e.jsxs(ls,{className:"w-[280px]",children:[e.jsx(Ua,{className:"mr-2 h-4 w-4"}),e.jsx(hs,{placeholder:"Select brokerage"})]}),e.jsx(cs,{children:a.map(c=>e.jsx(Ze,{value:c.id,children:c.name},c.id))})]})]}):e.jsx("div",{}),l&&e.jsx(B2t,{brokerageId:l,trigger:e.jsxs(B,{size:"sm",className:"gap-1.5",children:[e.jsx(fr,{className:"h-4 w-4"})," Record & Send Video"]})})]}),l?e.jsxs(Fr,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Rr,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Zt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(An,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Zt,{value:"video-outreach",children:[e.jsx(fr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Zt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"interest",children:"Interest Form"}),e.jsx(Zt,{value:"landing-page",children:"Landing Page"}),e.jsx(Zt,{value:"goals",children:"Goals"}),e.jsx(Zt,{value:"metrics",children:"Metrics"}),e.jsx(Zt,{value:"templates",children:"Email Templates"}),e.jsxs(Zt,{value:"campaigns",children:[e.jsx(Gs,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Zt,{value:"drip-assignments",children:[e.jsx(lr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsx(Zt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Zt,{value:"email-settings",children:[e.jsx(Ko,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Zt,{value:"pipeline-stages",children:[e.jsx(e4,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]}),e.jsxs(Zt,{value:"unsubscribed",children:[e.jsx(LA,{className:"h-3.5 w-3.5 mr-1"}),"Unsubscribed"]})]}),e.jsxs(is,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs(B,{variant:n==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("board"),children:[e.jsx(ff,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(B,{variant:n==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>r("table"),children:[e.jsx(mL,{className:"h-3.5 w-3.5"})," Table"]})]})}),n==="board"?e.jsx(I2t,{brokerageId:l}):e.jsx(Lge,{brokerageId:l})]}),e.jsx(is,{value:"contacts",children:e.jsx(Lge,{brokerageId:l})}),e.jsx(is,{value:"video-outreach",children:e.jsx($2t,{brokerageId:l})}),e.jsx(is,{value:"follow-ups",children:e.jsx(F2t,{brokerageId:l})}),e.jsx(is,{value:"referrals",children:e.jsx(R2t,{brokerageId:l})}),e.jsx(is,{value:"interest",children:e.jsx(O2t,{brokerageId:l})}),e.jsx(is,{value:"landing-page",children:e.jsx(z2t,{brokerageId:l})}),e.jsx(is,{value:"goals",children:e.jsx(U2t,{brokerageId:l})}),e.jsx(is,{value:"metrics",children:e.jsx(P2t,{brokerageId:l})}),e.jsx(is,{value:"templates",children:e.jsx(L2t,{brokerageId:l})}),e.jsx(is,{value:"campaigns",children:e.jsx(H2t,{brokerageId:l})}),e.jsx(is,{value:"drip-assignments",children:e.jsx(G2t,{brokerageId:l})}),e.jsx(is,{value:"activity",children:e.jsx(D2t,{brokerageId:l})}),e.jsx(is,{value:"email-settings",children:e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Email Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Configure sender identity, merge fields, and brokerage location for recruiting emails."}),e.jsx(i8e,{brokerageId:l})]})}),e.jsx(is,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(W2t,{brokerageId:l})})}),e.jsx(is,{value:"unsubscribed",children:e.jsx(Ben,{brokerageId:l})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ua,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found. Create a brokerage first."})]})]})})}function Uen({brokerageId:s}){const[t,n]=N.useState(""),[r,a]=N.useState("all"),{data:i,isLoading:l}=dt({queryKey:["recruit-sent-emails",s],queryFn:async()=>{var v;const{data:d,error:u}=await q.from("recruit_prospects").select("id, first_name, last_name, email").eq("brokerage_id",s);if(u)throw u;const h=new Map((d||[]).map(j=>[j.id,j]));if(Array.from(h.keys()).length===0)return[];const{data:f}=await q.from("recruit_videos").select("id, prospect_id, share_token, sent_at, sent_via, view_count, first_viewed_at, cta_clicked_at, video:agent_videos(title)").eq("brokerage_id",s).not("sent_at","is",null).order("sent_at",{ascending:!1}),{data:y}=await q.from("recruit_campaign_sends").select("id, prospect_id, subject, status, sent_at, opened_at, clicked_at, error_message, email_number").eq("brokerage_id",s).order("sent_at",{ascending:!1,nullsFirst:!1}),_=[];for(const j of f||[]){const w=h.get(j.prospect_id);w&&_.push({id:`v-${j.id}`,kind:"video",prospect_id:j.prospect_id,prospect_name:`${w.first_name||""} ${w.last_name||""}`.trim()||"—",prospect_email:w.email,subject:(v=j.video)!=null&&v.title?`Video: ${j.video.title}`:"Recruiting Video",status:j.cta_clicked_at?"clicked":j.first_viewed_at?"viewed":"sent",sent_at:j.sent_at,opened_at:j.first_viewed_at,clicked_at:j.cta_clicked_at,view_count:j.view_count,share_token:j.share_token})}for(const j of y||[]){if(!j.sent_at)continue;const w=h.get(j.prospect_id);w&&_.push({id:`c-${j.id}`,kind:"campaign",prospect_id:j.prospect_id,prospect_name:`${w.first_name||""} ${w.last_name||""}`.trim()||"—",prospect_email:w.email,subject:j.subject||`Email #${j.email_number}`,status:j.status||"sent",sent_at:j.sent_at,opened_at:j.opened_at,clicked_at:j.clicked_at,error:j.error_message})}return _.sort((j,w)=>new Date(w.sent_at).getTime()-new Date(j.sent_at).getTime()),_}}),o=N.useMemo(()=>{const d=i||[];return{total:d.length,videos:d.filter(u=>u.kind==="video").length,campaigns:d.filter(u=>u.kind==="campaign").length,opened:d.filter(u=>u.opened_at).length,clicked:d.filter(u=>u.clicked_at).length}},[i]),c=N.useMemo(()=>(i||[]).filter(u=>{if(r!=="all"&&u.kind!==r)return!1;if(!t)return!0;const h=t.toLowerCase();return u.prospect_name.toLowerCase().includes(h)||(u.prospect_email||"").toLowerCase().includes(h)||u.subject.toLowerCase().includes(h)}),[i,t,r]);return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-5 gap-3",children:[{label:"Total Sent",value:o.total,icon:lr,color:"text-primary"},{label:"Video Emails",value:o.videos,icon:fr,color:"text-blue-500"},{label:"Campaign Emails",value:o.campaigns,icon:Gs,color:"text-violet-500"},{label:"Opened / Viewed",value:o.opened,icon:Sr,color:"text-amber-500"},{label:"Clicked",value:o.clicked,icon:oc,color:"text-emerald-500"}].map(d=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-3 flex items-center gap-2.5",children:[e.jsx("div",{className:`h-9 w-9 rounded-lg bg-muted flex items-center justify-center ${d.color}`,children:e.jsx(d.icon,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-xl font-bold leading-tight",children:d.value}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:d.label})]})]})},d.label))}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap",children:[e.jsx(Rt,{className:"text-lg",children:"Sent Emails"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Fr,{value:r,onValueChange:d=>a(d),children:e.jsxs(Rr,{className:"h-8",children:[e.jsx(Zt,{value:"all",className:"text-xs h-7",children:"All"}),e.jsx(Zt,{value:"video",className:"text-xs h-7",children:"Video"}),e.jsx(Zt,{value:"campaign",className:"text-xs h-7",children:"Campaign"})]})}),e.jsxs("div",{className:"relative w-56",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search recruit, subject...",value:t,onChange:d=>n(d.target.value),className:"pl-9 h-9"})]})]})]})}),e.jsx(Ee,{children:l?e.jsx("div",{className:"flex items-center justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):c.length===0?e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Gs,{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(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(fr,{className:"h-3 w-3"}),"Video"]}):e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(Gs,{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(Ue,{variant:"destructive",className:"gap-1",children:[e.jsx(Bi,{className:"h-3 w-3"}),d.status]}):d.clicked_at?e.jsxs(Ue,{className:"bg-emerald-500/15 text-emerald-700 border-emerald-200 gap-1",children:[e.jsx(oc,{className:"h-3 w-3"}),"Clicked"]}):d.opened_at?e.jsxs(Ue,{className:"bg-blue-500/15 text-blue-700 border-blue-200 gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"}),"Opened"]}):e.jsxs(Ue,{variant:"secondary",className:"gap-1",children:[e.jsx(lr,{className:"h-3 w-3"}),"Sent"]}),d.error&&e.jsx("p",{className:"text-[10px] text-destructive mt-0.5 max-w-[200px] truncate",title:d.error,children:d.error})]}),e.jsxs("td",{className:"px-3 py-2 text-xs text-muted-foreground whitespace-nowrap",children:[Ss(new Date(d.sent_at),"MMM d, yyyy"),e.jsx("div",{className:"text-[10px]",children:Ss(new Date(d.sent_at),"h:mm a")})]}),e.jsx("td",{className:"px-3 py-2 text-right",children:e.jsxs("div",{className:"flex items-center gap-2 justify-end text-xs text-muted-foreground",children:[d.kind==="video"&&d.view_count!=null&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"}),d.view_count]}),d.kind==="video"&&d.share_token&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7",onClick:()=>window.open(`/recruit-video/${d.share_token}`,"_blank"),title:"Open landing page",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})]})})]},d.id))})]})})})]})]})}function qen(){var l;const{managedBrokerages:s,selectedBrokerageId:t,setSelectedBrokerageId:n}=vs(),[r,a]=N.useState("board"),i=t||((l=s[0])==null?void 0:l.id)||"";return s.length===0?e.jsx(Cs,{title:"Recruiting",description:"Agent Recruiting Pipeline",children:e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ua,{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(Cs,{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(us,{value:i,onValueChange:n,children:[e.jsxs(ls,{className:"w-[280px]",children:[e.jsx(Ua,{className:"mr-2 h-4 w-4"}),e.jsx(hs,{placeholder:"Select brokerage"})]}),e.jsx(cs,{children:s.map(o=>e.jsx(Ze,{value:o.id,children:o.name},o.id))})]})]}),i?e.jsxs(Fr,{defaultValue:"pipeline",className:"space-y-4",children:[e.jsxs(Rr,{className:"flex-wrap h-auto gap-1",children:[e.jsx(Zt,{value:"pipeline",children:"Pipeline"}),e.jsxs(Zt,{value:"contacts",children:[e.jsx(An,{className:"h-3.5 w-3.5 mr-1"}),"Contacts"]}),e.jsxs(Zt,{value:"video-outreach",children:[e.jsx(fr,{className:"h-3.5 w-3.5 mr-1"}),"Video Outreach"]}),e.jsx(Zt,{value:"follow-ups",children:"Follow-ups"}),e.jsx(Zt,{value:"referrals",children:"Referrals"}),e.jsx(Zt,{value:"interest",children:"Interest Form"}),e.jsx(Zt,{value:"landing-page",children:"Landing Page"}),e.jsx(Zt,{value:"goals",children:"Goals"}),e.jsx(Zt,{value:"metrics",children:"Metrics"}),e.jsx(Zt,{value:"templates",children:"Email Templates"}),e.jsxs(Zt,{value:"campaigns",children:[e.jsx(Gs,{className:"h-3.5 w-3.5 mr-1"}),"Campaigns"]}),e.jsxs(Zt,{value:"drip-assignments",children:[e.jsx(lr,{className:"h-3.5 w-3.5 mr-1"}),"Drip Assignments"]}),e.jsxs(Zt,{value:"sent-emails",children:[e.jsx(H2,{className:"h-3.5 w-3.5 mr-1"}),"Sent Emails"]}),e.jsx(Zt,{value:"activity",children:"Recruiter Activity"}),e.jsxs(Zt,{value:"email-settings",children:[e.jsx(Ko,{className:"h-3.5 w-3.5 mr-1"}),"Email Settings"]}),e.jsxs(Zt,{value:"pipeline-stages",children:[e.jsx(e4,{className:"h-3.5 w-3.5 mr-1"}),"Pipeline Stages"]})]}),e.jsxs(is,{value:"pipeline",children:[e.jsx("div",{className:"flex justify-end mb-3",children:e.jsxs("div",{className:"flex items-center rounded-md border bg-muted p-0.5",children:[e.jsxs(B,{variant:r==="board"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("board"),children:[e.jsx(ff,{className:"h-3.5 w-3.5"})," Board"]}),e.jsxs(B,{variant:r==="table"?"default":"ghost",size:"sm",className:"h-7 px-2.5 gap-1.5",onClick:()=>a("table"),children:[e.jsx(mL,{className:"h-3.5 w-3.5"})," Table"]})]})}),r==="board"?e.jsx(I2t,{brokerageId:i}):e.jsx(Lge,{brokerageId:i})]}),e.jsx(is,{value:"contacts",children:e.jsx(Lge,{brokerageId:i})}),e.jsx(is,{value:"video-outreach",children:e.jsx($2t,{brokerageId:i})}),e.jsx(is,{value:"follow-ups",children:e.jsx(F2t,{brokerageId:i})}),e.jsx(is,{value:"referrals",children:e.jsx(R2t,{brokerageId:i})}),e.jsx(is,{value:"interest",children:e.jsx(O2t,{brokerageId:i})}),e.jsx(is,{value:"landing-page",children:e.jsx(z2t,{brokerageId:i})}),e.jsx(is,{value:"goals",children:e.jsx(U2t,{brokerageId:i})}),e.jsx(is,{value:"metrics",children:e.jsx(P2t,{brokerageId:i})}),e.jsx(is,{value:"templates",children:e.jsx(L2t,{brokerageId:i})}),e.jsx(is,{value:"campaigns",children:e.jsx(H2t,{brokerageId:i})}),e.jsx(is,{value:"drip-assignments",children:e.jsx(G2t,{brokerageId:i})}),e.jsx(is,{value:"sent-emails",children:e.jsx(Uen,{brokerageId:i})}),e.jsx(is,{value:"activity",children:e.jsx(D2t,{brokerageId:i})}),e.jsx(is,{value:"email-settings",children:e.jsxs("div",{className:"max-w-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"Email Settings"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Configure sender identity, merge fields, and brokerage location for recruiting emails."}),e.jsx(i8e,{brokerageId:i})]})}),e.jsx(is,{value:"pipeline-stages",children:e.jsx("div",{className:"max-w-2xl",children:e.jsx(W2t,{brokerageId:i})})})]}):e.jsxs("div",{className:"text-center py-12 text-muted-foreground",children:[e.jsx(Ua,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{children:"No brokerages found."})]})]})})}function Ven(){const[s,t]=N.useState(""),{data:n,isLoading:r}=dt({queryKey:["admin-brokerage-content-activity"],queryFn:async()=>{const{data:o}=await q.from("brokerages").select("id, name");if(!o)return[];const{data:c}=await q.from("brokerage_content").select("id, brokerage_id, content_type, created_at"),{data:d}=await q.from("brokerage_content_categories").select("id, brokerage_id"),u=c||[],h=d||[],p=o.map(f=>{const y=u.filter(j=>j.brokerage_id===f.id),_=h.filter(j=>j.brokerage_id===f.id),v=y.length>0?y.reduce((j,w)=>w.created_at>j?w.created_at:j,y[0].created_at):null;return{brokerage_id:f.id,brokerage_name:f.name,total_items:y.length,videos:y.filter(j=>j.content_type==="video").length,pdfs:y.filter(j=>j.content_type==="pdf").length,links:y.filter(j=>j.content_type==="link"||j.content_type==="canva_link").length,events:y.filter(j=>j.content_type==="event").length,graphics:y.filter(j=>j.content_type==="graphic").length,latest_item_date:v,categories:_.length}});return p.sort((f,y)=>y.total_items-f.total_items),p}}),a=(n||[]).filter(o=>o.brokerage_name.toLowerCase().includes(s.toLowerCase())),i=a.reduce((o,c)=>o+c.total_items,0),l=a.filter(o=>o.total_items>0).length;return e.jsx(Cs,{title:"Brokerage Content Activity",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Bd,{title:"Brokerage Content Activity",description:"See which brokerages are creating custom content for their agents"}),e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-3 gap-4",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Active Brokerages"})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-2xl font-bold",children:l}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"with content uploaded"})]})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Content Items"})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-2xl font-bold",children:i}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"across all brokerages"})]})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-2",children:e.jsx(Rt,{className:"text-sm font-medium text-muted-foreground",children:"Total Brokerages"})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"text-2xl font-bold",children:a.length}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"registered"})]})]})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search brokerages...",value:s,onChange:o=>t(o.target.value),className:"pl-9"})]}),e.jsx(fe,{children:e.jsx(Ee,{className:"p-0",children:e.jsxs(la,{children:[e.jsx(ca,{children:e.jsxs(Hs,{children:[e.jsx(Tt,{children:"Brokerage"}),e.jsx(Tt,{className:"text-center",children:"Total"}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(fr,{className:"h-3 w-3"})," Videos"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(br,{className:"h-3 w-3"})," PDFs"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Tl,{className:"h-3 w-3"})," Links"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Cl,{className:"h-3 w-3"})," Events"]})}),e.jsx(Tt,{className:"text-center",children:e.jsxs("div",{className:"flex items-center justify-center gap-1",children:[e.jsx(Xo,{className:"h-3 w-3"})," Graphics"]})}),e.jsx(Tt,{className:"text-center",children:"Categories"}),e.jsx(Tt,{children:"Last Upload"})]})}),e.jsx(da,{children:r?e.jsx(Hs,{children:e.jsx(ht,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"Loading..."})}):a.length===0?e.jsx(Hs,{children:e.jsx(ht,{colSpan:9,className:"text-center py-8 text-muted-foreground",children:"No brokerages found"})}):a.map(o=>e.jsxs(Hs,{className:o.total_items===0?"opacity-50":"",children:[e.jsx(ht,{children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ua,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"font-medium",children:o.brokerage_name})]})}),e.jsx(ht,{className:"text-center",children:o.total_items>0?e.jsx(Ue,{variant:"secondary",className:"font-bold",children:o.total_items}):e.jsx("span",{className:"text-muted-foreground",children:"0"})}),e.jsx(ht,{className:"text-center",children:o.videos||"–"}),e.jsx(ht,{className:"text-center",children:o.pdfs||"–"}),e.jsx(ht,{className:"text-center",children:o.links||"–"}),e.jsx(ht,{className:"text-center",children:o.events||"–"}),e.jsx(ht,{className:"text-center",children:o.graphics||"–"}),e.jsx(ht,{className:"text-center",children:o.categories||"–"}),e.jsx(ht,{children:o.latest_item_date?e.jsx("span",{className:"text-sm text-muted-foreground",children:Ss(new Date(o.latest_item_date),"MMM d, yyyy")}):e.jsx("span",{className:"text-muted-foreground",children:"–"})})]},o.brokerage_id))})]})})})]})})}const Hen=[{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:"📉"}],cXe=[{value:"instagram-square",label:"Instagram Post",dimensions:"1080×1080",icon:e.jsx(ou,{className:"h-4 w-4"})},{value:"instagram-story",label:"Instagram Story",dimensions:"1080×1920",icon:e.jsx(ou,{className:"h-4 w-4"})},{value:"facebook-post",label:"Facebook Post",dimensions:"1200×630",icon:e.jsx(Mh,{className:"h-4 w-4"})}],Gen=[{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:"📰"}],dXe=s=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(s),uXe={"luxury-dark":bIe,"modern-clean":_Ie,"bold-colorful":wIe,editorial:jIe};function Wen(){const[s,t]=N.useState(""),[n,r]=N.useState("address"),[a,i]=N.useState(!1),[l,o]=N.useState([]),[c,d]=N.useState(null),[u,h]=N.useState(0),[p,f]=N.useState("just-listed"),[y,_]=N.useState(["instagram-square"]),[v,j]=N.useState("luxury-dark"),[w,S]=N.useState(!1),[A,E]=N.useState(""),[O,D]=N.useState(""),[I,F]=N.useState(""),[z,H]=N.useState(!1),[Z,Y]=N.useState(!1),[W,ee]=N.useState([]),[se,oe]=N.useState("search"),he=N.useRef({});N.useEffect(()=>{(async()=>{const{data:{user:Pe}}=await q.auth.getUser();if(!Pe)return;const{data:Re}=await q.from("profiles").select("name, avatar_url, brokerages(name)").eq("id",Pe.id).single();if(Re){E(Re.name||""),F(Re.avatar_url||"");const Ae=Re.brokerages;D((Ae==null?void 0:Ae.name)||"")}})()},[]);const ce=async()=>{var Me;if(s.trim()){i(!0),o([]);try{const{data:Pe,error:Re}=await q.functions.invoke("repliers-mls-search",{body:{searchType:n,query:s.trim()}});if(Re)throw Re;if(Pe.error)throw new Error(Pe.error);o(Pe.listings||[]),((Me=Pe.listings)==null?void 0:Me.length)===0&&ae.info("No listings found. Try a different search.")}catch(Pe){ae.error(Pe.message||"Search failed")}finally{i(!1)}}},me=Me=>{var Pe;d(Me),h(0),oe("customize"),Me.soldDate||(Pe=Me.status)!=null&&Pe.toLowerCase().includes("sold")?f("just-sold"):f("just-listed")},le=Me=>{_(Pe=>Pe.includes(Me)?Pe.filter(Re=>Re!==Me):[...Pe,Me])},ve=N.useCallback(async()=>{if(!(!c||y.length===0)){H(!0),ee([]),oe("generate");try{await new Promise(Pe=>setTimeout(Pe,500));const Me=[];for(const Pe of y){const Re=`${v}-${Pe}`,Ae=he.current[Re];if(!Ae)continue;const Be=ES[Pe],we=await vIe(Ae,{width:Be.width,height:Be.height,pixelRatio:1,cacheBust:!0,style:{transform:"none",transformOrigin:"top left"}});Me.push({format:Pe,imageUrl:we})}ee(Me),ae.success(`Generated ${Me.length} social post${Me.length>1?"s":""}!`)}catch(Me){ae.error(Me.message||"Generation failed")}finally{H(!1)}}},[c,y,v,u,w,A,O,I,p]),ge=async()=>{if(!(!c||y.length===0)){H(!0),ee([]),oe("generate");try{const Me={...c,photos:c.photos.length>0?[c.photos[u]]:[]},Pe=[];for(const Re of y){const{data:Ae,error:Be}=await q.functions.invoke("generate-listing-social-post",{body:{listing:Me,postType:p,format:Re,branding:w?{enabled:!0,agentName:A,brokerage:O}:{enabled:!1}}});if(Be)throw Be;if(Ae.error)throw new Error(Ae.error);Pe.push({format:Re,imageUrl:Ae.imageUrl})}ee(Pe),ae.success(`Generated ${Pe.length} AI post${Pe.length>1?"s":""}!`)}catch(Me){ae.error(Me.message||"AI generation failed")}finally{H(!1)}}},Te=()=>Z?ge():ve(),Ie=(Me,Pe)=>{var Ae;const Re=document.createElement("a");Re.href=Me,Re.download=`${((Ae=c==null?void 0:c.address)==null?void 0:Ae.replace(/\s+/g,"-"))||"listing"}-${p}-${Pe}.png`,document.body.appendChild(Re),Re.click(),document.body.removeChild(Re)},Ce=c?{listing:c,postType:p,format:"instagram-square",branding:w?{enabled:!0,agentName:A,brokerage:O,agentPhotoUrl:I||void 0}:{enabled:!1},selectedPhotoIndex:u}:null;return e.jsx(Cs,{children:e.jsxs("div",{className:"space-y-6 p-4 md:p-8",children:[e.jsx(Bd,{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 ${se==="search"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground hover:text-foreground"}`,children:[e.jsx(gr,{className:"h-3.5 w-3.5"})," 1. Find Listing"]}),e.jsx(ga,{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 ${se==="customize"?"bg-primary text-primary-foreground":c?"bg-muted text-muted-foreground hover:text-foreground":"bg-muted text-muted-foreground/50 cursor-not-allowed"}`,children:[e.jsx(un,{className:"h-3.5 w-3.5"})," 2. Customize"]}),e.jsx(ga,{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 ${se==="generate"?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground/50"}`,children:[e.jsx(Xo,{className:"h-3.5 w-3.5"})," 3. Generate"]})]}),se==="search"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(gr,{className:"h-5 w-5 text-primary"})," Search MLS Listings ",e.jsx(Omt,{})]}),e.jsx(Vn,{children:"Find a listing by MLS number or property address using Repliers.io"})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx(Fr,{value:n,onValueChange:Me=>r(Me),children:e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"address",children:[e.jsx(ka,{className:"h-4 w-4 mr-1.5"})," Address"]}),e.jsxs(Zt,{value:"mls",children:[e.jsx(oh,{className:"h-4 w-4 mr-1.5"})," MLS #"]})]})}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:s,onChange:Me=>t(Me.target.value),placeholder:n==="mls"?"Enter MLS number...":"Enter property address...",className:"flex-1",onKeyDown:Me=>Me.key==="Enter"&&ce()}),e.jsxs(B,{onClick:ce,disabled:a||!s.trim(),children:[a?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(gr,{className:"h-4 w-4"})," Search"]})]})]})]}),l.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("h3",{className:"text-sm font-medium text-muted-foreground",children:[l.length," listing",l.length!==1?"s":""," found"]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:l.map((Me,Pe)=>{var Re;return e.jsx(fe,{className:"cursor-pointer hover:border-primary/50 hover:shadow-md transition-all group",onClick:()=>me(Me),children:e.jsx(Ee,{className:"p-0",children:e.jsxs("div",{className:"flex",children:[e.jsx("div",{className:"w-32 h-28 flex-shrink-0 bg-muted rounded-l-lg overflow-hidden",children:(Re=Me.photos)!=null&&Re[0]?e.jsx("img",{src:Me.photos[0],alt:Me.address,className:"w-full h-full object-cover group-hover:scale-105 transition-transform"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(Or,{className:"h-8 w-8 text-muted-foreground/40"})})}),e.jsxs("div",{className:"flex-1 p-3 min-w-0",children:[e.jsx("p",{className:"font-bold text-foreground",children:dXe(Me.price)}),e.jsx("p",{className:"text-sm text-muted-foreground truncate",children:Me.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Me.city,", ",Me.state," ",Me.zip]}),e.jsxs("div",{className:"flex items-center gap-3 mt-1.5 text-xs text-muted-foreground",children:[Me.bedrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(U2,{className:"h-3 w-3"})," ",Me.bedrooms]}),Me.bathrooms>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(kp,{className:"h-3 w-3"})," ",Me.bathrooms]}),Me.sqft>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(AA,{className:"h-3 w-3"})," ",Me.sqft.toLocaleString()]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:Me.mlsNumber}),e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:Me.status})]})]})]})})},Me.mlsNumber||Pe)})})]})]}),se==="customize"&&c&&e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"lg:col-span-1",children:[e.jsx(It,{className:"pb-3",children:e.jsx(Rt,{className:"text-base",children:"Selected Listing"})}),e.jsxs(Ee,{className:"space-y-3",children:[c.photos.length>0&&e.jsxs("div",{className:"relative",children:[e.jsx("div",{className:"aspect-[4/3] rounded-lg overflow-hidden bg-muted",children:e.jsx("img",{src:c.photos[u],alt:"Listing photo",className:"w-full h-full object-cover"})}),c.photos.length>1&&e.jsxs("div",{className:"flex items-center justify-between mt-2",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(Me=>Math.max(0,Me-1)),disabled:u===0,children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u+1," of ",c.photos.length]}),e.jsx(B,{variant:"outline",size:"icon",className:"h-7 w-7",onClick:()=>h(Me=>Math.min(c.photos.length-1,Me+1)),disabled:u===c.photos.length-1,children:e.jsx(ga,{className:"h-4 w-4"})})]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-lg",children:dXe(c.price)}),e.jsx("p",{className:"text-sm text-muted-foreground",children:c.address}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[c.city,", ",c.state," ",c.zip]})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-2 text-center",children:[c.bedrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bedrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Beds"})]}),c.bathrooms>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.bathrooms}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Baths"})]}),c.sqft>0&&e.jsxs("div",{className:"bg-muted/50 rounded-lg p-2",children:[e.jsx("p",{className:"text-sm font-semibold",children:c.sqft.toLocaleString()}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:"Sq Ft"})]})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{oe("search"),d(null)},children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Choose Different Listing"]})]})]}),e.jsxs(fe,{className:"lg:col-span-2",children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"})," Customize Your Post"]}),e.jsx(Vn,{children:"Choose template, post type, format, and branding"})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between p-3 rounded-lg border bg-muted/30",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:Z?"AI Custom Generation":"Template-Based (Free)"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:Z?"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(jn,{checked:Z,onCheckedChange:Y}),Z&&e.jsx(Im,{className:"h-4 w-4 text-purple-500"})]})]}),!Z&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(pl,{className:"h-4 w-4"})," Template Style"]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Gen.map(Me=>e.jsxs("button",{onClick:()=>j(Me.value),className:`flex flex-col items-center gap-1 px-3 py-3 rounded-lg border-2 transition-all text-center ${v===Me.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-2xl",children:Me.preview}),e.jsx("span",{className:"text-sm font-medium",children:Me.label}),e.jsx("span",{className:"text-[10px] text-muted-foreground leading-tight",children:Me.description})]},Me.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Post Type"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-2",children:Hen.map(Me=>e.jsxs("button",{onClick:()=>f(Me.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm font-medium ${p===Me.value?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("span",{className:"text-lg",children:Me.icon})," ",Me.label]},Me.value))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Output Formats"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-2",children:cXe.map(Me=>e.jsxs("button",{onClick:()=>le(Me.value),className:`flex items-center gap-2 px-3 py-2.5 rounded-lg border-2 transition-all text-sm ${y.includes(Me.value)?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[Me.icon,e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-medium",children:Me.label}),e.jsx("p",{className:"text-[10px] text-muted-foreground",children:Me.dimensions})]})]},Me.value))})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(ne,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(Wi,{className:"h-4 w-4"})," Agent Branding"]}),e.jsx(jn,{checked:w,onCheckedChange:S})]}),w&&e.jsxs("div",{className:"space-y-3 pl-6 border-l-2 border-primary/20",children:[I&&e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("img",{src:I,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(ne,{className:"text-xs text-muted-foreground",children:"Agent Name"}),e.jsx(ye,{value:A,onChange:Me=>E(Me.target.value),placeholder:"Jane Smith"})]}),e.jsxs("div",{className:"space-y-1",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Brokerage (optional)"}),e.jsx(ye,{value:O,onChange:Me=>D(Me.target.value),placeholder:"XYZ Realty"})]})]})]})]}),!Z&&Ce&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{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*(ES[y[0]||"instagram-square"].height/ES[y[0]||"instagram-square"].width)},children:(()=>{const Me=uXe[v],Pe=y[0]||"instagram-square";return e.jsx(Me,{...Ce,format:Pe})})()})})]}),e.jsx(B,{onClick:Te,disabled:y.length===0||z,size:"lg",className:"w-full gap-2",children:z?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-5 w-5 animate-spin"})," Generating ",y.length," post",y.length>1?"s":"","..."]}):e.jsxs(e.Fragment,{children:[Z?e.jsx(Im,{className:"h-5 w-5"}):e.jsx(un,{className:"h-5 w-5"}),"Generate ",y.length," Social Post",y.length>1?"s":"",Z&&e.jsx(Ue,{variant:"outline",className:"ml-2 text-[10px]",children:"Uses Credits"})]})})]})]})]}),se==="generate"&&e.jsxs("div",{className:"space-y-4",children:[z&&e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(rs,{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:Z?"AI is creating your unique designs":"Rendering templates to high-res images"})]})}),W.length>0&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("h3",{className:"text-lg font-semibold",children:"Generated Posts"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>oe("customize"),children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Regenerate"]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:W.map((Me,Pe)=>{const Re=cXe.find(Ae=>Ae.value===Me.format);return e.jsxs(fe,{className:"overflow-hidden",children:[e.jsx("div",{className:"bg-muted/30 p-1",children:e.jsx("img",{src:Me.imageUrl,alt:`${Me.format} social post`,className:"w-full rounded"})}),e.jsxs(Ee,{className:"p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-1.5",children:[Re==null?void 0:Re.icon,e.jsx("span",{className:"text-sm font-medium",children:Re==null?void 0:Re.label})]}),e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:Re==null?void 0:Re.dimensions})]}),e.jsxs(B,{size:"sm",className:"w-full gap-1.5",onClick:()=>Ie(Me.imageUrl,Me.format),children:[e.jsx(Ia,{className:"h-3.5 w-3.5"})," Download"]})]})]},Pe)})})]})]}),se==="generate"&&!Z&&c&&Ce&&e.jsx("div",{style:{position:"absolute",left:"-9999px",top:0},"aria-hidden":!0,children:y.map(Me=>{const Pe=uXe[v],Re=ES[Me];return e.jsx("div",{style:{width:Re.width,height:Re.height},children:e.jsx(Pe,{ref:Ae=>{he.current[`${v}-${Me}`]=Ae},...Ce,format:Me})},`${v}-${Me}`)})})]})})}function Ken(){return dt({queryKey:["lms-courses-admin"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(count), access:lms_course_access(*)").order("sort_order");if(t)throw t;return s}})}function Yen(s){return dt({queryKey:["lms-course-admin",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*)), access:lms_course_access(*)").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function Zen(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_courses").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function K2t(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_courses").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-courses-admin"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Qen(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("lms_courses").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["lms-courses"]})})}function Xen(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_modules").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function Jen(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("lms_modules").update({...n,updated_at:new Date().toISOString()}).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function etn(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("lms_modules").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function ttn(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.from("lms_module_resources").insert(t).select().single();if(r)throw r;return n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function stn(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("lms_module_resources").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-course"]}),s.invalidateQueries({queryKey:["lms-course-admin"]})}})}function ntn(){const s=Kt();return yt({mutationFn:async({courseId:t,accessRules:n})=>{const{error:r}=await q.from("lms_course_access").delete().eq("course_id",t);if(r)throw r;if(n.length>0){const a=n.map(l=>({...l,course_id:t})),{error:i}=await q.from("lms_course_access").insert(a);if(i)throw i}},onSuccess:()=>{s.invalidateQueries({queryKey:["lms-courses"]}),s.invalidateQueries({queryKey:["lms-course"]})}})}function rtn(){return dt({queryKey:["lms-courses-agent"],queryFn:async()=>{const{data:s,error:t}=await q.from("lms_courses").select("*, modules:lms_modules(id)").eq("is_published",!0).order("sort_order");if(t)throw t;return s}})}function atn(s){return dt({queryKey:["lms-course-agent",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("lms_courses").select("*, modules:lms_modules(*, resources:lms_module_resources(*))").eq("id",s).single();if(n)throw n;return t!=null&&t.modules&&(t.modules.sort((r,a)=>r.sort_order-a.sort_order),t.modules.forEach(r=>{r.resources&&r.resources.sort((a,i)=>a.sort_order-i.sort_order)})),t},enabled:!!s})}function Y2t(s){return dt({queryKey:["lms-progress",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("lms_progress").select("*").eq("course_id",s);if(n)throw n;return t},enabled:!!s})}function itn(){const s=Kt();return yt({mutationFn:async({courseId:t,moduleId:n,userId:r})=>{const{data:a,error:i}=await q.from("lms_progress").upsert({user_id:r,course_id:t,module_id:n,completed:!0,completed_at:new Date().toISOString()},{onConflict:"user_id,module_id"}).select().single();if(i)throw i;return a},onSuccess:()=>s.invalidateQueries({queryKey:["lms-progress"]})})}function otn(){const{user:s}=vs(),t=Ln(),{data:n,isLoading:r}=Ken(),a=Zen(),i=K2t(),l=Qen(),[o,c]=N.useState(!1),[d,u]=N.useState(""),[h,p]=N.useState(""),[f,y]=N.useState(!0),_=async()=>{if(!(!d.trim()||!s))try{const w=await a.mutateAsync({title:d.trim(),description:h.trim()||void 0,is_sequential:f,created_by:s.id});ae.success("Course created"),c(!1),u(""),p(""),y(!0),t(`/admin/lms/${w.id}`)}catch{ae.error("Failed to create course")}},v=async w=>{try{await i.mutateAsync({id:w.id,is_published:!w.is_published}),ae.success(w.is_published?"Course unpublished":"Course published")}catch{ae.error("Failed to update course")}},j=async w=>{if(confirm("Delete this course and all its modules? This cannot be undone."))try{await l.mutateAsync(w),ae.success("Course deleted")}catch{ae.error("Failed to delete")}};return e.jsxs(Cs,{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(yd,{className:"h-7 w-7 text-primary"}),"LevelUp U — Course Manager"]}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create and manage training courses for your agents"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>t("/admin/lms/stats"),children:[e.jsx(_o,{className:"h-4 w-4 mr-2"}),"Analytics"]}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New Course"]})]})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:[1,2,3].map(w=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(It,{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"})]})},w))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:n.map(w=>{var O,D;const S=((D=(O=w.modules)==null?void 0:O[0])==null?void 0:D.count)??0,A=w.access||[],E=A.length===0?"No access set":A.some(I=>I.access_type==="all")?"All agents":`${A.length} rule(s)`;return e.jsxs(fe,{className:"group hover:shadow-md transition-all hover:border-primary/50 cursor-pointer",onClick:()=>t(`/admin/lms/${w.id}`),children:[e.jsx(It,{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(Rt,{className:"text-base truncate",children:w.title}),w.description&&e.jsx(Vn,{className:"mt-1 line-clamp-2",children:w.description})]}),e.jsx(Ue,{variant:w.is_published?"default":"secondary",className:"ml-2 shrink-0",children:w.is_published?"Published":"Draft"})]})}),e.jsxs(Ee,{className:"pt-0",children:[e.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(rm,{className:"h-3.5 w-3.5"}),S," module",S!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[w.is_sequential?e.jsx(ub,{className:"h-3.5 w-3.5"}):e.jsx(DA,{className:"h-3.5 w-3.5"}),w.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(An,{className:"h-3.5 w-3.5"}),E]})]}),e.jsxs("div",{className:"flex items-center gap-2 mt-3 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsxs(B,{size:"sm",variant:"ghost",onClick:I=>{I.stopPropagation(),v(w)},children:[w.is_published?e.jsx(mf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1"}),w.is_published?"Unpublish":"Publish"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:I=>{I.stopPropagation(),j(w.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})}),e.jsx("div",{className:"flex-1"}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground"})]})]})]},w.id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(rm,{className:"h-12 w-12 text-muted-foreground/50 mb-4"}),e.jsx("h3",{className:"text-lg font-semibold text-foreground mb-1",children:"No courses yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mb-4",children:"Create your first training course to get started"}),e.jsxs(B,{onClick:()=>c(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create Course"]})]})})]}),e.jsx(_s,{open:o,onOpenChange:c,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create New Course"}),e.jsx(Jn,{children:"Set up a new training course for your agents"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Course Title"}),e.jsx(ye,{value:d,onChange:w=>u(w.target.value),placeholder:"e.g. LevelUp Onboarding"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{value:h,onChange:w=>p(w.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(jn,{checked:f,onCheckedChange:y})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:_,disabled:!d.trim()||a.isPending,children:a.isPending?"Creating...":"Create Course"})]})]})})]})}function ltn(){const{courseId:s}=bi(),t=Ln(),{data:n,isLoading:r}=Yen(s),a=K2t(),i=Xen(),l=Jen(),o=etn(),c=ttn(),d=stn(),u=ntn(),{data:h}=dt({queryKey:["all-brokerages"],queryFn:async()=>{const{data:tt}=await q.from("brokerages").select("id, name").order("name");return tt||[]}}),[p,f]=N.useState(null),[y,_]=N.useState(!1),[v,j]=N.useState({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),[w,S]=N.useState(null),[A,E]=N.useState({title:"",resource_type:"link",url:""}),[O,D]=N.useState(new Set),[I,F]=N.useState(null),[z,H]=N.useState(0),[Z,Y]=N.useState(!1),W=N.useRef(null),ee=N.useRef(null),[se,oe]=N.useState(!1),[he,ce]=N.useState(""),[me,le]=N.useState(""),[ve,ge]=N.useState(""),[Te,Ie]=N.useState(!1);if(r)return e.jsx(Cs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})});if(!n)return e.jsx(Cs,{title:"Course Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>t("/admin/lms"),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"})," Back to Courses"]})]})});const Ce=n.modules||[],Me=n.access||[],Pe=Me.some(tt=>tt.access_type==="all"),Re=Me.filter(tt=>tt.access_type==="brokerage").map(tt=>tt.brokerage_id),Ae=(h||[]).filter(tt=>tt.name.toLowerCase().includes(he.toLowerCase())),Be=tt=>{const at=new Set(O);at.has(tt)?at.delete(tt):at.add(tt),D(at)},we=async()=>{if(!I)return null;Y(!0),H(0);try{const{data:tt,error:at}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:I.name}});if(at)throw new Error(at.message);const{videoId:Ye,libraryId:ut}=tt,{data:_t,error:bt}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:Ye,libraryId:ut}});if(bt)throw new Error(bt.message);const $t=new XMLHttpRequest;return await new Promise((Yt,Ds)=>{$t.upload.onprogress=Ls=>{Ls.lengthComputable&&H(Math.round(Ls.loaded/Ls.total*100))},$t.onload=()=>$t.status>=200&&$t.status<300?Yt():Ds(new Error(`Upload failed: ${$t.status}`)),$t.onerror=()=>Ds(new Error("Upload failed")),$t.open("PUT",_t.uploadUrl),$t.setRequestHeader("AccessKey",_t.apiKey),$t.send(I)}),`https://iframe.mediadelivery.net/embed/${ut}/${Ye}`}catch(tt){return console.error("Bunny upload error:",tt),ae.error("Video upload failed"),null}finally{Y(!1),H(0)}},Je=async()=>{if(v.title.trim())try{let tt=v.video_url.trim()||void 0;if(I){const at=await we();if(!at)return;tt=at}await i.mutateAsync({course_id:n.id,title:v.title.trim(),description:v.description.trim()||void 0,video_url:tt,text_content:v.text_content.trim()||void 0,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):void 0,sort_order:Ce.length}),ae.success("Module added"),_(!1),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""}),F(null)}catch{ae.error("Failed to add module")}},ke=async()=>{if(p)try{let tt=v.video_url.trim()||null;if(I){const at=await we();if(!at)return;tt=at}await l.mutateAsync({id:p.id,title:v.title.trim(),description:v.description.trim()||null,video_url:tt,text_content:v.text_content.trim()||null,duration_minutes:v.duration_minutes?parseInt(v.duration_minutes):null}),ae.success("Module updated"),f(null),F(null)}catch{ae.error("Failed to update")}},it=async tt=>{if(confirm("Delete this module?"))try{await o.mutateAsync(tt),ae.success("Module deleted")}catch{ae.error("Failed to delete")}},je=async tt=>{if(A.title.trim())try{await c.mutateAsync({module_id:tt,title:A.title.trim(),resource_type:A.resource_type,url:A.url.trim()||void 0}),ae.success("Resource added"),S(null),E({title:"",resource_type:"link",url:""})}catch{ae.error("Failed to add resource")}},He=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[{access_type:"all"}]}),ae.success("Access updated: All brokerages / all agents")}catch{ae.error("Failed to update access")}},$e=async tt=>{const at=Me.filter(bt=>bt.access_type==="brokerage").map(bt=>bt.brokerage_id),Ye=at.includes(tt);let ut;Ye?ut=at.filter(bt=>bt!==tt):ut=[...at,tt];const _t=ut.map(bt=>({access_type:"brokerage",brokerage_id:bt}));try{await u.mutateAsync({courseId:n.id,accessRules:_t}),ae.success(Ye?"Brokerage removed":"Brokerage added")}catch{ae.error("Failed to update access")}},Ke=async()=>{try{await u.mutateAsync({courseId:n.id,accessRules:[]}),ae.success("Access cleared")}catch{ae.error("Failed")}},Ge=async(tt,at)=>{const Ye=at==="up"?tt-1:tt+1;if(!(Ye<0||Ye>=Ce.length))try{await Promise.all([l.mutateAsync({id:Ce[tt].id,sort_order:Ye}),l.mutateAsync({id:Ce[Ye].id,sort_order:tt})])}catch{ae.error("Failed to reorder")}},rt=async()=>{try{await a.mutateAsync({id:n.id,title:me,description:ve||null}),ae.success("Course updated"),Ie(!1)}catch{ae.error("Failed to update")}};return e.jsxs(Cs,{title:n.title,children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/admin/lms"),children:e.jsx(qr,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:n.title}),e.jsx(Ue,{variant:n.is_published?"default":"secondary",children:n.is_published?"Published":"Draft"})]}),n.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:n.description}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[n.is_sequential?e.jsx(ub,{className:"h-3.5 w-3.5"}):e.jsx(DA,{className:"h-3.5 w-3.5"}),n.is_sequential?"Sequential":"Free order"]}),e.jsxs("span",{children:[Ce.length," module",Ce.length!==1?"s":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{le(n.title),ge(n.description||""),Ie(!0)},children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1"})," Edit"]}),e.jsxs(B,{variant:n.is_published?"secondary":"default",size:"sm",onClick:()=>a.mutateAsync({id:n.id,is_published:!n.is_published}).then(()=>ae.success(n.is_published?"Unpublished":"Published")),children:[n.is_published?e.jsx(mf,{className:"h-3.5 w-3.5 mr-1"}):e.jsx(Sr,{className:"h-3.5 w-3.5 mr-1"}),n.is_published?"Unpublish":"Publish"]})]})]}),e.jsxs(Fr,{defaultValue:"modules",className:"w-full",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"modules",children:"Modules"}),e.jsx(Zt,{value:"access",children:"Access & Permissions"}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(is,{value:"modules",className:"mt-6 space-y-4",children:[Ce.map((tt,at)=>e.jsxs(fe,{className:"overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-4 cursor-pointer hover:bg-muted/50 transition-colors",onClick:()=>Be(tt.id),children:[e.jsx("span",{className:"flex items-center gap-1 text-muted-foreground",children:e.jsxs("div",{className:"flex flex-col",children:[e.jsx("button",{onClick:Ye=>{Ye.stopPropagation(),Ge(at,"up")},disabled:at===0,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(ex,{className:"h-3.5 w-3.5"})}),e.jsx("button",{onClick:Ye=>{Ye.stopPropagation(),Ge(at,"down")},disabled:at===Ce.length-1,className:"hover:text-foreground disabled:opacity-30",children:e.jsx(ao,{className:"h-3.5 w-3.5"})})]})}),e.jsx(Ue,{variant:"outline",className:"shrink-0 font-mono text-xs",children:at+1}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm truncate",children:tt.title}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground mt-0.5",children:[tt.video_url&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(fr,{className:"h-3 w-3"})," Video"]}),tt.text_content&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(br,{className:"h-3 w-3"})," Text"]}),tt.duration_minutes&&e.jsxs("span",{children:[tt.duration_minutes," min"]}),tt.resources&&tt.resources.length>0&&e.jsxs("span",{className:"flex items-center gap-0.5",children:[e.jsx(Tl,{className:"h-3 w-3"})," ",tt.resources.length," resource(s)"]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{size:"sm",variant:"ghost",onClick:Ye=>{var ut;Ye.stopPropagation(),f(tt),j({title:tt.title,description:tt.description||"",video_url:tt.video_url||"",text_content:tt.text_content||"",duration_minutes:((ut=tt.duration_minutes)==null?void 0:ut.toString())||""})},children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-destructive",onClick:Ye=>{Ye.stopPropagation(),it(tt.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),O.has(tt.id)&&e.jsxs("div",{className:"border-t bg-muted/30 p-4 space-y-3",children:[tt.description&&e.jsx("p",{className:"text-sm text-muted-foreground",children:tt.description}),tt.video_url&&e.jsxs("div",{className:"text-xs",children:[e.jsx("span",{className:"text-muted-foreground",children:"Video: "}),e.jsx("a",{href:tt.video_url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline break-all",children:tt.video_url})]}),tt.text_content&&e.jsx("div",{className:"text-sm bg-background rounded-md p-3 border max-h-40 overflow-auto whitespace-pre-wrap",children:tt.text_content}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Resources"}),e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:()=>{S(tt.id),E({title:"",resource_type:"link",url:""})},children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add Resource"]})]}),tt.resources&&tt.resources.length>0?e.jsx("div",{className:"space-y-1",children:tt.resources.map(Ye=>e.jsxs("div",{className:"flex items-center gap-2 text-sm bg-background rounded p-2 border",children:[e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:Ye.resource_type}),e.jsx("span",{className:"flex-1 truncate",children:Ye.title}),Ye.url&&e.jsx("a",{href:Ye.url,target:"_blank",rel:"noreferrer",className:"text-primary hover:underline text-xs",children:"Open"}),e.jsx(B,{size:"sm",variant:"ghost",className:"h-6 w-6 p-0 text-destructive",onClick:()=>d.mutateAsync(Ye.id),children:e.jsx($n,{className:"h-3 w-3"})})]},Ye.id))}):e.jsx("p",{className:"text-xs text-muted-foreground",children:"No resources yet"})]})]})]},tt.id)),e.jsxs(B,{variant:"outline",className:"w-full border-dashed",onClick:()=>{_(!0),j({title:"",description:"",video_url:"",text_content:"",duration_minutes:""})},children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Add Module"]})]}),e.jsx(is,{value:"access",className:"mt-6 space-y-4",children:e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Who can access this course?"})}),e.jsxs(Ee,{className:"space-y-5",children:[e.jsxs("div",{className:Mt("flex items-center gap-3 p-4 rounded-xl border-2 cursor-pointer transition-all",Pe?"border-primary bg-primary/5":"border-muted hover:border-muted-foreground/30"),onClick:He,children:[e.jsx("div",{className:Mt("h-10 w-10 rounded-full flex items-center justify-center shrink-0",Pe?"bg-primary/15 text-primary":"bg-muted text-muted-foreground"),children:e.jsx(lc,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"text-sm font-semibold",children:"All Brokerages / All Agents"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Every agent on the platform can access this course"})]}),e.jsx(jn,{checked:Pe,onCheckedChange:He})]}),!Pe&&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:Re.length===0?"No brokerages selected — agents won't see this course":`${Re.length} brokerage${Re.length!==1?"s":""} selected`})]}),Re.length>0&&e.jsx(B,{size:"sm",variant:"ghost",className:"text-xs text-muted-foreground",onClick:Ke,children:"Clear all"})]}),e.jsx(ye,{placeholder:"Search brokerages...",value:he,onChange:tt=>ce(tt.target.value),className:"h-9"}),e.jsx("div",{className:"border rounded-lg divide-y max-h-[360px] overflow-auto",children:Ae.length===0?e.jsx("div",{className:"p-4 text-center text-sm text-muted-foreground",children:"No brokerages found"}):Ae.map(tt=>{const at=Re.includes(tt.id);return e.jsxs("div",{className:Mt("flex items-center gap-3 px-3 py-2.5 cursor-pointer transition-colors",at?"bg-primary/5":"hover:bg-muted/50"),onClick:()=>$e(tt.id),children:[e.jsx("div",{className:Mt("h-5 w-5 rounded border-2 flex items-center justify-center shrink-0 transition-colors",at?"bg-primary border-primary":"border-muted-foreground/30"),children:at&&e.jsx("svg",{className:"h-3 w-3 text-primary-foreground",fill:"none",viewBox:"0 0 24 24",stroke:"currentColor",strokeWidth:3,children:e.jsx("path",{strokeLinecap:"round",strokeLinejoin:"round",d:"M5 13l4 4L19 7"})})}),e.jsx(Ua,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("span",{className:"text-sm flex-1 truncate",children:tt.name}),at&&e.jsx(Ue,{variant:"secondary",className:"text-[10px] shrink-0",children:"Active"})]},tt.id)})})]})]})]})}),e.jsxs(is,{value:"settings",className:"mt-6 space-y-4",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Course Thumbnail"})}),e.jsx(Ee,{children:e.jsxs("div",{className:"flex items-start gap-6",children:[n.thumbnail_url?e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:n.thumbnail_url,alt:"Course thumbnail",className:"w-48 h-28 object-cover rounded-lg border"}),e.jsx("button",{onClick:()=>a.mutateAsync({id:n.id,thumbnail_url:null}).then(()=>ae.success("Thumbnail removed")),className:"absolute -top-2 -right-2 bg-destructive text-destructive-foreground rounded-full p-1 opacity-0 group-hover:opacity-100 transition-opacity",children:e.jsx($n,{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(ty,{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:ee,type:"file",accept:"image/*",className:"hidden",onChange:async tt=>{var Ye;const at=(Ye=tt.target.files)==null?void 0:Ye[0];if(!(!at||!n)){oe(!0);try{const ut=at.name.split(".").pop(),_t=`${n.id}/thumbnail.${ut}`,{error:bt}=await q.storage.from("lms-thumbnails").upload(_t,at,{upsert:!0});if(bt)throw bt;const{data:$t}=q.storage.from("lms-thumbnails").getPublicUrl(_t),Yt=`${$t.publicUrl}?t=${Date.now()}`;await a.mutateAsync({id:n.id,thumbnail_url:Yt}),ae.success("Thumbnail uploaded")}catch{ae.error("Failed to upload thumbnail")}finally{oe(!1),ee.current&&(ee.current.value="")}}}}),e.jsxs(B,{variant:"outline",size:"sm",disabled:se,onClick:()=>{var tt;return(tt=ee.current)==null?void 0:tt.click()},children:[se?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(_a,{className:"h-4 w-4 mr-2"}),se?"Uploading...":"Upload Thumbnail"]})]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Course Settings"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Sequential Learning"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Agents must complete modules in order before advancing"})]}),e.jsx(jn,{checked:n.is_sequential,onCheckedChange:tt=>a.mutateAsync({id:n.id,is_sequential:tt}).then(()=>ae.success("Updated"))})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this course visible to agents with access"})]}),e.jsx(jn,{checked:n.is_published,onCheckedChange:tt=>a.mutateAsync({id:n.id,is_published:tt}).then(()=>ae.success("Updated"))})]})]})]})]})]})]}),e.jsx(_s,{open:y||!!p,onOpenChange:tt=>{tt||(_(!1),f(null))},children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(ws,{children:p?"Edit Module":"Add Module"}),e.jsx(Jn,{children:"Configure the module content"})]}),e.jsxs("div",{className:"space-y-4 max-h-[60vh] overflow-auto",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:v.title,onChange:tt=>j(at=>({...at,title:tt.target.value})),placeholder:"Module title"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{value:v.description,onChange:tt=>j(at=>({...at,description:tt.target.value})),placeholder:"Brief description",rows:2})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Video"}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:Mt("border-2 border-dashed rounded-lg p-4 text-center cursor-pointer transition-colors hover:border-primary/50",I?"border-primary bg-primary/5":"border-muted-foreground/25"),onClick:()=>{var tt;return(tt=W.current)==null?void 0:tt.click()},children:[e.jsx("input",{ref:W,type:"file",accept:"video/*",className:"hidden",onChange:tt=>{var Ye;const at=(Ye=tt.target.files)==null?void 0:Ye[0];at&&(F(at),j(ut=>({...ut,video_url:""})))}}),I?e.jsxs("div",{className:"flex items-center justify-center gap-2 text-sm",children:[e.jsx(fr,{className:"h-4 w-4 text-primary"}),e.jsx("span",{className:"font-medium text-primary",children:I.name}),e.jsx(B,{type:"button",size:"sm",variant:"ghost",className:"h-6 w-6 p-0",onClick:tt=>{tt.stopPropagation(),F(null)},children:e.jsx($n,{className:"h-3 w-3"})})]}):e.jsxs("div",{className:"flex flex-col items-center gap-1 text-muted-foreground",children:[e.jsx(_a,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Click to upload a video file"})]})]}),Z&&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(rs,{className:"h-3.5 w-3.5 animate-spin"}),e.jsxs("span",{children:["Uploading to Bunny.net... ",z,"%"]})]}),e.jsx(fi,{value:z,className:"h-1.5"})]}),!I&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx("div",{className:"flex-1 h-px bg-border"}),e.jsx("span",{children:"or paste a URL"}),e.jsx("div",{className:"flex-1 h-px bg-border"})]}),e.jsx(ye,{value:v.video_url,onChange:tt=>j(at=>({...at,video_url:tt.target.value})),placeholder:"YouTube, Vimeo, or Bunny.net URL"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Text Content"}),e.jsx(Ms,{value:v.text_content,onChange:tt=>j(at=>({...at,text_content:tt.target.value})),placeholder:"Additional text content, instructions, notes...",rows:4})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Duration (minutes)"}),e.jsx(ye,{type:"number",value:v.duration_minutes,onChange:tt=>j(at=>({...at,duration_minutes:tt.target.value})),placeholder:"e.g. 15"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>{_(!1),f(null),F(null)},children:"Cancel"}),e.jsxs(B,{onClick:p?ke:Je,disabled:!v.title.trim()||Z,children:[Z?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):e.jsx(Jo,{className:"h-4 w-4 mr-2"}),Z?"Uploading...":p?"Save Changes":"Add Module"]})]})]})}),e.jsx(_s,{open:!!w,onOpenChange:tt=>{tt||S(null)},children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Add Resource"}),e.jsx(Jn,{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(ne,{children:"Title"}),e.jsx(ye,{value:A.title,onChange:tt=>E(at=>({...at,title:tt.target.value})),placeholder:"Resource title"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Type"}),e.jsxs(us,{value:A.resource_type,onValueChange:tt=>E(at=>({...at,resource_type:tt})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"link",children:"Link"}),e.jsx(Ze,{value:"pdf",children:"PDF"}),e.jsx(Ze,{value:"template",children:"Template"}),e.jsx(Ze,{value:"worksheet",children:"Worksheet"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"URL"}),e.jsx(ye,{value:A.url,onChange:tt=>E(at=>({...at,url:tt.target.value})),placeholder:"https://..."})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{onClick:()=>w&&je(w),disabled:!A.title.trim(),children:"Add Resource"})]})]})}),e.jsx(_s,{open:Te,onOpenChange:Ie,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Edit Course"}),e.jsx(Jn,{children:"Update the course title and description"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:me,onChange:tt=>le(tt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{value:ve,onChange:tt=>ge(tt.target.value),rows:3})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>Ie(!1),children:"Cancel"}),e.jsx(B,{onClick:rt,disabled:!me.trim(),children:"Save"})]})]})})]})}function ctn(){return dt({queryKey:["lms-stats-overview"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_stats");if(t)throw t;return s}})}function dtn(){return dt({queryKey:["lms-stats-courses"],queryFn:async()=>{const{data:s,error:t}=await q.rpc("get_lms_course_stats");if(t)throw t;return s||[]}})}function utn(s){return dt({queryKey:["lms-stats-agents",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.rpc("get_lms_agent_progress",{p_course_id:s});if(n)throw n;return t||[]},enabled:!!s})}function htn(){const s=Ln(),{data:t,isLoading:n}=ctn(),{data:r,isLoading:a}=dtn(),[i,l]=N.useState(null),{data:o,isLoading:c}=utn(i),[d,u]=N.useState(""),h=r==null?void 0:r.find(y=>y.course_id===i),p=o==null?void 0:o.filter(y=>{var _,v;return!d||((_=y.agent_name)==null?void 0:_.toLowerCase().includes(d.toLowerCase()))||((v=y.email)==null?void 0:v.toLowerCase().includes(d.toLowerCase()))}),f=[{label:"Total Courses",value:(t==null?void 0:t.total_courses)??0,icon:rm,color:"text-primary"},{label:"Published",value:(t==null?void 0:t.published_courses)??0,icon:vr,color:"text-emerald-500"},{label:"Enrolled Agents",value:(t==null?void 0:t.total_enrollments)??0,icon:An,color:"text-blue-500"},{label:"Modules Completed",value:(t==null?void 0:t.total_completions)??0,icon:xo,color:"text-amber-500"},{label:"Active (30d)",value:(t==null?void 0:t.active_learners)??0,icon:go,color:"text-violet-500"},{label:"Total Modules",value:(t==null?void 0:t.total_modules)??0,icon:_o,color:"text-rose-500"}];return e.jsx(Cs,{title:"LevelUp U - Stats",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/admin/lms"),children:e.jsx(qr,{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(yd,{className:"h-7 w-7 text-primary"}),"LevelUp U — Analytics"]}),e.jsx("p",{className:"text-muted-foreground text-sm mt-0.5",children:"Track enrollment, progress, and completion across all courses"})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-6 gap-3",children:f.map(y=>e.jsx(fe,{className:Mt("transition-all",n&&"animate-pulse"),children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(y.icon,{className:Mt("h-4 w-4",y.color)}),e.jsx("span",{className:"text-xs font-medium text-muted-foreground",children:y.label})]}),e.jsx("p",{className:"text-2xl font-bold text-foreground",children:n?"—":y.value})]})},y.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(_o,{className:"h-5 w-5 text-primary"}),"Course Breakdown"]}),a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(y=>e.jsx(fe,{className:"animate-pulse",children:e.jsx(Ee,{className:"p-4",children:e.jsx("div",{className:"h-16 bg-muted rounded"})})},y))}):r!=null&&r.length?e.jsx("div",{className:"space-y-2",children:r.map(y=>{const _=i===y.course_id;return e.jsx(fe,{className:Mt("cursor-pointer transition-all hover:shadow-md",_?"border-primary ring-1 ring-primary/30 shadow-md":"hover:border-primary/40"),onClick:()=>l(_?null:y.course_id),children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-start justify-between mb-3",children:[e.jsx("div",{className:"flex-1 min-w-0",children:e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-semibold text-sm text-foreground truncate",children:y.course_title}),e.jsx(Ue,{variant:y.is_published?"default":"secondary",className:"shrink-0 text-[10px] px-1.5 py-0",children:y.is_published?"Live":"Draft"})]})}),e.jsx(ga,{className:Mt("h-4 w-4 text-muted-foreground transition-transform shrink-0 ml-2",_&&"rotate-90")})]}),e.jsxs("div",{className:"grid grid-cols-3 gap-3 text-center",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-lg font-bold text-foreground",children:y.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:y.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:y.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:[y.avg_completion_pct,"%"]})]}),e.jsx(fi,{value:y.avg_completion_pct,className:"h-2"})]})]})},y.course_id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ee,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:"No courses created yet"})})})]}),e.jsxs("div",{className:"xl:col-span-3 space-y-3",children:[e.jsxs("h2",{className:"text-lg font-semibold text-foreground flex items-center gap-2",children:[e.jsx(xb,{className:"h-5 w-5 text-primary"}),h?`Agent Progress — ${h.course_title}`:"Agent Progress"]}),i?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{value:d,onChange:y=>u(y.target.value),placeholder:"Search agents...",className:"pl-9"})]}),c?e.jsx("div",{className:"space-y-2",children:[1,2,3,4].map(y=>e.jsx(fe,{className:"animate-pulse",children:e.jsx(Ee,{className:"p-4",children:e.jsx("div",{className:"h-12 bg-muted rounded"})})},y))}):p!=null&&p.length?e.jsx("div",{className:"space-y-2 max-h-[600px] overflow-y-auto pr-1",children:p.map((y,_)=>{const v=y.completion_pct>=100;return e.jsx(fe,{className:Mt("transition-all",v&&"border-emerald-200 bg-emerald-50/30 dark:border-emerald-900/40 dark:bg-emerald-950/10"),children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Mt("flex items-center justify-center w-7 h-7 rounded-full text-xs font-bold shrink-0",_===0?"bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400":_===1?"bg-slate-100 text-slate-600 dark:bg-slate-800 dark:text-slate-400":_===2?"bg-orange-100 text-orange-700 dark:bg-orange-900/30 dark:text-orange-400":"bg-muted text-muted-foreground"),children:_+1}),e.jsxs(Jr,{className:"h-9 w-9 shrink-0",children:[e.jsx(ti,{src:y.avatar_url||void 0}),e.jsx(ea,{className:"text-xs bg-primary/10 text-primary",children:(y.agent_name||y.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:y.agent_name||y.email}),v&&e.jsxs(Ue,{variant:"default",className:"text-[10px] px-1.5 py-0 bg-emerald-500 hover:bg-emerald-600 shrink-0",children:[e.jsx(vr,{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:[y.modules_completed,"/",y.total_modules," modules"]}),y.last_activity&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),Ss(new Date(y.last_activity),"MMM d, yyyy")]})]})]}),e.jsxs("div",{className:"text-right shrink-0 w-20",children:[e.jsxs("p",{className:Mt("text-sm font-bold",v?"text-emerald-600 dark:text-emerald-400":"text-foreground"),children:[y.completion_pct,"%"]}),e.jsx(fi,{value:y.completion_pct,className:"h-1.5 mt-1"})]})]})})},y.user_id)})}):e.jsx(fe,{className:"border-dashed",children:e.jsx(Ee,{className:"py-10 text-center",children:e.jsx("p",{className:"text-muted-foreground text-sm",children:d?"No agents match your search":"No agents have started this course yet"})})})]}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"py-16 text-center",children:[e.jsx(An,{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 mtn(){const{user:s}=vs(),t=Ln(),{data:n,isLoading:r}=rtn();return e.jsx(Cs,{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(yd,{className:"h-6 w-6 text-primary"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold text-foreground",children:"LevelUp U"}),e.jsx("p",{className:"text-muted-foreground text-sm",children:"Your training & development hub"})]})]})}),e.jsx("div",{className:"absolute top-0 right-0 w-64 h-64 bg-primary/5 rounded-full -translate-y-1/2 translate-x-1/2"})]}),r?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(a=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(Ee,{className:"p-6",children:[e.jsx("div",{className:"h-5 bg-muted rounded w-2/3"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2 mt-3"})]})},a))}):n!=null&&n.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:n.map(a=>e.jsx(ptn,{course:a,userId:s==null?void 0:s.id,onClick:()=>t(`/levelup-u/${a.id}`)},a.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx(rm,{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 ptn({course:s,userId:t,onClick:n}){var o;const r=((o=s.modules)==null?void 0:o.length)??0,{data:a}=Y2t(s.id),i=(a==null?void 0:a.filter(c=>c.completed).length)??0,l=r>0?Math.round(i/r*100):0;return e.jsxs(fe,{className:"group cursor-pointer hover:shadow-lg transition-all hover:border-primary/50 overflow-hidden",onClick:n,children:[s.thumbnail_url?e.jsx("div",{className:"aspect-video bg-muted overflow-hidden",children:e.jsx("img",{src:s.thumbnail_url,alt:s.title,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"})}):e.jsx("div",{className:"aspect-video bg-gradient-to-br from-primary/15 via-primary/5 to-muted flex items-center justify-center",children:e.jsx(yd,{className:"h-10 w-10 text-primary/40"})}),e.jsxs(Ee,{className:"p-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-foreground group-hover:text-primary transition-colors line-clamp-1",children:s.title}),s.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 line-clamp-2",children:s.description})]}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(rm,{className:"h-3.5 w-3.5"}),r," module",r!==1?"s":""]}),e.jsxs("span",{className:"flex items-center gap-1",children:[s.is_sequential?e.jsx(ub,{className:"h-3.5 w-3.5"}):e.jsx(DA,{className:"h-3.5 w-3.5"}),s.is_sequential?"In order":"Any order"]})]}),r>0&&e.jsxs("div",{className:"space-y-1.5",children:[e.jsxs("div",{className:"flex items-center justify-between text-xs",children:[e.jsxs("span",{className:"text-muted-foreground",children:[i," of ",r," completed"]}),e.jsxs("span",{className:"font-medium text-foreground",children:[l,"%"]})]}),e.jsx(fi,{value:l,className:"h-1.5"})]}),e.jsx("div",{className:"flex items-center justify-end",children:e.jsxs("span",{className:"text-xs text-primary font-medium flex items-center gap-1 opacity-0 group-hover:opacity-100 transition-opacity",children:[l===100?"Review":l>0?"Continue":"Start"," Course",e.jsx(ga,{className:"h-3.5 w-3.5"})]})})]})]})}function ftn(){const{courseId:s}=bi(),t=Ln(),{user:n}=vs(),{data:r,isLoading:a}=atn(s),{data:i}=Y2t(s),l=itn(),[o,c]=N.useState(null),d=(r==null?void 0:r.modules)||[],u=new Set((i==null?void 0:i.filter(w=>w.completed).map(w=>w.module_id))||[]),h=u.size,p=d.length>0?Math.round(h/d.length*100):0;N.useEffect(()=>{if(d.length>0&&!o){const w=d.find(S=>!u.has(S.id));c((w==null?void 0:w.id)||d[0].id)}},[d,o,u]);const f=d.find(w=>w.id===o),y=d.findIndex(w=>w.id===o),_=(w,S)=>{if(!(r!=null&&r.is_sequential)||S===0)return!1;for(let A=0;A{if(!(!f||!n||!s))try{await l.mutateAsync({courseId:s,moduleId:f.id,userId:n.id}),ae.success("Module completed! 🎉"),y{const S=w.match(/(?:youtube\.com\/(?:watch\?v=|embed\/)|youtu\.be\/)([a-zA-Z0-9_-]{11})/);if(S)return`https://www.youtube.com/embed/${S[1]}`;const A=w.match(/vimeo\.com\/(\d+)/);if(A)return`https://player.vimeo.com/video/${A[1]}`;const E=w.match(/(?:iframe\.mediadelivery\.net|video\.bunnycdn\.com)\/(?:play|embed)\/(\d+)\/([a-f0-9-]+)/);return E?`https://iframe.mediadelivery.net/embed/${E[1]}/${E[2]}?responsive=true`:w};return a?e.jsx(Cs,{title:"Loading...",children:e.jsx("div",{className:"flex items-center justify-center py-20",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):r?e.jsx(Cs,{title:r.title,children:e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>t("/levelup-u"),children:e.jsx(qr,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h1",{className:"text-xl font-bold text-foreground truncate",children:r.title}),e.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground mt-0.5",children:[e.jsxs("span",{children:[h,"/",d.length," completed"]}),e.jsxs("span",{children:[p,"%"]})]})]}),e.jsx("div",{className:"w-32",children:e.jsx(fi,{value:p,className:"h-2"})})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-[320px_1fr] gap-4 items-start",children:[e.jsx(fe,{className:"lg:sticky lg:top-4",children:e.jsxs(Ee,{className:"p-0",children:[e.jsx("div",{className:"p-3 border-b",children:e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Modules"})}),e.jsx(di,{className:"max-h-[calc(100vh-280px)]",children:e.jsx("div",{className:"p-1",children:d.map((w,S)=>{const A=_(w,S),E=u.has(w.id),O=w.id===o;return e.jsxs("button",{disabled:A,onClick:()=>!A&&c(w.id),className:Mt("w-full flex items-center gap-3 p-3 rounded-lg text-left transition-all text-sm",O?"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(Gc,{className:"h-4 w-4 text-muted-foreground"}):E?e.jsx(vr,{className:"h-4 w-4 text-green-500"}):e.jsx(am,{className:"h-4 w-4 text-muted-foreground"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("p",{className:Mt("font-medium truncate",O&&"text-primary"),children:[S+1,". ",w.title]}),w.duration_minutes&&e.jsxs("span",{className:"text-[11px] text-muted-foreground flex items-center gap-0.5 mt-0.5",children:[e.jsx(pr,{className:"h-3 w-3"})," ",w.duration_minutes," min"]})]})]},w.id)})})})]})}),e.jsx("div",{className:"space-y-4",children:f?e.jsxs(e.Fragment,{children:[f.video_url&&e.jsx(fe,{className:"overflow-hidden",children:e.jsx("div",{className:"aspect-video bg-black",children:e.jsx("iframe",{src:j(f.video_url),className:"w-full h-full",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0})})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-lg font-semibold",children:f.title}),f.description&&e.jsx("p",{className:"text-muted-foreground mt-1",children:f.description})]}),u.has(f.id)?e.jsxs(Ue,{className:"bg-green-500/15 text-green-600 border-green-500/30 shrink-0",children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1"})," Completed"]}):e.jsxs(B,{size:"sm",onClick:v,disabled:l.isPending,children:[e.jsx(vr,{className:"h-4 w-4 mr-1"}),"Mark Complete"]})]}),f.text_content&&e.jsx("div",{className:"prose prose-sm max-w-none text-foreground border-t pt-4 whitespace-pre-wrap",children:f.text_content}),f.resources&&f.resources.length>0&&e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("p",{className:"text-sm font-medium mb-2",children:"Resources"}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-2",children:f.resources.map(w=>e.jsxs("a",{href:w.url||w.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:[w.resource_type==="pdf"?e.jsx(br,{className:"h-4 w-4 text-red-500 shrink-0"}):w.resource_type==="template"?e.jsx(yd,{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:w.title}),e.jsx(tr,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"})]},w.id))})]}),e.jsxs("div",{className:"flex items-center justify-between border-t pt-4",children:[e.jsxs(B,{variant:"outline",size:"sm",disabled:y===0,onClick:()=>y>0&&c(d[y-1].id),children:[e.jsx(qr,{className:"h-3.5 w-3.5 mr-1"})," Previous"]}),yc(d[y+1].id),children:["Next ",e.jsx(ga,{className:"h-3.5 w-3.5 ml-1"})]}):p===100&&e.jsx(Ue,{className:"bg-green-500/15 text-green-600 border-green-500/30 text-sm px-3 py-1.5",children:"🎉 Course Complete!"})]})]})})]}):e.jsx(fe,{children:e.jsx(Ee,{className:"flex items-center justify-center py-16 text-muted-foreground",children:"Select a module to begin"})})})]})]})}):e.jsx(Cs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-20",children:[e.jsx("p",{className:"text-muted-foreground",children:"Course not found"}),e.jsxs(B,{variant:"outline",className:"mt-4",onClick:()=>t("/levelup-u"),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"})," Back"]})]})})}function xtn({headline:s,subtext:t,primaryColor:n,accentColor:r,heroImageUrl:a,logoUrl:i,brokerageName:l}){return e.jsxs("section",{className:"relative min-h-screen flex items-center justify-center overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(160deg, ${r} 0%, ${n} 50%, ${r}ee 100%)`}}),a&&e.jsx("div",{className:"absolute inset-0 bg-cover bg-center opacity-20",style:{backgroundImage:`url(${a})`}}),e.jsx("div",{className:"absolute inset-0 opacity-[0.03]",style:{backgroundImage:"radial-gradient(circle at 25% 25%, white 1px, transparent 1px), radial-gradient(circle at 75% 75%, white 1px, transparent 1px)",backgroundSize:"60px 60px"}}),e.jsx("div",{className:"absolute bottom-0 left-0 right-0 h-32 bg-gradient-to-t from-white to-transparent"}),e.jsxs("div",{className:"relative z-10 text-center max-w-4xl mx-auto px-6 py-24",children:[i&&e.jsx(Zn.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(Zn.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(Zn.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(Zn.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(Zn.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.7,delay:.9},className:"flex flex-col sm:flex-row items-center justify-center gap-4",children:[e.jsxs("a",{href:"#apply",className:"group inline-flex items-center gap-3 px-10 py-4 rounded-full text-lg font-semibold shadow-2xl transition-all duration-300 hover:scale-105 hover:shadow-3xl",style:{backgroundColor:"white",color:r},children:["Get In Touch",e.jsx(Oa,{className:"h-5 w-5 transition-transform group-hover:translate-x-1"})]}),e.jsx("a",{href:"#benefits",className:"inline-flex items-center gap-2 px-8 py-4 rounded-full text-base font-medium text-white/90 border border-white/30 backdrop-blur-sm transition-all duration-300 hover:bg-white/10 hover:border-white/50",children:"Learn More"})]})]}),e.jsx(Zn.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 by({children:s,className:t="",delay:n=0,direction:r="up"}){const a=N.useRef(null),i=zXt(a,{once:!0,margin:"-80px"}),l={hidden:{opacity:0,y:r==="up"?40:0,x:r==="left"?-40:r==="right"?40:0},visible:{opacity:1,y:0,x:0}};return e.jsx(Zn.div,{ref:a,initial:"hidden",animate:i?"visible":"hidden",variants:l,transition:{duration:.7,delay:n,ease:[.25,.46,.45,.94]},className:t,children:s})}function gtn({benefits:s,accentColor:t,primaryColor:n}){return s.length===0?null:e.jsx("section",{id:"benefits",className:"py-24 md:py-32 px-6 bg-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(by,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase mb-4 block",style:{color:n},children:"Why Top Agents Choose Us"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold mb-4 tracking-tight",style:{color:t},children:"Built For Your Success"}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full mt-6",style:{backgroundColor:n}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 lg:grid-cols-3 gap-6 md:gap-8",children:s.map((r,a)=>e.jsx(by,{delay:a*.1,children:e.jsxs("div",{className:"group relative p-8 rounded-2xl border border-gray-100 bg-white hover:border-transparent hover:shadow-2xl transition-all duration-500 h-full",children:[e.jsx("div",{className:"absolute inset-0 rounded-2xl opacity-0 group-hover:opacity-100 transition-opacity duration-500",style:{background:`linear-gradient(135deg, ${n}08, ${t}05)`}}),e.jsxs("div",{className:"relative z-10",children:[e.jsx("div",{className:"w-14 h-14 rounded-xl flex items-center justify-center text-2xl mb-5 transition-transform duration-300 group-hover:scale-110",style:{backgroundColor:`${n}12`},children:r.icon}),e.jsx("h3",{className:"text-xl font-bold mb-3 tracking-tight",style:{color:t},children:r.title}),e.jsx("p",{className:"text-gray-500 leading-relaxed text-[15px]",children:r.description})]})]})},a))})]})})}function ytn({images:s,primaryColor:t,accentColor:n}){const[r,a]=N.useState(null);return s.length===0?null:e.jsxs(e.Fragment,{children:[e.jsx("section",{className:"py-24 md:py-32 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(by,{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(An,{className:"h-4 w-4",style:{color:t}}),e.jsx("span",{className:"text-sm font-medium text-gray-600",children:"Life at Our Brokerage"})]}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:n},children:"Our Team & Culture"})]})}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3 md:gap-4",children:s.map((i,l)=>e.jsx(by,{delay:l*.08,children:e.jsxs("button",{onClick:()=>a(l),className:"relative w-full aspect-[4/3] overflow-hidden rounded-xl group cursor-pointer",children:[e.jsx("img",{src:i,alt:`Team ${l+1}`,className:"w-full h-full object-cover transition-transform duration-700 group-hover:scale-110"}),e.jsx("div",{className:"absolute inset-0 bg-black/0 group-hover:bg-black/20 transition-all duration-500"})]})},l))})]})}),r!==null&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/90 flex items-center justify-center p-4 cursor-pointer",onClick:()=>a(null),children:[e.jsx("button",{onClick:()=>a(null),className:"absolute top-6 right-6 text-white/80 hover:text-white transition-colors",children:e.jsx($n,{className:"h-8 w-8"})}),e.jsx("img",{src:s[r],alt:"Gallery",className:"max-w-full max-h-[85vh] object-contain rounded-lg",onClick:i=>i.stopPropagation()})]})]})}function vtn({testimonials:s,primaryColor:t,accentColor:n}){return s.length===0?null:e.jsx("section",{className:"py-24 md:py-32 px-6 bg-white",children:e.jsxs("div",{className:"max-w-6xl mx-auto",children:[e.jsx(by,{children:e.jsxs("div",{className:"text-center mb-16",children:[e.jsx("span",{className:"text-sm font-semibold tracking-[0.15em] uppercase mb-4 block",style:{color:t},children:"Agent Testimonials"}),e.jsx("h2",{className:"text-3xl md:text-5xl font-bold tracking-tight",style:{color:n},children:"Hear From Our Agents"}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full mt-6",style:{backgroundColor:t}})]})}),e.jsx("div",{className:"grid md:grid-cols-2 gap-8",children:s.map((r,a)=>{var i;return e.jsx(by,{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(gw,{className:"h-8 w-8 mb-5 opacity-20",style:{color:t}}),e.jsxs("p",{className:"text-gray-700 text-lg leading-relaxed mb-8 font-light italic",children:['"',r.quote,'"']}),e.jsxs("div",{className:"flex items-center gap-4",children:[r.photo_url?e.jsx("img",{src:r.photo_url,alt:r.name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white shadow-md"}):e.jsx("div",{className:"h-12 w-12 rounded-full flex items-center justify-center text-white text-base font-bold shadow-md",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:((i=r.name)==null?void 0:i[0])||"?"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-base",style:{color:n},children:r.name}),r.role&&e.jsx("p",{className:"text-sm text-gray-500",children:r.role})]})]})]})},a)})})]})})}function btn({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i}){return e.jsxs("section",{id:"apply",className:"py-24 md:py-32 px-6 relative overflow-hidden",children:[e.jsx("div",{className:"absolute inset-0 top-0 h-1/2",style:{background:`linear-gradient(160deg, ${i}, ${a})`}}),e.jsx("div",{className:"absolute inset-0 top-1/2 bg-gray-50"}),e.jsxs("div",{className:"relative z-10 max-w-xl mx-auto",children:[e.jsx(by,{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(by,{delay:.2,children:e.jsxs("form",{onSubmit:l=>{l.preventDefault(),n()},className:"bg-white rounded-3xl shadow-2xl p-8 md:p-10 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(ye,{required:!0,value:s.first_name,onChange:l=>t(o=>({...o,first_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(ye,{value:s.last_name,onChange:l=>t(o=>({...o,last_name:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(ye,{type:"email",required:!0,value:s.email,onChange:l=>t(o=>({...o,email:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Phone"}),e.jsx(ye,{value:s.phone,onChange:l=>t(o=>({...o,phone:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(ye,{value:s.current_brokerage,onChange:l=>t(o=>({...o,current_brokerage:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"Your current brokerage name"})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"License #"}),e.jsx(ye,{value:s.license_number,onChange:l=>t(o=>({...o,license_number:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ye,{type:"number",min:"0",value:s.experience_years,onChange:l=>t(o=>({...o,experience_years:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(ye,{value:s.annual_production,onChange:l=>t(o=>({...o,annual_production:l.target.value})),className:"h-11 rounded-lg border-gray-200 focus:border-gray-400 transition-colors",placeholder:"e.g. $5M, 20 transactions"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Why are you interested?"}),e.jsx(Ms,{value:s.why_interested,onChange:l=>t(o=>({...o,why_interested:l.target.value})),rows:3,className:"rounded-lg border-gray-200 focus:border-gray-400 transition-colors resize-none",placeholder:"Tell us about your goals and what you're looking for..."})]}),e.jsx(B,{type:"submit",className:"w-full h-13 text-base font-semibold rounded-xl group transition-all duration-300 hover:shadow-lg",style:{background:`linear-gradient(135deg, ${a}, ${i})`},disabled:r,children:r?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Submitting..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:["Send My Info",e.jsx(Oa,{className:"h-4 w-4 transition-transform group-hover:translate-x-1"})]})}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-gray-400 pt-1",children:[e.jsx(Ih,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:"Your information is confidential and will not be shared."})]})]})})]})]})}function _tn({form:s,setForm:t,onSubmit:n,isPending:r,primaryColor:a,accentColor:i,showConfidentialBadges:l=!0}){const[o,c]=N.useState(1),[d,u]=N.useState(""),h=3,p=!!s.first_name&&!!s.email,f=y=>{u(y),t(_=>({..._,why_interested:y})),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(by,{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(Gc,{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(by,{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(y=>e.jsx("div",{className:"h-1 flex-1 rounded-full transition-colors duration-500",style:{backgroundColor:y<=o?a:"#e5e7eb"}},y)),e.jsxs("span",{className:"text-xs text-gray-400 ml-2",children:[o,"/",h]})]}),e.jsxs(pye,{mode:"wait",children:[o===1&&e.jsxs(Zn.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(y=>e.jsxs("button",{type:"button",onClick:()=>f(y.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:y.icon}),e.jsx("span",{className:"font-medium text-gray-700 group-hover:text-gray-900 flex-1",children:y.label}),e.jsx(Oa,{className:"h-4 w-4 text-gray-300 group-hover:text-gray-500 group-hover:translate-x-1 transition-all"})]},y.val))]},"step1"),o===2&&e.jsxs(Zn.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(ne,{className:"text-gray-700 text-sm font-medium",children:"First Name *"}),e.jsx(ye,{required:!0,value:s.first_name,onChange:y=>t(_=>({..._,first_name:y.target.value})),className:"h-11",placeholder:"John"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Last Name"}),e.jsx(ye,{value:s.last_name,onChange:y=>t(_=>({..._,last_name:y.target.value})),className:"h-11",placeholder:"Smith"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Email *"}),e.jsx(ye,{type:"email",required:!0,value:s.email,onChange:y=>t(_=>({..._,email:y.target.value})),className:"h-11",placeholder:"john@email.com"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Phone (preferred)"}),e.jsx(ye,{value:s.phone,onChange:y=>t(_=>({..._,phone:y.target.value})),className:"h-11",placeholder:"(555) 123-4567"})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>c(1),className:"h-11",children:[e.jsx(qr,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsxs(B,{type:"button",disabled:!p,onClick:()=>c(3),className:"flex-1 h-11 text-white font-semibold",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:["Continue ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]})]})]},"step2"),o===3&&e.jsxs(Zn.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(ne,{className:"text-gray-700 text-sm font-medium",children:"Current Brokerage"}),e.jsx(ye,{value:s.current_brokerage,onChange:y=>t(_=>({..._,current_brokerage:y.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(ne,{className:"text-gray-700 text-sm font-medium",children:"Years Experience"}),e.jsx(ye,{type:"number",min:"0",value:s.experience_years,onChange:y=>t(_=>({..._,experience_years:y.target.value})),className:"h-11"})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Annual Production"}),e.jsx(ye,{value:s.annual_production,onChange:y=>t(_=>({..._,annual_production:y.target.value})),className:"h-11",placeholder:"e.g. $5M"})]})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-gray-700 text-sm font-medium",children:"Anything else?"}),e.jsx(Ms,{value:s.why_interested,onChange:y=>t(_=>({..._,why_interested:y.target.value})),rows:2,className:"resize-none",placeholder:"Optional message..."})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsxs(B,{type:"button",variant:"ghost",onClick:()=>c(2),className:"h-11",children:[e.jsx(qr,{className:"h-4 w-4 mr-1"})," Back"]}),e.jsx(B,{type:"button",onClick:n,disabled:r,className:"flex-1 h-12 text-white font-semibold rounded-xl",style:{background:`linear-gradient(135deg, ${a}, ${i})`},children:r?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-2 border-white border-t-transparent"}),"Sending..."]}):e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx(Lr,{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(Ih,{className:"h-3 w-3"})," Confidential"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Ai,{className:"h-3 w-3"})," Text first"]}),e.jsxs("div",{className:"flex items-center gap-1 justify-center",children:[e.jsx(Cr,{className:"h-3 w-3"})," No spam"]})]})]})})]})]})}function wtn({config:s,primaryColor:t,accentColor:n,brokerageId:r,brokerageName:a}){const{toast:i}=Fa(),[l,o]=N.useState("250000"),[c,d]=N.useState("12"),[u,h]=N.useState("70"),[p,f]=N.useState("150"),[y,_]=N.useState(""),[v,j]=N.useState(!1),[w,S]=N.useState(!1),A=s.commission_split_pct??80,E=s.cap_amount??16e3,O=s.post_cap_split_pct??100,D=s.monthly_fee??99,I=s.transaction_fee??0,F=N.useMemo(()=>{const Z=parseFloat(l)||0,Y=Math.max(0,parseInt(c,10)||0),W=parseFloat(u)||0,ee=parseFloat(p)||0,se=Z*(W/100)-ee*12-I*Y,oe=1-A/100,he=oe>0?E/oe:Z,ce=Math.min(Z,he),me=Math.max(0,Z-he),le=ce*oe+me*(1-O/100),ve=Z-le-D*12-I*Y,ge=ve-se;return{currentNet:se,newNet:ve,diff:ge}},[l,c,u,p,A,E,O,D,I]),z=Z=>new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(Z),H=async Z=>{if(Z.preventDefault(),!!y){S(!0);try{const{error:Y}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:y,source:"calculator"});if(Y)throw Y;const{error:W}=await q.functions.invoke("send-calculator-breakdown",{body:{brokerage_id:r,brokerage_name:a,email:y,inputs:{gci:parseFloat(l)||0,transactions:parseInt(c,10)||0,current_split_pct:parseFloat(u)||0,current_monthly_fee:parseFloat(p)||0},plan:{commission_split_pct:A,cap_amount:E,post_cap_split_pct:O,monthly_fee:D,transaction_fee:I},result:F,primary_color:t,accent_color:n}});W&&console.error("Breakdown email failed:",W),j(!0),i({title:"Sent!",description:"Check your email for the full breakdown."})}catch(Y){i({title:"Error",description:Y.message,variant:"destructive"})}finally{S(!1)}}};return e.jsx("section",{className:"py-20 md:py-28 px-6 bg-gray-50",children:e.jsxs("div",{className:"max-w-5xl mx-auto",children:[e.jsx(by,{children:e.jsxs("div",{className:"text-center mb-10",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-4 py-1.5 rounded-full text-xs font-semibold mb-4",style:{backgroundColor:`${t}15`,color:n},children:[e.jsx(Gc,{className:"h-3 w-3"})," 100% Confidential — No Signup Required"]}),e.jsx("h2",{className:"text-3xl md:text-4xl font-bold tracking-tight mb-3",style:{color:n},children:s.headline||"See What You Could Earn With Us"}),e.jsx("p",{className:"text-gray-500 text-lg font-light max-w-xl mx-auto",children:s.subtext||"Confidential 60-second calculator — no signup required."})]})}),e.jsx(by,{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(dw,{className:"h-5 w-5",style:{color:t}}),e.jsx("h3",{className:"font-semibold",style:{color:n},children:"Your Numbers"})]}),e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-gray-600 text-sm",children:"Your GCI Last 12 Months"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(ye,{type:"number",value:l,onChange:Z=>o(Z.target.value),className:"pl-7 h-11 text-base",placeholder:"250,000"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-gray-600 text-sm",children:"Transactions per Year"}),e.jsx(ye,{type:"number",min:"0",value:c,onChange:Z=>d(Z.target.value),className:"mt-1.5 h-11 text-base",placeholder:"12"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-gray-600 text-sm",children:"Your Current Commission Split (%)"}),e.jsx(ye,{type:"number",value:u,onChange:Z=>h(Z.target.value),className:"mt-1.5 h-11 text-base",placeholder:"70"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-gray-600 text-sm",children:"Your Current Monthly Fees"}),e.jsxs("div",{className:"relative mt-1.5",children:[e.jsx("span",{className:"absolute left-3 top-1/2 -translate-y-1/2 text-gray-400 text-sm",children:"$"}),e.jsx(ye,{type:"number",value:p,onChange:Z=>f(Z.target.value),className:"pl-7 h-11 text-base",placeholder:"150"})]})]})]})]}),e.jsxs("div",{className:"p-8 md:p-10 text-white",style:{background:`linear-gradient(160deg, ${n}, ${t})`},children:[e.jsxs("div",{className:"flex items-center gap-2 mb-6",children:[e.jsx(go,{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(Zn.div,{initial:{scale:.95,opacity:0},animate:{scale:1,opacity:1},className:"bg-white/10 backdrop-blur rounded-2xl p-5 text-center",children:[e.jsx("p",{className:"text-white/80 text-xs uppercase tracking-wide mb-1",children:F.diff>=0?"You could earn":"Difference"}),e.jsxs("p",{className:"text-4xl font-bold mb-1",children:[F.diff>=0?"+":"",z(F.diff)]}),e.jsx("p",{className:"text-white/70 text-xs",children:F.diff>=0?"more per year":"per year"})]},F.diff),s.show_email_capture&&!v&&e.jsxs("form",{onSubmit:H,className:"mt-6 space-y-2",children:[e.jsx("p",{className:"text-white/80 text-xs",children:s.email_capture_label||"Want the full breakdown? Enter your email."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{type:"email",required:!0,value:y,onChange:Z=>_(Z.target.value),placeholder:"you@email.com",className:"bg-white/95 border-0 text-gray-900 h-10 text-sm"}),e.jsx(B,{type:"submit",disabled:w,className:"h-10 bg-white text-gray-900 hover:bg-white/90 text-sm font-semibold",children:"Send"})]})]}),v&&e.jsxs("div",{className:"mt-6 flex items-center gap-2 text-sm text-white/90 bg-white/10 rounded-lg p-3",children:[e.jsx(Lr,{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 jtn({config:s,primaryColor:t,accentColor:n,brokerageId:r}){const{toast:a}=Fa(),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),[h,p]=N.useState(!1),f=async y=>{y.preventDefault(),p(!0);try{const{error:_}=await q.from("recruit_lead_magnet_downloads").insert({brokerage_id:r,email:i,first_name:o||null,source:"lead_magnet",user_agent:navigator.userAgent,referrer:document.referrer||null});if(_)throw _;u(!0),s.pdf_url&&window.open(s.pdf_url,"_blank","noopener,noreferrer")}catch(_){a({title:"Error",description:_.message,variant:"destructive"})}finally{p(!1)}};return e.jsx("section",{className:"py-20 md:py-24 px-6 bg-white",children:e.jsx("div",{className:"max-w-3xl mx-auto",children:e.jsx(by,{children:e.jsx("div",{className:"rounded-3xl p-8 md:p-12 shadow-xl border border-gray-100",style:{background:`linear-gradient(135deg, ${t}08, ${n}08)`},children:e.jsxs("div",{className:"flex flex-col md:flex-row items-center gap-8",children:[e.jsx("div",{className:"shrink-0 h-24 w-24 rounded-2xl flex items-center justify-center shadow-lg",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:e.jsx(_A,{className:"h-12 w-12 text-white"})}),e.jsxs("div",{className:"flex-1 text-center md:text-left",children:[e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-3 py-1 rounded-full text-[11px] font-semibold mb-3",style:{backgroundColor:`${t}15`,color:n},children:[e.jsx(Gc,{className:"h-2.5 w-2.5"})," No call required — instant download"]}),e.jsx("h3",{className:"text-2xl md:text-3xl font-bold tracking-tight mb-2",style:{color:n},children:s.title||"Get the Full Comp Plan PDF"}),e.jsx("p",{className:"text-gray-500 leading-relaxed mb-5",children:s.description||"See exactly how splits, caps, and fees work — no call required."}),d?e.jsxs("div",{className:"flex items-center gap-2 p-4 rounded-xl bg-green-50 border border-green-200 text-green-800 text-sm",children:[e.jsx(Lr,{className:"h-5 w-5 shrink-0"}),e.jsxs("span",{children:["Sent! ",s.pdf_url?"Your download should open in a new tab.":"Check your email shortly."]})]}):e.jsxs("form",{onSubmit:f,className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:[e.jsx(ye,{value:o,onChange:y=>c(y.target.value),placeholder:"First name (optional)",className:"h-11"}),e.jsx(ye,{type:"email",required:!0,value:i,onChange:y=>l(y.target.value),placeholder:"your@email.com",className:"h-11"})]}),e.jsxs(B,{type:"submit",disabled:h,className:"w-full sm:w-auto h-12 px-6 text-white font-semibold",style:{background:`linear-gradient(135deg, ${t}, ${n})`},children:[e.jsx(_A,{className:"h-4 w-4 mr-2"}),h?"Sending...":s.button_text||"Email Me the PDF"]})]})]})]})})})})})}function Ntn(){const{slug:s}=bi(),{toast:t}=Fa(),[n,r]=N.useState(!1),[a,i]=N.useState({first_name:"",last_name:"",email:"",phone:"",current_brokerage:"",experience_years:"",annual_production:"",license_number:"",why_interested:""});N.useEffect(()=>{document.body.classList.add("recruit-landing-page");const F=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(Y=>document.querySelectorAll(Y).forEach(W=>W.style.display="none"))};F();const z=[setTimeout(F,500),setTimeout(F,1500),setTimeout(F,3e3)],H=new MutationObserver(F);return H.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-landing-page"),z.forEach(clearTimeout),H.disconnect()}},[]);const{data:l,isLoading:o,error:c}=dt({queryKey:["recruit-form-brokerage",s],queryFn:async()=>{const{data:F,error:z}=await q.from("brokerages").select("id, name, recruit_form_enabled").eq("recruit_form_slug",s).single();if(z)throw z;return F},enabled:!!s}),{data:d}=dt({queryKey:["recruit-landing-public",l==null?void 0:l.id],queryFn:async()=>{const{data:F,error:z}=await q.from("recruit_landing_page_settings").select("*").eq("brokerage_id",l.id).single();if(z&&z.code!=="PGRST116")throw z;return F},enabled:!!(l!=null&&l.id)}),u=yt({mutationFn:async()=>{const F={brokerage_id:l.id,first_name:a.first_name,last_name:a.last_name||null,email:a.email,phone:a.phone||null,current_brokerage:a.current_brokerage||null,experience_years:a.experience_years?parseInt(a.experience_years):null,annual_production:a.annual_production||null,license_number:a.license_number||null,why_interested:a.why_interested||null},{error:z}=await q.from("recruit_interest_submissions").insert(F);if(z)throw z;q.functions.invoke("recruit-lead-notify",{body:{lead:F,brokerage_id:l.id}}).catch(H=>console.error("Lead notification error:",H))},onSuccess:()=>r(!0),onError:F=>t({title:"Error",description:F.message,variant:"destructive"})});if(o)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-3 border-gray-200 border-t-gray-800"}),e.jsx("span",{className:"text-sm text-gray-400 tracking-wide",children:"Loading..."})]})});if(c||!l||!l.recruit_form_enabled)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"max-w-md w-full mx-4 text-center",children:[e.jsx(Ua,{className:"h-10 w-10 mx-auto text-gray-300 mb-4"}),e.jsx("p",{className:"text-gray-400 text-lg",children:"This page is not available."})]})});const h=d,p=(h==null?void 0:h.primary_color)||"#406E71",f=(h==null?void 0:h.accent_color)||"#2a4c64",y=(h==null?void 0:h.benefits)||[],_=(h==null?void 0:h.testimonials)||[],v=(h==null?void 0:h.gallery_images)||[],j=(h==null?void 0:h.hero_headline)||`Join ${l.name}`,w=(h==null?void 0:h.hero_subtext)||"Take your real estate career to the next level with a brokerage that invests in your growth.",S=(h==null?void 0:h.calculator_enabled)===!0,A=(h==null?void 0:h.calculator_config)||{},E=(h==null?void 0:h.lead_magnet_enabled)===!0,O=(h==null?void 0:h.lead_magnet_config)||{},D=(h==null?void 0:h.form_style)||"classic",I=(h==null?void 0:h.confidential_messaging)!==!1;return n?e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs(Zn.div,{initial:{opacity:0,scale:.9},animate:{opacity:1,scale:1},transition:{duration:.6},className:"max-w-md w-full mx-4 text-center",children:[e.jsx("div",{className:"h-20 w-20 rounded-full flex items-center justify-center mx-auto mb-6 shadow-lg",style:{background:`linear-gradient(135deg, ${p}, ${f})`},children:e.jsx(Lr,{className:"h-10 w-10 text-white"})}),e.jsx("h2",{className:"text-3xl font-bold mb-3 tracking-tight",style:{color:f},children:"Thank You!"}),e.jsxs("p",{className:"text-gray-500 text-lg leading-relaxed mb-8",children:["Your interest in joining ",e.jsx("span",{className:"font-semibold",style:{color:f},children:l.name})," has been received. A member of our recruitment team will be in touch shortly."]}),e.jsx("div",{className:"w-16 h-1 mx-auto rounded-full",style:{backgroundColor:p}})]})}):e.jsxs("div",{className:"min-h-screen bg-white",style:{"--recruit-primary":p,"--recruit-accent":f},children:[e.jsx("nav",{className:"fixed top-0 left-0 right-0 z-40 bg-white/80 backdrop-blur-lg border-b border-gray-100/50",children:e.jsxs("div",{className:"max-w-6xl mx-auto px-6 h-14 flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[(h==null?void 0:h.logo_url)&&e.jsx("img",{src:h.logo_url,alt:l.name,className:"h-8 w-auto"}),e.jsx("span",{className:"font-semibold text-sm tracking-tight",style:{color:f},children:l.name})]}),e.jsxs("a",{href:"#apply",className:"inline-flex items-center gap-2 px-5 py-2 rounded-full text-sm font-semibold text-white transition-all duration-300 hover:shadow-md hover:scale-105",style:{background:`linear-gradient(135deg, ${p}, ${f})`},children:["Apply Now ",e.jsx(Oa,{className:"h-3.5 w-3.5"})]})]})}),e.jsx(xtn,{headline:j,subtext:w,primaryColor:p,accentColor:f,heroImageUrl:h==null?void 0:h.hero_image_url,logoUrl:h==null?void 0:h.logo_url,brokerageName:l.name}),e.jsx(gtn,{benefits:y,accentColor:f,primaryColor:p}),e.jsx(ytn,{images:v,primaryColor:p,accentColor:f}),e.jsx(vtn,{testimonials:_,primaryColor:p,accentColor:f}),S&&e.jsx(wtn,{config:A,primaryColor:p,accentColor:f,brokerageId:l.id,brokerageName:l.name}),E&&e.jsx(jtn,{config:O,primaryColor:p,accentColor:f,brokerageId:l.id}),D==="multi_step"?e.jsx(_tn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:p,accentColor:f,showConfidentialBadges:I}):e.jsx(btn,{form:a,setForm:i,onSubmit:()=>u.mutate(),isPending:u.isPending,primaryColor:p,accentColor:f}),e.jsx("footer",{className:"py-10 text-center bg-white border-t border-gray-100",children:e.jsxs("p",{className:"text-sm text-gray-400",children:["© ",new Date().getFullYear()," ",l.name,". All rights reserved."]})})]})}function ktn(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 Stn(){var p,f,y,_;const{shareToken:s}=bi(),t=N.useRef(!1),{data:n,isLoading:r,error:a}=dt({queryKey:["public-recruit-video",s],queryFn:async()=>{var E;if(!s)throw new Error("No token");const{data:v,error:j}=await q.from("recruit_videos").select(` *, prospect:recruit_prospects(first_name, last_name), video:agent_videos(id, title, playback_url, thumbnail_url, duration_seconds, owner_user_id) `).eq("share_token",s).single();if(j)throw j;const{data:w}=await q.from("profiles").select("name, avatar_url, title, recruit_cta_url").eq("id",(E=v.video)==null?void 0:E.owner_user_id).single(),{data:S}=await q.from("brokerages").select("name").eq("id",v.brokerage_id).single(),{data:A}=await q.from("recruit_landing_page_settings").select("logo_url, primary_color, accent_color, hero_headline").eq("brokerage_id",v.brokerage_id).maybeSingle();return{rv:v,profile:w,brokerage:S,settings:A}},enabled:!!s});if(N.useEffect(()=>{var v;!((v=n==null?void 0:n.rv)!=null&&v.id)||t.current||(t.current=!0,q.rpc("log_recruit_video_view",{p_recruit_video_id:n.rv.id,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null}).then(()=>{}))},[(p=n==null?void 0:n.rv)==null?void 0:p.id]),r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})});if(a||!n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsx("p",{className:"text-muted-foreground",children:"This video is no longer available."})});const{rv:i,profile:l,brokerage:o,settings:c}=n,d=(c==null?void 0:c.primary_color)||"#3b82f6",u=((f=i.prospect)==null?void 0:f.first_name)||"there",h=(y=i.video)!=null&&y.playback_url?ktn(i.video.playback_url):null;return e.jsxs(e.Fragment,{children:[e.jsx(Zo,{children:e.jsx("title",{children:o!=null&&o.name?`${o.name} — A Message For You`:"Personal Video Message"})}),e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 to-slate-100",children:[e.jsx("header",{className:"border-b bg-white/80 backdrop-blur-sm",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-4 flex items-center gap-3",children:[(c==null?void 0:c.logo_url)&&e.jsx("img",{src:c.logo_url,alt:"",className:"h-8 object-contain"}),e.jsx("span",{className:"font-semibold text-sm",style:{color:d},children:(o==null?void 0:o.name)||"Recruiting"})]})}),e.jsxs("main",{className:"max-w-3xl mx-auto px-4 py-8 space-y-6",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsxs("h1",{className:"text-2xl font-bold text-foreground",children:["Hey ",u,", ",l==null?void 0:l.name," has a message for you"]}),i.message&&e.jsx("p",{className:"text-muted-foreground max-w-xl mx-auto",children:i.message})]}),h&&e.jsx("div",{className:"rounded-xl overflow-hidden shadow-xl bg-black",children:e.jsx("div",{style:{position:"relative",paddingTop:"56.25%"},children:e.jsx("iframe",{src:h,loading:"lazy",style:{border:0,position:"absolute",top:0,left:0,width:"100%",height:"100%"},allow:"accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0})})}),e.jsxs("div",{className:"bg-white rounded-xl shadow-sm border p-6 flex items-center gap-4",children:[l!=null&&l.avatar_url?e.jsx("img",{src:l.avatar_url,alt:"",className:"h-14 w-14 rounded-full object-cover"}):e.jsx("div",{className:"h-14 w-14 rounded-full flex items-center justify-center text-white text-lg font-bold",style:{backgroundColor:d},children:((_=l==null?void 0:l.name)==null?void 0:_.charAt(0))||"?"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("p",{className:"font-semibold",children:l==null?void 0:l.name}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[(l==null?void 0:l.title)||"Recruiter"," · ",o==null?void 0:o.name]})]})]}),(l==null?void 0:l.recruit_cta_url)&&e.jsx("div",{className:"text-center",children:e.jsx(B,{size:"lg",asChild:!0,className:"text-white shadow-lg hover:shadow-xl transition-shadow px-8",style:{backgroundColor:d},onClick:()=>{q.from("recruit_videos").update({cta_clicked_at:new Date().toISOString()}).eq("id",i.id).then(()=>{})},children:e.jsxs("a",{href:l.recruit_cta_url,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(yr,{className:"h-5 w-5 mr-2"})," Schedule a Conversation"]})})})]}),e.jsx("footer",{className:"text-center py-6 text-xs text-muted-foreground",children:"Powered by LevelUp"})]})]})}const Ctn="relzejiswnotikjgvjhz",hXe=`https://${Ctn}.supabase.co/functions/v1/recruit-unsubscribe`;function Ttn(){const[s]=xl(),t=s.get("token")||"",[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(""),[u,h]=N.useState({});N.useEffect(()=>{document.body.classList.add("recruit-unsubscribe-page");const f=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]','[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]",'div[id^="hubspot"]',".widget-visible"].forEach(j=>document.querySelectorAll(j).forEach(w=>w.style.display="none"))};f();const y=[setTimeout(f,500),setTimeout(f,1500),setTimeout(f,3e3)],_=new MutationObserver(f);return _.observe(document.body,{childList:!0,subtree:!0}),()=>{document.body.classList.remove("recruit-unsubscribe-page"),y.forEach(clearTimeout),_.disconnect()}},[]),N.useEffect(()=>{if(!t){h({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${hXe}?token=${encodeURIComponent(t)}`).then(async f=>{const y=await f.json();if(!f.ok)throw new Error(y.error||"Lookup failed");h(y),y.already_unsubscribed&&o(!0)}).catch(f=>h({error:f.message||"Could not load status"})).finally(()=>r(!1))},[t]);const p=async()=>{i(!0);try{const f=await fetch(hXe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t,reason:c.trim()||null})}),y=await f.json();if(!f.ok)throw new Error(y.error||"Failed");o(!0)}catch(f){h({...u,error:f.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(rs,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):u.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(Bi,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:u.error}),e.jsx("p",{className:"text-xs text-slate-400 pt-2",children:"If you continue to receive emails you don't want, please reply directly to one of them and we'll remove you immediately."})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(vr,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",u.first_name?`, ${u.first_name}`:""]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You won't receive any more recruiting emails from ",u.brokerage_name||"this brokerage",". Your conversation remains 100% confidential."]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400 pt-2",children:[e.jsx(eg,{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(eg,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe",u.first_name?`, ${u.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll be removed from ",u.brokerage_name||"this brokerage","'s recruiting emails immediately. Everything stays confidential."]}),u.email&&e.jsx("p",{className:"text-xs text-slate-400",children:u.email})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"reason",className:"text-xs text-slate-500",children:"Optional — what's the main reason? (helps us improve)"}),e.jsx(Ms,{id:"reason",value:c,onChange:f=>d(f.target.value),placeholder:"e.g. Not currently looking, too many emails, already moved…",rows:3,className:"resize-none"})]}),e.jsx(B,{onClick:p,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Confirm Unsubscribe"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. We process your request instantly."})]})})})}const Etn="relzejiswnotikjgvjhz",mXe=`https://${Etn}.supabase.co/functions/v1/event-invite-unsubscribe`;function Atn(){const[s]=xl(),t=s.get("token")||"",[n,r]=N.useState(!0),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState({});N.useEffect(()=>(document.body.classList.add("event-invite-unsubscribe-page"),()=>{document.body.classList.remove("event-invite-unsubscribe-page")}),[]),N.useEffect(()=>{if(!t){d({error:"Missing unsubscribe token in link."}),r(!1);return}fetch(`${mXe}?token=${encodeURIComponent(t)}`).then(async h=>{const p=await h.json();if(!h.ok)throw new Error(p.error||"Lookup failed");d(p),p.already_unsubscribed&&o(!0)}).catch(h=>d({error:h.message||"Could not load status"})).finally(()=>r(!1))},[t]);const u=async()=>{i(!0);try{const h=await fetch(mXe,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({token:t})}),p=await h.json();if(!h.ok)throw new Error(p.error||"Failed");o(!0)}catch(h){d({...c,error:h.message||"Could not unsubscribe"})}finally{i(!1)}};return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsx("div",{className:"w-full max-w-lg bg-white rounded-2xl shadow-xl border border-slate-200 p-8 sm:p-10",children:n?e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 gap-3 text-slate-500",children:[e.jsx(rs,{className:"h-8 w-8 animate-spin"}),e.jsx("p",{className:"text-sm",children:"Loading…"})]}):c.error?e.jsxs("div",{className:"text-center space-y-3",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-red-50 flex items-center justify-center",children:e.jsx(Bi,{className:"h-7 w-7 text-red-500"})}),e.jsx("h1",{className:"text-xl font-semibold text-slate-800",children:"Link Invalid"}),e.jsx("p",{className:"text-sm text-slate-500",children:c.error})]}):l?e.jsxs("div",{className:"text-center space-y-4",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-emerald-50 flex items-center justify-center",children:e.jsx(vr,{className:"h-7 w-7 text-emerald-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["You're unsubscribed",c.first_name?`, ${c.first_name}`:""]}),e.jsx("p",{className:"text-sm text-slate-500",children:"You won't receive event invite emails from LevelUp anymore."}),e.jsxs("div",{className:"mt-4 rounded-xl bg-slate-50 border border-slate-200 p-4 text-left",children:[e.jsx("p",{className:"text-sm font-medium text-slate-800 mb-1",children:"You'll still get:"}),e.jsxs("ul",{className:"text-sm text-slate-600 space-y-1 list-disc list-inside",children:[e.jsx("li",{children:"The Monday weekly digest"}),e.jsx("li",{children:"Account & billing notifications"}),e.jsx("li",{children:"Anything you directly requested"})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 text-xs text-slate-400 pt-2",children:[e.jsx(eg,{className:"h-3.5 w-3.5"}),"Preference saved · You can turn this back on anytime in your Profile."]})]}):e.jsxs("div",{className:"space-y-5",children:[e.jsxs("div",{className:"text-center space-y-2",children:[e.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-slate-100 flex items-center justify-center",children:e.jsx(z7,{className:"h-7 w-7 text-slate-500"})}),e.jsxs("h1",{className:"text-xl font-semibold text-slate-800",children:["Unsubscribe from event invites",c.first_name?`, ${c.first_name}`:"","?"]}),e.jsxs("p",{className:"text-sm text-slate-500",children:["You'll stop receiving event invite emails from LevelUp. Your ",e.jsx("span",{className:"font-medium text-slate-700",children:"Monday weekly digest"})," will keep coming."]}),c.email&&e.jsx("p",{className:"text-xs text-slate-400",children:c.email})]}),e.jsx(B,{onClick:u,disabled:a,className:"w-full h-11",variant:"default",children:a?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Unsubscribing…"]}):"Unsubscribe from event invites only"}),e.jsx("p",{className:"text-[11px] text-slate-400 text-center",children:"No login required. You can re-enable event invites anytime in your Profile."})]})})})}function Mtn(){const s=Ln(),t=Kt(),{isAdmin:n}=vs(),[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState(null),{data:d,isLoading:u}=dt({queryKey:["my-social-accounts"],queryFn:async()=>{const{data:{user:E},error:O}=await q.auth.getUser();if(O)throw O;if(!E)return[];const{data:D,error:I}=await q.from("social_accounts").select("*").eq("user_id",E.id).order("created_at",{ascending:!1});if(I)throw I;return D}}),h=yt({mutationFn:async E=>{const{data:{user:O},error:D}=await q.auth.getUser();if(D)throw D;if(!O)throw new Error("Not authenticated");const{error:I}=await q.from("social_accounts").delete().eq("id",E).eq("user_id",O.id);if(I)throw I},onSuccess:()=>{t.invalidateQueries({queryKey:["my-social-accounts"]}),t.invalidateQueries({queryKey:["social-accounts-for-post"]}),ae.success("Account disconnected successfully")},onError:()=>{ae.error("Failed to disconnect account")}}),p=async E=>{a(!0);try{const{data:O,error:D}=await q.functions.invoke("meta-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/callback",authMode:E}});if(D)throw D;if(O!=null&&O.authUrl)window.location.href=O.authUrl;else throw new Error("Failed to get authorization URL")}catch(O){console.error("Meta OAuth error:",O),ae.error("Failed to start connection. Please try again."),a(!1)}},f=async()=>{a(!0);try{const{data:E,error:O}=await q.functions.invoke("linkedin-oauth",{body:{action:"get_auth_url",callbackPath:"/social-connections/linkedin-callback"}});if(O)throw O;if(E!=null&&E.authUrl)window.location.href=E.authUrl;else throw new Error("Failed to get LinkedIn authorization URL")}catch(E){console.error("LinkedIn OAuth error:",E),ae.error("Failed to start LinkedIn connection. Please try again."),a(!1)}},y=async()=>{a(!0);try{const{data:E,error:O}=await q.functions.invoke("google-business-oauth",{body:{action:"get_auth_url"}});if(O)throw O;if(E!=null&&E.authUrl)window.location.href=E.authUrl;else throw new Error("Failed to get Google authorization URL")}catch(E){console.error("Google OAuth error:",E),ae.error("Failed to start Google connection. Please try again."),a(!1)}},_=(d==null?void 0:d.filter(E=>E.platform==="facebook"))||[],v=(d==null?void 0:d.filter(E=>E.platform==="instagram"))||[],j=(d==null?void 0:d.filter(E=>E.platform==="linkedin"))||[],w=(d==null?void 0:d.filter(E=>E.platform==="google_business"))||[],S=((d==null?void 0:d.length)||0)>0,A=async(E,O)=>{l(E),c(null);try{const{data:D,error:I}=await q.functions.invoke("meta-api-test",{body:{testType:"all",accountId:E}});if(I)throw I;c(D.results||[]),ae.success(D.summary||"API tests completed")}catch(D){console.error("Meta API test error:",D),ae.error("Failed to run API tests")}finally{l(null)}};return e.jsx(Cs,{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(Ue,{variant:"secondary",className:"bg-white/20 text-white border-0 backdrop-blur-sm",children:[e.jsx(un,{className:"h-3 w-3 mr-1"}),"Post directly from Social Swag"]})}),e.jsx("h1",{className:"text-2xl md:text-3xl font-bold mb-2",children:"Connect Your Social Accounts"}),e.jsx("p",{className:"text-white/90 max-w-xl",children:"Link your Facebook Pages and Instagram Business accounts to post content directly from Social Swag with one click."})]})]}),e.jsxs(B,{variant:"ghost",onClick:()=>s("/social-swag-2"),className:"gap-2",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back to Social Swag"]}),S&&e.jsx(fe,{className:"border-green-200 bg-green-50 dark:bg-green-950/20 dark:border-green-900",children:e.jsxs(Ee,{className:"flex items-center gap-4 p-4",children:[e.jsx("div",{className:"rounded-full bg-green-500 p-2",children:e.jsx(Pi,{className:"h-5 w-5 text-white"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-green-800 dark:text-green-200",children:"You're all set!"}),e.jsx("p",{className:"text-sm text-green-600 dark:text-green-400",children:"You can now post directly to your connected accounts from Social Swag."})]})]})}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2 lg:grid-cols-3",children:[e.jsxs(fe,{children:[e.jsx(It,{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(Mh,{className:"h-6 w-6 text-blue-600"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:"Facebook"}),e.jsx(Vn,{children:"Connect your Facebook Pages"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ei,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):_.length>0?e.jsx("div",{className:"space-y-3",children:_.map(E=>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(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:E.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(Mh,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:E.page_name||E.platform_username||"Facebook Page"}),e.jsx(Ue,{variant:E.is_active?"default":"secondary",className:"text-xs",children:E.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Facebook?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>h.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Facebook pages connected yet"}),e.jsxs(B,{onClick:()=>p("facebook"),disabled:r,className:"w-full gap-2",variant:_.length>0?"outline":"default",children:[r?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),_.length>0?"Connect Another Page":"Connect Facebook Page"]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{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(ou,{className:"h-6 w-6 text-pink-600"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:"Instagram"}),e.jsx(Vn,{children:"Connect Instagram Business accounts"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ei,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):v.length>0?e.jsx("div",{className:"space-y-3",children:v.map(E=>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(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:E.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(ou,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsxs("p",{className:"font-medium",children:["@",E.platform_username||"Instagram Account"]}),e.jsx(Ue,{variant:E.is_active?"default":"secondary",className:"text-xs",children:E.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Instagram?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>h.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No Instagram accounts connected yet"}),e.jsxs(B,{onClick:()=>p("instagram"),disabled:r,className:"w-full gap-2",variant:v.length>0?"outline":"default",children:[r?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),v.length>0?"Connect Another Account":"Connect Instagram Professional"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Use Instagram login for Business or Creator accounts; Facebook Page login is only needed if you want to connect Pages."})]})]}),e.jsxs(fe,{children:[e.jsx(It,{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(xf,{className:"h-6 w-6 text-blue-700"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:"LinkedIn"}),e.jsx(Vn,{children:"Connect your LinkedIn profile"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ei,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):j.length>0?e.jsx("div",{className:"space-y-3",children:j.map(E=>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(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:E.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(xf,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:E.platform_username||"LinkedIn Account"}),e.jsx(Ue,{variant:E.is_active?"default":"secondary",className:"text-xs",children:E.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect LinkedIn?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>h.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:"No LinkedIn account connected yet"}),e.jsxs(B,{onClick:f,disabled:r,className:"w-full gap-2",variant:j.length>0?"outline":"default",children:[r?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),j.length>0?"Reconnect LinkedIn":"Connect LinkedIn"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Share content directly to your LinkedIn profile"})]})]}),e.jsxs(fe,{className:`relative overflow-hidden ${n?"":"opacity-75"}`,children:[!n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Ue,{variant:"secondary",className:"bg-amber-100 text-amber-800 dark:bg-amber-900/30 dark:text-amber-400",children:"Coming Soon"})}),n&&e.jsx("div",{className:"absolute top-3 right-3 z-10",children:e.jsx(Ue,{variant:"secondary",className:"bg-green-100 text-green-800 dark:bg-green-900/30 dark:text-green-400",children:"Admin Testing"})}),e.jsx(It,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-red-500/10 p-3",children:e.jsx(ka,{className:"h-6 w-6 text-red-600"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:"Google Business"}),e.jsx(Vn,{children:"Connect your Google Business Profile"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[u?e.jsx("div",{className:"flex items-center justify-center py-8",children:e.jsx(Ei,{className:"h-6 w-6 animate-spin text-muted-foreground"})}):w.length>0?e.jsx("div",{className:"space-y-3",children:w.map(E=>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(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:E.profile_picture_url||""}),e.jsx(ea,{children:e.jsx(ka,{className:"h-5 w-5"})})]}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:E.page_name||E.platform_username||"Google Business"}),e.jsx(Ue,{variant:E.is_active?"default":"secondary",className:"text-xs",children:E.is_active?"Connected":"Inactive"})]})]}),e.jsxs(Oo,{children:[e.jsx(Eh,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})}),e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Disconnect Google Business?"}),e.jsx(Mo,{children:"This will remove the connection. You'll need to reconnect to post content."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>h.mutate(E.id),className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:"Disconnect"})]})]})]})]},E.id))}):e.jsx("p",{className:"text-sm text-muted-foreground py-4 text-center",children:n?"No Google Business account connected yet":"Google Business Profile integration is coming soon!"}),e.jsxs(B,{onClick:n?y:void 0,disabled:!n||r,className:"w-full gap-2",variant:w.length>0?"outline":"default",children:[r?e.jsx(Ei,{className:"h-4 w-4 animate-spin"}):e.jsx(Is,{className:"h-4 w-4"}),w.length>0?"Reconnect Google Business":"Connect Google Business"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Post updates directly to your Google Business Profile"})]})]})]}),n&&(_.length>0||v.length>0)&&e.jsxs(fe,{className:"border-amber-200 bg-amber-50 dark:bg-amber-950/20 dark:border-amber-900",children:[e.jsx(It,{children:e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"rounded-full bg-amber-500/10 p-3",children:e.jsx(qS,{className:"h-6 w-6 text-amber-600"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-lg",children:"Meta API Testing (Admin Only)"}),e.jsx(Vn,{children:"Run API tests to trigger all required permissions for Meta App Review"})]})]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("p",{className:"text-sm text-muted-foreground",children:['Click "Run Tests" on an account to trigger API calls for: ',e.jsx("strong",{children:"public_profile"}),", ",e.jsx("strong",{children:"pages_show_list"}),", ",e.jsx("strong",{children:"pages_read_engagement"}),", ",e.jsx("strong",{children:"instagram_basic"}),", ",e.jsx("strong",{children:"pages_manage_posts"}),", and ",e.jsx("strong",{children:"instagram_content_publish"}),"."]}),e.jsxs("div",{className:"space-y-3",children:[_.map(E=>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(Mh,{className:"h-5 w-5 text-blue-600"}),e.jsx("span",{className:"font-medium",children:E.page_name||"Facebook Page"})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(E.id),disabled:i===E.id,children:i===E.id?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qS,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-fb-${E.id}`)),v.map(E=>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(ou,{className:"h-5 w-5 text-pink-600"}),e.jsxs("span",{className:"font-medium",children:["@",E.platform_username||"Instagram"]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>A(E.id),disabled:i===E.id,children:i===E.id?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Testing..."]}):e.jsxs(e.Fragment,{children:[e.jsx(qS,{className:"h-4 w-4 mr-2"}),"Run Tests"]})})]},`test-ig-${E.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((E,O)=>e.jsxs("div",{className:"flex items-start gap-2 text-sm",children:[E.status==="success"?e.jsx(vr,{className:"h-4 w-4 text-green-600 mt-0.5 shrink-0"}):E.status==="pending"?e.jsx(rs,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}):e.jsx(Uc,{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:E.test}),e.jsx("span",{className:"ml-2 text-muted-foreground",children:E.details})]})]},O))})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Note: Facebook posts are auto-deleted. Instagram posts will remain and should be manually deleted. Allow up to 24 hours for Meta to register the API calls."})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-lg",children:"How it works"})}),e.jsx(Ee,{children:e.jsxs("div",{className:"grid gap-4 md:grid-cols-3",children:[e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"1"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Connect your accounts"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Link your Facebook, Instagram, or LinkedIn account"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"2"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Browse Social Swag"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Find the perfect image and caption for your post"})]})]}),e.jsxs("div",{className:"flex gap-3",children:[e.jsx("div",{className:"flex h-8 w-8 shrink-0 items-center justify-center rounded-full bg-primary text-primary-foreground text-sm font-medium",children:"3"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Post with one click"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:'Click "Create Post" to share directly to your accounts'})]})]})]})})]})]})})}function Itn(){const[s]=xl(),t=Ln(),[n,r]=N.useState("loading"),[a,i]=N.useState("Processing your connection...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("meta-oauth",{body:{action:"exchange_code",code:o,state:u,callbackPath:"/social-connections/callback"}});if(f)throw f;if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||0} account(s)!`),ae.success("Social accounts connected successfully!");else throw new Error((p==null?void 0:p.error)||"Unknown error")}catch(p){console.error("OAuth callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect accounts"),ae.error("Failed to connect: "+(p instanceof Error?p.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{className:"text-center",children:[n==="loading"&&e.jsx(rs,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Pi,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Uc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Rt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/mission-control/integrations"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function Ptn(){const[s]=xl(),t=Ln(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your Google Business Profile...");return N.useEffect(()=>{(async()=>{const o=s.get("code"),c=s.get("error"),d=s.get("error_description"),u=s.get("state");if(c){r("error"),i(d||"Authorization was denied"),ae.error("Connection failed: "+(d||c));return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:h,error:p}=await q.functions.invoke("google-business-oauth",{body:{action:"exchange_code",code:o,state:u}});if(p)throw p;if(h!=null&&h.success)r("success"),i(h.message||"Successfully connected Google Business Profile!"),ae.success("Google Business Profile connected!");else throw new Error((h==null?void 0:h.error)||"Unknown error")}catch(h){console.error("Google OAuth callback error:",h),r("error"),i(h instanceof Error?h.message:"Failed to connect Google Business Profile"),ae.error("Failed to connect: "+(h instanceof Error?h.message:"Unknown error"))}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background p-4",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{className:"text-center",children:[n==="loading"&&e.jsx(rs,{className:"h-12 w-12 animate-spin mx-auto text-primary"}),n==="success"&&e.jsx(Pi,{className:"h-12 w-12 mx-auto text-green-500"}),n==="error"&&e.jsx(Uc,{className:"h-12 w-12 mx-auto text-destructive"}),e.jsxs(Rt,{className:"mt-4",children:[n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:n!=="loading"&&e.jsx(B,{onClick:()=>t("/social-connections"),children:n==="success"?"View Connected Accounts":"Try Again"})})]})})}function Ltn(){const[s]=xl(),t=Ln(),[n,r]=N.useState("loading"),[a,i]=N.useState("Connecting your LinkedIn account...");return N.useEffect(()=>{(async()=>{var h;const o=s.get("code"),c=s.get("state"),d=s.get("error"),u=s.get("error_description");if(d){console.error("LinkedIn OAuth error:",d,u),r("error"),i(u||"Failed to connect LinkedIn account"),ae.error(u||"Failed to connect LinkedIn");return}if(!o){r("error"),i("No authorization code received"),ae.error("No authorization code received");return}try{const{data:p,error:f}=await q.functions.invoke("linkedin-oauth",{body:{action:"exchange_code",code:o,state:c,callbackPath:"/social-connections/linkedin-callback"}});if(f)throw f;if(p!=null&&p.success)r("success"),i(`Successfully connected ${((h=p.accounts)==null?void 0:h.length)||1} LinkedIn account`),ae.success("LinkedIn connected successfully!");else throw new Error((p==null?void 0:p.error)||"Failed to connect LinkedIn account")}catch(p){console.error("LinkedIn callback error:",p),r("error"),i(p instanceof Error?p.message:"Failed to connect LinkedIn account"),ae.error("Failed to connect LinkedIn")}})()},[s]),e.jsx("div",{className:"min-h-screen flex items-center justify-center p-4 bg-background",children:e.jsxs(fe,{className:"w-full max-w-md",children:[e.jsxs(It,{className:"text-center",children:[e.jsxs("div",{className:"mx-auto mb-4 rounded-full bg-blue-600/10 p-4 w-fit",children:[n==="loading"&&e.jsx(rs,{className:"h-8 w-8 animate-spin text-blue-600"}),n==="success"&&e.jsx(Pi,{className:"h-8 w-8 text-green-600"}),n==="error"&&e.jsx(Uc,{className:"h-8 w-8 text-red-600"})]}),e.jsxs(Rt,{className:"flex items-center justify-center gap-2",children:[e.jsx(xf,{className:"h-5 w-5 text-blue-600"}),n==="loading"&&"Connecting...",n==="success"&&"Connected!",n==="error"&&"Connection Failed"]}),e.jsx(Vn,{children:a})]}),e.jsx(Ee,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/mission-control/integrations"),disabled:n==="loading",children:n==="success"?"View Integrations":"Back to Integrations"})})]})})}function Dtn(){const s=Ln(),[t,n]=N.useState(null),{data:r,isLoading:a}=w2t(t||void 0,!0),{data:i,isLoading:l}=r8e(!0),{cartItems:o}=Sye(),c=o.reduce((u,h)=>u+h.quantity,0),d=u=>{s(`/marketplace/${u.id}`)};return a||l?e.jsx(Cs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[1,2,3].map(u=>e.jsx(Ws,{className:"h-10 w-24 flex-shrink-0"},u))}),e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:[1,2,3,4].map(u=>e.jsx(Ws,{className:"h-72 w-full"},u))})]})}):e.jsx(Cs,{title:"Marketplace",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Marketplace"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Shop exclusive products for LevelUp members"})]}),e.jsxs(B,{variant:"outline",onClick:()=>s("/marketplace/cart"),className:"relative",children:[e.jsx(Dg,{className:"h-4 w-4 mr-2"}),"Cart",c>0&&e.jsx(Ue,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:c})]})]}),i&&i.length>0&&e.jsxs("div",{className:"flex gap-2 overflow-x-auto pb-2",children:[e.jsx(B,{variant:t===null?"default":"outline",size:"sm",onClick:()=>n(null),children:"All"}),i.map(u=>e.jsx(B,{variant:t===u.id?"default":"outline",size:"sm",onClick:()=>n(u.id),children:u.name},u.id))]}),r&&r.length>0?e.jsx("div",{className:"grid gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4",children:r.map(u=>{var h;return e.jsxs(fe,{className:"overflow-hidden cursor-pointer hover:shadow-lg transition-shadow",onClick:()=>d(u),children:[e.jsxs("div",{className:"aspect-square bg-muted relative",children:[u.images&&u.images.length>0?e.jsx("img",{src:((h=u.images.find(p=>p.is_primary))==null?void 0:h.image_url)||u.images[0].image_url,alt:u.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Ec,{className:"h-12 w-12 text-muted-foreground"})}),u.category&&e.jsx(Ue,{className:"absolute top-2 left-2",variant:"secondary",children:u.category.name})]}),e.jsxs(Ee,{className:"p-4",children:[e.jsx("h3",{className:"font-semibold mb-1 line-clamp-1",children:u.name}),u.description&&e.jsx("p",{className:"text-sm text-muted-foreground mb-2 line-clamp-2",children:u.description}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("span",{className:"font-bold text-lg",children:["$",Number(u.base_price).toFixed(2)]}),u.variants&&u.variants.length>0&&e.jsxs("span",{className:"text-xs text-muted-foreground",children:[u.variants.length," options"]})]})]})]},u.id)})}):e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ec,{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 Z2t=N.forwardRef(({...s},t)=>e.jsx("nav",{ref:t,"aria-label":"breadcrumb",...s}));Z2t.displayName="Breadcrumb";const Q2t=N.forwardRef(({className:s,...t},n)=>e.jsx("ol",{ref:n,className:Mt("flex flex-wrap items-center gap-1.5 break-words text-sm text-muted-foreground sm:gap-2.5",s),...t}));Q2t.displayName="BreadcrumbList";const Kme=N.forwardRef(({className:s,...t},n)=>e.jsx("li",{ref:n,className:Mt("inline-flex items-center gap-1.5",s),...t}));Kme.displayName="BreadcrumbItem";const lTe=N.forwardRef(({asChild:s,className:t,...n},r)=>{const a=s?BEe:"a";return e.jsx(a,{ref:r,className:Mt("transition-colors hover:text-foreground",t),...n})});lTe.displayName="BreadcrumbLink";const X2t=N.forwardRef(({className:s,...t},n)=>e.jsx("span",{ref:n,role:"link","aria-disabled":"true","aria-current":"page",className:Mt("font-normal text-foreground",s),...t}));X2t.displayName="BreadcrumbPage";const cTe=({children:s,className:t,...n})=>e.jsx("li",{role:"presentation","aria-hidden":"true",className:Mt("[&>svg]:size-3.5",t),...n,children:s??e.jsx(ga,{})});cTe.displayName="BreadcrumbSeparator";function Rtn(){var Y,W;const{productId:s}=bi(),t=Ln(),{data:n,isLoading:r}=TJs(s||""),{addToCart:a,cartItems:i}=Sye(),[l,o]=N.useState(null),[c,d]=N.useState(1),[u,h]=N.useState(0),[p,f]=N.useState(null),[y,_]=N.useState(!1),[v,j]=N.useState(!1),w=(Y=n==null?void 0:n.variants)==null?void 0:Y.find(ee=>ee.id===l),S=((W=n==null?void 0:n.variants)==null?void 0:W.filter(ee=>ee.is_active))||[],A=Number((n==null?void 0:n.base_price)||0),E=w?Number(w.price_adjustment):0,O=A+E,D=Number((n==null?void 0:n.shipping_fee)||0),I=i.reduce((ee,se)=>ee+se.quantity,0),F=async ee=>{if(!ee.target.files||ee.target.files.length===0)return;_(!0);const se=ee.target.files[0],oe=se.name.split(".").pop(),he=`artwork/${Date.now()}-${Math.random().toString(36).substring(7)}.${oe}`;try{const{error:ce}=await q.storage.from("marketplace").upload(he,se);if(ce)throw ce;const{data:{publicUrl:me}}=q.storage.from("marketplace").getPublicUrl(he);f(me),ae.success("Artwork uploaded successfully")}catch(ce){ae.error("Failed to upload artwork: "+ce.message)}finally{_(!1)}},z=()=>{if(n){if(S.length>0&&!l){ae.error("Please select an option");return}a(n,w||void 0,c,p||void 0),j(!0),ae.success("Added to cart!"),setTimeout(()=>j(!1),2e3)}},H=()=>{n!=null&&n.images&&h(ee=>(ee+1)%n.images.length)},Z=()=>{n!=null&&n.images&&h(ee=>(ee-1+n.images.length)%n.images.length)};return r?e.jsx(Cs,{title:"Product",children:e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsx(Ws,{className:"aspect-square w-full"}),e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-3/4"}),e.jsx(Ws,{className:"h-6 w-1/4"}),e.jsx(Ws,{className:"h-24 w-full"}),e.jsx(Ws,{className:"h-12 w-full"})]})]})}):n?e.jsxs(Cs,{title:n.name,children:[e.jsx(Z2t,{className:"mb-6",children:e.jsxs(Q2t,{children:[e.jsx(Kme,{children:e.jsx(lTe,{asChild:!0,children:e.jsx(In,{to:"/marketplace",children:"Marketplace"})})}),n.category&&e.jsxs(e.Fragment,{children:[e.jsx(cTe,{}),e.jsx(Kme,{children:e.jsx(lTe,{asChild:!0,children:e.jsx(In,{to:`/marketplace?category=${n.category.id}`,children:n.category.name})})})]}),e.jsx(cTe,{}),e.jsx(Kme,{children:e.jsx(X2t,{children:n.name})})]})}),e.jsxs("div",{className:"grid gap-8 lg:grid-cols-2",children:[e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"relative aspect-square bg-muted rounded-lg overflow-hidden flex items-center justify-center",children:n.images&&n.images.length>0?e.jsxs(e.Fragment,{children:[e.jsx("img",{src:n.images[u].image_url,alt:n.name,className:"max-w-full max-h-full object-contain"}),n.images.length>1&&e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"ghost",size:"icon",className:"absolute left-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:Z,children:e.jsx(ml,{className:"h-6 w-6"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"absolute right-2 top-1/2 -translate-y-1/2 bg-background/80 hover:bg-background",onClick:H,children:e.jsx(ga,{className:"h-6 w-6"})})]})]}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(Ec,{className:"h-24 w-24 text-muted-foreground"})})}),n.images&&n.images.length>1&&e.jsx("div",{className:"flex gap-2 overflow-x-auto pb-2",children:n.images.map((ee,se)=>e.jsx("button",{onClick:()=>h(se),className:`w-16 h-16 flex-shrink-0 rounded-md overflow-hidden border-2 ${se===u?"border-primary":"border-transparent"}`,children:e.jsx("img",{src:ee.image_url,alt:"",className:"w-full h-full object-cover"})},ee.id))}),n.video&&e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("h4",{className:"font-medium mb-2",children:"Product Video"}),e.jsx("div",{className:"aspect-video",children:e.jsx("iframe",{src:n.video.video_url,className:"w-full h-full rounded-lg",allowFullScreen:!0})})]})})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[n.category&&e.jsx(Ue,{variant:"secondary",className:"mb-2",children:n.category.name}),e.jsx("h1",{className:"text-3xl font-bold mb-2",children:n.name}),e.jsxs("div",{className:"flex items-baseline gap-2",children:[e.jsxs("span",{className:"text-3xl font-bold",children:["$",O.toFixed(2)]}),D>0&&e.jsxs("span",{className:"text-muted-foreground",children:["+ $",D.toFixed(2)," shipping"]})]})]}),n.description&&e.jsx("div",{className:"prose prose-sm max-w-none",children:e.jsx("p",{className:"text-muted-foreground whitespace-pre-wrap",children:n.description})}),S.length>0&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{children:"Select Option"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:S.map(ee=>e.jsxs(B,{variant:l===ee.id?"default":"outline",onClick:()=>o(ee.id),children:[ee.name,Number(ee.price_adjustment)!==0&&e.jsxs("span",{className:"ml-1 opacity-70",children:["(",Number(ee.price_adjustment)>0?"+":"","$",Number(ee.price_adjustment).toFixed(2),")"]})]},ee.id))})]}),n.allow_artwork_upload&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{children:"Upload Your Artwork (Optional)"}),p?e.jsxs("div",{className:"relative inline-block",children:[e.jsx("img",{src:p,alt:"Your artwork",className:"h-24 w-auto rounded-lg border"}),e.jsx(B,{variant:"ghost",size:"sm",className:"absolute -top-2 -right-2",onClick:()=>f(null),children:"×"})]}):e.jsxs("div",{className:"border-2 border-dashed rounded-lg p-6",children:[e.jsx("input",{type:"file",accept:"image/*,.pdf,.ai,.eps",onChange:F,className:"hidden",id:"artwork-upload",disabled:y}),e.jsxs("label",{htmlFor:"artwork-upload",className:"flex flex-col items-center cursor-pointer",children:[e.jsx(_a,{className:"h-8 w-8 text-muted-foreground mb-2"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:y?"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(ne,{children:"Quantity"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(ee=>Math.max(1,ee-1)),children:"-"}),e.jsx(ye,{type:"number",value:c,onChange:ee=>d(Math.max(1,parseInt(ee.target.value)||1)),className:"w-20 text-center",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",onClick:()=>d(ee=>ee+1),children:"+"})]})]}),e.jsxs("div",{className:"flex gap-4",children:[e.jsx(B,{size:"lg",className:"flex-1",onClick:z,disabled:v,children:v?e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-5 w-5 mr-2"}),"Added!"]}):e.jsxs(e.Fragment,{children:[e.jsx(Dg,{className:"h-5 w-5 mr-2"}),"Add to Cart"]})}),e.jsxs(B,{variant:"outline",size:"lg",onClick:()=>t("/marketplace/cart"),className:"relative",children:[e.jsx(Dg,{className:"h-5 w-5"}),I>0&&e.jsx(Ue,{className:"absolute -top-2 -right-2 h-5 w-5 flex items-center justify-center p-0 text-xs",children:I})]})]}),n.requires_proof_approval&&e.jsx("p",{className:"text-sm text-muted-foreground bg-muted p-3 rounded-lg",children:"📋 This product requires proof approval before production. You'll receive a proof to review after your order is placed."})]})]})]}):e.jsx(Cs,{title:"Product Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ec,{className:"h-12 w-12 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Product not found"}),e.jsx(B,{onClick:()=>t("/marketplace"),children:"Back to Marketplace"})]})})}function Otn(){const s=Ln(),{cartItems:t,removeFromCart:n,updateQuantity:r,getItemPrice:a,getSubtotal:i,getShippingTotal:l,getTotal:o,clearCart:c}=Sye(),[d,u]=N.useState(!1),[h,p]=N.useState(""),f=async()=>{if(t.length===0){ae.error("Your cart is empty");return}u(!0);try{const{data:y,error:_}=await q.functions.invoke("marketplace-checkout",{body:{items:t.map(v=>{var j;return{product_id:v.product.id,variant_id:((j=v.variant)==null?void 0:j.id)||null,quantity:v.quantity,artwork_url:v.artworkUrl||null}}),notes:h.trim()||null}});if(_)throw _;if(y!=null&&y.url)c(),window.open(y.url,"_blank");else throw new Error("No checkout URL received")}catch(y){ae.error("Checkout failed: "+y.message)}finally{u(!1)}};return t.length===0?e.jsx(Cs,{title:"Shopping Cart",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(yw,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your cart is empty"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Add some products to get started!"}),e.jsx(B,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Cs,{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(y=>{var _,v;return e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex gap-4",children:[e.jsx("div",{className:"w-24 h-24 flex-shrink-0 bg-muted rounded-lg overflow-hidden",children:y.product.images&&y.product.images.length>0?e.jsx("img",{src:((_=y.product.images.find(j=>j.is_primary))==null?void 0:_.image_url)||y.product.images[0].image_url,alt:y.product.name,className:"w-full h-full object-cover"}):e.jsx("div",{className:"flex items-center justify-center h-full",children:e.jsx(yw,{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:y.product.name}),y.variant&&e.jsx("p",{className:"text-sm text-muted-foreground",children:y.variant.name}),e.jsxs("p",{className:"font-medium mt-1",children:["$",a(y).toFixed(2),Number(y.product.shipping_fee)>0&&e.jsxs("span",{className:"text-sm text-muted-foreground ml-2",children:["+ $",Number(y.product.shipping_fee).toFixed(2)," shipping"]})]}),y.artworkUrl&&e.jsx("div",{className:"mt-2",children:e.jsx("span",{className:"text-xs text-muted-foreground",children:"Artwork uploaded ✓"})})]}),e.jsxs("div",{className:"flex flex-col items-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return n(y.product.id,(j=y.variant)==null?void 0:j.id)},children:e.jsx(_n,{className:"h-4 w-4 text-destructive"})}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return r(y.product.id,(j=y.variant)==null?void 0:j.id,y.quantity-1)},disabled:y.quantity<=1,children:e.jsx(hb,{className:"h-3 w-3"})}),e.jsx(ye,{type:"number",value:y.quantity,onChange:j=>{var w;return r(y.product.id,(w=y.variant)==null?void 0:w.id,parseInt(j.target.value)||1)},className:"w-14 h-8 text-center text-sm",min:"1"}),e.jsx(B,{variant:"outline",size:"icon",className:"h-8 w-8",onClick:()=>{var j;return r(y.product.id,(j=y.variant)==null?void 0:j.id,y.quantity+1)},children:e.jsx(Is,{className:"h-3 w-3"})})]})]})]})})},`${y.product.id}-${((v=y.variant)==null?void 0:v.id)||"base"}`)}),e.jsx(B,{variant:"ghost",className:"text-destructive",onClick:c,children:"Clear Cart"})]}),e.jsx("div",{children:e.jsxs(fe,{className:"sticky top-4",children:[e.jsx(It,{children:e.jsx(Rt,{children:"Order Summary"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsxs("span",{children:["Subtotal (",t.reduce((y,_)=>y+_.quantity,0)," items)"]}),e.jsxs("span",{children:["$",i().toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",l().toFixed(2)]})]}),e.jsx(al,{}),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(al,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"orderNotes",children:"Order Notes (Optional)"}),e.jsx(Ms,{id:"orderNotes",placeholder:"Add any special instructions, design notes, or comments for your order...",value:h,onChange:y=>p(y.target.value),rows:3,className:"resize-none"})]}),e.jsx(B,{className:"w-full",size:"lg",onClick:f,disabled:d,children:d?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-5 w-5 mr-2 animate-spin"}),"Processing..."]}):e.jsxs(e.Fragment,{children:["Checkout",e.jsx(Oa,{className:"h-5 w-5 ml-2"})]})}),e.jsx("p",{className:"text-xs text-center text-muted-foreground",children:"Secure checkout powered by Stripe"})]})]})})]})})}function Ftn(){const s=Ln(),{data:t,isLoading:n}=zJs();return n?e.jsx(Cs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:[1,2,3].map(r=>e.jsx(Ws,{className:"h-32 w-full"},r))})}):!t||t.length===0?e.jsx(Cs,{title:"My Orders",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ec,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"No orders yet"}),e.jsx("p",{className:"text-muted-foreground mb-6",children:"Start shopping to see your orders here!"}),e.jsx(B,{onClick:()=>s("/marketplace"),children:"Browse Marketplace"})]})}):e.jsx(Cs,{title:"My Orders",children:e.jsx("div",{className:"space-y-4",children:t.map(r=>{var a,i,l;return e.jsx(fe,{className:"cursor-pointer hover:shadow-md transition-shadow",onClick:()=>s(`/marketplace/orders/${r.id}`),children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:r.order_number}),e.jsx("span",{className:"text-muted-foreground text-sm ml-2",children:Ss(new Date(r.created_at),"MMM d, yyyy")})]}),e.jsx(Ue,{className:n8e[r.status],children:zL[r.status]})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("div",{className:"flex -space-x-2",children:[(a=r.items)==null?void 0:a.slice(0,3).map((o,c)=>e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",style:{zIndex:3-c},children:[o.quantity,"×"]},o.id)),r.items&&r.items.length>3&&e.jsxs("div",{className:"w-10 h-10 bg-muted rounded border-2 border-background flex items-center justify-center text-xs font-medium",children:["+",r.items.length-3]})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm",children:((i=r.items)==null?void 0:i.length)===1?r.items[0].product_name:`${(l=r.items)==null?void 0:l.length} items`}),e.jsxs("p",{className:"font-semibold",children:["$",Number(r.total).toFixed(2)]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[r.tracking_url&&e.jsxs(B,{variant:"outline",size:"sm",onClick:o=>{o.stopPropagation(),window.open(r.tracking_url,"_blank")},children:[e.jsx(tr,{className:"h-4 w-4 mr-1"}),"Track"]}),e.jsx(ga,{className:"h-5 w-5 text-muted-foreground"})]})]})]})},r.id)})})})}const pXe=["order_submitted","awaiting_proof_approval","proof_approved","processing","in_production","shipped","completed"];function ztn({currentStatus:s,statusHistory:t}){const n=pXe.indexOf(s);return e.jsx("div",{className:"space-y-3",children:pXe.map((r,a)=>{const i=t==null?void 0:t.find(d=>d.status===r),l=an;return e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:`mt-0.5 flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center ${l?"bg-green-500 text-white":o?"bg-primary text-primary-foreground":"bg-muted text-muted-foreground"}`,children:l?e.jsx(vr,{className:"h-4 w-4"}):o?e.jsx(pr,{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:zL[r]}),i&&e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Ss(new Date(i.created_at),"MMM d, yyyy h:mm a"),i.notes&&` — ${i.notes}`]})]})]},r)})})}function Btn(){var j;const{orderId:s}=bi(),t=Ln(),{data:n,isLoading:r,refetch:a}=BJs(s||""),i=qJs(),l=VJs(),[o,c]=N.useState(!1),[d,u]=N.useState(null),[h,p]=N.useState(""),[f,y]=N.useState(null),_=async w=>{y(w);try{await i.mutateAsync({orderId:s,itemId:w}),ae.success("Proof approved!"),a()}catch{ae.error("Failed to approve proof")}finally{y(null)}},v=async()=>{if(d){y(d);try{await l.mutateAsync({orderId:s,itemId:d,reason:h}),ae.success("Revision requested"),c(!1),p(""),u(null),a()}catch{ae.error("Failed to request revision")}finally{y(null)}}};return r?e.jsx(Cs,{title:"Order Details",children:e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-48 w-full"})]}),e.jsx(Ws,{className:"h-96 w-full"})]})}):n?e.jsxs(Cs,{title:`Order ${n.order_number}`,children:[e.jsxs("div",{className:"grid gap-6 lg:grid-cols-3",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsx(Rt,{children:"Order Status"}),e.jsx(Ue,{className:n8e[n.status],children:zL[n.status]})]}),e.jsx(Ee,{children:e.jsx(ztn,{currentStatus:n.status,statusHistory:n.status_history})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Items"})}),e.jsx(Ee,{className:"space-y-4",children:(j=n.items)==null?void 0:j.map(w=>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:w.product_name}),w.variant_name&&e.jsx("p",{className:"text-sm text-muted-foreground",children:w.variant_name}),e.jsxs("p",{className:"text-sm",children:["Qty: ",w.quantity," × $",Number(w.unit_price).toFixed(2)]})]}),e.jsxs("p",{className:"font-semibold",children:["$",(Number(w.unit_price)*w.quantity).toFixed(2)]})]}),w.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:w.artwork_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline",children:[e.jsx(q2,{className:"h-4 w-4"}),"View Artwork",e.jsx(tr,{className:"h-3 w-3"})]})]}),w.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:w.proof_url,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 text-primary hover:underline mb-3",children:[e.jsx(q2,{className:"h-4 w-4"}),"View Proof",e.jsx(tr,{className:"h-3 w-3"})]}),w.proof_status==="pending"&&e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",onClick:()=>_(w.id),disabled:f===w.id,children:[f===w.id?e.jsx(rs,{className:"h-4 w-4 mr-1 animate-spin"}):e.jsx($m,{className:"h-4 w-4 mr-1"}),"Approve"]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{u(w.id),c(!0)},disabled:f===w.id,children:[e.jsx(N9,{className:"h-4 w-4 mr-1"}),"Request Changes"]})]}),w.proof_status==="approved"&&e.jsxs(Ue,{className:"bg-green-100 text-green-800",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"}),"Proof Approved"]}),w.proof_status==="rejected"&&w.proof_notes&&e.jsxs("div",{className:"mt-2",children:[e.jsx(Ue,{variant:"destructive",className:"mb-2",children:"Revision Requested"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:w.proof_notes})]})]})]},w.id))})]}),n.shipping_name&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(S9,{className:"h-5 w-5"}),"Shipping"]})}),e.jsxs(Ee,{children:[e.jsx("p",{className:"font-medium",children:n.shipping_name}),e.jsxs("p",{className:"text-muted-foreground",children:[n.shipping_address,e.jsx("br",{}),n.shipping_city,", ",n.shipping_state," ",n.shipping_zip]}),n.tracking_number&&e.jsxs("div",{className:"mt-4 p-3 bg-muted rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Tracking Number:"}),e.jsx("p",{className:"font-mono font-medium",children:n.tracking_number}),n.tracking_url&&e.jsxs(B,{variant:"link",className:"p-0 h-auto mt-1",onClick:()=>window.open(n.tracking_url,"_blank"),children:["Track Package",e.jsx(tr,{className:"h-3 w-3 ml-1"})]})]})]})]})]}),e.jsx("div",{children:e.jsxs(fe,{className:"sticky top-4",children:[e.jsx(It,{children:e.jsx(Rt,{children:"Order Summary"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"text-sm text-muted-foreground",children:["Placed on ",Ss(new Date(n.created_at),"MMMM d, yyyy")]}),e.jsx(al,{}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Subtotal"}),e.jsxs("span",{children:["$",Number(n.subtotal).toFixed(2)]})]}),e.jsxs("div",{className:"flex justify-between text-sm",children:[e.jsx("span",{children:"Shipping"}),e.jsxs("span",{children:["$",Number(n.shipping_total).toFixed(2)]})]})]}),e.jsx(al,{}),e.jsxs("div",{className:"flex justify-between font-bold text-lg",children:[e.jsx("span",{children:"Total"}),e.jsxs("span",{children:["$",Number(n.total).toFixed(2)]})]}),n.notes&&e.jsxs(e.Fragment,{children:[e.jsx(al,{}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium mb-1",children:"Order Notes"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:n.notes})]})]})]})]})})]}),e.jsx(_s,{open:o,onOpenChange:c,children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Request Changes"}),e.jsx(Jn,{children:"Please describe what changes you'd like made to the proof."})]}),e.jsx(Ms,{placeholder:"Describe the changes needed...",value:h,onChange:w=>p(w.target.value),rows:4}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsxs(B,{onClick:v,disabled:!h.trim()||f!==null,children:[f?e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}):null,"Submit Request"]})]})]})})]}):e.jsx(Cs,{title:"Order Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx(Ec,{className:"h-16 w-16 mx-auto text-muted-foreground mb-4"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Order not found"}),e.jsx(B,{onClick:()=>t("/marketplace/orders"),children:"View All Orders"})]})})}function $tn(){const s=Ln(),[t]=xl();return t.get("session_id"),N.useEffect(()=>{localStorage.removeItem("marketplace-cart")},[]),e.jsx(Cs,{title:"Order Confirmed",children:e.jsx("div",{className:"max-w-lg mx-auto text-center py-8",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-8 pb-6",children:[e.jsx("div",{className:"w-16 h-16 bg-green-100 rounded-full flex items-center justify-center mx-auto mb-6",children:e.jsx(vr,{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(Ec,{className:"h-4 w-4"}),"What happens next?"]}),e.jsxs("ul",{className:"text-sm text-muted-foreground space-y-2",children:[e.jsx("li",{children:"• We'll review your order and prepare it for production"}),e.jsx("li",{children:"• If your order requires a proof, you'll receive it for approval"}),e.jsx("li",{children:"• Once approved, we'll begin production and ship when ready"}),e.jsx("li",{children:"• You'll receive tracking info when your order ships"})]})]}),e.jsxs("div",{className:"flex flex-col sm:flex-row gap-3",children:[e.jsxs(B,{className:"flex-1",onClick:()=>s("/marketplace/orders"),children:["View My Orders",e.jsx(Oa,{className:"h-4 w-4 ml-2"})]}),e.jsx(B,{variant:"outline",className:"flex-1",onClick:()=>s("/marketplace"),children:"Continue Shopping"})]})]})})})})}function Utn(){const{user:s}=vs(),[t,n]=N.useState("store"),[r,a]=N.useState(null),[i,l]=N.useState(null),[o,c]=N.useState(!1),[d,u]=N.useState(5),[h,p]=N.useState(""),[f,y]=N.useState(!1),[_,v]=N.useState(!1),[j,w]=N.useState(""),[S,A]=N.useState(null),[E,O]=N.useState(!1),{hasSubmittedReview:D,submitReview:I,markPostedToGoogle:F}=dmt(),{data:z}=N2t(),{data:H,isLoading:Z}=j2t(),{data:Y,isLoading:W}=QJs(r),{data:ee,isLoading:se}=XJs(s==null?void 0:s.id),{data:oe=0}=een(s==null?void 0:s.id),he=ten(),ce=new Set((ee==null?void 0:ee.map(Ce=>Ce.item_id))||[]),me=async()=>{if(i)try{const Ce=await he.mutateAsync(i.id);i.item_type==="reelflow_credits"?ae.success(`🎬 ${i.max_quantity} ReelFlow credits added to your balance!`):ae.success(`Successfully purchased "${i.name}"!`),l(null)}catch(Ce){ae.error(Ce.message||"Failed to purchase item")}},le=async()=>{if(!h.trim()){ae.error("Please write a review");return}y(!0);const Ce=await I(d,h);y(!1),Ce.success?(ae.success("Thank you for your review! You earned 25 points!"),w(h),v(!0),p(""),u(5)):ae.error(Ce.error||"Failed to submit review")},ve=()=>{navigator.clipboard.writeText(j),ae.success("Review copied to clipboard!")},ge=()=>{F(),window.open("https://g.page/r/CT8bqTBTm7nJEBM/review","_blank")},Te=()=>{v(!1),c(!1),w("")};return Z||W||se?e.jsx(Cs,{title:"Reward Store",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Ws,{className:"h-24 w-full"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(Ce=>e.jsx(Ws,{className:"h-64"},Ce))})]})}):e.jsxs(Cs,{title:"Reward Store",children:[e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-5xl font-bold text-foreground",children:"Reward Store"}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Redeem your points for exclusive rewards"})]}),e.jsx(fe,{className:"bg-gradient-to-r from-primary/10 to-primary/5 border-primary/20",children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-primary/20 flex items-center justify-center",children:e.jsx(oa,{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(xo,{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(Hc,{className:"h-4 w-4 text-orange-500"}),e.jsx("span",{children:"Streak bonuses add extra points!"})]})]})]})})}),e.jsx(oy,{open:E,onOpenChange:O,children:e.jsxs(fe,{className:"border-primary/20",children:[e.jsx(ly,{asChild:!0,children:e.jsx(It,{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(xo,{className:"h-5 w-5 text-primary"})}),e.jsxs("div",{children:[e.jsx(Rt,{className:"text-base",children:"How to Earn Points"}),e.jsx(Vn,{children:"See all the ways you can earn spendable points"})]})]}),E?e.jsx(ex,{className:"h-5 w-5 text-muted-foreground"}):e.jsx(ao,{className:"h-5 w-5 text-muted-foreground"})]})})}),e.jsx(cy,{children:e.jsx(Ee,{className:"pt-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3",children:[z==null?void 0:z.filter(Ce=>Ce.is_active).map(Ce=>{const Me=Pe=>{switch(Pe){case"event_attendance":return e.jsx(yr,{className:"h-5 w-5"});case"leave_review":return e.jsx(oa,{className:"h-5 w-5"});case"add_listing":return e.jsx(Or,{className:"h-5 w-5"});case"first_contact":return e.jsx(An,{className:"h-5 w-5"});case"first_video":return e.jsx(fr,{className:"h-5 w-5"});case"first_community_post":return e.jsx(Ai,{className:"h-5 w-5"});default:return e.jsx(Oi,{className:"h-5 w-5"})}};return e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-muted/50 border",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center text-primary shrink-0",children:Me(Ce.action_key)}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"font-medium text-sm",children:Ce.action_name}),Ce.description&&e.jsx("p",{className:"text-xs text-muted-foreground truncate",children:Ce.description})]}),e.jsxs(Ue,{variant:"secondary",className:"font-bold shrink-0",children:["+",Ce.points]})]},Ce.id)}),e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg bg-orange-500/10 border border-orange-500/20",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-orange-500/20 flex items-center justify-center text-orange-500 shrink-0",children:e.jsx(Hc,{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(Ue,{variant:"outline",className:"font-bold shrink-0 border-orange-500/50 text-orange-600",children:"+Bonus"})]})]})})})]})}),!D&&e.jsx(fe,{className:"bg-gradient-to-r from-yellow-500/10 to-orange-500/10 border-yellow-500/20",children:e.jsx(Ee,{className:"pt-6",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsx("div",{className:"h-12 w-12 rounded-full bg-yellow-500/20 flex items-center justify-center",children:e.jsx(Ai,{className:"h-6 w-6 text-yellow-600"})}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium",children:"Earn 25 Free Points!"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Leave a quick review and earn 25 spendable points"})]})]}),e.jsxs(B,{onClick:()=>c(!0),className:"bg-yellow-600 hover:bg-yellow-700",children:[e.jsx(oa,{className:"h-4 w-4 mr-2"}),"Leave Review"]})]})})}),e.jsxs(Fr,{value:t,onValueChange:n,children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"store",className:"flex items-center gap-2",children:[e.jsx(yw,{className:"h-4 w-4"}),"Store"]}),e.jsxs(Zt,{value:"my-rewards",className:"flex items-center gap-2",children:[e.jsx(Ec,{className:"h-4 w-4"}),"My Rewards",ee&&ee.length>0&&e.jsx(Ue,{variant:"secondary",className:"ml-1",children:ee.length})]})]}),e.jsxs(is,{value:"store",className:"mt-6",children:[H&&H.length>0&&e.jsxs("div",{className:"flex flex-wrap gap-2 mb-6",children:[e.jsx(B,{variant:r===null?"default":"outline",size:"sm",onClick:()=>a(null),children:"All"}),H.map(Ce=>e.jsxs(B,{variant:r===Ce.id?"default":"outline",size:"sm",onClick:()=>a(Ce.id),children:[Ce.icon&&`${Ce.icon} `,Ce.name]},Ce.id))]}),!Y||Y.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Oi,{className:"h-12 w-12 mx-auto mb-4 opacity-50"}),e.jsx("p",{className:"font-medium",children:"No items available"}),e.jsx("p",{className:"text-sm",children:"Check back later for new rewards!"})]})})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:Y.map(Ce=>{const Me=Ce.item_type==="reelflow_credits",Pe=!Me&&ce.has(Ce.id),Re=!Me&&Ce.max_quantity!==null&&Ce.current_quantity===0,Ae=oe>=Ce.points_cost;return e.jsxs(fe,{className:`overflow-hidden transition-all cursor-pointer hover:shadow-lg ${Pe?"ring-2 ring-green-500/50 bg-green-500/5":""}`,onClick:()=>A(Ce),children:[Ce.preview_image_url?e.jsxs("div",{className:"aspect-video relative overflow-hidden bg-muted",children:[e.jsx("img",{src:Ce.preview_image_url,alt:Ce.name,className:"w-full h-full object-cover"}),Pe&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ue,{className:"bg-green-500 text-white",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"}),"Owned"]})}),Re&&!Pe&&e.jsx("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center",children:e.jsx(Ue,{variant:"destructive",children:"Sold Out"})})]}):e.jsxs("div",{className:"aspect-video bg-muted flex items-center justify-center relative",children:[e.jsx(Oi,{className:"h-12 w-12 text-muted-foreground/50"}),Pe&&e.jsx("div",{className:"absolute top-2 right-2",children:e.jsxs(Ue,{className:"bg-green-500 text-white",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"}),"Owned"]})})]}),e.jsxs(It,{className:"pb-2",children:[e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsx(Rt,{className:"text-lg",children:Ce.name}),e.jsxs(Ue,{variant:"secondary",className:"font-bold shrink-0",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),Ce.points_cost]})]}),Ce.category&&e.jsxs(Ue,{variant:"outline",className:"w-fit",children:[Ce.category.icon&&`${Ce.category.icon} `,Ce.category.name]})]}),e.jsxs(Ee,{children:[e.jsx(Vn,{className:"mb-4 line-clamp-2",children:Ce.description||"No description available"}),Ce.max_quantity!==null&&!Pe&&!Me&&e.jsxs("p",{className:"text-xs text-muted-foreground mb-3",children:[Ce.current_quantity," of ",Ce.max_quantity," remaining"]}),Me&&e.jsxs("p",{className:"text-xs text-violet-600 font-medium mb-3",children:["🎬 Grants ",Ce.max_quantity," ReelFlow credits per purchase"]}),Pe?e.jsx(B,{className:"w-full",onClick:Be=>{Be.stopPropagation(),Ce.file_url&&SNe(Ce.file_url,Ce.name)},disabled:!Ce.file_url,children:Ce.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):e.jsx(B,{className:"w-full",onClick:Be=>{Be.stopPropagation(),l(Ce)},disabled:Re||!Ae,children:Re?"Sold Out":Ae?e.jsxs(e.Fragment,{children:[e.jsx(yw,{className:"h-4 w-4 mr-2"}),"Purchase"]}):`Need ${Ce.points_cost-oe} more pts`})]})]},Ce.id)})})]}),e.jsx(is,{value:"my-rewards",className:"mt-6",children:!ee||ee.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12",children:e.jsxs("div",{className:"text-center text-muted-foreground",children:[e.jsx(Ec,{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:ee.map(Ce=>{var Me,Pe,Re,Ae,Be,we,Je;return e.jsxs(fe,{className:"overflow-hidden",children:[(Me=Ce.item)!=null&&Me.preview_image_url?e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted",children:e.jsx("img",{src:Ce.item.preview_image_url,alt:((Pe=Ce.item)==null?void 0:Pe.name)||"Reward",className:"w-full h-full object-cover"})}):e.jsx("div",{className:"aspect-video bg-muted flex items-center justify-center",children:e.jsx(Oi,{className:"h-12 w-12 text-muted-foreground/50"})}),e.jsxs(It,{className:"pb-2",children:[e.jsx(Rt,{className:"text-lg",children:((Re=Ce.item)==null?void 0:Re.name)||"Unknown Item"}),e.jsxs(Vn,{className:"text-xs",children:["Purchased for ",Ce.points_spent," points • ",new Date(Ce.purchased_at).toLocaleDateString()]})]}),e.jsx(Ee,{children:((Ae=Ce.item)==null?void 0:Ae.item_type)==="reelflow_credits"?e.jsxs(B,{className:"w-full",variant:"outline",disabled:!0,children:[e.jsx(vr,{className:"h-4 w-4 mr-2 text-green-500"}),(Be=Ce.item)==null?void 0:Be.max_quantity," Credits Applied"]}):e.jsx(B,{className:"w-full",onClick:()=>{var ke,it;(ke=Ce.item)!=null&&ke.file_url&&SNe(Ce.item.file_url,(it=Ce.item)==null?void 0:it.name)},disabled:!((we=Ce.item)!=null&&we.file_url),children:((Je=Ce.item)==null?void 0:Je.item_type)==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Access"]})})})]},Ce.id)})})})]})]}),e.jsx(Oo,{open:!!i,onOpenChange:()=>l(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Confirm Purchase"}),e.jsxs(Mo,{children:['Are you sure you want to purchase "',i==null?void 0:i.name,'" for ',i==null?void 0:i.points_cost," points?",(i==null?void 0:i.item_type)==="reelflow_credits"&&e.jsxs(e.Fragment,{children:[e.jsx("br",{}),e.jsx("br",{}),"🎬 ",e.jsxs("strong",{children:[i==null?void 0:i.max_quantity," ReelFlow credits"]})," will be added to your balance instantly."]}),e.jsx("br",{}),e.jsx("br",{}),"You currently have ",e.jsxs("strong",{children:[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(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:me,disabled:he.isPending,children:he.isPending?"Purchasing...":"Confirm Purchase"})]})]})}),e.jsx(_s,{open:o,onOpenChange:Ce=>{!Ce&&_?Te():c(Ce)},children:e.jsx(bs,{children:_?e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(vr,{className:"h-5 w-5 text-green-500"}),"Thank You for Your Review!"]}),e.jsx(Jn,{children:"Would you also share your review on Google? It helps other agents discover LevelUp!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"bg-muted p-4 rounded-lg",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:"Your review:"}),e.jsxs("p",{className:"text-sm italic",children:['"',j,'"']})]}),e.jsxs(B,{variant:"outline",className:"w-full",onClick:ve,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Copy Review to Clipboard"]})]}),e.jsxs(Xn,{className:"flex-col sm:flex-row gap-2",children:[e.jsx(B,{variant:"outline",onClick:Te,children:"Maybe Later"}),e.jsxs(B,{onClick:ge,className:"bg-blue-600 hover:bg-blue-700",children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Leave Google Review"]})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Leave a Review"}),e.jsx(Jn,{children:"Share your experience with LevelUp and earn 25 spendable points!"})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Rating"}),e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(Ce=>e.jsx("button",{type:"button",onClick:()=>u(Ce),className:"focus:outline-none",children:e.jsx(oa,{className:`h-8 w-8 transition-colors ${d>=Ce?"fill-yellow-400 text-yellow-400":"text-muted-foreground hover:text-yellow-400"}`})},Ce))})]}),e.jsxs("div",{children:[e.jsx("label",{className:"text-sm font-medium mb-2 block",children:"Your Review"}),e.jsx(Ms,{placeholder:"What do you love about LevelUp? How has it helped your business?",value:h,onChange:Ce=>p(Ce.target.value),rows:4})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>c(!1),children:"Cancel"}),e.jsx(B,{onClick:le,disabled:f,className:"bg-yellow-600 hover:bg-yellow-700",children:f?"Submitting...":"Submit & Earn 25 Points"})]})]})})}),e.jsx(_s,{open:!!S,onOpenChange:()=>A(null),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[S==null?void 0:S.name,e.jsxs(Ue,{variant:"secondary",className:"font-bold",children:[e.jsx(oa,{className:"h-3 w-3 mr-1"}),S==null?void 0:S.points_cost]})]}),(S==null?void 0:S.category)&&e.jsxs(Ue,{variant:"outline",className:"w-fit",children:[S.category.icon&&`${S.category.icon} `,S.category.name]})]}),(S==null?void 0:S.preview_image_url)&&e.jsx("div",{className:"aspect-video relative overflow-hidden bg-muted rounded-lg",children:e.jsx("img",{src:S.preview_image_url,alt:S.name,className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-muted-foreground",children:(S==null?void 0:S.description)||"No description available"}),(S==null?void 0:S.item_type)==="reelflow_credits"&&e.jsxs("p",{className:"text-sm text-violet-600 font-medium",children:["🎬 Grants ",S==null?void 0:S.max_quantity," ReelFlow credits per purchase"]}),(S==null?void 0:S.item_type)!=="reelflow_credits"&&(S==null?void 0:S.max_quantity)!==null&&!ce.has((S==null?void 0:S.id)||"")&&e.jsxs("p",{className:"text-sm text-muted-foreground",children:[S==null?void 0:S.current_quantity," of ",S==null?void 0:S.max_quantity," remaining"]})]}),e.jsx(Xn,{children:S&&S.item_type!=="reelflow_credits"&&ce.has(S.id)?e.jsx(B,{className:"w-full",onClick:()=>{S.file_url&&SNe(S.file_url,S.name)},disabled:!S.file_url,children:S.item_type==="file"?e.jsxs(e.Fragment,{children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Download"]}):e.jsxs(e.Fragment,{children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Access"]})}):S&&e.jsx(B,{className:"w-full",onClick:()=>{A(null),l(S)},disabled:S.item_type!=="reelflow_credits"&&S.max_quantity!==null&&S.current_quantity===0||oe{s&&se()},[s==null?void 0:s.id]);const se=async()=>{if(!s)return;o(!0),j(!1),_(!0);const{data:Be}=await q.from("point_reward_settings").select("action_key, points").in("action_key",["referral_signup","referral_paid"]);Be==null||Be.forEach(it=>{it.action_key==="referral_signup"&&h(it.points),it.action_key==="referral_paid"&&f(it.points)});const{data:we}=await q.from("profiles").select("name").eq("id",s.id).maybeSingle();we!=null&&we.name&&S(we.name);let{data:Je}=await q.from("agent_referral_codes").select("code").eq("user_id",s.id).maybeSingle();if(!Je){const{data:it}=await q.rpc("generate_agent_referral_code",{_user_id:s.id}),je=it||`agent${s.id.slice(0,6)}`,{data:He,error:$e}=await q.from("agent_referral_codes").insert({user_id:s.id,code:je}).select("code").maybeSingle();!$e&&He&&(Je=He)}i((Je==null?void 0:Je.code)??null);const{data:ke}=await q.from("agent_referrals").select("id, referred_user_id, status, signed_up_at, qualified_at, signup_points_awarded, paid_points_awarded").eq("referrer_user_id",s.id).order("signed_up_at",{ascending:!1});if(ke&&ke.length>0){const it=ke.map($e=>$e.referred_user_id),{data:je}=await q.from("profiles").select("id, name, email").in("id",it),He=new Map((je==null?void 0:je.map($e=>[$e.id,$e]))??[]);d(ke.map($e=>({...$e,referred_profile:He.get($e.referred_user_id)??null})))}else d([]);o(!1)},oe=N.useMemo(()=>a?`${qtn}/trial?ref=${a}`:"",[a]),he=c.length,ce=c.filter(Be=>Be.status==="qualified").length,me=c.filter(Be=>Be.signup_points_awarded).length*u+c.filter(Be=>Be.paid_points_awarded).length*p,le=async()=>{oe&&(await navigator.clipboard.writeText(oe),ae.success("Referral link copied!"))},ve=()=>{const Be=encodeURIComponent("Join me on LevelUp"),we=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=${Be}&body=${we}`},ge=()=>{const Be=encodeURIComponent(`Hey! I think you'd love LevelUp for your business — sign up with my link: ${oe}`);window.location.href=`sms:?&body=${Be}`},Te=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 le()},Ie=Be=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(Be.trim()),Ce=Be=>{const we=(Be??O).trim().replace(/,$/,"");if(!we)return;const Je=we.split(/[\s,;]+/).filter(Boolean),ke=[...I];let it=0;for(const je of Je){if(!Ie(je)){ae.error(`Invalid email: ${je}`);continue}ke.includes(je)||(ke.push(je),it++)}F(ke),it>0&&D("")},Me=Be=>F(I.filter(we=>we!==Be)),Pe=()=>{Y(`${w?w.split(" ")[0]+" invited you to":"Join me on"} LevelUp`),H("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."),E(!0)},Re=Be=>{const we=Be.replace(/&/g,"&").replace(//g,">").replace(/\n/g,"
"),Je=w||"A fellow agent",ke="https://relzejiswnotikjgvjhz.supabase.co/storage/v1/object/public/email-assets/levelup-logo-email.png",it=oe;return`
LevelUp
You're Invited

${Je} thinks you'd love LevelUp 🎉

${we}

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

`.trim()},Ae=async()=>{if(I.length===0&&(O.trim()&&Ce(),I.length===0)){ae.error("Add at least one recipient");return}if(!Z.trim()){ae.error("Subject is required");return}ee(!0);const Be=Re(z);let we=0,Je=0;for(const ke of I)try{const{data:it,error:je}=await q.functions.invoke("gmail-send",{body:{to:ke,subject:Z,body:Be,source:"referral_invite"}});if(je||it!=null&&it.error)throw new Error((je==null?void 0:je.message)||(it==null?void 0:it.error));we++}catch(it){console.error("Gmail send failed for",ke,it),Je++}ee(!1),we>0?(ae.success(`Invite sent to ${we} ${we===1?"person":"people"}`+(Je>0?` (${Je} failed)`:"")),F([]),D(""),E(!1)):ae.error("Failed to send invites")};return!v&&!y?e.jsx(Cs,{title:"Refer & Earn",children:e.jsxs("div",{className:"container max-w-3xl mx-auto p-4 md:p-8",children:[e.jsx(Zo,{children:e.jsx("title",{children:"Refer & Earn | LevelUp"})}),e.jsxs(fe,{className:"border-2 border-dashed",children:[e.jsxs(It,{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(Gc,{className:"h-6 w-6 text-muted-foreground"})}),e.jsx(Rt,{children:"Refer & Earn is for active members"}),e.jsx(Vn,{children:"Activate your subscription to unlock your personal referral link and start earning points."})]}),e.jsx(Ee,{className:"flex justify-center",children:e.jsx(B,{onClick:()=>t("/subscription"),children:"View Subscription"})})]})]})}):e.jsxs(Cs,{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(Zo,{children:[e.jsx("title",{children:"Refer & Earn | LevelUp"}),e.jsx("meta",{name:"description",content:"Invite peers to LevelUp and earn points for every agent who joins."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Oi,{className:"h-7 w-7 text-primary"}),e.jsx("h1",{className:"text-3xl font-bold tracking-tight",children:"Refer & Earn"})]}),e.jsxs("p",{className:"text-muted-foreground",children:["Share LevelUp with peers, mentees, or fellow agents. Earn"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[u," points"]})," when they sign up and"," ",e.jsxs("span",{className:"font-semibold text-foreground",children:[p," more"]})," when they activate a paid plan."]})]}),e.jsxs("div",{className:"grid gap-3 md:grid-cols-3",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx(An,{className:"h-5 w-5 text-muted-foreground"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:he}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Friends signed up"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx(vr,{className:"h-5 w-5 text-emerald-600"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:ce}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Activated paid plan"})]})]})}),e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4 flex items-center gap-3",children:[e.jsx(xo,{className:"h-5 w-5 text-amber-500"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-bold",children:me.toLocaleString()}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Points earned"})]})]})})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Your referral link"]}),e.jsx(Vn,{children:"Anyone who signs up through this link is credited to you."})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex flex-col sm:flex-row gap-2",children:[e.jsx(ye,{readOnly:!0,value:l?"Loading…":oe,className:"font-mono text-sm",onFocus:Be=>Be.currentTarget.select()}),e.jsxs(B,{onClick:le,disabled:!oe,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"}),"Copy link"]})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[n&&e.jsxs(B,{size:"sm",onClick:Pe,disabled:!oe,className:"bg-primary hover:bg-primary/90",children:[e.jsx(lr,{className:"h-4 w-4 mr-2"})," Send via Gmail"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ve,disabled:!oe,children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"})," Email"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:ge,disabled:!oe,children:[e.jsx(Ai,{className:"h-4 w-4 mr-2"})," Text"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:Te,disabled:!oe,children:[e.jsx(Vl,{className:"h-4 w-4 mr-2"})," More…"]})]}),!n&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["💡 ",e.jsx("button",{onClick:()=>t("/integrations"),className:"underline hover:text-foreground",children:"Connect Gmail"})," to send branded invite emails directly from your inbox."]}),a&&e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Your code: ",e.jsx("span",{className:"font-mono font-semibold text-foreground",children:a})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Your Referrals"}),e.jsx(Vn,{children:"Track who joined and when they upgrade."})]}),e.jsx(Ee,{children:l?e.jsx("p",{className:"text-sm text-muted-foreground py-6 text-center",children:"Loading…"}):c.length===0?e.jsxs("div",{className:"text-center py-10 space-y-2",children:[e.jsx(An,{className:"h-10 w-10 mx-auto text-muted-foreground/50"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"No referrals yet. Share your link to get started!"})]}):e.jsx("div",{className:"divide-y",children:c.map(Be=>{var ke,it;const we=((ke=Be.referred_profile)==null?void 0:ke.name)||((it=Be.referred_profile)==null?void 0:it.email)||"New agent",Je=new Intl.DateTimeFormat("en-US",{timeZone:"America/New_York",month:"short",day:"numeric",year:"numeric"}).format(new Date(Be.signed_up_at));return e.jsxs("div",{className:"py-3 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"font-medium truncate",children:we}),e.jsxs("div",{className:"text-xs text-muted-foreground",children:["Joined ",Je]})]}),Be.status==="qualified"?e.jsxs(Ue,{className:"bg-emerald-100 text-emerald-700 border-emerald-200 hover:bg-emerald-100",children:[e.jsx(vr,{className:"h-3 w-3 mr-1"})," Paid · +",u+p," pts"]}):e.jsxs(Ue,{variant:"secondary",children:[e.jsx(pr,{className:"h-3 w-3 mr-1"})," Signed up · +",u," pts"]})]},Be.id)})})})]}),e.jsx(fe,{className:"bg-muted/30",children:e.jsxs(Ee,{className:"p-6",children:[e.jsxs("h3",{className:"font-semibold mb-3 flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"})," How it works"]}),e.jsxs("ol",{className:"text-sm text-muted-foreground space-y-2 list-decimal list-inside",children:[e.jsx("li",{children:"Share your unique link with peers, mentees, or other agents."}),e.jsxs("li",{children:["They sign up — you instantly earn ",e.jsxs("strong",{className:"text-foreground",children:[u," points"]}),"."]}),e.jsxs("li",{children:["When they activate a paid plan, you earn another ",e.jsxs("strong",{className:"text-foreground",children:[p," points"]}),"."]}),e.jsxs("li",{children:["Redeem points in the ",e.jsx("a",{href:"/reward-store",className:"text-primary underline",children:"Reward Store"}),"."]})]})]})}),e.jsx(al,{className:"opacity-0"})]}),e.jsx(_s,{open:A,onOpenChange:E,children:e.jsxs(bs,{className:"sm:max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(lr,{className:"h-5 w-5 text-primary"})," Send referral invites via Gmail"]}),e.jsxs(Jn,{children:["Sending from ",e.jsx("span",{className:"font-medium text-foreground",children:r}),". We'll deliver a branded LevelUp invite with your personal note."]})]}),e.jsxs("div",{className:"space-y-4 py-2",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Recipients"}),e.jsxs("div",{className:"flex flex-wrap gap-1.5 p-2 border rounded-md min-h-[44px] bg-background",children:[I.map(Be=>e.jsxs(Ue,{variant:"secondary",className:"gap-1 pr-1",children:[Be,e.jsx("button",{type:"button",onClick:()=>Me(Be),className:"hover:bg-muted-foreground/20 rounded-full p-0.5","aria-label":`Remove ${Be}`,children:e.jsx($n,{className:"h-3 w-3"})})]},Be)),e.jsx("input",{type:"email",value:O,onChange:Be=>D(Be.target.value),onKeyDown:Be=>{Be.key==="Enter"||Be.key===","||Be.key===" "?(Be.preventDefault(),Ce()):Be.key==="Backspace"&&!O&&I.length>0&&F(I.slice(0,-1))},onBlur:()=>O.trim()&&Ce(),onPaste:Be=>{const we=Be.clipboardData.getData("text");/[\s,;]/.test(we)&&(Be.preventDefault(),Ce(we))},placeholder:I.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(ne,{htmlFor:"email-subject",children:"Subject"}),e.jsx(ye,{id:"email-subject",value:Z,onChange:Be=>Y(Be.target.value),placeholder:"Subject line"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"personal-note",children:"Your personal note"}),e.jsx(Ms,{id:"personal-note",value:z,onChange:Be=>H(Be.target.value),rows:4,placeholder:"Write a quick note explaining why they'd love LevelUp…"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Preview"}),e.jsxs("div",{className:"border rounded-md overflow-hidden bg-muted/30",children:[e.jsxs("div",{className:"px-3 py-2 bg-muted/60 border-b text-xs text-muted-foreground flex items-center justify-between",children:[e.jsxs("span",{className:"truncate",children:["From: ",r]}),e.jsxs("span",{className:"truncate ml-2",children:["Subject: ",Z||"(no subject)"]})]}),e.jsx("iframe",{title:"Email preview",srcDoc:Re(z),className:"w-full h-[420px] bg-white"})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>E(!1),disabled:W,children:"Cancel"}),e.jsxs(B,{onClick:Ae,disabled:W,children:[e.jsx(lr,{className:"h-4 w-4 mr-2"}),W?"Sending…":`Send${I.length>0?` to ${I.length}`:""}`]})]})]})})]})}const J2t=()=>{const{user:s}=vs(),t=Kt(),n=dt({queryKey:["smart-presentations",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentations").select("*").eq("owner_user_id",s.id).neq("status","archived").order("created_at",{ascending:!1});if(u)throw u;return d||[]},enabled:!!s}),r=dt({queryKey:["smart-presentation-templates",s==null?void 0:s.id],queryFn:async()=>{const{data:d,error:u}=await q.from("smart_presentation_templates").select("*").eq("is_active",!0).order("created_at",{ascending:!0});if(u)throw u;return d||[]},enabled:!!s}),a=yt({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").insert({owner_user_id:s.id,...d}).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),i=yt({mutationFn:async({id:d,...u})=>{const{data:h,error:p}=await q.from("smart_presentations").update(u).eq("id",d).select().single();if(p)throw p;return h},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]})}}),l=yt({mutationFn:async d=>{const{data:u,error:h}=await q.from("smart_presentations").update({status:"published",published_at:new Date().toISOString()}).eq("id",d).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation published!")}}),o=yt({mutationFn:async d=>{const{error:u}=await q.from("smart_presentations").update({status:"archived"}).eq("id",d);if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentations"]}),ae.success("Presentation archived")}}),c=yt({mutationFn:async d=>{const{error:u}=await q.from("smart_presentation_templates").insert({owner_user_id:s.id,name:d.title+" Template",description:"Created from "+d.title,template_type:"custom",icon:"📄",sections:d.sections,cta_config:{type:d.cta_type,label:d.cta_label},is_system:!1});if(u)throw u},onSuccess:()=>{t.invalidateQueries({queryKey:["smart-presentation-templates"]}),ae.success("Saved as template!")}});return{presentations:n.data||[],templates:r.data||[],isLoading:n.isLoading,templatesLoading:r.isLoading,createPresentation:a,updatePresentation:i,publishPresentation:l,archivePresentation:o,saveAsTemplate:c}},Htn=()=>{const s=Ln(),{presentations:t,isLoading:n,archivePresentation:r,saveAsTemplate:a}=J2t(),i=o=>o.status==="draft"?e.jsx(Ue,{variant:"outline",className:"text-xs",children:"Draft"}):o.view_count>1?e.jsx(Ue,{className:"text-xs bg-emerald-100 text-emerald-700 border-emerald-200",children:"Revisited"}):o.view_count===1?e.jsx(Ue,{className:"text-xs bg-blue-100 text-blue-700 border-blue-200",children:"Opened"}):e.jsx(Ue,{variant:"secondary",className:"text-xs",children:"Not Opened"}),l=o=>{const c=`https://presentations.relevelup.com/${o}`;navigator.clipboard.writeText(c),ae.success("Link copied!")};return e.jsx(Cs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-5xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"flex items-center gap-2",children:e.jsx("h1",{className:"text-2xl font-serif font-bold text-foreground",children:"Smart Presentations"})}),e.jsx("p",{className:"text-muted-foreground mt-1",children:"Create personalized, video-first presentations for your clients"})]}),e.jsxs(B,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Create Presentation"]})]}),n?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(o=>e.jsx(Ws,{className:"h-20 w-full rounded-lg"},o))}):t.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(ny,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No presentations yet"}),e.jsx("p",{className:"text-muted-foreground mb-6 max-w-md",children:"Create your first Smart Presentation to impress clients with personalized, video-first content."}),e.jsxs(B,{onClick:()=>s("/mission-control/presentations/new"),className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Create Your First Presentation"]})]})}):e.jsx("div",{className:"space-y-3",children:t.map(o=>e.jsx(fe,{className:"hover:shadow-sm transition-shadow",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(br,{className:"h-5 w-5 text-primary"})}),e.jsx("div",{className:"min-w-0 flex-1",children:e.jsxs("div",{className:"flex flex-col sm:flex-row sm:items-start sm:justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold truncate",children:o.title}),i(o)]}),e.jsxs("div",{className:"flex items-center gap-x-3 gap-y-0.5 flex-wrap text-sm text-muted-foreground mt-0.5",children:[o.client_name&&e.jsx("span",{children:o.client_name}),e.jsxs("span",{children:["Created ",Ss(new Date(o.created_at),"MMM d, yyyy")]}),o.view_count>0&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"})," ",o.view_count," view",o.view_count!==1?"s":""]}),o.cta_clicked_count>0&&e.jsx("span",{className:"text-emerald-600 font-medium",children:"CTA clicked"})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap sm:flex-nowrap sm:shrink-0",children:[o.status==="published"&&o.share_token&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>l(o.share_token),children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Copy Link"]}),o.status==="published"&&e.jsx(B,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}?edit=true`),children:"Edit"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>s(`/mission-control/presentations/${o.id}`),children:o.status==="draft"?"Edit":"View"}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",children:e.jsx(Ag,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",children:[o.status==="published"&&o.share_token&&e.jsxs(Kr,{onClick:()=>window.open(`https://presentations.relevelup.com/${o.share_token}`,"_blank"),children:[e.jsx(tr,{className:"h-4 w-4 mr-2"}),"Preview Link"]}),e.jsxs(Kr,{onClick:()=>a.mutate(o),children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"Save as Template"]}),e.jsxs(Kr,{onClick:()=>r.mutate(o.id),className:"text-destructive",children:[e.jsx(tm,{className:"h-4 w-4 mr-2"}),"Archive"]})]})]})]})]})})]})})},o.id))})]})})},fXe={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."}]},Gtn=[{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 Wtn(s){const t=fXe[s];if(t)return t;const n=s.toLowerCase();for(const[r,a]of Object.entries(fXe))if(n.includes(r.toLowerCase())||r.toLowerCase().includes(n))return a;return Gtn}function Ktn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=N.useState(!1),[i,l]=N.useState("script"),[o,c]=N.useState(0),[d,u]=N.useState(0),{canRecord:h}=m_t(),p=CN(),[f,y]=N.useState(""),[_,v]=N.useState(!1),[j,w]=N.useState(!0),[S,A]=N.useState(!1),[E,O]=N.useState(null),D=Wtn(s),I=()=>{l("script"),c(0),u(0),y(""),v(!1),w(!0),A(!1),O(null)},F=W=>{!W&&(i==="uploading"||i==="processing")||(a(W),W||I())},z=W=>{O(W),y(D[W].text),v(!1)},H=()=>{l("record"),w(f.trim().length>0)},Z=()=>{y(""),w(!1),l("record")},Y=N.useCallback(async(W,ee)=>{l("uploading");try{const se=s||"Presentation Video",{videoId:oe,uploadUrl:he,libraryId:ce}=await t6(se),{apiKey:me}=await s6(oe),le=new XMLHttpRequest;le.upload.onprogress=Ce=>{Ce.lengthComputable&&c(Ce.loaded/Ce.total*100)},await new Promise((Ce,Me)=>{le.onload=()=>le.status>=200&&le.status<300?Ce():Me(new Error("Upload failed")),le.onerror=()=>Me(new Error("Upload failed")),le.open("PUT",he),le.setRequestHeader("AccessKey",me),le.send(W)}),l("processing");let ve=0;const ge=Date.now(),Te=9e4;let Ie=null;for(;ve<4;){if(await new Promise(Me=>setTimeout(Me,3e3)),Date.now()-ge>Te){const Me=W.size/1048576,Pe=`https://iframe.mediadelivery.net/embed/${ce}/${oe}?responsive=true`;await p.mutateAsync({bunny_video_id:oe,playback_url:Pe,file_size_mb:Me,title:se,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(Pe),ae.success("Video saved — still encoding. It will be ready shortly."),l("done"),setTimeout(()=>a(!1),1500);return}const Ce=await Fw(oe);if(ve=Ce.status,u(Ce.encodeProgress||0),ve===4)Ie={playbackUrl:Ce.directPlayUrl,thumbnailUrl:Ce.thumbnailUrl,previewUrl:Ce.previewUrl||null,duration:Ce.length||ee,fileSizeMb:(Ce.storageSize||W.size)/(1024*1024)};else if(ve===5||ve===6)throw new Error("Video processing failed")}if(!Ie)throw new Error("No video data");await p.mutateAsync({bunny_video_id:oe,contact_id:t||void 0,playback_url:Ie.playbackUrl,thumbnail_url:Ie.thumbnailUrl,preview_url:Ie.previewUrl,duration_seconds:Ie.duration,file_size_mb:Ie.fileSizeMb,title:se,status:"ready",touch_type:"presentation"}),n(Ie.playbackUrl),ae.success("Video recorded, saved to library & attached!"),l("done"),setTimeout(()=>a(!1),1500)}catch(se){console.error("Recording upload error:",se),ae.error("Failed to process video. Please try again."),l("record")}},[s,t,n,p]);return e.jsxs(_s,{open:r,onOpenChange:F,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Record a video",children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),"Record"]})}),e.jsxs(bs,{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(js,{children:e.jsxs(ws,{children:[i==="script"&&`Prepare your script for "${s}"`,i==="record"&&`Record video for "${s}"`,i==="uploading"&&"Uploading...",i==="processing"&&"Processing...",i==="done"&&"Done!"]})}),i==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Choose a starter script below, edit it to make it yours, or skip and speak freely."}),e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Starter Scripts"}),e.jsx("div",{className:"grid gap-2",children:D.map((W,ee)=>e.jsxs("button",{onClick:()=>z(ee),className:Mt("text-left p-3 rounded-lg border transition-all hover:bg-accent/50",E===ee?"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(br,{className:"h-3.5 w-3.5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm font-medium",children:W.label})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 ml-5.5",children:W.text})]},ee))})]}),f&&e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Your Script"}),!_&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>v(!0),className:"h-7 text-xs gap-1",children:[e.jsx(ya,{className:"h-3 w-3"}),"Edit"]})]}),_?e.jsx(Ms,{value:f,onChange:W=>y(W.target.value),rows:5,placeholder:"Type your script here...",className:"text-sm"}):e.jsx("div",{className:"p-3 rounded-lg bg-muted/50 text-sm text-foreground leading-relaxed",children:f})]}),!f&&e.jsxs("div",{className:"space-y-2",children:[e.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Or Write Your Own"}),e.jsx(Ms,{value:f,onChange:W=>{y(W.target.value),O(null)},rows:4,placeholder:"Type your own script here...",className:"text-sm"})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:Z,className:"text-muted-foreground",children:"Skip — no teleprompter"}),e.jsx(B,{onClick:H,disabled:!1,children:f.trim()?"Continue with Script":"Continue Without Script"})]})]}),!h&&i==="record"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-8 text-center",children:[e.jsx(ic,{className:"h-10 w-10 text-destructive"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"You've reached your video storage limit. Delete some videos to free up space."})]}):i==="record"?e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-xs text-muted-foreground",children:"Record up to 5 minutes. Saved to your library & auto-attached."}),f.trim()&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>w(!j),className:"h-7 text-xs gap-1",children:[j?e.jsx(mf,{className:"h-3 w-3"}):e.jsx(Sr,{className:"h-3 w-3"}),j?"Hide Script":"Show Script"]})]}),e.jsx(i6,{maxDurationSeconds:600,onRecordingComplete:Y,onRecordingStateChange:A,onError:W=>ae.error(W),teleprompterContent:f.trim()?e.jsx(QLe,{text:f,isVisible:j,onToggleVisibility:()=>w(!j),isRecording:S,startCountdown:!1}):void 0}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>l("script"),className:"text-xs text-muted-foreground",children:"← Back to script"})]}):i==="uploading"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(rs,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(fi,{value:o,className:"h-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground text-center",children:["Uploading... ",Math.round(o),"%"]})]})]}):i==="processing"?e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(rs,{className:"h-10 w-10 animate-spin text-primary"}),e.jsxs("div",{className:"w-full max-w-xs space-y-2",children:[e.jsx(fi,{value:d,className:"h-2"}),e.jsxs("p",{className:"text-sm text-muted-foreground text-center",children:["Processing... ",Math.round(d),"%"]}),e.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"This usually takes less than a minute"})]})]}):i==="done"?e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Pi,{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 Ytn({sectionTitle:s,contactId:t,onVideoReady:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(null),[o,c]=N.useState("idle"),[d,u]=N.useState(0),h=N.useRef(null),p=CN(),{data:f}=g1e(),y=(f==null?void 0:f.total_storage_mb)||0,v=((f==null?void 0:f.max_storage_mb)||1024)-y,j=()=>{l(null),c("idle"),u(0)},w=D=>{!D&&o!=="idle"&&o!=="done"||(a(D),D||j())},S=D=>{var z;const I=(z=D.target.files)==null?void 0:z[0];if(!I)return;if(!I.type.startsWith("video/")){ae.error("Please select a video file");return}const F=I.size/(1024*1024);if(F>500){ae.error("Video file must be less than 500MB");return}if(F>v){ae.error(`Not enough storage. You have ${v.toFixed(1)} MB remaining.`);return}l(I)},A=N.useCallback(async()=>{if(i){c("creating"),u(0);try{const D=s||i.name,{data:I,error:F}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:D,isAgentVideo:!0}});if(F)throw new Error(F.message);const{videoId:z,libraryId:H}=I;c("uploading");const{data:Z,error:Y}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:z,isAgentVideo:!0}});if(Y)throw new Error(Y.message);await new Promise((se,oe)=>{const he=new XMLHttpRequest;he.upload.addEventListener("progress",ce=>{ce.lengthComputable&&u(Math.round(ce.loaded/ce.total*100))}),he.addEventListener("load",()=>he.status>=200&&he.status<300?se():oe(new Error(`Upload failed (${he.status})`))),he.addEventListener("error",()=>oe(new Error("Upload failed"))),he.open("PUT",Z.uploadUrl),he.setRequestHeader("AccessKey",Z.apiKey),he.send(i)}),c("processing");const W=i.size/(1024*1024),ee=`https://iframe.mediadelivery.net/embed/${H}/${z}`;await p.mutateAsync({bunny_video_id:z,playback_url:ee,file_size_mb:W,title:D,contact_id:t||void 0,status:"processing",touch_type:"presentation"}),n(ee),c("done"),ae.success("Video uploaded & attached to section!"),setTimeout(()=>a(!1),1200)}catch(D){console.error("Upload error:",D),ae.error(D instanceof Error?D.message:"Failed to upload video"),c("idle")}}},[i,s,t,n,p]),E=()=>{switch(o){case"creating":return"Preparing upload...";case"uploading":return`Uploading... ${d}%`;case"processing":return"Saving video...";case"done":return"Done!";default:return""}},O=o!=="idle"&&o!=="done";return e.jsxs(_s,{open:r,onOpenChange:w,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5 shrink-0",title:"Upload a video file",children:[e.jsx(_a,{className:"h-3.5 w-3.5"}),"Upload"]})}),e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsx(js,{children:e.jsxs(ws,{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(fr,{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"]})]}),!O&&e.jsx(B,{variant:"ghost",size:"icon",className:"h-8 w-8",onClick:()=>l(null),children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs("div",{className:"border-2 border-dashed border-muted-foreground/25 rounded-lg p-8 text-center cursor-pointer hover:border-primary/50 transition-colors",onClick:()=>{var D;return(D=h.current)==null?void 0:D.click()},children:[e.jsx(_a,{className:"h-8 w-8 mx-auto text-muted-foreground mb-2"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Click to select a video file"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"MP4, MOV, WebM (max 500MB)"})]}),e.jsx("input",{ref:h,type:"file",accept:"video/*",className:"hidden",onChange:S,disabled:O}),O&&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(rs,{className:"h-4 w-4 animate-spin"}),e.jsx("span",{children:E()})]}),e.jsx(fi,{value:o==="uploading"?d:o==="processing"?100:10})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>w(!1),disabled:O,children:"Cancel"}),e.jsx(B,{onClick:A,disabled:!i||O,children:O?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"}),"Uploading..."]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-4 w-4 mr-2"}),"Upload & Attach"]})})]})]})]})}const xXe=[{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"}],gXe=()=>{const s=Ln(),{id:t}=bi(),{user:n}=vs(),{templates:r,templatesLoading:a,createPresentation:i,updatePresentation:l,publishPresentation:o}=J2t(),{isGmailConnected:c,gmailEmail:d}=Dh(),[u,h]=N.useState(!1),[p,f]=N.useState("client"),[y,_]=N.useState(!1),[v,j]=N.useState(""),[w,S]=N.useState([]),[A,E]=N.useState(!1),[O,D]=N.useState(null),[I,F]=N.useState(!1),[z,H]=N.useState(""),[Z,Y]=N.useState(""),[W,ee]=N.useState(""),[se,oe]=N.useState("buyer"),[he,ce]=N.useState(""),[me,le]=N.useState(null),[ve,ge]=N.useState(""),[Te,Ie]=N.useState([]),[Ce,Me]=N.useState("schedule_call"),[Pe,Re]=N.useState("Schedule a Call"),[Ae,Be]=N.useState(""),[we,Je]=N.useState(""),[ke,it]=N.useState(null),[je,He]=N.useState(t||null),[$e,Ke]=N.useState(null),[Ge,rt]=N.useState(!1),tt=async(gt,zt)=>{if(!n)return;const As=5*1024*1024;if(gt.size>As){ae.error("Image must be under 5MB");return}if(!gt.type.startsWith("image/")){ae.error("Please upload an image file");return}it(zt);try{const Xt=gt.name.split(".").pop()||"jpg",Qs=`${n.id}/${Date.now()}.${Xt}`,{error:ks}=await q.storage.from("listing-photos").upload(Qs,gt);if(ks)throw ks;const{data:{publicUrl:$s}}=q.storage.from("listing-photos").getPublicUrl(Qs);$t(zt,{image_url:$s}),ae.success("Image uploaded")}catch{ae.error("Failed to upload image")}finally{it(null)}};N.useEffect(()=>{t&&at(t)},[t]);const at=async gt=>{const{data:zt,error:As}=await q.from("smart_presentations").select("*").eq("id",gt).single();if(As||!zt)return;const Xt=zt;if(_(!0),ge(Xt.title),H(Xt.client_name||""),ce(Xt.property_address||""),Ie(Xt.sections||[]),Me(Xt.cta_type||"schedule_call"),Re(Xt.cta_label||"Schedule a Call"),Be(Xt.cta_url||""),Je(Xt.heading||""),Ke(Xt.share_token),rt(Xt.status==="published"),He(Xt.id),f("builder"),Xt.contact_id){const{data:Qs}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone").eq("id",Xt.contact_id).maybeSingle();Qs&&(D(Qs),Y(Qs.email||""),ee(Qs.phone||""))}};N.useEffect(()=>{if(!n||v.length<1){S([]);return}const gt=setTimeout(async()=>{E(!0);const{data:zt}=await q.from("innercircle_contacts").select("id, first_name, last_name, email, phone, lead_source").eq("owner_user_id",n.id).or(`first_name.ilike.%${v}%,last_name.ilike.%${v}%,email.ilike.%${v}%`).limit(10);S(zt||[]),E(!1)},300);return()=>clearTimeout(gt)},[v,n]);const Ye=gt=>{D(gt),H(`${gt.first_name} ${gt.last_name||""}`.trim()),Y(gt.email||""),ee(gt.phone||""),F(!1)},ut=async()=>{if(!z.trim()){ae.error("Client name is required");return}const gt=z.trim().split(" "),zt=gt[0],As=gt.slice(1).join(" ")||null,{data:Xt,error:Qs}=await q.from("innercircle_contacts").insert({owner_user_id:n.id,first_name:zt,last_name:As,email:Z||null,phone:W||null,lead_source:"Smart Presentation"}).select().single();if(Qs){ae.error("Failed to create client");return}D(Xt),ae.success("Client created & saved to Agent OS"),f("template")},_t=gt=>{le(gt);const zt=(gt.sections||[]).map(As=>({...As,is_visible:!0,video_url:"",text:""}));if(Ie(zt),ge(gt.name+(z?` for ${z}`:"")),gt.cta_config){const As=gt.cta_config;Me(As.type||"schedule_call"),Re(As.label||"Schedule a Call")}f("builder")},bt=()=>{Ie([{title:"Welcome",description:"A personal welcome",type:"video",icon:"👋",is_visible:!0}]),ge(z?`Presentation for ${z}`:"New Presentation"),f("builder")},$t=(gt,zt)=>{Ie(As=>As.map((Xt,Qs)=>Qs===gt?{...Xt,...zt}:Xt))},Yt=gt=>{$t(gt,{is_visible:!Te[gt].is_visible})},Ds=()=>{Ie(gt=>[...gt,{title:"New Section",description:"",type:"video",icon:"📝",is_visible:!0}])},Ls=gt=>{Ie(zt=>zt.filter((As,Xt)=>Xt!==gt))},xs=async()=>{if(!ve.trim()){ae.error("Title is required");return}try{if(je){const gt=await l.mutateAsync({id:je,title:ve,sections:Te,client_name:z,property_address:he||null,cta_type:Ce,cta_label:Pe,cta_url:Ae||null,heading:we||null});ae.success("Saved")}else{const gt=await i.mutateAsync({title:ve,contact_id:(O==null?void 0:O.id)||void 0,client_name:z,property_address:he||void 0,template_id:(me==null?void 0:me.id)||void 0,sections:Te,cta_type:Ce,cta_label:Pe,cta_url:Ae||void 0,heading:we||void 0});He(gt.id),Ke(gt.share_token),ae.success("Presentation created!")}}catch(gt){console.error("Failed to save presentation:",gt);const zt=(gt==null?void 0:gt.message)||(gt==null?void 0:gt.toString())||"Unknown error";ae.error(`Failed to save: ${zt}`)}},Lt=async()=>{try{await xs();const gt=je;if(gt){const zt=await o.mutateAsync(gt);Ke(zt.share_token),rt(!0),f("share")}}catch(gt){console.error("Failed to publish presentation:",gt),ae.error(`Failed to publish: ${(gt==null?void 0:gt.message)||"Unknown error"}`)}},Jt=$e?`https://presentations.relevelup.com/${$e}`:"";return e.jsx(Cs,{title:"Smart Presentations",children:e.jsxs("div",{className:"max-w-4xl mx-auto space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>s("/mission-control/presentations"),children:e.jsx(qr,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-serif font-bold text-foreground",children:y?"Edit Presentation":"Create Smart Presentation"}),e.jsxs("p",{className:"text-sm text-muted-foreground",children:[p==="client"&&"Who is this presentation for?",p==="template"&&"Choose a starting template",p==="builder"&&"Customize your presentation",p==="share"&&"Share with your client"]})]})]}),!y&&e.jsx("div",{className:"flex items-center gap-2",children:["client","template","builder","share"].map((gt,zt)=>e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:Mt("w-8 h-8 rounded-full flex items-center justify-center text-sm font-medium transition-colors",p===gt?"bg-primary text-primary-foreground":zt<["client","template","builder","share"].indexOf(p)?"bg-emerald-100 text-emerald-700":"bg-muted text-muted-foreground"),children:zt<["client","template","builder","share"].indexOf(p)?e.jsx(Lr,{className:"h-4 w-4"}):zt+1}),e.jsx("span",{className:"text-sm font-medium capitalize hidden sm:inline",children:gt}),zt<3&&e.jsx("div",{className:"w-8 h-px bg-border"})]},gt))}),p==="client"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs("button",{onClick:()=>{D(null),H(""),Y(""),ee(""),F(!1),f("template")},className:"w-full group flex items-center justify-between gap-4 rounded-xl border border-dashed border-primary/30 bg-primary/5 hover:bg-primary/10 transition-all p-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(lr,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"font-semibold text-foreground text-sm",children:"Skip — Use as Lead Gen Tool"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"No specific client. Share broadly to capture new leads."})]})]}),e.jsx(Oa,{className:"h-4 w-4 text-muted-foreground group-hover:text-primary transition-colors shrink-0"})]}),e.jsxs("div",{className:"grid gap-6 md:grid-cols-2",children:[e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(gr,{className:"h-4 w-4 text-muted-foreground"}),"Select Existing Client"]})}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search by name or email...",value:v,onChange:gt=>j(gt.target.value),className:"pl-10"})]}),e.jsxs("div",{className:"space-y-2 max-h-56 overflow-y-auto",children:[A&&e.jsx(Ws,{className:"h-12 w-full"}),w.map(gt=>e.jsxs("button",{onClick:()=>Ye(gt),className:Mt("w-full text-left p-3 rounded-lg border transition-colors",(O==null?void 0:O.id)===gt.id?"border-primary bg-primary/5":"border-border hover:border-primary/50"),children:[e.jsxs("p",{className:"font-medium text-sm",children:[gt.first_name," ",gt.last_name]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:gt.email||gt.phone||"No contact info"})]},gt.id)),!v&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"Start typing to search your contacts"}),v&&w.length===0&&!A&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No clients found"})]}),O&&e.jsxs(B,{onClick:()=>f("template"),className:"w-full gap-2",children:["Continue with ",O.first_name,e.jsx(Oa,{className:"h-4 w-4"})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(Fo,{className:"h-4 w-4 text-muted-foreground"}),"Add New Client"]})}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{className:"text-xs",children:"Name *"}),e.jsx(ye,{value:z,onChange:gt=>{H(gt.target.value),F(!0),D(null)},placeholder:"Sarah & Mike Johnson"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Email"}),e.jsx(ye,{value:Z,onChange:gt=>Y(gt.target.value),placeholder:"Optional",type:"email"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Phone"}),e.jsx(ye,{value:W,onChange:gt=>ee(gt.target.value),placeholder:"Optional"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Client Type"}),e.jsxs(us,{value:se,onValueChange:oe,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"}),e.jsx(Ze,{value:"recruit",children:"Recruit"}),e.jsx(Ze,{value:"other",children:"Other"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Property Address"}),e.jsx(ye,{value:he,onChange:gt=>ce(gt.target.value),placeholder:"Optional"})]})]}),I&&z&&e.jsxs(B,{onClick:ut,className:"w-full gap-2",children:["Create Client & Continue",e.jsx(Oa,{className:"h-4 w-4"})]})]})]})]})]}),p==="template"&&e.jsxs("div",{className:"space-y-6",children:[e.jsxs(Fr,{defaultValue:"system",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"mine",children:"My Core Templates"}),e.jsx(Zt,{value:"system",children:"LevelUp Smart Templates"}),e.jsx(Zt,{value:"blank",children:"+ Start Blank"})]}),e.jsx(is,{value:"mine",className:"mt-4",children:a?e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[1,2].map(gt=>e.jsx(Ws,{className:"h-32"},gt))}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(gt=>!gt.is_system).length===0?e.jsx("p",{className:"text-muted-foreground col-span-2 text-center py-8",children:"You haven't saved any templates yet. Create a presentation and save it as a template!"}):r.filter(gt=>!gt.is_system).map(gt=>e.jsx(yXe,{template:gt,onSelect:_t},gt.id))})}),e.jsx(is,{value:"system",className:"mt-4",children:e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-4",children:r.filter(gt=>gt.is_system).map(gt=>e.jsx(yXe,{template:gt,onSelect:_t},gt.id))})}),e.jsx(is,{value:"blank",className:"mt-4",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx("p",{className:"text-muted-foreground mb-4",children:"Start with a blank canvas and add your own sections."}),e.jsx(B,{onClick:bt,children:"Start from Scratch"})]})})})]}),e.jsxs(B,{variant:"outline",onClick:()=>f("client"),className:"gap-2",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back"]})]}),p==="builder"&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Presentation Title"}),e.jsx(ye,{value:ve,onChange:gt=>ge(gt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Page Heading"}),e.jsx(ye,{value:we,onChange:gt=>Je(gt.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(ne,{children:"Client Name"}),e.jsx(ye,{value:z,onChange:gt=>H(gt.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Property Address"}),e.jsx(ye,{value:he,onChange:gt=>ce(gt.target.value),placeholder:"Optional"})]})]})]})}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("h2",{className:"text-lg font-semibold",children:"Sections"}),e.jsx(B,{variant:"outline",size:"sm",onClick:Ds,children:"+ Add Section"})]}),e.jsx("div",{className:"space-y-3",children:Te.map((gt,zt)=>e.jsx(fe,{className:Mt(!gt.is_visible&&"opacity-50"),children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col items-center gap-1 pt-1",children:[e.jsx(Pu,{className:"h-4 w-4 text-muted-foreground cursor-grab"}),e.jsx("span",{className:"text-lg",children:gt.icon})]}),e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ye,{value:gt.title,onChange:As=>$t(zt,{title:As.target.value}),className:"font-semibold border-none p-0 h-auto text-base focus-visible:ring-0 bg-transparent"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Yt(zt),children:gt.is_visible?e.jsx(Sr,{className:"h-4 w-4"}):e.jsx(mf,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",onClick:()=>Ls(zt),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})]}),e.jsx(ye,{value:gt.description||"",onChange:As=>$t(zt,{description:As.target.value}),placeholder:"Section description...",className:"text-sm"}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{className:"text-xs",children:"Video URL"}),e.jsx(ye,{value:gt.video_url||"",onChange:As=>$t(zt,{video_url:As.target.value}),placeholder:"Paste a YouTube or video URL...",className:"text-sm"})]}),e.jsx(Ktn,{sectionTitle:gt.title,contactId:O==null?void 0:O.id,onVideoReady:As=>$t(zt,{video_url:As})}),e.jsx(Ytn,{sectionTitle:gt.title,contactId:O==null?void 0:O.id,onVideoReady:As=>$t(zt,{video_url:As})}),e.jsx(e6,{userId:n==null?void 0:n.id,onSelect:As=>$t(zt,{video_url:As})})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Image (optional — shown if no video is set)"}),gt.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:gt.image_url,alt:"",className:"w-full max-h-40 object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>$t(zt,{image_url:""}),children:e.jsx($n,{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:[ke===zt?e.jsx(rs,{className:"h-4 w-4 animate-spin text-muted-foreground"}):e.jsx(ty,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"text-sm text-muted-foreground",children:ke===zt?"Uploading...":"Click to upload an image"}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",disabled:ke===zt,onChange:As=>{var Qs;const Xt=(Qs=As.target.files)==null?void 0:Qs[0];Xt&&tt(Xt,zt),As.target.value=""}})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Text (optional)"}),e.jsx(Ab,{content:gt.text||"",onChange:As=>$t(zt,{text:As}),placeholder:"Add supporting text...",minHeight:"80px",compact:!0})]})]})]})})},zt))})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Call to Action"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"CTA Type"}),e.jsxs(us,{value:Ce,onValueChange:gt=>{Me(gt);const zt=xXe.find(As=>As.value===gt);zt&&Re(zt.label)},children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:xXe.map(gt=>e.jsx(Ze,{value:gt.value,children:gt.label},gt.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Button Label"}),e.jsx(ye,{value:Pe,onChange:gt=>Re(gt.target.value)})]}),e.jsxs("div",{children:[e.jsxs(ne,{children:["Link URL ",e.jsx("span",{className:"text-muted-foreground",children:"(optional — leave blank to show a lead capture form instead)"})]}),e.jsx(ye,{value:Ae,onChange:gt=>Be(gt.target.value),placeholder:"https://calendly.com/..."}),!Ae&&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:[!y&&e.jsxs(B,{variant:"outline",onClick:()=>f("template"),className:"gap-2",children:[e.jsx(qr,{className:"h-4 w-4"}),"Back"]}),e.jsxs("div",{className:"flex gap-3 ml-auto",children:[e.jsx(B,{variant:"outline",onClick:xs,disabled:i.isPending||l.isPending,children:"Save Draft"}),e.jsxs(B,{onClick:Lt,disabled:o.isPending,className:"gap-2",children:[e.jsx(lr,{className:"h-4 w-4"}),Ge?"Update & Reshare":"Publish & Share"]})]})]})]}),p==="share"&&$e&&e.jsxs("div",{className:"space-y-6",children:[e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center py-12 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-full bg-emerald-100 flex items-center justify-center mb-4",children:e.jsx(Lr,{className:"h-8 w-8 text-emerald-600"})}),e.jsx("h2",{className:"text-xl font-semibold mb-2",children:"Your Presentation is Live!"}),e.jsxs("p",{className:"text-muted-foreground mb-6 max-w-md",children:["Share this link with ",z||"your client",". You'll be notified when they view it."]}),e.jsxs("div",{className:"flex items-center gap-2 w-full max-w-lg",children:[e.jsx(ye,{value:Jt,readOnly:!0,className:"text-center font-mono text-sm"}),e.jsx(B,{onClick:()=>{navigator.clipboard.writeText(Jt),ae.success("Link copied!")},children:e.jsx(Zr,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex gap-3 mt-6",children:[e.jsxs(B,{variant:"outline",className:"gap-2",onClick:()=>{const gt=`Hi ${z||""}! I put together something for you — check it out: ${Jt}`;navigator.clipboard.writeText(gt),ae.success("Message copied!")},children:[e.jsx(Ai,{className:"h-4 w-4"}),"Copy Text Message"]}),e.jsxs(B,{variant:"outline",className:"gap-2",onClick:()=>{c?h(!0):window.open(`mailto:${Z||""}?subject=${encodeURIComponent(ve)}&body=${encodeURIComponent(`Hi ${(O==null?void 0:O.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${Jt} Looking forward to connecting!`)}`)},children:[e.jsx(Gs,{className:"h-4 w-4"}),"Send Email"]})]}),c&&e.jsx(Xv,{open:u,onOpenChange:h,contact:O?{id:O.id,first_name:O.first_name,last_name:O.last_name,email:Z||O.email||""}:Z?{id:"",first_name:(z==null?void 0:z.split(" ")[0])||"",last_name:(z==null?void 0:z.split(" ").slice(1).join(" "))||"",email:Z}:void 0,defaultSubject:ve,defaultBody:`Hi ${(O==null?void 0:O.first_name)||(z==null?void 0:z.split(" ")[0])||""}, I put together a personalized presentation for you: ${Jt} Looking forward to connecting!`,gmailEmail:d})]})}),e.jsxs("div",{className:"flex justify-between",children:[e.jsxs(B,{variant:"outline",onClick:()=>f("builder"),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"}),"Edit Presentation"]}),e.jsx(B,{onClick:()=>s("/mission-control/presentations"),children:"Done"})]})]})]})})},yXe=({template:s,onSelect:t})=>e.jsx(fe,{className:"hover:shadow-sm transition-shadow",children:e.jsxs(Ee,{className:"p-5",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("span",{className:"text-2xl",children:s.icon}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold",children:s.name}),e.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:s.description}),e.jsxs("div",{className:"flex items-center gap-2 mt-2",children:[e.jsx(Ue,{variant:"outline",className:"text-xs capitalize",children:s.template_type}),e.jsxs("span",{className:"text-xs text-muted-foreground",children:[(s.sections||[]).length," sections"]})]})]})]}),e.jsx(B,{className:"w-full mt-4",size:"sm",onClick:()=>t(s),children:"Use Template"})]})}),Ztn=()=>{var _;const{shareToken:s}=bi(),[t,n]=N.useState(null),[r,a]=N.useState(!0),[i,l]=N.useState(0),[o,c]=N.useState(!1);N.useEffect(()=>(document.body.classList.add("presentation-page"),()=>{document.body.classList.remove("presentation-page")}),[]),N.useEffect(()=>{s&&d()},[s]);const d=async()=>{const{data:v,error:j}=await q.from("smart_presentations").select("*").eq("share_token",s).eq("status","published").single();if(j||!v){c(!0),a(!1);return}const{data:w}=await q.from("profiles").select("name, email, phone, avatar_url, title, brokerage_id").eq("id",v.owner_user_id).single();let S;if(w!=null&&w.brokerage_id){const{data:E}=await q.from("brokerages").select("name").eq("id",w.brokerage_id).single();S=(E==null?void 0:E.name)||void 0}let A=null;if(v.contact_id){const{data:E}=await q.from("innercircle_contacts").select("first_name, last_name, email, phone").eq("id",v.contact_id).single();A=E}n({...v,owner_name:w==null?void 0:w.name,owner_email:w==null?void 0:w.email,owner_phone:w==null?void 0:w.phone,owner_avatar:w==null?void 0:w.avatar_url,owner_title:(w==null?void 0:w.title)||void 0,brokerage_name:S,contact_name:A?[A.first_name,A.last_name].filter(Boolean).join(" "):void 0,contact_email:(A==null?void 0:A.email)||void 0,contact_phone:(A==null?void 0:A.phone)||void 0}),a(!1);try{await q.rpc("log_presentation_view",{p_presentation_id:v.id,p_section_index:0,p_cta_clicked:!1,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:document.referrer||null})}catch{}},u=async()=>{if(t){try{await q.rpc("log_presentation_view",{p_presentation_id:t.id,p_section_index:null,p_cta_clicked:!0,p_ip_hash:null,p_user_agent:navigator.userAgent,p_referrer:null})}catch{}t.cta_url&&window.open(t.cta_url,"_blank")}};if(r)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"space-y-4 w-full max-w-2xl px-4",children:[e.jsx(Ws,{className:"h-12 w-3/4 mx-auto"}),e.jsx(Ws,{className:"h-64 w-full"}),e.jsx(Ws,{className:"h-8 w-1/2 mx-auto"})]})});if(o||!t)return e.jsx("div",{className:"min-h-screen bg-white flex items-center justify-center",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Presentation Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This presentation may have been removed or is no longer available."})]})});const h=t.sections.filter(v=>v.is_visible!==!1),p=h[i],f=v=>{const j=v.match(/(?:youtube\.com\/watch\?v=|youtu\.be\/)([a-zA-Z0-9_-]+)/);if(j)return`https://www.youtube.com/embed/${j[1]}?rel=0`;if(v.includes("iframe.mediadelivery.net/play/")){const A=v.replace("/play/","/embed/"),E=A.includes("?")?"&":"?";return`${A}${E}responsive=true`}if(v.includes("iframe.mediadelivery.net")){if(v.match(/\/embed\/(\d+)\/([a-f0-9-]+)/)){const E=v.includes("?")?"&":"?";return`${v}${E}responsive=true`}return""}const w=v.match(/loom\.com\/share\/([a-zA-Z0-9]+)/);if(w)return`https://www.loom.com/embed/${w[1]}`;const S=v.match(/video\.bunnycdn\.com\/play\/(\d+)\/([a-f0-9-]+)/);return S?`https://iframe.mediadelivery.net/embed/${S[1]}/${S[2]}?responsive=true`:v},y=!!((_=t.cta_url)!=null&&_.trim());return e.jsxs("div",{className:"min-h-screen bg-gradient-to-b from-slate-50 to-white",children:[e.jsx("header",{className:"bg-white border-b border-gray-100 sticky top-0 z-10",children:e.jsxs("div",{className:"max-w-5xl mx-auto px-4 py-3 flex items-center justify-between",children:[e.jsx("div",{}),e.jsxs("div",{className:"flex items-center gap-3",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-10 w-10 rounded-full object-cover border border-gray-200"}),e.jsxs("div",{className:"text-right text-sm",children:[e.jsx("p",{className:"font-semibold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.owner_title}),t.brokerage_name&&!t.owner_title&&e.jsx("p",{className:"text-gray-500 text-xs",children:t.brokerage_name})]})]})]})}),e.jsxs("main",{className:"max-w-5xl mx-auto px-4 py-8",children:[e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("h1",{className:"text-3xl md:text-4xl font-bold text-gray-900 mb-2",children:t.heading||(t.client_name?`Welcome, ${t.client_name}!`:t.title)}),t.property_address&&e.jsxs("p",{className:"text-lg text-gray-600",children:["Here's the plan for your home at ",e.jsx("strong",{children:t.property_address}),"."]})]}),e.jsxs("div",{className:"grid md:grid-cols-5 gap-8",children:[e.jsxs("div",{className:"md:col-span-3",children:[p!=null&&p.video_url&&f(p.video_url)?e.jsx("div",{className:"relative w-full rounded-xl overflow-hidden shadow-lg bg-gray-900",style:{paddingTop:"56.25%"},children:e.jsx("iframe",{src:f(p.video_url),className:"absolute inset-0 w-full h-full border-0",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,loading:"lazy"})}):p!=null&&p.image_url?e.jsx("div",{className:"rounded-xl overflow-hidden shadow-lg",children:e.jsx("img",{src:p.image_url,alt:p.title,className:"w-full h-auto object-cover",loading:"lazy"})}):e.jsxs("div",{className:"aspect-video bg-gradient-to-br from-blue-50 to-slate-100 rounded-xl flex flex-col items-center justify-center shadow-lg",children:[e.jsx("span",{className:"text-5xl mb-3",children:p==null?void 0:p.icon}),e.jsx("h3",{className:"text-xl font-semibold text-gray-800",children:p==null?void 0:p.title}),e.jsx("p",{className:"text-gray-500 mt-1 text-sm",children:p==null?void 0:p.description})]}),(p==null?void 0:p.text)&&e.jsx("div",{className:"mt-4 p-4 bg-white rounded-lg border text-gray-700 text-sm leading-relaxed prose prose-sm max-w-none",dangerouslySetInnerHTML:{__html:p.text}})]}),e.jsx("div",{className:"md:col-span-2 space-y-3",children:h.map((v,j)=>e.jsx("button",{onClick:()=>l(j),className:Mt("w-full text-left p-4 rounded-xl border transition-all",i===j?"border-blue-500 bg-blue-50 shadow-sm":"border-gray-200 bg-white hover:border-blue-200 hover:bg-blue-50/50"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("span",{className:"text-blue-600 font-bold text-sm mt-0.5",children:[String(j+1).padStart(2,"0"),"."]}),e.jsxs("div",{children:[e.jsx("span",{className:"mr-2",children:v.icon}),e.jsx("span",{className:"font-semibold text-gray-900",children:v.title}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:v.description})]})]})},j))})]}),e.jsxs("div",{className:"mt-12 max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6 text-center",children:[t.owner_avatar&&e.jsx("img",{src:t.owner_avatar,alt:t.owner_name||"Agent",className:"h-20 w-20 rounded-full object-cover mx-auto mb-3 border-2 border-gray-100"}),e.jsx("h3",{className:"text-lg font-bold text-gray-900",children:t.owner_name}),t.owner_title&&e.jsx("p",{className:"text-sm text-gray-500",children:t.owner_title}),t.brokerage_name&&e.jsx("p",{className:"text-sm text-gray-500",children:t.brokerage_name}),e.jsxs("div",{className:"mt-3 flex flex-col items-center gap-1 text-sm text-gray-600",children:[t.owner_phone&&e.jsx("a",{href:`tel:${t.owner_phone}`,className:"hover:text-blue-600 transition-colors",children:t.owner_phone}),t.owner_email&&e.jsx("a",{href:`mailto:${t.owner_email}`,className:"hover:text-blue-600 transition-colors",children:t.owner_email})]})]}),t.cta_label&&e.jsxs("div",{className:"text-center mt-8 py-8",children:[e.jsx("h2",{className:"text-2xl font-bold text-gray-900 mb-4",children:"Ready to Get Started?"}),y?e.jsxs(B,{size:"lg",onClick:u,className:"text-lg px-8 py-6 rounded-xl bg-blue-600 hover:bg-blue-700 text-white shadow-lg",children:[t.cta_label,e.jsx(tr,{className:"h-5 w-5 ml-2"})]}):e.jsx("div",{className:"max-w-md mx-auto bg-white rounded-2xl border border-gray-200 shadow-sm p-6",children:e.jsx(Ylt,{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 Qtn({openHouseId:s,enableSurvey:t,onToggleSurvey:n}){const{data:r,isLoading:a}=Tzt(s),i=Izt(),l=Pzt(),o=Lzt(),c=Dzt(),[d,u]=N.useState(""),[h,p]=N.useState("rating"),f=async j=>{n(j),j&&(!r||r.length===0)&&await c.mutateAsync(s)},y=async()=>{if(!d.trim())return;const j=(r==null?void 0:r.reduce((w,S)=>Math.max(w,S.sort_order),0))??0;await i.mutateAsync({open_house_id:s,question_type:h,question_text:d.trim(),sort_order:j+1}),u("")},_=async j=>{await l.mutateAsync({id:j.id,open_house_id:s,is_active:!j.is_active})},v=async j=>{await o.mutateAsync({id:j.id,open_house_id:s})};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsxs(ne,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(cb,{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(jn,{checked:t,onCheckedChange:f})]}),t&&e.jsx("div",{className:"space-y-3 pt-2 border-t border-border",children:a?e.jsx("div",{className:"flex items-center justify-center py-4",children:e.jsx(rs,{className:"h-4 w-4 animate-spin text-muted-foreground"})}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"space-y-2",children:r==null?void 0:r.map(j=>e.jsxs("div",{className:"flex items-center gap-2 p-2 rounded-lg border border-border bg-muted/20",children:[e.jsx(Pu,{className:"h-3.5 w-3.5 text-muted-foreground shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm truncate",children:j.question_text}),e.jsx("p",{className:"text-xs text-muted-foreground capitalize",children:j.question_type.replace("_"," ")})]}),e.jsx(jn,{checked:j.is_active,onCheckedChange:()=>_(j),className:"scale-75"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0 text-muted-foreground hover:text-destructive",onClick:()=>v(j),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]},j.id))}),e.jsxs("div",{className:"flex items-end gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Add Question"}),e.jsx(ye,{value:d,onChange:j=>u(j.target.value),placeholder:"e.g. How did you hear about this listing?",className:"mt-1 h-9 text-sm",onKeyDown:j=>j.key==="Enter"&&y()})]}),e.jsxs(us,{value:h,onValueChange:p,children:[e.jsx(ls,{className:"w-28 h-9 text-xs",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"rating",children:"Rating"}),e.jsx(Ze,{value:"open_text",children:"Text"})]})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:y,disabled:!d.trim()||i.isPending,className:"h-9",children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]})]})})]})}function Xtn({openHouseId:s}){const{user:t}=vs(),{data:n=[],isLoading:r}=zzt(s),a=$zt(),[i,l]=N.useState(""),[o,c]=N.useState(!1),d=async()=>{const u=i.trim();if(u){c(!0);try{await a.mutateAsync({open_house_id:s,name:u,sort_order:n.length}),l("")}finally{c(!1)}}};return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-sm font-medium",children:"Rooms"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Add rooms and upload photos or videos. Visitors swipe through them on mobile and tab through them on desktop."})]}),r?e.jsxs("div",{className:"py-6 text-center text-sm text-muted-foreground",children:[e.jsx(rs,{className:"h-4 w-4 animate-spin inline"})," Loading…"]}):n.length===0?e.jsx("p",{className:"text-xs text-muted-foreground italic",children:"No rooms yet — add your first below."}):e.jsx("div",{className:"space-y-3",children:n.map((u,h)=>e.jsx(Jtn,{room:u,index:h,total:n.length,userId:(t==null?void 0:t.id)||"",openHouseId:s},u.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(ye,{value:i,onChange:u=>l(u.target.value),placeholder:"e.g. Kitchen, Primary Bedroom, Backyard…",onKeyDown:u=>{u.key==="Enter"&&(u.preventDefault(),d())}}),e.jsx(B,{onClick:d,disabled:!i.trim()||o,size:"sm",children:o?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add"]})})]})]})}function Jtn({room:s,index:t,total:n,userId:r,openHouseId:a}){const i=Uzt(),l=qzt(),o=Vzt(),c=Hzt(),d=N.useRef(null),[u,h]=N.useState(!0),[p,f]=N.useState(s.name),[y,_]=N.useState(s.description||""),[v,j]=N.useState(!1),w=N.useMemo(()=>s.media.filter(F=>F.kind==="video"&&F.agent_video_id).map(F=>F.agent_video_id),[s.media]),{data:S={}}=dt({queryKey:["room-video-statuses",s.id,w.join(",")],enabled:w.length>0,queryFn:async()=>{const{data:F,error:z}=await q.from("agent_videos").select("id, status, bunny_video_id, thumbnail_url, preview_url").in("id",w);if(z)throw z;const H=F||[],Z=H.filter(W=>W.status==="processing"&&W.bunny_video_id);await Promise.all(Z.map(async W=>{try{const{data:ee}=await q.functions.invoke("bunny-upload",{body:{action:"status",videoId:W.bunny_video_id,isAgentVideo:!0}});ee&&ee.status===4&&(await q.from("agent_videos").update({status:"ready",playback_url:ee.directPlayUrl,thumbnail_url:ee.thumbnailUrl,preview_url:ee.previewUrl,duration_seconds:ee.length||void 0,updated_at:new Date().toISOString()}).eq("id",W.id),W.status="ready",W.thumbnail_url=ee.thumbnailUrl,W.preview_url=ee.previewUrl)}catch{}}));const Y={};return H.forEach(W=>{Y[W.id]={status:W.status,thumbnail_url:W.thumbnail_url,preview_url:W.preview_url}}),Y},refetchInterval:F=>{const z=F.state.data;return z?Object.values(z).some(H=>H.status!=="ready"&&H.status!=="failed")?5e3:!1:5e3}}),A=()=>{p.trim()&&p!==s.name&&i.mutate({id:s.id,open_house_id:a,name:p.trim()})},E=()=>{y!==(s.description||"")&&i.mutate({id:s.id,open_house_id:a,description:y.trim()||null})},O=()=>{confirm(`Delete "${s.name}" and all its media?`)&&l.mutate({id:s.id,open_house_id:a})},D=F=>{i.mutate({id:s.id,open_house_id:a,sort_order:t+F})},I=async F=>{const z=Array.from(F.target.files||[]);if(!(!z.length||!r)){j(!0);try{for(const H of z){const Z=H.type.startsWith("video/"),Y=Z?500*1024*1024:15*1024*1024;if(H.size>Y){Br({title:`${H.name} is too large`,description:Z?"Videos must be under 500MB":"Photos must be under 15MB",variant:"destructive"});continue}if(Z){try{const he=`${s.name} – ${H.name.replace(/\.[^/.]+$/,"")}`,{data:ce,error:me}=await q.functions.invoke("bunny-upload",{body:{action:"create",title:he,isAgentVideo:!0}});if(me||!ce)throw new Error((me==null?void 0:me.message)||"Could not start upload");const{videoId:le,libraryId:ve}=ce,{data:ge,error:Te}=await q.functions.invoke("bunny-upload",{body:{action:"upload-url",videoId:le,isAgentVideo:!0}});if(Te||!ge)throw new Error((Te==null?void 0:Te.message)||"Could not get upload URL");await new Promise((Re,Ae)=>{const Be=new XMLHttpRequest;Be.addEventListener("load",()=>{Be.status>=200&&Be.status<300?Re():Ae(new Error(`Upload failed (${Be.status})`))}),Be.addEventListener("error",()=>Ae(new Error("Upload failed"))),Be.open("PUT",ge.uploadUrl),Be.setRequestHeader("AccessKey",ge.apiKey),Be.send(H)});const Ie=`https://iframe.mediadelivery.net/embed/${ve}/${le}`,Ce=H.size/(1024*1024),{data:Me,error:Pe}=await q.from("agent_videos").insert({owner_user_id:r,bunny_video_id:le,playback_url:Ie,file_size_mb:Ce,title:he,status:"processing",touch_type:"open_house_tour",category:"open_house",page_template:"default"}).select().single();if(Pe)throw Pe;await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:Ie,sort_order:s.media.length,agent_video_id:Me.id}),Br({title:"Video uploaded",description:"Processing in the background — it’ll appear in your Video Library too."})}catch(he){Br({title:"Video upload failed",description:(he==null?void 0:he.message)||"Try again",variant:"destructive"})}continue}const W=H.name.split(".").pop()||"jpg",ee=`${r}/${a}/rooms/${s.id}-${Date.now()}-${Math.random().toString(36).slice(2,7)}.${W}`,{error:se}=await q.storage.from("open-house-tour-media").upload(ee,H,{upsert:!1,contentType:H.type});if(se){Br({title:"Upload failed",description:se.message,variant:"destructive"});continue}const{data:oe}=q.storage.from("open-house-tour-media").getPublicUrl(ee);await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"photo",url:oe.publicUrl,sort_order:s.media.length})}}finally{j(!1),d.current&&(d.current.value="")}}};return e.jsxs("div",{className:"rounded-lg border border-border bg-card",children:[e.jsxs("div",{className:"flex items-center gap-2 px-3 py-2 border-b border-border",children:[e.jsx(Pu,{className:"h-4 w-4 text-muted-foreground"}),e.jsxs("button",{onClick:()=>h(F=>!F),className:"flex-1 text-left text-sm font-medium truncate",children:[s.name," ",e.jsxs("span",{className:"text-muted-foreground font-normal text-xs",children:["· ",s.media.length," ",s.media.length===1?"item":"items"]})]}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(-1),disabled:t===0,children:e.jsx(ex,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7",onClick:()=>D(1),disabled:t===n-1,children:e.jsx(ao,{className:"h-4 w-4"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-7 w-7 text-destructive",onClick:O,children:e.jsx(_n,{className:"h-4 w-4"})})]}),u&&e.jsxs("div",{className:"p-3 space-y-3",children:[e.jsx(ye,{value:p,onChange:F=>f(F.target.value),onBlur:A,placeholder:"Room name",className:"h-9"}),e.jsx(Ms,{value:y,onChange:F=>_(F.target.value),onBlur:E,placeholder:"Optional description — what makes this room special?",rows:2,className:"text-sm"}),s.media.length>0&&e.jsx("div",{className:"grid grid-cols-3 gap-2",children:s.media.map(F=>{const z=F.agent_video_id?S[F.agent_video_id]:void 0,H=z==null?void 0:z.status,Z=F.kind==="video"&&H&&H!=="ready"&&H!=="failed",Y=F.kind==="video"&&H==="failed",W=(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:[W?e.jsx("img",{src:W,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"}),!Z&&!Y&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-black/30 pointer-events-none",children:e.jsx(fr,{className:"h-6 w-6 text-white"})}),Z&&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(rs,{className:"h-5 w-5 animate-spin"}),e.jsx("span",{className:"text-[10px] font-medium uppercase tracking-wide",children:"Processing"})]}),Y&&e.jsx("div",{className:"absolute inset-0 flex items-center justify-center bg-destructive/80 text-white text-[10px] font-medium uppercase tracking-wide pointer-events-none px-2 text-center",children:"Failed"})]}):e.jsx("img",{src:F.url,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>c.mutate({id:F.id,open_house_id:a}),className:"absolute top-1 right-1 w-6 h-6 rounded-full bg-black/60 text-white flex items-center justify-center opacity-0 group-hover:opacity-100 transition",children:e.jsx($n,{className:"h-3.5 w-3.5"})})]},F.id)})}),e.jsx("input",{ref:d,type:"file",accept:"image/*,video/*",multiple:!0,onChange:I,className:"hidden"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{var F;return(F=d.current)==null?void 0:F.click()},disabled:v,className:"flex-1",children:v?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-4 w-4 mr-2"})," Upload"]})}),e.jsx(e6,{userId:r,triggerLabel:"From Video Library",triggerClassName:"gap-1.5 flex-1 justify-center",onSelect:()=>{},onSelectVideo:async F=>{try{await o.mutateAsync({open_house_id:a,room_id:s.id,kind:"video",url:F.playback_url||"",sort_order:s.media.length,agent_video_id:F.id}),Br({title:"Video added to room"})}catch(z){Br({title:"Failed to add video",description:z==null?void 0:z.message,variant:"destructive"})}}})]})]})]})}function esn({open:s,onOpenChange:t,openHouse:n}){const r=Qlt(),{user:a}=vs(),i=N.useRef(null),l=N.useRef(null),o=N.useRef(null),c=n.kind==="virtual",[d,u]=N.useState(n.auto_forward_to_card??!1),[h,p]=N.useState(n.disclosure_pdf_url??""),[f,y]=N.useState(n.enable_survey??!1),[_,v]=N.useState(n.ask_visitor_intent??!0),[j,w]=N.useState(n.ask_visitor_address??!1),[S,A]=N.useState(n.photo_url??""),[E,O]=N.useState(!1),[D,I]=N.useState(!1),[F,z]=N.useState(!1),[H,Z]=N.useState(n.hero_video_url??""),[Y,W]=N.useState(!1),[ee,se]=N.useState(n.price!=null?String(n.price):""),[oe,he]=N.useState(n.beds!=null?String(n.beds):""),[ce,me]=N.useState(n.baths!=null?String(n.baths):""),[le,ve]=N.useState(n.sqft!=null?String(n.sqft):""),[ge,Te]=N.useState(n.enable_question??!0),[Ie,Ce]=N.useState(n.enable_showing??!0),[Me,Pe]=N.useState(n.enable_disclosures??!0),[Re,Ae]=N.useState(n.enable_offer??!0),[Be,we]=N.useState(n.brand_color_override??""),[Je,ke]=N.useState(n.property_description??""),it=async rt=>{var bt;const tt=(bt=rt.target.files)==null?void 0:bt[0];if(!tt||!a)return;if(tt.size>200*1024*1024){Br({title:"Video must be under 200MB",variant:"destructive"});return}if(!tt.type.startsWith("video/")){Br({title:"Please upload a video file",variant:"destructive"});return}W(!0);const at=tt.name.split(".").pop()||"mp4",Ye=`${a.id}/${n.id}/hero-${Date.now()}.${at}`,{error:ut}=await q.storage.from("open-house-tour-media").upload(Ye,tt,{upsert:!0,contentType:tt.type});if(ut){Br({title:"Upload failed",description:ut.message,variant:"destructive"}),W(!1);return}const{data:_t}=q.storage.from("open-house-tour-media").getPublicUrl(Ye);Z(_t.publicUrl),W(!1),Br({title:"Video uploaded!"})},je=async rt=>{var bt;const tt=(bt=rt.target.files)==null?void 0:bt[0];if(!tt||!a)return;if(tt.size>10*1024*1024){Br({title:"Image must be under 10MB",variant:"destructive"});return}if(!tt.type.startsWith("image/")){Br({title:"Please upload an image file",variant:"destructive"});return}I(!0);const at=tt.name.split(".").pop()||"jpg",Ye=`${a.id}/${n.id}-${Date.now()}.${at}`,{error:ut}=await q.storage.from("open-house-photos").upload(Ye,tt,{upsert:!0});if(ut){Br({title:"Upload failed",description:ut.message,variant:"destructive"}),I(!1);return}const{data:_t}=q.storage.from("open-house-photos").getPublicUrl(Ye);A(_t.publicUrl),I(!1),Br({title:"Photo updated!"})},He=()=>{A(""),l.current&&(l.current.value="")},$e=async rt=>{var _t;const tt=(_t=rt.target.files)==null?void 0:_t[0];if(!tt||!a)return;if(tt.size>20*1024*1024){Br({title:"File must be under 20MB",variant:"destructive"});return}if(tt.type!=="application/pdf"){Br({title:"Only PDF files are accepted",variant:"destructive"});return}O(!0);const at=`${a.id}/disclosures/${n.id}-${Date.now()}.pdf`,{error:Ye}=await q.storage.from("open-house-photos").upload(at,tt,{upsert:!0});if(Ye){Br({title:"Upload failed",description:Ye.message,variant:"destructive"}),O(!1);return}const{data:ut}=q.storage.from("open-house-photos").getPublicUrl(at);p(ut.publicUrl),O(!1),Br({title:"PDF uploaded!"})},Ke=()=>{p(""),i.current&&(i.current.value="")},Ge=async()=>{z(!0);try{const rt={id:n.id,auto_forward_to_card:d,disclosure_pdf_url:h||null,enable_survey:f,ask_visitor_intent:_,ask_visitor_address:j,photo_url:S||null};c&&(rt.hero_video_url=H||null,rt.price=ee.trim()?Number(ee):null,rt.beds=oe.trim()?parseInt(oe,10):null,rt.baths=ce.trim()?Number(ce):null,rt.sqft=le.trim()?parseInt(le,10):null,rt.enable_question=ge,rt.enable_showing=Ie,rt.enable_disclosures=Me,rt.enable_offer=Re,rt.brand_color_override=Be.trim()||null,rt.property_description=Je.trim()||null),await r.mutateAsync(rt),Br({title:"Settings saved!"}),t(!1)}catch{Br({title:"Failed to save",variant:"destructive"})}finally{z(!1)}};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-md max-h-[85vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:c?"Virtual Open House Settings":"Guest Book Settings"}),e.jsx(Jn,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-6 pt-2",children:[c&&e.jsxs(e.Fragment,{children:[n.tour_mode==="single_video"?e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{className:"text-sm font-medium flex items-center gap-2",children:[e.jsx(fr,{className:"h-4 w-4"})," Hero Tour Video"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"The video visitors watch right after they sign in. MP4 recommended (max 200MB)."}),e.jsx("input",{ref:o,type:"file",accept:"video/*",onChange:it,className:"hidden"}),H?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border bg-black",children:[e.jsx("video",{src:H,controls:!0,className:"w-full max-h-48"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsx(B,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var rt;return(rt=o.current)==null?void 0:rt.click()},disabled:Y,children:Y?e.jsx(rs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),"Replace"]})}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:()=>Z(""),children:e.jsx($n,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=o.current)==null?void 0:rt.click()},disabled:Y,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:Y?e.jsx(rs,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(fr,{className:"h-5 w-5"}),e.jsx("span",{className:"text-xs",children:"Upload tour video (max 200MB)"})]})})]}):e.jsx(Xtn,{openHouseId:n.id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{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(ne,{className:"text-xs text-muted-foreground",children:"Price (USD)"}),e.jsx(ye,{type:"number",value:ee,onChange:rt=>se(rt.target.value),placeholder:"650000",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Sq Ft"}),e.jsx(ye,{type:"number",value:le,onChange:rt=>ve(rt.target.value),placeholder:"2200",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Beds"}),e.jsx(ye,{type:"number",value:oe,onChange:rt=>he(rt.target.value),placeholder:"3",className:"mt-1"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs text-muted-foreground",children:"Baths"}),e.jsx(ye,{type:"number",step:"0.5",value:ce,onChange:rt=>me(rt.target.value),placeholder:"2.5",className:"mt-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Property Description"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Showcase the home — features, finishes, location highlights. Shown on the virtual tour page below the headline."}),e.jsx(Ms,{value:Je,onChange:rt=>ke(rt.target.value),placeholder:"Stunning 4-bedroom in the heart of River Oaks. Chef's kitchen, oversized primary suite, and a backyard oasis perfect for entertaining…",rows:5,className:"w-full resize-y"})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{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(jn,{checked:ge,onCheckedChange:Te})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Schedule a private showing"}),e.jsx(jn,{checked:Ie,onCheckedChange:Ce})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Request seller disclosures"}),e.jsx(jn,{checked:Me,onCheckedChange:Pe})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm",children:"Make an offer / express interest"}),e.jsx(jn,{checked:Re,onCheckedChange:Ae})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Brand Accent Color"}),e.jsx("p",{className:"text-xs text-muted-foreground -mt-1",children:"Used for highlights and CTA buttons on your virtual tour page. Leave blank to use the default."}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:Be||"#0f172a",onChange:rt=>we(rt.target.value),className:"h-10 w-14 rounded-md border border-input cursor-pointer bg-transparent"}),e.jsx(ye,{value:Be,onChange:rt=>we(rt.target.value),placeholder:"#0f172a",className:"flex-1 font-mono text-sm"}),Be&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>we(""),children:"Reset"})]}),e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:["#0f172a","#406E71","#2a4c64","#7c2d12","#1e3a8a","#581c87","#9f1239","#065f46"].map(rt=>e.jsx("button",{type:"button",onClick:()=>we(rt),className:"w-6 h-6 rounded-full border border-border hover:scale-110 transition-transform",style:{backgroundColor:rt},"aria-label":rt},rt))})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Property Photo"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown on the sign-in screen and printable QR sheet"}),e.jsx("input",{ref:l,type:"file",accept:"image/*",onChange:je,className:"hidden"}),S?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:S,alt:"Property",className:"w-full h-40 object-cover"}),e.jsxs("div",{className:"absolute top-2 right-2 flex gap-2",children:[e.jsxs(B,{variant:"secondary",size:"sm",className:"h-8",onClick:()=>{var rt;return(rt=l.current)==null?void 0:rt.click()},disabled:D,children:[D?e.jsx(rs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),D?"":"Replace"]}),e.jsx(B,{variant:"secondary",size:"icon",className:"h-8 w-8",onClick:He,children:e.jsx($n,{className:"h-4 w-4"})})]})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=l.current)==null?void 0:rt.click()},disabled:D,className:"w-full h-32 rounded-xl border-2 border-dashed border-muted-foreground/25 hover:border-muted-foreground/50 flex flex-col items-center justify-center gap-2 text-muted-foreground hover:text-foreground transition-colors",children:D?e.jsx(rs,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Xo,{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(ne,{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(jn,{checked:d,onCheckedChange:u})]})}),!d&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{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:$e,className:"hidden"}),h?e.jsxs("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:[e.jsx(br,{className:"h-5 w-5 text-primary shrink-0"}),e.jsx("span",{className:"text-sm truncate flex-1",children:"Disclosure PDF uploaded"}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-7 w-7 shrink-0",onClick:Ke,children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsx("button",{type:"button",onClick:()=>{var rt;return(rt=i.current)==null?void 0:rt.click()},disabled:E,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:E?e.jsx(rs,{className:"h-5 w-5 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{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(ne,{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(jn,{checked:_,onCheckedChange:v})]})}),e.jsx("div",{className:"space-y-2",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"space-y-0.5",children:[e.jsx(ne,{className:"text-sm font-medium",children:"Ask for visitor's home address"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Adds an optional address field to the sign-in form — helpful for follow-up and market reports."})]}),e.jsx(jn,{checked:j,onCheckedChange:w})]})}),e.jsx(Qtn,{openHouseId:n.id,enableSurvey:f,onToggleSurvey:y}),e.jsx(B,{onClick:Ge,disabled:F,className:"w-full",children:F?"Saving...":"Save Settings"})]})]})})}const eNt={5:"Excellent",4:"Good",3:"Neutral",2:"Bad",1:"Very Bad"};function tsn({question:s,responses:t}){const n=t.filter(l=>l.question_id===s.id&&l.rating_value!=null),r=n.length;if(r===0)return null;const a=n.reduce((l,o)=>l+(o.rating_value||0),0)/r,i=[5,4,3,2,1].map(l=>({val:l,count:n.filter(o=>o.rating_value===l).length,pct:Math.round(n.filter(o=>o.rating_value===l).length/r*100)}));return e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("span",{className:"text-sm font-medium",children:s.question_text}),e.jsxs("span",{className:"text-sm text-muted-foreground",children:[a.toFixed(1)," avg (",r," responses)"]})]}),e.jsx("div",{className:"space-y-1",children:i.map(l=>e.jsxs("div",{className:"flex items-center gap-2 text-xs",children:[e.jsx("span",{className:"w-16 text-muted-foreground text-right",children:eNt[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 ssn({openHouseId:s}){const{data:t,isLoading:n}=Mzt(s),{data:r}=Zlt(s),a=N.useMemo(()=>{const h={};return r==null||r.forEach(p=>{h[p.id]=p}),h},[r]);if(n||!t)return null;const{questions:i,responses:l}=t;if(i.length===0)return null;const o=i.filter(h=>h.question_type==="rating"),c=i.filter(h=>h.question_type!=="rating"),d=[...new Set(l.map(h=>h.visitor_id))],u=d.length;return u===0?e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(cb,{className:"h-4 w-4"}),"Survey Results"]})}),e.jsx(Ee,{children:e.jsx("p",{className:"text-sm text-muted-foreground",children:"No survey responses yet."})})]}):e.jsxs(fe,{children:[e.jsx(It,{className:"pb-3",children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(cb,{className:"h-4 w-4"}),"Survey Results",e.jsxs("span",{className:"text-xs font-normal text-muted-foreground ml-auto",children:[u," respondent",u!==1?"s":""]})]})}),e.jsx(Ee,{children:e.jsxs(Fr,{defaultValue:"summary",children:[e.jsxs(Rr,{className:"mb-4",children:[e.jsxs(Zt,{value:"summary",className:"text-xs gap-1",children:[e.jsx(_o,{className:"h-3.5 w-3.5"})," Summary"]}),e.jsxs(Zt,{value:"individual",className:"text-xs gap-1",children:[e.jsx(Wi,{className:"h-3.5 w-3.5"})," Per Visitor"]})]}),e.jsxs(is,{value:"summary",className:"space-y-6",children:[o.map(h=>e.jsx(tsn,{question:h,responses:l},h.id)),c.map(h=>{const p=l.filter(f=>f.question_id===h.id&&f.text_value);return p.length===0?null:e.jsxs("div",{className:"space-y-2",children:[e.jsx("span",{className:"text-sm font-medium",children:h.question_text}),e.jsx("div",{className:"space-y-1.5 max-h-40 overflow-y-auto",children:p.map(f=>{const y=a[f.visitor_id];return e.jsxs("div",{className:"text-sm p-2 bg-muted/30 rounded-lg",children:[e.jsxs("span",{className:"text-muted-foreground text-xs",children:[y?`${y.first_name} ${y.last_name||""}`.trim():"Visitor",":"]}),e.jsx("p",{className:"mt-0.5",children:f.text_value})]},f.id)})})]},h.id)})]}),e.jsx(is,{value:"individual",className:"space-y-4",children:d.map(h=>{const p=a[h],f=l.filter(y=>y.visitor_id===h);return e.jsxs("div",{className:"p-3 rounded-lg border border-border space-y-2",children:[e.jsxs("p",{className:"text-sm font-medium",children:[p?`${p.first_name} ${p.last_name||""}`.trim():"Unknown Visitor",(p==null?void 0:p.email)&&e.jsx("span",{className:"text-xs text-muted-foreground ml-2",children:p.email})]}),e.jsx("div",{className:"space-y-1",children:f.map(y=>{const _=i.find(v=>v.id===y.question_id);return _?e.jsxs("div",{className:"flex items-center justify-between text-sm",children:[e.jsx("span",{className:"text-muted-foreground",children:_.question_text}),e.jsx("span",{className:"font-medium",children:y.rating_value!=null?eNt[y.rating_value]||y.rating_value:y.text_value})]},y.id):null})})]},h)})})]})})]})}const nsn={question:{label:"Question",icon:Ai,color:"text-sky-700 dark:text-sky-300",bg:"bg-sky-100 dark:bg-sky-950"},showing:{label:"Showing",icon:yr,color:"text-orange-700 dark:text-orange-300",bg:"bg-orange-100 dark:bg-orange-950"},disclosure:{label:"Disclosures",icon:br,color:"text-indigo-700 dark:text-indigo-300",bg:"bg-indigo-100 dark:bg-indigo-950"},offer:{label:"Hot Lead",icon:Yl,color:"text-emerald-700 dark:text-emerald-300",bg:"bg-emerald-100 dark:bg-emerald-950"}},vXe={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 rsn({openHouseId:s}){const{data:t=[],isLoading:n}=Gzt(s),r=Wzt(),[a,i]=N.useState(null),[l,o]=N.useState("all"),c=t.filter(h=>l==="all"?!0:l==="new"?h.status==="new":h.action_type===l),d={all:t.length,new:t.filter(h=>h.status==="new").length,question:t.filter(h=>h.action_type==="question").length,showing:t.filter(h=>h.action_type==="showing").length,disclosure:t.filter(h=>h.action_type==="disclosure").length,offer:t.filter(h=>h.action_type==="offer").length},u=(h,p)=>{r.mutate({id:h,status:p,open_house_id:s})};return n?e.jsx("div",{className:"text-sm text-muted-foreground py-4",children:"Loading leads…"}):e.jsxs("div",{className:"border rounded-lg overflow-hidden",children:[e.jsxs("div",{className:"px-4 py-3 bg-muted/40 border-b flex items-center justify-between flex-wrap gap-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-sm font-semibold",children:[e.jsx(H2,{className:"h-4 w-4"}),"Virtual Open House Leads",e.jsx(Ue,{variant:"secondary",className:"ml-1",children:d.all}),d.new>0&&e.jsxs(Ue,{className:"bg-emerald-600 hover:bg-emerald-600",children:[d.new," new"]})]}),e.jsx("div",{className:"flex items-center gap-1 flex-wrap",children:[["all","All",d.all],["new","New",d.new],["offer","Hot",d.offer],["showing","Showings",d.showing],["question","Questions",d.question],["disclosure","Docs",d.disclosure]].map(([h,p,f])=>e.jsxs("button",{onClick:()=>o(h),className:`text-xs px-2.5 py-1 rounded-full transition-colors ${l===h?"bg-foreground text-background":"bg-background hover:bg-muted text-muted-foreground"}`,children:[p," ",e.jsx("span",{className:"opacity-60",children:f})]},h))})]}),c.length===0?e.jsx("div",{className:"px-4 py-10 text-center text-sm text-muted-foreground",children:t.length===0?"No leads yet. Share your virtual open house link to start capturing leads.":"No leads match this filter."}):e.jsx("ul",{className:"divide-y",children:c.map(h=>{const p=nsn[h.action_type],f=p.icon,y=h.payload||{},_=a===h.id,v=h.status==="contacted",j=h.status==="archived";return e.jsxs("li",{className:`transition-colors ${j?"opacity-60":""} ${h.status==="new"?"bg-emerald-50/40 dark:bg-emerald-950/10":""}`,children:[e.jsxs("button",{onClick:()=>i(_?null:h.id),className:"w-full text-left px-4 py-3 flex items-start gap-3 hover:bg-muted/40 transition-colors",children:[e.jsx("div",{className:`w-9 h-9 rounded-lg flex items-center justify-center shrink-0 ${p.bg}`,children:e.jsx(f,{className:`h-4 w-4 ${p.color}`})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"font-semibold text-sm truncate",children:y.visitor_name||"Visitor"}),e.jsx(Ue,{variant:"outline",className:`text-[10px] ${p.color}`,children:p.label}),h.status==="new"&&e.jsx("span",{className:"text-[10px] font-bold text-emerald-600 uppercase tracking-wide",children:"New"}),v&&e.jsxs("span",{className:"text-[10px] font-bold text-muted-foreground uppercase tracking-wide flex items-center gap-1",children:[e.jsx(vr,{className:"h-3 w-3"}),"Contacted"]})]}),y.message&&e.jsxs("p",{className:"text-sm text-muted-foreground line-clamp-1 mt-0.5 italic",children:['"',y.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(pr,{className:"h-3 w-3"}),Ss(new Date(h.created_at),"MMM d, h:mm a")]}),y.email&&e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(Gs,{className:"h-3 w-3"}),y.email]}),y.phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Cr,{className:"h-3 w-3"}),y.phone]})]})]}),_?e.jsx(ao,{className:"h-4 w-4 mt-1 text-muted-foreground"}):e.jsx(ga,{className:"h-4 w-4 mt-1 text-muted-foreground"})]}),_&&e.jsxs("div",{className:"px-4 pb-4 pl-16 space-y-3",children:[y.message&&e.jsxs("div",{className:"bg-muted/40 rounded-md p-3 text-sm border-l-2 border-foreground/30",children:['"',y.message,'"']}),Object.keys(vXe).some(w=>y[w]!=null&&y[w]!==""&&!(Array.isArray(y[w])&&y[w].length===0))&&e.jsx("div",{className:"grid grid-cols-2 gap-x-4 gap-y-1.5 text-sm",children:Object.entries(vXe).map(([w,S])=>{const A=y[w];return A==null||A===""||Array.isArray(A)&&A.length===0?null:e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] text-muted-foreground uppercase tracking-wide",children:S}),e.jsx("div",{className:"font-medium",children:Array.isArray(A)?A.join(", "):String(A)})]},w)})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-2 pt-1",children:[y.email&&e.jsx("a",{href:`mailto:${y.email}?subject=${encodeURIComponent("Re: your open house inquiry")}`,children:e.jsxs(B,{size:"sm",variant:"default",className:"gap-1.5",children:[e.jsx(Gs,{className:"h-3.5 w-3.5"}),"Reply"]})}),y.phone&&e.jsx("a",{href:`tel:${String(y.phone).replace(/[^0-9+]/g,"")}`,children:e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",children:[e.jsx(Cr,{className:"h-3.5 w-3.5"}),"Call"]})}),!v&&e.jsxs(B,{size:"sm",variant:"outline",className:"gap-1.5",onClick:()=>u(h.id,"contacted"),children:[e.jsx(vr,{className:"h-3.5 w-3.5"}),"Mark contacted"]}),j?e.jsx(B,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"new"),children:"Restore"}):e.jsxs(B,{size:"sm",variant:"ghost",className:"gap-1.5 text-muted-foreground",onClick:()=>u(h.id,"archived"),children:[e.jsx(tm,{className:"h-3.5 w-3.5"}),"Archive"]})]})]})]},h.id)})})]})}function asn({open:s,onOpenChange:t,openHouse:n}){const{isGmailConnected:r,gmailEmail:a}=Dh(),i=wa(),[l,o]=N.useState([]),[c,d]=N.useState([]),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[y,_]=N.useState(""),[v,j]=N.useState(""),[w,S]=N.useState(""),[A,E]=N.useState(!1),[O,D]=N.useState(!1),[I,F]=N.useState(!1),z=`https://guestbook.relevelup.com/${n.slug}`;N.useEffect(()=>{s&&(j(`Take a virtual tour of ${n.property_address}`),S(`I wanted to share an immersive virtual tour of ${n.property_address} with you. Step inside from anywhere — explore every room at your own pace.`),d([]),_(""),E(r),l.length===0&&H())},[s,n.id,r]);const H=async()=>{if(i){f(!0);try{const{data:ce,error:me}=await q.from("innercircle_contacts").select("id, first_name, last_name, email").eq("owner_user_id",i).not("email","is",null).neq("email","").order("first_name",{ascending:!0}).limit(1e3);if(me)throw me;o(ce||[])}catch{ae.error("Failed to load contacts")}finally{f(!1)}}},Z=ce=>`${ce.first_name} ${ce.last_name||""}`.trim(),Y=ce=>{d(me=>me.find(le=>le.id===ce.id)?me.filter(le=>le.id!==ce.id):[...me,ce])},W=()=>{const ce=y.trim();if(!ce)return;if(!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(ce)){ae.error("Invalid email");return}d(le=>[...le,{id:`manual-${ce}`,first_name:ce.split("@")[0],last_name:null,email:ce}]),_("")},ee=N.useMemo(()=>c.filter(ce=>!!ce.email).map(ce=>({email:ce.email,name:Z(ce)})),[c]),se=ce=>{const me=ce?`Hi ${ce},`:"Hi there,",le=w.split(/\n\n+/).map(ve=>`

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

`).join("");return`

${me}

${le}

▶ Start Virtual Tour

Or copy this link: ${z}

`},oe=async()=>{var ce;if(ee.length===0){ae.error("Add at least one recipient");return}D(!0);try{if(A&&r){let me=0;for(const le of ee){const{data:ve,error:ge}=await q.functions.invoke("gmail-send",{body:{to:le.email,subject:v,body:se((ce=le.name)==null?void 0:ce.split(" ")[0])}});!ge&&(ve!=null&&ve.success)?me+=1:console.warn("gmail-send error",ge,ve)}if(me===0)throw new Error("Gmail send failed");ae.success(`Sent to ${me} of ${ee.length} via Gmail`)}else{const{data:me,error:le}=await q.functions.invoke("send-virtual-tour-invite",{body:{openHouseId:n.id,recipients:ee,subject:v,personalMessage:w}});if(le)throw le;if(!(me!=null&&me.success))throw new Error((me==null?void 0:me.error)||"Send failed");ae.success(`Sent to ${me.sent} of ${me.total} recipient${me.total===1?"":"s"}`)}t(!1)}catch(me){ae.error((me==null?void 0:me.message)||"Failed to send")}finally{D(!1)}},he=async()=>{await navigator.clipboard.writeText(z),F(!0),setTimeout(()=>F(!1),1500)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-[560px] w-[calc(100vw-2rem)] max-h-[90vh] overflow-y-auto overflow-x-hidden",children:[e.jsxs(js,{className:"min-w-0",children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Gs,{className:"h-5 w-5 text-primary"}),"Share Virtual Tour"]}),e.jsx(Jn,{className:"truncate",children:n.property_address})]}),e.jsxs("div",{className:"space-y-4 min-w-0",children:[e.jsxs("div",{className:"rounded-lg border bg-muted/30 p-3 flex items-center gap-2 min-w-0",children:[e.jsx(Yo,{className:"h-4 w-4 text-muted-foreground shrink-0"}),e.jsx("code",{className:"flex-1 min-w-0 text-xs truncate",children:z}),e.jsxs(B,{variant:"ghost",size:"sm",onClick:he,className:"shrink-0 h-7 gap-1",children:[I?e.jsx(Lr,{className:"h-3.5 w-3.5 text-emerald-600"}):e.jsx(Zr,{className:"h-3.5 w-3.5"}),I?"Copied":"Copy"]})]}),r&&e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{type:"button",variant:A?"default":"outline",size:"sm",onClick:()=>E(!0),className:"gap-1.5",children:[e.jsx(Gs,{className:"h-3.5 w-3.5"}),"Send from Gmail"]}),e.jsx(B,{type:"button",variant:A?"outline":"default",size:"sm",onClick:()=>E(!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(ne,{className:"flex items-center gap-1.5",children:[e.jsx(An,{className:"h-3.5 w-3.5"}),"Recipients"]}),e.jsxs(il,{open:u,onOpenChange:h,modal:!0,children:[e.jsx(ol,{asChild:!0,children:e.jsxs(B,{variant:"outline",role:"combobox",className:"w-full justify-between",children:[e.jsx("span",{className:"text-muted-foreground",children:c.length?`${c.length} selected`:"Select contacts..."}),e.jsx($g,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),e.jsx(el,{className:"w-[440px] max-w-[calc(100vw-2rem)] p-0",align:"start",children:e.jsxs(Yg,{children:[e.jsx(Zg,{placeholder:"Search contacts..."}),e.jsxs(Qg,{className:"max-h-[300px] overflow-y-auto",children:[e.jsx(Xg,{children:p?"Loading...":"No contacts found."}),e.jsx(Jg,{children:l.map(ce=>{const me=!!c.find(ge=>ge.id===ce.id),le=Z(ce).slice(0,80),ve=(ce.email||"").slice(0,80);return e.jsxs(Zf,{value:`${le} ${ve}`,onSelect:()=>Y(ce),className:"py-2",children:[e.jsx(Lr,{className:Mt("mr-2 h-4 w-4 shrink-0",me?"opacity-100":"opacity-0")}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("div",{className:"font-medium text-sm truncate",children:le||"(no name)"}),e.jsx("div",{className:"text-xs text-muted-foreground truncate",children:ve})]})]},ce.id)})})]})]})})]}),c.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 pt-1",children:c.map(ce=>e.jsxs(Ue,{variant:"secondary",className:"gap-1 pl-2 pr-1 py-0.5",children:[e.jsx("span",{className:"text-xs",children:Z(ce)}),e.jsx("button",{onClick:()=>Y(ce),className:"hover:bg-muted-foreground/20 rounded p-0.5",children:e.jsx($n,{className:"h-3 w-3"})})]},ce.id))}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(ye,{value:y,onChange:ce=>_(ce.target.value),placeholder:"Or type an email...",type:"email",onKeyDown:ce=>{ce.key==="Enter"&&(ce.preventDefault(),W())}}),e.jsx(B,{type:"button",variant:"outline",size:"sm",onClick:W,children:"Add"})]})]}),e.jsx(al,{}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"vt-subject",children:"Subject"}),e.jsx(ye,{id:"vt-subject",value:v,onChange:ce=>j(ce.target.value)})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{htmlFor:"vt-message",children:"Personal Message"}),e.jsx(Ms,{id:"vt-message",value:w,onChange:ce=>S(ce.target.value),rows:4,className:"resize-y"})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>t(!1),disabled:O,children:"Cancel"}),e.jsxs(B,{onClick:oe,disabled:O||ee.length===0||!v.trim(),className:"gap-2",children:[O?e.jsx(rs,{className:"h-4 w-4 animate-spin"}):e.jsx(lr,{className:"h-4 w-4"}),O?"Sending...":`Send${ee.length?` to ${ee.length}`:""}`]})]})]})]})})}const dTe="guestbook.relevelup.com";function isn(){const{data:s,isLoading:t}=Nzt(),n=kzt(),r=Qlt(),a=Szt(),[i,l]=N.useState(!1),[o,c]=N.useState(null),{user:d}=vs(),u=wa(),[h,p]=N.useState(null),[f,y]=N.useState(null),[_,v]=N.useState(!1),j=N.useRef(null),[w,S]=N.useState({property_address:"",city:"",state:"",zip:"",event_date:Ss(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),A=I=>{var z;const F=(z=I.target.files)==null?void 0:z[0];if(F){if(F.size>5*1024*1024){Br({title:"Photo must be under 5MB",variant:"destructive"});return}p(F),y(URL.createObjectURL(F))}},E=()=>{p(null),y(null),j.current&&(j.current.value="")},O=async()=>{if(!w.property_address){Br({title:w.event_type==="community"?"Event name is required":"Address is required",variant:"destructive"});return}let I;if(h&&d){v(!0);const z=h.name.split(".").pop(),H=`${u}/${Date.now()}.${z}`,{error:Z}=await q.storage.from("open-house-photos").upload(H,h,{upsert:!0});if(Z){Br({title:"Photo upload failed",description:Z.message,variant:"destructive"}),v(!1);return}const{data:Y}=q.storage.from("open-house-photos").getPublicUrl(H);I=Y.publicUrl,v(!1)}const F=w.kind==="virtual"?{...w,start_time:void 0,end_time:void 0,photo_url:I}:{...w,photo_url:I};await n.mutateAsync(F),l(!1),S({property_address:"",city:"",state:"",zip:"",event_date:Ss(new Date,"yyyy-MM-dd"),start_time:"10:00",end_time:"14:00",agent_greeting:"Welcome! Please sign in below.",event_type:"property",kind:"physical",tour_mode:"rooms"}),E()},D=I=>{navigator.clipboard.writeText(`https://${dTe}/${I}`),Br({title:"Link copied!"})};return e.jsxs(Cs,{title:"Guest Book",children:[e.jsx(Zo,{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(_s,{open:i,onOpenChange:l,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New Open House"]})}),e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh] flex flex-col",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Create Open House"}),e.jsx(Jn,{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(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Open House Type"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>S(I=>({...I,kind:"physical"})),className:`p-3 rounded-lg border text-left transition-all ${w.kind==="physical"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Physical Open House"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"In-person sign-in at the property"})]}),e.jsxs("button",{type:"button",onClick:()=>S(I=>({...I,kind:"virtual",event_type:"property"})),className:`p-3 rounded-lg border text-left transition-all ${w.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"})]})]})]}),w.kind==="physical"&&e.jsx("div",{className:"flex items-center gap-3 p-3 rounded-lg border border-border bg-muted/30",children:e.jsxs("div",{className:"flex gap-1 flex-1",children:[e.jsx("button",{type:"button",onClick:()=>S(I=>({...I,event_type:"property"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${w.event_type==="property"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Single Property"}),e.jsx("button",{type:"button",onClick:()=>S(I=>({...I,event_type:"community"})),className:`flex-1 px-3 py-2 rounded-md text-sm font-medium transition-colors ${w.event_type==="community"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"}`,children:"Community Event"})]})}),w.kind==="virtual"&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs uppercase tracking-wide text-muted-foreground",children:"Tour Format"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("button",{type:"button",onClick:()=>S(I=>({...I,tour_mode:"rooms"})),className:`p-3 rounded-lg border text-left transition-all ${w.tour_mode==="rooms"?"border-primary bg-primary/5 ring-2 ring-primary/30":"border-border hover:border-muted-foreground/50"}`,children:[e.jsx("div",{className:"text-sm font-semibold",children:"Room-by-room"}),e.jsx("div",{className:"text-xs text-muted-foreground mt-0.5",children:"Photos & videos per room"})]}),e.jsxs("button",{type:"button",onClick:()=>S(I=>({...I,tour_mode:"single_video"})),className:`p-3 rounded-lg border text-left transition-all ${w.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(ne,{children:w.event_type==="community"?"Event Name *":"Property Address *"}),e.jsx(ye,{value:w.property_address,onChange:I=>S(F=>({...F,property_address:I.target.value})),placeholder:w.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(ne,{children:"City"}),e.jsx(ye,{value:w.city,onChange:I=>S(F=>({...F,city:I.target.value})),placeholder:"Austin"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"State"}),e.jsx(ye,{value:w.state,onChange:I=>S(F=>({...F,state:I.target.value})),placeholder:"TX",maxLength:2})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"ZIP"}),e.jsx(ye,{value:w.zip,onChange:I=>S(F=>({...F,zip:I.target.value})),placeholder:"78701"})]})]}),w.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(ne,{children:"Date"}),e.jsx(ye,{type:"date",value:w.event_date,onChange:I=>S(F=>({...F,event_date:I.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Start Time"}),e.jsx(ye,{type:"time",value:w.start_time,onChange:I=>S(F=>({...F,start_time:I.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"End Time"}),e.jsx(ye,{type:"time",value:w.end_time,onChange:I=>S(F=>({...F,end_time:I.target.value}))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Welcome Message"}),e.jsx(Ms,{value:w.agent_greeting,onChange:I=>S(F=>({...F,agent_greeting:I.target.value})),placeholder:"Welcome! Please sign in below."})]}),e.jsxs("div",{children:[e.jsx(ne,{children:w.event_type==="community"?"Event Photo":"Property Photo"}),e.jsx("input",{ref:j,type:"file",accept:"image/*",onChange:A,className:"hidden"}),f?e.jsxs("div",{className:"relative mt-1 rounded-xl overflow-hidden border border-border",children:[e.jsx("img",{src:f,alt:"Property preview",className:"w-full h-40 object-cover"}),e.jsx("button",{type:"button",onClick:E,className:"absolute top-2 right-2 bg-black/60 hover:bg-black/80 text-white rounded-full p-1 transition-colors",children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs("button",{type:"button",onClick:()=>{var I;return(I=j.current)==null?void 0:I.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(ty,{className:"h-6 w-6"}),e.jsxs("span",{className:"text-sm",children:["Add a ",w.event_type==="community"?"cover":"property"," photo"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:"Max 5MB"})]})]}),e.jsx(B,{onClick:O,disabled:n.isPending||_,className:"w-full",children:_?"Uploading photo...":n.isPending?"Creating...":w.kind==="virtual"?"Create Virtual Open House":w.event_type==="community"?"Create Community Event":"Create Open House"})]})]})]})]}),t?e.jsx("div",{className:"grid gap-4",children:[1,2].map(I=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(It,{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"})]})},I))}):s!=null&&s.length?e.jsx("div",{className:"space-y-4",children:s.map(I=>e.jsx(osn,{openHouse:I,isExpanded:o===I.id,onToggle:()=>c(o===I.id?null:I.id),onCopyLink:()=>D(I.slug||""),onToggleActive:()=>r.mutate({id:I.id,is_active:!I.is_active}),onDelete:()=>a.mutate(I.id)},I.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16 text-center",children:[e.jsx("div",{className:"w-16 h-16 rounded-2xl bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(ry,{className:"h-8 w-8 text-primary"})}),e.jsx("h3",{className:"text-lg font-semibold mb-1",children:"No Open Houses Yet"}),e.jsx("p",{className:"text-muted-foreground text-sm max-w-sm mb-6",children:"Create your first open house to get a beautiful, mobile-friendly sign-in page with a shareable link and QR code."}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Create Your First Open House"]})]})})]})]})}function osn({openHouse:s,isExpanded:t,onToggle:n,onCopyLink:r,onToggleActive:a,onDelete:i}){const{data:l}=Zlt(t?s.id:void 0),{data:o}=dt({queryKey:["agent-profile-flyer",s.agent_id],queryFn:async()=>{const{data:D,error:I}=await q.from("profiles").select("name, avatar_url, phone, title, brokerages:brokerage_id(name)").eq("id",s.agent_id).single();if(I)throw I;const F=D.brokerages;return{...D,brokerage_name:(F==null?void 0:F.name)||null}},enabled:!!s.agent_id}),[c,d]=N.useState(!1),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[y,_]=N.useState(!1),v=N.useRef(null),j=`https://${dTe}/${s.slug}`,w=D=>{if(!D)return"";const[I,F]=D.split(":"),z=parseInt(I),H=z>=12?"PM":"AM";return`${z>12?z-12:z||12}:${F} ${H}`},S=()=>{if(!(l!=null&&l.length))return;const D=["First Name","Last Name","Email","Phone","Address","Intent","Wants Market Updates","Message","Signed In"],I=l.map(Y=>[Y.first_name,Y.last_name||"",Y.email||"",Y.phone||"",Y.visitor_address||"",Y.visitor_intent||"",Y.wants_market_updates?"Yes":"No",(Y.message||"").replace(/"/g,'""'),Ss(new Date(Y.created_at),"MM/dd/yyyy h:mm a")]),F=[D,...I].map(Y=>Y.map(W=>`"${W}"`).join(",")).join(` `),z=new Blob([F],{type:"text/csv"}),H=URL.createObjectURL(z),Z=document.createElement("a");Z.href=H,Z.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-visitors.csv`,Z.click(),URL.revokeObjectURL(H)},A=N.useCallback(()=>{if(!v.current)return;const D=v.current.querySelector("svg");if(!D)return;const I=new XMLSerializer().serializeToString(D),F=document.createElement("canvas");F.width=1024,F.height=1024;const z=F.getContext("2d"),H=new Image;H.onload=()=>{z==null||z.drawImage(H,0,0,1024,1024);const Z=document.createElement("a");Z.download=`${s.property_address.replace(/[^a-zA-Z0-9]/g,"-")}-qr.png`,Z.href=F.toDataURL("image/png"),Z.click()},H.src="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I)))},[s.property_address]),E=N.useCallback(()=>{var ke;if(!v.current)return;const D=v.current.querySelector("svg");if(!D)return;const I=new XMLSerializer().serializeToString(D),F="data:image/svg+xml;base64,"+btoa(unescape(encodeURIComponent(I))),z=Ss(new Date(s.event_date+"T00:00:00"),"EEEE, MMMM d, yyyy"),H=s.start_time?`${w(s.start_time)}${s.end_time?" – "+w(s.end_time):""}`:"",Z=[s.city,s.state].filter(Boolean).join(", "),Y=s.agent_greeting||"Welcome! Please sign in below.",W=!!s.photo_url,ee=!!o,se=W||ee,oe=W&&ee,he=oe?"0.35in 0.75in 0.3in":"0.55in 0.75in 0.45in",ce=oe?"28px":"34px",me=oe?"0.2in 0.75in":se?"0.3in 0.75in":"0.4in 0.75in",le=se?"0.15in":"0.3in",ve=se?"0.15in":"0.3in",ge=oe?"14px 36px":"22px 44px",Te=oe?"20px":"24px",Ie=se?"0.2in":"0.35in",Ce=oe?"1.8in":"2.4in",Me=se?"0.15in":"0.3in",Pe=oe?"140px":se?"160px":"200px",Re=oe?"16px":"24px",Ae=oe?"10px 20px":"16px 28px",Be=oe?"44px":"56px",we="0.15in",Je=window.open("","_blank");Je&&(Je.document.write(` Open House – ${s.property_address}
${s.event_type==="community"?"Community Event":"Open House"}
${s.property_address}
${Z?`
${Z}${s.zip?" "+s.zip:""}
`:""}
Date
${z}
${H?`
Time
${H}
`:""}
${Y}
${o?`
${o.avatar_url?`${o.name}`:`
${((ke=o.name)==null?void 0:ke.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
`),Je.document.close(),setTimeout(()=>{Je.focus(),Je.print()},500))},[s,j,o]),O=async()=>{_(!0);try{const{error:D}=await q.functions.invoke("guestbook-email-link",{body:{openHouseId:s.id}});if(D)throw D;Br({title:"Email sent!",description:"Check your inbox for the guest book link."})}catch(D){Br({title:"Failed to send",description:D.message,variant:"destructive"})}finally{_(!1)}};return e.jsxs(fe,{className:`transition-all ${s.is_active?"border-primary/30":"opacity-75"}`,children:[e.jsx(It,{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(Rt,{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(Ue,{variant:s.is_active?"default":"secondary",className:"shrink-0 text-[11px]",children:s.is_active?"Active":"Inactive"}),s.kind==="virtual"?e.jsxs(Ue,{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(Sr,{className:"h-3 w-3"}),"Virtual"]}):e.jsxs(Ue,{variant:"outline",className:"shrink-0 gap-1 text-[11px] bg-emerald-50 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-300 border-emerald-200 dark:border-emerald-800",children:[e.jsx(ka,{className:"h-3 w-3"}),"In-Person"]}),s.agent_name&&e.jsxs(Ue,{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(Wi,{className:"h-3 w-3"}),s.agent_name]}),s.event_type==="community"&&e.jsxs(Ue,{variant:"outline",className:"shrink-0 gap-1 text-[11px]",children:[e.jsx(Ua,{className:"h-3 w-3"}),"Community"]})]})]}),e.jsx(B,{variant:"ghost",size:"icon",onClick:n,className:"shrink-0 -mr-2 -mt-1",children:t?e.jsx(ex,{className:"h-4 w-4"}):e.jsx(ao,{className:"h-4 w-4"})})]}),e.jsxs(Vn,{className:"flex flex-wrap items-center gap-x-4 gap-y-1 text-xs",children:[s.city&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"}),s.city,s.state?`, ${s.state}`:""]}),s.kind==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),"Always on"]}):e.jsxs(e.Fragment,{children:[e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(yr,{className:"h-3 w-3"}),Ss(new Date(s.event_date+"T00:00:00"),"MMM d, yyyy")]}),s.start_time&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),w(s.start_time),s.end_time?` – ${w(s.end_time)}`:""]})]}),e.jsxs("span",{className:"flex items-center gap-1 font-medium",children:[e.jsx(An,{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(ry,{className:"h-3 w-3"}),s.qr_scan_count," scan",s.qr_scan_count===1?"":"s"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 sm:flex sm:flex-wrap sm:items-center",children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.location.href=`/mission-control/guest-book/live/${s.id}`,title:"Go Live",className:"h-9 w-full justify-center gap-1.5 text-xs text-emerald-600 border-emerald-200 hover:bg-emerald-50 dark:text-emerald-400 dark:border-emerald-800 dark:hover:bg-emerald-900/20 sm:h-8 sm:w-auto",children:[e.jsx(yf,{className:"h-3.5 w-3.5"}),"Live"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:r,title:"Copy link",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),"Copy"]}),s.kind==="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>f(!0),title:"Share tour via email",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(Vl,{className:"h-3.5 w-3.5"}),"Share"]}),s.kind==="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`/guestbook/${s.slug}?preview=1`,"_blank"),title:"Preview tour as visitor",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(Sr,{className:"h-3.5 w-3.5"}),"Preview Tour"]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>d(!0),title:"QR Code",className:"h-9 w-full justify-center gap-1.5 text-xs sm:h-8 sm:w-auto",children:[e.jsx(ry,{className:"h-3.5 w-3.5"}),"QR"]}),s.kind!=="virtual"&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>window.open(`${j}?kiosk=1`,"_blank"),title:"Launch tablet/kiosk sign-in mode",className:"h-9 w-full justify-center gap-1.5 text-xs text-primary border-primary/30 hover:bg-primary/10 sm:h-8 sm:w-auto",children:[e.jsx(pL,{className:"h-3.5 w-3.5"}),"Tablet"]}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>h(!0),title:"Settings",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(Ko,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>window.open(j,"_blank"),title:"Preview",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:e.jsx(tr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:a,title:s.is_active?"Deactivate":"Activate",className:"h-9 w-full justify-center text-xs sm:h-8 sm:w-auto",children:s.is_active?e.jsx(mf,{className:"h-3.5 w-3.5"}):e.jsx(Sr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{variant:"outline",size:"sm",onClick:i,title:"Delete",className:"h-9 w-full justify-center text-xs text-destructive border-destructive/30 hover:bg-destructive/10 sm:h-8 sm:w-auto",children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})}),t&&e.jsxs(Ee,{className:"pt-0",children:[e.jsx(al,{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://",dTe,"/",s.slug]})]}),l!=null&&l.length?e.jsxs("div",{className:"space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("p",{className:"text-xs font-medium text-muted-foreground",children:[l.length," Visitor",l.length!==1?"s":""]}),e.jsxs(B,{variant:"outline",size:"sm",onClick:S,className:"h-7 text-xs gap-1",children:[e.jsx(Ia,{className:"h-3 w-3"}),"Export CSV"]})]}),e.jsx("div",{className:"rounded-lg border overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{children:e.jsxs("tr",{className:"bg-muted/30 text-xs text-muted-foreground",children:[e.jsx("th",{className:"text-left p-2 font-medium",children:"Name"}),e.jsx("th",{className:"text-left p-2 font-medium hidden sm:table-cell",children:"Contact"}),e.jsx("th",{className:"text-left p-2 font-medium hidden md:table-cell",children:"Intent"}),e.jsx("th",{className:"text-left p-2 font-medium",children:"Time"})]})}),e.jsx("tbody",{children:l.map(D=>e.jsxs("tr",{className:"border-t border-border/50",children:[e.jsxs("td",{className:"p-2 font-medium",children:[D.first_name,D.last_name?` ${D.last_name}`:""]}),e.jsxs("td",{className:"p-2 text-muted-foreground hidden sm:table-cell",children:[D.email&&e.jsx("div",{className:"truncate max-w-[180px]",children:D.email}),D.phone&&e.jsx("div",{className:"text-xs",children:D.phone}),D.visitor_address&&e.jsx("div",{className:"text-xs truncate max-w-[180px]",children:D.visitor_address})]}),e.jsx("td",{className:"p-2 hidden md:table-cell",children:D.visitor_intent?e.jsx(Ue,{variant:"outline",className:"text-xs capitalize",children:D.visitor_intent}):D.partial_signin?e.jsx(Ue,{variant:"outline",className:"text-xs text-amber-600 border-amber-300 dark:text-amber-400 dark:border-amber-700",children:"Didn't finish"}):null}),e.jsx("td",{className:"p-2 text-xs text-muted-foreground",children:Ss(new Date(D.created_at),"h:mm a")})]},D.id))})]})})]}):e.jsx("p",{className:"text-sm text-muted-foreground text-center py-6",children:"No visitors yet. Share the link to start collecting sign-ins!"}),s.kind==="virtual"&&e.jsx("div",{className:"mt-4",children:e.jsx(rsn,{openHouseId:s.id})}),s.enable_survey&&e.jsx("div",{className:"mt-4",children:e.jsx(ssn,{openHouseId:s.id})})]}),e.jsx(_s,{open:c,onOpenChange:d,children:e.jsxs(bs,{className:"sm:max-w-sm",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"QR Code"}),e.jsx(Jn,{className:"truncate",children:s.property_address})]}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx("div",{ref:v,className:"bg-white p-4 rounded-xl",children:e.jsx(zU,{value:j,size:240,level:"H"})}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:j}),e.jsxs("div",{className:"flex gap-2 w-full",children:[e.jsxs(B,{variant:"outline",className:"flex-1",onClick:A,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"}),"Download"]}),e.jsxs(B,{variant:"outline",className:"flex-1",onClick:E,children:[e.jsx(d9,{className:"h-4 w-4 mr-2"}),"Print Flyer"]})]}),e.jsxs(B,{variant:"default",className:"w-full",onClick:O,disabled:y,children:[e.jsx(Gs,{className:"h-4 w-4 mr-2"}),y?"Sending...":"Email Link to Me"]})]})]})}),e.jsx(esn,{open:u,onOpenChange:h,openHouse:s}),s.kind==="virtual"&&e.jsx(asn,{open:p,onOpenChange:f,openHouse:{id:s.id,slug:s.slug,property_address:s.property_address,city:s.city,state:s.state}})]})}function lsn(){const{slug:s}=bi();return s?e.jsx(fht,{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 tNt({photoUrl:s,videoUrl:t,onPhotoChange:n,onVideoChange:r,contactId:a}){const{user:i}=vs(),l=CN(),o=N.useRef(null),c=N.useRef(null),[d,u]=N.useState(!1),[h,p]=N.useState(!1),[f,y]=N.useState(0),_=async j=>{if(i){u(!0);try{const w=j.name.split(".").pop()||"jpg",S=`${i.id}/card-${Date.now()}.${w}`,{error:A}=await q.storage.from("listing-photos").upload(S,j);if(A)throw A;const{data:{publicUrl:E}}=q.storage.from("listing-photos").getPublicUrl(S);n(E),ae.success("Photo uploaded")}catch(w){ae.error(w.message||"Failed to upload photo")}finally{u(!1)}}},v=async j=>{if(i){if(j.size>500*1024*1024){ae.error("Video must be under 500MB");return}p(!0),y(0);try{const{videoId:w,libraryId:S}=await t6(`Card Video - ${Date.now()}`),{uploadUrl:A,apiKey:E}=await s6(w);await new Promise((I,F)=>{const z=new XMLHttpRequest;z.upload.addEventListener("progress",H=>{H.lengthComputable&&y(Math.round(H.loaded/H.total*100))}),z.addEventListener("load",()=>{z.status>=200&&z.status<300?I():F(new Error("Upload failed"))}),z.addEventListener("error",()=>F(new Error("Upload failed"))),z.open("PUT",A),z.setRequestHeader("AccessKey",E),z.send(j)});const O=`https://iframe.mediadelivery.net/embed/${S}/${w}`;r(O);const D=parseFloat((j.size/(1024*1024)).toFixed(2));await l.mutateAsync({bunny_video_id:w,playback_url:`https://iframe.mediadelivery.net/play/${S}/${w}`,file_size_mb:D,title:"Card Video",status:"processing",touch_type:"video",contact_id:a||void 0}),ae.success("Video uploaded & added to your library")}catch(w){ae.error(w.message||"Failed to upload video")}finally{p(!1),y(0)}}};return e.jsxs("div",{className:"space-y-3",children:[e.jsx(ne,{children:"Media (optional)"}),e.jsxs(Fr,{defaultValue:"photo",className:"w-full",children:[e.jsxs(Rr,{className:"grid w-full grid-cols-2",children:[e.jsxs(Zt,{value:"photo",className:"gap-1.5 text-xs",children:[e.jsx(Xo,{className:"h-3.5 w-3.5"}),"Photo"]}),e.jsxs(Zt,{value:"video",className:"gap-1.5 text-xs",children:[e.jsx(fr,{className:"h-3.5 w-3.5"}),"Video"]})]}),e.jsxs(is,{value:"photo",className:"mt-3",children:[s?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("img",{src:s,alt:"Card photo",className:"w-full h-40 object-cover"}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>n(null),children:e.jsx($n,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=o.current)==null?void 0:j.click()},disabled:d,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:d?e.jsx(rs,{className:"h-6 w-6 animate-spin"}):e.jsxs(e.Fragment,{children:[e.jsx(Jf,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a photo"})]})}),e.jsx("input",{ref:o,type:"file",accept:"image/*",className:"hidden",onChange:j=>{var S;const w=(S=j.target.files)==null?void 0:S[0];w&&_(w),j.target.value=""}})]}),e.jsxs(is,{value:"video",className:"mt-3",children:[t?e.jsxs("div",{className:"relative rounded-lg overflow-hidden border border-border",children:[e.jsx("iframe",{src:`${t}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0}),e.jsx(B,{variant:"destructive",size:"icon",className:"absolute top-2 right-2 h-7 w-7",onClick:()=>r(null),children:e.jsx($n,{className:"h-3.5 w-3.5"})})]}):e.jsx("button",{onClick:()=>{var j;return(j=c.current)==null?void 0:j.click()},disabled:h,className:"w-full h-32 border-2 border-dashed border-border rounded-lg flex flex-col items-center justify-center gap-2 text-muted-foreground hover:border-primary/40 hover:bg-accent/50 transition-colors",children:h?e.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e.jsx(rs,{className:"h-6 w-6 animate-spin"}),e.jsxs("span",{className:"text-xs",children:["Uploading... ",f,"%"]}),e.jsx("div",{className:"w-32 h-1.5 bg-muted rounded-full overflow-hidden",children:e.jsx("div",{className:"h-full bg-primary rounded-full transition-all",style:{width:`${f}%`}})})]}):e.jsxs(e.Fragment,{children:[e.jsx(_a,{className:"h-6 w-6"}),e.jsx("span",{className:"text-xs",children:"Upload a video (max 500MB)"})]})}),!t&&!h&&e.jsx("div",{className:"mt-2",children:e.jsx(XLe,{contactId:a,onVideoReady:j=>r(j)})}),e.jsx("input",{ref:c,type:"file",accept:"video/*",className:"hidden",onChange:j=>{var S;const w=(S=j.target.files)==null?void 0:S[0];w&&v(w),j.target.value=""}}),e.jsx("p",{className:"text-[10px] text-muted-foreground/60 mt-1.5 text-center",children:"Videos are also saved to your Video Library"})]})]})]})}const csn=[{type:"home_anniversary",label:"Home Anniversary",emoji:"🏡",description:"Celebrate their homeownership milestone",gradient:"from-blue-500/20 to-slate-500/20 border-blue-200 dark:border-blue-800"},{type:"wedding_anniversary",label:"Wedding Anniversary",emoji:"💍",description:"Celebrate their special day together",gradient:"from-rose-500/20 to-fuchsia-500/20 border-rose-200 dark:border-rose-800"},{type:"birthday",label:"Birthday",emoji:"🎂",description:"Wish them a happy birthday",gradient:"from-pink-500/20 to-purple-500/20 border-pink-200 dark:border-pink-800"},{type:"just_sold",label:"Just Sold",emoji:"🎉",description:"Announce a successful closing",gradient:"from-emerald-500/20 to-teal-500/20 border-emerald-200 dark:border-emerald-800"},{type:"just_listed",label:"Just Listed",emoji:"🏠",description:"Share a new listing announcement",gradient:"from-amber-500/20 to-orange-500/20 border-amber-200 dark:border-amber-800"},{type:"thank_you",label:"Thank You",emoji:"💐",description:"Show your appreciation",gradient:"from-rose-500/20 to-pink-500/20 border-rose-200 dark:border-rose-800"},{type:"congratulations",label:"Congratulations",emoji:"🏆",description:"Celebrate their achievements",gradient:"from-yellow-500/20 to-amber-500/20 border-yellow-200 dark:border-yellow-800"},{type:"holiday",label:"Holiday",emoji:"🎄",description:"Send seasonal greetings",gradient:"from-red-500/20 to-green-500/20 border-red-200 dark:border-red-800"},{type:"thinking_of_you",label:"Thinking of You",emoji:"💭",description:"Stay top of mind with a personal touch",gradient:"from-violet-500/20 to-indigo-500/20 border-violet-200 dark:border-violet-800"}];function dsn({onSelect:s}){return e.jsx("div",{className:"grid grid-cols-2 gap-2.5",children:csn.map((t,n)=>e.jsxs(Zn.button,{initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:n*.04,duration:.25},onClick:()=>s(t.type),className:`group relative flex flex-col items-start gap-1 p-3.5 rounded-xl border bg-gradient-to-br ${t.gradient} hover:shadow-md hover:scale-[1.02] active:scale-[0.98] transition-all text-left`,children:[e.jsx("span",{className:"text-2xl",children:t.emoji}),e.jsx("span",{className:"text-sm font-semibold text-foreground",children:t.label}),e.jsx("span",{className:"text-[11px] text-muted-foreground leading-tight",children:t.description})]},t.type))})}const ER={home_anniversary:{title:["Happy Home","Anniversary"],icon:"🏡",emojis:["🏡","✨","🎉","❤️","🎊","🏠"],defaultMessage:"Wishing you many more wonderful years of memories in your beautiful home. Thank you for letting me be part of your journey."},wedding_anniversary:{title:["Happy","Anniversary"],icon:"💍",emojis:["💍","💐","❤️","🥂","💕","✨"],defaultMessage:"Wishing you both a wonderful anniversary filled with love, laughter, and cherished memories. Here's to many more years together!"},just_listed:{title:["Just","Listed!"],icon:"🏠",emojis:["🏠","📋","🔑","⭐","🎯","✨"],defaultMessage:"Exciting news — this beautiful property just hit the market! Contact me for a private showing."},just_sold:{title:["Just","Sold!"],icon:"🎉",emojis:["🎉","🏡","🔑","🥂","🎊","💰"],defaultMessage:"Another successful closing! Congratulations to the new homeowners. It was a pleasure making this happen."},congratulations:{title:["Congratulations!",""],icon:"🏆",emojis:["🎉","🥳","🏆","⭐","🎊","✨"],defaultMessage:"What an incredible milestone! I'm so happy for you. Wishing you all the best in this exciting new chapter."},birthday:{title:["Happy","Birthday!"],icon:"🎂",emojis:["🎂","🎈","🎁","🥳","🎉","🧁"],defaultMessage:"Wishing you the happiest of birthdays! May this year bring you joy, laughter, and everything you've been dreaming of."},holiday:{title:["Happy","Holidays!"],icon:"🎄",emojis:["🎄","❄️","🎁","⭐","🕯️","🎅"],defaultMessage:"Wishing you and your family a season filled with warmth, joy, and cherished moments. Happy Holidays!"},thank_you:{title:["Thank","You!"],icon:"💐",emojis:["💐","🙏","❤️","⭐","✨","🤝"],defaultMessage:"Thank you so much for your trust and confidence. It truly means the world to me. I'm always here for you!"},thinking_of_you:{title:["Thinking","Of You"],icon:"💭",emojis:["💭","❤️","🌸","☀️","🦋","💫"],defaultMessage:"Just wanted to reach out and let you know I'm thinking of you. I hope you're doing well — don't hesitate to reach out anytime!"}};function bXe({initialOpen:s,initialCardType:t,initialContactId:n,initialRecipientName:r,initialAddress:a,initialDate:i,onOpenChange:l}){const{user:o}=vs(),c=Kt(),[d,u]=N.useState(!1),[h,p]=N.useState("type"),[f,y]=N.useState(""),[_,v]=N.useState(null),[j,w]=N.useState(!1),[S,A]=N.useState("home_anniversary"),[E,O]=N.useState(""),[D,I]=N.useState(""),[F,z]=N.useState(""),[H,Z]=N.useState(""),[Y,W]=N.useState("elegant"),[ee,se]=N.useState(null),[oe,he]=N.useState(null),ce=N.useState(!1);!ce[0]&&s&&t&&(ce[1](!0),u(!0),A(t),n&&v(n),r&&O(r),a&&I(a),i&&z(i),p(r?"details":"contact"));const{data:me}=dt({queryKey:["contacts-for-card",o==null?void 0:o.id,f],queryFn:async()=>{let Be=q.from("innercircle_contacts").select("id, first_name, last_name, address, city, state, home_anniversary, wedding_anniversary, email, phone").eq("owner_user_id",o.id).order("first_name").limit(20);f&&(Be=Be.or(`first_name.ilike.%${f}%,last_name.ilike.%${f}%`));const{data:we,error:Je}=await Be;if(Je)throw Je;return we},enabled:!!(o!=null&&o.id)&&d}),{data:le}=dt({queryKey:["agent-profile-card",o==null?void 0:o.id],queryFn:async()=>{const{data:Be,error:we}=await q.from("profiles").select("name, email, phone, avatar_url, brokerage:brokerages(name)").eq("id",o.id).single();if(we)throw we;return Be},enabled:!!(o!=null&&o.id)}),ve=Be=>{v(Be.id),O(`${Be.first_name}${Be.last_name?" "+Be.last_name:""}`),I([Be.address,Be.city,Be.state].filter(Boolean).join(", "));const we=S==="wedding_anniversary"?Be.wedding_anniversary:S==="home_anniversary"?Be.home_anniversary:"";z(we||""),p("details")},ge=Be=>{A(Be),p("contact")},Te=async()=>{var Be;if(!(!o||!le)){w(!0);try{const we={owner_user_id:o.id,contact_id:_,card_type:S,template:Y,recipient_name:E,property_address:D||null,home_anniversary_date:F||null,custom_message:H||null,property_photo_url:ee||null,video_url:oe||null,agent_name:le.name||"Agent",agent_photo_url:le.avatar_url,agent_phone:le.phone,agent_email:le.email,agent_brokerage:((Be=le.brokerage)==null?void 0:Be.name)||null},{error:Je}=await q.from("sendable_cards").insert(we);if(Je)throw Je;ae.success("Card created! Copy the link to share it."),c.invalidateQueries({queryKey:["sendable-cards"]}),Ie()}catch(we){ae.error(we.message||"Failed to create card")}finally{w(!1)}}},Ie=()=>{u(!1),p("type"),A("home_anniversary"),y(""),v(null),O(""),I(""),z(""),Z(""),W("elegant"),se(null),he(null)},Ce={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"},Me=ER[S],Pe=S==="home_anniversary"||S==="wedding_anniversary",Re=S==="wedding_anniversary"?"Wedding Anniversary Date":"Home Anniversary Date",Ae=["home_anniversary","just_listed","just_sold"].includes(S);return e.jsxs(_s,{open:d,onOpenChange:Be=>{Be?u(!0):(Ie(),l==null||l(!1))},children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{className:"gap-2",children:[e.jsx(Is,{className:"h-4 w-4"}),"Create Card"]})}),e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:h==="type"?"What type of card?":h==="contact"?`${Ce[S]} — Choose a Contact`:`${Ce[S]} — Customize`})}),h==="type"&&e.jsx(dsn,{onSelect:ge}),h==="contact"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>p("type"),children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to card types"]}),e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search contacts...",value:f,onChange:Be=>y(Be.target.value),className:"pl-9"})]}),e.jsxs("div",{className:"space-y-1 max-h-64 overflow-y-auto",children:[me==null?void 0:me.map(Be=>e.jsxs("button",{onClick:()=>ve(Be),className:"w-full flex items-center gap-3 p-3 rounded-lg hover:bg-accent text-left transition-colors",children:[e.jsx("div",{className:"h-9 w-9 rounded-full bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(Wi,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("p",{className:"text-sm font-medium truncate",children:[Be.first_name," ",Be.last_name]}),Be.address&&e.jsxs("p",{className:"text-xs text-muted-foreground truncate flex items-center gap-1",children:[e.jsx(Or,{className:"h-3 w-3"}),Be.address]})]}),(S==="home_anniversary"&&Be.home_anniversary||S==="wedding_anniversary"&&Be.wedding_anniversary)&&e.jsx("span",{className:"text-[10px] text-emerald-600 bg-emerald-500/10 px-2 py-0.5 rounded-full shrink-0",children:"Date set"})]},Be.id)),(me==null?void 0:me.length)===0&&e.jsx("p",{className:"text-sm text-muted-foreground text-center py-8",children:"No contacts found"})]}),e.jsx("div",{className:"border-t pt-3",children:e.jsx(B,{variant:"outline",size:"sm",className:"w-full",onClick:()=>{p("details")},children:"Skip — enter details manually"})})]}),h==="details"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1.5 -ml-2 text-muted-foreground",onClick:()=>p("contact"),children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back"]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Recipient Name"}),e.jsx(ye,{value:E,onChange:Be=>O(Be.target.value),placeholder:"John & Jane Smith"})]}),Ae&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Property Address"}),e.jsx(ye,{value:D,onChange:Be=>I(Be.target.value),placeholder:"123 Main St, Austin, TX"})]}),Pe&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:Re}),e.jsx(ye,{type:"date",value:F,onChange:Be=>z(Be.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Personal Message (optional)"}),e.jsx(Ms,{value:H,onChange:Be=>Z(Be.target.value),placeholder:Me.defaultMessage,rows:3})]}),e.jsx(tNt,{photoUrl:ee,videoUrl:oe,onPhotoChange:se,onVideoChange:he,contactId:_}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-5 gap-2",children:[{key:"elegant",label:"Elegant",gradient:"bg-gradient-to-br from-slate-100 to-blue-100 dark:from-slate-800 dark:to-slate-700"},{key:"bold",label:"Bold",gradient:"bg-gradient-to-br from-violet-500 to-fuchsia-500"},{key:"warm",label:"Warm",gradient:"bg-gradient-to-br from-amber-200 to-orange-300"},{key:"glass",label:"Glass",gradient:"bg-gradient-to-br from-slate-900 via-blue-900/50 to-slate-900 border border-white/10"},{key:"cinematic",label:"Cinema",gradient:"bg-gradient-to-br from-slate-950 via-blue-950 to-slate-950"}].map(({key:Be,label:we,gradient:Je})=>e.jsxs("button",{onClick:()=>W(Be),className:`p-2 rounded-lg border-2 transition-all text-center ${Y===Be?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-10 rounded-md mb-1.5 ${Je}`}),e.jsx("span",{className:"text-[10px] font-medium",children:we})]},Be))})]}),e.jsxs("div",{className:"flex gap-2 pt-2",children:[e.jsx(B,{variant:"outline",onClick:()=>p("contact"),className:"flex-1",children:"Back"}),e.jsx(B,{onClick:Te,disabled:!E||j,className:"flex-1 gap-2",children:j?"Creating...":"Create Card"})]})]})]})]})}function usn({open:s,onOpenChange:t}){const n=Ln(),r=a=>{t(!1),n(a)};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Set up an email sender"}),e.jsx(Jn,{children:"To send emails from the platform, connect Gmail or verify a Mass Email (Amazon SES) sender address. Either option lets you send from your own email."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("button",{onClick:()=>r("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(Gs,{className:"h-5 w-5 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Connect Gmail"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Send from your Google account with your full inbox history."})]})]}),e.jsxs("button",{onClick:()=>r("/integrations"),className:"w-full flex items-start gap-3 rounded-lg border p-4 text-left hover:bg-muted/50 transition",children:[e.jsx(H2,{className:"h-5 w-5 mt-0.5 text-primary"}),e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:"Verify a Mass Email sender"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Send via Amazon SES from any verified email address you own."})]})]}),e.jsx("div",{className:"flex justify-end pt-2",children:e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Not now"})})]})]})})}const hsn={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};function msn({card:s}){const{user:t}=vs(),{isGmailConnected:n,hasVerifiedSes:r,canSendEmail:a,sendMethod:i}=Dh(),l=Kt(),[o,c]=N.useState(!1),[d,u]=N.useState(!1),[h,p]=N.useState("");N.useEffect(()=>{o&&s.contact_id&&!h&&q.from("innercircle_contacts").select("email").eq("id",s.contact_id).maybeSingle().then(({data:E})=>{E!=null&&E.email&&p(E.email)})},[o,s.contact_id]);const f={home_anniversary:`🏡 Happy Home Anniversary, ${s.recipient_name}!`,wedding_anniversary:`💍 Happy Anniversary, ${s.recipient_name}!`,just_listed:`🏠 Just Listed — Check This Out, ${s.recipient_name}!`,just_sold:`🎉 Just Sold! Congrats, ${s.recipient_name}!`,congratulations:`🏆 Congratulations, ${s.recipient_name}!`,birthday:`🎂 Happy Birthday, ${s.recipient_name}!`,holiday:`🎄 Happy Holidays, ${s.recipient_name}!`,thank_you:`💐 Thank You, ${s.recipient_name}!`,thinking_of_you:`💭 Thinking of You, ${s.recipient_name}!`},[y,_]=N.useState(f[s.card_type]||`A Special Card for ${s.recipient_name}!`),[v,j]=N.useState(""),w=`https://cardstudio.relevelup.com/c/${s.share_token}`,S=yt({mutationFn:async()=>{var F;if(!h)throw new Error("Recipient email is required");const E=`
${v?`

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


`:""}

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

${s.property_address?`

${s.property_address}

`:""}
`,{data:O}=await q.auth.getSession(),D=(F=O==null?void 0:O.session)==null?void 0:F.access_token,I=await fetch("https://relzejiswnotikjgvjhz.supabase.co/functions/v1/gmail-send",{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${D}`},body:JSON.stringify({to:h,subject:y,body:E,contactId:s.contact_id||void 0})});if(!I.ok){const z=await I.json();throw new Error(z.error||"Failed to send")}return I.json()},onSuccess:async()=>{await q.from("sendable_cards").update({sent_at:new Date().toISOString(),sent_via:"gmail"}).eq("id",s.id),l.invalidateQueries({queryKey:["sendable-cards"]}),ae.success(`Card sent to ${h}!`),c(!1)},onError:E=>{ae.error(E.message||"Failed to send email")}}),A=i==="mass_email"?"Mass Email":"Gmail";return a?e.jsxs(_s,{open:o,onOpenChange:c,children:[e.jsx(ki,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(lr,{className:"h-3 w-3"})})}),e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsx(js,{children:e.jsxs(ws,{children:["Send Card via ",A]})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{htmlFor:"gmail-to",children:"To"}),e.jsx(n_t,{value:h,onChange:p,userId:t==null?void 0:t.id,placeholder:"Search contacts or type an email..."}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Pick from your Agent OS contacts, or type any email address."})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Subject"}),e.jsx(ye,{value:y,onChange:E=>_(E.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Personal Note (optional)"}),e.jsx(Ms,{value:v,onChange:E=>j(E.target.value),placeholder:"Add a warm personal note before the card link...",rows:3})]}),e.jsxs("div",{className:"rounded-lg bg-muted/50 p-3 text-xs text-muted-foreground",children:[i==="mass_email"?e.jsx(e.Fragment,{children:"Sending via your verified Mass Email sender (Gmail isn't connected)."}):e.jsx(e.Fragment,{children:"The email will include a beautiful button linking to your card at:"}),e.jsx("br",{}),e.jsx("span",{className:"font-mono text-foreground",children:w})]}),e.jsx(B,{onClick:()=>S.mutate(),disabled:!h||S.isPending,className:"w-full gap-2",children:S.isPending?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"})," Sending..."]}):e.jsxs(e.Fragment,{children:[e.jsx(lr,{className:"h-4 w-4"})," Send Card"]})})]})]})]}):e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",title:"Set up an email sender to send cards",onClick:()=>u(!0),children:e.jsx(lr,{className:"h-3 w-3"})}),e.jsx(usn,{open:d,onOpenChange:u})]})}function psn({card:s}){const t=Kt(),[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(s.recipient_name),[c,d]=N.useState(s.property_address||""),[u,h]=N.useState(s.home_anniversary_date||""),[p,f]=N.useState(s.custom_message||""),[y,_]=N.useState(s.template),[v,j]=N.useState(s.property_photo_url),[w,S]=N.useState(s.video_url||null),A=O=>{O&&(o(s.recipient_name),d(s.property_address||""),h(s.home_anniversary_date||""),f(s.custom_message||""),_(s.template),j(s.property_photo_url),S(s.video_url||null)),r(O)},E=async()=>{if(!l.trim()){ae.error("Recipient name is required");return}i(!0);try{const{error:O}=await q.from("sendable_cards").update({recipient_name:l.trim(),property_address:c.trim()||null,home_anniversary_date:u||null,custom_message:p.trim()||null,template:y,property_photo_url:v||null,video_url:w||null}).eq("id",s.id);if(O)throw O;t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card updated"),r(!1)}catch(O){ae.error(O.message||"Failed to update card")}finally{i(!1)}};return e.jsxs(_s,{open:n,onOpenChange:A,children:[e.jsx(ki,{asChild:!0,children:e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",children:e.jsx(ya,{className:"h-3 w-3"})})}),e.jsxs(bs,{className:"sm:max-w-lg max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Edit Card"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Recipient Name"}),e.jsx(ye,{value:l,onChange:O=>o(O.target.value),placeholder:"John & Jane Smith"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Property Address"}),e.jsx(ye,{value:c,onChange:O=>d(O.target.value),placeholder:"123 Main St, Austin, TX"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Home Anniversary Date"}),e.jsx(ye,{type:"date",value:u,onChange:O=>h(O.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Personal Message (optional)"}),e.jsx(Ms,{value:p,onChange:O=>f(O.target.value),placeholder:"Wishing you many more happy years in your beautiful home!",rows:3})]}),e.jsx(tNt,{photoUrl:v,videoUrl:w,onPhotoChange:j,onVideoChange:S,contactId:s.contact_id}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Template Style"}),e.jsx("div",{className:"grid grid-cols-3 gap-2",children:["elegant","bold","warm"].map(O=>e.jsxs("button",{onClick:()=>_(O),className:`p-3 rounded-lg border-2 transition-all text-center ${y===O?"border-primary bg-primary/5":"border-border hover:border-primary/30"}`,children:[e.jsx("div",{className:`h-12 rounded-md mb-2 ${O==="elegant"?"bg-gradient-to-br from-slate-100 to-slate-200 dark:from-slate-800 dark:to-slate-700":O==="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:O})]},O))})]}),e.jsx(B,{onClick:E,disabled:!l.trim()||a,className:"w-full gap-2",children:a?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 animate-spin"})," Saving..."]}):"Save Changes"})]})]})]})}function fsn(){const{user:s}=vs(),t=Kt(),[n,r]=N.useState(""),[a,i]=xl(),l=a.get("cardType"),o=a.get("contactId"),c=a.get("name"),d=a.get("address"),u=a.get("date"),h=!!l,{data:p,isLoading:f}=dt({queryKey:["sendable-cards",s==null?void 0:s.id],queryFn:async()=>{const{data:S,error:A}=await q.from("sendable_cards").select("*").eq("owner_user_id",s.id).order("created_at",{ascending:!1});if(A)throw A;return S},enabled:!!(s!=null&&s.id)}),y=yt({mutationFn:async S=>{const{error:A}=await q.from("sendable_cards").delete().eq("id",S);if(A)throw A},onSuccess:()=>{t.invalidateQueries({queryKey:["sendable-cards"]}),ae.success("Card deleted")}}),_=S=>{const A=`https://cardstudio.relevelup.com/c/${S}`;navigator.clipboard.writeText(A),ae.success("Share link copied!")},v=p==null?void 0:p.filter(S=>{var A;return!n||S.recipient_name.toLowerCase().includes(n.toLowerCase())||((A=S.property_address)==null?void 0:A.toLowerCase().includes(n.toLowerCase()))}),j={elegant:"Elegant",bold:"Bold",warm:"Warm"},w={home_anniversary:"Home Anniversary",wedding_anniversary:"Wedding Anniversary",just_listed:"Just Listed",just_sold:"Just Sold",congratulations:"Congratulations",birthday:"Birthday",holiday:"Holiday",thank_you:"Thank You",thinking_of_you:"Thinking of You"};return e.jsx(Cs,{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(bXe,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]}),e.jsxs("div",{className:"relative max-w-sm",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground"}),e.jsx(ye,{placeholder:"Search cards...",value:n,onChange:S=>r(S.target.value),className:"pl-9"})]}),f?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3].map(S=>e.jsx(fe,{className:"animate-pulse",children:e.jsxs(Ee,{className:"p-4",children:[e.jsx("div",{className:"h-40 bg-muted rounded-lg mb-3"}),e.jsx("div",{className:"h-4 bg-muted rounded w-2/3 mb-2"}),e.jsx("div",{className:"h-3 bg-muted rounded w-1/2"})]})},S))}):v!=null&&v.length?e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4",children:v.map(S=>e.jsxs(fe,{className:"group overflow-hidden hover:shadow-lg transition-shadow",children:[e.jsxs("div",{className:`aspect-[16/10] flex items-center justify-center relative overflow-hidden ${S.template==="elegant"?"bg-gradient-to-br from-slate-50 via-slate-100 to-slate-200 dark:from-slate-900 dark:via-slate-800 dark:to-slate-700":S.template==="bold"?"bg-gradient-to-br from-violet-600 via-fuchsia-500 to-pink-500":"bg-gradient-to-br from-amber-100 via-orange-200 to-rose-200 dark:from-amber-900 dark:via-orange-800 dark:to-rose-800"}`,children:[S.template==="elegant"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"absolute top-0 left-0 w-full h-full opacity-10",children:[e.jsx("div",{className:"absolute top-3 left-3 w-16 h-16 border-t-2 border-l-2 border-primary/40 rounded-tl-lg"}),e.jsx("div",{className:"absolute bottom-3 right-3 w-16 h-16 border-b-2 border-r-2 border-primary/40 rounded-br-lg"})]}),e.jsx("div",{className:"absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 w-32 h-32 rounded-full border border-primary/10"})]}),S.template==="bold"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-8 -right-8 w-32 h-32 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute -bottom-6 -left-6 w-24 h-24 rounded-full bg-white/10 blur-sm"}),e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(ellipse_at_center,rgba(255,255,255,0.15)_0%,transparent_70%)]"})]}),S.template==="warm"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"absolute -top-4 -left-4 w-28 h-28 rounded-full bg-orange-400/15 blur-md"}),e.jsx("div",{className:"absolute -bottom-6 -right-6 w-32 h-32 rounded-full bg-rose-400/15 blur-md"})]}),e.jsxs("div",{className:"text-center px-4 relative z-10",children:[e.jsx("div",{className:"text-3xl mb-1.5 opacity-80",children:S.card_type==="home_anniversary"?"🏡":S.card_type==="wedding_anniversary"?"💍":S.card_type==="birthday"?"🎂":S.card_type==="just_sold"?"🎉":S.card_type==="just_listed"?"🏠":S.card_type==="thank_you"?"💐":S.card_type==="congratulations"?"🏆":S.card_type==="holiday"?"🎄":S.card_type==="thinking_of_you"?"💭":"✉️"}),e.jsx("p",{className:`text-[10px] uppercase tracking-[0.2em] mb-1 ${S.template==="bold"?"text-white/70":"text-muted-foreground"}`,children:w[S.card_type]||S.card_type}),e.jsx("p",{className:`font-semibold text-base ${S.template==="bold"?"text-white":"text-foreground"}`,children:S.recipient_name}),S.property_address&&e.jsx("p",{className:`text-xs mt-1 ${S.template==="bold"?"text-white/60":"text-muted-foreground"}`,children:S.property_address})]}),e.jsx("div",{className:"absolute top-2 right-2 z-10",children:e.jsx(Ue,{variant:S.template==="bold"?"outline":"secondary",className:`text-[10px] ${S.template==="bold"?"border-white/30 text-white/80":""}`,children:j[S.template]||S.template})})]}),e.jsxs(Ee,{className:"p-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(Sr,{className:"h-3 w-3"}),S.view_count," views"]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:Uo(new Date(S.created_at),{addSuffix:!0})})]}),S.sent_at&&e.jsxs("p",{className:"text-[10px] text-emerald-600 mb-2",children:["Sent ",Ss(new Date(S.sent_at),"MMM d, yyyy")," via ",S.sent_via]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"flex-1 gap-1 text-xs",onClick:()=>_(S.share_token),children:[e.jsx(Zr,{className:"h-3 w-3"}),"Copy Link"]}),e.jsx(psn,{card:S}),e.jsx(msn,{card:S}),e.jsx(B,{variant:"outline",size:"sm",className:"gap-1 text-xs",onClick:()=>window.open(`https://cardstudio.relevelup.com/c/${S.share_token}`,"_blank"),children:e.jsx(tr,{className:"h-3 w-3"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-destructive hover:text-destructive gap-1 text-xs",onClick:()=>y.mutate(S.id),children:e.jsx(_n,{className:"h-3 w-3"})})]})]})]},S.id))}):e.jsx(fe,{className:"border-dashed",children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx("div",{className:"h-16 w-16 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:e.jsx(Gs,{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(bXe,{initialOpen:h,initialCardType:l,initialContactId:o||void 0,initialRecipientName:c||void 0,initialAddress:d||void 0,initialDate:u||void 0,onOpenChange:()=>i({})})]})})]})})}const _G=[{id:"mls",label:"MLS Description",tag:"Standard",icon:Or,accent:"from-sky-500 to-cyan-500",desc:"Polished MLS-ready listing",category:"listing"},{id:"luxury",label:"Luxury MLS",tag:"Premium",icon:hf,accent:"from-amber-500 to-orange-500",desc:"Evocative, high-end voice",category:"listing"},{id:"short",label:"Short MLS",tag:"Concise",icon:im,accent:"from-violet-500 to-fuchsia-500",desc:"Punchy 60–90 words",category:"listing"},{id:"openHouse",label:"Open House",tag:"Promo",icon:hw,accent:"from-emerald-500 to-teal-500",desc:"Friendly invite copy",category:"listing",extras:["openHouse"]},{id:"newConstruction",label:"New Construction",tag:"Build",icon:K7,accent:"from-rose-500 to-pink-500",desc:"Builder-focused angle",category:"listing",extras:["newConstruction"]},{id:"investment",label:"Investment",tag:"ROI",icon:go,accent:"from-indigo-500 to-blue-500",desc:"Cap rate & income hooks",category:"listing",extras:["investment"]},{id:"facebookPost",label:"Facebook Post",tag:"Social",icon:Mh,accent:"from-blue-600 to-blue-400",desc:"Engaging FB caption",category:"social"},{id:"instagramPost",label:"Instagram Post",tag:"Social",icon:ou,accent:"from-pink-500 via-fuchsia-500 to-orange-400",desc:"IG caption + hashtags",category:"social"},{id:"linkedinPost",label:"LinkedIn Post",tag:"Social",icon:xf,accent:"from-sky-700 to-sky-500",desc:"Professional tone",category:"social"},{id:"justListed",label:"Just Listed",tag:"Announce",icon:zd,accent:"from-emerald-500 to-green-500",desc:"Hit the market announcement",category:"social"},{id:"comingSoon",label:"Coming Soon",tag:"Tease",icon:pr,accent:"from-amber-500 to-yellow-500",desc:"Build pre-market buzz",category:"social",extras:["comingSoon"]},{id:"priceImprovement",label:"Price Improvement",tag:"Update",icon:fb,accent:"from-orange-500 to-red-500",desc:"New price announcement",category:"social",extras:["priceImprovement"]},{id:"openHousePost",label:"Open House Post",tag:"Event",icon:Cl,accent:"from-teal-500 to-emerald-500",desc:"Social invite to OH",category:"social",extras:["openHouse"]},{id:"underContract",label:"Under Contract",tag:"Status",icon:V7,accent:"from-indigo-500 to-purple-500",desc:"Pending celebration",category:"social",extras:["underContract"]},{id:"justSold",label:"Just Sold",tag:"Celebrate",icon:ih,accent:"from-fuchsia-500 to-pink-500",desc:"Sold success post",category:"social",extras:["sold"]},{id:"propertyTourScript",label:"Property Tour",tag:"Script",icon:fr,accent:"from-red-500 to-rose-500",desc:"Full walkthrough script",category:"video",extras:["signoff"]},{id:"reelScript",label:"Reel Script",tag:"Short",icon:Sh,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:Dv,accent:"from-violet-500 to-purple-500",desc:"5 scroll-stopping hooks",category:"video",extras:["vibe"]},{id:"luxuryWalkthrough",label:"Luxury Walkthrough",tag:"Premium",icon:hf,accent:"from-amber-500 to-yellow-500",desc:"Cinematic, refined tone",category:"video",extras:["signoff"]},{id:"droneScript",label:"Drone Script",tag:"Aerial",icon:l9,accent:"from-sky-500 to-blue-500",desc:"Voiceover for aerial b-roll",category:"video",extras:["signoff"]},{id:"neighborhoodTour",label:"Neighborhood Tour",tag:"Local",icon:ka,accent:"from-emerald-500 to-teal-500",desc:"Area lifestyle script",category:"video",extras:["neighborhood","signoff"]},{id:"justListedEmail",label:"Just Listed Email",tag:"Announce",icon:Gs,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:nL,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:An,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:fb,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:BS,accent:"from-fuchsia-500 to-pink-500",desc:"Sold announcement email",category:"email",extras:["sold","signoff"]},{id:"neighborhoodEmail",label:"Neighborhood Email",tag:"Nurture",icon:ka,accent:"from-sky-500 to-indigo-500",desc:"Area update / market touch",category:"email",extras:["neighborhood","signoff"]}];function xsn(){var xa,Ki,io,Xa,Mr,qi,Vi,si,Yi,Zi,aa;const{user:s}=vs(),[t,n]=N.useState(""),[r,a]=N.useState(""),[i,l]=N.useState([]),[o,c]=N.useState(""),[d,u]=N.useState([]),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState(""),[S,A]=N.useState(""),[E,O]=N.useState(""),[D,I]=N.useState(""),[F,z]=N.useState(null),[H,Z]=N.useState(""),[Y,W]=N.useState(""),[ee,se]=N.useState(""),[oe,he]=N.useState(""),[ce,me]=N.useState(""),[le,ve]=N.useState(""),[ge,Te]=N.useState(""),[Ie,Ce]=N.useState(""),[Me,Pe]=N.useState(""),[Re,Ae]=N.useState(""),[Be,we]=N.useState(""),[Je,ke]=N.useState(""),[it,je]=N.useState(""),[He,$e]=N.useState(""),[Ke,Ge]=N.useState(""),[rt,tt]=N.useState(""),[at,Ye]=N.useState(""),[ut,_t]=N.useState(""),[bt,$t]=N.useState(""),[Yt,Ds]=N.useState(""),[Ls,xs]=N.useState(""),[Lt,Jt]=N.useState(""),[gt,zt]=N.useState(""),[As,Xt]=N.useState(""),[Qs,ks]=N.useState(""),[$s,an]=N.useState("listing"),[tn,er]=N.useState("mls"),[xn,Pn]=N.useState({}),[Qn,sa]=N.useState({}),[na,Es]=N.useState(!1),[mi,Ar]=N.useState(!1),Hn=Nn=>{an(Nn);const La=_G.find(so=>so.category===Nn);La&&er(La.id)},{data:Ts}=dt({queryKey:["listing-studio-listings",s==null?void 0:s.id],enabled:!!(s!=null&&s.id)&&na,queryFn:async()=>{const{data:Nn,error:La}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, property_type, description").eq("agent_id",s.id).order("created_at",{ascending:!1}).limit(50);if(La)throw La;return Nn||[]}}),Un=()=>{const Nn=o.trim();Nn&&(l(La=>[...La,Nn]),c(""))},ir=Nn=>l(La=>La.filter((so,tl)=>tl!==Nn)),Tr=Nn=>{var La,so,tl,jl;z(Nn.id),n(Nn.property_address||""),O(Nn.city||""),I(Nn.state||""),w(((La=Nn.price)==null?void 0:La.toString())||""),p(((so=Nn.bedrooms)==null?void 0:so.toString())||""),y(((tl=Nn.bathrooms)==null?void 0:tl.toString())||""),v(((jl=Nn.square_footage)==null?void 0:jl.toString())||""),A(Nn.property_type||""),a(Nn.description||""),Es(!1),ae.success("Listing imported")},ts=async Nn=>{if(!(!Nn.target.files||!(s!=null&&s.id))){Ar(!0);try{const La=[];for(const so of Array.from(Nn.target.files).slice(0,10)){const tl=`${s.id}/${Date.now()}-${so.name.replace(/[^\w.-]/g,"_")}`,{error:jl}=await q.storage.from("listing-photos").upload(tl,so,{upsert:!1});if(jl){console.error(jl);continue}const{data:No}=q.storage.from("listing-photos").getPublicUrl(tl);La.push(No.publicUrl)}u(so=>[...so,...La]),La.length&&ae.success(`${La.length} photo(s) uploaded`)}catch(La){ae.error(La.message||"Photo upload failed")}finally{Ar(!1)}}},Fe=_G.find(Nn=>Nn.id===tn),Qe=async Nn=>{var so,tl,jl;const La=_G.find(No=>No.id===Nn);if(!t.trim()&&!r.trim()&&i.length===0){ae.error("Add a property address, MLS remarks, or features first");return}if((so=La.extras)!=null&&so.includes("openHouse")&&(!H||!Y||!ee)){ae.error("Add the open house date, start and end time");return}if((tl=La.extras)!=null&&tl.includes("priceImprovement")&&(!oe||!ce)){ae.error("Add previous and new price");return}if((jl=La.extras)!=null&&jl.includes("sold")&&!le){ae.error("Add the sold price");return}er(Nn),sa(No=>({...No,[Nn]:!0}));try{const{data:No,error:jd}=await q.functions.invoke("listing-studio-generate",{body:{copyType:Nn,propertyAddress:t,mlsRemarks:r,features:i,photoUrls:d,listingId:F,bedrooms:h?Number(h):null,bathrooms:f?Number(f):null,squareFootage:_?Number(_):null,price:j?Number(j):null,propertyType:S||null,city:E||null,state:D||null,openHouseDate:H||null,openHouseStart:Y||null,openHouseEnd:ee||null,previousPrice:oe?Number(oe):null,newPrice:ce?Number(ce):null,soldPrice:le?Number(le):null,soldDate:ge||null,comingSoonDate:Ie||null,builderName:Me||null,yearBuilt:Re?Number(Re):null,warrantyInfo:Be||null,monthlyRent:Je?Number(Je):null,capRate:it||null,occupancy:He||null,daysOnMarket:Ke?Number(Ke):null,offerCount:rt?Number(rt):null,originalListPrice:at?Number(at):null,soldDaysOnMarket:ut?Number(ut):null,commissionOffered:bt||null,refreshments:Yt||null,vibe:Ls||null,neighborhoodHighlights:Lt||null,agentName:gt||null,agentBrokerage:As||null,agentContact:Qs||null}});if(jd)throw jd;if(No!=null&&No.error)throw new Error(No.error);Pn(Bu=>({...Bu,[Nn]:No.content}))}catch(No){ae.error(No.message||"Generation failed")}finally{sa(No=>({...No,[Nn]:!1}))}},ot=Nn=>{navigator.clipboard.writeText(Nn),ae.success("Copied to clipboard")},St=Fe.icon,Bt=xn[tn]?xn[tn].trim().split(/\s+/).length:0,Vt=Nn=>e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3",children:_G.filter(La=>La.category===Nn).map(La=>{const so=La.icon,tl=tn===La.id,jl=!!xn[La.id];return e.jsxs("button",{onClick:()=>er(La.id),className:Mt("relative text-left p-4 rounded-2xl border transition-all overflow-hidden group",tl?"border-primary shadow-lg shadow-primary/10 bg-card":"border-border/60 hover:border-border bg-card/50 hover:bg-card"),children:[tl&&e.jsx("div",{className:Mt("absolute inset-0 opacity-[0.07] bg-gradient-to-br",La.accent)}),e.jsxs("div",{className:"relative space-y-2",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:Mt("h-9 w-9 rounded-xl grid place-items-center text-white bg-gradient-to-br shadow-sm",La.accent),children:e.jsx(so,{className:"h-4 w-4"})}),jl&&e.jsx("div",{className:"h-5 w-5 rounded-full bg-emerald-500/15 text-emerald-600 grid place-items-center",children:e.jsx(Lr,{className:"h-3 w-3"})})]}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold text-sm",children:La.label}),e.jsx("div",{className:"text-xs text-muted-foreground line-clamp-1",children:La.desc})]})]})]},La.id)})}),fs=(xa=Fe.extras)==null?void 0:xa.includes("openHouse"),lt=(Ki=Fe.extras)==null?void 0:Ki.includes("priceImprovement"),ns=(io=Fe.extras)==null?void 0:io.includes("sold"),Vs=(Xa=Fe.extras)==null?void 0:Xa.includes("comingSoon"),ys=(Mr=Fe.extras)==null?void 0:Mr.includes("newConstruction"),mn=(qi=Fe.extras)==null?void 0:qi.includes("investment"),On=(Vi=Fe.extras)==null?void 0:Vi.includes("underContract"),vn=(si=Fe.extras)==null?void 0:si.includes("brokerOpen"),Yn=(Yi=Fe.extras)==null?void 0:Yi.includes("vibe"),_r=(Zi=Fe.extras)==null?void 0:Zi.includes("neighborhood"),wr=(aa=Fe.extras)==null?void 0:aa.includes("signoff"),Er=fs||lt||ns||Vs||ys||mn||On||vn||Yn||_r||wr;return e.jsx(Cs,{title:"Listing Studio",children:e.jsxs("div",{className:"space-y-8 animate-fade-in",children:[e.jsxs("div",{className:"relative overflow-hidden rounded-3xl border bg-gradient-to-br from-fuchsia-500/10 via-violet-500/5 to-sky-500/10 dark:from-fuchsia-500/20 dark:via-violet-500/10 dark:to-sky-500/20",children:[e.jsx("div",{className:"absolute inset-0 bg-[radial-gradient(circle_at_top_right,_hsl(var(--primary)/0.15),_transparent_60%)]"}),e.jsx("div",{className:"absolute -top-24 -right-24 h-72 w-72 rounded-full bg-fuchsia-500/20 blur-3xl"}),e.jsx("div",{className:"absolute -bottom-24 -left-24 h-72 w-72 rounded-full bg-sky-500/20 blur-3xl"}),e.jsxs("div",{className:"relative px-6 py-8 sm:px-10 sm:py-12 flex flex-col md:flex-row md:items-center gap-6",children:[e.jsxs("div",{className:"flex-1 space-y-3",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 px-3 py-1 rounded-full bg-background/60 backdrop-blur-sm border text-xs font-medium",children:[e.jsx(un,{className:"h-3.5 w-3.5 text-fuchsia-500"}),"AI-powered listing & social copy"]}),e.jsx("h1",{className:"text-3xl sm:text-4xl font-bold tracking-tight bg-gradient-to-br from-foreground to-foreground/60 bg-clip-text",children:"Listing Studio"}),e.jsx("p",{className:"text-muted-foreground max-w-xl",children:"Drop in a property, generate magnetic MLS copy, luxury narratives, open-house promos, and ready-to-post social content — all in seconds."})]}),e.jsxs(_s,{open:na,onOpenChange:Es,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"lg",variant:"secondary",className:"shadow-lg shadow-fuchsia-500/10",children:[e.jsx(br,{className:"h-4 w-4 mr-2"}),"Import from Listings"]})}),e.jsxs(bs,{className:"max-w-2xl max-h-[80vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:"Import from Listing Exchange"})}),e.jsxs("div",{className:"space-y-2 mt-2",children:[!(Ts!=null&&Ts.length)&&e.jsx("p",{className:"text-sm text-muted-foreground py-8 text-center",children:"No listings found yet."}),Ts==null?void 0:Ts.map(Nn=>e.jsxs("button",{onClick:()=>Tr(Nn),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:Nn.property_address||"Untitled listing"}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[[Nn.city,Nn.state].filter(Boolean).join(", "),Nn.price?` · $${Number(Nn.price).toLocaleString()}`:"",Nn.bedrooms?` · ${Nn.bedrooms}bd`:"",Nn.bathrooms?` · ${Nn.bathrooms}ba`:""]})]},Nn.id))]})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-6",children:[e.jsx(fe,{className:"lg:col-span-2 border-border/60 shadow-sm",children:e.jsxs(Ee,{className:"p-6 space-y-5",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 grid place-items-center",children:e.jsx(Or,{className:"h-4 w-4 text-primary"})}),e.jsxs("div",{children:[e.jsx("div",{className:"font-semibold",children:"Property Details"}),e.jsx("div",{className:"text-xs text-muted-foreground",children:"Fill in what you have — AI handles the rest"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Address"}),e.jsx(ye,{value:t,onChange:Nn=>n(Nn.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(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"City"}),e.jsx(ye,{value:E,onChange:Nn=>O(Nn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"State"}),e.jsx(ye,{value:D,onChange:Nn=>I(Nn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Price"}),e.jsx(ye,{type:"number",value:j,onChange:Nn=>w(Nn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Type"}),e.jsx(ye,{value:S,onChange:Nn=>A(Nn.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(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Beds"}),e.jsx(ye,{type:"number",value:h,onChange:Nn=>p(Nn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Baths"}),e.jsx(ye,{type:"number",step:"0.5",value:f,onChange:Nn=>y(Nn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sqft"}),e.jsx(ye,{type:"number",value:_,onChange:Nn=>v(Nn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"MLS Remarks / Notes"}),e.jsx(Ms,{value:r,onChange:Nn=>a(Nn.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(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Features"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:o,onChange:Nn=>c(Nn.target.value),onKeyDown:Nn=>Nn.key==="Enter"&&(Nn.preventDefault(),Un()),placeholder:"e.g. Quartz countertops"}),e.jsx(B,{type:"button",size:"icon",variant:"secondary",onClick:Un,children:e.jsx(Is,{className:"h-4 w-4"})})]}),i.length>0&&e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-2 animate-fade-in",children:i.map((Nn,La)=>e.jsxs(Ue,{variant:"secondary",className:"pl-3 pr-1 py-1 gap-1",children:[Nn,e.jsx("button",{onClick:()=>ir(La),className:"ml-0.5 p-0.5 hover:bg-background/60 rounded-full",children:e.jsx($n,{className:"h-3 w-3"})})]},La))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{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(ty,{className:"h-4 w-4"}),mi?"Uploading…":"Click to upload photos",e.jsx("input",{type:"file",accept:"image/*",multiple:!0,onChange:ts,disabled:mi,className:"hidden"})]}),d.length>0&&e.jsx("div",{className:"grid grid-cols-4 gap-2 mt-2",children:d.map((Nn,La)=>e.jsxs("div",{className:"relative aspect-square rounded-lg overflow-hidden group",children:[e.jsx("img",{src:Nn,alt:"",className:"w-full h-full object-cover"}),e.jsx("button",{onClick:()=>u(so=>so.filter((tl,jl)=>jl!==La)),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($n,{className:"h-3 w-3"})})]},La))})]}),Er&&e.jsxs("div",{className:"space-y-4 p-4 rounded-xl border border-dashed border-primary/40 bg-primary/5 animate-fade-in",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-primary"}),e.jsxs("div",{className:"text-sm font-semibold",children:["Extra info for ",Fe.label]})]}),fs&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Date"}),e.jsx(ye,{type:"date",value:H,onChange:Nn=>Z(Nn.target.value)})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Start"}),e.jsx(ye,{type:"time",value:Y,onChange:Nn=>W(Nn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"End"}),e.jsx(ye,{type:"time",value:ee,onChange:Nn=>se(Nn.target.value)})]})]})]}),lt&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Previous Price"}),e.jsx(ye,{type:"number",value:oe,onChange:Nn=>he(Nn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"New Price"}),e.jsx(ye,{type:"number",value:ce,onChange:Nn=>me(Nn.target.value),placeholder:"$"})]})]}),ns&&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(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Price"}),e.jsx(ye,{type:"number",value:le,onChange:Nn=>ve(Nn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Sold Date"}),e.jsx(ye,{type:"date",value:ge,onChange:Nn=>Te(Nn.target.value)})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Original List Price (optional)"}),e.jsx(ye,{type:"number",value:at,onChange:Nn=>Ye(Nn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ye,{type:"number",value:ut,onChange:Nn=>_t(Nn.target.value)})]})]})]}),Vs&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Expected Live Date (optional)"}),e.jsx(ye,{type:"date",value:Ie,onChange:Nn=>Ce(Nn.target.value)})]}),ys&&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(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Builder Name"}),e.jsx(ye,{value:Me,onChange:Nn=>Pe(Nn.target.value),placeholder:"ABC Homes"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Year Built"}),e.jsx(ye,{type:"number",value:Re,onChange:Nn=>Ae(Nn.target.value),placeholder:"2026"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Warranty / Energy / Smart-home (optional)"}),e.jsx(ye,{value:Be,onChange:Nn=>we(Nn.target.value),placeholder:"10-yr structural, ENERGY STAR, smart-home pkg"})]})]}),mn&&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(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Monthly Rent (optional)"}),e.jsx(ye,{type:"number",value:Je,onChange:Nn=>ke(Nn.target.value),placeholder:"$"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Cap Rate (optional)"}),e.jsx(ye,{value:it,onChange:Nn=>je(Nn.target.value),placeholder:"6.5%"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Occupancy"}),e.jsxs("select",{value:He,onChange:Nn=>$e(Nn.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"})]})]})]}),On&&e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Days on Market (optional)"}),e.jsx(ye,{type:"number",value:Ke,onChange:Nn=>Ge(Nn.target.value),placeholder:"e.g. 3"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"# of Offers (optional)"}),e.jsx(ye,{type:"number",value:rt,onChange:Nn=>tt(Nn.target.value),placeholder:"e.g. 5"})]})]}),vn&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Commission / Co-op Offered (optional)"}),e.jsx(ye,{value:bt,onChange:Nn=>$t(Nn.target.value),placeholder:"2.5% buyer agent commission"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Refreshments / Perks (optional)"}),e.jsx(ye,{value:Yt,onChange:Nn=>Ds(Nn.target.value),placeholder:"Lunch + raffle for $100 gift card"})]})]}),Yn&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Vibe / Tone"}),e.jsxs("select",{value:Ls,onChange:Nn=>xs(Nn.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"})]})]}),_r&&e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Nearby Highlights (optional)"}),e.jsx(Ms,{value:Lt,onChange:Nn=>Jt(Nn.target.value),rows:3,placeholder:"Top schools, parks, coffee shops, restaurants, commute, walkability…"})]}),wr&&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(ne,{className:"text-xs font-medium text-muted-foreground",children:"Agent Name"}),e.jsx(ye,{value:gt,onChange:Nn=>zt(Nn.target.value)})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Brokerage"}),e.jsx(ye,{value:As,onChange:Nn=>Xt(Nn.target.value)})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{className:"text-xs font-medium text-muted-foreground",children:"Phone / Email"}),e.jsx(ye,{value:Qs,onChange:Nn=>ks(Nn.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:br},{key:"social",label:"Social Media",icon:ou},{key:"video",label:"Video Scripts",icon:fr},{key:"email",label:"Email Marketing",icon:Gs}].map(Nn=>{const La=Nn.icon,so=$s===Nn.key;return e.jsxs("button",{onClick:()=>Hn(Nn.key),className:Mt("flex-1 flex items-center justify-center gap-2 px-4 py-2.5 rounded-lg text-sm font-medium transition-all",so?"bg-card shadow-sm text-foreground border border-border/60":"text-muted-foreground hover:text-foreground hover:bg-background/50"),children:[e.jsx(La,{className:"h-4 w-4"}),Nn.label]},Nn.key)})}),Vt($s),e.jsxs(fe,{className:"border-border/60 shadow-sm overflow-hidden",children:[e.jsx("div",{className:Mt("h-1 bg-gradient-to-r",Fe.accent)}),e.jsxs(Ee,{className:"p-6 space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:Mt("h-10 w-10 rounded-xl grid place-items-center text-white bg-gradient-to-br",Fe.accent),children:e.jsx(St,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsxs("div",{className:"font-semibold flex items-center gap-2",children:[Fe.label,e.jsx(Ue,{variant:"outline",className:"text-[10px] font-normal",children:Fe.tag})]}),e.jsx("div",{className:"text-xs text-muted-foreground",children:xn[tn]?`${Bt} words`:"Ready to generate"})]})]}),e.jsxs("div",{className:"flex gap-2",children:[xn[tn]&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>ot(xn[tn]),children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Copy"]}),e.jsx(B,{onClick:()=>Qe(tn),disabled:Qn[tn],className:Mt("shadow-lg shadow-primary/10 bg-gradient-to-r text-white border-0 hover:opacity-90",Fe.accent),size:"sm",children:Qn[tn]?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-4 w-4 mr-2 animate-spin"})," Generating"]}):xn[tn]?e.jsxs(e.Fragment,{children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"})," Regenerate"]}):e.jsxs(e.Fragment,{children:[e.jsx(Im,{className:"h-4 w-4 mr-2"})," Generate"]})})]})]}),xn[tn]?e.jsx(Ms,{value:xn[tn],onChange:Nn=>Pn(La=>({...La,[tn]:Nn.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:Mt("mx-auto h-14 w-14 rounded-2xl grid place-items-center text-white bg-gradient-to-br mb-4",Fe.accent),children:e.jsx(Im,{className:"h-6 w-6"})}),e.jsxs("div",{className:"font-medium mb-1",children:["Generate a ",Fe.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 IF({delay:s,x:t,y:n,size:r}){return e.jsx(Zn.div,{className:"absolute rounded-full bg-slate-300/30 dark:bg-slate-500/20",style:{left:t,top:n,width:r,height:r},animate:{y:[0,-20,0],opacity:[.3,.7,.3],scale:[1,1.2,1]},transition:{duration:4,delay:s,repeat:1/0,ease:"easeInOut"}})}function gsn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=ER[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(Zn.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(Zn.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(IF,{delay:0,x:"15%",y:"20%",size:8}),e.jsx(IF,{delay:1,x:"80%",y:"30%",size:6}),e.jsx(IF,{delay:2,x:"60%",y:"70%",size:10}),e.jsx(IF,{delay:.5,x:"25%",y:"80%",size:7}),e.jsx(IF,{delay:1.5,x:"70%",y:"15%",size:5})]}),e.jsxs(Zn.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(Zn.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(Zn.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(Zn.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(Zn.div,{className:"absolute inset-0 rounded-2xl border-2 border-slate-200/50 dark:border-slate-600/50",animate:{scale:[1,1.15,1],opacity:[.5,0,.5]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl",children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Zn.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(Zn.h1,{className:"text-4xl font-light text-slate-800 dark:text-slate-100 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Zn.h2,{className:"text-4xl font-bold text-slate-800 dark:text-slate-100 mb-8 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:f.title[1]}),e.jsxs(Zn.div,{initial:{opacity:0},animate:{opacity:1},transition:{duration:.5,delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-slate-700 dark:text-slate-200 mb-1",children:n}),r&&e.jsx("p",{className:"text-sm text-slate-400 dark:text-slate-500 mb-6",children:r})]}),e.jsx(Zn.div,{className:"h-px bg-gradient-to-r from-transparent via-slate-300 dark:via-slate-600 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"80%"},transition:{duration:.8,delay:1.1},style:{margin:"0 auto 1.5rem"}}),h&&e.jsx(Zn.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Zn.div,{className:"mb-6 rounded-xl overflow-hidden shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.p,{className:"text-sm text-slate-500 dark:text-slate-400 leading-relaxed max-w-xs mx-auto mb-8 italic",initial:{opacity:0},animate:{opacity:1},transition:{duration:.6,delay:1.3},children:i||f.defaultMessage}),e.jsxs(Zn.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(Zn.img,{src:o,alt:l,className:"h-12 w-12 rounded-full object-cover ring-2 ring-slate-200 dark:ring-slate-700 shadow-md",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-full bg-gradient-to-br from-slate-200 to-blue-100 dark:from-slate-700 dark:to-slate-600 flex items-center justify-center shadow-md",children:e.jsx("span",{className:"text-sm font-semibold text-slate-600 dark:text-slate-300",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-slate-700 dark:text-slate-200",children:l}),u&&e.jsx("p",{className:"text-xs text-slate-400 dark:text-slate-500",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-3 mt-4",children:[c&&e.jsxs(Zn.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(Cr,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zn.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(Gs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zn.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 CNe({delay:s,x:t,y:n,color:r,size:a}){return e.jsx(Zn.div,{className:`absolute rounded-full blur-2xl ${r}`,style:{left:t,top:n,width:a,height:a},animate:{scale:[1,1.4,1],opacity:[.2,.5,.2]},transition:{duration:5,delay:s,repeat:1/0,ease:"easeInOut"}})}function PF({delay:s,x:t,y:n}){return e.jsx(Zn.div,{className:"absolute text-white/30 text-lg",style:{left:t,top:n},animate:{opacity:[0,1,0],scale:[.5,1,.5],rotate:[0,180,360]},transition:{duration:3,delay:s,repeat:1/0,ease:"easeInOut"},children:"✦"})}const _Xe={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 ysn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=ER[t],y=_Xe[t]||_Xe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-br ${y.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[e.jsx(CNe,{delay:0,x:"10%",y:"10%",color:y.orbs[0],size:200}),e.jsx(CNe,{delay:1,x:"70%",y:"60%",color:y.orbs[1],size:180}),e.jsx(CNe,{delay:2,x:"50%",y:"20%",color:y.orbs[2],size:150}),e.jsx(PF,{delay:0,x:"20%",y:"25%"}),e.jsx(PF,{delay:.8,x:"75%",y:"15%"}),e.jsx(PF,{delay:1.6,x:"85%",y:"65%"}),e.jsx(PF,{delay:2.4,x:"10%",y:"75%"}),e.jsx(PF,{delay:.4,x:"45%",y:"85%"}),e.jsxs(Zn.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(Zn.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(Zn.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(Zn.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(Zn.div,{className:"absolute inset-0 rounded-2xl bg-gradient-to-br from-violet-500 to-fuchsia-500",animate:{scale:[1,1.3,1],opacity:[.6,0,.6]},transition:{duration:2,repeat:1/0,ease:"easeInOut"}}),e.jsx("span",{className:"text-4xl relative z-10",children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zn.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(Zn.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(Zn.h1,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-violet-200 via-white to-fuchsia-200 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Zn.h2,{className:"text-5xl font-black text-transparent bg-clip-text bg-gradient-to-r from-fuchsia-300 via-violet-200 to-purple-300 mb-2 leading-tight",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{duration:.5,delay:.85},children:f.title[1]}),e.jsx(Zn.div,{className:"text-3xl mb-4",initial:{opacity:0,scale:0},animate:{opacity:1,scale:1},transition:{duration:.4,delay:1,type:"spring",stiffness:300},children:f.emojis.slice(0,3).join("")}),e.jsxs(Zn.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:"text-xl font-semibold text-white/90 mb-1",children:n}),r&&e.jsxs("p",{className:"text-sm text-violet-300/70 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(Or,{className:"h-3.5 w-3.5"}),r]})]}),h&&e.jsx(Zn.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Zn.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10 shadow-lg",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.div,{className:"bg-white/5 rounded-2xl p-5 border border-white/10 mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsx("p",{className:"text-sm text-violet-100/80 leading-relaxed",children:i||f.defaultMessage})}),e.jsxs(Zn.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(Zn.img,{src:o,alt:l,className:"h-12 w-12 rounded-xl object-cover ring-2 ring-violet-500/40 shadow-lg",whileHover:{scale:1.1}}):e.jsx("div",{className:"h-12 w-12 rounded-xl bg-gradient-to-br from-violet-500 to-fuchsia-500 flex items-center justify-center shadow-lg",children:e.jsx("span",{className:"text-sm font-bold text-white",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-bold text-white",children:l}),u&&e.jsx("p",{className:"text-xs text-violet-300/60",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-5",children:[c&&e.jsxs(Zn.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(Cr,{className:"h-3.5 w-3.5"})," Call Me"]}),d&&e.jsxs(Zn.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(Gs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zn.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 vsn({emoji:s,delay:t,x:n,duration:r}){return e.jsx(Zn.div,{className:"absolute text-2xl pointer-events-none",style:{left:n,bottom:-20},animate:{y:[0,-600],opacity:[0,1,1,0],x:[0,15,-10,5],rotate:[0,20,-15,10]},transition:{duration:r,delay:t,repeat:1/0,ease:"easeOut"},children:s})}const wXe={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 bsn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=ER[t],y=wXe[t]||wXe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${y.bg} flex items-center justify-center p-4 overflow-hidden relative`,children:[f.emojis.map((_,v)=>e.jsx(vsn,{emoji:_,delay:v*1.2,x:`${15+v*14}%`,duration:5+v%3},v)),e.jsx(Zn.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(Zn.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(Zn.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(Zn.div,{className:`h-28 bg-gradient-to-r ${y.header} relative overflow-hidden`,children:[e.jsx(Zn.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(Zn.div,{className:"absolute top-3 left-10 text-5xl",animate:{rotate:[0,10,-5,0],y:[0,-3,0]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:f.emojis[0]}),e.jsx(Zn.div,{className:"absolute top-2 right-14 text-3xl",animate:{scale:[1,1.3,1],rotate:[0,15,0]},transition:{duration:2,repeat:1/0,ease:"easeInOut",delay:.5},children:f.emojis[1]}),e.jsx(Zn.div,{className:"absolute bottom-2 left-1/2 -translate-x-1/2 text-3xl",animate:{y:[0,-5,0],scale:[1,1.1,1]},transition:{duration:2.5,repeat:1/0,ease:"easeInOut",delay:1},children:f.emojis[2]})]}),e.jsxs("div",{className:"px-8 py-8 text-center -mt-10 relative",children:[e.jsx(Zn.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(Zn.div,{animate:{scale:[1,1.2,1]},transition:{duration:1.5,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-3xl",children:f.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsx(Zn.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 ${y.accent}`,children:[e.jsx(Zn.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(Zn.h1,{className:`text-3xl font-bold ${y.accent} mb-1`,initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:.9},children:[f.title.join(" ")," ",f.emojis[4]]}),e.jsxs(Zn.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1.1},children:[e.jsx("p",{className:`text-lg font-semibold ${y.text} mb-1`,children:n}),r&&e.jsxs("p",{className:`text-sm ${y.text} opacity-70 flex items-center justify-center gap-1 mb-5`,children:[e.jsx(ka,{className:"h-3 w-3"}),r]})]}),h&&e.jsx(Zn.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Zn.div,{className:"mb-5 rounded-2xl overflow-hidden border border-amber-200 shadow-md",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.25,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.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 ${y.text} leading-relaxed italic`,children:['"',i||f.defaultMessage,'"']})}),e.jsxs(Zn.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(Zn.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 ${y.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 ${y.accent}`,children:l}),u&&e.jsx("p",{className:`text-xs ${y.text} opacity-60`,children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Zn.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${y.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Cr,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zn.a,{href:`mailto:${d}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${y.header} text-xs font-semibold text-white shadow-md`,whileHover:{scale:1.05},whileTap:{scale:.95},children:[e.jsx(Gs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zn.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 wG({delay:s,x:t,y:n,size:r,color:a}){return e.jsx(Zn.div,{className:`absolute rounded-full ${a} blur-3xl`,style:{left:t,top:n,width:r,height:r},animate:{scale:[1,1.3,1],opacity:[.4,.7,.4],x:[0,20,-10,0],y:[0,-15,10,0]},transition:{duration:8,delay:s,repeat:1/0,ease:"easeInOut"}})}function TNe({delay:s,x:t,y:n,size:r}){return e.jsx(Zn.div,{className:"absolute rounded-full border border-white/10",style:{left:t,top:n,width:r,height:r},animate:{scale:[1,1.2,1],opacity:[.1,.3,.1],rotate:[0,180,360]},transition:{duration:12,delay:s,repeat:1/0,ease:"linear"}})}const jXe={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 _sn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=ER[t],y=jXe[t]||jXe.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(wG,{delay:0,x:"5%",y:"10%",size:300,color:y.mesh[0]}),e.jsx(wG,{delay:2,x:"60%",y:"50%",size:250,color:y.mesh[1]}),e.jsx(wG,{delay:4,x:"30%",y:"70%",size:200,color:y.mesh[2]}),e.jsx(wG,{delay:1,x:"80%",y:"15%",size:180,color:y.mesh[0]}),e.jsx(TNe,{delay:0,x:"15%",y:"20%",size:100}),e.jsx(TNe,{delay:3,x:"70%",y:"60%",size:140}),e.jsx(TNe,{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(Zn.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(Zn.div,{className:`relative rounded-[28px] overflow-hidden backdrop-blur-2xl bg-white/[0.06] border border-white/[0.12] shadow-2xl ${y.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(Zn.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(Zn.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(Zn.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(Zn.span,{className:"text-5xl",animate:{scale:[1,1.08,1]},transition:{duration:2,repeat:1/0,ease:"easeInOut"},children:f.icon})]}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zn.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(Zn.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] ${y.accent}`,children:a===1?"Year":"Years"})]}),e.jsx(Zn.h1,{className:"text-4xl font-extralight text-white/90 mb-1 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.7},children:f.title[0]}),f.title[1]&&e.jsx(Zn.h2,{className:"text-4xl font-bold text-white mb-6 tracking-tight",initial:{opacity:0,y:15},animate:{opacity:1,y:0},transition:{duration:.6,delay:.85},children:f.title[1]}),e.jsxs(Zn.div,{initial:{opacity:0},animate:{opacity:1},transition:{delay:1},children:[e.jsx("p",{className:"text-xl font-medium text-white/80 mb-1",children:n}),r&&e.jsxs("p",{className:"text-sm text-white/30 mb-6 flex items-center justify-center gap-1.5",children:[e.jsx(ka,{className:"h-3 w-3"})," ",r]})]}),e.jsx(Zn.div,{className:"h-px bg-gradient-to-r from-transparent via-white/15 to-transparent mx-auto mb-6",initial:{width:0},animate:{width:"70%"},transition:{duration:1,delay:1.1},style:{margin:"0 auto 1.5rem"}}),h&&e.jsx(Zn.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.15,duration:.5},children:e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"})}),p&&e.jsx(Zn.div,{className:"mb-6 rounded-2xl overflow-hidden border border-white/10",initial:{opacity:0,scale:.95},animate:{opacity:1,scale:1},transition:{delay:1.2,duration:.5},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.div,{className:"bg-white/[0.04] rounded-2xl p-5 border border-white/[0.08] mb-8 backdrop-blur-sm",initial:{opacity:0,y:10},animate:{opacity:1,y:0},transition:{delay:1.3},children:e.jsxs("p",{className:"text-sm text-white/60 leading-relaxed italic",children:['"',i||f.defaultMessage,'"']})}),e.jsxs(Zn.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(Zn.img,{src:o,alt:l,className:"h-12 w-12 rounded-2xl object-cover ring-1 ring-white/10",whileHover:{scale:1.08}}):e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white/[0.08] border border-white/[0.1] flex items-center justify-center",children:e.jsx("span",{className:"text-sm font-semibold text-white/60",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-semibold text-white/80",children:l}),u&&e.jsx("p",{className:"text-xs text-white/30",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2 mt-4",children:[c&&e.jsxs(Zn.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(Cr,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zn.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(Gs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})]}),e.jsx(Zn.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 ENe({delay:s,x:t,angle:n,color:r}){return e.jsx(Zn.div,{className:`absolute h-[400px] w-[1px] ${r} origin-top`,style:{left:t,top:"-10%",transform:`rotate(${n}deg)`},animate:{opacity:[0,.4,0],scaleY:[.5,1,.5]},transition:{duration:6,delay:s,repeat:1/0,ease:"easeInOut"}})}function jG({delay:s,x:t}){return e.jsx(Zn.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 NXe={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 wsn(s){const{cardType:t,recipientName:n,propertyAddress:r,anniversaryYears:a,customMessage:i,agentName:l,agentPhotoUrl:o,agentPhone:c,agentEmail:d,agentBrokerage:u,propertyPhotoUrl:h,videoUrl:p}=s,f=ER[t],y=NXe[t]||NXe.home_anniversary;return e.jsxs("div",{className:`min-h-screen bg-gradient-to-b ${y.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(ENe,{delay:0,x:"20%",angle:15,color:y.stripe}),e.jsx(ENe,{delay:2,x:"75%",angle:-12,color:y.stripe}),e.jsx(ENe,{delay:4,x:"50%",angle:5,color:y.stripe}),e.jsx(jG,{delay:0,x:"30%"}),e.jsx(jG,{delay:1.5,x:"60%"}),e.jsx(jG,{delay:3,x:"45%"}),e.jsx(jG,{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(Zn.div,{className:"w-full max-w-md relative z-10",initial:{opacity:0},animate:{opacity:1},transition:{duration:1.2},children:[e.jsx(Zn.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(Zn.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(Zn.div,{className:`h-20 w-20 mx-auto rounded-2xl bg-gradient-to-br ${y.accent} flex items-center justify-center shadow-2xl`,animate:{boxShadow:["0 0 40px rgba(255,255,255,0.05)","0 0 80px rgba(255,255,255,0.1)","0 0 40px rgba(255,255,255,0.05)"]},transition:{duration:3,repeat:1/0,ease:"easeInOut"},children:e.jsx("span",{className:"text-4xl",children:f.icon})})}),t==="home_anniversary"&&a!==null&&a>0&&e.jsxs(Zn.div,{className:"mb-6",initial:{opacity:0},animate:{opacity:1},transition:{delay:.7},children:[e.jsx(Zn.span,{className:`text-6xl font-black bg-gradient-to-r ${y.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(Zn.h1,{className:"text-5xl font-thin text-white/90 tracking-wide",initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.8,ease:[.16,1,.3,1]},children:f.title[0]})}),f.title[1]&&e.jsx("div",{className:"overflow-hidden mb-8",children:e.jsx(Zn.h2,{className:`text-5xl font-black bg-gradient-to-r ${y.accent} bg-clip-text text-transparent`,initial:{y:"100%"},animate:{y:0},transition:{duration:.7,delay:.95,ease:[.16,1,.3,1]},children:f.title[1]})}),e.jsxs(Zn.div,{initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.1,duration:.6},children:[e.jsx("p",{className:"text-lg font-light text-white/70 tracking-wide",children:n}),r&&e.jsxs("p",{className:"text-xs text-white/25 mt-1 flex items-center justify-center gap-1",children:[e.jsx(ka,{className:"h-3 w-3"})," ",r]})]}),e.jsxs(Zn.div,{className:"flex items-center justify-center gap-3 my-8",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.2},children:[e.jsx(Zn.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(Zn.span,{className:"text-white/10 text-xs",animate:{rotate:[0,360]},transition:{duration:20,repeat:1/0,ease:"linear"},children:"✦"}),e.jsx(Zn.div,{className:"h-px flex-1 max-w-[60px] bg-gradient-to-l from-transparent to-white/15",initial:{scaleX:0},animate:{scaleX:1},transition:{delay:1.3,duration:.8},style:{transformOrigin:"left"}})]}),h&&e.jsxs(Zn.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.3,duration:.6},children:[e.jsx("img",{src:h,alt:"Property",className:"w-full h-48 object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-slate-950/30 to-transparent pointer-events-none"})]}),p&&e.jsx(Zn.div,{className:"mb-8 rounded-2xl overflow-hidden ring-1 ring-white/5",initial:{opacity:0,y:20},animate:{opacity:1,y:0},transition:{delay:1.35,duration:.6},children:e.jsx("iframe",{src:`${p}?autoplay=false&responsive=true`,className:"w-full aspect-video",allow:"autoplay; encrypted-media",allowFullScreen:!0})}),e.jsx(Zn.p,{className:"text-sm text-white/40 leading-relaxed max-w-xs mx-auto mb-10 font-light",initial:{opacity:0},animate:{opacity:1},transition:{delay:1.4,duration:.8},children:i||f.defaultMessage}),e.jsxs(Zn.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(Zn.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 ${y.accent} flex items-center justify-center shadow-xl`,children:e.jsx("span",{className:"text-sm font-bold text-slate-900",children:l.charAt(0)})}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-sm font-medium text-white/70",children:l}),u&&e.jsx("p",{className:"text-[11px] text-white/25",children:u})]})]}),e.jsxs("div",{className:"flex items-center justify-center gap-2",children:[c&&e.jsxs(Zn.a,{href:`tel:${c}`,className:`flex items-center gap-1.5 px-5 py-2.5 rounded-full bg-gradient-to-r ${y.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(Cr,{className:"h-3.5 w-3.5"})," Call"]}),d&&e.jsxs(Zn.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(Gs,{className:"h-3.5 w-3.5"})," Email"]})]})]})]})}),e.jsx(Zn.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 sNt(){const{shareToken:s}=bi(),{data:t,isLoading:n,error:r}=dt({queryKey:["public-sendable-card",s],queryFn:async()=>{const{data:l,error:o}=await q.from("sendable_cards").select("*").eq("share_token",s).single();if(o)throw o;return l},enabled:!!s});if(N.useEffect(()=>{s&&q.rpc("log_sendable_card_view",{p_share_token:s}).then(({error:l})=>{l&&console.error("Error tracking view:",l)})},[s]),n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"animate-pulse space-y-4 text-center",children:[e.jsx("div",{className:"h-8 w-48 bg-muted rounded mx-auto"}),e.jsx("div",{className:"h-4 w-32 bg-muted rounded mx-auto"})]})});if(r||!t)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-background",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold mb-2",children:"Card not found"}),e.jsx("p",{className:"text-muted-foreground",children:"This card may have been removed or the link is invalid."})]})});const a=t.home_anniversary_date?Math.floor((Date.now()-Ll(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(ysn,{...i});case"warm":return e.jsx(bsn,{...i});case"glass":return e.jsx(_sn,{...i});case"cinematic":return e.jsx(wsn,{...i});case"elegant":default:return e.jsx(gsn,{...i})}}function jsn(){const s=wa();return dt({queryKey:["drip-settings",s],queryFn:async()=>{if(!s)return null;const{data:t,error:n}=await q.from("drip_settings").select("*").eq("user_id",s).maybeSingle();if(n)throw n;return t},enabled:!!s})}function Nsn(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r}=await q.from("drip_settings").select("id").eq("user_id",s).maybeSingle();if(r){const{data:a,error:i}=await q.from("drip_settings").update(n).eq("user_id",s).select().single();if(i)throw i;return a}else{const{data:a,error:i}=await q.from("drip_settings").insert({user_id:s,is_globally_enabled:n.is_globally_enabled??!1,append_signature:n.append_signature??!0}).select().single();if(i)throw i;return a}},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-settings"]})}})}function ksn(){const s=Ln(),{isGmailConnected:t,gmailEmail:n}=Dh(),{data:r,isLoading:a}=jsn(),i=Nsn(),[l,o]=N.useState(!1),[c,d]=N.useState(!0),[u,h]=N.useState(!1);N.useEffect(()=>{r&&(o(r.is_globally_enabled),d(r.append_signature))},[r]);const p=async y=>{if(y&&!t){ae.error("Connect your Gmail account first before enabling Smart Drips");return}o(y);try{await i.mutateAsync({is_globally_enabled:y}),ae.success(y?"Smart Drips enabled globally":"Smart Drips paused globally")}catch{o(!y),ae.error("Failed to update settings")}},f=async y=>{d(y);try{await i.mutateAsync({append_signature:y}),ae.success(y?"Signature will be appended to drip emails":"Signature disabled for drip emails")}catch{d(!y),ae.error("Failed to update settings")}};return e.jsxs(_s,{open:u,onOpenChange:h,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",children:[e.jsx(Ko,{className:"h-3.5 w-3.5"}),"Settings"]})}),e.jsxs(bs,{className:"sm:max-w-md",children:[e.jsxs(js,{children:[e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(Ko,{className:"h-5 w-5 text-primary"}),"Smart Drip Settings"]}),e.jsx(Jn,{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(Gs,{className:`h-4 w-4 ${t?"text-emerald-600":"text-destructive"}`})}),e.jsxs("div",{children:[e.jsx("p",{className:"text-sm font-medium",children:t?"Gmail Connected":"Gmail Not Connected"}),n&&e.jsx("p",{className:"text-xs text-muted-foreground",children:n})]})]}),t?e.jsxs(Ue,{variant:"outline",className:"gap-1 text-emerald-600 border-emerald-200 bg-emerald-500/10 text-[10px]",children:[e.jsx(vr,{className:"h-3 w-3"}),"Active"]}):e.jsxs(B,{variant:"outline",size:"sm",className:"text-xs gap-1",onClick:()=>{h(!1),s("/mission-control/integrations")},children:[e.jsx(tr,{className:"h-3 w-3"}),"Connect"]})]}),!t&&e.jsx("p",{className:"text-xs text-muted-foreground",children:"Smart Drips sends emails from your Gmail account. Connect Gmail to get started."})]}),e.jsx(al,{}),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(c9,{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(jn,{checked:l,onCheckedChange:p,disabled:a||i.isPending})]}),e.jsx(al,{}),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(_v,{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(jn,{checked:c,onCheckedChange:f,disabled:a||i.isPending})]}),c&&e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>{h(!1),s("/profile")},children:[e.jsx(_v,{className:"h-3 w-3 mr-1"}),"Edit your email signature in Profile settings"]})]})]})]})}function Ssn(){const s=wa();return dt({queryKey:["drip-templates",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("drip_templates").select("*").or(`owner_user_id.eq.${s},is_starter.eq.true`).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Csn(){const s=wa();return dt({queryKey:["drip-pipeline-stages",s],queryFn:async()=>{if(!s)return[];const{data:t,error:n}=await q.from("deal_pipeline_stages").select("*").eq("owner_user_id",s).order("sort_order",{ascending:!0});if(n)throw n;return t},enabled:!!s})}function Tsn(){const s=wa(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:n.stage_id,title:n.title||"",subject:n.subject||"",body:n.body||"",video_url:n.video_url||null,channel:n.channel||"email",delay_type:n.delay_type||"instant",delay_minutes:n.delay_minutes||0,is_enabled:!1,deal_type:n.deal_type||null,sort_order:n.sort_order||0}).select().single();if(a)throw a;return r},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}function Esn(){const s=Kt();return yt({mutationFn:async({id:t,...n})=>{const{data:r,error:a}=await q.from("drip_templates").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function Asn(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("drip_templates").delete().eq("id",t);if(n)throw n},onSuccess:()=>{s.invalidateQueries({queryKey:["drip-templates"]})}})}function Msn(){const s=wa(),t=Kt();return yt({mutationFn:async({templateId:n,stageId:r})=>{if(!s)throw new Error("Not authenticated");const{data:a,error:i}=await q.from("drip_templates").select("*").eq("id",n).single();if(i)throw i;const{data:l,error:o}=await q.from("drip_templates").insert({owner_user_id:s,stage_id:r,title:a.title,subject:a.subject,body:a.body,video_url:a.video_url,channel:a.channel,delay_type:a.delay_type,delay_minutes:a.delay_minutes,is_enabled:!1,is_starter:!1,deal_type:a.deal_type}).select().single();if(o)throw o;return l},onSuccess:()=>{t.invalidateQueries({queryKey:["drip-templates"]})}})}const Isn=[{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 Psn({open:s,onOpenChange:t,campaignId:n,campaignName:r}){const{data:a,isLoading:i}=HHs(n||void 0),l=WHs(),o=h_t(),c=async(h,p)=>{try{await l.mutateAsync({id:h,status:p}),ae.success(`Enrollment ${p}`)}catch{ae.error("Failed to update")}},d=async h=>{if(n)try{const p=await o.mutateAsync({campaignId:n,contactIds:[h]});p.enrolled>0?ae.success("Contact re-enrolled — first email queued"):p.skipped>0?ae.message("Already active in this campaign"):ae.error("Could not re-enroll")}catch{ae.error("Failed to re-enroll")}},u=h=>{const p={active:"bg-emerald-500/10 text-emerald-600 border-emerald-200",paused:"bg-amber-500/10 text-amber-600 border-amber-200",completed:"bg-blue-500/10 text-blue-600 border-blue-200",exited:"bg-muted text-muted-foreground"};return e.jsx(Ue,{variant:"outline",className:`text-[10px] capitalize ${p[h]||""}`,children:h})};return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{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(ws,{className:"flex items-center gap-2",children:[e.jsx(An,{className:"h-4 w-4 text-primary"}),"Enrollments — ",r||"Campaign"]}),e.jsx(Jn,{className:"text-xs mt-1",children:"Manage every contact currently in this campaign. Pause to take over, or exit to remove."})]}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsx("div",{className:"p-5",children:i?e.jsx("div",{className:"space-y-2",children:[1,2,3].map(h=>e.jsx(Ws,{className:"h-14"},h))}):!a||a.length===0?e.jsxs("div",{className:"text-center py-12",children:[e.jsx(An,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("p",{className:"text-sm font-medium mb-1",children:"No contacts enrolled yet"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Head to your contacts page and bulk-enroll to start nurturing."})]}):e.jsx("div",{className:"space-y-2",children:a.map(h=>{var p,f,y,_;return e.jsxs("div",{className:"flex items-center gap-3 p-3 border rounded-lg bg-card",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("p",{className:"font-medium text-sm truncate",children:[(p=h.contact)==null?void 0:p.first_name," ",(f=h.contact)==null?void 0:f.last_name]}),u(h.status)]}),e.jsxs("div",{className:"flex items-center gap-3 text-[11px] text-muted-foreground mt-0.5",children:[((y=h.contact)==null?void 0:y.email)&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Gs,{className:"h-2.5 w-2.5"})," ",h.contact.email]}),e.jsxs("span",{children:["Step ",h.current_step]}),h.next_send_at&&h.status==="active"&&e.jsxs("span",{children:["Next: ",Ss(new Date(h.next_send_at),"MMM d, h:mma")]}),h.exit_reason&&e.jsxs("span",{children:["Exit: ",h.exit_reason]})]})]}),h.status==="active"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"paused"),title:"Pause",children:e.jsx(gf,{className:"h-3.5 w-3.5"})}),h.status==="paused"&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"active"),title:"Resume",children:e.jsx(El,{className:"h-3.5 w-3.5"})}),(h.status==="active"||h.status==="paused")&&e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>c(h.id,"exited"),title:"Exit",children:e.jsx($n,{className:"h-3.5 w-3.5 text-destructive"})}),(h.status==="exited"||h.status==="completed")&&((_=h.contact)==null?void 0:_.id)&&e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-[11px] gap-1",onClick:()=>d(h.contact.id),disabled:o.isPending,children:[e.jsx(Bm,{className:"h-3 w-3"}),"Re-enroll"]})]},h.id)})})})})]})})}function Lsn(){var S;const{data:s,isLoading:t}=ZPe(),{hasLeadSite:n}=Ap(),r=$Hs(),a=BHs(),i=d_t(),[l,o]=N.useState(null),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(null),y=(s||[]).filter(A=>!A.is_starter),_=(s||[]).filter(A=>A.is_starter).filter(A=>!A.requires_lead_site||n),v=async A=>{try{await r.mutateAsync(A),ae.success("Campaign added to your library — customize and activate it!"),o(null)}catch(E){ae.error(E.message||"Failed to copy campaign")}},j=async A=>{try{await i.mutateAsync({id:A.id,is_active:!A.is_active}),ae.success(A.is_active?"Campaign paused":"Campaign activated")}catch{ae.error("Failed to update")}},w=async A=>{if(confirm("Delete this campaign? Active enrollments will be removed."))try{await a.mutateAsync(A),ae.success("Campaign deleted")}catch{ae.error("Failed to delete")}};return t?e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:[1,2,3,4,5,6].map(A=>e.jsx(Ws,{className:"h-44 rounded-xl"},A))}):e.jsxs("div",{className:"space-y-8",children:[e.jsx("div",{className:"rounded-xl border bg-gradient-to-br from-primary/5 via-background to-background p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-lg bg-primary/10 flex items-center justify-center shrink-0",children:e.jsx(fw,{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(Ac,{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(lr,{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(An,{className:"h-4 w-4 text-primary"}),"My Campaigns"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Custom drip campaigns you've created or copied"})]}),e.jsxs(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," New Campaign"]})]}),y.length===0?e.jsxs("div",{className:"text-center py-10 border border-dashed rounded-xl bg-muted/20",children:[e.jsx(un,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold mb-1",children:"No custom campaigns yet"}),e.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"Build one from scratch or clone a starter from the library below."}),e.jsxs(B,{size:"sm",onClick:()=>{h(null),d(!0)},children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," Create your first campaign"]})]}):e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:y.map(A=>e.jsx(Dsn,{campaign:A,onPreview:()=>o(A.id),onToggleActive:()=>j(A),onDelete:()=>w(A.id),onEdit:()=>{h(A.id),d(!0)},onViewEnrollments:()=>f(A.id)},A.id))})]}),e.jsxs("section",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsxs("h2",{className:"text-lg font-semibold flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-amber-500"}),"Starter Library"]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Premium, ready-to-go campaigns crafted for real estate. One-click copy."})]}),e.jsxs(Ue,{variant:"outline",className:"text-[10px]",children:[_.length," templates"]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:_.map(A=>e.jsx(Rsn,{campaign:A,onPreview:()=>o(A.id)},A.id))})]}),e.jsx(Osn,{campaignId:l,open:!!l,onOpenChange:A=>!A&&o(null),onClone:v,isCloning:r.isPending,onEdit:A=>{o(null),h(A),d(!0)}}),e.jsx(f_t,{open:c,onOpenChange:d,campaignId:u}),e.jsx(Psn,{open:!!p,onOpenChange:A=>!A&&f(null),campaignId:p,campaignName:(S=y.find(A=>A.id===p))==null?void 0:S.name})]})}function Dsn({campaign:s,onPreview:t,onToggleActive:n,onDelete:r,onEdit:a,onViewEnrollments:i}){const o=GHs(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(Ue,{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(Ue,{variant:"outline",className:"text-[9px] mt-2",children:x1e[s.category]}),c&&e.jsxs("button",{onClick:n,className:"mt-2 w-full flex items-start gap-1.5 p-2 rounded-md bg-amber-500/10 border border-amber-500/30 text-left hover:bg-amber-500/15 transition-colors",children:[e.jsx(ic,{className:"h-3 w-3 text-amber-600 dark:text-amber-400 shrink-0 mt-0.5"}),e.jsxs("span",{className:"text-[10px] leading-tight text-amber-700 dark:text-amber-300",children:[e.jsxs("strong",{children:[o," contact",o===1?"":"s"," enrolled"]})," but not sending — tap to activate"]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-1.5 mt-3",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"h-7 text-xs",onClick:a,children:[e.jsx(ya,{className:"h-3 w-3 mr-1"})," Edit"]}),e.jsx(B,{size:"sm",variant:s.is_active?"secondary":"default",className:"h-7 text-xs",onClick:n,children:s.is_active?"Pause":"Activate"})]}),e.jsxs("div",{className:"flex items-center justify-between mt-2 text-[10px]",children:[e.jsx("button",{onClick:i,className:"text-primary hover:underline",children:"View enrollments"}),e.jsx("button",{onClick:t,className:"text-muted-foreground hover:underline",children:"Preview"}),e.jsx("button",{onClick:r,className:"text-muted-foreground hover:text-destructive",children:"Delete"})]})]})]})}function Rsn({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(Ue,{className:"absolute top-2 right-2 bg-white/90 text-foreground hover:bg-white text-[10px]",children:[e.jsx(un,{className:"h-2.5 w-2.5 mr-0.5"})," Starter"]})]}),e.jsxs("div",{className:"p-3.5",children:[e.jsx("h3",{className:"font-semibold text-sm",children:s.name}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1 min-h-[2rem]",children:s.description}),e.jsx(Ue,{variant:"outline",className:"text-[9px] mt-2",children:x1e[s.category]})]})]})}function Osn({campaignId:s,open:t,onOpenChange:n,onClone:r,isCloning:a,onEdit:i}){const{data:l}=ZPe(),{data:o}=u_t(s||void 0),[c,d]=N.useState(new Set),u=l==null?void 0:l.find(f=>f.id===s);if(!u)return null;const h=f=>{d(y=>{const _=new Set(y);return _.has(f)?_.delete(f):_.add(f),_})},p=(f,y)=>{if(f.delay_type==="calendar_anchor"){const v=f.anchor_field==="birthday"?"birthday":"home anniversary",j=f.anchor_offset_days||0;return j===0?`On their ${v}`:j<0?`${Math.abs(j)} days before ${v}`:`${j} days after ${v}`}if(y===0&&f.delay_days===0&&f.delay_hours===0)return"Sends immediately";const _=[];return f.delay_days&&_.push(`${f.delay_days}d`),f.delay_hours&&_.push(`${f.delay_hours}h`),y===0?`After ${_.join(" ")}`:`+${_.join(" ")}`};return e.jsx(_s,{open:t,onOpenChange:n,children:e.jsxs(bs,{className:"max-w-2xl max-h-[85vh] flex flex-col p-0 overflow-hidden",children:[e.jsx("div",{className:`bg-gradient-to-br ${u.cover_color} p-6 text-white shrink-0`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("span",{className:"text-5xl drop-shadow-sm",children:u.icon}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ws,{className:"text-xl font-bold text-white",children:u.name}),e.jsx(Jn,{className:"text-white/90 mt-1",children:u.description}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsx(Ue,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:x1e[u.category]}),e.jsxs(Ue,{className:"bg-white/20 text-white border-white/20 hover:bg-white/20",children:[(o==null?void 0:o.length)||0," step",(o==null?void 0:o.length)!==1?"s":""]})]})]})]})}),e.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto",children:e.jsxs("div",{className:"p-6 space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("h4",{className:"text-xs font-semibold uppercase tracking-wide text-muted-foreground",children:"The sequence"}),u.is_starter?e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Copy to your library to edit"}):e.jsx("span",{className:"text-[10px] text-muted-foreground italic",children:"Tap a step to expand · Edit to customize"})]}),o==null?void 0:o.map((f,y)=>{const _=c.has(f.id);return e.jsxs("div",{className:"flex gap-3",children:[e.jsxs("div",{className:"shrink-0 flex flex-col items-center",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-primary/10 text-primary flex items-center justify-center text-xs font-semibold",children:y+1}),yh(f.id),className:"flex-1 pb-4 text-left",children:e.jsxs("div",{className:"border rounded-lg p-3 bg-muted/20 hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-1.5 text-xs text-muted-foreground",children:[f.delay_type==="calendar_anchor"?e.jsx(yr,{className:"h-3 w-3"}):e.jsx(pr,{className:"h-3 w-3"}),e.jsx("span",{children:p(f,y)}),e.jsx("span",{children:"·"}),e.jsx(Gs,{className:"h-3 w-3"}),e.jsx("span",{className:"capitalize",children:f.channel})]}),e.jsx("p",{className:"font-medium text-sm",children:f.subject}),(()=>{const v=f.body||"",j=/<\/?[a-z][\s\S]*>/i.test(v),w=j?v.replace(//gi,"").replace(/<[^>]+>/g," ").replace(/ /g," ").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/\s+/g," ").trim():v;return _?j?e.jsx("div",{className:"text-xs text-foreground mt-2 prose prose-sm max-w-none [&_a]:text-primary",dangerouslySetInnerHTML:{__html:v}}):e.jsx("p",{className:"text-xs text-muted-foreground mt-2 whitespace-pre-line",children:v}):e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2 mt-1",children:w})})(),f.body&&f.body.length>160&&e.jsx("span",{className:"text-[10px] text-primary mt-1.5 inline-block",children:_?"Show less":"Show full email"})]})})]},f.id)})]})}),e.jsxs(Xn,{className:"border-t p-4 shrink-0",children:[e.jsx(B,{variant:"outline",onClick:()=>n(!1),children:"Close"}),!u.is_starter&&i&&e.jsxs(B,{variant:"secondary",onClick:()=>i(u.id),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1.5"})," Edit Campaign"]}),u.is_starter&&e.jsxs(B,{onClick:()=>r(u.id),disabled:a,children:[a?e.jsx(rs,{className:"h-3.5 w-3.5 mr-1.5 animate-spin"}):e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1.5"}),"Copy to my campaigns"]})]})]})})}function Fsn(){const s=wa(),t=Ln(),{isGmailConnected:n,gmailEmail:r,isLoading:a}=Dh(),{data:i,isLoading:l}=Ssn(),{data:o,isLoading:c}=Csn(),d=Tsn(),u=Esn(),h=Asn(),p=Msn(),[f,y]=N.useState(null),[_,v]=N.useState(null),j=(i==null?void 0:i.filter(F=>!F.is_starter&&F.owner_user_id===s))||[],w=(i==null?void 0:i.filter(F=>F.is_starter))||[],S=F=>j.filter(z=>z.stage_id===F),A=async F=>{try{await u.mutateAsync({id:F.id,is_enabled:!F.is_enabled}),ae.success(F.is_enabled?"Drip disabled":"Drip enabled")}catch{ae.error("Failed to update")}},E=async F=>{try{const z=o==null?void 0:o.find(H=>H.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}),y(F),ae.success("Drip template created")}catch{ae.error("Failed to create template")}},O=async F=>{try{await h.mutateAsync(F),ae.success("Template deleted")}catch{ae.error("Failed to delete")}},D=async F=>{if(!o||o.length===0){ae.error("No pipeline stages found");return}const z=o[0].id;try{await p.mutateAsync({templateId:F,stageId:z}),ae.success("Template copied to your drips!")}catch{ae.error("Failed to copy template")}},I=l||c;return e.jsx(Cs,{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(im,{className:"h-5 w-5 text-primary"}),e.jsx("h1",{className:"text-2xl font-bold",children:"Smart Drips"}),e.jsx(Ue,{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(ksn,{})]}),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(fw,{className:"h-4 w-4 text-primary mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm text-muted-foreground",children:[e.jsx("p",{className:"font-medium text-foreground mb-1",children:"How it works"}),e.jsxs("p",{children:["When a deal moves to a new stage in your pipeline, Smart Drips automatically sends your pre-written email to the client. Nothing sends until you create a template ",e.jsx("strong",{children:"and"})," toggle it on."]})]})]}),!a&&(n?e.jsxs("div",{className:"bg-emerald-500/5 border border-emerald-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(Gs,{className:"h-4 w-4 text-emerald-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsxs("p",{className:"font-medium text-foreground mb-0.5",children:["Sending from your Gmail",r?` (${r})`:""]}),e.jsx("p",{className:"text-muted-foreground",children:"Drips will send directly from your connected Gmail for the most personal feel and best deliverability."})]})]}):e.jsxs("div",{className:"bg-amber-500/5 border border-amber-500/20 rounded-xl p-4 mb-6 flex items-start gap-3",children:[e.jsx(fw,{className:"h-4 w-4 text-amber-600 mt-0.5 shrink-0"}),e.jsxs("div",{className:"text-sm flex-1",children:[e.jsx("p",{className:"font-medium text-foreground mb-0.5",children:"Drips will send from our shared sender"}),e.jsxs("p",{className:"text-muted-foreground mb-2",children:["You haven't connected Gmail, so drips will send from ",e.jsx("strong",{children:"send.relevelup.com"})," with your name on the From line and your email as Reply-To. Connect Gmail to send directly from your own inbox for better deliverability and a more personal touch."]}),e.jsxs(B,{variant:"outline",size:"sm",className:"h-7 text-xs",onClick:()=>t("/mission-control/integrations"),children:[e.jsx(Gs,{className:"h-3 w-3 mr-1.5"}),"Connect Gmail"]})]})]})),e.jsxs(Fr,{defaultValue:"my-drips",children:[e.jsxs(Rr,{className:"grid grid-cols-3 w-full max-w-lg mb-6",children:[e.jsx(Zt,{value:"my-drips",children:"Stage Drips"}),e.jsxs(Zt,{value:"campaigns",children:["Campaigns",e.jsx(Ue,{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(Zt,{value:"starters",children:["Stage Starters",w.length>0&&e.jsx(Ue,{variant:"secondary",className:"ml-1.5 text-[10px] px-1.5 py-0",children:w.length})]})]}),e.jsx(is,{value:"campaigns",children:e.jsx(Lsn,{})}),e.jsx(is,{value:"my-drips",children:I?e.jsx("div",{className:"space-y-3",children:[1,2,3,4].map(F=>e.jsx(Ws,{className:"h-16 w-full rounded-xl"},F))}):!o||o.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(im,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Pipeline Stages"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:"Create pipeline stages first to set up drip automations."})]}):e.jsxs("div",{className:"space-y-2",children:[o.filter(F=>!F.is_won_stage&&!F.is_lost_stage).map(F=>{const z=S(F.id),H=f===F.id,Z=z.some(Y=>Y.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden",children:[e.jsxs("button",{onClick:()=>y(H?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(Ue,{variant:"outline",className:`text-[10px] ${Z?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",Z&&" · Active"]}),H?e.jsx(ao,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"})]}),H&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:z.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>E(F.id),disabled:d.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(Y=>e.jsx(kXe,{template:Y,isEditing:_===Y.id,onToggleEdit:()=>v(_===Y.id?null:Y.id),onToggleEnabled:()=>A(Y),onUpdate:W=>u.mutateAsync({id:Y.id,...W}),onDelete:()=>O(Y.id),userId:s||""},Y.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>E(F.id),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)}),o.filter(F=>F.is_won_stage||F.is_lost_stage).length>0&&e.jsxs("div",{className:"pt-2",children:[e.jsx("p",{className:"text-xs text-muted-foreground font-medium mb-2 px-1",children:"Closing Stages"}),o.filter(F=>F.is_won_stage||F.is_lost_stage).map(F=>{const z=S(F.id),H=f===F.id,Z=z.some(Y=>Y.is_enabled);return e.jsxs("div",{className:"border rounded-xl overflow-hidden mb-2",children:[e.jsxs("button",{onClick:()=>y(H?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(Ue,{variant:"outline",className:`text-[10px] ${Z?"bg-emerald-500/10 text-emerald-600 border-emerald-200":"text-muted-foreground"}`,children:[z.length," drip",z.length!==1?"s":"",Z&&" · Active"]}),H?e.jsx(ao,{className:"h-4 w-4 text-muted-foreground"}):e.jsx(ga,{className:"h-4 w-4 text-muted-foreground"})]}),H&&e.jsx("div",{className:"border-t bg-muted/10 p-4 space-y-3",children:z.length===0?e.jsxs("div",{className:"text-center py-6",children:[e.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"No drip set for this stage"}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>E(F.id),disabled:d.isPending,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"})," Create Drip"]})]}):e.jsxs(e.Fragment,{children:[z.map(Y=>e.jsx(kXe,{template:Y,isEditing:_===Y.id,onToggleEdit:()=>v(_===Y.id?null:Y.id),onToggleEnabled:()=>A(Y),onUpdate:W=>u.mutateAsync({id:Y.id,...W}),onDelete:()=>O(Y.id),userId:s||""},Y.id)),e.jsxs(B,{variant:"ghost",size:"sm",className:"w-full text-xs text-muted-foreground",onClick:()=>E(F.id),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add another drip"]})]})})]},F.id)})]})]})}),e.jsx(is,{value:"starters",children:w.length===0?e.jsxs("div",{className:"text-center py-12 border border-dashed rounded-xl",children:[e.jsx(un,{className:"h-10 w-10 text-muted-foreground/40 mx-auto mb-3"}),e.jsx("h3",{className:"font-semibold text-lg mb-1",children:"No Starter Templates Yet"}),e.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:"Admin-created starter templates will appear here. You'll be able to copy them into your own drips."})]}):e.jsx("div",{className:"space-y-3",children:w.map(F=>e.jsx(zsn,{template:F,onCopy:()=>D(F.id),isCopying:p.isPending},F.id))})})]})]})})}function kXe({template:s,isEditing:t,onToggleEdit:n,onToggleEnabled:r,onUpdate:a,onDelete:i,userId:l}){const[o,c]=N.useState(s.title),[d,u]=N.useState(s.subject),[h,p]=N.useState(s.body),[f,y]=N.useState(s.video_url||""),[_,v]=N.useState(s.channel),[j,w]=N.useState(s.delay_type),[S,A]=N.useState(s.delay_minutes),[E,O]=N.useState(!1),D=async()=>{O(!0);try{await a({title:o,subject:d,body:h,video_url:f||null,channel:_,delay_type:j,delay_minutes:S}),ae.success("Drip saved"),n()}catch{ae.error("Failed to save")}finally{O(!1)}},I=F=>{p(z=>z+F)};return e.jsxs("div",{className:"border rounded-lg bg-background overflow-hidden",children:[e.jsxs("div",{className:"flex items-center gap-3 p-3",children:[e.jsxs("div",{className:"flex-1 min-w-0",role:"button",onClick:n,children:[e.jsx("p",{className:"text-sm font-medium truncate",children:s.title||"Untitled drip"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[s.channel==="sms"?e.jsx(Ai,{className:"h-3 w-3 text-muted-foreground"}):e.jsx(Gs,{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(fr,{className:"h-3 w-3 text-primary"})]})]}),e.jsx(jn,{checked:s.is_enabled,onCheckedChange:r})]}),t&&e.jsxs("div",{className:"border-t p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium",children:"Title (internal)"}),e.jsx(ye,{value:o,onChange:F=>c(F.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Buyer intro video"})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Channel"}),e.jsx("div",{className:"flex gap-1 mt-1",children:["email","sms"].map(F=>e.jsxs("button",{onClick:()=>v(F),className:`flex-1 flex items-center justify-center gap-1.5 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${_===F?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[F==="sms"?e.jsx(Ai,{className:"h-3 w-3"}):e.jsx(Gs,{className:"h-3 w-3"}),F==="sms"?"SMS":"Email"]},F))})]}),e.jsxs("div",{className:"flex-1",children:[e.jsx(ne,{className:"text-xs font-medium",children:"Timing"}),e.jsxs("div",{className:"flex gap-1 mt-1",children:[e.jsx("button",{onClick:()=>w("instant"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${j==="instant"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:"Instant"}),e.jsxs("button",{onClick:()=>w("scheduled"),className:`flex-1 px-3 py-1.5 rounded-md text-xs font-medium border transition-colors ${j==="scheduled"?"bg-primary text-primary-foreground border-primary":"bg-background text-muted-foreground border-input hover:border-primary/50"}`,children:[e.jsx(pr,{className:"h-3 w-3 mr-1 inline"}),"Delay"]})]})]})]}),j==="scheduled"&&e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium",children:"Delay"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx(ye,{type:"number",min:1,value:S>=60?Math.round(S/60):S,onChange:F=>{const z=parseInt(F.target.value)||0;A(S>=60?z*60:z)},className:"h-8 w-20 text-sm"}),e.jsx("div",{className:"flex gap-1",children:[{label:"Minutes",mins:S<60?S:30},{label:"Hours",mins:S>=60?S:60},{label:"Days",mins:S>=1440?S:1440}].map(F=>e.jsx("button",{className:`px-2 py-1 rounded text-xs border transition-colors ${F.label==="Minutes"&&S<60||F.label==="Hours"&&S>=60&&S<1440||F.label==="Days"&&S>=1440?"bg-primary/10 text-primary border-primary/30":"text-muted-foreground border-input"}`,onClick:()=>{F.label==="Minutes"?A(30):F.label==="Hours"?A(60):A(1440)},children:F.label},F.label))})]})]}),_==="email"&&e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium",children:"Subject Line"}),e.jsx(ye,{value:d,onChange:F=>u(F.target.value),className:"mt-1 h-8 text-sm",placeholder:"e.g. Next steps for your home purchase"})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ne,{className:"text-xs font-medium",children:_==="sms"?"Message":"Email Body"}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx("span",{className:"text-[10px] text-muted-foreground",children:"Insert:"}),e.jsxs("select",{className:"text-[10px] border rounded px-1 py-0.5 bg-background text-muted-foreground",value:"",onChange:F=>{F.target.value&&I(F.target.value),F.target.value=""},children:[e.jsx("option",{value:"",children:"Merge variable..."}),Isn.map(F=>e.jsx("option",{value:F.key,children:F.label},F.key))]})]})]}),e.jsx("textarea",{value:h,onChange:F=>p(F.target.value),placeholder:_==="sms"?"Hey {{client_first_name}}, great talking with you today! Here's a quick video about what's next...":`Hi {{client_first_name}}, It was great meeting with you! Here's a video about what to expect next...`,className:"w-full rounded-md border border-input bg-background px-3 py-2 text-sm min-h-[100px] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs font-medium",children:"Attached Video"}),f?e.jsxs("div",{className:"mt-1 flex items-center gap-2",children:[e.jsxs("div",{className:"flex-1 text-xs text-muted-foreground truncate bg-muted/50 rounded px-2 py-1.5 border border-input",children:[e.jsx(fr,{className:"h-3 w-3 inline mr-1 text-primary"}),f.length>50?f.slice(0,50)+"...":f]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-destructive",onClick:()=>y(""),children:"Remove"})]}):e.jsxs("div",{className:"mt-1 flex items-center gap-1.5",children:[e.jsx(XLe,{onVideoReady:F=>y(F)}),e.jsx(e6,{userId:l,onSelect:F=>y(F),triggerSize:"sm",triggerClassName:"gap-1.5 flex-1"}),e.jsxs(B,{variant:"ghost",size:"sm",className:"gap-1 text-xs text-muted-foreground flex-1",onClick:()=>{const F=prompt("Paste a YouTube or Loom URL:");F&&y(F)},children:[e.jsx(Yo,{className:"h-3 w-3"})," Paste URL"]})]})]}),e.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-xs text-destructive hover:text-destructive",onClick:i,children:[e.jsx(_n,{className:"h-3 w-3 mr-1"})," Delete"]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",size:"sm",className:"text-xs",onClick:n,children:"Cancel"}),e.jsx(B,{size:"sm",className:"text-xs",onClick:D,disabled:E,children:E?"Saving...":"Save Drip"})]})]})]})]})}function zsn({template:s,onCopy:t,isCopying:n}){const[r,a]=N.useState(!1),i=s.body.replace(/<[^>]+>/g,""),l=s.deal_type==="buyer"?"Buyer":s.deal_type==="seller"?"Seller":null,o=s.delay_type==="instant"?"Sends instantly":s.delay_minutes>=1440?`Sends after ${Math.round(s.delay_minutes/1440)} day${Math.round(s.delay_minutes/1440)!==1?"s":""}`:s.delay_minutes>=60?`Sends after ${Math.round(s.delay_minutes/60)} hour${Math.round(s.delay_minutes/60)!==1?"s":""}`:`Sends after ${s.delay_minutes} min`;return e.jsxs("div",{className:"border rounded-xl overflow-hidden transition-all hover:shadow-sm",children:[e.jsxs("button",{onClick:()=>a(!r),className:"w-full flex items-start gap-3 p-4 text-left hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h4",{className:"font-medium text-sm",children:s.title}),e.jsx("p",{className:"text-xs text-muted-foreground mt-0.5 truncate",children:s.subject}),!r&&e.jsx("p",{className:"text-xs text-muted-foreground/70 line-clamp-1 mt-1",children:i})]}),e.jsxs("div",{className:"flex items-center gap-1.5 shrink-0 pt-0.5",children:[l&&e.jsx(Ue,{variant:"secondary",className:"text-[10px] px-1.5 py-0",children:l}),e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1",children:[s.channel==="sms"?e.jsx(Ai,{className:"h-3 w-3"}):e.jsx(Gs,{className:"h-3 w-3"}),s.channel==="sms"?"SMS":"Email"]}),e.jsxs(Ue,{variant:"outline",className:"text-[10px] gap-1",children:[e.jsx(pr,{className:"h-3 w-3"}),s.delay_type==="instant"?"Instant":o.replace("Sends ","")]}),r?e.jsx(ao,{className:"h-4 w-4 text-muted-foreground ml-1"}):e.jsx(ga,{className:"h-4 w-4 text-muted-foreground ml-1"})]})]}),r&&e.jsxs("div",{className:"border-t bg-muted/10 p-4 space-y-4",children:[e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Subject Line"}),e.jsx("p",{className:"text-sm font-medium",children:s.subject})]}),e.jsxs("div",{children:[e.jsx("p",{className:"text-[10px] uppercase font-semibold text-muted-foreground tracking-wider mb-1",children:"Email Body"}),e.jsx("div",{className:"text-sm text-foreground/80 bg-background rounded-lg border p-4 prose prose-sm max-w-none [&_ul]:list-disc [&_ul]:pl-5 [&_ol]:list-decimal [&_ol]:pl-5 [&_li]:my-0.5 [&_p]:my-2 [&_a]:text-primary [&_a]:underline",dangerouslySetInnerHTML:{__html:s.body}})]}),e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),e.jsx("span",{children:o})]}),e.jsxs(B,{onClick:c=>{c.stopPropagation(),t()},size:"sm",className:"w-full gap-1.5",disabled:n,children:[e.jsx(Zr,{className:"h-3.5 w-3.5"}),"Use This Template"]})]})]})}const nNt=()=>{const s=Xl();return N.useEffect(()=>{console.error("404 Error: User attempted to access non-existent route:",s.pathname)},[s.pathname]),e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-gray-100",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"mb-4 text-4xl font-bold",children:"404"}),e.jsx("p",{className:"mb-4 text-xl text-gray-600",children:"Oops! Page not found"}),e.jsx("a",{href:"/",className:"text-blue-500 underline hover:text-blue-700",children:"Return to Home"})]})})};function Bsn(){return N.useEffect(()=>(document.body.classList.add("cardstudio-page"),()=>{document.body.classList.remove("cardstudio-page")}),[]),e.jsxs(Bpe,{children:[e.jsx(as,{path:"/c/:shareToken",element:e.jsx(sNt,{})}),e.jsx(as,{path:"*",element:e.jsx(nNt,{})})]})}const ANe={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function rNt({slugOverride:s}){const t=bi(),n=s||t.slug,[r,a]=N.useState("types"),[i,l]=N.useState(null),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState(new Date),[f,y]=N.useState({name:"",email:"",phone:"",message:""}),[_,v]=N.useState(!1),{data:j,isLoading:w}=dt({queryKey:["public-booking-settings",n],queryFn:async()=>{const{data:W,error:ee}=await q.from("agent_booking_settings").select("*").eq("slug",n).eq("is_active",!0).single();if(ee)throw ee;return W},enabled:!!n}),{data:S}=dt({queryKey:["public-booking-profile",j==null?void 0:j.user_id],queryFn:async()=>{const{data:W,error:ee}=await q.from("profiles").select("name, avatar_url, email, phone, title, bio").eq("id",j.user_id).single();if(ee)throw ee;return W},enabled:!!(j!=null&&j.user_id)}),{data:A=[]}=dt({queryKey:["public-booking-types",j==null?void 0:j.user_id],queryFn:async()=>{const{data:W,error:ee}=await q.from("agent_booking_types").select("id, name, description, duration_minutes, color, icon, qualification_enabled").eq("user_id",j.user_id).eq("is_active",!0).order("sort_order");if(ee)throw ee;return W},enabled:!!(j!=null&&j.user_id)}),{data:E=[]}=dt({queryKey:["public-availability",j==null?void 0:j.user_id],queryFn:async()=>{const{data:W,error:ee}=await q.from("agent_availability_slots").select("day_of_week, start_time, end_time").eq("user_id",j.user_id).eq("is_active",!0);if(ee)throw ee;return W},enabled:!!(j!=null&&j.user_id)}),{data:O=[]}=dt({queryKey:["public-blocked-dates",j==null?void 0:j.user_id],queryFn:async()=>{const{data:W,error:ee}=await q.from("agent_blocked_dates").select("blocked_date").eq("user_id",j.user_id);if(ee)throw ee;return W.map(se=>se.blocked_date)},enabled:!!(j!=null&&j.user_id)}),{data:D=[]}=dt({queryKey:["public-existing-bookings",j==null?void 0:j.user_id,o],queryFn:async()=>{if(!o)return[];const W=Ss(o,"yyyy-MM-dd"),{data:ee,error:se}=await q.from("bookings").select("start_time, end_time").eq("agent_user_id",j.user_id).eq("booking_date",W).eq("status","confirmed");if(se)throw se;return ee},enabled:!!(j!=null&&j.user_id)&&!!o}),I=N.useMemo(()=>[...new Set(E.map(W=>W.day_of_week))],[E]),F=W=>{const ee=wf(new Date),se=Bl(ee,(j==null?void 0:j.max_advance_days)||30),oe=Bl(ee,0);return yb(W,oe)||Ov(W,se)||O.includes(Ss(W,"yyyy-MM-dd"))?!1:I.includes(W.getDay())},z=N.useMemo(()=>{if(!o||!i||!j)return[];const W=E.filter(me=>me.day_of_week===o.getDay()),ee=i.duration_minutes,se=j.buffer_minutes||0,oe=[],he=new Date,ce=(j.min_notice_hours||2)*60*60*1e3;for(const me of W){const[le,ve]=me.start_time.split(":").map(Number),[ge,Te]=me.end_time.split(":").map(Number);let Ie=F9(O9(o,le),ve);const Ce=F9(O9(o,ge),Te);for(;bP(Ie,ee)<=Ce;){const Me=Ss(Ie,"HH:mm"),Pe=Ss(bP(Ie,ee),"HH:mm");Ie.getTime()-he.getTime()>=ce&&(D.some(Ae=>{const Be=Ae.start_time.slice(0,5),we=Ae.end_time.slice(0,5);return MeBe})||oe.push(Me)),Ie=bP(Ie,ee+se)}}return oe},[o,i,E,j,D]),H=N.useMemo(()=>{const W=h.getFullYear(),ee=h.getMonth(),se=new Date(W,ee,1),oe=new Date(W,ee+1,0),he=se.getDay(),ce=[];for(let me=0;me{if(!(!i||!o||!d||!f.name||!j)){v(!0);try{const W=Ss(bP(F9(O9(new Date,parseInt(d.split(":")[0])),parseInt(d.split(":")[1])),i.duration_minutes),"HH:mm"),{error:ee}=await q.from("bookings").insert({agent_user_id:j.user_id,booking_type_id:i.id,booking_date:Ss(o,"yyyy-MM-dd"),start_time:d,end_time:W,guest_name:f.name,guest_email:f.email||null,guest_phone:f.phone||null,guest_message:f.message||null});if(ee)throw ee;q.functions.invoke("booking-notify",{body:{agentUserId:j.user_id,guestName:f.name,guestEmail:f.email||null,guestPhone:f.phone||null,guestMessage:f.message||null,bookingTypeName:i.name,bookingDate:Ss(o,"yyyy-MM-dd"),startTime:d,endTime:W,durationMinutes:i.duration_minutes,meetingLink:j.meeting_link||null}}).catch(se=>console.error("Booking notify error:",se)),a("confirmed")}catch(W){ae.error("Failed to book: "+W.message)}finally{v(!1)}}},Y=W=>{const[ee,se]=W.split(":").map(Number),oe=ee>=12?"PM":"AM";return`${ee%12||12}:${se.toString().padStart(2,"0")} ${oe}`};return w?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8] flex items-center justify-center",children:e.jsxs("div",{className:"flex flex-col items-center gap-3",children:[e.jsx("div",{className:"animate-spin rounded-full h-8 w-8 border-2 border-[#406E71] border-t-transparent"}),e.jsx("p",{className:"text-sm text-slate-500",children:"Loading booking page..."})]})}):j?e.jsxs("div",{className:"min-h-screen bg-gradient-to-br from-[#f0f4f8] via-white to-[#e8f0f8]",children:[e.jsx("div",{className:"h-1.5 bg-gradient-to-r from-[#406E71] via-[#5a9a9d] to-[#2a4c64]"}),e.jsxs("div",{className:"max-w-lg mx-auto px-4 py-6 sm:py-10",children:[e.jsxs("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden mb-6",children:[e.jsx("div",{className:"relative bg-gradient-to-r from-[#406E71] to-[#2a4c64] px-6 pt-6 pb-12",children:e.jsxs("div",{className:"absolute inset-0 opacity-10",children:[e.jsx("div",{className:"absolute top-2 right-8 w-20 h-20 rounded-full border-2 border-white/30"}),e.jsx("div",{className:"absolute bottom-4 left-12 w-10 h-10 rounded-full border border-white/20"})]})}),e.jsx("div",{className:"relative -mt-10 px-6",children:e.jsxs("div",{className:"flex items-end gap-4",children:[S!=null&&S.avatar_url?e.jsx("img",{src:S.avatar_url,alt:(S==null?void 0:S.name)||"Agent",className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl object-cover border-4 border-white shadow-md"}):e.jsx("div",{className:"w-20 h-20 sm:w-24 sm:h-24 rounded-2xl bg-gradient-to-br from-[#406E71] to-[#2a4c64] border-4 border-white shadow-md flex items-center justify-center",children:e.jsx(Wi,{className:"h-10 w-10 text-white"})}),e.jsxs("div",{className:"pb-1.5",children:[e.jsx("h1",{className:"text-xl sm:text-2xl font-bold text-slate-800 leading-tight",children:(S==null?void 0:S.name)||"Agent"}),(S==null?void 0:S.title)&&e.jsx("p",{className:"text-sm text-slate-500 mt-0.5",children:S.title})]})]})}),e.jsxs("div",{className:"px-6 py-4 flex flex-wrap gap-2",children:[(S==null?void 0:S.phone)&&e.jsxs("a",{href:`tel:${S.phone}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#406E71]/8 hover:bg-[#406E71]/15 text-[#406E71] text-xs font-medium transition-colors",children:[e.jsx(Cr,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:S.phone}),e.jsx("span",{className:"sm:hidden",children:"Call"})]}),(S==null?void 0:S.email)&&e.jsxs("a",{href:`mailto:${S.email}`,className:"inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-[#2a4c64]/8 hover:bg-[#2a4c64]/15 text-[#2a4c64] text-xs font-medium transition-colors",children:[e.jsx(Gs,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden sm:inline",children:S.email}),e.jsx("span",{className:"sm:hidden",children:"Email"})]})]})]}),e.jsx("div",{className:"bg-white rounded-2xl shadow-lg shadow-slate-200/60 border border-slate-100 overflow-hidden",children:e.jsxs("div",{className:"p-5 sm:p-6",children:[r==="types"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-base font-semibold text-slate-800",children:"Select a meeting type"}),e.jsx("p",{className:"text-xs text-slate-400 mt-0.5",children:"Choose the type of meeting you'd like to schedule"})]}),e.jsx("div",{className:"space-y-2.5",children:A.map(W=>e.jsx("button",{onClick:()=>{l(W),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:W.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:ANe[W.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:W.name}),W.description&&e.jsx("p",{className:"text-xs text-slate-500 mt-0.5 line-clamp-2",children:W.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(pr,{className:"h-3 w-3"}),W.duration_minutes,"m"]})]})})},W.id))})]}),r==="date"&&i&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>{a("types"),c(null),u(null)},className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(qr,{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:ANe[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(pr,{className:"h-3 w-3"}),i.duration_minutes," min"]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ss(h,"MMMM yyyy")}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>p(new Date(h.getFullYear(),h.getMonth()-1)),children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx("button",{className:"h-8 w-8 rounded-lg flex items-center justify-center text-slate-500 hover:bg-slate-100 hover:text-slate-800 transition-colors",onClick:()=>p(new Date(h.getFullYear(),h.getMonth()+1)),children:e.jsx(ga,{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(W=>e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400 font-semibold py-2",children:W},W)),H.map((W,ee)=>{if(!W)return e.jsx("div",{},`pad-${ee}`);const se=F(W),oe=o&&ql(W,o),he=ql(W,new Date);return e.jsx("button",{disabled:!se,onClick:()=>{c(W),u(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":se?"hover:bg-[#406E71]/10 text-slate-700 hover:text-[#406E71]":"text-slate-200 cursor-not-allowed"} ${he&&!oe?"ring-1 ring-[#406E71]/40":""}`,children:W.getDate()},W.toISOString())})]})]}),o&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Cl,{className:"h-4 w-4 text-[#406E71]"}),e.jsx("h3",{className:"font-semibold text-sm text-slate-800",children:Ss(o,"EEEE, MMMM d")})]}),z.length===0?e.jsxs("div",{className:"text-center py-8 space-y-2",children:[e.jsx(pr,{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(W=>{const ee=d===W;return e.jsx("button",{onClick:()=>u(W),className:`px-3 py-2.5 rounded-xl text-sm font-medium transition-all duration-150 ${ee?"bg-[#406E71] text-white shadow-md shadow-[#406E71]/30 scale-[1.02]":"bg-slate-50 text-slate-700 hover:bg-[#406E71]/10 hover:text-[#406E71] border border-slate-150"}`,children:Y(W)},W)})}),d&&e.jsx(B,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg",onClick:()=>a("form"),children:"Continue to Details"})]})]}),r==="form"&&i&&o&&d&&e.jsxs("div",{className:"space-y-5",children:[e.jsxs("button",{onClick:()=>a("date"),className:"flex items-center gap-1.5 text-xs font-medium text-slate-500 hover:text-slate-800 transition-colors",children:[e.jsx(qr,{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:ANe[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(Cl,{className:"h-3.5 w-3.5 text-[#406E71]"}),Ss(o,"EEE, MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{className:"h-3.5 w-3.5 text-[#406E71]"}),Y(d)," · ",i.duration_minutes," min"]})]})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{className:"text-xs font-semibold text-slate-700",children:"Full Name *"}),e.jsx(ye,{value:f.name,onChange:W=>y({...f,name:W.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(ne,{className:"text-xs font-semibold text-slate-700",children:"Email"}),e.jsxs("div",{className:"relative",children:[e.jsx(Gs,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{type:"email",value:f.email,onChange:W=>y({...f,email:W.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(ne,{className:"text-xs font-semibold text-slate-700",children:"Phone"}),e.jsxs("div",{className:"relative",children:[e.jsx(Cr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{type:"tel",value:f.phone,onChange:W=>y({...f,phone:W.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(ne,{className:"text-xs font-semibold text-slate-700",children:"Message (optional)"}),e.jsx(Ms,{value:f.message,onChange:W=>y({...f,message:W.target.value}),placeholder:"Anything you'd like the agent to know ahead of time?",rows:3,className:"rounded-xl border-slate-200 focus:border-[#406E71] focus:ring-[#406E71]/20 resize-none"})]})]}),e.jsx(B,{className:"w-full h-12 rounded-xl bg-[#406E71] hover:bg-[#365c5e] text-white font-semibold shadow-md shadow-[#406E71]/20 transition-all hover:shadow-lg disabled:opacity-60",onClick:Z,disabled:!f.name||_,children:_?e.jsxs("span",{className:"flex items-center gap-2",children:[e.jsx("div",{className:"animate-spin rounded-full h-4 w-4 border-2 border-white border-t-transparent"}),"Booking..."]}):"Confirm Booking"})]}),r==="confirmed"&&e.jsxs("div",{className:"text-center space-y-5 py-6",children:[e.jsxs("div",{className:"relative mx-auto w-20 h-20",children:[e.jsx("div",{className:"absolute inset-0 rounded-full bg-emerald-100 animate-ping opacity-30"}),e.jsx("div",{className:"relative w-20 h-20 rounded-full bg-gradient-to-br from-emerald-400 to-emerald-600 flex items-center justify-center shadow-lg shadow-emerald-200",children:e.jsx(vr,{className:"h-10 w-10 text-white"})})]}),e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold text-slate-800",children:"You're booked!"}),e.jsxs("p",{className:"text-slate-500 mt-1.5",children:[i==null?void 0:i.name," with ",(S==null?void 0:S.name)||"your agent"]})]}),e.jsx("div",{className:"inline-flex items-center gap-3 px-5 py-3 rounded-xl bg-slate-50 border border-slate-100",children:e.jsxs("div",{className:"text-left text-sm",children:[e.jsx("p",{className:"font-semibold text-slate-800",children:o&&Ss(o,"EEEE, MMMM d, yyyy")}),e.jsxs("p",{className:"text-slate-500",children:[d&&Y(d)," · ",i==null?void 0:i.duration_minutes," min"]})]})}),e.jsx("p",{className:"text-sm text-slate-400 max-w-xs mx-auto",children:"A confirmation with meeting details will be sent to you shortly."}),((S==null?void 0:S.phone)||(S==null?void 0:S.email))&&e.jsxs("div",{className:"flex flex-col items-center gap-2 pt-2",children:[e.jsx("p",{className:"text-xs text-slate-400 uppercase tracking-wider font-semibold",children:"Contact"}),e.jsxs("div",{className:"flex gap-3",children:[(S==null?void 0:S.phone)&&e.jsxs("a",{href:`tel:${S.phone}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#406E71]/10 text-[#406E71] text-xs font-medium hover:bg-[#406E71]/20 transition-colors",children:[e.jsx(Cr,{className:"h-3.5 w-3.5"})," Call"]}),(S==null?void 0:S.email)&&e.jsxs("a",{href:`mailto:${S.email}`,className:"inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-[#2a4c64]/10 text-[#2a4c64] text-xs font-medium hover:bg-[#2a4c64]/20 transition-colors",children:[e.jsx(Gs,{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(Cl,{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 $sn(){const t=Xl().pathname.slice(1).split("/")[0];return N.useEffect(()=>{document.body.classList.add("booking-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("booking-page"),r.forEach(clearTimeout)}},[]),t?e.jsx(rNt,{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 Usn(){const t=Xl().pathname.slice(1);return N.useEffect(()=>{document.body.classList.add("connect-page");const n=()=>{['[id*="lc_text_widget"]','[id*="lc_text-widget"]','[class*="lc-text-widget"]','[class*="lc_text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("connect-page"),r.forEach(clearTimeout)}},[]),!t||t===""?e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-slate-100 flex items-center justify-center p-6",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-slate-800 mb-2",children:"Connect"}),e.jsx("p",{className:"text-slate-500",children:"Stay connected with your real estate professional."}),e.jsx("p",{className:"text-slate-400 text-sm mt-2",children:"Visit a specific agent link to get started."})]})}):e.jsx(Nmt,{slugOverride:t})}function qsn(s){try{const t=document.createElement("canvas"),n=t.width=Math.min(s.naturalWidth,64),r=t.height=Math.min(s.naturalHeight,64),a=t.getContext("2d");if(!a)return!0;a.drawImage(s,0,0,n,r);const i=a.getImageData(0,0,n,r).data,l=[[0,0],[n-1,0],[0,r-1],[n-1,r-1],[Math.floor(n/2),0],[Math.floor(n/2),r-1],[0,Math.floor(r/2)],[n-1,Math.floor(r/2)]];for(const[o,c]of l)if(i[(c*n+o)*4+3]<250)return!0;return!1}catch{return!0}}const Vsn={playfair:"'Playfair Display', Georgia, serif",baskerville:"'Libre Baskerville', Georgia, serif",instrument:"'Instrument Serif', Georgia, serif",sans:"'Inter', system-ui, sans-serif"};function Hsn({page:s,fields:t,answers:n,setAnswers:r,onSubmit:a,isSubmitting:i,renderField:l}){const o=s.accent_color||"#E8B84A",c=s.primary_color||"#0F1B3D",d=Vsn[s.heading_font||"playfair"],u=s.eyebrow||null,h=s.headline_accent||null,p=Array.isArray(s.trust_pills)?s.trust_pills:[],f=t.slice(0,5);return e.jsxs("section",{className:"relative w-full min-h-screen md:min-h-[760px] overflow-hidden",style:{backgroundColor:c},children:[s.hero_image_url?e.jsx("img",{src:s.hero_image_url,alt:"",className:"absolute inset-0 w-full h-full object-cover",loading:"eager"}):e.jsx("div",{className:"absolute inset-0",style:{background:`linear-gradient(135deg, ${c}, #000)`}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-r from-black/85 via-black/55 to-black/25"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/70 via-transparent to-black/20"}),e.jsx("div",{className:"relative z-10 mx-auto w-full max-w-7xl px-6 md:px-10 py-16 md:py-24 min-h-screen md:min-h-[760px] flex items-center",children:e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-5 gap-10 lg:gap-12 w-full items-center",children:[e.jsxs("div",{className:"lg:col-span-3 text-white",children:[s.logo_url&&e.jsx(Gsn,{src:s.logo_url}),u&&e.jsx("p",{className:"text-xs md:text-sm font-semibold tracking-[0.22em] text-white/80 mb-4 uppercase",children:u}),e.jsxs("h1",{className:"font-bold leading-[1.04] mb-5 text-4xl sm:text-5xl md:text-6xl lg:text-[68px]",style:{fontFamily:d,letterSpacing:"-0.015em"},children:[s.hero_headline,h&&e.jsxs(e.Fragment,{children:[" ",e.jsx("span",{style:{color:o,fontStyle:"italic"},children:h})]})]}),s.hero_subtext&&e.jsx("p",{className:"text-base md:text-lg text-white/85 leading-relaxed max-w-xl",children:s.hero_subtext}),s.agent_name&&e.jsxs("div",{className:"mt-8 flex items-center gap-3",children:[s.agent_photo_url&&e.jsx("img",{src:s.agent_photo_url,alt:s.agent_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-white/30"}),e.jsxs("div",{className:"text-white/90",children:[e.jsx("p",{className:"font-semibold text-sm",children:s.agent_name}),e.jsxs("div",{className:"flex flex-wrap gap-x-4 gap-y-1 text-xs text-white/70 mt-0.5",children:[s.agent_phone&&e.jsxs("a",{href:`tel:${s.agent_phone}`,className:"flex items-center gap-1 hover:text-white",children:[e.jsx(Cr,{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(Gs,{className:"h-3 w-3"})," ",s.agent_email]})]})]})]})]}),e.jsx("div",{className:"lg:col-span-2",children:e.jsxs("div",{className:"rounded-2xl border border-white/15 bg-white/10 backdrop-blur-xl shadow-2xl p-5 md:p-6",children:[e.jsxs("form",{className:"space-y-3",onSubmit:a,children:[f.map(y=>e.jsxs("div",{children:[e.jsxs(ne,{className:"block text-[11px] font-semibold tracking-wider uppercase text-white/85 mb-1.5",children:[y.label,y.is_required&&e.jsx("span",{className:"ml-1",style:{color:o},children:"*"})]}),e.jsx("div",{className:"[&_input]:bg-white/95 [&_input]:border-0 [&_input]:text-neutral-900 [&_input]:placeholder:text-neutral-400 [&_textarea]:bg-white/95 [&_textarea]:border-0 [&_textarea]:text-neutral-900 [&_textarea]:placeholder:text-neutral-400 [&_button[role=combobox]]:bg-white/95 [&_button[role=combobox]]:border-0 [&_button[role=combobox]]:text-neutral-900",children:l(y,n,r,c)})]},y.id)),e.jsx("button",{type:"submit",disabled:i,className:"w-full px-6 py-3.5 rounded-lg font-bold text-neutral-900 text-base md:text-lg shadow-lg hover:brightness-110 active:brightness-95 transition-all disabled:opacity-60 mt-2",style:{backgroundColor:o},children:i?"Submitting...":s.cta_text||"Get Started"})]}),p.length>0&&e.jsx("div",{className:"flex flex-wrap gap-x-5 gap-y-2 mt-4",children:p.map((y,_)=>e.jsxs("span",{className:"flex items-center gap-1.5 text-[11px] md:text-xs text-white/80 font-medium",children:[e.jsx("span",{className:"h-1 w-1 rounded-full",style:{backgroundColor:o}}),y]},_))})]})})]})})]})}function Gsn({src:s}){const[t,n]=N.useState(null),r=e.jsx("img",{src:s,alt:"Logo",crossOrigin:"anonymous",className:"h-10 md:h-12 w-auto object-contain",onLoad:a=>n(qsn(a.currentTarget)),onError:()=>n(!0)});return t===!1?e.jsx("span",{className:"inline-flex items-center rounded-md bg-white/90 backdrop-blur px-3 py-2 mb-6 shadow-sm",children:r}):e.jsx("div",{className:"mb-6 inline-block drop-shadow-md",children:r})}function Wsn(s){const t=Math.max(0,Math.floor(s/1e3));return{d:Math.floor(t/86400),h:Math.floor(t%86400/3600),m:Math.floor(t%3600/60),s:t%60}}function Ksn(s,t,n){const r=new Date(t),a=new Date(r.getTime()+60*60*1e3),i=o=>o.toISOString().replace(/[-:]|\.\d{3}/g,""),l=new URL("https://www.google.com/calendar/render");return l.searchParams.set("action","TEMPLATE"),l.searchParams.set("text",s),l.searchParams.set("dates",`${i(r)}/${i(a)}`),n&&l.searchParams.set("location",n),l.toString()}function Ysn(s,t,n){const r=new Date(t),a=new Date(r.getTime()+60*60*1e3),i=o=>o.toISOString().replace(/[-:]|\.\d{3}/g,""),l=["BEGIN:VCALENDAR","VERSION:2.0","BEGIN:VEVENT",`UID:${Date.now()}@levelup`,`DTSTAMP:${i(new Date)}`,`DTSTART:${i(r)}`,`DTEND:${i(a)}`,`SUMMARY:${s}`,n?`LOCATION:${n}`:"","END:VEVENT","END:VCALENDAR"].filter(Boolean).join(`\r `);return`data:text/calendar;charset=utf-8,${encodeURIComponent(l)}`}function Zsn({startsAt:s,locationName:t,address:n,title:r,accent:a}){const[i,l]=N.useState(Date.now());N.useEffect(()=>{const f=setInterval(()=>l(Date.now()),1e3);return()=>clearInterval(f)},[]);const o=new Date(s).getTime();if(!Number.isFinite(o))return null;const c=Wsn(o-i),d=o-i<=0,u=new Date(s).toLocaleString("en-US",{weekday:"long",month:"long",day:"numeric",hour:"numeric",minute:"2-digit"}),h=[t,n].filter(Boolean).join(" · "),p=n?`https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(n)}`:null;return e.jsx("section",{className:"max-w-5xl mx-auto px-4 py-10",children:e.jsx("div",{className:"rounded-2xl border bg-white/80 backdrop-blur p-6 md:p-8 shadow-sm",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{className:"space-y-1.5",children:[e.jsx("div",{className:"text-xs uppercase tracking-wider font-medium",style:{color:a},children:d?"Just happened":"Event starts in"}),d?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Missed this one? Submit the form and we'll let you know about the next one."}):e.jsx("div",{className:"flex items-baseline gap-3",children:[{v:c.d,l:"days"},{v:c.h,l:"hrs"},{v:c.m,l:"min"},{v:c.s,l:"sec"}].map(f=>e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-3xl md:text-4xl font-bold tabular-nums",style:{color:a},children:String(f.v).padStart(2,"0")}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-muted-foreground",children:f.l})]},f.l))}),e.jsxs("div",{className:"flex flex-wrap items-center gap-x-4 gap-y-1 pt-2 text-sm text-neutral-700",children:[e.jsxs("span",{className:"inline-flex items-center gap-1.5",children:[e.jsx(pr,{className:"h-3.5 w-3.5"})," ",u]}),h&&e.jsxs("a",{href:p||"#",target:p?"_blank":void 0,rel:"noreferrer",className:"inline-flex items-center gap-1.5 hover:underline",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," ",h]})]})]}),!d&&e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs("a",{href:Ksn(r,s,h||null),target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[e.jsx(yr,{className:"h-4 w-4"})," Add to Google"]}),e.jsxs("a",{href:Ysn(r,s,h||null),download:`${r.replace(/\W+/g,"-").toLowerCase()}.ics`,className:"inline-flex items-center gap-2 text-sm font-medium rounded-lg border px-3 py-2 hover:bg-neutral-50",children:[e.jsx(yr,{className:"h-4 w-4"})," Apple / Outlook"]})]})]})})})}function Qsn(){try{const s="_lp_sid";let t=sessionStorage.getItem(s);return t||(t=crypto.randomUUID?crypto.randomUUID():`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,sessionStorage.setItem(s,t)),t}catch{return`s_${Date.now()}`}}function aNt({slugOverride:s}){var H;const{slug:t}=bi(),n=s||t,[r,a]=N.useState(!1),[i,l]=N.useState({}),[o,c]=N.useState(0),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f]=N.useState(()=>Date.now()),y=N.useState(()=>Qsn())[0],{data:_,isLoading:v}=dt({queryKey:["public-landing-page",n],queryFn:async()=>{const{data:Z,error:Y}=await q.from("landing_pages").select("*").eq("slug",n).eq("is_published",!0).single();if(Y)throw Y;return Z},enabled:!!n}),{data:j=[]}=dt({queryKey:["public-landing-page-fields",_==null?void 0:_.id],queryFn:async()=>{const{data:Z,error:Y}=await q.from("landing_page_fields").select("*").eq("page_id",_.id).order("sort_order");if(Y)throw Y;return Z},enabled:!!(_!=null&&_.id)});N.useEffect(()=>{_!=null&&_.id&&q.from("landing_pages").update({view_count:(_.view_count||0)+1}).eq("id",_.id).then(()=>{})},[_==null?void 0:_.id]),N.useEffect(()=>{if(!(_!=null&&_.id))return;const Z=new URLSearchParams(window.location.search);q.functions.invoke("landing-page-track",{body:{page_id:_.id,event_type:"view",session_id:y,utm_source:Z.get("utm_source"),utm_medium:Z.get("utm_medium"),utm_campaign:Z.get("utm_campaign"),referrer:document.referrer||null,device:window.matchMedia("(max-width: 768px)").matches?"mobile":"desktop"}}).catch(()=>{})},[_==null?void 0:_.id,y]);const w=yt({mutationFn:async()=>{const Z=j.find(le=>le.field_type==="text"&&le.label.toLowerCase().includes("name")),Y=j.find(le=>le.field_type==="email"),W=j.find(le=>le.field_type==="phone"),ee=Z?String(i[Z.label]||""):null,se=Y?String(i[Y.label]||""):null,oe=W?String(i[W.label]||""):null,he=new URLSearchParams(window.location.search),{data:ce,error:me}=await q.functions.invoke("landing-page-submit",{body:{page_id:_.id,answers:JSON.parse(JSON.stringify(i)),contact_name:ee,contact_email:se,contact_phone:oe,session_id:y,honeypot:h,rendered_at:f,utm_source:he.get("utm_source"),utm_medium:he.get("utm_medium"),utm_campaign:he.get("utm_campaign"),referrer:document.referrer||null}});if(me)throw me;return ce},onSuccess:Z=>{a(!0),Z!=null&&Z.redirect_url&&setTimeout(()=>{window.location.href=Z.redirect_url},1500)}}),S=Z=>{Z.preventDefault(),!(j.filter(W=>W.is_required&&!i[W.label]).length>0)&&w.mutate()};if(v)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-gray-400 border-t-transparent"})});if(!_)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50",children:e.jsxs("div",{className:"text-center",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-700",children:"Page Not Found"}),e.jsx("p",{className:"text-gray-500 mt-2",children:"This page doesn't exist or is no longer available."})]})});const A=_.primary_color||"#406E71",E=_.accent_color||"#2a4c64",O=_,D=_.page_type==="lead_magnet",I=_.page_type==="just_listed"||_.page_type==="just_sold",F=Array.isArray(O.property_photos)?O.property_photos:[],z=O.lead_magnet_file_url||O.lead_magnet_external_url;if(r)return e.jsx("div",{className:"min-h-screen flex items-center justify-center",style:{background:`linear-gradient(135deg, ${A}, ${E})`},children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl p-8 max-w-md mx-4 text-center",children:[e.jsx(vr,{className:"h-16 w-16 mx-auto mb-4",style:{color:A}}),e.jsx("h2",{className:"text-2xl font-bold mb-2",children:D?"Your download is ready!":"Submitted!"}),e.jsx("p",{className:"text-gray-600",children:_.success_message}),D&&z&&e.jsxs("a",{href:z,target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-2 mt-6 px-6 py-3 rounded-lg text-white font-semibold transition-transform hover:scale-105",style:{backgroundColor:A},children:[e.jsx(Ia,{className:"h-5 w-5"}),"Download ",O.lead_magnet_file_name||"Your File"]}),_.agent_name&&e.jsxs("div",{className:"mt-6 pt-4 border-t",children:[e.jsx("p",{className:"text-sm text-gray-500",children:"Contact"}),e.jsx("p",{className:"font-semibold",children:_.agent_name}),_.agent_phone&&e.jsxs("a",{href:`tel:${_.agent_phone}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:A},children:[e.jsx(Cr,{className:"h-3 w-3"})," ",_.agent_phone]}),_.agent_email&&e.jsxs("a",{href:`mailto:${_.agent_email}`,className:"text-sm flex items-center justify-center gap-1 mt-1",style:{color:A},children:[e.jsx(Gs,{className:"h-3 w-3"})," ",_.agent_email]})]})]})});if(I){const Z=Y=>{const W=parseFloat(Y.replace(/[^0-9.]/g,""));return isNaN(W)?Y:new Intl.NumberFormat("en-US",{style:"currency",currency:"USD",maximumFractionDigits:0}).format(W)};return e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[d&&F.length>0&&e.jsxs("div",{className:"fixed inset-0 z-50 bg-black/95 flex items-center justify-center",onClick:()=>u(!1),children:[e.jsx("button",{onClick:()=>u(!1),className:"absolute top-4 right-4 text-white/80 hover:text-white z-10",children:e.jsx($n,{className:"h-8 w-8"})}),e.jsx("button",{onClick:Y=>{Y.stopPropagation(),c(W=>W===0?F.length-1:W-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(ml,{className:"h-6 w-6"})}),e.jsx("img",{src:F[o],alt:`Property photo ${o+1}`,className:"max-h-[90vh] max-w-[90vw] object-contain rounded-lg",onClick:Y=>Y.stopPropagation()}),e.jsx("button",{onClick:Y=>{Y.stopPropagation(),c(W=>W===F.length-1?0:W+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(ga,{className:"h-6 w-6"})}),e.jsxs("div",{className:"absolute bottom-6 left-1/2 -translate-x-1/2 text-white/70 text-sm",children:[o+1," / ",F.length]})]}),F.length>0&&e.jsxs("div",{className:"relative max-w-6xl mx-auto px-4 pt-6",children:[e.jsx("div",{className:"absolute top-10 left-8 z-10 px-4 py-1.5 rounded-full text-white font-bold text-sm uppercase tracking-wider shadow-lg",style:{backgroundColor:O.property_status==="just_sold"?"#e74c3c":A},children:O.property_status==="just_sold"?"🎉 Just Sold":"🏡 Just Listed"}),F.length===1?e.jsxs("div",{className:"rounded-2xl overflow-hidden cursor-pointer group",onClick:()=>{c(0),u(!0)},children:[e.jsx("img",{src:F[0],alt:"Property",className:"w-full h-[50vh] object-cover group-hover:scale-105 transition-transform duration-500"}),e.jsxs("div",{className:"absolute bottom-4 right-4 bg-black/60 text-white px-3 py-1.5 rounded-lg text-sm flex items-center gap-1.5 opacity-0 group-hover:opacity-100 transition-opacity",children:[e.jsx(r4,{className:"h-4 w-4"})," View"]})]}):F.length===2?e.jsx("div",{className:"grid grid-cols-2 gap-2 rounded-2xl overflow-hidden",children:F.slice(0,2).map((Y,W)=>e.jsx("div",{className:"cursor-pointer group relative",onClick:()=>{c(W),u(!0)},children:e.jsx("img",{src:Y,alt:`Property ${W+1}`,className:"w-full h-[45vh] object-cover group-hover:scale-105 transition-transform duration-500"})},W))}):e.jsxs("div",{className:"grid grid-cols-4 gap-2 rounded-2xl overflow-hidden",style:{height:"55vh"},children:[e.jsx("div",{className:"col-span-2 row-span-2 cursor-pointer group relative",onClick:()=>{c(0),u(!0)},children:e.jsx("img",{src:F[0],alt:"Property main",className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"})}),F.slice(1,5).map((Y,W)=>e.jsxs("div",{className:"cursor-pointer group relative",onClick:()=>{c(W+1),u(!0)},children:[e.jsx("img",{src:Y,alt:`Property ${W+2}`,className:"w-full h-full object-cover group-hover:scale-105 transition-transform duration-500"}),W===3&&F.length>5&&e.jsxs("div",{className:"absolute inset-0 bg-black/50 flex items-center justify-center text-white font-bold text-lg",children:["+",F.length-5," more"]})]},W))]}),F.length>2&&e.jsxs("button",{onClick:()=>{c(0),u(!0)},className:"absolute bottom-4 right-8 bg-white shadow-lg hover:shadow-xl text-gray-800 px-4 py-2 rounded-lg text-sm font-medium flex items-center gap-2 transition-shadow",children:[e.jsx(r4,{className:"h-4 w-4"})," View all ",F.length," photos"]})]}),F.length===0&&e.jsx("div",{className:"relative py-16 px-4",style:{background:_.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${_.hero_image_url}) center/cover`:`linear-gradient(135deg, ${A}, ${E})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[_.logo_url&&e.jsx("img",{src:_.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:_.hero_headline}),_.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:_.hero_subtext})]})}),e.jsx("div",{className:"max-w-4xl mx-auto px-4 py-8",children:e.jsxs("div",{className:"grid md:grid-cols-5 gap-6",children:[e.jsx("div",{className:"md:col-span-3 space-y-6",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[O.property_price&&e.jsx("p",{className:"text-3xl md:text-4xl font-bold mb-2",style:{color:A},children:Z(O.property_price)}),O.property_address&&e.jsxs("p",{className:"text-gray-600 flex items-center gap-1.5 mb-5 text-lg",children:[e.jsx(ka,{className:"h-5 w-5 shrink-0"})," ",O.property_address]}),e.jsxs("div",{className:"flex gap-6 mb-5 py-4 border-y border-gray-100",children:[O.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(J0,{className:"h-5 w-5",style:{color:A}})," ",O.property_beds]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bedrooms"})]}),O.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(kp,{className:"h-5 w-5",style:{color:A}})," ",O.property_baths]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Bathrooms"})]}),O.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(Z2,{className:"h-5 w-5",style:{color:A}})," ",Number(O.property_sqft).toLocaleString()]}),e.jsx("p",{className:"text-xs text-gray-500 mt-0.5",children:"Sq Ft"})]})]}),O.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:O.property_description})]})]})}),e.jsx("div",{className:"md:col-span-2",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 sticky top-6",children:[e.jsx("h2",{className:"text-lg font-bold mb-1",style:{color:A},children:O.property_status==="just_sold"?"Want results like this?":"Interested in this property?"}),e.jsx("p",{className:"text-gray-500 text-sm mb-4",children:"Fill out the form and I'll be in touch!"}),_.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-5 pb-4 border-b",children:[_.agent_photo_url&&e.jsx("img",{src:_.agent_photo_url,alt:_.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold text-sm",children:_.agent_name}),e.jsxs("div",{className:"flex flex-col gap-0.5 text-xs text-gray-500",children:[_.agent_phone&&e.jsxs("a",{href:`tel:${_.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Cr,{className:"h-3 w-3"})," ",_.agent_phone]}),_.agent_email&&e.jsxs("a",{href:`mailto:${_.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Gs,{className:"h-3 w-3"})," ",_.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:S,className:"space-y-3",children:[j.map(Y=>e.jsxs("div",{children:[e.jsxs(ne,{className:"text-xs font-medium",children:[Y.label,Y.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),MNe(Y,i,l)]},Y.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:w.isPending,children:w.isPending?"Submitting...":"Submit"}),w.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center",children:"Something went wrong. Please try again."})]})]})})]})}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]})}return _.theme_style!=="classic"&&!D?e.jsxs("div",{className:"min-h-screen bg-neutral-50",children:[e.jsx("input",{type:"text",name:"company_website",tabIndex:-1,autoComplete:"off","aria-hidden":"true",value:h,onChange:Z=>p(Z.target.value),style:{position:"absolute",left:"-10000px",top:"auto",width:"1px",height:"1px",overflow:"hidden"}}),e.jsx(Hsn,{page:_,fields:j,answers:i,setAnswers:l,onSubmit:S,isSubmitting:w.isPending,renderField:MNe}),_.page_type==="event_registration"&&((H=_.settings)==null?void 0:H.event_starts_at)&&e.jsx(Zsn,{startsAt:_.settings.event_starts_at,locationName:_.settings.event_location_name,address:_.settings.event_address,title:_.hero_headline||_.title,accent:_.accent_color||_.primary_color||"#406E71"}),w.isError&&e.jsx("p",{className:"text-sm text-red-500 text-center py-4",children:"Something went wrong. Please try again."}),e.jsx("div",{className:"text-center py-8 text-xs text-gray-400",children:"Powered by LevelUp"})]}):e.jsxs("div",{className:"min-h-screen bg-gray-50",children:[e.jsx("div",{className:"relative py-16 px-4",style:{background:_.hero_image_url?`linear-gradient(rgba(0,0,0,0.55), rgba(0,0,0,0.55)), url(${_.hero_image_url}) center/cover`:`linear-gradient(135deg, ${A}, ${E})`},children:e.jsxs("div",{className:"max-w-2xl mx-auto text-center text-white",children:[_.logo_url&&e.jsx("img",{src:_.logo_url,alt:"Logo",className:"h-12 w-auto mx-auto mb-6"}),e.jsx("h1",{className:"text-3xl md:text-4xl font-bold",children:_.hero_headline}),_.hero_subtext&&e.jsx("p",{className:"mt-3 text-lg opacity-90",children:_.hero_subtext}),D&&O.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(Ia,{className:"h-4 w-4"}),"Free Download: ",O.lead_magnet_file_name]})]})}),e.jsx("div",{className:"max-w-2xl mx-auto px-4 -mt-8",children:e.jsxs("div",{className:"bg-white rounded-2xl shadow-xl p-6 md:p-8",children:[D&&e.jsx("p",{className:"text-sm text-gray-500 mb-4 text-center",children:"Fill out the form below to get your free download!"}),_.agent_name&&e.jsxs("div",{className:"flex items-center gap-3 mb-6 pb-4 border-b",children:[_.agent_photo_url&&e.jsx("img",{src:_.agent_photo_url,alt:_.agent_name,className:"h-12 w-12 rounded-full object-cover"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-semibold",children:_.agent_name}),e.jsxs("div",{className:"flex items-center gap-3 text-sm text-gray-500",children:[_.agent_phone&&e.jsxs("a",{href:`tel:${_.agent_phone}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Cr,{className:"h-3 w-3"})," ",_.agent_phone]}),_.agent_email&&e.jsxs("a",{href:`mailto:${_.agent_email}`,className:"flex items-center gap-1 hover:underline",children:[e.jsx(Gs,{className:"h-3 w-3"})," ",_.agent_email]})]})]})]}),e.jsxs("form",{onSubmit:S,className:"space-y-4",children:[j.map(Z=>e.jsxs("div",{children:[e.jsxs(ne,{className:"text-sm font-medium",children:[Z.label,Z.is_required&&e.jsx("span",{className:"text-red-500 ml-1",children:"*"})]}),MNe(Z,i,l)]},Z.id)),e.jsx(B,{type:"submit",className:"w-full text-white",style:{backgroundColor:A},disabled:w.isPending,children:w.isPending?"Submitting...":D?"Get My Free Download":"Submit"}),w.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 MNe(s,t,n,r){const a=t[s.label]||"",i=Array.isArray(s.options)?s.options:[];switch(s.field_type){case"text":case"email":case"phone":return e.jsx(ye,{type:s.field_type==="email"?"email":s.field_type==="phone"?"tel":"text",value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",className:"mt-1"});case"textarea":return e.jsx(Ms,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),placeholder:s.placeholder||"",rows:3,className:"mt-1"});case"select":return e.jsxs(us,{value:String(a),onValueChange:l=>n(o=>({...o,[s.label]:l})),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{placeholder:"Select..."})}),e.jsx(cs,{children:i.map(l=>e.jsx(Ze,{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(hi,{checked:o.includes(l),onCheckedChange:c=>{const d=c?[...o,l]:o.filter(u=>u!==l);n(u=>({...u,[s.label]:d}))}}),e.jsx("span",{className:"text-sm",children:l})]},l)})});case"toggle":return e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[e.jsx(jn,{checked:!!a,onCheckedChange:l=>n(o=>({...o,[s.label]:l?"Yes":"No"}))}),e.jsx("span",{className:"text-sm text-gray-600",children:a?"Yes":"No"})]});default:return e.jsx(ye,{value:String(a),onChange:l=>n(o=>({...o,[s.label]:l.target.value})),className:"mt-1"})}}function Xsn(){const t=Xl().pathname.slice(1).split("/")[0];return N.useEffect(()=>{document.body.classList.add("landing-page-public");const n=()=>{['[id*="lc_text_widget"]','[class*="lc-text-widget"]','[class*="lc_text_widget"]',".lc_text-widget--bubble",'[id*="chat-widget"]','[class*="chat-widget"]','iframe[src*="widgets.leadconnectorhq"]','iframe[src*="leadconnector"]','iframe[src*="msgsndr"]',"[data-chat-widget]","[data-widget-id]",'div[style*="z-index"][style*="position: fixed"][style*="bottom"]','div[id^="fc_"]','div[id^="hubspot"]',".widget-visible"].forEach(i=>{document.querySelectorAll(i).forEach(l=>{l.style.display="none"})})};n();const r=[setTimeout(n,500),setTimeout(n,1500),setTimeout(n,3e3),setTimeout(n,5e3)];return()=>{document.body.classList.remove("landing-page-public"),r.forEach(clearTimeout)}},[]),t?e.jsx(aNt,{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 Jsn=[{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}],Hfn={hero:"Hero Section",featured_listings:"Featured Listings",featured_areas:"Featured Areas",about:"About Me",testimonials:"Testimonials",cta_banner:"Call To Action",new_listings:"New Listings Carousel",open_houses:"Open Houses Carousel",my_listings:"My Listings Carousel",city_pages:"City Pages Grid",property_types:"Property Types Gallery",advantages:"Advantages / Why Choose Us",rate_my_agent:"RateMyAgent Reviews",lifestyle_gallery:"Lifestyle Gallery",market_pulse:"Market Pulse",concierge_services:"Concierge Services",land_use_guide:"Land Use Guide",land_valuation_cta:"Land Valuation CTA",acreage_showcase:"Acreage Showcase",featured_video:"Featured Video"},Gfn={hero:"Full-screen background image with headline, subtitle, and search bar",featured_listings:"Grid of highlighted properties from the MLS",featured_areas:"Spotlight regions or neighborhoods that link to property search",about:"Agent photo, bio, and credentials section",testimonials:"Client reviews carousel with quotes",cta_banner:"Call-to-action block to drive contact and search engagement",new_listings:"Horizontal carousel of newest listings, filterable by city",open_houses:"Horizontal carousel of open house listings, filterable by city",my_listings:"Showcase the agent's own active listings in a carousel",city_pages:"Grid of your city landing pages with photos and links",property_types:"Visual gallery of property categories (Ranch, Farm, Land, etc.)",advantages:"Feature cards highlighting your expertise and unique value",rate_my_agent:"Verified client reviews carousel powered by RateMyAgent",lifestyle_gallery:"Cinematic photo grid showcasing luxury living — pools, views, interiors",market_pulse:"Sleek market stats dashboard with avg price, days on market, inventory",concierge_services:"White-glove services showcase — staging, design, moving coordination",land_use_guide:"Interactive land use cards — Agriculture, Hunting, Equestrian, Recreational",land_valuation_cta:`"What's Your Land Worth?" — bold call-to-action for landowners`,acreage_showcase:"Large visual cards emphasizing lot size with aerial imagery",featured_video:"Embedded YouTube or Bunny video section for cinematic storytelling"},SXe={basic:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","featured_video","cta_banner"],luxury:["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","lifestyle_gallery","market_pulse","concierge_services","featured_video"],"land-ranch":["hero","featured_listings","new_listings","open_houses","my_listings","city_pages","featured_areas","about","testimonials","rate_my_agent","cta_banner","property_types","advantages","land_use_guide","land_valuation_cta","acreage_showcase","featured_video"]};function Wfn(s){return SXe[s]||SXe.basic}function enn(s){const t=s.theme_config||{};return{themeTier:s.theme_tier||"basic",brandColor:s.brand_color||"#0f172a",accentColor:s.accent_color||"#3b82f6",fontFamily:s.font_family||"Inter",heroImageUrl:s.hero_image_url||null,homepageModules:Array.isArray(s.homepage_modules)&&s.homepage_modules.length?s.homepage_modules.map(n=>typeof n=="string"?{type:n,enabled:!0}:{enabled:!0,...n}):Jsn,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 tnn(){const t=window.location.hostname.match(/^([^.]+)\.thelocalmove\.com$/i);return t?t[1]:null}function snn(){const s=tnn(),{data:t,isLoading:n,error:r}=dt({queryKey:["lead-site",s],queryFn:async()=>{var u;if(!s)return null;const{data:a,error:i}=await q.from("lead_sites").select("*").eq("subdomain_slug",s).eq("is_active",!0).maybeSingle();if(i)throw i;if(!a)return null;const{data:l}=await q.from("profiles").select("id, name, avatar_url, email, phone, title, bio, areas_served, years_experience, instagram_url, facebook_url, linkedin_url").eq("id",a.agent_id).single();let o=null;if(a.show_team_logo)if(a.team_logo_url)o=a.team_logo_url;else{const{data:h}=await q.from("team_members").select("team_id, teams(avatar_url, name)").eq("user_id",a.agent_id).limit(1).maybeSingle();h&&((u=h.teams)!=null&&u.avatar_url)&&(o=h.teams.avatar_url)}const c={id:a.id,agentId:a.agent_id,subdomainSlug:a.subdomain_slug,mlsProviderId:a.mls_provider_id,siteTitle:a.site_title,siteTagline:a.site_tagline,leadRegistrationMode:a.lead_registration_mode||"disabled",registrationTriggerCount:a.registration_trigger_count??1,themeConfig:a.theme_config||{},isActive:a.is_active,brokerageLegalName:a.brokerage_legal_name||null,brokerageLicenseNumber:a.brokerage_license_number||null,agentLicenseNumber:a.agent_license_number||null,licenseState:a.license_state||null,mlsDisclaimerText:a.mls_disclaimer_text||null,mlsLogoUrl:a.mls_logo_url||null,equalHousingEnabled:a.equal_housing_enabled??!0,faviconUrl:a.favicon_url||null,ogImageUrl:a.og_image_url||null,showTeamLogo:a.show_team_logo??!1,teamLogoUrl:o,noMlsMode:a.no_mls_mode===!0,bookingUrl:a.booking_url||null,pageSubtitles:a.page_subtitles||{},agent:l?{id:l.id,full_name:l.name||"",avatar_url:l.avatar_url,email:l.email,phone:l.phone,title:l.title,bio:l.bio,areas_served:l.areas_served||null,years_experience:l.years_experience??null,instagram_url:l.instagram_url||null,facebook_url:l.facebook_url||null,linkedin_url:l.linkedin_url||null}:void 0,testimonials:Array.isArray(a.testimonials)?a.testimonials.filter(h=>h&&typeof h=="object"&&h.text).map(h=>({name:String(h.name||"Client"),text:String(h.text),rating:typeof h.rating=="number"?h.rating:5,location:h.location?String(h.location):void 0})):[],seoMetaTitle:a.seo_meta_title||null,seoMetaDescription:a.seo_meta_description||null},d=enn(a);return{siteConfig:c,themeConfig:d}},enabled:!!s,staleTime:5*60*1e3,gcTime:30*60*1e3,refetchOnWindowFocus:!1});return{siteConfig:(t==null?void 0:t.siteConfig)??null,themeConfig:(t==null?void 0:t.themeConfig)??null,isLoading:n,error:r,slug:s}}async function nnn(s,t){try{await q.functions.invoke("lead-site-notify",{body:{lead:t,lead_site_id:s}})}catch(n){console.warn("Lead notification failed:",n)}}const iNt=N.createContext(null);function V1e(){const s=N.useContext(iNt);if(!s)throw new Error("useLeadSiteAuth must be used within LeadSiteAuthProvider");return s}function rnn({siteConfig:s,children:t}){const[n,r]=N.useState(null),[a,i]=N.useState(null),[l,o]=N.useState(!0);N.useEffect(()=>{const{data:{subscription:h}}=q.auth.onAuthStateChange(async(p,f)=>{const y=(f==null?void 0:f.user)??null;if(r(y),y){const{data:_}=await q.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",y.id).eq("lead_site_id",s.id).maybeSingle();_&&i({..._,email:y.email||""})}else i(null);o(!1)});return q.auth.getSession().then(({data:{session:p}})=>{r((p==null?void 0:p.user)??null),p!=null&&p.user?q.from("lead_site_consumer_profiles").select("id, name, phone").eq("user_id",p.user.id).eq("lead_site_id",s.id).maybeSingle().then(({data:f})=>{f&&i({...f,email:p.user.email||""}),o(!1)}):o(!1)}),()=>h.unsubscribe()},[s.id]);const c=N.useCallback(async h=>{const p=h.email.toLowerCase().trim(),f=h.phone.replace(/\D/g,""),{data:y,error:_}=await q.auth.signUp({email:p,password:f,options:{data:{full_name:h.name,consumer_site_id:s.id},emailRedirectTo:window.location.origin}});if(_){if(_.message.includes("already registered")){await d(p,f);return}throw _}if(y.user){const{error:v}=await q.from("lead_site_consumer_profiles").insert({user_id:y.user.id,lead_site_id:s.id,name:h.name.trim(),phone:h.phone.trim()});v&&console.warn("Consumer profile insert error:",v);const{error:j}=await q.from("lead_site_leads").insert({lead_site_id:s.id,name:h.name.trim(),email:p,phone:h.phone.trim(),message:"Created account on website",source_page:window.location.pathname,lead_type:"website_registration",metadata:{registered:!0,has_account:!0}});j&&console.error("Lead insert error (CRM sync may not trigger):",j),nnn(s.id,{name:h.name.trim(),email:p,phone:h.phone.trim(),lead_type:"website_registration",message:"Created account on website",source_page:window.location.pathname})}},[s.id]),d=N.useCallback(async(h,p)=>{const f=p.replace(/\D/g,""),{error:y}=await q.auth.signInWithPassword({email:h.toLowerCase().trim(),password:f});if(y)throw y},[]),u=N.useCallback(async()=>{await q.auth.signOut(),r(null),i(null)},[]);return e.jsx(iNt.Provider,{value:{user:n,profile:a,isLoading:l,signUp:c,signIn:d,signOut:u},children:t})}const ann=new Set(["7605cc2e-ce21-4f4f-8bb1-4c0f217b1109"]),inn=new Set(["tomlois"]);function oNt(s,t){var n;return s?(t==null?void 0:t.referralMode)===!0||((n=s.themeConfig)==null?void 0:n.referralMode)===!0||s.noMlsMode===!0||ann.has(s.id||"")||inn.has((s.subdomainSlug||"").toLowerCase())||!s.mlsProviderId:!1}function Kfn(s){return`Contact ${s.split(" ")[0]||"Me"}`}function o8e({open:s,mode:t,siteConfig:n,onComplete:r,onSkip:a,theme:i="default",accentColor:l}){var Y;const{signUp:o,signIn:c}=V1e(),[d,u]=N.useState(!1),[h,p]=N.useState(""),[f,y]=N.useState(""),[_,v]=N.useState(""),[j,w]=N.useState(!1),[S,A]=N.useState(""),E=t==="required",O=i==="luxury",D=l||(O?"#c9a96e":"#2563eb"),I=((Y=n.agent)==null?void 0:Y.full_name)||"the agent",F={borderColor:`${D}66`,"--tw-ring-color":`${D}66`},z=async W=>{var se;if(W.preventDefault(),A(""),!f.trim()||!_.trim()){A("Email and phone number are required.");return}if(!d&&!h.trim()){A("Name is required.");return}if(_.replace(/\D/g,"").length<7){A("Please enter a valid phone number.");return}w(!0);try{d?await c(f,_):await o({name:h,email:f,phone:_}),r()}catch(oe){(se=oe==null?void 0:oe.message)!=null&&se.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{w(!1)}},H=O?"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",Z=O?F:void 0;return e.jsx(_s,{open:s,onOpenChange:E?void 0:W=>{W||a()},children:e.jsxs(bs,{className:`sm:max-w-md ${O?"border-white/10 bg-[#f7f1e7] text-[#201915]":""}`,onPointerDownOutside:E?W=>W.preventDefault():void 0,onEscapeKeyDown:E?W=>W.preventDefault():void 0,children:[e.jsxs(js,{children:[e.jsx(ws,{className:"text-xl",style:O?{fontFamily:"'Playfair Display', Georgia, serif"}:void 0,children:d?"Welcome Back":E?"Create a Free Account to Continue":"Save Your Search & Get Updates"}),e.jsx(Jn,{className:O?"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 ${I}.`})]}),e.jsxs("form",{onSubmit:z,className:"space-y-3 mt-2",children:[!d&&e.jsx("input",{type:"text",required:!0,placeholder:"Your name",value:h,onChange:W=>p(W.target.value),className:H,style:Z}),e.jsx("input",{type:"email",required:!0,placeholder:"Email address",value:f,onChange:W=>y(W.target.value),className:H,style:Z}),e.jsxs("div",{children:[e.jsx("input",{type:"tel",required:!0,placeholder:"Phone number",value:_,onChange:W=>v(W.target.value),className:H,style:Z}),e.jsx("p",{className:`text-xs mt-1 ${O?"text-[#8a7869]":"text-gray-400"}`,children:d?"Your phone number is your password":"Your phone number will be used as your password"})]}),S&&e.jsx("p",{className:"text-red-600 text-sm",children:S}),e.jsx("button",{type:"submit",disabled:j,className:`w-full py-2.5 font-medium rounded-lg disabled:opacity-50 transition-colors ${O?"text-black hover:opacity-90 tracking-wider uppercase text-sm":"bg-blue-600 text-white hover:bg-blue-700"}`,style:O?{backgroundColor:D}:void 0,children:j?d?"Signing in...":"Creating account...":d?"Sign In":"Create Account"}),e.jsx("button",{type:"button",onClick:()=>{u(!d),A("")},className:"w-full text-center text-sm hover:opacity-80 transition-opacity",style:{color:D},children:d?"Don't have an account? Sign up":"Already have an account? Sign in"}),!E&&!d&&e.jsx("button",{type:"button",onClick:a,className:`w-full py-2 text-sm transition-colors ${O?"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 ${O?"text-[#8a7869]":"text-gray-400"}`,children:"By registering you agree to receive property updates. You can unsubscribe anytime."})]})})}function l8e({siteConfig:s,pagePath:t}){const n=s.agent;if(!n)return null;const r=`https://${s.subdomainSlug}.thelocalmove.com`,i=(n.areas_served||"").split(/,|;|\|/).map(S=>S.trim()).filter(Boolean),l=i[0]||"",[o,c]=l.split(/,\s*/),d=(n.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],u=[...new Set(d.map(S=>S.toUpperCase()))],h=s.testimonials||[],p=h.length?{"@type":"AggregateRating",ratingValue:(h.reduce((S,A)=>S+(A.rating||5),0)/h.length).toFixed(1),reviewCount:h.length,bestRating:5,worstRating:1}:void 0,f=[n.facebook_url,n.instagram_url,n.linkedin_url].filter(Boolean),y={"@context":"https://schema.org","@type":["RealEstateAgent","LocalBusiness"],"@id":`${r}/#agent`,name:n.full_name,url:r,image:n.avatar_url||s.ogImageUrl||void 0,logo:s.ogImageUrl||n.avatar_url||void 0,email:n.email,telephone:n.phone||void 0,jobTitle:n.title||"Real Estate Agent",description:n.bio||`${n.full_name} is a trusted local real estate professional${l?` serving ${l}`:""}.`,priceRange:"$$",...f.length&&{sameAs:f},...s.brokerageLegalName&&{worksFor:{"@type":"RealEstateAgent",name:s.brokerageLegalName,...s.brokerageLicenseNumber&&{identifier:s.brokerageLicenseNumber}}},...s.agentLicenseNumber&&{identifier:s.agentLicenseNumber},...o&&{address:{"@type":"PostalAddress",addressLocality:o,...c&&{addressRegion:c},addressCountry:"US"}},...i.length&&{areaServed:i.map(S=>{const[A,E]=S.split(/,\s*/);return{"@type":"City",name:A,...E&&{containedInPlace:{"@type":"State",name:E}}}})},...p&&{aggregateRating:p},...h.length&&{review:h.slice(0,10).map(S=>({"@type":"Review",author:{"@type":"Person",name:S.name},reviewBody:S.text,reviewRating:{"@type":"Rating",ratingValue:S.rating||5,bestRating:5,worstRating:1},...S.location&&{locationCreated:{"@type":"Place",name:S.location}}}))}},_={"@context":"https://schema.org","@type":"Person","@id":`${r}/#person`,name:n.full_name,jobTitle:n.title||"Real Estate Agent",description:n.bio||void 0,image:n.avatar_url||void 0,url:r,email:n.email,telephone:n.phone||void 0,...f.length&&{sameAs:f},...n.years_experience&&{knowsAbout:["Residential Real Estate","Home Buying","Home Selling",l?`${l} Real Estate`:"Local Real Estate"].filter(Boolean)},...u.length&&{hasCredential:u.map(S=>({"@type":"EducationalOccupationalCredential",credentialCategory:"designation",name:S}))},...s.brokerageLegalName&&{worksFor:{"@type":"Organization",name:s.brokerageLegalName}}},v={"@context":"https://schema.org","@type":"WebSite","@id":`${r}/#website`,name:s.siteTitle||`${n.full_name} Real Estate`,url:r,publisher:{"@id":`${r}/#agent`},potentialAction:{"@type":"SearchAction",target:{"@type":"EntryPoint",urlTemplate:`${r}/search?q={search_term_string}`},"query-input":"required name=search_term_string"}},j=[{name:"Search Homes",description:`Browse all current MLS listings${l?` in ${l}`:""}.`,path:"/search"},{name:"Featured Areas",description:"Explore featured neighborhoods, cities, and communities.",path:"/areas"},{name:"Sold Properties",description:"See recently sold homes and local market activity.",path:"/sold"},{name:"Home Valuation",description:"Get a free, no-obligation estimate of what your home is worth.",path:"/sell"},{name:"About",description:`Learn more about ${n.full_name}${s.brokerageLegalName?` and ${s.brokerageLegalName}`:""}.`,path:"/about"},{name:"Contact",description:`Get in touch with ${n.full_name} for buying, selling, or relocation help.`,path:"/contact"}],w={"@context":"https://schema.org","@type":"ItemList","@id":`${r}/#nav`,name:"Main Navigation",itemListElement:j.map((S,A)=>({"@type":"SiteNavigationElement",position:A+1,name:S.name,description:S.description,url:`${r}${S.path}`}))};return e.jsxs(Zo,{children:[e.jsx("script",{type:"application/ld+json",children:JSON.stringify(y)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(_)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(v)}),e.jsx("script",{type:"application/ld+json",children:JSON.stringify(w)})]})}function Yfn({items:s,siteConfig:t}){const n=`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"BreadcrumbList",itemListElement:s.map((a,i)=>({"@type":"ListItem",position:i+1,name:a.name,item:`${n}${a.path}`}))};return e.jsx(Zo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function Zfn({listing:s,siteConfig:t}){var a;const n=`https://${t.subdomainSlug}.thelocalmove.com`,r={"@context":"https://schema.org","@type":"SingleFamilyResidence",name:`${s.address}, ${s.city}, ${s.state} ${s.zip}`,url:`${n}/listing/${s.mlsNumber}`,image:((a=s.photos)==null?void 0:a[0])||void 0,numberOfRooms:s.bedrooms,numberOfBathroomsTotal:s.bathrooms,floorSize:s.sqft?{"@type":"QuantitativeValue",value:s.sqft,unitCode:"FTK"}:void 0,address:{"@type":"PostalAddress",streetAddress:s.address,addressLocality:s.city,addressRegion:s.state,postalCode:s.zip},...s.latitude&&s.longitude&&{geo:{"@type":"GeoCoordinates",latitude:s.latitude,longitude:s.longitude}},offers:{"@type":"Offer",price:s.price,priceCurrency:"USD",availability:s.status==="Active"?"https://schema.org/InStock":"https://schema.org/SoldOut"},...s.yearBuilt&&{yearBuilt:s.yearBuilt}};return e.jsx(Zo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(r)})})}function onn({faqs:s}){if(!s.length)return null;const t={"@context":"https://schema.org","@type":"FAQPage",mainEntity:s.map(n=>({"@type":"Question",name:n.question,acceptedAnswer:{"@type":"Answer",text:n.answer}}))};return e.jsx(Zo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(t)})})}function Qfn({title:s,description:t,publishedAt:n,imageUrl:r,slug:a,siteConfig:i}){const l=`https://${i.subdomainSlug}.thelocalmove.com`,o=i.agent,c={"@context":"https://schema.org","@type":"Article",headline:s,description:t,url:`${l}/blog/${a}`,datePublished:n,...r&&{image:r},author:o?{"@type":"Person",name:o.full_name,url:l}:void 0,publisher:{"@type":"Organization",name:i.siteTitle||(o==null?void 0:o.full_name)||"Agent",url:l}};return e.jsx(Zo,{children:e.jsx("script",{type:"application/ld+json",children:JSON.stringify(c)})})}function c8e({siteConfig:s}){var f;const t=s.agent;if(!t)return null;const n=t.full_name,r=s.brokerageLegalName||"their brokerage",a=t.areas_served||"the local market",i=((f=a.split(/,|;|\|/)[0])==null?void 0:f.trim())||"the local area",l=t.years_experience,o=t.phone||"",c=t.email,d=s.agentLicenseNumber,u=(t.bio||"").match(/\b(CRS|GRI|ABR|CNE|SRES|SRS|RENE|MRP|PSA|AHWD|C2EX|CIPS|CRB|e-?PRO)\b/gi)||[],h=[...new Set(u.map(y=>y.toUpperCase()))],p=[{question:`Who is ${n}?`,answer:`${n} is a ${t.title||"REALTOR®"} with ${r}${l?`, with ${l}+ years of local real estate experience`:""} serving ${a}. ${t.bio?t.bio.slice(0,280):""}`.trim()},{question:`What areas does ${n} serve?`,answer:`${n} serves ${a} and surrounding communities. Whether you're buying, selling, relocating, or downsizing, ${n.split(" ")[0]} provides expert local guidance.`},{question:`How can I contact ${n}?`,answer:`You can reach ${n} by ${o?`phone at ${o}, `:""}email at ${c}, or by booking a consultation directly through this website.`},...h.length?[{question:`What real estate designations does ${n} hold?`,answer:`${n} holds the following professional designations: ${h.join(", ")}. These designations represent advanced training in specialized areas of real estate.`}]:[],...d?[{question:`Is ${n} a licensed real estate agent?`,answer:`Yes, ${n} is a fully licensed real estate professional (License #${d}) with ${r}.`}]:[],{question:`How do I search for homes for sale in ${i}?`,answer:`Use the property search on this site to view all current MLS listings in ${i}. You can filter by price, bedrooms, neighborhood, school district, and more. Save searches to receive instant email alerts when new homes match your criteria.`},{question:`What is the home buying process like in ${i}?`,answer:`${n} guides buyers through every step: getting pre-approved, searching MLS listings, touring homes, writing competitive offers, navigating inspections and appraisals, and closing on schedule. Contact ${n.split(" ")[0]} for a free buyer consultation.`},{question:`How do I find out what my home is worth in ${i}?`,answer:`Request a free, no-obligation home valuation from ${n}. ${n.split(" ")[0]} provides a comparative market analysis (CMA) using recent sold comps and current market conditions in ${i}.`}];return e.jsx(onn,{faqs:p})}const CXe="ls_visitor_geo",lnn=1e3*60*60,INe="lu_lc_attrib_v1",cnn=1e3*60*60*24*90;function dnn(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 unn(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"sell":return"Sell Your Home";case"blog":return"Blog";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"dashboard":return"My Dashboard";default:return s}}async function hnn(){try{const s=localStorage.getItem(CXe);if(s){const t=JSON.parse(s);if(Date.now()-t.ts{i.current||(i.current=!0,hnn().then(l=>{a.current=l}))},[]),N.useEffect(()=>{if(!(s!=null&&s.id))return;const l=n.pathname;if(l===r.current)return;r.current=l;const o=dnn(l),c=unn(l,o),d=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,u=a.current;(async()=>{const p=new URLSearchParams(n.search),f=p.get("luc");if(f&&/^[0-9a-f-]{36}$/i.test(f)){try{localStorage.setItem(INe,JSON.stringify({contact_id:f,ts:Date.now()}))}catch{}return f}const y=p.get("lc");if(y&&/^[0-9a-f-]{36}$/i.test(y)){const{data:_}=await q.from("listing_email_recipients").select("contact_id").eq("id",y).maybeSingle(),v=_==null?void 0:_.contact_id;if(v){try{localStorage.setItem(INe,JSON.stringify({contact_id:v,ts:Date.now()}))}catch{}return v}}try{const _=localStorage.getItem(INe);if(_){const v=JSON.parse(_);if(v!=null&&v.contact_id&&Date.now()-(v.ts||0){q.from("lead_site_page_views").insert({lead_site_id:s.id,page_type:o,page_path:l,page_title:c,visitor_fingerprint:d,auth_user_id:t||null,contact_id:p,visitor_city:(u==null?void 0:u.city)||null,visitor_region:(u==null?void 0:u.region)||null,visitor_country:(u==null?void 0:u.country)||null,visitor_lat:(u==null?void 0:u.lat)||null,visitor_lng:(u==null?void 0:u.lng)||null}).then(({error:f})=>{f&&console.error("[PageTracking] insert failed:",f.message)})})},[n.pathname,n.search,s==null?void 0:s.id,t])}const mnn=3e4;function u8e(s,t){const n=Xl(),r=N.useRef(null),a=N.useRef(null),i=N.useRef(0),l=n.pathname,o=pnn(l),c=fnn(l,o),d=o==="listing"&&l.split("/listing/")[1]||null;N.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;o==="listing"&&(i.current+=1);const u=localStorage.getItem(`ls_visitor_fp_${s.id}`)||null,h=async()=>{const{data:p,error:f}=await q.from("lead_site_active_visitors").upsert({lead_site_id:s.id,auth_user_id:t,visitor_fingerprint:u,current_page_path:l,current_page_title:c,current_mls_number:d,last_seen_at:new Date().toISOString(),listing_views_count:i.current},{onConflict:"lead_site_id,coalesce(auth_user_id::text,visitor_fingerprint,'')"}).select("id, notified_agent").single();!f&&p&&(r.current=p.id,i.current>=2&&!p.notified_agent&&q.functions.invoke("lead-site-presence-notify",{body:{visitor_id:p.id,lead_site_id:s.id}}).catch(()=>{}))};return h(),a.current&&clearInterval(a.current),a.current=setInterval(h,mnn),()=>{a.current&&clearInterval(a.current)}},[s==null?void 0:s.id,t,l]),N.useEffect(()=>{if(!(s!=null&&s.id)||!t)return;const u=()=>{r.current&&q.from("lead_site_active_visitors").delete().eq("id",r.current).then(()=>{})};return window.addEventListener("beforeunload",u),()=>window.removeEventListener("beforeunload",u)},[s==null?void 0:s.id,t])}function pnn(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 fnn(s,t){switch(t){case"home":return"Home";case"search":return"Search";case"listing":return`Listing ${s.split("/listing/")[1]||""}`;case"city":return s.replace("/homes-for-sale-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");case"subdivision":return s.replace("/homes-in-","").split("-").map(r=>r.charAt(0).toUpperCase()+r.slice(1)).join(" ");default:return s}}const Pa=Number.isFinite||function(s){return typeof s=="number"&&isFinite(s)},xnn=Number.isSafeInteger||function(s){return typeof s=="number"&&Math.abs(s)<=gnn},gnn=Number.MAX_SAFE_INTEGER||9007199254740991;let ui=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}({}),Mn=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}({}),jt=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 rl={MANIFEST:"manifest",LEVEL:"level",AUDIO_TRACK:"audioTrack",SUBTITLE_TRACK:"subtitleTrack"},Wa={MAIN:"main",AUDIO:"audio",SUBTITLE:"subtitle"};class FI{constructor(t,n=0,r=0){this.halfLife=void 0,this.alpha_=void 0,this.estimate_=void 0,this.totalWeight_=void 0,this.halfLife=t,this.alpha_=t?Math.exp(Math.log(.5)/t):0,this.estimate_=n,this.totalWeight_=r}sample(t,n){const r=Math.pow(this.alpha_,t);this.estimate_=n*(1-r)+r*this.estimate_,this.totalWeight_+=t}getTotalWeight(){return this.totalWeight_}getEstimate(){if(this.alpha_){const t=1-Math.pow(this.alpha_,this.totalWeight_);if(t)return this.estimate_/t}return this.estimate_}}class ynn{constructor(t,n,r,a=100){this.defaultEstimate_=void 0,this.minWeight_=void 0,this.minDelayMs_=void 0,this.slow_=void 0,this.fast_=void 0,this.defaultTTFB_=void 0,this.ttfb_=void 0,this.defaultEstimate_=r,this.minWeight_=.001,this.minDelayMs_=50,this.slow_=new FI(t),this.fast_=new FI(n),this.defaultTTFB_=a,this.ttfb_=new FI(t)}update(t,n){const{slow_:r,fast_:a,ttfb_:i}=this;r.halfLife!==t&&(this.slow_=new FI(t,r.getEstimate(),r.getTotalWeight())),a.halfLife!==n&&(this.fast_=new FI(n,a.getEstimate(),a.getTotalWeight())),i.halfLife!==t&&(this.ttfb_=new FI(t,i.getEstimate(),i.getTotalWeight()))}sample(t,n){t=Math.max(t,this.minDelayMs_);const r=8*n,a=t/1e3,i=r/a;this.fast_.sample(a,i),this.slow_.sample(a,i)}sampleTTFB(t){const n=t/1e3,r=Math.sqrt(2)*Math.exp(-Math.pow(n,2)/2);this.ttfb_.sample(r,Math.max(t,5))}canEstimate(){return this.fast_.getTotalWeight()>=this.minWeight_}getEstimate(){return this.canEstimate()?Math.min(this.fast_.getEstimate(),this.slow_.getEstimate()):this.defaultEstimate_}getEstimateTTFB(){return this.ttfb_.getTotalWeight()>=this.minWeight_?this.ttfb_.getEstimate():this.defaultTTFB_}get defaultEstimate(){return this.defaultEstimate_}destroy(){}}function vnn(s,t,n){return(t=_nn(t))in s?Object.defineProperty(s,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):s[t]=n,s}function Wc(){return Wc=Object.assign?Object.assign.bind():function(s){for(var t=1;t`):Jk}function EXe(s,t,n){return t[s]?t[s].bind(t):jnn(s,n)}const hTe=uTe();function Nnn(s,t,n){const r=uTe();if(typeof console=="object"&&s===!0||typeof s=="object"){const a=["debug","log","info","warn","error"];a.forEach(i=>{r[i]=EXe(i,s,n)});try{r.log(`Debug logs enabled for "${t}" in hls.js version 1.6.16`)}catch{return uTe()}a.forEach(i=>{hTe[i]=EXe(i,s)})}else Wc(hTe,r);return r}const Cc=hTe;function I4(s=!0){return typeof self>"u"?void 0:(s||!self.MediaSource)&&self.ManagedMediaSource||self.MediaSource||self.WebKitMediaSource}function knn(s){return typeof self<"u"&&s===self.ManagedMediaSource}function lNt(s,t){const n=Object.keys(s),r=Object.keys(t),a=n.length,i=r.length;return!a||!i||a===i&&!n.some(l=>r.indexOf(l)===-1)}function fy(s,t=!1){if(typeof TextDecoder<"u"){const d=new TextDecoder("utf-8").decode(s);if(t){const u=d.indexOf("\0");return u!==-1?d.substring(0,u):d}return d.replace(/\0/g,"")}const n=s.length;let r,a,i,l="",o=0;for(;o>4){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:l+=String.fromCharCode(r);break;case 12:case 13:a=s[o++],l+=String.fromCharCode((r&31)<<6|a&63);break;case 14:a=s[o++],i=s[o++],l+=String.fromCharCode((r&15)<<12|(a&63)<<6|(i&63)<<0);break}}return l}function tf(s){let t="";for(let n=0;n1||a===1&&(n=this.levelkeys[r[0]])!=null&&n.encrypted)return!0}return!1}get programDateTime(){return this._programDateTime===null&&this.rawProgramDateTime&&(this.programDateTime=Date.parse(this.rawProgramDateTime)),this._programDateTime}set programDateTime(t){if(!Pa(t)){this._programDateTime=this.rawProgramDateTime=null;return}this._programDateTime=t}get ref(){return Nh(this)?(this._ref||(this._ref={base:this.base,start:this.start,duration:this.duration,sn:this.sn,programDateTime:this.programDateTime}),this._ref):null}addStart(t){this.setStart(this.start+t)}setStart(t){this.start=t,this._ref&&(this._ref.start=t)}setDuration(t){this.duration=t,this._ref&&(this._ref.duration=t)}setKeyFormat(t){const n=this.levelkeys;if(n){var r;const a=n[t];a&&!((r=this._decryptdata)!=null&&r.keyId)&&(this._decryptdata=a.getDecryptData(this.sn,n))}}abortRequests(){var t,n;(t=this.loader)==null||t.abort(),(n=this.keyLoader)==null||n.abort()}setElementaryStreamInfo(t,n,r,a,i,l=!1){const{elementaryStreams:o}=this,c=o[t];if(!c){o[t]={startPTS:n,endPTS:r,startDTS:a,endDTS:i,partial:l};return}c.startPTS=Math.min(c.startPTS,n),c.endPTS=Math.max(c.endPTS,r),c.startDTS=Math.min(c.startDTS,a),c.endDTS=Math.max(c.endDTS,i)}}class Tnn extends dNt{constructor(t,n,r,a,i){super(r),this.fragOffset=0,this.duration=0,this.gap=!1,this.independent=!1,this.relurl=void 0,this.fragment=void 0,this.index=void 0,this.duration=t.decimalFloatingPoint("DURATION"),this.gap=t.bool("GAP"),this.independent=t.bool("INDEPENDENT"),this.relurl=t.enumeratedString("URI"),this.fragment=n,this.index=a;const l=t.enumeratedString("BYTERANGE");l&&this.setByteRange(l,i),i&&(this.fragOffset=i.fragOffset+i.duration)}get start(){return this.fragment.start+this.fragOffset}get end(){return this.start+this.duration}get loaded(){const{elementaryStreams:t}=this;return!!(t.audio||t.video||t.audiovideo)}}function uNt(s,t){const n=Object.getPrototypeOf(s);if(n){const r=Object.getOwnPropertyDescriptor(n,t);return r||uNt(n,t)}}function Enn(s,t){const n=uNt(s,t);n&&(n.enumerable=!0,Object.defineProperty(s,t,n))}const MXe=Math.pow(2,32)-1,Ann=[].push,hNt={video:1,audio:2,id3:3,text:4};function Tm(s){return String.fromCharCode.apply(null,s)}function mNt(s,t){const n=s[t]<<8|s[t+1];return n<0?65536+n:n}function uo(s,t){const n=pNt(s,t);return n<0?4294967296+n:n}function IXe(s,t){let n=uo(s,t);return n*=Math.pow(2,32),n+=uo(s,t+4),n}function pNt(s,t){return s[t]<<24|s[t+1]<<16|s[t+2]<<8|s[t+3]}function Mnn(s){const t=s.byteLength;for(let n=0;n8&&s[n+4]===109&&s[n+5]===111&&s[n+6]===111&&s[n+7]===102)return!0;n=r>1?n+r:t}return!1}function Qo(s,t){const n=[];if(!t.length)return n;const r=s.byteLength;for(let a=0;a1?a+i:r;if(l===t[0])if(t.length===1)n.push(s.subarray(a+8,o));else{const c=Qo(s.subarray(a+8,o),t.slice(1));c.length&&Ann.apply(n,c)}a=o}return n}function Inn(s){const t=[],n=s[0];let r=8;const a=uo(s,r);r+=4;let i=0,l=0;n===0?(i=uo(s,r),l=uo(s,r+4),r+=8):(i=IXe(s,r),l=IXe(s,r+8),r+=16),r+=2;let o=s.length+l;const c=mNt(s,r);r+=2;for(let d=0;d>>31===1)return Cc.warn("SIDX has hierarchical references (not supported)"),null;const y=uo(s,u);u+=4,t.push({referenceSize:p,subsegmentDuration:y,info:{duration:y/a,start:o,end:o+p-1}}),o+=p,u+=4,r=u}return{earliestPresentationTime:i,timescale:a,version:n,referencesCount:c,references:t}}function fNt(s){const t=[],n=Qo(s,["moov","trak"]);for(let a=0;a{const i=uo(a,4),l=t[i];l&&(l.default={duration:uo(a,12),flags:uo(a,20)})}),t}function Pnn(s){const t=s.subarray(8),n=t.subarray(86),r=Tm(t.subarray(4,8));let a=r,i;const l=r==="enca"||r==="encv";if(l){const d=Qo(t,[r])[0].subarray(r==="enca"?28:78);Qo(d,["sinf"]).forEach(h=>{const p=Qo(h,["schm"])[0];if(p){const f=Tm(p.subarray(4,8));if(f==="cbcs"||f==="cenc"){const y=Qo(h,["frma"])[0];y&&(a=Tm(y))}}})}const o=a;switch(a){case"avc1":case"avc2":case"avc3":case"avc4":{const c=Qo(n,["avcC"])[0];c&&c.length>3&&(a+="."+kG(c[1])+kG(c[2])+kG(c[3]),i=NG(o==="avc1"?"dva1":"dvav",n));break}case"mp4a":{const c=Qo(t,[r])[0],d=Qo(c.subarray(28),["esds"])[0];if(d&&d.length>7){let u=4;if(d[u++]!==3)break;u=DNe(d,u),u+=2;const h=d[u++];if(h&128&&(u+=2),h&64&&(u+=d[u++]),d[u++]!==4)break;u=DNe(d,u);const p=d[u++];if(p===64)a+="."+kG(p);else break;if(u+=12,d[u++]!==5)break;u=DNe(d,u);const f=d[u++];let y=(f&248)>>3;y===31&&(y+=1+((f&7)<<3)+((d[u]&224)>>5)),a+="."+y}break}case"hvc1":case"hev1":{const c=Qo(n,["hvcC"])[0];if(c&&c.length>12){const d=c[1],u=["","A","B","C"][d>>6],h=d&31,p=uo(c,2),f=(d&32)>>5?"H":"L",y=c[12],_=c.subarray(6,12);a+="."+u+h,a+="."+Lnn(p).toString(16).toUpperCase(),a+="."+f+y;let v="";for(let j=_.length;j--;){const w=_[j];(w||v)&&(v="."+w.toString(16).toUpperCase()+v)}a+=v}i=NG(o=="hev1"?"dvhe":"dvh1",n);break}case"dvh1":case"dvhe":case"dvav":case"dva1":case"dav1":{a=NG(a,n)||a;break}case"vp09":{const c=Qo(n,["vpcC"])[0];if(c&&c.length>6){const d=c[4],u=c[5],h=c[6]>>4&15;a+="."+z_(d)+"."+z_(u)+"."+z_(h)}break}case"av01":{const c=Qo(n,["av1C"])[0];if(c&&c.length>2){const d=c[1]>>>5,u=c[1]&31,h=c[2]>>>7?"H":"M",p=(c[2]&64)>>6,f=(c[2]&32)>>5,y=d===2&&p?f?12:10:p?10:8,_=(c[2]&16)>>4,v=(c[2]&8)>>3,j=(c[2]&4)>>2,w=c[2]&3;a+="."+d+"."+z_(u)+h+"."+z_(y)+"."+_+"."+v+j+w+"."+z_(1)+"."+z_(1)+"."+z_(1)+"."+0,i=NG("dav1",n)}break}}return{codec:a,encrypted:l,supplemental:i}}function NG(s,t){const n=Qo(t,["dvvC"]),r=n.length?n[0]:Qo(t,["dvcC"])[0];if(r){const a=r[2]>>1&127,i=r[2]<<5&32|r[3]>>3&31;return s+"."+z_(a)+"."+z_(i)}}function Lnn(s){let t=0;for(let n=0;n<32;n++)t|=(s>>n&1)<<31-n;return t>>>0}function DNe(s,t){const n=t+5;for(;s[t++]&128&&t{const i=r.subarray(8,24);i.some(l=>l!==0)||(Cc.log(`[eme] Patching keyId in 'enc${a?"a":"v"}>sinf>>tenc' box: ${tf(i)} -> ${tf(n)}`),r.set(n,8))})}function Rnn(s){const t=[];return xNt(s,n=>t.push(n.subarray(8,24))),t}function xNt(s,t){Qo(s,["moov","trak"]).forEach(r=>{const a=Qo(r,["mdia","minf","stbl","stsd"])[0];if(!a)return;const i=a.subarray(8);let l=Qo(i,["enca"]);const o=l.length>0;o||(l=Qo(i,["encv"])),l.forEach(c=>{const d=o?c.subarray(28):c.subarray(78);Qo(d,["sinf"]).forEach(h=>{const p=gNt(h);p&&t(p,o)})})})}function gNt(s){const t=Qo(s,["schm"])[0];if(t){const n=Tm(t.subarray(4,8));if(n==="cbcs"||n==="cenc"){const r=Qo(s,["schi","tenc"])[0];if(r)return r}}}function Onn(s,t,n){const r={},a=Qo(s,["moof","traf"]);for(let i=0;ir[i].duration)){let i=1/0,l=0;const o=Qo(s,["sidx"]);for(let c=0;ch+p.info.duration||0,0);l=Math.max(l,u+d.earliestPresentationTime/d.timescale)}}l&&Pa(l)&&Object.keys(r).forEach(c=>{r[c].duration||(r[c].duration=l*r[c].timescale-r[c].start)})}return r}function Fnn(s){const t={valid:null,remainder:null},n=Qo(s,["moof"]);if(n.length<2)return t.remainder=s,t;const r=n[n.length-1];return t.valid=s.slice(0,r.byteOffset-8),t.remainder=s.slice(r.byteOffset-8),t}function Gv(s,t){const n=new Uint8Array(s.length+t.length);return n.set(s),n.set(t,s.length),n}function PXe(s,t){const n=[],r=t.samples,a=t.timescale,i=t.id;let l=!1;return Qo(r,["moof"]).map(c=>{const d=c.byteOffset-8;Qo(c,["traf"]).map(h=>{const p=Qo(h,["tfdt"]).map(f=>{const y=f[0];let _=uo(f,4);return y===1&&(_*=Math.pow(2,32),_+=uo(f,8)),_/a})[0];return p!==void 0&&(s=p),Qo(h,["tfhd"]).map(f=>{const y=uo(f,4),_=uo(f,0)&16777215,v=(_&1)!==0,j=(_&2)!==0,w=(_&8)!==0;let S=0;const A=(_&16)!==0;let E=0;const O=(_&32)!==0;let D=8;y===i&&(v&&(D+=8),j&&(D+=4),w&&(S=uo(f,D),D+=4),A&&(E=uo(f,D),D+=4),O&&(D+=4),t.type==="video"&&(l=H1e(t.codec)),Qo(h,["trun"]).map(I=>{const F=I[0],z=uo(I,0)&16777215,H=(z&1)!==0;let Z=0;const Y=(z&4)!==0,W=(z&256)!==0;let ee=0;const se=(z&512)!==0;let oe=0;const he=(z&1024)!==0,ce=(z&2048)!==0;let me=0;const le=uo(I,4);let ve=8;H&&(Z=uo(I,ve),ve+=4),Y&&(ve+=4);let ge=Z+d;for(let Te=0;Te>1&63;return n===39||n===40}else return(t&31)===6}function p8e(s,t,n,r){const a=yNt(s);let i=0;i+=t;let l=0,o=0,c=0;for(;i=a.length)break;c=a[i++],l+=c}while(c===255);o=0;do{if(i>=a.length)break;c=a[i++],o+=c}while(c===255);const d=a.length-i;let u=i;if(od){Cc.error(`Malformed SEI payload. ${o} is too small, only ${d} bytes left to parse.`);break}if(l===4){if(a[u++]===181){const p=mNt(a,u);if(u+=2,p===49){const f=uo(a,u);if(u+=4,f===1195456820){const y=a[u++];if(y===3){const _=a[u++],v=31&_,j=64&_,w=j?2+v*3:0,S=new Uint8Array(w);if(j){S[0]=_;for(let A=1;A16){const h=[];for(let y=0;y<16;y++){const _=a[u++].toString(16);h.push(_.length==1?"0"+_:_),(y===3||y===5||y===7||y===9)&&h.push("-")}const p=o-16,f=new Uint8Array(p);for(let y=0;y>24&255,i[1]=r>>16&255,i[2]=r>>8&255,i[3]=r&255,i.set(s,4),a=0,r=8;a0?(i=new Uint8Array(4),t.length>0&&new DataView(i.buffer).setUint32(0,t.length,!1)):i=new Uint8Array;const l=new Uint8Array(4);return n.byteLength>0&&new DataView(l.buffer).setUint32(0,n.byteLength,!1),$nn([112,115,115,104],new Uint8Array([r,0,0,0]),s,i,a,l,n)}function qnn(s){const t=[];if(s instanceof ArrayBuffer){const n=s.byteLength;let r=0;for(;r+32>>24;if(i!==0&&i!==1)return{offset:n,size:t};const l=s.buffer,o=tf(new Uint8Array(l,n+12,16));let c=null,d=null,u=0;if(i===0)u=28;else{const p=s.getUint32(28);if(!p||r<32+p*16)return{offset:n,size:t};c=[];for(let f=0;f/\(Windows.+Firefox\//i.test(navigator.userAgent),mD={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 f8e(s,t){const n=mD[t];return!!n&&!!n[s.slice(0,4)]}function h$(s,t,n=!0){return!s.split(",").some(r=>!x8e(r,t,n))}function x8e(s,t,n=!0){var r;const a=I4(n);return(r=a==null?void 0:a.isTypeSupported(m$(s,t)))!=null?r:!1}function m$(s,t){return`${t}/mp4;codecs=${s}`}function LXe(s){if(s){const t=s.substring(0,4);return mD.video[t]}return 2}function Dge(s){const t=vNt();return s.split(",").reduce((n,r)=>{const i=t&&H1e(r)?9:mD.video[r];return i?(i*2+n)/(n?3:2):(mD.audio[r]+n)/(n?2:1)},0)}const RNe={};function Hnn(s,t=!0){if(RNe[s])return RNe[s];const n={flac:["flac","fLaC","FLAC"],opus:["opus","Opus"],"mp4a.40.34":["mp3"]}[s];for(let a=0;aHnn(n.toLowerCase(),t))}function Wnn(s,t){const n=[];if(s){const r=s.split(",");for(let a=0;a4||["ac-3","ec-3","alac","fLaC","Opus"].indexOf(s)!==-1)&&(DXe(s,"audio")||DXe(s,"video")))return s;if(t){const n=t.split(",");if(n.length>1){if(s){for(let r=n.length;r--;)if(n[r].substring(0,4)===s.substring(0,4))return n[r]}return n[0]}}return t||s}function DXe(s,t){return f8e(s,t)&&x8e(s,t)}function Knn(s){const t=s.split(",");for(let n=0;n2&&r[0]==="avc1"&&(t[n]=`avc1.${parseInt(r[1]).toString(16)}${("000"+parseInt(r[2]).toString(16)).slice(-4)}`)}return t.join(",")}function Ynn(s){if(s.startsWith("av01.")){const t=s.split("."),n=["0","111","01","01","01","0"];for(let r=t.length;r>4&&r<10;r++)t[r]=n[r-4];return t.join(".")}return s}function RXe(s){const t=I4(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 mTe(s){return s.replace(/^.+codecs=["']?([^"']+).*$/,"$1")}const Znn={supported:!0,powerEfficient:!0,smooth:!0},Qnn={supported:!1,smooth:!1,powerEfficient:!1},bNt={supported:!0,configurations:[],decodingInfoResults:[Znn]};function _Nt(s,t){return{supported:!1,configurations:t,decodingInfoResults:[Qnn],error:s}}function Xnn(s,t,n,r,a,i){const l=s.videoCodec,o=s.audioCodec?s.audioGroups:null,c=i==null?void 0:i.audioCodec,d=i==null?void 0:i.channels,u=d?parseInt(d):c?1/0:2;let h=null;if(o!=null&&o.length)try{o.length===1&&o[0]?h=t.groups[o[0]].channels:h=o.reduce((p,f)=>{if(f){const y=t.groups[f];if(!y)throw new Error(`Audio track group ${f} not found`);Object.keys(y.channels).forEach(_=>{p[_]=(p[_]||0)+y.channels[_]})}return p},{2:0})}catch{return!0}return l!==void 0&&(l.split(",").some(p=>H1e(p))||s.width>1920&&s.height>1088||s.height>1920&&s.width>1088||s.frameRate>Math.max(r,30)||s.videoRange!=="SDR"&&s.videoRange!==n||s.bitrate>Math.max(a,8e6))||!!h&&Pa(u)&&Object.keys(h).some(p=>parseInt(p)>u)}function wNt(s,t,n,r={}){const a=s.videoCodec;if(!a&&!s.audioCodec||!n)return Promise.resolve(bNt);const i=[],l=Jnn(s),o=l.length,c=ern(s,t,o>0),d=c.length;for(let u=o||1*d||1;u--;){const h={type:"media-source"};if(o&&(h.video=l[u%o]),d){h.audio=c[u%d];const p=h.audio.bitrate;h.video&&p&&(h.video.bitrate-=p)}i.push(h)}if(a){const u=navigator.userAgent;if(a.split(",").some(h=>H1e(h))&&vNt())return Promise.resolve(_Nt(new Error(`Overriding Windows Firefox HEVC MediaCapabilities result based on user-agent string: (${u})`),i))}return Promise.all(i.map(u=>{const h=srn(u);return r[h]||(r[h]=n.decodingInfo(u))})).then(u=>({supported:!u.some(h=>!h.supported),configurations:i,decodingInfoResults:u})).catch(u=>({supported:!1,configurations:i,decodingInfoResults:[],error:u}))}function Jnn(s){var t;const n=(t=s.videoCodec)==null?void 0:t.split(","),r=jNt(s),a=s.width||640,i=s.height||480,l=s.frameRate||30,o=s.videoRange.toLowerCase();return n?n.map(c=>{const d={contentType:m$(Ynn(c),"video"),width:a,height:i,bitrate:r,framerate:l};return o!=="sdr"&&(d.transferFunction=o),d}):[]}function ern(s,t,n){var r;const a=(r=s.audioCodec)==null?void 0:r.split(","),i=jNt(s);return a&&s.audioGroups?s.audioGroups.reduce((l,o)=>{var c;const d=o?(c=t.groups[o])==null?void 0:c.tracks:null;return d?d.reduce((u,h)=>{if(h.groupId===o){const p=parseFloat(h.channels||"");a.forEach(f=>{const y={contentType:m$(f,"audio"),bitrate:n?trn(f,i):i};p&&(y.channels=""+p),u.push(y)})}return u},l):l},[]):[]}function trn(s,t){if(t<=1)return 1;let n=128e3;return s==="ec-3"?n=768e3:s==="ac-3"&&(n=64e4),Math.min(t/2,n)}function jNt(s){return Math.ceil(Math.max(s.bitrate*.9,s.averageBitrate)/1e3)*1e3||1}function srn(s){let t="";const{audio:n,video:r}=s;if(r){const a=mTe(r.contentType);t+=`${a}_r${r.height}x${r.width}f${Math.ceil(r.framerate)}${r.transferFunction||"sd"}_${Math.ceil(r.bitrate/1e5)}`}if(n){const a=mTe(n.contentType);t+=`${r?"_":""}${a}_c${n.channels}`}return t}const pTe=["NONE","TYPE-0","TYPE-1",null];function nrn(s){return pTe.indexOf(s)>-1}const Oge=["SDR","PQ","HLG"];function rrn(s){return!!s&&Oge.indexOf(s)>-1}var Zme={No:"",Yes:"YES",v2:"v2"};function OXe(s){const{canSkipUntil:t,canSkipDateRanges:n,age:r}=s,a=r!!r).map(r=>r.substring(0,4)).join(","),"supplemental"in t){var n;this.supplemental=t.supplemental;const r=(n=t.supplemental)==null?void 0:n.videoCodec;r&&r!==t.videoCodec&&(this.codecSet+=`,${r.substring(0,4)}`)}this.addGroupId("audio",t.attrs.AUDIO),this.addGroupId("text",t.attrs.SUBTITLES)}get maxBitrate(){return Math.max(this.realBitrate,this.bitrate)}get averageBitrate(){return this._avgBitrate||this.realBitrate||this.bitrate}get attrs(){return this._attrs[0]}get codecs(){return this.attrs.CODECS||""}get pathwayId(){return this.attrs["PATHWAY-ID"]||"."}get videoRange(){return this.attrs["VIDEO-RANGE"]||"SDR"}get score(){return this.attrs.optionalFloat("SCORE",0)}get uri(){return this.url[0]||""}hasAudioGroup(t){return zXe(this._audioGroups,t)}hasSubtitleGroup(t){return zXe(this._subtitleGroups,t)}get audioGroups(){return this._audioGroups}get subtitleGroups(){return this._subtitleGroups}addGroupId(t,n){if(n){if(t==="audio"){let r=this._audioGroups;r||(r=this._audioGroups=[]),r.indexOf(n)===-1&&r.push(n)}else if(t==="text"){let r=this._subtitleGroups;r||(r=this._subtitleGroups=[]),r.indexOf(n)===-1&&r.push(n)}}}get urlId(){return 0}set urlId(t){}get audioGroupIds(){return this.audioGroups?[this.audioGroupId]:void 0}get textGroupIds(){return this.subtitleGroups?[this.textGroupId]:void 0}get audioGroupId(){var t;return(t=this.audioGroups)==null?void 0:t[0]}get textGroupId(){var t;return(t=this.subtitleGroups)==null?void 0:t[0]}addFallback(){}}function zXe(s,t){return!t||!s?!1:s.indexOf(t)!==-1}function arn(){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 irn(s,t){let n=!1,r=[];if(s&&(n=s!=="SDR",r=[s]),t){r=t.allowedVideoRanges||Oge.slice(0);const a=r.join("")!=="SDR"&&!t.videoCodec;n=t.preferHDR!==void 0?t.preferHDR:a&&arn(),n||(r=["SDR"])}return{preferHDR:n,allowedVideoRanges:r}}const orn=s=>{const t=new WeakSet;return(n,r)=>{if(s&&(r=s(n,r)),typeof r=="object"&&r!==null){if(t.has(r))return;t.add(r)}return r}},rd=(s,t)=>JSON.stringify(s,orn(t));function lrn(s,t,n,r,a){const i=Object.keys(s),l=r==null?void 0:r.channels,o=r==null?void 0:r.audioCodec,c=a==null?void 0:a.videoCodec,d=l&&parseInt(l)===2;let u=!1,h=!1,p=1/0,f=1/0,y=1/0,_=1/0,v=0,j=[];const{preferHDR:w,allowedVideoRanges:S}=irn(t,a);for(let I=i.length;I--;){const F=s[i[I]];u||(u=F.channels[2]>0),p=Math.min(p,F.minHeight),f=Math.min(f,F.minFramerate),y=Math.min(y,F.minBitrate),S.filter(H=>F.videoRanges[H]>0).length>0&&(h=!0)}p=Pa(p)?p:0,f=Pa(f)?f:0;const A=Math.max(1080,p),E=Math.max(30,f);y=Pa(y)?y:n,n=Math.max(y,n),h||(t=void 0);const O=i.length>1;return{codecSet:i.reduce((I,F)=>{const z=s[F];if(F===I)return I;if(j=h?S.filter(H=>z.videoRanges[H]>0):[],O){if(z.minBitrate>n)return C_(F,`min bitrate of ${z.minBitrate} > current estimate of ${n}`),I;if(!z.hasDefaultAudio)return C_(F,"no renditions with default or auto-select sound found"),I;if(o&&F.indexOf(o.substring(0,4))%5!==0)return C_(F,`audio codec preference "${o}" not found`),I;if(l&&!d){if(!z.channels[l])return C_(F,`no renditions with ${l} channel sound found (channels options: ${Object.keys(z.channels)})`),I}else if((!o||d)&&u&&z.channels[2]===0)return C_(F,"no renditions with stereo sound found"),I;if(z.minHeight>A)return C_(F,`min resolution of ${z.minHeight} > maximum of ${A}`),I;if(z.minFramerate>E)return C_(F,`min framerate of ${z.minFramerate} > maximum of ${E}`),I;if(!j.some(H=>z.videoRanges[H]>0))return C_(F,`no variants with VIDEO-RANGE of ${rd(j)} found`),I;if(c&&F.indexOf(c.substring(0,4))%5!==0)return C_(F,`video codec preference "${c}" not found`),I;if(z.maxScore=Dge(I)||z.fragmentError>s[I].fragmentError)?I:(_=z.minIndex,v=z.maxScore,F)},void 0),videoRanges:j,preferHDR:w,minFramerate:f,minBitrate:y,minIndex:_}}function C_(s,t){Cc.log(`[abr] start candidates with "${s}" ignored because ${t}`)}function NNt(s){return s.reduce((t,n)=>{let r=t.groups[n.groupId];r||(r=t.groups[n.groupId]={tracks:[],channels:{2:0},hasDefault:!1,hasAutoSelect:!1}),r.tracks.push(n);const a=n.channels||"2";return r.channels[a]=(r.channels[a]||0)+1,r.hasDefault=r.hasDefault||n.default,r.hasAutoSelect=r.hasAutoSelect||n.autoselect,r.hasDefault&&(t.hasDefaultAudio=!0),r.hasAutoSelect&&(t.hasAutoSelectAudio=!0),t},{hasDefaultAudio:!1,hasAutoSelectAudio:!1,groups:{}})}function crn(s,t,n,r){return s.slice(n,r+1).reduce((a,i,l)=>{if(!i.codecSet)return a;const o=i.audioGroups;let c=a[i.codecSet];c||(a[i.codecSet]=c={minBitrate:1/0,minHeight:1/0,minFramerate:1/0,minIndex:l,maxScore:0,videoRanges:{SDR:0},channels:{2:0},hasDefaultAudio:!o,fragmentError:0}),c.minBitrate=Math.min(c.minBitrate,i.bitrate);const d=Math.min(i.height,i.width);return c.minHeight=Math.min(c.minHeight,d),c.minFramerate=Math.min(c.minFramerate,i.frameRate),c.minIndex=Math.min(c.minIndex,l),c.maxScore=Math.max(c.maxScore,i.score),c.fragmentError+=i.fragmentError,c.videoRanges[i.videoRange]=(c.videoRanges[i.videoRange]||0)+1,o&&o.forEach(u=>{if(!u)return;const h=t.groups[u];h&&(c.hasDefaultAudio=c.hasDefaultAudio||t.hasDefaultAudio?h.hasDefault:h.hasAutoSelect||!t.hasDefaultAudio&&!t.hasAutoSelectAudio,Object.keys(h.channels).forEach(p=>{c.channels[p]=(c.channels[p]||0)+h.channels[p]}))}),a},{})}function BXe(s){if(!s)return s;const{lang:t,assocLang:n,characteristics:r,channels:a,audioCodec:i}=s;return{lang:t,assocLang:n,characteristics:r,channels:a,audioCodec:i}}function rw(s,t,n){if("attrs"in s){const r=t.indexOf(s);if(r!==-1)return r}for(let r=0;rr.indexOf(a)===-1)}function AE(s,t){const{audioCodec:n,channels:r}=s;return(n===void 0||(t.audioCodec||"").substring(0,4)===n.substring(0,4))&&(r===void 0||r===(t.channels||"2"))}function hrn(s,t,n,r,a){const i=t[r],o=t.reduce((p,f,y)=>{const _=f.uri;return(p[_]||(p[_]=[])).push(y),p},{})[i.uri];o.length>1&&(r=Math.max.apply(Math,o));const c=i.videoRange,d=i.frameRate,u=i.codecSet.substring(0,4),h=$Xe(t,r,p=>{if(p.videoRange!==c||p.frameRate!==d||p.codecSet.substring(0,4)!==u)return!1;const f=p.audioGroups,y=n.filter(_=>!f||f.indexOf(_.groupId)!==-1);return rw(s,y,a)>-1});return h>-1?h:$Xe(t,r,p=>{const f=p.audioGroups,y=n.filter(_=>!f||f.indexOf(_.groupId)!==-1);return rw(s,y,a)>-1})}function $Xe(s,t,n){for(let r=t;r>-1;r--)if(n(s[r]))return r;for(let r=t+1;r{var r;const{fragCurrent:a,partCurrent:i,hls:l}=this,{autoLevelEnabled:o,media:c}=l;if(!a||!c)return;const d=performance.now(),u=i?i.stats:a.stats,h=i?i.duration:a.duration,p=d-u.loading.start,f=l.minAutoLevel,y=a.level,_=this._nextAutoLevel;if(u.aborted||u.loaded&&u.loaded===u.total||y<=f){this.clearTimer(),this._nextAutoLevel=-1;return}if(!o)return;const v=_>-1&&_!==y,j=!!n||v;if(!j&&(c.paused||!c.playbackRate||!c.readyState))return;const w=l.mainForwardBufferInfo;if(!j&&w===null)return;const S=this.bwEstimator.getEstimateTTFB(),A=Math.abs(c.playbackRate);if(p<=Math.max(S,1e3*(h/(A*2))))return;const E=w?w.len/A:0,O=u.loading.first?u.loading.first-u.loading.start:-1,D=u.loaded&&O>-1,I=this.getBwEstimate(),F=l.levels,z=F[y],H=Math.max(u.loaded,Math.round(h*(a.bitrate||z.averageBitrate)/8));let Z=D?p-O:p;Z<1&&D&&(Z=Math.min(p,u.loaded*8/I));const Y=D?u.loaded*1e3/Z:0,W=S/1e3,ee=Y?(H-u.loaded)/Y:H*8/I+W;if(ee<=E)return;const se=Y?Y*8:I,oe=((r=(n==null?void 0:n.details)||this.hls.latestLevelDetails)==null?void 0:r.live)===!0,he=this.hls.config.abrBandWidthUpFactor;let ce=Number.POSITIVE_INFINITY,me;for(me=y-1;me>f;me--){const Te=F[me].maxBitrate,Ie=!F[me].details||oe;if(ce=this.getTimeToLoadFrag(W,se,h*Te,Ie),ce=ee||ce>h*10)return;D?this.bwEstimator.sample(p-Math.min(S,O),u.loaded):this.bwEstimator.sampleTTFB(p);const le=F[me].maxBitrate;this.getBwEstimate()*he>le&&this.resetEstimator(le);const ve=this.findBestLevel(le,f,me,0,E,1,1);ve>-1&&(me=ve),this.warn(`Fragment ${a.sn}${i?" part "+i.index:""} of level ${y} is loading too slowly; Fragment duration: ${a.duration.toFixed(3)} Time to underbuffer: ${E.toFixed(3)} s Estimated load time for current fragment: ${ee.toFixed(3)} s Estimated load time for down switch fragment: ${ce.toFixed(3)} s TTFB estimate: ${O|0} ms Current BW estimate: ${Pa(I)?I|0:"Unknown"} bps New BW estimate: ${this.getBwEstimate()|0} bps Switching to level ${me} @ ${le|0} bps`),l.nextLoadLevel=l.nextAutoLevel=me,this.clearTimer();const ge=()=>{if(this.clearTimer(),this.fragCurrent===a&&this.hls.loadLevel===me&&me>0){const Te=this.getStarvationDelay();if(this.warn(`Aborting inflight request ${me>0?"and switching down":""} Fragment duration: ${a.duration.toFixed(3)} s Time to underbuffer: ${Te.toFixed(3)} s`),a.abortRequests(),this.fragCurrent=this.partCurrent=null,me>f){let Ie=this.findBestLevel(this.hls.levels[f].bitrate,f,me,0,Te,1,1);Ie===-1&&(Ie=f),this.hls.nextLoadLevel=this.hls.nextAutoLevel=Ie,this.resetEstimator(this.hls.levels[Ie].bitrate)}}};v||ee>ce*2?ge():this.timer=self.setInterval(ge,ce*1e3),l.trigger(jt.FRAG_LOAD_EMERGENCY_ABORTED,{frag:a,part:i,stats:u})},this.hls=t,this.bwEstimator=this.initEstimator(),this.registerListeners()}resetEstimator(t){t&&(this.log(`setting initial bwe to ${t}`),this.hls.config.abrEwmaDefaultEstimate=t),this.firstSelection=-1,this.bwEstimator=this.initEstimator()}initEstimator(){const t=this.hls.config;return new ynn(t.abrEwmaSlowVoD,t.abrEwmaFastVoD,t.abrEwmaDefaultEstimate)}registerListeners(){const{hls:t}=this;t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.FRAG_LOADING,this.onFragLoading,this),t.on(jt.FRAG_LOADED,this.onFragLoaded,this),t.on(jt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(jt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(jt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(jt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.on(jt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t&&(t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.FRAG_LOADING,this.onFragLoading,this),t.off(jt.FRAG_LOADED,this.onFragLoaded,this),t.off(jt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(jt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(jt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(jt.MAX_AUTO_LEVEL_UPDATED,this.onMaxAutoLevelUpdated,this),t.off(jt.ERROR,this.onError,this))}destroy(){this.unregisterListeners(),this.clearTimer(),this.hls=this._abandonRulesCheck=this.supportedCache=null,this.fragCurrent=this.partCurrent=null}onManifestLoading(t,n){this.lastLoadedFragLevel=-1,this.firstSelection=-1,this.lastLevelLoadSec=0,this.supportedCache={},this.fragCurrent=this.partCurrent=null,this.onLevelsUpdated(),this.clearTimer()}onLevelsUpdated(){this.lastLoadedFragLevel>-1&&this.fragCurrent&&(this.lastLoadedFragLevel=this.fragCurrent.level),this._nextAutoLevel=-1,this.onMaxAutoLevelUpdated(),this.codecTiers=null,this.audioTracksByGroup=null}onMaxAutoLevelUpdated(){this.firstSelection=-1,this.nextAutoLevelKey=""}onFragLoading(t,n){const r=n.frag;if(!this.ignoreFragment(r)){if(!r.bitrateTest){var a;this.fragCurrent=r,this.partCurrent=(a=n.part)!=null?a:null}this.clearTimer(),this.timer=self.setInterval(this._abandonRulesCheck,100)}}onLevelSwitching(t,n){this.clearTimer()}onError(t,n){if(!n.fatal)switch(n.details){case Mn.BUFFER_ADD_CODEC_ERROR:case Mn.BUFFER_APPEND_ERROR:this.lastLoadedFragLevel=-1,this.firstSelection=-1;break;case Mn.FRAG_LOAD_TIMEOUT:{const r=n.frag,{fragCurrent:a,partCurrent:i}=this;if(r&&a&&r.sn===a.sn&&r.level===a.level){const l=performance.now(),o=i?i.stats:r.stats,c=l-o.loading.start,d=o.loading.first?o.loading.first-o.loading.start:-1;if(o.loaded&&d>-1){const h=this.bwEstimator.getEstimateTTFB();this.bwEstimator.sample(c-Math.min(h,d),o.loaded)}else this.bwEstimator.sampleTTFB(c)}break}}}getTimeToLoadFrag(t,n,r,a){const i=t+r/n,l=a?t+this.lastLevelLoadSec:0;return i+l}onLevelLoaded(t,n){const r=this.hls.config,{loading:a}=n.stats,i=a.end-a.first;Pa(i)&&(this.lastLevelLoadSec=i/1e3),n.details.live?this.bwEstimator.update(r.abrEwmaSlowLive,r.abrEwmaFastLive):this.bwEstimator.update(r.abrEwmaSlowVoD,r.abrEwmaFastVoD),this.timer>-1&&this._abandonRulesCheck(n.levelInfo)}onFragLoaded(t,{frag:n,part:r}){const a=r?r.stats:n.stats;if(n.type===Wa.MAIN&&this.bwEstimator.sampleTTFB(a.loading.first-a.loading.start),!this.ignoreFragment(n)){if(this.clearTimer(),n.level===this._nextAutoLevel&&(this._nextAutoLevel=-1),this.firstSelection=-1,this.hls.config.abrMaxWithRealBitrate){const i=r?r.duration:n.duration,l=this.hls.levels[n.level],o=(l.loaded?l.loaded.bytes:0)+a.loaded,c=(l.loaded?l.loaded.duration:0)+i;l.loaded={bytes:o,duration:c},l.realBitrate=Math.round(8*o/c)}if(n.bitrateTest){const i={stats:a,frag:n,part:r,id:n.type};this.onFragBuffered(jt.FRAG_BUFFERED,i),n.bitrateTest=!1}else this.lastLoadedFragLevel=n.level}}onFragBuffered(t,n){const{frag:r,part:a}=n,i=a!=null&&a.stats.loaded?a.stats:r.stats;if(i.aborted||this.ignoreFragment(r))return;const l=i.parsing.end-i.loading.start-Math.min(i.loading.first-i.loading.start,this.bwEstimator.getEstimateTTFB());this.bwEstimator.sample(l,i.loaded),i.bwEstimate=this.getBwEstimate(),r.bitrateTest?this.bitrateTestDelay=l/1e3:this.bitrateTestDelay=0}ignoreFragment(t){return t.type!==Wa.MAIN||t.sn==="initSegment"}clearTimer(){this.timer>-1&&(self.clearInterval(this.timer),this.timer=-1)}get firstAutoLevel(){const{maxAutoLevel:t,minAutoLevel:n}=this.hls,r=this.getBwEstimate(),a=this.hls.config.maxStarvationDelay,i=this.findBestLevel(r,n,t,0,a,1,1);if(i>-1)return i;const l=this.hls.firstLevel,o=Math.min(Math.max(l,n),t);return this.warn(`Could not find best starting auto level. Defaulting to first in playlist ${l} clamped to ${o}`),o}get forcedAutoLevel(){return this.nextAutoLevelKey?-1:this._nextAutoLevel}get nextAutoLevel(){const t=this.forcedAutoLevel,r=this.bwEstimator.canEstimate(),a=this.lastLoadedFragLevel>-1;if(t!==-1&&(!r||!a||this.nextAutoLevelKey===this.getAutoLevelKey()))return t;const i=r&&a?this.getNextABRAutoLevel():this.firstAutoLevel;if(t!==-1){const l=this.hls.levels;if(l.length>Math.max(t,i)&&l[t].loadError<=l[i].loadError)return t}return this._nextAutoLevel=i,this.nextAutoLevelKey=this.getAutoLevelKey(),i}getAutoLevelKey(){return`${this.getBwEstimate()}_${this.getStarvationDelay().toFixed(2)}`}getNextABRAutoLevel(){const{fragCurrent:t,partCurrent:n,hls:r}=this;if(r.levels.length<=1)return r.loadLevel;const{maxAutoLevel:a,config:i,minAutoLevel:l}=r,o=n?n.duration:t?t.duration:0,c=this.getBwEstimate(),d=this.getStarvationDelay();let u=i.abrBandWidthFactor,h=i.abrBandWidthUpFactor;if(d){const v=this.findBestLevel(c,l,a,d,0,u,h);if(v>=0)return this.rebufferNotice=-1,v}let p=o?Math.min(o,i.maxStarvationDelay):i.maxStarvationDelay;if(!d){const v=this.bitrateTestDelay;v&&(p=(o?Math.min(o,i.maxLoadingDelay):i.maxLoadingDelay)-v,this.info(`bitrate test took ${Math.round(1e3*v)}ms, set first fragment max fetchDuration to ${Math.round(1e3*p)} ms`),u=h=1)}const f=this.findBestLevel(c,l,a,d,p,u,h);if(this.rebufferNotice!==f&&(this.rebufferNotice=f,this.info(`${d?"rebuffering expected":"buffer is empty"}, optimal quality level ${f}`)),f>-1)return f;const y=r.levels[l],_=r.loadLevelObj;return _&&(y==null?void 0:y.bitrate)<_.bitrate?l:r.loadLevel}getStarvationDelay(){const t=this.hls,n=t.media;if(!n)return 1/0;const r=n&&n.playbackRate!==0?Math.abs(n.playbackRate):1,a=t.mainForwardBufferInfo;return(a?a.len:0)/r}getBwEstimate(){return this.bwEstimator.canEstimate()?this.bwEstimator.getEstimate():this.hls.config.abrEwmaDefaultEstimate}findBestLevel(t,n,r,a,i,l,o){var c;const d=a+i,u=this.lastLoadedFragLevel,h=u===-1?this.hls.firstLevel:u,{fragCurrent:p,partCurrent:f}=this,{levels:y,allAudioTracks:_,loadLevel:v,config:j}=this.hls;if(y.length===1)return 0;const w=y[h],S=!!((c=this.hls.latestLevelDetails)!=null&&c.live),A=v===-1||u===-1;let E,O="SDR",D=(w==null?void 0:w.frameRate)||0;const{audioPreference:I,videoPreference:F}=j,z=this.audioTracksByGroup||(this.audioTracksByGroup=NNt(_));let H=-1;if(A){if(this.firstSelection!==-1)return this.firstSelection;const se=this.codecTiers||(this.codecTiers=crn(y,z,n,r)),oe=lrn(se,O,t,I,F),{codecSet:he,videoRanges:ce,minFramerate:me,minBitrate:le,minIndex:ve,preferHDR:ge}=oe;H=ve,E=he,O=ge?ce[ce.length-1]:ce[0],D=me,t=Math.max(t,le),this.log(`picked start tier ${rd(oe)}`)}else E=w==null?void 0:w.codecSet,O=w==null?void 0:w.videoRange;const Z=f?f.duration:p?p.duration:0,Y=this.bwEstimator.getEstimateTTFB()/1e3,W=[];for(let se=r;se>=n;se--){var ee;const oe=y[se],he=se>h;if(!oe)continue;if(j.useMediaCapabilities&&!oe.supportedResult&&!oe.supportedPromise){const Ie=navigator.mediaCapabilities;typeof(Ie==null?void 0:Ie.decodingInfo)=="function"&&Xnn(oe,z,O,D,t,I)?(oe.supportedPromise=wNt(oe,z,Ie,this.supportedCache),oe.supportedPromise.then(Ce=>{if(!this.hls)return;oe.supportedResult=Ce;const Me=this.hls.levels,Pe=Me.indexOf(oe);Ce.error?this.warn(`MediaCapabilities decodingInfo error: "${Ce.error}" for level ${Pe} ${rd(Ce)}`):Ce.supported?Ce.decodingInfoResults.some(Re=>Re.smooth===!1||Re.powerEfficient===!1)&&this.log(`MediaCapabilities decodingInfo for level ${Pe} not smooth or powerEfficient: ${rd(Ce)}`):(this.warn(`Unsupported MediaCapabilities decodingInfo result for level ${Pe} ${rd(Ce)}`),Pe>-1&&Me.length>1&&(this.log(`Removing unsupported level ${Pe}`),this.hls.removeLevel(Pe),this.hls.loadLevel===-1&&(this.hls.nextLoadLevel=0)))}).catch(Ce=>{this.warn(`Error handling MediaCapabilities decodingInfo: ${Ce}`)})):oe.supportedResult=bNt}if((E&&oe.codecSet!==E||O&&oe.videoRange!==O||he&&D>oe.frameRate||!he&&D>0&&DIe.smooth===!1))&&(!A||se!==H)){W.push(se);continue}const ce=oe.details,me=(f?ce==null?void 0:ce.partTarget:ce==null?void 0:ce.averagetargetduration)||Z;let le;he?le=o*t:le=l*t;const ve=Z&&a>=Z*2&&i===0?oe.averageBitrate:oe.maxBitrate,ge=this.getTimeToLoadFrag(Y,le,ve*me,ce===void 0);if(le>=ve&&(se===u||oe.loadError===0&&oe.fragmentError===0)&&(ge<=Y||!Pa(ge)||S&&!this.bitrateTestDelay||ge${se} adjustedbw(${Math.round(le)})-bitrate=${Math.round(le-ve)} ttfb:${Y.toFixed(1)} avgDuration:${me.toFixed(1)} maxFetchDuration:${d.toFixed(1)} fetchDuration:${ge.toFixed(1)} firstSelection:${A} codecSet:${oe.codecSet} videoRange:${oe.videoRange} hls.loadLevel:${v}`)),A&&(this.firstSelection=se),se}}return-1}set nextAutoLevel(t){const n=this.deriveNextAutoLevel(t);this._nextAutoLevel!==n&&(this.nextAutoLevelKey="",this._nextAutoLevel=n)}deriveNextAutoLevel(t){const{maxAutoLevel:n,minAutoLevel:r}=this.hls;return Math.min(Math.max(t,r),n)}}const kNt={search:function(s,t){let n=0,r=s.length-1,a=null,i=null;for(;n<=r;){a=(n+r)/2|0,i=s[a];const l=t(i);if(l>0)n=a+1;else if(l<0)r=a-1;else return i}return null}};function prn(s,t,n){if(t===null||!Array.isArray(s)||!s.length||!Pa(t))return null;const r=s[0].programDateTime;if(t<(r||0))return null;const a=s[s.length-1].endProgramDateTime;if(t>=(a||0))return null;for(let i=0;i0&&o<15e-7&&(n+=15e-7),i&&s.level!==i.level&&i.end<=s.end&&(i=t[2+s.sn-t[0].sn]||null)}else n===0&&t[0].start===0&&(i=t[0]);if(i&&((!s||s.level===i.level)&&UXe(n,r,i)===0||frn(i,s,Math.min(a,r))))return i;const l=kNt.search(t,UXe.bind(null,n,r));return l&&(l!==s||!i)?l:i}function frn(s,t,n){if(t&&t.start===0&&t.level0){const r=t.tagList.reduce((a,i)=>(i[0]==="INF"&&(a+=parseFloat(i[1])),a),n);return s.start<=r}return!1}function UXe(s=0,t=0,n){if(n.start<=s&&n.start+n.duration>s)return 0;const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0));return n.start+n.duration-r<=s?1:n.start-r>s&&n.start?-1:0}function xrn(s,t,n){const r=Math.min(t,n.duration+(n.deltaPTS?n.deltaPTS:0))*1e3;return(n.endProgramDateTime||0)-r>s}function SNt(s,t,n){if(s&&s.startCC<=t&&s.endCC>=t){let r=s.fragments;const{fragmentHint:a}=s;a&&(r=r.concat(a));let i;return kNt.search(r,l=>l.cct?-1:(i=l,l.end<=n?1:l.start>n?-1:0)),i||null}return null}function zge(s){switch(s.details){case Mn.FRAG_LOAD_TIMEOUT:case Mn.KEY_LOAD_TIMEOUT:case Mn.LEVEL_LOAD_TIMEOUT:case Mn.MANIFEST_LOAD_TIMEOUT:return!0}return!1}function CNt(s){return s.details.startsWith("key")}function TNt(s){return CNt(s)&&!!s.frag&&!s.frag.decryptdata}function qXe(s,t){const n=zge(t);return s.default[`${n?"timeout":"error"}Retry`]}function g8e(s,t){const n=s.backoff==="linear"?1:Math.pow(2,t);return Math.min(n*s.retryDelayMs,s.maxRetryDelayMs)}function VXe(s){return wc(wc({},s),{errorRetry:null,timeoutRetry:null})}function Bge(s,t,n,r){if(!s)return!1;const a=r==null?void 0:r.code,i=t499)}function fTe(s){return s===0&&navigator.onLine===!1}var ef={DoNothing:0,SendEndCallback:1,SendAlternateToPenaltyBox:2,RemoveAlternatePermanently:3,InsertDiscontinuity:4,RetryRequest:5},O0={None:0,MoveAllAlternatesMatchingHost:1,MoveAllAlternatesMatchingHDCP:2,MoveAllAlternatesMatchingKey:4,SwitchToSDR:8};class yrn extends t1{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(jt.ERROR,this.onError,this),t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.LEVEL_UPDATED,this.onLevelUpdated,this)}unregisterListeners(){const t=this.hls;t&&(t.off(jt.ERROR,this.onError,this),t.off(jt.ERROR,this.onErrorOut,this),t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.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)===Wa.MAIN?t.level:this.getVariantIndex()}getVariantIndex(){var t;const n=this.hls,r=n.currentLevel;return(t=n.loadLevelObj)!=null&&t.details||r===-1?n.loadLevel:r}variantHasKey(t,n){if(t){var r;if((r=t.details)!=null&&r.hasKey(n))return!0;const a=t.audioGroups;if(a)return this.hls.allAudioTracks.filter(l=>a.indexOf(l.groupId)>=0).some(l=>{var o;return(o=l.details)==null?void 0:o.hasKey(n)})}return!1}onManifestLoading(){this.playlistError=0}onLevelUpdated(){this.playlistError=0}onError(t,n){var r;if(n.fatal)return;const a=this.hls,i=n.context;switch(n.details){case Mn.FRAG_LOAD_ERROR:case Mn.FRAG_LOAD_TIMEOUT:case Mn.KEY_LOAD_ERROR:case Mn.KEY_LOAD_TIMEOUT:n.errorAction=this.getFragRetryOrSwitchAction(n);return;case Mn.FRAG_PARSING_ERROR:if((r=n.frag)!=null&&r.gap){n.errorAction=BL();return}case Mn.FRAG_GAP:case Mn.FRAG_DECRYPT_ERROR:{n.errorAction=this.getFragRetryOrSwitchAction(n),n.errorAction.action=ef.SendAlternateToPenaltyBox;return}case Mn.LEVEL_EMPTY_ERROR:case Mn.LEVEL_PARSING_ERROR:{var l;const c=n.parent===Wa.MAIN?n.level:a.loadLevel;n.details===Mn.LEVEL_EMPTY_ERROR&&((l=n.context)!=null&&(l=l.levelDetails)!=null&&l.live)?n.errorAction=this.getPlaylistRetryOrSwitchAction(n,c):(n.levelRetry=!1,n.errorAction=this.getLevelSwitchAction(n,c))}return;case Mn.LEVEL_LOAD_ERROR:case Mn.LEVEL_LOAD_TIMEOUT:typeof(i==null?void 0:i.level)=="number"&&(n.errorAction=this.getPlaylistRetryOrSwitchAction(n,i.level));return;case Mn.AUDIO_TRACK_LOAD_ERROR:case Mn.AUDIO_TRACK_LOAD_TIMEOUT:case Mn.SUBTITLE_LOAD_ERROR:case Mn.SUBTITLE_TRACK_LOAD_TIMEOUT:if(i){const c=a.loadLevelObj;if(c&&(i.type===rl.AUDIO_TRACK&&c.hasAudioGroup(i.groupId)||i.type===rl.SUBTITLE_TRACK&&c.hasSubtitleGroup(i.groupId))){n.errorAction=this.getPlaylistRetryOrSwitchAction(n,a.loadLevel),n.errorAction.action=ef.SendAlternateToPenaltyBox,n.errorAction.flags=O0.MoveAllAlternatesMatchingHost;return}}return;case Mn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:n.errorAction={action:ef.SendAlternateToPenaltyBox,flags:O0.MoveAllAlternatesMatchingHDCP};return;case Mn.KEY_SYSTEM_SESSION_UPDATE_FAILED:case Mn.KEY_SYSTEM_STATUS_INTERNAL_ERROR:case Mn.KEY_SYSTEM_NO_SESSION:n.errorAction={action:ef.SendAlternateToPenaltyBox,flags:O0.MoveAllAlternatesMatchingKey};return;case Mn.BUFFER_ADD_CODEC_ERROR:case Mn.REMUX_ALLOC_ERROR:case Mn.BUFFER_APPEND_ERROR:if(!n.errorAction){var o;n.errorAction=this.getLevelSwitchAction(n,(o=n.level)!=null?o:a.loadLevel)}return;case Mn.INTERNAL_EXCEPTION:case Mn.BUFFER_APPENDING_ERROR:case Mn.BUFFER_FULL_ERROR:case Mn.LEVEL_SWITCH_ERROR:case Mn.BUFFER_STALLED_ERROR:case Mn.BUFFER_SEEK_OVER_HOLE:case Mn.BUFFER_NUDGE_ON_STALL:n.errorAction=BL();return}n.type===ui.KEY_SYSTEM_ERROR&&(n.levelRetry=!1,n.errorAction=BL())}getPlaylistRetryOrSwitchAction(t,n){const r=this.hls,a=qXe(r.config.playlistLoadPolicy,t),i=this.playlistError++;if(Bge(a,i,zge(t),t.response))return{action:ef.RetryRequest,flags:O0.None,retryConfig:a,retryCount:i};const o=this.getLevelSwitchAction(t,n);return a&&(o.retryConfig=a,o.retryCount=i),o}getFragRetryOrSwitchAction(t){const n=this.hls,r=this.getVariantLevelIndex(t.frag),a=n.levels[r],{fragLoadPolicy:i,keyLoadPolicy:l}=n.config,o=qXe(CNt(t)?l:i,t),c=n.levels.reduce((u,h)=>u+h.fragmentError,0);if(a&&(t.details!==Mn.FRAG_GAP&&a.fragmentError++,!TNt(t)&&Bge(o,c,zge(t),t.response)))return{action:ef.RetryRequest,flags:O0.None,retryConfig:o,retryCount:c};const d=this.getLevelSwitchAction(t,r);return o&&(d.retryConfig=o,d.retryCount=c),d}getLevelSwitchAction(t,n){const r=this.hls;n==null&&(n=r.loadLevel);const a=this.hls.levels[n];if(a){var i,l;const d=t.details;a.loadError++,d===Mn.BUFFER_APPEND_ERROR&&a.fragmentError++;let u=-1;const{levels:h,loadLevel:p,minAutoLevel:f,maxAutoLevel:y}=r;!r.autoLevelEnabled&&!r.config.preserveManualLevelOnError&&(r.loadLevel=-1);const _=(i=t.frag)==null?void 0:i.type,j=(_===Wa.AUDIO&&d===Mn.FRAG_PARSING_ERROR||t.sourceBufferName==="audio"&&(d===Mn.BUFFER_ADD_CODEC_ERROR||d===Mn.BUFFER_APPEND_ERROR))&&h.some(({audioCodec:O})=>a.audioCodec!==O),S=t.sourceBufferName==="video"&&(d===Mn.BUFFER_ADD_CODEC_ERROR||d===Mn.BUFFER_APPEND_ERROR)&&h.some(({codecSet:O,audioCodec:D})=>a.codecSet!==O&&a.audioCodec===D),{type:A,groupId:E}=(l=t.context)!=null?l:{};for(let O=h.length;O--;){const D=(O+p)%h.length;if(D!==p&&D>=f&&D<=y&&h[D].loadError===0){var o,c;const I=h[D];if(d===Mn.FRAG_GAP&&_===Wa.MAIN&&t.frag){const F=h[D].details;if(F){const z=LM(t.frag,F.fragments,t.frag.start);if(z!=null&&z.gap)continue}}else{if(A===rl.AUDIO_TRACK&&I.hasAudioGroup(E)||A===rl.SUBTITLE_TRACK&&I.hasSubtitleGroup(E))continue;if(_===Wa.AUDIO&&(o=a.audioGroups)!=null&&o.some(F=>I.hasAudioGroup(F))||_===Wa.SUBTITLE&&(c=a.subtitleGroups)!=null&&c.some(F=>I.hasSubtitleGroup(F))||j&&a.audioCodec===I.audioCodec||S&&a.codecSet===I.codecSet||!j&&a.codecSet!==I.codecSet)continue}u=D;break}}if(u>-1&&r.loadLevel!==u)return t.levelRetry=!0,this.playlistError=0,{action:ef.SendAlternateToPenaltyBox,flags:O0.None,nextAutoLevel:u}}return{action:ef.SendAlternateToPenaltyBox,flags:O0.MoveAllAlternatesMatchingHost}}onErrorOut(t,n){var r;switch((r=n.errorAction)==null?void 0:r.action){case ef.DoNothing:break;case ef.SendAlternateToPenaltyBox:this.sendAlternateToPenaltyBox(n),!n.errorAction.resolved&&n.details!==Mn.FRAG_GAP?n.fatal=!0:/MediaSource readyState: ended/.test(n.error.message)&&(this.warn(`MediaSource ended after "${n.sourceBufferName}" sourceBuffer append error. Attempting to recover from media error.`),this.hls.recoverMediaError());break}if(n.fatal){this.hls.stopLoad();return}}sendAlternateToPenaltyBox(t){const n=this.hls,r=t.errorAction;if(!r)return;const{flags:a}=r,i=r.nextAutoLevel;switch(a){case O0.None:this.switchLevel(t,i);break;case O0.MoveAllAlternatesMatchingHDCP:{const c=this.getVariantLevelIndex(t.frag),d=n.levels[c],u=d==null?void 0:d.attrs["HDCP-LEVEL"];if(r.hdcpLevel=u,u==="NONE")this.warn("HDCP policy resticted output with HDCP-LEVEL=NONE");else if(u){n.maxHdcpLevel=pTe[pTe.indexOf(u)-1],r.resolved=!0,this.warn(`Restricting playback to HDCP-LEVEL of "${n.maxHdcpLevel}" or lower`);break}}case O0.MoveAllAlternatesMatchingKey:{const c=t.decryptdata;if(c){const d=this.hls.levels,u=d.length;for(let p=u;p--;)if(this.variantHasKey(d[p],c)){var l,o;this.log(`Banned key found in level ${p} (${d[p].bitrate}bps) or audio group "${(l=d[p].audioGroups)==null?void 0:l.join(",")}" (${(o=t.frag)==null?void 0:o.type} fragment) ${tf(c.keyId||[])}`),d[p].fragmentError++,d[p].loadError++,this.log(`Removing level ${p} with key error (${t.error})`),this.hls.removeLevel(p)}const h=t.frag;if(this.hls.levels.length{const c=this.fragments[o];if(!c||l>=c.body.sn)return;if(!c.buffered&&(!c.loaded||i)){c.body.type===r&&this.removeFragment(c.body);return}const d=c.range[t];if(d){if(d.time.length===0){this.removeFragment(c.body);return}d.time.some(u=>{const h=!this.isTimeBuffered(u.startPTS,u.endPTS,n);return h&&this.removeFragment(c.body),h})}})}detectPartialFragments(t){const n=this.timeRanges;if(!n||t.frag.sn==="initSegment")return;const r=t.frag,a=zI(r),i=this.fragments[a];if(!i||i.buffered&&r.gap)return;const l=!r.relurl;Object.keys(n).forEach(o=>{const c=r.elementaryStreams[o];if(!c)return;const d=n[o],u=l||c.partial===!0;i.range[o]=this.getBufferedTimes(r,t.part,u,d)}),i.loaded=null,Object.keys(i.range).length?(this.bufferedEnd(i,r),SG(i)||this.removeParts(r.sn-1,r.type)):this.removeFragment(i.body)}bufferedEnd(t,n){t.buffered=!0,(t.body.endList=n.endList||t.body.endList)&&(this.endListFragments[t.body.type]=t)}removeParts(t,n){const r=this.activePartLists[n];r&&(this.activePartLists[n]=HXe(r,a=>a.fragment.sn>=t))}fragBuffered(t,n){const r=zI(t);let a=this.fragments[r];!a&&n&&(a=this.fragments[r]={body:t,appendedPTS:null,loaded:null,buffered:!1,range:Object.create(null)},t.gap&&(this.hasGaps=!0)),a&&(a.loaded=null,this.bufferedEnd(a,t))}getBufferedTimes(t,n,r,a){const i={time:[],partial:r},l=t.start,o=t.end,c=t.minEndPTS||o,d=t.maxStartPTS||l;for(let u=0;u=h&&c<=p){i.time.push({startPTS:Math.max(l,a.start(u)),endPTS:Math.min(o,a.end(u))});break}else if(lh){const f=Math.max(l,a.start(u)),y=Math.min(o,a.end(u));y>f&&(i.partial=!0,i.time.push({startPTS:f,endPTS:y}))}else if(o<=h)break}return i}getPartialFragment(t){let n=null,r,a,i,l=0;const{bufferPadding:o,fragments:c}=this;return Object.keys(c).forEach(d=>{const u=c[d];u&&SG(u)&&(a=u.body.start-o,i=u.body.end+o,t>=a&&t<=i&&(r=Math.min(t-a,i-t),l<=r&&(n=u.body,l=r)))}),n}isEndListAppended(t){const n=this.endListFragments[t];return n!==void 0&&(n.buffered||SG(n))}getState(t){const n=zI(t),r=this.fragments[n];return r?r.buffered?SG(r)?Mm.PARTIAL:Mm.OK:Mm.APPENDING:Mm.NOT_LOADED}isTimeBuffered(t,n,r){let a,i;for(let l=0;l=a&&n<=i)return!0;if(n<=a)return!1}return!1}onManifestLoading(){this.removeAllFragments()}onFragLoaded(t,n){if(n.frag.sn==="initSegment"||n.frag.bitrateTest)return;const r=n.frag,a=n.part?null:n,i=zI(r);this.fragments[i]={body:r,appendedPTS:null,loaded:a,buffered:!1,range:Object.create(null)}}onBufferAppended(t,n){const{frag:r,part:a,timeRanges:i,type:l}=n;if(r.sn==="initSegment")return;const o=r.type;if(a){let d=this.activePartLists[o];d||(this.activePartLists[o]=d=[]),d.push(a)}this.timeRanges=i;const c=i[l];this.detectEvictedFragments(l,c,o,a)}onFragBuffered(t,n){this.detectPartialFragments(n)}hasFragment(t){const n=zI(t);return!!this.fragments[n]}hasFragments(t){const{fragments:n}=this,r=Object.keys(n);if(!t)return r.length>0;for(let a=r.length;a--;){const i=n[r[a]];if((i==null?void 0:i.body.type)===t)return!0}return!1}hasParts(t){var n;return!!((n=this.activePartLists[t])!=null&&n.length)}removeFragmentsInRange(t,n,r,a,i){a&&!this.hasGaps||Object.keys(this.fragments).forEach(l=>{const o=this.fragments[l];if(!o)return;const c=o.body;c.type!==r||a&&!c.gap||c.startt&&(o.buffered||i)&&this.removeFragment(c)})}removeFragment(t){const n=zI(t);t.clearElementaryStreamInfo();const r=this.activePartLists[t.type];if(r){const a=t.sn;this.activePartLists[t.type]=HXe(r,i=>i.fragment.sn!==a)}delete this.fragments[n],t.endList&&delete this.endListFragments[t.type]}removeAllFragments(){var t;this.fragments=Object.create(null),this.endListFragments=Object.create(null),this.activePartLists=Object.create(null),this.hasGaps=!1;const n=(t=this.hls)==null||(t=t.latestLevelDetails)==null?void 0:t.partList;n&&n.forEach(r=>r.clearElementaryStreamInfo())}}function SG(s){var t,n,r;return s.buffered&&!!(s.body.gap||(t=s.range.video)!=null&&t.partial||(n=s.range.audio)!=null&&n.partial||(r=s.range.audiovideo)!=null&&r.partial)}function zI(s){return`${s.type}_${s.level}_${s.sn}`}function HXe(s,t){return s.filter(n=>{const r=t(n);return r||n.clearElementaryStreamInfo(),r})}var P4={cbc:0,ctr:1};class brn{constructor(t,n,r){this.subtle=void 0,this.aesIV=void 0,this.aesMode=void 0,this.subtle=t,this.aesIV=n,this.aesMode=r}decrypt(t,n){switch(this.aesMode){case P4.cbc:return this.subtle.decrypt({name:"AES-CBC",iv:this.aesIV},n,t);case P4.ctr:return this.subtle.decrypt({name:"AES-CTR",counter:this.aesIV,length:64},n,t);default:throw new Error(`[AESCrypto] invalid aes mode ${this.aesMode}`)}}}function _rn(s){const t=s.byteLength,n=t&&new DataView(s.buffer).getUint8(t-1);return n?s.slice(0,t-n):s}class wrn{constructor(){this.rcon=[0,1,2,4,8,16,32,64,128,27,54],this.subMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.invSubMix=[new Uint32Array(256),new Uint32Array(256),new Uint32Array(256),new Uint32Array(256)],this.sBox=new Uint32Array(256),this.invSBox=new Uint32Array(256),this.key=new Uint32Array(0),this.ksRows=0,this.keySize=0,this.keySchedule=void 0,this.invKeySchedule=void 0,this.initTable()}uint8ArrayToUint32Array_(t){const n=new DataView(t),r=new Uint32Array(4);for(let a=0;a<4;a++)r[a]=n.getUint32(a*4);return r}initTable(){const t=this.sBox,n=this.invSBox,r=this.subMix,a=r[0],i=r[1],l=r[2],o=r[3],c=this.invSubMix,d=c[0],u=c[1],h=c[2],p=c[3],f=new Uint32Array(256);let y=0,_=0,v=0;for(v=0;v<256;v++)v<128?f[v]=v<<1:f[v]=v<<1^283;for(v=0;v<256;v++){let j=_^_<<1^_<<2^_<<3^_<<4;j=j>>>8^j&255^99,t[y]=j,n[j]=y;const w=f[y],S=f[w],A=f[S];let E=f[j]*257^j*16843008;a[y]=E<<24|E>>>8,i[y]=E<<16|E>>>16,l[y]=E<<8|E>>>24,o[y]=E,E=A*16843009^S*65537^w*257^y*16843008,d[j]=E<<24|E>>>8,u[j]=E<<16|E>>>16,h[j]=E<<8|E>>>24,p[j]=E,y?(y=w^f[f[f[A^w]]],_^=f[f[_]]):y=_=1}}expandKey(t){const n=this.uint8ArrayToUint32Array_(t);let r=!0,a=0;for(;a{const o=ArrayBuffer.isView(t)?t:new Uint8Array(t);this.softwareDecrypt(o,n,r,a);const c=this.flush();c?i(c.buffer):l(new Error("[softwareDecrypt] Failed to decrypt data"))}):this.webCryptoDecrypt(new Uint8Array(t),n,r,a)}softwareDecrypt(t,n,r,a){const{currentIV:i,currentResult:l,remainderData:o}=this;if(a!==P4.cbc||n.byteLength!==16)return Cc.warn("SoftwareDecrypt: can only handle AES-128-CBC"),null;this.logOnce("JS AES decrypt"),o&&(t=Gv(o,t),this.remainderData=null);const c=this.getValidChunk(t);if(!c.length)return null;i&&(r=i);let d=this.softwareDecrypter;d||(d=this.softwareDecrypter=new wrn),d.expandKey(n);const u=l;return this.currentResult=d.decrypt(c.buffer,0,r),this.currentIV=c.slice(-16).buffer,u||null}webCryptoDecrypt(t,n,r,a){if(this.key!==n||!this.fastAesKey){if(!this.subtle)return Promise.resolve(this.onWebCryptoError(t,n,r,a));this.key=n,this.fastAesKey=new jrn(this.subtle,n,a)}return this.fastAesKey.expandKey().then(i=>this.subtle?(this.logOnce("WebCrypto AES decrypt"),new brn(this.subtle,new Uint8Array(r),a).decrypt(t.buffer,i)):Promise.reject(new Error("web crypto not initialized"))).catch(i=>(Cc.warn(`[decrypter]: WebCrypto Error, disable WebCrypto API, ${i.name}: ${i.message}`),this.onWebCryptoError(t,n,r,a)))}onWebCryptoError(t,n,r,a){const i=this.enableSoftwareAES;if(i){this.useSoftware=!0,this.logEnabled=!0,this.softwareDecrypt(t,n,r,a);const l=this.flush();if(l)return l.buffer}throw new Error("WebCrypto"+(i?" and softwareDecrypt":"")+": failed to decrypt data")}getValidChunk(t){let n=t;const r=t.length-t.length%krn;return r!==t.length&&(n=t.slice(0,r),this.remainderData=t.slice(r)),n}logOnce(t){this.logEnabled&&(Cc.log(`[decrypter]: ${t}`),this.logEnabled=!1)}}const GXe=Math.pow(2,17);class Srn{constructor(t){this.config=void 0,this.loader=null,this.partLoadTimeout=-1,this.config=t}destroy(){this.loader&&(this.loader.destroy(),this.loader=null)}abort(){this.loader&&this.loader.abort()}load(t,n){const r=t.url;if(!r)return Promise.reject(new _2({type:ui.NETWORK_ERROR,details:Mn.FRAG_LOAD_ERROR,fatal:!1,frag:t,error:new Error(`Fragment does not have a ${r?"part list":"url"}`),networkDetails:null}));this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap)if(t.tagList.some(y=>y[0]==="GAP")){c(KXe(t));return}else t.gap=!1;const d=this.loader=i?new i(a):new l(a),u=WXe(t);t.loader=d;const h=VXe(a.fragLoadPolicy.default),p={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:t.sn==="initSegment"?1/0:GXe};t.stats=d.stats;const f={onSuccess:(y,_,v,j)=>{this.resetLoader(t,d);let w=y.data;v.resetIV&&t.decryptdata&&(t.decryptdata.iv=new Uint8Array(w.slice(0,16)),w=w.slice(16)),o({frag:t,part:null,payload:w,networkDetails:j})},onError:(y,_,v,j)=>{this.resetLoader(t,d),c(new _2({type:ui.NETWORK_ERROR,details:Mn.FRAG_LOAD_ERROR,fatal:!1,frag:t,response:wc({url:r,data:void 0},y),error:new Error(`HTTP Error ${y.code} ${y.text}`),networkDetails:v,stats:j}))},onAbort:(y,_,v)=>{this.resetLoader(t,d),c(new _2({type:ui.NETWORK_ERROR,details:Mn.INTERNAL_ABORTED,fatal:!1,frag:t,error:new Error("Aborted"),networkDetails:v,stats:y}))},onTimeout:(y,_,v)=>{this.resetLoader(t,d),c(new _2({type:ui.NETWORK_ERROR,details:Mn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:v,stats:y}))}};n&&(f.onProgress=(y,_,v,j)=>n({frag:t,part:null,payload:v,networkDetails:j})),d.load(u,p,f)})}loadPart(t,n,r){this.abort();const a=this.config,i=a.fLoader,l=a.loader;return new Promise((o,c)=>{if(this.loader&&this.loader.destroy(),t.gap||n.gap){c(KXe(t,n));return}const d=this.loader=i?new i(a):new l(a),u=WXe(t,n);t.loader=d;const h=VXe(a.fragLoadPolicy.default),p={loadPolicy:h,timeout:h.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0,highWaterMark:GXe};n.stats=d.stats,d.load(u,p,{onSuccess:(f,y,_,v)=>{this.resetLoader(t,d),this.updateStatsFromPart(t,n);const j={frag:t,part:n,payload:f.data,networkDetails:v};r(j),o(j)},onError:(f,y,_,v)=>{this.resetLoader(t,d),c(new _2({type:ui.NETWORK_ERROR,details:Mn.FRAG_LOAD_ERROR,fatal:!1,frag:t,part:n,response:wc({url:u.url,data:void 0},f),error:new Error(`HTTP Error ${f.code} ${f.text}`),networkDetails:_,stats:v}))},onAbort:(f,y,_)=>{t.stats.aborted=n.stats.aborted,this.resetLoader(t,d),c(new _2({type:ui.NETWORK_ERROR,details:Mn.INTERNAL_ABORTED,fatal:!1,frag:t,part:n,error:new Error("Aborted"),networkDetails:_,stats:f}))},onTimeout:(f,y,_)=>{this.resetLoader(t,d),c(new _2({type:ui.NETWORK_ERROR,details:Mn.FRAG_LOAD_TIMEOUT,fatal:!1,frag:t,part:n,error:new Error(`Timeout after ${p.timeout}ms`),networkDetails:_,stats:f}))}})})}updateStatsFromPart(t,n){const r=t.stats,a=n.stats,i=a.total;if(r.loaded+=a.loaded,i){const c=Math.round(t.duration/n.duration),d=Math.min(Math.round(r.loaded/i),c),h=(c-d)*Math.round(r.loaded/d);r.total=r.loaded+h}else r.total=Math.max(r.loaded,r.total);const l=r.loading,o=a.loading;l.start?l.first+=o.first-o.start:(l.start=o.start,l.first=o.first),l.end=o.end}resetLoader(t,n){t.loader=null,this.loader===n&&(self.clearTimeout(this.partLoadTimeout),this.loader=null),n.destroy()}}function WXe(s,t=null){const n=t||s,r={frag:s,part:t,responseType:"arraybuffer",url:n.url,headers:{},rangeStart:0,rangeEnd:0},a=n.byteRangeStartOffset,i=n.byteRangeEndOffset;if(Pa(a)&&Pa(i)){var l;let o=a,c=i;if(s.sn==="initSegment"&&Crn((l=s.decryptdata)==null?void 0:l.method)){const d=i-a;d%16&&(c=i+(16-d%16)),a!==0&&(r.resetIV=!0,o=a-16)}r.rangeStart=o,r.rangeEnd=c}return r}function KXe(s,t){const n=new Error(`GAP ${s.gap?"tag":"attribute"} found`),r={type:ui.MEDIA_ERROR,details:Mn.FRAG_GAP,fatal:!1,frag:s,error:n,networkDetails:null};return t&&(r.part=t),(t||s).stats.aborted=!0,new _2(r)}function Crn(s){return s==="AES-128"||s==="AES-256"}class _2 extends Error{constructor(t){super(t.error.message),this.data=void 0,this.data=t}}class ENt extends t1{constructor(t,n){super(t,n),this._boundTick=void 0,this._tickTimer=null,this._tickInterval=null,this._tickCallCount=0,this._boundTick=this.tick.bind(this)}destroy(){this.onHandlerDestroying(),this.onHandlerDestroyed()}onHandlerDestroying(){this.clearNextTick(),this.clearInterval()}onHandlerDestroyed(){}hasInterval(){return!!this._tickInterval}hasNextTick(){return!!this._tickTimer}setInterval(t){return this._tickInterval?!1:(this._tickCallCount=0,this._tickInterval=self.setInterval(this._boundTick,t),!0)}clearInterval(){return this._tickInterval?(self.clearInterval(this._tickInterval),this._tickInterval=null,!0):!1}clearNextTick(){return this._tickTimer?(self.clearTimeout(this._tickTimer),this._tickTimer=null,!0):!1}tick(){this._tickCallCount++,this._tickCallCount===1&&(this.doTick(),this._tickCallCount>1&&this.tickImmediate(),this._tickCallCount=0)}tickImmediate(){this.clearNextTick(),this._tickTimer=self.setTimeout(this._boundTick,0)}doTick(){}}class v8e{constructor(t,n,r,a=0,i=-1,l=!1){this.level=void 0,this.sn=void 0,this.part=void 0,this.id=void 0,this.size=void 0,this.partial=void 0,this.transmuxing=CG(),this.buffering={audio:CG(),video:CG(),audiovideo:CG()},this.level=t,this.sn=n,this.id=r,this.size=a,this.part=i,this.partial=l}}function CG(){return{start:0,executeStart:0,executeEnd:0,end:0}}const YXe={length:0,start:()=>0,end:()=>0};class bo{static isBuffered(t,n){if(t){const r=bo.getBuffered(t);for(let a=r.length;a--;)if(n>=r.start(a)&&n<=r.end(a))return!0}return!1}static bufferedRanges(t){if(t){const n=bo.getBuffered(t);return bo.timeRangesToArray(n)}return[]}static timeRangesToArray(t){const n=[];for(let r=0;r1&&t.sort((u,h)=>u.start-h.start||h.end-u.end);let a=-1,i=[];if(r)for(let u=0;u=t[u].start&&n<=t[u].end&&(a=u);const h=i.length;if(h){const p=i[h-1].end;t[u].start-pp&&(i[h-1].end=t[u].end):i.push(t[u])}else i.push(t[u])}else i=t;let l=0,o,c=n,d=n;for(let u=0;u=h&&n<=p&&(a=u),n+r>=h&&n{const a=r.substring(2,r.length-1),i=n==null?void 0:n[a];return i===void 0?(s.playlistParsingError||(s.playlistParsingError=new Error(`Missing preceding EXT-X-DEFINE tag for Variable Reference: "${a}"`)),r):i})}return t}function QXe(s,t,n){let r=s.variableList;r||(s.variableList=r={});let a,i;if("QUERYPARAM"in t){a=t.QUERYPARAM;try{const l=new self.URL(n).searchParams;if(l.has(a))i=l.get(a);else throw new Error(`"${a}" does not match any query parameter in URI: "${n}"`)}catch(l){s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE QUERYPARAM: ${l.message}`))}}else a=t.NAME,i=t.VALUE;a in r?s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE duplicate Variable Name declarations: "${a}"`)):r[a]=i||""}function Trn(s,t,n){const r=t.IMPORT;if(n&&r in n){let a=s.variableList;a||(s.variableList=a={}),a[r]=n[r]}else s.playlistParsingError||(s.playlistParsingError=new Error(`EXT-X-DEFINE IMPORT attribute not found in Multivariant Playlist: "${r}"`))}const Ern=/^(\d+)x(\d+)$/,XXe=/(.+?)=(".*?"|.*?)(?:,|$)/g;class bu{constructor(t,n){typeof t=="string"&&(t=bu.parseAttrList(t,n)),Wc(this,t)}get clientAttrs(){return Object.keys(this).filter(t=>t.substring(0,2)==="X-")}decimalInteger(t){const n=parseInt(this[t],10);return n>Number.MAX_SAFE_INTEGER?1/0:n}hexadecimalInteger(t){if(this[t]){let n=(this[t]||"0x").slice(2);n=(n.length&1?"0":"")+n;const r=new Uint8Array(n.length/2);for(let a=0;aNumber.MAX_SAFE_INTEGER?1/0:n}decimalFloatingPoint(t){return parseFloat(this[t])}optionalFloat(t,n){const r=this[t];return r?parseFloat(r):n}enumeratedString(t){return this[t]}enumeratedStringList(t,n){const r=this[t];return(r?r.split(/[ ,]+/):[]).reduce((a,i)=>(a[i.toLowerCase()]=!0,a),n)}bool(t){return this[t]==="YES"}decimalResolution(t){const n=Ern.exec(this[t]);if(n!==null)return{width:parseInt(n[1],10),height:parseInt(n[2],10)}}static parseAttrList(t,n){let r;const a={},i='"';for(XXe.lastIndex=0;(r=XXe.exec(t))!==null;){const l=r[1].trim();let o=r[2];const c=o.indexOf(i)===0&&o.lastIndexOf(i)===o.length-1;let d=!1;if(c)o=o.slice(1,-1);else switch(l){case"IV":case"SCTE35-CMD":case"SCTE35-IN":case"SCTE35-OUT":d=!0}if(n&&(c||d))o=xTe(n,o);else if(!d&&!c)switch(l){case"CLOSED-CAPTIONS":if(o==="NONE")break;case"ALLOWED-CPC":case"CLASS":case"ASSOC-LANGUAGE":case"AUDIO":case"BYTERANGE":case"CHANNELS":case"CHARACTERISTICS":case"CODECS":case"DATA-ID":case"END-DATE":case"GROUP-ID":case"ID":case"IMPORT":case"INSTREAM-ID":case"KEYFORMAT":case"KEYFORMATVERSIONS":case"LANGUAGE":case"NAME":case"PATHWAY-ID":case"QUERYPARAM":case"RECENTLY-REMOVED-DATERANGES":case"SERVER-URI":case"STABLE-RENDITION-ID":case"STABLE-VARIANT-ID":case"START-DATE":case"SUBTITLES":case"SUPPLEMENTAL-CODECS":case"URI":case"VALUE":case"VIDEO":case"X-ASSET-LIST":case"X-ASSET-URI":Cc.warn(`${t}: attribute ${l} is missing quotes`)}a[l]=o}return a}}const Arn="com.apple.hls.interstitial";function Mrn(s){return s!=="ID"&&s!=="CLASS"&&s!=="CUE"&&s!=="START-DATE"&&s!=="DURATION"&&s!=="END-DATE"&&s!=="END-ON-NEXT"}function Irn(s){return s==="SCTE35-OUT"||s==="SCTE35-IN"||s==="SCTE35-CMD"}class MNt{constructor(t,n,r=0){var a;if(this.attr=void 0,this.tagAnchor=void 0,this.tagOrder=void 0,this._startDate=void 0,this._endDate=void 0,this._dateAtEnd=void 0,this._cue=void 0,this._badValueForSameId=void 0,this.tagAnchor=(n==null?void 0:n.tagAnchor)||null,this.tagOrder=(a=n==null?void 0:n.tagOrder)!=null?a:r,n){const i=n.attr;for(const l in i)if(Object.prototype.hasOwnProperty.call(t,l)&&t[l]!==i[l]){Cc.warn(`DATERANGE tag attribute: "${l}" does not match for tags with ID: "${t.ID}"`),this._badValueForSameId=l;break}t=Wc(new bu({}),i,t)}if(this.attr=t,n?(this._startDate=n._startDate,this._cue=n._cue,this._endDate=n._endDate,this._dateAtEnd=n._dateAtEnd):this._startDate=new Date(t["START-DATE"]),"END-DATE"in this.attr){const i=(n==null?void 0:n.endDate)||new Date(this.attr["END-DATE"]);Pa(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?(Cc.warn(`Expected tagAnchor Fragment with PDT set for DateRange "${this.id}": ${t}`),NaN):t.start+(this.startDate.getTime()-t.programDateTime)/1e3}get startDate(){return this._startDate}get endDate(){const t=this._endDate||this._dateAtEnd;if(t)return t;const n=this.duration;return n!==null?this._dateAtEnd=new Date(this._startDate.getTime()+n*1e3):null}get duration(){if("DURATION"in this.attr){const t=this.attr.decimalFloatingPoint("DURATION");if(Pa(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===Arn}get isValid(){return!!this.id&&!this._badValueForSameId&&Pa(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 Prn=10;class Lrn{constructor(t){this.PTSKnown=!1,this.alignedSliding=!1,this.averagetargetduration=void 0,this.endCC=0,this.endSN=0,this.fragments=void 0,this.fragmentHint=void 0,this.partList=null,this.dateRanges=void 0,this.dateRangeTagCount=0,this.live=!0,this.requestScheduled=-1,this.ageHeader=0,this.advancedDateTime=void 0,this.updated=!0,this.advanced=!0,this.misses=0,this.startCC=0,this.startSN=0,this.startTimeOffset=null,this.targetduration=0,this.totalduration=0,this.type=null,this.url=void 0,this.m3u8="",this.version=null,this.canBlockReload=!1,this.canSkipUntil=0,this.canSkipDateRanges=!1,this.skippedSegments=0,this.recentlyRemovedDateranges=void 0,this.partHoldBack=0,this.holdBack=0,this.partTarget=0,this.preloadHint=void 0,this.renditionReports=void 0,this.tuneInGoal=0,this.deltaUpdateFailed=void 0,this.driftStartTime=0,this.driftEndTime=0,this.driftStart=0,this.driftEnd=0,this.encryptedFragments=void 0,this.playlistParsingError=null,this.variableList=null,this.hasVariableRefs=!1,this.appliedTimelineOffset=void 0,this.fragments=[],this.encryptedFragments=[],this.dateRanges={},this.url=t}reloaded(t){if(!t){this.advanced=!0,this.updated=!0;return}const n=this.lastPartSn-t.lastPartSn,r=this.lastPartIndex-t.lastPartIndex;this.updated=this.endSN!==t.endSN||!!r||!!n||!this.live,this.advanced=this.endSN>t.endSN||n>0||n===0&&r>0,this.updated||this.advanced?this.misses=Math.floor(t.misses*.6):this.misses=t.misses+1}hasKey(t){return this.encryptedFragments.some(n=>{let r=n.decryptdata;return r||(n.setKeyFormat(t.keyFormat),r=n.decryptdata),!!r&&t.matches(r)})}get hasProgramDateTime(){return this.fragments.length?Pa(this.fragments[this.fragments.length-1].programDateTime):!1}get levelTargetDuration(){return this.averagetargetduration||this.targetduration||Prn}get drift(){const t=this.driftEndTime-this.driftStartTime;return t>0?(this.driftEnd-this.driftStart)*1e3/t:1}get edge(){return this.partEnd||this.fragmentEnd}get partEnd(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].end:this.fragmentEnd}get fragmentEnd(){return this.fragments.length?this.fragments[this.fragments.length-1].end:0}get fragmentStart(){return this.fragments.length?this.fragments[0].start:0}get age(){return this.advancedDateTime?Math.max(Date.now()-this.advancedDateTime,0)/1e3:0}get lastPartIndex(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].index:-1}get maxPartIndex(){const t=this.partList;if(t){const n=this.lastPartIndex;if(n!==-1){for(let r=t.length;r--;)if(t[r].index>n)return t[r].index;return n}}return 0}get lastPartSn(){var t;return(t=this.partList)!=null&&t.length?this.partList[this.partList.length-1].fragment.sn:this.endSN}get expired(){if(this.live&&this.age&&this.misses<3){const t=this.partEnd-this.fragmentStart;return this.age>Math.max(t,this.totalduration)+this.levelTargetDuration}return!1}}function $ge(s,t){return s.length===t.length?!s.some((n,r)=>n!==t[r]):!1}function JXe(s,t){return!s&&!t?!0:!s||!t?!1:$ge(s,t)}function $L(s){return s==="AES-128"||s==="AES-256"||s==="AES-256-CTR"}function b8e(s){switch(s){case"AES-128":case"AES-256":return P4.cbc;case"AES-256-CTR":return P4.ctr;default:throw new Error(`invalid full segment method ${s}`)}}function _8e(s){return Uint8Array.from(atob(s),t=>t.charCodeAt(0))}function gTe(s){return Uint8Array.from(unescape(encodeURIComponent(s)),t=>t.charCodeAt(0))}function Drn(s){const t=gTe(s).subarray(0,16),n=new Uint8Array(16);return n.set(t,16-t.length),n}function INt(s){const t=function(r,a,i){const l=r[a];r[a]=r[i],r[i]=l};t(s,0,3),t(s,1,2),t(s,4,5),t(s,6,7)}function PNt(s){const t=s.split(":");let n=null;if(t[0]==="data"&&t.length===2){const r=t[1].split(";"),a=r[r.length-1].split(",");if(a.length===2){const i=a[0]==="base64",l=a[1];i?(r.splice(-1,1),n=_8e(l)):n=Drn(l)}}return n}const Uge=typeof self<"u"?self:void 0;var Cu={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.fps",PLAYREADY:"com.microsoft.playready",WIDEVINE:"com.widevine.alpha"},rf={CLEARKEY:"org.w3.clearkey",FAIRPLAY:"com.apple.streamingkeydelivery",PLAYREADY:"com.microsoft.playready",WIDEVINE:"urn:uuid:edef8ba9-79d6-4ace-a3c8-27dcd51d21ed"};function Qme(s){switch(s){case rf.FAIRPLAY:return Cu.FAIRPLAY;case rf.PLAYREADY:return Cu.PLAYREADY;case rf.WIDEVINE:return Cu.WIDEVINE;case rf.CLEARKEY:return Cu.CLEARKEY}}function ONe(s){switch(s){case Cu.FAIRPLAY:return rf.FAIRPLAY;case Cu.PLAYREADY:return rf.PLAYREADY;case Cu.WIDEVINE:return rf.WIDEVINE;case Cu.CLEARKEY:return rf.CLEARKEY}}function v7(s){const{drmSystems:t,widevineLicenseUrl:n}=s,r=t?[Cu.FAIRPLAY,Cu.WIDEVINE,Cu.PLAYREADY,Cu.CLEARKEY].filter(a=>!!t[a]):[];return!r[Cu.WIDEVINE]&&n&&r.push(Cu.WIDEVINE),r}const LNt=function(s){return Uge!=null&&(s=Uge.navigator)!=null&&s.requestMediaKeySystemAccess?self.navigator.requestMediaKeySystemAccess.bind(self.navigator):null}();function Rrn(s,t,n,r){let a;switch(s){case Cu.FAIRPLAY:a=["cenc","sinf"];break;case Cu.WIDEVINE:case Cu.PLAYREADY:a=["cenc"];break;case Cu.CLEARKEY:a=["cenc","keyids"];break;default:throw new Error(`Unknown key-system: ${s}`)}return Orn(a,t,n,r)}function Orn(s,t,n,r){return[{initDataTypes:s,persistentState:r.persistentState||"optional",distinctiveIdentifier:r.distinctiveIdentifier||"optional",sessionTypes:r.sessionTypes||[r.sessionType||"temporary"],audioCapabilities:t.map(i=>({contentType:`audio/mp4; codecs=${i}`,robustness:r.audioRobustness||"",encryptionScheme:r.audioEncryptionScheme||null})),videoCapabilities:n.map(i=>({contentType:`video/mp4; codecs=${i}`,robustness:r.videoRobustness||"",encryptionScheme:r.videoEncryptionScheme||null}))}]}function Frn(s){var t;return!!s&&(s.sessionType==="persistent-license"||!!((t=s.sessionTypes)!=null&&t.some(n=>n==="persistent-license")))}function DNt(s){const t=new Uint16Array(s.buffer,s.byteOffset,s.byteLength/2),n=String.fromCharCode.apply(null,Array.from(t)),r=n.substring(n.indexOf("<"),n.length),l=new DOMParser().parseFromString(r,"text/xml").getElementsByTagName("KID")[0];if(l){const o=l.childNodes[0]?l.childNodes[0].nodeValue:l.getAttribute("VALUE");if(o){const c=_8e(o).subarray(0,16);return INt(c),c}}return null}let BI={};class x4{static clearKeyUriToKeyIdMap(){BI={}}static setKeyIdForUri(t,n){BI[t]=n}static addKeyIdForUri(t){const n=Object.keys(BI).length%Number.MAX_SAFE_INTEGER,r=new Uint8Array(16);return new DataView(r.buffer,12,4).setUint32(0,n),BI[t]=r,r}constructor(t,n,r,a=[1],i=null,l){this.uri=void 0,this.method=void 0,this.keyFormat=void 0,this.keyFormatVersions=void 0,this.encrypted=void 0,this.isCommonEncryption=void 0,this.iv=null,this.key=null,this.keyId=null,this.pssh=null,this.method=t,this.uri=n,this.keyFormat=r,this.keyFormatVersions=a,this.iv=i,this.encrypted=t?t!=="NONE":!1,this.isCommonEncryption=this.encrypted&&!$L(t),l!=null&&l.startsWith("0x")&&(this.keyId=new Uint8Array(cNt(l)))}matches(t){return t.uri===this.uri&&t.method===this.method&&t.encrypted===this.encrypted&&t.keyFormat===this.keyFormat&&$ge(t.keyFormatVersions,this.keyFormatVersions)&&JXe(t.iv,this.iv)&&JXe(t.keyId,this.keyId)}isSupported(){if(this.method){if($L(this.method)||this.method==="NONE")return!0;if(this.keyFormat==="identity")return this.method==="SAMPLE-AES";switch(this.keyFormat){case rf.FAIRPLAY:case rf.WIDEVINE:case rf.PLAYREADY:case rf.CLEARKEY:return["SAMPLE-AES","SAMPLE-AES-CENC","SAMPLE-AES-CTR"].indexOf(this.method)!==-1}}return!1}getDecryptData(t,n){if(!this.encrypted||!this.uri)return null;if($L(this.method)){let i=this.iv;return i||(typeof t!="number"&&(Cc.warn(`missing IV for initialization segment with method="${this.method}" - compliance issue`),t=0),i=Brn(t)),new x4(this.method,this.uri,"identity",this.keyFormatVersions,i)}if(this.keyId){const i=BI[this.uri];if(i&&!$ge(this.keyId,i)&&x4.setKeyIdForUri(this.uri,this.keyId),this.pssh)return this}const r=PNt(this.uri);if(r)switch(this.keyFormat){case rf.WIDEVINE:if(this.pssh=r,!this.keyId){const i=qnn(r.buffer);if(i.length){var a;const l=i[0];this.keyId=(a=l.kids)!=null&&a.length?l.kids[0]:null}}this.keyId||(this.keyId=eJe(n));break;case rf.PLAYREADY:{const i=new Uint8Array([154,4,240,121,152,64,66,134,171,146,230,91,224,136,95,149]);this.pssh=Unn(i,null,r),this.keyId=DNt(r);break}default:{let i=r.subarray(0,16);if(i.length!==16){const l=new Uint8Array(16);l.set(i,16-i.length),i=l}this.keyId=i;break}}if(!this.keyId||this.keyId.byteLength!==16){let i;i=zrn(n),i||(i=eJe(n),i||(i=BI[this.uri])),i&&(this.keyId=i,x4.setKeyIdForUri(this.uri,i))}return this}}function zrn(s){const t=s==null?void 0:s[rf.WIDEVINE];return t?t.keyId:null}function eJe(s){const t=s==null?void 0:s[rf.PLAYREADY];if(t){const n=PNt(t.uri);if(n)return DNt(n)}return null}function Brn(s){const t=new Uint8Array(16);for(let n=12;n<16;n++)t[n]=s>>8*(15-n)&255;return t}const tJe=/#EXT-X-STREAM-INF:([^\r\n]*)(?:[\r\n](?:#[^\r\n]*)?)*([^\r\n]+)|#EXT-X-(SESSION-DATA|SESSION-KEY|DEFINE|CONTENT-STEERING|START):([^\r\n]*)[\r\n]+/g,sJe=/#EXT-X-MEDIA:(.*)/g,$rn=/^#EXT(?:INF|-X-TARGETDURATION):/m,FNe=new RegExp([/#EXTINF:\s*(\d*(?:\.\d+)?)(?:,(.*)\s+)?/.source,/(?!#) *(\S[^\r\n]*)/.source,/#.*/.source].join("|"),"g"),Urn=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 aw{static findGroup(t,n){for(let r=0;r0&&i.length({id:d.attrs.AUDIO,audioCodec:d.audioCodec})),SUBTITLES:l.map(d=>({id:d.attrs.SUBTITLES,textCodec:d.textCodec})),"CLOSED-CAPTIONS":[]};let c=0;for(sJe.lastIndex=0;(a=sJe.exec(t))!==null;){const d=new bu(a[1],r),u=d.TYPE;if(u){const h=o[u],p=i[u]||[];i[u]=p;const f=d.LANGUAGE,y=d["ASSOC-LANGUAGE"],_=d.CHANNELS,v=d.CHARACTERISTICS,j=d["INSTREAM-ID"],w={attrs:d,bitrate:0,id:c++,groupId:d["GROUP-ID"]||"",name:d.NAME||f||"",type:u,default:d.bool("DEFAULT"),autoselect:d.bool("AUTOSELECT"),forced:d.bool("FORCED"),lang:f,url:d.URI?aw.resolve(d.URI,n):""};if(y&&(w.assocLang=y),_&&(w.channels=_),v&&(w.characteristics=v),j&&(w.instreamId=j),h!=null&&h.length){const S=aw.findGroup(h,w.groupId)||h[0];iJe(w,S,"audioCodec"),iJe(w,S,"textCodec")}p.push(w)}}return i}static parseLevelPlaylist(t,n,r,a,i,l){var o;const c={url:n},d=new Lrn(n),u=d.fragments,h=[];let p=null,f=0,y=0,_=0,v=0,j=0,w=null,S=new LNe(a,c),A,E,O,D=-1,I=!1,F=null,z;if(FNe.lastIndex=0,d.m3u8=t,d.hasVariableRefs=ZXe(t),((o=FNe.exec(t))==null?void 0:o[0])!=="#EXTM3U")return d.playlistParsingError=new Error("Missing format identifier #EXTM3U"),d;for(;(A=FNe.exec(t))!==null;){I&&(I=!1,S=new LNe(a,c),S.playlistOffset=_,S.setStart(_),S.sn=f,S.cc=v,j&&(S.bitrate=j),S.level=r,p&&(S.initSegment=p,p.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime,p.rawProgramDateTime=null),F&&(S.setByteRange(F),F=null)));const W=A[1];if(W){S.duration=parseFloat(W);const ee=(" "+A[2]).slice(1);S.title=ee||null,S.tagList.push(ee?["INF",W,ee]:["INF",W])}else if(A[3]){if(Pa(S.duration)){S.playlistOffset=_,S.setStart(_),O&&lJe(S,O,d),S.sn=f,S.level=r,S.cc=v,u.push(S);const ee=(" "+A[3]).slice(1);S.relurl=xTe(d,ee),yTe(S,w,h),w=S,_+=S.duration,f++,y=0,I=!0}}else{if(A=A[0].match(Urn),!A){Cc.warn("No matches on slow regex match for level playlist!");continue}for(E=1;E0&&cJe(d,ee,A),f=d.startSN=parseInt(se);break;case"SKIP":{d.skippedSegments&&c2(d,ee,A);const he=new bu(se,d),ce=he.decimalInteger("SKIPPED-SEGMENTS");if(Pa(ce)){d.skippedSegments+=ce;for(let le=ce;le--;)u.push(null);f+=ce}const me=he.enumeratedString("RECENTLY-REMOVED-DATERANGES");me&&(d.recentlyRemovedDateranges=(d.recentlyRemovedDateranges||[]).concat(me.split(" ")));break}case"TARGETDURATION":d.targetduration!==0&&c2(d,ee,A),d.targetduration=Math.max(parseInt(se),1);break;case"VERSION":d.version!==null&&c2(d,ee,A),d.version=parseInt(se);break;case"INDEPENDENT-SEGMENTS":break;case"ENDLIST":d.live||c2(d,ee,A),d.live=!1;break;case"#":(se||oe)&&S.tagList.push(oe?[se,oe]:[se]);break;case"DISCONTINUITY":v++,S.tagList.push(["DIS"]);break;case"GAP":S.gap=!0,S.tagList.push([ee]);break;case"BITRATE":S.tagList.push([ee,se]),j=parseInt(se)*1e3,Pa(j)?S.bitrate=j:j=0;break;case"DATERANGE":{const he=new bu(se,d),ce=new MNt(he,d.dateRanges[he.ID],d.dateRangeTagCount);d.dateRangeTagCount++,ce.isValid||d.skippedSegments?d.dateRanges[ce.id]=ce:Cc.warn(`Ignoring invalid DATERANGE tag: "${se}"`),S.tagList.push(["EXT-X-DATERANGE",se]);break}case"DEFINE":{{const he=new bu(se,d);"IMPORT"in he?Trn(d,he,l):QXe(d,he,n)}break}case"DISCONTINUITY-SEQUENCE":d.startCC!==0?c2(d,ee,A):u.length>0&&cJe(d,ee,A),d.startCC=v=parseInt(se);break;case"KEY":{const he=nJe(se,n,d);if(he.isSupported()){if(he.method==="NONE"){O=void 0;break}O||(O={});const ce=O[he.keyFormat];ce!=null&&ce.matches(he)||(ce&&(O=Wc({},O)),O[he.keyFormat]=he)}else Cc.warn(`[Keys] Ignoring unsupported EXT-X-KEY tag: "${se}"`);break}case"START":d.startTimeOffset=rJe(se);break;case"MAP":{const he=new bu(se,d);if(S.duration){const ce=new LNe(a,c);oJe(ce,he,r,O),p=ce,S.initSegment=p,p.rawProgramDateTime&&!S.rawProgramDateTime&&(S.rawProgramDateTime=p.rawProgramDateTime)}else{const ce=S.byteRangeEndOffset;if(ce){const me=S.byteRangeStartOffset;F=`${ce-me}@${me}`}else F=null;oJe(S,he,r,O),p=S,I=!0}p.cc=v;break}case"SERVER-CONTROL":{z&&c2(d,ee,A),z=new bu(se),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&&c2(d,ee,A);const he=new bu(se);d.partTarget=he.decimalFloatingPoint("PART-TARGET");break}case"PART":{let he=d.partList;he||(he=d.partList=[]);const ce=y>0?he[he.length-1]:void 0,me=y++,le=new bu(se,d),ve=new Tnn(le,S,c,me,ce);he.push(ve),S.duration+=ve.duration;break}case"PRELOAD-HINT":{const he=new bu(se,d);d.preloadHint=he;break}case"RENDITION-REPORT":{const he=new bu(se,d);d.renditionReports=d.renditionReports||[],d.renditionReports.push(he);break}default:Cc.warn(`line parsed but not handled: ${A}`);break}}}w&&!w.relurl?(u.pop(),_-=w.duration,d.partList&&(d.fragmentHint=w)):d.partList&&(yTe(S,w,h),S.cc=v,d.fragmentHint=S,O&&lJe(S,O,d)),d.targetduration||(d.playlistParsingError=new Error("Missing Target Duration"));const H=u.length,Z=u[0],Y=u[H-1];if(_+=d.skippedSegments*d.targetduration,_>0&&H&&Y){d.averagetargetduration=_/H;const W=Y.sn;d.endSN=W!=="initSegment"?W:0,d.live||(Y.endList=!0),D>0&&(Vrn(u,D),Z&&h.unshift(Z))}return d.fragmentHint&&(_+=d.fragmentHint.duration),d.totalduration=_,h.length&&d.dateRangeTagCount&&Z&&RNt(h,d),d.endCC=v,d}}function RNt(s,t){let n=s.length;if(!n)if(t.hasProgramDateTime){const o=t.fragments[t.fragments.length-1];s.push(o),n++}else return;const r=s[n-1],a=t.live?1/0:t.totalduration,i=Object.keys(t.dateRanges);for(let o=i.length;o--;){const c=t.dateRanges[i[o]],d=c.startDate.getTime();c.tagAnchor=r.ref;for(let u=n;u--;){var l;if(((l=s[u])==null?void 0:l.sn)=o||r===0){var l;const c=(((l=n[r+1])==null?void 0:l.start)||a)-i.start;if(t<=o+c*1e3){const d=n[r].sn-s.startSN;if(d<0)return-1;const u=s.fragments;if(u.length>n.length){const p=(n[r+1]||u[u.length-1]).sn-s.startSN;for(let f=p;f>d;f--){const y=u[f].programDateTime;if(t>=y&&tr);["video","audio","text"].forEach(r=>{const a=n.filter(i=>f8e(i,r));a.length&&(t[`${r}Codec`]=a.map(i=>i.split("/")[0]).join(","),n=n.filter(i=>a.indexOf(i)===-1))}),t.unknownCodecs=n}function iJe(s,t,n){const r=t[n];r&&(s[n]=r)}function Vrn(s,t){let n=s[t];for(let r=t;r--;){const a=s[r];if(!a)return;a.programDateTime=n.programDateTime-a.duration*1e3,n=a}}function yTe(s,t,n){s.rawProgramDateTime?n.push(s):t!=null&&t.programDateTime&&(s.programDateTime=t.endProgramDateTime)}function oJe(s,t,n,r){s.relurl=t.URI,t.BYTERANGE&&s.setByteRange(t.BYTERANGE),s.level=n,s.sn="initSegment",r&&(s.levelkeys=r),s.initSegment=null}function lJe(s,t,n){s.levelkeys=t;const{encryptedFragments:r}=n;(!r.length||r[r.length-1].levelkeys!==t)&&Object.keys(t).some(a=>t[a].isCommonEncryption)&&r.push(s)}function c2(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must not appear more than once (${n[0]})`)}function cJe(s,t,n){s.playlistParsingError=new Error(`#EXT-X-${t} must appear before the first Media Segment (${n[0]})`)}function zNe(s,t){const n=t.startPTS;if(Pa(n)){let r=0,a;t.sn>s.sn?(r=n-s.start,a=s):(r=s.start-n,a=t),a.duration!==r&&a.setDuration(r)}else t.sn>s.sn?s.cc===t.cc&&s.minEndPTS?t.setStart(s.start+(s.minEndPTS-s.start)):t.setStart(s.start+s.duration):t.setStart(Math.max(s.start-t.duration,0))}function ONt(s,t,n,r,a,i,l){r-n<=0&&(l.warn("Fragment should have a positive duration",t),r=n+t.duration,i=a+t.duration);let c=n,d=r;const u=t.startPTS,h=t.endPTS;if(Pa(u)){const j=Math.abs(u-n);s&&j>s.totalduration?l.warn(`media timestamps and playlist times differ by ${j}s for level ${t.level} ${s.url}`):Pa(t.deltaPTS)?t.deltaPTS=Math.max(j,t.deltaPTS):t.deltaPTS=j,c=Math.max(n,u),n=Math.min(n,u),a=t.startDTS!==void 0?Math.min(a,t.startDTS):a,d=Math.min(r,h),r=Math.max(r,h),i=t.endDTS!==void 0?Math.max(i,t.endDTS):i}const p=n-t.start;t.start!==0&&t.setStart(n),t.setDuration(r-t.start),t.startPTS=n,t.maxStartPTS=c,t.startDTS=a,t.endPTS=r,t.minEndPTS=d,t.endDTS=i;const f=t.sn;if(!s||fs.endSN)return 0;let y;const _=f-s.startSN,v=s.fragments;for(v[_]=t,y=_;y>0;y--)zNe(v[y],v[y-1]);for(y=_;y=0;u--){const h=a[u].initSegment;if(h){r=h;break}}s.fragmentHint&&delete s.fragmentHint.endPTS;let i;Krn(s,t,(u,h,p,f)=>{if((!t.startCC||t.skippedSegments)&&h.cc!==u.cc){const y=u.cc-h.cc;for(let _=p;_{var h;u&&(!u.initSegment||u.initSegment.relurl===((h=r)==null?void 0:h.relurl))&&(u.initSegment=r)}),t.skippedSegments){if(t.deltaUpdateFailed=l.some(u=>!u),t.deltaUpdateFailed){n.warn("[level-helper] Previous playlist missing segments skipped in delta playlist");for(let u=t.skippedSegments;u--;)l.shift();t.startSN=l[0].sn}else{t.canSkipDateRanges&&(t.dateRanges=Grn(s.dateRanges,t,n));const u=s.fragments.filter(h=>h.rawProgramDateTime);if(s.hasProgramDateTime&&!t.hasProgramDateTime)for(let h=1;h{h.elementaryStreams=u.elementaryStreams,h.stats=u.stats}),i?ONt(t,i,i.startPTS,i.endPTS,i.startDTS,i.endDTS,n):FNt(s,t),l.length&&(t.totalduration=t.edge-l[0].start),t.driftStartTime=s.driftStartTime,t.driftStart=s.driftStart;const d=t.advancedDateTime;if(t.advanced&&d){const u=t.edge;t.driftStart||(t.driftStartTime=d,t.driftStart=u),t.driftEndTime=d,t.driftEnd=u}else t.driftEndTime=s.driftEndTime,t.driftEnd=s.driftEnd,t.advancedDateTime=s.advancedDateTime;t.requestScheduled===-1&&(t.requestScheduled=s.requestScheduled)}function Grn(s,t,n){const{dateRanges:r,recentlyRemovedDateranges:a}=t,i=Wc({},s);a&&a.forEach(c=>{delete i[c]});const o=Object.keys(i).length;return o?(Object.keys(r).forEach(c=>{const d=i[c],u=new MNt(r[c].attr,d);u.isValid?(i[c]=u,d||(u.tagOrder+=o)):n.warn(`Ignoring invalid Playlist Delta Update DATERANGE tag: "${rd(r[c].attr)}"`)}),i):r}function Wrn(s,t,n){if(s&&t){let r=0;for(let a=0,i=s.length;a<=i;a++){const l=s[a],o=t[a+r];l&&o&&l.index===o.index&&l.fragment.sn===o.fragment.sn?n(l,o):r--}}}function Krn(s,t,n){const r=t.skippedSegments,a=Math.max(s.startSN,t.startSN)-t.startSN,i=(s.fragmentHint?1:0)+(r?t.endSN:Math.min(s.endSN,t.endSN))-t.startSN,l=t.startSN-s.startSN,o=t.fragmentHint?t.fragments.concat(t.fragmentHint):t.fragments,c=s.fragmentHint?s.fragments.concat(s.fragmentHint):s.fragments;for(let d=a;d<=i;d++){const u=c[l+d];let h=o[d];if(r&&!h&&u&&(h=t.fragments[d]=u),u&&h){n(u,h,d,o);const p=u.relurl,f=h.relurl;if(p&&Yrn(p,f)){t.playlistParsingError=dJe(`media sequence mismatch ${h.sn}:`,s,t,u,h);return}else if(u.cc!==h.cc){t.playlistParsingError=dJe(`discontinuity sequence mismatch (${u.cc}!=${h.cc})`,s,t,u,h);return}}}}function dJe(s,t,n,r,a){return new Error(`${s} ${a.url} Playlist starting @${t.startSN} ${t.m3u8} Playlist starting @${n.startSN} ${n.m3u8}`)}function FNt(s,t,n=!0){const r=t.startSN+t.skippedSegments-s.startSN,a=s.fragments,i=r>=0;let l=0;if(i&&rt){const i=r[r.length-1].duration*1e3;i{var r;(r=t.details)==null||r.fragments.forEach(a=>{a.level=n,a.initSegment&&(a.initSegment.level=n)})})}function Yrn(s,t){return s!==t&&t?hJe(s)!==hJe(t):!1}function hJe(s){return s.replace(/\?[^?]*$/,"")}function wz(s,t){for(let r=0,a=s.length;rs.startCC)}function mJe(s,t){const n=s.start+t;s.startPTS=n,s.setStart(n),s.endPTS=n+s.duration}function qNt(s,t){const n=t.fragments;for(let r=0,a=n.length;r{const{config:l,fragCurrent:o,media:c,mediaBuffer:d,state:u}=this,h=c?c.currentTime:0,p=bo.bufferInfo(d||c,h,l.maxBufferHole),f=!p.len;if(this.log(`Media seeking to ${Pa(h)?h.toFixed(3):h}, state: ${u}, ${f?"out of":"in"} buffer`),this.state===cr.ENDED)this.resetLoadingState();else if(o){const y=l.maxFragLookUpTolerance,_=o.start-y,v=o.start+o.duration+y;if(f||vp.end){const j=h>v;(h<_||j)&&(j&&o.loader&&(this.log(`Cancelling fragment load for seek (sn: ${o.sn})`),o.abortRequests(),this.resetLoadingState()),this.fragPrevious=null)}}if(c){this.fragmentTracker.removeFragmentsInRange(h,1/0,this.playlistType,!0);const y=this.lastCurrentTime;if(h>y&&(this.lastCurrentTime=h),!this.loadingParts){const _=Math.max(p.end,h),v=this.shouldLoadParts(this.getLevelDetails(),_);v&&(this.log(`LL-Part loading ON after seeking to ${h.toFixed(2)} with buffer @${_.toFixed(2)}`),this.loadingParts=v)}}this.hls.hasEnoughToStart||(this.log(`Setting ${f?"startPosition":"nextLoadPosition"} to ${h} for seek without enough to start`),this.nextLoadPosition=h,f&&(this.startPosition=h)),f&&this.state===cr.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 Srn(t.config),this.keyLoader=r,this.fragmentTracker=n,this.config=t.config,this.decrypter=new y8e(t.config)}registerListeners(){const{hls:t}=this;t.on(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(jt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(jt.ERROR,this.onError,this)}doTick(){this.onTickEnd()}onTickEnd(){}startLoad(t){}stopLoad(){if(this.state===cr.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=cr.STOPPED}get startPositionValue(){const{nextLoadPosition:t,startPosition:n}=this;return n===-1&&t?t:n}get bufferingEnabled(){return this.buffering}pauseBuffering(){this.buffering=!1}resumeBuffering(){this.buffering=!0}get inFlightFrag(){return{frag:this.fragCurrent,state:this.state}}_streamEnded(t,n){if(n.live||!this.media)return!1;const r=t.end||0,a=this.config.timelineOffset||0;if(r<=a)return!1;const i=t.buffered;this.config.maxBufferHole&&i&&i.length>1&&(t=bo.bufferedInfo(i,t.start,0));const l=t.nextStart;if(l&&l>a&&l{const l=i.frag;if(this.fragContextChanged(l)){this.warn(`${l.type} sn: ${l.sn}${i.part?" part: "+i.part.index:""} of ${this.fragInfo(l,!1,i.part)}) was dropped during download.`),this.fragmentTracker.removeFragment(l);return}l.stats.chunkCount++,this._handleFragmentLoadProgress(i)};this._doFragLoad(t,n,r,a).then(i=>{if(!i)return;const l=this.state,o=i.frag;if(this.fragContextChanged(o)){(l===cr.FRAG_LOADING||!this.fragCurrent&&l===cr.PARSING)&&(this.fragmentTracker.removeFragment(o),this.state=cr.IDLE);return}"payload"in i&&(this.log(`Loaded ${o.type} sn: ${o.sn} of ${this.playlistLabel()} ${o.level}`),this.hls.trigger(jt.FRAG_LOADED,i)),this._handleFragmentLoadComplete(i)}).catch(i=>{this.state===cr.STOPPED||this.state===cr.ERROR||(this.warn(`Frag error: ${(i==null?void 0:i.message)||i}`),this.resetFragmentLoading(t))})}clearTrackerIfNeeded(t){var n;const{fragmentTracker:r}=this;if(r.getState(t)===Mm.APPENDING){const i=t.type,l=this.getFwdBufferInfo(this.mediaBuffer,i),o=Math.max(t.duration,l?l.len:this.config.maxBufferLength),c=this.backtrackFragment;((c?t.sn-c.sn:0)===1||this.reduceMaxBufferLength(o,t.duration))&&r.removeFragment(t)}else((n=this.mediaBuffer)==null?void 0:n.buffered.length)===0?r.removeAllFragments():r.hasParts(t.type)&&(r.detectPartialFragments({frag:t,part:null,stats:t.stats,id:t.type}),r.getState(t)===Mm.PARTIAL&&r.removeFragment(t))}checkLiveUpdate(t){if(t.updated&&!t.live){const n=t.fragments[t.fragments.length-1];this.fragmentTracker.detectPartialFragments({frag:n,part:null,stats:n.stats,id:n.type})}t.fragments[0]||(t.deltaUpdateFailed=!0)}waitForLive(t){const n=t.details;return(n==null?void 0:n.live)&&n.type!=="EVENT"&&(this.levelLastLoaded!==t||n.expired)}flushMainBuffer(t,n,r=null){if(!(t-n))return;const a={startOffset:t,endOffset:n,type:r};this.hls.trigger(jt.BUFFER_FLUSHING,a)}_loadInitSegment(t,n){this._doFragLoad(t,n).then(r=>{const a=r==null?void 0:r.frag;if(!a||this.fragContextChanged(a)||!this.levels)throw new Error("init load aborted");return r}).then(r=>{const{hls:a}=this,{frag:i,payload:l}=r,o=i.decryptdata;if(l&&l.byteLength>0&&o!=null&&o.key&&o.iv&&$L(o.method)){const c=self.performance.now();return this.decrypter.decrypt(new Uint8Array(l),o.key.buffer,o.iv.buffer,b8e(o.method)).catch(d=>{throw a.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.FRAG_DECRYPT_ERROR,fatal:!1,error:d,reason:d.message,frag:i}),d}).then(d=>{const u=self.performance.now();return a.trigger(jt.FRAG_DECRYPTED,{frag:i,payload:d,stats:{tstart:c,tdecrypt:u}}),r.payload=d,this.completeInitSegmentLoad(r)})}return this.completeInitSegmentLoad(r)}).catch(r=>{this.state===cr.STOPPED||this.state===cr.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}completeInitSegmentLoad(t){const{levels:n}=this;if(!n)throw new Error("init load aborted, missing levels");const r=t.frag.stats;this.state!==cr.STOPPED&&(this.state=cr.IDLE),t.frag.data=new Uint8Array(t.payload),r.parsing.start=r.buffering.start=self.performance.now(),r.parsing.end=r.buffering.end=self.performance.now(),this.tick()}unhandledEncryptionError(t,n){var r,a;const i=t.tracks;if(i&&!n.encrypted&&((r=i.audio)!=null&&r.encrypted||(a=i.video)!=null&&a.encrypted)&&(!this.config.emeEnabled||!this.keyLoader.emeController)){const l=this.media,o=new Error(`Encrypted track with no key in ${this.fragInfo(n)} (media ${l?"attached mediaKeys: "+l.mediaKeys:"detached"})`);return this.warn(o.message),!l||l.mediaKeys?!1:(this.hls.trigger(jt.ERROR,{type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_NO_KEYS,fatal:!1,error:o,frag:n}),this.resetTransmuxer(),!0)}return!1}fragContextChanged(t){const{fragCurrent:n}=this;return!t||!n||t.sn!==n.sn||t.level!==n.level}fragBufferedComplete(t,n){const r=this.mediaBuffer?this.mediaBuffer:this.media;if(this.log(`Buffered ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)} > buffer:${r?Xrn.toString(bo.getBuffered(r)):"(detached)"})`),Nh(t)){var a;if(t.type!==Wa.SUBTITLE){const l=t.elementaryStreams;if(!Object.keys(l).some(o=>!!l[o])){this.state=cr.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=cr.IDLE}_handleFragmentLoadComplete(t){const{transmuxer:n}=this;if(!n)return;const{frag:r,part:a,partsLoaded:i}=t,l=!i||i.length===0||i.some(c=>!c),o=new v8e(r.level,r.sn,r.stats.chunkCount+1,0,a?a.index:-1,!l);n.flush(o)}_handleFragmentLoadProgress(t){}_doFragLoad(t,n,r=null,a){var i;this.fragCurrent=t;const l=n.details;if(!this.levels||!l)throw new Error(`frag load aborted, missing level${l?"":" detail"}s`);let o=null;if(t.encrypted&&!((i=t.decryptdata)!=null&&i.key)){if(this.log(`Loading key for ${t.sn} of [${l.startSN}-${l.endSN}], ${this.playlistLabel()} ${t.level}`),this.state=cr.KEY_LOADING,this.fragCurrent=t,o=this.keyLoader.load(t).then(p=>{if(!this.fragContextChanged(p.frag))return this.hls.trigger(jt.KEY_LOADED,p),this.state===cr.KEY_LOADING&&(this.state=cr.IDLE),p}),this.hls.trigger(jt.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(Nh(t)&&(!c||t.sn!==c.sn)){const p=this.shouldLoadParts(n.details,t.end);p!==this.loadingParts&&(this.log(`LL-Part loading ${p?"ON":"OFF"} loading sn ${c==null?void 0:c.sn}->${t.sn}`),this.loadingParts=p)}if(r=Math.max(t.start,r||0),this.loadingParts&&Nh(t)){const p=l.partList;if(p&&a){r>l.fragmentEnd&&l.fragmentHint&&(t=l.fragmentHint);const f=this.getNextPart(p,t,r);if(f>-1){const y=p[f];t=this.fragCurrent=y.fragment,this.log(`Loading ${t.type} sn: ${t.sn} part: ${y.index} (${f}/${p.length-1}) of ${this.fragInfo(t,!1,y)}) cc: ${t.cc} [${l.startSN}-${l.endSN}], target: ${parseFloat(r.toFixed(3))}`),this.nextLoadPosition=y.start+y.duration,this.state=cr.FRAG_LOADING;let _;return o?_=o.then(v=>!v||this.fragContextChanged(v.frag)?null:this.doFragPartsLoad(t,y,n,a)).catch(v=>this.handleFragLoadError(v)):_=this.doFragPartsLoad(t,y,n,a).catch(v=>this.handleFragLoadError(v)),this.hls.trigger(jt.FRAG_LOADING,{frag:t,part:y,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING parts")):_}else if(!t.url||this.loadedEndOfParts(p,r))return Promise.resolve(null)}}if(Nh(t)&&this.loadingParts){var d;this.log(`LL-Part loading OFF after next part miss @${r.toFixed(2)} Check buffer at sn: ${t.sn} loaded parts: ${(d=l.partList)==null?void 0:d.filter(p=>p.loaded).map(p=>`[${p.start}-${p.end}]`)}`),this.loadingParts=!1}else if(!t.url)return Promise.resolve(null);this.log(`Loading ${t.type} sn: ${t.sn} of ${this.fragInfo(t,!1)}) cc: ${t.cc} ${"["+l.startSN+"-"+l.endSN+"]"}, target: ${parseFloat(r.toFixed(3))}`),Pa(t.sn)&&!this.bitrateTest&&(this.nextLoadPosition=t.start+t.duration),this.state=cr.FRAG_LOADING;const u=this.config.progressive&&t.type!==Wa.SUBTITLE;let h;return u&&o?h=o.then(p=>!p||this.fragContextChanged(p.frag)?null:this.fragmentLoader.load(t,a)).catch(p=>this.handleFragLoadError(p)):h=Promise.all([this.fragmentLoader.load(t,u?a:void 0),o]).then(([p])=>(!u&&a&&a(p),p)).catch(p=>this.handleFragLoadError(p)),this.hls.trigger(jt.FRAG_LOADING,{frag:t,targetBufferTime:r}),this.fragCurrent===null?Promise.reject(new Error("frag load aborted, context changed in FRAG_LOADING")):h}doFragPartsLoad(t,n,r,a){return new Promise((i,l)=>{var o;const c=[],d=(o=r.details)==null?void 0:o.partList,u=h=>{this.fragmentLoader.loadPart(t,h,a).then(p=>{c[h.index]=p;const f=p.part;this.hls.trigger(jt.FRAG_LOADED,p);const y=uJe(r.details,t.sn,h.index+1)||$Nt(d,t.sn,h.index+1);if(y)u(y);else return i({frag:t,part:f,partsLoaded:c})}).catch(l)};u(n)})}handleFragLoadError(t){if("data"in t){const n=t.data;n.frag&&n.details===Mn.INTERNAL_ABORTED?this.handleFragLoadAborted(n.frag,n.part):n.frag&&n.type===ui.KEY_SYSTEM_ERROR?(n.frag.abortRequests(),this.resetStartWhenNotLoaded(),this.resetFragmentLoading(n.frag)):this.hls.trigger(jt.ERROR,n)}else this.hls.trigger(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.INTERNAL_EXCEPTION,err:t,error:t,fatal:!0});return null}_handleTransmuxerFlush(t){const n=this.getCurrentContext(t);if(!n||this.state!==cr.PARSING){!this.fragCurrent&&this.state!==cr.STOPPED&&this.state!==cr.ERROR&&(this.state=cr.IDLE);return}const{frag:r,part:a,level:i}=n,l=self.performance.now();r.stats.parsing.end=l,a&&(a.stats.parsing.end=l);const o=this.getLevelDetails(),d=o&&r.sn>o.endSN||this.shouldLoadParts(o,r.end);d!==this.loadingParts&&(this.log(`LL-Part loading ${d?"ON":"OFF"} after parsing segment ending @${r.end.toFixed(2)}`),this.loadingParts=d),this.updateLevelTiming(r,a,i,t.partial)}shouldLoadParts(t,n){if(this.config.lowLatencyMode){if(!t)return this.loadingParts;if(t.partList){var r;const i=t.partList[0];if(i.fragment.type===Wa.SUBTITLE)return!1;const l=i.end+(((r=t.fragmentHint)==null?void 0:r.duration)||0);if(n>=l){var a;if((this.hls.hasEnoughToStart?((a=this.media)==null?void 0:a.currentTime)||this.lastCurrentTime:this.getLoadPosition())>i.start-i.fragment.duration)return!0}}}return!1}getCurrentContext(t){const{levels:n,fragCurrent:r}=this,{level:a,sn:i,part:l}=t;if(!(n!=null&&n[a]))return this.warn(`Levels object was unset while buffering fragment ${i} of ${this.playlistLabel()} ${a}. The current chunk will not be buffered.`),null;const o=n[a],c=o.details,d=l>-1?uJe(c,i,l):null,u=d?d.fragment:BNt(c,i,r);return u?(r&&r!==u&&(u.stats=r.stats),{frag:u,part:d,level:o}):null}bufferFragmentData(t,n,r,a,i){if(this.state!==cr.PARSING)return;const{data1:l,data2:o}=t;let c=l;if(o&&(c=Gv(l,o)),!c.length)return;const d=this.initPTS[n.cc],u=d?-d.baseTime/d.timescale:void 0,h={type:t.type,frag:n,part:r,chunkMeta:a,offset:u,parent:n.type,data:c};if(this.hls.trigger(jt.BUFFER_APPENDING,h),t.dropped&&t.independent&&!r){if(i)return;this.flushBufferGap(n)}}flushBufferGap(t){const n=this.media;if(!n)return;if(!bo.isBuffered(n,n.currentTime)){this.flushMainBuffer(0,t.start);return}const r=n.currentTime,a=bo.bufferInfo(n,r,0),i=t.duration,l=Math.min(this.config.maxFragLookUpTolerance*2,i*.25),o=Math.max(Math.min(t.start-l,a.end-l),r+l);t.start-o>l&&this.flushMainBuffer(o,t.start)}getFwdBufferInfo(t,n){var r;const a=this.getLoadPosition();if(!Pa(a))return null;const l=this.lastCurrentTime>a||(r=this.media)!=null&&r.paused?0:this.config.maxBufferHole;return this.getFwdBufferInfoAtPos(t,a,n,l)}getFwdBufferInfoAtPos(t,n,r,a){const i=bo.bufferInfo(t,n,a);if(i.len===0&&i.nextStart!==void 0){const l=this.fragmentTracker.getBufferedFrag(n,r);if(l&&(i.nextStart<=l.end||l.gap)){const o=Math.max(Math.min(i.nextStart,l.end)-n,a);return bo.bufferInfo(t,n,o)}}return i}getMaxBufferLength(t){const{config:n}=this;let r;return t?r=Math.max(8*n.maxBufferSize/t,n.maxBufferLength):r=n.maxBufferLength,Math.min(r,n.maxMaxBufferLength)}exceedsMaxBuffer(t,n,r){const a=t.nextStart;if(a&&r.start>a){const i=t.buffered;if(i){let l=t.len;const o=t.bufferedIndex;for(let c=i.length-1;c>o;c--)i[c].start=n}}return!1}reduceMaxBufferLength(t,n){const r=this.config,a=Math.max(Math.min(t-n,r.maxBufferLength),n),i=Math.max(t-n*3,r.maxMaxBufferLength/2,a);return i>=a?(r.maxMaxBufferLength=i,this.warn(`Reduce max buffer length to ${i}s`),!0):!1}getAppendedFrag(t,n=Wa.MAIN){const r=this.fragmentTracker?this.fragmentTracker.getAppendedFrag(t,n):null;return r&&"fragment"in r?r.fragment:r}getNextFragment(t,n){const r=n.fragments,a=r.length;if(!a)return null;const{config:i}=this,l=n.fragmentStart,o=i.lowLatencyMode&&!!n.partList;let c=null;if(n.live){const h=i.initialLiveManifestSize;if(a=l?(v=f,j=f===p?"config":"next load start"):y!==null?(v=y,j="live edge"):(v=t,j="buffer pos"),v<_&&(v=_,j="live frag start"),v=i){const c=l.sn;return this.loopSn!==c&&(this.log(`buffer full after gaps in "${a}" playlist starting at sn: ${c}`),this.loopSn=c),null}}return this.loopSn=void 0,l}get primaryPrefetch(){if(pJe(this.config)){var t;if((t=this.hls.interstitialsManager)==null||(t=t.playingItem)==null?void 0:t.event)return!0}return!1}filterReplacedPrimary(t,n){if(!t)return t;if(pJe(this.config)&&t.type!==Wa.SUBTITLE){const r=this.hls.interstitialsManager,a=r==null?void 0:r.bufferingItem;if(a){const l=a.event;if(l){if(l.appendInPlace||Math.abs(t.start-a.start)>1||a.start===0)return null}else if(t.end<=a.start&&(n==null?void 0:n.live)===!1||t.start>a.end&&a.nextEvent&&(a.nextEvent.appendInPlace||t.start-a.end>1))return null}const i=r==null?void 0:r.playerQueue;if(i)for(let l=i.length;l--;){const o=i[l].interstitial;if(o.appendInPlace&&t.start>=o.startTime&&t.end<=o.resumeTime)return null}}return t}mapToInitFragWhenRequired(t){return t!=null&&t.initSegment&&!t.initSegment.data&&!this.bitrateTest?t.initSegment:t}getNextPart(t,n,r){let a=-1,i=!1,l=!0;for(let o=0,c=t.length;o-1&&rr.start)return!0}return!1}getInitialLiveFragment(t){const n=t.fragments,r=this.fragPrevious;let a=null;if(r){if(t.hasProgramDateTime&&(a=prn(n,r.endProgramDateTime,this.config.maxFragLookUpTolerance),a&&this.log(`Live playlist, switching playlist, load frag with same PDT: ${r.programDateTime}`)),!a){const i=r.sn+1;if(i>=t.startSN&&i<=t.endSN){const l=n[i-t.startSN];r.cc===l.cc&&(a=l,this.log(`Live playlist, switching playlist, load frag with next SN: ${a.sn}`))}a||(a=SNt(t,r.cc,r.end),a&&this.log(`Live playlist, switching playlist, load frag with same CC: ${a.sn}`))}}else{const i=this.hls.liveSyncPosition;i!==null&&(a=this.getFragmentAtPosition(i,this.bitrateTest?t.fragmentEnd:t.edge,t))}return a}getFragmentAtPosition(t,n,r){const{config:a}=this;let{fragPrevious:i}=this,{fragments:l,endSN:o}=r;const{fragmentHint:c}=r,{maxFragLookUpTolerance:d}=a,u=r.partList,h=!!(this.loadingParts&&u!=null&&u.length&&c);h&&!this.bitrateTest&&u[u.length-1].fragment.sn===c.sn&&(l=l.concat(c),o=c.sn);let p;if(tn-d||(f=this.media)!=null&&f.paused||!this.startFragRequested?0:d;p=LM(i,l,t,_)}else p=l[l.length-1];if(p){const y=p.sn-r.startSN,_=this.fragmentTracker.getState(p);if((_===Mm.OK||_===Mm.PARTIAL&&p.gap)&&(i=p),i&&p.sn===i.sn&&(!h||u[0].fragment.sn>p.sn||!r.live)&&p.level===i.level){const j=l[y+1];p.sn${t.startSN} fragments: ${a}`),c}return i}waitForCdnTuneIn(t){return t.live&&t.canBlockReload&&t.partTarget&&t.tuneInGoal>Math.max(t.partHoldBack,t.partTarget*3)}setStartPosition(t,n){let r=this.startPosition;r=0&&(r=this.nextLoadPosition),r}handleFragLoadAborted(t,n){this.transmuxer&&t.type===this.playlistType&&Nh(t)&&t.stats.aborted&&(this.log(`Fragment ${t.sn}${n?" part "+n.index:""} of ${this.playlistLabel()} ${t.level} was aborted`),this.resetFragmentLoading(t))}resetFragmentLoading(t){(!this.fragCurrent||!this.fragContextChanged(t)&&this.state!==cr.FRAG_LOADING_WAITING_RETRY)&&(this.state=cr.IDLE)}onFragmentOrKeyLoadError(t,n){var r;if(n.chunkMeta&&!n.frag){const j=this.getCurrentContext(n.chunkMeta);j&&(n.frag=j.frag)}const a=n.frag;if(!a||a.type!==t||!this.levels)return;if(this.fragContextChanged(a)){var i;this.warn(`Frag load error must match current frag to retry ${a.url} > ${(i=this.fragCurrent)==null?void 0:i.url}`);return}const l=n.details===Mn.FRAG_GAP;l&&this.fragmentTracker.fragBuffered(a,!0);const o=n.errorAction;if(!o){this.state=cr.ERROR;return}const{action:c,flags:d,retryCount:u=0,retryConfig:h}=o,p=!!h,f=p&&c===ef.RetryRequest,y=p&&!o.resolved&&d===O0.MoveAllAlternatesMatchingHost,_=(r=this.hls.latestLevelDetails)==null?void 0:r.live;if(!f&&y&&Nh(a)&&!a.endList&&_&&!TNt(n))this.resetFragmentErrors(t),this.treatAsGap(a),o.resolved=!0;else if((f||y)&&u=n||r&&!fTe(0))&&(r&&this.log("Connection restored (online)"),this.resetStartWhenNotLoaded(),this.state=cr.IDLE)}reduceLengthAndFlushBuffer(t){if(this.state===cr.PARSING||this.state===cr.PARSED){const n=t.frag,r=t.parent,a=this.getFwdBufferInfo(this.mediaBuffer,r),i=a&&a.len>.5;i&&this.reduceMaxBufferLength(a.len,(n==null?void 0:n.duration)||10);const l=!i;return l&&this.warn(`Buffer full error while media.currentTime (${this.getLoadPosition()}) is not buffered, flush ${r} buffer`),n&&(this.fragmentTracker.removeFragment(n),this.nextLoadPosition=n.start),this.resetLoadingState(),l}return!1}resetFragmentErrors(t){t===Wa.AUDIO&&(this.fragCurrent=null),this.hls.hasEnoughToStart||(this.startFragRequested=!1),this.state!==cr.STOPPED&&(this.state=cr.IDLE)}afterBufferFlushed(t,n,r){if(!t)return;const a=bo.getBuffered(t);this.fragmentTracker.detectEvictedFragments(n,a,r),this.state===cr.ENDED&&this.resetLoadingState()}resetLoadingState(){this.log("Reset loading state"),this.fragCurrent=null,this.fragPrevious=null,this.state!==cr.STOPPED&&(this.state=cr.IDLE)}resetStartWhenNotLoaded(){if(!this.hls.hasEnoughToStart){this.startFragRequested=!1;const t=this.levelLastLoaded,n=t?t.details:null;n!=null&&n.live?(this.log("resetting startPosition for live start"),this.startPosition=-1,this.setStartPosition(n,n.fragmentStart),this.resetLoadingState()):this.nextLoadPosition=this.startPosition}}resetWhenMissingContext(t){this.log(`Loading context changed while buffering sn ${t.sn} of ${this.playlistLabel()} ${t.level===-1?"":t.level}. This chunk will not be buffered.`),this.removeUnbufferedFrags(),this.resetStartWhenNotLoaded(),this.resetLoadingState()}removeUnbufferedFrags(t=0){this.fragmentTracker.removeFragmentsInRange(t,1/0,this.playlistType,!1,!0)}updateLevelTiming(t,n,r,a){const i=r.details;if(!i){this.warn("level.details undefined");return}if(!Object.keys(t.elementaryStreams).reduce((c,d)=>{const u=t.elementaryStreams[d];if(u){const h=u.endPTS-u.startPTS;if(h<=0)return this.warn(`Could not parse fragment ${t.sn} ${d} duration reliably (${h})`),c||!1;const p=a?0:ONt(i,t,u.startPTS,u.endPTS,u.startDTS,u.endDTS,this);return this.hls.trigger(jt.LEVEL_PTS_UPDATED,{details:i,level:r,drift:p,type:d,frag:t,start:u.startPTS,end:u.endPTS}),!0}return c},!1)){var o;const c=((o=this.transmuxer)==null?void 0:o.error)===null;if((r.fragmentError===0||c&&(r.fragmentError<2||t.endList))&&this.treatAsGap(t,r),c){const d=new Error(`Found no media in fragment ${t.sn} of ${this.playlistLabel()} ${t.level} resetting transmuxer to fallback to playlist timing`);if(this.warn(d.message),this.hls.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.FRAG_PARSING_ERROR,fatal:!1,error:d,frag:t,reason:`Found no media in msn ${t.sn} of ${this.playlistLabel()} "${r.url}"`}),!this.hls)return;this.resetTransmuxer()}}this.state=cr.PARSED,this.log(`Parsed ${t.type} sn: ${t.sn}${n?" part: "+n.index:""} of ${this.fragInfo(t,!1,n)})`),this.hls.trigger(jt.FRAG_PARSED,{frag:t,part:n})}playlistLabel(){return this.playlistType===Wa.MAIN?"level":"track"}fragInfo(t,n=!0,r){var a,i;return`${this.playlistLabel()} ${t.level} (${r?"part":"frag"}:[${((a=n&&!r?t.startPTS:(r||t).start)!=null?a:NaN).toFixed(3)}-${((i=n&&!r?t.endPTS:(r||t).end)!=null?i:NaN).toFixed(3)}]${r&&t.type==="main"?"INDEPENDENT="+(r.independent?"YES":"NO"):""}`}treatAsGap(t,n){n&&n.fragmentError++,t.gap=!0,this.fragmentTracker.removeFragment(t),this.fragmentTracker.fragBuffered(t,!0)}resetTransmuxer(){var t;(t=this.transmuxer)==null||t.reset()}recoverWorkerError(t){t.event==="demuxerWorker"&&(this.fragmentTracker.removeAllFragments(),this.transmuxer&&(this.transmuxer.destroy(),this.transmuxer=null),this.resetStartWhenNotLoaded(),this.resetLoadingState())}set state(t){const n=this._state;n!==t&&(this._state=t,this.log(`${n}->${t}`))}get state(){return this._state}}function pJe(s){return!!s.interstitialsController&&s.enableInterstitialPlayback!==!1}class HNt{constructor(){this.chunks=[],this.dataLength=0}push(t){this.chunks.push(t),this.dataLength+=t.length}flush(){const{chunks:t,dataLength:n}=this;let r;if(t.length)t.length===1?r=t[0]:r=Jrn(t,n);else return new Uint8Array(0);return this.reset(),r}reset(){this.chunks.length=0,this.dataLength=0}}function Jrn(s,t){const n=new Uint8Array(t);let r=0;for(let a=0;a0)return s.subarray(n,n+r)}function ian(s,t,n,r){const a=[96e3,88200,64e3,48e3,44100,32e3,24e3,22050,16e3,12e3,11025,8e3,7350],i=t[n+2],l=i>>2&15;if(l>12){const f=new Error(`invalid ADTS sampling index:${l}`);s.emit(jt.ERROR,jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.FRAG_PARSING_ERROR,fatal:!0,error:f,reason:f.message});return}const o=(i>>6&3)+1,c=t[n+3]>>6&3|(i&1)<<2,d="mp4a.40."+o,u=a[l];let h=l;(o===5||o===29)&&(h-=3);const p=[o<<3|(h&14)>>1,(h&1)<<7|c<<3];return Cc.log(`manifest codec:${r}, parsed codec:${d}, channels:${c}, rate:${u} (ADTS object type:${o} sampling index:${l})`),{config:p,samplerate:u,channelCount:c,codec:d,parsedCodec:d,manifestCodec:r}}function WNt(s,t){return s[t]===255&&(s[t+1]&246)===240}function KNt(s,t){return s[t+1]&1?7:9}function k8e(s,t){return(s[t+3]&3)<<11|s[t+4]<<3|(s[t+5]&224)>>>5}function oan(s,t){return t+5=s.length)return!1;const r=k8e(s,t);if(r<=n)return!1;const a=t+r;return a===s.length||Vge(s,a)}return!1}function YNt(s,t,n,r,a){if(!s.samplerate){const i=ian(t,n,r,a);if(!i)return;Wc(s,i)}}function ZNt(s){return 1024*9e4/s}function dan(s,t){const n=KNt(s,t);if(t+n<=s.length){const r=k8e(s,t)-n;if(r>0)return{headerLength:n,frameLength:r}}}function QNt(s,t,n,r,a){const i=ZNt(s.samplerate),l=r+a*i,o=dan(t,n);let c;if(o){const{frameLength:h,headerLength:p}=o,f=p+h,y=Math.max(0,n+f-t.length);y?(c=new Uint8Array(f-p),c.set(t.subarray(n+p,t.length),0)):c=t.subarray(n+p,n+f);const _={unit:c,pts:l};return y||s.samples.push(_),{sample:_,length:f,missing:y}}const d=t.length-n;return c=new Uint8Array(d),c.set(t.subarray(n,t.length),0),{sample:{unit:c,pts:l},length:d,missing:-1}}function uan(s,t){return N8e(s,t)&&G1e(s,t+6)+10<=s.length-t}function han(s){return s instanceof ArrayBuffer?s:s.byteOffset==0&&s.byteLength==s.buffer.byteLength?s.buffer:new Uint8Array(s).buffer}function $Ne(s,t=0,n=1/0){return man(s,t,n,Uint8Array)}function man(s,t,n,r){const a=pan(s);let i=1;"BYTES_PER_ELEMENT"in r&&(i=r.BYTES_PER_ELEMENT);const l=fan(s)?s.byteOffset:0,o=(l+s.byteLength)/i,c=(l+t)/i,d=Math.floor(Math.max(0,Math.min(c,o))),u=Math.floor(Math.min(d+Math.max(n,0),o));return new r(a,d,u-d)}function pan(s){return s instanceof ArrayBuffer?s:s.buffer}function fan(s){return s&&s.buffer instanceof ArrayBuffer&&s.byteLength!==void 0&&s.byteOffset!==void 0}function xan(s){const t={key:s.type,description:"",data:"",mimeType:null,pictureType:null},n=3;if(s.size<2)return;if(s.data[0]!==n){console.log("Ignore frame with unrecognized character encoding");return}const r=s.data.subarray(1).indexOf(0);if(r===-1)return;const a=fy($Ne(s.data,1,r)),i=s.data[2+r],l=s.data.subarray(3+r).indexOf(0);if(l===-1)return;const o=fy($Ne(s.data,3+r,l));let c;return a==="-->"?c=fy($Ne(s.data,4+r+l)):c=han(s.data.subarray(4+r+l)),t.mimeType=a,t.pictureType=i,t.description=o,t.data=c,t}function gan(s){if(s.size<2)return;const t=fy(s.data,!0),n=new Uint8Array(s.data.subarray(t.length+1));return{key:s.type,info:t,data:n.buffer}}function yan(s){if(s.size<2)return;if(s.type==="TXXX"){let n=1;const r=fy(s.data.subarray(n),!0);n+=r.length+1;const a=fy(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=fy(s.data.subarray(1));return{key:s.type,info:"",data:t}}function van(s){if(s.type==="WXXX"){if(s.size<2)return;let n=1;const r=fy(s.data.subarray(n),!0);n+=r.length+1;const a=fy(s.data.subarray(n));return{key:s.type,info:r,data:a}}const t=fy(s.data);return{key:s.type,info:"",data:t}}function ban(s){return s.type==="PRIV"?gan(s):s.type[0]==="W"?van(s):s.type==="APIC"?xan(s):yan(s)}function _an(s){const t=String.fromCharCode(s[0],s[1],s[2],s[3]),n=G1e(s,4),r=10;return{type:t,size:n,data:s.subarray(r,r+n)}}const TG=10,wan=10;function XNt(s){let t=0;const n=[];for(;N8e(s,t);){const r=G1e(s,t+6);s[t+5]>>6&1&&(t+=TG),t+=TG;const a=t+r;for(;t+wan0&&o.samples.push({pts:this.lastPTS,dts:this.lastPTS,data:r,type:G0.audioId3,duration:Number.POSITIVE_INFINITY});a{if(Pa(s))return s*90;const r=n?n.baseTime*9e4/n.timescale:0;return t*9e4+r};let EG=null;const kan=[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],San=[44100,48e3,32e3,22050,24e3,16e3,11025,12e3,8e3],Can=[[0,72,144,12],[0,0,0,0],[0,72,144,12],[0,144,144,12]],Tan=[0,1,1,4];function ekt(s,t,n,r,a){if(n+24>t.length)return;const i=tkt(t,n);if(i&&n+i.frameLength<=t.length){const l=i.samplesPerFrame*9e4/i.sampleRate,o=r+a*l,c={unit:t.subarray(n,n+i.frameLength),pts:o,dts:o};return s.config=[],s.channelCount=i.channelCount,s.samplerate=i.sampleRate,s.samples.push(c),{sample:c,length:i.frameLength,missing:0}}}function tkt(s,t){const n=s[t+1]>>3&3,r=s[t+1]>>1&3,a=s[t+2]>>4&15,i=s[t+2]>>2&3;if(n!==1&&a!==0&&a!==15&&i!==3){const l=s[t+2]>>1&1,o=s[t+3]>>6,c=n===3?3-r:r===3?3:4,d=kan[c*14+a-1]*1e3,h=San[(n===3?0:n===2?1:2)*3+i],p=o===3?1:2,f=Can[n][r],y=Tan[r],_=f*8*y,v=Math.floor(f*d/h+l)*y;if(EG===null){const S=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);EG=S?parseInt(S[1]):0}return!!EG&&EG<=87&&r===2&&d>=224e3&&o===0&&(s[t+3]=s[t+3]|128),{sampleRate:h,channelCount:p,frameLength:v,samplesPerFrame:_}}}function T8e(s,t){return s[t]===255&&(s[t+1]&224)===224&&(s[t+1]&6)!==0}function skt(s,t){return t+1{let n=0,r=5;t+=r;const a=new Uint32Array(1),i=new Uint32Array(1),l=new Uint8Array(1);for(;r>0;){l[0]=s[t];const o=Math.min(r,8),c=8-o;i[0]=4278190080>>>24+c<>c,n=n?n<t.length||t[n]!==11||t[n+1]!==119)return-1;const i=t[n+4]>>6;if(i>=3)return-1;const o=[48e3,44100,32e3][i],c=t[n+4]&63,u=[64,69,96,64,70,96,80,87,120,80,88,120,96,104,144,96,105,144,112,121,168,112,122,168,128,139,192,128,140,192,160,174,240,160,175,240,192,208,288,192,209,288,224,243,336,224,244,336,256,278,384,256,279,384,320,348,480,320,349,480,384,417,576,384,418,576,448,487,672,448,488,672,512,557,768,512,558,768,640,696,960,640,697,960,768,835,1152,768,836,1152,896,975,1344,896,976,1344,1024,1114,1536,1024,1115,1536,1152,1253,1728,1152,1254,1728,1280,1393,1920,1280,1394,1920][c*3+i]*2;if(n+u>t.length)return-1;const h=t[n+6]>>5;let p=0;h===2?p+=2:(h&1&&h!==1&&(p+=2),h&4&&(p+=2));const f=(t[n+6]<<8|t[n+7])>>12-p&1,_=[2,1,2,3,3,4,4,5][h]+f,v=t[n+5]>>3,j=t[n+5]&7,w=new Uint8Array([i<<6|v<<1|j>>2,(j&3)<<6|h<<3|f<<2|c>>4,c<<4&224]),S=1536/o*9e4,A=r+a*S,E=t.subarray(n,n+u);return s.config=w,s.channelCount=_,s.samplerate=o,s.samples.push({unit:E,pts:A}),u}class Ian extends C8e{resetInitSegment(t,n,r,a){super.resetInitSegment(t,n,r,a),this._audioTrack={container:"audio/mpeg",type:"audio",id:2,pid:-1,sequenceNumber:0,segmentCodec:"mp3",samples:[],manifestCodec:n,duration:a,inputTimeScale:9e4,dropped:0}}static probe(t){if(!t)return!1;const n=x$(t,0);let r=(n==null?void 0:n.length)||0;if(n&&t[r]===11&&t[r+1]===119&&S8e(n)!==void 0&&rkt(t,r)<=16)return!1;for(let a=t.length;r{const l=Bnn(i);if(Pan.test(l.schemeIdUri)){const o=xJe(l,n);let c=l.eventDuration===4294967295?Number.POSITIVE_INFINITY:l.eventDuration/l.timeScale;c<=.001&&(c=Number.POSITIVE_INFINITY);const d=l.payload;r.samples.push({data:d,len:d.byteLength,dts:o,pts:o,type:G0.emsg,duration:c})}else if(this.config.enableEmsgKLVMetadata&&l.schemeIdUri.startsWith("urn:misb:KLV:bin:1910.1")){const o=xJe(l,n);r.samples.push({data:l.payload,len:l.payload.byteLength,dts:o,pts:o,type:G0.misbklv,duration:Number.POSITIVE_INFINITY})}})}return r}demuxSampleAes(t,n,r){return Promise.reject(new Error("The MP4 demuxer does not support SAMPLE-AES decryption"))}destroy(){this.config=null,this.remainderData=null,this.videoTrack=this.audioTrack=this.id3Track=this.txtTrack=void 0}}function xJe(s,t){return Pa(s.presentationTime)?s.presentationTime/s.timeScale:t+s.presentationTimeDelta/s.timeScale}class Dan{constructor(t,n,r){this.keyData=void 0,this.decrypter=void 0,this.keyData=r,this.decrypter=new y8e(n,{removePKCS7Padding:!1})}decryptBuffer(t){return this.decrypter.decrypt(t,this.keyData.key.buffer,this.keyData.iv.buffer,P4.cbc)}decryptAacSample(t,n,r){const a=t[n].unit;if(a.length<=16)return;const i=a.subarray(16,a.length-a.length%16),l=i.buffer.slice(i.byteOffset,i.byteOffset+i.length);this.decryptBuffer(l).then(o=>{const c=new Uint8Array(o);a.set(c,16),this.decrypter.isSync()||this.decryptAacSamples(t,n+1,r)}).catch(r)}decryptAacSamples(t,n,r){for(;;n++){if(n>=t.length){r();return}if(!(t[n].unit.length<32)&&(this.decryptAacSample(t,n,r),!this.decrypter.isSync()))return}}getAvcEncryptedData(t){const n=Math.floor((t.length-48)/160)*16+16,r=new Int8Array(n);let a=0;for(let i=32;i{i.data=this.getAvcDecryptedUnit(l,c),this.decrypter.isSync()||this.decryptAvcSamples(t,n,r+1,a)}).catch(a)}decryptAvcSamples(t,n,r,a){if(t instanceof Uint8Array)throw new Error("Cannot decrypt samples of type Uint8Array");for(;;n++,r=0){if(n>=t.length){a();return}const i=t[n].units;for(;!(r>=i.length);r++){const l=i[r];if(!(l.data.length<=48||l.type!==1&&l.type!==5)&&(this.decryptAvcSample(t,n,r,a,l),!this.decrypter.isSync()))return}}}}class ikt{constructor(){this.VideoSample=null}createVideoSample(t,n,r){return{key:t,frame:!1,pts:n,dts:r,units:[],length:0}}getLastNalUnit(t){var n;let r=this.VideoSample,a;if((!r||r.units.length===0)&&(r=t[t.length-1]),(n=r)!=null&&n.units){const i=r.units;a=i[i.length-1]}return a}pushAccessUnit(t,n){if(t.units.length&&t.frame){if(t.pts===void 0){const r=n.samples,a=r.length;if(a){const i=r[a-1];t.pts=i.pts,t.dts=i.dts}else{n.dropped++;return}}n.samples.push(t)}}parseNALu(t,n,r){const a=n.byteLength;let i=t.naluState||0;const l=i,o=[];let c=0,d,u,h,p=-1,f=0;for(i===-1&&(p=0,f=this.getNALuType(n,0),i=0,c=1);c=0){const y={data:n.subarray(p,u),type:f};o.push(y)}else{const y=this.getLastNalUnit(t.samples);y&&(l&&c<=4-l&&y.state&&(y.data=y.data.subarray(0,y.data.byteLength-l)),u>0&&(y.data=Gv(y.data,n.subarray(0,u)),y.state=0))}c=0&&i>=0){const y={data:n.subarray(p,a),type:f,state:i};o.push(y)}if(o.length===0){const y=this.getLastNalUnit(t.samples);y&&(y.data=Gv(y.data,n))}return t.naluState=i,o}}class jz{constructor(t){this.data=void 0,this.bytesAvailable=void 0,this.word=void 0,this.bitsAvailable=void 0,this.data=t,this.bytesAvailable=t.byteLength,this.word=0,this.bitsAvailable=0}loadWord(){const t=this.data,n=this.bytesAvailable,r=t.byteLength-n,a=new Uint8Array(4),i=Math.min(4,n);if(i===0)throw new Error("no bytes available");a.set(t.subarray(r,r+i)),this.word=new DataView(a.buffer).getUint32(0),this.bitsAvailable=i*8,this.bytesAvailable-=i}skipBits(t){let n;t=Math.min(t,this.bytesAvailable*8+this.bitsAvailable),this.bitsAvailable>t?(this.word<<=t,this.bitsAvailable-=t):(t-=this.bitsAvailable,n=t>>3,t-=n<<3,this.bytesAvailable-=n,this.loadWord(),this.word<<=t,this.bitsAvailable-=t)}readBits(t){let n=Math.min(this.bitsAvailable,t);const r=this.word>>>32-n;if(t>32&&Cc.error("Cannot read more than 32 bits at a time"),this.bitsAvailable-=n,this.bitsAvailable>0)this.word<<=n;else if(this.bytesAvailable>0)this.loadWord();else throw new Error("no bits available");return n=t-n,n>0&&this.bitsAvailable?r<>>t)return this.word<<=t,this.bitsAvailable-=t,t;return this.loadWord(),t+this.skipLZ()}skipUEG(){this.skipBits(1+this.skipLZ())}skipEG(){this.skipBits(1+this.skipLZ())}readUEG(){const t=this.skipLZ();return this.readBits(t+1)-1}readEG(){const t=this.readUEG();return 1&t?1+t>>>1:-1*(t>>>1)}readBoolean(){return this.readBits(1)===1}readUByte(){return this.readBits(8)}readUShort(){return this.readBits(16)}readUInt(){return this.readBits(32)}}class Ran extends ikt{parsePES(t,n,r,a){const i=this.parseNALu(t,r.data,a);let l=this.VideoSample,o,c=!1;r.data=null,l&&i.length&&!t.audFound&&(this.pushAccessUnit(l,t),l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),i.forEach(d=>{var u,h;switch(d.type){case 1:{let _=!1;o=!0;const v=d.data;if(c&&v.length>4){const j=this.readSliceType(v);(j===2||j===4||j===7||j===9)&&(_=!0)}if(_){var p;(p=l)!=null&&p.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.frame=!0,l.key=_;break}case 5:o=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 6:{o=!0,p8e(d.data,1,r.pts,n.samples);break}case 7:{var f,y;o=!0,c=!0;const _=d.data,v=this.readSPS(_);if(!t.sps||t.width!==v.width||t.height!==v.height||((f=t.pixelRatio)==null?void 0:f[0])!==v.pixelRatio[0]||((y=t.pixelRatio)==null?void 0:y[1])!==v.pixelRatio[1]){t.width=v.width,t.height=v.height,t.pixelRatio=v.pixelRatio,t.sps=[_];const j=_.subarray(1,4);let w="avc1.";for(let S=0;S<3;S++){let A=j[S].toString(16);A.length<2&&(A="0"+A),w+=A}t.codec=w}break}case 8:o=!0,t.pps=[d.data];break;case 9:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;case 12:o=!0;break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}getNALuType(t,n){return t[n]&31}readSliceType(t){const n=new jz(t);return n.readUByte(),n.readUEG(),n.readUEG()}skipScalingList(t,n){let r=8,a=8,i;for(let l=0;l{var u,h;switch(d.type){case 0:case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 9:l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts)),l.frame=!0,o=!0;break;case 16:case 17:case 18:case 21:if(o=!0,c){var p;(p=l)!=null&&p.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null)}l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 19:case 20:o=!0,(u=l)!=null&&u.frame&&!l.key&&(this.pushAccessUnit(l,t),l=this.VideoSample=null),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0,l.frame=!0;break;case 39:o=!0,p8e(d.data,2,r.pts,n.samples);break;case 32:o=!0,t.vps||(typeof t.params!="object"&&(t.params={}),t.params=Wc(t.params,this.readVPS(d.data)),this.initVPS=d.data),t.vps=[d.data];break;case 33:if(o=!0,c=!0,t.vps!==void 0&&t.vps[0]!==this.initVPS&&t.sps!==void 0&&!this.matchSPS(t.sps[0],d.data)&&(this.initVPS=t.vps[0],t.sps=t.pps=void 0),!t.sps){const f=this.readSPS(d.data);t.width=f.width,t.height=f.height,t.pixelRatio=f.pixelRatio,t.codec=f.codecString,t.sps=[],typeof t.params!="object"&&(t.params={});for(const y in f.params)t.params[y]=f.params[y]}this.pushParameterSet(t.sps,d.data,t.vps),l||(l=this.VideoSample=this.createVideoSample(!0,r.pts,r.dts)),l.key=!0;break;case 34:if(o=!0,typeof t.params=="object"){if(!t.pps){t.pps=[];const f=this.readPPS(d.data);for(const y in f)t.params[y]=f[y]}this.pushParameterSet(t.pps,d.data,t.vps)}break;case 35:o=!0,t.audFound=!0,(h=l)!=null&&h.frame&&(this.pushAccessUnit(l,t),l=null),l||(l=this.VideoSample=this.createVideoSample(!1,r.pts,r.dts));break;default:o=!1;break}l&&o&&l.units.push(d)}),a&&l&&(this.pushAccessUnit(l,t),this.VideoSample=null)}pushParameterSet(t,n,r){(r&&r[0]===this.initVPS||!r&&!t.length)&&t.push(n)}getNALuType(t,n){return(t[n]&126)>>>1}ebsp2rbsp(t){const n=new Uint8Array(t.byteLength);let r=0;for(let a=0;a=2&&t[a]===3&&t[a-1]===0&&t[a-2]===0||(n[r]=t[a],r++);return new Uint8Array(n.buffer,0,r)}pushAccessUnit(t,n){super.pushAccessUnit(t,n),this.initVPS&&(this.initVPS=null)}readVPS(t){const n=new jz(t);n.readUByte(),n.readUByte(),n.readBits(4),n.skipBits(2),n.readBits(6);const r=n.readBits(3),a=n.readBoolean();return{numTemporalLayers:r+1,temporalIdNested:a}}readSPS(t){const n=new jz(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.readBits(4);const r=n.readBits(3);n.readBoolean();const a=n.readBits(2),i=n.readBoolean(),l=n.readBits(5),o=n.readUByte(),c=n.readUByte(),d=n.readUByte(),u=n.readUByte(),h=n.readUByte(),p=n.readUByte(),f=n.readUByte(),y=n.readUByte(),_=n.readUByte(),v=n.readUByte(),j=n.readUByte(),w=[],S=[];for(let je=0;je0)for(let je=r;je<8;je++)n.readBits(2);for(let je=0;je1&&n.readEG();for(let rt=0;rt0&&tt<16?(ve=at[tt-1],ge=Ye[tt-1]):tt===255&&(ve=n.readBits(16),ge=n.readBits(16))}if(n.readBoolean()&&n.readBoolean(),n.readBoolean()&&(n.readBits(3),n.readBoolean(),n.readBoolean()&&(n.readUByte(),n.readUByte(),n.readUByte())),n.readBoolean()&&(n.readUEG(),n.readUEG()),n.readBoolean(),n.readBoolean(),n.readBoolean(),Me=n.readBoolean(),Me&&(n.skipUEG(),n.skipUEG(),n.skipUEG(),n.skipUEG()),n.readBoolean()&&(Ie=n.readBits(32),Ce=n.readBits(32),n.readBoolean()&&n.readUEG(),n.readBoolean())){const Ye=n.readBoolean(),ut=n.readBoolean();let _t=!1;(Ye||ut)&&(_t=n.readBoolean(),_t&&(n.readUByte(),n.readBits(5),n.readBoolean(),n.readBits(5)),n.readBits(4),n.readBits(4),_t&&n.readBits(4),n.readBits(5),n.readBits(5),n.readBits(5));for(let bt=0;bt<=r;bt++){Te=n.readBoolean();const $t=Te||n.readBoolean();let Yt=!1;$t?n.readEG():Yt=n.readBoolean();const Ds=Yt?1:n.readUEG()+1;if(Ye)for(let Ls=0;Ls>je&1)<<31-je)>>>0;let ke=Je.toString(16);return l===1&&ke==="2"&&(ke="6"),{codecString:`hvc1.${Be}${l}.${ke}.${i?"H":"L"}${j}.B0`,params:{general_tier_flag:i,general_profile_idc:l,general_profile_space:a,general_profile_compatibility_flags:[o,c,d,u],general_constraint_indicator_flags:[h,p,f,y,_,v],general_level_idc:j,bit_depth:Z+8,bit_depth_luma_minus8:Z,bit_depth_chroma_minus8:Y,min_spatial_segmentation_idc:le,chroma_format_idc:A,frame_rate:{fixed:Te,fps:Ce/Ie}},width:Re,height:Ae,pixelRatio:[ve,ge]}}readPPS(t){const n=new jz(this.ebsp2rbsp(t));n.readUByte(),n.readUByte(),n.skipUEG(),n.skipUEG(),n.skipBits(2),n.skipBits(3),n.skipBits(2),n.skipUEG(),n.skipUEG(),n.skipEG(),n.skipBits(2),n.readBoolean()&&n.skipUEG(),n.skipEG(),n.skipEG(),n.skipBits(4);const a=n.readBoolean(),i=n.readBoolean();let l=1;return i&&a?l=0:i?l=3:a&&(l=2),{parallelismType:l}}matchSPS(t,n){return String.fromCharCode.apply(null,t).substr(3)===String.fromCharCode.apply(null,n).substr(3)}}const hp=188;class eS{constructor(t,n,r,a){this.logger=void 0,this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.sampleAes=null,this.pmtParsed=!1,this.audioCodec=void 0,this.videoCodec=void 0,this._pmtId=-1,this._videoTrack=void 0,this._audioTrack=void 0,this._id3Track=void 0,this._txtTrack=void 0,this.aacOverFlow=null,this.remainderData=null,this.videoParser=void 0,this.observer=t,this.config=n,this.typeSupported=r,this.logger=a,this.videoParser=null}static probe(t,n){const r=eS.syncOffset(t);return r>0&&n.warn(`MPEG2-TS detected but first sync word found @ offset ${r}`),r!==-1}static syncOffset(t){const n=t.length;let r=Math.min(hp*5,n-hp)+1,a=0;for(;a1&&(l===0&&o>2||c+hp>r))return l}else{if(o)return-1;break}a++}return-1}static createTrack(t,n){return{container:t==="video"||t==="audio"?"video/mp2t":void 0,type:t,id:hNt[t],pid:-1,inputTimeScale:9e4,sequenceNumber:0,samples:[],dropped:0,duration:t==="audio"?n:void 0}}resetInitSegment(t,n,r,a){this.pmtParsed=!1,this._pmtId=-1,this._videoTrack=eS.createTrack("video"),this._videoTrack.duration=a,this._audioTrack=eS.createTrack("audio",a),this._id3Track=eS.createTrack("id3"),this._txtTrack=eS.createTrack("text"),this._audioTrack.segmentCodec="aac",this.videoParser=null,this.aacOverFlow=null,this.remainderData=null,this.audioCodec=n,this.videoCodec=r}resetTimeStamp(){}resetContiguity(){const{_audioTrack:t,_videoTrack:n,_id3Track:r}=this;t&&(t.pesData=null),n&&(n.pesData=null),r&&(r.pesData=null),this.aacOverFlow=null,this.remainderData=null}demux(t,n,r=!1,a=!1){r||(this.sampleAes=null);let i;const l=this._videoTrack,o=this._audioTrack,c=this._id3Track,d=this._txtTrack;let u=l.pid,h=l.pesData,p=o.pid,f=c.pid,y=o.pesData,_=c.pesData,v=null,j=this.pmtParsed,w=this._pmtId,S=t.length;if(this.remainderData&&(t=Gv(this.remainderData,t),S=t.length,this.remainderData=null),S>4;let H;if(z>1){if(H=D+5+t[D+4],H===D+hp)continue}else H=D+4;switch(F){case u:I&&(h&&(i=$I(h,this.logger))&&(this.readyVideoParser(l.segmentCodec),this.videoParser!==null&&this.videoParser.parsePES(l,d,i,!1)),h={data:[],size:0}),h&&(h.data.push(t.subarray(H,D+hp)),h.size+=D+hp-H);break;case p:if(I){if(y&&(i=$I(y,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}y={data:[],size:0}}y&&(y.data.push(t.subarray(H,D+hp)),y.size+=D+hp-H);break;case f:I&&(_&&(i=$I(_,this.logger))&&this.parseID3PES(c,i),_={data:[],size:0}),_&&(_.data.push(t.subarray(H,D+hp)),_.size+=D+hp-H);break;case 0:I&&(H+=t[H]+1),w=this._pmtId=Fan(t,H);break;case w:{I&&(H+=t[H]+1);const Z=zan(t,H,this.typeSupported,r,this.observer,this.logger);u=Z.videoPid,u>0&&(l.pid=u,l.segmentCodec=Z.segmentVideoCodec),p=Z.audioPid,p>0&&(o.pid=p,o.segmentCodec=Z.segmentAudioCodec),f=Z.id3Pid,f>0&&(c.pid=f),v!==null&&!j&&(this.logger.warn(`MPEG-TS PMT found at ${D} after unknown PID '${v}'. Backtracking to sync byte @${A} to parse all TS packets.`),v=null,D=A-188),j=this.pmtParsed=!0;break}case 17:case 8191:break;default:v=F;break}}else E++;E>0&&_Te(this.observer,new Error(`Found ${E} TS packet/s that do not start with 0x47`),void 0,this.logger),l.pesData=h,o.pesData=y,c.pesData=_;const O={audioTrack:o,videoTrack:l,id3Track:c,textTrack:d};return a&&this.extractRemainingSamples(O),O}flush(){const{remainderData:t}=this;this.remainderData=null;let n;return t?n=this.demux(t,-1,!1,!0):n={videoTrack:this._videoTrack,audioTrack:this._audioTrack,id3Track:this._id3Track,textTrack:this._txtTrack},this.extractRemainingSamples(n),this.sampleAes?this.decrypt(n,this.sampleAes):n}extractRemainingSamples(t){const{audioTrack:n,videoTrack:r,id3Track:a,textTrack:i}=t,l=r.pesData,o=n.pesData,c=a.pesData;let d;if(l&&(d=$I(l,this.logger))?(this.readyVideoParser(r.segmentCodec),this.videoParser!==null&&(this.videoParser.parsePES(r,i,d,!0),r.pesData=null)):r.pesData=l,o&&(d=$I(o,this.logger))){switch(n.segmentCodec){case"aac":this.parseAACPES(n,d);break;case"mp3":this.parseMPEGPES(n,d);break;case"ac3":this.parseAC3PES(n,d);break}n.pesData=null}else o!=null&&o.size&&this.logger.log("last AAC PES packet truncated,might overlap between fragments"),n.pesData=o;c&&(d=$I(c,this.logger))?(this.parseID3PES(a,d),a.pesData=null):a.pesData=c}demuxSampleAes(t,n,r){const a=this.demux(t,r,!0,!this.config.progressive),i=this.sampleAes=new Dan(this.observer,this.config,n);return this.decrypt(a,i)}readyVideoParser(t){this.videoParser===null&&(t==="avc"?this.videoParser=new Ran:t==="hevc"&&(this.videoParser=new Oan))}decrypt(t,n){return new Promise(r=>{const{audioTrack:a,videoTrack:i}=t;a.samples&&a.segmentCodec==="aac"?n.decryptAacSamples(a.samples,0,()=>{i.samples?n.decryptAvcSamples(i.samples,0,0,()=>{r(t)}):r(t)}):i.samples&&n.decryptAvcSamples(i.samples,0,0,()=>{r(t)})})}destroy(){this.observer&&this.observer.removeAllListeners(),this.config=this.logger=this.observer=null,this.aacOverFlow=this.videoParser=this.remainderData=this.sampleAes=null,this._videoTrack=this._audioTrack=this._id3Track=this._txtTrack=void 0}parseAACPES(t,n){let r=0;const a=this.aacOverFlow;let i=n.data;if(a){this.aacOverFlow=null;const h=a.missing,p=a.sample.unit.byteLength;if(h===-1)i=Gv(a.sample.unit,i);else{const f=p-h;a.sample.unit.set(i.subarray(0,h),f),t.samples.push(a.sample),r=a.missing}}let l,o;for(l=r,o=i.length;l0;)o+=c}}parseID3PES(t,n){if(n.pts===void 0){this.logger.warn("[tsdemuxer]: ID3 PES unknown PTS");return}const r=Wc({},n,{type:this._videoTrack?G0.emsg:G0.audioId3,duration:Number.POSITIVE_INFINITY});t.samples.push(r)}}function bTe(s,t){return((s[t+1]&31)<<8)+s[t+2]}function Fan(s,t){return(s[t+10]&31)<<8|s[t+11]}function zan(s,t,n,r,a,i){const l={audioPid:-1,videoPid:-1,id3Pid:-1,segmentVideoCodec:"avc",segmentAudioCodec:"aac"},o=(s[t+1]&15)<<8|s[t+2],c=t+3+o-4,d=(s[t+10]&15)<<8|s[t+11];for(t+=12+d;t0){let p=t+5,f=h;for(;f>2;){switch(s[p]){case 106:n.ac3!==!0?i.log("AC-3 audio found, not supported in this browser for now"):(l.audioPid=u,l.segmentAudioCodec="ac3");break}const _=s[p+1]+2;p+=_,f-=_}}break;case 194:case 135:return _Te(a,new Error("Unsupported EC-3 in M2TS found"),void 0,i),l;case 36:l.videoPid===-1&&(l.videoPid=u,l.segmentVideoCodec="hevc",i.log("HEVC in M2TS found"));break}t+=h+5}return l}function _Te(s,t,n,r){r.warn(`parsing error: ${t.message}`),s.emit(jt.ERROR,jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.FRAG_PARSING_ERROR,fatal:!1,levelRetry:n,error:t,reason:t.message})}function UNe(s,t){t.log(`${s} with AES-128-CBC encryption found in unencrypted stream`)}function $I(s,t){let n=0,r,a,i,l,o;const c=s.data;if(!s||s.size===0)return null;for(;c[0].length<19&&c.length>1;)c[0]=Gv(c[0],c[1]),c.splice(1,1);if(r=c[0],(r[0]<<16)+(r[1]<<8)+r[2]===1){if(a=(r[4]<<8)+r[5],a&&a>s.size-6)return null;const u=r[7];u&192&&(l=(r[9]&14)*536870912+(r[10]&255)*4194304+(r[11]&254)*16384+(r[12]&255)*128+(r[13]&254)/2,u&64?(o=(r[14]&14)*536870912+(r[15]&255)*4194304+(r[16]&254)*16384+(r[17]&255)*128+(r[18]&254)/2,l-o>60*9e4&&(t.warn(`${Math.round((l-o)/9e4)}s delta between PTS and DTS, align them`),l=o)):o=l),i=r[8];let h=i+9;if(s.size<=h)return null;s.size-=h;const p=new Uint8Array(s.size);for(let f=0,y=c.length;f_){h-=_;continue}else r=r.subarray(h),_-=h,h=0;p.set(r,n),n+=_}return a&&(a-=i+3),{data:p,pts:l,dts:o,len:a}}return null}class Ban{static getSilentFrame(t,n){switch(t){case"mp4a.40.2":if(n===1)return new Uint8Array([0,200,0,128,35,128]);if(n===2)return new Uint8Array([33,0,73,144,2,25,0,35,128]);if(n===3)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,142]);if(n===4)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,128,44,128,8,2,56]);if(n===5)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,56]);if(n===6)return new Uint8Array([0,200,0,128,32,132,1,38,64,8,100,0,130,48,4,153,0,33,144,2,0,178,0,32,8,224]);break;default:if(n===1)return new Uint8Array([1,64,34,128,163,78,230,128,186,8,0,0,0,28,6,241,193,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===2)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);if(n===3)return new Uint8Array([1,64,34,128,163,94,230,128,186,8,0,0,0,0,149,0,6,241,161,10,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,90,94]);break}}}const Ck=Math.pow(2,32)-1;class En{static init(){En.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 En.types)En.types.hasOwnProperty(t)&&(En.types[t]=[t.charCodeAt(0),t.charCodeAt(1),t.charCodeAt(2),t.charCodeAt(3)]);const n=new Uint8Array([0,0,0,0,0,0,0,0,118,105,100,101,0,0,0,0,0,0,0,0,0,0,0,0,86,105,100,101,111,72,97,110,100,108,101,114,0]),r=new Uint8Array([0,0,0,0,0,0,0,0,115,111,117,110,0,0,0,0,0,0,0,0,0,0,0,0,83,111,117,110,100,72,97,110,100,108,101,114,0]);En.HDLR_TYPES={video:n,audio:r};const a=new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,12,117,114,108,32,0,0,0,1]),i=new Uint8Array([0,0,0,0,0,0,0,0]);En.STTS=En.STSC=En.STCO=i,En.STSZ=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0]),En.VMHD=new Uint8Array([0,0,0,1,0,0,0,0,0,0,0,0]),En.SMHD=new Uint8Array([0,0,0,0,0,0,0,0]),En.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]);En.FTYP=En.box(En.types.ftyp,l,c,l,o),En.DINF=En.box(En.types.dinf,En.box(En.types.dref,a))}static box(t,...n){let r=8,a=n.length;const i=a;for(;a--;)r+=n[a].byteLength;const l=new Uint8Array(r);for(l[0]=r>>24&255,l[1]=r>>16&255,l[2]=r>>8&255,l[3]=r&255,l.set(t,4),a=0,r=8;a>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255,85,196,0,0]))}static mdia(t){return En.box(En.types.mdia,En.mdhd(t.timescale||0,t.duration||0),En.hdlr(t.type),En.minf(t))}static mfhd(t){return En.box(En.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"?En.box(En.types.minf,En.box(En.types.smhd,En.SMHD),En.DINF,En.stbl(t)):En.box(En.types.minf,En.box(En.types.vmhd,En.VMHD),En.DINF,En.stbl(t))}static moof(t,n,r){return En.box(En.types.moof,En.mfhd(t),En.traf(r,n))}static moov(t){let n=t.length;const r=[];for(;n--;)r[n]=En.trak(t[n]);return En.box.apply(null,[En.types.moov,En.mvhd(t[0].timescale||0,t[0].duration||0)].concat(r).concat(En.mvex(t)))}static mvex(t){let n=t.length;const r=[];for(;n--;)r[n]=En.trex(t[n]);return En.box.apply(null,[En.types.mvex,...r])}static mvhd(t,n){n*=t;const r=Math.floor(n/(Ck+1)),a=Math.floor(n%(Ck+1)),i=new Uint8Array([1,0,0,0,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,t>>24&255,t>>16&255,t>>8&255,t&255,r>>24,r>>16&255,r>>8&255,r&255,a>>24,a>>16&255,a>>8&255,a&255,0,1,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,255,255,255,255]);return En.box(En.types.mvhd,i)}static sdtp(t){const n=t.samples||[],r=new Uint8Array(4+n.length);let a,i;for(a=0;a>>8&255),n.push(l&255),n=n.concat(Array.prototype.slice.call(i));for(a=0;a>>8&255),r.push(l&255),r=r.concat(Array.prototype.slice.call(i));const o=En.box(En.types.avcC,new Uint8Array([1,n[3],n[4],n[5],255,224|t.sps.length].concat(n).concat([t.pps.length]).concat(r))),c=t.width,d=t.height,u=t.pixelRatio[0],h=t.pixelRatio[1];return En.box(En.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,En.box(En.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),En.box(En.types.pasp,new Uint8Array([u>>24,u>>16&255,u>>8&255,u&255,h>>24,h>>16&255,h>>8&255,h&255])))}static esds(t){const n=t.config;return new Uint8Array([0,0,0,0,3,25,0,1,0,4,17,64,21,0,0,0,0,0,0,0,0,0,0,0,5,2,...n,6,1,2])}static audioStsd(t){const n=t.samplerate||0;return new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,t.channelCount||0,0,16,0,0,0,0,n>>8&255,n&255,0,0])}static mp4a(t){return En.box(En.types.mp4a,En.audioStsd(t),En.box(En.types.esds,En.esds(t)))}static mp3(t){return En.box(En.types[".mp3"],En.audioStsd(t))}static ac3(t){return En.box(En.types["ac-3"],En.audioStsd(t),En.box(En.types.dac3,t.config))}static stsd(t){const{segmentCodec:n}=t;if(t.type==="audio"){if(n==="aac")return En.box(En.types.stsd,En.STSD,En.mp4a(t));if(n==="ac3"&&t.config)return En.box(En.types.stsd,En.STSD,En.ac3(t));if(n==="mp3"&&t.codec==="mp3")return En.box(En.types.stsd,En.STSD,En.mp3(t))}else if(t.pps&&t.sps){if(n==="avc")return En.box(En.types.stsd,En.STSD,En.avc1(t));if(n==="hevc"&&t.vps)return En.box(En.types.stsd,En.STSD,En.hvc1(t))}else throw new Error("video track missing pps or sps");throw new Error(`unsupported ${t.type} segment codec (${n}/${t.codec})`)}static tkhd(t){const n=t.id,r=(t.duration||0)*(t.timescale||0),a=t.width||0,i=t.height||0,l=Math.floor(r/(Ck+1)),o=Math.floor(r%(Ck+1));return En.box(En.types.tkhd,new Uint8Array([1,0,0,7,0,0,0,0,0,0,0,2,0,0,0,0,0,0,0,3,n>>24&255,n>>16&255,n>>8&255,n&255,0,0,0,0,l>>24,l>>16&255,l>>8&255,l&255,o>>24,o>>16&255,o>>8&255,o&255,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,64,0,0,0,a>>8&255,a&255,0,0,i>>8&255,i&255,0,0]))}static traf(t,n){const r=En.sdtp(t),a=t.id,i=Math.floor(n/(Ck+1)),l=Math.floor(n%(Ck+1));return En.box(En.types.traf,En.box(En.types.tfhd,new Uint8Array([0,0,0,0,a>>24,a>>16&255,a>>8&255,a&255])),En.box(En.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])),En.trun(t,r.length+16+20+8+16+8+8),r)}static trak(t){return t.duration=t.duration||4294967295,En.box(En.types.trak,En.tkhd(t),En.mdia(t))}static trex(t){const n=t.id;return En.box(En.types.trex,new Uint8Array([0,0,0,0,n>>24,n>>16&255,n>>8&255,n&255,0,0,0,1,0,0,0,0,0,0,0,0,0,1,0,1]))}static trun(t,n){const r=t.samples||[],a=r.length,i=12+16*a,l=new Uint8Array(i);let o,c,d,u,h,p;for(n+=8+i,l.set([t.type==="video"?1:0,0,15,1,a>>>24&255,a>>>16&255,a>>>8&255,a&255,n>>>24&255,n>>>16&255,n>>>8&255,n&255],0),o=0;o>>24&255,d>>>16&255,d>>>8&255,d&255,u>>>24&255,u>>>16&255,u>>>8&255,u&255,h.isLeading<<2|h.dependsOn,h.isDependedOn<<6|h.hasRedundancy<<4|h.paddingValue<<1|h.isNonSync,h.degradPrio&61440,h.degradPrio&15,p>>>24&255,p>>>16&255,p>>>8&255,p&255],12+16*o);return En.box(En.types.trun,l)}static initSegment(t){En.types||En.init();const n=En.moov(t);return Gv(En.FTYP,n)}static hvc1(t){const n=t.params,r=[t.vps,t.sps,t.pps],a=4,i=new Uint8Array([1,n.general_profile_space<<6|(n.general_tier_flag?32:0)|n.general_profile_idc,n.general_profile_compatibility_flags[0],n.general_profile_compatibility_flags[1],n.general_profile_compatibility_flags[2],n.general_profile_compatibility_flags[3],n.general_constraint_indicator_flags[0],n.general_constraint_indicator_flags[1],n.general_constraint_indicator_flags[2],n.general_constraint_indicator_flags[3],n.general_constraint_indicator_flags[4],n.general_constraint_indicator_flags[5],n.general_level_idc,240|n.min_spatial_segmentation_idc>>8,255&n.min_spatial_segmentation_idc,252|n.parallelismType,252|n.chroma_format_idc,248|n.bit_depth_luma_minus8,248|n.bit_depth_chroma_minus8,0,parseInt(n.frame_rate.fps),a-1|n.temporal_id_nested<<2|n.num_temporal_layers<<3|(n.frame_rate.fixed?64:0),r.length]);let l=i.length;for(let y=0;y>8,r[y][_].length&255]),l),l+=2,o.set(r[y][_],l),l+=r[y][_].length}const d=En.box(En.types.hvcC,o),u=t.width,h=t.height,p=t.pixelRatio[0],f=t.pixelRatio[1];return En.box(En.types.hvc1,new Uint8Array([0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,u>>8&255,u&255,h>>8&255,h&255,0,72,0,0,0,72,0,0,0,0,0,0,0,1,18,100,97,105,108,121,109,111,116,105,111,110,47,104,108,115,46,106,115,0,0,0,0,0,0,0,0,0,0,0,0,0,0,24,17,17]),d,En.box(En.types.btrt,new Uint8Array([0,28,156,128,0,45,198,192,0,45,198,192])),En.box(En.types.pasp,new Uint8Array([p>>24,p>>16&255,p>>8&255,p&255,f>>24,f>>16&255,f>>8&255,f&255])))}}En.types=void 0;En.HDLR_TYPES=void 0;En.STTS=void 0;En.STSC=void 0;En.STCO=void 0;En.STSZ=void 0;En.VMHD=void 0;En.SMHD=void 0;En.STSD=void 0;En.FTYP=void 0;En.DINF=void 0;const okt=9e4;function E8e(s,t,n=1,r=!1){const a=s*t*n;return r?Math.round(a):a}function $an(s,t,n=1,r=!1){return E8e(s,t,1/n,r)}function LF(s,t=!1){return E8e(s,1e3,1/okt,t)}function Uan(s,t=1){return E8e(s,okt,1/t)}function gJe(s){const{baseTime:t,timescale:n,trackId:r}=s;return`${t/n} (${t}/${n}) trackId: ${r}`}const qan=10*1e3,Van=1024,Han=1152,Gan=1536;let UI=null,qNe=null;function yJe(s,t,n,r){return{duration:t,size:n,cts:r,flags:{isLeading:0,isDependedOn:0,hasRedundancy:0,degradPrio:0,dependsOn:s?2:1,isNonSync:s?0:1}}}class Xme extends t1{constructor(t,n,r,a){if(super("mp4-remuxer",a),this.observer=void 0,this.config=void 0,this.typeSupported=void 0,this.ISGenerated=!1,this._initPTS=null,this._initDTS=null,this.nextVideoTs=null,this.nextAudioTs=null,this.videoSampleDuration=null,this.isAudioContiguous=!1,this.isVideoContiguous=!1,this.videoTrackConfig=void 0,this.observer=t,this.config=n,this.typeSupported=r,this.ISGenerated=!1,UI===null){const l=(navigator.userAgent||"").match(/Chrome\/(\d+)/i);UI=l?parseInt(l[1]):0}if(qNe===null){const i=navigator.userAgent.match(/Safari\/(\d+)/i);qNe=i?parseInt(i[1]):0}}destroy(){this.config=this.videoTrackConfig=this._initPTS=this._initDTS=null}resetTimeStamp(t){const n=this._initPTS;(!n||!t||t.trackId!==n.trackId||t.baseTime!==n.baseTime||t.timescale!==n.timescale)&&this.log(`Reset initPTS: ${n&&gJe(n)} > ${t&&gJe(t)}`),this._initPTS=this._initDTS=t}resetNextTimestamp(){this.log("reset next timestamp"),this.isVideoContiguous=!1,this.isAudioContiguous=!1}resetInitSegment(){this.log("ISGenerated flag reset"),this.ISGenerated=!1,this.videoTrackConfig=void 0}getVideoStartPts(t){let n=!1;const r=t[0].pts,a=t.reduce((i,l)=>{let o=l.pts,c=o-i;return c<-4294967296&&(n=!0,o=F0(o,r),c=o-i),c>0?i:o},r);return n&&this.debug("PTS rollover detected"),a}remux(t,n,r,a,i,l,o,c){let d,u,h,p,f,y,_=i,v=i;const j=t.pid>-1,w=n.pid>-1,S=n.samples.length,A=t.samples.length>0,E=o&&S>0||S>1;if((!j||A)&&(!w||E)||this.ISGenerated||o){if(this.ISGenerated){var D,I,F,z;const W=this.videoTrackConfig;(W&&(n.width!==W.width||n.height!==W.height||((D=n.pixelRatio)==null?void 0:D[0])!==((I=W.pixelRatio)==null?void 0:I[0])||((F=n.pixelRatio)==null?void 0:F[1])!==((z=W.pixelRatio)==null?void 0:z[1]))||!W&&E||this.nextAudioTs===null&&A)&&this.resetInitSegment()}this.ISGenerated||(h=this.generateIS(t,n,i,l));const H=this.isVideoContiguous;let Z=-1,Y;if(E&&(Z=Wan(n.samples),!H&&this.config.forceKeyFrameOnDiscontinuity))if(y=!0,Z>0){this.warn(`Dropped ${Z} out of ${S} video samples due to a missing keyframe`);const W=this.getVideoStartPts(n.samples);n.samples=n.samples.slice(Z),n.dropped+=Z,v+=(n.samples[0].pts-W)/n.inputTimeScale,Y=v}else Z===-1&&(this.warn(`No keyframe found out of ${S} video samples`),y=!1);if(this.ISGenerated){if(A&&E){const W=this.getVideoStartPts(n.samples),se=(F0(t.samples[0].pts,W)-W)/n.inputTimeScale;_+=Math.max(0,se),v+=Math.max(0,-se)}if(A){if(t.samplerate||(this.warn("regenerate InitSegment as audio detected"),h=this.generateIS(t,n,i,l)),u=this.remuxAudio(t,_,this.isAudioContiguous,l,w||E||c===Wa.AUDIO?v:void 0),E){const W=u?u.endPTS-u.startPTS:0;n.inputTimeScale||(this.warn("regenerate InitSegment as video detected"),h=this.generateIS(t,n,i,l)),d=this.remuxVideo(n,v,H,W)}}else E&&(d=this.remuxVideo(n,v,H,0));d&&(d.firstKeyFrame=Z,d.independent=Z!==-1,d.firstKeyFramePTS=Y)}}return this.ISGenerated&&this._initPTS&&this._initDTS&&(r.samples.length&&(f=lkt(r,i,this._initPTS,this._initDTS)),a.samples.length&&(p=ckt(a,i,this._initPTS))),{audio:u,video:d,initSegment:h,independent:y,text:p,id3:f}}computeInitPts(t,n,r,a){const i=Math.round(r*n);let l=F0(t,i);if(l0?le-1:le].dts&&(w=!0)}w&&l.sort(function(le,ve){const ge=le.dts-ve.dts,Te=le.pts-ve.pts;return ge||Te}),y=l[0].dts,_=l[l.length-1].dts;const A=_-y,E=A?Math.round(A/(c-1)):f||t.inputTimeScale/30;if(r){const le=y-S,ve=le>E,ge=le<-1;if((ve||ge)&&(ve?this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${LF(le,!0)} ms (${le}dts) hole between fragments detected at ${n.toFixed(3)}`):this.warn(`${(t.segmentCodec||"").toUpperCase()}: ${LF(-le,!0)} ms (${le}dts) overlapping between fragments detected at ${n.toFixed(3)}`),!ge||S>=l[0].pts||UI)){y=S;const Te=l[0].pts-le;if(ve)l[0].dts=y,l[0].pts=Te;else{let Ie=!0;for(let Ce=0;CeTe&&Ie);Ce++){const Me=l[Ce].pts;if(l[Ce].dts-=le,l[Ce].pts-=le,Ce0?ve.dts-l[le-1].dts:E;if(Ie=le>0?ve.pts-l[le-1].pts:E,Me.stretchShortVideoTrack&&this.nextAudioTs!==null){const Re=Math.floor(Me.maxBufferHole*i),Ae=(a?v+a*i:this.nextAudioTs+u)-ve.pts;Ae>Re?(f=Ae-Pe,f<0?f=Pe:Z=!0,this.log(`It is approximately ${Ae/90} ms to the next segment; using duration ${f/90} ms for the last video frame.`)):f=Pe}else f=Pe}const Ce=Math.round(ve.pts-ve.dts);Y=Math.min(Y,f),ee=Math.max(ee,f),W=Math.min(W,Ie),se=Math.max(se,Ie),o.push(yJe(ve.key,f,Te,Ce))}if(o.length){if(UI){if(UI<70){const le=o[0].flags;le.dependsOn=2,le.isNonSync=0}}else if(qNe&&se-W0&&(a&&Math.abs(S-(j+w))<9e3||Math.abs(F0(_[0].pts,S)-(j+w))<20*u),_.forEach(function(se){se.pts=F0(se.pts,S)}),!r||j<0){const se=_.length;if(_=_.filter(oe=>oe.pts>=0),se!==_.length&&this.warn(`Removed ${_.length-se} of ${se} samples (initPTS ${w} / ${l})`),!_.length)return;i===0?j=0:a&&!y?j=Math.max(0,S-w):j=_[0].pts-w}if(t.segmentCodec==="aac"){const se=this.config.maxAudioFramesDrift;for(let oe=0,he=j+w;oe<_.length;oe++){const ce=_[oe],me=ce.pts,le=me-he,ve=Math.abs(1e3*le/l);if(le<=-se*u&&y)oe===0&&(this.warn(`Audio frame @ ${(me/l).toFixed(3)}s overlaps marker by ${Math.round(1e3*le/l)} ms.`),this.nextAudioTs=j=me-w,he=me);else if(le>=se*u&&ve0){D+=v;try{O=new Uint8Array(D)}catch(ve){this.observer.emit(jt.ERROR,jt.ERROR,{type:ui.MUX_ERROR,details:Mn.REMUX_ALLOC_ERROR,fatal:!1,error:ve,bytes:D,reason:`fail allocating audio mdat ${D}`});return}p||(new DataView(O.buffer).setUint32(0,D),O.set(En.types.mdat,4))}else return;O.set(ce,v);const le=ce.byteLength;v+=le,f.push(yJe(!0,d,le,0)),E=me}const F=f.length;if(!F)return;const z=f[f.length-1];j=E-w,this.nextAudioTs=j+c*z.duration;const H=p?new Uint8Array(0):En.moof(t.sequenceNumber++,A/c,Wc({},t,{samples:f}));t.samples=[];const Z=(A-w)/l,Y=this.nextAudioTs/l,ee={data1:H,data2:O,startPTS:Z,endPTS:Y,startDTS:Z,endDTS:Y,type:"audio",hasAudio:!0,hasVideo:!1,nb:F};return this.isAudioContiguous=!0,ee}}function F0(s,t){let n;if(t===null)return s;for(t4294967296;)s+=n;return s}function Wan(s){for(let t=0;tl.pts-o.pts);const i=s.samples;return s.samples=[],{samples:i}}class Kan extends t1{constructor(t,n,r,a){super("passthrough-remuxer",a),this.emitInitSegment=!1,this.audioCodec=void 0,this.videoCodec=void 0,this.initData=void 0,this.initPTS=null,this.initTracks=void 0,this.lastEndTime=null,this.isVideoContiguous=!1}destroy(){}resetTimeStamp(t){this.lastEndTime=null;const n=this.initPTS;n&&t&&n.baseTime===t.baseTime&&n.timescale===t.timescale||(this.initPTS=t)}resetNextTimestamp(){this.isVideoContiguous=!1,this.lastEndTime=null}resetInitSegment(t,n,r,a){this.audioCodec=n,this.videoCodec=r,this.generateInitSegment(t,a),this.emitInitSegment=!0}generateInitSegment(t,n){let{audioCodec:r,videoCodec:a}=this;if(!(t!=null&&t.byteLength)){this.initTracks=void 0,this.initData=void 0;return}const{audio:i,video:l}=this.initData=fNt(t);if(n)Dnn(t,n);else{const c=i||l;c!=null&&c.encrypted&&this.warn(`Init segment with encrypted track with has no key ("${c.codec}")!`)}i&&(r=vJe(i,Jc.AUDIO,this)),l&&(a=vJe(l,Jc.VIDEO,this));const o={};i&&l?o.audiovideo={container:"video/mp4",codec:r+","+a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:i?o.audio={container:"audio/mp4",codec:r,encrypted:i.encrypted,initSegment:t,id:"audio"}:l?o.video={container:"video/mp4",codec:a,supplemental:l.supplemental,encrypted:l.encrypted,initSegment:t,id:"main"}:this.warn("initSegment does not contain moov or trak boxes."),this.initTracks=o}remux(t,n,r,a,i,l){var o,c;let{initPTS:d,lastEndTime:u}=this;const h={audio:void 0,video:void 0,text:a,id3:r,initSegment:void 0};Pa(u)||(u=this.lastEndTime=i||0);const p=n.samples;if(!p.length)return h;const f={initPTS:void 0,timescale:void 0,trackId:void 0};let y=this.initData;if((o=y)!=null&&o.length||(this.generateInitSegment(p),y=this.initData),!((c=y)!=null&&c.length))return this.warn("Failed to generate initSegment."),h;this.emitInitSegment&&(f.tracks=this.initTracks,this.emitInitSegment=!1);const _=Onn(p,y,this),v=y.audio?_[y.audio.id]:null,j=y.video?_[y.video.id]:null,w=AG(j,1/0),S=AG(v,1/0),A=AG(j,0,!0),E=AG(v,0,!0);let O=i,D=0;const I=v&&(!j||!d&&S0?this.lastEndTime=H:(this.warn("Duration parsed from mp4 should be greater than zero"),this.resetNextTimestamp());const Z=!!y.audio,Y=!!y.video;let W="";Z&&(W+="audio"),Y&&(W+="video");const ee=(y.audio?y.audio.encrypted:!1)||(y.video?y.video.encrypted:!1),se={data1:p,startPTS:z,startDTS:z,endPTS:H,endDTS:H,type:W,hasAudio:Z,hasVideo:Y,nb:1,dropped:0,encrypted:ee};h.audio=Z&&!Y?se:void 0,h.video=Y?se:void 0;const oe=j==null?void 0:j.sampleCount;if(oe){const he=j.keyFrameIndex,ce=he!==-1;se.nb=oe,se.dropped=he===0||this.isVideoContiguous?0:ce?he:oe,se.independent=ce,se.firstKeyFrame=he,ce&&j.keyFrameStart&&(se.firstKeyFramePTS=(j.keyFrameStart-d.baseTime)/d.timescale),this.isVideoContiguous||(h.independent=ce),this.isVideoContiguous||(this.isVideoContiguous=ce),se.dropped&&this.warn(`fmp4 does not start with IDR: firstIDR ${he}/${oe} dropped: ${se.dropped} start: ${se.firstKeyFramePTS||"NA"}`)}return h.initSegment=f,h.id3=lkt(r,i,d,d),a.samples.length&&(h.text=ckt(a,i,d)),h}}function AG(s,t,n=!1){return(s==null?void 0:s.start)!==void 0?(s.start+(n?s.duration:0))/s.timescale:t}function Yan(s,t,n,r){if(s===null)return!0;const a=Math.max(r,1),i=t-s.baseTime/s.timescale;return Math.abs(i-n)>a}function vJe(s,t,n){const r=s.codec;return r&&r.length>4?r:t===Jc.AUDIO?r==="ec-3"||r==="ac-3"||r==="alac"?r:r==="fLaC"||r==="Opus"?Rge(r,!1):(n.warn(`Unhandled audio codec "${r}" in mp4 MAP`),r||"mp4a"):(n.warn(`Unhandled video codec "${r}" in mp4 MAP`),r||"avc1")}let w2;try{w2=self.performance.now.bind(self.performance)}catch{w2=Date.now}const Jme=[{demux:Lan,remux:Kan},{demux:eS,remux:Xme},{demux:Aan,remux:Xme},{demux:Ian,remux:Xme}];Jme.splice(2,0,{demux:Man,remux:Xme});class bJe{constructor(t,n,r,a,i,l){this.asyncResult=!1,this.logger=void 0,this.observer=void 0,this.typeSupported=void 0,this.config=void 0,this.id=void 0,this.demuxer=void 0,this.remuxer=void 0,this.decrypter=void 0,this.probe=void 0,this.decryptionPromise=null,this.transmuxConfig=void 0,this.currentTransmuxState=void 0,this.observer=t,this.typeSupported=n,this.config=r,this.id=i,this.logger=l}configure(t){this.transmuxConfig=t,this.decrypter&&this.decrypter.reset()}push(t,n,r,a){const i=r.transmuxing;i.executeStart=w2();let l=new Uint8Array(t);const{currentTransmuxState:o,transmuxConfig:c}=this;a&&(this.currentTransmuxState=a);const{contiguous:d,discontinuity:u,trackSwitch:h,accurateTimeOffset:p,timeOffset:f,initSegmentChange:y}=a||o,{audioCodec:_,videoCodec:v,defaultInitPts:j,duration:w,initSegmentData:S}=c,A=Zan(l,n);if(A&&$L(A.method)){const I=this.getDecrypter(),F=b8e(A.method);if(I.isSync()){let z=I.softwareDecrypt(l,A.key.buffer,A.iv.buffer,F);if(r.part>-1){const Z=I.flush();z=Z&&Z.buffer}if(!z)return i.executeEnd=w2(),VNe(r);l=new Uint8Array(z)}else return this.asyncResult=!0,this.decryptionPromise=I.webCryptoDecrypt(l,A.key.buffer,A.iv.buffer,F).then(z=>{const H=this.push(z,null,r);return this.decryptionPromise=null,H}),this.decryptionPromise}const E=this.needsProbing(u,h);if(E){const I=this.configureTransmuxer(l);if(I)return this.logger.warn(`[transmuxer] ${I.message}`),this.observer.emit(jt.ERROR,jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.FRAG_PARSING_ERROR,fatal:!1,error:I,reason:I.message}),i.executeEnd=w2(),VNe(r)}(u||h||y||E)&&this.resetInitSegment(S,_,v,w,n),(u||y||E)&&this.resetInitialTimestamp(j),d||this.resetContiguity();const O=this.transmux(l,A,f,p,r);this.asyncResult=g$(O);const D=this.currentTransmuxState;return D.contiguous=!0,D.discontinuity=!1,D.trackSwitch=!1,i.executeEnd=w2(),O}flush(t){const n=t.transmuxing;n.executeStart=w2();const{decrypter:r,currentTransmuxState:a,decryptionPromise:i}=this;if(i)return this.asyncResult=!0,i.then(()=>this.flush(t));const l=[],{timeOffset:o}=a;if(r){const h=r.flush();h&&l.push(this.push(h.buffer,null,t))}const{demuxer:c,remuxer:d}=this;if(!c||!d){n.executeEnd=w2();const h=[VNe(t)];return this.asyncResult?Promise.resolve(h):h}const u=c.flush(o);return g$(u)?(this.asyncResult=!0,u.then(h=>(this.flushRemux(l,h,t),l))):(this.flushRemux(l,u,t),this.asyncResult?Promise.resolve(l):l)}flushRemux(t,n,r){const{audioTrack:a,videoTrack:i,id3Track:l,textTrack:o}=n,{accurateTimeOffset:c,timeOffset:d}=this.currentTransmuxState;this.logger.log(`[transmuxer.ts]: Flushed ${this.id} sn: ${r.sn}${r.part>-1?" part: "+r.part:""} of ${this.id===Wa.MAIN?"level":"track"} ${r.level}`);const u=this.remuxer.remux(a,i,l,o,d,c,!0,this.id);t.push({remuxResult:u,chunkMeta:r}),r.transmuxing.executeEnd=w2()}resetInitialTimestamp(t){const{demuxer:n,remuxer:r}=this;!n||!r||(n.resetTimeStamp(t),r.resetTimeStamp(t))}resetContiguity(){const{demuxer:t,remuxer:n}=this;!t||!n||(t.resetContiguity(),n.resetNextTimestamp())}resetInitSegment(t,n,r,a,i){const{demuxer:l,remuxer:o}=this;!l||!o||(l.resetInitSegment(t,n,r,a),o.resetInitSegment(t,n,r,i))}destroy(){this.demuxer&&(this.demuxer.destroy(),this.demuxer=void 0),this.remuxer&&(this.remuxer.destroy(),this.remuxer=void 0)}transmux(t,n,r,a,i){let l;return n&&n.method==="SAMPLE-AES"?l=this.transmuxSampleAes(t,n,r,a,i):l=this.transmuxUnencrypted(t,r,a,i),l}transmuxUnencrypted(t,n,r,a){const{audioTrack:i,videoTrack:l,id3Track:o,textTrack:c}=this.demuxer.demux(t,n,!1,!this.config.progressive);return{remuxResult:this.remuxer.remux(i,l,o,c,n,r,!1,this.id),chunkMeta:a}}transmuxSampleAes(t,n,r,a,i){return this.demuxer.demuxSampleAes(t,n,r).then(l=>({remuxResult:this.remuxer.remux(l.audioTrack,l.videoTrack,l.id3Track,l.textTrack,r,a,!1,this.id),chunkMeta:i}))}configureTransmuxer(t){const{config:n,observer:r,typeSupported:a}=this;let i;for(let h=0,p=Jme.length;h0&&(t==null?void 0:t.key)!=null&&t.iv!==null&&t.method!=null&&(n=t),n}const VNe=s=>({remuxResult:{},chunkMeta:s});function g$(s){return"then"in s&&s.then instanceof Function}class Qan{constructor(t,n,r,a,i){this.audioCodec=void 0,this.videoCodec=void 0,this.initSegmentData=void 0,this.duration=void 0,this.defaultInitPts=void 0,this.audioCodec=t,this.videoCodec=n,this.initSegmentData=r,this.duration=a,this.defaultInitPts=i||null}}class Xan{constructor(t,n,r,a,i,l){this.discontinuity=void 0,this.contiguous=void 0,this.accurateTimeOffset=void 0,this.trackSwitch=void 0,this.timeOffset=void 0,this.initSegmentChange=void 0,this.discontinuity=t,this.contiguous=n,this.accurateTimeOffset=r,this.trackSwitch=a,this.timeOffset=i,this.initSegmentChange=l}}let _Je=0;class dkt{constructor(t,n,r,a){this.error=null,this.hls=void 0,this.id=void 0,this.instanceNo=_Je++,this.observer=void 0,this.frag=null,this.part=null,this.useWorker=void 0,this.workerContext=null,this.transmuxer=null,this.onTransmuxComplete=void 0,this.onFlush=void 0,this.onWorkerMessage=c=>{const d=c.data,u=this.hls;if(!(!u||!(d!=null&&d.event)||d.instanceNo!==this.instanceNo))switch(d.event){case"init":{var h;const p=(h=this.workerContext)==null?void 0:h.objectURL;p&&self.URL.revokeObjectURL(p);break}case"transmuxComplete":{this.handleTransmuxComplete(d.data);break}case"flush":{this.onFlush(d.data);break}case"workerLog":{u.logger[d.data.logType]&&u.logger[d.data.logType](d.data.message);break}default:{d.data=d.data||{},d.data.frag=this.frag,d.data.part=this.part,d.data.id=this.id,u.trigger(d.event,d.data);break}}},this.onWorkerError=c=>{if(!this.hls)return;const d=new Error(`${c.message} (${c.filename}:${c.lineno})`);this.hls.config.enableWorker=!1,this.hls.logger.warn(`Error in "${this.id}" Web Worker, fallback to inline`),this.hls.trigger(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.INTERNAL_EXCEPTION,fatal:!1,event:"demuxerWorker",error:d})};const i=t.config;this.hls=t,this.id=n,this.useWorker=!!i.enableWorker,this.onTransmuxComplete=r,this.onFlush=a;const l=(c,d)=>{d=d||{},d.frag=this.frag||void 0,c===jt.ERROR&&(d=d,d.parent=this.id,d.part=this.part,this.error=d.error),this.hls.trigger(c,d)};this.observer=new j8e,this.observer.on(jt.FRAG_DECRYPTED,l),this.observer.on(jt.ERROR,l);const o=RXe(i.preferManagedMediaSource);if(this.useWorker&&typeof Worker<"u"){const c=this.hls.logger;if(i.workerPath||san()){try{i.workerPath?(c.log(`loading Web Worker ${i.workerPath} for "${n}"`),this.workerContext=ran(i.workerPath)):(c.log(`injecting Web Worker for "${n}"`),this.workerContext=nan());const{worker:u}=this.workerContext;u.addEventListener("message",this.onWorkerMessage),u.addEventListener("error",this.onWorkerError),u.postMessage({instanceNo:this.instanceNo,cmd:"init",typeSupported:o,id:n,config:rd(i)})}catch(u){c.warn(`Error setting up "${n}" Web Worker, fallback to inline`,u),this.terminateWorker(),this.error=null,this.transmuxer=new bJe(this.observer,o,i,"",n,t.logger)}return}}this.transmuxer=new bJe(this.observer,o,i,"",n,t.logger)}reset(){if(this.frag=null,this.part=null,this.workerContext){const t=this.instanceNo;this.instanceNo=_Je++;const n=this.hls.config,r=RXe(n.preferManagedMediaSource);this.workerContext.worker.postMessage({instanceNo:this.instanceNo,cmd:"reset",resetNo:t,typeSupported:r,id:this.id,config:rd(n)})}}terminateWorker(){if(this.workerContext){const{worker:t}=this.workerContext;this.workerContext=null,t.removeEventListener("message",this.onWorkerMessage),t.removeEventListener("error",this.onWorkerError),aan(this.hls.config.workerPath)}}destroy(){if(this.workerContext)this.terminateWorker(),this.onWorkerMessage=this.onWorkerError=null;else{const n=this.transmuxer;n&&(n.destroy(),this.transmuxer=null)}const t=this.observer;t&&t.removeAllListeners(),this.frag=null,this.part=null,this.observer=null,this.hls=null}push(t,n,r,a,i,l,o,c,d,u){var h,p;d.transmuxing.start=self.performance.now();const{instanceNo:f,transmuxer:y}=this,_=l?l.start:i.start,v=i.decryptdata,j=this.frag,w=!(j&&i.cc===j.cc),S=!(j&&d.level===j.level),A=j?d.sn-j.sn:-1,E=this.part?d.part-this.part.index:-1,O=A===0&&d.id>1&&d.id===(j==null?void 0:j.stats.chunkCount),D=!S&&(A===1||A===0&&(E===1||O&&E<=0)),I=self.performance.now();(S||A||i.stats.parsing.start===0)&&(i.stats.parsing.start=I),l&&(E||!D)&&(l.stats.parsing.start=I);const F=!(j&&((h=i.initSegment)==null?void 0:h.url)===((p=j.initSegment)==null?void 0:p.url)),z=new Xan(w,D,c,S,_,F);if(!D||w||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===Wa.MAIN?"level":"track"}: ${d.level} id: ${d.id} discontinuity: ${w} trackSwitch: ${S} contiguous: ${D} accurateTimeOffset: ${c} timeOffset: ${_} initSegmentChange: ${F}`);const H=new Qan(r,a,n,o,u);this.configureTransmuxer(H)}if(this.frag=i,this.part=l,this.workerContext)this.workerContext.worker.postMessage({instanceNo:f,cmd:"demux",data:t,decryptdata:v,chunkMeta:d,state:z},t instanceof ArrayBuffer?[t]:[]);else if(y){const H=y.push(t,v,d,z);g$(H)?H.then(Z=>{this.handleTransmuxComplete(Z)}).catch(Z=>{this.transmuxerError(Z,d,"transmuxer-interface push error")}):this.handleTransmuxComplete(H)}}flush(t){t.transmuxing.start=self.performance.now();const{instanceNo:n,transmuxer:r}=this;if(this.workerContext)this.workerContext.worker.postMessage({instanceNo:n,cmd:"flush",chunkMeta:t});else if(r){const a=r.flush(t);g$(a)?a.then(i=>{this.handleFlushResult(i,t)}).catch(i=>{this.transmuxerError(i,t,"transmuxer-interface flush error")}):this.handleFlushResult(a,t)}}transmuxerError(t,n,r){this.hls&&(this.error=t,this.hls.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.FRAG_PARSING_ERROR,chunkMeta:n,frag:this.frag||void 0,part:this.part||void 0,fatal:!1,error:t,err:t,reason:r}))}handleFlushResult(t,n){t.forEach(r=>{this.handleTransmuxComplete(r)}),this.onFlush(n)}configureTransmuxer(t){const{instanceNo:n,transmuxer:r}=this;this.workerContext?this.workerContext.worker.postMessage({instanceNo:n,cmd:"configure",config:t}):r&&r.configure(t)}handleTransmuxComplete(t){t.chunkMeta.transmuxing.end=self.performance.now(),this.onTransmuxComplete(t)}}const wJe=100;class Jan extends w8e{constructor(t,n,r){super(t,n,r,"audio-stream-controller",Wa.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(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(jt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.on(jt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(jt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(jt.BUFFER_RESET,this.onBufferReset,this),t.on(jt.BUFFER_CREATED,this.onBufferCreated,this),t.on(jt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(jt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(jt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(jt.FRAG_LOADING,this.onFragLoading,this),t.on(jt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){const{hls:t}=this;t&&(super.unregisterListeners(),t.off(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(jt.AUDIO_TRACKS_UPDATED,this.onAudioTracksUpdated,this),t.off(jt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(jt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(jt.BUFFER_RESET,this.onBufferReset,this),t.off(jt.BUFFER_CREATED,this.onBufferCreated,this),t.off(jt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(jt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(jt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(jt.FRAG_LOADING,this.onFragLoading,this),t.off(jt.FRAG_BUFFERED,this.onFragBuffered,this))}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){if(r===Wa.MAIN){const o=n.cc,c=this.fragCurrent;if(this.initPTS[o]={baseTime:a,timescale:i,trackId:l},this.log(`InitPTS for cc: ${o} found from main: ${a/i} (${a}/${i}) trackId: ${l}`),this.mainAnchor=n,this.state===cr.WAITING_INIT_PTS){const d=this.waitingData;(!d&&!this.loadingParts||d&&d.frag.cc!==o)&&this.syncWithAnchor(n,d==null?void 0:d.frag)}else!this.hls.hasEnoughToStart&&c&&c.cc!==o?(c.abortRequests(),this.syncWithAnchor(n,c)):this.state===cr.IDLE&&this.tick()}}getLoadPosition(){return!this.startFragRequested&&this.nextLoadPosition>=0?this.nextLoadPosition:super.getLoadPosition()}syncWithAnchor(t,n){var r;const a=((r=this.mainFragLoading)==null?void 0:r.frag)||null;if(n&&(a==null?void 0:a.cc)===n.cc)return;const i=(a||t).cc,l=this.getLevelDetails(),o=this.getLoadPosition(),c=SNt(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===cr.IDLE&&this.doTickIdle())}startLoad(t,n){if(!this.levels){this.startPosition=t,this.state=cr.STOPPED;return}const r=this.lastCurrentTime;this.stopLoad(),this.setInterval(wJe),r>0&&t===-1?(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r,this.state=cr.IDLE):this.state=cr.WAITING_TRACK,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}doTick(){switch(this.state){case cr.IDLE:this.doTickIdle();break;case cr.WAITING_TRACK:{const{levels:t,trackId:n}=this,r=t==null?void 0:t[n],a=r==null?void 0:r.details;if(a&&!this.waitForLive(r)){if(this.waitForCdnTuneIn(a))break;this.state=cr.WAITING_INIT_PTS}break}case cr.FRAG_LOADING_WAITING_RETRY:{this.checkRetryDate();break}case cr.WAITING_INIT_PTS:{const t=this.waitingData;if(t){const{frag:n,part:r,cache:a,complete:i}=t,l=this.mainAnchor;if(this.initPTS[n.cc]!==void 0){this.waitingData=null,this.state=cr.FRAG_LOADING;const o=a.flush().buffer,c={frag:n,part:r,payload:o,networkDetails:null};this._handleFragmentLoadProgress(c),i&&super._handleFragmentLoadComplete(c)}else l&&l.cc!==t.frag.cc&&this.syncWithAnchor(l,t.frag)}else this.state=cr.IDLE}}this.onTickEnd()}resetLoadingState(){const t=this.waitingData;t&&(this.fragmentTracker.removeFragment(t.frag),this.waitingData=null),super.resetLoadingState()}onTickEnd(){const{media:t}=this;t!=null&&t.readyState&&(this.lastCurrentTime=t.currentTime)}doTickIdle(){var t;const{hls:n,levels:r,media:a,trackId:i}=this,l=n.config;if(!this.buffering||!a&&!this.primaryPrefetch&&(this.startFragRequested||!l.startFragPrefetch)||!(r!=null&&r[i]))return;const o=r[i],c=o.details;if(!c||this.waitForLive(o)||this.waitForCdnTuneIn(c)){this.state=cr.WAITING_TRACK,this.startFragRequested=!1;return}const d=this.mediaBuffer?this.mediaBuffer:this.media;this.bufferFlushed&&d&&(this.bufferFlushed=!1,this.afterBufferFlushed(d,Jc.AUDIO,Wa.AUDIO));const u=this.getFwdBufferInfo(d,Wa.AUDIO);if(u===null)return;if(!this.switchingTrack&&this._streamEnded(u,c)){n.trigger(jt.BUFFER_EOS,{type:"audio"}),this.state=cr.ENDED;return}const h=u.len,p=n.maxBufferLength,f=c.fragments,y=f[0].start,_=this.getLoadPosition(),v=this.flushing?_:u.end;if(this.switchingTrack&&a){const S=_;c.PTSKnown&&Sy||u.nextStart)&&(this.log("Alt audio track ahead of main track, seek to start of alt audio track"),a.currentTime=y+.05)}if(h>=p&&!this.switchingTrack&&vw.end){const A=this.fragmentTracker.getFragAtPos(v,Wa.MAIN);A&&A.end>w.end&&(w=A,this.mainFragLoading={frag:A,targetBufferTime:null})}if(j.start>w.end)return}this.loadFragment(j,o,v)}onMediaDetaching(t,n){this.bufferFlushed=this.flushing=!1,super.onMediaDetaching(t,n)}onAudioTracksUpdated(t,{audioTracks:n}){this.resetTransmuxer(),this.levels=n.map(r=>new p$(r))}onAudioTrackSwitching(t,n){const r=!!n.url;this.trackId=n.id;const{fragCurrent:a}=this;a&&(a.abortRequests(),this.removeUnbufferedFrags(a.start)),this.resetLoadingState(),r?(this.switchingTrack=n,this.flushAudioIfNeeded(n),this.state!==cr.STOPPED&&(this.setInterval(wJe),this.state=cr.IDLE,this.tick())):(this.resetTransmuxer(),this.switchingTrack=null,this.bufferedTrack=n,this.clearInterval())}onManifestLoading(){super.onManifestLoading(),this.bufferFlushed=this.flushing=this.audioOnly=!1,this.resetItem(),this.trackId=-1}onLevelLoaded(t,n){this.mainDetails=n.details;const r=this.cachedTrackLoadedData;r&&(this.cachedTrackLoadedData=null,this.onAudioTrackLoaded(jt.AUDIO_TRACK_LOADED,r))}onAudioTrackLoaded(t,n){var r;const{levels:a}=this,{details:i,id:l,groupId:o,track:c}=n;if(!a){this.warn(`Audio tracks reset while loading track ${l} "${c.name}" of "${o}"`);return}const d=this.mainDetails;if(!d||i.endCC>d.endCC||d.expired){this.cachedTrackLoadedData=n,this.state!==cr.STOPPED&&(this.state=cr.WAITING_TRACK);return}this.cachedTrackLoadedData=null,this.log(`Audio track ${l} "${c.name}" of "${o}" loaded [${i.startSN},${i.endSN}]${i.lastPartSn?`[part-${i.lastPartSn}-${i.lastPartIndex}]`:""},duration:${i.totalduration}`);const u=a[l];let h=0;if(i.live||(r=u.details)!=null&&r.live){if(this.checkLiveUpdate(i),i.deltaUpdateFailed)return;if(u.details){var p;h=this.alignPlaylists(i,u.details,(p=this.levelLastLoaded)==null?void 0:p.details)}i.alignedSliding||(VNt(i,d),i.alignedSliding||qge(i,d),h=i.fragmentStart)}u.details=i,this.levelLastLoaded=u,this.startFragRequested||this.setStartPosition(d,h),this.hls.trigger(jt.AUDIO_TRACK_UPDATED,{details:i,id:l,groupId:n.groupId}),this.state===cr.WAITING_TRACK&&!this.waitForCdnTuneIn(i)&&(this.state=cr.IDLE),this.tick()}_handleFragmentLoadProgress(t){var n;const r=t.frag,{part:a,payload:i}=t,{config:l,trackId:o,levels:c}=this;if(!c){this.warn(`Audio tracks were reset while fragment load was in progress. Fragment ${r.sn} of level ${r.level} will not be buffered`);return}const d=c[o];if(!d){this.warn("Audio track is undefined on fragment load progress");return}const u=d.details;if(!u){this.warn("Audio track details undefined on fragment load progress"),this.removeUnbufferedFrags(r.start);return}const h=l.defaultAudioCodec||d.audioCodec||"mp4a.40.2";let p=this.transmuxer;p||(p=this.transmuxer=new dkt(this.hls,Wa.AUDIO,this._handleTransmuxComplete.bind(this),this._handleTransmuxerFlush.bind(this)));const f=this.initPTS[r.cc],y=(n=r.initSegment)==null?void 0:n.data;if(f!==void 0){const v=a?a.index:-1,j=v!==-1,w=new v8e(r.level,r.sn,r.stats.chunkCount,i.byteLength,v,j);p.push(i,y,h,"",r,a,u.totalduration,!1,w,f)}else{this.log(`Unknown video PTS for cc ${r.cc}, waiting for video PTS before demuxing audio frag ${r.sn} of [${u.startSN} ,${u.endSN}],track ${o}`);const{cache:_}=this.waitingData=this.waitingData||{frag:r,part:a,cache:new HNt,complete:!1};_.push(new Uint8Array(i)),this.state!==cr.STOPPED&&(this.state=cr.WAITING_INIT_PTS)}}_handleFragmentLoadComplete(t){if(this.waitingData){this.waitingData.complete=!0;return}super._handleFragmentLoadComplete(t)}onBufferReset(){this.mediaBuffer=null}onBufferCreated(t,n){this.bufferFlushed=this.flushing=!1;const r=n.tracks.audio;r&&(this.mediaBuffer=r.buffer||null)}onFragLoading(t,n){!this.audioOnly&&n.frag.type===Wa.MAIN&&Nh(n.frag)&&(this.mainFragLoading=n,this.state===cr.IDLE&&this.tick())}onFragBuffered(t,n){const{frag:r,part:a}=n;if(r.type!==Wa.AUDIO){!this.audioOnly&&r.type===Wa.MAIN&&!r.elementaryStreams.video&&!r.elementaryStreams.audiovideo&&(this.audioOnly=!0,this.mainFragLoading=null);return}if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${a?" p: "+a.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}, audioSwitch: ${this.switchingTrack?this.switchingTrack.name:"false"}`);return}if(Nh(r)){this.fragPrevious=r;const i=this.switchingTrack;i&&(this.bufferedTrack=i,this.switchingTrack=null,this.hls.trigger(jt.AUDIO_TRACK_SWITCHED,wc({},i)))}this.fragBufferedComplete(r,a),this.media&&this.tick()}onError(t,n){var r;if(n.fatal){this.state=cr.ERROR;return}switch(n.details){case Mn.FRAG_GAP:case Mn.FRAG_PARSING_ERROR:case Mn.FRAG_DECRYPT_ERROR:case Mn.FRAG_LOAD_ERROR:case Mn.FRAG_LOAD_TIMEOUT:case Mn.KEY_LOAD_ERROR:case Mn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Wa.AUDIO,n);break;case Mn.AUDIO_TRACK_LOAD_ERROR:case Mn.AUDIO_TRACK_LOAD_TIMEOUT:case Mn.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===cr.WAITING_TRACK&&((r=n.context)==null?void 0:r.type)===rl.AUDIO_TRACK&&(this.state=cr.IDLE);break;case Mn.BUFFER_ADD_CODEC_ERROR:case Mn.BUFFER_APPEND_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)||this.resetLoadingState();break;case Mn.BUFFER_FULL_ERROR:if(n.parent!=="audio")return;this.reduceLengthAndFlushBuffer(n)&&(this.bufferedTrack=null,super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"));break;case Mn.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onBufferFlushing(t,{type:n}){n!==Jc.VIDEO&&(this.flushing=!0)}onBufferFlushed(t,{type:n}){if(n!==Jc.VIDEO){this.flushing=!1,this.bufferFlushed=!0,this.state===cr.ENDED&&(this.state=cr.IDLE);const r=this.mediaBuffer||this.media;r&&(this.afterBufferFlushed(r,n,Wa.AUDIO),this.tick())}}_handleTransmuxComplete(t){var n;const r="audio",{hls:a}=this,{remuxResult:i,chunkMeta:l}=t,o=this.getCurrentContext(l);if(!o){this.resetWhenMissingContext(l);return}const{frag:c,part:d,level:u}=o,{details:h}=u,{audio:p,text:f,id3:y,initSegment:_}=i;if(this.fragContextChanged(c)||!h){this.fragmentTracker.removeFragment(c);return}if(this.state=cr.PARSING,this.switchingTrack&&p&&this.completeAudioSwitch(this.switchingTrack),_!=null&&_.tracks){const v=c.initSegment||c;if(this.unhandledEncryptionError(_,c))return;this._bufferInitSegment(u,_.tracks,v,l),a.trigger(jt.FRAG_PARSING_INIT_SEGMENT,{frag:v,id:r,tracks:_.tracks})}if(p){const{startPTS:v,endPTS:j,startDTS:w,endDTS:S}=p;d&&(d.elementaryStreams[Jc.AUDIO]={startPTS:v,endPTS:j,startDTS:w,endDTS:S}),c.setElementaryStreamInfo(Jc.AUDIO,v,j,w,S),this.bufferFragmentData(p,c,d,l)}if(y!=null&&(n=y.samples)!=null&&n.length){const v=Wc({id:r,frag:c,details:h},y);a.trigger(jt.FRAG_PARSING_METADATA,v)}if(f){const v=Wc({id:r,frag:c,details:h},f);a.trigger(jt.FRAG_PARSING_USERDATA,v)}}_bufferInitSegment(t,n,r,a){if(this.state!==cr.PARSING||(n.video&&delete n.video,n.audiovideo&&delete n.audiovideo,!n.audio))return;const i=n.audio;i.id=Wa.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(jt.BUFFER_CODECS,n);const o=i.initSegment;if(o!=null&&o.byteLength){const c={type:"audio",frag:r,part:null,chunkMeta:a,parent:r.type,data:o};this.hls.trigger(jt.BUFFER_APPENDING,c)}this.tickImmediate()}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);if(this.switchingTrack||a===Mm.NOT_LOADED||a===Mm.PARTIAL){var i;if(!Nh(t))this._loadInitSegment(t,n);else if((i=n.details)!=null&&i.live&&!this.initPTS[t.cc]){this.log(`Waiting for video PTS in continuity counter ${t.cc} of live stream before loading audio fragment ${t.sn} of level ${this.trackId}`),this.state=cr.WAITING_INIT_PTS;const l=this.mainDetails;l&&l.fragmentStart!==n.details.fragmentStart&&qge(n.details,l)}else super.loadFragment(t,n,r)}else this.clearTrackerIfNeeded(t)}flushAudioIfNeeded(t){if(this.media&&this.bufferedTrack){const{name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o}=this.bufferedTrack;eM({name:n,lang:r,assocLang:a,characteristics:i,audioCodec:l,channels:o},t,AE)||(Fge(t.url,this.hls)?(this.log("Switching audio track : flushing all audio"),super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio"),this.bufferedTrack=null):this.bufferedTrack=t)}}completeAudioSwitch(t){const{hls:n}=this;this.flushAudioIfNeeded(t),this.bufferedTrack=t,this.switchingTrack=null,n.trigger(jt.AUDIO_TRACK_SWITCHED,wc({},t))}}class A8e extends t1{constructor(t,n){super(n,t.logger),this.hls=void 0,this.canLoad=!1,this.timer=-1,this.hls=t}destroy(){this.clearTimer(),this.hls=this.log=this.warn=null}clearTimer(){this.timer!==-1&&(self.clearTimeout(this.timer),this.timer=-1)}startLoad(){this.canLoad=!0,this.loadPlaylist()}stopLoad(){this.canLoad=!1,this.clearTimer()}switchParams(t,n,r){const a=n==null?void 0:n.renditionReports;if(a){let i=-1;for(let l=0;l=0&&u>n.partTarget&&(c+=1)}const d=r&&OXe(r);return new FXe(o,c>=0?c:void 0,d)}}}loadPlaylist(t){this.clearTimer()}loadingPlaylist(t,n){this.clearTimer()}shouldLoadPlaylist(t){return this.canLoad&&!!t&&!!t.url&&(!t.details||t.details.live)}getUrlWithDirectives(t,n){if(n)try{return n.addDirectives(t)}catch(r){this.warn(`Could not construct new URL with HLS Delivery Directives: ${r}`)}return t}playlistLoaded(t,n,r){const{details:a,stats:i}=n,l=self.performance.now(),o=i.loading.first?Math.max(0,l-i.loading.first):0;a.advancedDateTime=Date.now()-o;const c=this.hls.config.timelineOffset;if(c!==a.appliedTimelineOffset){const u=Math.max(c||0,0);a.appliedTimelineOffset=u,a.fragments.forEach(h=>{h.setStart(h.playlistOffset+u)})}if(a.live||r!=null&&r.live){const u="levelInfo"in n?n.levelInfo:n.track;if(a.reloaded(r),r&&a.fragments.length>0){Hrn(r,a,this);const w=a.playlistParsingError;if(w){this.warn(w);const S=this.hls;if(!S.config.ignorePlaylistParsingErrors){var d;const{networkDetails:A}=n;S.trigger(jt.ERROR,{type:ui.NETWORK_ERROR,details:Mn.LEVEL_PARSING_ERROR,fatal:!1,url:a.url,error:w,reason:w.message,level:n.level||void 0,parent:(d=a.fragments[0])==null?void 0:d.type,networkDetails:A,stats:i});return}a.playlistParsingError=null}}a.requestScheduled===-1&&(a.requestScheduled=i.loading.start);const h=this.hls.mainForwardBufferInfo,p=h?h.end-h.len:0,f=(a.edge-p)*1e3,y=zNt(a,f);if(a.requestScheduled+y0){if(F>a.targetduration*3)this.log(`Playlist last advanced ${I.toFixed(2)}s ago. Omitting segment and part directives.`),v=void 0,j=void 0;else if(r!=null&&r.tuneInGoal&&F-a.partTarget>r.tuneInGoal)this.warn(`CDN Tune-in goal increased from: ${r.tuneInGoal} to: ${z} with playlist age: ${a.age}`),z=0;else{const H=Math.floor(z/a.targetduration);if(v+=H,j!==void 0){const Z=Math.round(z%a.targetduration/a.partTarget);j+=Z}this.log(`CDN Tune-in age: ${a.ageHeader}s last advanced ${I.toFixed(2)}s goal: ${z} skip sn ${H} to part ${j}`)}a.tuneInGoal=z}if(_=this.getDeliveryDirectives(a,n.deliveryDirectives,v,j),w||!D){a.requestScheduled=l,this.loadingPlaylist(u,_);return}}else(a.canBlockReload||a.canSkipUntil)&&(_=this.getDeliveryDirectives(a,n.deliveryDirectives,v,j));_&&v!==void 0&&a.canBlockReload&&(a.requestScheduled=i.loading.first+Math.max(y-o*2,y/2)),this.scheduleLoading(u,_,a)}else this.clearTimer()}scheduleLoading(t,n,r){const a=r||t.details;if(!a){this.loadingPlaylist(t,n);return}const i=self.performance.now(),l=a.requestScheduled;if(i>=l){this.loadingPlaylist(t,n);return}const o=l-i;this.log(`reload live playlist ${t.name||t.bitrate+"bps"} in ${Math.round(o)} ms`),this.clearTimer(),this.timer=self.setTimeout(()=>this.loadingPlaylist(t,n),o)}getDeliveryDirectives(t,n,r,a){let i=OXe(t);return n!=null&&n.skip&&t.deltaUpdateFailed&&(r=n.msn,a=n.part,i=Zme.No),new FXe(r,a,i)}checkRetry(t){const n=t.details,r=zge(t),a=t.errorAction,{action:i,retryCount:l=0,retryConfig:o}=a||{},c=!!a&&!!o&&(i===ef.RetryRequest||!a.resolved&&i===ef.SendAlternateToPenaltyBox);if(c){var d;if(l>=o.maxNumRetry)return!1;if(r&&(d=t.context)!=null&&d.deliveryDirectives)this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${n}" without delivery-directives`),this.loadPlaylist();else{const u=g8e(o,l);this.clearTimer(),this.timer=self.setTimeout(()=>this.loadPlaylist(),u),this.warn(`Retrying playlist loading ${l+1}/${o.maxNumRetry} after "${n}" in ${u}ms`)}t.levelRetry=!0,a.resolved=!0}return c}}function ukt(s,t){if(s.length!==t.length)return!1;for(let n=0;ns[a]!==t[a])}function wTe(s,t){return t.label.toLowerCase()===s.name.toLowerCase()&&(!t.language||t.language.toLowerCase()===(s.lang||"").toLowerCase())}class ein extends A8e{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(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(jt.LEVEL_LOADING,this.onLevelLoading,this),t.on(jt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(jt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.on(jt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(jt.LEVEL_LOADING,this.onLevelLoading,this),t.off(jt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(jt.AUDIO_TRACK_LOADED,this.onAudioTrackLoaded,this),t.off(jt.ERROR,this.onError,this)}destroy(){this.unregisterListeners(),this.tracks.length=0,this.tracksInGroup.length=0,this.currentTrack=null,super.destroy()}onManifestLoading(){this.tracks=[],this.tracksInGroup=[],this.groupIds=null,this.currentTrack=null,this.trackId=-1,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.audioTracks||[]}onAudioTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Audio track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Audio track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.audioGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(o=>(a==null?void 0:a.indexOf(o))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const o=this.tracks.filter(p=>!r||r.indexOf(p.groupId)!==-1);if(o.length)this.selectDefaultTrack&&!o.some(p=>p.default)&&(this.selectDefaultTrack=!1),o.forEach((p,f)=>{p.id=f});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=o;const c=this.hls.config.audioPreference;if(!i&&c){const p=rw(c,o,AE);if(p>-1)i=o[p];else{const f=rw(c,this.tracks);i=this.tracks[f]}}let d=this.findTrackId(i);d===-1&&i&&(d=this.findTrackId(null));const u={audioTracks:o};this.log(`Updating audio tracks, ${o.length} track(s) found in group(s): ${r==null?void 0:r.join(",")}`),this.hls.trigger(jt.AUDIO_TRACKS_UPDATED,u);const h=this.trackId;if(d!==-1&&h===-1)this.setAudioTrack(d);else if(o.length&&h===-1){var l;const p=new Error(`No audio track selected for current audio group-ID(s): ${(l=this.groupIds)==null?void 0:l.join(",")} track count: ${o.length}`);this.warn(p.message),this.hls.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.AUDIO_TRACK_LOAD_ERROR,fatal:!0,error:p})}}}onError(t,n){n.fatal||!n.context||n.context.type===rl.AUDIO_TRACK&&n.context.id===this.trackId&&(!this.groupIds||this.groupIds.indexOf(n.context.groupId)!==-1)&&this.checkRetry(n)}get allAudioTracks(){return this.tracks}get audioTracks(){return this.tracksInGroup}get audioTrack(){return this.trackId}set audioTrack(t){this.selectDefaultTrack=!1,this.setAudioTrack(t)}setAudioOption(t){const n=this.hls;if(n.config.audioPreference=t,t){const r=this.allAudioTracks;if(this.selectDefaultTrack=!1,r.length){const a=this.currentTrack;if(a&&eM(t,a,AE))return a;const i=rw(t,this.tracksInGroup,AE);if(i>-1){const l=this.tracksInGroup[i];return this.setAudioTrack(i),l}else if(a){let l=n.loadLevel;l===-1&&(l=n.firstAutoLevel);const o=hrn(t,n.levels,r,l,AE);if(o===-1)return null;n.nextLoadLevel=o}if(t.channels||t.audioCodec){const l=rw(t,r);if(l>-1)return r[l]}}}return null}setAudioTrack(t){const n=this.tracksInGroup;if(t<0||t>=n.length){this.warn(`Invalid audio track id: ${t}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,a=n[t],i=a.details&&!a.details.live;if(t===this.trackId&&a===r&&i||(this.log(`Switching to audio-track ${t} "${a.name}" lang:${a.lang} group:${a.groupId} channels:${a.channels}`),this.trackId=t,this.currentTrack=a,this.hls.trigger(jt.AUDIO_TRACK_SWITCHING,wc({},a)),i))return;const l=this.switchParams(a.url,r==null?void 0:r.details,a.details);this.loadPlaylist(l)}findTrackId(t){const n=this.tracksInGroup;for(let r=0;r{const r={label:"async-blocker",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.append(r,t)})}prependBlocker(t){return new Promise(n=>{if(this.queues){const r={label:"async-blocker-prepend",execute:n,onStart:()=>{},onComplete:()=>{},onError:()=>{}};this.queues[t].unshift(r)}})}removeBlockers(){this.queues!==null&&[this.queues.video,this.queues.audio,this.queues.audiovideo].forEach(t=>{var n;const r=(n=t[0])==null?void 0:n.label;(r==="async-blocker"||r==="async-blocker-prepend")&&(t[0].execute(),t.splice(0,1))})}unblockAudio(t){if(this.queues===null)return;this.queues.audio[0]===t&&this.shiftAndExecuteNext("audio")}executeNext(t){if(this.queues===null||this.tracks===null)return;const n=this.queues[t];if(n.length){const a=n[0];try{a.execute()}catch(i){var r;if(a.onError(i),this.queues===null||this.tracks===null)return;const l=(r=this.tracks[t])==null?void 0:r.buffer;l!=null&&l.updating||this.shiftAndExecuteNext(t)}}}shiftAndExecuteNext(t){this.queues!==null&&(this.queues[t].shift(),this.executeNext(t))}current(t){var n;return((n=this.queues)==null?void 0:n[t][0])||null}toString(){const{queues:t,tracks:n}=this;return t===null||n===null?"":` ${this.list("video")} ${this.list("audio")} ${this.list("audiovideo")}}`}list(t){var n,r;return(n=this.queues)!=null&&n[t]||(r=this.tracks)!=null&&r[t]?`${t}: (${this.listSbInfo(t)}) ${this.listOps(t)}`:""}listSbInfo(t){var n;const r=(n=this.tracks)==null?void 0:n[t],a=r==null?void 0:r.buffer;return a?`SourceBuffer${a.updating?" updating":""}${r.ended?" ended":""}${r.ending?" ending":""}`:"none"}listOps(t){var n;return((n=this.queues)==null?void 0:n[t].map(r=>r.label).join(", "))||""}}const jJe=/(avc[1234]|hvc1|hev1|dvh[1e]|vp09|av01)(?:\.[^.,]+)+/,hkt="HlsJsTrackRemovedError";class sin extends Error{constructor(t){super(t),this.name=hkt}}class nin extends t1{constructor(t,n){super("buffer-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.details=null,this._objectUrl=null,this.operationQueue=null,this.bufferCodecEventsTotal=0,this.media=null,this.mediaSource=null,this.lastMpegAudioChunk=null,this.blockedAudioAppend=null,this.lastVideoAppendEnd=0,this.appendSource=void 0,this.transferData=void 0,this.overrides=void 0,this.appendErrors={audio:0,video:0,audiovideo:0},this.tracks={},this.sourceBuffers=[[null,null],[null,null]],this._onEndStreaming=r=>{var a;this.hls&&((a=this.mediaSource)==null?void 0:a.readyState)==="open"&&this.hls.pauseBuffering()},this._onStartStreaming=r=>{this.hls&&this.hls.resumeBuffering()},this._onMediaSourceOpen=r=>{const{media:a,mediaSource:i}=this;r&&this.log("Media source opened"),!(!a||!i)&&(i.removeEventListener("sourceopen",this._onMediaSourceOpen),a.removeEventListener("emptied",this._onMediaEmptied),this.updateDuration(),this.hls.trigger(jt.MEDIA_ATTACHED,{media:a,mediaSource:i}),this.mediaSource!==null&&this.checkPendingTracks())},this._onMediaSourceClose=()=>{this.log("Media source closed")},this._onMediaSourceEnded=()=>{this.log("Media source ended")},this._onMediaEmptied=()=>{const{mediaSrc:r,_objectUrl:a}=this;r!==a&&this.error(`Media element src was set while attaching MediaSource (${a} > ${r})`)},this.hls=t,this.fragmentTracker=n,this.appendSource=knn(I4(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(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(jt.BUFFER_RESET,this.onBufferReset,this),t.on(jt.BUFFER_APPENDING,this.onBufferAppending,this),t.on(jt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(jt.BUFFER_EOS,this.onBufferEos,this),t.on(jt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(jt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(jt.FRAG_PARSED,this.onFragParsed,this),t.on(jt.FRAG_CHANGED,this.onFragChanged,this),t.on(jt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(jt.BUFFER_RESET,this.onBufferReset,this),t.off(jt.BUFFER_APPENDING,this.onBufferAppending,this),t.off(jt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(jt.BUFFER_EOS,this.onBufferEos,this),t.off(jt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(jt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(jt.FRAG_PARSED,this.onFragParsed,this),t.off(jt.FRAG_CHANGED,this.onFragChanged,this),t.off(jt.ERROR,this.onError,this)}transferMedia(){const{media:t,mediaSource:n}=this;if(!t)return null;const r={};if(this.operationQueue){const i=this.isUpdating();i||this.operationQueue.removeBlockers();const l=this.isQueued();(i||l)&&this.warn(`Transfering MediaSource with${l?" operations in queue":""}${i?" updating SourceBuffer(s)":""} ${this.operationQueue}`),this.operationQueue.destroy()}const a=this.transferData;return!this.sourceBufferCount&&a&&a.mediaSource===n?Wc(r,a.tracks):this.sourceBuffers.forEach(i=>{const[l]=i;l&&(r[l]=Wc({},this.tracks[l]),this.removeBuffer(l)),i[0]=i[1]=null}),{media:t,mediaSource:n,tracks:r}}initTracks(){const t={};this.sourceBuffers=[[null,null],[null,null]],this.tracks=t,this.resetQueue(),this.resetAppendErrors(),this.lastMpegAudioChunk=this.blockedAudioAppend=null,this.lastVideoAppendEnd=0}onManifestLoading(){this.bufferCodecEventsTotal=0,this.details=null}onManifestParsed(t,n){var r;let a=2;(n.audio&&!n.video||!n.altAudio)&&(a=1),this.bufferCodecEventsTotal=a,this.log(`${a} bufferCodec event(s) expected.`),(r=this.transferData)!=null&&r.mediaSource&&this.sourceBufferCount&&a&&this.bufferCreated()}onMediaAttaching(t,n){const r=this.media=n.media;this.transferData=this.overrides=void 0;const a=I4(this.appendSource);if(a){const i=!!n.mediaSource;(i||n.overrides)&&(this.transferData=n,this.overrides=n.overrides);const l=this.mediaSource=n.mediaSource||new a;if(this.assignMediaSource(l),i)this._objectUrl=r.src,this.attachTransferred();else{const o=this._objectUrl=self.URL.createObjectURL(l);if(this.appendSource)try{r.removeAttribute("src");const c=self.ManagedMediaSource;r.disableRemotePlayback=r.disableRemotePlayback||c&&l instanceof c,NJe(r),rin(r,o),r.load()}catch{r.src=o}else r.src=o}r.addEventListener("emptied",this._onMediaEmptied)}}assignMediaSource(t){var n,r;this.log(`${((n=this.transferData)==null?void 0:n.mediaSource)===t?"transferred":"created"} media source: ${(r=t.constructor)==null?void 0:r.name}`),t.addEventListener("sourceopen",this._onMediaSourceOpen),t.addEventListener("sourceended",this._onMediaSourceEnded),t.addEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(t.addEventListener("startstreaming",this._onStartStreaming),t.addEventListener("endstreaming",this._onEndStreaming))}attachTransferred(){const t=this.media,n=this.transferData;if(!n||!t)return;const r=this.tracks,a=n.tracks,i=a?Object.keys(a):null,l=i?i.length:0,o=()=>{Promise.resolve().then(()=>{this.media&&this.mediaSourceOpenOrEnded&&this._onMediaSourceOpen()})};if(a&&i&&l){if(!this.tracksReady){this.hls.config.startFragPrefetch=!0,this.log("attachTransferred: waiting for SourceBuffer track info");return}if(this.log(`attachTransferred: (bufferCodecEventsTotal ${this.bufferCodecEventsTotal}) required tracks: ${rd(r,(c,d)=>c==="initSegment"?void 0:d)}; transfer tracks: ${rd(a,(c,d)=>c==="initSegment"?void 0:d)}}`),!lNt(a,r)){n.mediaSource=null,n.tracks=void 0;const c=t.currentTime,d=this.details,u=Math.max(c,(d==null?void 0:d.fragments[0].start)||0);if(u-c>1){this.log(`attachTransferred: waiting for playback to reach new tracks start time ${c} -> ${u}`);return}this.warn(`attachTransferred: resetting MediaSource for incompatible tracks ("${Object.keys(a)}"->"${Object.keys(r)}") start time: ${u} currentTime: ${c}`),this.onMediaDetaching(jt.MEDIA_DETACHING,{}),this.onMediaAttaching(jt.MEDIA_ATTACHING,n),t.currentTime=u;return}this.transferData=void 0,i.forEach(c=>{const d=c,u=a[d];if(u){const h=u.buffer;if(h){const p=this.fragmentTracker,f=u.id;if(p.hasFragments(f)||p.hasParts(f)){const v=bo.getBuffered(h);p.detectEvictedFragments(d,v,f,null,!0)}const y=HNe(d),_=[d,h];this.sourceBuffers[y]=_,h.updating&&this.operationQueue&&this.operationQueue.prependBlocker(d),this.trackSourceBuffer(d,u)}}}),o(),this.bufferCreated()}else this.log("attachTransferred: MediaSource w/o SourceBuffers"),o()}get mediaSourceOpenOrEnded(){var t;const n=(t=this.mediaSource)==null?void 0:t.readyState;return n==="open"||n==="ended"}onMediaDetaching(t,n){const r=!!n.transferMedia;this.transferData=this.overrides=void 0;const{media:a,mediaSource:i,_objectUrl:l}=this;if(i){if(this.log(`media source ${r?"transferring":"detaching"}`),r)this.sourceBuffers.forEach(([o])=>{o&&this.removeBuffer(o)}),this.resetQueue();else{if(this.mediaSourceOpenOrEnded){const o=i.readyState==="open";try{const c=i.sourceBuffers;for(let d=c.length;d--;)o&&c[d].abort(),i.removeSourceBuffer(c[d]);o&&i.endOfStream()}catch(c){this.warn(`onMediaDetaching: ${c.message} while calling endOfStream`)}}this.sourceBufferCount&&this.onBufferReset()}i.removeEventListener("sourceopen",this._onMediaSourceOpen),i.removeEventListener("sourceended",this._onMediaSourceEnded),i.removeEventListener("sourceclose",this._onMediaSourceClose),this.appendSource&&(i.removeEventListener("startstreaming",this._onStartStreaming),i.removeEventListener("endstreaming",this._onEndStreaming)),this.mediaSource=null,this._objectUrl=null}a&&(a.removeEventListener("emptied",this._onMediaEmptied),r||(l&&self.URL.revokeObjectURL(l),this.mediaSrc===l?(a.removeAttribute("src"),this.appendSource&&NJe(a),a.load()):this.warn("media|source.src was changed by a third party - skip cleanup")),this.media=null),this.hls.trigger(jt.MEDIA_DETACHED,n)}onBufferReset(){this.sourceBuffers.forEach(([t])=>{t&&this.resetBuffer(t)}),this.initTracks()}resetBuffer(t){var n;const r=(n=this.tracks[t])==null?void 0:n.buffer;if(this.removeBuffer(t),r)try{var a;(a=this.mediaSource)!=null&&a.sourceBuffers.length&&this.mediaSource.removeSourceBuffer(r)}catch(i){this.warn(`onBufferReset ${t}`,i)}delete this.tracks[t]}removeBuffer(t){this.removeBufferListeners(t),this.sourceBuffers[HNe(t)]=[null,null];const n=this.tracks[t];n&&(n.buffer=void 0)}resetQueue(){this.operationQueue&&this.operationQueue.destroy(),this.operationQueue=new tin(this.tracks)}onBufferCodecs(t,n){var r;const a=this.tracks,i=Object.keys(n);this.log(`BUFFER_CODECS: "${i}" (current SB count ${this.sourceBufferCount})`);const l="audiovideo"in n&&(a.audio||a.video)||a.audiovideo&&("audio"in n||"video"in n),o=!l&&this.sourceBufferCount&&this.media&&i.some(c=>!a[c]);if(l||o){this.warn(`Unsupported transition between "${Object.keys(a)}" and "${i}" SourceBuffers`);return}i.forEach(c=>{var d,u;const h=n[c],{id:p,codec:f,levelCodec:y,container:_,metadata:v,supplemental:j}=h;let w=a[c];const S=(d=this.transferData)==null||(d=d.tracks)==null?void 0:d[c],A=S!=null&&S.buffer?S:w,E=(A==null?void 0:A.pendingCodec)||(A==null?void 0:A.codec),O=A==null?void 0:A.levelCodec;w||(w=a[c]={buffer:void 0,listeners:[],codec:f,supplemental:j,container:_,levelCodec:y,metadata:v,id:p});const D=Yme(E,O),I=D==null?void 0:D.replace(jJe,"$1");let F=Yme(f,y);const z=(u=F)==null?void 0:u.replace(jJe,"$1");F&&D&&I!==z&&(c.slice(0,5)==="audio"&&(F=Rge(F,this.appendSource)),this.log(`switching codec ${E} to ${F}`),F!==(w.pendingCodec||w.codec)&&(w.pendingCodec=F),w.container=_,this.appendChangeType(c,_,F))}),(this.tracksReady||this.sourceBufferCount)&&(n.tracks=this.sourceBufferTracks),!this.sourceBufferCount&&(this.bufferCodecEventsTotal>1&&!this.tracks.video&&!n.video&&((r=n.audio)==null?void 0:r.id)==="main"&&(this.log("Main audio-only"),this.bufferCodecEventsTotal=1),this.mediaSourceOpenOrEnded&&this.checkPendingTracks())}get sourceBufferTracks(){return Object.keys(this.tracks).reduce((t,n)=>{const r=this.tracks[n];return t[n]={id:r.id,container:r.container,codec:r.codec,levelCodec:r.levelCodec},t},{})}appendChangeType(t,n,r){const a=`${n};codecs=${r}`,i={label:`change-type=${a}`,execute:()=>{const l=this.tracks[t];if(l){const o=l.buffer;o!=null&&o.changeType&&(this.log(`changing ${t} sourceBuffer type to ${a}`),o.changeType(a),l.codec=r,l.container=n)}this.shiftAndExecuteNext(t)},onStart:()=>{},onComplete:()=>{},onError:l=>{this.warn(`Failed to change ${t} SourceBuffer type`,l)}};this.append(i,t,this.isPending(this.tracks[t]))}blockAudio(t){var n;const r=t.start,a=r+t.duration*.05;if(((n=this.fragmentTracker.getAppendedFrag(r,Wa.MAIN))==null?void 0:n.gap)===!0)return;const l={label:"block-audio",execute:()=>{var o;const c=this.tracks.video;(this.lastVideoAppendEnd>a||c!=null&&c.buffer&&bo.isBuffered(c.buffer,a)||((o=this.fragmentTracker.getAppendedFrag(a,Wa.MAIN))==null?void 0:o.gap)===!0)&&(this.blockedAudioAppend=null,this.shiftAndExecuteNext("audio"))},onStart:()=>{},onComplete:()=>{},onError:o=>{this.warn("Error executing block-audio operation",o)}};this.blockedAudioAppend={op:l,frag:t},this.append(l,"audio",!0)}unblockAudio(){const{blockedAudioAppend:t,operationQueue:n}=this;t&&n&&(this.blockedAudioAppend=null,n.unblockAudio(t.op))}onBufferAppending(t,n){const{tracks:r}=this,{data:a,type:i,parent:l,frag:o,part:c,chunkMeta:d,offset:u}=n,h=d.buffering[i],{sn:p,cc:f}=o,y=self.performance.now();h.start=y;const _=o.stats.buffering,v=c?c.stats.buffering:null;_.start===0&&(_.start=y),v&&v.start===0&&(v.start=y);const j=r.audio;let w=!1;i==="audio"&&(j==null?void 0:j.container)==="audio/mpeg"&&(w=!this.lastMpegAudioChunk||d.id===1||this.lastMpegAudioChunk.sn!==d.sn,this.lastMpegAudioChunk=d);const S=r.video,A=S==null?void 0:S.buffer;if(A&&p!=="initSegment"){const D=c||o,I=this.blockedAudioAppend;if(i==="audio"&&l!=="main"&&!this.blockedAudioAppend&&!(S.ending||S.ended)){const z=D.start+D.duration*.05,H=A.buffered,Z=this.currentOp("video");!H.length&&!Z?this.blockAudio(D):!Z&&!bo.isBuffered(A,z)&&this.lastVideoAppendEndz||F{var D;h.executeStart=self.performance.now();const I=(D=this.tracks[i])==null?void 0:D.buffer;I&&(w?this.updateTimestampOffset(I,E,.1,i,p,f):u!==void 0&&Pa(u)&&this.updateTimestampOffset(I,u,1e-6,i,p,f)),this.appendExecutor(a,i)},onStart:()=>{},onComplete:()=>{const D=self.performance.now();h.executeEnd=h.end=D,_.first===0&&(_.first=D),v&&v.first===0&&(v.first=D);const I={};this.sourceBuffers.forEach(([F,z])=>{F&&(I[F]=bo.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(jt.BUFFER_APPENDED,{type:i,frag:o,part:c,chunkMeta:d,parent:o.type,timeRanges:I})},onError:D=>{var I;const F={type:ui.MEDIA_ERROR,parent:o.type,details:Mn.BUFFER_APPEND_ERROR,sourceBufferName:i,frag:o,part:c,chunkMeta:d,error:D,err:D,fatal:!1},z=(I=this.media)==null?void 0:I.error;if(D.code===DOMException.QUOTA_EXCEEDED_ERR||D.name=="QuotaExceededError"||"quota"in D)F.details=Mn.BUFFER_FULL_ERROR;else if(D.code===DOMException.INVALID_STATE_ERR&&this.mediaSourceOpenOrEnded&&!z)F.errorAction=BL(!0);else if(D.name===hkt&&this.sourceBufferCount===0)F.errorAction=BL(!0);else{const H=++this.appendErrors[i];this.warn(`Failed ${H}/${this.hls.config.appendErrorMaxRetry} times to append segment in "${i}" sourceBuffer (${z||"no media error"})`),(H>=this.hls.config.appendErrorMaxRetry||z)&&(F.fatal=!0)}this.hls.trigger(jt.ERROR,F)}};this.log(`queuing "${i}" append sn: ${p}${c?" p: "+c.index:""} of ${o.type===Wa.MAIN?"level":"track"} ${o.level} cc: ${f}`),this.append(O,i,this.isPending(this.tracks[i]))}getFlushOp(t,n,r){return this.log(`queuing "${t}" remove ${n}-${r}`),{label:"remove",execute:()=>{this.removeExecutor(t,n,r)},onStart:()=>{},onComplete:()=>{this.hls.trigger(jt.BUFFER_FLUSHED,{type:t})},onError:a=>{this.warn(`Failed to remove ${n}-${r} from "${t}" SourceBuffer`,a)}}}onBufferFlushing(t,n){const{type:r,startOffset:a,endOffset:i}=n;r?this.append(this.getFlushOp(r,a,i),r):this.sourceBuffers.forEach(([l])=>{l&&this.append(this.getFlushOp(l,a,i),l)})}onFragParsed(t,n){const{frag:r,part:a}=n,i=[],l=a?a.elementaryStreams:r.elementaryStreams;l[Jc.AUDIOVIDEO]?i.push("audiovideo"):(l[Jc.AUDIO]&&i.push("audio"),l[Jc.VIDEO]&&i.push("video"));const o=()=>{const c=self.performance.now();r.stats.buffering.end=c,a&&(a.stats.buffering.end=c);const d=a?a.stats:r.stats;this.hls.trigger(jt.FRAG_BUFFERED,{frag:r,part:a,stats:d,id:r.type})};i.length===0&&this.warn(`Fragments must have at least one ElementaryStreamType set. type: ${r.type} level: ${r.level} sn: ${r.sn}`),this.blockBuffers(o,i).catch(c=>{this.warn(`Fragment buffered callback ${c}`),this.stepOperationQueue(this.sourceBufferTypes)})}onFragChanged(t,n){this.trimBuffers()}get bufferedToEnd(){return this.sourceBufferCount>0&&!this.sourceBuffers.some(([t])=>{if(t){const n=this.tracks[t];if(n)return!n.ended||n.ending}return!1})}onBufferEos(t,n){var r;this.sourceBuffers.forEach(([l])=>{if(l){const o=this.tracks[l];(!n.type||n.type===l)&&(o.ending=!0,o.ended||(o.ended=!0,this.log(`${l} buffer reached EOS`)))}});const a=((r=this.overrides)==null?void 0:r.endOfStream)!==!1;this.sourceBufferCount>0&&!this.sourceBuffers.some(([l])=>{var o;return l&&!((o=this.tracks[l])!=null&&o.ended)})?a?(this.log("Queueing EOS"),this.blockUntilOpen(()=>{this.tracksEnded();const{mediaSource:l}=this;if(!l||l.readyState!=="open"){l&&this.log(`Could not call mediaSource.endOfStream(). mediaSource.readyState: ${l.readyState}`);return}this.log("Calling mediaSource.endOfStream()"),l.endOfStream(),this.hls.trigger(jt.BUFFERED_TO_END,void 0)})):(this.tracksEnded(),this.hls.trigger(jt.BUFFERED_TO_END,void 0)):n.type==="video"&&this.unblockAudio()}tracksEnded(){this.sourceBuffers.forEach(([t])=>{if(t!==null){const n=this.tracks[t];n&&(n.ending=!1)}})}onLevelUpdated(t,{details:n}){n.fragments.length&&(this.details=n,this.updateDuration())}updateDuration(){this.blockUntilOpen(()=>{const t=this.getDurationAndRange();t&&this.updateMediaSource(t)})}onError(t,n){if(n.details===Mn.BUFFER_APPEND_ERROR&&n.frag){var r;const a=(r=n.errorAction)==null?void 0:r.nextAutoLevel;Pa(a)&&a!==n.frag.level&&this.resetAppendErrors()}}resetAppendErrors(){this.appendErrors={audio:0,video:0,audiovideo:0}}trimBuffers(){const{hls:t,details:n,media:r}=this;if(!r||n===null||!this.sourceBufferCount)return;const a=t.config,i=r.currentTime,l=n.levelTargetDuration,o=n.live&&a.liveBackBufferLength!==null?a.liveBackBufferLength:a.backBufferLength;if(Pa(o)&&o>=0){const d=Math.max(o,l),u=Math.floor(i/l)*l-d;this.flushBackBuffer(i,l,u)}const c=a.frontBufferFlushThreshold;if(Pa(c)&&c>0){const d=Math.max(a.maxBufferLength,c),u=Math.max(d,l),h=Math.floor(i/l)*l+u;this.flushFrontBuffer(i,l,h)}}flushBackBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const o=bo.getBuffered(i);if(o.length>0&&r>o.start(0)){var l;this.hls.trigger(jt.BACK_BUFFER_REACHED,{bufferEnd:r});const c=this.tracks[a];if((l=this.details)!=null&&l.live)this.hls.trigger(jt.LIVE_BACK_BUFFER_REACHED,{bufferEnd:r});else if(c!=null&&c.ended){this.log(`Cannot flush ${a} back buffer while SourceBuffer is in ended state`);return}this.hls.trigger(jt.BUFFER_FLUSHING,{startOffset:0,endOffset:r,type:a})}}})}flushFrontBuffer(t,n,r){this.sourceBuffers.forEach(([a,i])=>{if(i){const l=bo.getBuffered(i),o=l.length;if(o<2)return;const c=l.start(o-1),d=l.end(o-1);if(r>c||t>=c&&t<=d)return;this.hls.trigger(jt.BUFFER_FLUSHING,{startOffset:c,endOffset:1/0,type:a})}})}getDurationAndRange(){var t;const{details:n,mediaSource:r}=this;if(!n||!this.media||(r==null?void 0:r.readyState)!=="open")return null;const a=n.edge;if(n.live&&this.hls.config.liveDurationInfinity){if(n.fragments.length&&r.setLiveSeekableRange){const d=Math.max(0,n.fragmentStart),u=Math.max(d,a);return{duration:1/0,start:d,end:u}}return{duration:1/0}}const i=(t=this.overrides)==null?void 0:t.duration;if(i)return Pa(i)?{duration:i}:null;const l=this.media.duration,o=Pa(r.duration)?r.duration:0;return a>o&&a>l||!Pa(l)?{duration:a}:null}updateMediaSource({duration:t,start:n,end:r}){const a=this.mediaSource;!this.media||!a||a.readyState!=="open"||(a.duration!==t&&(Pa(t)&&this.log(`Updating MediaSource duration to ${t.toFixed(3)}`),a.duration=t),n!==void 0&&r!==void 0&&(this.log(`MediaSource duration is set to ${a.duration}. Setting seekable range to ${n}-${r}.`),a.setLiveSeekableRange(n,r)))}get tracksReady(){const t=this.pendingTrackCount;return t>0&&(t>=this.bufferCodecEventsTotal||this.isPending(this.tracks.audiovideo))}checkPendingTracks(){const{bufferCodecEventsTotal:t,pendingTrackCount:n,tracks:r}=this;if(this.log(`checkPendingTracks (pending: ${n} codec events expected: ${t}) ${rd(r)}`),this.tracksReady){var a;const i=(a=this.transferData)==null?void 0:a.tracks;i&&Object.keys(i).length?this.attachTransferred():this.createSourceBuffers()}}bufferCreated(){if(this.sourceBufferCount){const t={};this.sourceBuffers.forEach(([n,r])=>{if(n){const a=this.tracks[n];t[n]={buffer:r,container:a.container,codec:a.codec,supplemental:a.supplemental,levelCodec:a.levelCodec,id:a.id,metadata:a.metadata}}}),this.hls.trigger(jt.BUFFER_CREATED,{tracks:t}),this.log(`SourceBuffers created. Running queue: ${this.operationQueue}`),this.sourceBuffers.forEach(([n])=>{this.executeNext(n)})}else{const t=new Error("could not create source buffer for media codec(s)");this.hls.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.BUFFER_INCOMPATIBLE_CODECS_ERROR,fatal:!0,error:t,reason:t.message})}}createSourceBuffers(){const{tracks:t,sourceBuffers:n,mediaSource:r}=this;if(!r)throw new Error("createSourceBuffers called when mediaSource was null");for(const i in t){const l=i,o=t[l];if(this.isPending(o)){const c=this.getTrackCodec(o,l),d=`${o.container};codecs=${c}`;o.codec=c,this.log(`creating sourceBuffer(${d})${this.currentOp(l)?" Queued":""} ${rd(o)}`);try{const u=r.addSourceBuffer(d),h=HNe(l),p=[l,u];n[h]=p,o.buffer=u}catch(u){var a;this.error(`error while trying to add sourceBuffer: ${u.message}`),this.shiftAndExecuteNext(l),(a=this.operationQueue)==null||a.removeBlockers(),delete this.tracks[l],this.hls.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.BUFFER_ADD_CODEC_ERROR,fatal:!1,error:u,sourceBufferName:l,mimeType:d,parent:o.id});return}this.trackSourceBuffer(l,o)}}this.bufferCreated()}getTrackCodec(t,n){const r=t.supplemental;let a=t.codec;r&&(n==="video"||n==="audiovideo")&&h$(r,"video")&&(a=Wnn(a,r));const i=Yme(a,t.levelCodec);return i?n.slice(0,5)==="audio"?Rge(i,this.appendSource):i:""}trackSourceBuffer(t,n){const r=n.buffer;if(!r)return;const a=this.getTrackCodec(n,t);this.tracks[t]={buffer:r,codec:a,container:n.container,levelCodec:n.levelCodec,supplemental:n.supplemental,metadata:n.metadata,id:n.id,listeners:[]},this.removeBufferListeners(t),this.addBufferListener(t,"updatestart",this.onSBUpdateStart),this.addBufferListener(t,"updateend",this.onSBUpdateEnd),this.addBufferListener(t,"error",this.onSBUpdateError),this.appendSource&&this.addBufferListener(t,"bufferedchange",(i,l)=>{const o=l.removedRanges;o!=null&&o.length&&this.hls.trigger(jt.BUFFER_FLUSHED,{type:i})})}get mediaSrc(){var t,n;const r=((t=this.media)==null||(n=t.querySelector)==null?void 0:n.call(t,"source"))||this.media;return r==null?void 0:r.src}onSBUpdateStart(t){const n=this.currentOp(t);n&&n.onStart()}onSBUpdateEnd(t){var n;if(((n=this.mediaSource)==null?void 0:n.readyState)==="closed"){this.resetBuffer(t);return}const r=this.currentOp(t);r&&(r.onComplete(),this.shiftAndExecuteNext(t))}onSBUpdateError(t,n){var r;const a=new Error(`${t} SourceBuffer error. MediaSource readyState: ${(r=this.mediaSource)==null?void 0:r.readyState}`);this.error(`${a}`,n),this.hls.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.BUFFER_APPENDING_ERROR,sourceBufferName:t,error:a,fatal:!1});const i=this.currentOp(t);i&&i.onError(a)}updateTimestampOffset(t,n,r,a,i,l){const o=n-t.timestampOffset;Math.abs(o)>=r&&(this.log(`Updating ${a} SourceBuffer timestampOffset to ${n} (sn: ${i} cc: ${l})`),t.timestampOffset=n)}removeExecutor(t,n,r){const{media:a,mediaSource:i}=this,l=this.tracks[t],o=l==null?void 0:l.buffer;if(!a||!i||!o){this.warn(`Attempting to remove from the ${t} SourceBuffer, but it does not exist`),this.shiftAndExecuteNext(t);return}const c=Pa(a.duration)?a.duration:1/0,d=Pa(i.duration)?i.duration:1/0,u=Math.max(0,n),h=Math.min(r,c,d);h>u&&(!l.ending||l.ended)?(l.ended=!1,this.log(`Removing [${u},${h}] from the ${t} SourceBuffer`),o.remove(u,h)):this.shiftAndExecuteNext(t)}appendExecutor(t,n){const r=this.tracks[n],a=r==null?void 0:r.buffer;if(!a)throw new sin(`Attempting to append to the ${n} SourceBuffer, but it does not exist`);r.ending=!1,r.ended=!1,a.appendBuffer(t)}blockUntilOpen(t){if(this.isUpdating()||this.isQueued())this.blockBuffers(t).catch(n=>{this.warn(`SourceBuffer blocked callback ${n}`),this.stepOperationQueue(this.sourceBufferTypes)});else try{t()}catch(n){this.warn(`Callback run without blocking ${this.operationQueue} ${n}`)}}isUpdating(){return this.sourceBuffers.some(([t,n])=>t&&n.updating)}isQueued(){return this.sourceBuffers.some(([t])=>t&&!!this.currentOp(t))}isPending(t){return!!t&&!t.buffer}blockBuffers(t,n=this.sourceBufferTypes){if(!n.length)return this.log("Blocking operation requested, but no SourceBuffers exist"),Promise.resolve().then(t);const{operationQueue:r}=this,a=n.map(l=>this.appendBlocker(l));return n.length>1&&!!this.blockedAudioAppend&&this.unblockAudio(),Promise.all(a).then(l=>{r===this.operationQueue&&(t(),this.stepOperationQueue(this.sourceBufferTypes))})}stepOperationQueue(t){t.forEach(n=>{var r;const a=(r=this.tracks[n])==null?void 0:r.buffer;!a||a.updating||this.shiftAndExecuteNext(n)})}append(t,n,r){this.operationQueue&&this.operationQueue.append(t,n,r)}appendBlocker(t){if(this.operationQueue)return this.operationQueue.appendBlocker(t)}currentOp(t){return this.operationQueue?this.operationQueue.current(t):null}executeNext(t){t&&this.operationQueue&&this.operationQueue.executeNext(t)}shiftAndExecuteNext(t){this.operationQueue&&this.operationQueue.shiftAndExecuteNext(t)}get pendingTrackCount(){return Object.keys(this.tracks).reduce((t,n)=>t+(this.isPending(this.tracks[n])?1:0),0)}get sourceBufferCount(){return this.sourceBuffers.reduce((t,[n])=>t+(n?1:0),0)}get sourceBufferTypes(){return this.sourceBuffers.map(([t])=>t).filter(t=>!!t)}addBufferListener(t,n,r){const a=this.tracks[t];if(!a)return;const i=a.buffer;if(!i)return;const l=r.bind(this,t);a.listeners.push({event:n,listener:l}),i.addEventListener(n,l)}removeBufferListeners(t){const n=this.tracks[t];if(!n)return;const r=n.buffer;r&&(n.listeners.forEach(a=>{r.removeEventListener(a.event,a.listener)}),n.listeners.length=0)}}function NJe(s){const t=s.querySelectorAll("source");[].slice.call(t).forEach(n=>{s.removeChild(n)})}function rin(s,t){const n=self.document.createElement("source");n.type="video/mp4",n.src=t,s.appendChild(n)}function HNe(s){return s==="audio"?1:0}class M8e{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(jt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.on(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(jt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(jt.BUFFER_CODECS,this.onBufferCodecs,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListener(){const{hls:t}=this;t.off(jt.FPS_DROP_LEVEL_CAPPING,this.onFpsDropLevelCapping,this),t.off(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(jt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(jt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this)}onFpsDropLevelCapping(t,n){const r=this.hls.levels[n.droppedLevel];this.isLevelAllowed(r)&&this.restrictedLevels.push({bitrate:r.bitrate,height:r.height,width:r.width})}onMediaAttaching(t,n){this.media=n.media instanceof HTMLVideoElement?n.media:null,this.clientRect=null,this.timer&&this.hls.levels.length&&this.detectPlayerSize()}onManifestParsed(t,n){const r=this.hls;this.restrictedLevels=[],this.firstLevel=n.firstLevel,r.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onLevelsUpdated(t,n){this.timer&&Pa(this.autoLevelCapping)&&this.detectPlayerSize()}onBufferCodecs(t,n){this.hls.config.capLevelToPlayerSize&&n.video&&this.startCapping()}onMediaDetaching(){this.stopCapping(),this.media=null}detectPlayerSize(){if(this.media){if(this.mediaHeight<=0||this.mediaWidth<=0){this.clientRect=null;return}const t=this.hls.levels;if(t.length){const n=this.hls,r=this.getMaxLevel(t.length-1);r!==this.autoLevelCapping&&n.logger.log(`Setting autoLevelCapping to ${r}: ${t[r].height}p@${t[r].bitrate} for media ${this.mediaWidth}x${this.mediaHeight}`),n.autoLevelCapping=r,n.autoLevelEnabled&&n.autoLevelCapping>this.autoLevelCapping&&this.streamController&&this.streamController.nextLevelSwitch(),this.autoLevelCapping=n.autoLevelCapping}}}getMaxLevel(t){const n=this.hls.levels;if(!n.length)return-1;const r=n.filter((a,i)=>this.isLevelAllowed(a)&&i<=t);return this.clientRect=null,M8e.getMaxLevelByMediaSize(r,this.mediaWidth,this.mediaHeight)}startCapping(){this.timer||(this.autoLevelCapping=Number.POSITIVE_INFINITY,self.clearInterval(this.timer),this.timer=self.setInterval(this.detectPlayerSize.bind(this),1e3),this.detectPlayerSize())}stopCapping(){this.restrictedLevels=[],this.firstLevel=-1,this.autoLevelCapping=Number.POSITIVE_INFINITY,this.timer&&(self.clearInterval(this.timer),this.timer=void 0)}getDimensions(){if(this.clientRect)return this.clientRect;const t=this.media,n={width:0,height:0};if(t){const r=t.getBoundingClientRect();n.width=r.width,n.height=r.height,!n.width&&!n.height&&(n.width=r.right-r.left||t.width||0,n.height=r.bottom-r.top||t.height||0)}return this.clientRect=n,n}get mediaWidth(){return this.getDimensions().width*this.contentScaleFactor}get mediaHeight(){return this.getDimensions().height*this.contentScaleFactor}get contentScaleFactor(){let t=1;if(!this.hls.config.ignoreDevicePixelRatio)try{t=self.devicePixelRatio}catch{}return Math.min(t,this.hls.config.maxDevicePixelRatio)}isLevelAllowed(t){return!this.restrictedLevels.some(r=>t.bitrate===r.bitrate&&t.width===r.width&&t.height===r.height)}static getMaxLevelByMediaSize(t,n,r){if(!(t!=null&&t.length))return-1;const a=(o,c)=>c?o.width!==c.width||o.height!==c.height:!0;let i=t.length-1;const l=Math.max(n,r);for(let o=0;o=l||c.height>=l)&&a(c,t[o+1])){i=o;break}}return i}}const ain={MANIFEST:"m",AUDIO:"a",VIDEO:"v",MUXED:"av",INIT:"i",CAPTION:"c",TIMED_TEXT:"tt",KEY:"k",OTHER:"o"},jg=ain,iin={HLS:"h"},oin=iin;class Bw{constructor(t,n){Array.isArray(t)&&(t=t.map(r=>r instanceof Bw?r:new Bw(r))),this.value=t,this.params=n}}const lin="Dict";function cin(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 din(s,t,n,r){return new Error(`failed to ${s} "${cin(t)}" as ${n}`,{cause:r})}function $w(s,t,n){return din("serialize",s,t,n)}class mkt{constructor(t){this.description=t}}const kJe="Bare Item",uin="Boolean";function hin(s){if(typeof s!="boolean")throw $w(s,uin);return s?"?1":"?0"}function min(s){return btoa(String.fromCharCode(...s))}const pin="Byte Sequence";function fin(s){if(ArrayBuffer.isView(s)===!1)throw $w(s,pin);return`:${min(s)}:`}const xin="Integer";function gin(s){return s<-999999999999999||99999999999999912)throw $w(s,vin);const n=t.toString();return n.includes(".")?n:`${n}.0`}const _in="String",win=/[\x00-\x1f\x7f]+/;function jin(s){if(win.test(s))throw $w(s,_in);return`"${s.replace(/\\/g,"\\\\").replace(/"/g,'\\"')}"`}function Nin(s){return s.description||s.toString().slice(7,-1)}const kin="Token";function SJe(s){const t=Nin(s);if(/^([a-zA-Z*])([!#$%&'*+\-.^_`|~\w:/]*)$/.test(t)===!1)throw $w(t,kin);return t}function jTe(s){switch(typeof s){case"number":if(!Pa(s))throw $w(s,kJe);return Number.isInteger(s)?pkt(s):bin(s);case"string":return jin(s);case"symbol":return SJe(s);case"boolean":return hin(s);case"object":if(s instanceof Date)return yin(s);if(s instanceof Uint8Array)return fin(s);if(s instanceof mkt)return SJe(s);default:throw $w(s,kJe)}}const Sin="Key";function NTe(s){if(/^[a-z*][a-z0-9\-_.*]*$/.test(s)===!1)throw $w(s,Sin);return s}function I8e(s){return s==null?"":Object.entries(s).map(([t,n])=>n===!0?`;${NTe(t)}`:`;${NTe(t)}=${jTe(n)}`).join("")}function xkt(s){return s instanceof Bw?`${jTe(s.value)}${I8e(s.params)}`:jTe(s)}function Cin(s){return`(${s.value.map(xkt).join(" ")})${I8e(s.params)}`}function Tin(s,t={whitespace:!0}){if(typeof s!="object"||s==null)throw $w(s,lin);const n=s instanceof Map?s.entries():Object.entries(s),r=t!=null&&t.whitespace?" ":"";return Array.from(n).map(([a,i])=>{i instanceof Bw||(i=new Bw(i));let l=NTe(a);return i.value===!0?l+=I8e(i.params):(l+="=",Array.isArray(i.value)?l+=Cin(i):l+=xkt(i)),l}).join(`,${r}`)}function gkt(s,t){return Tin(s,t)}const T_="CMCD-Object",Qu="CMCD-Request",d3="CMCD-Session",Tk="CMCD-Status",Ein={br:T_,ab:T_,d:T_,ot:T_,tb:T_,tpb:T_,lb:T_,tab:T_,lab:T_,url:T_,pb:Qu,bl:Qu,tbl:Qu,dl:Qu,ltc:Qu,mtp:Qu,nor:Qu,nrr:Qu,rc:Qu,sn:Qu,sta:Qu,su:Qu,ttfb:Qu,ttfbb:Qu,ttlb:Qu,cmsdd:Qu,cmsds:Qu,smrt:Qu,df:Qu,cs:Qu,ts:Qu,cid:d3,pr:d3,sf:d3,sid:d3,st:d3,v:d3,msd:d3,bs:Tk,bsd:Tk,cdn:Tk,rtp:Tk,bg:Tk,pt:Tk,ec:Tk,e:Tk},Ain={REQUEST:Qu};function Min(s){return Object.keys(s).reduce((t,n)=>{var r;return(r=s[n])===null||r===void 0||r.forEach(a=>t[a]=n),t},{})}function Iin(s,t){const n={};if(!s)return n;const r=Object.keys(s),a=t?Min(t):{};return r.reduce((i,l)=>{var o;const c=Ein[l]||a[l]||Ain.REQUEST,d=(o=i[c])!==null&&o!==void 0?o:i[c]={};return d[l]=s[l],i},n)}function Pin(s){return["ot","sf","st","e","sta"].includes(s)}function Lin(s){return typeof s=="number"?Pa(s):s!=null&&s!==""&&s!==!1}const ykt="event";function Din(s,t){const n=new URL(s),r=new URL(t);if(n.origin!==r.origin)return s;const a=n.pathname.split("/").slice(1),i=r.pathname.split("/").slice(1,-1);for(;a[0]===i[0];)a.shift(),i.shift();for(;i.length;)i.shift(),a.unshift("..");return a.join("/")+n.search+n.hash}const epe=s=>Math.round(s),kTe=(s,t)=>Array.isArray(s)?s.map(n=>kTe(n,t)):s instanceof Bw&&typeof s.value=="string"?new Bw(kTe(s.value,t),s.params):(t.baseUrl&&(s=Din(s,t.baseUrl)),t.version===1?encodeURIComponent(s):s),MG=s=>epe(s/100)*100,Rin=(s,t)=>{let n=s;return t.version>=2&&(s instanceof Bw&&typeof s.value=="string"?n=new Bw([s]):typeof s=="string"&&(n=[s])),kTe(n,t)},Oin={br:epe,d:epe,bl:MG,dl:MG,mtp:MG,nor:Rin,rtp:MG,tb:epe},vkt="request",bkt="response",P8e=["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"],Fin=["e"],zin=/^[a-zA-Z0-9-.]+-[a-zA-Z0-9-.]+$/;function W1e(s){return zin.test(s)}function Bin(s){return P8e.includes(s)||Fin.includes(s)||W1e(s)}const _kt=["d","dl","nor","ot","rtp","su"];function $in(s){return P8e.includes(s)||_kt.includes(s)||W1e(s)}const Uin=["cmsdd","cmsds","rc","smrt","ttfb","ttfbb","ttlb","url"];function qin(s){return P8e.includes(s)||_kt.includes(s)||Uin.includes(s)||W1e(s)}const Vin=["bl","br","bs","cid","d","dl","mtp","nor","nrr","ot","pr","rtp","sf","sid","st","su","tb","v"];function Hin(s){return Vin.includes(s)||W1e(s)}const Gin={[bkt]:qin,[ykt]:Bin,[vkt]:$in};function wkt(s,t={}){const n={};if(s==null||typeof s!="object")return n;const r=t.version||s.v||1,a=t.reportingMode||vkt,i=r===1?Hin:Gin[a];let l=Object.keys(s).filter(i);const o=t.filter;typeof o=="function"&&(l=l.filter(o));const c=a===bkt||a===ykt;c&&!l.includes("ts")&&l.push("ts"),r>1&&!l.includes("v")&&l.push("v");const d=Wc({},Oin,t.formatters),u={version:r,reportingMode:a,baseUrl:t.baseUrl};return l.sort().forEach(h=>{let p=s[h];const f=d[h];if(typeof f=="function"&&(p=f(p,u)),h==="v"){if(r===1)return;p=r}h=="pr"&&p===1||(c&&h==="ts"&&!Pa(p)&&(p=Date.now()),Lin(p)&&(Pin(h)&&typeof p=="string"&&(p=new mkt(p)),n[h]=p))}),n}function Win(s,t={}){const n={};if(!s)return n;const r=wkt(s,t),a=Iin(r,t==null?void 0:t.customHeaderMap);return Object.entries(a).reduce((i,[l,o])=>{const c=gkt(o,{whitespace:!1});return c&&(i[l]=c),i},n)}function Kin(s,t,n){return Wc(s,Win(t,n))}const Yin="CMCD";function Zin(s,t={}){return s?gkt(wkt(s,t),{whitespace:!1}):""}function Qin(s,t={}){if(!s)return"";const n=Zin(s,t);return encodeURIComponent(n)}function Xin(s,t={}){if(!s)return"";const n=Qin(s,t);return`${Yin}=${n}`}const CJe=/CMCD=[^&#]+/;function Jin(s,t,n){const r=Xin(t,n);if(!r)return s;if(CJe.test(s))return s.replace(CJe,r);const a=s.includes("?")?"&":"?";return`${s}${a}${r}`}class eon{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:jg.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===jg.VIDEO||c===jg.AUDIO||c==jg.MUXED)&&(d.br=o.bitrate/1e3,d.tb=this.getTopBandwidth(c)/1e3,d.bl=this.getBufferLength(c));const u=l?this.getNextPart(l):this.getNextFrag(i);u!=null&&u.url&&u.url!==i.url&&(d.nor=u.url),this.apply(a,d)}catch(i){this.hls.logger.warn("Could not generate segment CMCD data.",i)}},this.hls=t;const n=this.config=t.config,{cmcd:r}=n;r!=null&&(n.pLoader=this.createPlaylistLoader(),n.fLoader=this.createFragmentLoader(),this.sid=r.sessionId||t.sessionId,this.cid=r.contentId,this.useHeaders=r.useHeaders===!0,this.includeKeys=r.includeKeys,this.registerListeners())}registerListeners(){const t=this.hls;t.on(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(jt.MEDIA_DETACHED,this.onMediaDetached,this),t.on(jt.BUFFER_CREATED,this.onBufferCreated,this)}unregisterListeners(){const t=this.hls;t.off(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(jt.MEDIA_DETACHED,this.onMediaDetached,this),t.off(jt.BUFFER_CREATED,this.onBufferCreated,this)}destroy(){this.unregisterListeners(),this.onMediaDetached(),this.hls=this.config=this.audioBuffer=this.videoBuffer=null,this.onWaiting=this.onPlaying=this.media=null}onMediaAttached(t,n){this.media=n.media,this.media.addEventListener("waiting",this.onWaiting),this.media.addEventListener("playing",this.onPlaying)}onMediaDetached(){this.media&&(this.media.removeEventListener("waiting",this.onWaiting),this.media.removeEventListener("playing",this.onPlaying),this.media=null)}onBufferCreated(t,n){var r,a;this.audioBuffer=(r=n.tracks.audio)==null?void 0:r.buffer,this.videoBuffer=(a=n.tracks.video)==null?void 0:a.buffer}createData(){var t;return{v:1,sf:oin.HLS,sid:this.sid,cid:this.cid,pr:(t=this.media)==null?void 0:t.playbackRate,mtp:this.hls.bandwidthEstimate/1e3}}apply(t,n={}){Wc(n,this.createData());const r=n.ot===jg.INIT||n.ot===jg.VIDEO||n.ot===jg.MUXED;this.starved&&r&&(n.bs=!0,n.su=!0,this.starved=!1),n.su==null&&(n.su=this.buffering);const{includeKeys:a}=this;a&&(n=Object.keys(n).reduce((l,o)=>(a.includes(o)&&(l[o]=n[o]),l),{}));const i={baseUrl:t.url};this.useHeaders?(t.headers||(t.headers={}),Kin(t.headers,n,i)):t.url=Jin(t.url,n,i)}getNextFrag(t){var n;const r=(n=this.hls.levels[t.level])==null?void 0:n.details;if(r){const a=t.sn-r.startSN;return r.fragments[a+1]}}getNextPart(t){var n;const{index:r,fragment:a}=t,i=(n=this.hls.levels[a.level])==null||(n=n.details)==null?void 0:n.partList;if(i){const{sn:l}=a;for(let o=i.length-1;o>=0;o--){const c=i[o];if(c.index===r&&c.fragment.sn===l)return i[o+1]}}}getObjectType(t){const{type:n}=t;if(n==="subtitle")return jg.TIMED_TEXT;if(t.sn==="initSegment")return jg.INIT;if(n==="audio")return jg.AUDIO;if(n==="main")return this.hls.audioTracks.length?jg.VIDEO:jg.MUXED}getTopBandwidth(t){let n=0,r;const a=this.hls;if(t===jg.AUDIO)r=a.audioTracks;else{const i=a.maxAutoLevel,l=i>-1?i+1:a.levels.length;r=a.levels.slice(0,l)}return r.forEach(i=>{i.bitrate>n&&(n=i.bitrate)}),n>0?n:NaN}getBufferLength(t){const n=this.media,r=t===jg.AUDIO?this.audioBuffer:this.videoBuffer;return!r||!n?NaN:bo.bufferInfo(r,n.currentTime,this.config.maxBufferHole).len*1e3}createPlaylistLoader(){const{pLoader:t}=this.config,n=this.applyPlaylistData,r=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){n(i),this.loader.load(i,l,o)}}}createFragmentLoader(){const{fLoader:t}=this.config,n=this.applyFragmentData,r=t||this.config.loader;return class{constructor(i){this.loader=void 0,this.loader=new r(i)}get stats(){return this.loader.stats}get context(){return this.loader.context}destroy(){this.loader.destroy()}abort(){this.loader.abort()}load(i,l,o){n(i),this.loader.load(i,l,o)}}}}const ton=3e5;class son extends t1{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(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(jt.ERROR,this.onError,this)}unregisterListeners(){const t=this.hls;t&&(t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(jt.ERROR,this.onError,this))}pathways(){return(this.levels||[]).reduce((t,n)=>(t.indexOf(n.pathwayId)===-1&&t.push(n.pathwayId),t),[])}get pathwayPriority(){return this._pathwayPriority}set pathwayPriority(t){this.updatePathwayPriority(t)}startLoad(){if(this.started=!0,this.clearTimeout(),this.enabled&&this.uri){if(this.updated){const t=this.timeToLoad*1e3-(performance.now()-this.updated);if(t>0){this.scheduleRefresh(this.uri,t);return}}this.loadSteeringManifest(this.uri)}}stopLoad(){this.started=!1,this.loader&&(this.loader.destroy(),this.loader=null),this.clearTimeout()}clearTimeout(){this.reloadTimer!==-1&&(self.clearTimeout(this.reloadTimer),this.reloadTimer=-1)}destroy(){this.unregisterListeners(),this.stopLoad(),this.hls=null,this.levels=this.audioTracks=this.subtitleTracks=null}removeLevel(t){const n=this.levels;n&&(this.levels=n.filter(r=>r!==t))}onManifestLoading(){this.stopLoad(),this.enabled=!0,this.timeToLoad=300,this.updated=0,this.uri=null,this.pathwayId=".",this.levels=this.audioTracks=this.subtitleTracks=null}onManifestLoaded(t,n){const{contentSteering:r}=n;r!==null&&(this.pathwayId=r.pathwayId,this.uri=r.uri,this.started&&this.startLoad())}onManifestParsed(t,n){this.audioTracks=n.audioTracks,this.subtitleTracks=n.subtitleTracks}onError(t,n){const{errorAction:r}=n;if((r==null?void 0:r.action)===ef.SendAlternateToPenaltyBox&&r.flags===O0.MoveAllAlternatesMatchingHost){const a=this.levels;let i=this._pathwayPriority,l=this.pathwayId;if(n.context){const{groupId:o,pathwayId:c,type:d}=n.context;o&&a?l=this.getPathwayForGroupId(o,d,l):c&&(l=c)}l in this.penalizedPathways||(this.penalizedPathways[l]=performance.now()),!i&&a&&(i=this.pathways()),i&&i.length>1&&(this.updatePathwayPriority(i),r.resolved=this.pathwayId!==l),n.details===Mn.BUFFER_APPEND_ERROR&&!n.fatal?r.resolved=!0:r.resolved||this.warn(`Could not resolve ${n.details} ("${n.error.message}") with content-steering for Pathway: ${l} levels: ${a&&a.length} priorities: ${rd(i)} penalized: ${rd(this.penalizedPathways)}`)}}filterParsedLevels(t){this.levels=t;let n=this.getLevelsForPathway(this.pathwayId);if(n.length===0){const r=t[0].pathwayId;this.log(`No levels found in Pathway ${this.pathwayId}. Setting initial Pathway to "${r}"`),n=this.getLevelsForPathway(r),this.pathwayId=r}return n.length!==t.length&&this.log(`Found ${n.length}/${t.length} levels in Pathway "${this.pathwayId}"`),n}getLevelsForPathway(t){return this.levels===null?[]:this.levels.filter(n=>t===n.pathwayId)}updatePathwayPriority(t){this._pathwayPriority=t;let n;const r=this.penalizedPathways,a=performance.now();Object.keys(r).forEach(i=>{a-r[i]>ton&&delete r[i]});for(let i=0;i0){this.log(`Setting Pathway to "${l}"`),this.pathwayId=l,UNt(n),this.hls.trigger(jt.LEVELS_UPDATED,{levels:n});const d=this.hls.levels[o];c&&d&&this.levels&&(d.attrs["STABLE-VARIANT-ID"]!==c.attrs["STABLE-VARIANT-ID"]&&d.bitrate!==c.bitrate&&this.log(`Unstable Pathways change from bitrate ${c.bitrate} to ${d.bitrate}`),this.hls.nextLoadLevel=o);break}}}getPathwayForGroupId(t,n,r){const a=this.getLevelsForPathway(r).concat(this.levels||[]);for(let i=0;i{const{ID:l,"BASE-ID":o,"URI-REPLACEMENT":c}=i;if(n.some(u=>u.pathwayId===l))return;const d=this.getLevelsForPathway(o).map(u=>{const h=new bu(u.attrs);h["PATHWAY-ID"]=l;const p=h.AUDIO&&`${h.AUDIO}_clone_${l}`,f=h.SUBTITLES&&`${h.SUBTITLES}_clone_${l}`;p&&(r[h.AUDIO]=p,h.AUDIO=p),f&&(a[h.SUBTITLES]=f,h.SUBTITLES=f);const y=jkt(u.uri,h["STABLE-VARIANT-ID"],"PER-VARIANT-URIS",c),_=new p$({attrs:h,audioCodec:u.audioCodec,bitrate:u.bitrate,height:u.height,name:u.name,url:y,videoCodec:u.videoCodec,width:u.width});if(u.audioGroups)for(let v=1;v{this.log(`Loaded steering manifest: "${a}"`);const y=u.data;if((y==null?void 0:y.VERSION)!==1){this.log(`Steering VERSION ${y.VERSION} not supported!`);return}this.updated=performance.now(),this.timeToLoad=y.TTL;const{"RELOAD-URI":_,"PATHWAY-CLONES":v,"PATHWAY-PRIORITY":j}=y;if(_)try{this.uri=new self.URL(_,a).href}catch{this.enabled=!1,this.log(`Failed to parse Steering Manifest RELOAD-URI: ${_}`);return}this.scheduleRefresh(this.uri||p.url),v&&this.clonePathways(v);const w={steeringManifest:y,url:a.toString()};this.hls.trigger(jt.STEERING_MANIFEST_LOADED,w),j&&this.updatePathwayPriority(j)},onError:(u,h,p,f)=>{if(this.log(`Error loading steering manifest: ${u.code} ${u.text} (${h.url})`),this.stopLoad(),u.code===410){this.enabled=!1,this.log(`Steering manifest ${h.url} no longer available`);return}let y=this.timeToLoad*1e3;if(u.code===429){const _=this.loader;if(typeof(_==null?void 0:_.getResponseHeader)=="function"){const v=_.getResponseHeader("Retry-After");v&&(y=parseFloat(v)*1e3)}this.log(`Steering manifest ${h.url} rate limited`);return}this.scheduleRefresh(this.uri||h.url,y)},onTimeout:(u,h,p)=>{this.log(`Timeout loading steering manifest (${h.url})`),this.scheduleRefresh(this.uri||h.url)}};this.log(`Requesting steering manifest: ${a}`),this.loader.load(i,c,d)}scheduleRefresh(t,n=this.timeToLoad*1e3){this.clearTimeout(),this.reloadTimer=self.setTimeout(()=>{var r;const a=(r=this.hls)==null?void 0:r.media;if(a&&!a.ended){this.loadSteeringManifest(t);return}this.scheduleRefresh(t,this.timeToLoad*1e3)},n)}}function TJe(s,t,n,r){s&&Object.keys(t).forEach(a=>{const i=s.filter(l=>l.groupId===a).map(l=>{const o=Wc({},l);return o.details=void 0,o.attrs=new bu(o.attrs),o.url=o.attrs.URI=jkt(l.url,l.attrs["STABLE-RENDITION-ID"],"PER-RENDITION-URIS",n),o.groupId=o.attrs["GROUP-ID"]=t[a],o.attrs["PATHWAY-ID"]=r,o});s.push(...i)})}function jkt(s,t,n,r){const{HOST:a,PARAMS:i,[n]:l}=r;let o;t&&(o=l==null?void 0:l[t],o&&(s=o));const c=new self.URL(s);return a&&!o&&(c.host=a),i&&Object.keys(i).sort().forEach(d=>{d&&c.searchParams.set(d,i[d])}),c.href}class UL extends t1{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=UL.CDMCleanupPromise?[UL.CDMCleanupPromise]:[],this.bannedKeyIds={},this.onMediaEncrypted=n=>{const{initDataType:r,initData:a}=n,i=`"${n.type}" event: init data type: "${r}"`;if(this.debug(i),a!==null){if(!this.keyFormatPromise){let l=Object.keys(this.keySystemAccessPromises);l.length||(l=v7(this.config));const o=l.map(ONe).filter(c=>!!c);this.keyFormatPromise=this.getKeyFormatPromise(o)}this.keyFormatPromise.then(l=>{const o=Qme(l);if(r!=="sinf"||o!==Cu.FAIRPLAY){this.log(`Ignoring "${n.type}" event with init data type: "${r}" for selected key-system ${o}`);return}let c;try{const f=Tm(new Uint8Array(a)),y=_8e(JSON.parse(f).sinf),_=gNt(y);if(!_)throw new Error("'schm' box missing or not cbcs/cenc with schi > tenc");c=new Uint8Array(_.subarray(8,24))}catch(f){this.warn(`${i} Failed to parse sinf: ${f}`);return}const d=tf(c),{keyIdToKeySessionPromise:u,mediaKeySessions:h}=this;let p=u[d];for(let f=0;fthis.generateRequestWithPreferredKeySession(y,r,a,"encrypted-event-key-match")),p.catch(j=>this.handleError(j));break}}p||this.handleError(new Error(`Key ID ${d} not encountered in playlist. Key-system sessions ${h.length}.`))}).catch(l=>this.handleError(l))}},this.onWaitingForKey=n=>{this.log(`"${n.type}" event`)},this.hls=t,this.config=t.config,this.registerListeners()}destroy(){this.onDestroying(),this.onMediaDetached();const t=this.config;t.requestMediaKeySystemAccessFunc=null,t.licenseXhrSetup=t.licenseResponseCallback=void 0,t.drmSystems=t.drmSystemOptions={},this.hls=this.config=this.keyIdToKeySessionPromise=null,this.onMediaEncrypted=this.onWaitingForKey=null}registerListeners(){this.hls.on(jt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.on(jt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.on(jt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.on(jt.DESTROYING,this.onDestroying,this)}unregisterListeners(){this.hls.off(jt.MEDIA_ATTACHED,this.onMediaAttached,this),this.hls.off(jt.MEDIA_DETACHED,this.onMediaDetached,this),this.hls.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),this.hls.off(jt.MANIFEST_LOADED,this.onManifestLoaded,this),this.hls.off(jt.DESTROYING,this.onDestroying,this)}getLicenseServerUrl(t){const{drmSystems:n,widevineLicenseUrl:r}=this.config,a=n==null?void 0:n[t];if(a)return a.licenseUrl;if(t===Cu.WIDEVINE&&r)return r}getLicenseServerUrlOrThrow(t){const n=this.getLicenseServerUrl(t);if(n===void 0)throw new Error(`no license server URL configured for key-system "${t}"`);return n}getServerCertificateUrl(t){const{drmSystems:n}=this.config,r=n==null?void 0:n[t];if(r)return r.serverCertificateUrl;this.log(`No Server Certificate in config.drmSystems["${t}"]`)}attemptKeySystemAccess(t){const n=this.hls.levels,r=(l,o,c)=>!!l&&c.indexOf(l)===o,a=n.map(l=>l.audioCodec).filter(r),i=n.map(l=>l.videoCodec).filter(r);return a.length+i.length===0&&i.push("avc1.42e01e"),new Promise((l,o)=>{const c=d=>{const u=d.shift();this.getMediaKeysPromise(u,a,i).then(h=>l({keySystem:u,mediaKeys:h})).catch(h=>{d.length?c(d):h instanceof L0?o(h):o(new L0({type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_NO_ACCESS,error:h,fatal:!0},h.message))})};c(t)})}requestMediaKeySystemAccess(t,n){const{requestMediaKeySystemAccessFunc:r}=this.config;if(typeof r!="function"){let a=`Configured requestMediaKeySystemAccess is not a function ${r}`;return LNt===null&&self.location.protocol==="http:"&&(a=`navigator.requestMediaKeySystemAccess is not available over insecure protocol ${location.protocol}`),Promise.reject(new Error(a))}return r(t,n)}getMediaKeysPromise(t,n,r){var a;const i=Rrn(t,n,r,this.config.drmSystemOptions||{});let l=this.keySystemAccessPromises[t],o=(a=l)==null?void 0:a.keySystemAccess;if(!o){this.log(`Requesting encrypted media "${t}" key-system access with config: ${rd(i)}`),o=this.requestMediaKeySystemAccess(t,i);const c=l=this.keySystemAccessPromises[t]={keySystemAccess:o};return o.catch(d=>{this.log(`Failed to obtain access to key-system "${t}": ${d}`)}),o.then(d=>{this.log(`Access for key-system "${d.keySystem}" obtained`);const u=this.fetchServerCertificate(t);this.log(`Create media-keys for "${t}"`);const h=c.mediaKeys=d.createMediaKeys().then(p=>(this.log(`Media-keys created for "${t}"`),c.hasMediaKeys=!0,u.then(f=>f?this.setMediaKeysServerCertificate(p,t,f):p)));return h.catch(p=>{this.error(`Failed to create media-keys for "${t}"}: ${p}`)}),h})}return o.then(()=>l.mediaKeys)}createMediaKeySessionContext({decryptdata:t,keySystem:n,mediaKeys:r}){this.log(`Creating key-system session "${n}" keyId: ${tf(t.keyId||[])} keyUri: ${t.uri}`);const a=r.createSession(),i={decryptdata:t,keySystem:n,mediaKeys:r,mediaKeysSession:a,keyStatus:"status-pending"};return this.mediaKeySessions.push(i),i}renewKeySession(t){const n=t.decryptdata;if(n.pssh){const r=this.createMediaKeySessionContext(t),a=IG(n),i="cenc";this.keyIdToKeySessionPromise[a]=this.generateRequestWithPreferredKeySession(r,i,n.pssh.buffer,"expired")}else this.warn("Could not renew expired session. Missing pssh initData.");this.removeSession(t)}updateKeySession(t,n){const r=t.mediaKeysSession;return this.log(`Updating key-session "${r.sessionId}" for keyId ${tf(t.decryptdata.keyId||[])} } (data length: ${n.byteLength})`),r.update(n)}getSelectedKeySystemFormats(){return Object.keys(this.keySystemAccessPromises).map(t=>({keySystem:t,hasMediaKeys:this.keySystemAccessPromises[t].hasMediaKeys})).filter(({hasMediaKeys:t})=>!!t).map(({keySystem:t})=>ONe(t)).filter(t=>!!t)}getKeySystemAccess(t){return this.getKeySystemSelectionPromise(t).then(({keySystem:n,mediaKeys:r})=>this.attemptSetMediaKeys(n,r))}selectKeySystem(t){return new Promise((n,r)=>{this.getKeySystemSelectionPromise(t).then(({keySystem:a})=>{const i=ONe(a);i?n(i):r(new Error(`Unable to find format for key-system "${a}"`))}).catch(r)})}selectKeySystemFormat(t){const n=Object.keys(t.levelkeys||{});return this.keyFormatPromise||(this.log(`Selecting key-system from fragment (sn: ${t.sn} ${t.type}: ${t.level}) key formats ${n.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(n)),this.keyFormatPromise}getKeyFormatPromise(t){const n=v7(this.config),r=t.map(Qme).filter(a=>!!a&&n.indexOf(a)!==-1);return this.selectKeySystem(r)}getKeyStatus(t){const{mediaKeySessions:n}=this;for(let r=0;r(this.throwIfDestroyed(),this.log(`Handle encrypted media sn: ${t.frag.sn} ${t.frag.type}: ${t.frag.level} using key ${i}`),this.attemptSetMediaKeys(c,d).then(()=>(this.throwIfDestroyed(),this.createMediaKeySessionContext({keySystem:c,mediaKeys:d,decryptdata:n}))))).then(c=>{const d="cenc",u=n.pssh?n.pssh.buffer:null;return this.generateRequestWithPreferredKeySession(c,d,u,"playlist-key")});return o.catch(c=>this.handleError(c,t.frag)),this.keyIdToKeySessionPromise[r]=o,o}return l.catch(o=>{if(o instanceof L0){const c=wc({},o.data);this.getKeyStatus(n)==="internal-error"&&(c.decryptdata=n);const d=new L0(c,o.message);this.handleError(d,t.frag)}}),l}throwIfDestroyed(t="Invalid state"){if(!this.hls)throw new Error("invalid state")}handleError(t,n){if(this.hls)if(t instanceof L0){n&&(t.data.frag=n);const r=t.data.decryptdata;this.error(`${t.message}${r?` (${tf(r.keyId||[])})`:""}`),this.hls.trigger(jt.ERROR,t.data)}else this.error(t.message),this.hls.trigger(jt.ERROR,{type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_NO_KEYS,error:t,fatal:!0})}getKeySystemForKeyPromise(t){const n=IG(t),r=this.keyIdToKeySessionPromise[n];if(!r){const a=Qme(t.keyFormat),i=a?[a]:v7(this.config);return this.attemptKeySystemAccess(i)}return r}getKeySystemSelectionPromise(t){if(t.length||(t=v7(this.config)),t.length===0)throw new L0({type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_NO_CONFIGURED_LICENSE,fatal:!0},`Missing key-system license configuration options ${rd({drmSystems:this.config.drmSystems})}`);return this.attemptKeySystemAccess(t)}attemptSetMediaKeys(t,n){if(this.mediaResolved=void 0,this.mediaKeys===n)return Promise.resolve();const r=this.setMediaKeysQueue.slice();this.log(`Setting media-keys for "${t}"`);const a=Promise.all(r).then(()=>this.media?this.media.setMediaKeys(n):new Promise((i,l)=>{this.mediaResolved=()=>{if(this.mediaResolved=void 0,!this.media)return l(new Error("Attempted to set mediaKeys without media element attached"));this.mediaKeys=n,this.media.setMediaKeys(n).then(i).catch(l)}}));return this.mediaKeys=n,this.setMediaKeysQueue.push(a),a.then(()=>{this.log(`Media-keys set for "${t}"`),r.push(a),this.setMediaKeysQueue=this.setMediaKeysQueue.filter(i=>r.indexOf(i)===-1)})}generateRequestWithPreferredKeySession(t,n,r,a){var i;const l=(i=this.config.drmSystems)==null||(i=i[t.keySystem])==null?void 0:i.generateRequest;if(l)try{const y=l.call(this.hls,n,r,t);if(!y)throw new Error("Invalid response from configured generateRequest filter");n=y.initDataType,r=y.initData?y.initData:null,t.decryptdata.pssh=r?new Uint8Array(r):null}catch(y){if(this.warn(y.message),this.hls&&this.hls.config.debug)throw y}if(r===null)return this.log(`Skipping key-session request for "${a}" (no initData)`),Promise.resolve(t);const o=IG(t.decryptdata),c=t.decryptdata.uri;this.log(`Generating key-session request for "${a}" keyId: ${o} URI: ${c} (init data type: ${n} length: ${r.byteLength})`);const d=new j8e,u=t._onmessage=y=>{const _=t.mediaKeysSession;if(!_){d.emit("error",new Error("invalid state"));return}const{messageType:v,message:j}=y;this.log(`"${v}" message event for session "${_.sessionId}" message size: ${j.byteLength}`),v==="license-request"||v==="license-renewal"?this.renewLicense(t,j).catch(w=>{d.eventNames().length?d.emit("error",w):this.handleError(w)}):v==="license-release"?t.keySystem===Cu.FAIRPLAY&&this.updateKeySession(t,gTe("acknowledged")).then(()=>this.removeSession(t)).catch(w=>this.handleError(w)):this.warn(`unhandled media key message type "${v}"`)},h=(y,_)=>{_.keyStatus=y;let v;y.startsWith("usable")?d.emit("resolved"):y==="internal-error"||y==="output-restricted"||y==="output-downscaled"?v=EJe(y,_.decryptdata):y==="expired"?v=new Error(`key expired (keyId: ${o})`):y==="released"?v=new Error("key released"):y==="status-pending"||this.warn(`unhandled key status change "${y}" (keyId: ${o})`),v&&(d.eventNames().length?d.emit("error",v):this.handleError(v))},p=t._onkeystatuseschange=y=>{if(!t.mediaKeysSession){d.emit("error",new Error("invalid state"));return}const v=this.getKeyStatuses(t);if(!Object.keys(v).some(A=>v[A]!=="status-pending"))return;if(v[o]==="expired"){this.log(`Expired key ${rd(v)} in key-session "${t.mediaKeysSession.sessionId}"`),this.renewKeySession(t);return}let w=v[o];if(w)h(w,t);else{var S;t.keyStatusTimeouts||(t.keyStatusTimeouts={}),(S=t.keyStatusTimeouts)[o]||(S[o]=self.setTimeout(()=>{if(!t.mediaKeysSession||!this.mediaKeys)return;const E=this.getKeyStatus(t.decryptdata);if(E&&E!=="status-pending")return this.log(`No status for keyId ${o} in key-session "${t.mediaKeysSession.sessionId}". Using session key-status ${E} from other session.`),h(E,t);this.log(`key status for ${o} in key-session "${t.mediaKeysSession.sessionId}" timed out after 1000ms`),w="internal-error",h(w,t)},1e3)),this.log(`No status for keyId ${o} (${rd(v)}).`)}};Xx(t.mediaKeysSession,"message",u),Xx(t.mediaKeysSession,"keystatuseschange",p);const f=new Promise((y,_)=>{d.on("error",_),d.on("resolved",y)});return t.mediaKeysSession.generateRequest(n,r).then(()=>{this.log(`Request generated for key-session "${t.mediaKeysSession.sessionId}" keyId: ${o} URI: ${c}`)}).catch(y=>{throw new L0({type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_NO_SESSION,error:y,decryptdata:t.decryptdata,fatal:!1},`Error generating key-session request: ${y}`)}).then(()=>f).catch(y=>(d.removeAllListeners(),this.removeSession(t).then(()=>{throw y}))).then(()=>(d.removeAllListeners(),t))}getKeyStatuses(t){const n={};return t.mediaKeysSession.keyStatuses.forEach((r,a)=>{if(typeof a=="string"&&typeof r=="object"){const o=a;a=r,r=o}const i="buffer"in a?new Uint8Array(a.buffer,a.byteOffset,a.byteLength):new Uint8Array(a);if(t.keySystem===Cu.PLAYREADY&&i.length===16){const o=tf(i);n[o]=r,INt(i)}const l=tf(i);r==="internal-error"&&(this.bannedKeyIds[l]=r),this.log(`key status change "${r}" for keyStatuses keyId: ${l} key-session "${t.mediaKeysSession.sessionId}"`),n[l]=r}),n}fetchServerCertificate(t){const n=this.config,r=n.loader,a=new r(n),i=this.getServerCertificateUrl(t);return i?(this.log(`Fetching server certificate for "${t}"`),new Promise((l,o)=>{const c={responseType:"arraybuffer",url:i},d=n.certLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(p,f,y,_)=>{l(p.data)},onError:(p,f,y,_)=>{o(new L0({type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:wc({url:c.url,data:void 0},p)},`"${t}" certificate request failed (${i}). Status: ${p.code} (${p.text})`))},onTimeout:(p,f,y)=>{o(new L0({type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_SERVER_CERTIFICATE_REQUEST_FAILED,fatal:!0,networkDetails:y,response:{url:c.url,data:void 0}},`"${t}" certificate request timed out (${i})`))},onAbort:(p,f,y)=>{o(new Error("aborted"))}};a.load(c,u,h)})):Promise.resolve()}setMediaKeysServerCertificate(t,n,r){return new Promise((a,i)=>{t.setServerCertificate(r).then(l=>{this.log(`setServerCertificate ${l?"success":"not supported by CDM"} (${r.byteLength}) on "${n}"`),a(t)}).catch(l=>{i(new L0({type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_SERVER_CERTIFICATE_UPDATE_FAILED,error:l,fatal:!0},l.message))})})}renewLicense(t,n){return this.requestLicense(t,new Uint8Array(n)).then(r=>this.updateKeySession(t,new Uint8Array(r)).catch(a=>{throw new L0({type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_SESSION_UPDATE_FAILED,decryptdata:t.decryptdata,error:a,fatal:!1},a.message)}))}unpackPlayReadyKeyMessage(t,n){const r=String.fromCharCode.apply(null,new Uint16Array(n.buffer));if(!r.includes("PlayReadyKeyMessage"))return t.setRequestHeader("Content-Type","text/xml; charset=utf-8"),n;const a=new DOMParser().parseFromString(r,"application/xml"),i=a.querySelectorAll("HttpHeader");if(i.length>0){let u;for(let h=0,p=i.length;h in key message");return gTe(atob(d))}setupLicenseXHR(t,n,r,a){const i=this.config.licenseXhrSetup;return i?Promise.resolve().then(()=>{if(!r.decryptdata)throw new Error("Key removed");return i.call(this.hls,t,n,r,a)}).catch(l=>{if(!r.decryptdata)throw l;return t.open("POST",n,!0),i.call(this.hls,t,n,r,a)}).then(l=>(t.readyState||t.open("POST",n,!0),{xhr:t,licenseChallenge:l||a})):(t.open("POST",n,!0),Promise.resolve({xhr:t,licenseChallenge:a}))}requestLicense(t,n){const r=this.config.keyLoadPolicy.default;return new Promise((a,i)=>{const l=this.getLicenseServerUrlOrThrow(t.keySystem);this.log(`Sending license request to URL: ${l}`);const o=new XMLHttpRequest;o.responseType="arraybuffer",o.onreadystatechange=()=>{if(!this.hls||!t.mediaKeysSession)return i(new Error("invalid state"));if(o.readyState===4)if(o.status===200){this._requestLicenseFailureCount=0;let c=o.response;this.log(`License received ${c instanceof ArrayBuffer?c.byteLength:c}`);const d=this.config.licenseResponseCallback;if(d)try{c=d.call(this.hls,o,l,t)}catch(u){this.error(u)}a(c)}else{const c=r.errorRetry,d=c?c.maxNumRetry:0;if(this._requestLicenseFailureCount++,this._requestLicenseFailureCount>d||o.status>=400&&o.status<500)i(new L0({type:ui.KEY_SYSTEM_ERROR,details:Mn.KEY_SYSTEM_LICENSE_REQUEST_FAILED,decryptdata:t.decryptdata,fatal:!0,networkDetails:o,response:{url:l,data:void 0,code:o.status,text:o.statusText}},`License Request XHR failed (${l}). Status: ${o.status} (${o.statusText})`));else{const u=d-this._requestLicenseFailureCount+1;this.warn(`Retrying license request, ${u} attempts left`),this.requestLicense(t,n).then(a,i)}}},t.licenseXhr&&t.licenseXhr.readyState!==XMLHttpRequest.DONE&&t.licenseXhr.abort(),t.licenseXhr=o,this.setupLicenseXHR(o,l,t,n).then(({xhr:c,licenseChallenge:d})=>{t.keySystem==Cu.PLAYREADY&&(d=this.unpackPlayReadyKeyMessage(c,d)),c.send(d)}).catch(i)})}onDestroying(){this.unregisterListeners(),this._clear()}onMediaAttached(t,n){if(!this.config.emeEnabled)return;const r=n.media;this.media=r,Xx(r,"encrypted",this.onMediaEncrypted),Xx(r,"waitingforkey",this.onWaitingForKey);const a=this.mediaResolved;a?a():this.mediaKeys=r.mediaKeys}onMediaDetached(){const t=this.media;t&&(Og(t,"encrypted",this.onMediaEncrypted),Og(t,"waitingforkey",this.onWaitingForKey),this.media=null,this.mediaKeys=null)}_clear(){var t;this._requestLicenseFailureCount=0,this.keyIdToKeySessionPromise={},this.bannedKeyIds={};const n=this.mediaResolved;if(n&&n(),!this.mediaKeys&&!this.mediaKeySessions.length)return;const r=this.media,a=this.mediaKeySessions.slice();this.mediaKeySessions=[],this.mediaKeys=null,x4.clearKeyUriToKeyIdMap();const i=a.length;UL.CDMCleanupPromise=Promise.all(a.map(l=>this.removeSession(l)).concat((r==null||(t=r.setMediaKeys(null))==null?void 0:t.catch(l=>{this.log(`Could not clear media keys: ${l}`),this.hls&&this.hls.trigger(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.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(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close sessions and clear media keys: ${l}`)})}).then(()=>{i&&this.log("finished closing key sessions and clearing media keys")})}onManifestLoading(){this._clear()}onManifestLoaded(t,{sessionKeys:n}){if(!(!n||!this.config.emeEnabled)&&!this.keyFormatPromise){const r=n.reduce((a,i)=>(a.indexOf(i.keyFormat)===-1&&a.push(i.keyFormat),a),[]);this.log(`Selecting key-system from session-keys ${r.join(", ")}`),this.keyFormatPromise=this.getKeyFormatPromise(r)}}removeSession(t){const{mediaKeysSession:n,licenseXhr:r,decryptdata:a}=t;if(n){this.log(`Remove licenses and keys and close session "${n.sessionId}" keyId: ${tf((a==null?void 0:a.keyId)||[])}`),t._onmessage&&(n.removeEventListener("message",t._onmessage),t._onmessage=void 0),t._onkeystatuseschange&&(n.removeEventListener("keystatuseschange",t._onkeystatuseschange),t._onkeystatuseschange=void 0),r&&r.readyState!==XMLHttpRequest.DONE&&r.abort(),t.mediaKeysSession=t.decryptdata=t.licenseXhr=void 0;const i=this.mediaKeySessions.indexOf(t);i>-1&&this.mediaKeySessions.splice(i,1);const{keyStatusTimeouts:l}=t;l&&Object.keys(l).forEach(d=>self.clearTimeout(l[d]));const{drmSystemOptions:o}=this.config;return(Frn(o)?new Promise((d,u)=>{self.setTimeout(()=>u(new Error("MediaKeySession.remove() timeout")),8e3),n.remove().then(d).catch(u)}):Promise.resolve()).catch(d=>{this.log(`Could not remove session: ${d}`),this.hls&&this.hls.trigger(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.KEY_SYSTEM_DESTROY_REMOVE_SESSION_ERROR,fatal:!1,error:new Error(`Could not remove session: ${d}`)})}).then(()=>n.close()).catch(d=>{this.log(`Could not close session: ${d}`),this.hls&&this.hls.trigger(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.KEY_SYSTEM_DESTROY_CLOSE_SESSION_ERROR,fatal:!1,error:new Error(`Could not close session: ${d}`)})})}return Promise.resolve()}}UL.CDMCleanupPromise=void 0;function IG(s){if(!s)throw new Error("Could not read keyId of undefined decryptdata");if(s.keyId===null)throw new Error("keyId is null");return tf(s.keyId)}function non(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 L0 extends Error{constructor(t,n){super(n),this.data=void 0,t.error||(t.error=new Error(n)),this.data=t,t.err=t.error}}function EJe(s,t){const n=s==="output-restricted",r=n?Mn.KEY_SYSTEM_STATUS_OUTPUT_RESTRICTED:Mn.KEY_SYSTEM_STATUS_INTERNAL_ERROR;return new L0({type:ui.KEY_SYSTEM_ERROR,details:r,fatal:!1,decryptdata:t},n?"HDCP level output restricted":`key status changed to "${s}"`)}class ron{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(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this)}unregisterListeners(){this.hls.off(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),this.hls.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this)}destroy(){this.timer&&clearInterval(this.timer),this.unregisterListeners(),this.isVideoPlaybackQualityAvailable=!1,this.media=null}onMediaAttaching(t,n){const r=this.hls.config;if(r.capLevelOnFPSDrop){const a=n.media instanceof self.HTMLVideoElement?n.media:null;this.media=a,a&&typeof a.getVideoPlaybackQuality=="function"&&(this.isVideoPlaybackQualityAvailable=!0),self.clearInterval(this.timer),this.timer=self.setInterval(this.checkFPSInterval.bind(this),r.fpsDroppedMonitoringPeriod)}}onMediaDetaching(){this.media=null}checkFPS(t,n,r){const a=performance.now();if(n){if(this.lastTime){const i=a-this.lastTime,l=r-this.lastDroppedFrames,o=n-this.lastDecodedFrames,c=1e3*l/i,d=this.hls;if(d.trigger(jt.FPS_DROP,{currentDropped:l,currentDecoded:o,totalDroppedFrames:r}),c>0&&l>d.config.fpsDroppedMonitoringThreshold*o){let u=d.currentLevel;d.logger.warn("drop FPS ratio greater than max allowed value for currentLevel: "+u),u>0&&(d.autoLevelCapping===-1||d.autoLevelCapping>=u)&&(u=u-1,d.trigger(jt.FPS_DROP_LEVEL_CAPPING,{level:u,droppedLevel:d.currentLevel}),d.autoLevelCapping=u,this.streamController.nextLevelSwitch())}}this.lastTime=a,this.lastDroppedFrames=r,this.lastDecodedFrames=n}}checkFPSInterval(){const t=this.media;if(t)if(this.isVideoPlaybackQualityAvailable){const n=t.getVideoPlaybackQuality();this.checkFPS(t,n.totalVideoFrames,n.droppedVideoFrames)}else this.checkFPS(t,t.webkitDecodedFrameCount,t.webkitDroppedFrameCount)}}function Nkt(s,t){let n;try{n=new Event("addtrack")}catch{n=document.createEvent("Event"),n.initEvent("addtrack",!1,!1)}n.track=s,t.dispatchEvent(n)}function kkt(s,t){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues&&!s.cues.getCueById(t.id))try{if(s.addCue(t),!s.cues.getCueById(t.id))throw new Error(`addCue is failed for: ${t}`)}catch(r){Cc.debug(`[texttrack-utils]: ${r}`);try{const a=new self.TextTrackCue(t.startTime,t.endTime,t.text);a.id=t.id,s.addCue(a)}catch(a){Cc.debug(`[texttrack-utils]: Legacy TextTrackCue fallback failed: ${a}`)}}n==="disabled"&&(s.mode=n)}function RP(s,t){const n=s.mode;if(n==="disabled"&&(s.mode="hidden"),s.cues)for(let r=s.cues.length;r--;)t&&s.cues[r].removeEventListener("enter",t),s.removeCue(s.cues[r]);n==="disabled"&&(s.mode=n)}function STe(s,t,n,r){const a=s.mode;if(a==="disabled"&&(s.mode="hidden"),s.cues&&s.cues.length>0){const i=ion(s.cues,t,n);for(let l=0;ls[n].endTime)return-1;let r=0,a=n,i;for(;r<=a;)if(i=Math.floor((a+r)/2),ts[i].startTime&&r-1)for(let i=a,l=s.length;i=t&&o.endTime<=n)r.push(o);else if(o.startTime>n)return r}return r}function tpe(s){const t=[];for(let n=0;nthis.pollTrackChange(0),this.onTextTracksChanged=()=>{if(this.useTextTrackPolling||self.clearInterval(this.subtitlePollingInterval),!this.media||!this.hls.config.renderTextTracksNatively)return;let n=null;const r=tpe(this.media.textTracks);for(let i=0;i-1&&this.toggleTrackModes()}registerListeners(){const{hls:t}=this;t.on(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(jt.LEVEL_LOADING,this.onLevelLoading,this),t.on(jt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.on(jt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(jt.ERROR,this.onError,this)}unregisterListeners(){const{hls:t}=this;t.off(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(jt.LEVEL_LOADING,this.onLevelLoading,this),t.off(jt.LEVEL_SWITCHING,this.onLevelSwitching,this),t.off(jt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(jt.ERROR,this.onError,this)}onMediaAttached(t,n){this.media=n.media,this.media&&(this.queuedDefaultTrack>-1&&(this.subtitleTrack=this.queuedDefaultTrack,this.queuedDefaultTrack=-1),this.useTextTrackPolling=!(this.media.textTracks&&"onchange"in this.media.textTracks),this.useTextTrackPolling?this.pollTrackChange(500):this.media.textTracks.addEventListener("change",this.asyncPollTrackChange))}pollTrackChange(t){self.clearInterval(this.subtitlePollingInterval),this.subtitlePollingInterval=self.setInterval(this.onTextTracksChanged,t)}onMediaDetaching(t,n){const r=this.media;if(!r)return;const a=!!n.transferMedia;if(self.clearInterval(this.subtitlePollingInterval),this.useTextTrackPolling||r.textTracks.removeEventListener("change",this.asyncPollTrackChange),this.trackId>-1&&(this.queuedDefaultTrack=this.trackId),this.subtitleTrack=-1,this.media=null,a)return;tpe(r.textTracks).forEach(l=>{RP(l)})}onManifestLoading(){this.tracks=[],this.groupIds=null,this.tracksInGroup=[],this.trackId=-1,this.currentTrack=null,this.selectDefaultTrack=!0}onManifestParsed(t,n){this.tracks=n.subtitleTracks}onSubtitleTrackLoaded(t,n){const{id:r,groupId:a,details:i}=n,l=this.tracksInGroup[r];if(!l||l.groupId!==a){this.warn(`Subtitle track with id:${r} and group:${a} not found in active group ${l==null?void 0:l.groupId}`);return}const o=l.details;l.details=n.details,this.log(`Subtitle track ${r} "${l.name}" lang:${l.lang} group:${a} loaded [${i.startSN}-${i.endSN}]`),r===this.trackId&&this.playlistLoaded(r,n,o)}onLevelLoading(t,n){this.switchLevel(n.level)}onLevelSwitching(t,n){this.switchLevel(n.level)}switchLevel(t){const n=this.hls.levels[t];if(!n)return;const r=n.subtitleGroups||null,a=this.groupIds;let i=this.currentTrack;if(!r||(a==null?void 0:a.length)!==(r==null?void 0:r.length)||r!=null&&r.some(l=>(a==null?void 0:a.indexOf(l))===-1)){this.groupIds=r,this.trackId=-1,this.currentTrack=null;const l=this.tracks.filter(u=>!r||r.indexOf(u.groupId)!==-1);if(l.length)this.selectDefaultTrack&&!l.some(u=>u.default)&&(this.selectDefaultTrack=!1),l.forEach((u,h)=>{u.id=h});else if(!i&&!this.tracksInGroup.length)return;this.tracksInGroup=l;const o=this.hls.config.subtitlePreference;if(!i&&o){this.selectDefaultTrack=!1;const u=rw(o,l);if(u>-1)i=l[u];else{const h=rw(o,this.tracks);i=this.tracks[h]}}let c=this.findTrackId(i);c===-1&&i&&(c=this.findTrackId(null));const d={subtitleTracks:l};this.log(`Updating subtitle tracks, ${l.length} track(s) found in "${r==null?void 0:r.join(",")}" group-id`),this.hls.trigger(jt.SUBTITLE_TRACKS_UPDATED,d),c!==-1&&this.trackId===-1&&this.setSubtitleTrack(c)}}findTrackId(t){const n=this.tracksInGroup,r=this.selectDefaultTrack;for(let a=0;a-1){const i=this.tracksInGroup[a];return this.setSubtitleTrack(a),i}else{if(r)return null;{const i=rw(t,n);if(i>-1)return n[i]}}}}return null}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentTrack)&&this.scheduleLoading(this.currentTrack,t)}loadingPlaylist(t,n){super.loadingPlaylist(t,n);const r=t.id,a=t.groupId,i=this.getUrlWithDirectives(t.url,n),l=t.details,o=l==null?void 0:l.age;this.log(`Loading subtitle ${r} "${t.name}" lang:${t.lang} group:${a}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${i}`),this.hls.trigger(jt.SUBTITLE_TRACK_LOADING,{url:i,id:r,groupId:a,deliveryDirectives:n||null,track:t})}toggleTrackModes(){const{media:t}=this;if(!t)return;const n=tpe(t.textTracks),r=this.currentTrack;let a;if(r&&(a=n.filter(i=>wTe(r,i))[0],a||this.warn(`Unable to find subtitle TextTrack with name "${r.name}" and language "${r.lang}"`)),[].slice.call(n).forEach(i=>{i.mode!=="disabled"&&i!==a&&(i.mode="disabled")}),a){const i=this.subtitleDisplay?"showing":"hidden";a.mode!==i&&(a.mode=i)}}setSubtitleTrack(t){const n=this.tracksInGroup;if(!this.media){this.queuedDefaultTrack=t;return}if(t<-1||t>=n.length||!Pa(t)){this.warn(`Invalid subtitle track id: ${t}`);return}this.selectDefaultTrack=!1;const r=this.currentTrack,a=n[t]||null;if(this.trackId=t,this.currentTrack=a,this.toggleTrackModes(),!a){this.hls.trigger(jt.SUBTITLE_TRACK_SWITCH,{id:t});return}const i=!!a.details&&!a.details.live;if(t===this.trackId&&a===r&&i)return;this.log(`Switching to subtitle-track ${t}`+(a?` "${a.name}" lang:${a.lang} group:${a.groupId}`:""));const{id:l,groupId:o="",name:c,type:d,url:u}=a;this.hls.trigger(jt.SUBTITLE_TRACK_SWITCH,{id:l,groupId:o,name:c,type:d,url:u});const h=this.switchParams(a.url,r==null?void 0:r.details,a.details);this.loadPlaylist(h)}}function lon(){try{return crypto.randomUUID()}catch{try{const t=URL.createObjectURL(new Blob),n=t.toString();return URL.revokeObjectURL(t),n.slice(n.lastIndexOf("/")+1)}catch{let n=new Date().getTime();return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,a=>{const i=(n+Math.random()*16)%16|0;return n=Math.floor(n/16),(a=="x"?i:i&3|8).toString(16)})}}}function Nz(s){let t=5381,n=s.length;for(;n;)t=t*33^s.charCodeAt(--n);return(t>>>0).toString()}const qL=.025;let Hge=function(s){return s[s.Point=0]="Point",s[s.Range=1]="Range",s}({});function con(s,t,n){return`${s.identifier}-${n+1}-${Nz(t)}`}class don{constructor(t,n){this.base=void 0,this._duration=null,this._timelineStart=null,this.appendInPlaceDisabled=void 0,this.appendInPlaceStarted=void 0,this.dateRange=void 0,this.hasPlayed=!1,this.cumulativeDuration=0,this.resumeOffset=NaN,this.playoutLimit=NaN,this.restrictions={skip:!1,jump:!1},this.snapOptions={out:!1,in:!1},this.assetList=[],this.assetListLoader=void 0,this.assetListResponse=null,this.resumeAnchor=void 0,this.error=void 0,this.resetOnResume=void 0,this.base=n,this.dateRange=t,this.setDateRange(t)}setDateRange(t){this.dateRange=t,this.resumeOffset=t.attr.optionalFloat("X-RESUME-OFFSET",this.resumeOffset),this.playoutLimit=t.attr.optionalFloat("X-PLAYOUT-LIMIT",this.playoutLimit),this.restrictions=t.attr.enumeratedStringList("X-RESTRICT",this.restrictions),this.snapOptions=t.attr.enumeratedStringList("X-SNAP",this.snapOptions)}reset(){var t;this.appendInPlaceStarted=!1,(t=this.assetListLoader)==null||t.destroy(),this.assetListLoader=void 0,this.supplementsPrimary||(this.assetListResponse=null,this.assetList=[],this._duration=null)}isAssetPastPlayoutLimit(t){var n;if(t>0&&t>=this.assetList.length)return!0;const r=this.playoutLimit;return t<=0||isNaN(r)?!1:r===0?!0:(((n=this.assetList[t])==null?void 0:n.startOffset)||0)>r}findAssetIndex(t){return this.assetList.indexOf(t)}get identifier(){return this.dateRange.id}get startDate(){return this.dateRange.startDate}get startTime(){const t=this.dateRange.startTime;if(this.snapOptions.out){const n=this.dateRange.tagAnchor;if(n)return GNe(t,n)}return t}get startOffset(){return this.cue.pre?0:this.startTime}get startIsAligned(){if(this.startTime===0||this.snapOptions.out)return!0;const t=this.dateRange.tagAnchor;if(t){const n=this.dateRange.startTime,r=GNe(n,t);return n-r<.1}return!1}get resumptionOffset(){const t=this.resumeOffset,n=Pa(t)?t:this.duration;return this.cumulativeDuration+n}get resumeTime(){const t=this.startOffset+this.resumptionOffset;if(this.snapOptions.in){const n=this.resumeAnchor;if(n)return GNe(t,n)}return t}get appendInPlace(){return this.appendInPlaceStarted?!0:this.appendInPlaceDisabled?!1:!!(!this.cue.once&&!this.cue.pre&&this.startIsAligned&&(isNaN(this.playoutLimit)&&isNaN(this.resumeOffset)||this.resumeOffset&&this.duration&&Math.abs(this.resumeOffset-this.duration)0||this.assetListResponse!==null}toString(){return uon(this)}}function GNe(s,t){return s-t.start":s.cue.post?"":""}${s.timelineStart.toFixed(2)}-${s.resumeTime.toFixed(2)}]`}function iP(s){const t=s.timelineStart,n=s.duration||0;return`["${s.identifier}" ${t.toFixed(2)}-${(t+n).toFixed(2)}]`}class hon{constructor(t,n,r,a){this.hls=void 0,this.interstitial=void 0,this.assetItem=void 0,this.tracks=null,this.hasDetails=!1,this.mediaAttached=null,this._currentTime=void 0,this._bufferedEosTime=void 0,this.checkPlayout=()=>{this.reachedPlayout(this.currentTime)&&this.hls&&this.hls.trigger(jt.PLAYOUT_LIMIT_REACHED,{})};const i=this.hls=new t(n);this.interstitial=r,this.assetItem=a;const l=()=>{this.hasDetails=!0};i.once(jt.LEVEL_LOADED,l),i.once(jt.AUDIO_TRACK_LOADED,l),i.once(jt.SUBTITLE_TRACK_LOADED,l),i.on(jt.MEDIA_ATTACHING,(o,{media:c})=>{this.removeMediaListeners(),this.mediaAttached=c,this.interstitial.playoutLimit&&(c.addEventListener("timeupdate",this.checkPlayout),this.appendInPlace&&i.on(jt.BUFFER_APPENDED,()=>{const u=this.bufferedEnd;this.reachedPlayout(u)&&(this._bufferedEosTime=u,i.trigger(jt.BUFFERED_TO_END,void 0))}))})}get appendInPlace(){return this.interstitial.appendInPlace}loadSource(){const t=this.hls;if(t)if(t.url)t.levels.length&&!t.started&&t.startLoad(-1,!0);else{let n=this.assetItem.uri;try{n=Skt(n,t.config.primarySessionId||"").href}catch{}t.loadSource(n)}}bufferedInPlaceToEnd(t){var n;if(!this.appendInPlace)return!1;if((n=this.hls)!=null&&n.bufferedToEnd)return!0;if(!t)return!1;const r=Math.min(this._bufferedEosTime||1/0,this.duration),a=this.timelineOffset,i=bo.bufferInfo(t,a,0);return this.getAssetTime(i.end)>=r-.02}reachedPlayout(t){const r=this.interstitial.playoutLimit;return this.startOffset+t>=r}get destroyed(){var t;return!((t=this.hls)!=null&&t.userConfig)}get assetId(){return this.assetItem.identifier}get interstitialId(){return this.assetItem.parentIdentifier}get media(){var t;return((t=this.hls)==null?void 0:t.media)||null}get bufferedEnd(){const t=this.media||this.mediaAttached;if(!t)return this._bufferedEosTime?this._bufferedEosTime:this.currentTime;const n=bo.bufferInfo(t,t.currentTime,.001);return this.getAssetTime(n.end)}get currentTime(){const t=this.media||this.mediaAttached;return t?this.getAssetTime(t.currentTime):this._currentTime||0}get duration(){const t=this.assetItem.duration;if(!t)return 0;const n=this.interstitial.playoutLimit;if(n){const r=n-this.startOffset;if(r>0&&r1/9e4&&this.hls){if(this.hasDetails)throw new Error("Cannot set timelineOffset after playlists are loaded");this.hls.config.timelineOffset=t}}}getAssetTime(t){const n=this.timelineOffset,r=this.duration;return Math.min(Math.max(0,t-n),r)}removeMediaListeners(){const t=this.mediaAttached;t&&(this._currentTime=t.currentTime,this.bufferSnapShot(),t.removeEventListener("timeupdate",this.checkPlayout))}bufferSnapShot(){if(this.mediaAttached){var t;(t=this.hls)!=null&&t.bufferedToEnd&&(this._bufferedEosTime=this.bufferedEnd)}}destroy(){this.removeMediaListeners(),this.hls&&this.hls.destroy(),this.hls=null,this.tracks=this.mediaAttached=this.checkPlayout=null}attachMedia(t){var n;this.loadSource(),(n=this.hls)==null||n.attachMedia(t)}detachMedia(){var t;this.removeMediaListeners(),this.mediaAttached=null,(t=this.hls)==null||t.detachMedia()}resumeBuffering(){var t;(t=this.hls)==null||t.resumeBuffering()}pauseBuffering(){var t;(t=this.hls)==null||t.pauseBuffering()}transferMedia(){var t;return this.bufferSnapShot(),((t=this.hls)==null?void 0:t.transferMedia())||null}resetDetails(){const t=this.hls;if(t&&this.hasDetails){t.stopLoad();const n=r=>delete r.details;t.levels.forEach(n),t.allAudioTracks.forEach(n),t.allSubtitleTracks.forEach(n),this.hasDetails=!1}}on(t,n,r){var a;(a=this.hls)==null||a.on(t,n)}once(t,n,r){var a;(a=this.hls)==null||a.once(t,n)}off(t,n,r){var a;(a=this.hls)==null||a.off(t,n)}toString(){var t;return`HlsAssetPlayer: ${iP(this.assetItem)} ${(t=this.hls)==null?void 0:t.sessionId} ${this.appendInPlace?"append-in-place":""}`}}const AJe=.033;class mon extends t1{constructor(t,n){super("interstitials-sched",n),this.onScheduleUpdate=void 0,this.eventMap={},this.events=null,this.items=null,this.durations={primary:0,playout:0,integrated:0},this.onScheduleUpdate=t}destroy(){this.reset(),this.onScheduleUpdate=null}reset(){this.eventMap={},this.setDurations(0,0,0),this.events&&this.events.forEach(t=>t.reset()),this.events=this.items=null}resetErrorsInRange(t,n){return this.events?this.events.reduce((r,a)=>t<=a.startOffset&&n>a.startOffset?(delete a.error,r+1):r,0):0}get duration(){const t=this.items;return t?t[t.length-1].end:0}get length(){return this.items?this.items.length:0}getEvent(t){return t&&this.eventMap[t]||null}hasEvent(t){return t in this.eventMap}findItemIndex(t,n){if(t.event)return this.findEventIndex(t.event.identifier);let r=-1;t.nextEvent?r=this.findEventIndex(t.nextEvent.identifier)-1:t.previousEvent&&(r=this.findEventIndex(t.previousEvent.identifier)+1);const a=this.items;if(a)for(a[r]||(n===void 0&&(n=t.start),r=this.findItemIndexAtTime(n));r>=0&&(i=a[r])!=null&&i.event;){var i;r--}return r}findItemIndexAtTime(t,n){const r=this.items;if(r)for(let a=0;ai.start&&t1)for(let i=0;io&&(n!o.includes(d.identifier)):[];l.length&&l.sort((d,u)=>{const h=d.cue.pre,p=d.cue.post,f=u.cue.pre,y=u.cue.post;if(h&&!f)return-1;if(f&&!h||p&&!y)return 1;if(y&&!p)return-1;if(!h&&!f&&!p&&!y){const _=d.startTime,v=u.startTime;if(_!==v)return _-v}return d.dateRange.tagOrder-u.dateRange.tagOrder}),this.events=l,c.forEach(d=>{this.removeEvent(d)}),this.updateSchedule(t,c)}updateSchedule(t,n=[],r=!1){const a=this.events||[];if(a.length||n.length||this.length<2){const i=this.items,l=this.parseSchedule(a,t);(r||n.length||(i==null?void 0:i.length)!==l.length||l.some((c,d)=>Math.abs(c.playout.start-i[d].playout.start)>.005||Math.abs(c.playout.end-i[d].playout.end)>.005))&&(this.items=l,this.onScheduleUpdate(n,i))}}parseDateRanges(t,n,r){const a=[],i=Object.keys(t);for(let l=0;l!c.error&&!(c.cue.once&&c.hasPlayed)),t.length){this.resolveOffsets(t,n);let c=0,d=0;if(t.forEach((u,h)=>{const p=u.cue.pre,f=u.cue.post,y=t[h-1]||null,_=u.appendInPlace,v=f?i:u.startOffset,j=u.duration,w=u.timelineOccupancy===Hge.Range?j:0,S=u.resumptionOffset,A=(y==null?void 0:y.startTime)===v,E=v+u.cumulativeDuration;let O=_?E+j:v+S;if(p||!f&&v<=0){const I=d;d+=w,u.timelineStart=E;const F=l;l+=j,r.push({event:u,start:E,end:O,playout:{start:F,end:l},integrated:{start:I,end:d}})}else if(v<=i){if(!A){const z=v-c;if(z>AJe){const H=c,Z=d;d+=z;const Y=l;l+=z;const W={previousEvent:t[h-1]||null,nextEvent:u,start:H,end:H+z,playout:{start:Y,end:l},integrated:{start:Z,end:d}};r.push(W)}else z>0&&y&&(y.cumulativeDuration+=z,r[r.length-1].end=v)}f&&(O=E),u.timelineStart=E;const I=d;d+=w;const F=l;l+=j,r.push({event:u,start:E,end:O,playout:{start:F,end:l},integrated:{start:I,end:d}})}else return;const D=u.resumeTime;f||D>i?c=i:c=D}),c{const d=o.cue.pre,u=o.cue.post,h=d?0:u?a:o.startTime;this.updateAssetDurations(o),l===h?o.cumulativeDuration=i:(i=0,l=h),!u&&o.snapOptions.in&&(o.resumeAnchor=LM(null,r.fragments,o.startOffset+o.resumptionOffset,0,0)||void 0),o.appendInPlace&&!o.appendInPlaceStarted&&(this.primaryCanResumeInPlaceAt(o,n)||(o.appendInPlace=!1)),!o.appendInPlace&&c+1qL?(this.log(`"${t.identifier}" resumption ${r} not aligned with estimated timeline end ${a}`),!1):!Object.keys(n).some(l=>{const o=n[l].details,c=o.edge;if(r>=c)return this.log(`"${t.identifier}" resumption ${r} past ${l} playlist end ${c}`),!1;const d=LM(null,o.fragments,r);if(!d)return this.log(`"${t.identifier}" resumption ${r} does not align with any fragments in ${l} playlist (${o.fragStart}-${o.fragmentEnd})`),!0;const u=l==="audio"?.175:0;return Math.abs(d.start-r){const v=p.data,j=v==null?void 0:v.ASSETS;if(!Array.isArray(j)){const w=this.assignAssetListError(t,Mn.ASSET_LIST_PARSING_ERROR,new Error("Invalid interstitial asset list"),y.url,f,_);this.hls.trigger(jt.ERROR,w);return}t.assetListResponse=v,this.hls.trigger(jt.ASSET_LIST_LOADED,{event:t,assetListResponse:v,networkDetails:_})},onError:(p,f,y,_)=>{const v=this.assignAssetListError(t,Mn.ASSET_LIST_LOAD_ERROR,new Error(`Error loading X-ASSET-LIST: HTTP status ${p.code} ${p.text} (${f.url})`),f.url,_,y);this.hls.trigger(jt.ERROR,v)},onTimeout:(p,f,y)=>{const _=this.assignAssetListError(t,Mn.ASSET_LIST_LOAD_TIMEOUT,new Error(`Timeout loading X-ASSET-LIST (${f.url})`),f.url,p,y);this.hls.trigger(jt.ERROR,_)}};return o.load(c,u,h),this.hls.trigger(jt.ASSET_LIST_LOADING,{event:t}),o}assignAssetListError(t,n,r,a,i,l){return t.error=r,{type:ui.NETWORK_ERROR,details:n,fatal:!1,interstitial:t,url:a,error:r,networkDetails:l,stats:i}}}function MJe(s){var t;s==null||(t=s.play())==null||t.catch(()=>{})}function qI(s,t){return`[${s}] Advancing timeline position to ${t}`}class fon extends t1{constructor(t,n){super("interstitials",t.logger),this.HlsPlayerClass=void 0,this.hls=void 0,this.assetListLoader=void 0,this.mediaSelection=null,this.altSelection=null,this.media=null,this.detachedData=null,this.requiredTracks=null,this.manager=null,this.playerQueue=[],this.bufferedPos=-1,this.timelinePos=-1,this.schedule=void 0,this.playingItem=null,this.bufferingItem=null,this.waitingItem=null,this.endedItem=null,this.playingAsset=null,this.endedAsset=null,this.bufferingAsset=null,this.shouldPlay=!1,this.onPlay=()=>{this.shouldPlay=!0},this.onPause=()=>{this.shouldPlay=!1},this.onSeeking=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled||!this.schedule)return;const a=r-this.timelinePos;if(Math.abs(a)<1/7056e5)return;const l=a<=-.01;this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),this.timelinePos=r,this.bufferedPos=r;const o=this.playingItem;if(!o){this.checkBuffer();return}if(l&&this.schedule.resetErrorsInRange(r,r-a)&&this.updateSchedule(!0),this.checkBuffer(),l&&r=o.end){var c;const f=this.findItemIndex(o);let y=this.schedule.findItemIndexAtTime(r);if(y===-1&&(y=f+(l?-1:1),this.log(`seeked ${l?"back ":""}to position not covered by schedule ${r} (resolving from ${f} to ${y})`)),!this.isInterstitial(o)&&(c=this.media)!=null&&c.paused&&(this.shouldPlay=!1),!l&&y>f){const _=this.schedule.findJumpRestrictedIndex(f+1,y);if(_>f){this.setSchedulePosition(_);return}}this.setSchedulePosition(y);return}const d=this.playingAsset;if(!d){if(this.playingLastItem&&this.isInterstitial(o)){const f=o.event.assetList[0];f&&(this.endedItem=this.playingItem,this.playingItem=null,this.setScheduleToAssetAtTime(r,f))}return}const u=d.timelineStart,h=d.duration||0;if(l&&r=u+h){var p;(p=o.event)!=null&&p.appendInPlace&&(this.clearAssetPlayers(o.event,o),this.flushFrontBuffer(r)),this.setScheduleToAssetAtTime(r,d)}},this.onTimeupdate=()=>{const r=this.currentTime;if(r===void 0||this.playbackDisabled)return;if(this.timelinePos===-1&&!this.effectivePlayingItem&&this.checkStart(),r>this.timelinePos)this.timelinePos=r,r>this.bufferedPos&&this.checkBuffer();else return;const a=this.playingItem;if(!a||this.playingLastItem)return;if(r>=a.end){this.timelinePos=a.end;const o=this.findItemIndex(a);this.setSchedulePosition(o+1)}const i=this.playingAsset;if(!i)return;const l=i.timelineStart+(i.duration||0);r>=l&&this.setScheduleToAssetAtTime(r,i)},this.onScheduleUpdate=(r,a)=>{const i=this.schedule;if(!i)return;const l=this.playingItem,o=i.events||[],c=i.items||[],d=i.durations,u=r.map(_=>_.identifier),h=!!(o.length||u.length);(h||a)&&this.log(`INTERSTITIALS_UPDATED (${o.length}): ${o} Schedule: ${c.map(_=>O1(_))} pos: ${this.timelinePos}`),u.length&&this.log(`Removed events ${u}`);let p=null,f=null;l&&(p=this.updateItem(l,this.timelinePos),this.itemsMatch(l,p)?this.playingItem=p:this.waitingItem=this.endedItem=null),this.waitingItem=this.updateItem(this.waitingItem),this.endedItem=this.updateItem(this.endedItem);const y=this.bufferingItem;if(y&&(f=this.updateItem(y,this.bufferedPos),this.itemsMatch(y,f)?this.bufferingItem=f:y.event&&(this.bufferingItem=this.playingItem,this.clearInterstitial(y.event,null))),r.forEach(_=>{_.assetList.forEach(v=>{this.clearAssetPlayer(v.identifier,null)})}),this.playerQueue.forEach(_=>{if(_.interstitial.appendInPlace){const v=_.assetItem.timelineStart,j=_.timelineOffset-v;if(j)try{_.timelineOffset=v}catch(w){Math.abs(j)>qL&&this.warn(`${w} ("${_.assetId}" ${_.timelineOffset}->${v})`)}}}),h||a){if(this.hls.trigger(jt.INTERSTITIALS_UPDATED,{events:o.slice(0),schedule:c.slice(0),durations:d,removedIds:u}),this.isInterstitial(l)&&u.includes(l.event.identifier)){this.warn(`Interstitial "${l.event.identifier}" removed while playing`),this.primaryFallback(l.event);return}l&&this.trimInPlace(p,l),y&&f!==p&&this.trimInPlace(f,y),this.checkBuffer()}},this.hls=t,this.HlsPlayerClass=n,this.assetListLoader=new pon(t),this.schedule=new mon(this.onScheduleUpdate,t.logger),this.registerListeners()}registerListeners(){const t=this.hls;t&&(t.on(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(jt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(jt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.on(jt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(jt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.on(jt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.on(jt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.on(jt.BUFFER_APPENDED,this.onBufferAppended,this),t.on(jt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(jt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.on(jt.MEDIA_ENDED,this.onMediaEnded,this),t.on(jt.ERROR,this.onError,this),t.on(jt.DESTROYING,this.onDestroying,this))}unregisterListeners(){const t=this.hls;t&&(t.off(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(jt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(jt.AUDIO_TRACK_UPDATED,this.onAudioTrackUpdated,this),t.off(jt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(jt.SUBTITLE_TRACK_UPDATED,this.onSubtitleTrackUpdated,this),t.off(jt.EVENT_CUE_ENTER,this.onInterstitialCueEnter,this),t.off(jt.ASSET_LIST_LOADED,this.onAssetListLoaded,this),t.off(jt.BUFFER_CODECS,this.onBufferCodecs,this),t.off(jt.BUFFER_APPENDED,this.onBufferAppended,this),t.off(jt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(jt.BUFFERED_TO_END,this.onBufferedToEnd,this),t.off(jt.MEDIA_ENDED,this.onMediaEnded,this),t.off(jt.ERROR,this.onError,this),t.off(jt.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){Og(t,"play",this.onPlay),Og(t,"pause",this.onPause),Og(t,"seeking",this.onSeeking),Og(t,"timeupdate",this.onTimeupdate)}onMediaAttaching(t,n){const r=this.media=n.media;Xx(r,"seeking",this.onSeeking),Xx(r,"timeupdate",this.onTimeupdate),Xx(r,"play",this.onPlay),Xx(r,"pause",this.onPause)}onMediaAttached(t,n){const r=this.effectivePlayingItem,a=this.detachedData;if(this.detachedData=null,r===null)this.checkStart();else if(!a){this.clearScheduleState();const i=this.findItemIndex(r);this.setSchedulePosition(i)}}clearScheduleState(){this.log("clear schedule state"),this.playingItem=this.bufferingItem=this.waitingItem=this.endedItem=this.playingAsset=this.endedAsset=this.bufferingAsset=null}onMediaDetaching(t,n){const r=!!n.transferMedia,a=this.media;if(this.media=null,!r&&(a&&this.removeMediaListeners(a),this.detachedData)){const i=this.getBufferingPlayer();i&&(this.log(`Removing schedule state for detachedData and ${i}`),this.playingAsset=this.endedAsset=this.bufferingAsset=this.bufferingItem=this.waitingItem=this.detachedData=null,i.detachMedia()),this.shouldPlay=!1}}get interstitialsManager(){if(!this.hls)return null;if(this.manager)return this.manager;const t=this,n=()=>t.bufferingItem||t.waitingItem,r=h=>h&&t.getAssetPlayer(h.identifier),a=(h,p,f,y,_)=>{if(h){let v=h[p].start;const j=h.event;if(j){if(p==="playout"||j.timelineOccupancy!==Hge.Point){const w=r(f);(w==null?void 0:w.interstitial)===j&&(v+=w.assetItem.startOffset+w[_])}}else{const w=y==="bufferedPos"?l():t[y];v+=w-h.start}return v}return 0},i=(h,p)=>{var f;if(h!==0&&p!=="primary"&&(f=t.schedule)!=null&&f.length){var y;const _=t.schedule.findItemIndexAtTime(h),v=(y=t.schedule.items)==null?void 0:y[_];if(v){const j=v[p].start-v.start;return h+j}}return h},l=()=>{const h=t.bufferedPos;return h===Number.MAX_VALUE?o("primary"):Math.max(h,0)},o=h=>{var p,f;return(p=t.primaryDetails)!=null&&p.live?t.primaryDetails.edge:((f=t.schedule)==null?void 0:f.durations[h])||0},c=(h,p)=>{var f,y;const _=t.effectivePlayingItem;if(_!=null&&(f=_.event)!=null&&f.restrictions.skip||!t.schedule)return;t.log(`seek to ${h} "${p}"`);const v=t.effectivePlayingItem,j=t.schedule.findItemIndexAtTime(h,p),w=(y=t.schedule.items)==null?void 0:y[j],S=t.getBufferingPlayer(),A=S==null?void 0:S.interstitial,E=A==null?void 0:A.appendInPlace,O=v&&t.itemsMatch(v,w);if(v&&(E||O)){const D=r(t.playingAsset),I=(D==null?void 0:D.media)||t.primaryMedia;if(I){const F=p==="primary"?I.currentTime:a(v,p,t.playingAsset,"timelinePos","currentTime"),z=h-F,H=(E?F:I.currentTime)+z;if(H>=0&&(!D||E||H<=D.duration)){I.currentTime=H;return}}}if(w){let D=h;if(p!=="primary"){const F=w[p].start,z=h-F;D=w.start+z}const I=!t.isInterstitial(w);if((!t.isInterstitial(v)||v.event.appendInPlace)&&(I||w.event.appendInPlace)){const F=t.media||(E?S==null?void 0:S.media:null);F&&(F.currentTime=D)}else if(v){const F=t.findItemIndex(v);if(j>F){const H=t.schedule.findJumpRestrictedIndex(F+1,j);if(H>F){t.setSchedulePosition(H);return}}let z=0;if(I)t.timelinePos=D,t.checkBuffer();else{const H=w.event.assetList,Z=h-(w[p]||w).start;for(let Y=H.length;Y--;){const W=H[Y];if(W.duration&&Z>=W.startOffset&&Z{const h=t.effectivePlayingItem;if(t.isInterstitial(h))return h;const p=n();return t.isInterstitial(p)?p:null},u={get bufferedEnd(){const h=n(),p=t.bufferingItem;if(p&&p===h){var f;return a(p,"playout",t.bufferingAsset,"bufferedPos","bufferedEnd")-p.playout.start||((f=t.bufferingAsset)==null?void 0:f.startOffset)||0}return 0},get currentTime(){const h=d(),p=t.effectivePlayingItem;return p&&p===h?a(p,"playout",t.effectivePlayingAsset,"timelinePos","currentTime")-p.playout.start:0},set currentTime(h){const p=d(),f=t.effectivePlayingItem;f&&f===p&&c(h+f.playout.start,"playout")},get duration(){const h=d();return h?h.playout.end-h.playout.start:0},get assetPlayers(){var h;const p=(h=d())==null?void 0:h.event.assetList;return p?p.map(f=>t.getAssetPlayer(f.identifier)):[]},get playingIndex(){var h;const p=(h=d())==null?void 0:h.event;return p&&t.effectivePlayingAsset?p.findAssetIndex(t.effectivePlayingAsset):-1},get scheduleItem(){return d()}};return this.manager={get events(){var h;return((h=t.schedule)==null||(h=h.events)==null?void 0:h.slice(0))||[]},get schedule(){var h;return((h=t.schedule)==null||(h=h.items)==null?void 0:h.slice(0))||[]},get interstitialPlayer(){return d()?u:null},get playerQueue(){return t.playerQueue.slice(0)},get bufferingAsset(){return t.bufferingAsset},get bufferingItem(){return n()},get bufferingIndex(){const h=n();return t.findItemIndex(h)},get playingAsset(){return t.effectivePlayingAsset},get playingItem(){return t.effectivePlayingItem},get playingIndex(){const h=t.effectivePlayingItem;return t.findItemIndex(h)},primary:{get bufferedEnd(){return l()},get currentTime(){const h=t.timelinePos;return h>0?h:0},set currentTime(h){c(h,"primary")},get duration(){return o("primary")},get seekableStart(){var h;return((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0}},integrated:{get bufferedEnd(){return a(n(),"integrated",t.bufferingAsset,"bufferedPos","bufferedEnd")},get currentTime(){return a(t.effectivePlayingItem,"integrated",t.effectivePlayingAsset,"timelinePos","currentTime")},set currentTime(h){c(h,"integrated")},get duration(){return o("integrated")},get seekableStart(){var h;return i(((h=t.primaryDetails)==null?void 0:h.fragmentStart)||0,"integrated")}},skip:()=>{const h=t.effectivePlayingItem,p=h==null?void 0:h.event;if(p&&!p.restrictions.skip){const f=t.findItemIndex(h);if(p.appendInPlace){const y=h.playout.start+h.event.duration;c(y+.001,"playout")}else t.advanceAfterAssetEnded(p,f,1/0)}}}}get effectivePlayingItem(){return this.waitingItem||this.playingItem||this.endedItem}get effectivePlayingAsset(){return this.playingAsset||this.endedAsset}get playingLastItem(){var t;const n=this.playingItem,r=(t=this.schedule)==null?void 0:t.items;return!this.playbackStarted||!n||!r?!1:this.findItemIndex(n)===r.length-1}get playbackStarted(){return this.effectivePlayingItem!==null}get currentTime(){var t,n;if(this.mediaSelection===null)return;const r=this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&!r.event.appendInPlace)return;let a=this.media;!a&&(t=this.bufferingItem)!=null&&(t=t.event)!=null&&t.appendInPlace&&(a=this.primaryMedia);const i=(n=a)==null?void 0:n.currentTime;if(!(i===void 0||!Pa(i)))return i}get primaryMedia(){var t;return this.media||((t=this.detachedData)==null?void 0:t.media)||null}isInterstitial(t){return!!(t!=null&&t.event)}retreiveMediaSource(t,n){const r=this.getAssetPlayer(t);r&&this.transferMediaFromPlayer(r,n)}transferMediaFromPlayer(t,n){const r=t.interstitial.appendInPlace,a=t.media;if(r&&a===this.primaryMedia){if(this.bufferingAsset=null,(!n||this.isInterstitial(n)&&!n.event.appendInPlace)&&n&&a){this.detachedData={media:a};return}const i=t.transferMedia();this.log(`transfer MediaSource from ${t} ${rd(i)}`),this.detachedData=i}else n&&a&&(this.shouldPlay||(this.shouldPlay=!a.paused))}transferMediaTo(t,n){var r,a;if(t.media===n)return;let i=null;const l=this.hls,o=t!==l,c=o&&t.interstitial.appendInPlace,d=(r=this.detachedData)==null?void 0:r.mediaSource;let u;if(l.media)c&&(i=l.transferMedia(),this.detachedData=i),u="Primary";else if(d){const y=this.getBufferingPlayer();y?(i=y.transferMedia(),u=`${y}`):u="detached MediaSource"}else u="detached media";if(!i){if(d)i=this.detachedData,this.log(`using detachedData: MediaSource ${rd(i)}`);else if(!this.detachedData||l.media===n){const y=this.playerQueue;y.length>1&&y.forEach(_=>{if(o&&_.interstitial.appendInPlace!==c){const v=_.interstitial;this.clearInterstitial(_.interstitial,null),v.appendInPlace=!1,v.appendInPlace&&this.warn(`Could not change append strategy for queued assets ${v}`)}}),this.hls.detachMedia(),this.detachedData={media:n}}}const h=i&&"mediaSource"in i&&((a=i.mediaSource)==null?void 0:a.readyState)!=="closed",p=h&&i?i:n;this.log(`${h?"transfering MediaSource":"attaching media"} to ${o?t:"Primary"} from ${u} (media.currentTime: ${n.currentTime})`);const f=this.schedule;if(p===i&&f){const y=o&&t.assetId===f.assetIdAtEnd;p.overrides={duration:f.duration,endOfStream:!o||y,cueRemoval:!o}}t.attachMedia(p)}onInterstitialCueEnter(){this.onTimeupdate()}checkStart(){const t=this.schedule,n=t==null?void 0:t.events;if(!n||this.playbackDisabled||!this.media)return;this.bufferedPos===-1&&(this.bufferedPos=0);const r=this.timelinePos,a=this.effectivePlayingItem;if(r===-1){const i=this.hls.startPosition;if(this.timelinePos=i,n.length===0)this.setSchedulePosition(0);else if(n[0].cue.pre){this.log(qI("checkStart (preroll)",i));const l=t.findEventIndex(n[0].identifier);this.setSchedulePosition(l)}else if(i>=0||!this.primaryLive){this.log(qI("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(qI("checkStart (playing item)",a.start));const i=t.findItemIndex(a);this.setSchedulePosition(i)}}advanceAssetBuffering(t,n){const r=t.event,a=r.findAssetIndex(n),i=WNe(r,a);if(!r.isAssetPastPlayoutLimit(i))this.bufferedToEvent(t,i);else if(this.schedule){var l;const o=(l=this.schedule.items)==null?void 0:l[this.findItemIndex(t)+1];o&&this.bufferedToItem(o)}}advanceAfterAssetEnded(t,n,r){const a=WNe(t,r);if(t.isAssetPastPlayoutLimit(a)){if(this.schedule){const i=this.schedule.items;if(i){const l=n+1,o=i.length;if(l>=o){this.setSchedulePosition(-1);return}const c=t.resumeTime;this.timelinePos=0?a[t]:null;this.log(`setSchedulePosition ${t}, ${n} (${i&&O1(i)}) pos: ${this.timelinePos}`);const l=this.waitingItem||this.playingItem,o=this.playingLastItem;if(this.isInterstitial(l)){const u=l.event,h=this.playingAsset,p=h==null?void 0:h.identifier,f=p?this.getAssetPlayer(p):null;if(f&&p&&(!this.eventItemsMatch(l,i)||n!==void 0&&p!==u.assetList[n].identifier)){var c;const y=u.findAssetIndex(h);if(this.log(`INTERSTITIAL_ASSET_ENDED ${y+1}/${u.assetList.length} ${iP(h)}`),this.endedAsset=h,this.playingAsset=null,this.hls.trigger(jt.INTERSTITIAL_ASSET_ENDED,{asset:h,assetListIndex:y,event:u,schedule:a.slice(0),scheduleIndex:t,player:f}),l!==this.playingItem){this.itemsMatch(l,this.playingItem)&&!this.playingAsset&&this.advanceAfterAssetEnded(u,this.findItemIndex(this.playingItem),y);return}this.retreiveMediaSource(p,i),f.media&&!((c=this.detachedData)!=null&&c.mediaSource)&&f.detachMedia()}if(!this.eventItemsMatch(l,i)&&(this.endedItem=l,this.playingItem=null,this.log(`INTERSTITIAL_ENDED ${u} ${O1(l)}`),u.hasPlayed=!0,this.hls.trigger(jt.INTERSTITIAL_ENDED,{event:u,schedule:a.slice(0),scheduleIndex:t}),u.cue.once)){var d;this.updateSchedule();const y=(d=this.schedule)==null?void 0:d.items;if(i&&y){const _=this.findItemIndex(i);this.advanceSchedule(_,y,n,l,o)}return}}this.advanceSchedule(t,a,n,l,o)}advanceSchedule(t,n,r,a,i){const l=this.schedule;if(!l)return;const o=n[t]||null,c=this.primaryMedia,d=this.playerQueue;if(d.length&&d.forEach(u=>{const h=u.interstitial,p=l.findEventIndex(h.identifier);(pt+1)&&this.clearInterstitial(h,o)}),this.isInterstitial(o)){this.timelinePos=Math.min(Math.max(this.timelinePos,o.start),o.end);const u=o.event;if(r===void 0){r=l.findAssetIndex(u,this.timelinePos);const y=WNe(u,r-1);if(u.isAssetPastPlayoutLimit(y)||u.appendInPlace&&this.timelinePos===o.end){this.advanceAfterAssetEnded(u,t,r);return}r=y}const h=this.waitingItem;this.assetsBuffered(o,c)||this.setBufferingItem(o);let p=this.preloadAssets(u,r);if(this.eventItemsMatch(o,h||a)||(this.waitingItem=o,this.log(`INTERSTITIAL_STARTED ${O1(o)} ${u.appendInPlace?"append in place":""}`),this.hls.trigger(jt.INTERSTITIAL_STARTED,{event:u,schedule:n.slice(0),scheduleIndex:t})),!u.assetListLoaded){this.log(`Waiting for ASSET-LIST to complete loading ${u}`);return}if(u.assetListLoader&&(u.assetListLoader.destroy(),u.assetListLoader=void 0),!c){this.log(`Waiting for attachMedia to start Interstitial ${u}`);return}this.waitingItem=this.endedItem=null,this.playingItem=o;const f=u.assetList[r];if(!f){this.advanceAfterAssetEnded(u,t,r||0);return}if(p||(p=this.getAssetPlayer(f.identifier)),p===null||p.destroyed){const y=u.assetList.length;this.warn(`asset ${r+1}/${y} player destroyed ${u}`),p=this.createAssetPlayer(u,f,r),p.loadSource()}if(!this.eventItemsMatch(o,this.bufferingItem)&&u.appendInPlace&&this.isAssetBuffered(f))return;this.startAssetPlayer(p,r,n,t,c),this.shouldPlay&&MJe(p.media)}else o?(this.resumePrimary(o,t,a),this.shouldPlay&&MJe(this.hls.media)):i&&this.isInterstitial(a)&&(this.endedItem=null,this.playingItem=a,a.event.appendInPlace||this.attachPrimary(l.durations.primary,null))}get playbackDisabled(){return this.hls.config.enableInterstitialPlayback===!1}get primaryDetails(){var t;return(t=this.mediaSelection)==null?void 0:t.main.details}get primaryLive(){var t;return!!((t=this.primaryDetails)!=null&&t.live)}resumePrimary(t,n,r){var a,i;if(this.playingItem=t,this.playingAsset=this.endedAsset=null,this.waitingItem=this.endedItem=null,this.bufferedToItem(t),this.log(`resuming ${O1(t)}`),!((a=this.detachedData)!=null&&a.mediaSource)){let o=this.timelinePos;(o=t.end)&&(o=this.getPrimaryResumption(t,n),this.log(qI("resumePrimary",o)),this.timelinePos=o),this.attachPrimary(o,t)}if(!r)return;const l=(i=this.schedule)==null?void 0:i.items;l&&(this.log(`INTERSTITIALS_PRIMARY_RESUMED ${O1(t)}`),this.hls.trigger(jt.INTERSTITIALS_PRIMARY_RESUMED,{schedule:l.slice(0),scheduleIndex:n}),this.checkBuffer())}getPrimaryResumption(t,n){const r=t.start;if(this.primaryLive){const a=this.primaryDetails;if(n===0)return this.hls.startPosition;if(a&&(ra.edge))return this.hls.liveSyncPosition||-1}return r}isAssetBuffered(t){const n=this.getAssetPlayer(t.identifier);return n!=null&&n.hls?n.hls.bufferedToEnd:bo.bufferInfo(this.primaryMedia,this.timelinePos,0).end+1>=t.timelineStart+(t.duration||0)}attachPrimary(t,n,r){n?this.setBufferingItem(n):this.bufferingItem=this.playingItem,this.bufferingAsset=null;const a=this.primaryMedia;if(!a)return;const i=this.hls;i.media?this.checkBuffer():(this.transferMediaTo(i,a),r&&this.startLoadingPrimaryAt(t,r)),r||(this.log(qI("attachPrimary",t)),this.timelinePos=t,this.startLoadingPrimaryAt(t,r))}startLoadingPrimaryAt(t,n){var r;const a=this.hls;!a.loadingEnabled||!a.media||Math.abs((((r=a.mainForwardBufferInfo)==null?void 0:r.start)||a.media.currentTime)-t)>.5?a.startLoad(t,n):a.bufferingEnabled||a.resumeBuffering()}onManifestLoading(){var t;this.stopLoad(),(t=this.schedule)==null||t.reset(),this.emptyPlayerQueue(),this.clearScheduleState(),this.shouldPlay=!1,this.bufferedPos=this.timelinePos=-1,this.mediaSelection=this.altSelection=this.manager=this.requiredTracks=null,this.hls.off(jt.BUFFER_CODECS,this.onBufferCodecs,this),this.hls.on(jt.BUFFER_CODECS,this.onBufferCodecs,this)}onLevelUpdated(t,n){if(n.level===-1||!this.schedule)return;const r=this.hls.levels[n.level];if(!r.details)return;const a=wc(wc({},this.mediaSelection||this.altSelection),{},{main:r});this.mediaSelection=a,this.schedule.parseInterstitialDateRanges(a,this.hls.config.interstitialAppendInPlace),!this.effectivePlayingItem&&this.schedule.items&&this.checkStart()}onAudioTrackUpdated(t,n){const r=this.hls.audioTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=wc(wc({},this.altSelection),{},{audio:r});return}const i=wc(wc({},a),{},{audio:r});this.mediaSelection=i}onSubtitleTrackUpdated(t,n){const r=this.hls.subtitleTracks[n.id],a=this.mediaSelection;if(!a){this.altSelection=wc(wc({},this.altSelection),{},{subtitles:r});return}const i=wc(wc({},a),{},{subtitles:r});this.mediaSelection=i}onAudioTrackSwitching(t,n){const r=BXe(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setAudioOption(n)||a.setAudioOption(r)))}onSubtitleTrackSwitch(t,n){const r=BXe(n);this.playerQueue.forEach(({hls:a})=>a&&(a.setSubtitleOption(n)||n.id!==-1&&a.setSubtitleOption(r)))}onBufferCodecs(t,n){const r=n.tracks;r&&(this.requiredTracks=r)}onBufferAppended(t,n){this.checkBuffer()}onBufferFlushed(t,n){const r=this.playingItem;if(r&&!this.itemsMatch(r,this.bufferingItem)&&!this.isInterstitial(r)){const a=this.timelinePos;this.bufferedPos=a,this.checkBuffer()}}onBufferedToEnd(t){if(!this.schedule)return;const n=this.schedule.events;if(this.bufferedPos.25){t.event.assetList.forEach((i,l)=>{t.event.isAssetPastPlayoutLimit(l)&&this.clearAssetPlayer(i.identifier,null)});const r=t.end+.25,a=bo.bufferInfo(this.primaryMedia,r,0);(a.end>r||(a.nextStart||0)>r)&&(this.log(`trim buffered interstitial ${O1(t)} (was ${O1(n)})`),this.attachPrimary(r,null,!0),this.flushFrontBuffer(r))}}itemsMatch(t,n){return!!n&&(t===n||t.event&&n.event&&this.eventItemsMatch(t,n)||!t.event&&!n.event&&this.findItemIndex(t)===this.findItemIndex(n))}eventItemsMatch(t,n){var r;return!!n&&(t===n||t.event.identifier===((r=n.event)==null?void 0:r.identifier))}findItemIndex(t,n){return t&&this.schedule?this.schedule.findItemIndex(t,n):-1}updateSchedule(t=!1){var n;const r=this.mediaSelection;r&&((n=this.schedule)==null||n.updateSchedule(r,[],t))}checkBuffer(t){var n;const r=(n=this.schedule)==null?void 0:n.items;if(!r)return;const a=bo.bufferInfo(this.primaryMedia,this.timelinePos,0);t&&(this.bufferedPos=this.timelinePos),t||(t=a.len<1),this.updateBufferedPos(a.end,r,t)}updateBufferedPos(t,n,r){const a=this.schedule,i=this.bufferingItem;if(this.bufferedPos>t||!a)return;if(n.length===1&&this.itemsMatch(n[0],i)){this.bufferedPos=t;return}const l=this.playingItem,o=this.findItemIndex(l);let c=a.findItemIndexAtTime(t);if(this.bufferedPos=i.end||(d=p.event)!=null&&d.appendInPlace&&t+.01>=p.start)&&(c=h),this.isInterstitial(i)){const f=i.event;if(h-o>1&&f.appendInPlace===!1||f.assetList.length===0&&f.assetListLoader)return}if(this.bufferedPos=t,c>u&&c>o)this.bufferedToItem(p);else{const f=this.primaryDetails;this.primaryLive&&f&&t>f.edge-f.targetduration&&p.start{const i=this.getAssetPlayer(a.identifier);return!(i!=null&&i.bufferedInPlaceToEnd(n))})}setBufferingItem(t){const n=this.bufferingItem,r=this.schedule;if(!this.itemsMatch(t,n)&&r){const{items:a,events:i}=r;if(!a||!i)return n;const l=this.isInterstitial(t),o=this.getBufferingPlayer();this.bufferingItem=t,this.bufferedPos=Math.max(t.start,Math.min(t.end,this.timelinePos));const c=o?o.remaining:n?n.end-this.timelinePos:0;if(this.log(`INTERSTITIALS_BUFFERED_TO_BOUNDARY ${O1(t)}`+(n?` (${c.toFixed(2)} remaining)`:"")),!this.playbackDisabled)if(l){const d=r.findAssetIndex(t.event,this.bufferedPos);t.event.assetList.forEach((u,h)=>{const p=this.getAssetPlayer(u.identifier);p&&(h===d&&p.loadSource(),p.resumeBuffering())})}else this.hls.resumeBuffering(),this.playerQueue.forEach(d=>d.pauseBuffering());this.hls.trigger(jt.INTERSTITIALS_BUFFERED_TO_BOUNDARY,{events:i.slice(0),schedule:a.slice(0),bufferingIndex:this.findItemIndex(t),playingIndex:this.findItemIndex(this.playingItem)})}else this.bufferingItem!==t&&(this.bufferingItem=t);return n}bufferedToItem(t,n=0){const r=this.setBufferingItem(t);if(!this.playbackDisabled){if(this.isInterstitial(t))this.bufferedToEvent(t,n);else if(r!==null){this.bufferingAsset=null;const a=this.detachedData;a?a.mediaSource?this.attachPrimary(t.start,t,!0):this.preloadPrimary(t):this.preloadPrimary(t)}}}preloadPrimary(t){const n=this.findItemIndex(t),r=this.getPrimaryResumption(t,n);this.startLoadingPrimaryAt(r)}bufferedToEvent(t,n){const r=t.event,a=r.assetList.length===0&&!r.assetListLoader,i=r.cue.once;if(a||!i){const l=this.preloadAssets(r,n);if(l!=null&&l.interstitial.appendInPlace){const o=this.primaryMedia;o&&this.bufferAssetPlayer(l,o)}}}preloadAssets(t,n){const r=t.assetUrl,a=t.assetList.length,i=a===0&&!t.assetListLoader,l=t.cue.once;if(i){const c=t.timelineStart;if(t.appendInPlace){var o;const p=this.playingItem;!this.isInterstitial(p)&&(p==null||(o=p.nextEvent)==null?void 0:o.identifier)===t.identifier&&this.flushFrontBuffer(c+.25)}let d,u=0;if(!this.playingItem&&this.primaryLive&&(u=this.hls.startPosition,u===-1&&(u=this.hls.liveSyncPosition||0)),u&&!(t.cue.pre||t.cue.post)){const p=u-c;p>0&&(d=Math.round(p*1e3)/1e3)}if(this.log(`Load interstitial asset ${n+1}/${r?1:a} ${t}${d?` live-start: ${u} start-offset: ${d}`:""}`),r)return this.createAsset(t,0,0,c,t.duration,r);const h=this.assetListLoader.loadAssetList(t,d);h&&(t.assetListLoader=h)}else if(!l&&a){for(let d=n;d{this.hls.trigger(jt.BUFFER_FLUSHING,{startOffset:t,endOffset:1/0,type:a})})}getAssetPlayerQueueIndex(t){const n=this.playerQueue;for(let r=0;r1){const E=n.duration;E&&A{if(A.live){var E;const I=new Error(`Interstitials MUST be VOD assets ${t}`),F={fatal:!0,type:ui.OTHER_ERROR,details:Mn.INTERSTITIAL_ASSET_ITEM_ERROR,error:I},z=((E=this.schedule)==null?void 0:E.findEventIndex(t.identifier))||-1;this.handleAssetItemError(F,t,z,r,I.message);return}const O=A.edge-A.fragmentStart,D=n.duration;(_||D===null||O>D)&&(_=!1,this.log(`Interstitial asset "${h}" duration change ${D} > ${O}`),n.duration=O,this.updateSchedule())};y.on(jt.LEVEL_UPDATED,(A,{details:E})=>v(E)),y.on(jt.LEVEL_PTS_UPDATED,(A,{details:E})=>v(E)),y.on(jt.EVENT_CUE_ENTER,()=>this.onInterstitialCueEnter());const j=(A,E)=>{const O=this.getAssetPlayer(h);if(O&&E.tracks){O.off(jt.BUFFER_CODECS,j),O.tracks=E.tracks;const D=this.primaryMedia;this.bufferingAsset===O.assetItem&&D&&!O.media&&this.bufferAssetPlayer(O,D)}};y.on(jt.BUFFER_CODECS,j);const w=()=>{var A;const E=this.getAssetPlayer(h);if(this.log(`buffered to end of asset ${E}`),!E||!this.schedule)return;const O=this.schedule.findEventIndex(t.identifier),D=(A=this.schedule.items)==null?void 0:A[O];this.isInterstitial(D)&&this.advanceAssetBuffering(D,n)};y.on(jt.BUFFERED_TO_END,w);const S=A=>()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;this.shouldPlay=!0;const O=this.schedule.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,O,A)};return y.once(jt.MEDIA_ENDED,S(r)),y.once(jt.PLAYOUT_LIMIT_REACHED,S(1/0)),y.on(jt.ERROR,(A,E)=>{if(!this.schedule)return;const O=this.getAssetPlayer(h);if(E.details===Mn.BUFFER_STALLED_ERROR){if(O!=null&&O.appendInPlace){this.handleInPlaceStall(t);return}this.onTimeupdate(),this.checkBuffer(!0);return}this.handleAssetItemError(E,t,this.schedule.findEventIndex(t.identifier),r,`Asset player error ${E.error} ${t}`)}),y.on(jt.DESTROYING,()=>{if(!this.getAssetPlayer(h)||!this.schedule)return;const E=new Error(`Asset player destroyed unexpectedly ${h}`),O={fatal:!0,type:ui.OTHER_ERROR,details:Mn.INTERSTITIAL_ASSET_ITEM_ERROR,error:E};this.handleAssetItemError(O,t,this.schedule.findEventIndex(t.identifier),r,E.message)}),this.log(`INTERSTITIAL_ASSET_PLAYER_CREATED ${iP(n)}`),this.hls.trigger(jt.INTERSTITIAL_ASSET_PLAYER_CREATED,{asset:n,assetListIndex:r,event:t,player:y}),y}clearInterstitial(t,n){this.clearAssetPlayers(t,n),t.reset()}clearAssetPlayers(t,n){t.assetList.forEach(r=>{this.clearAssetPlayer(r.identifier,n)})}resetAssetPlayer(t){const n=this.getAssetPlayerQueueIndex(t);if(n!==-1){this.log(`reset asset player "${t}" after error`);const r=this.playerQueue[n];this.transferMediaFromPlayer(r,null),r.resetDetails()}}clearAssetPlayer(t,n){const r=this.getAssetPlayerQueueIndex(t);if(r!==-1){const a=this.playerQueue[r];this.log(`clear ${a} toSegment: ${n&&O1(n)}`),this.transferMediaFromPlayer(a,n),this.playerQueue.splice(r,1),a.destroy()}}emptyPlayerQueue(){let t;for(;t=this.playerQueue.pop();)t.destroy();this.playerQueue=[]}startAssetPlayer(t,n,r,a,i){const{interstitial:l,assetItem:o,assetId:c}=t,d=l.assetList.length,u=this.playingAsset;this.endedAsset=null,this.playingAsset=o,(!u||u.identifier!==c)&&(u&&(this.clearAssetPlayer(u.identifier,r[a]),delete u.error),this.log(`INTERSTITIAL_ASSET_STARTED ${n+1}/${d} ${iP(o)}`),this.hls.trigger(jt.INTERSTITIAL_ASSET_STARTED,{asset:o,assetListIndex:n,event:l,schedule:r.slice(0),scheduleIndex:a,player:t})),this.bufferAssetPlayer(t,i)}bufferAssetPlayer(t,n){var r,a;if(!this.schedule)return;const{interstitial:i,assetItem:l}=t,o=this.schedule.findEventIndex(i.identifier),c=(r=this.schedule.items)==null?void 0:r[o];if(!c)return;t.loadSource(),this.setBufferingItem(c),this.bufferingAsset=l;const d=this.getBufferingPlayer();if(d===t)return;const u=i.appendInPlace;if(u&&(d==null?void 0:d.interstitial.appendInPlace)===!1)return;const h=(d==null?void 0:d.tracks)||((a=this.detachedData)==null?void 0:a.tracks)||this.requiredTracks;if(u&&l!==this.playingAsset){if(!t.tracks){this.log(`Waiting for track info before buffering ${t}`);return}if(h&&!lNt(h,t.tracks)){const p=new Error(`Asset ${iP(l)} SourceBuffer tracks ('${Object.keys(t.tracks)}') are not compatible with primary content tracks ('${Object.keys(h)}')`),f={fatal:!0,type:ui.OTHER_ERROR,details:Mn.INTERSTITIAL_ASSET_ITEM_ERROR,error:p},y=i.findAssetIndex(l);this.handleAssetItemError(f,i,o,y,p.message);return}}this.transferMediaTo(t,n)}handleInPlaceStall(t){const n=this.schedule,r=this.primaryMedia;if(!n||!r)return;const a=r.currentTime,i=n.findAssetIndex(t,a),l=t.assetList[i];if(l){const o=this.getAssetPlayer(l.identifier);if(o){const c=o.currentTime||a-l.timelineStart,d=o.duration-c;if(this.warn(`Stalled at ${c} of ${c+d} in ${o} ${t} (media.currentTime: ${a})`),c&&(d/r.playbackRate<.5||o.bufferedInPlaceToEnd(r))&&o.hls){const u=n.findEventIndex(t.identifier);this.advanceAfterAssetEnded(t,u,i)}}}}advanceInPlace(t){const n=this.primaryMedia;n&&n.currentTime!_.error))n.error=y;else for(let _=a;_{const j=parseFloat(_.DURATION);this.createAsset(i,v,u,c+u,j,_.URI),u+=j}),i.duration=u,this.log(`Loaded asset-list with duration: ${u} (was: ${d}) ${i}`);const h=this.waitingItem,p=(h==null?void 0:h.event.identifier)===l;this.updateSchedule();const f=(a=this.bufferingItem)==null?void 0:a.event;if(p){var y;const _=this.schedule.findEventIndex(l),v=(y=this.schedule.items)==null?void 0:y[_];if(v){if(!this.playingItem&&this.timelinePos>v.end&&this.schedule.findItemIndexAtTime(this.timelinePos)!==_){i.error=new Error(`Interstitial ${o.length?"no longer within playback range":"asset-list is empty"} ${this.timelinePos} ${i}`),this.log(i.error.message),this.updateSchedule(!0),this.primaryFallback(i);return}this.setBufferingItem(v)}this.setSchedulePosition(_)}else if((f==null?void 0:f.identifier)===l){const _=i.assetList[0];if(_){const v=this.getAssetPlayer(_.identifier);if(f.appendInPlace){const j=this.primaryMedia;v&&j&&this.bufferAssetPlayer(v,j)}else v&&v.loadSource()}}}onError(t,n){if(this.schedule)switch(n.details){case Mn.ASSET_LIST_PARSING_ERROR:case Mn.ASSET_LIST_LOAD_ERROR:case Mn.ASSET_LIST_LOAD_TIMEOUT:{const r=n.interstitial;r&&(this.updateSchedule(!0),this.primaryFallback(r));break}case Mn.BUFFER_STALLED_ERROR:{const r=this.endedItem||this.waitingItem||this.playingItem;if(this.isInterstitial(r)&&r.event.appendInPlace){this.handleInPlaceStall(r.event);return}this.log(`Primary player stall @${this.timelinePos} bufferedPos: ${this.bufferedPos}`),this.onTimeupdate(),this.checkBuffer(!0);break}}}}const IJe=500;class xon extends w8e{constructor(t,n,r){super(t,n,r,"subtitle-stream-controller",Wa.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(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(jt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(jt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.on(jt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.on(jt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.on(jt.BUFFER_FLUSHING,this.onBufferFlushing,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(jt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(jt.SUBTITLE_TRACK_SWITCH,this.onSubtitleTrackSwitch,this),t.off(jt.SUBTITLE_TRACK_LOADED,this.onSubtitleTrackLoaded,this),t.off(jt.SUBTITLE_FRAG_PROCESSED,this.onSubtitleFragProcessed,this),t.off(jt.BUFFER_FLUSHING,this.onBufferFlushing,this)}startLoad(t,n){this.stopLoad(),this.state=cr.IDLE,this.setInterval(IJe),this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}onManifestLoading(){super.onManifestLoading(),this.mainDetails=null}onMediaDetaching(t,n){this.tracksBuffered=[],super.onMediaDetaching(t,n)}onLevelLoaded(t,n){this.mainDetails=n.details}onSubtitleFragProcessed(t,n){const{frag:r,success:a}=n;if(this.fragContextChanged(r)||(Nh(r)&&(this.fragPrevious=r),this.state=cr.IDLE),!a)return;const i=this.tracksBuffered[this.currentTrackId];if(!i)return;let l;const o=r.start;for(let d=0;d=i[d].start&&o<=i[d].end){l=i[d];break}const c=r.start+r.duration;l?l.end=c:(l={start:o,end:c},i.push(l)),this.fragmentTracker.fragBuffered(r),this.fragBufferedComplete(r,null),this.media&&this.tick()}onBufferFlushing(t,n){const{startOffset:r,endOffset:a}=n;if(r===0&&a!==Number.POSITIVE_INFINITY){const i=a-1;if(i<=0)return;n.endOffsetSubtitles=Math.max(0,i),this.tracksBuffered.forEach(l=>{for(let o=0;onew p$(r));return}this.tracksBuffered=[],this.levels=n.map(r=>{const a=new p$(r);return this.tracksBuffered[a.id]=[],a}),this.fragmentTracker.removeFragmentsInRange(0,Number.POSITIVE_INFINITY,Wa.SUBTITLE),this.fragPrevious=null,this.mediaBuffer=null}onSubtitleTrackSwitch(t,n){var r;if(this.currentTrackId=n.id,!((r=this.levels)!=null&&r.length)||this.currentTrackId===-1){this.clearInterval();return}const a=this.levels[this.currentTrackId];a!=null&&a.details?this.mediaBuffer=this.mediaBufferTimeRanges:this.mediaBuffer=null,a&&this.state!==cr.STOPPED&&this.setInterval(IJe)}onSubtitleTrackLoaded(t,n){var r;const{currentTrackId:a,levels:i}=this,{details:l,id:o}=n;if(!i){this.warn(`Subtitle tracks were reset while loading level ${o}`);return}const c=i[o];if(o>=i.length||!c)return;this.log(`Subtitle track ${o} loaded [${l.startSN},${l.endSN}]${l.lastPartSn?`[part-${l.lastPartSn}-${l.lastPartIndex}]`:""},duration:${l.totalduration}`),this.mediaBuffer=this.mediaBufferTimeRanges;let d=0;if(l.live||(r=c.details)!=null&&r.live){if(l.deltaUpdateFailed)return;const h=this.mainDetails;if(!h){this.startFragRequested=!1;return}const p=h.fragments[0];if(!c.details)l.hasProgramDateTime&&h.hasProgramDateTime?(qge(l,h),d=l.fragmentStart):p&&(d=p.start,vTe(l,d));else{var u;d=this.alignPlaylists(l,c.details,(u=this.levelLastLoaded)==null?void 0:u.details),d===0&&p&&(d=p.start,vTe(l,d))}h&&!this.startFragRequested&&this.setStartPosition(h,d)}c.details=l,this.levelLastLoaded=c,o===a&&(this.hls.trigger(jt.SUBTITLE_TRACK_UPDATED,{details:l,id:o,groupId:n.groupId}),this.tick(),l.live&&!this.fragCurrent&&this.media&&this.state===cr.IDLE&&(LM(null,l.fragments,this.media.currentTime,0)||(this.warn("Subtitle playlist not aligned with playback"),c.details=void 0)))}_handleFragmentLoadComplete(t){const{frag:n,payload:r}=t,a=n.decryptdata,i=this.hls;if(!this.fragContextChanged(n)&&r&&r.byteLength>0&&a!=null&&a.key&&a.iv&&$L(a.method)){const l=performance.now();this.decrypter.decrypt(new Uint8Array(r),a.key.buffer,a.iv.buffer,b8e(a.method)).catch(o=>{throw i.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.FRAG_DECRYPT_ERROR,fatal:!1,error:o,reason:o.message,frag:n}),o}).then(o=>{const c=performance.now();i.trigger(jt.FRAG_DECRYPTED,{frag:n,payload:o,stats:{tstart:l,tdecrypt:c}})}).catch(o=>{this.warn(`${o.name}: ${o.message}`),this.state=cr.IDLE})}}doTick(){if(!this.media){this.state=cr.IDLE;return}if(this.state===cr.IDLE){const{currentTrackId:t,levels:n}=this,r=n==null?void 0:n[t];if(!r||!n.length||!r.details||this.waitForLive(r))return;const{config:a}=this,i=this.getLoadPosition(),l=bo.bufferedInfo(this.tracksBuffered[this.currentTrackId]||[],i,a.maxBufferHole),{end:o,len:c}=l,d=r.details,u=this.hls.maxBufferLength+d.levelTargetDuration;if(c>u)return;const h=d.fragments,p=h.length,f=d.edge;let y=null;const _=this.fragPrevious;if(of-w?0:w;y=LM(_,h,Math.max(h[0].start,o),S),!y&&_&&_.start{if(a=a>>>0,a>i-1)throw new DOMException(`Failed to execute '${r}' on 'TimeRanges': The index provided (${a}) is greater than the maximum bound (${i})`);return t[a][r]};this.buffered={get length(){return t.length},end(r){return n("end",r,t.length)},start(r){return n("start",r,t.length)}}}}const yon={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},Ckt=s=>String.fromCharCode(yon[s]||s),$1=15,d2=100,von={17:1,18:3,21:5,22:7,23:9,16:11,19:12,20:14},bon={17:2,18:4,21:6,22:8,23:10,19:13,20:15},_on={25:1,26:3,29:5,30:7,31:9,24:11,27:12,28:14},won={25:2,26:4,29:6,30:8,31:10,27:13,28:15},jon=["white","green","blue","cyan","red","yellow","magenta","black","transparent"];class Non{constructor(){this.time=null,this.verboseLevel=0}log(t,n){if(this.verboseLevel>=t){const r=typeof n=="function"?n():n;Cc.log(`${this.time} [${t}] ${r}`)}}}const u3=function(t){const n=[];for(let r=0;rd2&&(this.logger.log(3,"Too large cursor position "+this.pos),this.pos=d2)}moveCursor(t){const n=this.pos+t;if(t>1)for(let r=this.pos+1;r=144&&this.backSpace();const n=Ckt(t);if(this.pos>=d2){this.logger.log(0,()=>"Cannot insert "+t.toString(16)+" ("+n+") at position "+this.pos+". Skipping it!");return}this.chars[this.pos].setChar(n,this.currPenState),this.moveCursor(1)}clearFromPos(t){let n;for(n=t;n"pacData = "+rd(t));let n=t.row-1;if(this.nrRollUpRows&&n"bkgData = "+rd(t)),this.backSpace(),this.setPen(t),this.insertChar(32)}setRollUpRows(t){this.nrRollUpRows=t}rollUp(){if(this.nrRollUpRows===null){this.logger.log(3,"roll_up but nrRollUpRows not set yet");return}this.logger.log(1,()=>this.getDisplayText());const t=this.currRow+1-this.nrRollUpRows,n=this.rows.splice(t,1)[0];n.clear(),this.rows.splice(this.currRow,0,n),this.logger.log(2,"Rolling up")}getDisplayText(t){t=t||!1;const n=[];let r="",a=-1;for(let i=0;i<$1;i++){const l=this.rows[i].getTextString();l&&(a=i+1,t?n.push("Row "+a+": '"+l+"'"):n.push(l.trim()))}return n.length>0&&(t?r="["+n.join(" | ")+"]":r=n.join(` `)),r}getTextAndFormat(){return this.rows}}class PJe{constructor(t,n,r){this.chNr=void 0,this.outputFilter=void 0,this.mode=void 0,this.verbose=void 0,this.displayedMemory=void 0,this.nonDisplayedMemory=void 0,this.lastOutputScreen=void 0,this.currRollUpRow=void 0,this.writeScreen=void 0,this.cueStartTime=void 0,this.logger=void 0,this.chNr=t,this.outputFilter=n,this.mode=null,this.verbose=0,this.displayedMemory=new KNe(r),this.nonDisplayedMemory=new KNe(r),this.lastOutputScreen=new KNe(r),this.currRollUpRow=this.displayedMemory.rows[$1-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null,this.logger=r}reset(){this.mode=null,this.displayedMemory.reset(),this.nonDisplayedMemory.reset(),this.lastOutputScreen.reset(),this.outputFilter.reset(),this.currRollUpRow=this.displayedMemory.rows[$1-1],this.writeScreen=this.displayedMemory,this.mode=null,this.cueStartTime=null}getHandler(){return this.outputFilter}setHandler(t){this.outputFilter=t}setPAC(t){this.writeScreen.setPAC(t)}setBkgData(t){this.writeScreen.setBkgData(t)}setMode(t){t!==this.mode&&(this.mode=t,this.logger.log(2,()=>"MODE="+t),this.mode==="MODE_POP-ON"?this.writeScreen=this.nonDisplayedMemory:(this.writeScreen=this.displayedMemory,this.writeScreen.reset()),this.mode!=="MODE_ROLL-UP"&&(this.displayedMemory.nrRollUpRows=null,this.nonDisplayedMemory.nrRollUpRows=null),this.mode=t)}insertChars(t){for(let r=0;rn+": "+this.writeScreen.getDisplayText(!0)),(this.mode==="MODE_PAINT-ON"||this.mode==="MODE_ROLL-UP")&&(this.logger.log(1,()=>"DISPLAYED: "+this.displayedMemory.getDisplayText(!0)),this.outputDataUpdate())}ccRCL(){this.logger.log(2,"RCL - Resume Caption Loading"),this.setMode("MODE_POP-ON")}ccBS(){this.logger.log(2,"BS - BackSpace"),this.mode!=="MODE_TEXT"&&(this.writeScreen.backSpace(),this.writeScreen===this.displayedMemory&&this.outputDataUpdate())}ccAOF(){}ccAON(){}ccDER(){this.logger.log(2,"DER- Delete to End of Row"),this.writeScreen.clearToEndOfRow(),this.outputDataUpdate()}ccRU(t){this.logger.log(2,"RU("+t+") - Roll Up"),this.writeScreen=this.displayedMemory,this.setMode("MODE_ROLL-UP"),this.writeScreen.setRollUpRows(t)}ccFON(){this.logger.log(2,"FON - Flash On"),this.writeScreen.setPen({flash:!0})}ccRDC(){this.logger.log(2,"RDC - Resume Direct Captioning"),this.setMode("MODE_PAINT-ON")}ccTR(){this.logger.log(2,"TR"),this.setMode("MODE_TEXT")}ccRTD(){this.logger.log(2,"RTD"),this.setMode("MODE_TEXT")}ccEDM(){this.logger.log(2,"EDM - Erase Displayed Memory"),this.displayedMemory.reset(),this.outputDataUpdate(!0)}ccCR(){this.logger.log(2,"CR - Carriage Return"),this.writeScreen.rollUp(),this.outputDataUpdate(!0)}ccENM(){this.logger.log(2,"ENM - Erase Non-displayed Memory"),this.nonDisplayedMemory.reset()}ccEOC(){if(this.logger.log(2,"EOC - End Of Caption"),this.mode==="MODE_POP-ON"){const t=this.displayedMemory;this.displayedMemory=this.nonDisplayedMemory,this.nonDisplayedMemory=t,this.writeScreen=this.nonDisplayedMemory,this.logger.log(1,()=>"DISP: "+this.displayedMemory.getDisplayText())}this.outputDataUpdate(!0)}ccTO(t){this.logger.log(2,"TO("+t+") - Tab Offset"),this.writeScreen.moveCursor(t)}ccMIDROW(t){const n={flash:!1};if(n.underline=t%2===1,n.italics=t>=46,n.italics)n.foreground="white";else{const r=Math.floor(t/2)-16,a=["white","green","blue","cyan","red","yellow","magenta"];n.foreground=a[r]}this.logger.log(2,"MIDROW: "+rd(n)),this.writeScreen.setPen(n)}outputDataUpdate(t=!1){const n=this.logger.time;n!==null&&this.outputFilter&&(this.cueStartTime===null&&!this.displayedMemory.isEmpty()?this.cueStartTime=n:this.displayedMemory.equals(this.lastOutputScreen)||(this.outputFilter.newCue(this.cueStartTime,n,this.lastOutputScreen),t&&this.outputFilter.dispatchCue&&this.outputFilter.dispatchCue(),this.cueStartTime=this.displayedMemory.isEmpty()?null:n),this.lastOutputScreen.copy(this.displayedMemory))}cueSplitAtTime(t){this.outputFilter&&(this.displayedMemory.isEmpty()||(this.outputFilter.newCue&&this.outputFilter.newCue(this.cueStartTime,t,this.displayedMemory),this.cueStartTime=t))}}class LJe{constructor(t,n,r){this.channels=void 0,this.currentChannel=0,this.cmdHistory=Ton(),this.logger=void 0;const a=this.logger=new Non;this.channels=[null,new PJe(t,n,a),new PJe(t+1,r,a)]}getHandler(t){return this.channels[t].getHandler()}setHandler(t,n){this.channels[t].setHandler(n)}addData(t,n){this.logger.time=t;for(let r=0;r"["+u3([n[r],n[r+1]])+"] -> ("+u3([a,i])+")");const c=this.cmdHistory;if(a>=16&&a<=31){if(Con(a,i,c)){PG(null,null,c),this.logger.log(3,()=>"Repeated command ("+u3([a,i])+") is dropped");continue}PG(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 PG(null,null,c);if(!l&&(o=this.parseChars(a,i),o)){const u=this.currentChannel;u&&u>0?this.channels[u].insertChars(o):this.logger.log(2,"No channel found yet. TEXT-MODE?")}!l&&!o&&this.logger.log(2,()=>"Couldn't parse cleaned data "+u3([a,i])+" orig: "+u3([n[r],n[r+1]]))}}parseCmd(t,n){const r=(t===20||t===28||t===21||t===29)&&n>=32&&n<=47,a=(t===23||t===31)&&n>=33&&n<=35;if(!(r||a))return!1;const i=t===20||t===21||t===23?1:2,l=this.channels[i];return t===20||t===21||t===28||t===29?n===32?l.ccRCL():n===33?l.ccBS():n===34?l.ccAOF():n===35?l.ccAON():n===36?l.ccDER():n===37?l.ccRU(2):n===38?l.ccRU(3):n===39?l.ccRU(4):n===40?l.ccFON():n===41?l.ccRDC():n===42?l.ccTR():n===43?l.ccRTD():n===44?l.ccEDM():n===45?l.ccCR():n===46?l.ccENM():n===47&&l.ccEOC():l.ccTO(n-32),this.currentChannel=i,!0}parseMidrow(t,n){let r=0;if((t===17||t===25)&&n>=32&&n<=47){if(t===17?r=1:r=2,r!==this.currentChannel)return this.logger.log(0,"Mismatch channel in midrow parsing"),!1;const a=this.channels[r];return a?(a.ccMIDROW(n),this.logger.log(3,()=>"MIDROW ("+u3([t,n])+")"),!0):!1}return!1}parsePAC(t,n){let r;const a=(t>=17&&t<=23||t>=25&&t<=31)&&n>=64&&n<=127,i=(t===16||t===24)&&n>=64&&n<=95;if(!(a||i))return!1;const l=t<=23?1:2;n>=64&&n<=95?r=l===1?von[t]:_on[t]:r=l===1?bon[t]:won[t];const o=this.channels[l];return o?(o.setPAC(this.interpretPAC(r,n)),this.currentChannel=l,!0):!1}interpretPAC(t,n){let r;const a={color:null,italics:!1,indent:null,underline:!1,row:t};return n>95?r=n-96:r=n-64,a.underline=(r&1)===1,r<=13?a.color=["white","green","blue","cyan","red","yellow","magenta","white"][Math.floor(r/2)]:r<=15?(a.italics=!0,a.color="white"):a.indent=Math.floor((r-16)/2)*4,a}parseChars(t,n){let r,a=null,i=null;if(t>=25?(r=2,i=t-8):(r=1,i=t),i>=17&&i<=19){let l;i===17?l=n+80:i===18?l=n+112:l=n+144,this.logger.log(2,()=>"Special char '"+Ckt(l)+"' in channel "+r),a=[l]}else t>=32&&t<=127&&(a=n===0?[t]:[t,n]);return a&&this.logger.log(3,()=>"Char codes = "+u3(a).join(",")),a}parseBackgroundAttributes(t,n){const r=(t===16||t===24)&&n>=32&&n<=47,a=(t===23||t===31)&&n>=45&&n<=47;if(!(r||a))return!1;let i;const l={};t===16||t===24?(i=Math.floor((n-32)/2),l.background=jon[i],n%2===1&&(l.background=l.background+"_semi")):n===45?l.background="transparent":(l.foreground="black",n===47&&(l.underline=!0));const o=t<=23?1:2;return this.channels[o].setBkgData(l),!0}reset(){for(let t=0;t100)throw new Error("Position must be between 0 and 100.");O=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"positionAlign",i({},h,{get:function(){return D},set:function(z){const H=a(z);if(!H)throw new SyntaxError("An invalid or illegal string was specified.");D=H,this.hasBeenReset=!0}})),Object.defineProperty(u,"size",i({},h,{get:function(){return I},set:function(z){if(z<0||z>100)throw new Error("Size must be between 0 and 100.");I=z,this.hasBeenReset=!0}})),Object.defineProperty(u,"align",i({},h,{get:function(){return F},set:function(z){const H=a(z);if(!H)throw new SyntaxError("An invalid or illegal string was specified.");F=H,this.hasBeenReset=!0}})),u.displayState=void 0}return l.prototype.getCueAsHTML=function(){return self.WebVTT.convertCueToDOMTree(self,this.text)},l}();class Eon{decode(t,n){if(!t)return"";if(typeof t!="string")throw new Error("Error - expected string data.");return decodeURIComponent(encodeURIComponent(t))}}function Ekt(s){function t(r,a,i,l){return(r|0)*3600+(a|0)*60+(i|0)+parseFloat(l||0)}const n=s.match(/^(?:(\d+):)?(\d{2}):(\d{2})(\.\d+)?/);return n?parseFloat(n[2])>59?t(n[2],n[3],0,n[4]):t(n[1],n[2],n[3],n[4]):null}class Aon{constructor(){this.values=Object.create(null)}set(t,n){!this.get(t)&&n!==""&&(this.values[t]=n)}get(t,n,r){return r?this.has(t)?this.values[t]:n[r]:this.has(t)?this.values[t]:n}has(t){return t in this.values}alt(t,n,r){for(let a=0;a=0&&r<=100)return this.set(t,r),!0}return!1}}function Akt(s,t,n,r){const a=r?s.split(r):[s];for(const i in a){if(typeof a[i]!="string")continue;const l=a[i].split(n);if(l.length!==2)continue;const o=l[0],c=l[1];t(o,c)}}const CTe=new L8e(0,0,""),LG=CTe.align==="middle"?"middle":"center";function Mon(s,t,n){const r=s;function a(){const o=Ekt(s);if(o===null)throw new Error("Malformed timestamp: "+r);return s=s.replace(/^[^\sa-zA-Z-]+/,""),o}function i(o,c){const d=new Aon;Akt(o,function(p,f){let y;switch(p){case"region":for(let _=n.length-1;_>=0;_--)if(n[_].id===f){d.set(p,n[_].region);break}break;case"vertical":d.alt(p,f,["rl","lr"]);break;case"line":y=f.split(","),d.integer(p,y[0]),d.percent(p,y[0])&&d.set("snapToLines",!1),d.alt(p,y[0],["auto"]),y.length===2&&d.alt("lineAlign",y[1],["start",LG,"end"]);break;case"position":y=f.split(","),d.percent(p,y[0]),y.length===2&&d.alt("positionAlign",y[1],["start",LG,"end","line-left","line-right","auto"]);break;case"size":d.percent(p,f);break;case"align":d.alt(p,f,["start",LG,"end","left","right"]);break}},/:/,/\s/),c.region=d.get("region",null),c.vertical=d.get("vertical","");let u=d.get("line","auto");u==="auto"&&CTe.line===-1&&(u=-1),c.line=u,c.lineAlign=d.get("lineAlign","start"),c.snapToLines=d.get("snapToLines",!0),c.size=d.get("size",100),c.align=d.get("align",LG);let h=d.get("position","auto");h==="auto"&&CTe.position===50&&(h=c.align==="start"||c.align==="left"?0:c.align==="end"||c.align==="right"?100:50),c.position=h}function l(){s=s.replace(/^\s+/,"")}if(l(),t.startTime=a(),l(),s.slice(0,3)!=="-->")throw new Error("Malformed time stamp (time stamps must be separated by '-->'): "+r);s=s.slice(3),l(),t.endTime=a(),l(),i(s,t)}function Mkt(s){return s.replace(//gi,` `)}class Ion{constructor(){this.state="INITIAL",this.buffer="",this.decoder=new Eon,this.regionList=[],this.cue=null,this.oncue=void 0,this.onparsingerror=void 0,this.onflush=void 0}parse(t){const n=this;t&&(n.buffer+=n.decoder.decode(t,{stream:!0}));function r(){let i=n.buffer,l=0;for(i=Mkt(i);l")===-1){n.cue.id=i;continue}case"CUE":if(!n.cue){n.state="BADCUE";continue}try{Mon(i,n.cue,n.regionList)}catch{n.cue=null,n.state="BADCUE";continue}n.state="CUETEXT";continue;case"CUETEXT":{const o=i.indexOf("-->")!==-1;if(!i||o&&(l=!0)){n.oncue&&n.cue&&n.oncue(n.cue),n.cue=null,n.state="ID";continue}if(n.cue===null)continue;n.cue.text&&(n.cue.text+=` `),n.cue.text+=i}continue;case"BADCUE":i||(n.state="ID")}}}catch{n.state==="CUETEXT"&&n.cue&&n.oncue&&n.oncue(n.cue),n.cue=null,n.state=n.state==="INITIAL"?"BADWEBVTT":"BADCUE"}return this}flush(){const t=this;try{if((t.cue||t.state==="HEADER")&&(t.buffer+=` `,t.parse()),t.state==="INITIAL"||t.state==="BADWEBVTT")throw new Error("Malformed WebVTT signature.")}catch(n){t.onparsingerror&&t.onparsingerror(n)}return t.onflush&&t.onflush(),this}}const Pon=/\r\n|\n\r|\n|\r/g,YNe=function(t,n,r=0){return t.slice(r,r+n.length)===n},Lon=function(t){let n=parseInt(t.slice(-3));const r=parseInt(t.slice(-6,-4)),a=parseInt(t.slice(-9,-7)),i=t.length>9?parseInt(t.substring(0,t.indexOf(":"))):0;if(!Pa(n)||!Pa(r)||!Pa(a)||!Pa(i))throw Error(`Malformed X-TIMESTAMP-MAP: Local:${t}`);return n+=1e3*r,n+=60*1e3*a,n+=60*60*1e3*i,n};function D8e(s,t,n){return Nz(s.toString())+Nz(t.toString())+Nz(n)}const Don=function(t,n,r){let a=t[n],i=t[a.prevCC];if(!i||!i.new&&a.new){t.ccOffset=t.presentationOffset=a.start,a.new=!1;return}for(;(l=i)!=null&&l.new;){var l;t.ccOffset+=a.start-i.start,a.new=!1,a=i,i=t[a.prevCC]}t.presentationOffset=r};function Ron(s,t,n,r,a,i,l){const o=new Ion,c=fy(new Uint8Array(s)).trim().replace(Pon,` `).split(` `),d=[],u=t?Uan(t.baseTime,t.timescale):0;let h="00:00.000",p=0,f=0,y,_=!0;o.oncue=function(v){const j=n[r];let w=n.ccOffset;const S=(p-u)/9e4;if(j!=null&&j.new&&(f!==void 0?w=n.ccOffset=j.start:Don(n,r,S)),S){if(!t){y=new Error("Missing initPTS for VTT MPEGTS");return}w=S-n.presentationOffset}const A=v.endTime-v.startTime,E=F0((v.startTime+w-f)*9e4,a*9e4)/9e4;v.startTime=Math.max(E,0),v.endTime=Math.max(E+A,0);const O=v.text.trim();v.text=decodeURIComponent(encodeURIComponent(O)),v.id||(v.id=D8e(v.startTime,v.endTime,O)),v.endTime>0&&d.push(v)},o.onparsingerror=function(v){y=v},o.onflush=function(){if(y){l(y);return}i(d)},c.forEach(v=>{if(_)if(YNe(v,"X-TIMESTAMP-MAP=")){_=!1,v.slice(16).split(",").forEach(j=>{YNe(j,"LOCAL:")?h=j.slice(6):YNe(j,"MPEGTS:")&&(p=parseInt(j.slice(7)))});try{f=Lon(h)/1e3}catch(j){y=j}return}else v===""&&(_=!1);o.parse(v+` `)}),o.flush()}const ZNe="stpp.ttml.im1t",Ikt=/^(\d{2,}):(\d{2}):(\d{2}):(\d{2})\.?(\d+)?$/,Pkt=/^(\d*(?:\.\d*)?)(h|m|s|ms|f|t)$/,Oon={left:"start",center:"center",right:"end",start:"start",end:"end"};function DJe(s,t,n,r){const a=Qo(new Uint8Array(s),["mdat"]);if(a.length===0){r(new Error("Could not parse IMSC1 mdat"));return}const i=a.map(o=>fy(o)),l=$an(t.baseTime,1,t.timescale);try{i.forEach(o=>n(Fon(o,l)))}catch(o){r(o)}}function Fon(s,t){const a=new DOMParser().parseFromString(s,"text/xml").getElementsByTagName("tt")[0];if(!a)throw new Error("Invalid ttml");const i={frameRate:30,subFrameRate:1,frameRateMultiplier:0,tickRate:0},l=Object.keys(i).reduce((h,p)=>(h[p]=a.getAttribute(`ttp:${p}`)||i[p],h),{}),o=a.getAttribute("xml:space")!=="preserve",c=RJe(QNe(a,"styling","style")),d=RJe(QNe(a,"layout","region")),u=QNe(a,"body","[begin]");return[].map.call(u,h=>{const p=Lkt(h,o);if(!p||!h.hasAttribute("begin"))return null;const f=JNe(h.getAttribute("begin"),l),y=JNe(h.getAttribute("dur"),l);let _=JNe(h.getAttribute("end"),l);if(f===null)throw OJe(h);if(_===null){if(y===null)throw OJe(h);_=f+y}const v=new L8e(f-t,_-t,p);v.id=D8e(v.startTime,v.endTime,v.text);const j=d[h.getAttribute("region")],w=c[h.getAttribute("style")],S=zon(j,w,c),{textAlign:A}=S;if(A){const E=Oon[A];E&&(v.lineAlign=E),v.align=A}return Wc(v,S),v}).filter(h=>h!==null)}function QNe(s,t,n){const r=s.getElementsByTagName(t)[0];return r?[].slice.call(r.querySelectorAll(n)):[]}function RJe(s){return s.reduce((t,n)=>{const r=n.getAttribute("xml:id");return r&&(t[r]=n),t},{})}function Lkt(s,t){return[].slice.call(s.childNodes).reduce((n,r,a)=>{var i;return r.nodeName==="br"&&a?n+` `:(i=r.childNodes)!=null&&i.length?Lkt(r,t):t?n+r.textContent.trim().replace(/\s+/g," "):n+r.textContent},"")}function zon(s,t,n){const r="http://www.w3.org/ns/ttml#styling";let a=null;const i=["displayAlign","textAlign","color","backgroundColor","fontSize","fontFamily"],l=s!=null&&s.hasAttribute("style")?s.getAttribute("style"):null;return l&&n.hasOwnProperty(l)&&(a=n[l]),i.reduce((o,c)=>{const d=XNe(t,r,c)||XNe(s,r,c)||XNe(a,r,c);return d&&(o[c]=d),o},{})}function XNe(s,t,n){return s&&s.hasAttributeNS(t,n)?s.getAttributeNS(t,n):null}function OJe(s){return new Error(`Could not parse ttml timestamp ${s}`)}function JNe(s,t){if(!s)return null;let n=Ekt(s);return n===null&&(Ikt.test(s)?n=Bon(s,t):Pkt.test(s)&&(n=$on(s,t))),n}function Bon(s,t){const n=Ikt.exec(s),r=(n[4]|0)+(n[5]|0)/t.subFrameRate;return(n[1]|0)*3600+(n[2]|0)*60+(n[3]|0)+r/t.frameRate}function $on(s,t){const n=Pkt.exec(s),r=Number(n[1]);switch(n[2]){case"h":return r*3600;case"m":return r*60;case"ms":return r*1e3;case"f":return r/t.frameRate;case"t":return r/t.tickRate}return r}class DG{constructor(t,n){this.timelineController=void 0,this.cueRanges=[],this.trackName=void 0,this.startTime=null,this.endTime=null,this.screen=null,this.timelineController=t,this.trackName=n}dispatchCue(){this.startTime!==null&&(this.timelineController.addCues(this.trackName,this.startTime,this.endTime,this.screen,this.cueRanges),this.startTime=null)}newCue(t,n,r){(this.startTime===null||this.startTime>t)&&(this.startTime=t),this.endTime=n,this.screen=r,this.timelineController.createCaptionsTrack(this.trackName)}reset(){this.cueRanges=[],this.startTime=null}}class Uon{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=zJe(),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(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(jt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.on(jt.FRAG_LOADING,this.onFragLoading,this),t.on(jt.FRAG_LOADED,this.onFragLoaded,this),t.on(jt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.on(jt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.on(jt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.on(jt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.on(jt.BUFFER_FLUSHING,this.onBufferFlushing,this)}destroy(){const{hls:t}=this;t.off(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(jt.SUBTITLE_TRACKS_UPDATED,this.onSubtitleTracksUpdated,this),t.off(jt.FRAG_LOADING,this.onFragLoading,this),t.off(jt.FRAG_LOADED,this.onFragLoaded,this),t.off(jt.FRAG_PARSING_USERDATA,this.onFragParsingUserdata,this),t.off(jt.FRAG_DECRYPTED,this.onFragDecrypted,this),t.off(jt.INIT_PTS_FOUND,this.onInitPtsFound,this),t.off(jt.SUBTITLE_TRACKS_CLEARED,this.onSubtitleTracksCleared,this),t.off(jt.BUFFER_FLUSHING,this.onBufferFlushing,this),this.hls=this.config=this.media=null,this.cea608Parser1=this.cea608Parser2=void 0}initCea608Parsers(){const t=new DG(this,"textTrack1"),n=new DG(this,"textTrack2"),r=new DG(this,"textTrack3"),a=new DG(this,"textTrack4");this.cea608Parser1=new LJe(1,t,n),this.cea608Parser2=new LJe(3,r,a)}addCues(t,n,r,a,i){let l=!1;for(let o=i.length;o--;){const c=i[o],d=qon(c[0],c[1],n,r);if(d>=0&&(c[0]=Math.min(c[0],n),c[1]=Math.max(c[1],r),l=!0,d/(r-n)>.5))return}if(l||i.push([n,r]),this.config.renderTextTracksNatively){const o=this.captionsTracks[t];this.Cues.newCue(o,n,r,a)}else{const o=this.Cues.newCue(null,n,r,a);this.hls.trigger(jt.CUES_PARSED,{type:"captions",cues:o,track:t})}}onInitPtsFound(t,{frag:n,id:r,initPTS:a,timescale:i,trackId:l}){const{unparsedVttFrags:o}=this;r===Wa.MAIN&&(this.initPTS[n.cc]={baseTime:a,timescale:i,trackId:l}),o.length&&(this.unparsedVttFrags=[],o.forEach(c=>{this.initPTS[c.frag.cc]?this.onFragLoaded(jt.FRAG_LOADED,c):this.hls.trigger(jt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:c.frag,error:new Error("Subtitle discontinuity domain does not match main")})}))}getExistingTrack(t,n){const{media:r}=this;if(r)for(let a=0;a{RP(a[i]),delete a[i]}),this.nonNativeCaptionsTracks={}}onManifestLoading(){this.lastCc=-1,this.lastSn=-1,this.lastPartIndex=-1,this.prevCC=-1,this.vttCCs=zJe(),this._cleanTracks(),this.tracks=[],this.captionsTracks={},this.nonNativeCaptionsTracks={},this.textTracks=[],this.unparsedVttFrags=[],this.initPTS=[],this.cea608Parser1&&this.cea608Parser2&&(this.cea608Parser1.reset(),this.cea608Parser2.reset())}_cleanTracks(){const{media:t}=this;if(!t)return;const n=t.textTracks;if(n)for(let r=0;ri.textCodec===ZNe);if(this.config.enableWebVTT||a&&this.config.enableIMSC1){if(ukt(this.tracks,r)){this.tracks=r;return}if(this.textTracks=[],this.tracks=r,this.config.renderTextTracksNatively){const l=this.media,o=l?tpe(l.textTracks):null;if(this.tracks.forEach((c,d)=>{let u;if(o){let h=null;for(let p=0;pd!==null).map(d=>d.label);c.length&&this.hls.logger.warn(`Media element contains unused subtitle tracks: ${c.join(", ")}. Replace media element for each source to clear TextTracks and captions menu.`)}}else if(this.tracks.length){const l=this.tracks.map(o=>({label:o.name,kind:o.type.toLowerCase(),default:o.default,subtitleTrack:o}));this.hls.trigger(jt.NON_NATIVE_TEXT_TRACKS_FOUND,{tracks:l})}}}onManifestLoaded(t,n){this.config.enableCEA708Captions&&n.captions&&n.captions.forEach(r=>{const a=/(?:CC|SERVICE)([1-4])/.exec(r.instreamId);if(!a)return;const i=`textTrack${a[1]}`,l=this.captionsProperties[i];l&&(l.label=r.name,r.lang&&(l.languageCode=r.lang),l.media=r)})}closedCaptionsForLevel(t){const n=this.hls.levels[t.level];return n==null?void 0:n.attrs["CLOSED-CAPTIONS"]}onFragLoading(t,n){if(this.enabled&&n.frag.type===Wa.MAIN){var r,a;const{cea608Parser1:i,cea608Parser2:l,lastSn:o}=this,{cc:c,sn:d}=n.frag,u=(r=(a=n.part)==null?void 0:a.index)!=null?r:-1;i&&l&&(d!==o+1||d===o&&u!==this.lastPartIndex+1||c!==this.lastCc)&&(i.reset(),l.reset()),this.lastCc=c,this.lastSn=d,this.lastPartIndex=u}}onFragLoaded(t,n){const{frag:r,payload:a}=n;if(r.type===Wa.SUBTITLE)if(a.byteLength){const i=r.decryptdata,l="stats"in n;if(i==null||!i.encrypted||l){const o=this.tracks[r.level],c=this.vttCCs;c[r.cc]||(c[r.cc]={start:r.start,prevCC:this.prevCC,new:!0},this.prevCC=r.cc),o&&o.textCodec===ZNe?this._parseIMSC1(r,a):this._parseVTTs(n)}}else this.hls.trigger(jt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:new Error("Empty subtitle payload")})}_parseIMSC1(t,n){const r=this.hls;DJe(n,this.initPTS[t.cc],a=>{this._appendCues(a,t.level),r.trigger(jt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:t})},a=>{r.logger.log(`Failed to parse IMSC1: ${a}`),r.trigger(jt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:t,error:a})})}_parseVTTs(t){var n;const{frag:r,payload:a}=t,{initPTS:i,unparsedVttFrags:l}=this,o=i.length-1;if(!i[r.cc]&&o===-1){l.push(t);return}const c=this.hls,d=(n=r.initSegment)!=null&&n.data?Gv(r.initSegment.data,new Uint8Array(a)).buffer:a;Ron(d,this.initPTS[r.cc],this.vttCCs,r.cc,r.start,u=>{this._appendCues(u,r.level),c.trigger(jt.SUBTITLE_FRAG_PROCESSED,{success:!0,frag:r})},u=>{const h=u.message==="Missing initPTS for VTT MPEGTS";h?l.push(t):this._fallbackToIMSC1(r,a),c.logger.log(`Failed to parse VTT cue: ${u}`),!(h&&o>r.cc)&&c.trigger(jt.SUBTITLE_FRAG_PROCESSED,{success:!1,frag:r,error:u})})}_fallbackToIMSC1(t,n){const r=this.tracks[t.level];r.textCodec||DJe(n,this.initPTS[t.cc],()=>{r.textCodec=ZNe,this._parseIMSC1(t,n)},()=>{r.textCodec="wvtt"})}_appendCues(t,n){const r=this.hls;if(this.config.renderTextTracksNatively){const a=this.textTracks[n];if(!a||a.mode==="disabled")return;t.forEach(i=>kkt(a,i))}else{const a=this.tracks[n];if(!a)return;const i=a.default?"default":"subtitles"+n;r.trigger(jt.CUES_PARSED,{type:"subtitles",cues:t,track:i})}}onFragDecrypted(t,n){const{frag:r}=n;r.type===Wa.SUBTITLE&&this.onFragLoaded(jt.FRAG_LOADED,n)}onSubtitleTracksCleared(){this.tracks=[],this.captionsTracks={}}onFragParsingUserdata(t,n){if(!this.enabled||!this.config.enableCEA708Captions)return;const{frag:r,samples:a}=n;if(!(r.type===Wa.MAIN&&this.closedCaptionsForLevel(r)==="NONE"))for(let i=0;iSTe(o[c],n,r))}if(this.config.renderTextTracksNatively&&n===0&&a!==void 0){const{textTracks:o}=this;Object.keys(o).forEach(c=>STe(o[c],n,a))}}}extractCea608Data(t){const n=[[],[]],r=t[0]&31;let a=2;for(let i=0;i=16?c--:c++;const f=Mkt(d.trim()),y=D8e(t,n,f);s!=null&&(h=s.cues)!=null&&h.getCueById(y)||(l=new u(t,n,f),l.id=y,l.line=p+1,l.align="left",l.position=10+Math.min(80,Math.floor(c*8/32)*10),a.push(l))}return s&&a.length&&(a.sort((p,f)=>p.line==="auto"||f.line==="auto"?0:p.line>8&&f.line>8?f.line-p.line:p.line-f.line),a.forEach(p=>kkt(s,p))),a}};function Gon(){if(self.fetch&&self.AbortController&&self.ReadableStream&&self.Request)try{return new self.ReadableStream({}),!0}catch{}return!1}const Won=/(\d+)-(\d+)\/(\d+)/;class BJe{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||Qon,this.controller=new self.AbortController,this.stats=new m8e}destroy(){this.loader=this.callbacks=this.context=this.config=this.request=null,this.abortInternal(),this.response=null,this.fetchSetup=this.controller=this.stats=null}abortInternal(){this.controller&&!this.stats.loading.end&&(this.stats.aborted=!0,this.controller.abort())}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.response)}load(t,n,r){const a=this.stats;if(a.loading.start)throw new Error("Loader can only be used once.");a.loading.start=self.performance.now();const i=Kon(t,this.controller.signal),l=t.responseType==="arraybuffer",o=l?"byteLength":"length",{maxTimeToFirstByteMs:c,maxLoadTimeMs:d}=n.loadPolicy;this.context=t,this.config=n,this.callbacks=r,this.request=this.fetchSetup(t,i),self.clearTimeout(this.requestTimeout),n.timeout=c&&Pa(c)?c:d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},n.timeout),(g$(this.request)?this.request.then(self.fetch):self.fetch(this.request)).then(h=>{var p;this.response=this.loader=h;const f=Math.max(self.performance.now(),a.loading.start);if(self.clearTimeout(this.requestTimeout),n.timeout=d,this.requestTimeout=self.setTimeout(()=>{this.callbacks&&(this.abortInternal(),this.callbacks.onTimeout(a,t,this.response))},d-(f-a.loading.start)),!h.ok){const{status:_,statusText:v}=h;throw new Xon(v||"fetch, bad network response",_,h)}a.loading.first=f,a.total=Zon(h.headers)||a.total;const y=(p=this.callbacks)==null?void 0:p.onProgress;return y&&Pa(n.highWaterMark)?this.loadProgressively(h,a,t,n.highWaterMark,y):l?h.arrayBuffer():t.responseType==="json"?h.json():h.text()}).then(h=>{var p,f;const y=this.response;if(!y)throw new Error("loader destroyed");self.clearTimeout(this.requestTimeout),a.loading.end=Math.max(self.performance.now(),a.loading.first);const _=h[o];_&&(a.loaded=a.total=_);const v={url:y.url,data:h,code:y.status},j=(p=this.callbacks)==null?void 0:p.onProgress;j&&!Pa(n.highWaterMark)&&j(a,t,h,y),(f=this.callbacks)==null||f.onSuccess(v,a,t,y)}).catch(h=>{var p;if(self.clearTimeout(this.requestTimeout),a.aborted)return;const f=h&&h.code||0,y=h?h.message:null;(p=this.callbacks)==null||p.onError({code:f,text:y},t,h?h.details:null,a)})}getCacheAge(){let t=null;if(this.response){const n=this.response.headers.get("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.response?this.response.headers.get(t):null}loadProgressively(t,n,r,a=0,i){const l=new HNt,o=t.body.getReader(),c=()=>o.read().then(d=>{if(d.done)return l.dataLength&&i(n,r,l.flush().buffer,t),Promise.resolve(new ArrayBuffer(0));const u=d.value,h=u.length;return n.loaded+=h,h=a&&i(n,r,l.flush().buffer,t)):i(n,r,u.buffer,t),c()}).catch(()=>Promise.reject());return c()}}function Kon(s,t){const n={method:"GET",mode:"cors",credentials:"same-origin",signal:t,headers:new self.Headers(Wc({},s.headers))};return s.rangeEnd&&n.headers.set("Range","bytes="+s.rangeStart+"-"+String(s.rangeEnd-1)),n}function Yon(s){const t=Won.exec(s);if(t)return parseInt(t[2])-parseInt(t[1])+1}function Zon(s){const t=s.get("Content-Range");if(t){const r=Yon(t);if(Pa(r))return r}const n=s.get("Content-Length");if(n)return parseInt(n)}function Qon(s,t){return new self.Request(s.url,t)}class Xon extends Error{constructor(t,n,r){super(t),this.code=void 0,this.details=void 0,this.code=n,this.details=r}}const Jon=/^age:\s*[\d.]+\s*$/im;class Rkt{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 m8e,this.retryDelay=0}destroy(){this.callbacks=null,this.abortInternal(),this.loader=null,this.config=null,this.context=null,this.xhrSetup=null}abortInternal(){const t=this.loader;self.clearTimeout(this.requestTimeout),self.clearTimeout(this.retryTimeout),t&&(t.onreadystatechange=null,t.onprogress=null,t.readyState!==4&&(this.stats.aborted=!0,t.abort()))}abort(){var t;this.abortInternal(),(t=this.callbacks)!=null&&t.onAbort&&this.callbacks.onAbort(this.stats,this.context,this.loader)}load(t,n,r){if(this.stats.loading.start)throw new Error("Loader can only be used once.");this.stats.loading.start=self.performance.now(),this.context=t,this.config=n,this.callbacks=r,this.loadInternal()}loadInternal(){const{config:t,context:n}=this;if(!t||!n)return;const r=this.loader=new self.XMLHttpRequest,a=this.stats;a.loading.first=0,a.loaded=0,a.aborted=!1;const i=this.xhrSetup;i?Promise.resolve().then(()=>{if(!(this.loader!==r||this.stats.aborted))return i(r,n.url)}).catch(l=>{if(!(this.loader!==r||this.stats.aborted))return r.open("GET",n.url,!0),i(r,n.url)}).then(()=>{this.loader!==r||this.stats.aborted||this.openAndSendXhr(r,n,t)}).catch(l=>{var o;(o=this.callbacks)==null||o.onError({code:r.status,text:l.message},n,r,a)}):this.openAndSendXhr(r,n,t)}openAndSendXhr(t,n,r){t.readyState||t.open("GET",n.url,!0);const a=n.headers,{maxTimeToFirstByteMs:i,maxLoadTimeMs:l}=r.loadPolicy;if(a)for(const o in a)t.setRequestHeader(o,a[o]);n.rangeEnd&&t.setRequestHeader("Range","bytes="+n.rangeStart+"-"+(n.rangeEnd-1)),t.onreadystatechange=this.readystatechange.bind(this),t.onprogress=this.loadprogress.bind(this),t.responseType=n.responseType,self.clearTimeout(this.requestTimeout),r.timeout=i&&Pa(i)?i:l,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),r.timeout),t.send()}readystatechange(){const{context:t,loader:n,stats:r}=this;if(!t||!n)return;const a=n.readyState,i=this.config;if(!r.aborted&&a>=2&&(r.loading.first===0&&(r.loading.first=Math.max(self.performance.now(),r.loading.start),i.timeout!==i.loadPolicy.maxLoadTimeMs&&(self.clearTimeout(this.requestTimeout),i.timeout=i.loadPolicy.maxLoadTimeMs,this.requestTimeout=self.setTimeout(this.loadtimeout.bind(this),i.loadPolicy.maxLoadTimeMs-(r.loading.first-r.loading.start)))),a===4)){self.clearTimeout(this.requestTimeout),n.onreadystatechange=null,n.onprogress=null;const d=n.status,u=n.responseType==="text"?n.responseText:null;if(d>=200&&d<300){const y=u??n.response;if(y!=null){var l,o;r.loading.end=Math.max(self.performance.now(),r.loading.first);const _=n.responseType==="arraybuffer"?y.byteLength:y.length;r.loaded=r.total=_,r.bwEstimate=r.total*8e3/(r.loading.end-r.loading.first);const v=(l=this.callbacks)==null?void 0:l.onProgress;v&&v(r,t,y,n);const j={url:n.responseURL,data:y,code:d};(o=this.callbacks)==null||o.onSuccess(j,r,t,n);return}}const h=i.loadPolicy.errorRetry,p=r.retry,f={url:t.url,data:void 0,code:d};if(Bge(h,p,!1,f))this.retry(h);else{var c;Cc.error(`${d} while loading ${t.url}`),(c=this.callbacks)==null||c.onError({code:d,text:n.statusText},t,n,r)}}}loadtimeout(){if(!this.config)return;const t=this.config.loadPolicy.timeoutRetry,n=this.stats.retry;if(Bge(t,n,!0))this.retry(t);else{var r;Cc.warn(`timeout while loading ${(r=this.context)==null?void 0:r.url}`);const a=this.callbacks;a&&(this.abortInternal(),a.onTimeout(this.stats,this.context,this.loader))}}retry(t){const{context:n,stats:r}=this;this.retryDelay=g8e(t,r.retry),r.retry++,Cc.warn(`${status?"HTTP Status "+status:"Timeout"} while loading ${n==null?void 0:n.url}, retrying ${r.retry}/${t.maxNumRetry} in ${this.retryDelay}ms`),this.abortInternal(),this.loader=null,self.clearTimeout(this.retryTimeout),this.retryTimeout=self.setTimeout(this.loadInternal.bind(this),this.retryDelay)}loadprogress(t){const n=this.stats;n.loaded=t.loaded,t.lengthComputable&&(n.total=t.total)}getCacheAge(){let t=null;if(this.loader&&Jon.test(this.loader.getAllResponseHeaders())){const n=this.loader.getResponseHeader("age");t=n?parseFloat(n):null}return t}getResponseHeader(t){return this.loader&&new RegExp(`^${t}:\\s*[\\d.]+\\s*$`,"im").test(this.loader.getAllResponseHeaders())?this.loader.getResponseHeader(t):null}}const eln={maxTimeToFirstByteMs:8e3,maxLoadTimeMs:2e4,timeoutRetry:null,errorRetry:null},tln=wc(wc({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:Rkt,fLoader:void 0,pLoader:void 0,xhrSetup:void 0,licenseXhrSetup:void 0,licenseResponseCallback:void 0,abrController:mrn,bufferController:nin,capLevelController:M8e,errorController:yrn,fpsController:ron,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:LNt,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:eln},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},sln()),{},{subtitleStreamController:xon,subtitleTrackController:oon,timelineController:Uon,audioStreamController:Jan,audioTrackController:ein,emeController:UL,cmcdController:eon,contentSteeringController:son,interstitialsController:fon});function sln(){return{cueHandler:Hon,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 nln(s,t,n){if((t.liveSyncDurationCount||t.liveMaxLatencyDurationCount)&&(t.liveSyncDuration||t.liveMaxLatencyDuration))throw new Error("Illegal hls.js config: don't mix up liveSyncDurationCount/liveMaxLatencyDurationCount and liveSyncDuration/liveMaxLatencyDuration");if(t.liveMaxLatencyDurationCount!==void 0&&(t.liveSyncDurationCount===void 0||t.liveMaxLatencyDurationCount<=t.liveSyncDurationCount))throw new Error('Illegal hls.js config: "liveMaxLatencyDurationCount" must be greater than "liveSyncDurationCount"');if(t.liveMaxLatencyDuration!==void 0&&(t.liveSyncDuration===void 0||t.liveMaxLatencyDuration<=t.liveSyncDuration))throw new Error('Illegal hls.js config: "liveMaxLatencyDuration" must be greater than "liveSyncDuration"');const r=TTe(s),a=["manifest","level","frag"],i=["TimeOut","MaxRetry","RetryDelay","MaxRetryTimeout"];return a.forEach(l=>{const o=`${l==="level"?"playlist":l}LoadPolicy`,c=t[o]===void 0,d=[];i.forEach(u=>{const h=`${l}Loading${u}`,p=t[h];if(p!==void 0&&c){d.push(h);const f=r[o].default;switch(t[o]={default:f},u){case"TimeOut":f.maxLoadTimeMs=p,f.maxTimeToFirstByteMs=p;break;case"MaxRetry":f.errorRetry.maxNumRetry=p,f.timeoutRetry.maxNumRetry=p;break;case"RetryDelay":f.errorRetry.retryDelayMs=p,f.timeoutRetry.retryDelayMs=p;break;case"MaxRetryTimeout":f.errorRetry.maxRetryDelayMs=p,f.timeoutRetry.maxRetryDelayMs=p;break}}}),d.length&&n.warn(`hls.js config: "${d.join('", "')}" setting(s) are deprecated, use "${o}": ${rd(t[o])}`)}),wc(wc({},r),t)}function TTe(s){return s&&typeof s=="object"?Array.isArray(s)?s.map(TTe):Object.keys(s).reduce((t,n)=>(t[n]=TTe(s[n]),t),{}):s}function rln(s,t){const n=s.loader;n!==BJe&&n!==Rkt?(t.log("[config]: Custom loader detected, cannot enable progressive streaming"),s.progressive=!1):Gon()&&(s.loader=BJe,s.progressive=!0,s.enableSoftwareAES=!0,t.log("[config]: Progressive streaming enabled, using FetchLoader"))}const spe=2,aln=.1,iln=.05,oln=100;class lln extends ENt{constructor(t,n){super("gap-controller",t.logger),this.hls=void 0,this.fragmentTracker=void 0,this.media=null,this.mediaSource=void 0,this.nudgeRetry=0,this.stallReported=!1,this.stalled=null,this.moved=!1,this.seeking=!1,this.buffered={},this.lastCurrentTime=0,this.ended=0,this.waiting=0,this.onMediaPlaying=()=>{this.ended=0,this.waiting=0},this.onMediaWaiting=()=>{var r;(r=this.media)!=null&&r.seeking||(this.waiting=self.performance.now(),this.tick())},this.onMediaEnded=()=>{if(this.hls){var r;this.ended=((r=this.media)==null?void 0:r.currentTime)||1,this.hls.trigger(jt.MEDIA_ENDED,{stalled:!1})}},this.hls=t,this.fragmentTracker=n,this.registerListeners()}registerListeners(){const{hls:t}=this;t&&(t.on(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(jt.BUFFER_APPENDED,this.onBufferAppended,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(jt.BUFFER_APPENDED,this.onBufferAppended,this))}destroy(){super.destroy(),this.unregisterListeners(),this.media=this.hls=this.fragmentTracker=null,this.mediaSource=void 0}onMediaAttached(t,n){this.setInterval(oln),this.mediaSource=n.mediaSource;const r=this.media=n.media;Xx(r,"playing",this.onMediaPlaying),Xx(r,"waiting",this.onMediaWaiting),Xx(r,"ended",this.onMediaEnded)}onMediaDetaching(t,n){this.clearInterval();const{media:r}=this;r&&(Og(r,"playing",this.onMediaPlaying),Og(r,"waiting",this.onMediaWaiting),Og(r,"ended",this.onMediaEnded),this.media=null),this.mediaSource=void 0}onBufferAppended(t,n){this.buffered=n.timeRanges}get hasBuffered(){return Object.keys(this.buffered).length>0}tick(){var t;if(!((t=this.media)!=null&&t.readyState)||!this.hasBuffered)return;const n=this.media.currentTime;this.poll(n,this.lastCurrentTime),this.lastCurrentTime=n}poll(t,n){var r,a;const i=(r=this.hls)==null?void 0:r.config;if(!i)return;const l=this.media;if(!l)return;const{seeking:o}=l,c=this.seeking&&!o,d=!this.seeking&&o,u=l.paused&&!o||l.ended||l.playbackRate===0;if(this.seeking=o,t!==n){n&&(this.ended=0),this.moved=!0,o||(this.nudgeRetry=0,i.nudgeOnVideoHole&&!u&&t>n&&this.nudgeOnVideoHole(t,n)),this.waiting===0&&this.stallResolved(t);return}if(d||c){c&&this.stallResolved(t);return}if(u){this.nudgeRetry=0,this.stallResolved(t),!this.ended&&l.ended&&this.hls&&(this.ended=t||1,this.hls.trigger(jt.MEDIA_ENDED,{stalled:!1}));return}if(!bo.getBuffered(l).length){this.nudgeRetry=0;return}const h=bo.bufferInfo(l,t,0),p=h.nextStart||0,f=this.fragmentTracker;if(o&&f&&this.hls){const O=$Je(this.hls.inFlightFragments,t),D=h.len>spe,I=!p||O||p-t>spe&&!f.getPartialFragment(t);if(D||I)return;this.moved=!1}const y=(a=this.hls)==null?void 0:a.latestLevelDetails;if(!this.moved&&this.stalled!==null&&f){if(!(h.len>0)&&!p)return;const D=Math.max(p,h.start||0)-t,F=!!(y!=null&&y.live)?y.targetduration*2:spe,z=RG(t,f);if(D>0&&(D<=F||z)){l.paused||this._trySkipBufferHole(z);return}}const _=i.detectStallWithCurrentTimeMs,v=self.performance.now(),j=this.waiting;let w=this.stalled;if(w===null)if(j>0&&v-j<_)w=this.stalled=j;else{this.stalled=v;return}const S=v-w;if(!o&&(S>=_||j)&&this.hls){var A;if(((A=this.mediaSource)==null?void 0:A.readyState)==="ended"&&!(y!=null&&y.live)&&Math.abs(t-((y==null?void 0:y.edge)||0))<1){if(this.ended)return;this.ended=t||1,this.hls.trigger(jt.MEDIA_ENDED,{stalled:!0});return}if(this._reportStall(h),!this.media||!this.hls)return}const E=bo.bufferInfo(l,t,i.maxBufferHole);this._tryFixBufferStall(E,S,t)}stallResolved(t){const n=this.stalled;if(n&&this.hls&&(this.stalled=null,this.stallReported)){const r=self.performance.now()-n;this.log(`playback not stuck anymore @${t}, after ${Math.round(r)}ms`),this.stallReported=!1,this.waiting=0,this.hls.trigger(jt.STALL_RESOLVED,{})}}nudgeOnVideoHole(t,n){var r;const a=this.buffered.video;if(this.hls&&this.media&&this.fragmentTracker&&(r=this.buffered.audio)!=null&&r.length&&a&&a.length>1&&t>a.end(0)){const i=bo.bufferedInfo(bo.timeRangesToArray(this.buffered.audio),t,0);if(i.len>1&&n>=i.start){const l=bo.timeRangesToArray(a),o=bo.bufferedInfo(l,n,0).bufferedIndex;if(o>-1&&oo)&&u-d<1&&t-d<2){const h=new Error(`nudging playhead to flush pipeline after video hole. currentTime: ${t} hole: ${d} -> ${u} buffered index: ${c}`);this.warn(h.message),this.media.currentTime+=1e-6;let p=RG(t,this.fragmentTracker);p&&"fragment"in p?p=p.fragment:p||(p=void 0);const f=bo.bufferInfo(this.media,t,0);this.hls.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.BUFFER_SEEK_OVER_HOLE,fatal:!1,error:h,reason:h.message,frag:p,buffer:f.len,bufferInfo:f})}}}}}_tryFixBufferStall(t,n,r){var a,i;const{fragmentTracker:l,media:o}=this,c=(a=this.hls)==null?void 0:a.config;if(!o||!l||!c)return;const d=(i=this.hls)==null?void 0:i.latestLevelDetails,u=RG(r,l);if((u||d!=null&&d.live&&r1&&t.len>c.maxBufferHole||t.nextStart&&(t.nextStart-rc.highBufferWatchdogPeriod*1e3||this.waiting)&&(this.warn("Trying to nudge playhead over buffer-hole"),this._tryNudgeBuffer(t))}adjacentTraversal(t,n){const r=this.fragmentTracker,a=t.nextStart;if(r&&a){const i=r.getFragAtPos(n,Wa.MAIN),l=r.getFragAtPos(a,Wa.MAIN);if(i&&l)return l.sn-i.sn<2}return!1}_reportStall(t){const{hls:n,media:r,stallReported:a,stalled:i}=this;if(!a&&i!==null&&r&&n){this.stallReported=!0;const l=new Error(`Playback stalling at @${r.currentTime} due to low buffer (${rd(t)})`);this.warn(l.message),n.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.BUFFER_STALLED_ERROR,fatal:!1,error:l,buffer:t.len,bufferInfo:t,stalled:{start:i}})}}_trySkipBufferHole(t){var n;const{fragmentTracker:r,media:a}=this,i=(n=this.hls)==null?void 0:n.config;if(!a||!r||!i)return 0;const l=a.currentTime,o=bo.bufferInfo(a,l,0),c=l0&&o.len<1&&a.readyState<3,p=c-l;if(p>0&&(u||h)){if(p>i.maxBufferHole){let y=!1;if(l===0){const _=r.getAppendedFrag(0,Wa.MAIN);_&&c<_.end&&(y=!0)}if(!y&&t){var d;if(!((d=this.hls.loadLevelObj)!=null&&d.details)||$Je(this.hls.inFlightFragments,c))return 0;let v=!1,j=t.end;for(;j"u"))return self.VTTCue||self.TextTrackCue}function eke(s,t,n,r,a){let i=new s(t,n,"");try{i.value=r,a&&(i.type=a)}catch{i=new s(t,n,rd(a?wc({type:a},r):r))}return i}const OG=(()=>{const s=ETe();try{s&&new s(0,Number.POSITIVE_INFINITY,"")}catch{return Number.MAX_VALUE}return Number.POSITIVE_INFINITY})();class dln{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(jt.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(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.on(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.on(jt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.on(jt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(jt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}_unregisterListeners(){const{hls:t}=this;t&&(t.off(jt.MEDIA_ATTACHING,this.onMediaAttaching,this),t.off(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.FRAG_PARSING_METADATA,this.onFragParsingMetadata,this),t.off(jt.BUFFER_FLUSHING,this.onBufferFlushing,this),t.off(jt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(jt.LEVEL_PTS_UPDATED,this.onLevelPtsUpdated,this))}onMediaAttaching(t,n){var r;this.media=n.media,((r=n.overrides)==null?void 0:r.cueRemoval)===!1&&(this.removeCues=!1)}onMediaAttached(){var t;const n=(t=this.hls)==null?void 0:t.latestLevelDetails;n&&this.updateDateRangeCues(n)}onMediaDetaching(t,n){this.media=null,!n.transferMedia&&(this.id3Track&&(this.removeCues&&RP(this.id3Track,this.onEventCueEnter),this.id3Track=null),this.dateRangeCuesAppended={})}onManifestLoading(){this.dateRangeCuesAppended={}}createTrack(t){const n=this.getID3Track(t.textTracks);return n.mode="hidden",n}getID3Track(t){if(this.media){for(let n=0;nOG&&(h=OG),h-u<=0&&(h=u+cln);for(let f=0;fu.type===G0.audioId3&&c:a==="video"?d=u=>u.type===G0.emsg&&o:d=u=>u.type===G0.audioId3&&c||u.type===G0.emsg&&o,STe(i,n,r,d)}}onLevelUpdated(t,{details:n}){this.updateDateRangeCues(n,!0)}onLevelPtsUpdated(t,n){Math.abs(n.drift)>.01&&this.updateDateRangeCues(n.details)}updateDateRangeCues(t,n){if(!this.hls||!this.media)return;const{assetPlayerId:r,timelineOffset:a,enableDateRangeMetadataCues:i,interstitialsController:l}=this.hls.config;if(!i)return;const o=ETe();if(r&&a&&!l){const{fragmentStart:_,fragmentEnd:v}=t;let j=this.assetCue;j?(j.startTime=_,j.endTime=v):o&&(j=this.assetCue=eke(o,_,v,{assetPlayerId:this.hls.config.assetPlayerId},"hlsjs.interstitial.asset"),j&&(j.id=r,this.id3Track||(this.id3Track=this.createTrack(this.media)),this.id3Track.addCue(j),j.addEventListener("enter",this.onEventCueEnter)))}if(!t.hasProgramDateTime)return;const{id3Track:c}=this,{dateRanges:d}=t,u=Object.keys(d);let h=this.dateRangeCuesAppended;if(c&&n){var p;if((p=c.cues)!=null&&p.length){const _=Object.keys(h).filter(v=>!u.includes(v));for(let v=_.length;v--;){var f;const j=_[v],w=(f=h[j])==null?void 0:f.cues;delete h[j],w&&Object.keys(w).forEach(S=>{const A=w[S];if(A){A.removeEventListener("enter",this.onEventCueEnter);try{c.removeCue(A)}catch{}}})}}else h=this.dateRangeCuesAppended={}}const y=t.fragments[t.fragments.length-1];if(!(u.length===0||!Pa(y==null?void 0:y.programDateTime))){this.id3Track||(this.id3Track=this.createTrack(this.media));for(let _=0;_{if(Z!==j.id){const Y=d[Z];if(Y.class===j.class&&Y.startDate>j.startDate&&(!H||j.startDate.01&&(Z.startTime=w,Z.endTime=O);else if(o){let Y=j.attr[H];Irn(H)&&(Y=cNt(Y));const ee=eke(o,w,O,{key:H,data:Y},G0.dateRange);ee&&(ee.id=v,this.id3Track.addCue(ee),A[H]=ee,l&&(H==="X-ASSET-LIST"||H==="X-ASSET-URL")&&ee.addEventListener("enter",this.onEventCueEnter))}}h[v]={cues:A,dateRange:j,durationKnown:E}}}}}class uln{constructor(t){this.hls=void 0,this.config=void 0,this.media=null,this.currentTime=0,this.stallCount=0,this._latency=null,this._targetLatencyUpdated=!1,this.onTimeupdate=()=>{const{media:n}=this,r=this.levelDetails;if(!n||!r)return;this.currentTime=n.currentTime;const a=this.computeLatency();if(a===null)return;this._latency=a;const{lowLatencyMode:i,maxLiveSyncPlaybackRate:l}=this.config;if(!i||l===1||!r.live)return;const o=this.targetLatency;if(o===null)return;const c=a-o,d=Math.min(this.maxLatency,o+r.targetduration);if(c.05&&this.forwardBufferLength>1){const h=Math.min(2,Math.max(1,l)),p=Math.round(2/(1+Math.exp(-.75*c-this.edgeStalled))*20)/20,f=Math.min(h,Math.max(1,p));this.changeMediaPlaybackRate(n,f)}else n.playbackRate!==1&&n.playbackRate!==0&&this.changeMediaPlaybackRate(n,1)},this.hls=t,this.config=t.config,this.registerListeners()}get levelDetails(){var t;return((t=this.hls)==null?void 0:t.latestLevelDetails)||null}get latency(){return this._latency||0}get maxLatency(){const{config:t}=this;if(t.liveMaxLatencyDuration!==void 0)return t.liveMaxLatencyDuration;const n=this.levelDetails;return n?t.liveMaxLatencyDurationCount*n.targetduration:0}get targetLatency(){const t=this.levelDetails;if(t===null||this.hls===null)return null;const{holdBack:n,partHoldBack:r,targetduration:a}=t,{liveSyncDuration:i,liveSyncDurationCount:l,lowLatencyMode:o}=this.config,c=this.hls.userConfig;let d=o&&r||n;(this._targetLatencyUpdated||c.liveSyncDuration||c.liveSyncDurationCount||d===0)&&(d=i!==void 0?i:l*a);const u=a;return d+Math.min(this.stallCount*this.config.liveSyncOnStallIncrease,u)}set targetLatency(t){this.stallCount=0,this.config.liveSyncDuration=t,this._targetLatencyUpdated=!0}get liveSyncPosition(){const t=this.estimateLiveEdge(),n=this.targetLatency;if(t===null||n===null)return null;const r=this.levelDetails;if(r===null)return null;const a=r.edge,i=t-n-this.edgeStalled,l=a-r.totalduration,o=a-(this.config.lowLatencyMode&&r.partTarget||r.targetduration);return Math.min(Math.max(l,i),o)}get drift(){const t=this.levelDetails;return t===null?1:t.drift}get edgeStalled(){const t=this.levelDetails;if(t===null)return 0;const n=(this.config.lowLatencyMode&&t.partTarget||t.targetduration)*3;return Math.max(t.age-n,0)}get forwardBufferLength(){const{media:t}=this,n=this.levelDetails;if(!t||!n)return 0;const r=t.buffered.length;return(r?t.buffered.end(r-1):n.edge)-this.currentTime}destroy(){this.unregisterListeners(),this.onMediaDetaching(),this.hls=null}registerListeners(){const{hls:t}=this;t&&(t.on(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.on(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.LEVEL_UPDATED,this.onLevelUpdated,this),t.on(jt.ERROR,this.onError,this))}unregisterListeners(){const{hls:t}=this;t&&(t.off(jt.MEDIA_ATTACHED,this.onMediaAttached,this),t.off(jt.MEDIA_DETACHING,this.onMediaDetaching,this),t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.LEVEL_UPDATED,this.onLevelUpdated,this),t.off(jt.ERROR,this.onError,this))}onMediaAttached(t,n){this.media=n.media,this.media.addEventListener("timeupdate",this.onTimeupdate)}onMediaDetaching(){this.media&&(this.media.removeEventListener("timeupdate",this.onTimeupdate),this.media=null)}onManifestLoading(){this._latency=null,this.stallCount=0}onLevelUpdated(t,{details:n}){n.advanced&&this.onTimeupdate(),!n.live&&this.media&&this.media.removeEventListener("timeupdate",this.onTimeupdate)}onError(t,n){var r;n.details===Mn.BUFFER_STALLED_ERROR&&(this.stallCount++,this.hls&&(r=this.levelDetails)!=null&&r.live&&this.hls.logger.warn("[latency-controller]: Stall detected, adjusting target latency"))}changeMediaPlaybackRate(t,n){var r,a;t.playbackRate!==n&&((r=this.hls)==null||r.logger.debug(`[latency-controller]: latency=${this.latency.toFixed(3)}, targetLatency=${(a=this.targetLatency)==null?void 0:a.toFixed(3)}, forwardBufferLength=${this.forwardBufferLength.toFixed(3)}: adjusting playback rate from ${t.playbackRate} to ${n}`),t.playbackRate=n)}estimateLiveEdge(){const t=this.levelDetails;return t===null?null:t.edge+t.age}computeLatency(){const t=this.estimateLiveEdge();return t===null?null:t-this.currentTime}}class hln extends A8e{constructor(t,n){super(t,"level-controller"),this._levels=[],this._firstLevel=-1,this._maxAutoLevel=-1,this._startLevel=void 0,this.currentLevel=null,this.currentLevelIndex=-1,this.manualLevelIndex=-1,this.steering=void 0,this.onParsedComplete=void 0,this.steering=n,this._registerListeners()}_registerListeners(){const{hls:t}=this;t.on(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.MANIFEST_LOADED,this.onManifestLoaded,this),t.on(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(jt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(jt.FRAG_BUFFERED,this.onFragBuffered,this),t.on(jt.ERROR,this.onError,this)}_unregisterListeners(){const{hls:t}=this;t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.MANIFEST_LOADED,this.onManifestLoaded,this),t.off(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(jt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(jt.FRAG_BUFFERED,this.onFragBuffered,this),t.off(jt.ERROR,this.onError,this)}destroy(){this._unregisterListeners(),this.steering=null,this.resetLevels(),super.destroy()}stopLoad(){this._levels.forEach(n=>{n.loadError=0,n.fragmentError=0}),super.stopLoad()}resetLevels(){this._startLevel=void 0,this.manualLevelIndex=-1,this.currentLevelIndex=-1,this.currentLevel=null,this._levels=[],this._maxAutoLevel=-1}onManifestLoading(t,n){this.resetLevels()}onManifestLoaded(t,n){const r=this.hls.config.preferManagedMediaSource,a=[],i={},l={};let o=!1,c=!1,d=!1;n.levels.forEach(u=>{const h=u.attrs;let{audioCodec:p,videoCodec:f}=u;p&&(u.audioCodec=p=Rge(p,r)||void 0),f&&(f=u.videoCodec=Knn(f));const{width:y,height:_,unknownCodecs:v}=u,j=(v==null?void 0:v.length)||0;if(o||(o=!!(y&&_)),c||(c=!!f),d||(d=!!p),j||p&&!this.isAudioSupported(p)||f&&!this.isVideoSupported(f)){this.log(`Some or all CODECS not supported "${h.CODECS}"`);return}const{CODECS:w,"FRAME-RATE":S,"HDCP-LEVEL":A,"PATHWAY-ID":E,RESOLUTION:O,"VIDEO-RANGE":D}=h,F=`${`${E||"."}-`}${u.bitrate}-${O}-${S}-${w}-${D}-${A}`;if(i[F])if(i[F].uri!==u.url&&!u.attrs["PATHWAY-ID"]){const z=l[F]+=1;u.attrs["PATHWAY-ID"]=new Array(z+1).join(".");const H=this.createLevel(u);i[F]=H,a.push(H)}else i[F].addGroupId("audio",h.AUDIO),i[F].addGroupId("text",h.SUBTITLES);else{const z=this.createLevel(u);i[F]=z,l[F]=1,a.push(z)}}),this.filterAndSortMediaOptions(a,n,o,c,d)}createLevel(t){const n=new p$(t),r=t.supplemental;if(r!=null&&r.videoCodec&&!this.isVideoSupported(r.videoCodec)){const a=new Error(`SUPPLEMENTAL-CODECS not supported "${r.videoCodec}"`);this.log(a.message),n.supportedResult=_Nt(a,[])}return n}isAudioSupported(t){return h$(t,"audio",this.hls.config.preferManagedMediaSource)}isVideoSupported(t){return h$(t,"video",this.hls.config.preferManagedMediaSource)}filterAndSortMediaOptions(t,n,r,a,i){var l;let o=[],c=[],d=t;const u=((l=n.stats)==null?void 0:l.parsing)||{};if((r||a)&&i&&(d=d.filter(({videoCodec:w,videoRange:S,width:A,height:E})=>(!!w||!!(A&&E))&&rrn(S))),d.length===0){Promise.resolve().then(()=>{if(this.hls){let w="no level with compatible codecs found in manifest",S=w;n.levels.length&&(S=`one or more CODECS in variant not supported: ${rd(n.levels.map(E=>E.attrs.CODECS).filter((E,O,D)=>D.indexOf(E)===O))}`,this.warn(S),w+=` (${S})`);const A=new Error(w);this.hls.trigger(jt.ERROR,{type:ui.MEDIA_ERROR,details:Mn.MANIFEST_INCOMPATIBLE_CODECS_ERROR,fatal:!0,url:n.url,error:A,reason:S})}}),u.end=performance.now();return}n.audioTracks&&(o=n.audioTracks.filter(w=>!w.audioCodec||this.isAudioSupported(w.audioCodec)),qJe(o)),n.subtitles&&(c=n.subtitles,qJe(c));const h=d.slice(0);d.sort((w,S)=>{if(w.attrs["HDCP-LEVEL"]!==S.attrs["HDCP-LEVEL"])return(w.attrs["HDCP-LEVEL"]||"")>(S.attrs["HDCP-LEVEL"]||"")?1:-1;if(r&&w.height!==S.height)return w.height-S.height;if(w.frameRate!==S.frameRate)return w.frameRate-S.frameRate;if(w.videoRange!==S.videoRange)return Oge.indexOf(w.videoRange)-Oge.indexOf(S.videoRange);if(w.videoCodec!==S.videoCodec){const A=LXe(w.videoCodec),E=LXe(S.videoCodec);if(A!==E)return E-A}if(w.uri===S.uri&&w.codecSet!==S.codecSet){const A=Dge(w.codecSet),E=Dge(S.codecSet);if(A!==E)return E-A}return w.averageBitrate!==S.averageBitrate?w.averageBitrate-S.averageBitrate:0});let p=h[0];if(this.steering&&(d=this.steering.filterParsedLevels(d),d.length!==h.length)){for(let w=0;wA&&A===this.hls.abrEwmaDefaultEstimate&&(this.hls.bandwidthEstimate=E)}break}const y=i&&!a,_=this.hls.config,v=!!(_.audioStreamController&&_.audioTrackController),j={levels:d,audioTracks:o,subtitleTracks:c,sessionData:n.sessionData,sessionKeys:n.sessionKeys,firstLevel:this._firstLevel,stats:n.stats,audio:i,video:a,altAudio:v&&!y&&o.some(w=>!!w.url)};u.end=performance.now(),this.hls.trigger(jt.MANIFEST_PARSED,j)}get levels(){return this._levels.length===0?null:this._levels}get loadLevelObj(){return this.currentLevel}get level(){return this.currentLevelIndex}set level(t){const n=this._levels;if(n.length===0)return;if(t<0||t>=n.length){const u=new Error("invalid level idx"),h=t<0;if(this.hls.trigger(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.LEVEL_SWITCH_ERROR,level:t,fatal:h,error:u,reason:u.message}),h)return;t=Math.min(t,n.length-1)}const r=this.currentLevelIndex,a=this.currentLevel,i=a?a.attrs["PATHWAY-ID"]:void 0,l=n[t],o=l.attrs["PATHWAY-ID"];if(this.currentLevelIndex=t,this.currentLevel=l,r===t&&a&&i===o)return;this.log(`Switching to level ${t} (${l.height?l.height+"p ":""}${l.videoRange?l.videoRange+" ":""}${l.codecSet?l.codecSet+" ":""}@${l.bitrate})${o?" with Pathway "+o:""} from level ${r}${i?" with Pathway "+i:""}`);const c={level:t,attrs:l.attrs,details:l.details,bitrate:l.bitrate,averageBitrate:l.averageBitrate,maxBitrate:l.maxBitrate,realBitrate:l.realBitrate,width:l.width,height:l.height,codecSet:l.codecSet,audioCodec:l.audioCodec,videoCodec:l.videoCodec,audioGroups:l.audioGroups,subtitleGroups:l.subtitleGroups,loaded:l.loaded,loadError:l.loadError,fragmentError:l.fragmentError,name:l.name,id:l.id,uri:l.uri,url:l.url,urlId:0,audioGroupIds:l.audioGroupIds,textGroupIds:l.textGroupIds};this.hls.trigger(jt.LEVEL_SWITCHING,c);const d=l.details;if(!d||d.live){const u=this.switchParams(l.uri,a==null?void 0:a.details,d);this.loadPlaylist(u)}}get manualLevel(){return this.manualLevelIndex}set manualLevel(t){this.manualLevelIndex=t,this._startLevel===void 0&&(this._startLevel=t),t!==-1&&(this.level=t)}get firstLevel(){return this._firstLevel}set firstLevel(t){this._firstLevel=t}get startLevel(){if(this._startLevel===void 0){const t=this.hls.config.startLevel;return t!==void 0?t:this.hls.firstAutoLevel}return this._startLevel}set startLevel(t){this._startLevel=t}get pathways(){return this.steering?this.steering.pathways():[]}get pathwayPriority(){return this.steering?this.steering.pathwayPriority:null}set pathwayPriority(t){if(this.steering){const n=this.steering.pathways(),r=t.filter(a=>n.indexOf(a)!==-1);if(t.length<1){this.warn(`pathwayPriority ${t} should contain at least one pathway from list: ${n}`);return}this.steering.pathwayPriority=r}}onError(t,n){n.fatal||!n.context||n.context.type===rl.LEVEL&&n.context.level===this.level&&this.checkRetry(n)}onFragBuffered(t,{frag:n}){if(n!==void 0&&n.type===Wa.MAIN){const r=n.elementaryStreams;if(!Object.keys(r).some(i=>!!r[i]))return;const a=this._levels[n.level];a!=null&&a.loadError&&(this.log(`Resetting level error count of ${a.loadError} on frag buffered`),a.loadError=0)}}onLevelLoaded(t,n){var r;const{level:a,details:i}=n,l=n.levelInfo;if(!l){var o;this.warn(`Invalid level index ${a}`),(o=n.deliveryDirectives)!=null&&o.skip&&(i.deltaUpdateFailed=!0);return}if(l===this.currentLevel||n.withoutMultiVariant){l.fragmentError===0&&(l.loadError=0);let c=l.details;c===n.details&&c.advanced&&(c=void 0),this.playlistLoaded(a,n,c)}else(r=n.deliveryDirectives)!=null&&r.skip&&(i.deltaUpdateFailed=!0)}loadPlaylist(t){super.loadPlaylist(),this.shouldLoadPlaylist(this.currentLevel)&&this.scheduleLoading(this.currentLevel,t)}loadingPlaylist(t,n){super.loadingPlaylist(t,n);const r=this.getUrlWithDirectives(t.uri,n),a=this.currentLevelIndex,i=t.attrs["PATHWAY-ID"],l=t.details,o=l==null?void 0:l.age;this.log(`Loading level index ${a}${(n==null?void 0:n.msn)!==void 0?" at sn "+n.msn+" part "+n.part:""}${i?" Pathway "+i:""}${o&&l.live?" age "+o.toFixed(1)+(l.type&&" "+l.type||""):""} ${r}`),this.hls.trigger(jt.LEVEL_LOADING,{url:r,level:a,levelInfo:t,pathwayId:t.attrs["PATHWAY-ID"],id:0,deliveryDirectives:n||null})}get nextLoadLevel(){return this.manualLevelIndex!==-1?this.manualLevelIndex:this.hls.nextAutoLevel}set nextLoadLevel(t){this.level=t,this.manualLevelIndex===-1&&(this.hls.nextAutoLevel=t)}removeLevel(t){var n;if(this._levels.length===1)return;const r=this._levels.filter((i,l)=>l!==t?!0:(this.steering&&this.steering.removeLevel(i),i===this.currentLevel&&(this.currentLevel=null,this.currentLevelIndex=-1,i.details&&i.details.fragments.forEach(o=>o.level=-1)),!1));UNt(r),this._levels=r,this.currentLevelIndex>-1&&(n=this.currentLevel)!=null&&n.details&&(this.currentLevelIndex=this.currentLevel.details.fragments[0].level),this.manualLevelIndex>-1&&(this.manualLevelIndex=this.currentLevelIndex);const a=r.length-1;this._firstLevel=Math.min(this._firstLevel,a),this._startLevel&&(this._startLevel=Math.min(this._startLevel,a)),this.hls.trigger(jt.LEVELS_UPDATED,{levels:r})}onLevelsUpdated(t,{levels:n}){this._levels=n}checkMaxAutoUpdated(){const{autoLevelCapping:t,maxAutoLevel:n,maxHdcpLevel:r}=this.hls;this._maxAutoLevel!==n&&(this._maxAutoLevel=n,this.hls.trigger(jt.MAX_AUTO_LEVEL_UPDATED,{autoLevelCapping:t,levels:this.levels,maxAutoLevel:n,minAutoLevel:this.hls.minAutoLevel,maxHdcpLevel:r}))}}function qJe(s){const t={};s.forEach(n=>{const r=n.groupId||"";n.id=t[r]=t[r]||0,t[r]++})}function Okt(){return self.SourceBuffer||self.WebKitSourceBuffer}function Fkt(){if(!I4())return!1;const t=Okt();return!t||t.prototype&&typeof t.prototype.appendBuffer=="function"&&typeof t.prototype.remove=="function"}function mln(){if(!Fkt())return!1;const s=I4();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(m$(t,"video")))||["mp4a.40.2","fLaC"].some(t=>s.isTypeSupported(m$(t,"audio"))))}function pln(){var s;const t=Okt();return typeof(t==null||(s=t.prototype)==null?void 0:s.changeType)=="function"}const fln=100;class xln extends w8e{constructor(t,n,r){super(t,n,r,"stream-controller",Wa.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||!Pa(i)||(this.log(`Media seeked to ${i.toFixed(3)}`),!this.getBufferedFrag(i)))return;const l=this.getFwdBufferInfoAtPos(a,i,Wa.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(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.on(jt.LEVEL_LOADING,this.onLevelLoading,this),t.on(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.on(jt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.on(jt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.on(jt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.on(jt.BUFFER_CREATED,this.onBufferCreated,this),t.on(jt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.on(jt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.on(jt.FRAG_BUFFERED,this.onFragBuffered,this)}unregisterListeners(){super.unregisterListeners();const{hls:t}=this;t.off(jt.MANIFEST_PARSED,this.onManifestParsed,this),t.off(jt.LEVEL_LOADED,this.onLevelLoaded,this),t.off(jt.FRAG_LOAD_EMERGENCY_ABORTED,this.onFragLoadEmergencyAborted,this),t.off(jt.AUDIO_TRACK_SWITCHING,this.onAudioTrackSwitching,this),t.off(jt.AUDIO_TRACK_SWITCHED,this.onAudioTrackSwitched,this),t.off(jt.BUFFER_CREATED,this.onBufferCreated,this),t.off(jt.BUFFER_FLUSHED,this.onBufferFlushed,this),t.off(jt.LEVELS_UPDATED,this.onLevelsUpdated,this),t.off(jt.FRAG_BUFFERED,this.onFragBuffered,this)}onHandlerDestroying(){this.onMediaPlaying=this.onMediaSeeked=null,this.unregisterListeners(),super.onHandlerDestroying()}startLoad(t,n){if(this.levels){const{lastCurrentTime:r,hls:a}=this;if(this.stopLoad(),this.setInterval(fln),this.level=-1,!this.startFragRequested){let i=a.startLevel;i===-1&&(a.config.testBandwidth&&this.levels.length>1?(i=0,this.bitrateTest=!0):i=a.firstAutoLevel),a.nextLoadLevel=i,this.level=a.loadLevel,this._hasEnoughToStart=!!n}r>0&&t===-1&&!n&&(this.log(`Override startPosition with lastCurrentTime @${r.toFixed(3)}`),t=r),this.state=cr.IDLE,this.nextLoadPosition=this.lastCurrentTime=t+this.timelineOffset,this.startPosition=n?-1:t,this.tick()}else this._forceStartLoad=!0,this.state=cr.STOPPED}stopLoad(){this._forceStartLoad=!1,super.stopLoad()}doTick(){switch(this.state){case cr.WAITING_LEVEL:{const{levels:t,level:n}=this,r=t==null?void 0:t[n],a=r==null?void 0:r.details;if(a&&(!a.live||this.levelLastLoaded===r&&!this.waitForLive(r))){if(this.waitForCdnTuneIn(a))break;this.state=cr.IDLE;break}else if(this.hls.nextLoadLevel!==this.level){this.state=cr.IDLE;break}break}case cr.FRAG_LOADING_WAITING_RETRY:this.checkRetryDate();break}this.state===cr.IDLE&&this.doTickIdle(),this.onTickEnd()}onTickEnd(){var t;super.onTickEnd(),(t=this.media)!=null&&t.readyState&&this.media.seeking===!1&&(this.lastCurrentTime=this.media.currentTime),this.checkFragmentChanged()}doTickIdle(){const{hls:t,levelLastLoaded:n,levels:r,media:a}=this;if(n===null||!a&&!this.primaryPrefetch&&(this.startFragRequested||!t.config.startFragPrefetch)||this.altAudio&&this.audioOnly)return;const i=this.buffering?t.nextLoadLevel:t.loadLevel;if(!(r!=null&&r[i]))return;const l=r[i],o=this.getMainFwdBufferInfo();if(o===null)return;const c=this.getLevelDetails();if(c&&this._streamEnded(o,c)){const _={};this.altAudio===2&&(_.type="video"),this.hls.trigger(jt.BUFFER_EOS,_),this.state=cr.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===cr.WAITING_LEVEL||this.waitForLive(l)){this.level=i,this.state=cr.WAITING_LEVEL,this.startFragRequested=!1;return}const u=o.len,h=this.getMaxBufferLength(l.maxBitrate);if(u>=h)return;this.backtrackFragment&&this.backtrackFragment.start>o.end&&(this.backtrackFragment=null);const p=this.backtrackFragment?this.backtrackFragment.start:o.end;let f=this.getNextFragment(p,d);if(this.couldBacktrack&&!this.fragPrevious&&f&&Nh(f)&&this.fragmentTracker.getState(f)!==Mm.OK){var y;const v=((y=this.backtrackFragment)!=null?y:f).sn-d.startSN,j=d.fragments[v-1];j&&f.cc===j.cc&&(f=j,this.fragmentTracker.removeFragment(j))}else this.backtrackFragment&&o.len&&(this.backtrackFragment=null);if(f&&this.isLoopLoading(f,p)){if(!f.gap){const v=this.audioOnly&&!this.altAudio?Jc.AUDIO:Jc.VIDEO,j=(v===Jc.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;j&&this.afterBufferFlushed(j,v,Wa.MAIN)}f=this.getNextFragmentLoopLoading(f,d,o,Wa.MAIN,h)}f&&(this.exceedsMaxBuffer(o,h,f)||(f.initSegment&&!f.initSegment.data&&!this.bitrateTest&&(f=f.initSegment),this.loadFragment(f,l,p)))}loadFragment(t,n,r){const a=this.fragmentTracker.getState(t);a===Mm.NOT_LOADED||a===Mm.PARTIAL?Nh(t)?this.bitrateTest?(this.log(`Fragment ${t.sn} of level ${t.level} is being downloaded to test bitrate and will not be buffered`),this._loadBitrateTestFrag(t,n)):super.loadFragment(t,n,r):this._loadInitSegment(t,n):this.clearTrackerIfNeeded(t)}getBufferedFrag(t){return this.fragmentTracker.getBufferedFrag(t,Wa.MAIN)}followingBufferedFrag(t){return t?this.getBufferedFrag(t.end+.5):null}immediateLevelSwitch(){if(this.abortCurrentFrag(),this.flushMainBuffer(0,Number.POSITIVE_INFINITY),this.altAudio!==0){var t;(((t=this.getLevelDetails())==null?void 0:t.fragmentStart)||0)>this.lastCurrentTime&&super.flushMainBuffer(0,Number.POSITIVE_INFINITY,"audio")}}nextLevelSwitch(){const{levels:t,media:n}=this;if(n!=null&&n.readyState){let r;const a=this.getAppendedFrag(n.currentTime);a&&a.start>1&&this.flushMainBuffer(0,a.start-1);const i=this.getLevelDetails();if(i!=null&&i.live){const o=this.getMainFwdBufferInfo();if(!o||o.len=l-n.maxFragLookUpTolerance&&i<=o;if(a!==null&&r.duration>a&&(i{this.hls&&this.hls.trigger(jt.AUDIO_TRACK_SWITCHED,n)}),r.trigger(jt.BUFFER_FLUSHING,{startOffset:0,endOffset:Number.POSITIVE_INFINITY,type:null});return}r.trigger(jt.AUDIO_TRACK_SWITCHED,n)}}onAudioTrackSwitched(t,n){const r=Fge(n.url,this.hls);if(r){const a=this.videoBuffer;a&&this.mediaBuffer!==a&&(this.log("Switching on alternate audio, use video.buffered to schedule main fragment loading"),this.mediaBuffer=a)}this.altAudio=r?2:0,this.tick()}onBufferCreated(t,n){const r=n.tracks;let a,i,l=!1;for(const o in r){const c=r[o];if(c.id==="main"){if(i=o,a=c,o==="video"){const d=r[o];d&&(this.videoBuffer=d.buffer)}}else l=!0}l&&a?(this.log(`Alternate track found, use ${i}.buffered to schedule main fragment loading`),this.mediaBuffer=a.buffer):this.mediaBuffer=this.media}onFragBuffered(t,n){const{frag:r,part:a}=n,i=r.type===Wa.MAIN;if(i){if(this.fragContextChanged(r)){this.warn(`Fragment ${r.sn}${a?" p: "+a.index:""} of level ${r.level} finished buffering, but was aborted. state: ${this.state}`),this.state===cr.PARSED&&(this.state=cr.IDLE);return}const o=a?a.stats:r.stats;this.fragLastKbps=Math.round(8*o.total/(o.buffering.end-o.loading.first)),Nh(r)&&(this.fragPrevious=r),this.fragBufferedComplete(r,a)}const l=this.media;l&&(!this._hasEnoughToStart&&bo.getBuffered(l).length&&(this._hasEnoughToStart=!0,this.seekToStartPos()),i&&this.tick())}get hasEnoughToStart(){return this._hasEnoughToStart}onError(t,n){var r;if(n.fatal){this.state=cr.ERROR;return}switch(n.details){case Mn.FRAG_GAP:case Mn.FRAG_PARSING_ERROR:case Mn.FRAG_DECRYPT_ERROR:case Mn.FRAG_LOAD_ERROR:case Mn.FRAG_LOAD_TIMEOUT:case Mn.KEY_LOAD_ERROR:case Mn.KEY_LOAD_TIMEOUT:this.onFragmentOrKeyLoadError(Wa.MAIN,n);break;case Mn.LEVEL_LOAD_ERROR:case Mn.LEVEL_LOAD_TIMEOUT:case Mn.LEVEL_PARSING_ERROR:!n.levelRetry&&this.state===cr.WAITING_LEVEL&&((r=n.context)==null?void 0:r.type)===rl.LEVEL&&(this.state=cr.IDLE);break;case Mn.BUFFER_ADD_CODEC_ERROR:case Mn.BUFFER_APPEND_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&this.resetLoadingState();break;case Mn.BUFFER_FULL_ERROR:if(n.parent!=="main")return;this.reduceLengthAndFlushBuffer(n)&&(!this.config.interstitialsController&&this.config.assetPlayerId?this._hasEnoughToStart=!0:this.flushMainBuffer(0,Number.POSITIVE_INFINITY));break;case Mn.INTERNAL_EXCEPTION:this.recoverWorkerError(n);break}}onFragLoadEmergencyAborted(){this.state=cr.IDLE,this._hasEnoughToStart||(this.startFragRequested=!1,this.nextLoadPosition=this.lastCurrentTime),this.tickImmediate()}onBufferFlushed(t,{type:n}){if(n!==Jc.AUDIO||!this.altAudio){const r=(n===Jc.VIDEO?this.videoBuffer:this.mediaBuffer)||this.media;r&&(this.afterBufferFlushed(r,n,Wa.MAIN),this.tick())}}onLevelsUpdated(t,n){this.level>-1&&this.fragCurrent&&(this.level=this.fragCurrent.level,this.level===-1&&this.resetWhenMissingContext(this.fragCurrent)),this.levels=n.levels}swapAudioCodec(){this.audioCodecSwap=!this.audioCodecSwap}seekToStartPos(){const{media:t}=this;if(!t)return;const n=t.currentTime;let r=this.startPosition;if(r>=0&&n0&&(c{const{hls:a}=this,i=r==null?void 0:r.frag;if(!i||this.fragContextChanged(i))return;n.fragmentError=0,this.state=cr.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(jt.FRAG_LOADED,r),i.bitrateTest=!1}).catch(r=>{this.state===cr.STOPPED||this.state===cr.ERROR||(this.warn(r),this.resetFragmentLoading(t))})}_handleTransmuxComplete(t){const n=this.playlistType,{hls:r}=this,{remuxResult:a,chunkMeta:i}=t,l=this.getCurrentContext(i);if(!l){this.resetWhenMissingContext(i);return}const{frag:o,part:c,level:d}=l,{video:u,text:h,id3:p,initSegment:f}=a,{details:y}=d,_=this.altAudio?void 0:a.audio;if(this.fragContextChanged(o)){this.fragmentTracker.removeFragment(o);return}if(this.state=cr.PARSING,f){const v=f.tracks;if(v){const A=o.initSegment||o;if(this.unhandledEncryptionError(f,o))return;this._bufferInitSegment(d,v,A,i),r.trigger(jt.FRAG_PARSING_INIT_SEGMENT,{frag:A,id:n,tracks:v})}const j=f.initPTS,w=f.timescale,S=this.initPTS[o.cc];if(Pa(j)&&(!S||S.baseTime!==j||S.timescale!==w)){const A=f.trackId;this.initPTS[o.cc]={baseTime:j,timescale:w,trackId:A},r.trigger(jt.INIT_PTS_FOUND,{frag:o,id:n,initPTS:j,timescale:w,trackId:A})}}if(u&&y){_&&u.type==="audiovideo"&&this.logMuxedErr(o);const v=y.fragments[o.sn-1-y.startSN],j=o.sn===y.startSN,w=!v||o.cc>v.cc;if(a.independent!==!1){const{startPTS:S,endPTS:A,startDTS:E,endDTS:O}=u;if(c)c.elementaryStreams[u.type]={startPTS:S,endPTS:A,startDTS:E,endDTS:O};else if(u.firstKeyFrame&&u.independent&&i.id===1&&!w&&(this.couldBacktrack=!0),u.dropped&&u.independent){const D=this.getMainFwdBufferInfo(),I=(D?D.end:this.getLoadPosition())+this.config.maxBufferHole,F=u.firstKeyFramePTS?u.firstKeyFramePTS:S;if(!j&&Ispe&&(o.gap=!0);o.setElementaryStreamInfo(u.type,S,A,E,O),this.backtrackFragment&&(this.backtrackFragment=o),this.bufferFragmentData(u,o,c,i,j||w)}else if(j||w)o.gap=!0;else{this.backtrack(o);return}}if(_){const{startPTS:v,endPTS:j,startDTS:w,endDTS:S}=_;c&&(c.elementaryStreams[Jc.AUDIO]={startPTS:v,endPTS:j,startDTS:w,endDTS:S}),o.setElementaryStreamInfo(Jc.AUDIO,v,j,w,S),this.bufferFragmentData(_,o,c,i)}if(y&&p!=null&&p.samples.length){const v={id:n,frag:o,details:y,samples:p.samples};r.trigger(jt.FRAG_PARSING_METADATA,v)}if(y&&h){const v={id:n,frag:o,details:y,samples:h.samples};r.trigger(jt.FRAG_PARSING_USERDATA,v)}}logMuxedErr(t){this.warn(`${Nh(t)?"Media":"Init"} segment with muxed audiovideo where only video expected: ${t.url}`)}_bufferInitSegment(t,n,r,a){if(this.state!==cr.PARSING)return;this.audioOnly=!!n.audio&&!n.video,this.altAudio&&!this.audioOnly&&(delete n.audio,n.audiovideo&&this.logMuxedErr(r));const{audio:i,video:l,audiovideo:o}=n;if(i){const d=t.audioCodec;let u=Yme(i.codec,d);u==="mp4a"&&(u="mp4a.40.5");const h=navigator.userAgent.toLowerCase();if(this.audioCodecSwitch){u&&(u.indexOf("mp4a.40.5")!==-1?u="mp4a.40.2":u="mp4a.40.5");const p=i.metadata;p&&"channelCount"in p&&(p.channelCount||1)!==1&&h.indexOf("firefox")===-1&&(u="mp4a.40.5")}u&&u.indexOf("mp4a.40.5")!==-1&&h.indexOf("android")!==-1&&i.container!=="audio/mpeg"&&(u="mp4a.40.2",this.log(`Android: force audio codec to ${u}`)),d&&d!==u&&this.log(`Swapping manifest audio codec "${d}" for "${u}"`),i.levelCodec=u,i.id=Wa.MAIN,this.log(`Init audio buffer, container:${i.container}, codecs[selected/level/parsed]=[${u||""}/${d||""}/${i.codec}]`),delete n.audiovideo}if(l){l.levelCodec=t.videoCodec,l.id=Wa.MAIN;const d=l.codec;if((d==null?void 0:d.length)===4)switch(d){case"hvc1":case"hev1":l.codec="hvc1.1.6.L120.90";break;case"av01":l.codec="av01.0.04M.08";break;case"avc1":l.codec="avc1.42e01e";break}this.log(`Init video buffer, container:${l.container}, codecs[level/parsed]=[${t.videoCodec||""}/${d}]${l.codec!==d?" parsed-corrected="+l.codec:""}${l.supplemental?" supplemental="+l.supplemental:""}`),delete n.audiovideo}o&&(this.log(`Init audiovideo buffer, container:${o.container}, codecs[level/parsed]=[${t.codecs}/${o.codec}]`),delete n.video,delete n.audio);const c=Object.keys(n);if(c.length){if(this.hls.trigger(jt.BUFFER_CODECS,n),!this.hls)return;c.forEach(d=>{const h=n[d].initSegment;h!=null&&h.byteLength&&this.hls.trigger(jt.BUFFER_APPENDING,{type:d,data:h,frag:r,part:null,chunkMeta:a,parent:r.type})})}this.tickImmediate()}getMainFwdBufferInfo(){const t=this.mediaBuffer&&this.altAudio===2?this.mediaBuffer:this.media;return this.getFwdBufferInfo(t,Wa.MAIN)}get maxBufferLength(){const{levels:t,level:n}=this,r=t==null?void 0:t[n];return r?this.getMaxBufferLength(r.maxBitrate):this.config.maxBufferLength}backtrack(t){this.couldBacktrack=!0,this.backtrackFragment=t,this.resetTransmuxer(),this.flushBufferGap(t),this.fragmentTracker.removeFragment(t),this.fragPrevious=null,this.nextLoadPosition=t.start,this.state=cr.IDLE}checkFragmentChanged(){const t=this.media;let n=null;if(t&&t.readyState>1&&t.seeking===!1){const r=t.currentTime;if(bo.isBuffered(t,r)?n=this.getAppendedFrag(r):bo.isBuffered(t,r+.1)&&(n=this.getAppendedFrag(r+.1)),n){this.backtrackFragment=null;const a=this.fragPlaying,i=n.level;(!a||n.sn!==a.sn||a.level!==i)&&(this.fragPlaying=n,this.hls.trigger(jt.FRAG_CHANGED,{frag:n}),(!a||a.level!==i)&&this.hls.trigger(jt.LEVEL_SWITCHED,{level:i}))}}}get nextLevel(){const t=this.nextBufferedFrag;return t?t.level:-1}get currentFrag(){var t;if(this.fragPlaying)return this.fragPlaying;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;return Pa(n)?this.getAppendedFrag(n):null}get currentProgramDateTime(){var t;const n=((t=this.media)==null?void 0:t.currentTime)||this.lastCurrentTime;if(Pa(n)){const r=this.getLevelDetails(),a=this.currentFrag||(r?LM(null,r.fragments,n):null);if(a){const i=a.programDateTime;if(i!==null){const l=i+(n-a.start)*1e3;return new Date(l)}}}return null}get currentLevel(){const t=this.currentFrag;return t?t.level:-1}get nextBufferedFrag(){const t=this.currentFrag;return t?this.followingBufferedFrag(t):null}get forceStartLoad(){return this._forceStartLoad}}class gln extends t1{constructor(t,n){super("key-loader",n),this.config=void 0,this.keyIdToKeyInfo={},this.emeController=null,this.config=t}abort(t){for(const r in this.keyIdToKeyInfo){const a=this.keyIdToKeyInfo[r].loader;if(a){var n;if(t&&t!==((n=a.context)==null?void 0:n.frag.type))return;a.abort()}}}detach(){for(const t in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[t];(n.mediaKeySessionContext||n.decryptdata.isCommonEncryption)&&delete this.keyIdToKeyInfo[t]}}destroy(){this.detach();for(const t in this.keyIdToKeyInfo){const n=this.keyIdToKeyInfo[t].loader;n&&n.destroy()}this.keyIdToKeyInfo={}}createKeyLoadError(t,n=Mn.KEY_LOAD_ERROR,r,a,i){return new _2({type:ui.NETWORK_ERROR,details:n,fatal:!1,frag:t,response:i,error:r,networkDetails:a})}loadClear(t,n,r){if(this.emeController&&this.config.emeEnabled&&!this.emeController.getSelectedKeySystemFormats().length){if(n.length)for(let a=0,i=n.length;a{if(!this.emeController)return;l.setKeyFormat(o);const c=Qme(o);if(c)return this.emeController.getKeySystemAccess([c])})}if(this.config.requireKeySystemAccessOnStart){const a=v7(this.config);if(a.length)return this.emeController.getKeySystemAccess(a)}}return null}load(t){return!t.decryptdata&&t.encrypted&&this.emeController&&this.config.emeEnabled?this.emeController.selectKeySystemFormat(t).then(n=>this.loadInternal(t,n)):this.loadInternal(t)}loadInternal(t,n){var r,a;n&&t.setKeyFormat(n);const i=t.decryptdata;if(!i){const d=new Error(n?`Expected frag.decryptdata to be defined after setting format ${n}`:`Missing decryption data on fragment in onKeyLoading (emeEnabled with controller: ${this.emeController&&this.config.emeEnabled})`);return Promise.reject(this.createKeyLoadError(t,Mn.KEY_LOAD_ERROR,d))}const l=i.uri;if(!l)return Promise.reject(this.createKeyLoadError(t,Mn.KEY_LOAD_ERROR,new Error(`Invalid key URI: "${l}"`)));const o=tke(i);let c=this.keyIdToKeyInfo[o];if((r=c)!=null&&r.decryptdata.key)return i.key=c.decryptdata.key,Promise.resolve({frag:t,keyInfo:c});if(this.emeController&&(a=c)!=null&&a.keyLoadPromise)switch(this.emeController.getKeyStatus(c.decryptdata)){case"usable":case"usable-in-future":return c.keyLoadPromise.then(u=>{const{keyInfo:h}=u;return i.key=h.decryptdata.key,{frag:t,keyInfo:h}})}switch(this.log(`${this.keyIdToKeyInfo[o]?"Rel":"L"}oading${i.keyId?" keyId: "+tf(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,Mn.KEY_LOAD_ERROR,new Error(`Key supplied with unsupported METHOD: "${i.method}"`)))}}loadKeyEME(t,n){const r={frag:n,keyInfo:t};if(this.emeController&&this.config.emeEnabled){var a;if(!t.decryptdata.keyId&&(a=n.initSegment)!=null&&a.data){const l=Rnn(n.initSegment.data);if(l.length){let o=l[0];o.some(c=>c!==0)?(this.log(`Using keyId found in init segment ${tf(o)}`),x4.setKeyIdForUri(t.decryptdata.uri,o)):(o=x4.addKeyIdForUri(t.decryptdata.uri),this.log(`Generating keyId to patch media ${tf(o)}`)),t.decryptdata.keyId=o}}if(!t.decryptdata.keyId&&!Nh(n))return Promise.resolve(r);const i=this.emeController.loadKey(r);return(t.keyLoadPromise=i.then(l=>(t.mediaKeySessionContext=l,r))).catch(l=>{throw t.keyLoadPromise=null,"data"in l&&(l.data.frag=n),l})}return Promise.resolve(r)}loadKeyHTTP(t,n){const r=this.config,a=r.loader,i=new a(r);return n.keyLoader=t.loader=i,t.keyLoadPromise=new Promise((l,o)=>{const c={keyInfo:t,frag:n,responseType:"arraybuffer",url:t.decryptdata.uri},d=r.keyLoadPolicy.default,u={loadPolicy:d,timeout:d.maxLoadTimeMs,maxRetry:0,retryDelay:0,maxRetryDelay:0},h={onSuccess:(p,f,y,_)=>{const{frag:v,keyInfo:j}=y,w=tke(j.decryptdata);if(!v.decryptdata||j!==this.keyIdToKeyInfo[w])return o(this.createKeyLoadError(v,Mn.KEY_LOAD_ERROR,new Error("after key load, decryptdata unset or changed"),_));j.decryptdata.key=v.decryptdata.key=new Uint8Array(p.data),v.keyLoader=null,j.loader=null,l({frag:v,keyInfo:j})},onError:(p,f,y,_)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Mn.KEY_LOAD_ERROR,new Error(`HTTP Error ${p.code} loading key ${p.text}`),y,wc({url:c.url,data:void 0},p)))},onTimeout:(p,f,y)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Mn.KEY_LOAD_TIMEOUT,new Error("key loading timed out"),y))},onAbort:(p,f,y)=>{this.resetLoader(f),o(this.createKeyLoadError(n,Mn.INTERNAL_ABORTED,new Error("key loading aborted"),y))}};i.load(c,u,h)})}resetLoader(t){const{frag:n,keyInfo:r,url:a}=t,i=r.loader;n.keyLoader===i&&(n.keyLoader=null,r.loader=null);const l=tke(r.decryptdata)||a;delete this.keyIdToKeyInfo[l],i&&i.destroy()}}function tke(s){if(s.keyFormat!==rf.FAIRPLAY){const t=s.keyId;if(t)return tf(t)}return s.uri}function VJe(s){const{type:t}=s;switch(t){case rl.AUDIO_TRACK:return Wa.AUDIO;case rl.SUBTITLE_TRACK:return Wa.SUBTITLE;default:return Wa.MAIN}}function ske(s,t){let n=s.url;return(n===void 0||n.indexOf("data:")===0)&&(n=t.url),n}class yln{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(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.on(jt.LEVEL_LOADING,this.onLevelLoading,this),t.on(jt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.on(jt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.on(jt.LEVELS_UPDATED,this.onLevelsUpdated,this)}unregisterListeners(){const{hls:t}=this;t.off(jt.MANIFEST_LOADING,this.onManifestLoading,this),t.off(jt.LEVEL_LOADING,this.onLevelLoading,this),t.off(jt.AUDIO_TRACK_LOADING,this.onAudioTrackLoading,this),t.off(jt.SUBTITLE_TRACK_LOADING,this.onSubtitleTrackLoading,this),t.off(jt.LEVELS_UPDATED,this.onLevelsUpdated,this)}createInternalLoader(t){const n=this.hls.config,r=n.pLoader,a=n.loader,i=r||a,l=new i(n);return this.loaders[t.type]=l,l}getInternalLoader(t){return this.loaders[t.type]}resetInternalLoader(t){this.loaders[t]&&delete this.loaders[t]}destroyInternalLoaders(){for(const t in this.loaders){const n=this.loaders[t];n&&n.destroy(),this.resetInternalLoader(t)}}destroy(){this.variableList=null,this.unregisterListeners(),this.destroyInternalLoaders()}onManifestLoading(t,n){const{url:r}=n;this.variableList=null,this.load({id:null,level:0,responseType:"text",type:rl.MANIFEST,url:r,deliveryDirectives:null,levelOrTrack:null})}onLevelLoading(t,n){const{id:r,level:a,pathwayId:i,url:l,deliveryDirectives:o,levelInfo:c}=n;this.load({id:r,level:a,pathwayId:i,responseType:"text",type:rl.LEVEL,url:l,deliveryDirectives:o,levelOrTrack:c})}onAudioTrackLoading(t,n){const{id:r,groupId:a,url:i,deliveryDirectives:l,track:o}=n;this.load({id:r,groupId:a,level:null,responseType:"text",type:rl.AUDIO_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onSubtitleTrackLoading(t,n){const{id:r,groupId:a,url:i,deliveryDirectives:l,track:o}=n;this.load({id:r,groupId:a,level:null,responseType:"text",type:rl.SUBTITLE_TRACK,url:i,deliveryDirectives:l,levelOrTrack:o})}onLevelsUpdated(t,n){const r=this.loaders[rl.LEVEL];if(r){const a=r.context;a&&!n.levels.some(i=>i===a.levelOrTrack)&&(r.abort(),delete this.loaders[rl.LEVEL])}}load(t){var n;const r=this.hls.config;let a=this.getInternalLoader(t);if(a){const d=this.hls.logger,u=a.context;if(u&&u.levelOrTrack===t.levelOrTrack&&(u.url===t.url||u.deliveryDirectives&&!t.deliveryDirectives)){u.url===t.url?d.log(`[playlist-loader]: ignore ${t.url} ongoing request`):d.log(`[playlist-loader]: ignore ${t.url} in favor of ${u.url}`);return}d.log(`[playlist-loader]: aborting previous loader for type: ${t.type}`),a.abort()}let i;if(t.type===rl.MANIFEST?i=r.manifestLoadPolicy.default:i=Wc({},r.playlistLoadPolicy.default,{timeoutRetry:null,errorRetry:null}),a=this.createInternalLoader(t),Pa((n=t.deliveryDirectives)==null?void 0:n.part)){let d;if(t.type===rl.LEVEL&&t.level!==null?d=this.hls.levels[t.level].details:t.type===rl.AUDIO_TRACK&&t.id!==null?d=this.hls.audioTracks[t.id].details:t.type===rl.SUBTITLE_TRACK&&t.id!==null&&(d=this.hls.subtitleTracks[t.id].details),d){const u=d.partTarget,h=d.targetduration;if(u&&h){const p=Math.max(u*3,h*.8)*1e3;i=Wc({},i,{maxTimeToFirstByteMs:Math.min(p,i.maxTimeToFirstByteMs),maxLoadTimeMs:Math.min(p,i.maxTimeToFirstByteMs)})}}}const l=i.errorRetry||i.timeoutRetry||{},o={loadPolicy:i,timeout:i.maxLoadTimeMs,maxRetry:l.maxNumRetry||0,retryDelay:l.retryDelayMs||0,maxRetryDelay:l.maxRetryDelayMs||0},c={onSuccess:(d,u,h,p)=>{const f=this.getInternalLoader(h);this.resetInternalLoader(h.type);const y=d.data;u.parsing.start=performance.now(),aw.isMediaPlaylist(y)||h.type!==rl.MANIFEST?this.handleTrackOrLevelPlaylist(d,u,h,p||null,f):this.handleMasterPlaylist(d,u,h,p)},onError:(d,u,h,p)=>{this.handleNetworkError(u,h,!1,d,p)},onTimeout:(d,u,h)=>{this.handleNetworkError(u,h,!0,void 0,d)}};a.load(t,o,c)}checkAutostartLoad(){if(!this.hls)return;const{config:{autoStartLoad:t,startPosition:n},forceStartLoad:r}=this.hls;(t||r)&&(this.hls.logger.log(`${t?"auto":"force"} startLoad with configured startPosition ${n}`),this.hls.startLoad(n))}handleMasterPlaylist(t,n,r,a){const i=this.hls,l=t.data,o=ske(t,r),c=aw.parseMasterPlaylist(l,o);if(c.playlistParsingError){n.parsing.end=performance.now(),this.handleManifestParsingError(t,r,c.playlistParsingError,a,n);return}const{contentSteering:d,levels:u,sessionData:h,sessionKeys:p,startTimeOffset:f,variableList:y}=c;this.variableList=y,u.forEach(w=>{const{unknownCodecs:S}=w;if(S){const{preferManagedMediaSource:A}=this.hls.config;let{audioCodec:E,videoCodec:O}=w;for(let D=S.length;D--;){const I=S[D];h$(I,"audio",A)?(w.audioCodec=E=E?`${E},${I}`:I,mD.audio[E.substring(0,4)]=2,S.splice(D,1)):h$(I,"video",A)&&(w.videoCodec=O=O?`${O},${I}`:I,mD.video[O.substring(0,4)]=2,S.splice(D,1))}}});const{AUDIO:_=[],SUBTITLES:v,"CLOSED-CAPTIONS":j}=aw.parseMasterPlaylistMedia(l,o,c);_.length&&!_.some(S=>!S.url)&&u[0].audioCodec&&!u[0].attrs.AUDIO&&(this.hls.logger.log("[playlist-loader]: audio codec signaled in quality level, but no embedded audio track signaled, create one"),_.unshift({type:"main",name:"main",groupId:"main",default:!1,autoselect:!1,forced:!1,id:-1,attrs:new bu({}),bitrate:0,url:""})),i.trigger(jt.MANIFEST_LOADED,{levels:u,audioTracks:_,subtitles:v,captions:j,contentSteering:d,url:o,stats:n,networkDetails:a,sessionData:h,sessionKeys:p,startTimeOffset:f,variableList:y})}handleTrackOrLevelPlaylist(t,n,r,a,i){const l=this.hls,{id:o,level:c,type:d}=r,u=ske(t,r),h=Pa(c)?c:Pa(o)?o:0,p=VJe(r),f=aw.parseLevelPlaylist(t.data,u,h,p,0,this.variableList);if(d===rl.MANIFEST){const y={attrs:new bu({}),bitrate:0,details:f,name:"",url:u};f.requestScheduled=n.loading.start+zNt(f,0),l.trigger(jt.MANIFEST_LOADED,{levels:[y],audioTracks:[],url:u,stats:n,networkDetails:a,sessionData:null,sessionKeys:null,contentSteering:null,startTimeOffset:null,variableList:null})}n.parsing.end=performance.now(),r.levelDetails=f,this.handlePlaylistLoaded(f,t,n,r,a,i)}handleManifestParsingError(t,n,r,a,i){this.hls.trigger(jt.ERROR,{type:ui.NETWORK_ERROR,details:Mn.MANIFEST_PARSING_ERROR,fatal:n.type===rl.MANIFEST,url:t.url,err:r,error:r,reason:r.message,response:t,context:n,networkDetails:a,stats:i})}handleNetworkError(t,n,r=!1,a,i){let l=`A network ${r?"timeout":"error"+(a?" (status "+a.code+")":"")} occurred while loading ${t.type}`;t.type===rl.LEVEL?l+=`: ${t.level} id: ${t.id}`:(t.type===rl.AUDIO_TRACK||t.type===rl.SUBTITLE_TRACK)&&(l+=` id: ${t.id} group-id: "${t.groupId}"`);const o=new Error(l);this.hls.logger.warn(`[playlist-loader]: ${l}`);let c=Mn.UNKNOWN,d=!1;const u=this.getInternalLoader(t);switch(t.type){case rl.MANIFEST:c=r?Mn.MANIFEST_LOAD_TIMEOUT:Mn.MANIFEST_LOAD_ERROR,d=!0;break;case rl.LEVEL:c=r?Mn.LEVEL_LOAD_TIMEOUT:Mn.LEVEL_LOAD_ERROR,d=!1;break;case rl.AUDIO_TRACK:c=r?Mn.AUDIO_TRACK_LOAD_TIMEOUT:Mn.AUDIO_TRACK_LOAD_ERROR,d=!1;break;case rl.SUBTITLE_TRACK:c=r?Mn.SUBTITLE_TRACK_LOAD_TIMEOUT:Mn.SUBTITLE_LOAD_ERROR,d=!1;break}u&&this.resetInternalLoader(t.type);const h={type:ui.NETWORK_ERROR,details:c,fatal:d,url:t.url,loader:u,context:t,error:o,networkDetails:n,stats:i};if(a){const p=(n==null?void 0:n.url)||t.url;h.response=wc({url:p,data:void 0},a)}this.hls.trigger(jt.ERROR,h)}handlePlaylistLoaded(t,n,r,a,i,l){const o=this.hls,{type:c,level:d,levelOrTrack:u,id:h,groupId:p,deliveryDirectives:f}=a,y=ske(n,a),_=VJe(a);let v=typeof a.level=="number"&&_===Wa.MAIN?d:void 0;const j=t.playlistParsingError;if(j){if(this.hls.logger.warn(`${j} ${t.url}`),!o.config.ignorePlaylistParsingErrors){o.trigger(jt.ERROR,{type:ui.NETWORK_ERROR,details:Mn.LEVEL_PARSING_ERROR,fatal:!1,url:y,error:j,reason:j.message,response:n,context:a,level:v,parent:_,networkDetails:i,stats:r});return}t.playlistParsingError=null}if(!t.fragments.length){const w=t.playlistParsingError=new Error("No Segments found in Playlist");o.trigger(jt.ERROR,{type:ui.NETWORK_ERROR,details:Mn.LEVEL_EMPTY_ERROR,fatal:!1,url:y,error:w,reason:w.message,response:n,context:a,level:v,parent:_,networkDetails:i,stats:r});return}switch(t.live&&l&&(l.getCacheAge&&(t.ageHeader=l.getCacheAge()||0),(!l.getCacheAge||isNaN(t.ageHeader))&&(t.ageHeader=0)),c){case rl.MANIFEST:case rl.LEVEL:if(v){if(!u)v=0;else if(u!==o.levels[v]){const w=o.levels.indexOf(u);w>-1&&(v=w)}}o.trigger(jt.LEVEL_LOADED,{details:t,levelInfo:u||o.levels[0],level:v||0,id:h||0,stats:r,networkDetails:i,deliveryDirectives:f,withoutMultiVariant:c===rl.MANIFEST});break;case rl.AUDIO_TRACK:o.trigger(jt.AUDIO_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:p||"",stats:r,networkDetails:i,deliveryDirectives:f});break;case rl.SUBTITLE_TRACK:o.trigger(jt.SUBTITLE_TRACK_LOADED,{details:t,track:u,id:h||0,groupId:p||"",stats:r,networkDetails:i,deliveryDirectives:f});break}}}class Q_{static get version(){return f$}static isMSESupported(){return Fkt()}static isSupported(){return mln()}static getMediaSource(){return I4()}static get Events(){return jt}static get MetadataSchema(){return G0}static get ErrorTypes(){return ui}static get ErrorDetails(){return Mn}static get DefaultConfig(){return Q_.defaultConfig?Q_.defaultConfig:tln}static set DefaultConfig(t){Q_.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 j8e,this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.abrController=void 0,this.bufferController=void 0,this.capLevelController=void 0,this.latencyController=void 0,this.levelController=void 0,this.streamController=void 0,this.audioStreamController=void 0,this.subtititleStreamController=void 0,this.audioTrackController=void 0,this.subtitleTrackController=void 0,this.interstitialsController=void 0,this.gapController=void 0,this.emeController=void 0,this.cmcdController=void 0,this._media=null,this._url=null,this._sessionId=void 0,this.triggeringException=void 0,this.started=!1;const n=this.logger=Nnn(t.debug||!1,"Hls instance",t.assetPlayerId),r=this.config=nln(Q_.DefaultConfig,t,n);this.userConfig=t,r.progressive&&rln(r,n);const{abrController:a,bufferController:i,capLevelController:l,errorController:o,fpsController:c}=r,d=new o(this),u=this.abrController=new a(this),h=new vrn(this),p=r.interstitialsController,f=p?this.interstitialsController=new p(this,Q_):null,y=this.bufferController=new i(this,h),_=this.capLevelController=new l(this),v=new c(this),j=new yln(this),w=r.contentSteeringController,S=w?new w(this):null,A=this.levelController=new hln(this,S),E=new dln(this),O=new gln(this.config,this.logger),D=this.streamController=new xln(this,h,O),I=this.gapController=new lln(this,h);_.setStreamController(D),v.setStreamController(D);const F=[j,A,D];f&&F.splice(1,0,f),S&&F.splice(1,0,S),this.networkControllers=F;const z=[u,y,I,_,v,E,h];this.audioTrackController=this.createController(r.audioTrackController,F);const H=r.audioStreamController;H&&F.push(this.audioStreamController=new H(this,h,O)),this.subtitleTrackController=this.createController(r.subtitleTrackController,F);const Z=r.subtitleStreamController;Z&&F.push(this.subtititleStreamController=new Z(this,h,O)),this.createController(r.timelineController,z),O.emeController=this.emeController=this.createController(r.emeController,z),this.cmcdController=this.createController(r.cmcdController,z),this.latencyController=this.createController(uln,z),this.coreComponents=z,F.push(d);const Y=d.onErrorOut;typeof Y=="function"&&this.on(jt.ERROR,Y,d),this.on(jt.MANIFEST_LOADED,j.onManifestLoaded,j)}createController(t,n){if(t){const r=new t(this);return n&&n.push(r),r}return null}on(t,n,r=this){this._emitter.on(t,n,r)}once(t,n,r=this){this._emitter.once(t,n,r)}removeAllListeners(t){this._emitter.removeAllListeners(t)}off(t,n,r=this,a){this._emitter.off(t,n,r,a)}listeners(t){return this._emitter.listeners(t)}emit(t,n,r){return this._emitter.emit(t,n,r)}trigger(t,n){if(this.config.debug)return this.emit(t,t,n);try{return this.emit(t,t,n)}catch(r){if(this.logger.error("An internal error happened while handling event "+t+'. Error message: "'+r.message+'". Here is a stacktrace:',r),!this.triggeringException){this.triggeringException=!0;const a=t===jt.ERROR;this.trigger(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.INTERNAL_EXCEPTION,fatal:a,event:t,error:r}),this.triggeringException=!1}}return!1}listenerCount(t){return this._emitter.listenerCount(t)}destroy(){this.logger.log("destroy"),this.trigger(jt.DESTROYING,void 0),this.detachMedia(),this.removeAllListeners(),this._autoLevelCapping=-1,this._url=null,this.networkControllers.forEach(n=>n.destroy()),this.networkControllers.length=0,this.coreComponents.forEach(n=>n.destroy()),this.coreComponents.length=0;const t=this.config;t.xhrSetup=t.fetchSetup=void 0,this.userConfig=null}attachMedia(t){if(!t||"media"in t&&!t.media){const i=new Error(`attachMedia failed: invalid argument (${t})`);this.trigger(jt.ERROR,{type:ui.OTHER_ERROR,details:Mn.ATTACH_MEDIA_ERROR,fatal:!0,error:i});return}this.logger.log("attachMedia"),this._media&&(this.logger.warn("media must be detached before attaching"),this.detachMedia());const n="media"in t,r=n?t.media:t,a=n?t:{media:r};this._media=r,this.trigger(jt.MEDIA_ATTACHING,a)}detachMedia(){this.logger.log("detachMedia"),this.trigger(jt.MEDIA_DETACHING,{}),this._media=null}transferMedia(){this._media=null;const t=this.bufferController.transferMedia();return this.trigger(jt.MEDIA_DETACHING,{transferMedia:t}),t}loadSource(t){this.stopLoad();const n=this.media,r=this._url,a=this._url=h8e.buildAbsoluteURL(self.location.href,t,{alwaysNormalize:!0});this._autoLevelCapping=-1,this._maxHdcpLevel=null,this.logger.log(`loadSource:${a}`),n&&r&&(r!==a||this.bufferController.hasSourceTypes())&&(this.detachMedia(),this.attachMedia(n)),this.trigger(jt.MANIFEST_LOADING,{url:t})}get url(){return this._url}get hasEnoughToStart(){return this.streamController.hasEnoughToStart}get startPosition(){return this.streamController.startPositionValue}startLoad(t=-1,n){this.logger.log(`startLoad(${t+(n?", ":"")})`),this.started=!0,this.resumeBuffering();for(let r=0;r{t.resumeBuffering&&t.resumeBuffering()}))}pauseBuffering(){this.bufferingEnabled&&(this.logger.log("pause buffering"),this.networkControllers.forEach(t=>{t.pauseBuffering&&t.pauseBuffering()}))}get inFlightFragments(){const t={[Wa.MAIN]:this.streamController.inFlightFrag};return this.audioStreamController&&(t[Wa.AUDIO]=this.audioStreamController.inFlightFrag),this.subtititleStreamController&&(t[Wa.SUBTITLE]=this.subtititleStreamController.inFlightFrag),t}swapAudioCodec(){this.logger.log("swapAudioCodec"),this.streamController.swapAudioCodec()}recoverMediaError(){this.logger.log("recoverMediaError");const t=this._media,n=t==null?void 0:t.currentTime;this.detachMedia(),t&&(this.attachMedia(t),n&&this.startLoad(n))}removeLevel(t){this.levelController.removeLevel(t)}get sessionId(){let t=this._sessionId;return t||(t=this._sessionId=lon()),t}get levels(){const t=this.levelController.levels;return t||[]}get latestLevelDetails(){return this.streamController.getLevelDetails()||null}get loadLevelObj(){return this.levelController.loadLevelObj}get currentLevel(){return this.streamController.currentLevel}set currentLevel(t){this.logger.log(`set currentLevel:${t}`),this.levelController.manualLevel=t,this.streamController.immediateLevelSwitch()}get nextLevel(){return this.streamController.nextLevel}set nextLevel(t){this.logger.log(`set nextLevel:${t}`),this.levelController.manualLevel=t,this.streamController.nextLevelSwitch()}get loadLevel(){return this.levelController.level}set loadLevel(t){this.logger.log(`set loadLevel:${t}`),this.levelController.manualLevel=t}get nextLoadLevel(){return this.levelController.nextLoadLevel}set nextLoadLevel(t){this.levelController.nextLoadLevel=t}get firstLevel(){return Math.max(this.levelController.firstLevel,this.minAutoLevel)}set firstLevel(t){this.logger.log(`set firstLevel:${t}`),this.levelController.firstLevel=t}get startLevel(){const t=this.levelController.startLevel;return t===-1&&this.abrController.forcedAutoLevel>-1?this.abrController.forcedAutoLevel:t}set startLevel(t){this.logger.log(`set startLevel:${t}`),t!==-1&&(t=Math.max(t,this.minAutoLevel)),this.levelController.startLevel=t}get capLevelToPlayerSize(){return this.config.capLevelToPlayerSize}set capLevelToPlayerSize(t){const n=!!t;n!==this.config.capLevelToPlayerSize&&(n?this.capLevelController.startCapping():(this.capLevelController.stopCapping(),this.autoLevelCapping=-1,this.streamController.nextLevelSwitch()),this.config.capLevelToPlayerSize=n)}get autoLevelCapping(){return this._autoLevelCapping}get bandwidthEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimate():NaN}set bandwidthEstimate(t){this.abrController.resetEstimator(t)}get abrEwmaDefaultEstimate(){const{bwEstimator:t}=this.abrController;return t?t.defaultEstimate:NaN}get ttfbEstimate(){const{bwEstimator:t}=this.abrController;return t?t.getEstimateTTFB():NaN}set autoLevelCapping(t){this._autoLevelCapping!==t&&(this.logger.log(`set autoLevelCapping:${t}`),this._autoLevelCapping=t,this.levelController.checkMaxAutoUpdated())}get maxHdcpLevel(){return this._maxHdcpLevel}set maxHdcpLevel(t){nrn(t)&&this._maxHdcpLevel!==t&&(this._maxHdcpLevel=t,this.levelController.checkMaxAutoUpdated())}get autoLevelEnabled(){return this.levelController.manualLevel===-1}get manualLevel(){return this.levelController.manualLevel}get minAutoLevel(){const{levels:t,config:{minAutoBitrate:n}}=this;if(!t)return 0;const r=t.length;for(let a=0;a=n)return a;return 0}get maxAutoLevel(){const{levels:t,autoLevelCapping:n,maxHdcpLevel:r}=this;let a;if(n===-1&&t!=null&&t.length?a=t.length-1:a=n,r)for(let i=a;i--;){const l=t[i].attrs["HDCP-LEVEL"];if(l&&l<=r)return i}return a}get firstAutoLevel(){return this.abrController.firstAutoLevel}get nextAutoLevel(){return this.abrController.nextAutoLevel}set nextAutoLevel(t){this.abrController.nextAutoLevel=t}get playingDate(){return this.streamController.currentProgramDateTime}get mainForwardBufferInfo(){return this.streamController.getMainFwdBufferInfo()}get maxBufferLength(){return this.streamController.maxBufferLength}setAudioOption(t){var n;return((n=this.audioTrackController)==null?void 0:n.setAudioOption(t))||null}setSubtitleOption(t){var n;return((n=this.subtitleTrackController)==null?void 0:n.setSubtitleOption(t))||null}get allAudioTracks(){const t=this.audioTrackController;return t?t.allAudioTracks:[]}get audioTracks(){const t=this.audioTrackController;return t?t.audioTracks:[]}get audioTrack(){const t=this.audioTrackController;return t?t.audioTrack:-1}set audioTrack(t){const n=this.audioTrackController;n&&(n.audioTrack=t)}get allSubtitleTracks(){const t=this.subtitleTrackController;return t?t.allSubtitleTracks:[]}get subtitleTracks(){const t=this.subtitleTrackController;return t?t.subtitleTracks:[]}get subtitleTrack(){const t=this.subtitleTrackController;return t?t.subtitleTrack:-1}get media(){return this._media}set subtitleTrack(t){const n=this.subtitleTrackController;n&&(n.subtitleTrack=t)}get subtitleDisplay(){const t=this.subtitleTrackController;return t?t.subtitleDisplay:!1}set subtitleDisplay(t){const n=this.subtitleTrackController;n&&(n.subtitleDisplay=t)}get lowLatencyMode(){return this.config.lowLatencyMode}set lowLatencyMode(t){this.config.lowLatencyMode=t}get liveSyncPosition(){return this.latencyController.liveSyncPosition}get latency(){return this.latencyController.latency}get maxLatency(){return this.latencyController.maxLatency}get targetLatency(){return this.latencyController.targetLatency}set targetLatency(t){this.latencyController.targetLatency=t}get drift(){return this.latencyController.drift}get forceStartLoad(){return this.streamController.forceStartLoad}get pathways(){return this.levelController.pathways}get pathwayPriority(){return this.levelController.pathwayPriority}set pathwayPriority(t){this.levelController.pathwayPriority=t}get bufferedToEnd(){var t;return!!((t=this.bufferController)!=null&&t.bufferedToEnd)}get interstitialsManager(){var t;return((t=this.interstitialsController)==null?void 0:t.interstitialsManager)||null}getMediaDecodingInfo(t,n=this.allAudioTracks){const r=NNt(n);return wNt(t,r,navigator.mediaCapabilities)}}Q_.defaultConfig=void 0;const vln=/(?:player\.mediadelivery\.net|iframe\.mediadelivery\.net|iframe\.n\.net|video\.bunnycdn\.com|[a-z0-9-]+\.b-cdn\.net)/i;function OP(s){return!!s&&vln.test(s)&&!/\.mp4($|\?)/i.test(s)}function bln(s){const t=s.match(/\/(?:play|embed)\/(\d+)\/([a-z0-9-]+)/i);return t?{libraryId:t[1],videoId:t[2]}:null}function _ln(s,t){if(!s)return null;const n=bln(s);if(n){const r=new URLSearchParams({autoplay:t!=null&&t.autoplay?"true":"false",muted:t!=null&&t.muted?"true":"false",loop:t!=null&&t.loop?"true":"false",preload:"true",responsive:"true",playsinline:"true"});return`https://player.mediadelivery.net/embed/${n.libraryId}/${n.videoId}?${r.toString()}`}return/player\.mediadelivery\.net\/embed\//i.test(s)?s:/iframe\.mediadelivery\.net\/(?:play|embed)\//i.test(s)?s.replace("iframe.mediadelivery.net/play/","player.mediadelivery.net/embed/").replace("iframe.mediadelivery.net/embed/","player.mediadelivery.net/embed/"):s}function wln(s){const t=s.match(/https:\/\/[^"']+playlist\.m3u8[^"']*/i);return t?t[0].replace(/&/g,"&").replace(/\u0026/g,"&"):null}const ATe=N.forwardRef(function({sourceUrl:t,thumbnailUrl:n,autoPlay:r,muted:a,loop:i,playsInline:l=!0,...o},c){const d=N.useRef(null),[u,h]=N.useState(null),p=N.useMemo(()=>_ln(t,{autoplay:!!r,muted:!!a,loop:!!i}),[t,r,a,i]);N.useEffect(()=>{let y=!1;if(!t){h(null);return}if(!OP(t)){h(t);return}if(!p){h(null);return}return h(null),fetch(p).then(async _=>{if(!_.ok)throw new Error(`Failed to load Bunny embed (${_.status})`);const v=await _.text();return wln(v)}).then(_=>{y||h(_)}).catch(()=>{y||h(null)}),()=>{y=!0}},[p,t]),N.useEffect(()=>{const y=d.current;if(!y||!u)return;let _=null;const v=()=>{if(!r)return;const w=y.play();w&&w.catch(()=>{})};if(y.muted=!!a,y.loop=!!i,u.endsWith(".m3u8")){if(y.canPlayType("application/vnd.apple.mpegurl")){y.src=u;const w=()=>v();return y.addEventListener("loadedmetadata",w),()=>{y.removeEventListener("loadedmetadata",w),y.removeAttribute("src"),y.load()}}return Q_.isSupported()?(_=new Q_({enableWorker:!0,lowLatencyMode:!0}),_.loadSource(u),_.attachMedia(y),_.on(Q_.Events.MANIFEST_PARSED,v),()=>{_==null||_.destroy(),y.removeAttribute("src"),y.load()}):void 0}y.src=u;const j=()=>v();return y.addEventListener("loadedmetadata",j),()=>{y.removeEventListener("loadedmetadata",j),y.removeAttribute("src"),y.load()}},[r,i,a,u]),N.useEffect(()=>{const y=d.current;if(y){if(y.muted=!!a,y.loop=!!i,r&&u){const _=y.play();_&&_.catch(()=>{});return}y.pause()}},[r,i,a,u]);const f=y=>{if(d.current=y,typeof c=="function"){c(y);return}c&&(c.current=y)};return e.jsx("video",{ref:f,poster:n||void 0,autoPlay:r,muted:a,loop:i,playsInline:l,preload:"metadata",...o})}),jln={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 Nln(){try{let s=localStorage.getItem("vg_visitor_token");return s||(s=crypto.randomUUID(),localStorage.setItem("vg_visitor_token",s)),s}catch{return null}}function HJe(s,t){return!s||s.length===0?!1:s.some(n=>n?n===t?!0:n.endsWith("*")?t.startsWith(n.slice(0,-1)):t.startsWith(n):!1)}function R8e({config:s,appSlug:t="video_greeter",preview:n=!1,embedded:r=!1}){const[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!0),[u,h]=N.useState(!1),[p,f]=N.useState("portrait"),[y,_]=N.useState(!1),[v,j]=N.useState(!1),[w,S]=N.useState({name:"",email:"",phone:""}),[A,E]=N.useState(()=>({width:typeof window<"u"?window.innerWidth:1280,height:typeof window<"u"?window.innerHeight:720})),O=N.useRef(null),D=N.useRef(null),I=N.useRef(!1),F=async(je,He)=>{if(!n)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:t,event_type:je,visitor_token:Nln(),page_url:typeof window<"u"?window.location.href:null,metadata:He||{}})}catch{}};N.useEffect(()=>{if(u)return;const je=typeof window<"u"?window.location.pathname:"/",He=s.targeting||{mode:"all"};if(He.mode==="include"&&!HJe(He.include,je)||He.mode==="exclude"&&HJe(He.exclude,je))return;const $e=s.trigger||{type:"immediate"};if($e.type==="immediate"||n){i(!0);return}if($e.type==="delay"){const Ke=($e.value||3)*1e3,Ge=setTimeout(()=>i(!0),Ke);return()=>clearTimeout(Ge)}if($e.type==="scroll"){const Ke=($e.value||25)/100,Ge=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight>=Ke&&(i(!0),window.removeEventListener("scroll",Ge))};return window.addEventListener("scroll",Ge,{passive:!0}),()=>window.removeEventListener("scroll",Ge)}if($e.type==="exit_intent"){const Ke=Ge=>{Ge.clientY<=0&&i(!0)};return document.addEventListener("mouseleave",Ke),()=>document.removeEventListener("mouseleave",Ke)}},[u,s.targeting,s.trigger,n]),N.useEffect(()=>{a&&!I.current&&(I.current=!0,F("impression"))},[a]),N.useEffect(()=>{if(l&&D.current&&!OP(s.video_url)){D.current.currentTime=0,D.current.muted=!1,d(!1);const je=D.current.play();je&&je.catch(()=>{})}else l&&OP(s.video_url)&&d(!1)},[l,s.video_url]),N.useEffect(()=>{if(!s.thumbnail_url)return;let je=!1;const He=new Image;return He.onload=()=>{je||f(He.naturalWidth>He.naturalHeight?"landscape":"portrait")},He.src=s.thumbnail_url,()=>{je=!0}},[s.thumbnail_url]),N.useEffect(()=>{const je=()=>{E({width:window.innerWidth,height:window.innerHeight})};return je(),window.addEventListener("resize",je),()=>window.removeEventListener("resize",je)},[]);const z=()=>{o(!0),F("expand")},H=je=>{je.stopPropagation(),h(!0),o(!1)},Z=je=>{F("cta_click",{cta_id:je.id,label:je.label,url:je.url})},Y=async je=>{if(je.preventDefault(),n){_(!0);return}if(!(!w.email||!w.name)){j(!0);try{const{error:He}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:t,name:w.name,email:w.email,phone:w.phone||void 0,page_url:window.location.href}});if(He)throw He;F("lead_capture",{email:w.email}),_(!0)}catch(He){console.error("lead submit failed",He)}finally{j(!1)}}};if(!a||u||!s.video_url&&!s.video_embed_url)return null;const W=jln[p][s.size||"md"],ee=r?"absolute left-2 bottom-2":n?s.position==="bottom-right"?"absolute right-4 bottom-4":"absolute left-4 bottom-4":s.position==="bottom-right"?"fixed right-4 bottom-4 md:right-6 md:bottom-6":"fixed left-4 bottom-4 md:left-6 md:bottom-6",se=s.shape==="circle"?"rounded-full":"rounded-2xl",oe=n?p==="landscape"?"w-[280px]":"w-[220px]":p==="landscape"?"w-[360px] sm:w-[420px]":"w-[300px] sm:w-[340px]",he=p==="landscape"?"aspect-video":"aspect-[9/16]",ce=s.agent||{},me=s.lead_form_fields||["name","email","phone"],le=!!(s.show_socials&&(ce.instagram_url||ce.facebook_url||ce.linkedin_url)),ve=108+(s.ctas||[]).length*48+(s.lead_form_enabled&&!y?72+me.length*42:0)+(y?40:0)+(le?34:0),ge=Math.max(300,A.height-32),Te=Math.max(220,A.width-32),Ie=Math.max(150,ge-ve),Ce=Math.floor(p==="landscape"?Ie*(16/9):Ie*(9/16)),Me=p==="landscape"?Math.max(220,Math.min(420,Te,Ce)):Math.max(180,Math.min(340,Te,Ce)),Pe=r?"bg-white rounded-2xl shadow-2xl overflow-hidden border border-black/10 animate-in fade-in zoom-in-95 duration-300 flex flex-col":`${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`,Re=r?{width:`${Me}px`,maxHeight:"calc(100dvh - 2rem)"}:void 0,Ae=r?"p-3 space-y-2.5":"p-4 space-y-3",Be=r?"w-9 h-9 rounded-full object-cover":"w-10 h-10 rounded-full object-cover",we=r?"font-bold text-[15px] text-gray-900 leading-tight":"font-bold text-gray-900 leading-tight",Je=r?"text-[11px] text-gray-500 mt-0.5":"text-xs text-gray-500 mt-0.5",ke=r?"w-full px-3 py-1.5 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400":"w-full px-3 py-2 text-sm rounded-lg border border-gray-200 focus:border-gray-900 focus:outline-none bg-white text-gray-900 placeholder:text-gray-400",it=r?"w-full flex items-center justify-center gap-2 px-3 py-2 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60":"w-full flex items-center justify-center gap-2 px-3 py-2.5 bg-gray-900 text-white rounded-xl text-sm font-semibold hover:bg-black transition-colors disabled:opacity-60";return e.jsx("div",{"data-vg-widget":!0,"data-expanded":l?"true":"false",className:`${ee} z-[70]`,style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l?e.jsxs("div",{className:Pe,style:Re,children:[e.jsxs("div",{className:`relative bg-black ${he}`,children:[OP(s.video_url)?e.jsx(ATe,{ref:D,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:c,loop:!1,className:"w-full h-full object-cover",onLoadedMetadata:je=>{const{videoWidth:He,videoHeight:$e}=je.currentTarget;He&&$e&&f(He>$e?"landscape":"portrait")},onEnded:()=>F("watch_complete")},`expanded-${s.video_url}-${s.thumbnail_url||"no-thumb"}-${l?"on":"off"}`):e.jsx("video",{ref:D,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,playsInline:!0,controls:!1,className:"w-full h-full object-cover",onEnded:()=>F("watch_complete"),onLoadedMetadata:je=>{const{videoWidth:He,videoHeight:$e}=je.currentTarget;He&&$e&&f(He>$e?"landscape":"portrait")}}),e.jsx("button",{onClick:()=>{D.current&&(D.current.muted=!D.current.muted,d(D.current.muted))},className:"absolute bottom-3 right-3 w-9 h-9 rounded-full bg-black/60 hover:bg-black text-white flex items-center justify-center backdrop-blur",children:c?e.jsx(A9,{className:"w-4 h-4"}):e.jsx(E9,{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($n,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:Ae,children:[e.jsxs("div",{className:"flex items-center gap-3",children:[ce.avatar_url&&e.jsx("img",{src:ce.avatar_url,alt:ce.name||"",className:Be}),e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsx("p",{className:we,children:s.greeting_title||"Glad you're here!"}),s.greeting_subtitle&&e.jsx("p",{className:Je,children:s.greeting_subtitle})]})]}),(s.ctas||[]).length>0&&e.jsx("div",{className:"space-y-2",children:(s.ctas||[]).map(je=>{var He;return e.jsxs("a",{href:je.url,target:(He=je.url)!=null&&He.startsWith("http")?"_blank":void 0,rel:"noopener noreferrer",onClick:()=>Z(je),className:`flex items-center justify-between gap-2 ${r?"px-3 py-2":"px-3.5 py-2.5"} rounded-xl text-sm font-semibold transition-colors ${je.style==="secondary"?"bg-gray-100 text-gray-900 hover:bg-gray-200":"bg-gray-900 text-white hover:bg-gray-800"}`,children:[e.jsx("span",{children:je.label}),e.jsx(tr,{className:"w-3.5 h-3.5 opacity-60"})]},je.id)})}),s.lead_form_enabled&&!y&&e.jsxs("form",{onSubmit:Y,className:"space-y-2 pt-1",children:[me.includes("name")&&e.jsx("input",{type:"text",placeholder:"Name",required:!0,value:w.name,onChange:je=>S({...w,name:je.target.value}),className:ke}),me.includes("email")&&e.jsx("input",{type:"email",placeholder:"Email",required:!0,value:w.email,onChange:je=>S({...w,email:je.target.value}),className:ke}),me.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:w.phone,onChange:je=>S({...w,phone:je.target.value}),className:ke}),e.jsxs("button",{type:"submit",disabled:v,className:it,children:[e.jsx(lr,{className:"w-3.5 h-3.5"}),v?"Sending...":"Send"]})]}),y&&e.jsx("p",{className:"text-sm text-emerald-600 font-medium text-center py-2",children:"Thanks! I'll be in touch shortly."}),s.show_socials&&(ce.instagram_url||ce.facebook_url||ce.linkedin_url)&&e.jsxs("div",{className:"flex items-center justify-center gap-3 pt-2 border-t border-gray-100",children:[ce.instagram_url&&e.jsx("a",{href:ce.instagram_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"instagram"}),children:e.jsx(ou,{className:"w-4 h-4"})}),ce.facebook_url&&e.jsx("a",{href:ce.facebook_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"facebook"}),children:e.jsx(Mh,{className:"w-4 h-4"})}),ce.linkedin_url&&e.jsx("a",{href:ce.linkedin_url,target:"_blank",rel:"noopener noreferrer",className:"text-gray-400 hover:text-gray-900",onClick:()=>F("cta_click",{social:"linkedin"}),children:e.jsx(xf,{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 ${se} overflow-hidden shadow-2xl ring-2 ring-white/40 hover:ring-white/80 hover:scale-105 transition-all bg-black`,style:{width:W.w,height:W.h},"aria-label":"Play video greeting",children:[OP(s.video_url)?e.jsx(ATe,{ref:O,sourceUrl:s.video_url,thumbnailUrl:s.thumbnail_url,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-cover pointer-events-none",onLoadedMetadata:je=>{const{videoWidth:He,videoHeight:$e}=je.currentTarget;He&&$e&&f(He>$e?"landscape":"portrait")}},`collapsed-${s.video_url}-${s.thumbnail_url||"no-thumb"}`):e.jsx("video",{ref:O,src:s.video_url||void 0,poster:s.thumbnail_url||void 0,autoPlay:!0,muted:!0,loop:!0,playsInline:!0,preload:"metadata",className:"w-full h-full object-cover",onLoadedMetadata:je=>{const{videoWidth:He,videoHeight:$e}=je.currentTarget;He&&$e&&f(He>$e?"landscape":"portrait")}}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-black/40 via-transparent to-transparent pointer-events-none"}),e.jsx("div",{className:"absolute bottom-2 left-1/2 -translate-x-1/2 w-12 h-12 rounded-full bg-white/95 flex items-center justify-center shadow-lg pointer-events-none",children:e.jsx("svg",{viewBox:"0 0 24 24",className:"w-6 h-6 text-black ml-0.5",fill:"currentColor",children:e.jsx("path",{d:"M8 5v14l11-7z"})})}),e.jsx("span",{className:"absolute top-2 right-2 px-2 py-0.5 text-[10px] font-bold uppercase tracking-wider bg-red-500 text-white rounded-full animate-pulse",children:"Live"})]}),e.jsx("button",{onClick:H,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($n,{className:"w-3.5 h-3.5"})})]})})}function O8e({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_video_greeter_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(R8e,{config:t}):null}const zkt="eip_last_shown",GJe="eip_visitor_token";function kln(){try{let s=localStorage.getItem(GJe);return s||(s=crypto.randomUUID(),localStorage.setItem(GJe,s)),s}catch{return}}function Sln(s){try{const t=Number(localStorage.getItem(zkt)||0);return t?Date.now()-t>s*24*60*60*1e3:!0}catch{return!0}}function Cln(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,r=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?r:!r}function Bkt({config:s,preview:t=!1,forceOpen:n=!1}){const[r,a]=N.useState(n),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState({name:"",email:"",phone:""}),h=N.useRef(!1),p=N.useRef(!1),f=async(O,D={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"exit_intent",event_type:O,visitor_token:kln(),page_url:window.location.href,metadata:D})}catch{}};N.useEffect(()=>{if(t||!Cln(s.targeting)||!Sln(s.frequency_days))return;const O=/Mobi|Android/i.test(navigator.userAgent),D={low:5,medium:15,high:30}[s.trigger_sensitivity]||15,I=Z=>{if(!h.current){h.current=!0,a(!0);try{localStorage.setItem(zkt,String(Date.now()))}catch{}f("impression",{reason:Z})}},F=Z=>{Z.clientY<=D&&I("mouse_leave")},z=()=>{s.enable_mobile_back&&O&&I("back_button")};if(s.enable_mobile_back&&O){try{window.history.pushState({eip:!0},"")}catch{}window.addEventListener("popstate",z)}else document.addEventListener("mouseleave",F);let H;return s.enable_time_fallback&&(H=window.setTimeout(()=>I("time_fallback"),Math.max(5,s.time_fallback_seconds)*1e3)),()=>{document.removeEventListener("mouseleave",F),window.removeEventListener("popstate",z),H&&window.clearTimeout(H)}},[s,t]),N.useEffect(()=>{r&&!p.current&&!t&&!h.current&&(p.current=!0)},[r,t]);const y=()=>{a(!1),t||f("close")},_=async O=>{if(O.preventDefault(),t){l(!0);return}if(!(!d.email||!d.name)){c(!0);try{const{error:D}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"exit_intent",name:d.name,email:d.email,phone:d.phone||void 0,page_url:window.location.href}});if(D)throw D;f("lead_capture",{email:d.email}),l(!0),s.cta_url&&setTimeout(()=>{window.location.href=s.cta_url},1200)}catch(D){console.error("exit intent submit failed",D)}finally{c(!1)}}};if(!r)return null;const v=s.form_fields||["name","email"],j=s.agent||{},w=[j.first_name,j.last_name].filter(Boolean).join(" "),S=s.use_agent_photo&&j.avatar_url||s.image_url,A=s.theme_color||"#f97316",E=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:E,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:O=>O.stopPropagation(),children:[e.jsx("div",{className:"h-2 w-full",style:{background:`linear-gradient(90deg, ${A}, ${nke(A,-25)})`}}),e.jsx("button",{onClick:y,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($n,{className:"w-4 h-4"})}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[S&&e.jsx("img",{src:S,alt:w||"Agent",className:"w-14 h-14 rounded-full object-cover ring-2 shadow-md",style:{boxShadow:`0 0 0 2px ${A}33`,"--tw-ring-color":A}}),e.jsxs("div",{className:"inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-xs font-semibold",style:{background:`${A}1A`,color:A},children:[e.jsx(un,{className:"w-3 h-3"}),s.offer_label]})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.headline}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.subheadline})]}),i?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${A}10`,color:A},children:[e.jsx("div",{className:"text-3xl",children:"🎉"}),e.jsx("p",{className:"text-sm font-medium",style:{color:A},children:s.success_message})]}):s.form_enabled?e.jsxs("form",{onSubmit:_,className:"space-y-2.5",children:[v.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:d.name,onChange:O=>u({...d,name:O.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),v.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:d.email,onChange:O=>u({...d,email:O.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":A},required:!0}),v.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:d.phone,onChange:O=>u({...d,phone:O.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}, ${nke(A,-20)})`},children:o?"Sending...":s.cta_label}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We respect your inbox. Unsubscribe anytime."})]}):e.jsx("a",{href:s.cta_url||"#",onClick:()=>f("cta_click",{url:s.cta_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 transition",style:{background:`linear-gradient(135deg, ${A}, ${nke(A,-20)})`},children:s.cta_label}),w&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground pt-1",children:["Sent personally by ",w]})]})]})})}function nke(s,t){try{const n=parseInt(s.slice(1),16),r=t<0?0:255,a=Math.abs(t)/100,i=n>>16,l=n>>8&255,o=n&255,c=Math.round((r-i)*a)+i,d=Math.round((r-l)*a)+l,u=Math.round((r-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+u).toString(16).slice(1)}catch{return s}}function F8e({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_exit_intent_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(Bkt,{config:t}):null}const WJe="lm_dismissed",KJe="lm_visitor_token";function Tln(){try{let s=localStorage.getItem(KJe);return s||(s=crypto.randomUUID(),localStorage.setItem(KJe,s)),s}catch{return}}function Eln(s){if(!s||s.mode==="all")return!0;const t=window.location.pathname,r=(s.mode==="include"?s.include||[]:s.exclude||[]).some(a=>t.startsWith(a));return s.mode==="include"?r:!r}function z8e({config:s,preview:t=!1}){const[n,r]=N.useState(!1),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState({name:"",email:"",phone:""}),p=N.useRef(!1),f=async(S,A={})=>{if(!t)try{await q.from("widget_events").insert({user_id:s.user_id,app_slug:"lead_magnet",event_type:S,visitor_token:Tln(),page_url:window.location.href,metadata:A})}catch{}};N.useEffect(()=>{if(t){r(!0);return}if(!Eln(s.targeting))return;try{if(sessionStorage.getItem(WJe))return}catch{}const S=()=>{p.current||(p.current=!0,r(!0),f("impression"))};if(s.trigger_type==="immediate")S();else if(s.trigger_type==="delay"){const A=window.setTimeout(S,Math.max(0,s.trigger_value)*1e3);return()=>window.clearTimeout(A)}else if(s.trigger_type==="scroll"){const A=()=>{(window.scrollY+window.innerHeight)/document.documentElement.scrollHeight*100>=(s.trigger_value||30)&&S()};return window.addEventListener("scroll",A,{passive:!0}),()=>window.removeEventListener("scroll",A)}},[s,t]);const y=()=>{r(!1);try{sessionStorage.setItem(WJe,"1")}catch{}t||f("close")},_=async S=>{if(S.preventDefault(),t){o(!0);return}if(!(!u.email||!u.name)){d(!0);try{const{error:A}=await q.functions.invoke("submit-widget-lead",{body:{user_id:s.user_id,app_slug:"lead_magnet",name:u.name,email:u.email,phone:u.phone||void 0,page_url:window.location.href}});if(A)throw A;f("lead_capture",{email:u.email}),o(!0),(s.delivery_method==="instant"||s.delivery_method==="both")&&s.download_url&&setTimeout(()=>{const E=document.createElement("a");E.href=s.download_url,E.target="_blank",E.rel="noopener",E.download="",document.body.appendChild(E),E.click(),E.remove()},600)}catch(A){console.error("lead magnet submit failed",A)}finally{d(!1)}}};if(!n)return null;const v=s.theme_color||"#2563eb",j=t?s.position==="bottom-left"?"absolute left-4 bottom-4":"absolute right-4 bottom-4":s.position==="bottom-left"?"fixed left-4 bottom-4 md:left-6 md:bottom-6":"fixed right-4 bottom-4 md:right-6 md:bottom-6";if(s.display_style==="bar")return e.jsxs("div",{className:t?"absolute left-0 right-0 bottom-0 z-10":"fixed left-0 right-0 bottom-0 z-[75]",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"text-white shadow-2xl",style:{background:`linear-gradient(90deg, ${v}, ${DF(v,-20)})`},children:e.jsxs("div",{className:"max-w-6xl mx-auto px-4 py-3 flex items-center gap-3 flex-wrap",children:[e.jsx(Oi,{className:"w-5 h-5 shrink-0"}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("p",{className:"text-sm font-semibold truncate",children:s.title}),e.jsx("p",{className:"text-xs text-white/80 truncate",children:s.description})]}),e.jsx("button",{onClick:()=>{i(!0),f("expand")},className:"px-4 py-2 rounded-lg text-sm font-semibold bg-white shrink-0 hover:bg-white/95 transition",style:{color:v},children:s.download_label}),e.jsx("button",{onClick:y,className:"text-white/80 hover:text-white","aria-label":"Close",children:e.jsx($n,{className:"w-4 h-4"})})]})}),a&&w()]});if(!a)return e.jsxs(e.Fragment,{children:[e.jsxs("button",{onClick:()=>{i(!0),f("expand")},className:`${j} z-[75] group flex items-center gap-3 pl-3 pr-4 py-3 rounded-2xl shadow-2xl hover:shadow-3xl transition-all hover:scale-[1.03] animate-in fade-in slide-in-from-bottom-4 duration-500`,style:{background:`linear-gradient(135deg, ${v}, ${DF(v,-20)})`,paddingBottom:"env(safe-area-inset-bottom)"},children:[e.jsx("div",{className:"w-10 h-10 rounded-xl bg-white/20 backdrop-blur flex items-center justify-center text-white",children:e.jsx(rm,{className:"w-5 h-5"})}),e.jsxs("div",{className:"text-left text-white",children:[e.jsx("div",{className:"text-[10px] uppercase tracking-wider opacity-90 font-semibold",children:s.badge_label}),e.jsx("div",{className:"text-sm font-bold leading-tight max-w-[180px] truncate",children:s.title})]}),e.jsx("button",{onClick:S=>{S.stopPropagation(),y()},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($n,{className:"w-3 h-3"})})]}),a&&w()]});return w();function w(){const S=s.form_fields||["name","email"],A=s.agent||{},E=[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:O=>O.stopPropagation(),children:[e.jsxs("div",{className:"relative h-44 sm:h-52 overflow-hidden",style:{background:`linear-gradient(135deg, ${v}, ${DF(v,-25)})`},children:[s.cover_image_url?e.jsx("img",{src:s.cover_image_url,alt:s.title,className:"w-full h-full object-cover opacity-90"}):e.jsx("div",{className:"w-full h-full flex items-center justify-center",children:e.jsx(br,{className:"w-20 h-20 text-white/40"})}),e.jsxs("div",{className:"absolute top-3 left-3 inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold bg-white shadow",style:{color:v},children:[e.jsx(Oi,{className:"w-3 h-3"}),s.badge_label]}),e.jsx("button",{onClick:()=>i(!1),className:"absolute top-3 right-3 w-8 h-8 rounded-full bg-white/95 hover:bg-white flex items-center justify-center text-foreground/70 hover:text-foreground transition","aria-label":"Close",children:e.jsx($n,{className:"w-4 h-4"})})]}),e.jsxs("div",{className:"p-6 sm:p-7 space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-2xl font-extrabold tracking-tight leading-tight",children:s.title}),e.jsx("p",{className:"text-sm text-muted-foreground mt-2",children:s.description})]}),l?e.jsxs("div",{className:"rounded-xl p-5 text-center space-y-2",style:{background:`${v}10`},children:[e.jsx(Ia,{className:"w-8 h-8 mx-auto",style:{color:v}}),e.jsx("p",{className:"text-sm font-medium",style:{color:v},children:s.success_message}),s.download_url&&e.jsx("a",{href:s.download_url,target:"_blank",rel:"noopener",className:"inline-block mt-2 text-xs underline",style:{color:v},children:"Click here if download didn't start"})]}):s.form_enabled?e.jsxs("form",{onSubmit:_,className:"space-y-2.5",children:[S.includes("name")&&e.jsx("input",{type:"text",placeholder:"Your name",value:u.name,onChange:O=>h({...u,name:O.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v},required:!0}),S.includes("email")&&e.jsx("input",{type:"email",placeholder:"you@email.com",value:u.email,onChange:O=>h({...u,email:O.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v},required:!0}),S.includes("phone")&&e.jsx("input",{type:"tel",placeholder:"Phone (optional)",value:u.phone,onChange:O=>h({...u,phone:O.target.value}),className:"w-full px-4 py-3 text-sm rounded-lg border border-input bg-background focus:outline-none focus:ring-2 transition",style:{"--tw-ring-color":v}}),e.jsxs("button",{type:"submit",disabled:c,className:"w-full py-3 rounded-lg font-semibold text-white shadow-lg hover:opacity-95 active:scale-[0.99] transition disabled:opacity-60 inline-flex items-center justify-center gap-2",style:{background:`linear-gradient(135deg, ${v}, ${DF(v,-20)})`},children:[e.jsx(Ia,{className:"w-4 h-4"}),c?"Sending...":s.download_label]}),e.jsx("p",{className:"text-[10px] text-center text-muted-foreground pt-1",children:"We'll email you a copy too. No spam — promise."})]}):e.jsx("a",{href:s.download_url||"#",target:"_blank",rel:"noopener",onClick:()=>f("cta_click",{url:s.download_url}),className:"block w-full text-center py-3 rounded-lg font-semibold text-white shadow-lg",style:{background:`linear-gradient(135deg, ${v}, ${DF(v,-20)})`},children:s.download_label}),E&&e.jsxs("p",{className:"text-[11px] text-center text-muted-foreground",children:["Curated by ",E]})]})]})})}}function DF(s,t){try{const n=parseInt(s.slice(1),16),r=t<0?0:255,a=Math.abs(t)/100,i=n>>16,l=n>>8&255,o=n&255,c=Math.round((r-i)*a)+i,d=Math.round((r-l)*a)+l,u=Math.round((r-o)*a)+o;return"#"+(16777216+(c<<16)+(d<<8)+u).toString(16).slice(1)}catch{return s}}function B8e({slug:s}){const[t,n]=N.useState(null);return N.useEffect(()=>{if(!s)return;let r=!1;return(async()=>{const{data:a,error:i}=await q.rpc("get_public_lead_magnet_config",{_slug:s});!r&&!i&&a&&n(a)})(),()=>{r=!0}},[s]),t?e.jsx(z8e,{config:t}):null}function Aln({children:s,siteConfig:t}){var ge,Te,Ie,Ce,Me,Pe,Re,Ae,Be;const n=Xl(),r=Ln(),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState([]),[p,f]=N.useState([]),[y,_]=N.useState(null),v=N.useRef(null),j=N.useRef(null),{user:w,profile:S,signOut:A}=V1e();d8e(t,w==null?void 0:w.id),u8e(t,w==null?void 0:w.id);const E=((ge=t.agent)==null?void 0:ge.full_name)||"Agent",O=t.siteTitle||`${E} Real Estate`,D=n.pathname==="/search",I=n.pathname==="/",F=t.leadRegistrationMode!=="disabled";N.useEffect(()=>{(async()=>{const{data:Je}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(Je||[])})()},[t.id]),N.useEffect(()=>{(async()=>{const{data:Je}=await q.from("lead_site_menu_items").select("*").eq("site_id",t.id).eq("is_visible",!0).order("sort_order",{ascending:!0});f(Je||[])})()},[t.id]),N.useEffect(()=>{const we=Je=>{v.current&&!v.current.contains(Je.target)&&d(!1),j.current&&!j.current.contains(Je.target)&&_(null)};return document.addEventListener("mousedown",we),()=>document.removeEventListener("mousedown",we)},[]);const z=oNt(t),H=t==null?void 0:t.bookingUrl,Z=z?p.filter(we=>{const Je=String(we.target_url||"").toLowerCase(),ke=String(we.label||"").toLowerCase();return Je!=="/search"&&!Je.startsWith("/search?")&&!ke.includes("search")}):p,Y=Z.length>0,W=[{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"}],ee=Y?[]:W,se=Z.filter(we=>!we.parent_id),oe=we=>Z.filter(Je=>Je.parent_id===we),he=I?"bg-transparent text-white":"bg-white/95 backdrop-blur text-gray-900 border-b border-gray-100 shadow-sm",ce=t.siteTitle||`${E} - Real Estate`,me=t.siteTagline||`Browse homes and listings with ${E}`,le=t.ogImageUrl||((Te=t.agent)==null?void 0:Te.avatar_url)||"",ve=`https://${t.subdomainSlug||""}.thelocalmove.com`;return e.jsxs("div",{className:`flex flex-col ${D?"h-screen overflow-hidden":"min-h-screen"} bg-white`,children:[e.jsx(l8e,{siteConfig:t,pagePath:n.pathname}),e.jsx(c8e,{siteConfig:t}),e.jsxs(Zo,{children:[e.jsx("title",{children:ce}),e.jsx("meta",{name:"description",content:me}),e.jsx("meta",{property:"og:title",content:ce}),e.jsx("meta",{property:"og:description",content:me}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ve+n.pathname}),le&&e.jsx("meta",{property:"og:image",content:le}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:ce}),e.jsx("meta",{name:"twitter:description",content:me}),le&&e.jsx("meta",{name:"twitter:image",content:le}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ve}${n.pathname}`}),t.subdomainSlug==="matthogg"&&e.jsx("script",{src:"https://analytics.ahrefs.com/analytics.js","data-key":"kyFjzruyvE0yTdMokzgCBw",async:!0})]}),e.jsxs("header",{className:`${I?"absolute":"sticky"} top-0 left-0 right-0 z-50 transition-all ${he}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-20",children:[e.jsxs(In,{to:"/",className:"flex items-center gap-3",children:[((Ie=t.agent)==null?void 0:Ie.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:E,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:O})})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[ee.map(we=>e.jsx(In,{to:we.to,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname===we.to?I?"bg-white/15 text-white":"bg-gray-100 text-gray-900":I?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:we.label},we.to)),Y&&se.map(we=>{if(we.item_type==="dropdown"){const Je=oe(we.id);return e.jsxs("div",{ref:j,className:"relative",children:[e.jsxs("button",{onClick:()=>_(y===we.id?null:we.id),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${I?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[we.label," ",e.jsx(ao,{className:`h-3.5 w-3.5 transition-transform ${y===we.id?"rotate-180":""}`})]}),y===we.id&&Je.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:Je.map(ke=>e.jsx(FG,{item:ke,onClick:()=>_(null),className:"w-full text-left px-4 py-2.5 text-sm text-gray-700 hover:bg-gray-50 hover:text-gray-900 transition-colors block"},ke.id))})]},we.id)}return e.jsx(FG,{item:we,className:`px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${I?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`},we.id)}),u.length>0&&e.jsxs("div",{ref:v,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 rounded-lg text-sm font-medium tracking-wide transition-colors ${n.pathname.startsWith("/homes-for-sale-in-")?I?"bg-white/15 text-white":"bg-gray-100 text-gray-900":I?"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(ao,{className:`h-3.5 w-3.5 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-52 bg-white rounded-xl shadow-xl border border-gray-100 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:u.map(we=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${we.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:we.city_name},we.city_slug))})]}),w?e.jsxs("div",{className:"flex items-center gap-1 ml-2",children:[e.jsxs(In,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${I?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(gi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:"Saved"})]}),e.jsxs(In,{to:"/account",className:`flex items-center gap-1.5 px-3 py-2 rounded-lg text-sm font-medium transition-colors ${I?"text-white/70 hover:text-white hover:bg-white/10":"text-gray-500 hover:text-gray-900 hover:bg-gray-50"}`,children:[e.jsx(Wi,{className:"h-4 w-4"}),e.jsx("span",{className:"hidden lg:inline",children:((Ce=S==null?void 0:S.name)==null?void 0:Ce.split(" ")[0])||"Account"})]})]}):F?e.jsx("button",{onClick:()=>o(!0),className:`ml-2 px-4 py-2 rounded-lg text-sm font-medium transition-colors ${I?"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 ${I?"text-white hover:bg-white/10":"text-gray-600 hover:bg-gray-100"}`,children:a?e.jsx($n,{className:"h-5 w-5"}):e.jsx(KS,{className:"h-5 w-5"})})]})}),a&&e.jsx("div",{className:`md:hidden border-t ${I?"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:[ee.map(we=>e.jsx(In,{to:we.to,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===we.to?I?"bg-white/15 text-white":"bg-gray-100 text-gray-900":I?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:we.label},we.to)),Y&&se.map(we=>{if(we.item_type==="dropdown"){const Je=oe(we.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 ${I?"text-white/40":"text-gray-400"}`,children:we.label}),Je.map(ke=>e.jsx(FG,{item:ke,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${I?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},ke.id))]},we.id)}return e.jsx(FG,{item:we,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${I?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`},we.id)}),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:`px-3 pt-3 pb-1 text-xs font-semibold uppercase tracking-wider ${I?"text-white/40":"text-gray-400"}`,children:"Cities"}),u.map(we=>e.jsx(In,{to:`/homes-for-sale-in-${we.city_slug}`,onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${n.pathname===`/homes-for-sale-in-${we.city_slug}`?I?"bg-white/15 text-white":"bg-gray-100 text-gray-900":I?"text-white/70 hover:bg-white/10":"text-gray-500 hover:bg-gray-50"}`,children:we.city_name},we.city_slug))]}),w?e.jsxs(e.Fragment,{children:[e.jsx(In,{to:"/account",onClick:()=>i(!1),className:`block px-3 py-2.5 rounded-lg text-sm font-medium ${I?"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 ${I?"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 ${I?"text-white/70 hover:bg-white/10":"text-blue-600 hover:bg-blue-50"}`,children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!D&&e.jsx("footer",{className:"bg-gray-950 text-gray-400",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-16",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-12",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-4 mb-4",children:[((Me=t.agent)==null?void 0:Me.avatar_url)&&e.jsx("img",{src:t.agent.avatar_url,alt:E,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:E}),e.jsx("p",{className:"text-sm text-gray-500",children:((Pe=t.agent)==null?void 0:Pe.title)||"Real Estate Professional"})]})]}),((Re=t.agent)==null?void 0:Re.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(Cr,{className:"h-3.5 w-3.5"})," ",t.agent.phone]})}),((Ae=t.agent)==null?void 0:Ae.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(Gs,{className:"h-3.5 w-3.5"})," ",t.agent.email]})})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Quick Links"}),e.jsxs("ul",{className:"space-y-3 text-sm",children:[ee.map(we=>e.jsx("li",{children:e.jsx(In,{to:we.to,className:"hover:text-white transition-colors",children:we.label})},we.to)),H&&e.jsx("li",{children:e.jsx("a",{href:H,target:"_blank",rel:"noopener noreferrer",className:"hover:text-white transition-colors",children:"Schedule a Call"})})]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"font-semibold text-white mb-4 text-sm tracking-wider uppercase",children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-gray-500 leading-relaxed mb-4",children:z?"Have a real estate question or need a trusted connection? Get in touch today.":"Ready to find your dream home? Get in touch today for a personalized consultation."}),e.jsx(In,{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:[E," · ",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()," ",E,". Powered by LevelUp."]})]})]})]})}),!D&&((Be=t.agent)==null?void 0:Be.avatar_url)&&e.jsx(Mln,{agent:t.agent,bookingUrl:H}),l&&e.jsx(o8e,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1)}),e.jsx(O8e,{slug:t.subdomainSlug}),e.jsx(F8e,{slug:t.subdomainSlug}),e.jsx(B8e,{slug:t.subdomainSlug})]})}function Mln({agent:s,bookingUrl:t}){var i;const[n,r]=N.useState(!1),a=Ln();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:n?e.jsxs("div",{className:"bg-white rounded-2xl shadow-2xl border border-gray-200 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-3",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-2 ring-gray-100"}),e.jsxs("div",{children:[e.jsx("p",{className:"font-bold text-gray-900 text-sm",children:s.full_name}),e.jsx("p",{className:"text-xs text-gray-500",children:s.title||"Real Estate Professional"})]})]}),e.jsx("p",{className:"text-xs text-gray-500 mb-4",children:"Have questions about a property or the area? I'm here to help!"}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2 bg-gray-50 hover:bg-gray-100 rounded-xl text-sm text-gray-700 transition-colors",children:[e.jsx(Cr,{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(Gs,{className:"h-4 w-4 text-gray-400"}),"Email Me"]}),e.jsx("button",{onClick:()=>{r(!1),a("/contact")},className:"w-full px-3 py-2.5 bg-blue-600 hover:bg-blue-700 text-white text-sm font-semibold rounded-xl transition-colors",children:"Ask a Question"}),t&&e.jsx("a",{href:t,target:"_blank",rel:"noopener noreferrer",className:"block text-center w-full px-3 py-2.5 bg-gray-900 hover:bg-gray-800 text-white text-sm font-semibold rounded-xl transition-colors",children:"Schedule a Call"})]})]}),e.jsx("button",{onClick:()=>r(!1),className:"absolute top-3 right-3 p-1 text-gray-400 hover:text-gray-600 rounded-full hover:bg-gray-100",children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>r(!0),className:"group flex items-center gap-3 bg-white pl-1.5 pr-5 py-1.5 rounded-full shadow-xl border border-gray-200 hover:shadow-2xl transition-all hover:scale-105",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-2 ring-blue-100"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-xs font-bold text-gray-900 leading-none",children:(i=s.full_name)==null?void 0:i.split(" ")[0]}),e.jsx("p",{className:"text-[10px] text-blue-600 font-medium mt-0.5",children:"Chat with me →"})]})]})}):null}function FG({item:s,className:t,onClick:n}){const r=s.target_url||"#";return s.item_type==="external"||s.open_in_new_tab?e.jsx("a",{href:r,target:"_blank",rel:"noopener noreferrer",className:t,onClick:n,children:s.label}):e.jsx(In,{to:r,className:t,onClick:n,children:s.label})}const YJe={california:"California DRE License",ca:"California DRE License"};function MTe(s){const t=(s||"").trim();if(!t)return"Real Estate License";const n=t.toLowerCase();return YJe[n]?YJe[n]:`${t.replace(/\b\w/g,a=>a.toUpperCase())} Real Estate License`}function ZJe(s){if(s)return s.replace(/^\s*DRE\s*#?\s*/i,"").replace(/^\s*#/,"").trim()||void 0}function Iln({children:s,siteConfig:t}){var le,ve,ge,Te,Ie,Ce,Me;const n=Xl(),r=Ln(),[a,i]=N.useState(!1),[l,o]=N.useState(!1),[c,d]=N.useState(!1),[u,h]=N.useState([]),[p,f]=N.useState(!1),y=N.useRef(null),{user:_,profile:v,signOut:j}=V1e();d8e(t,_==null?void 0:_.id),u8e(t,_==null?void 0:_.id);const w=((le=t.agent)==null?void 0:le.full_name)||"Agent",S=ZJe(t.agentLicenseNumber),A=ZJe(t.brokerageLicenseNumber),E=t.siteTitle||`${w} Real Estate`,O=t.brokerageLegalName?`${w} | ${t.brokerageLegalName}`:w,D=Pe=>{if(!Pe)return Pe;const Re=w.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),Ae=new RegExp(`^\\s*${Re}\\s*[|\\-–—:]\\s*`,"i");return Pe.replace(Ae,"").trim()},I=E&&E!==`${w} Real Estate`?E:null,F=I?D(I):null,z=F&&F.toLowerCase()!==w.toLowerCase()?F:null,H=n.pathname==="/search",Z=n.pathname==="/",Y=t.leadRegistrationMode!=="disabled",W="#c9a96e";N.useEffect(()=>{const Pe=()=>f(window.scrollY>80);return window.addEventListener("scroll",Pe,{passive:!0}),()=>window.removeEventListener("scroll",Pe)},[]),N.useEffect(()=>{(async()=>{const{data:Re}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order",{ascending:!0});h(Re||[])})()},[t.id]),N.useEffect(()=>{const Pe=Re=>{y.current&&!y.current.contains(Re.target)&&d(!1)};return document.addEventListener("mousedown",Pe),()=>document.removeEventListener("mousedown",Pe)},[]);const ee=[{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"}],se=t.siteTitle||`${w} - Real Estate`,oe=t.siteTagline||`Browse homes and listings with ${w}`,he=t.ogImageUrl||((ve=t.agent)==null?void 0:ve.avatar_url)||"",ce=`https://${t.subdomainSlug||""}.thelocalmove.com`,me=Z?p?"bg-[#0d0b0a]/95 backdrop-blur-lg border-b border-white/5":"bg-transparent":"bg-[#0d0b0a] border-b border-white/5";return e.jsxs("div",{className:`flex flex-col ${H?"h-screen overflow-hidden":"min-h-screen"} bg-[#0d0b0a]`,children:[e.jsx(l8e,{siteConfig:t,pagePath:n.pathname}),e.jsx(c8e,{siteConfig:t}),e.jsxs(Zo,{children:[e.jsx("title",{children:se}),e.jsx("meta",{name:"description",content:oe}),e.jsx("meta",{property:"og:title",content:se}),e.jsx("meta",{property:"og:description",content:oe}),e.jsx("meta",{property:"og:type",content:"website"}),e.jsx("meta",{property:"og:url",content:ce+n.pathname}),he&&e.jsx("meta",{property:"og:image",content:he}),e.jsx("meta",{name:"twitter:card",content:"summary_large_image"}),e.jsx("meta",{name:"twitter:title",content:se}),e.jsx("meta",{name:"twitter:description",content:oe}),he&&e.jsx("meta",{name:"twitter:image",content:he}),t.faviconUrl&&e.jsx("link",{rel:"icon",href:t.faviconUrl,type:"image/png"}),e.jsx("link",{rel:"canonical",href:`${ce}${n.pathname}`}),e.jsx("link",{href:"https://fonts.googleapis.com/css2?family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400;1,500&display=swap",rel:"stylesheet"})]}),e.jsxs("header",{className:`${Z?"fixed":"sticky"} top-0 left-0 right-0 z-50 transition-all duration-500 ${me}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-6 lg:px-8",children:e.jsxs("div",{className:"flex items-center justify-between h-20",children:[e.jsx(In,{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:O}),z&&e.jsx("span",{className:"mt-1 text-[11px] tracking-[0.18em] uppercase text-white/70",children:z})]})}),e.jsxs("nav",{className:"hidden lg:flex items-center gap-1",children:[ee.map(Pe=>e.jsx(In,{to:Pe.to,className:`px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname===Pe.to?"text-white":"text-white/40 hover:text-white"}`,children:Pe.label},Pe.to)),u.length>0&&e.jsxs("div",{ref:y,className:"relative",children:[e.jsxs("button",{onClick:()=>d(!c),className:`flex items-center gap-1 px-4 py-2 text-xs tracking-[0.15em] uppercase transition-colors duration-300 ${n.pathname.startsWith("/homes-for-sale-in-")?"text-white":"text-white/40 hover:text-white"}`,children:["Cities ",e.jsx(ao,{className:`h-3 w-3 transition-transform ${c?"rotate-180":""}`})]}),c&&e.jsx("div",{className:"absolute top-full right-0 mt-2 w-56 bg-[#1a1715] border border-white/10 py-2 z-50 animate-in fade-in slide-in-from-top-2 duration-150",children:u.map(Pe=>e.jsx("button",{onClick:()=>{r(`/homes-for-sale-in-${Pe.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:Pe.city_name},Pe.city_slug))})]}),_?e.jsxs("div",{className:"flex items-center gap-1 ml-3",children:[e.jsxs(In,{to:"/account",className:"flex items-center gap-1.5 px-3 py-2 text-xs tracking-wider text-white/40 hover:text-white uppercase transition-colors",children:[e.jsx(gi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:"Saved"})]}),e.jsxs(In,{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(Wi,{className:"h-3.5 w-3.5"}),e.jsx("span",{className:"hidden xl:inline",children:((ge=v==null?void 0:v.name)==null?void 0:ge.split(" ")[0])||"Account"})]})]}):Y?e.jsx("button",{onClick:()=>o(!0),className:"ml-3 px-5 py-2 text-xs tracking-[0.2em] uppercase border border-white/20 text-white/60 hover:bg-white hover:text-black transition-all duration-500",children:"Sign In"}):null]}),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($n,{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:[ee.map(Pe=>e.jsx(In,{to:Pe.to,onClick:()=>i(!1),className:`block px-3 py-3 text-xs tracking-[0.2em] uppercase transition-colors ${n.pathname===Pe.to?"text-white":"text-white/40 hover:text-white"}`,children:Pe.label},Pe.to)),u.length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"px-3 pt-4 pb-2 text-[10px] tracking-[0.3em] uppercase",style:{color:W},children:"Cities"}),u.map(Pe=>e.jsx(In,{to:`/homes-for-sale-in-${Pe.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:Pe.city_name},Pe.city_slug))]}),_?e.jsxs(e.Fragment,{children:[e.jsx(In,{to:"/account",onClick:()=>i(!1),className:"block px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"My Account"}),e.jsx("button",{onClick:async()=>{await j(),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign Out"})]}):Y?e.jsx("button",{onClick:()=>{o(!0),i(!1)},className:"block w-full text-left px-3 py-3 text-xs tracking-[0.2em] uppercase text-white/40 hover:text-white",children:"Sign In / Register"}):null]})})]}),e.jsx("main",{className:"flex-1 min-h-0 flex flex-col",children:s}),!H&&e.jsx("footer",{className:"bg-[#0a0908] text-white/70 border-t border-white/10",children:e.jsxs("div",{className:"max-w-7xl mx-auto px-6 lg:px-8 py-20",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-16",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-white text-xl tracking-tight mb-3",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:w}),e.jsx("p",{className:"text-white/70 text-xs tracking-[0.15em] uppercase mb-6",children:((Te=t.agent)==null?void 0:Te.title)||"Real Estate Professional"}),(S||A)&&e.jsxs("div",{className:"mb-6 p-4 border border-white/10 bg-white/5",children:[S&&e.jsxs("p",{className:"text-sm text-white font-medium tracking-wide",children:[MTe(t.licenseState)," #",S]}),A&&e.jsxs("p",{className:"text-xs text-white/70 tracking-wider uppercase mt-1",children:["Brokerage License #",A]})]}),((Ie=t.agent)==null?void 0:Ie.phone)&&e.jsxs("a",{href:`tel:${t.agent.phone}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors mb-3",children:[e.jsx(Cr,{className:"h-3.5 w-3.5"})," ",t.agent.phone]}),((Ce=t.agent)==null?void 0:Ce.email)&&e.jsxs("a",{href:`mailto:${t.agent.email}`,className:"flex items-center gap-3 text-sm text-white/70 hover:text-white transition-colors",children:[e.jsx(Gs,{className:"h-3.5 w-3.5"})," ",t.agent.email]})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:W},children:"Quick Links"}),e.jsx("ul",{className:"space-y-3",children:ee.map(Pe=>e.jsx("li",{children:e.jsx(In,{to:Pe.to,className:"text-xs tracking-wider uppercase text-white/70 hover:text-white transition-colors",children:Pe.label})},Pe.to))})]}),e.jsxs("div",{children:[e.jsx("h4",{className:"text-xs tracking-[0.3em] uppercase mb-6 text-white",style:{color:W},children:"Get In Touch"}),e.jsx("p",{className:"text-sm text-white/70 leading-relaxed mb-6",style:{fontFamily:"'Playfair Display', Georgia, serif",fontStyle:"italic"},children:"Ready to experience luxury real estate? Let's connect."}),e.jsx(In,{to:"/contact",className:"inline-block px-8 py-3 text-xs tracking-[0.3em] uppercase border border-white/20 text-white/90 hover:bg-white hover:text-black transition-all duration-500",children:"Contact Me"})]})]}),e.jsxs("div",{className:"mt-16 pt-8 border-t border-white/10",children:[t.showTeamLogo&&t.teamLogoUrl&&e.jsx("div",{className:"flex items-center justify-center mb-6",children:e.jsx("img",{src:t.teamLogoUrl,alt:"Team",className:"h-10 w-auto object-contain opacity-70"})}),t.brokerageLegalName&&e.jsxs("div",{className:"flex flex-wrap items-center justify-center gap-x-4 gap-y-1 text-[11px] text-white/70 tracking-wider uppercase mb-3",children:[e.jsxs("span",{children:[w," · ",t.brokerageLegalName]}),S&&e.jsxs("span",{children:[MTe(t.licenseState)," #",S]}),A&&e.jsxs("span",{children:["Brokerage #",A]})]}),t.mlsDisclaimerText&&e.jsxs("div",{className:"flex items-start justify-center gap-3 mb-4",children:[t.mlsLogoUrl&&e.jsx("img",{src:t.mlsLogoUrl,alt:"MLS",className:"h-6 w-auto flex-shrink-0 mt-0.5 opacity-70"}),e.jsx("p",{className:"text-[11px] text-white/70 leading-relaxed max-w-3xl text-center",children:t.mlsDisclaimerText})]}),e.jsxs("div",{className:"flex items-center justify-center gap-4 text-[11px] text-white/70 tracking-wider uppercase",children:[t.equalHousingEnabled&&e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx("svg",{viewBox:"0 0 24 24",fill:"currentColor",className:"h-4 w-4",children:e.jsx("path",{d:"M12 2L2 8v2h20V8L12 2zm0 2.5L18.5 8h-13L12 4.5zM4 12v8h4v-6h8v6h4v-8H4zm6 8v-4h4v4h-4z"})}),e.jsx("span",{children:"Equal Housing Opportunity"})]}),e.jsxs("span",{children:["© ",new Date().getFullYear()," ",w,". Powered by LevelUp."]})]})]})]})}),!H&&((Me=t.agent)==null?void 0:Me.avatar_url)&&e.jsx(Pln,{agent:t.agent,agentLicense:S,siteConfig:t,accentColor:W}),l&&e.jsx(o8e,{open:l,mode:"optional",siteConfig:t,onComplete:()=>o(!1),onSkip:()=>o(!1),theme:"luxury",accentColor:W}),e.jsx(O8e,{slug:t.subdomainSlug}),e.jsx(F8e,{slug:t.subdomainSlug}),e.jsx(B8e,{slug:t.subdomainSlug})]})}function Pln({agent:s,agentLicense:t,siteConfig:n,accentColor:r}){var o;const[a,i]=N.useState(!1),l=Ln();return s?e.jsx("div",{className:"fixed bottom-6 right-6 z-40",children:a?e.jsxs("div",{className:"bg-[#1a1715] border border-white/10 w-72 overflow-hidden animate-in slide-in-from-bottom-4 fade-in duration-200",children:[e.jsxs("div",{className:"p-5",children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-12 w-12 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{children:[e.jsx("p",{className:"text-white text-sm font-medium",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:s.full_name}),e.jsx("p",{className:"text-white/50 text-[10px] tracking-[0.1em] uppercase",children:s.title||"Real Estate Professional"})]})]}),t&&e.jsxs("div",{className:"mb-3 px-3 py-2 bg-white/5 border border-white/10",children:[e.jsx("p",{className:"text-[10px] text-white/50 tracking-wider uppercase",children:MTe(n.licenseState)}),e.jsxs("p",{className:"text-xs text-white font-medium",children:["#",t]})]}),e.jsxs("div",{className:"space-y-2",children:[s.phone&&e.jsxs("a",{href:`tel:${s.phone}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[e.jsx(Cr,{className:"h-3.5 w-3.5"})," ",s.phone]}),s.email&&e.jsxs("a",{href:`mailto:${s.email}`,className:"flex items-center gap-2 w-full px-3 py-2.5 bg-white/5 hover:bg-white/10 text-xs text-white/70 hover:text-white transition-colors tracking-wider",children:[e.jsx(Gs,{className:"h-3.5 w-3.5"})," Email Me"]}),e.jsx("button",{onClick:()=>{i(!1),l("/contact")},className:"w-full px-3 py-2.5 text-xs tracking-[0.2em] uppercase text-black hover:opacity-90 transition-colors",style:{backgroundColor:r},children:"Send a Message"})]})]}),e.jsx("button",{onClick:()=>i(!1),className:"absolute top-3 right-3 p-1 text-white/20 hover:text-white/50",children:e.jsx($n,{className:"h-4 w-4"})})]}):e.jsxs("button",{onClick:()=>i(!0),className:"group flex items-center gap-3 bg-[#1a1715] border border-white/10 pl-1.5 pr-5 py-1.5 hover:border-white/20 transition-all",children:[e.jsx("img",{src:s.avatar_url,alt:s.full_name,className:"h-10 w-10 rounded-full object-cover ring-1 ring-white/10"}),e.jsxs("div",{className:"text-left",children:[e.jsx("p",{className:"text-[11px] text-white leading-none",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:(o=s.full_name)==null?void 0:o.split(" ")[0]}),e.jsx("p",{className:"text-[9px] tracking-[0.15em] uppercase mt-1",style:{color:r},children:"Let's connect →"})]})]})}):null}const RF="#2c1810",E_="#b8860b";function Lln({children:s,siteConfig:t}){var I,F,z;const n=Xl();Ln();const[r,a]=N.useState(!1),[i,l]=N.useState(!1),[o,c]=N.useState(!1),[d,u]=N.useState([]),[h,p]=N.useState(!1),f=N.useRef(null),{user:y,profile:_,signOut:v}=V1e();d8e(t,y==null?void 0:y.id),u8e(t,y==null?void 0:y.id);const j=((I=t.agent)==null?void 0:I.full_name)||"Agent",w=t.siteTitle||`${j} Land & Ranch`,S=n.pathname==="/",A=t.leadRegistrationMode!=="disabled";N.useEffect(()=>{const H=()=>p(window.scrollY>80);return window.addEventListener("scroll",H,{passive:!0}),()=>window.removeEventListener("scroll",H)},[]),N.useEffect(()=>{(async()=>{const{data:Z}=await q.from("lead_site_city_pages").select("city_name, city_slug").eq("site_id",t.id).eq("is_published",!0).order("sort_order");Z&&u(Z)})()},[t.id]),N.useEffect(()=>{const H=Z=>{f.current&&!f.current.contains(Z.target)&&c(!1)};return document.addEventListener("mousedown",H),()=>document.removeEventListener("mousedown",H)},[]);const E=[{label:"Home",path:"/"},{label:"Search Properties",path:"/search"},{label:"About",path:"/about"},{label:"Blog",path:"/blog"},{label:"Contact",path:"/contact"}],O=h||!S?"bg-white/95 backdrop-blur-md shadow-sm":"bg-transparent",D=h||!S?RF:"#ffffff";return e.jsxs("div",{className:"min-h-screen",style:{fontFamily:"'Lora', Georgia, serif"},children:[e.jsxs(Zo,{children:[e.jsx("title",{children:w}),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(l8e,{siteConfig:t}),e.jsx(c8e,{siteConfig:t}),e.jsxs("header",{className:`fixed top-0 left-0 right-0 z-50 transition-all duration-300 ${O}`,children:[e.jsx("div",{className:"max-w-7xl mx-auto px-4 sm:px-6",children:e.jsxs("div",{className:"flex items-center justify-between h-16 md:h-20",children:[e.jsxs(In,{to:"/",className:"flex items-center gap-2.5",children:[e.jsx(YP,{className:"w-7 h-7",style:{color:E_}}),e.jsx("span",{className:"text-lg font-bold tracking-wide",style:{color:D,fontFamily:"'Playfair Display', Georgia, serif"},children:w})]}),e.jsxs("nav",{className:"hidden md:flex items-center gap-1",children:[E.map(H=>e.jsx(In,{to:H.path,className:"px-4 py-2 text-sm font-medium tracking-wide uppercase transition-colors hover:opacity-80",style:{color:n.pathname===H.path?E_:D},children:H.label},H.path)),d.length>0&&e.jsxs("div",{ref:f,className:"relative",children:[e.jsxs("button",{onClick:()=>c(!o),className:"px-4 py-2 text-sm font-medium tracking-wide uppercase flex items-center gap-1 transition-colors hover:opacity-80",style:{color:D},children:["Areas ",e.jsx(ao,{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(H=>e.jsx(In,{to:`/homes-for-sale-in-${H.city_slug}`,className:"block px-4 py-2.5 text-sm hover:bg-gray-50 transition-colors",style:{color:RF},onClick:()=>c(!1),children:H.city_name},H.city_slug))})]}),y?e.jsx("div",{className:"flex items-center gap-2 ml-3",children:e.jsxs(In,{to:"/account",className:"px-4 py-2 text-sm font-medium rounded-full border-2 transition-all hover:scale-105",style:{borderColor:E_,color:D},children:[e.jsx(Wi,{className:"w-4 h-4 inline mr-1.5"}),(_==null?void 0:_.name)||"Account"]})}):A?e.jsx("button",{onClick:()=>l(!0),className:"ml-3 px-5 py-2.5 text-sm font-semibold text-white rounded-full hover:shadow-lg transition-all hover:scale-105",style:{backgroundColor:E_},children:"Sign In"}):null]}),e.jsx("button",{onClick:()=>a(!r),className:"md:hidden p-2",style:{color:D},children:r?e.jsx($n,{className:"w-6 h-6"}):e.jsx(KS,{className:"w-6 h-6"})})]})}),r&&e.jsx("div",{className:"md:hidden bg-white border-t border-gray-100 shadow-xl animate-in slide-in-from-top-2",children:e.jsxs("div",{className:"px-4 py-4 space-y-1",children:[E.map(H=>e.jsx(In,{to:H.path,className:"block px-4 py-3 text-base font-medium rounded-lg hover:bg-gray-50 transition-colors",style:{color:n.pathname===H.path?E_:RF},onClick:()=>a(!1),children:H.label},H.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(H=>e.jsx(In,{to:`/homes-for-sale-in-${H.city_slug}`,className:"block px-4 py-2.5 text-sm rounded-lg hover:bg-gray-50",style:{color:RF},onClick:()=>a(!1),children:H.city_name},H.city_slug))]}),!y&&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:E_},children:"Sign In"})]})})]}),e.jsx("main",{children:s}),e.jsx("footer",{className:"py-16 px-4",style:{backgroundColor:RF},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(YP,{className:"w-6 h-6",style:{color:E_}}),e.jsx("span",{className:"text-lg font-bold text-white",style:{fontFamily:"'Playfair Display', Georgia, serif"},children:w})]}),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:E.map(H=>e.jsx(In,{to:H.path,className:"block text-white/60 hover:text-white text-sm transition-colors",children:H.label},H.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(Cr,{className:"w-4 h-4",style:{color:E_}}),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(Gs,{className:"w-4 h-4",style:{color:E_}}),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()," ",w,". All rights reserved."]}),e.jsx("div",{className:"h-px w-16",style:{backgroundColor:E_}})]})]})}),i&&e.jsx(o8e,{open:i,mode:t.leadRegistrationMode==="required"?"required":"optional",siteConfig:t,onSkip:()=>l(!1),onComplete:()=>l(!1)}),e.jsx(O8e,{slug:t.subdomainSlug}),e.jsx(F8e,{slug:t.subdomainSlug}),e.jsx(B8e,{slug:t.subdomainSlug})]})}function Dln(){const{pathname:s}=Xl();return N.useEffect(()=>{window.scrollTo({top:0,left:0,behavior:"auto"})},[s]),null}const Rln=N.lazy(()=>xi(()=>import("./LeadSiteHome-BoWLNAjR.js"),__vite__mapDeps([0,1,2,3]))),Oln=N.lazy(()=>xi(()=>import("./LeadSiteLuxuryHome-DNyeLG1D.js"),__vite__mapDeps([4,2,3]))),Fln=N.lazy(()=>xi(()=>import("./LeadSiteLandRanchHome-CUnQZCCF.js"),__vite__mapDeps([5,1,2,3]))),zln=N.lazy(()=>xi(()=>import("./LeadSiteSearch-BC4GLYwg.js"),__vite__mapDeps([6,1,7,3,8]))),Bln=N.lazy(()=>xi(()=>import("./LeadSiteLuxurySearch-oRPNnVRs.js"),__vite__mapDeps([9,1,7,3,8]))),$ln=N.lazy(()=>xi(()=>import("./LeadSiteListingDetail-BLDbi8JV.js"),__vite__mapDeps([10,11,3,12]))),Uln=N.lazy(()=>xi(()=>import("./LeadSiteLuxuryListingDetail-BEn4rDLg.js"),__vite__mapDeps([13,11,3,12]))),qln=N.lazy(()=>xi(()=>import("./LeadSiteAbout-B4i2fU0b.js"),[])),Vln=N.lazy(()=>xi(()=>import("./LeadSiteLuxuryAbout-D0Fa3DwP.js"),[])),Hln=N.lazy(()=>xi(()=>import("./LeadSiteContact-CJBCO-rG.js"),[])),Gln=N.lazy(()=>xi(()=>import("./LeadSiteLuxuryContact-BonyXHM3.js"),[])),Wln=N.lazy(()=>xi(()=>import("./LeadSiteConsumerDashboard-CSVcGCJ_.js"),[])),QJe=N.lazy(()=>xi(()=>import("./LeadSiteBlog-CRQG5mBm.js"),[])),Kln=N.lazy(()=>xi(()=>import("./LeadSiteCommunity-Dj7YAQEB.js"),[])),Yln=N.lazy(()=>xi(()=>import("./LeadSiteSellers-Lof3z5ro.js"),[])),Zln=N.lazy(()=>xi(()=>import("./LeadSiteCityPage-CrRJTLTr.js"),__vite__mapDeps([14,3,8]))),Qln=N.lazy(()=>xi(()=>import("./LeadSiteSubdivisionPage-CWx-Vqf5.js"),__vite__mapDeps([15,3]))),Xln=N.lazy(()=>xi(()=>import("./LeadSiteCustomPage-u4PBmS8N.js"),[]));function Jln(){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 ecn(){const{siteConfig:s,themeConfig:t,isLoading:n,error:r}=snn();if(n)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-white",children:e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-blue-600 border-t-transparent mx-auto mb-4"}),e.jsx("p",{className:"text-gray-500",children:"Loading..."})]})});if(r||!s)return e.jsx("div",{className:"min-h-screen flex items-center justify-center bg-gray-50 p-6",children:e.jsxs("div",{className:"text-center max-w-md",children:[e.jsx("h1",{className:"text-2xl font-bold text-gray-900 mb-2",children:"Site Not Found"}),e.jsx("p",{className:"text-gray-500",children:"This lead site is not available or has not been set up yet."})]})});const a=(t==null?void 0:t.themeTier)==="luxury",i=(t==null?void 0:t.themeTier)==="land-ranch",l=i?Lln:a?Iln:Aln,o=oNt(s,t),c=i?e.jsx(Fln,{siteConfig:s,themeConfig:t??void 0}):a?e.jsx(Oln,{siteConfig:s,themeConfig:t??void 0}):e.jsx(Rln,{siteConfig:s,themeConfig:t??void 0});return e.jsxs(rnn,{siteConfig:s,children:[e.jsx(Dln,{}),e.jsx(l,{siteConfig:s,children:e.jsx(N.Suspense,{fallback:e.jsx(Jln,{}),children:e.jsxs(Bpe,{children:[e.jsx(as,{path:"/",element:c}),e.jsx(as,{path:"/search",element:o?e.jsx(o4,{to:"/contact",replace:!0}):a?e.jsx(Bln,{siteConfig:s}):e.jsx(zln,{siteConfig:s})}),e.jsx(as,{path:"/listing/:mlsNumber",element:o?e.jsx(o4,{to:"/contact",replace:!0}):a?e.jsx(Uln,{siteConfig:s}):e.jsx($ln,{siteConfig:s})}),e.jsx(as,{path:"/about",element:a?e.jsx(Vln,{siteConfig:s}):e.jsx(qln,{siteConfig:s})}),e.jsx(as,{path:"/contact",element:a?e.jsx(Gln,{siteConfig:s}):e.jsx(Hln,{siteConfig:s})}),e.jsx(as,{path:"/account",element:e.jsx(Wln,{siteConfig:s})}),e.jsx(as,{path:"/blog",element:e.jsx(QJe,{siteConfig:s,isLuxury:a})}),e.jsx(as,{path:"/blog/:slug",element:e.jsx(QJe,{siteConfig:s,isLuxury:a})}),e.jsx(as,{path:"/sell",element:e.jsx(Yln,{siteConfig:s,themeConfig:t??void 0,isLuxury:a})}),e.jsx(as,{path:"/community",element:e.jsx(Kln,{siteConfig:s,isLuxury:a})}),e.jsx(as,{path:"/p/:pageSlug",element:e.jsx(Xln,{siteConfig:s})}),e.jsx(as,{path:"/*",element:e.jsx(tcn,{siteConfig:s,referralMode:o})})]})})})]})}function tcn({siteConfig:s,referralMode:t}){const n=Xl(),r=n.pathname.match(/^\/homes-in-(.+)$/);if(r)return e.jsx(Qln,{siteConfig:s,subdivisionSlug:r[1]});const a=n.pathname.match(/^\/homes-for-sale-in-(.+)$/);return a?e.jsx(Zln,{siteConfig:s,citySlugOverride:a[1],referralMode:t}):null}function scn(){const{user:s,loading:t}=vs(),{data:n,isLoading:r}=dt({queryKey:["feature-entitlement","levelup_attract",s==null?void 0:s.id],enabled:!!s,staleTime:5*60*1e3,queryFn:async()=>{const{data:a,error:i}=await q.from("feature_entitlements").select("enabled, expires_at, tier").eq("user_id",s.id).eq("feature_key","levelup_attract").maybeSingle();if(i)throw i;return a?{hasAccess:a.enabled&&(!a.expires_at||new Date(a.expires_at).getTime()>Date.now()),tier:a.tier??null}:{hasAccess:!1,tier:null}}});return{hasAccess:!!(n!=null&&n.hasAccess),tier:(n==null?void 0:n.tier)??null,isLoading:t||r}}function ncn({children:s}){const{user:t,loading:n}=vs(),{hasAccess:r,isLoading:a}=scn(),i=Xl();return N.useEffect(()=>{!n&&!a&&t&&!r&&ae.error("LevelUp Attract isn't available for your account yet.")},[n,a,t,r]),n||t&&a?e.jsx("div",{className:"flex min-h-screen items-center justify-center bg-background",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):t?r?e.jsx(e.Fragment,{children:s}):e.jsx(o4,{to:"/dashboard",replace:!0}):(sessionStorage.setItem("redirectAfterLogin",i.pathname),e.jsx(o4,{to:"/auth",replace:!0}))}function $U(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:["attract-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:i,error:l}=await q.from("attract_settings").select("*").eq("user_id",s.id).maybeSingle();if(l)throw l;return i}}),r=yt({mutationFn:async i=>{const l={...i,user_id:s.id},{data:o,error:c}=await q.from("attract_settings").upsert(l,{onConflict:"user_id"}).select().single();if(c)throw c;return o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Settings saved")},onError:i=>ae.error(i.message)}),a=yt({mutationFn:async()=>{const{error:i}=await q.from("attract_settings").update({onboarding_completed_at:null}).eq("user_id",s.id);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-settings"]}),ae.success("Onboarding reset — run it again anytime")}});return{settings:n.data,isLoading:n.isLoading,save:r,upsert:r,resetOnboarding:a}}const $kt="v1",Xc={recency:22,consistency:16,value_delivered:14,kit_engagement:16,event_participation:12,follow_up_discipline:10,pipeline_momentum:10};Object.values(Xc).reduce((s,t)=>s+t,0);const Ukt=864e5,Cm=(s,t=new Date)=>Math.floor((new Date(t).getTime()-new Date(s).getTime())/Ukt),qkt=["touch_logged","call","text","email","dm","meeting","note"];function rcn(s,t,n=new Date){var _,v,j;const a=t.activities.filter(w=>w.agent_id===s.id).filter(w=>qkt.includes(w.activity_type)).sort((w,S)=>+new Date(S.created_at)-+new Date(w.created_at)),i=s.last_touch_at||((_=a[0])==null?void 0:_.created_at)||null,l=t.shares.filter(w=>w.agent_id===s.id),o=new Set(l.map(w=>w.id)),c=t.kitEvents.filter(w=>o.has(w.share_id)),d={};for(const w of l)d[w.id]=[];for(const w of c)(d[v=w.share_id]||(d[v]=[])).push(w);const u=t.attendees.filter(w=>w.agent_id===s.id),h=t.followUps.filter(w=>w.agent_id===s.id),p=h.filter(w=>!w.completed_at),f=t.stageChanges.filter(w=>w.agent_id===s.id).sort((w,S)=>+new Date(S.created_at)-+new Date(w.created_at)),y=new Set(a.filter(w=>Cm(w.created_at,n)<=180).map(w=>w.created_at.slice(0,7)));return{agent:s,touches:a,lastTouchAt:i,daysSinceTouch:i?Cm(i,n):null,touches90:a.filter(w=>Cm(w.created_at,n)<=90).length,touches30:a.filter(w=>Cm(w.created_at,n)<=30).length,distinctTouchMonths:y.size,shares:l,shareEvents:d,highIntentShares:l.filter(w=>w.engagement_level==="high_intent"||w.engagement_level==="engaged"),lastShareAt:l.map(w=>w.created_at).sort().reverse()[0]||null,totalKitOpens:l.reduce((w,S)=>w+(S.open_count||0),0),downloads:c.filter(w=>w.event_type==="file_download").length,ctaClicks:c.filter(w=>w.event_type==="primary_cta_click"||w.event_type==="external_link_click").length,questions:c.filter(w=>w.event_type==="question_submitted").length,meetingRequests:c.filter(w=>w.event_type==="meeting_requested").length+u.filter(w=>w.meeting_requested).length,attendees:u,attended:u.filter(w=>!!w.checked_in_at||w.status==="attended").length,noShows:u.filter(w=>!!w.no_show_at||w.status==="no_show").length,invitedNotRegistered:u.filter(w=>!!w.invited_at&&!w.registered_at&&!w.checked_in_at).length,openFollowUps:p,overdueFollowUps:p.filter(w=>w.due_at&&new Date(w.due_at)!!w.completed_at),stageChanges:f,lastStageChangeAt:((j=f[0])==null?void 0:j.created_at)||null,daysSinceStageChange:f[0]?Cm(f[0].created_at,n):null,scoreEvents:t.scoreEvents.filter(w=>w.agent_id===s.id)}}const npe=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined"],rpe=["not_right_now","not_a_fit","long_term_relationship"];function acn(s,t=new Date){const n=[],r=[],a=[],i=[],l=s.daysSinceTouch;let o=0,c;l===null?(o=0,c="No meaningful touch has ever been logged.",a.push("No logged conversation yet"),i.push("Log your first real conversation with this agent.")):l<=10?(o=Xc.recency,c=`Last meaningful touch ${l} day(s) ago.`,r.push("Recent personal contact")):l<=21?(o=Xc.recency*.85,c=`Last touch ${l} days ago.`,r.push("Contact is still fresh")):l<=45?(o=Xc.recency*.6,c=`Last touch ${l} days ago.`,i.push("Reach out within the next week to keep momentum.")):l<=90?(o=Xc.recency*.3,c=`Last touch ${l} days ago.`,a.push(`${l} days since a real conversation`),i.push("A personal check-in would meaningfully lift this score.")):(o=Xc.recency*.05,c=`Last touch ${l} days ago.`,a.push(`Relationship has been quiet for ${l} days`),i.push("Restart the relationship with a no-ask personal check-in.")),n.push({key:"recency",label:"Recency of personal contact",weight:Xc.recency,earned:Math.round(o),detail:c,direction:o>=Xc.recency*.6?"positive":"negative"});const d=Math.min(s.distinctTouchMonths,6),u=Xc.consistency*(d/6),h=s.touches30>6;n.push({key:"consistency",label:"Consistency of touches",weight:Xc.consistency,earned:Math.round(u),detail:`${d} of the last 6 months had at least one logged touch (${s.touches90} touches in 90 days).`,direction:u>=Xc.consistency*.5?"positive":"neutral"}),d>=4&&r.push("Consistent rhythm across months"),d<=1&&i.push("Aim for at least one touch per month rather than bursts."),h&&a.push(`${s.touches30} touches in the last 30 days — give them room to breathe`);const p=s.shares.length,f=Xc.value_delivered*Math.min(p/3,1);n.push({key:"value_delivered",label:"Value delivered",weight:Xc.value_delivered,earned:Math.round(f),detail:p?`${p} resource kit share(s) sent.`:"No resource kit shared yet.",direction:p?"positive":"neutral"}),p?r.push(`${p} resource kit share(s) delivered`):i.push("Share a relevant Resource Kit — value first, no ask.");const y=(s.totalKitOpens>0?4:0)+Math.min(s.downloads,2)*2+Math.min(s.ctaClicks,2)*2+(s.questions>0?2:0)+(s.meetingRequests>0?4:0),_=Math.min(y,Xc.kit_engagement);n.push({key:"kit_engagement",label:"Kit engagement",weight:Xc.kit_engagement,earned:_,detail:p?`${s.totalKitOpens} open(s), ${s.downloads} download(s), ${s.ctaClicks} link click(s), ${s.questions} question(s), ${s.meetingRequests} meeting request(s).`:"Nothing shared yet, so no engagement to measure.",direction:_>0?"positive":"neutral"}),s.meetingRequests>0&&r.push("They asked for a conversation"),p&&s.totalKitOpens===0&&(a.push("Shared kit has never been opened"),i.push("Follow up personally — the kit link was never opened."));const v=Math.min(s.attended,2)*5+(s.attendees.length?2:0)-Math.min(s.noShows,2)*2,j=Math.max(0,Math.min(v,Xc.event_participation));n.push({key:"event_participation",label:"Event participation",weight:Xc.event_participation,earned:j,detail:s.attendees.length?`${s.attended} attended, ${s.noShows} no-show(s), ${s.attendees.length} total invitation(s)/registration(s).`:"Never invited to an event.",direction:j>0?"positive":"neutral"}),s.attended>0&&r.push(`${s.attended} event(s) attended`),s.attendees.length||i.push("Invite them to your next event or mastermind."),s.noShows>0&&a.push(`${s.noShows} no-show(s)`);const w=s.completedFollowUps.length+s.openFollowUps.length;let S=w===0?Xc.follow_up_discipline*.4:Xc.follow_up_discipline*(s.completedFollowUps.length/w);S-=Math.min(s.overdueFollowUps.length,3)*2,S=Math.max(0,Math.min(S,Xc.follow_up_discipline)),n.push({key:"follow_up_discipline",label:"Follow-up discipline",weight:Xc.follow_up_discipline,earned:Math.round(S),detail:w?`${s.completedFollowUps.length} of ${w} follow-ups completed, ${s.overdueFollowUps.length} overdue.`:"No follow-ups created yet.",direction:s.overdueFollowUps.length?"negative":"positive"}),s.overdueFollowUps.length&&(a.push(`${s.overdueFollowUps.length} overdue commitment(s)`),i.push("Clear the overdue follow-up you promised."));const A=npe.indexOf(s.agent.stage);let E=0,O;if(rpe.includes(s.agent.stage))E=Xc.pipeline_momentum*.3,O="Relationship is intentionally parked — long-term nurture.";else if(A<0)E=Xc.pipeline_momentum*.3,O=`Stage "${s.agent.stage}" is outside the advancing ladder.`;else{const F=Xc.pipeline_momentum*(A/(npe.length-1)),z=s.daysSinceStageChange!==null&&s.daysSinceStageChange>60;E=z?F*.5:F,O=`Stage ${A+1} of ${npe.length}`+(s.daysSinceStageChange!==null?`, last moved ${s.daysSinceStageChange} days ago.`:", never moved."),z&&(a.push("Stage has not moved in over 60 days"),i.push("Have the next real conversation that would justify a stage move."))}n.push({key:"pipeline_momentum",label:"Pipeline momentum",weight:Xc.pipeline_momentum,earned:Math.round(E),detail:O,direction:E>Xc.pipeline_momentum*.5?"positive":"neutral"});let D=n.reduce((F,z)=>F+z.earned,0);s.agent.temperature==="hot"&&(D+=4,r.push("You marked this relationship hot")),s.agent.temperature==="cold"&&(D-=4,a.push("You marked this relationship cold")),h&&(D-=3),D=Math.max(0,Math.min(100,Math.round(D)));const I=D>=75?"thriving":D>=55?"healthy":D>=35?"cooling":"at_risk";return{agent_id:s.agent.id,score:D,band:I,components:n,positives:r,negatives:a,improvements:Array.from(new Set(i)).slice(0,4),inputs:{days_since_touch:s.daysSinceTouch,touches_90:s.touches90,touches_30:s.touches30,distinct_touch_months_6mo:s.distinctTouchMonths,shares:s.shares.length,kit_opens:s.totalKitOpens,downloads:s.downloads,cta_clicks:s.ctaClicks,questions:s.questions,meeting_requests:s.meetingRequests,events_attended:s.attended,no_shows:s.noShows,invited_not_registered:s.invitedNotRegistered,open_follow_ups:s.openFollowUps.length,overdue_follow_ups:s.overdueFollowUps.length,completed_follow_ups:s.completedFollowUps.length,stage:s.agent.stage,days_since_stage_change:s.daysSinceStageChange,temperature:s.agent.temperature},weights:{...Xc},engine_version:$kt,calculated_at:t.toISOString()}}const Vkt=[{key:"high_intent",label:"High-intent engagement",blurb:"They took a real action — respond while it is warm.",tone:"rose"},{key:"renewed_interest",label:"Renewed interest",blurb:"Someone quiet came back and engaged again.",tone:"violet"},{key:"event_follow_up",label:"Event follow-up needed",blurb:"Within 48 hours of an event is where relationships are made.",tone:"indigo"},{key:"resource_follow_up",label:"Resource follow-up needed",blurb:"You shared value — close the loop personally.",tone:"teal"},{key:"overdue_commitment",label:"Overdue commitment",blurb:"You said you would follow up. Keep your word.",tone:"orange"},{key:"going_cold",label:"Relationship going cold",blurb:"Momentum is fading. A no-ask check-in resets it.",tone:"amber"},{key:"no_touch",label:"No meaningful touch recently",blurb:"Long silence. Restart the relationship, do not pitch.",tone:"slate"},{key:"ready_deeper",label:"Ready for a deeper conversation",blurb:"Signals suggest they are open to going further.",tone:"green"}],icn={urgent:100,high:70,medium:40,low:15},cv=(s,t=new Date)=>new Date(t.getTime()+s*Ukt).toISOString(),P_=s=>s.first_name||"there",ocn=3;function dv(s,t,n={}){var o,c;const r=P_(t.agent),a=(o=t.agent.goals)==null?void 0:o.trim(),i=(c=t.agent.challenges)==null?void 0:c.trim(),l=i?` You mentioned ${i.replace(/\.$/,"")} — that's still on my mind.`:a?` You mentioned ${a.replace(/\.$/,"")} — still thinking about that with you.`:"";switch(s){case"high_intent":return`Hey ${r} — saw you spent some time in the ${n.kitTitle??"resources"} I sent over. No agenda here; I'd just love to hear what stood out and what questions came up.${l} Any chance for a quick call this week?`;case"renewed_interest":return`${r}! You popped back into ${n.kitTitle??"that resource"} I shared a while back — figured I'd check in. How's everything going on your end?${l}`;case"event_follow_up":return`${r}, really glad you were at ${n.eventTitle??"the session"}. What was the most useful part for you? Happy to send over anything specific that would help you put it to work.`;case"event_no_show":return`Hey ${r} — noticed you couldn't make ${n.eventTitle??"the session"}, no worries at all. Life happens. Want me to send you the highlights, or would a quick 1:1 be more useful?`;case"event_invite_nudge":return`${r} — I've got ${n.eventTitle??"a small session"} coming up${n.eventWhen?` on ${n.eventWhen}`:""} and thought of you. Small group, real conversation, nothing salesy. Want me to save you a seat?`;case"resource_follow_up":return`Hey ${r} — I sent over ${n.kitTitle??"a few resources"} a bit ago. Didn't want it to get buried. Did any of it land, or is there something more specific I can pull together for you?`;case"resource_unopened":return`${r}, I sent you ${n.kitTitle??"something"} that I genuinely think would help — might've gone to spam. Want me to just walk you through the short version instead?`;case"overdue_commitment":return`Hey ${r} — I owe you a follow-up on "${n.followUpTitle??"what we talked about"}". Circling back now.${l} When's a good time?`;case"going_cold":return`${r} — it's been a bit. No agenda, genuinely just checking in on you. How's business feeling right now?${l}`;case"no_touch":return`Hey ${r} — long overdue message from me. I've been thinking about our last conversation and wanted to see how you're doing. No pitch, just catching up.`;case"ready_deeper":return`${r}, based on what you've shared I think it's worth a real conversation about what you actually want the next chapter to look like — no pressure either direction. Coffee or a call this week?`;case"share_value":return`${r} — put together ${n.kitTitle?`"${n.kitTitle}"`:"a small set of resources"} that I think fits exactly where you are right now. Sending it because it's useful, not because I want anything. Let me know if it helps.`;default:return`Hey ${r} — checking in. How are things going?${l}`}}function lcn(s,t,n=new Date){const r=[],a=s.agent;if(a.stage==="not_a_fit")return r;const i=s.daysSinceTouch!==null&&s.daysSinceTouch{var j;return(j=t.kits.find(w=>w.id===v))==null?void 0:j.title},o=v=>{r.push({...v,message_source:"rules",rank_score:v.rank_score??icn[v.priority]})},c=s.shares.find(v=>v.engagement_level==="high_intent");if(s.meetingRequests>0||s.questions>0||c){const v=c?l(c.kit_id):void 0,j=[s.meetingRequests>0&&`${s.meetingRequests} meeting request(s) submitted`,s.questions>0&&`${s.questions} question(s) asked inside a shared kit`,c&&`Kit engagement is classified High Intent (${c.open_count} opens)`,s.downloads>0&&`${s.downloads} file download(s)`].filter(Boolean);o({agent_id:a.id,rec_key:"high_intent",signal_group:"high_intent",signal_label:"High-intent engagement",action_type:"respond_to_intent",channel:s.meetingRequests>0?"call":"text",title:`Call ${P_(a)} — they are actively engaging`,reasons:j,priority:"urgent",suggested_due_at:cv(1,n),draft_message:dv("high_intent",s,{kitTitle:v}),suggested_kit_id:(c==null?void 0:c.kit_id)??null,source_signals:{meeting_requests:s.meetingRequests,questions:s.questions,downloads:s.downloads,share_id:c==null?void 0:c.id},rank_score:100+s.meetingRequests*5})}const d=s.shares.find(v=>v.last_opened_at&&v.first_opened_at&&Cm(v.last_opened_at,n)<=7&&Cm(v.first_opened_at,v.last_opened_at)>=14&&(v.open_count||0)>1);d&&(s.daysSinceTouch===null||s.daysSinceTouch>21)&&o({agent_id:a.id,rec_key:"renewed_interest",signal_group:"renewed_interest",signal_label:"Renewed interest",action_type:"reengage",channel:"text",title:`${P_(a)} came back to a kit you shared`,reasons:[`Re-opened "${l(d.kit_id)??"a shared kit"}" ${Cm(d.last_opened_at,n)} day(s) ago`,`${d.open_count} total opens`,s.daysSinceTouch===null?"No personal touch logged":`${s.daysSinceTouch} days since your last personal touch`],priority:"high",suggested_due_at:cv(2,n),draft_message:dv("renewed_interest",s,{kitTitle:l(d.kit_id)}),suggested_kit_id:d.kit_id,source_signals:{share_id:d.id,open_count:d.open_count},rank_score:88});const u=s.attendees.filter(v=>v.checked_in_at&&Cm(v.checked_in_at,n)<=7&&v.followup_status!=="done").sort((v,j)=>+new Date(j.checked_in_at)-+new Date(v.checked_in_at))[0];if(u){const v=t.events.find(w=>w.id===u.event_id),j=Math.round((n.getTime()-new Date(u.checked_in_at).getTime())/36e5);o({agent_id:a.id,rec_key:`event_follow_up:${u.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"event_follow_up",channel:"call",title:`Follow up on ${(v==null?void 0:v.title)??"the event"} — ${j}h since they attended`,reasons:[`Checked in to "${(v==null?void 0:v.title)??"event"}" ${j} hours ago`,`Follow-up status is "${u.followup_status??"pending"}"`,j<=48?"Inside the 48-hour window where follow-up matters most":"Past the ideal 48-hour window — still worth doing today"],priority:j<=48?"urgent":"high",suggested_due_at:cv(j<=48?1:0,n),draft_message:dv("event_follow_up",s,{eventTitle:v==null?void 0:v.title}),suggested_event_id:u.event_id,suggested_kit_id:(v==null?void 0:v.resource_kit_id)??null,source_signals:{attendee_id:u.id,hours_since:j},rank_score:j<=48?96:74})}else{const v=s.attendees.find(j=>j.no_show_at&&Cm(j.no_show_at,n)<=10);if(v){const j=t.events.find(w=>w.id===v.event_id);o({agent_id:a.id,rec_key:`event_no_show:${v.event_id}`,signal_group:"event_follow_up",signal_label:"Event follow-up needed",action_type:"no_show_recovery",channel:"text",title:`${P_(a)} missed ${(j==null?void 0:j.title)??"an event"} — recover gracefully`,reasons:[`Registered but did not attend "${(j==null?void 0:j.title)??"event"}"`,"No-show recovery works best within a week, with zero guilt"],priority:"medium",suggested_due_at:cv(2,n),draft_message:dv("event_no_show",s,{eventTitle:j==null?void 0:j.title}),suggested_event_id:v.event_id,source_signals:{attendee_id:v.id},rank_score:52})}}const h=s.shares.find(v=>v.first_opened_at&&Cm(v.first_opened_at,n)>=3&&Cm(v.first_opened_at,n)<=30&&(s.daysSinceTouch===null||s.lastTouchAt&&new Date(s.lastTouchAt)!v.first_opened_at&&Cm(v.created_at,n)>=5&&v.status==="active");h?o({agent_id:a.id,rec_key:`resource_follow_up:${h.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_follow_up",channel:"text",title:`Close the loop on "${l(h.kit_id)??"the kit"}"`,reasons:[`Opened ${Cm(h.first_opened_at,n)} day(s) ago`,`${h.open_count} open(s), engagement level "${h.engagement_level}"`,"No personal touch logged since they viewed it"],priority:"high",suggested_due_at:cv(2,n),draft_message:dv("resource_follow_up",s,{kitTitle:l(h.kit_id)}),suggested_kit_id:h.kit_id,source_signals:{share_id:h.id},rank_score:78}):p&&o({agent_id:a.id,rec_key:`resource_unopened:${p.id}`,signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"resource_nudge",channel:"text",title:`Shared kit never opened — nudge ${P_(a)} personally`,reasons:[`Shared ${Cm(p.created_at,n)} days ago and never opened`,"A personal message beats a resend"],priority:"medium",suggested_due_at:cv(2,n),draft_message:dv("resource_unopened",s,{kitTitle:l(p.kit_id)}),suggested_kit_id:p.kit_id,source_signals:{share_id:p.id},rank_score:46});const f=s.overdueFollowUps.sort((v,j)=>+new Date(v.due_at)-+new Date(j.due_at))[0];if(f){const v=Cm(f.due_at,n);o({agent_id:a.id,rec_key:`overdue:${f.id}`,signal_group:"overdue_commitment",signal_label:"Overdue commitment",action_type:"clear_overdue",channel:f.touch_type||"call",title:`Overdue ${v} day(s): ${f.title}`,reasons:[`Follow-up "${f.title}" was due ${v} day(s) ago`,`Priority: ${f.priority??"medium"}`],priority:v>7?"urgent":"high",suggested_due_at:cv(0,n),draft_message:dv("overdue_commitment",s,{followUpTitle:f.title}),source_signals:{follow_up_id:f.id,days_late:v},rank_score:92+Math.min(v,8)})}const y=npe.indexOf(a.stage);if(!rpe.includes(a.stage)&&y>=2&&s.attended>0&&(s.totalKitOpens>0||s.downloads>0)&&(s.daysSinceStageChange===null||s.daysSinceStageChange>21)&&o({agent_id:a.id,rec_key:"ready_deeper",signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"deeper_conversation",channel:"call",title:`Have the honest next-chapter conversation with ${P_(a)}`,reasons:[`Stage "${a.stage}" with real engagement behind it`,`${s.attended} event(s) attended and ${s.totalKitOpens} kit open(s)`,s.daysSinceStageChange!==null?`Stage unchanged for ${s.daysSinceStageChange} days`:"Stage has never moved"],priority:"high",suggested_due_at:cv(4,n),draft_message:dv("ready_deeper",s),source_signals:{stage:a.stage,attended:s.attended},rank_score:72}),s.daysSinceTouch===null&&Cm(a.created_at,n)>7)o({agent_id:a.id,rec_key:"no_first_touch",signal_group:"no_touch",signal_label:"No meaningful touch recently",action_type:"first_conversation",channel:"personal_check_in",title:`You have never logged a conversation with ${P_(a)}`,reasons:[`Added to your pipeline ${Cm(a.created_at,n)} days ago`,"No touch, kit, or event activity logged"],priority:"medium",suggested_due_at:cv(3,n),draft_message:dv("no_touch",s),source_signals:{created_at:a.created_at},rank_score:48});else if(s.daysSinceTouch!==null){const v=a.temperature==="hot"?14:a.temperature==="cold"?90:45;if(s.daysSinceTouch>v){const j=s.daysSinceTouch>v*2;o({agent_id:a.id,rec_key:j?"no_touch_long":"going_cold",signal_group:j?"no_touch":"going_cold",signal_label:j?"No meaningful touch recently":"Relationship going cold",action_type:"check_in",channel:"personal_check_in",title:`${P_(a)} has been quiet for ${s.daysSinceTouch} days`,reasons:[`Last meaningful touch ${s.daysSinceTouch} days ago`,`Your cadence for a "${a.temperature??"warm"}" relationship is ${v} days`,s.touches90?`${s.touches90} touch(es) in the last 90 days`:"No touches in the last 90 days"],priority:j?"high":"medium",suggested_due_at:cv(3,n),draft_message:dv(j?"no_touch":"going_cold",s),source_signals:{days_since_touch:s.daysSinceTouch,threshold:v},rank_score:j?62:44})}}if(!s.shares.length&&!rpe.includes(a.stage)&&t.primaryPillar==="provide"){const v=t.kits.find(j=>j.status==="published"&&(!j.audience||!a.production_context||!0));v&&o({agent_id:a.id,rec_key:"share_first_kit",signal_group:"resource_follow_up",signal_label:"Resource follow-up needed",action_type:"share_kit",channel:"resource_share",title:`Share "${v.title}" with ${P_(a)}`,reasons:["No resource has been shared with this agent yet","Your 90-day plan primary pillar is Provide — lead with value"],priority:"medium",suggested_due_at:cv(5,n),draft_message:dv("share_value",s,{kitTitle:v.title}),suggested_kit_id:v.id,source_signals:{pillar:"provide"},rank_score:38})}if(!s.attendees.length&&!rpe.includes(a.stage)&&t.primaryPillar==="connect"){const v=t.events.filter(j=>j.status==="published"&&j.starts_at&&new Date(j.starts_at)>n).sort((j,w)=>+new Date(j.starts_at)-+new Date(w.starts_at))[0];v&&o({agent_id:a.id,rec_key:`invite_event:${v.id}`,signal_group:"ready_deeper",signal_label:"Ready for a deeper conversation",action_type:"invite_to_event",channel:"event_invitation",title:`Invite ${P_(a)} to ${v.title}`,reasons:["Never invited to an event",`"${v.title}" is published and upcoming`,"Your 90-day plan primary pillar is Connect"],priority:"medium",suggested_due_at:cv(4,n),draft_message:dv("event_invite_nudge",s,{eventTitle:v.title,eventWhen:v.starts_at?new Date(v.starts_at).toLocaleDateString():void 0}),suggested_event_id:v.id,source_signals:{pillar:"connect",event_id:v.id},rank_score:40})}return(i?r.filter(v=>v.priority==="urgent"):r).sort((v,j)=>j.rank_score-v.rank_score).slice(0,3)}const XJe=[{key:"all",label:"Everything",kinds:[]},{key:"conversations",label:"Conversations",kinds:["touch","note","activity"]},{key:"pipeline",label:"Pipeline",kinds:["stage_change","temperature"]},{key:"follow_ups",label:"Follow-ups",kinds:["follow_up_created","follow_up_completed","follow_up_missed"]},{key:"value",label:"Value shared",kinds:["kit_shared","kit_engagement"]},{key:"events",label:"Events",kinds:["event_invited","event_registered","event_attended","event_no_show","event_note"]},{key:"score",label:"Score",kinds:["score"]}],ccn={page_view:"Viewed the kit",resource_open:"Opened a resource",file_download:"Downloaded a file",video_start:"Started a video",video_complete:"Finished a video",external_link_click:"Clicked a link",primary_cta_click:"Clicked the main call to action",question_submitted:"Submitted a question",meeting_requested:"Requested a meeting"};function dcn(s,t,n=[],r=new Date){const a=[],i=t.activities.filter(c=>c.agent_id===s.agent.id),l=c=>{var d;return((d=t.kits.find(u=>u.id===c))==null?void 0:d.title)??"Resource kit"},o=c=>{var d;return((d=t.events.find(u=>u.id===c))==null?void 0:d.title)??"Event"};for(const c of i)a.push({id:`act:${c.id}`,kind:qkt.includes(c.activity_type)?c.activity_type==="note"?"note":"touch":"activity",at:c.created_at,title:c.title,detail:c.description??void 0,meta:{activity_type:c.activity_type,pillar:c.pillar}});for(const c of s.stageChanges)a.push({id:`stage:${c.id}`,kind:"stage_change",at:c.created_at,title:`Stage moved to ${c.to_stage.replace(/_/g," ")}`,detail:c.from_stage?`From ${c.from_stage.replace(/_/g," ")}`:void 0});for(const c of t.followUps.filter(d=>d.agent_id===s.agent.id))a.push({id:`fuc:${c.id}`,kind:"follow_up_created",at:c.created_at,title:`Follow-up created: ${c.title}`,detail:c.due_at?`Due ${new Date(c.due_at).toLocaleDateString()}`:void 0}),c.completed_at?a.push({id:`fud:${c.id}`,kind:"follow_up_completed",at:c.completed_at,title:`Follow-up completed: ${c.title}`}):c.due_at&&new Date(c.due_at)d.agent_id===s.agent.id))a.push({id:`en:${c.id}`,kind:"event_note",at:c.created_at,title:`Event note — ${o(c.event_id)}`,detail:c.note});for(const c of s.scoreEvents)a.push({id:`sc:${c.id}`,kind:"score",at:c.created_at,title:`${c.points>0?"+":""}${c.points} Attract score — ${c.category}`,detail:c.description??void 0});return a.sort((c,d)=>+new Date(d.at)-+new Date(c.at))}function ucn(s,t,n){return s.shares.slice().sort((r,a)=>+new Date(a.created_at)-+new Date(r.created_at)).map(r=>{var p;const a=s.shareEvents[r.id]??[],i=a.filter(f=>f.event_type==="file_download").length,l=a.filter(f=>f.event_type==="primary_cta_click"||f.event_type==="external_link_click").length,o=a.filter(f=>f.event_type==="question_submitted").length,c=a.filter(f=>f.event_type==="meeting_requested").length,d=r.engagement_level==="high_intent"||c>0?"High Intent":r.engagement_level==="engaged"||i>0||l>0||o>0?"Engaged":r.first_opened_at?"Viewed":"Sent",u=t.followUps.filter(f=>f.agent_id===s.agent.id&&new Date(f.created_at)>=new Date(r.created_at)).sort((f,y)=>+new Date(f.created_at)-+new Date(y.created_at))[0]??null,h=s.stageChanges.filter(f=>new Date(f.created_at)>new Date(r.created_at)).sort((f,y)=>+new Date(f.created_at)-+new Date(y.created_at))[0]??null;return{share:r,kitTitle:((p=t.kits.find(f=>f.id===r.kit_id))==null?void 0:p.title)??"Resource kit",shareUrl:`${n}/attract-kit/${r.share_token}`,events:a,firstViewedAt:r.first_opened_at??null,lastViewedAt:r.last_opened_at??null,visits:r.open_count??0,downloads:i,ctaClicks:l,questions:o,meetingRequests:c,classification:d,followUp:u,stageAdvancedAfter:h}})}function hcn(s,t){const n=new Set(s.shares.map(l=>l.kit_id)),r=t.kits.filter(l=>l.status==="published"&&!n.has(l.id));if(!r.length)return null;const a=r.find(l=>l.pillar&&l.pillar===s.agent.primary_pillar);if(a)return{kit:a,why:`Matches this agent's primary pillar (${s.agent.primary_pillar}) and has not been shared yet.`};const i=r.find(l=>(l.audience??"").toLowerCase().includes("new"));return i&&s.agent.stage==="new_connection"?{kit:i,why:"They are a new connection and this kit is built for early-stage relationships."}:{kit:r[0],why:"Published, relevant, and not yet shared with this agent."}}const Fc=q;function mcn(){const{user:s}=vs();return dt({queryKey:["attract-intel-data",s==null?void 0:s.id],enabled:!!s,staleTime:3e4,queryFn:async()=>{var y,_;const[t,n,r,a,i,l,o,c,d,u,h,p]=await Promise.all([Fc.from("attract_agents").select("*").order("updated_at",{ascending:!1}),Fc.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(2e3),Fc.from("attract_follow_ups").select("*").order("created_at",{ascending:!1}).limit(2e3),Fc.from("attract_kit_shares").select("*").order("created_at",{ascending:!1}).limit(1e3),Fc.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Fc.from("attract_event_attendees").select("*").order("created_at",{ascending:!1}).limit(2e3),Fc.from("attract_events").select("id, title, starts_at, status, resource_kit_id, public_slug").limit(500),Fc.from("attract_pipeline_history").select("*").order("created_at",{ascending:!1}).limit(2e3),Fc.from("attract_score_events").select("*").order("created_at",{ascending:!1}).limit(2e3),Fc.from("attract_resource_kits").select("id, title, audience, pillar, status, is_template").eq("is_template",!1),Fc.from("attract_event_notes").select("*").order("created_at",{ascending:!1}).limit(1e3),Fc.from("attract_settings").select("primary_pillar, attraction_style, ninety_day_plan").eq("user_id",s.id).maybeSingle()]),f=[t,n,r,a,i,l,o,c,d,u,h].find(v=>v.error);if(f)throw f.error;return{agents:t.data??[],activities:n.data??[],followUps:r.data??[],shares:a.data??[],kitEvents:i.data??[],attendees:l.data??[],events:o.data??[],stageChanges:c.data??[],scoreEvents:d.data??[],kits:u.data??[],eventNotes:h.data??[],primaryPillar:((y=p==null?void 0:p.data)==null?void 0:y.primary_pillar)??((_=p==null?void 0:p.data)==null?void 0:_.attraction_style)??null}}})}function o6(){const s=mcn(),t=N.useMemo(()=>{if(!s.data)return[];const r=new Date;return s.data.agents.map(a=>{const i=rcn(a,s.data,r),l=acn(i,r),o=lcn(i,s.data,r);return{agent:a,signals:i,score:l,recommendations:o,primary:o[0]??null}})},[s.data]),n=N.useMemo(()=>new Map(t.map(r=>[r.agent.id,r])),[t]);return{...s,dataset:s.data,intel:t,byId:n}}function pcn(s){const{dataset:t,byId:n,isLoading:r,error:a,refetch:i}=o6(),l=s?n.get(s)??null:null,o=N.useMemo(()=>l&&t?dcn(l.signals,t,t.eventNotes??[]):[],[l,t]),c=N.useMemo(()=>l&&t?ucn(l.signals,t,typeof window<"u"?window.location.origin:""):[],[l,t]),d=N.useMemo(()=>l&&t?hcn(l.signals,t):null,[l,t]);return{item:l,dataset:t,timeline:o,valueShared:c,nextKit:d,isLoading:r,error:a,refetch:i}}function Hkt(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async({items:n,silent:r})=>{if(!s||!n.length)return{count:0,silent:r};const a=n.map(i=>({user_id:s.id,agent_id:i.agent.id,score:i.score.score,band:i.score.band,components:i.score.components,positives:i.score.positives,negatives:i.score.negatives,improvements:i.score.improvements,inputs:i.score.inputs,weights:i.score.weights,engine_version:$kt,calculated_at:i.score.calculated_at}));for(let i=0;i{t.invalidateQueries({queryKey:["attract-score-snapshots"]}),n&&!r&&ae.success(`Recalculated ${n} relationship score${n===1?"":"s"}`)},onError:n=>ae.error(n.message??"Could not save scores")})}function $8e(){const{user:s}=vs();return dt({queryKey:["attract-recommendations",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await Fc.from("attract_recommendations").select("*").order("rank_score",{ascending:!1});if(n)throw n;return t??[]}})}function U8e(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!s)return{inserted:0,refreshed:0};const r=n.flatMap(u=>u.recommendations),{data:a,error:i}=await Fc.from("attract_recommendations").select("id, agent_id, rec_key, status, snoozed_until");if(i)throw i;const l=new Map((a??[]).map(u=>[`${u.agent_id}|${u.rec_key}`,u])),o=[],c=[],d=new Date;for(const u of r){const h=`${u.agent_id}|${u.rec_key}`,p=l.get(h),f={user_id:s.id,agent_id:u.agent_id,rec_key:u.rec_key,signal_group:u.signal_group,action_type:u.action_type,channel:u.channel,title:u.title,reasons:u.reasons,priority:u.priority,rank_score:u.rank_score,suggested_due_at:u.suggested_due_at,draft_message:u.draft_message,message_source:u.message_source,suggested_kit_id:u.suggested_kit_id??null,suggested_event_id:u.suggested_event_id??null,source_signals:u.source_signals};p?p.status==="open"?c.push({id:p.id,patch:{...f,generated_at:d.toISOString()}}):p.status==="snoozed"&&p.snoozed_until&&new Date(p.snoozed_until)<=d&&c.push({id:p.id,patch:{...f,status:"open",snoozed_until:null,generated_at:d.toISOString()}}):o.push(f)}if(o.length){const{error:u}=await Fc.from("attract_recommendations").insert(o);if(u)throw u}for(const u of c)await Fc.from("attract_recommendations").update(u.patch).eq("id",u.id);return{inserted:o.length,refreshed:c.length}},onSuccess:()=>t.invalidateQueries({queryKey:["attract-recommendations"]}),onError:n=>ae.error(n.message??"Could not sync recommendations")})}function Gkt(){const{user:s}=vs(),t=Kt(),n=()=>{t.invalidateQueries({queryKey:["attract-recommendations"]}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]})},r=yt({mutationFn:async({id:c,patch:d})=>{const{error:u}=await Fc.from("attract_recommendations").update(d).eq("id",c);if(u)throw u},onSuccess:n,onError:c=>ae.error(c.message)}),a=yt({mutationFn:async c=>{const{error:d}=await Fc.from("attract_recommendations").update({status:"dismissed",dismissed_at:new Date().toISOString()}).eq("id",c);if(d)throw d},onSuccess:()=>{n(),ae.success("Dismissed")}}),i=yt({mutationFn:async({id:c,days:d})=>{const u=new Date(Date.now()+d*864e5).toISOString(),{error:h}=await Fc.from("attract_recommendations").update({status:"snoozed",snoozed_until:u}).eq("id",c);if(h)throw h},onSuccess:()=>{n(),ae.success("Snoozed")}}),l=yt({mutationFn:async c=>{if(c.follow_up_id){const{data:h}=await Fc.from("attract_follow_ups").select("id, completed_at").eq("id",c.follow_up_id).maybeSingle();if(h&&!h.completed_at)return{id:h.id,existed:!0}}const{data:d,error:u}=await Fc.from("attract_follow_ups").insert({user_id:s.id,agent_id:c.agent_id,title:c.title,touch_type:c.channel,due_at:c.suggested_due_at,priority:c.priority==="urgent"?"high":c.priority,notes:[c.draft_message,"","Why: "+(c.reasons??[]).join(" · ")].join(` `)}).select("id").single();if(u)throw u;return await Fc.from("attract_recommendations").update({follow_up_id:d.id}).eq("id",c.id),{id:d.id,existed:!1}},onSuccess:c=>{n(),ae.success(c.existed?"Follow-up already exists":"Follow-up created")},onError:c=>ae.error(c.message)}),o=yt({mutationFn:async({rec:c,note:d})=>{const u=new Date().toISOString(),{error:h}=await Fc.from("attract_activities").insert({user_id:s.id,agent_id:c.agent_id,activity_type:"touch_logged",title:c.title,description:d||c.draft_message,pillar:c.signal_group==="event_follow_up"?"connect":c.signal_group==="resource_follow_up"?"provide":null,metadata:{recommendation_id:c.id,channel:c.channel,rec_key:c.rec_key}});if(h)throw h;c.follow_up_id&&await Fc.from("attract_follow_ups").update({completed_at:u}).eq("id",c.follow_up_id).is("completed_at",null),await Fc.from("attract_score_events").insert({user_id:s.id,agent_id:c.agent_id,category:"follow_up",points:2,description:`Completed: ${c.title}`});const{error:p}=await Fc.from("attract_recommendations").update({status:"completed",completed_at:u}).eq("id",c.id);if(p)throw p},onSuccess:()=>{n(),t.invalidateQueries({queryKey:["attract-score"]}),ae.success("Logged — timeline and score updated")},onError:c=>ae.error(c.message)});return{update:r,dismiss:a,snooze:i,createFollowUp:l,logCompleted:o}}function fcn(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{const{error:r}=await Fc.from("attract_activities").insert({user_id:s.id,...n});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-intel-data"]}),t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-agents"]}),ae.success("Logged")},onError:n=>ae.error(n.message)})}const JJe={thriving:{label:"Thriving",ring:"ring-emerald-200",text:"text-emerald-700",bg:"bg-emerald-50"},healthy:{label:"Healthy",ring:"ring-teal-200",text:"text-teal-700",bg:"bg-teal-50"},cooling:{label:"Cooling",ring:"ring-amber-200",text:"text-amber-700",bg:"bg-amber-50"},at_risk:{label:"At risk",ring:"ring-rose-200",text:"text-rose-700",bg:"bg-rose-50"}};function q8e({score:s,className:t}){const n=JJe[s.band]??JJe.cooling;return e.jsxs(Ue,{variant:"outline",className:Mt("rounded-full gap-1.5 font-medium",n.bg,n.text,"border-transparent ring-1",n.ring,t),children:[e.jsx("span",{className:"tabular-nums font-semibold",children:s.score}),e.jsx("span",{className:"opacity-70",children:"·"}),e.jsx("span",{children:n.label})]})}function Wkt({score:s}){return e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-baseline gap-3",children:[e.jsx("div",{className:"text-4xl font-semibold tabular-nums text-slate-900",children:s.score}),e.jsx("div",{className:"text-slate-400 text-sm",children:"/ 100"}),e.jsx(q8e,{score:s})]}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:["Calculated ",new Date(s.calculated_at).toLocaleString()," · engine ",s.engine_version," · rules only, no AI guessing."]}),e.jsx("div",{className:"space-y-2.5",children:s.components.map(t=>{const n=t.weight?Math.round(t.earned/t.weight*100):0;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between text-[13px]",children:[e.jsx("span",{className:"font-medium text-slate-800",children:t.label}),e.jsxs("span",{className:"tabular-nums text-slate-500",children:[t.earned,e.jsxs("span",{className:"text-slate-300",children:["/",t.weight]})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mt-1 overflow-hidden",children:e.jsx("div",{className:Mt("h-full rounded-full transition-all",n>=70?"bg-emerald-500":n>=40?"bg-amber-400":"bg-rose-400"),style:{width:`${Math.max(n,2)}%`}})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-1 leading-snug",children:t.detail})]},t.key)})}),!!s.positives.length&&e.jsxs("div",{className:"rounded-xl bg-emerald-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-emerald-700 mb-1.5",children:[e.jsx(go,{className:"h-3.5 w-3.5"})," Helping"]}),e.jsx("ul",{className:"text-[12.5px] text-emerald-900/80 space-y-1 list-disc pl-4",children:s.positives.map((t,n)=>e.jsx("li",{children:t},n))})]}),!!s.negatives.length&&e.jsxs("div",{className:"rounded-xl bg-rose-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-rose-700 mb-1.5",children:[e.jsx(fb,{className:"h-3.5 w-3.5"})," Hurting"]}),e.jsx("ul",{className:"text-[12.5px] text-rose-900/80 space-y-1 list-disc pl-4",children:s.negatives.map((t,n)=>e.jsx("li",{children:t},n))})]}),!!s.improvements.length&&e.jsxs("div",{className:"rounded-xl bg-violet-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[11px] uppercase tracking-wider font-semibold text-violet-700 mb-1.5",children:[e.jsx(hb,{className:"h-3.5 w-3.5"})," What would improve it"]}),e.jsx("ul",{className:"text-[12.5px] text-violet-900/80 space-y-1 list-disc pl-4",children:s.improvements.map((t,n)=>e.jsx("li",{children:t},n))})]})]})}function eet({className:s}){const{intel:t}=o6(),[n,r]=N.useState(""),[a,i]=N.useState(!1),l=Ln(),o=N.useMemo(()=>{const c=n.trim().toLowerCase();return c?t.filter(d=>{const u=d.agent;return[u.first_name,u.last_name,u.brokerage,u.city,u.email,...u.tags??[]].filter(Boolean).join(" ").toLowerCase().includes(c)}).slice(0,6):[]},[t,n]);return e.jsxs("div",{className:Mt("relative",s),children:[e.jsx(gr,{className:"h-3.5 w-3.5 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx("input",{value:n,onChange:c=>{r(c.target.value),i(!0)},onFocus:()=>i(!0),onBlur:()=>setTimeout(()=>i(!1),150),placeholder:"Search relationships","aria-label":"Search relationships",className:"w-full h-9 rounded-full bg-white/5 border border-white/10 pl-9 pr-3 text-[12.5px] text-white placeholder:text-slate-500 focus:outline-none focus:ring-1 focus:ring-violet-500/60"}),a&&!!o.length&&e.jsx("div",{className:"absolute z-50 mt-1.5 w-full rounded-xl bg-white shadow-xl ring-1 ring-slate-200 overflow-hidden",children:o.map(c=>e.jsxs("button",{onMouseDown:()=>{l(`/attract/agents/${c.agent.id}`),r(""),i(!1)},className:"w-full text-left px-3 py-2.5 hover:bg-slate-50 flex items-center justify-between gap-2",children:[e.jsxs("span",{className:"min-w-0",children:[e.jsx("span",{className:"block text-[13px] font-medium text-slate-900 truncate",children:[c.agent.first_name,c.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("span",{className:"block text-[11px] text-slate-500 truncate capitalize",children:[c.agent.stage.replace(/_/g," "),c.agent.brokerage?` · ${c.agent.brokerage}`:""]})]}),e.jsx(q8e,{score:c.score})]},c.agent.id))}),a&&!!n.trim()&&!o.length&&e.jsxs("div",{className:"absolute z-50 mt-1.5 w-full rounded-xl bg-white shadow-xl ring-1 ring-slate-200 px-3 py-2.5 text-[12.5px] text-slate-500",children:['No relationships match "',n,'".']})]})}const rke=[{to:"/attract",label:"Dashboard",icon:GS,exact:!0},{to:"/attract/opportunities",label:"Opportunities",icon:IA},{to:"/attract/pipeline",label:"Agent Pipeline",icon:An},{to:"/attract/plan",label:"90-Day Plan",icon:Ac},{section:"The Four Pillars"},{to:"/attract/produce",label:"Produce",icon:go,tag:"Through Production"},{to:"/attract/influence",label:"Influence",icon:un,tag:"Through Influence"},{to:"/attract/influence/speaking",label:"Speaking Calendar",icon:Dv},{to:"/attract/provide",label:"Provide",icon:jA,tag:"Through Value"},{to:"/attract/provide/masterclasses",label:"Masterclasses",icon:yd},{to:"/attract/connect",label:"Connect",icon:uw,tag:"Through Events"},{to:"/attract/events",label:"Events",icon:uw},{section:"Systems"},{to:"/attract/follow-up",label:"Follow-Up Center",icon:lu},{to:"/attract/digest",label:"Weekly Digest",icon:Gs},{to:"/attract/resources",label:"Resources",icon:qg},{to:"/attract/templates",label:"Templates & Scripts",icon:xw},{to:"/attract/reports",label:"Reports",icon:_o},{to:"/attract/settings",label:"Settings",icon:Ko}];function xcn(){const s=Xl(),{settings:t,isLoading:n}=$U(),r=!n&&!!t&&!t.onboarding_completed_at,a=s.pathname==="/attract/onboarding";if(r&&!a&&!s.pathname.startsWith("/attract/settings"))return e.jsx(o4,{to:"/attract/onboarding",replace:!0});const l=rke.filter(o=>!("section"in o)).slice(0,5);return e.jsxs("div",{className:"attract-root min-h-screen bg-[#F7F7FB] text-slate-900",children:[e.jsx("style",{children:` .attract-root { --a-primary: 139 92 246; --a-primary-strong: 109 40 217; --a-indigo: 79 70 229; --a-teal: 20 184 166; --a-green: 22 163 74; --a-orange: 249 115 22; --a-rose: 244 63 94; } .attract-root .btn-primary { background: linear-gradient(135deg, rgb(var(--a-primary)) 0%, rgb(var(--a-indigo)) 100%); } `}),e.jsxs("div",{className:"flex min-h-screen",children:[e.jsxs("aside",{className:"hidden lg:flex w-72 flex-col bg-[#0B0F1E] text-slate-200 border-r border-white/5",children:[e.jsxs("div",{className:"px-6 py-6 border-b border-white/10",children:[e.jsxs(GO,{to:"/dashboard",className:"inline-flex items-center gap-1.5 text-[11px] uppercase tracking-widest text-slate-400 hover:text-white transition-colors",children:[e.jsx(qr,{className:"h-3 w-3"})," LevelUp Hub"]}),e.jsxs("div",{className:"mt-3 flex items-center gap-2.5",children:[e.jsx("div",{className:"h-9 w-9 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center shadow-lg shadow-violet-900/40",children:e.jsx(t4,{className:"h-4 w-4 text-white"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold tracking-tight text-white",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10.5px] text-slate-400 leading-tight",children:"Attract through value. Grow through relationships."})]})]})]}),e.jsx("div",{className:"px-4 pt-3",children:e.jsx(eet,{})}),e.jsx("nav",{className:"flex-1 overflow-y-auto py-3 px-3",children:rke.map((o,c)=>{if("section"in o)return e.jsx("div",{className:"px-3 mt-5 mb-1.5 text-[10px] uppercase tracking-[0.14em] text-slate-500 font-semibold",children:o.section},c);const d=o.icon;return e.jsxs(GO,{to:o.to,end:o.exact,className:({isActive:u})=>Mt("group flex items-center gap-3 px-3 py-2.5 rounded-xl text-[13.5px] font-medium transition-all",u?"bg-gradient-to-r from-violet-600/30 to-indigo-600/10 text-white ring-1 ring-inset ring-violet-500/40":"text-slate-300 hover:bg-white/5 hover:text-white"),children:[e.jsx(d,{className:"h-4 w-4 flex-shrink-0 opacity-80 group-hover:opacity-100"}),e.jsx("span",{className:"flex-1",children:o.label}),o.tag&&e.jsx("span",{className:"text-[9.5px] uppercase tracking-wider text-slate-500 group-hover:text-slate-400",children:o.tag})]},o.to)})}),e.jsx("div",{className:"px-4 py-4 border-t border-white/5",children:e.jsxs("div",{className:"rounded-xl bg-white/5 p-3",children:[e.jsx("div",{className:"text-[11px] font-medium text-violet-300",children:"Beta preview"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 mt-1 leading-snug",children:"Build relationships first. Personalize every message and verify brokerage and compensation info before sharing."})]})})]}),e.jsxs("div",{className:"lg:hidden fixed top-0 inset-x-0 z-40 bg-[#0B0F1E] text-white px-4 py-3 flex items-center gap-3 border-b border-white/10",children:[e.jsx(GO,{to:"/dashboard",className:"text-slate-400",children:e.jsx(qr,{className:"h-4 w-4"})}),e.jsx("div",{className:"h-8 w-8 rounded-lg bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center",children:e.jsx(t4,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold tracking-tight",children:"LEVELUP ATTRACT"}),e.jsx("div",{className:"text-[10px] text-slate-400",children:"Attract through value"})]})]}),e.jsxs("div",{className:"lg:hidden fixed bottom-0 inset-x-0 z-40 bg-[#0B0F1E]/95 backdrop-blur border-t border-white/10 flex",children:[l.map(o=>{const c=o.icon;return e.jsxs(GO,{to:o.to,end:o.exact,className:({isActive:d})=>Mt("flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px]",d?"text-white":"text-slate-400"),children:[e.jsx(c,{className:"h-4 w-4"}),e.jsx("span",{className:"truncate max-w-[70px]",children:o.label})]},o.to)}),e.jsxs(t0,{children:[e.jsx(Y$,{asChild:!0,children:e.jsxs("button",{className:"flex-1 min-w-0 flex flex-col items-center gap-1 py-2 text-[10px] text-slate-400",children:[e.jsx(Kf,{className:"h-4 w-4"}),e.jsx("span",{children:"More"})]})}),e.jsx(og,{side:"bottom",className:"bg-[#0B0F1E] text-slate-200 border-white/10 rounded-t-3xl max-h-[75vh] overflow-y-auto",children:e.jsxs("div",{className:"pt-4 pb-8",children:[e.jsx(eet,{className:"mb-4"}),e.jsx("div",{className:"text-[10px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"All sections"}),rke.map((o,c)=>{if("section"in o)return e.jsx("div",{className:"mt-4 mb-1 text-[10px] uppercase tracking-widest text-slate-500 font-semibold",children:o.section},c);const d=o.icon;return e.jsxs(GO,{to:o.to,end:o.exact,className:({isActive:u})=>Mt("flex items-center gap-3 rounded-xl px-3 py-3 text-[13.5px] font-medium",u?"bg-violet-600/30 text-white":"text-slate-300 hover:bg-white/5"),children:[e.jsx(d,{className:"h-4 w-4 opacity-80"}),e.jsx("span",{children:o.label})]},o.to)})]})})]})]}),e.jsx("main",{className:"flex-1 min-w-0 pt-16 lg:pt-0 pb-24 lg:pb-0",children:e.jsx("div",{className:"max-w-[1400px] mx-auto px-4 sm:px-6 lg:px-10 py-6 lg:py-10",children:e.jsx(lat,{})},s.pathname)})]})]})}function OF({label:s,value:t,delta:n,icon:r,tone:a="violet"}){const i={violet:"from-violet-500 to-indigo-600",teal:"from-teal-500 to-cyan-600",green:"from-emerald-500 to-green-600",orange:"from-orange-500 to-amber-600",rose:"from-rose-500 to-pink-600"};return e.jsx(fe,{className:"p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-slate-500",children:s}),e.jsx("div",{className:"mt-2 text-[26px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsxs("div",{className:"mt-1 text-[11.5px] font-medium text-emerald-600 flex items-center gap-1",children:[e.jsx(GP,{className:"h-3 w-3"}),n]})]}),e.jsx("div",{className:Mt("h-10 w-10 rounded-xl bg-gradient-to-br grid place-items-center shadow-sm",i[a]),children:e.jsx(r,{className:"h-5 w-5 text-white"})})]})})}function gcn(){const{user:s}=vs();return dt({queryKey:["attract-score",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_score_events").select("category, points, description, created_at");if(n)throw n;const r=t??[],a=r.reduce((l,o)=>l+(o.points??0),0),i={};for(const l of r)i[l.category]=(i[l.category]??0)+l.points;return{total:Math.min(a,100),rows:r,byCategory:i}}})}const ycn=[{key:"relationships_added",label:"Relationships Added",icon:q0,target:15},{key:"follow_ups_completed",label:"Follow-Ups Completed",icon:vr,target:15},{key:"resources_shared",label:"Resources Shared",icon:Vl,target:15},{key:"content_posted",label:"Agent Content Posted",icon:zd,target:15},{key:"events_connections",label:"Events / Connections",icon:uw,target:20},{key:"brokerage_conversations",label:"Brokerage Conversations",icon:oL,target:20}];function vcn(){const{data:s}=gcn(),t=(s==null?void 0:s.total)??0,n=(s==null?void 0:s.byCategory)??{},r=2*Math.PI*54,a=t/100*r;return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Your Attract Score"}),e.jsx("div",{className:"text-[19px] font-semibold text-slate-900 mt-1",children:"Great progress! Keep building relationships and providing value."})]}),e.jsx(go,{className:"h-5 w-5 text-violet-500"})]}),e.jsxs("div",{className:"flex items-center gap-6 flex-col sm:flex-row",children:[e.jsxs("div",{className:"relative h-36 w-36 flex-shrink-0",children:[e.jsxs("svg",{viewBox:"0 0 120 120",className:"h-full w-full -rotate-90",children:[e.jsx("defs",{children:e.jsxs("linearGradient",{id:"attract-score",x1:"0",x2:"1",y1:"0",y2:"1",children:[e.jsx("stop",{offset:"0%",stopColor:"rgb(139 92 246)"}),e.jsx("stop",{offset:"100%",stopColor:"rgb(79 70 229)"})]})}),e.jsx("circle",{cx:"60",cy:"60",r:"54",stroke:"rgb(226 232 240)",strokeWidth:"10",fill:"none"}),e.jsx("circle",{cx:"60",cy:"60",r:"54",stroke:"url(#attract-score)",strokeWidth:"10",fill:"none",strokeLinecap:"round",strokeDasharray:`${a} ${r}`,style:{transition:"stroke-dasharray 800ms ease"}})]}),e.jsxs("div",{className:"absolute inset-0 grid place-items-center flex-col text-center",children:[e.jsxs("div",{className:"flex items-baseline gap-1",children:[e.jsx("span",{className:"text-4xl font-semibold tracking-tight text-slate-900",children:t}),e.jsx("span",{className:"text-sm text-slate-500 font-medium",children:"/100"})]}),e.jsx("div",{className:"text-[10px] uppercase tracking-wider text-slate-400",children:"this cycle"})]})]}),e.jsx("div",{className:"flex-1 space-y-2 w-full",children:ycn.map(i=>{const l=n[i.key]??0,o=Math.min(100,Math.round(l/i.target*100)),c=i.icon;return e.jsxs("div",{className:"grid grid-cols-[16px_1fr_60px_auto] items-center gap-2.5",children:[e.jsx(c,{className:"h-4 w-4 text-slate-500"}),e.jsx("span",{className:"text-[12.5px] text-slate-700 truncate",children:i.label}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500",style:{width:`${o}%`}})}),e.jsx("span",{className:"text-[11px] tabular-nums text-slate-500 font-medium w-8 text-right",children:l})]},i.key)})})]}),e.jsx("div",{className:"mt-5 flex justify-end",children:e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",children:"View Score Breakdown"})})]})}const FF=q;function i0(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:["attract-agents",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:d,error:u}=await q.from("attract_agents").select("*").order("updated_at",{ascending:!1});if(u)throw u;return d??[]}}),r=()=>{["attract-agents","attract-intel","attract-intelligence","attract-agent-intel","attract-activities","attract-followups","attract-recommendations","attract-score","attract_milestones","attract-daily-plan"].forEach(d=>t.invalidateQueries({queryKey:[d]}))},a=yt({mutationFn:async d=>{const u={...d,user_id:s.id},{data:h,error:p}=d.id?await q.from("attract_agents").update(u).eq("id",d.id).select().single():await q.from("attract_agents").insert(u).select().single();if(p)throw p;return h},onSuccess:()=>{r(),ae.success("Saved")},onError:d=>ae.error(d.message)}),i=yt({mutationFn:async({id:d,to_stage:u,from_stage:h})=>{const{error:p}=await q.from("attract_agents").update({stage:u}).eq("id",d);if(p)throw p;await q.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:h??null,to_stage:u})},onSuccess:()=>r(),onError:d=>ae.error(d.message)}),l=yt({mutationFn:async({id:d,values:u,changedLabels:h,previousStage:p})=>{const{stage:f,...y}=u;if(Object.keys(y).length){const{error:_}=await FF.from("attract_agents").update(y).eq("id",d);if(_)throw _}if(f&&f!==p){const{error:_}=await FF.from("attract_agents").update({stage:f}).eq("id",d);if(_)throw _;await FF.from("attract_pipeline_history").insert({user_id:s.id,agent_id:d,from_stage:p??null,to_stage:f})}h.length&&await FF.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"note",_title:"Contact details updated",_description:`Updated: ${h.join(", ")}`,_pillar:"connect",_agent_id:d,_metadata:{},_dedupe_minutes:1})},onSuccess:()=>{r(),ae.success("Contact updated")},onError:d=>ae.error(d.message??"Could not save contact")}),o=yt({mutationFn:async({id:d,archived:u})=>{const{error:h}=await FF.from("attract_agents").update({is_archived:u}).eq("id",d);if(h)throw h},onSuccess:(d,u)=>{r(),ae.success(u.archived?"Removed from active pipeline":"Restored to pipeline")},onError:d=>ae.error(d.message)}),c=yt({mutationFn:async d=>{const{error:u}=await q.from("attract_agents").delete().eq("id",d);if(u)throw u},onSuccess:()=>{r(),ae.success("Contact permanently deleted")},onError:d=>ae.error(d.message)});return{agents:n.data??[],activeAgents:(n.data??[]).filter(d=>!d.is_archived),isLoading:n.isLoading,upsertAgent:a,saveAgentDetails:l,moveStage:i,archiveAgent:o,deleteAgent:c}}const ake=[{key:"new_connection",label:"New Connection"},{key:"building_relationship",label:"Building Relationship"},{key:"engaging_with_value",label:"Engaging With Value"},{key:"active_conversation",label:"Active Conversation"},{key:"exploring_options",label:"Exploring Options"},{key:"brokerage_presentation",label:"Brokerage Presentation"},{key:"decision_pending",label:"Decision Pending"},{key:"joined",label:"Joined"}];function bcn(){const{agents:s}=i0(),t=Math.max(1,...ake.map(n=>s.filter(r=>r.stage===n.key).length));return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-5",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Pipeline Overview"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Where relationships live right now"})]}),e.jsx(B,{asChild:!0,variant:"outline",size:"sm",className:"rounded-full gap-1",children:e.jsxs(In,{to:"/attract/pipeline",children:["View Full Pipeline ",e.jsx(ga,{className:"h-3.5 w-3.5"})]})})]}),e.jsx("div",{className:"space-y-2",children:ake.map((n,r)=>{const a=s.filter(o=>o.stage===n.key).length,i=30+a/t*70,l=.35+(1-r/ake.length)*.55;return e.jsxs("div",{className:"grid grid-cols-[180px_1fr_36px] items-center gap-3",children:[e.jsx("span",{className:"text-[12.5px] text-slate-700 font-medium",children:n.label}),e.jsx("div",{className:"h-8 rounded-lg bg-slate-50 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-lg flex items-center justify-end pr-3 text-white text-[11.5px] font-semibold",style:{width:`${i}%`,background:`linear-gradient(90deg, rgba(139,92,246,${l}) 0%, rgba(79,70,229,${l}) 100%)`},children:a>0&&a})}),e.jsx("span",{className:"text-[11px] tabular-nums text-slate-500 text-right",children:a})]},n.key)})})]})}function _cn(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:["attract-daily-plan",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_daily_plan").select("*").order("sort_order");if(i)throw i;return a??[]}}),r=yt({mutationFn:async a=>{const i=!a.completed,{error:l}=await q.from("attract_daily_plan").update({completed:i,progress:i?a.target:0}).eq("id",a.id);if(l)throw l},onSuccess:()=>t.invalidateQueries({queryKey:["attract-daily-plan"]})});return{items:n.data??[],isLoading:n.isLoading,toggle:r}}function Kkt(s=!0){const{intel:t,isLoading:n}=o6(),r=Hkt(),a=U8e(),i=N.useRef(!1);return N.useEffect(()=>{if(!s||n||i.current||!t.length)return;const o=sessionStorage.getItem("attract-intel-sync"),c=new Date().toISOString().slice(0,13);if(o===c){i.current=!0;return}i.current=!0,sessionStorage.setItem("attract-intel-sync",c),r.mutate({items:t,silent:!0}),a.mutate(t)},[s,n,t]),{runNow:()=>{r.mutate({items:t}),a.mutate(t)},isSyncing:r.isPending||a.isPending}}function wcn(){const{items:s,toggle:t}=_cn(),{data:n=[]}=$8e(),{byId:r}=o6(),{logCompleted:a}=Gkt();Kkt();const i=s.filter(u=>u.completed).length,l=s.length?Math.round(i/s.length*100):0,o=Date.now(),c=n.filter(u=>u.status==="open"||u.status==="snoozed"&&u.snoozed_until&&+new Date(u.snoozed_until)<=o).sort((u,h)=>h.rank_score-u.rank_score).slice(0,3),d=u=>{var p;const h=(p=r.get(u))==null?void 0:p.agent;return h?[h.first_name,h.last_name].filter(Boolean).join(" "):"this relationship"};return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Today's Attraction Plan"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small daily reps compound."})]}),e.jsxs("div",{className:"text-right",children:[e.jsxs("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:[i,e.jsxs("span",{className:"text-slate-400 text-base",children:["/",s.length]})]}),e.jsx("div",{className:"text-[11px] text-slate-500 uppercase tracking-wider",children:"complete"})]})]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-100 mb-4 overflow-hidden",children:e.jsx("div",{className:"h-full rounded-full bg-gradient-to-r from-violet-500 to-indigo-500 transition-all",style:{width:`${l}%`}})}),e.jsx("ul",{className:"space-y-1.5",children:s.map(u=>e.jsxs("li",{onClick:()=>t.mutate(u),className:"group flex items-center gap-3 px-3 py-2.5 rounded-xl hover:bg-slate-50 cursor-pointer transition-colors",children:[e.jsx(hi,{checked:u.completed,className:"border-slate-300 data-[state=checked]:bg-violet-600 data-[state=checked]:border-violet-600"}),e.jsx("span",{className:`flex-1 text-[13.5px] ${u.completed?"line-through text-slate-400":"text-slate-800"}`,children:u.label}),e.jsxs("span",{className:"text-[11px] tabular-nums text-slate-400",children:[u.progress,"/",u.target]}),u.completed&&e.jsx(vr,{className:"h-4 w-4 text-emerald-500"})]},u.id))}),e.jsxs("div",{className:"mt-5 pt-5 border-t border-slate-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2.5",children:"Who to reach today"}),c.length?e.jsx("ul",{className:"space-y-2",children:c.map(u=>e.jsx("li",{className:"rounded-xl bg-slate-50 px-3 py-2.5",children:e.jsxs("div",{className:"flex items-start justify-between gap-2 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx(In,{to:`/attract/agents/${u.agent_id}`,className:"text-[13.5px] font-medium text-slate-900 hover:text-violet-700",children:d(u.agent_id)}),e.jsx("div",{className:"text-[12px] text-slate-600 mt-0.5",children:u.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:(u.reasons??[]).slice(0,2).join(" · ")})]}),e.jsxs("div",{className:"flex items-center gap-1.5",children:[e.jsx(Ue,{variant:"outline",className:Mt("rounded-full text-[10.5px] capitalize",u.priority==="urgent"&&"bg-rose-50 text-rose-700 border-rose-200"),children:u.priority}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full h-7 px-2 text-[11.5px]",onClick:()=>a.mutate({rec:u}),disabled:a.isPending,children:"Done"})]})]})},u.id))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No recommendations right now — Attract only surfaces conversations backed by a real signal."})]}),e.jsxs("div",{className:"mt-4 flex justify-end gap-2",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsxs(In,{to:"/attract/opportunities",children:["All opportunities ",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1.5"})]})}),e.jsx(B,{variant:"ghost",size:"sm",className:"text-violet-700 hover:text-violet-900",asChild:!0,children:e.jsx(In,{to:"/attract/plan",children:"View full plan"})})]})]})}function Ykt(s=12){const{user:t}=vs(),n=dt({queryKey:["attract-activities",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_activities").select("*").order("created_at",{ascending:!1}).limit(s);if(a)throw a;return r??[]}});return{activities:n.data??[],isLoading:n.isLoading}}const jcn={agent_joined:un,resource_shared:Vl,presentation:ny,conversation:oL,social_engagement:gi,new_agent:Fo,content_posted:zd,follow_up:lu};function Ncn(){const{activities:s}=Ykt(8);return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Recent Activity"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Momentum from the past few days"})]}),e.jsxs("ol",{className:"relative space-y-4",children:[s.map(t=>{const n=jcn[t.activity_type]??un;return e.jsxs("li",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-8 w-8 rounded-full bg-violet-50 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx(n,{className:"h-4 w-4 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:t.title}),t.description&&e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:t.description}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-0.5",children:[Uo(new Date(t.created_at),{addSuffix:!0}),t.pillar&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:t.pillar})]})]})]})]},t.id)}),s.length===0&&e.jsx("li",{className:"text-sm text-slate-500 text-center py-6",children:"No activity yet — start with one small touch today."})]})]})}function K1e(s){const{user:t}=vs();return dt({queryKey:["attract-events",t==null?void 0:t.id,s],enabled:!!t,queryFn:async()=>{let n=q.from("attract_events").select("*").eq("is_template",!1).order("starts_at",{ascending:!0});const{data:r,error:a}=await n;if(a)throw a;return r??[]}})}function V8e(s){return dt({queryKey:["attract-event",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_events").select("*").eq("id",s).single();if(n)throw n;return t}})}function Zkt(s){return dt({queryKey:["attract-event-attendees",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_attendees").select("*, attract_agents(id, first_name, last_name, primary_pillar, stage)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function kcn(s){return dt({queryKey:["attract-event-invitations",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_invitations").select("*, attract_agents(id, first_name, last_name)").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Scn(s){return dt({queryKey:["attract-event-notes",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_event_notes").select("*").eq("event_id",s).order("created_at",{ascending:!1});if(n)throw n;return t??[]}})}function Qkt(){return dt({queryKey:["attract-event-templates"],queryFn:async()=>{const{data:s,error:t}=await q.from("attract_event_templates").select("*").order("title");if(t)throw t;return s??[]}})}function Xkt(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,title:n.title||"Untitled event",starts_at:n.starts_at||new Date(Date.now()+7*864e5).toISOString(),status:"draft",...n},{data:a,error:i}=await q.from("attract_events").insert(r).select().single();if(i)throw i;return a},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function Jkt(){const s=Kt();return yt({mutationFn:async({id:t,patch:n})=>{const{data:r,error:a}=await q.from("attract_events").update(n).eq("id",t).select().single();if(a)throw a;return r},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-events"]}),s.invalidateQueries({queryKey:["attract-event",t.id]})}})}function Ccn(){const s=Kt();return yt({mutationFn:async t=>{const{error:n}=await q.from("attract_events").delete().eq("id",t);if(n)throw n},onSuccess:()=>s.invalidateQueries({queryKey:["attract-events"]})})}function eSt(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const r={user_id:s.id,...n},{data:a,error:i}=n.id?await q.from("attract_event_attendees").update(r).eq("id",n.id).select().single():await q.from("attract_event_attendees").insert(r).select().single();if(i)throw i;return a},onSuccess:n=>{t.invalidateQueries({queryKey:["attract-event-attendees",n.event_id]}),t.invalidateQueries({queryKey:["attract-event",n.event_id]})}})}function Tcn(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_notes").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-notes",n.event_id]})})}function Ecn(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_event_invitations").insert({user_id:s.id,...n}).select().single();if(a)throw a;return r},onSuccess:n=>t.invalidateQueries({queryKey:["attract-event-invitations",n.event_id]})})}function Acn(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!s)throw new Error("Not authenticated");const{data:r,error:a}=await q.from("attract_events").select("*").eq("id",n).single();if(a)throw a;const{id:i,public_slug:l,check_in_token:o,published_at:c,registration_count:d,attendance_count:u,created_at:h,updated_at:p,...f}=r,{data:y,error:_}=await q.from("attract_events").insert({...f,title:r.title+" (Copy)",status:"draft"}).select().single();if(_)throw _;return y},onSuccess:()=>t.invalidateQueries({queryKey:["attract-events"]})})}function Y1e(s){return`${window.location.origin}/attract-event/${s}`}function Mcn(s,t){return`${window.location.origin}/attract-event-checkin/${s}?a=${encodeURIComponent(t)}`}function tSt(s){const t=l=>l.toISOString().replace(/[-:]/g,"").replace(/\.\d{3}/,""),n=new Date(s.starts_at),r=s.ends_at?new Date(s.ends_at):new Date(n.getTime()+60*60*1e3),a=[s.location,s.address,s.virtual_url].filter(Boolean).join(" — ");return["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//EN","BEGIN:VEVENT",`UID:${`${Date.now()}@attract.levelup`}`,`DTSTAMP:${t(new Date)}`,`DTSTART:${t(n)}`,`DTEND:${t(r)}`,`SUMMARY:${(s.title||"").replace(/\n/g," ")}`,`DESCRIPTION:${(s.description||"").replace(/\n/g,"\\n")}`,`LOCATION:${a.replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `)}function Icn(){const{data:s=[]}=K1e(),t=s.slice(0,3);return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Upcoming Events"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Places where relationships happen"})]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full gap-1",children:[e.jsx(Is,{className:"h-3.5 w-3.5"})," Create"]})]}),e.jsxs("div",{className:"space-y-3",children:[t.map(n=>{var i,l;const r=new Date(n.starts_at),a=((l=(i=n.attract_event_attendees)==null?void 0:i[0])==null?void 0:l.count)??0;return e.jsxs("div",{className:"flex items-center gap-4 p-3 rounded-xl hover:bg-slate-50 transition-colors",children:[e.jsxs("div",{className:"w-14 flex-shrink-0 text-center rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 text-white py-2",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider opacity-90",children:Ss(r,"MMM")}),e.jsx("div",{className:"text-xl font-semibold leading-tight",children:Ss(r,"d")})]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 truncate",children:n.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 flex items-center gap-2 mt-0.5",children:[e.jsx("span",{children:Ss(r,"p")}),"·",n.event_type==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fr,{className:"h-3 w-3"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1 truncate",children:[e.jsx(ka,{className:"h-3 w-3"})," ",n.location]})]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:a}),e.jsx("div",{className:"text-[10px] text-slate-400 uppercase tracking-wider",children:"RSVPs"})]})]},n.id)}),t.length===0&&e.jsxs("div",{className:"text-center py-8 text-slate-500",children:[e.jsx(uw,{className:"h-6 w-6 mx-auto text-slate-300 mb-2"}),e.jsx("div",{className:"text-sm",children:"No upcoming events yet."})]})]})]})}function sSt(){const{user:s}=vs(),t=dt({queryKey:["attract-resources",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resources").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}}),n=dt({queryKey:["attract-resource-shares",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:r,error:a}=await q.from("attract_resource_shares").select("*").order("created_at",{ascending:!1});if(a)throw a;return r??[]}});return{resources:t.data??[],shares:n.data??[],isLoading:t.isLoading}}function Pcn(){const{shares:s}=sSt(),t={resources:s.length,emails:s.filter(r=>r.channel==="email").length,opens:s.filter(r=>r.opened_at).length,clicks:s.filter(r=>r.clicked_at).length},n=[{label:"Resources Shared",value:t.resources,icon:Vl,tone:"text-violet-600 bg-violet-50"},{label:"Emails Sent",value:t.emails,icon:lr,tone:"text-teal-600 bg-teal-50"},{label:"Agent Opens",value:t.opens,icon:nL,tone:"text-emerald-600 bg-emerald-50"},{label:"Clicks",value:t.clicks,icon:oc,tone:"text-orange-600 bg-orange-50"}];return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"mb-4",children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Value Shared This Week"}),e.jsx("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:"Small gifts, measured."})]}),e.jsx("div",{className:"grid grid-cols-2 gap-3",children:n.map(r=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3.5",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${r.tone}`,children:e.jsx(r.icon,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900 mt-2 leading-none",children:r.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-1",children:r.label})]},r.label))})]})}function Lcn(){const{agents:s}=i0(),t=s.filter(r=>r.stage==="joined").sort((r,a)=>(a.joined_at??"").localeCompare(r.joined_at??"")),n=t.reduce((r,a)=>r+(Number(a.est_revenue_share)||0),0);return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200/70 bg-white shadow-sm",children:[e.jsxs("div",{className:"flex items-start justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Agents Joined"}),e.jsxs("div",{className:"text-[18px] font-semibold text-slate-900 mt-0.5",children:["Est. annual rev share ",e.jsx("span",{className:"text-violet-700",children:jc(n)})]})]}),e.jsx(un,{className:"h-5 w-5 text-violet-500"})]}),e.jsxs("ul",{className:"space-y-2.5",children:[t.map(r=>{var a;return e.jsxs("li",{className:"flex items-center gap-3 p-2.5 rounded-xl hover:bg-slate-50",children:[e.jsxs("div",{className:"h-9 w-9 rounded-full bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center text-[13px] font-semibold flex-shrink-0",children:[r.first_name[0],((a=r.last_name)==null?void 0:a[0])??""]}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[r.first_name," ",r.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 truncate",children:[r.brokerage," · ",r.city,", ",r.state]})]}),e.jsxs("div",{className:"text-right",children:[e.jsx("div",{className:"text-[13px] font-semibold text-emerald-600 tabular-nums",children:r.est_revenue_share?jc(Number(r.est_revenue_share)):"—"}),e.jsx("div",{className:"text-[10.5px] text-slate-400",children:r.joined_at?Uo(new Date(r.joined_at),{addSuffix:!0}):""})]})]},r.id)}),t.length===0&&e.jsx("li",{className:"text-sm text-slate-500 text-center py-6",children:"No joined agents yet."})]})]})}function UU(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:["attract-followups",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await q.from("attract_follow_ups").select("*").order("due_at",{ascending:!0,nullsFirst:!1});if(i)throw i;return a??[]}}),r=yt({mutationFn:async a=>{const{error:i}=await q.from("attract_follow_ups").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>t.invalidateQueries({queryKey:["attract-followups"]})});return{followUps:n.data??[],isLoading:n.isLoading,complete:r}}function Dcn(s){var r;const t=(s==null?void 0:s.user_metadata)??{},n=t.full_name||t.name||((r=s==null?void 0:s.email)==null?void 0:r.split("@")[0])||"there";return String(n).split(" ")[0]}const tet={produce:{label:"Your primary pillar is Produce — log one recent transaction today.",cta:"Open Transaction Tracker",to:"/attract/produce/transaction-tracker"},influence:{label:"Your primary pillar is Influence — create one authority post today.",cta:"Open Content Studio",to:"/attract/influence/content-studio"},provide:{label:"Your primary pillar is Provide — share one resource with an agent today.",cta:"Open Resources",to:"/attract/resources"},connect:{label:"Your primary pillar is Connect — schedule one 1:1 this week.",cta:"Open Follow-Up Center",to:"/attract/follow-up"},balanced:{label:"Balanced plan — pick one pillar for today and go deep.",cta:"View 90-Day Plan",to:"/attract/plan"}};function Rcn(){const{user:s}=vs(),t=Ln(),{agents:n}=i0(),{followUps:r}=UU(),{settings:a}=$U();N.useState(!1);const i=N.useMemo(()=>{const d=wf(new Date),u=n.filter(v=>!["joined","not_a_fit","not_right_now"].includes(v.stage)).length,h=n.filter(v=>new Date(v.created_at)>Bl(d,-30)).length,p=r.filter(v=>!v.completed_at&&v.due_at&&ql(new Date(v.due_at),d)).length,f=r.filter(v=>!v.completed_at&&v.due_at&&yb(new Date(v.due_at),d)).length,_=n.filter(v=>v.stage==="joined").reduce((v,j)=>v+(Number(j.est_revenue_share)||0),0);return{inPipeline:u,newRels:h,dueToday:p,overdue:f,revShare:_}},[n,r]),l=(a==null?void 0:a.primary_pillar)||(a==null?void 0:a.attraction_style)||"balanced",o=tet[l]??tet.balanced,c=a==null?void 0:a.ninety_day_plan;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4 mb-8",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"LevelUp Attract"}),e.jsxs("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:["Good to see you, ",Dcn(s),"."]}),e.jsxs("p",{className:"text-slate-600 mt-1.5",children:["Here's your attraction overview for today · ",Ss(new Date,"EEEE, MMM d")]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(us,{defaultValue:"week",children:[e.jsx(ls,{className:"w-[150px] rounded-full bg-white",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"week",children:"This Week"}),e.jsx(Ze,{value:"month",children:"This Month"}),e.jsx(Ze,{value:"90",children:"Last 90 Days"})]})]}),e.jsx(B,{variant:"outline",size:"icon",className:"rounded-full",children:e.jsx(nm,{className:"h-4 w-4"})}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700 gap-1.5 shadow-sm",children:[e.jsx(Is,{className:"h-4 w-4"})," Add New ",e.jsx(ao,{className:"h-3.5 w-3.5 opacity-70"})]})}),e.jsxs(gc,{align:"end",className:"w-64",children:[e.jsx(cM,{children:"Quick add"}),e.jsx(Kg,{}),e.jsxs(Kr,{onClick:()=>t("/attract/pipeline?new=1"),children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"})," Add Agent to Pipeline"]}),e.jsxs(Kr,{onClick:()=>t("/attract/produce/transaction-tracker"),children:[e.jsx(oa,{className:"h-4 w-4 mr-2"})," Log a Transaction"]}),e.jsxs(Kr,{onClick:()=>t("/attract/influence/content-studio"),children:[e.jsx(Im,{className:"h-4 w-4 mr-2"})," Create Authority Content"]}),e.jsxs(Kr,{onClick:()=>t("/attract/follow-up"),children:[e.jsx(lu,{className:"h-4 w-4 mr-2"})," Add Follow-Up"]}),e.jsxs(Kr,{onClick:()=>t("/attract/events/new"),children:[e.jsx(Lg,{className:"h-4 w-4 mr-2"})," Plan an Event"]}),e.jsxs(Kr,{onClick:()=>t("/attract/resources"),children:[e.jsx(qg,{className:"h-4 w-4 mr-2"})," Add Resource"]})]})]})]})]}),e.jsx(fe,{className:"p-4 rounded-2xl mb-6 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:e.jsxs("div",{className:"flex items-center gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-white grid place-items-center text-violet-700 shadow-sm",children:e.jsx(Ac,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:"Today's move"}),e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:o.label}),c&&e.jsxs("div",{className:"text-[12px] text-slate-600 mt-0.5",children:["Weekly goal: ",c.weekly_targets.new_relationships," new relationships · ",c.weekly_targets.content_pieces," content pieces"]})]}),e.jsx(B,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>t(o.to),children:o.cta})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 xl:grid-cols-5 gap-4 mb-6",children:[e.jsx(OF,{label:"Agents in Pipeline",value:i.inPipeline,delta:"+3 this week",icon:q0,tone:"violet"}),e.jsx(OF,{label:"New Relationships",value:i.newRels,delta:"+2 this week",icon:go,tone:"teal"}),e.jsx(OF,{label:"Follow-Ups Due Today",value:i.dueToday,icon:$7,tone:"orange"}),e.jsx(OF,{label:"Overdue Follow-Ups",value:i.overdue,icon:ic,tone:"rose"}),e.jsx(OF,{label:"Est. Revenue Share",value:jc(i.revShare,!0),delta:"annualized",icon:Yl,tone:"green"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs("div",{className:"xl:col-span-2 space-y-6",children:[e.jsx(vcn,{}),e.jsx(bcn,{}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-6",children:[e.jsx(Ncn,{}),e.jsx(Icn,{})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(wcn,{}),e.jsx(Pcn,{}),e.jsx(Lcn,{})]})]}),e.jsx("div",{className:"mt-8 rounded-2xl overflow-hidden bg-gradient-to-r from-violet-600 via-indigo-600 to-violet-700 p-6 md:p-7 text-white shadow-lg",children:e.jsxs("div",{className:"flex items-center justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80 mb-1",children:"Your 90-day promise"}),e.jsx("div",{className:"text-lg md:text-xl font-semibold",children:(c==null?void 0:c.outcome)??"Show up for agents the way you'd want someone to show up for you."}),e.jsx("div",{className:"text-white/80 mt-1 text-[13.5px]",children:"Small daily reps compound. Keep the rhythm."})]}),e.jsx(B,{asChild:!0,variant:"secondary",className:"rounded-full bg-white text-violet-700 hover:bg-white/90",children:e.jsx(In,{to:"/attract/plan",children:"View 90-Day Plan"})})]})})]})}function zu({eyebrow:s,title:t,description:n,actions:r,className:a}){return e.jsxs("div",{className:Mt("flex flex-col md:flex-row md:items-end md:justify-between gap-4 mb-8",a),children:[e.jsxs("div",{children:[s&&e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:s}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:t}),n&&e.jsx("p",{className:"text-slate-600 mt-2 max-w-2xl",children:n})]}),r&&e.jsx("div",{className:"flex items-center gap-2 flex-wrap",children:r})]})}function l6(){return e.jsxs("div",{className:"rounded-2xl border border-violet-200 bg-violet-50/60 px-5 py-3.5 text-[13px] text-violet-900 flex items-start gap-3",children:[e.jsx("div",{className:"h-6 w-6 rounded-full bg-violet-600 grid place-items-center flex-shrink-0 mt-0.5",children:e.jsx("span",{className:"text-white text-[11px] font-bold",children:"✓"})}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"Build relationships first."})," ","Personalize every message and verify brokerage and compensation information before sharing."]})]})}const Ocn=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined","long_term_relationship","not_right_now","not_a_fit"],Fcn={first_name:"first name",last_name:"last name",preferred_name:"preferred name",email:"email",phone:"phone",website_url:"website",instagram_url:"Instagram",linkedin_url:"LinkedIn",facebook_url:"Facebook",other_url:"other link",brokerage:"brokerage",team_name:"team",city:"city",state:"state",postal_code:"ZIP",market_area:"market area",source:"source",relationship_owner:"relationship owner",stage:"stage",temperature:"temperature",primary_pillar:"primary pillar",tags:"tags",goals:"goals",challenges:"challenges",interests:"interests",production_context:"production context",notes:"notes",birthday_on:"birthday",work_anniversary_on:"work anniversary",license_anniversary_on:"license anniversary",next_follow_up_at:"next follow-up",photo_url:"photo"},mp=s=>typeof s=="string"&&s.trim()===""?null:s,VI=s=>{const t=s.trim();return t?/^https?:\/\//i.test(t)?t:`https://${t}`:null},zcn=s=>{const t=s.trim();if(!t)return null;const n=t.replace(/[^\d]/g,"");return n.length===10?`(${n.slice(0,3)}) ${n.slice(3,6)}-${n.slice(6)}`:t},zF=s=>(s??"").replace(/[^\d]/g,""),Bcn=s=>/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s.trim()),zG=s=>s?String(s).slice(0,10):"";function set(s){return{first_name:s.first_name??"",last_name:s.last_name??"",preferred_name:s.preferred_name??"",email:s.email??"",phone:s.phone??"",website_url:s.website_url??"",instagram_url:s.instagram_url??"",linkedin_url:s.linkedin_url??"",facebook_url:s.facebook_url??"",other_url:s.other_url??"",photo_url:s.photo_url??"",brokerage:s.brokerage??"",team_name:s.team_name??"",city:s.city??"",state:s.state??"",postal_code:s.postal_code??"",market_area:s.market_area??"",source:s.source??"",relationship_owner:s.relationship_owner??"",stage:s.stage,temperature:s.temperature??"warm",primary_pillar:s.primary_pillar??"none",tags:(s.tags??[]).join(", "),goals:s.goals??"",challenges:s.challenges??"",interests:s.interests??"",production_context:s.production_context??"",notes:s.notes??"",birthday_on:zG(s.birthday_on),work_anniversary_on:zG(s.work_anniversary_on),license_anniversary_on:zG(s.license_anniversary_on),next_follow_up_at:zG(s.next_follow_up_at)}}function HI({title:s,hint:t,children:n}){return e.jsxs("section",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600",children:s}),t&&e.jsx("p",{className:"text-[12px] text-slate-500 mt-0.5",children:t})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 gap-3",children:n})]})}function Xd({label:s,value:t,onChange:n,className:r,...a}){return e.jsxs("div",{className:r,children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:s}),e.jsx(ye,{className:"mt-1",value:t,onChange:i=>n(i.target.value),...a})]})}function nSt({agent:s,open:t,onOpenChange:n,onDeleted:r}){const{agents:a,saveAgentDetails:i,archiveAgent:l,deleteAgent:o}=i0(),[c,d]=N.useState({}),[u,h]=N.useState(!1),[p,f]=N.useState(!1),[y,_]=N.useState(!1);N.useEffect(()=>{s&&t&&(d(set(s)),_(!1))},[s==null?void 0:s.id,t]);const v=N.useMemo(()=>s?set(s):{},[s]),j=N.useMemo(()=>Object.keys(c).filter(I=>String(c[I]??"")!==String(v[I]??"")),[c,v]),w=j.length>0,S=(I,F)=>d(z=>({...z,[I]:F}));if(!s)return null;const A=I=>{if(!I&&w){h(!0);return}n(I)},E=()=>{var H;const I=(H=c.email)==null?void 0:H.trim().toLowerCase(),F=zF(c.phone),z=`${c.first_name} ${c.last_name}`.trim().toLowerCase();return a.filter(Z=>{var Y;return Z.id===s.id||Z.is_archived?!1:!!(I&&((Y=Z.email)==null?void 0:Y.toLowerCase())===I||F.length>=10&&zF(Z.phone)===F||z&&`${Z.first_name} ${Z.last_name??""}`.trim().toLowerCase()===z)})},O=()=>{var Z,Y,W;if(!((Z=c.first_name)!=null&&Z.trim())){ae.error("First name is required");return}if((Y=c.email)!=null&&Y.trim()&&!Bcn(c.email)){ae.error("That email address looks incomplete");return}const I=E(),F=I.some(ee=>{var se,oe;return((se=c.email)==null?void 0:se.trim())&&((oe=ee.email)==null?void 0:oe.toLowerCase())===c.email.trim().toLowerCase()||zF(c.phone).length>=10&&zF(ee.phone)===zF(c.phone)});if(I.length&&!y){_(!0),ae.warning(F?`${I[0].first_name} ${I[0].last_name??""} already uses this email or phone. Save again to confirm.`:"A contact named the same already exists. Save again to confirm.");return}const z={first_name:c.first_name.trim(),last_name:mp(c.last_name),preferred_name:mp(c.preferred_name),email:(W=c.email)!=null&&W.trim()?c.email.trim().toLowerCase():null,phone:zcn(c.phone??""),website_url:VI(c.website_url??""),instagram_url:VI(c.instagram_url??""),linkedin_url:VI(c.linkedin_url??""),facebook_url:VI(c.facebook_url??""),other_url:VI(c.other_url??""),photo_url:VI(c.photo_url??""),brokerage:mp(c.brokerage),team_name:mp(c.team_name),city:mp(c.city),state:mp(c.state),postal_code:mp(c.postal_code),market_area:mp(c.market_area),source:mp(c.source),relationship_owner:mp(c.relationship_owner),temperature:c.temperature,primary_pillar:c.primary_pillar==="none"?null:c.primary_pillar,tags:String(c.tags??"").split(",").map(ee=>ee.trim()).filter(Boolean),goals:mp(c.goals),challenges:mp(c.challenges),interests:mp(c.interests),production_context:mp(c.production_context),notes:mp(c.notes),birthday_on:mp(c.birthday_on),work_anniversary_on:mp(c.work_anniversary_on),license_anniversary_on:mp(c.license_anniversary_on),next_follow_up_at:c.next_follow_up_at?new Date(`${c.next_follow_up_at}T12:00:00`).toISOString():null,stage:c.stage},H={};if(j.forEach(ee=>{ee in z&&(H[ee]=z[ee])}),!Object.keys(H).length){n(!1);return}i.mutate({id:s.id,values:H,changedLabels:j.map(ee=>Fcn[ee]??ee),previousStage:s.stage},{onSuccess:()=>n(!1)})},D=E();return e.jsxs(e.Fragment,{children:[e.jsx(t0,{open:t,onOpenChange:A,children:e.jsxs(og,{side:"right",className:"w-full sm:max-w-xl overflow-y-auto p-0",children:[e.jsx("div",{className:"sticky top-0 z-10 bg-gradient-to-r from-[#0B0F1E] to-[#1d1b4b] text-white px-5 py-4",children:e.jsxs(jy,{className:"space-y-1 text-left",children:[e.jsxs(Ny,{className:"text-white text-lg",children:["Edit ",[s.first_name,s.last_name].filter(Boolean).join(" ")]}),e.jsx(Z$,{className:"text-slate-300 text-[12.5px]",children:"Only the fields you change are saved. Stage changes are recorded in pipeline history."})]})}),e.jsxs("div",{className:"px-5 py-5 space-y-7 pb-40",children:[!!D.length&&e.jsxs("div",{className:"rounded-xl bg-amber-50 ring-1 ring-amber-200 p-3 text-[12.5px] text-amber-800 flex gap-2",children:[e.jsx(ic,{className:"h-4 w-4 mt-0.5 shrink-0"}),e.jsxs("span",{children:["Possible duplicate: ",D.slice(0,3).map(I=>`${I.first_name} ${I.last_name??""}`.trim()).join(", "),". You can still save — just double-check first."]})]}),e.jsxs(HI,{title:"Basic info",children:[e.jsx(Xd,{label:"First name *",value:c.first_name,onChange:I=>S("first_name",I)}),e.jsx(Xd,{label:"Last name",value:c.last_name,onChange:I=>S("last_name",I)}),e.jsx(Xd,{label:"Preferred name",value:c.preferred_name,onChange:I=>S("preferred_name",I),placeholder:"What they go by"}),e.jsx(Xd,{label:"Photo / headshot URL",value:c.photo_url,onChange:I=>S("photo_url",I),placeholder:"https://…"})]}),e.jsxs(HI,{title:"Contact & social",children:[e.jsx(Xd,{label:"Email",type:"email",value:c.email,onChange:I=>S("email",I)}),e.jsx(Xd,{label:"Phone",value:c.phone,onChange:I=>S("phone",I)}),e.jsx(Xd,{label:"Website",value:c.website_url,onChange:I=>S("website_url",I)}),e.jsx(Xd,{label:"Instagram",value:c.instagram_url,onChange:I=>S("instagram_url",I)}),e.jsx(Xd,{label:"LinkedIn",value:c.linkedin_url,onChange:I=>S("linkedin_url",I)}),e.jsx(Xd,{label:"Facebook",value:c.facebook_url,onChange:I=>S("facebook_url",I)}),e.jsx(Xd,{label:"Other link",value:c.other_url,onChange:I=>S("other_url",I),className:"sm:col-span-2"})]}),e.jsxs(HI,{title:"Brokerage & market",children:[e.jsx(Xd,{label:"Brokerage",value:c.brokerage,onChange:I=>S("brokerage",I)}),e.jsx(Xd,{label:"Team",value:c.team_name,onChange:I=>S("team_name",I)}),e.jsx(Xd,{label:"City",value:c.city,onChange:I=>S("city",I)}),e.jsx(Xd,{label:"State",value:c.state,onChange:I=>S("state",I)}),e.jsx(Xd,{label:"ZIP / postal code",value:c.postal_code,onChange:I=>S("postal_code",I)}),e.jsx(Xd,{label:"Market / service area",value:c.market_area,onChange:I=>S("market_area",I)})]}),e.jsxs(HI,{title:"Relationship intelligence",hint:"These drive scoring, recommendations, filters and reports.",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:"Pipeline stage"}),e.jsxs(us,{value:c.stage,onValueChange:I=>S("stage",I),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(cs,{children:Ocn.map(I=>e.jsx(Ze,{value:I,className:"capitalize",children:I.replace(/_/g," ")},I))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:"Temperature"}),e.jsxs(us,{value:c.temperature,onValueChange:I=>S("temperature",I),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(cs,{children:["cold","warm","hot"].map(I=>e.jsx(Ze,{value:I,className:"capitalize",children:I},I))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:"Primary pillar"}),e.jsxs(us,{value:c.primary_pillar,onValueChange:I=>S("primary_pillar",I),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"Not set"}),["produce","influence","provide","connect"].map(I=>e.jsx(Ze,{value:I,className:"capitalize",children:I},I))]})]})]}),e.jsx(Xd,{label:"Source",value:c.source,onChange:I=>S("source",I),placeholder:"Event, referral, social…"}),e.jsx(Xd,{label:"Relationship owner",value:c.relationship_owner,onChange:I=>S("relationship_owner",I),placeholder:"You, or a teammate"}),e.jsx(Xd,{label:"Tags (comma separated)",value:c.tags,onChange:I=>S("tags",I),className:"sm:col-span-2"}),!!String(c.tags??"").trim()&&e.jsx("div",{className:"sm:col-span-2 flex flex-wrap gap-1.5 -mt-1",children:String(c.tags).split(",").map(I=>I.trim()).filter(Boolean).map(I=>e.jsx(Ue,{variant:"outline",className:"rounded-full text-[11px]",children:I},I))})]}),e.jsxs(HI,{title:"Important dates",hint:"Birthdays and anniversaries feed Milestones & Celebrations automatically — no duplicate entry needed.",children:[e.jsx(Xd,{label:"Birthday",type:"date",value:c.birthday_on,onChange:I=>S("birthday_on",I)}),e.jsx(Xd,{label:"Work anniversary",type:"date",value:c.work_anniversary_on,onChange:I=>S("work_anniversary_on",I)}),e.jsx(Xd,{label:"License anniversary",type:"date",value:c.license_anniversary_on,onChange:I=>S("license_anniversary_on",I)}),e.jsx(Xd,{label:"Next follow-up",type:"date",value:c.next_follow_up_at,onChange:I=>S("next_follow_up_at",I)})]}),e.jsxs(HI,{title:"Notes",children:[e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:"Goals"}),e.jsx(Ms,{className:"mt-1",rows:2,value:c.goals,onChange:I=>S("goals",I.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:"Challenges"}),e.jsx(Ms,{className:"mt-1",rows:2,value:c.challenges,onChange:I=>S("challenges",I.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:"Interests"}),e.jsx(Ms,{className:"mt-1",rows:2,value:c.interests,onChange:I=>S("interests",I.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:"Production context"}),e.jsx(Ms,{className:"mt-1",rows:2,value:c.production_context,onChange:I=>S("production_context",I.target.value)})]}),e.jsxs("div",{className:"sm:col-span-2",children:[e.jsx(ne,{className:"text-[12px] text-slate-600",children:"Personal notes"}),e.jsx(Ms,{className:"mt-1",rows:4,value:c.notes,onChange:I=>S("notes",I.target.value)})]})]}),e.jsxs("section",{className:"rounded-xl ring-1 ring-rose-200 bg-rose-50/60 p-4 space-y-3",children:[e.jsx("h3",{className:"text-[11px] uppercase tracking-wider font-semibold text-rose-700",children:"Danger zone"}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>l.mutate({id:s.id,archived:!s.is_archived},{onSuccess:()=>n(!1)}),children:[e.jsx(tm,{className:"h-3.5 w-3.5 mr-1.5"}),s.is_archived?"Restore to pipeline":"Remove from pipeline (archive)"]}),e.jsxs(B,{variant:"destructive",size:"sm",className:"rounded-full",onClick:()=>f(!0),children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1.5"})," Delete permanently"]})]}),e.jsx("p",{className:"text-[12px] text-rose-700/80",children:"Archiving keeps every note, touch and score. Deleting is permanent."})]})]}),e.jsxs("div",{className:"sticky bottom-0 bg-white/95 backdrop-blur border-t px-5 py-3 flex items-center justify-between gap-3",children:[e.jsx("span",{className:"text-[12px] text-slate-500",children:i.isPending?"Saving…":w?`${j.length} unsaved change${j.length>1?"s":""}`:"All changes saved"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"ghost",className:"rounded-full",onClick:()=>A(!1),children:[e.jsx($n,{className:"h-4 w-4 mr-1"})," Cancel"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 text-white",disabled:!w||i.isPending,onClick:O,children:[i.isPending&&e.jsx(rs,{className:"h-4 w-4 mr-1.5 animate-spin"}),"Save changes"]})]})]})]})}),e.jsx(Oo,{open:u,onOpenChange:h,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Discard unsaved changes?"}),e.jsxs(Mo,{children:["You have ",j.length," unsaved change(s) on this contact."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Keep editing"}),e.jsx(wo,{onClick:()=>{h(!1),n(!1)},children:"Discard"})]})]})}),e.jsx(Oo,{open:p,onOpenChange:f,children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete this contact permanently?"}),e.jsx(Mo,{children:"This removes their timeline, follow-ups, pipeline history, scores and recommendations. Event, kit and transaction records will stay but will no longer be linked to anyone. This cannot be undone."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{className:"bg-rose-600 hover:bg-rose-700",onClick:()=>o.mutate(s.id,{onSuccess:()=>{f(!1),n(!1),r==null||r()}}),children:"Delete forever"})]})]})})]})}const BG=[{key:"new_connection",label:"New Connection",color:"#94a3b8"},{key:"building_relationship",label:"Building Relationship",color:"#38bdf8"},{key:"engaging_with_value",label:"Engaging With Value",color:"#14b8a6"},{key:"active_conversation",label:"Active Conversation",color:"#8b5cf6"},{key:"exploring_options",label:"Exploring Options",color:"#6366f1"},{key:"brokerage_presentation",label:"Brokerage Presentation",color:"#f97316"},{key:"decision_pending",label:"Decision Pending",color:"#f59e0b"},{key:"joined",label:"Joined",color:"#16a34a"},{key:"not_right_now",label:"Not Right Now",color:"#64748b"},{key:"long_term_relationship",label:"Long-Term Relationship",color:"#a78bfa"},{key:"not_a_fit",label:"Not a Fit",color:"#cbd5e1"}],net={hot:"bg-rose-100 text-rose-700 border-rose-200",warm:"bg-orange-100 text-orange-700 border-orange-200",cold:"bg-sky-100 text-sky-700 border-sky-200"};function $cn(){const s=Ln(),{agents:t,isLoading:n,upsertAgent:r,moveStage:a,archiveAgent:i,deleteAgent:l}=i0(),[o,c]=N.useState("kanban"),[d,u]=N.useState(""),[h,p]=N.useState(!1),[f,y]=N.useState(!1),[_,v]=N.useState(),[j,w]=N.useState(null),[S,A]=N.useState(null),[E,O]=N.useState(null),[D,I]=N.useState(null),{gmailEmail:F}=Dh(),z=t.filter(Y=>!!Y.is_archived!==h?!1:d?`${Y.first_name} ${Y.last_name??""} ${Y.brokerage??""} ${Y.city??""} ${(Y.tags??[]).join(" ")} ${Y.email??""}`.toLowerCase().includes(d.toLowerCase()):!0),H=j?t.find(Y=>Y.id===j.id)??j:null,Z=({agent:Y})=>e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6 -mr-1",onClick:W=>W.stopPropagation(),"aria-label":"Agent actions",children:e.jsx(Ag,{className:"h-3.5 w-3.5"})})}),e.jsxs(gc,{align:"end",onClick:W=>W.stopPropagation(),children:[e.jsxs(Kr,{onClick:()=>A(Y),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-2"})," Edit contact"]}),e.jsxs(Kr,{onClick:()=>s(`/attract/agents/${Y.id}`),children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-2"})," Open relationship"]}),e.jsx(Kg,{}),e.jsxs(Kr,{onClick:()=>i.mutate({id:Y.id,archived:!Y.is_archived}),children:[e.jsx(tm,{className:"h-3.5 w-3.5 mr-2"})," ",Y.is_archived?"Restore to pipeline":"Remove from pipeline"]})]})]});return e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Agent Pipeline",title:"Where relationships live",description:"Move agents through relationship-first stages. Never a target — always a real conversation.",actions:e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"flex bg-white border rounded-full p-0.5",children:[e.jsxs(B,{size:"sm",variant:o==="kanban"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>c("kanban"),children:[e.jsx(ff,{className:"h-3.5 w-3.5 mr-1"})," Board"]}),e.jsxs(B,{size:"sm",variant:o==="list"?"default":"ghost",className:"rounded-full h-8 px-3",onClick:()=>c("list"),children:[e.jsx(Sp,{className:"h-3.5 w-3.5 mr-1"})," List"]})]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:opacity-95",onClick:()=>{v(void 0),y(!0)},children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Agent"]})]})}),e.jsxs("div",{className:"mb-4 flex items-center gap-3 flex-wrap",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px] max-w-md",children:[e.jsx(gr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(ye,{value:d,onChange:Y=>u(Y.target.value),placeholder:"Search name, brokerage, city, tag, email…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs(B,{variant:h?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>p(Y=>!Y),children:[e.jsx(tm,{className:"h-3.5 w-3.5 mr-1.5"})," ",h?"Viewing archived":"Archived"]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[z.length," agents"]})]}),e.jsx("div",{className:"mb-4",children:e.jsx(l6,{})}),n?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading pipeline…"}):o==="kanban"?e.jsxs(di,{className:"w-full",children:[e.jsx("div",{className:"flex gap-4 pb-4",style:{minWidth:BG.length*300},children:BG.map(Y=>{const W=z.filter(ee=>ee.stage===Y.key);return e.jsxs("div",{className:"w-[280px] flex-shrink-0 flex flex-col",onDragOver:ee=>{ee.preventDefault(),ee.dataTransfer.dropEffect="move"},onDrop:ee=>{if(ee.preventDefault(),E){const se=t.find(oe=>oe.id===E);se&&se.stage!==Y.key&&a.mutate({id:E,to_stage:Y.key,from_stage:se.stage}),O(null)}},children:[e.jsxs("div",{className:"flex items-center justify-between px-1 mb-3",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:Y.color}}),e.jsx("h3",{className:"text-[13px] font-semibold text-slate-800",children:Y.label}),e.jsx(Ue,{variant:"secondary",className:"text-[10px] h-5 px-1.5",children:W.length})]}),e.jsx(B,{variant:"ghost",size:"icon",className:"h-6 w-6",onClick:()=>{v(Y.key),y(!0)},children:e.jsx(Is,{className:"h-3.5 w-3.5"})})]}),e.jsxs("div",{className:"rounded-2xl bg-slate-100/60 p-2 space-y-2 min-h-[200px]",children:[W.map(ee=>e.jsxs("div",{draggable:!0,onDragStart:()=>O(ee.id),onClick:()=>w(ee),className:"bg-white rounded-xl p-3 cursor-pointer hover:shadow-md border-l-[3px] transition-all",style:{borderLeftColor:Y.color},children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsxs("div",{className:"min-w-0 flex-1",children:[e.jsxs("div",{className:"text-[13.5px] font-semibold text-slate-900 truncate",children:[ee.first_name," ",ee.last_name]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 flex items-center gap-1 mt-0.5 truncate",children:[e.jsx(Ua,{className:"h-3 w-3"}),e.jsx("span",{className:"truncate",children:ee.brokerage??"—"})]})]}),ee.temperature&&e.jsxs(Ue,{variant:"outline",className:`text-[9.5px] px-1.5 py-0 ${net[ee.temperature]}`,children:[e.jsx(j9,{className:"h-2.5 w-2.5 mr-0.5"}),ee.temperature]}),e.jsx(Z,{agent:ee})]}),e.jsxs("div",{className:"mt-2 flex items-center gap-2 text-[11px] text-slate-500",children:[e.jsx(ka,{className:"h-3 w-3"}),e.jsxs("span",{className:"truncate",children:[ee.city,ee.state&&`, ${ee.state}`]})]}),ee.next_follow_up_at&&e.jsxs("div",{className:"mt-1.5 text-[10.5px] text-violet-700 font-medium",children:["Next touch · ",Ss(new Date(ee.next_follow_up_at),"MMM d")]})]},ee.id)),W.length===0&&e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center py-4",children:"Drop an agent here"})]})]},Y.key)})}),e.jsx(Q$,{orientation:"horizontal"})]}):e.jsx(fe,{className:"rounded-2xl overflow-hidden",children:e.jsxs("table",{className:"w-full text-sm",children:[e.jsx("thead",{className:"bg-slate-50 text-[11px] uppercase tracking-wider text-slate-500",children:e.jsxs("tr",{children:[e.jsx("th",{className:"text-left px-4 py-3",children:"Agent"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Brokerage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Location"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Stage"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Temp"}),e.jsx("th",{className:"text-left px-4 py-3",children:"Next Follow-Up"}),e.jsx("th",{className:"text-right px-4 py-3",children:"Actions"})]})}),e.jsxs("tbody",{children:[z.map(Y=>{const W=BG.find(ee=>ee.key===Y.stage);return e.jsxs("tr",{onClick:()=>w(Y),className:"border-t border-slate-100 hover:bg-slate-50 cursor-pointer",children:[e.jsxs("td",{className:"px-4 py-3 font-medium text-slate-900",children:[Y.first_name," ",Y.last_name]}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:Y.brokerage}),e.jsxs("td",{className:"px-4 py-3 text-slate-600",children:[Y.city,", ",Y.state]}),e.jsx("td",{className:"px-4 py-3",children:e.jsx(Ue,{style:{background:W==null?void 0:W.color,color:"white"},children:W==null?void 0:W.label})}),e.jsx("td",{className:"px-4 py-3",children:Y.temperature&&e.jsx(Ue,{variant:"outline",className:net[Y.temperature],children:Y.temperature})}),e.jsx("td",{className:"px-4 py-3 text-slate-600",children:Y.next_follow_up_at?Ss(new Date(Y.next_follow_up_at),"MMM d"):"—"}),e.jsx("td",{className:"px-4 py-3 text-right",children:e.jsx(Z,{agent:Y})})]},Y.id)}),z.length===0&&e.jsx("tr",{children:e.jsx("td",{colSpan:7,className:"px-4 py-10 text-center text-slate-500",children:"No agents match this view."})})]})]})}),e.jsx(Ucn,{open:f,onOpenChange:y,defaultStage:_,onSubmit:Y=>r.mutate(Y,{onSuccess:()=>y(!1)})}),e.jsx(nSt,{agent:S?t.find(Y=>Y.id===S.id)??S:null,open:!!S,onOpenChange:Y=>!Y&&A(null),onDeleted:()=>w(null)}),e.jsx(t0,{open:!!j,onOpenChange:Y=>!Y&&w(null),children:e.jsx(og,{className:"w-full sm:max-w-lg overflow-y-auto",children:H&&e.jsxs(e.Fragment,{children:[e.jsxs(jy,{children:[e.jsxs(Ny,{className:"text-xl",children:[H.first_name," ",H.last_name]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 flex items-center gap-2",children:[e.jsx(Ua,{className:"h-3.5 w-3.5"})," ",H.brokerage??"—"," · ",H.city,", ",H.state]})]}),e.jsxs("div",{className:"mt-6 space-y-5",children:[e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"gap-1.5 bg-gradient-to-r from-violet-600 to-indigo-600 text-white",onClick:()=>A(H),children:[e.jsx(ya,{className:"h-3.5 w-3.5"})," Edit contact"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${H.id}`),children:[e.jsx(tr,{className:"h-3.5 w-3.5"})," Open relationship"]}),H.email&&e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>I(H),children:[e.jsx(Gs,{className:"h-3.5 w-3.5"})," Email"]}),H.phone&&e.jsx(B,{variant:"outline",size:"sm",className:"gap-1.5",asChild:!0,children:e.jsxs("a",{href:`tel:${H.phone}`,children:[e.jsx(Cr,{className:"h-3.5 w-3.5"})," Call"]})}),e.jsxs(B,{variant:"outline",size:"sm",className:"gap-1.5",onClick:()=>s(`/attract/agents/${H.id}`),children:[e.jsx(Ai,{className:"h-3.5 w-3.5"})," Log touch"]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Stage"}),e.jsxs(us,{value:H.stage,onValueChange:Y=>a.mutate({id:H.id,to_stage:Y,from_stage:H.stage}),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(cs,{children:BG.map(Y=>e.jsx(Ze,{value:Y.key,children:Y.label},Y.key))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:"Temperature"}),e.jsxs(us,{value:H.temperature??"warm",onValueChange:Y=>r.mutate({id:H.id,first_name:H.first_name,temperature:Y}),children:[e.jsx(ls,{className:"mt-1",children:e.jsx(hs,{})}),e.jsx(cs,{children:["cold","warm","hot"].map(Y=>e.jsx(Ze,{value:Y,className:"capitalize",children:Y},Y))})]})]}),!!(H.tags??[]).length&&e.jsx("div",{className:"flex flex-wrap gap-1.5",children:(H.tags??[]).map(Y=>e.jsx(Ue,{variant:"outline",className:"rounded-full",children:Y},Y))}),e.jsx(ike,{label:"Notes",value:H.notes}),e.jsx(ike,{label:"Goals",value:H.goals}),e.jsx(ike,{label:"Challenges",value:H.challenges}),e.jsxs("div",{className:"pt-4 border-t flex justify-between",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>i.mutate({id:H.id,archived:!H.is_archived}),children:[e.jsx(tm,{className:"h-4 w-4 mr-1"})," ",H.is_archived?"Restore":"Remove from pipeline"]}),e.jsxs(B,{variant:"ghost",size:"sm",className:"text-rose-600",onClick:()=>A(H),children:[e.jsx(_n,{className:"h-4 w-4 mr-1"})," Delete…"]})]})]})]})})}),(D==null?void 0:D.email)&&e.jsx(Xv,{open:!!D,onOpenChange:Y=>!Y&&I(null),contact:{id:D.id,first_name:D.preferred_name||D.first_name,last_name:D.last_name||"",email:D.email},gmailEmail:F,sendSource:"attract",logTouchpoint:!1})]})}function ike({label:s,value:t}){return e.jsxs("div",{children:[e.jsx(ne,{className:"text-[11px] uppercase tracking-wider text-slate-500",children:s}),e.jsx("div",{className:"mt-1 text-[13.5px] text-slate-800 whitespace-pre-wrap min-h-[24px]",children:t||e.jsx("span",{className:"text-slate-400",children:"Not set"})})]})}function Ucn({open:s,onOpenChange:t,defaultStage:n,onSubmit:r}){const[a,i]=N.useState({first_name:"",last_name:"",brokerage:"",city:"",state:"",temperature:"warm",primary_pillar:"connect",stage:n??"new_connection",notes:""});return e.jsx(_s,{open:s,onOpenChange:t,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(ws,{children:"Add an agent to your pipeline"})}),e.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"First name *"}),e.jsx(ye,{value:a.first_name,onChange:l=>i({...a,first_name:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Last name"}),e.jsx(ye,{value:a.last_name,onChange:l=>i({...a,last_name:l.target.value})})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{children:"Current brokerage"}),e.jsx(ye,{value:a.brokerage,onChange:l=>i({...a,brokerage:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"City"}),e.jsx(ye,{value:a.city,onChange:l=>i({...a,city:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"State"}),e.jsx(ye,{value:a.state,onChange:l=>i({...a,state:l.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Temperature"}),e.jsxs(us,{value:a.temperature,onValueChange:l=>i({...a,temperature:l}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"cold",children:"Cold"}),e.jsx(Ze,{value:"warm",children:"Warm"}),e.jsx(Ze,{value:"hot",children:"Hot"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Primary pillar"}),e.jsxs(us,{value:a.primary_pillar,onValueChange:l=>i({...a,primary_pillar:l}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"produce",children:"Produce"}),e.jsx(Ze,{value:"influence",children:"Influence"}),e.jsx(Ze,{value:"provide",children:"Provide"}),e.jsx(Ze,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"col-span-2",children:[e.jsx(ne,{children:"Notes"}),e.jsx(Ms,{rows:3,value:a.notes,onChange:l=>i({...a,notes:l.target.value})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>t(!1),children:"Cancel"}),e.jsx(B,{disabled:!a.first_name,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>r(a),children:"Add Agent"})]})]})})}const qcn={call:Cr,email:Gs,coffee:ey,gift:Oi,text:Gs,event:Xf};function Vcn(){const{followUps:s,complete:t}=UU(),{agents:n}=i0(),r=N.useMemo(()=>{const l=wf(new Date),o=[],c=[],d=[],u=[],h=[];for(const p of s){if(p.completed_at){h.push(p);continue}if(!p.due_at){u.push(p);continue}const f=new Date(p.due_at);yb(f,l)?o.push(p):of(f)?c.push(p):cUt(f)?d.push(p):u.push(p)}return{overdue:o,today:c,tomorrow:d,later:u,done:h}},[s]),a=new Map(n.map(l=>[l.id,l])),i=[{label:"Overdue",value:r.overdue.length,tone:"text-rose-600 bg-rose-50",icon:Bi},{label:"Due Today",value:r.today.length,tone:"text-orange-600 bg-orange-50",icon:pr},{label:"Completed This Week",value:r.done.filter(l=>l.completed_at&&new Date(l.completed_at)>Bl(new Date,-7)).length,tone:"text-emerald-600 bg-emerald-50",icon:vr}];return e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Follow-Up Center",title:"One list. One rhythm. One relationship at a time.",description:"Everything you promised to do — organized so it never feels like a to-do list."}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4 mb-6",children:i.map(l=>e.jsxs(fe,{className:"p-5 rounded-2xl flex items-center gap-4",children:[e.jsx("div",{className:`h-11 w-11 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900",children:l.value}),e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:l.label})]})]},l.label))}),e.jsx("div",{className:"mb-6",children:e.jsx(l6,{})}),e.jsxs("div",{className:"space-y-6",children:[e.jsx(BF,{title:"Overdue",items:r.overdue,agentMap:a,onComplete:l=>t.mutate(l),tone:"rose"}),e.jsx(BF,{title:"Today",items:r.today,agentMap:a,onComplete:l=>t.mutate(l),tone:"orange"}),e.jsx(BF,{title:"Tomorrow",items:r.tomorrow,agentMap:a,onComplete:l=>t.mutate(l),tone:"violet"}),e.jsx(BF,{title:"Later This Week",items:r.later,agentMap:a,onComplete:l=>t.mutate(l),tone:"slate"}),r.done.length>0&&e.jsx(BF,{title:"Recently Completed",items:r.done.slice(0,5),agentMap:a,onComplete:()=>{},tone:"emerald",done:!0})]})]})}function BF({title:s,items:t,agentMap:n,onComplete:r,tone:a,done:i}){if(t.length===0)return null;const l={rose:"#f43f5e",orange:"#f97316",violet:"#8b5cf6",slate:"#94a3b8",emerald:"#10b981"};return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("span",{className:"h-2.5 w-2.5 rounded-full",style:{background:l[a]}}),e.jsx("h3",{className:"text-[13px] font-semibold uppercase tracking-wider text-slate-700",children:s}),e.jsx(Ue,{variant:"secondary",className:"text-[10px]",children:t.length})]}),e.jsx(fe,{className:"rounded-2xl divide-y divide-slate-100 overflow-hidden",children:t.map(o=>{const c=n.get(o.agent_id),d=qcn[o.touch_type??""]??Gs;return e.jsxs("div",{className:`flex items-start gap-3 p-4 hover:bg-slate-50 ${i?"opacity-60":""}`,children:[e.jsx(hi,{checked:!!o.completed_at,onCheckedChange:()=>r(o.id),className:"mt-1"}),e.jsx("div",{className:"h-8 w-8 rounded-lg grid place-items-center flex-shrink-0",style:{background:`${l[a]}18`,color:l[a]},children:e.jsx(d,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:o.title}),c&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["for ",c.first_name," ",c.last_name," · ",c.brokerage]}),o.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1",children:o.notes})]}),o.due_at&&e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:Ss(new Date(o.due_at),"MMM d")}),e.jsx(B,{variant:"ghost",size:"sm",children:"Snooze"})]},o.id)})})]})}const Hcn={pdf:br,link:Tl,video:fr,tool:gb,guide:rm},Gcn={script:"bg-violet-100 text-violet-700",checklist:"bg-teal-100 text-teal-700",tool:"bg-orange-100 text-orange-700",guide:"bg-indigo-100 text-indigo-700",masterclass:"bg-rose-100 text-rose-700"};function Wcn(){const{resources:s,isLoading:t}=sSt(),[n,r]=N.useState(""),[a,i]=N.useState("all"),l=Array.from(new Set(s.map(c=>c.category).filter(Boolean))),o=s.filter(c=>(a==="all"||c.category===a)&&(!n||`${c.title} ${c.description??""}`.toLowerCase().includes(n.toLowerCase())));return e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Resource Library",title:"The stack you share with future teammates.",description:"Every resource, script, and tool you use — ready to share in one click.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Resource"]})}),e.jsxs("div",{className:"flex flex-wrap items-center gap-3 mb-5",children:[e.jsxs("div",{className:"relative flex-1 min-w-[240px] max-w-md",children:[e.jsx(gr,{className:"h-4 w-4 text-slate-400 absolute left-3 top-1/2 -translate-y-1/2"}),e.jsx(ye,{value:n,onChange:c=>r(c.target.value),placeholder:"Search resources…",className:"pl-9 rounded-full bg-white"})]}),e.jsxs("div",{className:"flex gap-1.5 flex-wrap",children:[e.jsx(B,{size:"sm",variant:a==="all"?"default":"outline",className:"rounded-full h-8",onClick:()=>i("all"),children:"All"}),l.map(c=>e.jsx(B,{size:"sm",variant:a===c?"default":"outline",className:"rounded-full h-8 capitalize",onClick:()=>i(c),children:c},c))]})]}),t?e.jsx("div",{className:"py-24 text-center text-slate-500",children:"Loading resources…"}):o.length===0?e.jsx(fe,{className:"p-12 text-center rounded-2xl",children:e.jsx("div",{className:"text-slate-500",children:"No resources yet. Add your first shareable asset above."})}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:o.map(c=>{const d=Hcn[c.resource_type]??br;return e.jsxs(fe,{className:"p-5 rounded-2xl hover:shadow-md transition-all group",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 grid place-items-center text-violet-600",children:e.jsx(d,{className:"h-5 w-5"})}),c.category&&e.jsx(Ue,{className:`${Gcn[c.category]??"bg-slate-100 text-slate-700"} border-0 capitalize`,children:c.category})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:c.title}),c.description&&e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 line-clamp-2",children:c.description})]}),e.jsxs("div",{className:"mt-4 pt-4 border-t border-slate-100 flex items-center justify-between text-[12px] text-slate-500",children:[e.jsx("div",{children:"Shared 0×"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full gap-1",children:[e.jsx(Vl,{className:"h-3.5 w-3.5"})," Share"]})]})]},c.id)})})]})}const Kcn=[{category:"First Touch",icon:Ai,color:"#7c3aed",items:[{title:"Warm intro after meeting",body:"Hey {{first_name}} — really enjoyed meeting you at {{event}}. Would love to grab coffee sometime and hear more about what you're building at {{brokerage}}."},{title:"Congrats on a recent close",body:"Saw your closing at {{property}} pop up — nice work {{first_name}}. Those aren't easy right now. If you ever want to compare notes on how you're getting deals across the line, I'm always up for a coffee."}]},{category:"Value Share",icon:Gs,color:"#4f46e5",items:[{title:"Sending a helpful resource",body:"Hey {{first_name}} — thought of you when I put this together. No agenda, just something I think you'll actually use: {{resource_link}}"},{title:"Market update forward",body:"Sending along this month's local market snapshot — figured you might want it for your buyer conversations this week: {{link}}"}]},{category:"Coffee Invite",icon:ey,color:"#0d9488",items:[{title:"Casual 30-min coffee",body:"Hey {{first_name}}, are you free for a 30-min coffee sometime in the next couple weeks? No agenda — just want to hear how the year is going for you."},{title:"Follow-up after coffee",body:"Really enjoyed catching up {{first_name}}. Here's the {{resource}} I mentioned — and I'll circle back in a few weeks. In the meantime, if I can help with anything, just text."}]},{category:"Check-In",icon:Cr,color:"#9333ea",items:[{title:"Quarterly check-in",body:"Hey {{first_name}} — just thinking of you. How's the quarter shaping up? No ask, just checking in."},{title:"Birthday message",body:"Happy birthday {{first_name}}! Hope you get to slow down for a minute today. 🎉"}]}];function Ycn(){const s=t=>{navigator.clipboard.writeText(t),ae.success("Template copied")};return e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Message Templates",title:"Words that sound like you.",description:"Starting points — never scripts. Personalize the details and let the relationship speak."}),e.jsx("div",{className:"space-y-8",children:Kcn.map(t=>{const n=t.icon;return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl grid place-items-center",style:{background:`${t.color}18`,color:t.color},children:e.jsx(n,{className:"h-5 w-5"})}),e.jsxs("div",{children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:t.category}),e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[t.items.length," templates"]})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:t.items.map(r=>e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx("div",{className:"font-semibold text-slate-900",children:r.title}),e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:t.category})]}),e.jsx("p",{className:"mt-3 text-[13.5px] text-slate-700 leading-relaxed whitespace-pre-wrap",children:r.body}),e.jsx("div",{className:"mt-4 pt-4 border-t border-slate-100 flex justify-end",children:e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full gap-1",onClick:()=>s(r.body),children:[e.jsx(Zr,{className:"h-3.5 w-3.5"})," Copy"]})})]},r.title))})]},t.category)})})]})}const Zcn={produce:"#7c3aed",influence:"#4f46e5",provide:"#0d9488",connect:"#9333ea"};function Qcn(){const{agents:s}=i0(),{activities:t}=Ykt(180),n=N.useMemo(()=>Array.from({length:12},(l,o)=>Vm(R9(new Date,(11-o)*7))).map(l=>{const o=Bl(l,7),c=t.filter(d=>new Date(d.created_at)>=l&&new Date(d.created_at){const i={produce:0,influence:0,provide:0,connect:0};for(const l of t)l.pillar&&(i[l.pillar]=(i[l.pillar]||0)+1);return Object.entries(i).map(([l,o])=>({name:l,value:o,color:Zcn[l]}))},[t]),a=N.useMemo(()=>["new_connection","building_relationship","engaging_with_value","active_conversation","brokerage_presentation","joined"].map(l=>({stage:l.replace(/_/g," "),count:s.filter(o=>o.stage===l).length})),[s]);return e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Reports & Insights",title:"See the compounding effect.",description:"Attraction is a long game. These reports show you the small consistent trend lines that matter."}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-6",children:[e.jsxs(fe,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Weekly Activity"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Attraction activities · Last 12 weeks"}),e.jsx(ww,{width:"100%",height:260,children:e.jsxs(VPe,{data:n,children:[e.jsx(Rw,{dataKey:"week",tick:{fontSize:11}}),e.jsx(Ow,{tick:{fontSize:11}}),e.jsx(_p,{}),e.jsx(JM,{type:"monotone",dataKey:"activities",stroke:"#7c3aed",strokeWidth:2.5,dot:{r:3}})]})})]}),e.jsxs(fe,{className:"p-6 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pillar Balance"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Where you're investing time"}),e.jsx(ww,{width:"100%",height:260,children:e.jsxs(GPe,{children:[e.jsx(Db,{data:r,dataKey:"value",nameKey:"name",cx:"50%",cy:"50%",innerRadius:55,outerRadius:90,paddingAngle:2,children:r.map((i,l)=>e.jsx(oR,{fill:i.color},l))}),e.jsx(_p,{}),e.jsx(GA,{})]})})]}),e.jsxs(fe,{className:"p-6 rounded-2xl lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500 mb-1",children:"Pipeline Distribution"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Agents by stage"}),e.jsx(ww,{width:"100%",height:280,children:e.jsxs(HPe,{data:a,children:[e.jsx(Rw,{dataKey:"stage",tick:{fontSize:10}}),e.jsx(Ow,{tick:{fontSize:11}}),e.jsx(_p,{}),e.jsx(Dw,{dataKey:"count",fill:"#4f46e5",radius:[8,8,0,0]})]})})]})]})]})}function Xcn(){const{settings:s,upsert:t,resetOnboarding:n}=$U(),[r,a]=N.useState({});N.useEffect(()=>{s&&a(s)},[s]);const i=l=>a({...r,...l});return e.jsxs("div",{className:"max-w-3xl",children:[e.jsx(zu,{eyebrow:"Attract Settings",title:"Your attraction philosophy.",description:"A one-time setup that keeps every touch you send true to who you are."}),e.jsxs(fe,{className:"p-5 rounded-2xl mb-6 flex flex-col md:flex-row md:items-center gap-4 bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-white text-violet-700 grid place-items-center shadow-sm",children:e.jsx(Ac,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:"Your 90-day plan"}),e.jsx("div",{className:"text-[12.5px] text-slate-600",children:s!=null&&s.onboarding_completed_at?`Primary pillar: ${s.primary_pillar??s.attraction_style??"balanced"} · Outcome: ${s.ninety_day_outcome??"—"}`:"You haven't completed onboarding yet."})]}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{asChild:!0,variant:"outline",className:"rounded-full",children:e.jsx(In,{to:"/attract/plan",children:"View plan"})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>n.mutate(),children:[e.jsx(Bm,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})]})]}),e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Your voice & story"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"Used to personalize scripts, invites, and shared content."}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Elevator introduction"}),e.jsx(Ms,{rows:3,value:r.elevator_intro??"",onChange:l=>i({elevator_intro:l.target.value}),placeholder:"I help agents scale their business by trading isolation for a real team..."})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Focus market"}),e.jsx(ye,{value:r.focus_market??"",onChange:l=>i({focus_market:l.target.value}),placeholder:"Orange County, CA"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Annual attraction goal"}),e.jsx(ye,{type:"number",value:r.annual_attract_goal??"",onChange:l=>i({annual_attract_goal:Number(l.target.value)||null}),placeholder:"12"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:'Your "why" for attraction'}),e.jsx(Ms,{rows:3,value:r.why_statement??"",onChange:l=>i({why_statement:l.target.value}),placeholder:"Because the right agents in the right room change everyone's business..."})]})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"Cadence & rhythm"}),e.jsx("p",{className:"text-[13px] text-slate-600 mb-5",children:"How often should we remind you to show up for agents at each stage?"}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Hot leads follow-up"}),e.jsxs(us,{value:String(r.hot_cadence_days??3),onValueChange:l=>i({hot_cadence_days:Number(l)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"1",children:"Every day"}),e.jsx(Ze,{value:"3",children:"Every 3 days"}),e.jsx(Ze,{value:"7",children:"Every week"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Warm leads follow-up"}),e.jsxs(us,{value:String(r.warm_cadence_days??14),onValueChange:l=>i({warm_cadence_days:Number(l)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"7",children:"Weekly"}),e.jsx(Ze,{value:"14",children:"Every 2 weeks"}),e.jsx(Ze,{value:"30",children:"Monthly"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Long-term nurture"}),e.jsxs(us,{value:String(r.longterm_cadence_days??60),onValueChange:l=>i({longterm_cadence_days:Number(l)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"30",children:"Monthly"}),e.jsx(Ze,{value:"60",children:"Every 2 months"}),e.jsx(Ze,{value:"90",children:"Quarterly"})]})]})]}),e.jsx("div",{className:"flex flex-col justify-end",children:e.jsxs("div",{className:"flex items-center justify-between rounded-xl bg-slate-50 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900",children:"Weekly digest email"}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:"Every Sunday at 6pm"})]}),e.jsx(jn,{checked:r.weekly_digest_enabled??!0,onCheckedChange:l=>i({weekly_digest_enabled:l})})]})})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("h3",{className:"text-lg font-semibold text-slate-900 mb-1",children:"The Attract Trust Reminder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 leading-relaxed",children:"Attract is never a sales funnel. Every touch you make here should be something you'd be proud of if the agent saw every note you'd taken about them. Real relationships. On a rhythm. For years."})]}),e.jsx("div",{className:"flex justify-end",children:e.jsx(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 px-8",onClick:()=>t.mutate(r),disabled:t.isPending,children:"Save Settings"})})]})]})}const ITe=[{key:"transaction_tracker",pillar:"produce",title:"Transaction-to-Relationship Tracker",route:"/attract/produce/transaction-tracker",status:"live",tables:["attract_transactions","attract_agents"],notes:"Full CRUD, converts co-op agents into pipeline relationships."},{key:"production_goals",pillar:"produce",title:"Production Goals",route:"/attract/produce/goals",status:"live",tables:["attract_production_goals","attract_transactions"],notes:"Annual/quarterly/monthly targets, pace vs actual, auto closings from logged transactions, weekly breakdown."},{key:"awards",pillar:"produce",title:"Awards & Recognition",route:"/attract/produce/awards",status:"live",tables:["attract_awards"],notes:"CRUD + copyable proof points into Content Studio."},{key:"content_calendar",pillar:"produce",title:"Content Calendar",route:"/attract/influence/content-calendar",status:"live",tables:["attract_content_drafts","attract_market_presence","attract_speaking_opportunities"],notes:"Unified month grid; schedules undated drafts."},{key:"market_presence",pillar:"produce",title:"Market Presence",route:"/attract/produce/market-presence",status:"live",tables:["attract_market_presence"],notes:"Cadence commitments with status pipeline, past-due tracking, task + activity wiring."},{key:"testimonials",pillar:"produce",title:"Client Testimonials",route:"/attract/produce/testimonials",status:"live",tables:["attract_testimonials"],notes:"Permission tracking, approval gate, usage counter to prevent overexposure."},{key:"content_studio",pillar:"influence",title:"Authority Content Studio",route:"/attract/influence/content-studio",status:"live",tables:["attract_content_drafts"],notes:"AI-assisted drafts with status workflow."},{key:"speaking",pillar:"influence",title:"Speaking Calendar",route:"/attract/influence/speaking",status:"live",tables:["attract_speaking_opportunities","attract_follow_ups","attract_activities"],notes:"Month/week/agenda, full CRUD, status pipeline, ICS export, follow-up + activity wiring."},{key:"masterclass",pillar:"influence",title:"Masterclass Builder",route:"/attract/provide/masterclasses",status:"live",tables:["attract_masterclasses","attract_events","attract_resource_kits","attract_follow_ups"],notes:"Lives under Provide; 6-step builder, autosave, event + kit conversion."},{key:"podcast",pillar:"influence",title:"Podcast & Guest Spots",route:"/attract/influence/speaking",status:"partial",tables:["attract_speaking_opportunities"],notes:"Tracked as event_type = podcast inside the Speaking Calendar."},{key:"roundtables",pillar:"influence",title:"Agent Roundtables",route:"/attract/events/new",status:"partial",tables:["attract_events"],notes:"Uses the Connect Event Engine rather than a separate system."},{key:"resource_kits",pillar:"provide",title:"Resource Kit Builder",route:"/attract/provide/kits",status:"live",tables:["attract_resource_kits","attract_resource_kit_items","attract_kit_shares","attract_kit_events"],notes:"Flagship — build, share, track engagement."},{key:"kit_templates",pillar:"provide",title:"Starter Kit Library",route:"/attract/provide/kits/templates",status:"live",tables:["attract_kit_templates"],notes:"10 starter kits, clone to own."},{key:"masterclass_builder",pillar:"provide",title:"Masterclass Builder",route:"/attract/provide/masterclasses",status:"live",tables:["attract_masterclasses"],notes:"8 starter templates, deterministic copy generation, no auto-send."},{key:"value_library",pillar:"provide",title:"Value Library",route:"/attract/resources",status:"partial",tables:["attract_resources"],notes:"Read + save works; no categorization/search yet."},{key:"event_engine",pillar:"connect",title:"Event & Mastermind Engine",route:"/attract/events",status:"live",tables:["attract_events","attract_event_attendees","attract_event_invitations","attract_event_notes"],notes:"Builder, public registration, invitations, QR check-in, follow-up."},{key:"checkin",pillar:"connect",title:"Mobile Check-In",route:"/attract/events/:eventId/checkin",status:"live",tables:["attract_event_attendees"],notes:"QR + manual check-in."},{key:"coffee_meetings",pillar:"connect",title:"Coffee & Meetings",route:"/attract/follow-up",status:"partial",tables:["attract_follow_ups"],notes:"Handled as follow-ups; no dedicated meeting scheduler."},{key:"milestones",pillar:"connect",title:"Milestones & Celebrations",route:"/attract/connect/milestones",status:"live",tables:["attract_milestones","attract_follow_ups"],notes:"Recurring annual dates roll forward; reach-out tasks + celebration logging."},{key:"checkins",pillar:"connect",title:"Personal Check-Ins",route:"/attract/opportunities",status:"partial",tables:["attract_recommendations"],notes:"Surfaced by the intelligence layer as recommendations."},{key:"circles",pillar:"connect",title:"Agent Circles",route:"/attract/events/new",status:"partial",tables:["attract_events"],notes:"Create as a recurring mastermind event."},{key:"opportunities",pillar:"core",title:"Relationship Opportunities",route:"/attract/opportunities",status:"live",tables:["attract_recommendations","attract_agent_scores"],notes:"Ranked, explainable recommendations."},{key:"digest",pillar:"core",title:"Weekly Digest",route:"/attract/digest",status:"live",tables:["attract_digests","attract_digest_items","attract_digest_settings"],notes:"Manual send + preview via attract-send-digest."},{key:"plan",pillar:"core",title:"90-Day Plan",route:"/attract/plan",status:"live",tables:["attract_settings","attract_daily_plan"],notes:""},{key:"pipeline",pillar:"core",title:"Agent Pipeline",route:"/attract/pipeline",status:"live",tables:["attract_agents","attract_pipeline_history"],notes:"Kanban with stage history."},{key:"reports",pillar:"core",title:"Reports",route:"/attract/reports",status:"partial",tables:["attract_activities","attract_agents"],notes:"Core charts only; no export."}],PTe={live:"Live",partial:"Partial",placeholder:"Placeholder",integration_required:"Integration required"},rSt={live:"bg-emerald-50 text-emerald-700 border-emerald-200",partial:"bg-amber-50 text-amber-700 border-amber-200",placeholder:"bg-slate-100 text-slate-600 border-slate-200",integration_required:"bg-rose-50 text-rose-700 border-rose-200"};function Jcn({tool:s,accent:t}){const[n,r]=N.useState(!1),a=Ln(),i=s.icon,l=!!s.to,o=ITe.find(u=>u.key===s.key),c=(o==null?void 0:o.status)??(l?"live":"placeholder"),d=()=>{l&&s.to?a(s.to):r(!0)};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{onClick:d,className:"group p-5 rounded-2xl border-slate-200/70 bg-white shadow-sm hover:shadow-md cursor-pointer transition-all hover:-translate-y-0.5 relative",children:[e.jsxs("div",{className:`absolute top-3 right-3 inline-flex items-center gap-1 text-[10px] font-semibold uppercase tracking-wider rounded-full px-2 py-0.5 border ${rSt[c]}`,children:[c==="live"&&e.jsx(un,{className:"h-2.5 w-2.5"}),PTe[c]]}),e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl grid place-items-center flex-shrink-0",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.title}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-relaxed",children:s.description}),e.jsxs("div",{className:"mt-3 inline-flex items-center gap-1 text-[12.5px] font-semibold",style:{color:t},children:[s.cta??(l?"Open Tool":"Preview")," ",e.jsx(ga,{className:"h-3.5 w-3.5 group-hover:translate-x-0.5 transition-transform"})]})]})]})]}),e.jsx(_s,{open:n,onOpenChange:r,children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl grid place-items-center mb-2",style:{background:`${t}18`,color:t},children:e.jsx(i,{className:"h-6 w-6"})}),e.jsx(ws,{children:s.title})]}),e.jsxs("div",{className:"text-[14px] text-slate-700 leading-relaxed",children:[s.description,e.jsx("div",{className:"mt-4 rounded-xl bg-violet-50 border border-violet-100 p-4 text-[13px] text-violet-900",children:"This tool is on the roadmap. Mark your interest and it will jump the queue in your next release."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>r(!1),children:"Close"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{ae.success("Added to your plan"),r(!1)},children:"Add to My Plan"})]})]})})]})}function H8e({pillar:s,title:t,tagline:n,intro:r,accent:a,icon:i,tools:l,stats:o}){return e.jsxs("div",{children:[e.jsxs("div",{className:"rounded-3xl p-7 md:p-10 mb-8 relative overflow-hidden text-white",style:{background:`linear-gradient(135deg, ${a} 0%, #4f46e5 100%)`},children:[e.jsx("div",{className:"absolute -right-16 -top-16 h-64 w-64 rounded-full bg-white/10 blur-2xl"}),e.jsxs("div",{className:"relative",children:[e.jsxs("div",{className:"inline-flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] font-semibold opacity-80 mb-3",children:[e.jsx(i,{className:"h-4 w-4"})," Pillar ",s]}),e.jsx("h1",{className:"text-4xl md:text-5xl font-semibold tracking-tight",children:t}),e.jsx("p",{className:"text-white/85 text-lg mt-2",children:n}),e.jsx("p",{className:"text-white/70 mt-4 max-w-2xl leading-relaxed",children:r}),o&&e.jsx("div",{className:"mt-6 grid grid-cols-2 md:grid-cols-4 gap-3 max-w-2xl",children:o.map(c=>e.jsxs("div",{className:"rounded-xl bg-white/10 backdrop-blur px-4 py-3",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums",children:c.value}),e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider opacity-80",children:c.label})]},c.label))})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:l.map(c=>e.jsx(Jcn,{tool:c,accent:a},c.key))})]})}function ret(){return e.jsx(H8e,{pillar:"01",title:"Produce",accent:"#7c3aed",icon:xo,tagline:"Become the agent others want to be around.",intro:"Production isn't ego — it's proof. When you're actively closing, learning, and getting recognized, agents naturally lean in. Use these tools to make your production visible without bragging.",stats:[{label:"Closed YTD",value:24},{label:"Awards",value:3},{label:"Content Pieces",value:12},{label:"Speaking",value:2}],tools:[{key:"transaction_tracker",icon:oa,title:"Transaction-to-Relationship Tracker",description:"Turn great cooperating agents from real transactions into long-term professional relationships.",to:"/attract/produce/transaction-tracker"},{key:"production_goals",icon:tx,title:"Production Goals",description:"Set annual, quarterly, and monthly targets, then track whether you are ahead or behind pace.",to:"/attract/produce/goals"},{key:"awards",icon:fc,title:"Awards & Recognition",description:"Track brokerage and industry awards so you can reference them naturally in agent conversations.",to:"/attract/produce/awards"},{key:"content_calendar",icon:sy,title:"Content Calendar",description:"One month view of every draft, market update, and speaking date you have committed to.",to:"/attract/influence/content-calendar"},{key:"market_presence",icon:go,title:"Market Presence",description:"Publish market updates on a set cadence so agents see you as the local voice.",to:"/attract/produce/market-presence"},{key:"testimonials",icon:oa,title:"Client Testimonials",description:"A permission-tracked library of client quotes that make future agent conversations easier.",to:"/attract/produce/testimonials"}]})}function aet(){return e.jsx(H8e,{pillar:"02",title:"Influence",accent:"#4f46e5",icon:un,tagline:"Show up in ways that draw the right agents to you.",intro:"Influence is earned by helping publicly and consistently. These tools give you simple ways to teach, speak, and be seen — so the right agents come to you first.",stats:[{label:"Speaking Slots",value:4},{label:"Podcast Guests",value:2},{label:"Masterclasses",value:6},{label:"Reach",value:"12.4k"}],tools:[{key:"content_studio",icon:xw,title:"Authority Content Studio",description:"Turn your real experience into agent-focused content — script, caption, carousel, email — in one shot.",to:"/attract/influence/content-studio"},{key:"content_calendar",icon:Cl,title:"Content Calendar",description:"See drafts, market updates, and speaking dates on one month grid — and schedule what has no date.",to:"/attract/influence/content-calendar"},{key:"speaking",icon:Dv,title:"Speaking Calendar",description:"Track panels, MLS talks, podcasts, and keynotes from first idea through post-event follow-up.",to:"/attract/influence/speaking"},{key:"masterclass",icon:yd,title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend.",to:"/attract/provide/masterclasses"},{key:"podcast",icon:fr,title:"Podcast & Guest Spots",description:"Log podcast appearances in the Speaking Calendar and repurpose clips into agent touch points.",to:"/attract/influence/speaking"},{key:"roundtables",icon:An,title:"Agent Roundtables",description:"Host small-group conversations using the Connect Event Engine — value first, no pitching.",to:"/attract/events/new"}]})}const oP=["attract-kits"],$F=s=>["attract-kit-items",s],UF=s=>["attract-kit-shares",s??"all"],edn=s=>["attract-kit-events",s??"all"],tdn=["attract-kit-templates"];function AR(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:[...oP,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kits").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=yt({mutationFn:async o=>{if(!s)throw new Error("not authenticated");const{data:c,error:d}=await q.from("attract_resource_kits").insert({user_id:s.id,title:o.title||"Untitled Kit",...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:oP})}),a=yt({mutationFn:async({id:o,patch:c})=>{const{data:d,error:u}=await q.from("attract_resource_kits").update(c).eq("id",o).select("*").single();if(u)throw u;return d},onSuccess:()=>t.invalidateQueries({queryKey:oP})}),i=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kits").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:oP})}),l=yt({mutationFn:async o=>{const{data:c,error:d}=await q.rpc("duplicate_attract_kit",{_kit_id:o});if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:oP})});return{kits:n.data??[],isLoading:n.isLoading,create:r,update:a,remove:i,duplicate:l}}function aSt(s){return dt({queryKey:["attract-kit",s],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await q.from("attract_resource_kits").select("*").eq("id",s).single();if(n)throw n;return t}})}function sdn(s){const t=Kt(),n=dt({queryKey:$F(s??""),enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_resource_kit_items").select("*").eq("kit_id",s).order("sort_order");if(c)throw c;return o??[]}}),r=yt({mutationFn:async o=>{var u;const{data:c,error:d}=await q.from("attract_resource_kit_items").insert({kit_id:s,type:"text",title:"New item",sort_order:((u=n.data)==null?void 0:u.length)??0,...o}).select("*").single();if(d)throw d;return c},onSuccess:()=>t.invalidateQueries({queryKey:$F(s??"")})}),a=yt({mutationFn:async({id:o,patch:c})=>{const{error:d}=await q.from("attract_resource_kit_items").update(c).eq("id",o);if(d)throw d},onSuccess:()=>t.invalidateQueries({queryKey:$F(s??"")})}),i=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_resource_kit_items").delete().eq("id",o);if(c)throw c},onSuccess:()=>t.invalidateQueries({queryKey:$F(s??"")})}),l=yt({mutationFn:async o=>{await Promise.all(o.map((c,d)=>q.from("attract_resource_kit_items").update({sort_order:d}).eq("id",c)))},onSuccess:()=>t.invalidateQueries({queryKey:$F(s??"")})});return{items:n.data??[],isLoading:n.isLoading,add:r,update:a,remove:i,reorder:l}}function iSt(s){const{user:t}=vs(),n=Kt(),r=dt({queryKey:UF(s),enabled:!!t,queryFn:async()=>{let l=q.from("attract_kit_shares").select("*").order("created_at",{ascending:!1});s&&(l=l.eq("kit_id",s));const{data:o,error:c}=await l;if(c)throw c;return o??[]}}),a=yt({mutationFn:async l=>{if(!t)throw new Error("not authenticated");const{data:o,error:c}=await q.from("attract_kit_shares").insert({owner_user_id:t.id,...l}).select("*").single();if(c)throw c;return o},onSuccess:l=>{var o;n.invalidateQueries({queryKey:UF(s)}),n.invalidateQueries({queryKey:UF()});try{(o=navigator.clipboard)==null||o.writeText(lSt(l.share_token)),ae.success("Share link created and copied")}catch{ae.success("Share link created")}},onError:l=>ae.error((l==null?void 0:l.message)||"Could not create share link")}),i=yt({mutationFn:async l=>{const{error:o}=await q.from("attract_kit_shares").update({status:"revoked"}).eq("id",l);if(o)throw o},onSuccess:()=>{n.invalidateQueries({queryKey:UF(s)}),n.invalidateQueries({queryKey:UF()}),ae.success("Link revoked")},onError:l=>ae.error((l==null?void 0:l.message)||"Could not revoke link")});return{shares:r.data??[],isLoading:r.isLoading,create:a,revoke:i}}function oSt(s){return dt({queryKey:edn(s),queryFn:async()=>{let t=q.from("attract_kit_events").select("*").order("created_at",{ascending:!1}).limit(500);s&&(t=t.eq("kit_id",s));const{data:n,error:r}=await t;if(r)throw r;return n??[]}})}function ndn(){return dt({queryKey:tdn,queryFn:async()=>{const{data:s,error:t}=await q.from("attract_kit_templates").select("*").eq("is_active",!0).order("sort_order");if(t)throw t;return s??[]}})}function rdn(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.rpc("clone_attract_kit_template",{_template_id:t});if(r)throw r;return n},onSuccess:()=>s.invalidateQueries({queryKey:oP})})}function lSt(s){return`${typeof window<"u"?window.location.origin:""}/attract-kit/${s}`}function iet(){const{kits:s}=AR(),{data:t=[]}=oSt(),{followUps:n}=UU(),r=N.useMemo(()=>{const l=o=>t.filter(c=>c.event_type===o).length;return{published:s.filter(o=>o.status==="published").length,drafts:s.filter(o=>o.status==="draft").length,views:l("page_view"),downloads:l("file_download"),cta:l("primary_cta_click"),questions:l("question_submitted")}},[s,t]),a=t.slice(0,8),i=n.filter(l=>!l.completed_at&&l.touch_type==="kit_engagement").slice(0,6);return e.jsxs("div",{className:"space-y-6",children:[e.jsx(zu,{eyebrow:"Pillar 03 · Provide",title:"Give more value than any agent expected.",description:"Package the value you already share into beautiful, trackable kits. See exactly which value creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(In,{to:"/attract/provide/kits/templates",children:[e.jsx(qg,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsx(B,{asChild:!0,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsxs(In,{to:"/attract/provide/kits/new",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New kit"]})})]})}),e.jsx(fe,{className:"p-6 md:p-8 rounded-2xl bg-gradient-to-br from-teal-50 via-violet-50 to-indigo-50 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-white grid place-items-center shadow-sm",children:e.jsx(jA,{className:"h-6 w-6 text-teal-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Resource Kits — the flagship of Provide"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Bundle 3–7 pieces of real value (scripts, checklists, videos, tools) into a beautiful shareable kit. Send a personalized link to an agent, then let engagement recommend the next relationship touch. No pressure. Just real value that compounds."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(B,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(In,{to:"/attract/provide/kits/new",children:"Start a kit"})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsx(In,{to:"/attract/provide/kits/templates",children:"Browse 10 starter kits"})})]})]})]})}),e.jsx(fe,{className:"p-6 rounded-2xl border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 grid place-items-center",children:e.jsx(un,{className:"h-6 w-6 text-violet-600"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"Masterclass Builder"}),e.jsx("p",{className:"text-[13.5px] text-slate-700 mt-1 max-w-3xl",children:"Turn what you already know into a 45-minute teaching moment. Build the curriculum, workbook, promotion drafts and run-of-show — then convert it into a Connect event or a Resource Kit in one click."}),e.jsx("div",{className:"flex gap-2 mt-4",children:e.jsx(B,{asChild:!0,size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:e.jsx(In,{to:"/attract/provide/masterclasses",children:"Open Masterclass Builder"})})})]})]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-6 gap-3",children:[e.jsx(GI,{label:"Published",value:r.published}),e.jsx(GI,{label:"Drafts",value:r.drafts}),e.jsx(GI,{label:"Views",value:r.views,icon:Sr}),e.jsx(GI,{label:"Downloads",value:r.downloads,icon:Ia}),e.jsx(GI,{label:"CTA clicks",value:r.cta,icon:oc}),e.jsx(GI,{label:"Questions",value:r.questions,icon:Zl})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Recent kit engagement"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Live signals from agents opening your value."})]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs(In,{to:"/attract/provide/kits",children:["View kits ",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]})})]}),a.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-8 text-center border border-dashed rounded-xl",children:"No engagement yet. Share a published kit to start seeing activity."}):e.jsx("div",{className:"space-y-2",children:a.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsx("div",{className:"capitalize",children:l.event_type.replace(/_/g," ")}),e.jsx("div",{className:"text-slate-500 text-[11.5px]",children:Uo(new Date(l.created_at),{addSuffix:!0})})]},l.id))})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Recommended follow-ups"}),i.length===0?e.jsx("div",{className:"text-sm text-slate-500 py-6 text-center border border-dashed rounded-xl",children:"We'll surface follow-ups here as agents engage."}):e.jsx("div",{className:"space-y-2",children:i.map(l=>e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsx("div",{className:"font-medium text-slate-900 line-clamp-2",children:l.title}),l.due_at&&e.jsxs("div",{className:"text-slate-500 text-[11px] mt-1",children:["Due ",Uo(new Date(l.due_at),{addSuffix:!0})]})]},l.id))})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"My kits"}),e.jsx(B,{size:"sm",variant:"ghost",asChild:!0,children:e.jsxs(In,{to:"/attract/provide/kits",children:["See all ",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]})})]}),s.length===0?e.jsxs("div",{className:"text-sm text-slate-500 py-8 text-center border border-dashed rounded-xl",children:["No kits yet. ",e.jsx(In,{to:"/attract/provide/kits/templates",className:"text-violet-700 underline",children:"Start from a template"}),"."]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-3",children:s.slice(0,6).map(l=>e.jsxs(In,{to:`/attract/provide/kits/${l.id}/edit`,className:"block p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ue,{variant:"outline",className:"capitalize",children:l.status}),l.pillar&&e.jsx(Ue,{variant:"secondary",className:"capitalize",children:l.pillar})]}),e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:l.title}),l.description&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:l.description})]},l.id))})]}),e.jsx(l6,{})]})}function GI({label:s,value:t,icon:n}){return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[n&&e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[20px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function oet(){return e.jsx(H8e,{pillar:"04",title:"Connect",accent:"#9333ea",icon:NA,tagline:"Real relationships. On a rhythm. For years.",intro:"Connect is the pillar that makes the other three matter. It's showing up in the small, consistent ways real friendships require — birthdays, coffees, check-ins, celebrations.",stats:[{label:"Coffees This Q",value:14},{label:"Events Hosted",value:3},{label:"Birthdays Sent",value:22},{label:"On Cadence",value:"87%"}],tools:[{key:"coffee_meetings",icon:ey,title:"Coffee & Meetings",description:"The coffees to book this month, tracked as follow-ups in your Follow-Up Center.",to:"/attract/follow-up"},{key:"event_engine",icon:yr,title:"Attraction Events",description:"Design intimate gatherings — happy hours, dinners, mastermind lunches — with registration and check-in.",to:"/attract/events"},{key:"milestones",icon:Ah,title:"Milestones & Celebrations",description:"Never miss a birthday, license anniversary, or business milestone for a prospective agent.",to:"/attract/connect/milestones"},{key:"checkins",icon:Zl,title:"Personal Check-Ins",description:"Relationship-first check-ins surfaced by your intelligence layer, ranked by signal.",to:"/attract/opportunities"},{key:"circles",icon:q0,title:"Agent Circles",description:"Small peer groups you host quarterly — built on the Connect Event Engine.",to:"/attract/events/new"}]})}const adn=[{key:"coffee",label:"Coffee & Conversation",icon:ey,tone:"from-amber-500 to-orange-500",description:"A 1:1 or 3-person coffee where the goal is one real conversation."},{key:"roundtable",label:"Agent Roundtable",icon:q0,tone:"from-violet-500 to-indigo-500",description:"4–6 agents share what is actually working right now."},{key:"mastermind",label:"Mastermind",icon:un,tone:"from-fuchsia-500 to-pink-500",description:"A quarterly small group solving each other’s biggest questions."},{key:"workshop",label:"Workshop / Webinar",icon:Ac,tone:"from-sky-500 to-blue-500",description:"A live hands-on session that delivers one clear outcome."},{key:"dinner",label:"Dinner or Happy Hour",icon:M9,tone:"from-rose-500 to-red-500",description:"The relationship-first gathering. No agenda, just presence."},{key:"networking_plan",label:"Networking Game Plan",icon:NA,tone:"from-teal-500 to-emerald-500",description:"Not an event — a plan for the next 5 rooms you will walk into."}];function idn(){const s=Ln(),{data:t=[]}=K1e(),{followUps:n}=UU(),{agents:r}=i0(),a=N.useMemo(()=>{const l=new Date,o=Bl(l,7),c=t.filter(p=>p.status==="published"&&Ov(new Date(p.starts_at),l)),d=t.filter(p=>p.status==="draft").length,u=t.reduce((p,f)=>p+(Ov(new Date(f.created_at),Bl(l,-7))?f.registration_count:0),0),h=n.filter(p=>!p.completed_at&&p.due_at&&yb(new Date(p.due_at),o)&&(p.touch_type==="event_followup"||p.touch_type==="event_no_show")).length;return{upcoming:c,draftsNeedingInvites:d,regs:u,dueSoon:h}},[t,n]),i=a.upcoming[0];return e.jsxs("div",{className:"space-y-8",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Pillar 04 · Connect"}),e.jsx("h1",{className:"text-3xl md:text-[34px] font-semibold tracking-tight text-slate-900",children:"Real events. Small rooms. Long relationships."}),e.jsx("p",{className:"text-slate-600 mt-1.5 max-w-2xl",children:"Build the room, invite personally, host with care, capture one honest note, and follow up within 48 hours."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>s("/attract/events"),children:[e.jsx(yr,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700",onClick:()=>s("/attract/events/new"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Create an event"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[{label:"Upcoming events",value:a.upcoming.length,icon:yr,tone:"text-violet-700 bg-violet-100"},{label:"Drafts needing invites",value:a.draftsNeedingInvites,icon:lr,tone:"text-amber-700 bg-amber-100"},{label:"Registrations this week",value:a.regs,icon:go,tone:"text-emerald-700 bg-emerald-100"},{label:"48-hour follow-ups due",value:a.dueSoon,icon:lu,tone:"text-rose-700 bg-rose-100"}].map(l=>e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:`h-9 w-9 rounded-xl grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4.5 w-4.5"})}),e.jsx("div",{className:"text-[26px] font-semibold tabular-nums mt-3",children:l.value}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:l.label})]},l.label))}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"lg:col-span-2 p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white overflow-hidden relative",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60 mb-2",children:"Your next event"}),i?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl md:text-2xl font-semibold",children:i.title}),e.jsxs("div",{className:"text-white/70 mt-1",children:[Ss(new Date(i.starts_at),"EEE, MMM d · h:mm a")," · ",i.format.replace("_"," ")]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[e.jsxs(Ue,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[i.registration_count," registered"]}),i.capacity&&e.jsxs(Ue,{variant:"secondary",className:"bg-white/10 border-white/10 text-white",children:[Math.max(0,i.capacity-i.registration_count)," seats left"]})]}),e.jsxs("div",{className:"mt-5 flex gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s(`/attract/events/${i.id}`),children:["Open command center ",e.jsx(Oa,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full bg-transparent text-white border-white/30 hover:bg-white/10",onClick:()=>s(`/attract/events/${i.id}/checkin`),children:"Mobile check-in"})]})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold",children:"No upcoming events yet"}),e.jsx("div",{className:"text-white/70 mt-1",children:"Start with a small coffee. One conversation is enough."}),e.jsx(B,{size:"sm",className:"mt-5 rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:()=>s("/attract/events/new?type=coffee"),children:"Plan a coffee"})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-amber-200 bg-amber-50",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-amber-700 font-semibold mb-2",children:"Reminder"}),e.jsx("div",{className:"text-[15px] text-slate-900 leading-relaxed",children:"Build relationships first. Personalize every invitation and follow-up, and verify brokerage and compensation information before sharing."})]})]}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Quick starts"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"What kind of room do you want to build?"})]}),e.jsxs(In,{to:"/attract/events/new",className:"text-[13px] text-violet-700 hover:underline flex items-center gap-1",children:["Start from scratch ",e.jsx(ga,{className:"h-3.5 w-3.5"})]})]}),e.jsx("div",{className:"grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4",children:adn.map(l=>e.jsxs("button",{onClick:()=>s(`/attract/events/new?type=${l.key}`),className:"group text-left rounded-2xl border border-slate-200 bg-white p-5 hover:border-violet-300 hover:shadow-md transition",children:[e.jsx("div",{className:`h-10 w-10 rounded-xl grid place-items-center bg-gradient-to-br ${l.tone} text-white shadow-sm`,children:e.jsx(l.icon,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-3",children:l.label}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1 leading-snug",children:l.description}),e.jsxs("div",{className:"text-[12px] text-violet-700 mt-3 flex items-center gap-1 opacity-0 group-hover:opacity-100 transition",children:["Start planning ",e.jsx(Oa,{className:"h-3 w-3"})]})]},l.key))})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center justify-between mb-4",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold",children:"Personal connection goals"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900",children:"This week"})]}),e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>s("/attract/follow-up"),children:"Open Follow-Up Center"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[{label:"Coffees booked",target:3,actual:a.upcoming.filter(l=>(l.event_type_key||l.event_type)==="coffee").length,icon:ey,tone:"text-amber-600 bg-amber-50"},{label:"Roundtables/masterminds",target:1,actual:a.upcoming.filter(l=>["roundtable","mastermind"].includes(l.event_type_key||l.event_type)).length,icon:un,tone:"text-violet-600 bg-violet-50"},{label:"People in pipeline",target:r.length,actual:r.length,icon:q0,tone:"text-emerald-600 bg-emerald-50"}].map(l=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-4",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${l.tone}`,children:e.jsx(l.icon,{className:"h-4 w-4"})}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums mt-2 leading-none",children:[l.actual,e.jsxs("span",{className:"text-slate-400 text-[15px] font-normal",children:[" / ",l.target]})]}),e.jsx("div",{className:"text-[12px] text-slate-500 mt-1",children:l.label})]},l.label))})]})]})}function odn(){const s=Ln(),{data:t=[],isLoading:n}=K1e(),r=Acn(),a=Ccn(),[i,l]=N.useState("all"),[o,c]=N.useState(""),d=N.useMemo(()=>t.filter(u=>!(i!=="all"&&u.status!==i||o&&!u.title.toLowerCase().includes(o.toLowerCase()))),[t,i,o]);return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center md:justify-between gap-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Connect · Events"}),e.jsx("h1",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"Events"}),e.jsx("p",{className:"text-slate-600 mt-1",children:"Every room you have built — drafted, live, and complete."})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs("div",{className:"relative",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{placeholder:"Search events",className:"pl-9 rounded-full w-[240px] bg-white",value:o,onChange:u=>c(u.target.value)})]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 hover:from-violet-700 hover:to-indigo-700",onClick:()=>s("/attract/events/new"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," New event"]})]})]}),e.jsxs(Fr,{value:i,onValueChange:u=>l(u),children:[e.jsxs(Rr,{className:"rounded-full bg-white border border-slate-200",children:[e.jsxs(Zt,{value:"all",className:"rounded-full",children:["All (",t.length,")"]}),e.jsxs(Zt,{value:"draft",className:"rounded-full",children:["Drafts (",t.filter(u=>u.status==="draft").length,")"]}),e.jsxs(Zt,{value:"published",className:"rounded-full",children:["Published (",t.filter(u=>u.status==="published").length,")"]}),e.jsxs(Zt,{value:"completed",className:"rounded-full",children:["Completed (",t.filter(u=>u.status==="completed").length,")"]})]}),e.jsx(is,{value:i,className:"mt-5",children:n?e.jsx(fe,{className:"p-12 rounded-2xl text-center text-slate-500",children:"Loading events…"}):d.length===0?e.jsxs(fe,{className:"p-12 rounded-2xl text-center border-dashed",children:[e.jsx(yr,{className:"h-8 w-8 text-slate-300 mx-auto"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mt-3",children:"No events here yet"}),e.jsx("div",{className:"text-slate-500 mt-1",children:"Start with a small coffee or a mastermind — one conversation is enough."}),e.jsxs(B,{className:"mt-4 rounded-full",onClick:()=>s("/attract/events/new"),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Create your first event"]})]}):e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-5",children:d.map(u=>e.jsxs(fe,{className:"group rounded-2xl border-slate-200 bg-white overflow-hidden hover:shadow-md transition",children:[e.jsxs("div",{className:"h-32 bg-gradient-to-br from-violet-500 to-indigo-600 relative",children:[u.cover_image_url&&e.jsx("img",{src:u.cover_image_url,alt:"",className:"absolute inset-0 h-full w-full object-cover"}),e.jsxs("div",{className:"absolute top-3 left-3 flex gap-2",children:[e.jsx(Ue,{className:u.status==="published"?"bg-emerald-500":u.status==="completed"?"bg-slate-500":u.status==="cancelled"?"bg-rose-500":"bg-amber-500",children:u.status}),u.related_pillar&&e.jsx(Ue,{variant:"secondary",className:"bg-white/90 text-slate-800 capitalize",children:u.related_pillar})]})]}),e.jsxs("div",{className:"p-4",children:[e.jsxs("button",{onClick:()=>s(`/attract/events/${u.id}`),className:"text-left block w-full",children:[e.jsx("div",{className:"text-[15.5px] font-semibold text-slate-900 line-clamp-1",children:u.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:Ss(new Date(u.starts_at),"EEE, MMM d · h:mm a")})]}),e.jsxs("div",{className:"flex items-center gap-3 text-[12px] text-slate-500 mt-3",children:[u.format==="virtual"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fr,{className:"h-3.5 w-3.5"})," Virtual"]}):u.format==="hybrid"?e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(fr,{className:"h-3.5 w-3.5"})," Hybrid"]}):e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(ka,{className:"h-3.5 w-3.5"})," ",u.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(An,{className:"h-3.5 w-3.5"})," ",u.registration_count,u.capacity?` / ${u.capacity}`:""]})]}),e.jsxs("div",{className:"flex items-center justify-between mt-4",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>r.mutate(u.id),children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"})," Duplicate"]}),u.status==="published"&&u.public_slug&&e.jsxs(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-slate-500",onClick:()=>{navigator.clipboard.writeText(Y1e(u.public_slug)),ae.success("Registration link copied")},children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Link"]})]}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 rounded-full text-rose-600 hover:bg-rose-50",onClick:()=>{confirm("Delete this event?")&&a.mutate(u.id)},children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]},u.id))})})]})]})}const ldn=[{key:"coffee",label:"Coffee & Conversation"},{key:"roundtable",label:"Roundtable"},{key:"mastermind",label:"Mastermind"},{key:"workshop",label:"Workshop / Webinar"},{key:"dinner",label:"Dinner / Happy Hour"},{key:"networking",label:"Networking Event"},{key:"custom",label:"Custom"}];function cet(){const{eventId:s}=bi(),t=Ln(),[n]=xl(),r=n.get("type"),a=!!s,{data:i}=V8e(s),{data:l=[]}=Qkt(),{kits:o}=AR(),c=Xkt(),d=Jkt(),[u,h]=N.useState({title:"",description:"",event_type_key:r||"coffee",intended_audience:"",related_pillar:"connect",starts_at:new Date(Date.now()+7*864e5).toISOString().slice(0,16),ends_at:"",timezone:"America/New_York",format:"in_person",location:"",address:"",virtual_url:"",capacity:"",waitlist_enabled:!0,host_name:"",cohosts:[],agenda:[],learning_outcomes:[],registration_questions:[],confirmation_message:"",resource_kit_id:null,kit_delivery_trigger:"after_attendance",followup_hours:48});N.useEffect(()=>{i&&h({...i,starts_at:i.starts_at?i.starts_at.slice(0,16):"",ends_at:i.ends_at?i.ends_at.slice(0,16):"",capacity:i.capacity??"",cohosts:i.cohosts||[],agenda:i.agenda||[],learning_outcomes:i.learning_outcomes||[],registration_questions:i.registration_questions||[]})},[i]);const p=j=>h(w=>({...w,...j})),f=N.useMemo(()=>l.slice(0,4),[l]),y=j=>{p({title:j.title,description:j.description,event_type_key:j.event_type_key,related_pillar:j.related_pillar,intended_audience:j.intended_audience,agenda:j.suggested_agenda||[],learning_outcomes:j.suggested_outcomes||[],registration_questions:j.suggested_questions||[],confirmation_message:j.suggested_confirmation}),ae.success(`Loaded "${j.title}"`)},_=async(j={})=>{const w={...u,starts_at:u.starts_at?new Date(u.starts_at).toISOString():new Date().toISOString(),ends_at:u.ends_at?new Date(u.ends_at).toISOString():null,capacity:u.capacity===""?null:Number(u.capacity),status:j.publish?"published":u.status||"draft"};if(a)await d.mutateAsync({id:s,patch:w}),ae.success(j.publish?"Published":"Saved");else{const S=await c.mutateAsync(w);ae.success(j.publish?"Event published":"Draft saved"),t(`/attract/events/${S.id}${j.publish?"":"/edit"}`,{replace:!0})}},v=i!=null&&i.public_slug?Y1e(i.public_slug):null;return e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2",children:[v&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(v),ae.success("Registration link copied")},children:[e.jsx(Yo,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>_(),children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs(B,{size:"sm",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({publish:!0}),children:[e.jsx(tx,{className:"h-4 w-4 mr-2"})," ",(i==null?void 0:i.status)==="published"?"Update published":"Publish"]})]})]}),!a&&f.length>0&&e.jsxs(fe,{className:"p-5 rounded-2xl border-violet-200 bg-gradient-to-br from-violet-50 to-indigo-50",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:"Start from a premium template"})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:f.map(j=>e.jsxs("button",{onClick:()=>y(j),className:"text-left rounded-xl bg-white/70 border border-white p-3 hover:bg-white transition",children:[e.jsx("div",{className:"text-[13.5px] font-semibold text-slate-900",children:j.title}),e.jsx("div",{className:"text-[12px] text-slate-600 line-clamp-2 mt-0.5",children:j.description})]},j.id))})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 1"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Event basics"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:u.title,onChange:j=>p({title:j.target.value}),placeholder:"Coffee & Systems Roundtable"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Event type"}),e.jsxs(us,{value:u.event_type_key,onValueChange:j=>p({event_type_key:j}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:ldn.map(j=>e.jsx(Ze,{value:j.key,children:j.label},j.key))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Related pillar"}),e.jsxs(us,{value:u.related_pillar||"connect",onValueChange:j=>p({related_pillar:j}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"produce",children:"Produce"}),e.jsx(Ze,{value:"influence",children:"Influence"}),e.jsx(Ze,{value:"provide",children:"Provide"}),e.jsx(Ze,{value:"connect",children:"Connect"})]})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Intended audience"}),e.jsx(ye,{value:u.intended_audience||"",onChange:j=>p({intended_audience:j.target.value}),placeholder:"Producing agents 1–5 years in"})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{rows:4,value:u.description||"",onChange:j=>p({description:j.target.value}),placeholder:"What is this event and why does it matter?"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Starts at"}),e.jsx(ye,{type:"datetime-local",value:u.starts_at||"",onChange:j=>p({starts_at:j.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Ends at"}),e.jsx(ye,{type:"datetime-local",value:u.ends_at||"",onChange:j=>p({ends_at:j.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Time zone"}),e.jsxs(us,{value:u.timezone||"America/New_York",onValueChange:j=>p({timezone:j}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:["America/New_York","America/Chicago","America/Denver","America/Los_Angeles","America/Phoenix"].map(j=>e.jsx(Ze,{value:j,children:j},j))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Format"}),e.jsxs(us,{value:u.format,onValueChange:j=>p({format:j}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"in_person",children:"In person"}),e.jsx(Ze,{value:"virtual",children:"Virtual"}),e.jsx(Ze,{value:"hybrid",children:"Hybrid"})]})]})]}),u.format!=="virtual"&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Venue / location name"}),e.jsx(ye,{value:u.location||"",onChange:j=>p({location:j.target.value}),placeholder:"Rise Coffee — Downtown"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Address"}),e.jsx(ye,{value:u.address||"",onChange:j=>p({address:j.target.value}),placeholder:"123 Main St, City, ST"})]})]}),u.format!=="in_person"&&e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Virtual meeting URL"}),e.jsx(ye,{value:u.virtual_url||"",onChange:j=>p({virtual_url:j.target.value}),placeholder:"https://zoom.us/…"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Capacity (optional)"}),e.jsx(ye,{type:"number",value:u.capacity,onChange:j=>p({capacity:j.target.value}),placeholder:"No limit"})]}),e.jsxs("div",{className:"flex items-center gap-3 pt-6",children:[e.jsx(jn,{checked:u.waitlist_enabled,onCheckedChange:j=>p({waitlist_enabled:j}),id:"wl"}),e.jsx(ne,{htmlFor:"wl",className:"cursor-pointer",children:"Allow waitlist if full"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Host name (as shown publicly)"}),e.jsx(ye,{value:u.host_name||"",onChange:j=>p({host_name:j.target.value}),placeholder:"Jeremy from LevelUp"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Cover image URL"}),e.jsx(ye,{value:u.cover_image_url||"",onChange:j=>p({cover_image_url:j.target.value}),placeholder:"https://…"})]})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 2"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Experience & agenda"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{children:"Agenda"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>p({agenda:[...u.agenda||[],{time:"",item:""}]}),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add item"]})]}),e.jsxs("div",{className:"space-y-2",children:[(u.agenda||[]).map((j,w)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{className:"w-24",value:j.time||"",onChange:S=>{const A=[...u.agenda];A[w]={...A[w],time:S.target.value},p({agenda:A})},placeholder:"0:00"}),e.jsx(ye,{value:j.item||"",onChange:S=>{const A=[...u.agenda];A[w]={...A[w],item:S.target.value},p({agenda:A})},placeholder:"What happens here"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({agenda:u.agenda.filter((S,A)=>A!==w)}),children:e.jsx($n,{className:"h-4 w-4"})})]},w)),(u.agenda||[]).length===0&&e.jsx("div",{className:"text-[12px] text-slate-400",children:"Add each moment of the event so attendees know what to expect."})]})]}),e.jsx(al,{}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{children:"What attendees will receive"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>p({learning_outcomes:[...u.learning_outcomes||[],""]}),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add outcome"]})]}),e.jsx("div",{className:"space-y-2",children:(u.learning_outcomes||[]).map((j,w)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:j,onChange:S=>{const A=[...u.learning_outcomes];A[w]=S.target.value,p({learning_outcomes:A})},placeholder:"One clear, honest outcome"}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({learning_outcomes:u.learning_outcomes.filter((S,A)=>A!==w)}),children:e.jsx($n,{className:"h-4 w-4"})})]},w))})]})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 3"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Registration page"}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx(ne,{children:"Registration questions"}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>p({registration_questions:[...u.registration_questions||[],{key:`q${(u.registration_questions||[]).length+1}`,label:"",type:"text"}]}),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add question"]})]}),e.jsx("div",{className:"space-y-2",children:(u.registration_questions||[]).map((j,w)=>e.jsxs("div",{className:"flex gap-2 items-center",children:[e.jsx(ye,{className:"flex-1",value:j.label,onChange:S=>{const A=[...u.registration_questions];A[w]={...A[w],label:S.target.value,key:j.key||`q${w+1}`},p({registration_questions:A})},placeholder:"Question shown to registrants"}),e.jsxs(us,{value:j.type,onValueChange:S=>{const A=[...u.registration_questions];A[w]={...A[w],type:S},p({registration_questions:A})},children:[e.jsx(ls,{className:"w-32",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"text",children:"Short text"}),e.jsx(Ze,{value:"long",children:"Long text"})]})]}),e.jsx(B,{size:"icon",variant:"ghost",onClick:()=>p({registration_questions:u.registration_questions.filter((S,A)=>A!==w)}),children:e.jsx($n,{className:"h-4 w-4"})})]},w))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Confirmation message (shown after registration)"}),e.jsx(Ms,{rows:3,value:u.confirmation_message||"",onChange:j=>p({confirmation_message:j.target.value}),placeholder:"You are in — come with one honest question."})]})]})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 4"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-4",children:"Resource Kit & 48-hour follow-up"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Attach a Resource Kit"}),e.jsxs(us,{value:u.resource_kit_id||"none",onValueChange:j=>p({resource_kit_id:j==="none"?null:j}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"None"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"None"}),(o||[]).map(j=>e.jsx(Ze,{value:j.id,children:j.title},j.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Deliver kit"}),e.jsxs(us,{value:u.kit_delivery_trigger||"after_attendance",onValueChange:j=>p({kit_delivery_trigger:j}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"on_registration",children:"On registration"}),e.jsx(Ze,{value:"on_confirmation",children:"On confirmation"}),e.jsx(Ze,{value:"on_check_in",children:"At check-in"}),e.jsx(Ze,{value:"after_attendance",children:"After attendance"}),e.jsx(Ze,{value:"manual",children:"Only manually"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Default follow-up window (hours)"}),e.jsx(ye,{type:"number",value:u.followup_hours??48,onChange:j=>p({followup_hours:Number(j.target.value)})})]})]}),!u.resource_kit_id&&e.jsx("div",{className:"text-[12px] text-amber-700 bg-amber-50 border border-amber-200 rounded-lg p-3 mt-4",children:"Tip: attach a Resource Kit so attendees leave with something valuable — and so follow-ups have a natural reason."})]}),e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Step 5"}),e.jsx("div",{className:"text-lg font-semibold text-slate-900 mb-3",children:"Review & publish"}),e.jsxs("div",{className:"text-[13px] text-slate-600 leading-relaxed",children:["Publishing generates a premium public registration page at"," ",e.jsxs("code",{className:"bg-slate-100 px-1.5 py-0.5 rounded text-slate-800",children:["/attract-event/",(i==null?void 0:i.public_slug)||""]})," ","and enables the personal invitation flow. You can unpublish or cancel at any time."]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-4",children:[(!u.title||!u.starts_at)&&e.jsx(Ue,{variant:"secondary",className:"bg-rose-50 text-rose-700 border-rose-200",children:"Add title and start time"}),(u.agenda||[]).length===0&&e.jsx(Ue,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No agenda yet"}),(u.learning_outcomes||[]).length===0&&e.jsx(Ue,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No stated outcomes"}),!u.resource_kit_id&&e.jsx(Ue,{variant:"secondary",className:"bg-amber-50 text-amber-700 border-amber-200",children:"No Resource Kit attached"})]}),e.jsxs("div",{className:"flex justify-end gap-2 mt-5",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>_(),children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"})," Save draft"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({publish:!0}),children:[e.jsx(tx,{className:"h-4 w-4 mr-2"})," Publish"]})]})]})]})}const ape=s=>s?[s.first_name,s.last_name].filter(Boolean).join(" "):"";function cdn(){const{eventId:s}=bi(),t=Ln(),{data:n}=V8e(s),{data:r=[]}=Zkt(s),{data:a=[]}=kcn(s),{data:i=[]}=Scn(s),{agents:l}=i0(),{data:o=[]}=Qkt(),c=eSt(),d=Tcn(),u=Ecn(),h=Jkt(),p=N.useMemo(()=>{const _=r.length,v=r.filter(F=>F.status==="registered"||F.status==="confirmed").length,j=r.filter(F=>F.status==="attended").length,w=r.filter(F=>F.status==="no_show").length,S=r.filter(F=>F.status==="waitlisted").length,A=v+j+w,E=A>0?Math.round(j/A*100):0,O=a.length>0?Math.round(a.filter(F=>F.viewed_at).length/a.length*100):0,D=r.filter(F=>F.followup_status==="done").length,I=j>0?Math.round(D/j*100):0;return{total:_,registered:v,attended:j,noShow:w,waitlist:S,attendRate:E,invView:O,followed:D,followedRate:I}},[r,a]);if(!n)return e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"});const f=n.public_slug?Y1e(n.public_slug):null,y=()=>{const _=new Blob([tSt(n)],{type:"text/calendar"}),v=URL.createObjectURL(_),j=document.createElement("a");j.href=v,j.download=`${n.public_slug||"event"}.ics`,j.click(),URL.revokeObjectURL(v)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-3",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>t("/attract/events"),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"})," All events"]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:y,children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-2"})," ICS"]}),f&&e.jsxs(B,{variant:"outline",size:"sm",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(f),ae.success("Link copied")},children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]}),f&&e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:f,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-2"})," Preview page"]})}),e.jsxs(B,{size:"sm",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(ry,{className:"h-3.5 w-3.5 mr-2"})," Check-in mode"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Edit"})]})]}),e.jsx(fe,{className:"p-6 rounded-2xl border-slate-200 bg-gradient-to-br from-slate-900 to-slate-800 text-white",children:e.jsxs("div",{className:"flex items-start justify-between gap-4 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[e.jsx(Ue,{className:n.status==="published"?"bg-emerald-500":n.status==="completed"?"bg-slate-500":n.status==="cancelled"?"bg-rose-500":"bg-amber-500",children:n.status}),n.related_pillar&&e.jsx(Ue,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.related_pillar}),n.event_type_key&&e.jsx(Ue,{variant:"secondary",className:"bg-white/10 border-white/10 text-white capitalize",children:n.event_type_key.replace("_"," ")})]}),e.jsx("div",{className:"text-2xl md:text-3xl font-semibold",children:n.title}),e.jsxs("div",{className:"text-white/70 mt-1 flex items-center gap-4 flex-wrap",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-4 w-4"})," ",Ss(new Date(n.starts_at),"EEE, MMM d · h:mm a")]}),n.format==="virtual"?e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(fr,{className:"h-4 w-4"})," Virtual"]}):e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(ka,{className:"h-4 w-4"})," ",n.location||"In person"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx(An,{className:"h-4 w-4"})," ",n.registration_count," registered",n.capacity?` / ${n.capacity}`:""]})]})]}),n.status==="draft"&&e.jsx(B,{className:"rounded-full bg-white text-slate-900 hover:bg-white/90",onClick:async()=>{await h.mutateAsync({id:n.id,patch:{status:"published"}}),ae.success("Published")},children:"Publish now"}),n.status==="published"&&new Date(n.starts_at){await h.mutateAsync({id:n.id,patch:{status:"completed"}}),ae.success("Marked completed")},children:"Mark completed"})]})}),e.jsxs(Fr,{defaultValue:"overview",children:[e.jsxs(Rr,{className:"rounded-full bg-white border border-slate-200 flex-wrap h-auto",children:[e.jsx(Zt,{value:"overview",className:"rounded-full",children:"Overview"}),e.jsxs(Zt,{value:"invitations",className:"rounded-full",children:["Invitations (",a.length,")"]}),e.jsxs(Zt,{value:"registrations",className:"rounded-full",children:["Registrations (",r.length,")"]}),e.jsxs(Zt,{value:"notes",className:"rounded-full",children:["Notes (",i.length,")"]}),e.jsx(Zt,{value:"kit",className:"rounded-full",children:"Resource Kit"}),e.jsx(Zt,{value:"followup",className:"rounded-full",children:"48-hour follow-up"}),e.jsx(Zt,{value:"analytics",className:"rounded-full",children:"Analytics"})]}),e.jsxs(is,{value:"overview",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4 mb-6",children:[e.jsx(uv,{icon:An,label:"Registered",value:p.registered+p.attended}),e.jsx(uv,{icon:Lr,label:"Attended",value:p.attended}),e.jsx(uv,{icon:_o,label:"Attendance rate",value:`${p.attendRate}%`}),e.jsx(uv,{icon:lu,label:"Follow-up completion",value:`${p.followedRate}%`})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),(n.agenda||[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"No agenda yet"}):e.jsx("ul",{className:"space-y-2",children:n.agenda.map((_,v)=>e.jsxs("li",{className:"flex gap-3 text-[14px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:_.time||""}),e.jsx("span",{className:"text-slate-800",children:_.item})]},v))}),(n.learning_outcomes||[]).length>0&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mt-6 mb-2",children:"What attendees receive"}),e.jsx("ul",{className:"space-y-1.5",children:n.learning_outcomes.map((_,v)=>e.jsxs("li",{className:"text-[13.5px] text-slate-700 flex gap-2",children:[e.jsx(Lr,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",_]},v))})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Share"}),f?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Registration page"}),e.jsx("div",{className:"text-[12.5px] font-mono bg-slate-50 border border-slate-200 rounded-lg p-2 break-all",children:f}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full mt-2 w-full",onClick:()=>{navigator.clipboard.writeText(f),ae.success("Copied")},children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-2"})," Copy link"]})]}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"Publish the event to generate a shareable registration link."}),n.check_in_token&&e.jsxs("div",{className:"mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500 mb-1",children:"Check-in mode"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full w-full",onClick:()=>t(`/attract/events/${n.id}/checkin`),children:[e.jsx(ry,{className:"h-3.5 w-3.5 mr-2"})," Open check-in"]})]})]})]})]}),e.jsx(is,{value:"invitations",className:"mt-5",children:e.jsx(ddn,{eventId:n.id,eventSlug:n.public_slug,agents:l,invitations:a,templates:o,onCreate:u.mutate})}),e.jsx(is,{value:"registrations",className:"mt-5",children:e.jsx(udn,{eventId:n.id,attendees:r,onUpsert:c.mutate,checkInToken:n.check_in_token})}),e.jsx(is,{value:"notes",className:"mt-5",children:e.jsx(hdn,{eventId:n.id,attendees:r,notes:i,onCreate:d.mutate})}),e.jsx(is,{value:"kit",className:"mt-5",children:e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-1",children:"Resource Kit"}),n.resource_kit_id?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:"A Resource Kit is attached to this event."}),e.jsxs("div",{className:"text-[13px] text-slate-600 mt-1",children:["Deliver trigger: ",e.jsx("span",{className:"font-medium capitalize",children:(n.kit_delivery_trigger||"after_attendance").replace(/_/g," ")})]}),e.jsx(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>t(`/attract/provide/kits/${n.resource_kit_id}/analytics`),children:"Open kit analytics"})]}):e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-[15px] text-slate-700",children:"No kit attached yet. Attach one so attendees leave with something valuable."}),e.jsxs("div",{className:"flex gap-2 mt-4",children:[e.jsx(B,{className:"rounded-full",onClick:()=>t(`/attract/events/${n.id}/edit`),children:"Attach a kit"}),e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>t("/attract/provide/kits/new"),children:"Create a new kit"})]})]})]})}),e.jsx(is,{value:"followup",className:"mt-5",children:e.jsx(mdn,{eventId:n.id,attendees:r,onUpsert:c.mutate})}),e.jsxs(is,{value:"analytics",className:"mt-5",children:[e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-4",children:[e.jsx(uv,{icon:lr,label:"Invitations sent",value:a.length}),e.jsx(uv,{icon:tr,label:"Invitation view rate",value:`${p.invView}%`}),e.jsx(uv,{icon:An,label:"Registered",value:p.registered+p.attended}),e.jsx(uv,{icon:Lr,label:"Attended",value:p.attended}),e.jsx(uv,{icon:_o,label:"Attendance rate",value:`${p.attendRate}%`}),e.jsx(uv,{icon:lu,label:"Follow-up complete (48h)",value:`${p.followedRate}%`}),e.jsx(uv,{icon:xw,label:"Notes captured",value:i.length}),e.jsx(uv,{icon:Fo,label:"Meetings requested",value:r.filter(_=>_.meeting_requested).length})]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-3",children:["Where attribution is uncertain, we label movement as ",e.jsx("em",{children:"influenced"})," rather than caused."]})]})]})]})}function uv({icon:s,label:t,value:n}){return e.jsxs(fe,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-slate-500 text-[12px]",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("div",{className:"text-[24px] font-semibold tabular-nums text-slate-900 mt-2",children:n})]})}function ddn({eventId:s,eventSlug:t,agents:n,invitations:r,templates:a,onCreate:i}){const[l,o]=N.useState(""),[c,d]=N.useState(""),[u,h]=N.useState(""),[p,f]=N.useState("email"),[y,_]=N.useState(""),v=a==null?void 0:a[0],j=()=>{if(!v)return;const S=p==="sms"?v.suggested_invitation_sms:p==="dm"?v.suggested_invitation_dm:v.suggested_invitation_email,A=t?`${window.location.origin}/attract-event/${t}`:"";_((S||"").replaceAll("{{first_name}}",(c||"friend").split(" ")[0]).replaceAll("{{link}}",A).replaceAll("{{date}}",""))},w=()=>{if(!c||p==="email"&&!u){ae.error("Add a name and email");return}const S=n.find(A=>A.id===l);i({event_id:s,agent_id:l||null,recipient_name:c||ape(S),recipient_email:u||(S==null?void 0:S.email),channel:p,message_body:y,status:"sent"}),d(""),h(""),_(""),o(""),ae.success("Invitation logged")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Log a personal invitation"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Attract agent (optional)"}),e.jsxs(us,{value:l||"none",onValueChange:S=>{o(S==="none"?"":S);const A=n.find(E=>E.id===S);A&&(d(ape(A)),h(A.email||""))},children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Pick an agent"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"Guest (not in pipeline)"}),n.map(S=>e.jsx(Ze,{value:S.id,children:ape(S)},S.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Channel"}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"email",children:"Email"}),e.jsx(Ze,{value:"sms",children:"Text message"}),e.jsx(Ze,{value:"dm",children:"DM"}),e.jsx(Ze,{value:"call",children:"Phone call"}),e.jsx(Ze,{value:"in_person",children:"In person"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Recipient name"}),e.jsx(ye,{value:c,onChange:S=>d(S.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Recipient email"}),e.jsx(ye,{value:u,onChange:S=>h(S.target.value)})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsxs("div",{className:"flex items-center justify-between mb-1",children:[e.jsx(ne,{children:"Message"}),v&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-xs",onClick:j,children:[e.jsx(un,{className:"h-3 w-3 mr-1"})," Draft from template"]})]}),e.jsx(Ms,{rows:5,value:y,onChange:S=>_(S.target.value),placeholder:"Write it like you would to a friend."})]})]}),e.jsxs("div",{className:"flex justify-between items-center mt-4",children:[e.jsx("div",{className:"text-[12px] text-slate-500",children:"Never auto-sent. This just logs that you invited them."}),e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>{y&&(navigator.clipboard.writeText(y),ae.success("Copied"))},children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-2"})," Copy message"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:w,children:[e.jsx(lr,{className:"h-3.5 w-3.5 mr-2"})," Log invitation"]})]})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Recent invitations"}),r.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-2 max-h-[520px] overflow-auto",children:r.map(S=>e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900",children:S.recipient_name||S.recipient_email}),e.jsx(Ue,{variant:"secondary",className:"capitalize",children:S.status})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:["via ",S.channel," · ",Uo(new Date(S.sent_at))," ago",S.view_count>0?` · viewed ${S.view_count}×`:""]})]},S.id))})]})]})}function udn({eventId:s,attendees:t,onUpsert:n,checkInToken:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),c=()=>{if(!a){ae.error("Add a name");return}n({event_id:s,guest_name:a,guest_email:l||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),i(""),o(""),ae.success("Walk-in added")};return e.jsxs("div",{className:"space-y-5",children:[e.jsxs(fe,{className:"p-4 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Add a walk-in guest"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-4 gap-2",children:[e.jsx(ye,{placeholder:"Name",value:a,onChange:d=>i(d.target.value)}),e.jsx(ye,{placeholder:"Email (optional)",value:l,onChange:d=>o(d.target.value)}),e.jsxs(B,{className:"rounded-full md:col-span-2",onClick:c,children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]}),e.jsx(fe,{className:"rounded-2xl border-slate-200 bg-white overflow-hidden",children:t.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400",children:"No registrations yet"}):e.jsx("div",{className:"divide-y divide-slate-100",children:t.map(d=>e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:d.guest_name||ape(d.attract_agents)||d.guest_email}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:[d.guest_email," · ",d.invitation_source||"direct"]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{variant:"secondary",className:"capitalize",children:d.status}),e.jsxs(us,{value:d.status,onValueChange:u=>n({id:d.id,event_id:s,status:u,checked_in_at:u==="attended"&&!d.checked_in_at?new Date().toISOString():d.checked_in_at}),children:[e.jsx(ls,{className:"h-8 w-40 text-xs",children:e.jsx(hs,{})}),e.jsx(cs,{children:["invited","registered","confirmed","waitlisted","attended","no_show","cancelled"].map(u=>e.jsx(Ze,{value:u,className:"text-xs",children:u.replace("_"," ")},u))})]}),r&&d.personalized_token&&e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full text-xs",onClick:()=>{navigator.clipboard.writeText(Mcn(r,d.personalized_token)),ae.success("Check-in link copied")},children:e.jsx(Zr,{className:"h-3.5 w-3.5"})})]})]},d.id))})})]})}function hdn({eventId:s,attendees:t,notes:n,onCreate:r}){const[a,i]=N.useState(""),[l,o]=N.useState(""),[c,d]=N.useState("warm"),[u,h]=N.useState(!1),[p,f]=N.useState(""),y=()=>{if(!l.trim()){ae.error("Add a note");return}const _=t.find(v=>v.id===a);r({event_id:s,attendee_id:a||null,agent_id:(_==null?void 0:_.agent_id)||null,note:l,temperature:c,recommended_next_action:p||null,wants_one_on_one:u}),o(""),i(""),f(""),h(!1),ae.success("Note captured")};return e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white lg:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Capture one honest note"}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Attendee (optional)"}),e.jsxs(us,{value:a||"none",onValueChange:_=>i(_==="none"?"":_),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Anyone in the room"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"General note"}),t.map(_=>e.jsx(Ze,{value:_.id,children:_.guest_name||_.guest_email},_.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Note"}),e.jsx(Ms,{rows:4,value:l,onChange:_=>o(_.target.value),placeholder:"One real thing they said. One thing you noticed."})]}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Relationship temperature"}),e.jsxs(us,{value:c,onValueChange:d,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:["cold","warm","hot"].map(_=>e.jsx(Ze,{value:_,children:_},_))})]})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Recommended next action"}),e.jsx(ye,{value:p,onChange:_=>f(_.target.value),placeholder:"Text them the resource. Book a coffee."})]})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[13px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:u,onChange:_=>h(_.target.checked)}),"They should get a one-on-one conversation"]})]}),e.jsx("div",{className:"flex justify-end mt-4",children:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:y,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Save note"]})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Notes from this event"}),n.length===0?e.jsx("div",{className:"text-[13px] text-slate-400",children:"None yet."}):e.jsx("div",{className:"space-y-3 max-h-[520px] overflow-auto",children:n.map(_=>{const v=t.find(j=>j.id===_.attendee_id);return e.jsxs("div",{className:"rounded-xl border border-slate-100 p-3",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:(v==null?void 0:v.guest_name)||"General"}),e.jsx("div",{className:"text-[13px] text-slate-700 mt-1 whitespace-pre-wrap",children:_.note}),e.jsxs("div",{className:"flex items-center gap-2 mt-2 flex-wrap text-[11px] text-slate-500",children:[_.temperature&&e.jsx(Ue,{variant:"secondary",className:"capitalize",children:_.temperature}),_.wants_one_on_one&&e.jsx(Ue,{className:"bg-emerald-500",children:"Wants 1:1"}),_.recommended_next_action&&e.jsxs("span",{children:["Next: ",_.recommended_next_action]})]})]},_.id)})})]})]})}function mdn({eventId:s,attendees:t,onUpsert:n}){const r=N.useMemo(()=>({attended_engaged:t.filter(l=>l.status==="attended"&&l.temperature==="hot"),attended_no_notes:t.filter(l=>l.status==="attended"),no_show:t.filter(l=>l.status==="no_show"),meeting_requested:t.filter(l=>l.meeting_requested),not_followed:t.filter(l=>l.status==="attended"&&l.followup_status!=="done")}),[t]),a=(l,o)=>n({id:l,event_id:s,followup_status:o}),i=({title:l,list:o,color:c})=>e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3",children:[e.jsx("div",{className:`h-2 w-2 rounded-full ${c}`}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:l}),e.jsxs("div",{className:"text-[12px] text-slate-500",children:["(",o.length,")"]})]}),o.length===0?e.jsx("div",{className:"text-[12px] text-slate-400",children:"Nobody here."}):e.jsx("div",{className:"space-y-2",children:o.map(d=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl border border-slate-100 p-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:d.guest_name||d.guest_email}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[d.status," · followup: ",d.followup_status||"pending"]})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full h-8",onClick:()=>a(d.id,"in_progress"),children:"In progress"}),e.jsx(B,{size:"sm",className:"rounded-full h-8 bg-emerald-600 hover:bg-emerald-700",onClick:()=>a(d.id,"done"),children:e.jsx(Lr,{className:"h-3 w-3"})})]})]},d.id))})]});return e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsx(i,{title:"Attended and engaged",list:r.attended_engaged,color:"bg-emerald-500"}),e.jsx(i,{title:"Attended (no notes yet)",list:r.attended_no_notes,color:"bg-violet-500"}),e.jsx(i,{title:"Registered but no-show",list:r.no_show,color:"bg-amber-500"}),e.jsx(i,{title:"Meeting requested",list:r.meeting_requested,color:"bg-pink-500"}),e.jsx(i,{title:"Not yet followed up",list:r.not_followed,color:"bg-rose-500"})]})}var qU={},pdn=function(){return typeof Promise=="function"&&Promise.prototype&&Promise.prototype.then},cSt={},Ty={};let G8e;const fdn=[0,26,44,70,100,134,172,196,242,292,346,404,466,532,581,655,733,815,901,991,1085,1156,1258,1364,1474,1588,1706,1828,1921,2051,2185,2323,2465,2611,2761,2876,3034,3196,3362,3532,3706];Ty.getSymbolSize=function(t){if(!t)throw new Error('"version" cannot be null or undefined');if(t<1||t>40)throw new Error('"version" should be in range from 1 to 40');return t*4+17};Ty.getSymbolTotalCodewords=function(t){return fdn[t]};Ty.getBCHDigit=function(s){let t=0;for(;s!==0;)t++,s>>>=1;return t};Ty.setToSJISFunction=function(t){if(typeof t!="function")throw new Error('"toSJISFunc" is not a valid function.');G8e=t};Ty.isKanjiModeEnabled=function(){return typeof G8e<"u"};Ty.toSJIS=function(t){return G8e(t)};var Z1e={};(function(s){s.L={bit:1},s.M={bit:0},s.Q={bit:3},s.H={bit:2};function t(n){if(typeof n!="string")throw new Error("Param is not a string");switch(n.toLowerCase()){case"l":case"low":return s.L;case"m":case"medium":return s.M;case"q":case"quartile":return s.Q;case"h":case"high":return s.H;default:throw new Error("Unknown EC Level: "+n)}}s.isValid=function(r){return r&&typeof r.bit<"u"&&r.bit>=0&&r.bit<4},s.from=function(r,a){if(s.isValid(r))return r;try{return t(r)}catch{return a}}})(Z1e);function dSt(){this.buffer=[],this.length=0}dSt.prototype={get:function(s){const t=Math.floor(s/8);return(this.buffer[t]>>>7-s%8&1)===1},put:function(s,t){for(let n=0;n>>t-n-1&1)===1)},getLengthInBits:function(){return this.length},putBit:function(s){const t=Math.floor(this.length/8);this.buffer.length<=t&&this.buffer.push(0),s&&(this.buffer[t]|=128>>>this.length%8),this.length++}};var xdn=dSt;function VU(s){if(!s||s<1)throw new Error("BitMatrix size must be defined and greater than 0");this.size=s,this.data=new Uint8Array(s*s),this.reservedBit=new Uint8Array(s*s)}VU.prototype.set=function(s,t,n,r){const a=s*this.size+t;this.data[a]=n,r&&(this.reservedBit[a]=!0)};VU.prototype.get=function(s,t){return this.data[s*this.size+t]};VU.prototype.xor=function(s,t,n){this.data[s*this.size+t]^=n};VU.prototype.isReserved=function(s,t){return this.reservedBit[s*this.size+t]};var gdn=VU,uSt={};(function(s){const t=Ty.getSymbolSize;s.getRowColCoords=function(r){if(r===1)return[];const a=Math.floor(r/7)+2,i=t(r),l=i===145?26:Math.ceil((i-13)/(2*a-2))*2,o=[i-7];for(let c=1;c=0&&a<=7},s.from=function(a){return s.isValid(a)?parseInt(a,10):void 0},s.getPenaltyN1=function(a){const i=a.size;let l=0,o=0,c=0,d=null,u=null;for(let h=0;h=5&&(l+=t.N1+(o-5)),d=f,o=1),f=a.get(p,h),f===u?c++:(c>=5&&(l+=t.N1+(c-5)),u=f,c=1)}o>=5&&(l+=t.N1+(o-5)),c>=5&&(l+=t.N1+(c-5))}return l},s.getPenaltyN2=function(a){const i=a.size;let l=0;for(let o=0;o=10&&(o===1488||o===93)&&l++,c=c<<1&2047|a.get(u,d),u>=10&&(c===1488||c===93)&&l++}return l*t.N3},s.getPenaltyN4=function(a){let i=0;const l=a.data.length;for(let c=0;c=0;){const l=i[0];for(let c=0;c0){const i=new Uint8Array(this.degree);return i.set(r,a),i}return r};var vdn=W8e,xSt={},oC={},K8e={};K8e.isValid=function(t){return!isNaN(t)&&t>=1&&t<=40};var nj={};const gSt="[0-9]+",bdn="[A-Z $%*+\\-./:]+";let v$="(?:[u3000-u303F]|[u3040-u309F]|[u30A0-u30FF]|[uFF00-uFFEF]|[u4E00-u9FAF]|[u2605-u2606]|[u2190-u2195]|u203B|[u2010u2015u2018u2019u2025u2026u201Cu201Du2225u2260]|[u0391-u0451]|[u00A7u00A8u00B1u00B4u00D7u00F7])+";v$=v$.replace(/u/g,"\\u");const _dn="(?:(?![A-Z0-9 $%*+\\-./:]|"+v$+`)(?:.|[\r ]))+`;nj.KANJI=new RegExp(v$,"g");nj.BYTE_KANJI=new RegExp("[^A-Z0-9 $%*+\\-./:]+","g");nj.BYTE=new RegExp(_dn,"g");nj.NUMERIC=new RegExp(gSt,"g");nj.ALPHANUMERIC=new RegExp(bdn,"g");const wdn=new RegExp("^"+v$+"$"),jdn=new RegExp("^"+gSt+"$"),Ndn=new RegExp("^[A-Z0-9 $%*+\\-./:]+$");nj.testKanji=function(t){return wdn.test(t)};nj.testNumeric=function(t){return jdn.test(t)};nj.testAlphanumeric=function(t){return Ndn.test(t)};(function(s){const t=K8e,n=nj;s.NUMERIC={id:"Numeric",bit:1,ccBits:[10,12,14]},s.ALPHANUMERIC={id:"Alphanumeric",bit:2,ccBits:[9,11,13]},s.BYTE={id:"Byte",bit:4,ccBits:[8,16,16]},s.KANJI={id:"Kanji",bit:8,ccBits:[8,10,12]},s.MIXED={bit:-1},s.getCharCountIndicator=function(i,l){if(!i.ccBits)throw new Error("Invalid mode: "+i);if(!t.isValid(l))throw new Error("Invalid version: "+l);return l>=1&&l<10?i.ccBits[0]:l<27?i.ccBits[1]:i.ccBits[2]},s.getBestModeForData=function(i){return n.testNumeric(i)?s.NUMERIC:n.testAlphanumeric(i)?s.ALPHANUMERIC:n.testKanji(i)?s.KANJI:s.BYTE},s.toString=function(i){if(i&&i.id)return i.id;throw new Error("Invalid mode")},s.isValid=function(i){return i&&i.bit&&i.ccBits};function r(a){if(typeof a!="string")throw new Error("Param is not a string");switch(a.toLowerCase()){case"numeric":return s.NUMERIC;case"alphanumeric":return s.ALPHANUMERIC;case"kanji":return s.KANJI;case"byte":return s.BYTE;default:throw new Error("Unknown mode: "+a)}}s.from=function(i,l){if(s.isValid(i))return i;try{return r(i)}catch{return l}}})(oC);(function(s){const t=Ty,n=Q1e,r=Z1e,a=oC,i=K8e,l=7973,o=t.getBCHDigit(l);function c(p,f,y){for(let _=1;_<=40;_++)if(f<=s.getCapacity(_,y,p))return _}function d(p,f){return a.getCharCountIndicator(p,f)+4}function u(p,f){let y=0;return p.forEach(function(_){const v=d(_.mode,f);y+=v+_.getBitsLength()}),y}function h(p,f){for(let y=1;y<=40;y++)if(u(p,y)<=s.getCapacity(y,f,a.MIXED))return y}s.from=function(f,y){return i.isValid(f)?parseInt(f,10):y},s.getCapacity=function(f,y,_){if(!i.isValid(f))throw new Error("Invalid QR Code version");typeof _>"u"&&(_=a.BYTE);const v=t.getSymbolTotalCodewords(f),j=n.getTotalCodewordsCount(f,y),w=(v-j)*8;if(_===a.MIXED)return w;const S=w-d(_,f);switch(_){case a.NUMERIC:return Math.floor(S/10*3);case a.ALPHANUMERIC:return Math.floor(S/11*2);case a.KANJI:return Math.floor(S/13);case a.BYTE:default:return Math.floor(S/8)}},s.getBestVersionForData=function(f,y){let _;const v=r.from(y,r.M);if(Array.isArray(f)){if(f.length>1)return h(f,v);if(f.length===0)return 1;_=f[0]}else _=f;return c(_.mode,_.getLength(),v)},s.getEncodedBits=function(f){if(!i.isValid(f)||f<7)throw new Error("Invalid QR Code version");let y=f<<12;for(;t.getBCHDigit(y)-o>=0;)y^=l<=0;)a^=vSt<0&&(r=this.data.substr(n),a=parseInt(r,10),t.put(a,i*3+1))};var Cdn=fD;const Tdn=oC,oke=["0","1","2","3","4","5","6","7","8","9","A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"," ","$","%","*","+","-",".","/",":"];function xD(s){this.mode=Tdn.ALPHANUMERIC,this.data=s}xD.getBitsLength=function(t){return 11*Math.floor(t/2)+6*(t%2)};xD.prototype.getLength=function(){return this.data.length};xD.prototype.getBitsLength=function(){return xD.getBitsLength(this.data.length)};xD.prototype.write=function(t){let n;for(n=0;n+2<=this.data.length;n+=2){let r=oke.indexOf(this.data[n])*45;r+=oke.indexOf(this.data[n+1]),t.put(r,11)}this.data.length%2&&t.put(oke.indexOf(this.data[n]),6)};var Edn=xD;const Adn=oC;function gD(s){this.mode=Adn.BYTE,typeof s=="string"?this.data=new TextEncoder().encode(s):this.data=new Uint8Array(s)}gD.getBitsLength=function(t){return t*8};gD.prototype.getLength=function(){return this.data.length};gD.prototype.getBitsLength=function(){return gD.getBitsLength(this.data.length)};gD.prototype.write=function(s){for(let t=0,n=this.data.length;t=33088&&n<=40956)n-=33088;else if(n>=57408&&n<=60351)n-=49472;else throw new Error("Invalid SJIS character: "+this.data[t]+` Make sure your charset is UTF-8`);n=(n>>>8&255)*192+(n&255),s.put(n,13)}};var Ldn=yD,_St={exports:{}};(function(s){var t={single_source_shortest_paths:function(n,r,a){var i={},l={};l[r]=0;var o=t.PriorityQueue.make();o.push(r,0);for(var c,d,u,h,p,f,y,_,v;!o.empty();){c=o.pop(),d=c.value,h=c.cost,p=n[d]||{};for(u in p)p.hasOwnProperty(u)&&(f=p[u],y=h+f,_=l[u],v=typeof l[u]>"u",(v||_>y)&&(l[u]=y,o.push(u,y),i[u]=d))}if(typeof a<"u"&&typeof l[a]>"u"){var j=["Could not find a path from ",r," to ",a,"."].join("");throw new Error(j)}return i},extract_shortest_path_from_predecessor_list:function(n,r){for(var a=[],i=r;i;)a.push(i),n[i],i=n[i];return a.reverse(),a},find_path:function(n,r,a){var i=t.single_source_shortest_paths(n,r,a);return t.extract_shortest_path_from_predecessor_list(i,a)},PriorityQueue:{make:function(n){var r=t.PriorityQueue,a={},i;n=n||{};for(i in r)r.hasOwnProperty(i)&&(a[i]=r[i]);return a.queue=[],a.sorter=n.sorter||r.default_sorter,a},default_sorter:function(n,r){return n.cost-r.cost},push:function(n,r){var a={value:n,cost:r};this.queue.push(a),this.queue.sort(this.sorter)},pop:function(){return this.queue.shift()},empty:function(){return this.queue.length===0}}};s.exports=t})(_St);var Ddn=_St.exports;(function(s){const t=oC,n=Cdn,r=Edn,a=Mdn,i=Ldn,l=nj,o=Ty,c=Ddn;function d(j){return unescape(encodeURIComponent(j)).length}function u(j,w,S){const A=[];let E;for(;(E=j.exec(S))!==null;)A.push({data:E[0],index:E.index,mode:w,length:E[0].length});return A}function h(j){const w=u(l.NUMERIC,t.NUMERIC,j),S=u(l.ALPHANUMERIC,t.ALPHANUMERIC,j);let A,E;return o.isKanjiModeEnabled()?(A=u(l.BYTE,t.BYTE,j),E=u(l.KANJI,t.KANJI,j)):(A=u(l.BYTE_KANJI,t.BYTE,j),E=[]),w.concat(S,A,E).sort(function(D,I){return D.index-I.index}).map(function(D){return{data:D.data,mode:D.mode,length:D.length}})}function p(j,w){switch(w){case t.NUMERIC:return n.getBitsLength(j);case t.ALPHANUMERIC:return r.getBitsLength(j);case t.KANJI:return i.getBitsLength(j);case t.BYTE:return a.getBitsLength(j)}}function f(j){return j.reduce(function(w,S){const A=w.length-1>=0?w[w.length-1]:null;return A&&A.mode===S.mode?(w[w.length-1].data+=S.data,w):(w.push(S),w)},[])}function y(j){const w=[];for(let S=0;S=0&&o<=6&&(c===0||c===6)||c>=0&&c<=6&&(o===0||o===6)||o>=2&&o<=4&&c>=2&&c<=4?s.set(i+o,l+c,!0,!0):s.set(i+o,l+c,!1,!0))}}function Vdn(s){const t=s.size;for(let n=8;n>o&1)===1,s.set(a,i,l,!0),s.set(i,a,l,!0)}function dke(s,t,n){const r=s.size,a=$dn.getEncodedBits(t,n);let i,l;for(i=0;i<15;i++)l=(a>>i&1)===1,i<6?s.set(i,8,l,!0):i<8?s.set(i+1,8,l,!0):s.set(r-15+i,8,l,!0),i<8?s.set(8,r-i-1,l,!0):i<9?s.set(8,15-i-1+1,l,!0):s.set(8,15-i-1,l,!0);s.set(r-8,8,1,!0)}function Wdn(s,t){const n=s.size;let r=-1,a=n-1,i=7,l=0;for(let o=n-1;o>0;o-=2)for(o===6&&o--;;){for(let c=0;c<2;c++)if(!s.isReserved(a,o-c)){let d=!1;l>>i&1)===1),s.set(a,o-c,d),i--,i===-1&&(l++,i=7)}if(a+=r,a<0||n<=a){a-=r,r=-r;break}}}function Kdn(s,t,n){const r=new Rdn;n.forEach(function(c){r.put(c.mode.bit,4),r.put(c.getLength(),Udn.getCharCountIndicator(c.mode,s)),c.write(r)});const a=J1e.getSymbolTotalCodewords(s),i=RTe.getTotalCodewordsCount(s,t),l=(a-i)*8;for(r.getLengthInBits()+4<=l&&r.put(0,4);r.getLengthInBits()%8!==0;)r.putBit(0);const o=(l-r.getLengthInBits())/8;for(let c=0;c=7&&Gdn(c,t),Wdn(c,l),isNaN(r)&&(r=DTe.getBestMask(c,dke.bind(null,c,n))),DTe.applyMask(r,c),dke(c,n,r),{modules:c,version:t,errorCorrectionLevel:n,maskPattern:r,segments:a}}cSt.create=function(t,n){if(typeof t>"u"||t==="")throw new Error("No input text");let r=lke.M,a,i;return typeof n<"u"&&(r=lke.from(n.errorCorrectionLevel,lke.M),a=Wge.from(n.version),i=DTe.from(n.maskPattern),n.toSJISFunc&&J1e.setToSJISFunction(n.toSJISFunc)),Zdn(t,a,r,i)};var wSt={},Y8e={};(function(s){function t(n){if(typeof n=="number"&&(n=n.toString()),typeof n!="string")throw new Error("Color should be defined as hex string");let r=n.slice().replace("#","").split("");if(r.length<3||r.length===5||r.length>8)throw new Error("Invalid hex color: "+n);(r.length===3||r.length===4)&&(r=Array.prototype.concat.apply([],r.map(function(i){return[i,i]}))),r.length===6&&r.push("F","F");const a=parseInt(r.join(""),16);return{r:a>>24&255,g:a>>16&255,b:a>>8&255,a:a&255,hex:"#"+r.slice(0,6).join("")}}s.getOptions=function(r){r||(r={}),r.color||(r.color={});const a=typeof r.margin>"u"||r.margin===null||r.margin<0?4:r.margin,i=r.width&&r.width>=21?r.width:void 0,l=r.scale||4;return{width:i,scale:i?4:l,margin:a,color:{dark:t(r.color.dark||"#000000ff"),light:t(r.color.light||"#ffffffff")},type:r.type,rendererOpts:r.rendererOpts||{}}},s.getScale=function(r,a){return a.width&&a.width>=r+a.margin*2?a.width/(r+a.margin*2):a.scale},s.getImageWidth=function(r,a){const i=s.getScale(r,a);return Math.floor((r+a.margin*2)*i)},s.qrToImageData=function(r,a,i){const l=a.modules.size,o=a.modules.data,c=s.getScale(l,i),d=Math.floor((l+i.margin*2)*c),u=i.margin*c,h=[i.color.light,i.color.dark];for(let p=0;p=u&&f>=u&&p"u"&&(!l||!l.getContext)&&(c=l,l=void 0),l||(d=r()),c=t.getOptions(c);const u=t.getImageWidth(i.modules.size,c),h=d.getContext("2d"),p=h.createImageData(u,u);return t.qrToImageData(p.data,i,c),n(h,d,u),h.putImageData(p,0,0),d},s.renderToDataURL=function(i,l,o){let c=o;typeof c>"u"&&(!l||!l.getContext)&&(c=l,l=void 0),c||(c={});const d=s.render(i,l,c),u=c.type||"image/png",h=c.rendererOpts||{};return d.toDataURL(u,h.quality)}})(wSt);var jSt={};const Qdn=Y8e;function het(s,t){const n=s.a/255,r=t+'="'+s.hex+'"';return n<1?r+" "+t+'-opacity="'+n.toFixed(2).slice(1)+'"':r}function uke(s,t,n){let r=s+t;return typeof n<"u"&&(r+=" "+n),r}function Xdn(s,t,n){let r="",a=0,i=!1,l=0;for(let o=0;o0&&c>0&&s[o-1]||(r+=i?uke("M",c+n,.5+d+n):uke("m",a,0),a=0,i=!1),c+1':"",d="',u='viewBox="0 0 '+o+" "+o+'"',p=''+c+d+` `;return typeof r=="function"&&r(null,p),p};const Jdn=pdn,OTe=cSt,NSt=wSt,eun=jSt;function Z8e(s,t,n,r,a){const i=[].slice.call(arguments,1),l=i.length,o=typeof i[l-1]=="function";if(!o&&!Jdn())throw new Error("Callback required as last argument");if(o){if(l<2)throw new Error("Too few arguments provided");l===2?(a=n,n=t,t=r=void 0):l===3&&(t.getContext&&typeof a>"u"?(a=r,r=void 0):(a=r,r=n,n=t,t=void 0))}else{if(l<1)throw new Error("Too few arguments provided");return l===1?(n=t,t=r=void 0):l===2&&!t.getContext&&(r=n,n=t,t=void 0),new Promise(function(c,d){try{const u=OTe.create(n,r);c(s(u,t,r))}catch(u){d(u)}})}try{const c=OTe.create(n,r);a(null,s(c,t,r))}catch(c){a(c)}}qU.create=OTe.create;qU.toCanvas=Z8e.bind(null,NSt.render);qU.toDataURL=Z8e.bind(null,NSt.renderToDataURL);qU.toString=Z8e.bind(null,function(s,t,n){return eun.render(s,n)});function tun(){const{eventId:s}=bi(),t=Ln(),{data:n}=V8e(s),{data:r=[]}=Zkt(s),a=eSt(),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(""),[h,p]=N.useState(""),f=n!=null&&n.public_slug?Y1e(n.public_slug):"";N.useEffect(()=>{f&&qU.toDataURL(f,{width:320,margin:1}).then(p).catch(()=>{})},[f]);const y=N.useMemo(()=>i?r.filter(j=>(j.guest_name||"").toLowerCase().includes(i.toLowerCase())||(j.guest_email||"").toLowerCase().includes(i.toLowerCase())):r,[r,i]),_=j=>{a.mutate({id:j.id,event_id:s,status:"attended",checked_in_at:new Date().toISOString()}),ae.success(`${j.guest_name||"Guest"} checked in`)},v=()=>{o&&(a.mutate({event_id:s,guest_name:o,guest_email:d||null,status:"attended",checked_in_at:new Date().toISOString(),invitation_source:"walk_in"}),c(""),u(""),ae.success("Walk-in checked in"))};return n?e.jsx("div",{className:"min-h-screen bg-slate-50",children:e.jsxs("div",{className:"max-w-2xl mx-auto p-4 md:p-6",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"rounded-full mb-3",onClick:()=>t(`/attract/events/${s}`),children:[e.jsx(qr,{className:"h-4 w-4 mr-2"})," Back to event"]}),e.jsxs(fe,{className:"p-5 rounded-2xl bg-gradient-to-br from-slate-900 to-slate-800 text-white border-0",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-widest text-white/60",children:"Check-in mode"}),e.jsx("div",{className:"text-xl font-semibold mt-1",children:n.title}),e.jsxs("div",{className:"text-white/70 text-[13px] mt-0.5",children:[n.registration_count," registered · ",n.attendance_count," checked in"]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 mt-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[13px] font-semibold text-slate-900",children:[e.jsx(ry,{className:"h-4 w-4"})," Registration QR"]}),h?e.jsx("img",{src:h,alt:"QR code",className:"mx-auto mt-3 h-56 w-56"}):e.jsx("div",{className:"text-[12px] text-slate-400 mt-3",children:"Publish this event to generate a QR code."}),f&&e.jsx("div",{className:"text-[11px] font-mono text-center text-slate-500 mt-2 break-all",children:f})]}),e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white",children:[e.jsx("div",{className:"text-[13px] font-semibold text-slate-900 mb-3",children:"Add walk-in"}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ye,{placeholder:"Name",value:o,onChange:j=>c(j.target.value)}),e.jsx(ye,{placeholder:"Email (optional)",value:d,onChange:j=>u(j.target.value)}),e.jsxs(B,{className:"w-full rounded-full",onClick:v,children:[e.jsx(Fo,{className:"h-4 w-4 mr-2"})," Add & check in"]})]})]})]}),e.jsxs(fe,{className:"mt-4 rounded-2xl border-slate-200 bg-white overflow-hidden",children:[e.jsxs("div",{className:"p-3 border-b border-slate-100 relative",children:[e.jsx(gr,{className:"absolute left-6 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{placeholder:"Search attendees",value:i,onChange:j=>l(j.target.value),className:"pl-9 rounded-full border-slate-200"})]}),y.length===0?e.jsx("div",{className:"p-8 text-center text-slate-400 text-[13px]",children:"No matches."}):e.jsx("div",{className:"divide-y divide-slate-100 max-h-[60vh] overflow-auto",children:y.map(j=>{const w=j.status==="attended";return e.jsxs("div",{className:"p-4 flex items-center justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 truncate",children:j.guest_name||j.guest_email}),e.jsx("div",{className:"text-[12px] text-slate-500 truncate",children:j.guest_email})]}),w?e.jsxs(Ue,{className:"bg-emerald-500",children:[e.jsx(Lr,{className:"h-3 w-3 mr-1"})," Checked in"]}):e.jsxs(B,{size:"lg",className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_(j),children:[e.jsx(Lr,{className:"h-5 w-5 mr-2"})," Check in"]})]},j.id)})})]})]})}):e.jsx("div",{className:"p-8 text-slate-500",children:"Loading…"})}const sun=["Brand-new agents","Producing solo agents","Team leaders","Luxury agents","New construction agents","Agents struggling with marketing","Agents needing better systems/support","Agents interested in additional income"],nun=["Lead generation","Database marketing","Listing marketing","Social media/video","Open houses","Negotiation","Systems and technology","Team building","Leadership","New construction","Luxury","Business planning"],met=[{key:"produce",icon:xo,title:"Produce",blurb:"Attract through visible production and excellence.",example:"Publish weekly market updates, share every closing story with the lesson attached."},{key:"influence",icon:un,title:"Influence",blurb:"Teach publicly and earn a following of agents.",example:"Host a monthly masterclass. Post 3 authority pieces a week."},{key:"provide",icon:jA,title:"Provide",blurb:"Give resources, tools, and referrals that make agents better.",example:"Send curated resource kits and warm referrals to the right people."},{key:"connect",icon:uw,title:"Connect",blurb:"Bring the right people into the same room.",example:"Host quarterly masterminds and 1:1 coffees on a repeatable rhythm."},{key:"balanced",icon:t4,title:"Balanced Plan",blurb:"A little of all four. Best for veteran attractors.",example:"Rotate weekly focus between production, teaching, providing, and connecting."}],run=[{key:"new_relationships",label:"New agent relationships / month"},{key:"follow_ups",label:"Meaningful follow-ups / month"},{key:"content_pieces",label:"Agent-focused posts / month"},{key:"resources_shared",label:"Resources shared / month"},{key:"events",label:"Events hosted or attended / month"},{key:"brokerage_conversations",label:"Brokerage curiosity conversations / month"}],pet=["Build 25 meaningful agent relationships","Host 3 masterminds or events","Start a weekly agent newsletter","Share 30 valuable resources","Schedule 10 brokerage curiosity conversations","Help 5 agents solve a meaningful business challenge"];function fet(s){const t=(o,c=2)=>Math.max(2,Math.ceil((o||1)*c)),n={new_relationships:t(s.baseline.new_relationships/4,1.6),follow_ups:t(s.baseline.follow_ups/4,1.4),content_pieces:t(s.baseline.content_pieces/4,1.5),resources_shared:t(s.baseline.resources_shared/4,1.5),events:Math.max(1,Math.round((s.baseline.events||0)/4)),brokerage_conversations:Math.max(1,Math.round((s.baseline.brokerage_conversations||0)/4))},r=["Add 3 agents you already know to your Attract Pipeline","Review your last 5 closed transactions in the Transaction Tracker","Write your first Authority Content piece in Content Studio","Send one thoughtful resource to an agent you respect","Schedule one coffee or Zoom this week","Set your Follow-Up cadence in Settings","Book your next agent event on the calendar"],a={produce:"Post one production story + one market insight per week.",influence:"Post 3 authority pieces per week; go long-form once a month.",provide:"Share 2 resources per week and 1 warm referral per month.",connect:"One 1:1 per week + one small event per month.",balanced:"Rotate a Produce, Influence, Provide, and Connect focus week each month."},i={produce:"Transaction-to-Relationship Tracker",influence:"Authority Content Studio",provide:"Resource Library",connect:"Events & Follow-Up Center",balanced:"Dashboard Daily Plan"},l={produce:"Publish a 90-day production journal recap",influence:"Host a free 45-minute masterclass on your best system",provide:'Curate a "Top 10 tools every agent needs" resource kit',connect:"Invite 8 agents to a small-format mastermind",balanced:"Run a single flagship event featuring all four pillars"};return{primary_pillar:s.style,weekly_targets:n,first_7_days:r,content_rhythm:a[s.style],suggested_tool:i[s.style],suggested_offer:l[s.style],outcome:s.outcome,generated_at:new Date().toISOString()}}function aun(){const s=Ln(),{settings:t,save:n}=$U(),[r,a]=N.useState(0),[i,l]=N.useState([]),[o,c]=N.useState([]),[d,u]=N.useState(null),[h,p]=N.useState({}),[f,y]=N.useState("");N.useEffect(()=>{var S,A;t&&((S=t.audiences)!=null&&S.length&&l(t.audiences),(A=t.teachables)!=null&&A.length&&c(t.teachables),t.attraction_style&&u(t.attraction_style),t.activity_baseline&&p(t.activity_baseline),t.ninety_day_outcome&&y(t.ninety_day_outcome))},[t==null?void 0:t.user_id]);const _=["Welcome","Audience","Teach","Style","Baseline","Outcome","Plan"],v=N.useMemo(()=>r===1?i.length>0:r===2?o.length>0:r===3?!!d:r===5?!!f:!0,[r,i,o,d,f]),j=(S,A,E)=>{E(S.includes(A)?S.filter(O=>O!==A):[...S,A])},w=async()=>{if(!d)return;const S=fet({style:d,baseline:h,outcome:f});await n.mutateAsync({audiences:i,teachables:o,attraction_style:d,activity_baseline:h,ninety_day_outcome:f,ninety_day_plan:S,primary_pillar:d,onboarding_completed_at:new Date().toISOString()}),ae.success("Your 90-day plan is ready."),s("/attract")};return e.jsxs("div",{className:"max-w-3xl mx-auto",children:[e.jsx("div",{className:"flex items-center gap-2 mb-8",children:_.map((S,A)=>e.jsx("div",{className:Mt("h-1.5 flex-1 rounded-full transition-colors",A<=r?"bg-violet-600":"bg-slate-200")},S))}),e.jsx(pye,{mode:"wait",children:e.jsxs(Zn.div,{initial:{opacity:0,y:12},animate:{opacity:1,y:0},exit:{opacity:0,y:-8},transition:{duration:.25},children:[r===0&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"A strategy session"}),e.jsx("h1",{className:"text-4xl md:text-5xl font-semibold tracking-tight text-slate-900",children:"Build an attraction business people want to be part of."}),e.jsx("p",{className:"text-slate-600 mt-4 text-lg leading-relaxed",children:"Attract isn't a recruiting funnel. It's a way of doing business where the right agents naturally find you — because you produce, teach, provide, and connect at a rhythm no one else in your market keeps."}),e.jsx("div",{className:"mt-8 grid grid-cols-2 md:grid-cols-4 gap-3",children:met.filter(S=>S.key!=="balanced").map(S=>e.jsxs(fe,{className:"p-4 rounded-2xl border-slate-200",children:[e.jsx(S.icon,{className:"h-5 w-5 text-violet-600 mb-2"}),e.jsx("div",{className:"text-[13px] font-semibold text-slate-900",children:S.title}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:S.blurb})]},S.key))})]}),r===1&&e.jsx(qF,{icon:An,eyebrow:"Who can you best help?",title:"Pick every audience where you naturally shine.",subtitle:"You can adjust these anytime.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:sun.map(S=>e.jsx(hke,{label:S,active:i.includes(S),onClick:()=>j(i,S,l)},S))})}),r===2&&e.jsx(qF,{icon:yd,eyebrow:"What can you genuinely teach?",title:"Choose the areas you'd feel proud to teach on stage.",subtitle:"Content and events will pull from here.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:nun.map(S=>e.jsx(hke,{label:S,active:o.includes(S),onClick:()=>j(o,S,c)},S))})}),r===3&&e.jsx(qF,{icon:t4,eyebrow:"Your primary attraction style",title:"Which of these fits how you already show up?",subtitle:"This becomes your default pillar and shapes every recommendation.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:met.map(S=>e.jsx(fe,{onClick:()=>u(S.key),className:Mt("p-5 rounded-2xl cursor-pointer transition-all border-2",d===S.key?"border-violet-600 bg-violet-50/70 shadow-md":"border-slate-200 hover:border-violet-300"),children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-violet-100 text-violet-700 grid place-items-center",children:e.jsx(S.icon,{className:"h-5 w-5"})}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900",children:S.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:S.blurb}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 italic mt-2",children:["Example: ",S.example]})]}),d===S.key&&e.jsx(Lr,{className:"h-5 w-5 text-violet-600"})]})},S.key))})}),r===4&&e.jsx(qF,{icon:em,eyebrow:"Current baseline",title:"Roughly, what are you doing today?",subtitle:"Estimate is fine. We use this to set realistic 90-day targets.",children:e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:run.map(S=>e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12.5px] text-slate-700",children:S.label}),e.jsx(ye,{type:"number",min:0,value:h[S.key]??"",onChange:A=>p({...h,[S.key]:Number(A.target.value)||0})})]},S.key))})}),r===5&&e.jsx(qF,{icon:Ac,eyebrow:"90-day outcome",title:"Pick one outcome to chase for the next 90 days.",subtitle:"One clear promise to yourself is worth ten vague hopes.",children:e.jsxs("div",{className:"space-y-2",children:[pet.map(S=>e.jsx(hke,{label:S,active:f===S,onClick:()=>y(S),full:!0},S)),e.jsxs("div",{className:"mt-3",children:[e.jsx(ne,{className:"text-[12.5px] text-slate-700",children:"Or write your own"}),e.jsx(Ms,{rows:2,placeholder:"A specific outcome you can measure in 90 days...",value:pet.includes(f)?"":f,onChange:S=>y(S.target.value)})]})]})}),r===6&&d&&e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:"Your plan"}),e.jsx("h2",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:"You're ready. Here's your 90-day plan."}),e.jsx(kSt,{plan:fet({style:d,baseline:h,outcome:f})})]})]},r)}),e.jsxs("div",{className:"mt-10 flex items-center justify-between",children:[e.jsxs(B,{variant:"ghost",onClick:()=>r===0?s("/attract"):a(r-1),children:[e.jsx(qr,{className:"h-4 w-4 mr-1"})," ",r===0?"Skip for now":"Back"]}),r<6?e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",disabled:!v,onClick:()=>a(r+1),children:["Continue ",e.jsx(Oa,{className:"h-4 w-4 ml-1"})]}):e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full px-6",onClick:w,disabled:n.isPending,children:[e.jsx(tx,{className:"h-4 w-4 mr-1.5"})," Activate my 90-day plan"]})]})]})}function qF({icon:s,eyebrow:t,title:n,subtitle:r,children:a}){return e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2 text-[11px] uppercase tracking-[0.18em] text-violet-600 font-semibold mb-2",children:[e.jsx(s,{className:"h-3.5 w-3.5"})," ",t]}),e.jsx("h2",{className:"text-3xl font-semibold tracking-tight text-slate-900",children:n}),r&&e.jsx("p",{className:"text-slate-600 mt-1.5 mb-6",children:r}),e.jsx("div",{className:"mt-6",children:a})]})}function hke({label:s,active:t,onClick:n,full:r}){return e.jsx("button",{type:"button",onClick:n,className:Mt("text-left rounded-xl border px-4 py-3 text-[13.5px] transition-colors",r?"w-full":"",t?"border-violet-600 bg-violet-50 text-violet-900 shadow-sm":"border-slate-200 bg-white hover:border-violet-300 text-slate-800"),children:e.jsxs("span",{className:"inline-flex items-center gap-2",children:[t&&e.jsx(Lr,{className:"h-4 w-4 text-violet-600"})," ",s]})})}function kSt({plan:s}){return e.jsxs("div",{className:"mt-6 space-y-6",children:[e.jsxs(fe,{className:"p-6 rounded-2xl bg-gradient-to-br from-violet-600 to-indigo-700 text-white border-0",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.18em] opacity-80",children:"Primary focus"}),e.jsx("div",{className:"text-3xl font-semibold mt-1 capitalize",children:s.primary_pillar}),e.jsx("div",{className:"text-white/85 mt-2",children:s.content_rhythm}),e.jsxs("div",{className:"text-[13px] mt-4 rounded-xl bg-white/10 p-3",children:[e.jsx("span",{className:"opacity-80",children:"90-day outcome:"})," ",s.outcome]})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Weekly targets"}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-3 gap-3",children:Object.entries(s.weekly_targets).map(([t,n])=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900 tabular-nums",children:n}),e.jsx("div",{className:"text-[11.5px] text-slate-500 capitalize mt-0.5",children:t.replace(/_/g," ")})]},t))})]}),e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"First 7 days"}),e.jsx(fe,{className:"p-5 rounded-2xl",children:e.jsx("ul",{className:"space-y-2",children:s.first_7_days.map((t,n)=>e.jsxs("li",{className:"flex items-start gap-2.5 text-[13.5px] text-slate-800",children:[e.jsx("div",{className:"h-5 w-5 rounded-full bg-violet-100 text-violet-700 grid place-items-center text-[11px] font-semibold flex-shrink-0 mt-0.5",children:n+1}),t]},n))})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Recommended first tool"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_tool})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Suggested first offer"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:s.suggested_offer})]})]})]})}function iun(){const{settings:s,resetOnboarding:t}=$U(),n=s==null?void 0:s.ninety_day_plan;return e.jsxs("div",{className:"max-w-4xl",children:[e.jsx(zu,{eyebrow:"90-Day Plan",title:"Your personalized attraction plan.",description:"Generated from your onboarding responses. Adjust any time by rerunning onboarding.",actions:e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>t.mutate(),children:[e.jsx(Bm,{className:"h-4 w-4 mr-1.5"})," Rerun onboarding"]})}),n?e.jsx(kSt,{plan:n}):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("p",{className:"text-slate-700 mb-4",children:"You haven't set up your 90-day plan yet."}),e.jsx(B,{asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",children:e.jsx(In,{to:"/attract/onboarding",children:"Start onboarding"})})]})]})}async function xet(s,t,n,r={}){await q.rpc("award_attract_activity",{_user_id:s,_activity_type:t,_title:n,_description:r.description??null,_pillar:r.pillar??null,_agent_id:r.agent_id??null,_metadata:r.metadata??{},_dedupe_minutes:30})}function SSt(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:["attract-transactions",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_transactions").select("*").order("closing_date",{ascending:!1,nullsFirst:!1});if(c)throw c;return o??[]}}),r=yt({mutationFn:async o=>{const c=[o.rating_communication,o.rating_professionalism,o.rating_problem_solving].filter(y=>typeof y=="number"),d=c.length?Number((c.reduce((y,_)=>y+_,0)/c.length).toFixed(2)):null,u={...o,user_id:s.id,overall_rating:d},{data:h,error:p}=o.id?await q.from("attract_transactions").update(u).eq("id",o.id).select().single():await q.from("attract_transactions").insert(u).select().single();if(p)throw p;const f=h;return o.id||await xet(s.id,"transaction_logged",`Reviewed ${f.property_address}`,{description:f.cooperating_first_name?`Cooperating agent: ${f.cooperating_first_name} ${f.cooperating_last_name??""}`:null,pillar:"produce",metadata:{transaction_id:f.id,overall_rating:d}}),f},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Transaction saved")},onError:o=>ae.error(o.message)}),a=yt({mutationFn:async({id:o,decision:c,notes:d})=>{const{data:u,error:h}=await q.from("attract_transactions").update({decision:c,decision_notes:d??null}).eq("id",o).select().single();if(h)throw h;return u},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]})}}),i=yt({mutationFn:async o=>{let c=o.attract_agent_id;if(!c){const{data:d}=await q.from("attract_agents").select("id").eq("user_id",s.id).eq("first_name",o.cooperating_first_name??"").eq("last_name",o.cooperating_last_name??"").maybeSingle();if(d!=null&&d.id)c=d.id;else{const{data:u,error:h}=await q.from("attract_agents").insert({user_id:s.id,first_name:o.cooperating_first_name??"Unknown",last_name:o.cooperating_last_name,email:o.cooperating_email,phone:o.cooperating_phone,brokerage:o.cooperating_brokerage,source:"cooperating_transaction",stage:"new_connection",temperature:o.enjoy_business_with==="yes"?"warm":"cold",notes:o.stood_out}).select("id").single();if(h)throw h;c=u.id}}return await q.from("attract_transactions").update({attract_agent_id:c,decision:"add_pipeline"}).eq("id",o.id),await xet(s.id,"agent_added_from_transaction",`Added ${o.cooperating_first_name??"agent"} to pipeline`,{pillar:"produce",agent_id:c,metadata:{transaction_id:o.id}}),c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),t.invalidateQueries({queryKey:["attract-agents"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Added to Agent Pipeline")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_transactions").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-transactions"]}),ae.success("Transaction removed")}});return{transactions:n.data??[],isLoading:n.isLoading,upsert:r,setDecision:a,addToPipeline:i,remove:l}}function oun({value:s,onChange:t}){return e.jsx("div",{className:"flex gap-1",children:[1,2,3,4,5].map(n=>e.jsx("button",{type:"button",onClick:()=>t(n),children:e.jsx(oa,{className:Mt("h-5 w-5",(s??0)>=n?"fill-amber-400 text-amber-400":"text-slate-300")})},n))})}function lun(s,t){var l;const n=s.cooperating_first_name||"there",r=s.property_address||"the transaction",a=(l=s.stood_out)==null?void 0:l.trim(),i=a?`You ${a.replace(/^You\s+/i,"").replace(/[.!]$/,"")}.`:"You communicated clearly and handled the inevitable curveballs with real professionalism.";switch(t){case"warm":return`Hi ${n}, I really enjoyed working with you on ${r}. ${i} It made the deal feel smooth for both sides — and that's rare. Would love to stay connected. Grab coffee or a Zoom sometime this month? — `;case"peer":return`${n} — quick note. Working with you on ${r} was refreshing. ${i} We should stay in touch — I like being around agents who operate that way.`;case"text":return`Hey ${n} — just wanted to say thanks for the way you handled ${r}. ${i} Let's grab coffee soon.`;case"email":default:return`Subject: A quick thank you Hi ${n}, Wrapping up on ${r} and I wanted to send a note. ${i} It's the kind of transaction I remember for a long time. Would love to stay in touch — coffee, a Zoom, or a shared MLS thought when it hits. Whatever works. All the best, `}}const cun={1:"Poor",2:"Fair",3:"OK",4:"Good",5:"Excellent"},mke={add_pipeline:{label:"In Pipeline",color:"bg-emerald-100 text-emerald-800"},send_compliment:{label:"Compliment sent",color:"bg-violet-100 text-violet-800"},invite_coffee:{label:"Coffee invited",color:"bg-amber-100 text-amber-800"},share_resource:{label:"Resource shared",color:"bg-sky-100 text-sky-800"},no_action:{label:"No action",color:"bg-slate-100 text-slate-700"},pending:{label:"Needs review",color:"bg-rose-100 text-rose-800"}};function dun(){const{transactions:s,isLoading:t,upsert:n,setDecision:r,addToPipeline:a,remove:i}=SSt(),[l,o]=N.useState(""),[c,d]=N.useState(!1),[u,h]=N.useState(null),[p,f]=N.useState(null),y=N.useMemo(()=>{const v=l.trim().toLowerCase();return v?s.filter(j=>[j.property_address,j.cooperating_first_name,j.cooperating_last_name,j.cooperating_brokerage,j.city].filter(Boolean).some(w=>String(w).toLowerCase().includes(v))):s},[s,l]),_=N.useMemo(()=>{const v=s.length,j=s.filter(A=>A.enjoy_business_with==="yes").length,w=s.filter(A=>A.decision==="add_pipeline").length,S=s.filter(A=>A.follow_up_created).length;return{reviewed:v,highFit:j,inPipeline:w,followUps:S}},[s]);return e.jsxs("div",{children:[e.jsxs(In,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(zu,{eyebrow:"Produce → Tool",title:"Transaction-to-Relationship Tracker",description:"Every good cooperating agent is a future relationship. Log the transaction, note what stood out, and turn the best experiences into real professional friendships.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add Transaction"]})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(qG,{label:"Transactions reviewed",value:_.reviewed}),e.jsx(qG,{label:"High-fit agents",value:_.highFit,tone:"emerald"}),e.jsx(qG,{label:"Added to pipeline",value:_.inPipeline,tone:"violet"}),e.jsx(qG,{label:"Follow-ups created",value:_.followUps,tone:"amber"})]}),e.jsx("div",{className:"flex items-center gap-3 mb-4",children:e.jsxs("div",{className:"relative flex-1 max-w-md",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{value:l,onChange:v=>o(v.target.value),placeholder:"Search property, agent, brokerage...",className:"pl-9 rounded-full"})]})}),t?e.jsx("div",{className:"space-y-3",children:[0,1,2].map(v=>e.jsx(fe,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},v))}):y.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(un,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Turn transactions into relationships"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Add your last 5 closed transactions to spot the agents you'd love to be in business with — then send a thoughtful compliment that opens the door."}),e.jsxs(B,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>d(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add your first transaction"]})]}):e.jsx("div",{className:"space-y-3",children:y.map(v=>{var j,w;return e.jsx(fe,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex flex-col md:flex-row md:items-center gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 truncate",children:v.property_address}),v.closing_date&&e.jsx(Ue,{variant:"outline",className:"text-[10.5px]",children:Ss(new Date(v.closing_date),"MMM d, yyyy")}),e.jsx(Ue,{className:Mt("text-[10.5px] border-0",((j=mke[v.decision])==null?void 0:j.color)??mke.pending.color),children:((w=mke[v.decision])==null?void 0:w.label)??"Needs review"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1",children:[v.cooperating_first_name||v.cooperating_last_name?`${v.cooperating_first_name??""} ${v.cooperating_last_name??""}`:"Cooperating agent",v.cooperating_brokerage?` · ${v.cooperating_brokerage}`:""]}),e.jsxs("div",{className:"flex items-center gap-3 mt-2 text-[12px] text-slate-600",children:[v.overall_rating!=null&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(oa,{className:"h-3.5 w-3.5 fill-amber-400 text-amber-400"})," ",v.overall_rating]}),v.enjoy_business_with&&e.jsxs("span",{className:"capitalize",children:["Fit: ",e.jsx("span",{className:Mt("font-medium",v.enjoy_business_with==="yes"?"text-emerald-700":v.enjoy_business_with==="maybe"?"text-amber-700":"text-slate-600"),children:v.enjoy_business_with})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h(v),children:["Review ",e.jsx(ga,{className:"h-3.5 w-3.5 ml-1"})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>f(v),children:[e.jsx(iL,{className:"h-3.5 w-3.5 mr-1"})," Message"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600 hover:text-rose-700",onClick:()=>i.mutate(v.id),children:"Remove"})]})]})},v.id)})}),e.jsx("div",{className:"mt-8",children:e.jsx(l6,{})}),e.jsx(uun,{open:c,onClose:()=>d(!1),onSaved:v=>{d(!1),h(v)},upsert:n}),e.jsx(hun,{tx:u,onClose:()=>h(null),onDecision:v=>u&&r.mutate({id:u.id,decision:v}),onAddToPipeline:()=>u&&a.mutate(u),onMessage:()=>{f(u),h(null)}}),e.jsx(mun,{tx:p,onClose:()=>f(null)})]})}function qG({label:s,value:t,tone:n="slate"}){const r={slate:"text-slate-900",emerald:"text-emerald-700",violet:"text-violet-700",amber:"text-amber-700"};return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:Mt("text-2xl font-semibold tabular-nums",r[n]),children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:s})]})}function uun({open:s,onClose:t,onSaved:n,upsert:r}){const[a,i]=N.useState({enjoy_business_with:"maybe"}),l=c=>i({...a,...c}),o=async()=>{var d;if(!((d=a.property_address)!=null&&d.trim())){ae.error("Property address is required");return}const c=await r.mutateAsync(a);i({enjoy_business_with:"maybe"}),n(c)};return e.jsx(_s,{open:s,onOpenChange:c=>!c&&t(),children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Add Transaction"}),e.jsx(Jn,{children:"Capture what stood out while it's fresh."})]}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Property address *"}),e.jsx(ye,{value:a.property_address??"",onChange:c=>l({property_address:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"City"}),e.jsx(ye,{value:a.city??"",onChange:c=>l({city:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"State"}),e.jsx(ye,{value:a.state??"",onChange:c=>l({state:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Closing date"}),e.jsx(ye,{type:"date",value:a.closing_date??"",onChange:c=>l({closing_date:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"You represented"}),e.jsxs(us,{value:a.represented??"",onValueChange:c=>l({represented:c}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Buyer or seller"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"buyer",children:"Buyer"}),e.jsx(Ze,{value:"seller",children:"Seller"}),e.jsx(Ze,{value:"both",children:"Both"}),e.jsx(Ze,{value:"other",children:"Other"})]})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Cooperating agent"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"First name"}),e.jsx(ye,{value:a.cooperating_first_name??"",onChange:c=>l({cooperating_first_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Last name"}),e.jsx(ye,{value:a.cooperating_last_name??"",onChange:c=>l({cooperating_last_name:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Email"}),e.jsx(ye,{type:"email",value:a.cooperating_email??"",onChange:c=>l({cooperating_email:c.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Phone"}),e.jsx(ye,{value:a.cooperating_phone??"",onChange:c=>l({cooperating_phone:c.target.value})})]}),e.jsxs("div",{className:"md:col-span-2",children:[e.jsx(ne,{children:"Brokerage"}),e.jsx(ye,{value:a.cooperating_brokerage??"",onChange:c=>l({cooperating_brokerage:c.target.value})})]})]})]}),e.jsxs("div",{className:"border-t pt-4",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-3",children:"Experience"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[["rating_communication","Communication"],["rating_professionalism","Professionalism"],["rating_problem_solving","Problem solving"]].map(([c,d])=>e.jsxs("div",{children:[e.jsx(ne,{children:d}),e.jsx(oun,{value:a[c],onChange:u=>l({[c]:u})}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-1",children:cun[a[c]]??"—"})]},c))}),e.jsxs("div",{className:"mt-4",children:[e.jsx(ne,{children:"Would you enjoy being in business with this agent?"}),e.jsx("div",{className:"flex gap-2 mt-2",children:["yes","maybe","no"].map(c=>e.jsx("button",{type:"button",onClick:()=>l({enjoy_business_with:c}),className:Mt("rounded-full px-4 py-1.5 text-[12.5px] font-medium border capitalize",a.enjoy_business_with===c?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:c},c))})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(ne,{children:"What stood out?"}),e.jsx(Ms,{rows:2,value:a.stood_out??"",onChange:c=>l({stood_out:c.target.value})})]}),e.jsxs("div",{className:"mt-4",children:[e.jsx(ne,{children:"Private notes"}),e.jsx(Ms,{rows:2,value:a.private_notes??"",onChange:c=>l({private_notes:c.target.value}),placeholder:"Only you can see these."})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(B,{onClick:o,disabled:r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save & review"})]})]})})}function hun({tx:s,onClose:t,onDecision:n,onAddToPipeline:r,onMessage:a}){return s?e.jsx(_s,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Would you like to build a relationship?"}),e.jsxs(Jn,{children:[s.cooperating_first_name?`${s.cooperating_first_name} ${s.cooperating_last_name??""}`:"This agent"," on ",s.property_address,"."]})]}),e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsx(VF,{icon:Fo,label:"Add to Agent Pipeline",tone:"violet",onClick:r}),e.jsx(VF,{icon:iL,label:"Send a professional compliment",tone:"teal",onClick:()=>{n("send_compliment"),a()}}),e.jsx(VF,{icon:ey,label:"Invite to coffee",tone:"amber",onClick:()=>{n("invite_coffee"),a()}}),e.jsx(VF,{icon:un,label:"Share a relevant resource",tone:"sky",onClick:()=>n("share_resource")}),e.jsx(VF,{icon:Uc,label:"No action right now",tone:"slate",onClick:()=>{n("no_action"),t()}})]})]})}):null}function VF({icon:s,label:t,tone:n,onClick:r}){const a={violet:"bg-violet-50 text-violet-700 hover:bg-violet-100",teal:"bg-teal-50 text-teal-700 hover:bg-teal-100",amber:"bg-amber-50 text-amber-700 hover:bg-amber-100",sky:"bg-sky-50 text-sky-700 hover:bg-sky-100",slate:"bg-slate-50 text-slate-700 hover:bg-slate-100"};return e.jsxs("button",{onClick:r,className:Mt("flex items-center gap-3 rounded-xl px-4 py-3 text-left transition-colors",a[n]),children:[e.jsx(s,{className:"h-5 w-5"}),e.jsx("div",{className:"flex-1 text-[13.5px] font-medium",children:t}),e.jsx(ga,{className:"h-4 w-4 opacity-60"})]})}function mun({tx:s,onClose:t}){const[n,r]=N.useState("warm");if(!s)return null;const a=lun(s,n);return e.jsx(_s,{open:!!s,onOpenChange:i=>!i&&t(),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Personalized message"}),e.jsx(Jn,{children:"Adjust the tone, then copy and send from your usual inbox."})]}),e.jsx("div",{className:"flex gap-1.5 mb-3",children:[["warm","Warm & pro"],["peer","Casual peer"],["text","Short text"],["email","Email"]].map(([i,l])=>e.jsx("button",{onClick:()=>r(i),className:Mt("rounded-full px-3 py-1 text-[11.5px] font-medium border",n===i?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-700 border-slate-200"),children:l},i))}),e.jsx(Ms,{value:a,readOnly:!0,rows:10,className:"font-mono text-[12.5px]"}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Close"}),e.jsxs(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{navigator.clipboard.writeText(a),ae.success("Copied to clipboard")},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1.5"})," Copy"]})]})]})})}function CSt(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:["attract-content",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await q.from("attract_content_drafts").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=yt({mutationFn:async o=>{const{data:c,error:d}=await q.functions.invoke("attract-content-generate",{body:o});if(d)throw d;if(c!=null&&c.error)throw new Error(c.error);return c},onSuccess:o=>{t.invalidateQueries({queryKey:["attract-content"]}),o.demo?ae.info("Demo generation used — configure AI provider for live results"):ae.success("Content generated")},onError:o=>ae.error(o.message)}),a=yt({mutationFn:async o=>{const{data:c,error:d}=await q.from("attract_content_drafts").update(o).eq("id",o.id).select().single();if(d)throw d;return c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Saved")}}),i=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").update({status:"posted",posted_at:new Date().toISOString()}).eq("id",o);if(c)throw c;await q.rpc("award_attract_activity",{_user_id:s.id,_activity_type:"content_posted",_title:"Posted authority content",_description:null,_pillar:"influence",_agent_id:null,_metadata:{draft_id:o},_dedupe_minutes:30})},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),t.invalidateQueries({queryKey:["attract-activities"]}),ae.success("Marked as posted")}}),l=yt({mutationFn:async o=>{const{error:c}=await q.from("attract_content_drafts").delete().eq("id",o);if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-content"]}),ae.success("Draft removed")}});return{drafts:n.data??[],isLoading:n.isLoading,generate:r,save:a,markPosted:i,remove:l}}const FTe=[{key:"transaction_lesson",label:"Transaction Lesson",blurb:"A real story from a recent deal that teaches something.",fields:[{key:"what_happened",label:"What happened?",placeholder:"A short version of the story."},{key:"challenge",label:"What challenge came up?"},{key:"what_you_did",label:"What did you do?"},{key:"lesson",label:"What can another agent learn?"}]},{key:"behind_the_business",label:"Behind the Business",blurb:"A peek behind how you run the day-to-day.",fields:[{key:"topic",label:"What are you sharing?",placeholder:"A morning routine, tool stack, client system..."},{key:"why",label:"Why does it matter?"},{key:"takeaway",label:"What can they take away?"}]},{key:"unpopular_opinion",label:"Unpopular Industry Opinion",blurb:"Say what most people are afraid to say.",fields:[{key:"opinion",label:"What is your actual opinion?"},{key:"why",label:"Why do you believe it?"},{key:"example",label:"What real example supports it?"}]},{key:"system_win",label:"A System That Improved My Business",blurb:"A specific system with a before/after.",fields:[{key:"system",label:"What is the system?"},{key:"before",label:"What was life like before?"},{key:"after",label:"What changed after?"}]},{key:"mistake_to_avoid",label:"Mistake Agents Can Avoid",blurb:"A mistake you made or watched happen — and the fix.",fields:[{key:"mistake",label:"What is the mistake?"},{key:"result",label:"What did it cost?"},{key:"fix",label:"How do you avoid it now?"}]},{key:"do_differently",label:"What I Would Do Differently",blurb:"Reflection on a past year, launch, or transaction.",fields:[{key:"period",label:"What period are you reflecting on?"},{key:"what",label:"What would you do differently?"},{key:"why",label:"Why?"}]},{key:"leadership_lesson",label:"Leadership Lesson",blurb:"A moment that shaped how you lead.",fields:[{key:"story",label:"The moment/story"},{key:"lesson",label:"The lesson"}]},{key:"tool_tip",label:"Tool or Technology Tip",blurb:"A tool + how you use it + why it matters.",fields:[{key:"tool",label:"Which tool?"},{key:"how",label:"How do you use it?"},{key:"impact",label:"The impact on your business"}]},{key:"market_strategy",label:"Market Strategy",blurb:"Something you're seeing in your market that others are missing.",fields:[{key:"observation",label:"What are you seeing?"},{key:"strategy",label:"What are you doing about it?"},{key:"takeaway",label:"How can they apply it?"}]},{key:"event_promo",label:"Event Promotion",blurb:"Promote an event without sounding like a pitch.",fields:[{key:"event",label:"Event name"},{key:"who",label:"Who is it for?"},{key:"walk_away",label:"What will they walk away with?"},{key:"when_where",label:"When and where"}]}],pun=["Direct","Educational","Fun","Contrarian","Encouraging"],fun=["short","medium","long"],xun=["instagram","linkedin","facebook","youtube","email"],Kge={idea:{label:"Idea",color:"bg-slate-100 text-slate-700"},draft:{label:"Draft",color:"bg-amber-100 text-amber-800"},ready:{label:"Ready",color:"bg-emerald-100 text-emerald-800"},posted:{label:"Posted",color:"bg-violet-100 text-violet-800"}};function gun(){const{drafts:s,isLoading:t,generate:n,save:r,markPosted:a,remove:i}=CSt(),[l,o]=N.useState(!1),[c,d]=N.useState(null),u=N.useMemo(()=>({ready:s.filter(h=>h.status==="ready"),draft:s.filter(h=>h.status==="draft"),idea:s.filter(h=>h.status==="idea"),posted:s.filter(h=>h.status==="posted")}),[s]);return e.jsxs("div",{children:[e.jsxs(In,{to:"/attract/influence",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(zu,{eyebrow:"Influence → Tool",title:"Authority Content Studio",description:"Turn your real experience into agent-focused content that builds authority — without sounding like a brokerage pitch.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{d(null),o(!0)},children:[e.jsx(Im,{className:"h-4 w-4 mr-1.5"})," New Content"]})}),e.jsxs("div",{className:"mb-6 rounded-2xl border border-amber-200 bg-amber-50/70 px-5 py-3.5 text-[13px] text-amber-900 flex items-start gap-3",children:[e.jsx(un,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{children:[e.jsx("span",{className:"font-semibold",children:"80/20 rule:"})," Aim for 80% useful industry, business, and personal content — and no more than 20% direct brokerage content."]})]}),e.jsxs(Fr,{defaultValue:"all",className:"mb-8",children:[e.jsxs(Rr,{children:[e.jsxs(Zt,{value:"all",children:["All (",s.length,")"]}),e.jsxs(Zt,{value:"ready",children:["Ready (",u.ready.length,")"]}),e.jsxs(Zt,{value:"draft",children:["Draft (",u.draft.length,")"]}),e.jsxs(Zt,{value:"posted",children:["Posted (",u.posted.length,")"]})]}),e.jsx(is,{value:"all",children:e.jsx(VG,{drafts:s,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(is,{value:"ready",children:e.jsx(VG,{drafts:u.ready,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(is,{value:"draft",children:e.jsx(VG,{drafts:u.draft,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:h=>a.mutate(h),onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})}),e.jsx(is,{value:"posted",children:e.jsx(VG,{drafts:u.posted,isLoading:t,onOpen:h=>{d(h),o(!0)},onPosted:()=>{},onRemove:h=>i.mutate(h),onEmpty:()=>{d(null),o(!0)}})})]}),e.jsx(l6,{}),e.jsx(yun,{open:l,editing:c,onClose:()=>{o(!1),d(null)},generate:n,save:r,markPosted:h=>a.mutate(h)})]})}function VG({drafts:s,isLoading:t,onOpen:n,onPosted:r,onRemove:a,onEmpty:i}){return t?e.jsx("div",{className:"space-y-3 mt-4",children:[0,1,2].map(l=>e.jsx(fe,{className:"p-5 rounded-2xl h-24 animate-pulse bg-slate-100"},l))}):s.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center mt-4",children:[e.jsx("div",{className:"h-14 w-14 rounded-2xl bg-violet-100 grid place-items-center mx-auto mb-4",children:e.jsx(J1,{className:"h-6 w-6 text-violet-700"})}),e.jsx("h3",{className:"text-lg font-semibold text-slate-900",children:"Start your first authority piece"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 max-w-md mx-auto mt-2",children:"Pick a real experience, answer 3 quick questions, and get a script, caption, carousel outline, and email — all in one shot."}),e.jsxs(B,{className:"mt-6 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:i,children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Create your first draft"]})]}):e.jsx("div",{className:"space-y-3 mt-4",children:s.map(l=>{var c,d;const o=((c=FTe.find(u=>u.key===l.mode))==null?void 0:c.label)??l.mode;return e.jsx(fe,{className:"p-5 rounded-2xl hover:shadow-md transition-shadow",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Ue,{className:Mt("text-[10.5px] border-0",Kge[l.status].color),children:Kge[l.status].label}),e.jsx(Ue,{variant:"outline",className:"text-[10.5px]",children:o}),l.tone&&e.jsx(Ue,{variant:"outline",className:"text-[10.5px]",children:l.tone}),l.ratio_flag&&e.jsxs(Ue,{className:"text-[10.5px] bg-amber-100 text-amber-900 border-0 gap-1",children:[e.jsx(ic,{className:"h-3 w-3"})," Sounds promotional"]})]}),e.jsx("div",{className:"text-[14px] font-semibold text-slate-900 mt-2 line-clamp-1",children:l.topic??((d=l.hook_options)==null?void 0:d[0])??"Untitled draft"}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:l.caption??l.script??""}),e.jsx("div",{className:"text-[11px] text-slate-500 mt-2",children:l.posted_at?`Posted ${Ss(new Date(l.posted_at),"MMM d")}`:`Updated ${Ss(new Date(l.updated_at),"MMM d")}`})]}),e.jsxs("div",{className:"flex flex-col gap-1.5",children:[e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>n(l),children:"Open"}),l.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"ghost",className:"text-emerald-700",onClick:()=>r(l.id),children:[e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1"})," Posted"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(l.id),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})},l.id)})})}function yun({open:s,editing:t,onClose:n,generate:r,save:a,markPosted:i}){const[l,o]=N.useState((t==null?void 0:t.mode)??"transaction_lesson"),[c,d]=N.useState((t==null?void 0:t.input_json)??{}),[u,h]=N.useState((t==null?void 0:t.topic)??""),[p,f]=N.useState((t==null?void 0:t.tone)??"Educational"),[y,_]=N.useState((t==null?void 0:t.length)??"medium"),[v,j]=N.useState((t==null?void 0:t.platforms)??["instagram"]),[w,S]=N.useState((t==null?void 0:t.include_brokerage_reference)??!1),[A,E]=N.useState(t??null),[O,D]=N.useState(""),[I,F]=N.useState((t==null?void 0:t.status)??"draft"),z=FTe.find(Y=>Y.key===l),H=async Y=>{const W=await r.mutateAsync({mode:l,topic:u,inputs:c,tone:p,length:y,platforms:v,include_brokerage_reference:w,refinement:Y??O,draft_id:A==null?void 0:A.id});W!=null&&W.draft&&E(W.draft),D("")},Z=async Y=>{if(!A)return;const W=await a.mutateAsync({id:A.id,...Y});E(W)};return e.jsx(_s,{open:s,onOpenChange:Y=>!Y&&n(),children:e.jsx(bs,{className:"max-w-5xl max-h-[92vh] overflow-hidden p-0",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-[320px_1fr] max-h-[92vh]",children:[e.jsxs("div",{className:"border-r bg-slate-50 p-5 overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{className:"text-base",children:"Content Studio"}),e.jsx(Jn,{className:"text-[12px]",children:z.blurb})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px]",children:"Content mode"}),e.jsxs(us,{value:l,onValueChange:Y=>{o(Y),d({})},children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:FTe.map(Y=>e.jsx(Ze,{value:Y.key,children:Y.label},Y.key))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px]",children:"Topic (optional)"}),e.jsx(ye,{value:u,onChange:Y=>h(Y.target.value),placeholder:"1-line summary"})]}),z.fields.map(Y=>e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px]",children:Y.label}),e.jsx(Ms,{rows:2,value:c[Y.key]??"",onChange:W=>d({...c,[Y.key]:W.target.value}),placeholder:Y.placeholder})]},Y.key)),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px]",children:"Tone"}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:pun.map(Y=>e.jsx(Ze,{value:Y,children:Y},Y))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px]",children:"Length"}),e.jsxs(us,{value:y,onValueChange:_,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:fun.map(Y=>e.jsx(Ze,{value:Y,children:Y},Y))})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px]",children:"Platforms"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mt-1",children:xun.map(Y=>e.jsx("button",{type:"button",onClick:()=>j(v.includes(Y)?v.filter(W=>W!==Y):[...v,Y]),className:Mt("rounded-full px-2.5 py-1 text-[11px] capitalize border",v.includes(Y)?"bg-violet-600 text-white border-violet-600":"bg-white border-slate-200 text-slate-700"),children:Y},Y))})]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-700",children:[e.jsx("input",{type:"checkbox",checked:w,onChange:Y=>S(Y.target.checked)}),"Include a light brokerage reference"]}),e.jsxs(B,{className:"w-full bg-gradient-to-r from-violet-600 to-indigo-600 rounded-full",onClick:()=>H(),disabled:r.isPending,children:[e.jsx(Im,{className:"h-4 w-4 mr-1.5"})," ",r.isPending?"Generating…":A?"Regenerate":"Generate content"]})]})]}),e.jsx("div",{className:"overflow-y-auto p-6",children:A?e.jsxs("div",{className:"space-y-5",children:[A.ratio_flag&&e.jsxs("div",{className:"rounded-xl border border-amber-200 bg-amber-50 p-3 text-[12.5px] text-amber-900 flex items-start gap-2",children:[e.jsx(ic,{className:"h-4 w-4 mt-0.5"}),e.jsxs("div",{className:"flex-1",children:[e.jsx("div",{className:"font-semibold",children:"Heads up — this leans promotional."}),e.jsx("div",{children:"Not blocking anything, but you can rewrite it to feel more like teaching."})]}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>H("Make this less salesy — focus purely on the lesson."),children:"Less salesy"})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Ue,{className:Mt("text-[10.5px] border-0",Kge[I].color),children:Kge[I].label}),e.jsxs(us,{value:I,onValueChange:Y=>{F(Y),Z({status:Y})},children:[e.jsx(ls,{className:"h-8 w-32 text-[12px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"idea",children:"Idea"}),e.jsx(Ze,{value:"draft",children:"Draft"}),e.jsx(Ze,{value:"ready",children:"Ready"}),e.jsx(Ze,{value:"posted",children:"Posted"})]})]}),e.jsx(ye,{type:"date",className:"h-8 w-40 text-[12px]",value:A.planned_at?A.planned_at.slice(0,10):"",onChange:Y=>Z({planned_at:Y.target.value?new Date(Y.target.value).toISOString():null})}),A.status!=="posted"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>i(A.id),children:[e.jsx(lr,{className:"h-3.5 w-3.5 mr-1"})," Mark posted"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(In,{to:`/attract/provide/kits/new?seed=${encodeURIComponent(A.topic||A.mode)}`,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Turn into a kit"]})})]}),e.jsx(WI,{title:"Hook options",children:e.jsx("div",{className:"space-y-1.5",children:(A.hook_options??[]).map((Y,W)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13.5px] text-slate-800 flex items-start gap-2",children:[e.jsxs("span",{className:"text-violet-600 font-semibold",children:[W+1,"."]}),e.jsx("span",{className:"flex-1",children:Y}),e.jsx(zTe,{value:Y})]},W))})}),e.jsx(WI,{title:"Teleprompter script",children:e.jsx(pke,{value:A.script??"",onSave:Y=>Z({script:Y})})}),e.jsx(WI,{title:"Social caption",children:e.jsx(pke,{value:A.caption??"",onSave:Y=>Z({caption:Y})})}),e.jsx(WI,{title:"Carousel outline",children:e.jsx("div",{className:"space-y-1.5",children:(A.carousel_outline??[]).map((Y,W)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13px]",children:[e.jsxs("div",{className:"text-[10.5px] uppercase tracking-wider text-slate-500 font-semibold",children:["Slide ",Y.slide??W+1]}),e.jsx("div",{className:"text-slate-800 mt-0.5",children:Y.text})]},W))})}),e.jsx(WI,{title:"Email lesson",children:e.jsx(pke,{value:A.email_lesson??"",onSave:Y=>Z({email_lesson:Y})})}),e.jsx(WI,{title:"CTA options",children:e.jsx("div",{className:"space-y-1.5",children:(A.cta_options??[]).map((Y,W)=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-3 text-[13px] text-slate-800 flex items-start gap-2",children:[e.jsx("span",{className:"flex-1",children:Y}),e.jsx(zTe,{value:Y})]},W))})}),e.jsxs("div",{className:"rounded-xl border border-slate-200 p-3",children:[e.jsx("div",{className:"text-[12px] font-semibold text-slate-700 mb-2",children:"Refine further"}),e.jsx("div",{className:"flex flex-wrap gap-1.5 mb-2",children:["Make this sound more like me","Shorten the hook","Add a real example","Make it less salesy"].map(Y=>e.jsx(B,{size:"sm",variant:"outline",className:"text-[11.5px]",onClick:()=>H(Y),children:Y},Y))}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:O,onChange:Y=>D(Y.target.value),placeholder:"Custom refinement…"}),e.jsxs(B,{variant:"outline",onClick:()=>H(),disabled:r.isPending,children:[e.jsx(Ei,{className:"h-3.5 w-3.5 mr-1"})," Regenerate"]})]})]})]}):e.jsx("div",{className:"h-full flex items-center justify-center text-center text-slate-500",children:e.jsxs("div",{children:[e.jsx(f9,{className:"h-10 w-10 text-violet-300 mx-auto mb-3"}),e.jsx("div",{className:"text-[14px] font-medium text-slate-700",children:"Fill in the story on the left, then generate."}),e.jsx("div",{className:"text-[12.5px] mt-1",children:"You'll get a script, caption, carousel, email, and hooks in one shot."})]})})})]})})})}function WI({title:s,children:t}){return e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2 flex items-center gap-1.5",children:[e.jsx(yr,{className:"h-3 w-3 opacity-0"})," ",s]}),t]})}function pke({value:s,onSave:t}){const[n,r]=N.useState(s);return e.jsxs("div",{children:[e.jsx(Ms,{rows:5,value:n,onChange:a=>r(a.target.value),className:"text-[13.5px]"}),e.jsxs("div",{className:"flex gap-2 mt-2",children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>t(n),children:"Save edit"}),e.jsx(zTe,{value:n})]})]})}function zTe({value:s}){return e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{navigator.clipboard.writeText(s),ae.success("Copied")},children:e.jsx(Zr,{className:"h-3.5 w-3.5"})})}const vun={draft:"bg-slate-100 text-slate-700",published:"bg-emerald-100 text-emerald-800",archived:"bg-amber-100 text-amber-800"};function bun(){const{kits:s,isLoading:t,create:n,duplicate:r,remove:a}=AR(),i=Ln(),l=async()=>{const o=await n.mutateAsync({title:"Untitled Kit",status:"draft"});i(`/attract/provide/kits/${o.id}/edit`)};return e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Provide · Resource Kits",title:"Your Resource Kits",description:"Package the value you already share, then track what actually creates conversations.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(In,{to:"/attract/provide/kits/templates",children:[e.jsx(qg,{className:"h-4 w-4 mr-2"}),"Starter library"]})}),e.jsxs(B,{onClick:l,className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New kit"]})]})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading kits…"}),!t&&s.length===0&&e.jsxs(fe,{className:"p-10 text-center rounded-2xl border-dashed border-slate-300 bg-white",children:[e.jsx(un,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"mt-3 text-lg font-semibold",children:"You haven't built a kit yet."}),e.jsx("p",{className:"text-slate-600 max-w-md mx-auto mt-1 text-sm",children:"Start from a starter template or a blank kit. Bundle 3–7 pieces of real value and share with agents you'd love to work alongside."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-5",children:[e.jsx(B,{variant:"outline",asChild:!0,children:e.jsx(In,{to:"/attract/provide/kits/templates",children:"Browse starter library"})}),e.jsx(B,{onClick:l,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Start a blank kit"})]})]}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(o=>{var c;return e.jsxs(fe,{className:"p-5 rounded-2xl border-slate-200 bg-white hover:shadow-md transition-shadow flex flex-col",children:[e.jsx("div",{className:"flex items-start justify-between gap-2",children:e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{className:vun[o.status]+" capitalize",children:o.status}),o.pillar&&e.jsx(Ue,{variant:"outline",className:"capitalize",children:o.pillar})]}),e.jsx("div",{className:"mt-2 text-[16px] font-semibold text-slate-900 line-clamp-2",children:o.title}),o.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",o.audience]})]})}),o.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-3 line-clamp-3",children:o.description}),e.jsx("div",{className:"mt-4 flex flex-wrap gap-1",children:(c=o.tags)==null?void 0:c.slice(0,4).map(d=>e.jsxs(Ue,{variant:"secondary",className:"text-[10.5px]",children:["#",d]},d))}),e.jsxs("div",{className:"mt-auto pt-4 flex items-center gap-2 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(In,{to:`/attract/provide/kits/${o.id}/edit`,children:[e.jsx(i9,{className:"h-3.5 w-3.5 mr-1.5"}),"Edit"]})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs(In,{to:`/attract/provide/kits/${o.id}/analytics`,children:[e.jsx(_o,{className:"h-3.5 w-3.5 mr-1.5"}),"Analytics"]})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:async()=>{const d=await r.mutateAsync(o.id);ae.success("Duplicated"),i(`/attract/provide/kits/${d}/edit`)},children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>{confirm("Delete this kit? Shares and events will also be removed.")&&a.mutate(o.id,{onSuccess:()=>ae.success("Deleted")})},children:e.jsx(_n,{className:"h-3.5 w-3.5 text-rose-600"})})]})]},o.id)})})]})}const _un={pdf:br,video:El,link:Yo,checklist:lu,template:xw,text:br,content_studio:un,resource:br};function TSt({kit:s,items:t,owner:n,personalNote:r,mode:a="public",onEvent:i}){const l=(o,c,d)=>i==null?void 0:i(o,c,d);return e.jsxs("div",{className:"bg-[#0B0F1E] text-slate-100 rounded-2xl overflow-hidden",children:[s.cover_image_url?e.jsxs("div",{className:"aspect-[16/7] bg-slate-800 relative",children:[e.jsx("img",{src:s.cover_image_url,alt:"",className:"w-full h-full object-cover"}),e.jsx("div",{className:"absolute inset-0 bg-gradient-to-t from-[#0B0F1E] to-transparent"})]}):e.jsx("div",{className:"h-24 bg-gradient-to-br from-violet-700 via-indigo-700 to-slate-900"}),e.jsxs("div",{className:"p-5 md:p-8",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[n.avatar_url?e.jsx("img",{src:n.avatar_url,alt:"",className:"h-11 w-11 rounded-full object-cover ring-2 ring-white/10"}):e.jsx("div",{className:"h-11 w-11 rounded-full bg-white/10 grid place-items-center text-white/70 font-semibold",children:n.display_name.slice(0,1)}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-semibold",children:n.display_name}),n.brokerage&&e.jsx("div",{className:"text-[11px] text-slate-400",children:n.brokerage})]})]}),e.jsx("h1",{className:"mt-5 text-2xl md:text-3xl font-semibold tracking-tight text-white",children:s.title}),s.audience&&e.jsxs("div",{className:"text-[12px] uppercase tracking-widest text-violet-300 mt-1",children:["For ",s.audience]}),s.description&&e.jsx("p",{className:"text-slate-300 mt-3 text-[14.5px] leading-relaxed",children:s.description}),(r||s.intro_text)&&e.jsxs(fe,{className:"mt-6 p-4 bg-white/5 border-white/10 text-slate-200",children:[r&&e.jsx("div",{className:"text-[13px] whitespace-pre-line",children:r}),r&&s.intro_text&&e.jsx("div",{className:"my-2 border-t border-white/10"}),s.intro_text&&e.jsx("div",{className:"text-[13px] whitespace-pre-line text-slate-300",children:s.intro_text})]}),s.intro_video_url&&e.jsx("div",{className:"mt-5 aspect-video rounded-xl overflow-hidden bg-black",children:e.jsx("iframe",{src:wun(s.intro_video_url),className:"w-full h-full",allow:"autoplay; encrypted-media; picture-in-picture",allowFullScreen:!0,title:"Intro video",onLoad:()=>l("video_start")})}),e.jsx("div",{className:"mt-8 space-y-3",children:t.filter(o=>!o.is_hidden).map(o=>{var d,u;const c=_un[o.type]??br;return e.jsx(fe,{className:"p-4 bg-white/5 border-white/10 text-slate-100",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("div",{className:"h-9 w-9 rounded-lg bg-violet-600/20 text-violet-300 grid place-items-center flex-shrink-0",children:e.jsx(c,{className:"h-4 w-4"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("div",{className:"text-[14px] font-semibold text-white",children:o.title}),o.description&&e.jsx("div",{className:"text-[12.5px] text-slate-300 mt-0.5",children:o.description}),o.type==="checklist"&&((d=o.content)==null?void 0:d.items)&&e.jsx("ul",{className:"mt-2 space-y-1 text-[13px] text-slate-200",children:o.content.items.map((h,p)=>e.jsxs("li",{className:"flex gap-2",children:[e.jsx("span",{className:"text-violet-400",children:"•"}),h]},p))}),(o.type==="text"||o.type==="template")&&((u=o.content)==null?void 0:u.body)&&e.jsx("div",{className:"mt-2 text-[13px] text-slate-300 whitespace-pre-line",children:o.content.body}),o.url&&["video","pdf","link","resource"].includes(o.type)&&e.jsxs("div",{className:"mt-3 flex gap-2 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"secondary",asChild:!0,onClick:()=>l("resource_open",o.id),children:e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1.5"}),"Open"]})}),o.allow_download&&o.type!=="link"&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,onClick:()=>l("file_download",o.id),children:e.jsxs("a",{href:o.url,target:"_blank",rel:"noreferrer",download:!0,children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-1.5"}),"Download"]})}),o.type==="link"&&e.jsx(B,{size:"sm",variant:"outline",asChild:!0,onClick:()=>l("external_link_click",o.id),children:e.jsx("a",{href:o.url,target:"_blank",rel:"noreferrer",children:"Visit"})})]})]})]})},o.id)})}),s.cta_label&&s.cta_url&&e.jsx("div",{className:"mt-8 text-center",children:e.jsx(B,{size:"lg",asChild:!0,className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>l("primary_cta_click"),children:e.jsx("a",{href:s.cta_url,target:"_blank",rel:"noreferrer",children:s.cta_label})})}),e.jsx("div",{className:"mt-10 pt-6 border-t border-white/10 text-[11px] text-slate-500 leading-relaxed",children:"Brokerage and compensation information should always be verified in writing. Nothing shared here constitutes a formal offer, agreement, or guarantee of income."})]})]})}function wun(s){try{const t=new URL(s);if(t.hostname.includes("youtube.com")||t.hostname.includes("youtu.be")){const n=t.hostname.includes("youtu.be")?t.pathname.slice(1):t.searchParams.get("v");if(n)return`https://www.youtube.com/embed/${n}`}if(t.hostname.includes("vimeo.com")){const n=t.pathname.split("/").filter(Boolean).pop();if(n)return`https://player.vimeo.com/video/${n}`}return t.hostname.includes("loom.com")?s.replace("/share/","/embed/"):s}catch{return s}}const jun=[{value:"text",label:"Text lesson"},{value:"checklist",label:"Checklist"},{value:"template",label:"Template / Script"},{value:"video",label:"Video / Embed"},{value:"pdf",label:"PDF / File"},{value:"link",label:"External link"},{value:"content_studio",label:"Content Studio output"},{value:"resource",label:"Existing resource"}];function get(){var Y,W;const{kitId:s}=bi(),[t]=xl(),n=Ln(),{user:r}=vs(),a=s===void 0,{create:i,update:l}=AR(),{data:o,isLoading:c}=aSt(s),{items:d,add:u,update:h,remove:p,reorder:f}=sdn(s),{shares:y,create:_,revoke:v}=iSt(s),{agents:j}=i0(),[w,S]=N.useState(null),[A,E]=N.useState("desktop"),[O,D]=N.useState("idle"),I=N.useRef(null);N.useEffect(()=>{a&&!w&&(async()=>{const ee=t.get("seed"),se=await i.mutateAsync({title:ee?`From: ${ee}`:"Untitled Kit",status:"draft"});n(`/attract/provide/kits/${se.id}/edit`,{replace:!0})})()},[a]),N.useEffect(()=>{o&&S(o)},[o==null?void 0:o.id]);const F=ee=>{s&&(S(se=>({...se,...ee})),D("saving"),clearTimeout(I.current),I.current=setTimeout(async()=>{try{await l.mutateAsync({id:s,patch:ee}),D("saved"),setTimeout(()=>D("idle"),1500)}catch(se){ae.error(se.message??"Save failed"),D("idle")}},800))},z=async ee=>{!s||!r||await u.mutateAsync({user_id:r.id,type:ee,title:`New ${ee.replace("_"," ")}`})},H=(ee,se)=>{const oe=[...d],he=ee+se;he<0||he>=oe.length||([oe[ee],oe[he]]=[oe[he],oe[ee]],f.mutate(oe.map(ce=>ce.id)))},Z=y.filter(ee=>ee.status==="active");return a||!w?e.jsx("div",{className:"text-slate-500 text-sm",children:"Preparing your kit…"}):c?e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}):e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Provide · Kit builder",title:w.title||"Untitled Kit",description:O==="saving"?"Saving…":O==="saved"?"Saved":`Last edited ${Ss(new Date(w.updated_at),"MMM d, h:mm a")}`,actions:e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(In,{to:"/attract/provide/kits",children:[e.jsx(qr,{className:"h-4 w-4 mr-1"}),"Kits"]})}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsx(In,{to:`/attract/provide/kits/${s}/analytics`,children:"Analytics"})}),e.jsxs(us,{value:w.status,onValueChange:ee=>F({status:ee}),children:[e.jsx(ls,{className:"w-[130px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"draft",children:"Draft"}),e.jsx(Ze,{value:"published",children:"Published"}),e.jsx(Ze,{value:"archived",children:"Archived"})]})]})]})}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-12 gap-6",children:[e.jsxs("div",{className:"xl:col-span-4 space-y-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit details"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:w.title??"",onChange:ee=>F({title:ee.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Short description"}),e.jsx(Ms,{rows:3,value:w.description??"",onChange:ee=>F({description:ee.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Cover image URL"}),e.jsx(ye,{placeholder:"https://…",value:w.cover_image_url??"",onChange:ee=>F({cover_image_url:ee.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Audience"}),e.jsx(ye,{placeholder:"e.g. New agents",value:w.audience??"",onChange:ee=>F({audience:ee.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Pillar"}),e.jsxs(us,{value:w.pillar??"",onValueChange:ee=>F({pillar:ee}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Choose"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"produce",children:"Produce"}),e.jsx(Ze,{value:"influence",children:"Influence"}),e.jsx(Ze,{value:"provide",children:"Provide"}),e.jsx(Ze,{value:"connect",children:"Connect"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Tags (comma separated)"}),e.jsx(ye,{value:(w.tags??[]).join(", "),onChange:ee=>F({tags:ee.target.value.split(",").map(se=>se.trim()).filter(Boolean)})})]})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Personal welcome"}),e.jsxs("div",{className:"space-y-3 mt-3",children:[e.jsx(Ms,{rows:4,placeholder:"Write a short personal note that opens the kit.",value:w.intro_text??"",onChange:ee=>F({intro_text:ee.target.value})}),e.jsxs("div",{children:[e.jsx(ne,{children:"Intro video URL (optional)"}),e.jsx(ye,{placeholder:"Loom/YouTube/Vimeo",value:w.intro_video_url??"",onChange:ee=>F({intro_video_url:ee.target.value})})]})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Call to action"}),e.jsxs("div",{className:"grid grid-cols-2 gap-2 mt-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Button label"}),e.jsx(ye,{value:w.cta_label??"",onChange:ee=>F({cta_label:ee.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Button URL"}),e.jsx(ye,{placeholder:"https://…",value:w.cta_url??"",onChange:ee=>F({cta_url:ee.target.value})})]})]}),e.jsxs("div",{className:"mt-3",children:[e.jsx(ne,{children:"Expiration (optional)"}),e.jsx(ye,{type:"datetime-local",value:w.expires_at?w.expires_at.slice(0,16):"",onChange:ee=>F({expires_at:ee.target.value?new Date(ee.target.value).toISOString():null})})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Share this kit"}),e.jsx(Nun,{kitId:s,agents:j,shares:Z,onCreate:ee=>_.mutate(ee),onRevoke:ee=>v.mutate(ee),status:w.status})]})]}),e.jsx("div",{className:"xl:col-span-5 space-y-4",children:e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Kit sections"}),e.jsx("div",{className:"text-[13px] text-slate-600",children:"Drag order using arrows. Reorder to change how visitors experience the kit."})]}),e.jsxs(us,{onValueChange:ee=>z(ee),children:[e.jsx(ls,{className:"w-[180px]",children:e.jsx(hs,{placeholder:"+ Add item"})}),e.jsx(cs,{children:jun.map(ee=>e.jsx(Ze,{value:ee.value,children:ee.label},ee.value))})]})]}),e.jsxs("div",{className:"mt-4 space-y-3",children:[d.length===0&&e.jsx("div",{className:"text-center text-sm text-slate-500 py-10 border border-dashed rounded-xl",children:"No sections yet. Add your first item above."}),d.map((ee,se)=>{var oe,he;return e.jsx(fe,{className:"p-4 border-slate-200",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsxs("div",{className:"flex flex-col gap-1",children:[e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>H(se,-1),children:e.jsx(Iu,{className:"h-4 w-4"})}),e.jsx("button",{className:"text-slate-400 hover:text-slate-700",onClick:()=>H(se,1),children:e.jsx(sm,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"flex-1 min-w-0 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{variant:"outline",className:"capitalize",children:ee.type.replace("_"," ")}),e.jsx(ye,{className:"flex-1",value:ee.title,onChange:ce=>h.mutate({id:ee.id,patch:{title:ce.target.value}})})]}),e.jsx(Ms,{rows:2,placeholder:"Short description",value:ee.description??"",onChange:ce=>h.mutate({id:ee.id,patch:{description:ce.target.value}})}),["video","pdf","link","resource"].includes(ee.type)&&e.jsx(ye,{placeholder:"URL",value:ee.url??"",onChange:ce=>h.mutate({id:ee.id,patch:{url:ce.target.value}})}),["text","template"].includes(ee.type)&&e.jsx(Ms,{rows:4,placeholder:"Body text or script",value:((oe=ee.content)==null?void 0:oe.body)??"",onChange:ce=>h.mutate({id:ee.id,patch:{content:{...ee.content??{},body:ce.target.value}}})}),ee.type==="checklist"&&e.jsx(Ms,{rows:5,placeholder:"One item per line",value:(((he=ee.content)==null?void 0:he.items)??[]).join(` `),onChange:ce=>h.mutate({id:ee.id,patch:{content:{items:ce.target.value.split(` `).map(me=>me.trim()).filter(Boolean)}}})}),e.jsxs("div",{className:"flex items-center gap-4",children:[e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(jn,{checked:ee.allow_download,onCheckedChange:ce=>h.mutate({id:ee.id,patch:{allow_download:ce}})}),"Allow download"]}),e.jsxs("label",{className:"flex items-center gap-2 text-[12px] text-slate-600",children:[e.jsx(jn,{checked:!ee.is_hidden,onCheckedChange:ce=>h.mutate({id:ee.id,patch:{is_hidden:!ce}})}),"Visible"]}),e.jsxs("button",{className:"ml-auto text-rose-600 text-[12px] flex items-center gap-1",onClick:()=>p.mutate(ee.id),children:[e.jsx(_n,{className:"h-3.5 w-3.5"}),"Delete"]})]})]})]})},ee.id)})]})]})}),e.jsx("div",{className:"xl:col-span-3",children:e.jsxs(fe,{className:"p-4 rounded-2xl xl:sticky xl:top-4",children:[e.jsxs("div",{className:"flex items-center justify-between mb-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold",children:"Live preview"}),e.jsx(Fr,{value:A,onValueChange:ee=>E(ee),children:e.jsxs(Rr,{className:"h-8",children:[e.jsx(Zt,{value:"desktop",className:"h-6 px-2",children:e.jsx(mb,{className:"h-3.5 w-3.5"})}),e.jsx(Zt,{value:"mobile",className:"h-6 px-2",children:e.jsx(tg,{className:"h-3.5 w-3.5"})})]})})]}),e.jsx("div",{className:A==="mobile"?"max-w-[320px] mx-auto":"",children:e.jsx(TSt,{kit:w,items:d,owner:{display_name:((Y=r==null?void 0:r.user_metadata)==null?void 0:Y.full_name)||(r==null?void 0:r.email)||"You",avatar_url:((W=r==null?void 0:r.user_metadata)==null?void 0:W.avatar_url)??null,brokerage:null},mode:"preview"})})]})})]})]})}function Nun({kitId:s,agents:t,shares:n,onCreate:r,onRevoke:a,status:i}){const[l,o]=N.useState("general"),[c,d]=N.useState("");return i!=="published"?e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-3",children:"Publish this kit to generate share links."}):e.jsxs("div",{className:"mt-3 space-y-3",children:[e.jsxs("div",{className:"grid grid-cols-1 gap-2",children:[e.jsxs(us,{value:l,onValueChange:u=>o(u),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Choose agent"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"general",children:"General share link"}),t.map(u=>e.jsxs(Ze,{value:u.id,children:[u.first_name," ",u.last_name??""]},u.id))]})]}),e.jsx(Ms,{rows:2,placeholder:"Optional personal note shown on the page",value:c,onChange:u=>d(u.target.value)}),e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>{r({kit_id:s,agent_id:l==="general"?null:l,personal_note:c||null}),d("")},children:[e.jsx(Vl,{className:"h-4 w-4 mr-2"}),"Create share link"]})]}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-[12px] text-slate-500",children:"No active links yet."}),n.map(u=>{var f;const h=lSt(u.share_token),p=u.agent_id?((f=t.find(y=>y.id===u.agent_id))==null?void 0:f.first_name)??"Agent":"General";return e.jsxs("div",{className:"border rounded-lg p-2.5 text-[12.5px]",children:[e.jsxs("div",{className:"flex items-center justify-between gap-2",children:[e.jsx("span",{className:"font-medium",children:p}),e.jsx(Ue,{variant:"secondary",className:"capitalize",children:u.engagement_level.replace("_"," ")})]}),e.jsx("div",{className:"text-slate-500 truncate mt-1",children:h}),e.jsxs("div",{className:"flex gap-1 mt-2",children:[e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(h),ae.success("Link copied")},children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"}),"Copy"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:h,target:"_blank",rel:"noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"}),"Open"]})}),e.jsxs(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>a(u.id),children:[e.jsx(WP,{className:"h-3.5 w-3.5 mr-1"}),"Revoke"]})]})]},u.id)})]})]})}const kun={page_view:"Views",resource_open:"Resource opens",file_download:"Downloads",video_start:"Video starts",video_complete:"Video completes",external_link_click:"Link clicks",primary_cta_click:"CTA clicks",question_submitted:"Questions",meeting_requested:"Meetings requested"};function Sun(){const{kitId:s}=bi(),{data:t}=aSt(s),{shares:n}=iSt(s),{data:r=[]}=oSt(s),a=N.useMemo(()=>{const l=d=>r.filter(u=>u.event_type===d).length,o=new Set(n.filter(d=>d.agent_id).map(d=>d.agent_id)).size,c=n.filter(d=>d.first_opened_at).length;return{shares:n.length,uniqueAgents:o,viewRate:n.length?Math.round(c/n.length*100):0,engaged:n.filter(d=>["engaged","high_intent"].includes(d.engagement_level)).length,downloads:l("file_download"),ctaClicks:l("primary_cta_click"),questions:l("question_submitted"),meetings:l("meeting_requested")}},[n,r]),i=N.useMemo(()=>{const l=new Map;return r.forEach(o=>{const c=Ss(new Date(o.created_at),"MMM d");l.set(c,(l.get(c)??0)+1)}),Array.from(l.entries()).reverse().map(([o,c])=>({date:o,count:c}))},[r]);return e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Kit analytics",title:(t==null?void 0:t.title)??"Kit",description:"Which value is actually creating conversations.",actions:e.jsx(B,{variant:"outline",size:"sm",asChild:!0,className:"rounded-full",children:e.jsxs(In,{to:`/attract/provide/kits/${s}/edit`,children:[e.jsx(qr,{className:"h-4 w-4 mr-1"}),"Edit"]})})}),e.jsxs("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3 mb-6",children:[e.jsx(Ek,{label:"Shares",value:a.shares,icon:Sr,tone:"violet"}),e.jsx(Ek,{label:"Unique agents",value:a.uniqueAgents,icon:Sr,tone:"indigo"}),e.jsx(Ek,{label:"View rate",value:`${a.viewRate}%`,icon:Sr,tone:"teal"}),e.jsx(Ek,{label:"Engaged",value:a.engaged,icon:oc,tone:"emerald"}),e.jsx(Ek,{label:"Downloads",value:a.downloads,icon:Ia,tone:"orange"}),e.jsx(Ek,{label:"CTA clicks",value:a.ctaClicks,icon:oc,tone:"rose"}),e.jsx(Ek,{label:"Questions",value:a.questions,icon:Zl,tone:"violet"}),e.jsx(Ek,{label:"Meetings",value:a.meetings,icon:Xf,tone:"indigo"})]}),e.jsxs("div",{className:"grid grid-cols-1 xl:grid-cols-3 gap-6",children:[e.jsxs(fe,{className:"p-5 rounded-2xl xl:col-span-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Engagement over time"}),e.jsx("div",{className:"h-64",children:e.jsx(ww,{width:"100%",height:"100%",children:e.jsxs(VPe,{data:i,children:[e.jsx(UPe,{strokeDasharray:"3 3",stroke:"#eee"}),e.jsx(Rw,{dataKey:"date",fontSize:11}),e.jsx(Ow,{fontSize:11,allowDecimals:!1}),e.jsx(_p,{}),e.jsx(JM,{type:"monotone",dataKey:"count",stroke:"#7c3aed",strokeWidth:2})]})})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"By event type"}),e.jsx("div",{className:"space-y-2",children:Object.entries(kun).map(([l,o])=>{const c=r.filter(d=>d.event_type===l).length;return e.jsxs("div",{className:"flex justify-between text-[13px]",children:[e.jsx("span",{className:"text-slate-600",children:o}),e.jsx("span",{className:"font-semibold tabular-nums",children:c})]},l)})})]})]}),e.jsxs(fe,{className:"p-5 rounded-2xl mt-6",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Recipients"}),e.jsxs("div",{className:"space-y-2",children:[n.length===0&&e.jsx("div",{className:"text-sm text-slate-500",children:"No one has been shared this kit yet."}),n.map(l=>e.jsxs("div",{className:"flex items-center justify-between border-b py-2 text-[13px]",children:[e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:l.agent_id?"Personalized":"General link"}),e.jsxs("div",{className:"text-slate-500 text-[11.5px]",children:["Created ",Ss(new Date(l.created_at),"MMM d")," · ",l.open_count," opens",l.last_opened_at&&` · last opened ${Ss(new Date(l.last_opened_at),"MMM d")}`]})]}),e.jsx(Ue,{variant:"secondary",className:"capitalize",children:l.engagement_level.replace("_"," ")})]},l.id))]})]})]})}function Ek({label:s,value:t,icon:n,tone:r}){const a={violet:"text-violet-700 bg-violet-50",indigo:"text-indigo-700 bg-indigo-50",teal:"text-teal-700 bg-teal-50",emerald:"text-emerald-700 bg-emerald-50",orange:"text-orange-700 bg-orange-50",rose:"text-rose-700 bg-rose-50"};return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center ${a[r]}`,children:e.jsx(n,{className:"h-4 w-4"})}),e.jsx("div",{className:"mt-2 text-[22px] font-semibold tabular-nums",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function Cun(){const{data:s=[],isLoading:t}=ndn(),n=rdn(),r=Ln(),a=async i=>{try{const l=await n.mutateAsync(i);ae.success("Added to your drafts"),r(`/attract/provide/kits/${l}/edit`)}catch(l){ae.error(l.message??"Could not clone template")}};return e.jsxs("div",{children:[e.jsx(zu,{eyebrow:"Starter library",title:"LevelUp Starter Kits",description:"Ten proven relationship-first kits. Duplicate any of them into your workspace and personalize the parts that matter.",actions:e.jsx(B,{variant:"outline",asChild:!0,className:"rounded-full",children:e.jsxs(In,{to:"/attract/provide/kits",children:[e.jsx(qr,{className:"h-4 w-4 mr-2"}),"Back to my kits"]})})}),t&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading templates…"}),e.jsx("div",{className:"grid grid-cols-1 md:grid-cols-2 xl:grid-cols-3 gap-4",children:s.map(i=>{var l;return e.jsxs(fe,{className:"p-6 rounded-2xl border-slate-200 bg-white flex flex-col",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-700 font-semibold",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," Starter kit"]}),e.jsx("div",{className:"mt-2 text-[17px] font-semibold text-slate-900",children:i.title}),i.audience&&e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["For ",i.audience]}),e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:i.description}),e.jsxs("div",{className:"mt-3 flex flex-wrap gap-1",children:[i.pillar&&e.jsx(Ue,{variant:"outline",className:"capitalize",children:i.pillar}),(i.tags??[]).slice(0,4).map(o=>e.jsxs(Ue,{variant:"secondary",className:"text-[10.5px]",children:["#",o]},o))]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-3",children:[((l=i.suggested_items)==null?void 0:l.length)??0," suggested sections"]}),e.jsxs(B,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>a(i.id),children:[e.jsx(Im,{className:"h-4 w-4 mr-2"}),"Use this kit"]})]},i.id)})})]})}const yet={call:{icon:Cr,label:"Call"},text:{icon:Ai,label:"Text"},email:{icon:Gs,label:"Email"},dm:{icon:lr,label:"DM"},resource_share:{icon:qg,label:"Share a kit"},event_invitation:{icon:Lg,label:"Invite to event"},personal_check_in:{icon:NA,label:"Personal check-in"}},vet={urgent:"bg-rose-50 text-rose-700 ring-rose-200",high:"bg-orange-50 text-orange-700 ring-orange-200",medium:"bg-amber-50 text-amber-700 ring-amber-200",low:"bg-slate-50 text-slate-600 ring-slate-200"};function Tun(s){var t;return((t=Vkt.find(n=>n.key===s))==null?void 0:t.blurb)??""}function ESt(s){var t;return((t=Vkt.find(n=>n.key===s))==null?void 0:t.label)??s.replace(/_/g," ")}function BTe({rec:s,agentName:t,agentStage:n,kitTitle:r,eventTitle:a,compact:i,showAgentLink:l=!0,className:o}){const{update:c,dismiss:d,snooze:u,createFollowUp:h,logCompleted:p}=Gkt(),[f,y]=N.useState(!1),[_,v]=N.useState(s.draft_message??""),j=c.isPending||d.isPending||u.isPending||h.isPending||p.isPending,w=yet[s.channel]??yet.personal_check_in,S=s.suggested_due_at?new Date(s.suggested_due_at):null,A=S?S{c.mutate({id:s.id,patch:{draft_message:_}},{onSuccess:()=>{y(!1),ae.success("Opening message updated")}})},O=async()=>{try{await navigator.clipboard.writeText(s.draft_message??""),ae.success("Opening message copied — send it yourself from your phone or inbox")}catch{ae.error("Could not copy — select the text manually")}};return e.jsx(fe,{className:Mt("rounded-2xl border-slate-200/70 bg-white shadow-sm overflow-hidden",o),children:e.jsxs("div",{className:"p-4 sm:p-5",children:[e.jsxs("div",{className:"flex items-start gap-3 flex-wrap",children:[e.jsx("div",{className:"h-10 w-10 rounded-xl bg-gradient-to-br from-violet-500 to-indigo-600 text-white grid place-items-center shadow-sm flex-shrink-0",children:e.jsx(w.icon,{className:"h-4.5 w-4.5","aria-hidden":!0})}),e.jsxs("div",{className:"flex-1 min-w-[180px]",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx(Ue,{variant:"outline",className:Mt("rounded-full text-[10.5px] uppercase tracking-wider font-semibold ring-1 border-transparent",vet[s.priority]??vet.medium),children:s.priority}),e.jsx("span",{className:"text-[11px] text-violet-700 font-medium",children:ESt(s.signal_group)}),s.is_demo&&e.jsx(Ue,{variant:"outline",className:"rounded-full text-[10px] bg-slate-100 text-slate-500 border-transparent",children:"Demo data"})]}),e.jsx("h3",{className:"text-[15px] font-semibold text-slate-900 mt-1.5 leading-snug",children:s.title}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-1 flex items-center gap-2 flex-wrap",children:[l?e.jsxs(In,{to:`/attract/agents/${s.agent_id}`,className:"font-medium text-slate-700 hover:text-violet-700 inline-flex items-center gap-0.5",children:[t," ",e.jsx(ga,{className:"h-3 w-3"})]}):e.jsx("span",{className:"font-medium text-slate-700",children:t}),n&&e.jsxs("span",{className:"capitalize",children:["· ",n.replace(/_/g," ")]}),e.jsxs("span",{children:["· ",w.label]}),S&&e.jsxs("span",{className:Mt("inline-flex items-center gap-1",A?"text-rose-600 font-medium":""),children:["· ",e.jsx(pr,{className:"h-3 w-3"})," ",A?"Due now":`Do by ${S.toLocaleDateString()}`]})]})]}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full","aria-label":"More recommendation actions",children:e.jsx(Ag,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",className:"w-56",children:[e.jsx(cM,{children:"Recommendation"}),e.jsx(Kg,{}),e.jsxs(Kr,{onClick:()=>y(D=>!D),children:[e.jsx(ya,{className:"h-4 w-4 mr-2"})," Edit opening message"]}),e.jsxs(Kr,{onClick:O,children:[e.jsx(Zr,{className:"h-4 w-4 mr-2"})," Copy message"]}),e.jsx(Kg,{}),e.jsxs(Kr,{onClick:()=>u.mutate({id:s.id,days:3}),children:[e.jsx(pr,{className:"h-4 w-4 mr-2"})," Snooze 3 days"]}),e.jsxs(Kr,{onClick:()=>u.mutate({id:s.id,days:7}),children:[e.jsx(pr,{className:"h-4 w-4 mr-2"})," Snooze 1 week"]}),e.jsxs(Kr,{className:"text-rose-600",onClick:()=>d.mutate(s.id),children:[e.jsx($n,{className:"h-4 w-4 mr-2"})," Dismiss"]})]})]})]}),!!(s.reasons??[]).length&&e.jsxs("div",{className:"mt-3 rounded-xl bg-slate-50 p-3",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:[e.jsx(fw,{className:"h-3 w-3"})," Why this, right now"]}),e.jsx("ul",{className:"space-y-1",children:s.reasons.map((D,I)=>e.jsxs("li",{className:"text-[12.5px] text-slate-700 flex gap-2",children:[e.jsx("span",{className:"text-violet-500",children:"•"}),e.jsx("span",{children:D})]},I))}),e.jsx("div",{className:"text-[11px] text-slate-400 mt-2",children:Tun(s.signal_group)})]}),!i&&e.jsxs("div",{className:"mt-3",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-slate-500 mb-1.5",children:"Suggested opening"}),f?e.jsxs("div",{className:"space-y-2",children:[e.jsx(Ms,{value:_,onChange:D=>v(D.target.value),rows:4,className:"text-[13.5px]","aria-label":"Opening message"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:E,disabled:j,children:"Save message"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:()=>{v(s.draft_message??""),y(!1)},children:"Cancel"})]})]}):e.jsxs("button",{onClick:()=>y(!0),className:"w-full text-left rounded-xl border border-slate-200 bg-white p-3 text-[13.5px] leading-relaxed text-slate-700 hover:border-violet-300 transition-colors",children:[s.draft_message||"No draft message yet — click to write one.",e.jsx("span",{className:"block text-[11px] text-violet-600 mt-1.5",children:"Click to edit before you send"})]})]}),(r||a)&&e.jsxs("div",{className:"mt-3 flex flex-wrap gap-2 text-[11.5px]",children:[r&&e.jsxs("span",{className:"rounded-full bg-teal-50 text-teal-700 px-2.5 py-1",children:["Suggested kit: ",r]}),a&&e.jsxs("span",{className:"rounded-full bg-indigo-50 text-indigo-700 px-2.5 py-1",children:["Suggested event: ",a]})]}),e.jsxs("div",{className:"mt-4 flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",disabled:j,onClick:()=>p.mutate({rec:s}),children:[e.jsx(Lr,{className:"h-3.5 w-3.5 mr-1.5"})," I did this"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:j,onClick:()=>h.mutate(s),children:[e.jsx(Lg,{className:"h-3.5 w-3.5 mr-1.5"})," ",s.follow_up_id?"Follow-up created":"Create follow-up"]}),e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full",onClick:O,children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1.5"})," Copy message"]})]}),e.jsx("div",{className:"text-[10.5px] text-slate-400 mt-2",children:"Attract never sends messages for you — copy the opening and send it from your own phone or inbox."})]})})}function Eun({label:s="Nothing needs attention right now."}){return e.jsxs(fe,{className:"rounded-2xl border-dashed border-slate-300 bg-white/60 p-8 text-center",children:[e.jsx("div",{className:"h-11 w-11 rounded-2xl bg-emerald-50 text-emerald-600 grid place-items-center mx-auto mb-3",children:e.jsx(Lr,{className:"h-5 w-5"})}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:s}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Log a conversation, share a resource kit, or invite someone to an event and new opportunities will appear here."})]})}const Aun=q,Mun=["new_connection","building_relationship","engaging_with_value","active_conversation","exploring_options","brokerage_presentation","decision_pending","joined","long_term_relationship","not_right_now","not_a_fit"],Iun={hot:Hc,warm:pb,cold:Tv},HF=({label:s})=>e.jsxs("span",{className:"text-slate-400 italic",children:["Not recorded",s?` — add ${s}`:""]}),Ak=s=>[s.first_name,s.last_name].filter(Boolean).join(" "),Pun=s=>{var t,n;return`${((t=s.first_name)==null?void 0:t[0])??""}${((n=s.last_name)==null?void 0:n[0])??""}`.toUpperCase()||"?"};function KI({label:s,children:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider text-slate-400 font-semibold",children:s}),e.jsx("div",{className:"text-[13.5px] text-slate-800 mt-0.5 break-words",children:t})]})}const Lun={touch:"bg-violet-500",note:"bg-slate-400",stage_change:"bg-indigo-500",follow_up_created:"bg-amber-400",follow_up_completed:"bg-emerald-500",follow_up_missed:"bg-rose-500",kit_shared:"bg-teal-500",kit_engagement:"bg-teal-400",event_invited:"bg-indigo-300",event_registered:"bg-indigo-400",event_attended:"bg-emerald-500",event_no_show:"bg-rose-400",event_note:"bg-slate-400",score:"bg-green-500",temperature:"bg-orange-400",activity:"bg-slate-300"};function Dun(){const{agentId:s}=bi(),t=Ln(),{item:n,timeline:r,valueShared:a,nextKit:i,isLoading:l,error:o,refetch:c}=pcn(s),{data:d=[]}=$8e(),{upsertAgent:u,moveStage:h}=i0(),{followUps:p,complete:f}=UU(),y=fcn(),{gmailEmail:_}=Dh(),[v,j]=N.useState("all"),[w,S]=N.useState(!1),[A,E]=N.useState(!1),[O,D]=N.useState("call"),[I,F]=N.useState(""),[z,H]=N.useState(""),[Z,Y]=N.useState(!1),[W,ee]=N.useState(""),[se,oe]=N.useState(!1),[he,ce]=N.useState(""),[me,le]=N.useState(new Date(Date.now()+3*864e5).toISOString().slice(0,10)),[ve,ge]=N.useState(null),[Te,Ie]=N.useState(!1),Ce=N.useMemo(()=>d.filter(je=>je.agent_id===s&&je.status==="open").sort((je,He)=>He.rank_score-je.rank_score),[d,s]),Me=N.useMemo(()=>p.filter(je=>je.agent_id===s),[p,s]),Pe=N.useMemo(()=>{const je=XJe.find(He=>He.key===v);return!je||!je.kinds.length?r:r.filter(He=>je.kinds.includes(He.kind))},[r,v]);if(l)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-40"}),e.jsx(Ws,{className:"h-40 w-full rounded-2xl"}),e.jsx(Ws,{className:"h-64 w-full rounded-2xl"})]});if(o)return e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load this relationship."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:o.message}),e.jsxs(B,{className:"rounded-full mt-4",onClick:()=>c(),children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"})," Try again"]})]});if(!n)return e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Agent not found"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"This relationship may have been removed from your pipeline."}),e.jsx(B,{className:"rounded-full mt-4",onClick:()=>t("/attract/pipeline"),children:"Back to pipeline"})]});const Re=n.agent,Ae=n.signals,Be=Iun[Re.temperature??""]??pb,we=()=>{y.mutate({agent_id:Re.id,activity_type:O,title:I||`${O.replace(/_/g," ")} with ${Ak(Re)}`,description:z||void 0},{onSuccess:()=>{S(!1),F(""),H("")}})},Je=async()=>{var He;if(!W.trim())return;const je=[(He=Re.notes)==null?void 0:He.trim(),`[${new Date().toLocaleDateString()}] ${W.trim()}`].filter(Boolean).join(` `);u.mutate({id:Re.id,first_name:Re.first_name,notes:je},{onSuccess:()=>{Y(!1),ee(""),c()}}),y.mutate({agent_id:Re.id,activity_type:"note",title:"Note added",description:W.trim()})},ke=async()=>{if(!he.trim()){ae.error("Give the follow-up a title");return}if(Me.find(Ke=>!Ke.completed_at&&Ke.title.trim().toLowerCase()===he.trim().toLowerCase())){ae.error("An open follow-up with that title already exists");return}const{data:He}=await q.auth.getUser(),{error:$e}=await Aun.from("attract_follow_ups").insert({user_id:He.user.id,agent_id:Re.id,title:he.trim(),due_at:new Date(`${me}T12:00:00`).toISOString(),touch_type:"call",priority:"medium"});if($e){ae.error($e.message);return}ae.success("Follow-up created"),oe(!1),ce(""),c()},it=()=>{ve&&(window.open(ve.href,"_self"),y.mutate({agent_id:Re.id,activity_type:ve.kind,title:`${ve.kind==="call"?"Called":ve.kind==="text"?"Texted":"Emailed"} ${Ak(Re)}`}),ge(null))};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center gap-1.5 text-[12px] text-slate-500",children:[e.jsx(In,{to:"/attract",className:"hover:text-violet-700",children:"Attract"}),e.jsx(ga,{className:"h-3 w-3"}),e.jsx(In,{to:"/attract/pipeline",className:"hover:text-violet-700",children:"Pipeline"}),e.jsx(ga,{className:"h-3 w-3"}),e.jsx("span",{className:"text-slate-800 font-medium truncate",children:Ak(Re)})]}),e.jsxs(fe,{className:"rounded-2xl border-slate-200/70 overflow-hidden",children:[e.jsxs("div",{className:"bg-gradient-to-r from-[#0B0F1E] via-[#141a33] to-[#1d1b4b] p-5 sm:p-6 text-white",children:[e.jsxs(B,{variant:"ghost",size:"sm",className:"text-slate-300 hover:text-white -ml-2 mb-3 rounded-full",onClick:()=>t(-1),children:[e.jsx(qr,{className:"h-3.5 w-3.5 mr-1.5"})," Back"]}),e.jsxs("div",{className:"flex items-start gap-4 flex-wrap",children:[Re.photo_url?e.jsx("img",{src:Re.photo_url,alt:`${Ak(Re)} headshot`,className:"h-16 w-16 rounded-2xl object-cover ring-2 ring-white/20"}):e.jsx("div",{className:"h-16 w-16 rounded-2xl bg-gradient-to-br from-violet-500 to-indigo-600 grid place-items-center text-xl font-semibold ring-2 ring-white/10",children:Pun(Re)}),e.jsxs("div",{className:"flex-1 min-w-[220px]",children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:Ak(Re)}),e.jsxs("div",{className:"text-[13px] text-slate-300 mt-1 flex flex-wrap items-center gap-x-2 gap-y-1",children:[e.jsx("span",{children:Re.brokerage||"Brokerage not recorded"}),e.jsx("span",{className:"opacity-40",children:"·"}),e.jsx("span",{children:[Re.city,Re.state].filter(Boolean).join(", ")||"Market not recorded"}),Re.is_demo&&e.jsx(Ue,{className:"bg-amber-400/20 text-amber-200 border-transparent rounded-full",children:"Demo record"})]}),e.jsxs("div",{className:"flex flex-wrap gap-2 mt-3",children:[e.jsx(Ue,{className:"rounded-full bg-white/10 text-white border-transparent capitalize",children:Re.stage.replace(/_/g," ")}),e.jsxs(Ue,{className:"rounded-full bg-white/10 text-white border-transparent capitalize inline-flex items-center gap-1",children:[e.jsx(Be,{className:"h-3 w-3"})," ",Re.temperature??"temperature unset"]}),e.jsx(q8e,{score:n.score,className:"bg-white/10 text-white ring-white/20"}),(Re.tags??[]).map(je=>e.jsx(Ue,{variant:"outline",className:"rounded-full bg-transparent text-slate-200 border-white/20",children:je},je))]})]}),e.jsxs("div",{className:"text-[12px] text-slate-300 space-y-1 min-w-[190px]",children:[e.jsx("div",{children:Re.email?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`mailto:${Re.email}`,children:Re.email}):"No email on file"}),e.jsx("div",{children:Re.phone?e.jsx("a",{className:"hover:text-white underline decoration-white/30",href:`tel:${Re.phone}`,children:Re.phone}):"No phone on file"}),e.jsxs("div",{children:["Last meaningful touch: ",Ae.lastTouchAt?`${new Date(Ae.lastTouchAt).toLocaleDateString()} (${Ae.daysSinceTouch}d ago)`:"never logged"]}),e.jsxs("div",{children:["Next follow-up: ",Re.next_follow_up_at?new Date(Re.next_follow_up_at).toLocaleDateString():"none scheduled"]}),e.jsxs("div",{children:["Source: ",Re.source||"not recorded"," · Owner: ",Re.relationship_owner||"you"]})]})]})]}),e.jsxs("div",{className:"p-3 sm:p-4 bg-white flex flex-wrap gap-2",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>E(!0),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-1.5"})," Edit contact"]}),e.jsxs(_s,{open:w,onOpenChange:S,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1.5"})," Log touch"]})}),e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Log a conversation"}),e.jsx(Jn,{children:"This records what already happened — it does not send anything."})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Type"}),e.jsxs(us,{value:O,onValueChange:D,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:["call","text","email","dm","meeting","note"].map(je=>e.jsx(Ze,{value:je,className:"capitalize",children:je},je))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Title"}),e.jsx(ye,{value:I,onChange:je=>F(je.target.value),placeholder:`Call with ${Re.first_name}`})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"What happened"}),e.jsx(Ms,{rows:4,value:z,onChange:je=>H(je.target.value)})]})]}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:we,disabled:y.isPending,children:"Log it"})})]})]}),e.jsxs(_s,{open:Z,onOpenChange:Y,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(v9,{className:"h-3.5 w-3.5 mr-1.5"})," Add note"]})}),e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Add a relationship note"})}),e.jsx(Ms,{rows:5,value:W,onChange:je=>ee(je.target.value),placeholder:"What did you learn about them?"}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:Je,children:"Save note"})})]})]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Re.phone,onClick:()=>Re.phone&&ge({kind:"call",href:`tel:${Re.phone}`}),children:[e.jsx(Cr,{className:"h-3.5 w-3.5 mr-1.5"})," Call"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Re.phone,onClick:()=>Re.phone&&ge({kind:"text",href:`sms:${Re.phone}`}),children:[e.jsx(Ai,{className:"h-3.5 w-3.5 mr-1.5"})," Text"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",disabled:!Re.email,onClick:()=>Re.email&&Ie(!0),children:[e.jsx(Gs,{className:"h-3.5 w-3.5 mr-1.5"})," Email"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(In,{to:"/attract/provide/kits",children:[e.jsx(qg,{className:"h-3.5 w-3.5 mr-1.5"})," Share kit"]})}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(In,{to:"/attract/events",children:[e.jsx(Lg,{className:"h-3.5 w-3.5 mr-1.5"})," Invite to event"]})}),e.jsxs(_s,{open:se,onOpenChange:oe,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",children:[e.jsx(pr,{className:"h-3.5 w-3.5 mr-1.5"})," Create follow-up"]})}),e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Create a follow-up"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"What will you do?"}),e.jsx(ye,{value:he,onChange:je=>ce(je.target.value),placeholder:"Call about their Q3 goals"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Due"}),e.jsx(ye,{type:"date",value:me,onChange:je=>le(je.target.value)})]})]}),e.jsx(Xn,{children:e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:ke,children:"Create"})})]})]}),e.jsxs(us,{value:Re.stage,onValueChange:je=>h.mutate({id:Re.id,to_stage:je,from_stage:Re.stage}),children:[e.jsxs(ls,{className:"w-[210px] h-9 rounded-full text-[13px]","aria-label":"Change stage",children:[e.jsx(lw,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(hs,{})]}),e.jsx(cs,{children:Mun.map(je=>e.jsx(Ze,{value:je,className:"capitalize",children:je.replace(/_/g," ")},je))})]})]})]}),e.jsx(_s,{open:!!ve,onOpenChange:je=>!je&&ge(null),children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsxs(ws,{children:["Open your ",(ve==null?void 0:ve.kind)==="email"?"email app":(ve==null?void 0:ve.kind)==="text"?"messaging app":"phone app","?"]}),e.jsx(Jn,{children:"Attract will open your own device app so you send it personally. Nothing is sent by LevelUp. We'll log this as a touch."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>ge(null),children:"Cancel"}),e.jsx(B,{className:"rounded-full btn-primary text-white",onClick:it,children:"Continue"})]})]})}),e.jsxs(Fr,{defaultValue:"overview",children:[e.jsx(Rr,{className:"rounded-full bg-white border border-slate-200 p-1 flex-wrap h-auto",children:["overview","timeline","value","events","followups","notes"].map(je=>e.jsx(Zt,{value:je,className:"rounded-full text-[13px] capitalize data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:je==="value"?"Value shared":je==="followups"?"Follow-ups":je==="notes"?"Notes & insights":je},je))}),e.jsxs(is,{value:"overview",className:"mt-5 space-y-5",children:[e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-3 gap-5",children:[e.jsxs("div",{className:"lg:col-span-2 space-y-5",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Next best relationship touch"}),Ce[0]?e.jsx(BTe,{rec:Ce[0],agentName:Ak(Re),agentStage:Re.stage,showAgentLink:!1,className:"border-0 shadow-none"}):e.jsx("div",{className:"text-[13.5px] text-slate-500",children:"No open recommendation right now. Recommendations appear when real signals exist — a kit opened, an event attended, an overdue commitment, or silence beyond your cadence."})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"What we actually know"}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-4",children:[e.jsx(KI,{label:"Goals",children:Re.goals||e.jsx(HF,{label:"their goals"})}),e.jsx(KI,{label:"Challenges",children:Re.challenges||e.jsx(HF,{label:"their challenges"})}),e.jsx(KI,{label:"Interests",children:Re.interests||e.jsx(HF,{label:"interests"})}),e.jsx(KI,{label:"Production context",children:Re.production_context||e.jsx(HF,{label:"production context"})}),e.jsx(KI,{label:"Primary pillar",children:Re.primary_pillar?e.jsx("span",{className:"capitalize",children:Re.primary_pillar}):e.jsx(HF,{label:"a pillar"})}),e.jsx(KI,{label:"Added to pipeline",children:new Date(Re.created_at).toLocaleDateString()})]})]}),e.jsx("div",{className:"grid sm:grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Touches (90d)",value:Ae.touches90},{label:"Kits shared",value:Ae.shares.length},{label:"Kit opens",value:Ae.totalKitOpens},{label:"Events attended",value:Ae.attended}].map(je=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:je.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:je.label})]},je.label))})]}),e.jsxs(fe,{className:"p-5 rounded-2xl h-fit",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-3",children:"Relationship health"}),e.jsx(Wkt,{score:n.score})]})]}),Ce.length>1&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Other open recommendations"}),Ce.slice(1).map(je=>e.jsx(BTe,{rec:je,agentName:Ak(Re),showAgentLink:!1,compact:!0},je.id))]})]}),e.jsx(is,{value:"timeline",className:"mt-5",children:e.jsxs(fe,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap mb-4",children:[e.jsx("div",{className:"flex gap-1.5 flex-wrap",children:XJe.map(je=>e.jsx("button",{onClick:()=>j(je.key),className:Mt("rounded-full px-3 py-1.5 text-[12px] font-medium transition-colors",v===je.key?"bg-violet-600 text-white":"bg-slate-100 text-slate-600 hover:bg-slate-200"),children:je.label},je.key))}),e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>S(!0),children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1.5"})," Log something"]})]}),Pe.length?e.jsxs("ol",{className:"relative pl-5 sm:pl-6",children:[e.jsx("span",{"aria-hidden":!0,className:"absolute left-1.5 top-1 bottom-1 w-px bg-slate-200"}),Pe.map(je=>e.jsxs("li",{className:"relative pb-5",children:[e.jsx("span",{"aria-hidden":!0,className:Mt("absolute -left-[15px] sm:-left-[18px] top-1.5 h-2.5 w-2.5 rounded-full ring-2 ring-white",Lun[je.kind]??"bg-slate-300")}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:je.title}),je.detail&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5 whitespace-pre-wrap",children:je.detail}),e.jsxs("div",{className:"text-[11px] text-slate-400 mt-1",children:[new Date(je.at).toLocaleString()," · ",e.jsx("span",{className:"capitalize",children:je.kind.replace(/_/g," ")})]})]},je.id))]}):e.jsx("div",{className:"py-10 text-center text-[13.5px] text-slate-500",children:"Nothing in this view yet. Log a conversation to start the history."})]})}),e.jsxs(is,{value:"value",className:"mt-5 space-y-4",children:[i&&e.jsxs(fe,{className:"p-4 rounded-2xl bg-gradient-to-r from-teal-50 to-emerald-50 border-teal-100",children:[e.jsx("div",{className:"text-[10.5px] uppercase tracking-wider font-semibold text-teal-700",children:"Suggested next kit"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mt-1",children:i.kit.title}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:i.why}),e.jsx(B,{size:"sm",className:"rounded-full mt-3 btn-primary text-white",asChild:!0,children:e.jsx(In,{to:"/attract/provide/kits",children:"Open Resource Kits"})})]}),a.length?a.map(je=>e.jsxs(fe,{className:"p-4 sm:p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900",children:je.kitTitle}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:["Sent ",new Date(je.share.created_at).toLocaleDateString()," ·",je.firstViewedAt?` first viewed ${new Date(je.firstViewedAt).toLocaleDateString()}`:" never viewed",je.lastViewedAt?` · last viewed ${new Date(je.lastViewedAt).toLocaleDateString()}`:""]})]}),e.jsx(Ue,{variant:"outline",className:Mt("rounded-full border-transparent ring-1",je.classification==="High Intent"?"bg-rose-50 text-rose-700 ring-rose-200":je.classification==="Engaged"?"bg-teal-50 text-teal-700 ring-teal-200":je.classification==="Viewed"?"bg-amber-50 text-amber-700 ring-amber-200":"bg-slate-50 text-slate-600 ring-slate-200"),children:je.classification})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-5 gap-3 mt-4",children:[["Visits",je.visits],["Downloads",je.downloads],["Link clicks",je.ctaClicks],["Questions",je.questions],["Meeting asks",je.meetingRequests]].map(([He,$e])=>e.jsxs("div",{className:"rounded-xl bg-slate-50 p-2.5",children:[e.jsx("div",{className:"text-[17px] font-semibold tabular-nums text-slate-900",children:$e}),e.jsx("div",{className:"text-[10.5px] text-slate-500",children:He})]},He))}),e.jsxs("div",{className:"mt-3 text-[12.5px] text-slate-600 space-y-1",children:[e.jsxs("div",{children:["Link status: ",e.jsx("span",{className:"capitalize font-medium",children:je.share.status})]}),e.jsxs("div",{children:["Follow-up after sharing: ",je.followUp?`${je.followUp.title}${je.followUp.completed_at?" (completed)":" (open)"}`:"none created"]}),e.jsxs("div",{children:["Stage movement after sharing: ",je.stageAdvancedAfter?`moved to ${je.stageAdvancedAfter.to_stage.replace(/_/g," ")} on ${new Date(je.stageAdvancedAfter.created_at).toLocaleDateString()}`:"no stage movement yet"]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full mt-3",asChild:!0,children:e.jsxs("a",{href:je.shareUrl,target:"_blank",rel:"noreferrer",children:["Open share link ",e.jsx(tr,{className:"h-3.5 w-3.5 ml-1.5"})]})})]},je.share.id)):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Nothing shared yet"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Value first is how this whole system works. Share a Resource Kit to begin."})]})]}),e.jsx(is,{value:"events",className:"mt-5 space-y-3",children:Ae.attendees.length?Ae.attendees.map(je=>e.jsx(fe,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-center justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(In,{to:`/attract/events/${je.event_id}`,className:"text-[14.5px] font-semibold text-slate-900 hover:text-violet-700",children:"View event"}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[je.invited_at&&`Invited ${new Date(je.invited_at).toLocaleDateString()} · `,je.registered_at?`Registered ${new Date(je.registered_at).toLocaleDateString()}`:"Not registered",je.checked_in_at&&` · Attended ${new Date(je.checked_in_at).toLocaleDateString()}`,je.no_show_at&&" · No-show"]})]}),e.jsx(Ue,{variant:"outline",className:"rounded-full capitalize",children:je.followup_status?`follow-up ${je.followup_status}`:je.status??"invited"})]})},je.id)):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(q0,{className:"h-6 w-6 mx-auto text-slate-400 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"Never invited to an event"}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:"Events are the fastest way to deepen a relationship."}),e.jsx(B,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",asChild:!0,children:e.jsx(In,{to:"/attract/events",children:"See your events"})})]})}),e.jsx(is,{value:"followups",className:"mt-5 space-y-3",children:Me.length?Me.map(je=>{const He=!je.completed_at&&je.due_at&&new Date(je.due_at)f.mutate(je.id),children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1.5"})," Complete"]})]},je.id)}):e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No follow-ups yet"}),e.jsx(B,{size:"sm",className:"rounded-full mt-4 btn-primary text-white",onClick:()=>oe(!0),children:"Create one"})]})}),e.jsxs(is,{value:"notes",className:"mt-5 space-y-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-center justify-between mb-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500",children:"Your notes"}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>Y(!0),children:"Add note"})]}),Re.notes?e.jsx("div",{className:"text-[13.5px] text-slate-700 whitespace-pre-wrap",children:Re.notes}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No notes recorded yet."})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:"What the data says"}),e.jsx("ul",{className:"text-[13px] text-slate-700 space-y-1.5 list-disc pl-4",children:[...n.score.positives.map(je=>`Strength: ${je}`),...n.score.negatives.map(je=>`Risk: ${je}`),...n.score.improvements.map(je=>`Next: ${je}`)].map((je,He)=>e.jsx("li",{children:je},He))})]})]})]}),e.jsx(nSt,{agent:Re,open:A,onOpenChange:E,onDeleted:()=>t("/attract/pipeline")}),Re.email&&e.jsx(Xv,{open:Te,onOpenChange:Ie,contact:{id:Re.id,first_name:Re.preferred_name||Re.first_name,last_name:Re.last_name||"",email:Re.email},gmailEmail:_,sendSource:"attract",logTouchpoint:!1,onSendComplete:()=>{y.mutate({agent_id:Re.id,activity_type:"email",title:`Emailed ${Ak(Re)}`})}})]})}const Run=[{key:"all",label:"Everything"},{key:"high_intent",label:"High intent"},{key:"resource_follow_up",label:"Value shared"},{key:"event_follow_up",label:"Events"},{key:"commitment",label:"Commitments"},{key:"silence",label:"Going quiet"},{key:"stage",label:"Stage momentum"},{key:"new_relationship",label:"New connections"}];function Oun(){const{intel:s,byId:t,isLoading:n,error:r,refetch:a}=o6(),{data:i=[],isLoading:l}=$8e(),o=U8e();Kkt();const[c,d]=N.useState(""),[u,h]=N.useState("all"),[p,f]=N.useState("open"),y=j=>{var S;const w=(S=t.get(j))==null?void 0:S.agent;return w?[w.first_name,w.last_name].filter(Boolean).join(" "):"Unknown agent"},_=N.useMemo(()=>{const j=Date.now();return i.filter(w=>p==="open"?w.status==="open"||w.status==="snoozed"&&w.snoozed_until&&+new Date(w.snoozed_until)<=j:p==="snoozed"?w.status==="snoozed":p==="done"?w.status==="completed":p==="dismissed"?w.status==="dismissed":!0).filter(w=>u==="all"||w.signal_group===u).filter(w=>{if(!c.trim())return!0;const S=c.toLowerCase();return y(w.agent_id).toLowerCase().includes(S)||w.title.toLowerCase().includes(S)||(w.reasons??[]).join(" ").toLowerCase().includes(S)}).sort((w,S)=>S.rank_score-w.rank_score)},[i,p,u,c,t]),v=N.useMemo(()=>{const j=i.filter(w=>w.status==="open");return{open:j.length,urgent:j.filter(w=>w.priority==="urgent").length,highIntent:j.filter(w=>w.signal_group==="high_intent").length,overdue:j.filter(w=>w.suggested_due_at&&+new Date(w.suggested_due_at)e.jsx(Ws,{className:"h-28 w-full rounded-2xl"},j))}):r?e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"We couldn't load your opportunities."}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-1",children:r.message}),e.jsxs(B,{className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(Ei,{className:"h-4 w-4 mr-2"})," Try again"]})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Who needs attention"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-2xl",children:"Ranked by real signals only — value they engaged with, events they attended, commitments you made, and silence past your cadence. Nothing here is invented."})]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>o.mutate(s),disabled:o.isPending,children:[e.jsx(Ei,{className:Mt("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Recalculate"]})]}),e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[{label:"Open recommendations",value:v.open},{label:"Urgent",value:v.urgent},{label:"High intent signals",value:v.highIntent},{label:"Past suggested date",value:v.overdue}].map(j=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:j.value}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:j.label})]},j.label))}),e.jsxs(fe,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsxs("div",{className:"relative flex-1 min-w-[220px]",children:[e.jsx(gr,{className:"h-4 w-4 absolute left-3 top-1/2 -translate-y-1/2 text-slate-400"}),e.jsx(ye,{value:c,onChange:j=>d(j.target.value),placeholder:"Search agents or reasons",className:"pl-9 rounded-full h-9","aria-label":"Search recommendations"})]}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsxs(ls,{className:"w-[190px] h-9 rounded-full text-[13px]",children:[e.jsx(Lv,{className:"h-3.5 w-3.5 mr-1.5 opacity-60"}),e.jsx(hs,{})]}),e.jsx(cs,{children:Run.map(j=>e.jsx(Ze,{value:j.key,children:j.label},j.key))})]}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(ls,{className:"w-[150px] h-9 rounded-full text-[13px]",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"open",children:"Needs action"}),e.jsx(Ze,{value:"snoozed",children:"Snoozed"}),e.jsx(Ze,{value:"done",children:"Completed"}),e.jsx(Ze,{value:"dismissed",children:"Dismissed"}),e.jsx(Ze,{value:"all",children:"All"})]})]})]}),_.length?e.jsx("div",{className:"space-y-3",children:_.map(j=>{var w;return e.jsx(BTe,{rec:j,agentName:y(j.agent_id),agentStage:(w=t.get(j.agent_id))==null?void 0:w.agent.stage},j.id)})}):i.length?e.jsx(Eun,{label:"Nothing matches this view. Try switching the filter."}):e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(un,{className:"h-6 w-6 mx-auto text-violet-500 mb-2"}),e.jsx("div",{className:"text-[15px] font-semibold text-slate-800",children:"No recommendations yet"}),e.jsx("p",{className:"text-[13px] text-slate-500 mt-1 max-w-md mx-auto",children:"Attract only recommends what it can prove. Add agents to your pipeline, share a Resource Kit, or invite someone to an event — real signals will show up here."}),e.jsxs("div",{className:"flex gap-2 justify-center mt-4",children:[e.jsx(B,{className:"rounded-full btn-primary text-white",asChild:!0,children:e.jsx(In,{to:"/attract/pipeline",children:"Open pipeline"})}),e.jsx(B,{variant:"outline",className:"rounded-full",asChild:!0,children:e.jsx(In,{to:"/attract/provide/kits",children:"Share a kit"})})]})]}),!!_.length&&e.jsxs("div",{className:"text-[11.5px] text-slate-400",children:["Showing ",_.length," of ",i.length," tracked recommendations · grouped signals: ",[...new Set(_.map(j=>ESt(j.signal_group)))].join(", ")]})]})}const fke=s=>[s.first_name,s.last_name].filter(Boolean).join(" ");function Fun(s=new Date){const t=new Date(s),n=t.getDay(),r=n===0?-6:1-n;return t.setDate(t.getDate()+r),t.setHours(0,0,0,0),t}function ASt(s,t,n=new Date){const r=Fun(n),a=new Date(r.getTime()+6*864e5),i=new Date(n.getTime()-7*864e5),c=s.filter(I=>I.primary).slice().sort((I,F)=>F.primary.rank_score-I.primary.rank_score||I.score.score-F.score.score).slice(0,5).map((I,F)=>({agent_id:I.agent.id,agent_name:fke(I.agent),rank:F+1,reason:I.primary.reasons.join(" · "),channel:I.primary.channel,draft_message:I.primary.draft_message,score:I.score.score,stage:I.agent.stage})),d=I=>s.map(F=>{const z=I(F);return z?{agent_id:F.agent.id,agent_name:fke(F.agent),detail:z}:null}).filter(Boolean).slice(0,8),u=d(I=>I.signals.meetingRequests>0||I.signals.questions>0||I.signals.highIntentShares.some(F=>F.engagement_level==="high_intent")?`${I.signals.meetingRequests} meeting request(s), ${I.signals.questions} question(s), ${I.signals.totalKitOpens} kit open(s)`:null),h=d(I=>I.recommendations.some(F=>F.rec_key==="renewed_interest")?"Came back to a kit you shared after going quiet":null),p=d(I=>I.signals.overdueFollowUps.length?`${I.signals.overdueFollowUps.length} overdue follow-up(s) — oldest: ${I.signals.overdueFollowUps[0].title}`:null),f=d(I=>I.signals.daysSinceTouch!==null&&I.signals.daysSinceTouch>60?`${I.signals.daysSinceTouch} days since a real conversation`:null),y=t.shares.filter(I=>new Date(I.created_at)>=i),_={shares:y.length,opened:t.shares.filter(I=>I.first_opened_at&&new Date(I.first_opened_at)>=i).length,engaged:t.shares.filter(I=>I.engagement_level==="engaged").length,high_intent:t.shares.filter(I=>I.engagement_level==="high_intent").length,downloads:t.kitEvents.filter(I=>I.event_type==="file_download"&&new Date(I.created_at)>=i).length,questions:t.kitEvents.filter(I=>I.event_type==="question_submitted"&&new Date(I.created_at)>=i).length},v={invited:t.attendees.filter(I=>I.invited_at&&new Date(I.invited_at)>=i).length,registered:t.attendees.filter(I=>I.registered_at&&new Date(I.registered_at)>=i).length,attended:t.attendees.filter(I=>I.checked_in_at&&new Date(I.checked_in_at)>=i).length,no_shows:t.attendees.filter(I=>I.no_show_at&&new Date(I.no_show_at)>=i).length,follow_ups_pending:t.attendees.filter(I=>I.checked_in_at&&I.followup_status!=="done").length,upcoming:t.events.filter(I=>I.starts_at&&new Date(I.starts_at)>n&&I.status==="published").sort((I,F)=>+new Date(I.starts_at)-+new Date(F.starts_at)).slice(0,3).map(I=>({title:I.title,starts_at:I.starts_at??null}))},j=[...s.filter(I=>I.agent.next_follow_up_at&&new Date(I.agent.next_follow_up_at)>n&&Cm(n,I.agent.next_follow_up_at)<=7).slice(0,5).map(I=>({label:fke(I.agent),detail:`Follow-up scheduled ${new Date(I.agent.next_follow_up_at).toLocaleDateString()}`})),...v.upcoming.map(I=>({label:I.title,detail:I.starts_at?`Event on ${new Date(I.starts_at).toLocaleDateString()}`:"Event scheduled"}))].slice(0,6),w=t.activities.filter(I=>new Date(I.created_at)>=i),S={produce:0,influence:0,provide:0,connect:0};for(const I of w)I.pillar&&S[I.pillar]!==void 0&&S[I.pillar]++;const A=Object.entries(S).map(([I,F])=>({pillar:I,count:F})),E=A.slice().sort((I,F)=>I.count-F.count)[0],O=t.primaryPillar?`Your 90-day primary pillar is ${t.primaryPillar}. This week your lightest pillar was ${E.pillar} (${E.count} activities) — give it one deliberate rep.`:`Your lightest pillar this week was ${E.pillar} (${E.count} activities). Pick one action there.`,D={advanced:t.stageChanges.filter(I=>new Date(I.created_at)>=i).length,follow_ups_completed:t.followUps.filter(I=>I.completed_at&&new Date(I.completed_at)>=i).length,conversations_logged:w.filter(I=>["touch_logged","call","text","email","dm","meeting"].includes(I.activity_type)).length,kits_shared:y.length};return{week_start:r.toISOString().slice(0,10),week_end:a.toISOString().slice(0,10),generated_at:n.toISOString(),conversations:c,high_intent:u,renewed:h,overdue:p,stale:f,kit_summary:_,event_summary:v,upcoming_opportunities:j,pillar_balance:A,recommended_focus:O,wins:D}}function bet(s,t){const n=l=>String(l??"").replace(/[<>&]/g,o=>({"<":"<",">":">","&":"&"})[o]),r=(l,o)=>o?`
${n(l)}
${o}`:"",a=l=>l.length?`
    ${l.map(o=>`
  • ${n(o.agent_name)} — ${n(o.detail)}
  • `).join("")}
`:"",i=s.conversations.map(l=>`
${l.rank}. ${n(l.agent_name)} ${n(l.channel.replace(/_/g," "))} health ${l.score}
Why: ${n(l.reason)}
${n(l.draft_message)}
Open relationship →
`).join("");return`
${r("Five conversations for this week",i||'
No recommended conversations yet — add agents to your pipeline.
')} ${r("High-intent signals",a(s.high_intent))} ${r("Renewed interest",a(s.renewed))} ${r("Overdue commitments",a(s.overdue))} ${r("Going quiet",a(s.stale))} ${r("Resource kit engagement",`
${s.kit_summary.shares} shared · ${s.kit_summary.opened} opened · ${s.kit_summary.engaged} engaged · ${s.kit_summary.high_intent} high intent · ${s.kit_summary.downloads} downloads · ${s.kit_summary.questions} questions
`)} ${r("Events",`
${s.event_summary.invited} invited · ${s.event_summary.registered} registered · ${s.event_summary.attended} attended · ${s.event_summary.no_shows} no-shows · ${s.event_summary.follow_ups_pending} follow-ups pending
`)} ${r("Four-pillar balance",`
${s.pillar_balance.map(l=>`${l.pillar}: ${l.count}`).join(" · ")}
${n(s.recommended_focus)}
`)} ${r("Wins this week",`
${s.wins.advanced} relationships advanced · ${s.wins.follow_ups_completed} follow-ups completed · ${s.wins.conversations_logged} conversations logged · ${s.wins.kits_shared} kits shared
`)}
LevelUp Attract
Your Weekly Attraction Digest
Week of ${s.week_start} → ${s.week_end}
Open Relationship Opportunities
`}const B2=q;function zun(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:["attract-digest-settings",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await B2.from("attract_digest_settings").select("*").eq("user_id",s.id).maybeSingle();if(i)throw i;return a??null}}),r=yt({mutationFn:async a=>{const{error:i}=await B2.from("attract_digest_settings").upsert({user_id:s.id,...a},{onConflict:"user_id"});if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-settings"]}),ae.success("Digest settings saved")},onError:a=>ae.error(a.message)});return{settings:n.data,isLoading:n.isLoading,save:r}}function Bun(){const{user:s}=vs();return dt({queryKey:["attract-digests",s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:t,error:n}=await B2.from("attract_digests").select("*").order("week_start",{ascending:!1}).limit(26);if(n)throw n;return t??[]}})}function $un(s){const t=Kt(),n=dt({queryKey:["attract-digest-items",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await B2.from("attract_digest_items").select("*").eq("digest_id",s).order("rank");if(i)throw i;return a??[]}}),r=yt({mutationFn:async a=>{const{error:i}=await B2.from("attract_digest_items").update({completed_at:new Date().toISOString()}).eq("id",a);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digest-items",s]}),ae.success("Marked as done")}});return{items:n.data??[],isLoading:n.isLoading,markComplete:r}}function Uun(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{const{data:r,error:a}=await B2.from("attract_digests").upsert({user_id:s.id,week_start:n.week_start,payload:n,delivery_status:"generated",generated_at:n.generated_at},{onConflict:"user_id,week_start"}).select("id").single();if(a)throw a;const i=r.id;await B2.from("attract_digest_items").delete().eq("digest_id",i).is("completed_at",null);const{data:l}=await B2.from("attract_digest_items").select("agent_id").eq("digest_id",i),o=new Set((l??[]).map(d=>d.agent_id)),c=n.conversations.filter(d=>!o.has(d.agent_id)).map(d=>({digest_id:i,user_id:s.id,agent_id:d.agent_id,rank:d.rank,agent_name:d.agent_name,reason:d.reason,channel:d.channel,draft_message:d.draft_message}));if(c.length){const{error:d}=await B2.from("attract_digest_items").insert(c);if(d)throw d}return i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-digests"]}),t.invalidateQueries({queryKey:["attract-digest-items"]})},onError:n=>ae.error(n.message)})}function qun(){const s=Kt();return yt({mutationFn:async t=>{const{data:n,error:r}=await q.functions.invoke("attract-send-digest",{body:t});if(r)throw r;return n},onSuccess:t=>{s.invalidateQueries({queryKey:["attract-digests"]}),t!=null&&t.ok?ae.success("Digest email sent"):ae.error((t==null?void 0:t.reason)||"Email delivery is not configured yet")},onError:t=>ae.error(t.message??"Send failed")})}const Vun=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function YI({title:s,children:t}){return e.jsxs("div",{children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:s}),t]})}function HG({rows:s,empty:t}){return s.length?e.jsx("ul",{className:"space-y-1.5",children:s.map(n=>e.jsxs("li",{className:"text-[13px] text-slate-700",children:[e.jsx(In,{to:`/attract/agents/${n.agent_id}`,className:"font-medium text-slate-900 hover:text-violet-700",children:n.agent_name}),e.jsxs("span",{className:"text-slate-500",children:[" — ",n.detail]})]},n.agent_id+n.detail))}):e.jsx("div",{className:"text-[13px] text-slate-500",children:t})}function Hun(){var O;const{user:s}=vs(),{intel:t,dataset:n,isLoading:r}=o6(),{settings:a,save:i}=zun(),{data:l=[]}=Bun(),o=Uun(),c=qun(),[d,u]=N.useState(),h=d??((O=l[0])==null?void 0:O.id),{items:p,markComplete:f}=$un(h),[y,_]=N.useState(""),v=N.useMemo(()=>n?ASt(t,n):null,[t,n]),j=l.find(D=>D.id===h),w=(j==null?void 0:j.payload)??v,S=y||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",A=()=>{v&&o.mutate(v,{onSuccess:D=>{u(D),ae.success("This week's digest is ready")}})},E=D=>{if(!w)return;if(!S){ae.error("Add an email address first");return}const I=F=>c.mutate({digestId:F,to:S,subject:`Your Weekly Attraction Digest — ${w.week_start}`,html:bet(w,window.location.origin),test:D});j?I(j.id):v&&o.mutate(v,{onSuccess:F=>{u(F),I(F)}})};return r||!w?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-10 w-56"}),e.jsx(Ws,{className:"h-72 w-full rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-end justify-between gap-4 flex-wrap",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[11.5px] uppercase tracking-wider font-medium text-violet-600",children:"Relationship Intelligence"}),e.jsx("h1",{className:"text-2xl font-semibold tracking-tight text-slate-900 mt-0.5",children:"Weekly Attraction Digest"}),e.jsxs("p",{className:"text-[13.5px] text-slate-500 mt-1",children:["Week of ",new Date(`${w.week_start}T12:00:00`).toLocaleDateString()," – ",new Date(`${w.week_end}T12:00:00`).toLocaleDateString(),j&&e.jsxs(e.Fragment,{children:[" · ",e.jsx("span",{className:"capitalize",children:j.delivery_status.replace(/_/g," ")}),j.sent_at?` ${new Date(j.sent_at).toLocaleString()}`:""]})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:A,disabled:o.isPending,children:[e.jsx(Ei,{className:Mt("h-3.5 w-3.5 mr-1.5",o.isPending&&"animate-spin")})," Regenerate"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(bet(w,window.location.origin)),ae.success("Digest HTML copied")},children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1.5"})," Copy HTML"]}),e.jsxs(B,{className:"rounded-full btn-primary text-white",onClick:()=>E(!0),disabled:c.isPending,children:[e.jsx(lr,{className:"h-3.5 w-3.5 mr-1.5"})," Email it to me"]})]})]}),e.jsxs(Fr,{defaultValue:"digest",children:[e.jsx(Rr,{className:"rounded-full bg-white border border-slate-200 p-1",children:[["digest","This week"],["history","History"],["settings","Delivery settings"]].map(([D,I])=>e.jsx(Zt,{value:D,className:"rounded-full text-[13px] data-[state=active]:bg-violet-600 data-[state=active]:text-white",children:I},D))}),e.jsxs(is,{value:"digest",className:"mt-5 space-y-5",children:[e.jsx("div",{className:"grid grid-cols-2 lg:grid-cols-4 gap-3",children:[["Conversations logged",w.wins.conversations_logged],["Stage moves",w.wins.advanced],["Follow-ups completed",w.wins.follow_ups_completed],["Kits shared",w.wins.kits_shared]].map(([D,I])=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-2xl font-semibold tabular-nums text-slate-900",children:I}),e.jsx("div",{className:"text-[11.5px] text-slate-500 mt-0.5",children:D})]},D))}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-600 mb-3",children:"Your five conversations this week"}),w.conversations.length?e.jsx("div",{className:"space-y-3",children:w.conversations.map(D=>{const I=p.find(z=>z.agent_id===D.agent_id),F=!!(I!=null&&I.completed_at);return e.jsxs("div",{className:Mt("rounded-xl border border-slate-200 p-4",F&&"bg-emerald-50/60 border-emerald-200"),children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14.5px] font-semibold text-slate-900",children:[D.rank,". ",e.jsx(In,{to:`/attract/agents/${D.agent_id}`,className:"hover:text-violet-700",children:D.agent_name})]}),e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-0.5",children:D.reason})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{variant:"outline",className:"rounded-full capitalize",children:D.channel}),e.jsxs(Ue,{variant:"outline",className:"rounded-full",children:["Health ",D.score]})]})]}),D.draft_message&&e.jsx("div",{className:"mt-3 rounded-lg bg-slate-50 p-3 text-[13px] text-slate-700 whitespace-pre-wrap",children:D.draft_message}),e.jsxs("div",{className:"flex gap-2 mt-3",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{navigator.clipboard.writeText(D.draft_message||""),ae.success("Copied")},children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1.5"})," Copy"]}),I&&!F&&e.jsxs(B,{size:"sm",className:"rounded-full btn-primary text-white",onClick:()=>f.mutate(I.id),children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark done"]}),F&&e.jsx("span",{className:"text-[12.5px] text-emerald-700 font-medium self-center",children:"Completed"}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(In,{to:`/attract/agents/${D.agent_id}`,children:"Open relationship"})})]})]},D.agent_id)})}):e.jsx("div",{className:"text-[13px] text-slate-500",children:"No conversations to recommend yet — Attract needs real signals first."})]}),e.jsxs("div",{className:"grid grid-cols-1 lg:grid-cols-2 gap-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(YI,{title:"High intent",children:e.jsx(HG,{rows:w.high_intent,empty:"No high-intent signals this week."})}),e.jsx(YI,{title:"Renewed interest",children:e.jsx(HG,{rows:w.renewed,empty:"Nobody re-engaged after going quiet."})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl space-y-4",children:[e.jsx(YI,{title:"Overdue commitments",children:e.jsx(HG,{rows:w.overdue,empty:"Nothing overdue. Well kept."})}),e.jsx(YI,{title:"Going cold",children:e.jsx(HG,{rows:w.stale,empty:"No relationships past 60 days of silence."})})]}),e.jsx(fe,{className:"p-5 rounded-2xl",children:e.jsx(YI,{title:"Value shared",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[w.kit_summary.shares," kits shared · ",w.kit_summary.opened," opened"]}),e.jsxs("div",{children:[w.kit_summary.downloads," downloads · ",w.kit_summary.questions," questions asked"]}),e.jsxs("div",{children:[w.kit_summary.engaged," engaged · ",w.kit_summary.high_intent," high intent"]})]})})}),e.jsx(fe,{className:"p-5 rounded-2xl",children:e.jsx(YI,{title:"Events",children:e.jsxs("div",{className:"text-[13px] text-slate-700 space-y-1",children:[e.jsxs("div",{children:[w.event_summary.invited," invited · ",w.event_summary.registered," registered"]}),e.jsxs("div",{children:[w.event_summary.attended," attended · ",w.event_summary.no_shows," no-shows"]}),e.jsxs("div",{children:[w.event_summary.follow_ups_pending," attendee follow-ups still pending"]}),w.event_summary.upcoming.map(D=>e.jsxs("div",{className:"text-slate-600 flex items-center gap-1.5",children:[e.jsx(Cl,{className:"h-3.5 w-3.5"})," ",D.title,D.starts_at?` — ${new Date(D.starts_at).toLocaleDateString()}`:""]},D.title))]})})})]}),e.jsxs(fe,{className:"p-5 rounded-2xl bg-gradient-to-r from-violet-50 to-indigo-50 border-violet-100",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-violet-700",children:"Recommended focus"}),e.jsx("p",{className:"text-[14px] text-slate-800 mt-1.5",children:w.recommended_focus}),e.jsx("div",{className:"flex gap-2 mt-3 flex-wrap",children:w.pillar_balance.map(D=>e.jsxs(Ue,{variant:"outline",className:"rounded-full capitalize bg-white/70",children:[D.pillar,": ",D.count]},D.pillar))})]})]}),e.jsx(is,{value:"history",className:"mt-5 space-y-3",children:l.length?l.map(D=>e.jsxs(fe,{className:Mt("p-4 rounded-2xl flex items-center justify-between gap-3 flex-wrap",D.id===h&&"ring-1 ring-violet-300"),children:[e.jsxs("div",{children:[e.jsxs("div",{className:"text-[14px] font-semibold text-slate-900",children:["Week of ",new Date(`${D.week_start}T12:00:00`).toLocaleDateString()]}),e.jsxs("div",{className:"text-[12px] text-slate-500 mt-0.5",children:[e.jsx("span",{className:"capitalize",children:D.delivery_status.replace(/_/g," ")}),D.sent_at&&` · sent ${new Date(D.sent_at).toLocaleString()}`,D.delivery_note&&` · ${D.delivery_note}`]})]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u(D.id),children:"View"})]},D.id)):e.jsx(fe,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"No digests generated yet."})}),e.jsx(is,{value:"settings",className:"mt-5",children:e.jsxs(fe,{className:"p-5 rounded-2xl max-w-xl space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[14px] font-medium text-slate-900",children:"Weekly email"}),e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Send the digest automatically each week."})]}),e.jsx(jn,{checked:!!(a!=null&&a.enabled),onCheckedChange:D=>i.mutate({enabled:D})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Day"}),e.jsxs(us,{value:String((a==null?void 0:a.weekday)??1),onValueChange:D=>i.mutate({weekday:Number(D)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Vun.map((D,I)=>e.jsx(Ze,{value:String(I),children:D},D))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Hour (local)"}),e.jsxs(us,{value:String((a==null?void 0:a.send_hour)??7),onValueChange:D=>i.mutate({send_hour:Number(D)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Array.from({length:24},(D,I)=>e.jsxs(Ze,{value:String(I),children:[I,":00"]},I))})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Send to"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:y||(a==null?void 0:a.email)||(s==null?void 0:s.email)||"",onChange:D=>_(D.target.value),placeholder:"you@example.com"}),e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>i.mutate({email:S}),children:"Save"})]})]}),e.jsxs("div",{className:"rounded-xl bg-amber-50 border border-amber-200 p-3 text-[12.5px] text-amber-900 flex gap-2",children:[e.jsx(Gs,{className:"h-4 w-4 mt-0.5 shrink-0"}),`Automatic weekly scheduling is not wired to a scheduler yet — use "Email it to me" to send on demand. If delivery isn't configured, the digest is still saved here and the status will say so honestly.`]})]})})]})]})}const h3=q,Gun=[{first_name:"Dana",last_name:"Reyes (Demo)",stage:"engaging_with_value",temperature:"hot",brokerage:"Summit Realty",city:"Tulsa",state:"OK",goals:"Wants to double GCI",challenges:"No systems"},{first_name:"Marcus",last_name:"Webb (Demo)",stage:"building_relationship",temperature:"warm",brokerage:"Keystone Group",city:"Jenks",state:"OK",goals:"More listings",challenges:"Lead follow-up"},{first_name:"Priya",last_name:"Nair (Demo)",stage:"active_conversation",temperature:"hot",brokerage:"Northline",city:"Bixby",state:"OK",goals:"Team building",challenges:"Time management"}];function Wun(){const{user:s}=vs(),t=Kt(),{intel:n,dataset:r,isLoading:a,refetch:i}=o6(),l=U8e(),o=Hkt(),[c,d]=N.useState(""),[u,h]=N.useState(!1),p=N.useMemo(()=>r?ASt(n,r):null,[n,r]),f=N.useMemo(()=>{const v=c.toLowerCase().trim();return n.filter(j=>!v||`${j.agent.first_name} ${j.agent.last_name??""}`.toLowerCase().includes(v))},[n,c]),y=async()=>{if(!s)return;h(!0);const{data:v}=await h3.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0);if((v??[]).length){ae.info("Demo agents already exist"),h(!1);return}const{data:j,error:w}=await h3.from("attract_agents").insert(Gun.map(A=>({...A,user_id:s.id,is_demo:!0,source:"demo_seed"}))).select("id, first_name");if(w){ae.error(w.message),h(!1);return}const S=Date.now();await h3.from("attract_activities").insert((j??[]).map((A,E)=>({user_id:s.id,agent_id:A.id,activity_type:"touch_logged",pillar:"connect",title:`Demo conversation with ${A.first_name}`,created_at:new Date(S-(E+1)*14*864e5).toISOString()}))),await h3.from("attract_follow_ups").insert({user_id:s.id,agent_id:j[0].id,title:"Demo overdue commitment",touch_type:"call",priority:"high",due_at:new Date(S-6*864e5).toISOString()}),ae.success("Demo relationships seeded"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()},_=async()=>{if(!s)return;h(!0);const{data:v}=await h3.from("attract_agents").select("id").eq("user_id",s.id).eq("is_demo",!0),j=(v??[]).map(w=>w.id);if(!j.length){ae.info("No demo data to clear"),h(!1);return}for(const w of["attract_recommendations","attract_agent_scores","attract_follow_ups","attract_activities"])await h3.from(w).delete().in("agent_id",j);await h3.from("attract_agents").delete().in("id",j),ae.success("Demo data removed"),h(!1),t.invalidateQueries({queryKey:["attract-intel-data"]}),i()};return a?e.jsx(Ws,{className:"h-72 w-full rounded-2xl"}):e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(In,{to:"/admin",children:[e.jsx(qr,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Intelligence Debug"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Full transparency into scores, signals and recommendations for your own Attract data. Demo records are flagged and removable."})]}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>{o.mutate({items:n}),l.mutate(n)},disabled:l.isPending||o.isPending,children:[e.jsx(Ei,{className:"h-3.5 w-3.5 mr-1.5"})," Recompute & persist"]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:y,disabled:u,children:[e.jsx(P7,{className:"h-3.5 w-3.5 mr-1.5"})," Seed demo relationships"]}),e.jsxs(B,{variant:"outline",className:"rounded-full text-destructive",onClick:_,disabled:u,children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-1.5"})," Clear demo data"]})]}),e.jsxs(Fr,{defaultValue:"agents",children:[e.jsxs(Rr,{className:"rounded-full",children:[e.jsx(Zt,{value:"agents",className:"rounded-full",children:"Scores & signals"}),e.jsx(Zt,{value:"digest",className:"rounded-full",children:"Digest payload"})]}),e.jsxs(is,{value:"agents",className:"mt-4 space-y-3",children:[e.jsx(ye,{value:c,onChange:v=>d(v.target.value),placeholder:"Filter by name",className:"max-w-sm rounded-full"}),!f.length&&e.jsx(fe,{className:"p-6 rounded-2xl text-[13.5px] text-muted-foreground",children:"No agents in your Attract pipeline."}),f.map(v=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{children:[e.jsx(In,{to:`/attract/agents/${v.agent.id}`,className:"text-[15px] font-semibold hover:text-violet-700",children:[v.agent.first_name,v.agent.last_name].filter(Boolean).join(" ")}),e.jsxs("div",{className:"text-[12px] text-muted-foreground mt-0.5 capitalize",children:[v.agent.stage.replace(/_/g," ")," · ",v.agent.temperature??"no temperature"," · ",v.signals.daysSinceTouch??"—"," days since touch"]})]}),v.agent.is_demo&&e.jsx(Ue,{variant:"outline",className:"rounded-full",children:"Demo"})]}),e.jsxs("div",{className:"grid md:grid-cols-2 gap-4 mt-4",children:[e.jsx(Wkt,{score:v.score}),e.jsxs("div",{children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-muted-foreground mb-1.5",children:["Recommendations (",v.recommendations.length,")"]}),v.recommendations.length?e.jsx("ul",{className:"space-y-2",children:v.recommendations.map(j=>e.jsxs("li",{className:"text-[12.5px]",children:[e.jsx("span",{className:"font-medium",children:j.title}),e.jsxs("span",{className:"text-muted-foreground",children:[" · ",j.signal_group," · rank ",j.rank_score," · ",j.priority]}),e.jsx("div",{className:"text-muted-foreground",children:j.reasons.join(" · ")})]},j.rec_key))}):e.jsx("div",{className:"text-[13px] text-muted-foreground",children:"None generated."})]})]}),e.jsxs("details",{className:"mt-3",children:[e.jsx("summary",{className:"text-[12px] cursor-pointer text-muted-foreground",children:"Raw signals"}),e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto mt-2 max-h-72",children:JSON.stringify({touches90:v.signals.touches90,kitShares:v.signals.shares.length,kitOpens:v.signals.totalKitOpens,questions:v.signals.questions,meetingRequests:v.signals.meetingRequests,overdueFollowUps:v.signals.overdueFollowUps.length,attended:v.signals.attended},null,2)})]})]},v.agent.id))]}),e.jsx(is,{value:"digest",className:"mt-4",children:e.jsx(fe,{className:"p-4 rounded-2xl",children:e.jsx("pre",{className:"text-[11px] bg-muted p-3 rounded-lg overflow-auto max-h-[600px]",children:JSON.stringify(p,null,2)})})})]})]})}function Kun(){const[s,t]=N.useState(""),[n,r]=N.useState("all"),a=N.useMemo(()=>ITe.filter(l=>{const o=s.toLowerCase().trim();return n!=="all"&&l.status!==n?!1:!o||`${l.title} ${l.pillar} ${l.route??""}`.toLowerCase().includes(o)}),[s,n]),i=N.useMemo(()=>{const l={live:0,partial:0,placeholder:0,integration_required:0};return ITe.forEach(o=>{l[o.status]++}),l},[]);return e.jsxs("div",{className:"p-4 sm:p-6 max-w-6xl mx-auto space-y-5",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(In,{to:"/admin",children:[e.jsx(qr,{className:"h-3.5 w-3.5 mr-1.5"})," Admin"]})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-semibold tracking-tight",children:"Attract Pillar Tools QA"}),e.jsx("p",{className:"text-[13.5px] text-muted-foreground mt-1",children:"Private status map of every Attract tool — route, database dependencies, and what still needs work."})]}),e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Object.keys(i).map(l=>e.jsxs(fe,{className:"p-4 rounded-2xl cursor-pointer",onClick:()=>r(n===l?"all":l),children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums",children:i[l]}),e.jsx("div",{className:"text-[12px] text-muted-foreground",children:PTe[l]})]},l))}),e.jsxs("div",{className:"flex gap-2 flex-wrap",children:[e.jsx(ye,{value:s,onChange:l=>t(l.target.value),placeholder:"Filter tools",className:"max-w-sm rounded-full"}),n!=="all"&&e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>r("all"),children:"Clear status filter"})]}),e.jsx("div",{className:"space-y-2",children:a.map(l=>e.jsx(fe,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold",children:l.title}),e.jsx(Ue,{variant:"outline",className:"rounded-full capitalize",children:l.pillar}),e.jsx(Ue,{variant:"outline",className:`rounded-full ${rSt[l.status]}`,children:PTe[l.status]})]}),e.jsx("div",{className:"text-[12.5px] text-muted-foreground mt-1",children:l.notes||"—"}),e.jsxs("div",{className:"text-[11.5px] text-muted-foreground mt-1",children:["Tables: ",l.tables.length?l.tables.join(", "):"none"]})]}),l.route&&!l.route.includes(":")?e.jsx(B,{variant:"outline",size:"sm",className:"rounded-full",asChild:!0,children:e.jsxs(In,{to:l.route,children:[l.route," ",e.jsx(tr,{className:"h-3 w-3 ml-1.5"})]})}):e.jsx("span",{className:"text-[12px] text-muted-foreground",children:l.route??"No route"})]})},`${l.pillar}-${l.key}`))})]})}const m3=q,_et=["idea","researching","pitching","applied","tentative","confirmed","completed","declined","archived"],wet=["panel","keynote","mls_talk","podcast","webinar","mastermind","training","conference","other"],jet=["attract-speaking"];function MSt(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:[...jet,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:u,error:h}=await m3.from("attract_speaking_opportunities").select("*").order("starts_at",{ascending:!0,nullsFirst:!1});if(h)throw h;return u??[]}}),r=()=>{t.invalidateQueries({queryKey:jet}),t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-activities"]})},a=yt({mutationFn:async u=>{const{data:h,error:p}=await m3.from("attract_speaking_opportunities").insert({...u,user_id:s.id}).select("*").single();if(p)throw p;return h},onSuccess:()=>{r(),ae.success("Speaking opportunity saved")},onError:u=>ae.error(u.message)}),i=yt({mutationFn:async({id:u,...h})=>{const{error:p}=await m3.from("attract_speaking_opportunities").update(h).eq("id",u);if(p)throw p},onSuccess:()=>{r(),ae.success("Updated")},onError:u=>ae.error(u.message)}),l=yt({mutationFn:async u=>{const{id:h,created_at:p,updated_at:f,user_id:y,..._}=u,{data:v,error:j}=await m3.from("attract_speaking_opportunities").insert({..._,title:`${u.title} (copy)`,status:"idea",user_id:s.id}).select("id").single();if(j)throw j;return v},onSuccess:()=>{r(),ae.success("Duplicated")},onError:u=>ae.error(u.message)}),o=yt({mutationFn:async u=>{const{error:h}=await m3.from("attract_speaking_opportunities").delete().eq("id",u);if(h)throw h},onSuccess:()=>{r(),ae.success("Deleted")},onError:u=>ae.error(u.message)}),c=yt({mutationFn:async({title:u,dueAt:h,notes:p,touchType:f="speaking"})=>{const{error:y}=await m3.from("attract_follow_ups").insert({user_id:s.id,title:u,due_at:h??null,notes:p??null,touch_type:f,priority:"medium"});if(y)throw y},onSuccess:()=>{r(),ae.success("Added to Follow-Up Center")},onError:u=>ae.error(u.message)}),d=yt({mutationFn:async({title:u,pillar:h="influence",activityType:p="speaking_outreach",agentId:f})=>{const{error:y}=await m3.from("attract_activities").insert({user_id:s.id,title:u,pillar:h,activity_type:p,agent_id:f??null});if(y)throw y},onSuccess:()=>{r(),ae.success("Outreach logged")},onError:u=>ae.error(u.message)});return{items:n.data??[],isLoading:n.isLoading,error:n.error,refetch:n.refetch,create:a,update:i,duplicate:l,remove:o,addTask:c,logActivity:d}}const $Te={idea:"bg-slate-100 text-slate-700 border-slate-200",researching:"bg-sky-50 text-sky-700 border-sky-200",pitching:"bg-amber-50 text-amber-700 border-amber-200",applied:"bg-orange-50 text-orange-700 border-orange-200",tentative:"bg-violet-50 text-violet-700 border-violet-200",confirmed:"bg-emerald-50 text-emerald-700 border-emerald-200",completed:"bg-teal-50 text-teal-700 border-teal-200",declined:"bg-rose-50 text-rose-700 border-rose-200",archived:"bg-slate-100 text-slate-500 border-slate-200"},xke={title:"",organization:"",event_type:"panel",status:"idea",timezone:"America/New_York",pillar:"influence",linked_agent_ids:[]};function Yun(){const{items:s,isLoading:t,create:n,update:r,duplicate:a,remove:i,addTask:l,logActivity:o}=MSt(),{agents:c=[]}=i0(),{kits:d=[]}=AR(),u=K1e(),h=(u==null?void 0:u.events)??(u==null?void 0:u.data)??[],[p,f]=N.useState("month"),[y,_]=N.useState(new Date),[v,j]=N.useState("all"),[w,S]=N.useState("all"),[A,E]=N.useState("all"),[O,D]=N.useState(!1),[I,F]=N.useState(null),[z,H]=N.useState(null),Z=N.useMemo(()=>s.filter(le=>!(!O&&(le.is_archived||le.status==="archived")||v!=="all"&&le.status!==v||w!=="all"&&le.event_type!==w||A!=="all"&&!(le.linked_agent_ids??[]).includes(A))),[s,v,w,A,O]),Y=Z.filter(le=>le.starts_at),W=Z.filter(le=>!le.starts_at),ee=new Date,se=N.useMemo(()=>{const le=Y.filter(Ce=>Ov(Zh(Ce.starts_at),ee)&&["confirmed","tentative"].includes(Ce.status)),ve=Z.filter(Ce=>Ce.submission_deadline&&Ov(Zh(Ce.submission_deadline),ee)),ge=Z.filter(Ce=>["pitching","applied","researching"].includes(Ce.status)),Te=Z.filter(Ce=>Ce.status==="confirmed"),Ie=Z.filter(Ce=>Ce.follow_up_date&&Ce.status==="completed");return{upcoming:le,deadlines:ve,pitches:ge,confirmed:Te,followUps:Ie}},[Z,Y]),oe=N.useMemo(()=>x4e(p==="week"?{start:Vm(y),end:x8(y)}:{start:Vm(Rd(y)),end:x8($0(y))}),[y,p]),he=le=>Y.filter(ve=>ql(Zh(ve.starts_at),le)),ce=async()=>{var ve;if(!((ve=I==null?void 0:I.title)!=null&&ve.trim())){ae.error("Give the talk a title");return}const le={...I};delete le.created_at,delete le.updated_at,delete le.user_id,(le.fee===""||le.fee==null)&&(le.fee=null),["starts_at","ends_at","submission_deadline","follow_up_date","linked_event_id","linked_kit_id"].forEach(ge=>{le[ge]===""&&(le[ge]=null)}),I.id?await r.mutateAsync(le):await n.mutateAsync(le),F(null)},me=le=>{if(!le.starts_at){ae.error("Add a date first");return}const ve=Me=>new Date(Me).toISOString().replace(/[-:]|\.\d{3}/g,""),ge=le.ends_at??new Date(new Date(le.starts_at).getTime()+60*6e4).toISOString(),Te=["BEGIN:VCALENDAR","VERSION:2.0","PRODID:-//LevelUp Attract//Speaking//EN","BEGIN:VEVENT",`UID:${le.id}@levelup-attract`,`DTSTAMP:${ve(new Date().toISOString())}`,`DTSTART:${ve(le.starts_at)}`,`DTEND:${ve(ge)}`,`SUMMARY:${(le.title||"").replace(/\n/g," ")}`,`LOCATION:${(le.location||le.virtual_link||"").replace(/\n/g," ")}`,`DESCRIPTION:${[le.organization,le.topic].filter(Boolean).join(" — ").replace(/\n/g," ")}`,"END:VEVENT","END:VCALENDAR"].join(`\r `),Ie=URL.createObjectURL(new Blob([Te],{type:"text/calendar"})),Ce=document.createElement("a");Ce.href=Ie,Ce.download=`${le.title.replace(/\W+/g,"-").toLowerCase()}.ics`,Ce.click(),URL.revokeObjectURL(Ie)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-32 rounded-2xl"}),e.jsx(Ws,{className:"h-96 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(zu,{eyebrow:"Pillar 02 · Influence",title:"Speaking Calendar",description:"Every stage, panel, podcast, and MLS talk — from first idea to post-event follow-up.",actions:e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>F({...xke}),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New opportunity"]})}),e.jsxs("div",{className:"grid grid-cols-2 lg:grid-cols-5 gap-3",children:[e.jsx(GF,{label:"Upcoming talks",value:se.upcoming.length,icon:Dv}),e.jsx(GF,{label:"Deadlines ahead",value:se.deadlines.length,icon:pr}),e.jsx(GF,{label:"Pitches in flight",value:se.pitches.length,icon:lr}),e.jsx(GF,{label:"Confirmed",value:se.confirmed.length,icon:vr}),e.jsx(GF,{label:"Post-event follow-ups",value:se.followUps.length,icon:lu})]}),e.jsxs(fe,{className:"p-3 rounded-2xl flex flex-wrap items-center gap-2",children:[e.jsx("div",{className:"flex rounded-full bg-slate-100 p-1",children:["month","week","agenda"].map(le=>e.jsx("button",{onClick:()=>f(le),className:`px-3 py-1.5 rounded-full text-[12.5px] font-medium capitalize ${p===le?"bg-white shadow-sm text-slate-900":"text-slate-500"}`,children:le},le))}),p!=="agenda"&&e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>_(p==="week"?L2(y,-1):_f(y,-1)),children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-semibold min-w-[130px] text-center",children:Ss(y,p==="week"?"'Week of' MMM d":"MMMM yyyy")}),e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",onClick:()=>_(p==="week"?L2(y,1):_f(y,1)),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full",onClick:()=>_(new Date),children:"Today"})]}),e.jsx("div",{className:"flex-1"}),e.jsxs(us,{value:v,onValueChange:j,children:[e.jsx(ls,{className:"w-[140px] rounded-full h-9",children:e.jsx(hs,{placeholder:"Status"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All statuses"}),_et.map(le=>e.jsx(Ze,{value:le,className:"capitalize",children:le.replace(/_/g," ")},le))]})]}),e.jsxs(us,{value:w,onValueChange:S,children:[e.jsx(ls,{className:"w-[140px] rounded-full h-9",children:e.jsx(hs,{placeholder:"Type"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All types"}),wet.map(le=>e.jsx(Ze,{value:le,className:"capitalize",children:le.replace(/_/g," ")},le))]})]}),e.jsxs(us,{value:A,onValueChange:E,children:[e.jsx(ls,{className:"w-[160px] rounded-full h-9",children:e.jsx(hs,{placeholder:"Relationship"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All relationships"}),c.map(le=>e.jsx(Ze,{value:le.id,children:[le.first_name,le.last_name].filter(Boolean).join(" ")},le.id))]})]}),e.jsxs(B,{variant:O?"default":"outline",size:"sm",className:"rounded-full",onClick:()=>D(le=>!le),children:[e.jsx(tm,{className:"h-3.5 w-3.5 mr-1.5"}),"Archived"]})]}),s.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(Dv,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No speaking opportunities yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Start with the rooms you already have access to — your office meeting, a local MLS class, a peer's podcast. Track the pitch, the deadline, and the follow-up in one place."}),e.jsxs(B,{className:"mt-4 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>F({...xke}),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"Add your first opportunity"]})]}):p==="agenda"?e.jsxs("div",{className:"space-y-3",children:[[...Y,...W].length===0&&e.jsx(fe,{className:"p-8 rounded-2xl text-center text-[13.5px] text-slate-500",children:"Nothing matches these filters."}),[...Y,...W].map(le=>e.jsx(Zun,{o:le,onEdit:()=>F(le),onComplete:()=>H(le),onDuplicate:()=>a.mutate(le),onDelete:()=>i.mutate(le.id),onArchive:()=>r.mutate({id:le.id,is_archived:!le.is_archived,status:le.is_archived?"idea":"archived"}),onIcs:()=>me(le),onPitchTask:()=>l.mutate({title:`Pitch: ${le.title}${le.organization?` (${le.organization})`:""}`,dueAt:le.submission_deadline?new Date(le.submission_deadline).toISOString():null,notes:le.notes??void 0}),onLogOutreach:()=>o.mutate({title:`Outreach for ${le.title}`}),onConfirm:()=>r.mutate({id:le.id,status:"confirmed"})},le.id))]}):e.jsxs(fe,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 border-b bg-slate-50",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(le=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider font-semibold text-slate-500 text-center",children:le},le))}),e.jsx("div",{className:"grid grid-cols-7",children:oe.map(le=>{const ve=he(le);return e.jsxs("div",{className:`min-h-[92px] sm:min-h-[112px] border-b border-r p-1.5 ${W$(le,y)||p==="week"?"bg-white":"bg-slate-50/60"}`,children:[e.jsx("button",{onClick:()=>F({...xke,starts_at:new Date(le.setHours(10,0,0,0)).toISOString()}),className:`text-[11.5px] font-semibold h-6 w-6 rounded-full grid place-items-center ${ql(le,ee)?"bg-violet-600 text-white":"text-slate-500 hover:bg-slate-100"}`,children:Ss(le,"d")}),e.jsxs("div",{className:"mt-1 space-y-1",children:[ve.slice(0,3).map(ge=>e.jsx("button",{onClick:()=>F(ge),className:`w-full text-left text-[11px] px-1.5 py-1 rounded-md border truncate ${$Te[ge.status]??""}`,children:ge.title},ge.id)),ve.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-400 pl-1",children:["+",ve.length-3," more"]})]})]},le.toISOString())})}),W.length>0&&e.jsxs("div",{className:"p-3 bg-slate-50 border-t",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-wider font-semibold text-slate-500 mb-2",children:["Undated (",W.length,")"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:W.map(le=>e.jsx("button",{onClick:()=>F(le),className:`text-[12px] px-2.5 py-1 rounded-full border ${$Te[le.status]??""}`,children:le.title},le.id))})]})]}),e.jsx(l6,{}),e.jsx(_s,{open:!!I,onOpenChange:le=>!le&&F(null),children:e.jsxs(bs,{className:"max-w-3xl max-h-[90vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsx(ws,{children:I!=null&&I.id?"Edit speaking opportunity":"New speaking opportunity"})}),I&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(md,{label:"Title",className:"sm:col-span-2",children:e.jsx(ye,{value:I.title??"",onChange:le=>F({...I,title:le.target.value}),placeholder:"Panel: Winning listings in a shifting market"})}),e.jsx(md,{label:"Event / organization",children:e.jsx(ye,{value:I.organization??"",onChange:le=>F({...I,organization:le.target.value})})}),e.jsx(md,{label:"Event type",children:e.jsxs(us,{value:I.event_type??"panel",onValueChange:le=>F({...I,event_type:le}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:wet.map(le=>e.jsx(Ze,{value:le,className:"capitalize",children:le.replace(/_/g," ")},le))})]})}),e.jsx(md,{label:"Contact name",children:e.jsx(ye,{value:I.contact_name??"",onChange:le=>F({...I,contact_name:le.target.value})})}),e.jsx(md,{label:"Contact email",children:e.jsx(ye,{type:"email",value:I.contact_email??"",onChange:le=>F({...I,contact_email:le.target.value})})}),e.jsx(md,{label:"Contact phone",children:e.jsx(ye,{value:I.contact_phone??"",onChange:le=>F({...I,contact_phone:le.target.value})})}),e.jsx(md,{label:"Audience",children:e.jsx(ye,{value:I.audience??"",onChange:le=>F({...I,audience:le.target.value}),placeholder:"120 local agents"})}),e.jsx(md,{label:"Location",children:e.jsx(ye,{value:I.location??"",onChange:le=>F({...I,location:le.target.value})})}),e.jsx(md,{label:"Virtual link",children:e.jsx(ye,{value:I.virtual_link??"",onChange:le=>F({...I,virtual_link:le.target.value})})}),e.jsx(md,{label:"Starts",children:e.jsx(ye,{type:"datetime-local",value:Net(I.starts_at),onChange:le=>F({...I,starts_at:le.target.value?new Date(le.target.value).toISOString():null})})}),e.jsx(md,{label:"Ends",children:e.jsx(ye,{type:"datetime-local",value:Net(I.ends_at),onChange:le=>F({...I,ends_at:le.target.value?new Date(le.target.value).toISOString():null})})}),e.jsx(md,{label:"Status",children:e.jsxs(us,{value:I.status??"idea",onValueChange:le=>F({...I,status:le}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:_et.map(le=>e.jsx(Ze,{value:le,className:"capitalize",children:le},le))})]})}),e.jsx(md,{label:"Fee / honorarium",children:e.jsx(ye,{type:"number",value:I.fee??"",onChange:le=>F({...I,fee:le.target.value===""?null:Number(le.target.value)})})}),e.jsx(md,{label:"Submission deadline",children:e.jsx(ye,{type:"date",value:I.submission_deadline??"",onChange:le=>F({...I,submission_deadline:le.target.value||null})})}),e.jsx(md,{label:"Follow-up date",children:e.jsx(ye,{type:"date",value:I.follow_up_date??"",onChange:le=>F({...I,follow_up_date:le.target.value||null})})}),e.jsx(md,{label:"Application URL",className:"sm:col-span-2",children:e.jsx(ye,{value:I.application_url??"",onChange:le=>F({...I,application_url:le.target.value})})}),e.jsx(md,{label:"Topic",className:"sm:col-span-2",children:e.jsx(ye,{value:I.topic??"",onChange:le=>F({...I,topic:le.target.value})})}),e.jsx(md,{label:"Linked Connect event",children:e.jsxs(us,{value:I.linked_event_id??"none",onValueChange:le=>F({...I,linked_event_id:le==="none"?null:le}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"None"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"None"}),h.map(le=>e.jsx(Ze,{value:le.id,children:le.title},le.id))]})]})}),e.jsx(md,{label:"Linked Resource Kit",children:e.jsxs(us,{value:I.linked_kit_id??"none",onValueChange:le=>F({...I,linked_kit_id:le==="none"?null:le}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"None"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"None"}),d.map(le=>e.jsx(Ze,{value:le.id,children:le.title},le.id))]})]})}),e.jsx(md,{label:"Linked agent relationships",className:"sm:col-span-2",children:e.jsxs("div",{className:"flex flex-wrap gap-1.5 max-h-32 overflow-y-auto",children:[c.length===0&&e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"No agents in your pipeline yet."}),c.map(le=>{const ve=(I.linked_agent_ids??[]).includes(le.id);return e.jsx("button",{type:"button",onClick:()=>F({...I,linked_agent_ids:ve?(I.linked_agent_ids??[]).filter(ge=>ge!==le.id):[...I.linked_agent_ids??[],le.id]}),className:`text-[12px] px-2.5 py-1 rounded-full border ${ve?"bg-violet-600 text-white border-violet-600":"bg-white text-slate-600"}`,children:[le.first_name,le.last_name].filter(Boolean).join(" ")},le.id)})]})}),e.jsx(md,{label:"Travel notes",className:"sm:col-span-2",children:e.jsx(Ms,{rows:2,value:I.travel_notes??"",onChange:le=>F({...I,travel_notes:le.target.value})})}),e.jsx(md,{label:"Notes",className:"sm:col-span-2",children:e.jsx(Ms,{rows:3,value:I.notes??"",onChange:le=>F({...I,notes:le.target.value})})})]}),e.jsxs(Xn,{className:"gap-2",children:[e.jsx(B,{variant:"ghost",onClick:()=>F(null),children:"Cancel"}),e.jsx(B,{onClick:ce,disabled:n.isPending||r.isPending,className:"bg-gradient-to-r from-violet-600 to-indigo-600",children:"Save"})]})]})}),e.jsx(Qun,{item:z,onClose:()=>H(null),onSave:async(le,ve)=>{await r.mutateAsync({id:z.id,status:"completed",outcome:le}),ve&&await l.mutateAsync({title:`Post-event follow-up: ${z.title}`,dueAt:new Date(Date.now()+2*864e5).toISOString(),notes:le.next_actions}),await o.mutateAsync({title:`Spoke at ${z.title}`,activityType:"speaking_completed"}),H(null)}})]})}function Net(s){if(!s)return"";const t=new Date(s),n=t.getTimezoneOffset();return new Date(t.getTime()-n*6e4).toISOString().slice(0,16)}function md({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(ne,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function GF({label:s,value:t,icon:n}){return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx(n,{className:"h-4 w-4 text-violet-600"}),e.jsx("div",{className:"mt-1 text-[22px] font-semibold tabular-nums text-slate-900",children:t}),e.jsx("div",{className:"text-[11.5px] text-slate-500",children:s})]})}function Zun({o:s,onEdit:t,onComplete:n,onDuplicate:r,onDelete:a,onArchive:i,onIcs:l,onPitchTask:o,onLogOutreach:c,onConfirm:d}){var p;const u=s,h=u.submission_deadline?Vx(Zh(u.submission_deadline),new Date):null;return e.jsx(fe,{className:"p-4 rounded-2xl",children:e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("button",{onClick:t,className:"text-[15px] font-semibold text-slate-900 hover:text-violet-700 text-left",children:u.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-0.5",children:[u.organization,(p=u.event_type)==null?void 0:p.replace(/_/g," "),u.audience].filter(Boolean).join(" · ")||"No details yet"}),e.jsxs("div",{className:"text-[12.5px] text-slate-600 mt-1 flex items-center gap-3 flex-wrap",children:[u.starts_at&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(Cl,{className:"h-3.5 w-3.5"}),Ss(Zh(u.starts_at),"EEE MMM d, h:mm a")]}),h!==null&&e.jsxs("span",{className:`inline-flex items-center gap-1 ${h<7?"text-orange-600":""}`,children:[e.jsx(pr,{className:"h-3.5 w-3.5"}),"Deadline in ",h,"d"]}),(u.linked_agent_ids??[]).length>0&&e.jsxs("span",{className:"inline-flex items-center gap-1",children:[e.jsx(An,{className:"h-3.5 w-3.5"}),u.linked_agent_ids.length," linked"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Ue,{variant:"outline",className:`capitalize rounded-full ${$Te[u.status]??""}`,children:u.status}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full",children:e.jsx(Kf,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",children:[e.jsx(Kr,{onClick:t,children:"Edit"}),e.jsxs(Kr,{onClick:o,children:[e.jsx(lu,{className:"h-3.5 w-3.5 mr-2"}),"Add pitch task"]}),e.jsxs(Kr,{onClick:c,children:[e.jsx(lr,{className:"h-3.5 w-3.5 mr-2"}),"Log outreach"]}),e.jsxs(Kr,{onClick:d,children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-2"}),"Mark confirmed"]}),e.jsxs(Kr,{onClick:n,children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-2"}),"Mark completed"]}),e.jsxs(Kr,{onClick:l,children:[e.jsx(Ia,{className:"h-3.5 w-3.5 mr-2"}),"Download .ics"]}),e.jsxs(Kr,{onClick:r,children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Kr,{onClick:i,children:[e.jsx(tm,{className:"h-3.5 w-3.5 mr-2"}),u.is_archived?"Unarchive":"Archive"]}),e.jsxs(Kr,{className:"text-destructive",onClick:a,children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]})]})})}function Qun({item:s,onClose:t,onSave:n}){const[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState("");return e.jsx(_s,{open:!!s,onOpenChange:h=>!h&&t(),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsx(js,{children:e.jsx(ws,{children:"Capture the outcome"})}),e.jsxs("div",{className:"space-y-3",children:[e.jsx(md,{label:"Attendance",children:e.jsx(ye,{value:r,onChange:h=>a(h.target.value),placeholder:"How many were in the room?"})}),e.jsx(md,{label:"Leads / relationships created",children:e.jsx(Ms,{rows:2,value:i,onChange:h=>l(h.target.value)})}),e.jsx(md,{label:"Content captured",children:e.jsx(Ms,{rows:2,value:o,onChange:h=>c(h.target.value),placeholder:"Photos, clips, quotes"})}),e.jsx(md,{label:"Next actions",children:e.jsx(Ms,{rows:2,value:d,onChange:h=>u(h.target.value)})})]}),e.jsxs(Xn,{className:"gap-2",children:[e.jsx(B,{variant:"ghost",onClick:t,children:"Cancel"}),e.jsx(B,{variant:"outline",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!1),children:"Save only"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>n({attendance:r,leads:i,content:o,next_actions:d},!0),children:"Save + create follow-up"})]})]})})}const FP=q,UTe=["attract-masterclasses"];function Xun(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:[...UTe,s==null?void 0:s.id],enabled:!!s,queryFn:async()=>{const{data:o,error:c}=await FP.from("attract_masterclasses").select("*").order("updated_at",{ascending:!1});if(c)throw c;return o??[]}}),r=()=>t.invalidateQueries({queryKey:UTe}),a=yt({mutationFn:async o=>{const{data:c,error:d}=await FP.from("attract_masterclasses").insert({title:"Untitled masterclass",...o,user_id:s.id}).select("*").single();if(d)throw d;return c},onSuccess:()=>r(),onError:o=>ae.error(o.message)}),i=yt({mutationFn:async o=>{const{id:c,created_at:d,updated_at:u,user_id:h,...p}=o,{data:f,error:y}=await FP.from("attract_masterclasses").insert({...p,title:`${o.title} (copy)`,status:"draft",user_id:s.id}).select("id").single();if(y)throw y;return f},onSuccess:()=>{r(),ae.success("Duplicated")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await FP.from("attract_masterclasses").delete().eq("id",o);if(c)throw c},onSuccess:()=>{r(),ae.success("Deleted")},onError:o=>ae.error(o.message)});return{items:n.data??[],isLoading:n.isLoading,refetch:n.refetch,create:a,duplicate:i,remove:l}}function Jun(s){const t=Kt(),n=dt({queryKey:["attract-masterclass",s],enabled:!!s,queryFn:async()=>{const{data:a,error:i}=await FP.from("attract_masterclasses").select("*").eq("id",s).maybeSingle();if(i)throw i;return a}}),r=yt({mutationFn:async a=>{const{error:i}=await FP.from("attract_masterclasses").update(a).eq("id",s);if(i)throw i},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-masterclass",s]}),t.invalidateQueries({queryKey:UTe})},onError:a=>ae.error(a.message)});return{masterclass:n.data??null,isLoading:n.isLoading,save:r}}const Jd=(s,t)=>({id:crypto.randomUUID(),title:s,lessons:t.map(([n,r,a])=>({id:crypto.randomUUID(),title:n,minutes:r,talking_points:a}))}),ket=[{key:"listing_presentation",title:"Listing Presentation Masterclass",promise:"Walk out with a listing presentation that wins the room in the first five minutes.",target_audience:"Agents who get appointments but lose listings to bigger names.",problem_solved:"Presentations that talk about the agent instead of the seller outcome.",desired_outcome:"A rebuilt opening, pricing story, and close they can use this week.",pillar:"provide",duration_minutes:60,curriculum:[Jd("Open strong",[["Why sellers decide in 5 minutes",8,"Trust signals, pacing, the first question you ask"],["The pre-listing package",7,"What to send ahead and why it changes the room"]]),Jd("The pricing conversation",[["Framing price without arguing",12,"Data as a story, not a spreadsheet"],["Handling the overpriced seller",10,"Language patterns and walking-away criteria"]]),Jd("Close and next steps",[["Asking for the signature",8,"Assumptive close variations"],[`Follow-up if they say "we'll think about it"`,8,"48-hour sequence"]])]},{key:"database_revival",title:"Database Revival Workshop",promise:"Reactivate a cold database into real conversations in 30 days.",target_audience:"Agents with 200+ contacts and no consistent outreach.",problem_solved:"A database that exists but produces nothing.",desired_outcome:"A cleaned list, a cadence, and 10 conversations started live in class.",pillar:"provide",duration_minutes:60,curriculum:[Jd("Audit",[["Sorting your list into A/B/C",10,"Criteria that actually predict referrals"],["Fixing missing data",8,"Birthdays, anniversaries, spouse names"]]),Jd("The reach-out",[["The no-ask message",12,"Scripts that do not feel like prospecting"],["Voice notes and video",10,"Why they convert 3x text"]]),Jd("The cadence",[["Building a 12-touch year",12,"Pop-bys, events, market notes"],["Tracking without a CRM headache",8,"Simple weekly rhythm"]])]},{key:"open_house_conversion",title:"Open House Lead Conversion",promise:"Turn a normal open house into 3-5 real buyer conversations.",target_audience:"Newer agents relying on open houses for pipeline.",problem_solved:"Sign-in sheets full of names that never convert.",desired_outcome:"A pre-, during-, and post-open-house system.",pillar:"produce",duration_minutes:45,curriculum:[Jd("Before",[["Neighborhood invites",8,"Door knocking and digital invites"],["Setting the stage",7,"Materials that create conversations"]]),Jd("During",[["The three questions",10,"How to qualify without interrogating"],["Capturing real contact info",8,"Sign-in that people actually complete"]]),Jd("After",[["The 10-minute follow-up",7,"Speed to lead"],["Week-one nurture",5,"What to send day 1, 3, 7"]])]},{key:"social_authority",title:"Social Media Authority",promise:"Build a local social presence that makes agents and clients come to you.",target_audience:"Agents posting inconsistently with little engagement.",problem_solved:"Random posting with no positioning.",desired_outcome:"A content pillar map and 30 days of planned posts.",pillar:"influence",duration_minutes:60,curriculum:[Jd("Positioning",[["Pick your lane",10,"Neighborhood, niche, or narrative"],["What to never post",6,"The credibility killers"]]),Jd("Content system",[["The four content types",14,"Teach, prove, connect, invite"],["Batch filming",10,"One hour, ten pieces"]]),Jd("Distribution",[["Captions and hooks",10,"First-line formulas"],["Turning comments into DMs",10,"Relationship-first outreach"]])]},{key:"ai_for_agents",title:"AI for Agents",promise:"Use AI to save 5 hours a week without sounding like a robot.",target_audience:"Agents curious about AI but unsure where to start.",problem_solved:"Tool overwhelm and generic AI output.",desired_outcome:"Three working workflows they set up live.",pillar:"influence",duration_minutes:60,curriculum:[Jd("Foundations",[["What AI is good and bad at",10,"Drafting vs deciding"],["Prompting basics",10,"Context, role, constraints"]]),Jd("Workflows",[["Listing descriptions and marketing",12,"Brand voice inputs"],["Follow-up and email drafts",12,"Never auto-send"]]),Jd("Guardrails",[["Compliance and fair housing",10,"What to always review"],["Keeping your voice",6,"Editing pass checklist"]])]},{key:"new_construction",title:"New Construction Buyer Workshop",promise:"Represent new construction buyers with confidence and get paid.",target_audience:"Agents losing buyers to builder sales offices.",problem_solved:"Not knowing builder contracts or registration rules.",desired_outcome:"A registration process and builder relationship plan.",pillar:"produce",duration_minutes:60,curriculum:[Jd("The builder landscape",[["How builder comp works",12,"Registration rules that protect you"],["Local builders worth knowing",8,"Relationship map"]]),Jd("Representing the buyer",[["Contract differences",14,"What is negotiable"],["Inspections and walkthroughs",10,"Timeline checkpoints"]]),Jd("Winning the relationship",[["First-visit protocol",8,"Always accompany"],["Post-close referrals",8,"The neighborhood effect"]])]},{key:"luxury_experience",title:"Luxury Client Experience",promise:"Deliver an experience that earns luxury referrals.",target_audience:"Agents moving into a higher price band.",problem_solved:"Marketing and service that feels mid-market.",desired_outcome:"An upgraded listing experience and presentation standard.",pillar:"provide",duration_minutes:60,curriculum:[Jd("Standards",[["What luxury clients notice",12,"Response time, discretion, detail"],["Your materials",10,"Photography, print, web"]]),Jd("The listing experience",[["Pre-market strategy",12,"Whisper listings and staging"],["Private showings",8,"Choreography"]]),Jd("Referral engine",[["Post-close cadence",10,"Gifting and anniversaries"],["Building the circle",8,"Vendors and advisors"]])]},{key:"recruiting_value",title:"Recruiting Through Value",promise:"Attract agents by helping them, not pitching them.",target_audience:"Team leaders and agents building revenue share.",problem_solved:"Recruiting that feels salesy and gets ignored.",desired_outcome:"A value-first attraction plan for 20 named agents.",pillar:"connect",duration_minutes:60,curriculum:[Jd("Mindset",[["Why value beats pitching",10,"Relationship-first framing"],["Choosing your 20",8,"Fit criteria"]]),Jd("The value plan",[["Resource kits that help",14,"What agents actually want"],["Events and masterminds",10,"Small rooms win"]]),Jd("The conversation",[["When to talk business",10,"Earned invitation"],['Handling "I am happy where I am"',8,"Stay in relationship"]])]}];function ehn(s){return{title:s.title,promise:s.promise,target_audience:s.target_audience,problem_solved:s.problem_solved,desired_outcome:s.desired_outcome,pillar:s.pillar,duration_minutes:s.duration_minutes,curriculum:s.curriculum,source_template_key:s.key,status:"draft"}}function thn(s){const t=s.title||"Untitled masterclass",n=s.delivery_date?new Date(s.delivery_date).toLocaleString("en-US",{timeZone:"America/New_York",dateStyle:"full",timeStyle:"short"}):"Date to be announced",r=(s.curriculum??[]).flatMap(i=>i.lessons.map(l=>`• ${l.title}`)).slice(0,6).join(` `),a=s.promise||"A practical, no-pitch training session.";return{registration_copy:`${t} ${n} · ${s.duration_minutes??45} minutes · ${s.format??"virtual"} ${a} Who it's for: ${s.target_audience||"Agents who want a practical system."} What we'll cover: ${r||"• Curriculum coming soon"} What you'll leave with: ${s.desired_outcome||"A plan you can use immediately."}`,email_invite:`Subject: ${t} Hi {{first_name}}, I'm hosting ${t} on ${n}. ${a} It's built for ${s.target_audience||"agents like you"} — no pitch, just the system. We'll cover: ${r||"• Curriculum coming soon"} Want me to save you a seat? {{my_name}}`,social_post:`${a} I'm teaching ${t} on ${n}. ${r||""} Free. Comment "SEAT" and I'll send the link.`,dm_invite:`Hey {{first_name}} — I'm running a short session called "${t}" on ${n}. Thought of you because of ${s.problem_solved||"what we talked about"}. Want the link?`,reminder:`Hi {{first_name}} — quick reminder that ${t} starts ${n}. Here's the link: {{join_link}}. Bring one question.`,follow_up:`Hi {{first_name}} — thanks for joining ${t}. Here's the recording and the workbook: {{resource_link}}. One thing to try this week: ${s.desired_outcome||"pick a single takeaway and run it."} Happy to walk through it one-on-one if useful.`}}function shn(s){const t=[`RUN OF SHOW — ${s.title||"Masterclass"}`,""];let n=0;return t.push("0:00 Welcome, why we're here, one-line promise"),n+=3,(s.curriculum??[]).forEach(r=>{t.push("",`${GG(n)} SECTION: ${r.title}`),r.lessons.forEach(a=>{t.push(`${GG(n)} ${a.title}${a.minutes?` (${a.minutes}m)`:""}${a.talking_points?` — ${a.talking_points}`:""}`),n+=a.minutes??5})}),t.push("",`${GG(n)} Q&A`,`${GG(n+7)} Close: next step + resource kit`),t.join(` `)}function GG(s){const t=Math.floor(s/60),n=s%60;return`${t}:${String(n).padStart(2,"0")}`}function nhn(){const{items:s,isLoading:t,create:n,duplicate:r,remove:a}=Xun(),i=Ln(),[l,o]=N.useState(!1),c=s.filter(p=>!p.is_archived),d=s.filter(p=>p.is_archived),u=async()=>{const p=await n.mutateAsync({title:"Untitled masterclass"});i(`/attract/provide/masterclasses/${p.id}`)},h=async p=>{const f=ket.find(_=>_.key===p),y=await n.mutateAsync(ehn(f));i(`/attract/provide/masterclasses/${y.id}`)};return t?e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-28 rounded-2xl"}),e.jsx(Ws,{className:"h-64 rounded-2xl"})]}):e.jsxs("div",{className:"space-y-6",children:[e.jsx(zu,{eyebrow:"Pillar 03 · Provide",title:"Masterclass Builder",description:"Turn what you already know into a 45-minute teaching moment agents actually attend — curriculum, assets, promotion, run-of-show, and follow-up.",actions:e.jsxs("div",{className:"flex gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>o(p=>!p),children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),"Starter templates"]}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:u,disabled:n.isPending,children:[e.jsx(Is,{className:"h-4 w-4 mr-2"}),"New masterclass"]})]})}),(l||s.length===0)&&e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-3",children:"Starter templates"}),e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-4 gap-3",children:ket.map(p=>e.jsxs("button",{onClick:()=>h(p.key),className:"text-left p-4 rounded-xl border hover:border-violet-300 hover:shadow-sm transition",children:[e.jsx(Ue,{variant:"secondary",className:"capitalize mb-2",children:p.pillar}),e.jsx("div",{className:"font-semibold text-[14px] text-slate-900",children:p.title}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1 line-clamp-3",children:p.promise}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-2",children:[p.duration_minutes," min · ",p.curriculum.length," sections"]})]},p.key))})]}),c.length===0?e.jsxs(fe,{className:"p-10 rounded-2xl text-center",children:[e.jsx(yd,{className:"h-8 w-8 mx-auto text-violet-500"}),e.jsx("div",{className:"text-[16px] font-semibold mt-3",children:"No masterclasses yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-500 mt-1 max-w-md mx-auto",children:"Pick a starter template above or build one from scratch. Nothing sends automatically — every piece of copy stays an editable draft."})]}):e.jsx("div",{className:"grid sm:grid-cols-2 xl:grid-cols-3 gap-3",children:c.map(p=>e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-2",children:[e.jsx(Ue,{variant:"outline",className:"capitalize rounded-full",children:p.status}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{variant:"ghost",size:"icon",className:"rounded-full h-7 w-7",children:e.jsx(Kf,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",children:[e.jsx(Kr,{onClick:()=>i(`/attract/provide/masterclasses/${p.id}`),children:"Open builder"}),e.jsxs(Kr,{onClick:()=>r.mutate(p),children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-2"}),"Duplicate"]}),e.jsxs(Kr,{className:"text-destructive",onClick:()=>a.mutate(p.id),children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-2"}),"Delete"]})]})]})]}),e.jsxs(In,{to:`/attract/provide/masterclasses/${p.id}`,className:"block mt-2",children:[e.jsx("div",{className:"font-semibold text-slate-900 line-clamp-2",children:p.title}),p.promise&&e.jsx("div",{className:"text-[12.5px] text-slate-500 line-clamp-2 mt-1",children:p.promise})]}),e.jsxs("div",{className:"text-[11.5px] text-slate-400 mt-3",children:[(p.curriculum??[]).length," sections · ",p.duration_minutes??45," min",p.delivery_date&&` · ${Ss(new Date(p.delivery_date),"MMM d")}`]})]},p.id))}),d.length>0&&e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2 flex items-center gap-1.5",children:[e.jsx(tm,{className:"h-3.5 w-3.5"}),"Archived"]}),e.jsx("div",{className:"flex flex-wrap gap-2",children:d.map(p=>e.jsx(In,{to:`/attract/provide/masterclasses/${p.id}`,className:"text-[12.5px] px-2.5 py-1 rounded-full border text-slate-600",children:p.title},p.id))})]}),e.jsx(l6,{})]})}const Cet=q,rhn=["Strategy","Curriculum","Assets","Promotion","Delivery","Follow-up"];function ahn(){var Y,W,ee,se,oe,he,ce,me,le,ve,ge,Te,Ie;const{masterclassId:s}=bi(),t=Ln(),{user:n}=vs(),{masterclass:r,isLoading:a,save:i}=Jun(s),l=Xkt(),{create:o}=AR(),[c,d]=N.useState(null),[u,h]=N.useState(0),[p,f]=N.useState(!1),[y,_]=N.useState("idle"),v=N.useRef(null),j=N.useRef(!1);N.useEffect(()=>{r&&!c&&d(r)},[r,c]);const w=Ce=>{d(Me=>Me&&{...Me,...Ce}),j.current=!0,_("saving"),clearTimeout(v.current),v.current=setTimeout(()=>S({...c??{},...Ce}),900)},S=async Ce=>{const{id:Me,user_id:Pe,created_at:Re,updated_at:Ae,...Be}=Ce;await i.mutateAsync(Be),j.current=!1,_("saved"),setTimeout(()=>_(we=>we==="saved"?"idle":we),1800)},A=(c==null?void 0:c.curriculum)??[],E=Ce=>w({curriculum:Ce}),O=N.useMemo(()=>A.reduce((Ce,Me)=>Ce+Me.lessons.reduce((Pe,Re)=>Pe+(Re.minutes??0),0),0),[A]);if(a||!c)return e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-24 rounded-2xl"}),e.jsx(Ws,{className:"h-96 rounded-2xl"})]});const D=()=>{w({promotion:{...c.promotion,...thn(c)}}),ae.success("Draft copy generated — edit before you send anything")},I=()=>{w({delivery:{...c.delivery,run_of_show:shn(c)}}),ae.success("Run of show generated")},F=async()=>{const Ce=await l.mutateAsync({title:c.title,description:c.promise??void 0,event_type:"masterclass",intended_audience:c.target_audience??void 0,related_pillar:c.pillar??"provide",starts_at:c.delivery_date??new Date(Date.now()+12096e5).toISOString(),format:c.format==="in_person"?"in_person":"virtual",agenda:A.flatMap(Me=>Me.lessons.map(Pe=>({item:`${Me.title}: ${Pe.title}`}))),learning_outcomes:c.desired_outcome?[c.desired_outcome]:[]});await i.mutateAsync({linked_event_id:Ce.id,status:"scheduled"}),d(Me=>Me&&{...Me,linked_event_id:Ce.id,status:"scheduled"}),ae.success("Connect event created as a draft"),t(`/attract/events/${Ce.id}/edit`)},z=async()=>{var Pe,Re,Ae,Be,we;const Ce=await o.mutateAsync({title:`${c.title} — Resource Kit`,description:c.promise??void 0,audience:c.target_audience??void 0,pillar:c.pillar??"provide",intro_text:((Pe=c.assets)==null?void 0:Pe.workbook)??void 0,cta_label:((Re=c.assets)==null?void 0:Re.cta_label)??void 0,cta_url:((Ae=c.assets)==null?void 0:Ae.cta_url)??void 0}),Me=[...(((Be=c.assets)==null?void 0:Be.downloads)??[]).map((Je,ke)=>({type:"link",title:Je.title,url:Je.url,sort_order:ke})),...(((we=c.assets)==null?void 0:we.videos)??[]).map((Je,ke)=>({type:"video",title:Je.title,url:Je.url,sort_order:100+ke}))];Me.length&&await Cet.from("attract_resource_kit_items").insert(Me.map(Je=>({...Je,kit_id:Ce.id,user_id:n.id}))),await i.mutateAsync({linked_kit_id:Ce.id}),d(Je=>Je&&{...Je,linked_kit_id:Ce.id}),ae.success("Resource Kit created from your assets"),t(`/attract/provide/kits/${Ce.id}/edit`)},H=async()=>{const Ce=Date.now(),Me=[{title:`Send recap + resources: ${c.title}`,due_at:new Date(Ce+1*864e5).toISOString()},{title:`Personal check-in with attendees: ${c.title}`,due_at:new Date(Ce+3*864e5).toISOString()},{title:`Invite engaged attendees to a 1:1: ${c.title}`,due_at:new Date(Ce+7*864e5).toISOString()}],{error:Pe}=await Cet.from("attract_follow_ups").insert(Me.map(Re=>({...Re,user_id:n.id,touch_type:"masterclass",priority:"medium"})));if(Pe){ae.error(Pe.message);return}ae.success("3 follow-ups added to your Follow-Up Center")};return e.jsxs("div",{className:"space-y-5",children:[e.jsx(B,{variant:"ghost",size:"sm",className:"rounded-full -ml-2",asChild:!0,children:e.jsxs(In,{to:"/attract/provide/masterclasses",children:[e.jsx(qr,{className:"h-3.5 w-3.5 mr-1.5"}),"All masterclasses"]})}),e.jsx(zu,{eyebrow:"Pillar 03 · Provide",title:c.title||"Untitled masterclass",description:c.promise??"Build the promise, curriculum, assets, promotion, delivery and follow-up.",actions:e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[12px] text-slate-500 inline-flex items-center gap-1.5",children:y==="saving"?e.jsxs(e.Fragment,{children:[e.jsx(rs,{className:"h-3.5 w-3.5 animate-spin"}),"Saving…"]}):y==="saved"?e.jsxs(e.Fragment,{children:[e.jsx(Lr,{className:"h-3.5 w-3.5 text-emerald-600"}),"Saved"]}):"All changes saved"}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:()=>f(Ce=>!Ce),children:[e.jsx(Sr,{className:"h-4 w-4 mr-2"}),p?"Edit":"Preview"]})]})}),e.jsx(fe,{className:"p-2 rounded-2xl flex gap-1 overflow-x-auto",children:rhn.map((Ce,Me)=>e.jsxs("button",{onClick:()=>{f(!1),h(Me)},className:`px-3.5 py-2 rounded-xl text-[13px] font-medium whitespace-nowrap ${u===Me&&!p?"bg-violet-600 text-white":"text-slate-600 hover:bg-slate-100"}`,children:[Me+1,". ",Ce]},Ce))}),p?e.jsx(ohn,{m:c}):e.jsxs(fe,{className:"p-5 rounded-2xl space-y-4",children:[u===0&&e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Yu,{label:"Title",className:"sm:col-span-2",children:e.jsx(ye,{value:c.title,onChange:Ce=>w({title:Ce.target.value})})}),e.jsx(Yu,{label:"The promise",className:"sm:col-span-2",children:e.jsx(Ms,{rows:2,value:c.promise??"",onChange:Ce=>w({promise:Ce.target.value}),placeholder:"Walk out with…"})}),e.jsx(Yu,{label:"Target audience",children:e.jsx(ye,{value:c.target_audience??"",onChange:Ce=>w({target_audience:Ce.target.value})})}),e.jsx(Yu,{label:"Problem solved",children:e.jsx(ye,{value:c.problem_solved??"",onChange:Ce=>w({problem_solved:Ce.target.value})})}),e.jsx(Yu,{label:"Desired outcome",className:"sm:col-span-2",children:e.jsx(ye,{value:c.desired_outcome??"",onChange:Ce=>w({desired_outcome:Ce.target.value})})}),e.jsx(Yu,{label:"Pillar",children:e.jsxs(us,{value:c.pillar??"provide",onValueChange:Ce=>w({pillar:Ce}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:["produce","influence","provide","connect"].map(Ce=>e.jsx(Ze,{value:Ce,className:"capitalize",children:Ce},Ce))})]})}),e.jsx(Yu,{label:"Format",children:e.jsxs(us,{value:c.format??"virtual",onValueChange:Ce=>w({format:Ce}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:["virtual","in_person","hybrid"].map(Ce=>e.jsx(Ze,{value:Ce,className:"capitalize",children:Ce.replace("_"," ")},Ce))})]})}),e.jsx(Yu,{label:"Duration (minutes)",children:e.jsx(ye,{type:"number",value:c.duration_minutes??45,onChange:Ce=>w({duration_minutes:Number(Ce.target.value)})})}),e.jsx(Yu,{label:"Delivery date",children:e.jsx(ye,{type:"datetime-local",value:ihn(c.delivery_date),onChange:Ce=>w({delivery_date:Ce.target.value?new Date(Ce.target.value).toISOString():null})})}),e.jsx(Yu,{label:"Status",children:e.jsxs(us,{value:c.status,onValueChange:Ce=>w({status:Ce}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:["draft","ready","scheduled","delivered","archived"].map(Ce=>e.jsx(Ze,{value:Ce,className:"capitalize",children:Ce},Ce))})]})})]}),u===1&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"text-[12.5px] text-slate-500",children:[A.length," sections · ",O," minutes planned"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>E([...A,{id:crypto.randomUUID(),title:"New section",lessons:[]}]),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Add section"]})]}),A.length===0&&e.jsx("div",{className:"text-[13.5px] text-slate-500 border border-dashed rounded-xl p-8 text-center",children:"No sections yet. Add your first one."}),A.map((Ce,Me)=>e.jsxs(fe,{className:"p-4 rounded-xl bg-slate-50/60",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:Ce.title,onChange:Pe=>E(A.map(Re=>Re.id===Ce.id?{...Re,title:Pe.target.value}:Re)),className:"font-semibold"}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Me===0,onClick:()=>E(WG(A,Me,Me-1)),children:e.jsx(ex,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Me===A.length-1,onClick:()=>E(WG(A,Me,Me+1)),children:e.jsx(ao,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>E(A.filter(Pe=>Pe.id!==Ce.id)),children:e.jsx(_n,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"mt-3 space-y-3",children:[Ce.lessons.map((Pe,Re)=>e.jsxs("div",{className:"rounded-lg border bg-white p-3 space-y-2",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:Pe.title,placeholder:"Lesson title",onChange:Ae=>Z(Ce.id,Pe.id,{title:Ae.target.value})}),e.jsx(ye,{type:"number",className:"w-20",value:Pe.minutes??"",placeholder:"min",onChange:Ae=>Z(Ce.id,Pe.id,{minutes:Number(Ae.target.value)})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Re===0,onClick:()=>E(A.map(Ae=>Ae.id===Ce.id?{...Ae,lessons:WG(Ae.lessons,Re,Re-1)}:Ae)),children:e.jsx(ex,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",disabled:Re===Ce.lessons.length-1,onClick:()=>E(A.map(Ae=>Ae.id===Ce.id?{...Ae,lessons:WG(Ae.lessons,Re,Re+1)}:Ae)),children:e.jsx(ao,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>E(A.map(Ae=>Ae.id===Ce.id?{...Ae,lessons:Ae.lessons.filter(Be=>Be.id!==Pe.id)}:Ae)),children:e.jsx(_n,{className:"h-4 w-4"})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-2",children:[e.jsx(Ms,{rows:2,placeholder:"Talking points",value:Pe.talking_points??"",onChange:Ae=>Z(Ce.id,Pe.id,{talking_points:Ae.target.value})}),e.jsx(Ms,{rows:2,placeholder:"Exercise",value:Pe.exercise??"",onChange:Ae=>Z(Ce.id,Pe.id,{exercise:Ae.target.value})}),e.jsx(Ms,{rows:2,placeholder:"Example / story",value:Pe.example??"",onChange:Ae=>Z(Ce.id,Pe.id,{example:Ae.target.value})}),e.jsx(Ms,{rows:2,placeholder:"Speaker notes",value:Pe.speaker_notes??"",onChange:Ae=>Z(Ce.id,Pe.id,{speaker_notes:Ae.target.value})})]})]},Pe.id)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>E(A.map(Pe=>Pe.id===Ce.id?{...Pe,lessons:[...Pe.lessons,{id:crypto.randomUUID(),title:""}]}:Pe)),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Add lesson"]})]})]},Ce.id))]}),u===2&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Yu,{label:"Slide outline",children:e.jsx(Ms,{rows:5,value:((Y=c.assets)==null?void 0:Y.slide_outline)??"",onChange:Ce=>w({assets:{...c.assets,slide_outline:Ce.target.value}})})}),e.jsx(Yu,{label:"Workbook / checklist outline",children:e.jsx(Ms,{rows:5,value:((W=c.assets)==null?void 0:W.workbook)??"",onChange:Ce=>w({assets:{...c.assets,workbook:Ce.target.value}})})}),e.jsx(Tet,{label:"Downloads",items:((ee=c.assets)==null?void 0:ee.downloads)??[],onChange:Ce=>w({assets:{...c.assets,downloads:Ce}})}),e.jsx(Tet,{label:"Videos",items:((se=c.assets)==null?void 0:se.videos)??[],onChange:Ce=>w({assets:{...c.assets,videos:Ce}})}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsx(Yu,{label:"CTA label",children:e.jsx(ye,{value:((oe=c.assets)==null?void 0:oe.cta_label)??"",onChange:Ce=>w({assets:{...c.assets,cta_label:Ce.target.value}})})}),e.jsx(Yu,{label:"CTA URL",children:e.jsx(ye,{value:((he=c.assets)==null?void 0:he.cta_url)??"",onChange:Ce=>w({assets:{...c.assets,cta_url:Ce.target.value}})})})]}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:z,disabled:o.isPending,children:[e.jsx(a9,{className:"h-4 w-4 mr-2"}),"Create Resource Kit from these assets"]}),c.linked_kit_id&&e.jsx(Ue,{variant:"outline",className:"ml-2",children:"Kit linked"})]}),u===3&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between flex-wrap gap-2",children:[e.jsx("div",{className:"text-[12.5px] text-slate-500",children:"Every piece stays an editable draft. Nothing sends automatically."}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:D,children:[e.jsx(Im,{className:"h-4 w-4 mr-2"}),"Generate draft copy"]})]}),[["registration_copy","Registration page copy"],["email_invite","Email invite"],["social_post","Social post"],["dm_invite","DM / text invite"],["reminder","Reminder message"],["follow_up","Follow-up message"]].map(([Ce,Me])=>{var Pe;return e.jsx(Yu,{label:Me,children:e.jsx(Ms,{rows:5,value:((Pe=c.promotion)==null?void 0:Pe[Ce])??"",onChange:Re=>w({promotion:{...c.promotion,[Ce]:Re.target.value}})})},Ce)})]}),u===4&&e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"flex justify-end",children:e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:I,children:[e.jsx(Im,{className:"h-4 w-4 mr-2"}),"Build run of show"]})}),e.jsx(Yu,{label:"Run of show",children:e.jsx(Ms,{rows:12,className:"font-mono text-[12.5px]",value:((ce=c.delivery)==null?void 0:ce.run_of_show)??"",onChange:Ce=>w({delivery:{...c.delivery,run_of_show:Ce.target.value}})})}),e.jsx(Yu,{label:"Check-in link",children:e.jsx(ye,{value:((me=c.delivery)==null?void 0:me.checkin_link)??"",onChange:Ce=>w({delivery:{...c.delivery,checkin_link:Ce.target.value}}),placeholder:"Paste the Connect event check-in URL"})}),e.jsx(Yu,{label:"Event notes",children:e.jsx(Ms,{rows:4,value:((le=c.delivery)==null?void 0:le.event_notes)??"",onChange:Ce=>w({delivery:{...c.delivery,event_notes:Ce.target.value}})})}),e.jsxs("div",{className:"flex flex-wrap gap-2",children:[e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:F,disabled:l.isPending,children:[e.jsx(Lg,{className:"h-4 w-4 mr-2"}),"Convert to a Connect event"]}),c.linked_event_id&&e.jsx(B,{variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsx(In,{to:`/attract/events/${c.linked_event_id}`,children:"Open linked event"})})]})]}),u===5&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(Yu,{label:"Attendee segmentation",children:e.jsx(Ms,{rows:3,value:((ve=c.follow_up)==null?void 0:ve.segments)??"",onChange:Ce=>w({follow_up:{...c.follow_up,segments:Ce.target.value}}),placeholder:"Attended + asked a question / attended / registered no-show"})}),e.jsx(Yu,{label:"Resource kit sharing note",children:e.jsx(Ms,{rows:3,value:((ge=c.follow_up)==null?void 0:ge.kit_note)??"",onChange:Ce=>w({follow_up:{...c.follow_up,kit_note:Ce.target.value}})})}),e.jsx(Yu,{label:"Suggested personal follow-ups",children:e.jsx(Ms,{rows:3,value:((Te=c.follow_up)==null?void 0:Te.personal_touches)??"",onChange:Ce=>w({follow_up:{...c.follow_up,personal_touches:Ce.target.value}})})}),e.jsx(Yu,{label:"Conversion / relationship outcomes",children:e.jsx(Ms,{rows:3,value:((Ie=c.follow_up)==null?void 0:Ie.outcomes)??"",onChange:Ce=>w({follow_up:{...c.follow_up,outcomes:Ce.target.value}})})}),e.jsxs(B,{variant:"outline",className:"rounded-full",onClick:H,children:[e.jsx(lu,{className:"h-4 w-4 mr-2"}),"Add 3 follow-ups to Follow-Up Center"]})]})]})]});function Z(Ce,Me,Pe){E(A.map(Re=>Re.id===Ce?{...Re,lessons:Re.lessons.map(Ae=>Ae.id===Me?{...Ae,...Pe}:Ae)}:Re))}}function WG(s,t,n){const r=[...s],[a]=r.splice(t,1);return r.splice(n,0,a),r}function ihn(s){if(!s)return"";const t=new Date(s);return new Date(t.getTime()-t.getTimezoneOffset()*6e4).toISOString().slice(0,16)}function Yu({label:s,children:t,className:n}){return e.jsxs("div",{className:n,children:[e.jsx(ne,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),t]})}function Tet({label:s,items:t,onChange:n}){return e.jsxs("div",{children:[e.jsx(ne,{className:"text-[12px] text-slate-600 mb-1 block",children:s}),e.jsxs("div",{className:"space-y-2",children:[t.map((r,a)=>e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:r.title,placeholder:"Title",onChange:i=>n(t.map((l,o)=>o===a?{...l,title:i.target.value}:l))}),e.jsx(ye,{value:r.url,placeholder:"https://",onChange:i=>n(t.map((l,o)=>o===a?{...l,url:i.target.value}:l))}),e.jsx(B,{variant:"ghost",size:"icon",className:"text-destructive",onClick:()=>n(t.filter((i,l)=>l!==a)),children:e.jsx(_n,{className:"h-4 w-4"})})]},a)),e.jsxs(B,{size:"sm",variant:"ghost",onClick:()=>n([...t,{title:"",url:""}]),children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1.5"}),"Add ",s.toLowerCase().slice(0,-1)]})]})]})}function ohn({m:s}){var t,n,r;return e.jsxs("div",{className:"grid lg:grid-cols-2 gap-4",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Curriculum"}),(s.curriculum??[]).length===0?e.jsx("div",{className:"text-[13px] text-slate-500",children:"Nothing yet."}):(s.curriculum??[]).map(a=>e.jsxs("div",{className:"mb-3",children:[e.jsx("div",{className:"font-semibold text-[14px]",children:a.title}),e.jsx("ul",{className:"mt-1 space-y-1",children:a.lessons.map(i=>e.jsxs("li",{className:"text-[13px] text-slate-600",children:["• ",i.title,i.minutes?` (${i.minutes}m)`:""]},i.id))})]},a.id))]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Workbook outline"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((t=s.assets)==null?void 0:t.workbook)||"Nothing yet."})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Registration copy"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap text-slate-700",children:((n=s.promotion)==null?void 0:n.registration_copy)||"Nothing yet."})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-violet-700 font-semibold mb-2",children:"Presenter run of show"}),e.jsx("pre",{className:"text-[12.5px] whitespace-pre-wrap font-mono text-slate-700",children:((r=s.delivery)==null?void 0:r.run_of_show)||"Nothing yet."})]})]})}const tS=q;function HU(s,t={}){const{orderBy:n="created_at",ascending:r=!1,titleField:a="title",duplicateOverrides:i={},label:l="Record"}=t,{user:o}=vs(),c=Kt(),d=[s,o==null?void 0:o.id],u=dt({queryKey:d,enabled:!!o,queryFn:async()=>{const{data:j,error:w}=await tS.from(s).select("*").order(n,{ascending:r,nullsFirst:!1});if(w)throw w;return j??[]}}),h=()=>{c.invalidateQueries({queryKey:[s]}),c.invalidateQueries({queryKey:["attract-followups"]}),c.invalidateQueries({queryKey:["attract-activities"]})},p=yt({mutationFn:async j=>{const{data:w,error:S}=await tS.from(s).insert({...j,user_id:o.id}).select("*").single();if(S)throw S;return w},onSuccess:()=>{h(),ae.success(`${l} saved`)},onError:j=>ae.error(j.message)}),f=yt({mutationFn:async({id:j,...w})=>{const{error:S}=await tS.from(s).update(w).eq("id",j);if(S)throw S},onSuccess:()=>{h(),ae.success("Updated")},onError:j=>ae.error(j.message)}),y=yt({mutationFn:async j=>{const{id:w,created_at:S,updated_at:A,user_id:E,...O}=j,D={...O,...i,user_id:o.id};a&&D[a]&&(D[a]=`${D[a]} (copy)`);const{data:I,error:F}=await tS.from(s).insert(D).select("id").single();if(F)throw F;return I},onSuccess:()=>{h(),ae.success("Duplicated")},onError:j=>ae.error(j.message)}),_=yt({mutationFn:async({id:j,archived:w})=>{const{error:S}=await tS.from(s).update({is_archived:w}).eq("id",j);if(S)throw S},onSuccess:(j,w)=>{h(),ae.success(w.archived?"Archived":"Restored")},onError:j=>ae.error(j.message)}),v=yt({mutationFn:async j=>{const{error:w}=await tS.from(s).delete().eq("id",j);if(w)throw w},onSuccess:()=>{h(),ae.success("Deleted")},onError:j=>ae.error(j.message)});return{items:u.data??[],isLoading:u.isLoading,error:u.error,refetch:u.refetch,create:p,update:f,duplicate:y,archive:_,remove:v,userId:o==null?void 0:o.id}}function ebe(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async({title:n,dueAt:r,notes:a,touchType:i="task",agentId:l})=>{const{error:o}=await tS.from("attract_follow_ups").insert({user_id:s.id,title:n,due_at:r??null,notes:a??null,touch_type:i,priority:"medium",agent_id:l??null});if(o)throw o},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-followups"]}),t.invalidateQueries({queryKey:["attract-daily-plan"]}),ae.success("Added to Follow-Up Center & Today’s Plan")},onError:n=>ae.error(n.message)})}function GU(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async({title:n,description:r,pillar:a="produce",activityType:i="tool_action",agentId:l,metadata:o})=>{const{error:c}=await tS.rpc("award_attract_activity",{_user_id:s.id,_activity_type:i,_title:n,_description:r??null,_pillar:a,_agent_id:l??null,_metadata:o??{},_dedupe_minutes:5});if(c)throw c},onSuccess:()=>{t.invalidateQueries({queryKey:["attract-activities"]}),t.invalidateQueries({queryKey:["attract-score"]})},onError:n=>ae.error(n.message)})}const lhn=["annual","quarterly","monthly"],ZI=[{key:"closings",label:"Closings",target:"closings_target",actual:"closings_actual",format:"number"},{key:"gci",label:"GCI",target:"gci_target",actual:"gci_actual",format:"currency"},{key:"volume",label:"Volume",target:"volume_target",actual:"volume_actual",format:"currency"},{key:"listings",label:"Listings",target:"listings_target",actual:"listings_actual",format:"number"},{key:"buyer_sides",label:"Buyer Sides",target:"buyer_sides_target",actual:"buyer_sides_actual",format:"number"},{key:"appointments",label:"Appointments",target:"appointments_target",actual:"appointments_actual",format:"number"}];function QI(s){return s.period_type==="quarterly"?`Q${s.quarter??1} ${s.year}`:s.period_type==="monthly"?`${new Date(2e3,(s.month??1)-1,1).toLocaleString("en-US",{month:"long"})} ${s.year}`:`${s.year}`}function chn(s,t=new Date){let n,r;if(s.period_type==="monthly"){const l=(s.month??1)-1;n=new Date(s.year,l,1),r=new Date(s.year,l+1,1)}else if(s.period_type==="quarterly"){const l=(s.quarter??1)-1;n=new Date(s.year,l*3,1),r=new Date(s.year,l*3+3,1)}else n=new Date(s.year,0,1),r=new Date(s.year+1,0,1);const a=r.getTime()-n.getTime(),i=t.getTime()-n.getTime();return Math.max(0,Math.min(1,i/a))}function dhn(s,t){if(!s)return!1;const[n,r]=s.split(/[-/T]/).map(Number);return n!==t.year?!1:t.period_type==="monthly"?r===t.month:t.period_type==="quarterly"?Math.ceil(r/3)===t.quarter:!0}function uhn(){const s=HU("attract_production_goals",{orderBy:"year",ascending:!1,titleField:"label",label:"Goal",duplicateOverrides:{closings_actual:0,gci_actual:0,volume_actual:0,listings_actual:0,buyer_sides_actual:0,appointments_actual:0,is_archived:!1}}),{transactions:t}=SSt(),n=ebe(),r=GU(),a=N.useMemo(()=>{const i={};return s.items.forEach(l=>{i[l.id]={closings:t.filter(o=>dhn(o.closing_date,l)).length}}),i},[s.items,t]);return{...s,goals:s.items,autoProgress:a,quickTask:n,logActivity:r}}function hhn(s){const t=Number(s??0);return t?{monthly:t/12,weekly:t/52}:null}const mhn=Array.from({length:12},(s,t)=>({value:t+1,label:new Date(2e3,t,1).toLocaleString("en-US",{month:"long"})}));function u2(s,t){return Number.isFinite(s)?t==="currency"?s>=1e3?`$${Math.round(s).toLocaleString()}`:`$${s.toFixed(0)}`:Number.isInteger(s)?String(s):s.toFixed(1):"—"}function phn({pct:s,size:t=92}){const n=(t-12)/2,r=2*Math.PI*n,a=Math.max(0,Math.min(1,s));return e.jsxs("svg",{width:t,height:t,className:"-rotate-90 flex-shrink-0",children:[e.jsx("circle",{cx:t/2,cy:t/2,r:n,stroke:"#ede9fe",strokeWidth:9,fill:"none"}),e.jsx("circle",{cx:t/2,cy:t/2,r:n,stroke:"#7c3aed",strokeWidth:9,fill:"none",strokeLinecap:"round",strokeDasharray:r,strokeDashoffset:r*(1-a)})]})}const Eet={period_type:"annual",year:new Date().getFullYear(),quarter:1,month:new Date().getMonth()+1,use_auto_progress:!0};function fhn(){const{goals:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,autoProgress:d,quickTask:u,logActivity:h}=uhn(),[p,f]=N.useState(!1),[y,_]=N.useState(null),[v,j]=N.useState(null),[w,S]=N.useState(null),A=N.useMemo(()=>s.filter(I=>p?I.is_archived:!I.is_archived),[s,p]),E=(I,F)=>{var H;const z=Number(I[F.actual]??0);return I.use_auto_progress&&F.key==="closings"?Math.max(z,((H=d[I.id])==null?void 0:H.closings)??0):z},O=async()=>{var F;if(!y)return;const I={label:((F=y.label)==null?void 0:F.trim())||null,period_type:y.period_type??"annual",year:Number(y.year)||new Date().getFullYear(),quarter:y.period_type==="quarterly"?Number(y.quarter)||1:null,month:y.period_type==="monthly"?Number(y.month)||1:null,closings_target:y.closings_target??null,gci_target:y.gci_target??null,volume_target:y.volume_target??null,listings_target:y.listings_target??null,buyer_sides_target:y.buyer_sides_target??null,appointments_target:y.appointments_target??null,use_auto_progress:y.use_auto_progress??!0,notes:y.notes??null};y.id?await i.mutateAsync({id:y.id,...I}):await a.mutateAsync(I),_(null)},D=async()=>{if(!v)return;const I={};ZI.forEach(F=>{I[F.actual]=Number(v[F.actual]??0)}),await i.mutateAsync({id:v.id,...I}),await h.mutateAsync({title:`Updated production progress — ${QI(v)}`,pillar:"produce",activityType:"goal_progress"}),j(null)};return e.jsxs("div",{children:[e.jsxs(In,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(zu,{eyebrow:"Produce → Tool",title:"Production Goals",description:"Set the annual, quarterly, and monthly numbers you're playing for — then track pace, not just totals. Progress can be updated manually or pulled from the transactions you log.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>f(I=>!I),children:p?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...Eet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," New Goal"]})]})}),t&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:[0,1].map(I=>e.jsx(Ws,{className:"h-56 rounded-2xl"},I))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Bi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load your goals"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Ac,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:p?"No archived goals":"No production goals yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one annual goal. Attract will break it into monthly and weekly activity targets and show whether you're ahead or behind pace."}),!p&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>_({...Eet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Create your first goal"]})]}),e.jsx("div",{className:"grid gap-4 md:grid-cols-2",children:A.map(I=>{const F=chn(I),z=ZI.find(oe=>I[oe.target])??ZI[0],H=Number(I[z.target]??0),Z=E(I,z),Y=H?Z/H:0,W=H*F,ee=Z>=W,se=hhn(H);return e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[16px] font-semibold text-slate-900",children:I.label||`${QI(I)} Goals`}),e.jsx(Ue,{variant:"outline",className:"rounded-full capitalize",children:I.period_type}),e.jsx(Ue,{variant:"outline",className:"rounded-full",children:QI(I)})]}),I.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:I.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>_(I),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(I),children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:I.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:I.id,archived:!I.is_archived}),children:e.jsx(tm,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>S(I),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-4 mt-4",children:[e.jsxs("div",{className:"relative",children:[e.jsx(phn,{pct:Y}),e.jsx("div",{className:"absolute inset-0 grid place-items-center",children:e.jsxs("div",{className:"text-[15px] font-semibold tabular-nums text-slate-900",children:[Math.round(Y*100),"%"]})})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[12px] uppercase tracking-wider text-slate-500",children:z.label}),e.jsxs("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:[u2(Z,z.format)," ",e.jsxs("span",{className:"text-slate-400 text-[15px]",children:["/ ",u2(H,z.format)]})]}),e.jsxs("div",{className:`text-[12.5px] mt-0.5 font-medium ${ee?"text-emerald-600":"text-amber-600"}`,children:[ee?"Ahead of pace":"Behind pace"," · pace target ",u2(W,z.format)," (",Math.round(F*100),"% of period elapsed)"]})]})]}),e.jsx("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-2 mt-4",children:ZI.filter(oe=>I[oe.target]).map(oe=>{const he=Number(I[oe.target]),ce=E(I,oe);return e.jsxs("div",{className:"rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-wider text-slate-500",children:oe.label}),e.jsxs("div",{className:"text-[13.5px] font-semibold tabular-nums text-slate-900",children:[u2(ce,oe.format)," / ",u2(he,oe.format)]}),e.jsx("div",{className:"h-1.5 rounded-full bg-slate-200 mt-1.5 overflow-hidden",children:e.jsx("div",{className:"h-full bg-violet-600",style:{width:`${Math.min(100,he?ce/he*100:0)}%`}})})]},oe.key)})}),I.period_type==="annual"&&se&&e.jsxs("div",{className:"mt-3 rounded-xl border border-violet-100 bg-violet-50/60 px-3.5 py-2.5 text-[12.5px] text-violet-900",children:["Break it down: ",e.jsx("strong",{children:u2(se.monthly,z.format)})," per month ·"," ",e.jsx("strong",{children:u2(se.weekly,z.format)})," per week of ",z.label.toLowerCase(),"."]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>j({...I}),children:"Update progress"}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>u.mutate({title:`Goal push: ${z.label} — ${u2(se?se.weekly:H,z.format)} this week`,dueAt:new Date().toISOString(),notes:`From ${QI(I)} production goal`,touchType:"goal"}),children:[e.jsx(lu,{className:"h-3.5 w-3.5 mr-1.5"})," Add to Today's Plan"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>h.mutate({title:`Win logged toward ${QI(I)} goals`,pillar:"produce",activityType:"goal_win"}),children:[e.jsx(xo,{className:"h-3.5 w-3.5 mr-1.5"})," Log a win"]})]})]},I.id)})}),e.jsx(_s,{open:!!y,onOpenChange:I=>!I&&_(null),children:e.jsxs(bs,{className:"max-w-2xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:y!=null&&y.id?"Edit goal":"New production goal"}),e.jsx(Jn,{children:"Only fill in the targets you actually track. Blank targets are hidden."})]}),y&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Label (optional)"}),e.jsx(ye,{value:y.label??"",onChange:I=>_({...y,label:I.target.value}),placeholder:"e.g. 2026 Big Rock"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Period"}),e.jsxs(us,{value:y.period_type,onValueChange:I=>_({...y,period_type:I}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:lhn.map(I=>e.jsx(Ze,{value:I,className:"capitalize",children:I},I))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Year"}),e.jsx(ye,{type:"number",value:y.year??"",onChange:I=>_({...y,year:Number(I.target.value)})})]}),y.period_type==="quarterly"&&e.jsxs("div",{children:[e.jsx(ne,{children:"Quarter"}),e.jsxs(us,{value:String(y.quarter??1),onValueChange:I=>_({...y,quarter:Number(I)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:[1,2,3,4].map(I=>e.jsxs(Ze,{value:String(I),children:["Q",I]},I))})]})]}),y.period_type==="monthly"&&e.jsxs("div",{children:[e.jsx(ne,{children:"Month"}),e.jsxs(us,{value:String(y.month??1),onValueChange:I=>_({...y,month:Number(I)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:mhn.map(I=>e.jsx(Ze,{value:String(I.value),children:I.label},I.value))})]})]})]}),e.jsx("div",{className:"grid sm:grid-cols-3 gap-3",children:ZI.map(I=>e.jsxs("div",{children:[e.jsxs(ne,{children:[I.label," target"]}),e.jsx(ye,{type:"number",value:y[I.target]??"",onChange:F=>_({...y,[I.target]:F.target.value===""?null:Number(F.target.value)})})]},I.key))}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Pull closings from logged transactions"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Uses the transactions in your Transaction-to-Relationship Tracker for this period."})]}),e.jsx(jn,{checked:y.use_auto_progress??!0,onCheckedChange:I=>_({...y,use_auto_progress:I})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Notes"}),e.jsx(Ms,{value:y.notes??"",onChange:I=>_({...y,notes:I.target.value}),rows:3})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>_(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:O,disabled:a.isPending||i.isPending,children:"Save goal"})]})]})}),e.jsx(_s,{open:!!v,onOpenChange:I=>!I&&j(null),children:e.jsxs(bs,{className:"max-w-lg",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Update progress"}),e.jsxs(Jn,{children:[v?QI(v):""," — enter your actuals to date."]})]}),v&&e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:ZI.filter(I=>v[I.target]).map(I=>e.jsxs("div",{children:[e.jsx(ne,{children:I.label}),e.jsx(ye,{type:"number",value:v[I.actual]??0,onChange:F=>j({...v,[I.actual]:Number(F.target.value)})})]},I.key))}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:D,children:"Save progress"})]})]})}),e.jsx(_s,{open:!!w,onOpenChange:I=>!I&&S(null),children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Delete this goal?"}),e.jsx(Jn,{children:"This can't be undone. Archive it instead if you want to keep the history."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(w.id),S(null)},children:"Delete"})]})]})})]})}const gke=[{value:"award",label:"Award"},{value:"ranking",label:"Ranking"},{value:"certification",label:"Certification"},{value:"milestone",label:"Milestone"},{value:"media",label:"Media Mention"},{value:"production",label:"Production Recognition"}];function xhn(){const s=HU("attract_awards",{orderBy:"awarded_on",ascending:!1,label:"Award",duplicateOverrides:{is_archived:!1}}),t=GU();return{...s,awards:s.items,logActivity:t}}const Aet={category:"award",status:"active",is_public:!0};function Met(s){if(!s)return"No date";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,n-1,r).toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function ghn(){const{awards:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,logActivity:d}=xhn(),[u,h]=N.useState(!1),[p,f]=N.useState("all"),[y,_]=N.useState(""),[v,j]=N.useState(null),[w,S]=N.useState(null),A=N.useMemo(()=>s.filter(D=>{if(u!==!!D.is_archived||p!=="all"&&D.category!==p)return!1;const I=y.toLowerCase().trim();return!I||`${D.title} ${D.issuer??""} ${D.description??""}`.toLowerCase().includes(I)}),[s,u,p,y]),E=async()=>{var I;if(!((I=v==null?void 0:v.title)!=null&&I.trim())){ae.error("Add a title");return}const D={title:v.title.trim(),issuer:v.issuer||null,awarded_on:v.awarded_on||null,category:v.category??"award",description:v.description||null,proof_url:v.proof_url||null,production_period:v.production_period||null,is_public:v.is_public??!0};v.id?await i.mutateAsync({id:v.id,...D}):(await a.mutateAsync(D),await d.mutateAsync({title:`Added recognition: ${D.title}`,pillar:"produce",activityType:"award_added"})),j(null)},O=D=>{var F;const I=[D.title,D.issuer&&`— ${D.issuer}`,D.awarded_on&&`(${Met(D.awarded_on)})`].filter(Boolean).join(" ");(F=navigator.clipboard)==null||F.writeText(I),ae.success("Proof point copied — paste it into Content Studio")};return e.jsxs("div",{children:[e.jsxs(In,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(zu,{eyebrow:"Produce → Tool",title:"Awards & Recognition",description:"Your credibility file. Keep every award, ranking, and certification in one place so proof points are ready when you write content or pitch a speaking slot.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>h(D=>!D),children:u?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>j({...Aet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add Recognition"]})]})}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(ye,{value:y,onChange:D=>_(D.target.value),placeholder:"Search recognitions",className:"max-w-xs rounded-full"}),e.jsxs(us,{value:p,onValueChange:f,children:[e.jsx(ls,{className:"w-[190px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All categories"}),gke.map(D=>e.jsx(Ze,{value:D.value,children:D.label},D.value))]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(D=>e.jsx(Ws,{className:"h-36 rounded-2xl"},D))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Bi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load recognitions"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&A.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(fc,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:u?"Nothing archived":"No recognitions logged yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add awards, production rankings, and designations. Copy any one of them as a proof point when writing authority content."}),!u&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>j({...Aet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add your first"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:A.map(D=>{var I;return e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15.5px] font-semibold text-slate-900",children:D.title}),e.jsx(Ue,{variant:"outline",className:"rounded-full capitalize",children:((I=gke.find(F=>F.value===D.category))==null?void 0:I.label)??D.category})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[D.issuer,Met(D.awarded_on),D.production_period].filter(Boolean).join(" · ")}),D.description&&e.jsx("p",{className:"text-[13px] text-slate-600 mt-2 line-clamp-3",children:D.description})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>j(D),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(D),children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:D.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:D.id,archived:!D.is_archived}),children:e.jsx(tm,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>S(D),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-4 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>O(D),children:[e.jsx(Tl,{className:"h-3.5 w-3.5 mr-1.5"})," Copy proof point"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(In,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Write about it"]})}),D.proof_url&&e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs("a",{href:D.proof_url,target:"_blank",rel:"noreferrer",children:["Proof ",e.jsx(tr,{className:"h-3 w-3 ml-1.5"})]})})]})]},D.id)})}),e.jsx(_s,{open:!!v,onOpenChange:D=>!D&&j(null),children:e.jsxs(bs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:v!=null&&v.id?"Edit recognition":"Add recognition"}),e.jsx(Jn,{children:"Keep it factual — this feeds the proof points you use publicly."})]}),v&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title *"}),e.jsx(ye,{value:v.title??"",onChange:D=>j({...v,title:D.target.value}),placeholder:"e.g. Top 1% Producer"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Issued by"}),e.jsx(ye,{value:v.issuer??"",onChange:D=>j({...v,issuer:D.target.value}),placeholder:"Board, brokerage, publication"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Category"}),e.jsxs(us,{value:v.category??"award",onValueChange:D=>j({...v,category:D}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:gke.map(D=>e.jsx(Ze,{value:D.value,children:D.label},D.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Date awarded"}),e.jsx(ye,{type:"date",value:v.awarded_on??"",onChange:D=>j({...v,awarded_on:D.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Production period"}),e.jsx(ye,{value:v.production_period??"",onChange:D=>j({...v,production_period:D.target.value}),placeholder:"e.g. 2025"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Proof link"}),e.jsx(ye,{value:v.proof_url??"",onChange:D=>j({...v,proof_url:D.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{rows:3,value:v.description??"",onChange:D=>j({...v,description:D.target.value})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>j(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:E,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(_s,{open:!!w,onOpenChange:D=>!D&&S(null),children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Delete this recognition?"}),e.jsx(Jn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(w.id),S(null)},children:"Delete"})]})]})})]})}const yhn=q,Iet=[{value:"pending",label:"Permission pending"},{value:"granted",label:"Permission granted"},{value:"anonymous_only",label:"Anonymous use only"},{value:"declined",label:"Permission declined"}],vhn=["buyer","seller","both","investor","referral_partner","agent","other"];function KG(s){return s.status==="approved"&&(s.permission_status==="granted"||s.permission_status==="anonymous_only")}function bhn(){const s=HU("attract_testimonials",{orderBy:"created_at",ascending:!1,titleField:"client_name",label:"Testimonial",duplicateOverrides:{use_count:0,last_used_at:null,usage_log:[],status:"draft",is_archived:!1}}),t=GU(),n=Kt(),r=yt({mutationFn:async({item:a,kind:i,note:l})=>{const o=[...a.usage_log??[],{at:new Date().toISOString(),kind:i,note:l}].slice(-25),{error:c}=await yhn.from("attract_testimonials").update({use_count:(a.use_count??0)+1,last_used_at:new Date().toISOString(),usage_log:o}).eq("id",a.id);if(c)throw c},onSuccess:()=>{n.invalidateQueries({queryKey:["attract_testimonials"]}),ae.success("Usage recorded")},onError:a=>ae.error(a.message)});return{...s,testimonials:s.items,recordUse:r,logActivity:t}}const Pet={permission_status:"pending",status:"draft",rating:5,tags:[]};function _hn(){const{testimonials:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,recordUse:d,logActivity:u}=bhn(),[h,p]=N.useState(!1),[f,y]=N.useState("all"),[_,v]=N.useState(""),[j,w]=N.useState(null),[S,A]=N.useState(null),E=N.useMemo(()=>s.filter(F=>{if(h!==!!F.is_archived||f==="usable"&&!KG(F)||f==="pending"&&F.permission_status!=="pending")return!1;const z=_.toLowerCase().trim();return!z||`${F.client_name} ${F.quote} ${(F.tags??[]).join(" ")}`.toLowerCase().includes(z)}),[s,h,f,_]),O=s.filter(F=>!F.is_archived&&KG(F)).length,D=async()=>{var z,H;if(!((z=j==null?void 0:j.client_name)!=null&&z.trim())||!((H=j==null?void 0:j.quote)!=null&&H.trim())){ae.error("Client name and quote are required");return}const F={client_name:j.client_name.trim(),quote:j.quote.trim(),relationship_type:j.relationship_type||null,transaction_type:j.transaction_type||null,rating:j.rating??null,received_on:j.received_on||null,source_url:j.source_url||null,permission_status:j.permission_status??"pending",market:j.market||null,status:j.status??"draft",tags:j.tags??[]};j.id?await i.mutateAsync({id:j.id,...F}):(await a.mutateAsync(F),await u.mutateAsync({title:`Captured a testimonial from ${F.client_name}`,pillar:"produce",activityType:"testimonial_added"})),w(null)},I=(F,z)=>{var H;if(!KG(F)){ae.error("Mark it approved with permission before using it publicly");return}(H=navigator.clipboard)==null||H.writeText(`"${F.quote}" — ${F.permission_status==="anonymous_only"?"Client":F.client_name}`),d.mutate({item:F,kind:z})};return e.jsxs("div",{children:[e.jsxs(In,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(zu,{eyebrow:"Produce → Tool",title:"Client Testimonials",description:"Your social proof library. Capture the exact words clients use, track who gave permission, and see which quotes you've already used so nothing gets overexposed.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>p(F=>!F),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>w({...Pet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add Testimonial"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(F=>!F.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"In library"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:O}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Cleared for use"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:s.filter(F=>!F.is_archived&&F.permission_status==="pending").length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Permission pending"})]})]}),e.jsxs("div",{className:"flex gap-2 flex-wrap mb-4",children:[e.jsx(ye,{value:_,onChange:F=>v(F.target.value),placeholder:"Search quotes, clients, tags",className:"max-w-xs rounded-full"}),e.jsxs(us,{value:f,onValueChange:F=>y(F),children:[e.jsx(ls,{className:"w-[200px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All testimonials"}),e.jsx(Ze,{value:"usable",children:"Cleared for use"}),e.jsx(Ze,{value:"pending",children:"Permission pending"})]})]})]}),t&&e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:[0,1,2,3].map(F=>e.jsx(Ws,{className:"h-40 rounded-2xl"},F))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Bi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load testimonials"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&E.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(gw,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No testimonials match"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Paste in the reviews and thank-you notes you already have. Mark permission so you always know what's safe to publish."}),!h&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>w({...Pet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add one"]})]}),e.jsx("div",{className:"grid gap-3 md:grid-cols-2",children:E.map(F=>{var z;return e.jsxs(fe,{className:"p-5 rounded-2xl flex flex-col",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:F.client_name}),F.relationship_type&&e.jsx(Ue,{variant:"outline",className:"rounded-full capitalize",children:F.relationship_type.replace("_"," ")}),e.jsx(Ue,{variant:"outline",className:`rounded-full ${KG(F)?"bg-emerald-50 text-emerald-700 border-emerald-200":"bg-amber-50 text-amber-700 border-amber-200"}`,children:((z=Iet.find(H=>H.value===F.permission_status))==null?void 0:z.label)??F.permission_status})]}),!!F.rating&&e.jsx("div",{className:"flex gap-0.5 mt-1.5",children:Array.from({length:5}).map((H,Z)=>e.jsx(oa,{className:`h-3.5 w-3.5 ${Z<(F.rating??0)?"text-amber-500 fill-amber-500":"text-slate-200"}`},Z))})]}),e.jsxs("div",{className:"flex gap-1 flex-shrink-0",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>w(F),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(F),children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:F.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:F.id,archived:!F.is_archived}),children:e.jsx(tm,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>A(F),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("blockquote",{className:"mt-3 text-[13.5px] text-slate-700 border-l-2 border-violet-200 pl-3 italic",children:['"',F.quote,'"']}),e.jsxs("div",{className:"text-[11.5px] text-slate-500 mt-3",children:["Used ",F.use_count??0," ",F.use_count===1?"time":"times",F.last_used_at?` · last ${new Date(F.last_used_at).toLocaleDateString("en-US")}`:"",F.status==="approved"?"":" · draft"]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>I(F,"copied"),children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1.5"})," Copy & log use"]}),e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full",asChild:!0,children:e.jsxs(In,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Draft social proof"]})}),F.status!=="approved"&&e.jsxs(B,{size:"sm",variant:"ghost",className:"rounded-full text-emerald-700",onClick:()=>i.mutate({id:F.id,status:"approved"}),children:[e.jsx(eg,{className:"h-3.5 w-3.5 mr-1.5"})," Mark approved"]})]})]},F.id)})}),e.jsx(_s,{open:!!j,onOpenChange:F=>!F&&w(null),children:e.jsxs(bs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:j!=null&&j.id?"Edit testimonial":"Add testimonial"}),e.jsx(Jn,{children:"Use the client's own words. Only publish quotes where permission is granted."})]}),j&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Client name *"}),e.jsx(ye,{value:j.client_name??"",onChange:F=>w({...j,client_name:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Relationship"}),e.jsxs(us,{value:j.relationship_type??"",onValueChange:F=>w({...j,relationship_type:F}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select"})}),e.jsx(cs,{children:vhn.map(F=>e.jsx(Ze,{value:F,className:"capitalize",children:F.replace("_"," ")},F))})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Quote *"}),e.jsx(Ms,{rows:4,value:j.quote??"",onChange:F=>w({...j,quote:F.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Rating"}),e.jsxs(us,{value:String(j.rating??5),onValueChange:F=>w({...j,rating:Number(F)}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:[5,4,3,2,1].map(F=>e.jsxs(Ze,{value:String(F),children:[F," star",F>1?"s":""]},F))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Received on"}),e.jsx(ye,{type:"date",value:j.received_on??"",onChange:F=>w({...j,received_on:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Permission"}),e.jsxs(us,{value:j.permission_status??"pending",onValueChange:F=>w({...j,permission_status:F}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Iet.map(F=>e.jsx(Ze,{value:F.value,children:F.label},F.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Status"}),e.jsxs(us,{value:j.status??"draft",onValueChange:F=>w({...j,status:F}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"draft",children:"Draft"}),e.jsx(Ze,{value:"approved",children:"Approved"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Market / area"}),e.jsx(ye,{value:j.market??"",onChange:F=>w({...j,market:F.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Source link"}),e.jsx(ye,{value:j.source_url??"",onChange:F=>w({...j,source_url:F.target.value}),placeholder:"https://"})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>w(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:D,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(_s,{open:!!S,onOpenChange:F=>!F&&A(null),children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Delete this testimonial?"}),e.jsx(Jn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>A(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(S.id),A(null)},children:"Delete"})]})]})})]})}const Let=[{value:"market_update",label:"Market Update"},{value:"local_video",label:"Local Video"},{value:"newsletter",label:"Newsletter"},{value:"stats_post",label:"Stats Post"},{value:"neighborhood",label:"Neighborhood Content"},{value:"speaking",label:"Speaking Opportunity"}],Det=["idea","planned","drafted","scheduled","published","skipped"],whn=["weekly","biweekly","monthly","quarterly","one_off"];function ISt(){const s=HU("attract_market_presence",{orderBy:"planned_for",ascending:!0,label:"Commitment",duplicateOverrides:{status:"idea",published_url:null,results_notes:null,is_archived:!1}}),t=ebe(),n=GU();return{...s,commitments:s.items,quickTask:t,logActivity:n}}const Ret={content_type:"market_update",cadence:"monthly",status:"planned"};function jhn(s){if(!s)return"Unscheduled";const[t,n,r]=s.split(/[-/T]/).map(Number);return new Date(t,n-1,r).toLocaleDateString("en-US",{weekday:"short",month:"short",day:"numeric"})}const Nhn={idea:"bg-slate-100 text-slate-600 border-slate-200",planned:"bg-blue-50 text-blue-700 border-blue-200",drafted:"bg-violet-50 text-violet-700 border-violet-200",scheduled:"bg-amber-50 text-amber-700 border-amber-200",published:"bg-emerald-50 text-emerald-700 border-emerald-200",skipped:"bg-rose-50 text-rose-700 border-rose-200"};function khn(){const{commitments:s,isLoading:t,error:n,refetch:r,create:a,update:i,duplicate:l,archive:o,remove:c,quickTask:d,logActivity:u}=ISt(),[h,p]=N.useState(!1),[f,y]=N.useState("all"),[_,v]=N.useState(null),[j,w]=N.useState(null),S=N.useMemo(()=>s.filter(I=>h!==!!I.is_archived?!1:f==="all"||I.status===f),[s,h,f]),A=s.filter(I=>{if(I.status!=="published"||!I.planned_for)return!1;const[F,z,H]=I.planned_for.split(/[-/T]/).map(Number);return(Date.now()-new Date(F,z-1,H).getTime())/864e5<=30}).length,E=s.filter(I=>{if(I.is_archived||!I.planned_for||["published","skipped"].includes(I.status))return!1;const[F,z,H]=I.planned_for.split(/[-/T]/).map(Number);return new Date(F,z-1,H){var F;if(!((F=_==null?void 0:_.title)!=null&&F.trim())){ae.error("Add a title");return}const I={title:_.title.trim(),content_type:_.content_type??"market_update",cadence:_.cadence??"monthly",planned_for:_.planned_for||null,status:_.status??"planned",channel:_.channel||null,audience:_.audience||null,campaign:_.campaign||null,notes:_.notes||null,published_url:_.published_url||null,results_notes:_.results_notes||null};_.id?await i.mutateAsync({id:_.id,...I}):await a.mutateAsync(I),v(null)},D=async I=>{await i.mutateAsync({id:I.id,status:"published"}),await u.mutateAsync({title:`Published market presence: ${I.title}`,pillar:"produce",activityType:"market_presence_published"})};return e.jsxs("div",{children:[e.jsxs(In,{to:"/attract/produce",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to Produce"]}),e.jsx(zu,{eyebrow:"Produce → Tool",title:"Market Presence",description:"Consistency beats intensity. Commit to a cadence of market updates and local content, then track whether you actually shipped it.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>p(I=>!I),children:h?"Show active":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...Ret}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," New Commitment"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(I=>!I.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Active commitments"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-emerald-600",children:A}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Published last 30 days"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-amber-600",children:E.length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Past due"})]})]}),e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(us,{value:f,onValueChange:y,children:[e.jsx(ls,{className:"w-[190px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All statuses"}),Det.map(I=>e.jsx(Ze,{value:I,className:"capitalize",children:I},I))]})]})}),t&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(I=>e.jsx(Ws,{className:"h-24 rounded-2xl"},I))}),!t&&n&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Bi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load commitments"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:n.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>r(),children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!t&&!n&&S.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(yf,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:"No commitments yet"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Start with one: a monthly market update. Set the date, ship it, mark it published — that rhythm is what agents notice."}),!h&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v({...Ret}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add a commitment"]})]}),e.jsx("div",{className:"space-y-2",children:S.map(I=>{var F;return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:I.title}),e.jsx(Ue,{variant:"outline",className:"rounded-full",children:((F=Let.find(z=>z.value===I.content_type))==null?void 0:F.label)??I.content_type}),e.jsx(Ue,{variant:"outline",className:`rounded-full capitalize ${Nhn[I.status]??""}`,children:I.status}),e.jsx(Ue,{variant:"outline",className:"rounded-full capitalize",children:I.cadence.replace("_"," ")})]}),e.jsx("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[jhn(I.planned_for),I.channel,I.audience].filter(Boolean).join(" · ")}),I.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:I.notes})]}),e.jsxs("div",{className:"flex gap-1",children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>v(I),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>l.mutate(I),children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:I.is_archived?"Restore":"Archive",onClick:()=>o.mutate({id:I.id,archived:!I.is_archived}),children:e.jsx(tm,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>w(I),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[I.status!=="published"&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>D(I),children:[e.jsx(vr,{className:"h-3.5 w-3.5 mr-1.5"})," Mark published"]}),e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>d.mutate({title:`Create: ${I.title}`,dueAt:I.planned_for?`${I.planned_for}T09:00:00`:new Date().toISOString(),notes:I.notes,touchType:"content"}),children:[e.jsx(lu,{className:"h-3.5 w-3.5 mr-1.5"})," Add task"]}),e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full",asChild:!0,children:e.jsxs(In,{to:"/attract/influence/content-studio",children:[e.jsx(un,{className:"h-3.5 w-3.5 mr-1.5"})," Draft it"]})})]})]},I.id)})}),e.jsx(_s,{open:!!_,onOpenChange:I=>!I&&v(null),children:e.jsxs(bs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:_!=null&&_.id?"Edit commitment":"New commitment"}),e.jsx(Jn,{children:"Pick something you can genuinely sustain."})]}),_&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title *"}),e.jsx(ye,{value:_.title??"",onChange:I=>v({..._,title:I.target.value}),placeholder:"e.g. October market update video"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Type"}),e.jsxs(us,{value:_.content_type??"market_update",onValueChange:I=>v({..._,content_type:I}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Let.map(I=>e.jsx(Ze,{value:I.value,children:I.label},I.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Cadence"}),e.jsxs(us,{value:_.cadence??"monthly",onValueChange:I=>v({..._,cadence:I}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:whn.map(I=>e.jsx(Ze,{value:I,className:"capitalize",children:I.replace("_"," ")},I))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Planned for"}),e.jsx(ye,{type:"date",value:_.planned_for??"",onChange:I=>v({..._,planned_for:I.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Status"}),e.jsxs(us,{value:_.status??"planned",onValueChange:I=>v({..._,status:I}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Det.map(I=>e.jsx(Ze,{value:I,className:"capitalize",children:I},I))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Channel"}),e.jsx(ye,{value:_.channel??"",onChange:I=>v({..._,channel:I.target.value}),placeholder:"Instagram, email, YouTube"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Audience"}),e.jsx(ye,{value:_.audience??"",onChange:I=>v({..._,audience:I.target.value}),placeholder:"Agents, sphere, neighborhood"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Notes"}),e.jsx(Ms,{rows:3,value:_.notes??"",onChange:I=>v({..._,notes:I.target.value})})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Published URL"}),e.jsx(ye,{value:_.published_url??"",onChange:I=>v({..._,published_url:I.target.value}),placeholder:"https://"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Results"}),e.jsx(ye,{value:_.results_notes??"",onChange:I=>v({..._,results_notes:I.target.value}),placeholder:"Reach, replies, leads"})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>v(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:O,disabled:a.isPending||i.isPending,children:"Save"})]})]})}),e.jsx(_s,{open:!!j,onOpenChange:I=>!I&&w(null),children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Delete this commitment?"}),e.jsx(Jn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>w(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{c.mutate(j.id),w(null)},children:"Delete"})]})]})})]})}function Oet(s){if(!s)return null;const[t]=s.split("T");return t||null}const YG={draft:{label:"Content",icon:un,cls:"bg-violet-50 text-violet-700 border-violet-200"},presence:{label:"Market presence",icon:yf,cls:"bg-blue-50 text-blue-700 border-blue-200"},speaking:{label:"Speaking",icon:Dv,cls:"bg-amber-50 text-amber-700 border-amber-200"}};function Shn(){const{drafts:s,isLoading:t,save:n}=CSt(),{commitments:r,isLoading:a}=ISt(),i=MSt(),l=ebe(),[o,c]=N.useState(()=>{const E=new Date;return new Date(E.getFullYear(),E.getMonth(),1)}),[d,u]=N.useState("all"),[h,p]=N.useState(null),f=N.useMemo(()=>(i.items??[]).filter(E=>!E.is_archived).map(E=>({id:E.id,kind:"speaking",title:E.title,date:Oet(E.starts_at),status:E.status,href:"/attract/influence/speaking"})),[i.items]),y=N.useMemo(()=>{const E=s.map(D=>({id:D.id,kind:"draft",title:D.topic||D.mode.replace(/_/g," "),date:Oet(D.planned_at??D.posted_at??null),status:D.status,href:"/attract/influence/content-studio"})),O=r.filter(D=>!D.is_archived).map(D=>({id:D.id,kind:"presence",title:D.title,date:D.planned_for,status:D.status,href:"/attract/produce/market-presence"}));return[...E,...O,...f].filter(D=>d==="all"||D.kind===d)},[s,r,f,d]),_=`${o.getFullYear()}-${String(o.getMonth()+1).padStart(2,"0")}`,v=y.filter(E=>{var O;return(O=E.date)==null?void 0:O.startsWith(_)}),j=y.filter(E=>!E.date),w=N.useMemo(()=>{const E=new Date(o.getFullYear(),o.getMonth(),1),O=new Date(E);return O.setDate(E.getDate()-E.getDay()),Array.from({length:42},(D,I)=>{const F=new Date(O);F.setDate(O.getDate()+I);const z=`${F.getFullYear()}-${String(F.getMonth()+1).padStart(2,"0")}-${String(F.getDate()).padStart(2,"0")}`;return{date:F,key:z,inMonth:F.getMonth()===o.getMonth(),items:y.filter(H=>H.date===z)}})},[o,y]),S=(()=>{const E=new Date;return`${E.getFullYear()}-${String(E.getMonth()+1).padStart(2,"0")}-${String(E.getDate()).padStart(2,"0")}`})(),A=t||a;return e.jsxs("div",{children:[e.jsxs(In,{to:"/attract/influence",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to Influence"]}),e.jsx(zu,{eyebrow:"Produce + Influence → Tool",title:"Content Calendar",description:"One month view of everything you've committed to publish — Content Studio drafts, market presence commitments, and speaking dates.",actions:e.jsx(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",asChild:!0,children:e.jsxs(In,{to:"/attract/influence/content-studio",children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," New Draft"]})})}),e.jsxs("div",{className:"flex items-center justify-between gap-2 flex-wrap mb-4",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(B,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()-1,1)),children:e.jsx(ml,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900 min-w-[170px] text-center",children:o.toLocaleString("en-US",{month:"long",year:"numeric"})}),e.jsx(B,{size:"icon",variant:"outline",className:"rounded-full h-9 w-9",onClick:()=>c(new Date(o.getFullYear(),o.getMonth()+1,1)),children:e.jsx(ga,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",className:"rounded-full",onClick:()=>{const E=new Date;c(new Date(E.getFullYear(),E.getMonth(),1))},children:"Today"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Ue,{variant:"outline",className:"rounded-full",children:[v.length," scheduled this month"]}),e.jsxs(us,{value:d,onValueChange:E=>u(E),children:[e.jsx(ls,{className:"w-[180px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"all",children:"All types"}),e.jsx(Ze,{value:"draft",children:"Content drafts"}),e.jsx(Ze,{value:"presence",children:"Market presence"}),e.jsx(Ze,{value:"speaking",children:"Speaking"})]})]})]})]}),A?e.jsx(Ws,{className:"h-[560px] rounded-2xl"}):e.jsxs(fe,{className:"rounded-2xl overflow-hidden",children:[e.jsx("div",{className:"grid grid-cols-7 bg-slate-50 border-b",children:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"].map(E=>e.jsx("div",{className:"px-2 py-2 text-[11px] uppercase tracking-wider text-slate-500 font-semibold text-center",children:E},E))}),e.jsx("div",{className:"grid grid-cols-7",children:w.map(E=>e.jsxs("div",{className:`min-h-[96px] border-b border-r p-1.5 ${E.inMonth?"":"bg-slate-50/60"}`,children:[e.jsx("div",{className:`text-[11.5px] font-medium mb-1 ${E.key===S?"text-violet-700":E.inMonth?"text-slate-700":"text-slate-400"}`,children:E.date.getDate()}),e.jsxs("div",{className:"space-y-1",children:[E.items.slice(0,3).map(O=>{const D=YG[O.kind];return e.jsx(In,{to:O.href,className:`block truncate rounded-md border px-1.5 py-0.5 text-[11px] ${D.cls}`,title:O.title,children:O.title},`${O.kind}-${O.id}`)}),E.items.length>3&&e.jsxs("div",{className:"text-[10.5px] text-slate-500 px-1",children:["+",E.items.length-3," more"]})]})]},E.key))})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2 mt-5",children:[e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsxs("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:["Unscheduled (",j.length,")"]}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Give these a date so they show on the calendar."}),j.length===0&&e.jsx("div",{className:"text-[13px] text-slate-500",children:"Everything has a date. Nice."}),e.jsx("div",{className:"space-y-2",children:j.slice(0,8).map(E=>e.jsxs("div",{className:"flex items-center justify-between gap-2 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13px] font-medium text-slate-900 truncate capitalize",children:E.title}),e.jsxs("div",{className:"text-[11.5px] text-slate-500",children:[YG[E.kind].label," · ",E.status]})]}),E.kind==="draft"?e.jsx(B,{size:"sm",variant:"outline",className:"rounded-full flex-shrink-0",onClick:()=>p({id:E.id,title:E.title,date:S}),children:"Schedule"}):e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full flex-shrink-0",asChild:!0,children:e.jsx(In,{to:E.href,children:"Open"})})]},`${E.kind}-${E.id}`))})]}),e.jsxs(fe,{className:"p-5 rounded-2xl",children:[e.jsx("div",{className:"text-[15px] font-semibold text-slate-900 mb-1",children:"This month at a glance"}),e.jsx("p",{className:"text-[12.5px] text-slate-600 mb-3",children:"Keep a steady rhythm across all three surfaces."}),e.jsx("div",{className:"space-y-2",children:Object.keys(YG).map(E=>{const O=YG[E],D=O.icon,I=v.filter(F=>F.kind===E).length;return e.jsxs("div",{className:"flex items-center gap-3 rounded-xl bg-slate-50 px-3 py-2",children:[e.jsx("div",{className:`h-8 w-8 rounded-lg grid place-items-center border ${O.cls}`,children:e.jsx(D,{className:"h-4 w-4"})}),e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 flex-1",children:O.label}),e.jsx("div",{className:"text-[16px] font-semibold tabular-nums text-slate-900",children:I})]},E)})}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4 w-full",onClick:()=>l.mutate({title:`Plan content for ${o.toLocaleString("en-US",{month:"long"})}`,dueAt:new Date().toISOString(),touchType:"content"}),children:[e.jsx(lu,{className:"h-3.5 w-3.5 mr-1.5"})," Add planning block to Today's Plan"]}),e.jsx(B,{variant:"ghost",className:"rounded-full mt-2 w-full",asChild:!0,children:e.jsxs(In,{to:"/attract/produce/market-presence",children:[e.jsx(Cl,{className:"h-3.5 w-3.5 mr-1.5"})," Manage market presence cadence"]})})]})]}),e.jsx(_s,{open:!!h,onOpenChange:E=>!E&&p(null),children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Schedule draft"}),e.jsx(Jn,{className:"capitalize",children:h==null?void 0:h.title})]}),h&&e.jsxs("div",{children:[e.jsx(ne,{children:"Planned date"}),e.jsx(ye,{type:"date",value:h.date,onChange:E=>p({...h,date:E.target.value})})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>p(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:async()=>{h&&(await n.mutateAsync({id:h.id,planned_at:`${h.date}T09:00:00`}),p(null))},children:"Save"})]})]})})]})}const Fet=[{value:"birthday",label:"Birthday"},{value:"work_anniversary",label:"Work Anniversary"},{value:"license_anniversary",label:"License Anniversary"},{value:"production_milestone",label:"Production Milestone"},{value:"team_milestone",label:"Team Milestone"},{value:"family_milestone",label:"Family Milestone"},{value:"custom",label:"Custom Date"}];function Chn(s){const[t,n,r]=s.split(/[-/T]/).map(Number);return{y:t,m:n,d:r}}function qTe(s,t=new Date){const{y:n,m:r,d:a}=Chn(s.milestone_on);if(!s.recurs_annually)return new Date(n,r-1,a);const i=new Date(t.getFullYear(),r-1,a),l=new Date(t.getFullYear(),t.getMonth(),t.getDate());return i{const l=[];return r.forEach(o=>{const c=[o.preferred_name||o.first_name,o.last_name].filter(Boolean).join(" ");[["birthday",o.birthday_on,`${c} — Birthday`],["work_anniversary",o.work_anniversary_on,`${c} — Work Anniversary`],["license_anniversary",o.license_anniversary_on,`${c} — License Anniversary`]].forEach(([d,u,h])=>{u&&l.push({id:`agent:${o.id}:${d}`,user_id:o.user_id,title:h,milestone_type:d,milestone_on:String(u).slice(0,10),recurs_annually:!0,linked_agent_ids:[o.id],notes:null,last_celebrated_at:null,is_archived:!1,created_at:o.created_at,updated_at:o.updated_at})})}),l},[r]),i=N.useMemo(()=>{const l=new Set(s.items.filter(c=>!c.is_archived).map(c=>{var d;return`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${((d=c.linked_agent_ids)==null?void 0:d[0])??""}`}));return[...s.items.filter(c=>!c.is_archived),...a.filter(c=>!l.has(`${c.milestone_type}|${c.milestone_on.slice(5,10)}|${c.linked_agent_ids[0]}`))].map(c=>({item:c,next:qTe(c)})).map(c=>({...c,days:PSt(c.next)})).filter(c=>c.days>=0).sort((c,d)=>c.days-d.days)},[s.items,a]);return{...s,milestones:s.items,derived:a,upcoming:i,quickTask:t,logActivity:n}}const zet={milestone_type:"birthday",recurs_annually:!0,linked_agent_ids:[]};function Ehn(s){return s.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric"})}function Ahn(){var z;const{milestones:s,upcoming:t,isLoading:n,error:r,refetch:a,create:i,update:l,duplicate:o,archive:c,remove:d,quickTask:u,logActivity:h}=Thn(),p=i0(),f=(p==null?void 0:p.agents)??(p==null?void 0:p.items)??[],[y,_]=N.useState(!1),[v,j]=N.useState("90"),[w,S]=N.useState(null),[A,E]=N.useState(null),O=N.useMemo(()=>{if(y)return s.filter(Z=>Z.is_archived).map(Z=>({item:Z,next:qTe(Z),days:PSt(qTe(Z))}));const H=v==="all"?1/0:Number(v);return t.filter(Z=>Z.days<=H)},[s,t,y,v]),D=H=>{const Z=f.find(Y=>Y.id===H);return Z?[Z.preferred_name||Z.first_name,Z.last_name].filter(Boolean).join(" "):"Agent"},I=async()=>{var Z;if(!((Z=w==null?void 0:w.title)!=null&&Z.trim())||!(w!=null&&w.milestone_on)){ae.error("Title and date are required");return}const H={title:w.title.trim(),milestone_type:w.milestone_type??"birthday",milestone_on:w.milestone_on,recurs_annually:w.recurs_annually??!0,linked_agent_ids:w.linked_agent_ids??[],notes:w.notes||null};w.id?await l.mutateAsync({id:w.id,...H}):await i.mutateAsync(H),S(null)},F=async H=>{var Z;await l.mutateAsync({id:H.id,last_celebrated_at:new Date().toISOString()}),await h.mutateAsync({title:`Celebrated: ${H.title}`,pillar:"connect",activityType:"milestone_celebrated",agentId:((Z=H.linked_agent_ids)==null?void 0:Z[0])??null})};return e.jsxs("div",{children:[e.jsxs(In,{to:"/attract/connect",className:"inline-flex items-center gap-1.5 text-[12px] text-slate-500 hover:text-violet-700 mb-3",children:[e.jsx(qr,{className:"h-3.5 w-3.5"})," Back to Connect"]}),e.jsx(zu,{eyebrow:"Connect → Tool",title:"Milestones & Celebrations",description:"Remember the dates that matter to the agents in your pipeline. Recurring milestones roll forward every year so you never miss the reason to reach out.",actions:e.jsxs(e.Fragment,{children:[e.jsx(B,{variant:"outline",className:"rounded-full",onClick:()=>_(H=>!H),children:y?"Show upcoming":"Show archived"}),e.jsxs(B,{className:"rounded-full bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>S({...zet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add Milestone"]})]})}),e.jsxs("div",{className:"grid grid-cols-2 sm:grid-cols-3 gap-3 mb-4",children:[e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:t.filter(H=>H.days<=7).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 7 days"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-violet-600",children:t.filter(H=>H.days<=30).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Next 30 days"})]}),e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsx("div",{className:"text-[22px] font-semibold tabular-nums text-slate-900",children:s.filter(H=>!H.is_archived).length}),e.jsx("div",{className:"text-[12px] text-slate-500",children:"Tracked total"})]})]}),!y&&e.jsx("div",{className:"flex gap-2 flex-wrap mb-4",children:e.jsxs(us,{value:v,onValueChange:H=>j(H),children:[e.jsx(ls,{className:"w-[190px] rounded-full",children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"30",children:"Next 30 days"}),e.jsx(Ze,{value:"90",children:"Next 90 days"}),e.jsx(Ze,{value:"all",children:"All upcoming"})]})]})}),n&&e.jsx("div",{className:"space-y-2",children:[0,1,2].map(H=>e.jsx(Ws,{className:"h-20 rounded-2xl"},H))}),!n&&r&&e.jsxs(fe,{className:"p-8 rounded-2xl text-center",children:[e.jsx(Bi,{className:"h-6 w-6 text-rose-500 mx-auto mb-2"}),e.jsx("div",{className:"font-semibold text-slate-900",children:"Couldn't load milestones"}),e.jsx("div",{className:"text-[13px] text-slate-600 mt-1",children:r.message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-4",onClick:()=>a(),children:[e.jsx(Bm,{className:"h-3.5 w-3.5 mr-1.5"})," Retry"]})]}),!n&&!r&&O.length===0&&e.jsxs(fe,{className:"p-10 rounded-2xl text-center border-dashed",children:[e.jsx("div",{className:"h-12 w-12 rounded-2xl bg-violet-50 text-violet-600 grid place-items-center mx-auto mb-3",children:e.jsx(Ah,{className:"h-6 w-6"})}),e.jsx("div",{className:"text-[16px] font-semibold text-slate-900",children:y?"Nothing archived":"No milestones in this window"}),e.jsx("p",{className:"text-[13.5px] text-slate-600 mt-1.5 max-w-md mx-auto",children:"Add birthdays, license anniversaries, and production milestones for the agents you're building relationships with."}),!y&&e.jsxs(B,{className:"rounded-full mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>S({...zet}),children:[e.jsx(Is,{className:"h-4 w-4 mr-1.5"})," Add a milestone"]})]}),e.jsx("div",{className:"space-y-2",children:O.map(({item:H,next:Z,days:Y})=>{var ee,se;const W=String(H.id).startsWith("agent:");return e.jsxs(fe,{className:"p-4 rounded-2xl",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3 flex-wrap",children:[e.jsxs("div",{className:"flex items-start gap-3 min-w-0",children:[e.jsx("div",{className:"h-11 w-11 rounded-xl bg-violet-50 text-violet-700 grid place-items-center flex-shrink-0",children:e.jsxs("div",{className:"text-center leading-none",children:[e.jsx("div",{className:"text-[9px] uppercase tracking-wider",children:Z.toLocaleString("en-US",{month:"short"})}),e.jsx("div",{className:"text-[15px] font-semibold",children:Z.getDate()})]})}),e.jsxs("div",{className:"min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("span",{className:"text-[15px] font-semibold text-slate-900",children:H.title}),e.jsx(Ue,{variant:"outline",className:"rounded-full",children:((ee=Fet.find(oe=>oe.value===H.milestone_type))==null?void 0:ee.label)??H.milestone_type}),W&&e.jsx(Ue,{variant:"outline",className:"rounded-full bg-violet-50 text-violet-700 border-violet-200",children:"From contact record"}),!y&&e.jsx(Ue,{variant:"outline",className:`rounded-full ${Y<=7?"bg-amber-50 text-amber-700 border-amber-200":""}`,children:Y===0?"Today":Y===1?"Tomorrow":`in ${Y} days`}),H.recurs_annually&&e.jsx(Ue,{variant:"outline",className:"rounded-full",children:"Annual"})]}),e.jsxs("div",{className:"text-[12.5px] text-slate-500 mt-1",children:[Ehn(Z),(se=H.linked_agent_ids)!=null&&se.length?` · ${H.linked_agent_ids.map(D).join(", ")}`:"",H.last_celebrated_at?` · last celebrated ${new Date(H.last_celebrated_at).toLocaleDateString("en-US")}`:""]}),H.notes&&e.jsx("div",{className:"text-[12.5px] text-slate-600 mt-1 line-clamp-2",children:H.notes})]})]}),e.jsx("div",{className:"flex gap-1",children:W?e.jsx(B,{size:"sm",variant:"ghost",className:"rounded-full text-[12px]",asChild:!0,children:e.jsx(In,{to:`/attract/agents/${H.linked_agent_ids[0]}`,children:"Open contact"})}):e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Edit",onClick:()=>S(H),children:e.jsx(ya,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:"Duplicate",onClick:()=>o.mutate(H),children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8",title:H.is_archived?"Restore":"Archive",onClick:()=>c.mutate({id:H.id,archived:!H.is_archived}),children:e.jsx(tm,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"icon",variant:"ghost",className:"h-8 w-8 text-rose-600",title:"Delete",onClick:()=>E(H),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})})]}),e.jsxs("div",{className:"flex gap-2 mt-3 flex-wrap",children:[e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>{var oe;return u.mutate({title:`Reach out: ${H.title}`,dueAt:Z.toISOString(),notes:H.notes,touchType:"celebration",agentId:((oe=H.linked_agent_ids)==null?void 0:oe[0])??null})},children:[e.jsx(lu,{className:"h-3.5 w-3.5 mr-1.5"})," Add reach-out task"]}),!W&&e.jsxs(B,{size:"sm",variant:"outline",className:"rounded-full",onClick:()=>F(H),children:[e.jsx(ih,{className:"h-3.5 w-3.5 mr-1.5"})," Mark celebrated"]})]})]},H.id)})}),e.jsx(_s,{open:!!w,onOpenChange:H=>!H&&S(null),children:e.jsxs(bs,{className:"max-w-xl max-h-[90vh] overflow-y-auto",children:[e.jsxs(js,{children:[e.jsx(ws,{children:w!=null&&w.id?"Edit milestone":"Add milestone"}),e.jsx(Jn,{children:"Annual milestones roll forward automatically each year."})]}),w&&e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Title *"}),e.jsx(ye,{value:w.title??"",onChange:H=>S({...w,title:H.target.value}),placeholder:"e.g. Sarah's birthday"})]}),e.jsxs("div",{className:"grid sm:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Type"}),e.jsxs(us,{value:w.milestone_type??"birthday",onValueChange:H=>S({...w,milestone_type:H}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Fet.map(H=>e.jsx(Ze,{value:H.value,children:H.label},H.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Date *"}),e.jsx(ye,{type:"date",value:w.milestone_on??"",onChange:H=>S({...w,milestone_on:H.target.value})})]})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-xl border border-slate-200 px-4 py-3",children:[e.jsxs("div",{children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900",children:"Repeats every year"}),e.jsx("div",{className:"text-[12px] text-slate-600",children:"Turn off for one-time milestones."})]}),e.jsx(jn,{checked:w.recurs_annually??!0,onCheckedChange:H=>S({...w,recurs_annually:H})})]}),f.length>0&&e.jsxs("div",{children:[e.jsx(ne,{children:"Link to agent"}),e.jsxs(us,{value:((z=w.linked_agent_ids)==null?void 0:z[0])??"none",onValueChange:H=>S({...w,linked_agent_ids:H==="none"?[]:[H]}),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Optional"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"No agent"}),f.map(H=>e.jsx(Ze,{value:H.id,children:D(H.id)},H.id))]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Notes"}),e.jsx(Ms,{rows:3,value:w.notes??"",onChange:H=>S({...w,notes:H.target.value}),placeholder:"Gift ideas, personal details, how you'll reach out"})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>S(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:I,disabled:i.isPending||l.isPending,children:"Save"})]})]})}),e.jsx(_s,{open:!!A,onOpenChange:H=>!H&&E(null),children:e.jsxs(bs,{className:"max-w-md",children:[e.jsxs(js,{children:[e.jsx(ws,{children:"Delete this milestone?"}),e.jsx(Jn,{children:"This can't be undone."})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>E(null),children:"Cancel"}),e.jsx(B,{variant:"destructive",onClick:()=>{d.mutate(A.id),E(null)},children:"Delete"})]})]})})]})}function Mhn(){var c;const{shareToken:s}=bi(),[t,n]=N.useState("loading"),[r,a]=N.useState(null),[i,l]=N.useState(!1);N.useEffect(()=>{(async()=>{if(!s){n("not_found");return}const{data:d,error:u}=await q.rpc("public_get_attract_kit",{_token:s});if(u){n("error");return}if(!d||d.status!=="ok"){n((d==null?void 0:d.status)??"not_found");return}a(d),n("ok"),q.rpc("public_log_attract_kit_event",{_token:s,_event_type:"page_view",_item_id:null,_metadata:{}})})()},[s]);const o=(d,u,h)=>{s&&q.rpc("public_log_attract_kit_event",{_token:s,_event_type:d,_item_id:u??null,_metadata:h??{}})};return t==="loading"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center text-slate-300",children:"Loading…"}):t!=="ok"?e.jsx("div",{className:"min-h-screen bg-[#05070f] grid place-items-center px-6",children:e.jsxs(fe,{className:"max-w-md w-full p-8 bg-white/5 border-white/10 text-slate-100 rounded-2xl text-center",children:[e.jsx(Bi,{className:"h-8 w-8 text-amber-400 mx-auto"}),e.jsx("div",{className:"mt-3 text-xl font-semibold",children:t==="expired"?"This kit has expired":t==="revoked"?"This kit is no longer available":t==="not_found"?"This kit could not be found":"Something went wrong"}),e.jsx("p",{className:"text-slate-400 mt-2 text-sm",children:"Please reach out to the person who shared it with you for an updated link."})]})}):e.jsx("div",{className:"min-h-screen bg-[#05070f]",children:e.jsxs("div",{className:"max-w-3xl mx-auto py-6 px-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-[10.5px] uppercase tracking-widest text-violet-400 font-semibold justify-center py-3",children:[e.jsx(un,{className:"h-3.5 w-3.5"})," A LevelUp Attract kit"]}),e.jsx(TSt,{kit:r.kit,items:r.items,owner:r.owner,personalNote:(c=r.share)==null?void 0:c.personal_note,mode:"public",onEvent:o}),e.jsx(fe,{className:"mt-6 p-6 bg-white/5 border-white/10 text-slate-100 rounded-2xl",children:i?e.jsx(Ihn,{token:s,onSent:()=>l(!1),onEvent:o}):e.jsxs("div",{className:"text-center",children:[e.jsx("div",{className:"text-[15px] font-semibold",children:"Have a question about this?"}),e.jsxs("p",{className:"text-slate-400 text-[13px] mt-1",children:["Send a private note — ",r.owner.display_name," will get it right away."]}),e.jsx(B,{className:"mt-4 bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>l(!0),children:"Ask a question"})]})}),e.jsx("div",{className:"text-center text-[11px] text-slate-600 mt-6 pb-10",children:"Powered by LevelUp Attract"})]})})}function Ihn({token:s,onSent:t,onEvent:n}){const[r,a]=N.useState(""),[i,l]=N.useState(""),[o,c]=N.useState(""),[d,u]=N.useState(!1),h=async()=>{if(o.trim().length<2)return ae.error("Please add a short message");u(!0);const{data:p,error:f}=await q.rpc("public_submit_attract_kit_question",{_token:s,_name:r,_email:i,_message:o});if(u(!1),f||!(p!=null&&p.ok))return ae.error("Could not send — please try again");ae.success("Sent — thank you!"),t()};return e.jsxs("div",{className:"space-y-3",children:[e.jsx("div",{className:"text-[14px] font-semibold",children:"Send a private message"}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-2",children:[e.jsx(ye,{placeholder:"Your name (optional)",value:r,onChange:p=>a(p.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsx(ye,{placeholder:"Your email (optional)",value:i,onChange:p=>l(p.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"})]}),e.jsx(Ms,{rows:4,placeholder:"What's your question?",value:o,onChange:p=>c(p.target.value),className:"bg-white/5 border-white/10 text-white placeholder:text-slate-500"}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(B,{variant:"outline",onClick:()=>{n("meeting_requested"),ae.success("Request sent")},children:"Request a conversation"}),e.jsx(B,{onClick:h,disabled:d,className:"bg-gradient-to-r from-violet-600 to-indigo-600 ml-auto",children:d?"Sending…":"Send question"})]})]})}function Phn(){const{slug:s}=bi(),[t]=xl(),n=t.get("inv")||null,[r,a]=N.useState("loading"),[i,l]=N.useState(null),[o,c]=N.useState({name:"",email:"",phone:"",answers:{}}),[d,u]=N.useState(!1),[h,p]=N.useState(null);N.useEffect(()=>{s&&(async()=>{const{data:_,error:v}=await q.rpc("public_get_attract_event",{_slug:s});if(v||!_||_.error){a((_==null?void 0:_.error)||"not_found");return}l(_),a("ok"),n&&q.rpc("public_track_attract_invitation_view",{_token:n})})()},[s,n]);const f=async()=>{u(!0);const{data:_,error:v}=await q.rpc("public_register_attract_event",{_slug:s,_name:o.name,_email:o.email,_phone:o.phone||null,_answers:o.answers||{},_invitation_token:n});if(u(!1),v){alert("Something went wrong. Please try again.");return}const j=_;if(j!=null&&j.error){alert(j.error==="invalid_email"?"That email looks off.":j.error==="full"?"This event is full.":"Could not register.");return}p(j)},y=()=>{if(!i)return;const _=new Blob([tSt(i)],{type:"text/calendar"}),v=document.createElement("a");v.href=URL.createObjectURL(_),v.download=`${s}.ics`,v.click()};if(r==="loading")return e.jsx("div",{className:"min-h-screen grid place-items-center text-slate-400",children:"Loading…"});if(r!=="ok"||!i){const _=r==="cancelled"?"This event was cancelled.":r==="not_available"?"This event is not open for registration.":"This event could not be found.";return e.jsx("div",{className:"min-h-screen grid place-items-center px-6 text-center",children:e.jsxs("div",{children:[e.jsx("div",{className:"text-2xl font-semibold text-slate-900",children:_}),e.jsx("div",{className:"text-slate-500 mt-2",children:"The link may have expired."})]})})}return e.jsx("div",{className:"min-h-screen bg-gradient-to-br from-slate-50 via-white to-violet-50",children:e.jsxs("div",{className:"max-w-3xl mx-auto px-4 py-10 md:py-16",children:[i.cover_image_url&&e.jsx("div",{className:"rounded-3xl overflow-hidden mb-8 aspect-[16/7] bg-slate-100",children:e.jsx("img",{src:i.cover_image_url,alt:"",className:"w-full h-full object-cover"})}),e.jsxs("div",{className:"text-center mb-8",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-[0.2em] text-violet-600 font-semibold mb-3",children:"You are invited"}),e.jsx("h1",{className:"text-3xl md:text-5xl font-semibold tracking-tight text-slate-900",children:i.title}),i.host&&e.jsxs("div",{className:"text-slate-600 mt-3 text-[15px]",children:["Hosted by ",e.jsx("span",{className:"font-semibold",children:i.host.name}),i.host.brokerage_name?` · ${i.host.brokerage_name}`:""]})]}),e.jsxs(fe,{className:"p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4 text-[14px]",children:[e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx(yr,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"When"}),e.jsx("div",{className:"font-semibold text-slate-900",children:Ss(new Date(i.starts_at),"EEEE, MMMM d · h:mm a")}),e.jsx("div",{className:"text-slate-500 text-[12px]",children:i.timezone})]})]}),e.jsxs("div",{className:"flex items-start gap-3",children:[i.format==="virtual"?e.jsx(fr,{className:"h-5 w-5 text-violet-600 mt-0.5"}):e.jsx(ka,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"Where"}),e.jsx("div",{className:"font-semibold text-slate-900",children:i.format==="virtual"?"Virtual — link sent after registration":i.location||"In person"}),i.address&&e.jsx("div",{className:"text-slate-500 text-[12px]",children:i.address})]})]}),i.capacity&&e.jsxs("div",{className:"flex items-start gap-3 md:col-span-2",children:[e.jsx(An,{className:"h-5 w-5 text-violet-600 mt-0.5"}),e.jsxs("div",{children:[e.jsx("div",{className:"text-slate-500 text-[12px]",children:"Room size"}),e.jsx("div",{className:"font-semibold text-slate-900",children:i.seats_left===0?"Waitlist only":`${i.seats_left} of ${i.capacity} seats left`})]})]})]}),i.description&&e.jsx("p",{className:"text-[15px] text-slate-700 leading-relaxed mt-5",children:i.description}),(i.learning_outcomes||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"What you will receive"}),e.jsx("ul",{className:"space-y-1.5",children:i.learning_outcomes.map((_,v)=>e.jsxs("li",{className:"flex gap-2 text-[14px] text-slate-800",children:[e.jsx(Lr,{className:"h-4 w-4 text-emerald-600 shrink-0 mt-0.5"})," ",_]},v))})]}),(i.agenda||[]).length>0&&e.jsxs("div",{className:"mt-5",children:[e.jsx("div",{className:"text-[11px] uppercase tracking-widest text-slate-500 font-semibold mb-2",children:"Agenda"}),e.jsx("ul",{className:"space-y-1",children:i.agenda.map((_,v)=>e.jsxs("li",{className:"flex gap-3 text-[13.5px]",children:[e.jsx("span",{className:"text-slate-500 tabular-nums w-16 shrink-0",children:_.time}),e.jsx("span",{className:"text-slate-800",children:_.item})]},v))})]})]}),h?e.jsxs(fe,{className:"mt-6 p-8 rounded-3xl border-emerald-200 bg-emerald-50 text-center",children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(Lr,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold text-slate-900 mt-4",children:h.status==="waitlisted"?"You are on the waitlist":"You are in."}),i.confirmation_message&&e.jsx("div",{className:"text-[15px] text-slate-700 mt-2 max-w-lg mx-auto",children:i.confirmation_message}),e.jsxs(B,{variant:"outline",className:"rounded-full mt-5",onClick:y,children:[e.jsx(Ia,{className:"h-4 w-4 mr-2"})," Add to calendar"]})]}):e.jsxs(fe,{className:"mt-6 p-6 rounded-3xl border-slate-200 bg-white",children:[e.jsxs("div",{className:"text-lg font-semibold text-slate-900 mb-1 flex items-center gap-2",children:[e.jsx(un,{className:"h-4 w-4 text-violet-600"})," Save your seat"]}),e.jsx("div",{className:"text-[13px] text-slate-500 mb-4",children:"The room is small on purpose."}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Full name"}),e.jsx(ye,{value:o.name,onChange:_=>c({...o,name:_.target.value})})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Email"}),e.jsx(ye,{type:"email",value:o.email,onChange:_=>c({...o,email:_.target.value})})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Phone (optional)"}),e.jsx(ye,{value:o.phone,onChange:_=>c({...o,phone:_.target.value})})]})]}),(i.registration_questions||[]).map(_=>e.jsxs("div",{children:[e.jsx(ne,{children:_.label}),_.type==="long"?e.jsx(Ms,{rows:3,value:o.answers[_.key]||"",onChange:v=>c({...o,answers:{...o.answers,[_.key]:v.target.value}})}):e.jsx(ye,{value:o.answers[_.key]||"",onChange:v=>c({...o,answers:{...o.answers,[_.key]:v.target.value}})})]},_.key))]}),e.jsx(B,{disabled:d,className:"w-full mt-5 rounded-full bg-gradient-to-r from-violet-600 to-indigo-600 h-11",onClick:f,children:d?"Saving…":i.seats_left===0?"Join the waitlist":"Save my seat"}),e.jsx("div",{className:"text-[11.5px] text-slate-400 text-center mt-3",children:"Build relationships first. We will only email you about this event."})]})]})})}function Lhn(){const{token:s}=bi(),[t]=xl(),n=t.get("a"),[r,a]=N.useState("loading"),[i,l]=N.useState("");return N.useEffect(()=>{if(!s||!n){a("error");return}(async()=>{const{data:o}=await q.rpc("public_check_in_attendee",{_check_in_token:s,_attendee_token:n}),c=o;c!=null&&c.ok?(l(c.name||""),a(c.already?"already":"ok")):a("error")})()},[s,n]),e.jsx("div",{className:"min-h-screen grid place-items-center bg-slate-50 px-4",children:e.jsxs(fe,{className:"p-8 rounded-3xl border-slate-200 bg-white max-w-md w-full text-center",children:[r==="loading"&&e.jsx("div",{className:"text-slate-500",children:"Checking you in…"}),(r==="ok"||r==="already")&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"mx-auto h-14 w-14 rounded-full bg-emerald-500 text-white grid place-items-center",children:e.jsx(Lr,{className:"h-7 w-7"})}),e.jsx("div",{className:"text-2xl font-semibold mt-4 text-slate-900",children:r==="already"?"Already checked in":"You are in!"}),i&&e.jsxs("div",{className:"text-slate-600 mt-1",children:["Welcome, ",i,"."]}),e.jsx("div",{className:"text-[13px] text-slate-500 mt-4",children:"Find your seat and enjoy the room."})]}),r==="error"&&e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"text-xl font-semibold text-slate-900",children:"We could not check you in."}),e.jsx("div",{className:"text-slate-500 mt-2",children:"Please see the host at the door."})]})]})})}function Dhn(s){const{user:t}=vs(),n=Kt(),r=dt({queryKey:["admin-attract-list",s,t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{let o=q.from("profiles").select("id, email, full_name").order("full_name",{ascending:!0}).limit(100);if(s.trim()){const p=`%${s.trim()}%`;o=o.or(`email.ilike.${p},full_name.ilike.${p}`)}const{data:c,error:d}=await o;if(d)throw d;const u=(c??[]).map(p=>p.id);let h={};if(u.length){const{data:p,error:f}=await q.from("feature_entitlements").select("user_id, enabled, tier, enabled_at, expires_at, notes, enabled_by").eq("feature_key","levelup_attract").in("user_id",u);if(f)throw f;(p??[]).forEach(y=>{h[y.user_id]=y})}return(c??[]).map(p=>{var f,y,_,v,j,w;return{user_id:p.id,email:p.email,full_name:p.full_name,enabled:!!((f=h[p.id])!=null&&f.enabled),tier:((y=h[p.id])==null?void 0:y.tier)??null,enabled_at:((_=h[p.id])==null?void 0:_.enabled_at)??null,expires_at:((v=h[p.id])==null?void 0:v.expires_at)??null,notes:((j=h[p.id])==null?void 0:j.notes)??null,enabled_by:((w=h[p.id])==null?void 0:w.enabled_by)??null}})}}),a=dt({queryKey:["admin-attract-audit",t==null?void 0:t.id],enabled:!!t,queryFn:async()=>{const{data:o,error:c}=await q.from("feature_entitlement_audit").select("*").eq("feature_key","levelup_attract").order("created_at",{ascending:!1}).limit(50);if(c)throw c;return o??[]}}),i=yt({mutationFn:async({target_user_id:o,tier:c,expires_at:d,notes:u})=>{const h={user_id:o,feature_key:"levelup_attract",enabled:!0,tier:c??"beta",enabled_by:t.id,enabled_at:new Date().toISOString(),expires_at:d??null,notes:u??null},{error:p}=await q.from("feature_entitlements").upsert(h,{onConflict:"user_id,feature_key"});if(p)throw p;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"grant",tier:h.tier,expires_at:h.expires_at,notes:h.notes,performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),ae.success("Access granted")},onError:o=>ae.error(o.message)}),l=yt({mutationFn:async o=>{const{error:c}=await q.from("feature_entitlements").update({enabled:!1}).eq("user_id",o).eq("feature_key","levelup_attract");if(c)throw c;await q.from("feature_entitlement_audit").insert({feature_key:"levelup_attract",target_user_id:o,action:"revoke",performed_by:t.id})},onSuccess:()=>{n.invalidateQueries({queryKey:["admin-attract-list"]}),n.invalidateQueries({queryKey:["admin-attract-audit"]}),ae.success("Access revoked")},onError:o=>ae.error(o.message)});return{list:r,audit:a,grant:i,revoke:l}}function Rhn(){const[s,t]=N.useState(""),{list:n,audit:r,grant:a,revoke:i}=Dhn(s),[l,o]=N.useState(null),[c,d]=N.useState(null),[u,h]=N.useState("beta"),[p,f]=N.useState(""),[y,_]=N.useState(""),v=w=>{d(w),h(w.tier??"beta"),f(w.expires_at?w.expires_at.slice(0,10):""),_(w.notes??"")},j=async()=>{c&&(await a.mutateAsync({target_user_id:c.user_id,tier:u,expires_at:p?new Date(p).toISOString():null,notes:y||void 0}),d(null))};return e.jsxs("div",{className:"p-6",children:[e.jsx(Bd,{title:"LevelUp Attract — Access Management",description:"Grant or revoke access to LevelUp Attract for individual members. Every change is audited."}),e.jsx(fe,{className:"p-4 rounded-2xl mb-4",children:e.jsxs("div",{className:"relative max-w-md",children:[e.jsx(gr,{className:"absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-slate-400"}),e.jsx(ye,{value:s,onChange:w=>t(w.target.value),placeholder:"Search by name or email...",className:"pl-9"})]})}),e.jsxs(fe,{className:"rounded-2xl overflow-hidden mb-8",children:[e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 text-[11px] uppercase tracking-widest text-slate-500 font-semibold border-b",children:[e.jsx("div",{children:"Member"}),e.jsx("div",{children:"Access"}),e.jsx("div",{children:"Enabled"}),e.jsx("div",{children:"Actions"})]}),n.isLoading&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"Loading members…"}),!n.isLoading&&(n.data??[]).length===0&&e.jsx("div",{className:"p-6 text-center text-slate-500 text-sm",children:"No members match."}),(n.data??[]).map(w=>e.jsxs("div",{className:"grid grid-cols-[1fr_auto_auto_auto] gap-3 px-5 py-3 items-center border-b last:border-0 hover:bg-slate-50",children:[e.jsxs("div",{className:"min-w-0",children:[e.jsx("div",{className:"text-[13.5px] font-medium text-slate-900 truncate",children:w.full_name||w.email||w.user_id}),e.jsx("div",{className:"text-[11.5px] text-slate-500 truncate",children:w.email})]}),e.jsx("div",{children:w.enabled?e.jsxs(Ue,{className:"bg-emerald-100 text-emerald-800 border-0 gap-1",children:[e.jsx(un,{className:"h-3 w-3"})," ",w.tier??"enabled"]}):e.jsx(Ue,{variant:"outline",className:"text-slate-500",children:"Not enabled"})}),e.jsx("div",{className:"text-[11.5px] text-slate-500 whitespace-nowrap",children:w.enabled_at?Ss(new Date(w.enabled_at),"MMM d, yyyy"):"—"}),e.jsx("div",{className:"flex gap-1.5",children:w.enabled?e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>v(w),children:"Edit"}),e.jsx(B,{size:"sm",variant:"ghost",className:"text-rose-600",onClick:()=>o({user:w,action:"revoke"}),children:"Revoke"})]}):e.jsxs(B,{size:"sm",className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:()=>v(w),children:[e.jsx(eg,{className:"h-3.5 w-3.5 mr-1"})," Enable"]})})]},w.user_id))]}),e.jsxs(fe,{className:"rounded-2xl p-5",children:[e.jsxs("div",{className:"flex items-center gap-2 mb-3 text-[12px] uppercase tracking-widest text-slate-500 font-semibold",children:[e.jsx(kA,{className:"h-3.5 w-3.5"})," Recent audit history"]}),r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"Loading…"}),(r.data??[]).length===0&&!r.isLoading&&e.jsx("div",{className:"text-slate-500 text-sm",children:"No changes yet."}),e.jsx("div",{className:"space-y-1.5",children:(r.data??[]).map(w=>e.jsxs("div",{className:"text-[12.5px] text-slate-700 flex items-center gap-2",children:[e.jsx(Ue,{variant:"outline",className:"text-[10.5px] capitalize",children:w.action}),e.jsx("span",{className:"font-mono text-[11px] text-slate-500",children:w.target_user_id.slice(0,8)}),w.tier&&e.jsxs("span",{className:"text-slate-500",children:["· ",w.tier]}),w.notes&&e.jsxs("span",{className:"text-slate-500",children:["· ",w.notes]}),e.jsx("span",{className:"text-slate-400 ml-auto",children:Ss(new Date(w.created_at),"MMM d h:mm a")})]},w.id))})]}),e.jsx(_s,{open:!!c,onOpenChange:w=>!w&&d(null),children:e.jsxs(bs,{children:[e.jsxs(js,{children:[e.jsxs(ws,{children:[c!=null&&c.enabled?"Update":"Enable"," Attract access"]}),e.jsx(Jn,{children:(c==null?void 0:c.full_name)||(c==null?void 0:c.email)})]}),e.jsxs("div",{className:"space-y-3",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Tier"}),e.jsxs(us,{value:u,onValueChange:h,children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"beta",children:"Beta"}),e.jsx(Ze,{value:"standard",children:"Standard"}),e.jsx(Ze,{value:"pro",children:"Pro"}),e.jsx(Ze,{value:"founder",children:"Founder"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Expires (optional)"}),e.jsx(ye,{type:"date",value:p,onChange:w=>f(w.target.value)})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Internal notes (optional)"}),e.jsx(Ms,{rows:2,value:y,onChange:w=>_(w.target.value)})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"ghost",onClick:()=>d(null),children:"Cancel"}),e.jsx(B,{className:"bg-gradient-to-r from-violet-600 to-indigo-600",onClick:j,disabled:a.isPending,children:c!=null&&c.enabled?"Save changes":"Enable access"})]})]})}),e.jsx(Oo,{open:!!l,onOpenChange:w=>!w&&o(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Revoke Attract access?"}),e.jsxs(Mo,{children:[(l==null?void 0:l.user.full_name)||(l==null?void 0:l.user.email)," will lose access to LevelUp Attract immediately. Their data is preserved and access can be re-enabled."]})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsxs(wo,{className:"bg-rose-600 hover:bg-rose-700",onClick:async()=>{l&&await i.mutateAsync(l.user.user_id),o(null)},children:[e.jsx(Uc,{className:"h-4 w-4 mr-1.5"})," Revoke access"]})]})]})})]})}const Ohn=({team:s,onSelect:t})=>{const{data:n}=dt({queryKey:["team-card-info",s.id],queryFn:async()=>{const{data:r}=await q.from("team_members").select("user_id, role").eq("team_id",s.id),a=(r==null?void 0:r.length)||0,i=r==null?void 0:r.find(o=>o.role==="team_leader");let l=null;if(i){const{data:o}=await q.from("profiles").select("name, avatar_url").eq("id",i.user_id).single();l=o}return{count:a,leaderProfile:l}}});return e.jsxs(fe,{className:"cursor-pointer hover:shadow-md transition-shadow group",onClick:t,children:[e.jsx(It,{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(Rt,{className:"text-lg truncate",children:s.name}),s.description&&e.jsx(Vn,{className:"mt-1 line-clamp-2",children:s.description})]}),e.jsxs(Ue,{variant:"secondary",className:"ml-2 shrink-0",children:[e.jsx(An,{className:"h-3 w-3 mr-1"}),(n==null?void 0:n.count)??"…"]})]})}),e.jsxs(Ee,{className:"space-y-3",children:[(n==null?void 0:n.leaderProfile)&&e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(Jr,{className:"h-6 w-6",children:[e.jsx(ti,{src:n.leaderProfile.avatar_url||""}),e.jsx(ea,{className:"text-xs",children:(n.leaderProfile.name||"?").charAt(0).toUpperCase()})]}),e.jsxs("span",{className:"text-sm text-muted-foreground flex items-center gap-1",children:[e.jsx(hf,{className:"h-3 w-3 text-[hsl(var(--chart-4))]"}),n.leaderProfile.name||"Team Leader"]})]}),e.jsxs("div",{className:"flex items-center gap-2 flex-wrap text-sm text-muted-foreground",children:[e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(Ih,{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(Ue,{variant:"outline",className:"text-xs py-0",children:"Lead Pond"}),s.shared_assets_enabled&&e.jsx(Ue,{variant:"outline",className:"text-xs py-0",children:"Shared Assets"}),s.shared_videos_enabled&&e.jsx(Ue,{variant:"outline",className:"text-xs py-0",children:"Shared Videos"})]})]})]})},Fhn=()=>{const{user:s,isAdmin:t,isBrokerageManager:n,brokerageId:r,managedBrokerages:a,selectedBrokerageId:i}=vs(),l=i||(a.length>0?a[0].id:r),o=t?void 0:l||void 0,{teams:c,isLoading:d,createTeam:u,updateTeam:h,deleteTeam:p,addMember:f,removeMember:y,updateMemberRole:_}=YM(o),[v,j]=N.useState(!1),[w,S]=N.useState(null),{data:A}=dt({queryKey:["all-brokerages-for-teams"],queryFn:async()=>{const{data:D,error:I}=await q.from("brokerages").select("id, name").order("name");if(I)throw I;return D||[]},enabled:t}),{data:E}=dt({queryKey:["brokerage-agents-for-teams",l],queryFn:async()=>{const{data:D,error:I}=await q.from("profiles").select("id, name, email, avatar_url").eq("brokerage_id",l).order("name");if(I)throw I;return D||[]},enabled:!!l}),O=async D=>{const I=D.brokerage_id||l||null,F=await u.mutateAsync({name:D.name,brokerage_id:I,description:D.description});if(D.leaderId&&D.leaderId!=="none"&&await f.mutateAsync({team_id:F.id,user_id:D.leaderId,role:"team_leader"}),D.memberIds)for(const z of D.memberIds)await f.mutateAsync({team_id:F.id,user_id:z,role:"team_member"});j(!1)};return!n&&!t?e.jsx(Cs,{title:"Teams",description:"Team Management",children:e.jsxs("div",{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(An,{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(Cs,{title:"Teams",description:"Create and manage teams within your brokerage",children:e.jsxs("div",{className:"space-y-6",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h2",{className:"text-2xl font-bold tracking-tight",children:"Teams"}),e.jsx("p",{className:"text-muted-foreground",children:"Organize your agents into teams with leaders and shared resources."})]}),e.jsxs(B,{onClick:()=>j(!0),children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Team"]})]}),e.jsx(F0t,{open:v,onOpenChange:j,onCreateTeam:O,isCreating:u.isPending,brokerageAgents:E||[],isAdmin:t,allBrokerages:A,activeBrokerageId:l}),d&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:[1,2,3].map(D=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-6",children:[e.jsx(Ws,{className:"h-5 w-32 mb-3"}),e.jsx(Ws,{className:"h-4 w-48 mb-4"}),e.jsx(Ws,{className:"h-8 w-full"})]})},D))}),!d&&c.length===0&&!w&&e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(An,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold mb-2",children:"No Teams Yet"}),e.jsx("p",{className:"text-muted-foreground mb-4",children:"Create your first team to organize agents and share resources."}),e.jsxs(B,{onClick:()=>j(!0),children:[e.jsx(Is,{className:"mr-2 h-4 w-4"}),"Create Your First Team"]})]})}),!d&&c.length>0&&!w&&e.jsx("div",{className:"grid gap-4 md:grid-cols-2 lg:grid-cols-3",children:c.map(D=>e.jsx(Ohn,{team:D,onSelect:()=>S(D)},D.id))}),w&&e.jsx(O0t,{team:w,brokerageAgents:E||[],onBack:()=>S(null),onUpdate:D=>h.mutateAsync({id:w.id,...D}).then(I=>S(I)),onAddMember:(D,I)=>f.mutateAsync({team_id:w.id,user_id:D,role:I}),onRemoveMember:D=>y.mutateAsync({team_id:w.id,member_id:D}),onUpdateRole:(D,I)=>_.mutateAsync({team_id:w.id,member_id:D,role:I}),onDeleteTeam:()=>p.mutate(w.id),isUpdating:h.isPending,isAddingMember:f.isPending})]})})},zhn=()=>{const{data:s,isLoading:t}=Wv(),{useTeamMembers:n}=YM(),{data:r=[],isLoading:a}=n((s==null?void 0:s.teamId)||"");if(t)return e.jsx(Cs,{title:"My Team",description:"Your team",children:e.jsxs("div",{className:"space-y-4",children:[e.jsx(Ws,{className:"h-8 w-48"}),e.jsx(Ws,{className:"h-40 w-full"})]})});if(!s)return e.jsx(Cs,{title:"My Team",description:"Your team",children:e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-12 text-center",children:[e.jsx(An,{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(Cs,{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(Ue,{variant:s.role==="team_leader"?"default":"secondary",className:"capitalize",children:s.role==="team_leader"?e.jsxs(e.Fragment,{children:[e.jsx(hf,{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(Fr,{defaultValue:"members",className:"space-y-4",children:[e.jsxs(Rr,{className:"flex-wrap",children:[e.jsx(Zt,{value:"members",children:"Members"}),i.contact_visibility!=="private"&&e.jsxs(Zt,{value:"contacts",children:[e.jsx(bA,{className:"mr-1 h-3.5 w-3.5"}),"Team Contacts"]}),i.lead_pond_enabled&&e.jsxs(Zt,{value:"lead-pond",children:[e.jsx(db,{className:"mr-1 h-3.5 w-3.5"}),"Lead Pond"]}),i.shared_assets_enabled&&e.jsxs(Zt,{value:"shared-assets",children:[e.jsx(pf,{className:"mr-1 h-3.5 w-3.5"}),"Shared Assets"]})]}),e.jsx(is,{value:"members",className:"space-y-2",children:a?e.jsx("div",{className:"space-y-3",children:[1,2,3].map(l=>e.jsx(Ws,{className:"h-16 w-full"},l))}):r.map(l=>{var o,c,d,u;return e.jsx(fe,{children:e.jsxs(Ee,{className:"flex items-center gap-3 p-4",children:[e.jsxs(Jr,{className:"h-10 w-10",children:[e.jsx(ti,{src:((o=l.profile)==null?void 0:o.avatar_url)||""}),e.jsx(ea,{children:(((c=l.profile)==null?void 0:c.name)||"?").charAt(0).toUpperCase()})]}),e.jsxs("div",{className:"min-w-0",children:[e.jsx("p",{className:"font-medium",children:((d=l.profile)==null?void 0:d.name)||"Unknown"}),e.jsx("p",{className:"text-sm text-muted-foreground",children:(u=l.profile)==null?void 0:u.email})]}),l.role==="team_leader"?e.jsxs(Ue,{className:"ml-auto bg-amber-500/10 text-amber-600 border-amber-500",children:[e.jsx(hf,{className:"mr-1 h-3 w-3"})," Leader"]}):e.jsx(Ue,{variant:"secondary",className:"ml-auto",children:"Member"})]})},l.id)})}),i.contact_visibility!=="private"&&e.jsx(is,{value:"contacts",className:"space-y-4",children:e.jsx(TIe,{})}),i.lead_pond_enabled&&e.jsx(is,{value:"lead-pond",className:"space-y-4",children:e.jsx(EIe,{teamId:s.teamId})}),i.shared_assets_enabled&&e.jsx(is,{value:"shared-assets",className:"space-y-4",children:e.jsx(R0t,{teamId:s.teamId})})]})]})})};function Bhn(){const{user:s}=vs(),t=Kt(),n=dt({queryKey:["booking-settings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_settings").select("*").eq("user_id",s.id).maybeSingle();if(j)throw j;return v},enabled:!!s}),r=dt({queryKey:["booking-types",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_types").select("*").eq("user_id",s.id).order("sort_order");if(j)throw j;return v},enabled:!!s}),a=dt({queryKey:["availability-slots",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_availability_slots").select("*").eq("user_id",s.id).order("day_of_week").order("start_time");if(j)throw j;return v},enabled:!!s}),i=dt({queryKey:["blocked-dates",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("agent_blocked_dates").select("*").eq("user_id",s.id).order("blocked_date");if(j)throw j;return v},enabled:!!s}),l=dt({queryKey:["bookings",s==null?void 0:s.id],queryFn:async()=>{const{data:v,error:j}=await q.from("bookings").select("*, booking_type:agent_booking_types(*)").eq("agent_user_id",s.id).order("booking_date",{ascending:!1});if(j)throw j;return v},enabled:!!s}),o=yt({mutationFn:async()=>{const{data:v,error:j}=await q.from("agent_booking_settings").insert({user_id:s.id,slug:""}).select().single();if(j)throw j;const w=[{name:"Listing Consultation",description:"Get a comprehensive market analysis and listing strategy for your home",duration_minutes:60,color:"#10B981",icon:"Home",sort_order:0},{name:"Buyer Consultation",description:"Discuss your home search criteria, budget, and buying process",duration_minutes:45,color:"#3B82F6",icon:"Search",sort_order:1},{name:"Home Valuation",description:"Find out what your home is worth in today's market",duration_minutes:30,color:"#F59E0B",icon:"DollarSign",sort_order:2},{name:"General Meeting",description:"Coffee chat, check-in, or quick real estate question",duration_minutes:30,color:"#8B5CF6",icon:"Coffee",sort_order:3}],{error:S}=await q.from("agent_booking_types").insert(w.map(O=>({...O,user_id:s.id})));if(S)throw S;const A=[1,2,3,4,5].map(O=>({user_id:s.id,day_of_week:O,start_time:"09:00",end_time:"17:00"})),{error:E}=await q.from("agent_availability_slots").insert(A);if(E)throw E;return v},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),t.invalidateQueries({queryKey:["booking-types"]}),t.invalidateQueries({queryKey:["availability-slots"]}),ae.success("Scheduler set up successfully!")},onError:v=>ae.error(v.message)}),c=yt({mutationFn:async v=>{const{error:j}=await q.from("agent_booking_settings").update(v).eq("user_id",s.id);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-settings"]}),ae.success("Settings updated")},onError:v=>ae.error(v.message)}),d=yt({mutationFn:async v=>{const j={...v,user_id:s.id};if(v.id){const{error:w}=await q.from("agent_booking_types").update(j).eq("id",v.id);if(w)throw w}else{const{error:w}=await q.from("agent_booking_types").insert(j);if(w)throw w}},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type saved")},onError:v=>ae.error(v.message)}),u=yt({mutationFn:async v=>{const{error:j}=await q.from("agent_booking_types").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["booking-types"]}),ae.success("Booking type deleted")},onError:v=>ae.error(v.message)}),h=yt({mutationFn:async v=>{const j={...v,user_id:s.id};if(v.id){const{error:w}=await q.from("agent_availability_slots").update(j).eq("id",v.id);if(w)throw w}else{const{error:w}=await q.from("agent_availability_slots").insert(j);if(w)throw w}},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ae.error(v.message)}),p=yt({mutationFn:async v=>{const{error:j}=await q.from("agent_availability_slots").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["availability-slots"]})},onError:v=>ae.error(v.message)}),f=yt({mutationFn:async v=>{const{error:j}=await q.from("agent_blocked_dates").insert({...v,user_id:s.id});if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]}),ae.success("Date blocked")},onError:v=>ae.error(v.message)}),y=yt({mutationFn:async v=>{const{error:j}=await q.from("agent_blocked_dates").delete().eq("id",v);if(j)throw j},onSuccess:()=>{t.invalidateQueries({queryKey:["blocked-dates"]})},onError:v=>ae.error(v.message)}),_=yt({mutationFn:async({id:v,reason:j})=>{const{error:w}=await q.from("bookings").update({status:"cancelled",cancelled_at:new Date().toISOString(),cancel_reason:j}).eq("id",v);if(w)throw w},onSuccess:()=>{t.invalidateQueries({queryKey:["bookings"]}),ae.success("Booking cancelled")},onError:v=>ae.error(v.message)});return{settings:n.data,bookingTypes:r.data??[],availability:a.data??[],blockedDates:i.data??[],bookings:l.data??[],isLoading:n.isLoading,initializeSettings:o,updateSettings:c,upsertBookingType:d,deleteBookingType:u,upsertAvailability:h,deleteAvailability:p,addBlockedDate:f,removeBlockedDate:y,cancelBooking:_}}const Bet={Home:"🏠",Search:"🔍",DollarSign:"💰",Coffee:"☕",Calendar:"📅",Users:"👥",Phone:"📞",Video:"🎥"};function $hn({types:s,onSave:t,onDelete:n}){const[r,a]=N.useState(null),[i,l]=N.useState(!1),o=()=>{a({name:"",description:"",duration_minutes:30,color:"#3B82F6",icon:"Calendar",is_active:!0,qualification_enabled:!1}),l(!0)},c=u=>{a({...u}),l(!0)},d=()=>{r!=null&&r.name&&(t(r),l(!1),a(null))};return e.jsxs(e.Fragment,{children:[e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(Rt,{children:"Booking Types"}),e.jsx(Vn,{children:"The meeting types prospects can book with you"})]}),e.jsxs(B,{onClick:o,size:"sm",children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Add Type"]})]}),e.jsx(Ee,{children:s.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No booking types yet. Add one to get started."}):e.jsx("div",{className:"grid gap-3",children:s.map(u=>e.jsxs("div",{className:"flex items-center justify-between p-4 rounded-lg border hover:bg-muted/50 transition-colors",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx("div",{className:"w-10 h-10 rounded-lg flex items-center justify-center text-lg",style:{backgroundColor:u.color+"20"},children:Bet[u.icon]||"📅"}),e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("p",{className:"font-medium",children:u.name}),!u.is_active&&e.jsx(Ue,{variant:"secondary",className:"text-xs",children:"Inactive"}),u.qualification_enabled&&e.jsxs(Ue,{variant:"outline",className:"text-xs gap-1",children:[e.jsx(n9,{className:"h-3 w-3"})," Qualifying"]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx(pr,{className:"h-3 w-3"}),u.duration_minutes," min",u.description&&e.jsxs("span",{children:["· ",u.description.slice(0,60),u.description.length>60?"...":""]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-1",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>c(u),children:e.jsx(ya,{className:"h-4 w-4"})}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>n(u.id),className:"text-destructive hover:text-destructive",children:e.jsx(_n,{className:"h-4 w-4"})})]})]},u.id))})})]}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsxs(ws,{children:[r!=null&&r.id?"Edit":"New"," Booking Type"]})}),r&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Name"}),e.jsx(ye,{value:r.name||"",onChange:u=>a({...r,name:u.target.value}),placeholder:"e.g. Listing Consultation"})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{value:r.description||"",onChange:u=>a({...r,description:u.target.value}),placeholder:"Brief description for prospects",rows:2})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Duration (minutes)"}),e.jsx(ye,{type:"number",min:15,max:180,step:15,value:r.duration_minutes||30,onChange:u=>a({...r,duration_minutes:parseInt(u.target.value)||30})})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Color"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("input",{type:"color",value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"h-10 w-10 rounded border cursor-pointer"}),e.jsx(ye,{value:r.color||"#3B82F6",onChange:u=>a({...r,color:u.target.value}),className:"flex-1"})]})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Icon"}),e.jsx("div",{className:"flex flex-wrap gap-2",children:Object.entries(Bet).map(([u,h])=>e.jsx("button",{onClick:()=>a({...r,icon:u}),className:`w-10 h-10 rounded-lg text-lg flex items-center justify-center border transition-colors ${r.icon===u?"border-primary bg-primary/10":"hover:bg-muted"}`,children:h},u))})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Meeting Link Override (optional)"}),e.jsx(ye,{value:r.meeting_link_override||"",onChange:u=>a({...r,meeting_link_override:u.target.value||null}),placeholder:"Use a different link for this type"})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Pre-Qualification Questions"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Ask qualifying questions before booking"})]}),e.jsx(jn,{checked:r.qualification_enabled||!1,onCheckedChange:u=>a({...r,qualification_enabled:u})})]}),e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Active"}),e.jsx(jn,{checked:r.is_active??!0,onCheckedChange:u=>a({...r,is_active:u})})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:d,children:"Save"})]})]})})]})}const $et=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];function Uhn({slots:s,onSave:t,onDelete:n}){const[r,a]=N.useState(null),[i,l]=N.useState("09:00"),[o,c]=N.useState("17:00"),d=$et.map((h,p)=>s.filter(f=>f.day_of_week===p)),u=()=>{r!==null&&(t({day_of_week:r,start_time:i,end_time:o,is_active:!0}),a(null),l("09:00"),c("17:00"))};return e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(pr,{className:"h-5 w-5"}),"Weekly Availability"]}),e.jsx(Vn,{children:"Set your available hours for each day"})]}),e.jsx(Ee,{className:"space-y-2",children:$et.map((h,p)=>{const f=d[p];return e.jsxs("div",{className:"flex items-start gap-3 py-2 border-b last:border-0",children:[e.jsx("div",{className:"w-24 pt-1",children:e.jsx("p",{className:"text-sm font-medium",children:h})}),e.jsxs("div",{className:"flex-1 space-y-1",children:[f.length===0?e.jsx("p",{className:"text-sm text-muted-foreground py-1",children:"Unavailable"}):f.map(y=>{var _,v;return e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(_=y.start_time)==null?void 0:_.slice(0,5),onBlur:j=>t({id:y.id,start_time:j.target.value})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",defaultValue:(v=y.end_time)==null?void 0:v.slice(0,5),onBlur:j=>t({id:y.id,end_time:j.target.value})}),e.jsx(jn,{checked:y.is_active,onCheckedChange:j=>t({id:y.id,is_active:j})}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>n(y.id),children:e.jsx(_n,{className:"h-3.5 w-3.5 text-muted-foreground"})})]},y.id)}),r===p?e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",value:i,onChange:y=>l(y.target.value)}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"to"}),e.jsx(ye,{type:"time",className:"w-28 h-8 text-sm",value:o,onChange:y=>c(y.target.value)}),e.jsx(B,{size:"sm",className:"h-8",onClick:u,children:"Add"}),e.jsx(B,{variant:"ghost",size:"sm",className:"h-8",onClick:()=>a(null),children:"Cancel"})]}):e.jsxs(B,{variant:"ghost",size:"sm",className:"h-7 text-xs text-muted-foreground",onClick:()=>a(p),children:[e.jsx(Is,{className:"h-3 w-3 mr-1"})," Add hours"]})]})]},h)})})]})}const qhn={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 Vhn({bookings:s,onCancel:t}){const n=s.filter(i=>i.status==="confirmed"&&new Date(i.booking_date)>=new Date(new Date().toDateString())),r=s.filter(i=>i.status!=="confirmed"||new Date(i.booking_date){var o,c;return e.jsxs("div",{className:"flex items-start justify-between p-4 rounded-lg border hover:bg-muted/30 transition-colors",children:[e.jsxs("div",{className:"space-y-1",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(Wi,{className:"h-4 w-4 text-muted-foreground"}),e.jsx("span",{className:"font-medium",children:i.guest_name}),e.jsx(Ue,{className:`text-xs ${qhn[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(Cl,{className:"h-3.5 w-3.5"}),Ss(new Date(i.booking_date+"T00:00:00"),"MMM d, yyyy")]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(pr,{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(Gs,{className:"h-3 w-3"}),i.guest_email]}),i.guest_phone&&e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(Cr,{className:"h-3 w-3"}),i.guest_phone]})]}),i.booking_type&&e.jsx(Ue,{variant:"outline",className:"text-xs mt-1",children:i.booking_type.name}),i.guest_message&&e.jsxs("p",{className:"text-sm text-muted-foreground mt-1 italic",children:['"',i.guest_message,'"']})]}),l&&i.status==="confirmed"&&e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>t(i.id),className:"text-destructive hover:text-destructive",children:[e.jsx(Uc,{className:"h-4 w-4 mr-1"})," Cancel"]})]},i.id)};return e.jsxs("div",{className:"space-y-6",children:[e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Upcoming Bookings"}),e.jsxs(Vn,{children:[n.length," upcoming appointment",n.length!==1?"s":""]})]}),e.jsx(Ee,{children:n.length===0?e.jsx("p",{className:"text-center text-muted-foreground py-8",children:"No upcoming bookings"}):e.jsx("div",{className:"space-y-3",children:n.map(i=>a(i,!0))})})]}),r.length>0&&e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Past & Cancelled"})}),e.jsx(Ee,{children:e.jsx("div",{className:"space-y-3",children:r.slice(0,20).map(i=>a(i))})})]})]})}function Hhn({blockedDates:s,onAdd:t,onRemove:n}){const[r,a]=N.useState(!1),[i,l]=N.useState(""),[o,c]=N.useState(""),d=()=>{i&&(t({blocked_date:i,reason:o||void 0}),a(!1),l(""),c(""))};return e.jsxs(fe,{children:[e.jsxs(It,{className:"flex flex-row items-center justify-between",children:[e.jsxs("div",{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(F7,{className:"h-5 w-5"}),"Blocked Dates"]}),e.jsx(Vn,{children:"Block specific dates (vacations, holidays, etc.)"})]}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>a(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-1"})," Block Date"]})]}),e.jsxs(Ee,{children:[r&&e.jsxs("div",{className:"flex items-center gap-2 mb-3 p-3 rounded-lg border bg-muted/30",children:[e.jsx(ye,{type:"date",value:i,onChange:u=>l(u.target.value),className:"w-40"}),e.jsx(ye,{placeholder:"Reason (optional)",value:o,onChange:u=>c(u.target.value),className:"flex-1"}),e.jsx(B,{size:"sm",onClick:d,children:"Add"}),e.jsx(B,{size:"sm",variant:"ghost",onClick:()=>a(!1),children:"Cancel"})]}),s.length===0?e.jsx("p",{className:"text-sm text-muted-foreground text-center py-4",children:"No blocked dates"}):e.jsx("div",{className:"flex flex-wrap gap-2",children:s.map(u=>e.jsxs("div",{className:"flex items-center gap-1.5 px-3 py-1.5 rounded-full border bg-muted/50 text-sm",children:[e.jsx("span",{children:Ss(new Date(u.blocked_date+"T00:00:00"),"MMM d, yyyy")}),u.reason&&e.jsxs("span",{className:"text-muted-foreground",children:["(",u.reason,")"]}),e.jsx("button",{onClick:()=>n(u.id),className:"ml-1 text-muted-foreground hover:text-destructive",children:e.jsx($n,{className:"h-3.5 w-3.5"})})]},u.id))})]})]})}function Ghn(){const{settings:s,bookingTypes:t,availability:n,blockedDates:r,bookings:a,isLoading:i,initializeSettings:l,updateSettings:o,upsertBookingType:c,deleteBookingType:d,upsertAvailability:u,deleteAvailability:h,addBlockedDate:p,removeBlockedDate:f,cancelBooking:y}=Bhn(),[_,v]=N.useState("");N.useState(15),_||s!=null&&s.meeting_link;const j=s!=null&&s.slug?`https://booking.relevelup.com/${s.slug}`:null;return i?e.jsx(Cs,{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(Cs,{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(Cl,{className:"h-6 w-6 text-primary"}),"LevelUp Scheduler"]}),e.jsx("p",{className:"text-muted-foreground",children:"Manage your booking types, availability, and appointments"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[j&&e.jsxs(e.Fragment,{children:[e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{navigator.clipboard.writeText(j),ae.success("Booking link copied!")},children:[e.jsx(Zr,{className:"h-4 w-4 mr-1"})," Copy Link"]}),e.jsx(B,{variant:"outline",size:"sm",asChild:!0,children:e.jsxs("a",{href:j,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-4 w-4 mr-1"})," Preview"]})})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ne,{htmlFor:"scheduler-active",className:"text-sm",children:"Active"}),e.jsx(jn,{id:"scheduler-active",checked:s.is_active,onCheckedChange:w=>o.mutate({is_active:w})})]})]})]}),e.jsxs(Fr,{defaultValue:"types",className:"space-y-4",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"types",children:"Booking Types"}),e.jsx(Zt,{value:"availability",children:"Availability"}),e.jsx(Zt,{value:"settings",children:"Settings"}),e.jsxs(Zt,{value:"bookings",children:["Bookings",a.filter(w=>w.status==="confirmed").length>0&&e.jsx(Ue,{variant:"secondary",className:"ml-1.5 text-xs",children:a.filter(w=>w.status==="confirmed").length})]})]}),e.jsx(is,{value:"types",children:e.jsx($hn,{types:t,onSave:w=>c.mutate(w),onDelete:w=>d.mutate(w)})}),e.jsx(is,{value:"availability",children:e.jsxs("div",{className:"space-y-6",children:[e.jsx(Uhn,{slots:n,onSave:w=>u.mutate(w),onDelete:w=>h.mutate(w)}),e.jsx(Hhn,{blockedDates:r,onAdd:w=>p.mutate(w),onRemove:w=>f.mutate(w)})]})}),e.jsx(is,{value:"settings",children:e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsxs(Rt,{className:"flex items-center gap-2",children:[e.jsx(g9,{className:"h-5 w-5"}),"General Settings"]}),e.jsx(Vn,{children:"Configure your booking page defaults"})]}),e.jsxs(Ee,{className:"space-y-6",children:[e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Booking Page URL"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{value:s.slug,readOnly:!0,className:"bg-muted"}),e.jsx(B,{variant:"outline",size:"sm",onClick:()=>{j&&(navigator.clipboard.writeText(j),ae.success("Copied!"))},children:e.jsx(Zr,{className:"h-4 w-4"})})]}),e.jsx("p",{className:"text-xs text-muted-foreground",children:j})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsxs(ne,{htmlFor:"meeting-link",children:[e.jsx(Tl,{className:"h-4 w-4 inline mr-1"}),"Default Meeting Link"]}),e.jsx(ye,{id:"meeting-link",placeholder:"https://zoom.us/j/your-personal-link",defaultValue:s.meeting_link||"",onBlur:w=>o.mutate({meeting_link:w.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(ne,{children:"Buffer Between Meetings"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",min:0,max:60,defaultValue:s.buffer_minutes,onBlur:w=>o.mutate({buffer_minutes:parseInt(w.target.value)||15})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"min"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Minimum Notice"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",min:0,max:72,defaultValue:s.min_notice_hours,onBlur:w=>o.mutate({min_notice_hours:parseInt(w.target.value)||2})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"hours"})]})]}),e.jsxs("div",{className:"space-y-2",children:[e.jsx(ne,{children:"Max Advance Booking"}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(ye,{type:"number",min:1,max:90,defaultValue:s.max_advance_days,onBlur:w=>o.mutate({max_advance_days:parseInt(w.target.value)||30})}),e.jsx("span",{className:"text-sm text-muted-foreground",children:"days"})]})]})]})]})]})}),e.jsx(is,{value:"bookings",children:e.jsx(Vhn,{bookings:a,onCancel:w=>y.mutate({id:w})})})]})]})}):e.jsx(Cs,{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(Cl,{className:"h-8 w-8 text-primary"})}),e.jsx("h1",{className:"text-3xl font-bold",children:"LevelUp Scheduler"}),e.jsx("p",{className:"text-muted-foreground text-lg max-w-md mx-auto",children:"Your own booking page — built for real estate. Prospects book with you, get auto-added to your CRM, and you never miss a lead."})]}),e.jsx(fe,{children:e.jsxs(Ee,{className:"pt-6 space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 gap-4",children:[{icon:"🏠",title:"Listing Consultation",desc:"60 min"},{icon:"🔍",title:"Buyer Consultation",desc:"45 min"},{icon:"💰",title:"Home Valuation",desc:"30 min"},{icon:"☕",title:"General Meeting",desc:"30 min"}].map(w=>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:w.icon}),e.jsxs("div",{children:[e.jsx("p",{className:"font-medium text-sm",children:w.title}),e.jsx("p",{className:"text-xs text-muted-foreground",children:w.desc})]})]},w.title))}),e.jsx(al,{}),e.jsxs("div",{className:"space-y-2 text-sm text-muted-foreground",children:[e.jsx("p",{children:"✅ Auto-creates CRM contacts from every booking"}),e.jsx("p",{children:"✅ Optional pre-qualification questions per booking type"}),e.jsx("p",{children:"✅ Embeds on your Smart Card — replaces TidyCal"}),e.jsx("p",{children:"✅ Standalone shareable booking page"})]}),e.jsxs(B,{onClick:()=>l.mutate(),disabled:l.isPending,className:"w-full",size:"lg",children:[e.jsx(un,{className:"h-4 w-4 mr-2"}),l.isPending?"Setting up...":"Activate Scheduler"]})]})})]})})}const Uet=[{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 Whn(){const{user:s}=vs(),t=wa(),{toast:n}=Fa(),r=Ln(),a=Kt(),[i,l]=N.useState(!1),[o,c]=N.useState(null),[d,u]=N.useState(null),[h,p]=N.useState({title:"",description:"",page_type:"lead_capture"}),{data:f=[],isLoading:y}=dt({queryKey:["landing-pages",t],queryFn:async()=>{const{data:w,error:S}=await q.from("landing_pages").select("*").eq("user_id",t).is("deleted_at",null).order("created_at",{ascending:!1});if(S)throw S;return w},enabled:!!t}),_=yt({mutationFn:async()=>{const w=h.title.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/(^-|-$)/g,"")+"-"+Date.now().toString(36),{data:S}=await q.from("profiles").select("name, phone, avatar_url, email").eq("id",t).single(),A=h.page_type==="just_listed"||h.page_type==="just_sold",{data:E,error:O}=await q.from("landing_pages").insert({user_id:t,title:h.title,description:h.description||null,page_type:h.page_type,slug:w,hero_headline:A?h.page_type==="just_listed"?"🏡 Just Listed":"🎉 Just Sold":h.page_type==="lead_magnet"?"📥 Free Download":h.title,agent_name:(S==null?void 0:S.name)||null,agent_phone:(S==null?void 0:S.phone)||null,agent_email:(S==null?void 0:S.email)||s.email||null,agent_photo_url:(S==null?void 0:S.avatar_url)||null,property_status:A?h.page_type.replace("just_",""):null}).select().single();if(O)throw O;const D=Khn(h.page_type);if(D.length>0){const{error:I}=await q.from("landing_page_fields").insert(D.map((F,z)=>({...F,page_id:E.id,sort_order:z})));if(I)throw I}return E},onSuccess:w=>{a.invalidateQueries({queryKey:["landing-pages"]}),l(!1),p({title:"",description:"",page_type:"lead_capture"}),n({title:"Landing page created!"}),r(`/mission-control/landing-pages/${w.id}`)},onError:w=>n({title:"Error",description:w.message,variant:"destructive"})}),v=yt({mutationFn:async w=>{const{error:S}=await q.from("landing_pages").update({deleted_at:new Date().toISOString(),is_published:!1}).eq("id",w);if(S)throw S},onSuccess:()=>{a.invalidateQueries({queryKey:["landing-pages"]}),c(null),n({title:"Landing page deleted"})}}),j=w=>`https://pages.relevelup.com/${w}`;return e.jsxs(Cs,{title:"Landing Pages",children:[e.jsxs("div",{className:"space-y-6 max-w-5xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Pages"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1",children:"Create branded lead capture pages for events, consultations, and more"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsxs(B,{variant:"outline",onClick:()=>r("/mission-control/landing-pages/defaults"),children:[e.jsx(Ko,{className:"h-4 w-4 mr-2"})," Defaults"]}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," New Page"]})]})]}),y?e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})}):f.length===0?e.jsx(fe,{children:e.jsxs(Ee,{className:"flex flex-col items-center justify-center py-16",children:[e.jsx(br,{className:"h-12 w-12 text-muted-foreground mb-4"}),e.jsx("h3",{className:"text-lg font-semibold",children:"No landing pages yet"}),e.jsx("p",{className:"text-muted-foreground text-sm mt-1 mb-4",children:"Create your first page to start capturing leads"}),e.jsxs(B,{onClick:()=>l(!0),children:[e.jsx(Is,{className:"h-4 w-4 mr-2"})," Create Landing Page"]})]})}):e.jsx("div",{className:"grid gap-4",children:f.map(w=>{var S;return e.jsx(fe,{className:"hover:shadow-md transition-shadow",children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex-1 min-w-0 cursor-pointer",onClick:()=>r(`/mission-control/landing-pages/${w.id}`),children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("h3",{className:"font-semibold truncate",children:w.title}),e.jsx(Ue,{variant:w.is_published?"default":"secondary",className:"text-[10px]",children:w.is_published?"Published":"Draft"}),e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:((S=Uet.find(A=>A.id===w.page_type))==null?void 0:S.label)||w.page_type})]}),w.description&&e.jsx("p",{className:"text-sm text-muted-foreground mt-1 truncate",children:w.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(Sr,{className:"h-3 w-3"})," ",w.view_count," views"]}),e.jsxs("span",{className:"flex items-center gap-1",children:[e.jsx(br,{className:"h-3 w-3"})," ",w.submission_count," submissions"]})]})]}),e.jsxs("div",{className:"flex items-center gap-2 ml-4",children:[w.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>u(j(w.slug)),children:e.jsx(ry,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(j(w.slug)),n({title:"Link copied!"})},children:e.jsx(Zr,{className:"h-3.5 w-3.5"})}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsx("a",{href:j(w.slug),target:"_blank",rel:"noopener noreferrer",children:e.jsx(tr,{className:"h-3.5 w-3.5"})})})]}),e.jsxs(Mc,{children:[e.jsx(Ic,{asChild:!0,children:e.jsx(B,{size:"sm",variant:"ghost",children:e.jsx(Ag,{className:"h-4 w-4"})})}),e.jsxs(gc,{align:"end",children:[e.jsxs(Kr,{onClick:()=>r(`/mission-control/landing-pages/${w.id}`),children:[e.jsx(ya,{className:"h-3.5 w-3.5 mr-2"})," Edit"]}),e.jsxs(Kr,{onClick:()=>c(w.id),className:"text-destructive",children:[e.jsx(_n,{className:"h-3.5 w-3.5 mr-2"})," Delete"]})]})]})]})]})})},w.id)})})]}),e.jsx(_s,{open:i,onOpenChange:l,children:e.jsxs(bs,{children:[e.jsx(js,{children:e.jsx(ws,{children:"Create Landing Page"})}),e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Page Title"}),e.jsx(ye,{value:h.title,onChange:w=>p(S=>({...S,title:w.target.value})),placeholder:"e.g. Veterans Home & Land Expo"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Description (optional)"}),e.jsx(Ms,{value:h.description,onChange:w=>p(S=>({...S,description:w.target.value})),placeholder:"Brief internal description...",rows:2})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Page Template"}),e.jsxs(us,{value:h.page_type,onValueChange:w=>p(S=>({...S,page_type:w})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Uet.map(w=>e.jsx(Ze,{value:w.id,children:e.jsxs("div",{children:[e.jsx("div",{className:"font-medium",children:w.label}),e.jsx("div",{className:"text-xs text-muted-foreground",children:w.description})]})},w.id))})]})]})]}),e.jsxs(Xn,{children:[e.jsx(B,{variant:"outline",onClick:()=>l(!1),children:"Cancel"}),e.jsx(B,{onClick:()=>_.mutate(),disabled:!h.title.trim()||_.isPending,children:_.isPending?"Creating...":"Create Page"})]})]})}),e.jsx(Oo,{open:!!o,onOpenChange:()=>c(null),children:e.jsxs(Co,{children:[e.jsxs(To,{children:[e.jsx(Ao,{children:"Delete Landing Page?"}),e.jsx(Mo,{children:"This will permanently delete this page and all its submissions."})]}),e.jsxs(Eo,{children:[e.jsx(Io,{children:"Cancel"}),e.jsx(wo,{onClick:()=>o&&v.mutate(o),children:"Delete"})]})]})}),e.jsx(_s,{open:!!d,onOpenChange:()=>u(null),children:e.jsxs(bs,{className:"max-w-sm",children:[e.jsx(js,{children:e.jsx(ws,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[d&&e.jsx(zU,{value:d,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:d}),e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>{d&&(navigator.clipboard.writeText(d),n({title:"URL copied!"}))},children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"})," Copy URL"]})]})]})})]})}function Khn(s){const t=[{field_type:"text",label:"Full Name",placeholder:"Your name",is_required:!0},{field_type:"email",label:"Email",placeholder:"your@email.com",is_required:!0},{field_type:"phone",label:"Phone",placeholder:"(555) 123-4567",is_required:!1}];switch(s){case"event_registration":return[...t,{field_type:"select",label:"How did you hear about this event?",options:JSON.stringify(["Social Media","Friend/Referral","Email","Flyer/Sign","Other"]),is_required:!1},{field_type:"textarea",label:"Any questions or special needs?",placeholder:"Let us know...",is_required:!1}];case"buyer_consultation":return[...t,{field_type:"select",label:"Interested in",options:JSON.stringify(["Buying","Selling","Both"]),is_required:!0},{field_type:"select",label:"Timeline",options:JSON.stringify(["0-3 months","3-6 months","6-12 months","Just exploring"]),is_required:!1},{field_type:"toggle",label:"Already working with a Realtor?",is_required:!1},{field_type:"toggle",label:"Do you have property to sell?",is_required:!1},{field_type:"textarea",label:"Anything else we should know?",placeholder:"Tell us about your situation...",is_required:!1}];case"home_valuation":return[...t,{field_type:"text",label:"Property Address",placeholder:"123 Main St, City, State",is_required:!0},{field_type:"select",label:"Reason for Valuation",options:JSON.stringify(["Thinking of selling","Refinancing","Curiosity","Estate planning","Other"]),is_required:!1},{field_type:"select",label:"Timeline to Sell",options:JSON.stringify(["ASAP","1-3 months","3-6 months","6+ months","Not sure"]),is_required:!1}];case"lead_magnet":return[...t,{field_type:"select",label:"Are you currently working with a Realtor?",options:JSON.stringify(["Yes","No","Not yet"]),is_required:!1}];case"just_listed":return[...t,{field_type:"select",label:"I am interested in",options:JSON.stringify(["Scheduling a showing","Getting more details","Similar properties","Selling my home"]),is_required:!0},{field_type:"textarea",label:"Message",placeholder:"Tell me more about this property...",is_required:!1}];case"just_sold":return[...t,{field_type:"select",label:"I am looking to",options:JSON.stringify(["Sell my home","Buy a home","Both","Just curious"]),is_required:!0},{field_type:"text",label:"My Property Address",placeholder:"123 Main St, City, State",is_required:!1}];default:return[...t,{field_type:"textarea",label:"Message",placeholder:"How can we help you?",is_required:!1}]}}function Yhn(s,t){return t?`${(s/t*100).toFixed(1)}%`:"0%"}function Zhn({pageId:s}){const{data:t=[],isLoading:n}=dt({queryKey:["landing-page-events",s],queryFn:async()=>{const l=new Date(Date.now()-2592e6).toISOString(),{data:o,error:c}=await q.from("landing_page_events").select("event_type, session_id, utm_source, utm_medium, utm_campaign, referrer, device, created_at").eq("page_id",s).gte("created_at",l).order("created_at",{ascending:!1}).limit(1e3);if(c)throw c;return o||[]}}),{data:r=[]}=dt({queryKey:["landing-page-submissions-analytics",s],queryFn:async()=>{const{data:l}=await q.from("landing_page_submissions").select("id, created_at").eq("page_id",s);return l||[]}}),a=N.useMemo(()=>{const l=t.filter(y=>y.event_type==="view"),o=t.filter(y=>y.event_type==="click"),c=new Set(l.map(y=>y.session_id).filter(Boolean)),d=new Map,u=new Map,h=new Map;for(const y of l){const _=y.utm_source||"Direct / unknown";if(d.set(_,(d.get(_)||0)+1),y.referrer)try{const j=new URL(y.referrer).hostname.replace(/^www\./,"");u.set(j,(u.get(j)||0)+1)}catch{}const v=y.device||"unknown";h.set(v,(h.get(v)||0)+1)}const p=[];for(let y=13;y>=0;y--){const _=new Date;_.setHours(0,0,0,0),_.setDate(_.getDate()-y);const v=new Date(_);v.setDate(_.getDate()+1);const j=_.toLocaleDateString("en-US",{month:"numeric",day:"numeric"}),w=l.filter(A=>{const E=new Date(A.created_at);return E>=_&&E{const E=new Date(A.created_at);return E>=_&&Ey.views));return{views:l.length,sessions:c.size,clicks:o.length,submissions:r.length,conversion:Yhn(r.length,c.size||l.length),sourceCounts:[...d.entries()].sort((y,_)=>_[1]-y[1]).slice(0,6),referrerCounts:[...u.entries()].sort((y,_)=>_[1]-y[1]).slice(0,6),deviceCounts:[...h.entries()].sort((y,_)=>_[1]-y[1]),days:p,maxBar:f}},[t,r]);if(n)return e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:Array.from({length:4}).map((l,o)=>e.jsx(Ws,{className:"h-24"},o))});const i=[{label:"Views (30d)",value:a.views,icon:Sr},{label:"Unique visitors",value:a.sessions,icon:An},{label:"Submissions",value:a.submissions,icon:lr},{label:"Conversion rate",value:a.conversion,icon:go}];return e.jsxs("div",{className:"space-y-4",children:[e.jsx("div",{className:"grid grid-cols-2 md:grid-cols-4 gap-3",children:i.map(l=>e.jsx(fe,{children:e.jsxs(Ee,{className:"p-4",children:[e.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[e.jsx(l.icon,{className:"h-3.5 w-3.5"})," ",l.label]}),e.jsx("div",{className:"text-2xl font-semibold mt-1",children:l.value})]})},l.label))}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Last 14 days"})}),e.jsxs(Ee,{children:[a.views===0?e.jsx("p",{className:"text-sm text-muted-foreground",children:"No traffic yet. Share your page link or QR code to start collecting visits."}):e.jsx("div",{className:"flex items-end gap-1.5 h-32",children:a.days.map((l,o)=>e.jsxs("div",{className:"flex-1 flex flex-col items-center gap-1",children:[e.jsxs("div",{className:"w-full flex flex-col justify-end h-24",children:[e.jsx("div",{title:`${l.views} views · ${l.submits} submits`,className:"w-full rounded-t bg-primary/70",style:{height:`${l.views/a.maxBar*100}%`,minHeight:l.views?2:0}}),l.submits>0&&e.jsx("div",{className:"w-full bg-emerald-500",style:{height:`${Math.max(2,l.submits/a.maxBar*100)}%`}})]}),e.jsx("span",{className:"text-[10px] text-muted-foreground",children:l.label})]},o))}),e.jsxs("div",{className:"flex items-center gap-4 mt-3 text-xs text-muted-foreground",children:[e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-primary/70"})," Views"]}),e.jsxs("span",{className:"flex items-center gap-1.5",children:[e.jsx("span",{className:"w-2 h-2 rounded-sm bg-emerald-500"})," Submissions"]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-3",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(oc,{className:"h-4 w-4"})," Top sources"]})}),e.jsx(Ee,{children:a.sourceCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No UTM data yet."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.sourceCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Top referrers"})}),e.jsx(Ee,{children:a.referrerCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No external referrers tracked."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.referrerCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"truncate",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Devices"})}),e.jsx(Ee,{children:a.deviceCounts.length===0?e.jsx("p",{className:"text-xs text-muted-foreground",children:"No device data."}):e.jsx("ul",{className:"space-y-1.5 text-sm",children:a.deviceCounts.map(([l,o])=>e.jsxs("li",{className:"flex justify-between",children:[e.jsx("span",{className:"capitalize",children:l}),e.jsx("span",{className:"text-muted-foreground",children:o})]},l))})})]})]})]})}const Qhn=[{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 Xhn=0;const qet=()=>`f_${Date.now()}_${++Xhn}`;function Jhn({field:s,index:t,updateField:n,removeField:r}){const{attributes:a,listeners:i,setNodeRef:l,transform:o,transition:c,isDragging:d}=gve({id:s.clientId}),u={transform:E4.Transform.toString(o),transition:c,zIndex:d?50:void 0,opacity:d?.85:1};return e.jsx(fe,{ref:l,style:u,children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start gap-3",children:[e.jsx("button",{type:"button",...a,...i,className:"mt-1 p-1 rounded text-muted-foreground hover:text-foreground hover:bg-muted cursor-grab active:cursor-grabbing touch-none","aria-label":"Drag to reorder",children:e.jsx(Pu,{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(ne,{className:"text-xs",children:"Field Type"}),e.jsxs(us,{value:s.field_type,onValueChange:h=>n(t,{field_type:h}),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsx(cs,{children:Qhn.map(h=>e.jsx(Ze,{value:h.value,children:h.label},h.value))})]})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Label"}),e.jsx(ye,{value:s.label,onChange:h=>n(t,{label:h.target.value}),placeholder:"e.g. Full Name"})]}),e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Placeholder"}),e.jsx(ye,{value:s.placeholder||"",onChange:h=>n(t,{placeholder:h.target.value}),placeholder:"Optional hint text"})]})]}),(s.field_type==="select"||s.field_type==="multiselect")&&e.jsxs("div",{children:[e.jsx(ne,{className:"text-xs",children:"Options (comma-separated)"}),e.jsx(ye,{value:s.options?(typeof s.options=="string"?JSON.parse(s.options):s.options).join(", "):"",onChange:h=>n(t,{options:JSON.stringify(h.target.value.split(",").map(p=>p.trim()).filter(Boolean))}),placeholder:"Option 1, Option 2, Option 3"})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:s.is_required,onCheckedChange:h=>n(t,{is_required:h})}),e.jsx(ne,{className:"text-xs",children:"Required"})]})]}),e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>r(t),children:e.jsx(_n,{className:"h-3.5 w-3.5 text-destructive"})})]})})})}function emn(){const{pageId:s}=bi(),t=Ln(),{user:n}=vs(),r=wa(),{toast:a}=Fa(),i=Kt(),[l,o]=N.useState(null),[c,d]=N.useState(!1),{data:u,isLoading:h}=dt({queryKey:["landing-page",s],queryFn:async()=>{const{data:me,error:le}=await q.from("landing_pages").select("*").eq("id",s).single();if(le)throw le;return me},enabled:!!s}),{data:p=[],isLoading:f}=dt({queryKey:["landing-page-fields",s],queryFn:async()=>{const{data:me,error:le}=await q.from("landing_page_fields").select("*").eq("page_id",s).order("sort_order");if(le)throw le;return me},enabled:!!s}),{data:y=[]}=dt({queryKey:["landing-page-submissions",s],queryFn:async()=>{const{data:me,error:le}=await q.from("landing_page_submissions").select("*").eq("page_id",s).order("created_at",{ascending:!1});if(le)throw le;return me},enabled:!!s}),{data:_=[]}=dt({queryKey:["my-listings-for-pages",r],queryFn:async()=>{const{data:me,error:le}=await q.from("listings").select("id, property_address, city, state, price, bedrooms, bathrooms, square_footage, description, status").eq("agent_id",r).order("created_at",{ascending:!1});if(le)throw le;return me},enabled:!!n&&((u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold")}),{data:v=[]}=dt({queryKey:["drips-for-landing",r],queryFn:async()=>{const{data:me}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",r).eq("is_active",!0).order("name");return me||[]},enabled:!!r}),{data:j}=dt({queryKey:["agent-landing-defaults",r],queryFn:async()=>{const{data:me}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",r).maybeSingle();return me},enabled:!!r}),[w,S]=N.useState({title:"",hero_headline:"",hero_subtext:"",hero_image_url:null,logo_url:null,primary_color:"#406E71",accent_color:"#2a4c64",agent_name:"",agent_phone:"",agent_email:"",agent_photo_url:null,success_message:"Thank you! We'll be in touch soon.",is_published:!1,description:"",lead_magnet_file_url:null,lead_magnet_file_name:null,lead_magnet_external_url:null,listing_id:null,property_address:"",property_price:"",property_beds:"",property_baths:"",property_sqft:"",property_description:"",property_photos:[],property_status:"just_listed",theme_style:"premium",eyebrow:"",headline_accent:"",heading_font:"playfair",trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:"",settings_auto_responder_subject:"",settings_auto_responder_body:"",settings_drip_campaign_id:null,settings_disable_auto_responder:!1,settings_disable_drip:!1,settings_event_starts_at:"",settings_event_location_name:"",settings_event_address:""}),[A,E]=N.useState([]);N.useEffect(()=>{var me,le,ve,ge,Te,Ie,Ce,Me,Pe;u&&S({title:u.title,hero_headline:u.hero_headline,hero_subtext:u.hero_subtext||"",hero_image_url:u.hero_image_url,logo_url:u.logo_url,primary_color:u.primary_color,accent_color:u.accent_color,agent_name:u.agent_name||"",agent_phone:u.agent_phone||"",agent_email:u.agent_email||"",agent_photo_url:u.agent_photo_url,success_message:u.success_message||"Thank you! We'll be in touch soon.",is_published:u.is_published,description:u.description||"",lead_magnet_file_url:u.lead_magnet_file_url||null,lead_magnet_file_name:u.lead_magnet_file_name||null,lead_magnet_external_url:u.lead_magnet_external_url||null,listing_id:u.listing_id||null,property_address:u.property_address||"",property_price:u.property_price||"",property_beds:u.property_beds||"",property_baths:u.property_baths||"",property_sqft:u.property_sqft||"",property_description:u.property_description||"",property_photos:Array.isArray(u.property_photos)?u.property_photos:[],property_status:u.property_status||"just_listed",theme_style:u.theme_style||"premium",eyebrow:u.eyebrow||"",headline_accent:u.headline_accent||"",heading_font:u.heading_font||"playfair",trust_pills:Array.isArray(u.trust_pills)?u.trust_pills:["No obligation","100% free","60 seconds or less"],settings_redirect_url:((me=u.settings)==null?void 0:me.redirect_url)||"",settings_auto_responder_subject:((le=u.settings)==null?void 0:le.auto_responder_subject)||"",settings_auto_responder_body:((ve=u.settings)==null?void 0:ve.auto_responder_body)||"",settings_drip_campaign_id:((ge=u.settings)==null?void 0:ge.drip_campaign_id)||null,settings_disable_auto_responder:!!((Te=u.settings)!=null&&Te.disable_auto_responder),settings_disable_drip:!!((Ie=u.settings)!=null&&Ie.disable_drip),settings_event_starts_at:((Ce=u.settings)==null?void 0:Ce.event_starts_at)||"",settings_event_location_name:((Me=u.settings)==null?void 0:Me.event_location_name)||"",settings_event_address:((Pe=u.settings)==null?void 0:Pe.event_address)||""})},[u]),N.useEffect(()=>{p.length>0&&E(p.map(me=>({id:me.id,clientId:me.id||qet(),field_type:me.field_type,label:me.label,placeholder:me.placeholder,is_required:me.is_required,options:typeof me.options=="string"?me.options:me.options?JSON.stringify(me.options):null,sort_order:me.sort_order})))},[p]);const O=yt({mutationFn:async()=>{const{error:me}=await q.from("landing_pages").update({title:w.title,hero_headline:w.hero_headline,hero_subtext:w.hero_subtext||null,hero_image_url:w.hero_image_url,logo_url:w.logo_url,primary_color:w.primary_color,accent_color:w.accent_color,agent_name:w.agent_name||null,agent_phone:w.agent_phone||null,agent_email:w.agent_email||null,agent_photo_url:w.agent_photo_url,success_message:w.success_message,is_published:w.is_published,description:w.description||null,lead_magnet_file_url:w.lead_magnet_file_url,lead_magnet_file_name:w.lead_magnet_file_name,lead_magnet_external_url:w.lead_magnet_external_url,listing_id:w.listing_id,property_address:w.property_address||null,property_price:w.property_price||null,property_beds:w.property_beds||null,property_baths:w.property_baths||null,property_sqft:w.property_sqft||null,property_description:w.property_description||null,property_photos:w.property_photos,property_status:w.property_status,theme_style:w.theme_style,eyebrow:w.eyebrow||null,headline_accent:w.headline_accent||null,heading_font:w.heading_font,trust_pills:w.trust_pills,settings:{...(u==null?void 0:u.settings)||{},redirect_url:w.settings_redirect_url||null,auto_responder_subject:w.settings_auto_responder_subject||null,auto_responder_body:w.settings_auto_responder_body||null,drip_campaign_id:w.settings_drip_campaign_id||null,disable_auto_responder:!!w.settings_disable_auto_responder,disable_drip:!!w.settings_disable_drip,event_starts_at:w.settings_event_starts_at||null,event_location_name:w.settings_event_location_name||null,event_address:w.settings_event_address||null},updated_at:new Date().toISOString()}).eq("id",s);if(me)throw me;if(await q.from("landing_page_fields").delete().eq("page_id",s),A.length>0){const{error:le}=await q.from("landing_page_fields").insert(A.map((ve,ge)=>({page_id:s,field_type:ve.field_type,label:ve.label,placeholder:ve.placeholder||null,is_required:ve.is_required,options:ve.options?JSON.parse(ve.options):null,sort_order:ge})));if(le)throw le}},onSuccess:()=>{i.invalidateQueries({queryKey:["landing-page",s]}),i.invalidateQueries({queryKey:["landing-page-fields",s]}),a({title:"Page saved!"})},onError:me=>a({title:"Error",description:me.message,variant:"destructive"})}),D=async(me,le)=>{const ve=me.name.split(".").pop(),ge=`landing-pages/${n.id}/${le}-${Date.now()}.${ve}`,{error:Te}=await q.storage.from("recruit-landing").upload(ge,me);if(Te)throw Te;const{data:{publicUrl:Ie}}=q.storage.from("recruit-landing").getPublicUrl(ge);return Ie},I=async(me,le)=>{var ge;const ve=(ge=me.target.files)==null?void 0:ge[0];if(ve){o(le);try{const Te=await D(ve,le);S(Ie=>({...Ie,[le]:Te})),a({title:"Image uploaded!"})}catch(Te){a({title:"Upload failed",description:Te.message,variant:"destructive"})}finally{o(null)}}},F=async me=>{var ve;const le=(ve=me.target.files)==null?void 0:ve[0];if(le){o("lead_magnet");try{const ge=await D(le,"lead-magnet");S(Te=>({...Te,lead_magnet_file_url:ge,lead_magnet_file_name:le.name})),a({title:"File uploaded!"})}catch(ge){a({title:"Upload failed",description:ge.message,variant:"destructive"})}finally{o(null)}}},z=async me=>{const le=me.target.files;if(!(!le||le.length===0)){o("property_photos");try{const ve=[];for(const ge of Array.from(le)){const Te=await D(ge,"property-photo");ve.push(Te)}S(ge=>({...ge,property_photos:[...ge.property_photos,...ve]})),a({title:`${ve.length} photo(s) uploaded!`})}catch(ve){a({title:"Upload failed",description:ve.message,variant:"destructive"})}finally{o(null)}}},H=async me=>{const le=_.find(ge=>ge.id===me);if(!le)return;const{data:ve}=await q.from("listing_photos").select("photo_url").eq("listing_id",me).order("sort_order");S(ge=>({...ge,listing_id:me,property_address:le.property_address||`${le.city}, ${le.state}`,property_price:le.price?`$${le.price.toLocaleString()}`:"",property_beds:le.bedrooms?String(le.bedrooms):"",property_baths:le.bathrooms?String(le.bathrooms):"",property_sqft:le.square_footage?le.square_footage.toLocaleString():"",property_description:le.description||"",property_photos:(ve==null?void 0:ve.map(Te=>Te.photo_url))||ge.property_photos})),a({title:"Listing data imported!"})},Z=()=>{E(me=>[...me,{clientId:qet(),field_type:"text",label:"",placeholder:"",is_required:!1,options:null,sort_order:me.length}])},Y=(me,le)=>{E(ve=>ve.map((ge,Te)=>Te===me?{...ge,...le}:ge))},W=me=>{E(le=>le.filter((ve,ge)=>ge!==me))},ee=lve(A8(QD,{activationConstraint:{distance:6}}),A8(uve,{coordinateGetter:oyt})),se=me=>{const{active:le,over:ve}=me;!ve||le.id===ve.id||E(ge=>{const Te=ge.findIndex(Ce=>Ce.clientId===le.id),Ie=ge.findIndex(Ce=>Ce.clientId===ve.id);return Te<0||Ie<0?ge:fve(ge,Te,Ie).map((Ce,Me)=>({...Ce,sort_order:Me}))})},oe=u?`https://pages.relevelup.com/${u.slug}`:"",he=(u==null?void 0:u.page_type)==="lead_magnet",ce=(u==null?void 0:u.page_type)==="just_listed"||(u==null?void 0:u.page_type)==="just_sold";return h||f?e.jsx(Cs,{title:"Loading...",children:e.jsx("div",{className:"flex justify-center py-12",children:e.jsx("div",{className:"h-8 w-8 animate-spin rounded-full border-4 border-primary border-t-transparent"})})}):u?e.jsxs(Cs,{title:w.title||"Edit Page",children:[e.jsxs("div",{className:"space-y-6 max-w-4xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{className:"flex items-center gap-3",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>t("/mission-control/landing-pages"),children:e.jsx(qr,{className:"h-4 w-4"})}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-xl font-bold",children:w.title||"Untitled Page"}),e.jsxs("div",{className:"flex items-center gap-2 mt-0.5",children:[e.jsx(Ue,{variant:w.is_published?"default":"secondary",className:"text-[10px]",children:w.is_published?"Published":"Draft"}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(Sr,{className:"h-3 w-3"})," ",u.view_count," views"]}),e.jsxs("span",{className:"text-xs text-muted-foreground flex items-center gap-1",children:[e.jsx(An,{className:"h-3 w-3"})," ",y.length," submissions"]})]})]})]}),e.jsxs("div",{className:"flex items-center gap-2",children:[w.is_published&&e.jsxs(e.Fragment,{children:[e.jsx(B,{size:"sm",variant:"outline",onClick:()=>d(!0),children:e.jsx(ry,{className:"h-3.5 w-3.5"})}),e.jsxs(B,{size:"sm",variant:"outline",onClick:()=>{navigator.clipboard.writeText(oe),a({title:"Link copied!"})},children:[e.jsx(Zr,{className:"h-3.5 w-3.5 mr-1"})," Copy Link"]}),e.jsx(B,{size:"sm",variant:"outline",asChild:!0,children:e.jsxs("a",{href:oe,target:"_blank",rel:"noopener noreferrer",children:[e.jsx(tr,{className:"h-3.5 w-3.5 mr-1"})," Preview"]})})]}),e.jsxs(B,{onClick:()=>O.mutate(),disabled:O.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"}),O.isPending?"Saving...":"Save"]})]})]}),e.jsxs(Fr,{defaultValue:"design",children:[e.jsxs(Rr,{children:[e.jsx(Zt,{value:"design",children:"Design"}),he&&e.jsx(Zt,{value:"lead_magnet",children:"Lead Magnet"}),ce&&e.jsx(Zt,{value:"property",children:"Property Details"}),e.jsxs(Zt,{value:"fields",children:["Form Fields (",A.length,")"]}),e.jsxs(Zt,{value:"submissions",children:["Submissions (",y.length,")"]}),e.jsx(Zt,{value:"automation",children:"Automation"}),e.jsx(Zt,{value:"analytics",children:"Analytics"}),e.jsx(Zt,{value:"settings",children:"Settings"})]}),e.jsxs(is,{value:"design",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Page Details"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Page Title (internal)"}),e.jsx(ye,{value:w.title,onChange:me=>S(le=>({...le,title:me.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Description (internal)"}),e.jsx(ye,{value:w.description,onChange:me=>S(le=>({...le,description:me.target.value}))})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:["Theme & Style",e.jsx(Ue,{variant:"secondary",className:"text-[10px]",children:"New"})]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Theme Style"}),e.jsxs(us,{value:w.theme_style,onValueChange:me=>S(le=>({...le,theme_style:me})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"premium",children:"Premium — cinematic + glass form"}),e.jsx(Ze,{value:"classic",children:"Classic — centered card"})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Headline Font"}),e.jsxs(us,{value:w.heading_font,onValueChange:me=>S(le=>({...le,heading_font:me})),children:[e.jsx(ls,{children:e.jsx(hs,{})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"playfair",children:"Playfair Display (editorial serif)"}),e.jsx(Ze,{value:"baskerville",children:"Libre Baskerville (classic serif)"}),e.jsx(Ze,{value:"instrument",children:"Instrument Serif (modern serif)"}),e.jsx(Ze,{value:"sans",children:"Inter (clean sans-serif)"})]})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Trust Pills (comma separated, shown under CTA)"}),e.jsx(ye,{value:w.trust_pills.join(", "),onChange:me=>S(le=>({...le,trust_pills:me.target.value.split(",").map(ve=>ve.trim()).filter(Boolean)})),placeholder:"No obligation, 100% free, 60 seconds or less"})]}),e.jsx("p",{className:"text-[11px] text-muted-foreground",children:"Premium theme uses a cinematic full-screen hero, italic accent word, glass-effect form, and trust pills — magazine-style."})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Hero Section"})}),e.jsxs(Ee,{className:"space-y-4",children:[w.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(ne,{children:"Eyebrow (small label above headline)"}),e.jsx(ye,{value:w.eyebrow,onChange:me=>S(le=>({...le,eyebrow:me.target.value})),placeholder:"HOME VALUE"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Headline"}),e.jsx(ye,{value:w.hero_headline,onChange:me=>S(le=>({...le,hero_headline:me.target.value})),placeholder:"What Is Your Home"})]}),w.theme_style==="premium"&&e.jsxs("div",{children:[e.jsx(ne,{children:"Accent Word(s) — italic & colored (optional)"}),e.jsx(ye,{value:w.headline_accent,onChange:me=>S(le=>({...le,headline_accent:me.target.value})),placeholder:"Actually Worth?"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Subtext"}),e.jsx(Ms,{value:w.hero_subtext,onChange:me=>S(le=>({...le,hero_subtext:me.target.value})),rows:3,placeholder:"A brief description..."})]}),e.jsxs("div",{children:[e.jsxs(ne,{children:["Background Image ",w.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:[w.hero_image_url&&e.jsx("img",{src:w.hero_image_url,alt:"Hero",className:"h-16 w-28 object-cover rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="hero_image_url",children:e.jsxs("span",{children:[e.jsx(_a,{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:me=>I(me,"hero_image_url")})]}),w.hero_image_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>S(me=>({...me,hero_image_url:null})),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Branding"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Logo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[w.logo_url&&e.jsx("img",{src:w.logo_url,alt:"Logo",className:"h-10 w-auto rounded"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="logo_url",children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),l==="logo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:me=>I(me,"logo_url")})]})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Agent Photo"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[w.agent_photo_url&&e.jsx("img",{src:w.agent_photo_url,alt:"Agent",className:"h-10 w-10 rounded-full object-cover"}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="agent_photo_url",children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),l==="agent_photo_url"?"...":"Upload"]})}),e.jsx("input",{type:"file",accept:"image/*",className:"hidden",onChange:me=>I(me,"agent_photo_url")})]})]})]})]}),e.jsxs("div",{className:"grid grid-cols-2 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Primary Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:w.primary_color,onChange:me=>S(le=>({...le,primary_color:me.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:w.primary_color,onChange:me=>S(le=>({...le,primary_color:me.target.value})),className:"font-mono text-xs"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Accent Color"}),e.jsxs("div",{className:"flex items-center gap-2 mt-1",children:[e.jsx("input",{type:"color",value:w.accent_color,onChange:me=>S(le=>({...le,accent_color:me.target.value})),className:"h-9 w-12 rounded border cursor-pointer"}),e.jsx(ye,{value:w.accent_color,onChange:me=>S(le=>({...le,accent_color:me.target.value})),className:"font-mono text-xs"})]})]})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Agent Info (shown on page)"})}),e.jsx(Ee,{className:"space-y-4",children:e.jsxs("div",{className:"grid grid-cols-1 md:grid-cols-3 gap-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Name"}),e.jsx(ye,{value:w.agent_name,onChange:me=>S(le=>({...le,agent_name:me.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Phone"}),e.jsx(ye,{value:w.agent_phone,onChange:me=>S(le=>({...le,agent_phone:me.target.value}))})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Email"}),e.jsx(ye,{value:w.agent_email,onChange:me=>S(le=>({...le,agent_email:me.target.value}))})]})]})})]})]}),he&&e.jsx(is,{value:"lead_magnet",className:"space-y-4 mt-4",children:e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(Ia,{className:"h-4 w-4"})," Giveaway File"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Upload a file or provide an external URL. Visitors will receive the download link after submitting the form."}),e.jsxs("div",{children:[e.jsx(ne,{children:"Upload File (PDF, guide, checklist, etc.)"}),e.jsxs("div",{className:"flex items-center gap-3 mt-1",children:[w.lead_magnet_file_name&&e.jsxs(Ue,{variant:"outline",className:"gap-1",children:[e.jsx(Ia,{className:"h-3 w-3"})," ",w.lead_magnet_file_name]}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="lead_magnet",children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),l==="lead_magnet"?"Uploading...":"Upload File"]})}),e.jsx("input",{type:"file",className:"hidden",onChange:F})]}),w.lead_magnet_file_url&&e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>S(me=>({...me,lead_magnet_file_url:null,lead_magnet_file_name:null})),children:e.jsx(_n,{className:"h-3.5 w-3.5"})})]})]}),e.jsxs("div",{className:"flex items-center gap-2 text-sm text-muted-foreground",children:[e.jsx("div",{className:"flex-1 border-t"}),e.jsx("span",{children:"OR"}),e.jsx("div",{className:"flex-1 border-t"})]}),e.jsxs("div",{children:[e.jsxs(ne,{className:"flex items-center gap-1",children:[e.jsx(Tl,{className:"h-3.5 w-3.5"})," External URL"]}),e.jsx(ye,{value:w.lead_magnet_external_url||"",onChange:me=>S(le=>({...le,lead_magnet_external_url:me.target.value||null})),placeholder:"https://drive.google.com/... or https://dropbox.com/...",className:"mt-1"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Link to a file on Google Drive, Dropbox, or any URL"})]})]})]})}),ce&&e.jsxs(is,{value:"property",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsxs(Rt,{className:"text-base flex items-center gap-2",children:[e.jsx(Or,{className:"h-4 w-4"})," Import from Listing Exchange"]})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Pull property details and photos directly from one of your listings, or enter them manually below."}),e.jsxs(us,{value:w.listing_id||"",onValueChange:me=>H(me),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Select a listing to import..."})}),e.jsx(cs,{children:_.map(me=>{var le;return e.jsxs(Ze,{value:me.id,children:[me.property_address||`${me.city}, ${me.state}`," — $",(le=me.price)==null?void 0:le.toLocaleString()]},me.id)})})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Property Information"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Property Address"}),e.jsx(ye,{value:w.property_address,onChange:me=>S(le=>({...le,property_address:me.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(ne,{children:"Price"}),e.jsx(ye,{value:w.property_price,onChange:me=>S(le=>({...le,property_price:me.target.value})),placeholder:"$450,000"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Beds"}),e.jsx(ye,{value:w.property_beds,onChange:me=>S(le=>({...le,property_beds:me.target.value})),placeholder:"4"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Baths"}),e.jsx(ye,{value:w.property_baths,onChange:me=>S(le=>({...le,property_baths:me.target.value})),placeholder:"3"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Sq Ft"}),e.jsx(ye,{value:w.property_sqft,onChange:me=>S(le=>({...le,property_sqft:me.target.value})),placeholder:"2,400"})]})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Description"}),e.jsx(Ms,{value:w.property_description,onChange:me=>S(le=>({...le,property_description:me.target.value})),rows:3,placeholder:"Beautiful home in a great neighborhood..."})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Property Photos"})}),e.jsxs(Ee,{className:"space-y-4",children:[w.property_photos.length>0&&e.jsx("div",{className:"grid grid-cols-3 md:grid-cols-4 gap-2",children:w.property_photos.map((me,le)=>e.jsxs("div",{className:"relative group",children:[e.jsx("img",{src:me,alt:`Property ${le+1}`,className:"h-24 w-full object-cover rounded"}),e.jsx(B,{variant:"destructive",size:"sm",className:"absolute top-1 right-1 h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>S(ve=>({...ve,property_photos:ve.property_photos.filter((ge,Te)=>Te!==le)})),children:e.jsx(_n,{className:"h-3 w-3"})})]},le))}),e.jsxs("label",{className:"cursor-pointer",children:[e.jsx(B,{variant:"outline",size:"sm",asChild:!0,disabled:l==="property_photos",children:e.jsxs("span",{children:[e.jsx(_a,{className:"h-3.5 w-3.5 mr-1"}),l==="property_photos"?"Uploading...":"Add Photos"]})}),e.jsx("input",{type:"file",accept:"image/*",multiple:!0,className:"hidden",onChange:z})]})]})]})]}),e.jsxs(is,{value:"fields",className:"space-y-4 mt-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx("p",{className:"text-sm text-muted-foreground",children:"Configure the form fields visitors will fill out"}),e.jsxs(B,{size:"sm",onClick:Z,children:[e.jsx(Is,{className:"h-3.5 w-3.5 mr-1"})," Add Field"]})]}),A.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-8 text-center text-muted-foreground",children:"No fields yet. Add fields to build your form."})}):e.jsx(pve,{sensors:ee,collisionDetection:cve,onDragEnd:se,children:e.jsx(xve,{items:A.map(me=>me.clientId),strategy:hws,children:e.jsx("div",{className:"space-y-3",children:A.map((me,le)=>e.jsx(Jhn,{field:me,index:le,updateField:Y,removeField:W},me.clientId))})})})]}),e.jsx(is,{value:"submissions",className:"mt-4",children:y.length===0?e.jsx(fe,{children:e.jsx(Ee,{className:"py-12 text-center text-muted-foreground",children:"No submissions yet. Share your page to start collecting leads!"})}):e.jsx("div",{className:"space-y-3",children:y.map(me=>e.jsx(fe,{children:e.jsx(Ee,{className:"p-4",children:e.jsxs("div",{className:"flex items-start justify-between",children:[e.jsxs("div",{children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx("span",{className:"font-medium",children:me.contact_name||"Anonymous"}),me.synced_to_crm&&e.jsx(Ue,{variant:"outline",className:"text-[10px]",children:"Synced"})]}),e.jsxs("div",{className:"text-sm text-muted-foreground mt-0.5",children:[me.contact_email&&e.jsx("span",{className:"mr-3",children:me.contact_email}),me.contact_phone&&e.jsx("span",{children:me.contact_phone})]}),me.answers&&typeof me.answers=="object"&&e.jsx("div",{className:"mt-2 text-sm space-y-1",children:Object.entries(me.answers).map(([le,ve])=>e.jsxs("div",{children:[e.jsxs("span",{className:"font-medium text-muted-foreground",children:[le,":"]})," ",e.jsx("span",{children:String(ve)})]},le))})]}),e.jsx("span",{className:"text-xs text-muted-foreground",children:new Date(me.created_at).toLocaleDateString()})]})})},me.id))})}),e.jsxs(is,{value:"automation",className:"space-y-4 mt-4",children:[(u==null?void 0:u.page_type)==="event_registration"&&e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{className:"text-base",children:"Event details"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Shown to visitors as a live countdown with add-to-calendar buttons."})]}),e.jsxs(Ee,{className:"grid gap-3 md:grid-cols-2",children:[e.jsxs("div",{className:"space-y-1.5 md:col-span-2",children:[e.jsx(ne,{children:"Starts at"}),e.jsx(ye,{type:"datetime-local",value:w.settings_event_starts_at,onChange:me=>S(le=>({...le,settings_event_starts_at:me.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Venue / location name"}),e.jsx(ye,{placeholder:"e.g. The Grand Hotel",value:w.settings_event_location_name,onChange:me=>S(le=>({...le,settings_event_location_name:me.target.value}))})]}),e.jsxs("div",{className:"space-y-1.5",children:[e.jsx(ne,{children:"Address (for map link)"}),e.jsx(ye,{placeholder:"123 Main St, City, ST",value:w.settings_event_address,onChange:me=>S(le=>({...le,settings_event_address:me.target.value}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{className:"text-base",children:"Instant auto-reply to lead"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Sent the moment someone submits this page. Leave blank to use your",j!=null&&j.default_auto_responder_body?" account default":" built-in template",". Merge fields: ",e.jsx("code",{children:"{{client_first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{page_title}}"}),", ",e.jsx("code",{children:"{{calendar_link}}"}),"."]})]}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Send auto-reply for this page"}),e.jsx(jn,{checked:!w.settings_disable_auto_responder,onCheckedChange:me=>S(le=>({...le,settings_disable_auto_responder:!me}))})]}),!w.settings_disable_auto_responder&&e.jsxs(e.Fragment,{children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Subject (override)"}),e.jsx(ye,{value:w.settings_auto_responder_subject,onChange:me=>S(le=>({...le,settings_auto_responder_subject:me.target.value})),placeholder:(j==null?void 0:j.default_auto_responder_subject)||"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Body (override)"}),e.jsx(Ms,{rows:8,value:w.settings_auto_responder_body,onChange:me=>S(le=>({...le,settings_auto_responder_body:me.target.value})),placeholder:(j==null?void 0:j.default_auto_responder_body)||`Hi {{client_first_name}}, Thanks for reaching out…`})]})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{className:"text-base",children:"Smart Drip enrollment"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:["Automatically enroll every new lead into a drip campaign.",(j==null?void 0:j.default_drip_campaign_id)&&" Account default applies if no override is selected."]})]}),e.jsxs(Ee,{className:"space-y-3",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsx(ne,{children:"Enroll new leads in a drip"}),e.jsx(jn,{checked:!w.settings_disable_drip,onCheckedChange:me=>S(le=>({...le,settings_disable_drip:!me}))})]}),!w.settings_disable_drip&&e.jsxs("div",{children:[e.jsx(ne,{children:"Drip override for this page"}),e.jsxs("select",{className:"mt-1 w-full rounded-md border bg-background px-3 py-2 text-sm",value:w.settings_drip_campaign_id||"",onChange:me=>S(le=>({...le,settings_drip_campaign_id:me.target.value||null})),children:[e.jsx("option",{value:"",children:"— Use account default —"}),v.map(me=>e.jsx("option",{value:me.id,children:me.name},me.id))]})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Redirect after submit"})}),e.jsxs(Ee,{children:[e.jsx(ye,{value:w.settings_redirect_url,onChange:me=>S(le=>({...le,settings_redirect_url:me.target.value})),placeholder:(j==null?void 0:j.default_redirect_url)||"https://your-site.com/thank-you (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Leave blank to keep the inline Thank-You message."})]})]})]}),e.jsx(is,{value:"analytics",className:"space-y-4 mt-4",children:e.jsx(Zhn,{pageId:s})}),e.jsxs(is,{value:"settings",className:"space-y-4 mt-4",children:[e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Publishing"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Published"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"Make this page publicly accessible"})]}),e.jsx(jn,{checked:w.is_published,onCheckedChange:me=>S(le=>({...le,is_published:me}))})]}),w.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:oe})]})]})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{className:"text-base",children:"Thank You Message"})}),e.jsx(Ee,{children:e.jsx(Ms,{value:w.success_message,onChange:me=>S(le=>({...le,success_message:me.target.value})),rows:2,placeholder:"Message shown after form submission"})})]})]})]})]}),e.jsx(_s,{open:c,onOpenChange:d,children:e.jsxs(bs,{className:"max-w-sm",children:[e.jsx(js,{children:e.jsx(ws,{children:"QR Code"})}),e.jsxs("div",{className:"flex flex-col items-center gap-4 py-4",children:[e.jsx(zU,{value:oe,size:240}),e.jsx("p",{className:"text-xs text-muted-foreground text-center break-all",children:oe})]})]})})]}):e.jsx(Cs,{title:"Not Found",children:e.jsxs("div",{className:"text-center py-12",children:[e.jsx("p",{className:"text-muted-foreground",children:"Page not found"}),e.jsx(B,{variant:"link",onClick:()=>t("/mission-control/landing-pages"),children:"Go back"})]})})}const tmn={default_auto_responder_subject:"",default_auto_responder_body:"",default_drip_campaign_id:null,default_redirect_url:"",default_calendar_link:"",text_agent_on_lead:!1,agent_sms_phone:"",use_brand_kit:!0},smn=`Hi {{client_first_name}}, Thanks for reaching out — I've got your information and will personally follow up within one business day. If it's easier, you can also call or text me directly at {{agent_phone}}. Talk soon, {{agent_name}}`;function nmn(){const s=wa(),{toast:t}=Fa(),n=Ln(),r=Kt(),[a,i]=N.useState(tmn),{data:l}=dt({queryKey:["landing-page-defaults",s],queryFn:async()=>{const{data:d}=await q.from("agent_landing_page_defaults").select("*").eq("user_id",s).maybeSingle();return d||null},enabled:!!s}),{data:o=[]}=dt({queryKey:["drip-campaigns-mine",s],queryFn:async()=>{const{data:d}=await q.from("drip_campaigns").select("id, name").eq("owner_user_id",s).eq("is_active",!0).order("name");return d||[]},enabled:!!s});N.useEffect(()=>{l&&i({default_auto_responder_subject:l.default_auto_responder_subject??"",default_auto_responder_body:l.default_auto_responder_body??"",default_drip_campaign_id:l.default_drip_campaign_id??null,default_redirect_url:l.default_redirect_url??"",default_calendar_link:l.default_calendar_link??"",text_agent_on_lead:!!l.text_agent_on_lead,agent_sms_phone:l.agent_sms_phone??"",use_brand_kit:l.use_brand_kit??!0})},[l]);const c=yt({mutationFn:async()=>{const{error:d}=await q.from("agent_landing_page_defaults").upsert({user_id:s,...a},{onConflict:"user_id"});if(d)throw d},onSuccess:()=>{r.invalidateQueries({queryKey:["landing-page-defaults"]}),t({title:"Defaults saved"})},onError:d=>t({title:"Save failed",description:d.message,variant:"destructive"})});return e.jsx(Cs,{title:"Landing Page Defaults",children:e.jsxs("div",{className:"space-y-6 max-w-3xl mx-auto",children:[e.jsxs("div",{className:"flex items-center justify-between",children:[e.jsxs(B,{variant:"ghost",size:"sm",onClick:()=>n("/mission-control/landing-pages"),children:[e.jsx(qr,{className:"h-4 w-4 mr-1"})," Back to pages"]}),e.jsxs(B,{onClick:()=>c.mutate(),disabled:c.isPending,children:[e.jsx(Jo,{className:"h-4 w-4 mr-2"})," ",c.isPending?"Saving…":"Save Defaults"]})]}),e.jsxs("div",{children:[e.jsx("h1",{className:"text-2xl font-bold",children:"Landing Page Defaults"}),e.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"These run on every landing page automatically. Any page can override them in its own settings."})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Instant auto-reply to the lead"}),e.jsxs(Vn,{children:["Sent the moment someone submits one of your pages. Uses your Gmail if connected, otherwise your verified sender. Merge fields: ",e.jsx("code",{children:"{{client_first_name}}"}),", ",e.jsx("code",{children:"{{agent_name}}"}),", ",e.jsx("code",{children:"{{agent_phone}}"}),", ",e.jsx("code",{children:"{{page_title}}"}),", ",e.jsx("code",{children:"{{calendar_link}}"}),"."]})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Subject"}),e.jsx(ye,{value:a.default_auto_responder_subject||"",onChange:d=>i(u=>({...u,default_auto_responder_subject:d.target.value})),placeholder:"Thanks for reaching out, {{client_first_name}}!"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Message body"}),e.jsx(Ms,{rows:10,value:a.default_auto_responder_body||"",onChange:d=>i(u=>({...u,default_auto_responder_body:d.target.value})),placeholder:smn}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave blank to use the polished built-in template that adapts to each page type."})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Default Smart Drip"}),e.jsx(Vn,{children:"Every new lead drops into this drip unless a page overrides it."})]}),e.jsx(Ee,{children:e.jsxs(us,{value:a.default_drip_campaign_id||"none",onValueChange:d=>i(u=>({...u,default_drip_campaign_id:d==="none"?null:d})),children:[e.jsx(ls,{children:e.jsx(hs,{placeholder:"Pick a drip…"})}),e.jsxs(cs,{children:[e.jsx(Ze,{value:"none",children:"— No default drip —"}),o.map(d=>e.jsx(Ze,{value:d.id,children:d.name},d.id))]})]})})]}),e.jsxs(fe,{children:[e.jsx(It,{children:e.jsx(Rt,{children:"Defaults for every page"})}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx(ne,{children:"Default booking / calendar link"}),e.jsx(ye,{value:a.default_calendar_link||"",onChange:d=>i(u=>({...u,default_calendar_link:d.target.value})),placeholder:"https://calendly.com/your-name/intro"})]}),e.jsxs("div",{children:[e.jsx(ne,{children:"Default redirect after submit (optional)"}),e.jsx(ye,{value:a.default_redirect_url||"",onChange:d=>i(u=>({...u,default_redirect_url:d.target.value})),placeholder:"https://your-site.com/thanks"})]}),e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsxs("div",{children:[e.jsx(ne,{className:"text-base",children:"Use my brand kit colors"}),e.jsx("p",{className:"text-xs text-muted-foreground",children:"New pages pick up your brand colors/logo automatically."})]}),e.jsx(jn,{checked:a.use_brand_kit,onCheckedChange:d=>i(u=>({...u,use_brand_kit:d}))})]})]})]}),e.jsxs(fe,{children:[e.jsxs(It,{children:[e.jsx(Rt,{children:"Text me when a lead submits"}),e.jsx(Vn,{children:"Get an SMS the second a lead hits your inbox. Coming soon — requires SMS sender setup."})]}),e.jsxs(Ee,{className:"space-y-4",children:[e.jsxs("div",{className:"flex items-center justify-between rounded-lg border p-3",children:[e.jsx(ne,{className:"text-base",children:"SMS me new leads"}),e.jsx(jn,{checked:a.text_agent_on_lead,onCheckedChange:d=>i(u=>({...u,text_agent_on_lead:d}))})]}),a.text_agent_on_lead&&e.jsxs("div",{children:[e.jsx(ne,{children:"Phone number for alerts"}),e.jsx(ye,{type:"tel",value:a.agent_sms_phone||"",onChange:d=>i(u=>({...u,agent_sms_phone:d.target.value})),placeholder:"(555) 123-4567"})]})]})]})]})})}function rmn(){return dt({queryKey:["website-apps"],queryFn:async()=>{const{data:s,error:t}=await q.from("website_apps").select("*").order("sort_order",{ascending:!0});if(t)throw t;return s||[]}})}function tbe(){const{user:s}=vs();return dt({queryKey:["agent-website-app-installs",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return[];const{data:t,error:n}=await q.from("agent_website_app_installs").select("*").eq("user_id",s.id);if(n)throw n;return t||[]},enabled:!!(s!=null&&s.id)})}function sbe(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async({app_slug:n,enabled:r})=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:a}=await q.from("agent_website_app_installs").upsert({user_id:s.id,app_slug:n,enabled:r},{onConflict:"user_id,app_slug"});if(a)throw a},onSuccess:(n,r)=>{t.invalidateQueries({queryKey:["agent-website-app-installs"]}),ae.success(r.enabled?"App installed":"App turned off")},onError:n=>ae.error(n.message||"Failed to update app")})}const amn={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"}},imn={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 omn(){const s=Ln(),{data:t=[],isLoading:n}=rmn(),{data:r=[]}=tbe(),{hasLeadSite:a,siteUrl:i,isLoading:l}=Ap(),o=sbe(),[c,d]=N.useState(!1),u=p=>{var f;return((f=r.find(y=>y.app_slug===p))==null?void 0:f.enabled)??!1},h=p=>r.some(f=>f.app_slug===p);return e.jsxs(Cs,{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(im,{className:"w-3.5 h-3.5"})," Boost conversions on autopilot"]}),e.jsxs("h1",{className:"text-3xl lg:text-4xl font-extrabold tracking-tight text-white flex items-center gap-3",children:[e.jsx(un,{className:"w-8 h-8 text-yellow-300 drop-shadow"}),"Website Apps"]}),e.jsx("p",{className:"text-white/90 mt-2 max-w-2xl text-base lg:text-lg",children:"Drop-in widgets that turn website visitors into leads. Add them to your Lead Site or embed on your own website with one line of code."}),e.jsxs(B,{onClick:()=>d(!0),className:"mt-5 bg-white text-indigo-700 hover:bg-white/90 shadow-lg font-semibold gap-2",children:[e.jsx(jh,{className:"w-5 h-5"}),"Watch: How to use Website Apps"]})]})]}),e.jsxs("div",{className:"grid gap-4 md:grid-cols-2",children:[e.jsx(fe,{className:`p-5 border-2 ${a?"border-emerald-200 bg-emerald-50/50":"border-dashed border-muted"}`,children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:`w-11 h-11 rounded-xl flex items-center justify-center flex-shrink-0 ${a?"bg-emerald-500 text-white":"bg-muted text-muted-foreground"}`,children:e.jsx(lc,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsxs("div",{className:"flex items-center gap-2 flex-wrap",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 1 — The Local Move Websites"}),a&&e.jsxs(Ue,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 text-[10px] gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"})," Auto-installed"]})]}),a&&i?e.jsxs("a",{href:i,target:"_blank",rel:"noreferrer",className:"text-xs text-emerald-700 hover:underline inline-flex items-center gap-1 mt-1",children:[i.replace(/^https?:\/\//,"")," ",e.jsx(tr,{className:"w-3 h-3"})]}):e.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Don't have a Local Move website yet? Visit"," ",e.jsxs("a",{href:"https://www.thelocalmove.com",target:"_blank",rel:"noreferrer",className:"text-primary font-medium hover:underline inline-flex items-center gap-0.5",children:["www.thelocalmove.com ",e.jsx(tr,{className:"w-3 h-3"})]})," ","to learn more — apps install automatically once you have one."]})]})]})}),e.jsx(fe,{className:"p-5 border-2 border-indigo-200 bg-indigo-50/40",children:e.jsxs("div",{className:"flex items-start gap-4",children:[e.jsx("div",{className:"w-11 h-11 rounded-xl bg-gradient-to-br from-indigo-500 to-fuchsia-600 text-white flex items-center justify-center flex-shrink-0",children:e.jsx(N2,{className:"w-5 h-5"})}),e.jsxs("div",{className:"flex-1 min-w-0",children:[e.jsx("h3",{className:"font-semibold text-sm",children:"Option 2 — Your existing website"}),e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Already have a site (Wix, Squarespace, WordPress, custom)? Paste a one-line snippet and the widget appears anywhere."}),e.jsx("p",{className:"text-[11px] text-indigo-700 mt-2 font-medium",children:'Open any app below → "Install on my website" tab to copy your code.'})]})]})})]}),n?e.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading apps..."}):e.jsx("div",{className:"grid gap-5 sm:grid-cols-2 lg:grid-cols-3",children:t.map(p=>{const f=m0e[p.icon||"Sparkles"]||un,y=u(p.slug),_=h(p.slug),v=p.status==="coming_soon",j=amn[p.slug]||imn;return e.jsxs(fe,{className:`group relative overflow-hidden border-0 ring-1 ring-border ${j.ring} hover:ring-2 transition-all hover:shadow-xl ${v?"opacity-70":""}`,children:[e.jsx("div",{className:`h-1.5 w-full bg-gradient-to-r ${j.gradient}`}),e.jsxs("div",{className:"p-5 flex flex-col gap-4",children:[e.jsxs("div",{className:"flex items-start justify-between gap-3",children:[e.jsx("div",{className:`w-14 h-14 rounded-2xl ${j.iconBg} ${j.iconText} flex items-center justify-center shadow-md group-hover:scale-105 transition-transform`,children:e.jsx(f,{className:"w-7 h-7"})}),v?e.jsx(Ue,{variant:"secondary",children:"Coming soon"}):y?e.jsxs(Ue,{className:"bg-emerald-100 text-emerald-700 hover:bg-emerald-100 gap-1",children:[e.jsx("span",{className:"w-1.5 h-1.5 rounded-full bg-emerald-500 animate-pulse"}),"Live"]}):_?e.jsx(Ue,{variant:"outline",children:"Paused"}):e.jsx(Ue,{className:j.chip+" hover:"+j.chip,children:"New"})]}),e.jsxs("div",{className:"space-y-1 flex-1",children:[e.jsx("h3",{className:"font-bold text-lg",children:p.name}),e.jsx("p",{className:"text-sm text-muted-foreground",children:p.description})]}),!v&&e.jsxs("div",{className:"flex items-center justify-between gap-3 pt-3 border-t",children:[e.jsxs("div",{className:"flex items-center gap-2",children:[e.jsx(jn,{checked:y,onCheckedChange:w=>o.mutate({app_slug:p.slug,enabled:w})}),e.jsx("span",{className:"text-sm font-medium text-muted-foreground",children:y?"On":"Off"})]}),e.jsxs(B,{size:"sm",className:`bg-gradient-to-r ${j.gradient} text-white hover:opacity-90 shadow-md border-0`,onClick:()=>s(`/website-apps/${p.slug}`),children:[e.jsx(Ko,{className:"w-3.5 h-3.5 mr-1.5"}),"Configure",e.jsx(Oa,{className:"w-3.5 h-3.5 ml-1"})]})]})]})]},p.id)})})]}),e.jsx(_s,{open:c,onOpenChange:d,children:e.jsxs(bs,{className:"max-w-4xl p-0 overflow-hidden bg-black border-0",children:[e.jsx(js,{className:"px-5 pt-4 pb-2 bg-background",children:e.jsx(ws,{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 yke={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 lmn(){const{user:s}=vs();return dt({queryKey:["video-greeter-config",s==null?void 0:s.id],queryFn:async()=>{if(!(s!=null&&s.id))return yke;const{data:t,error:n}=await q.from("video_greeter_configs").select("*").eq("user_id",s.id).maybeSingle();if(n)throw n;return t?{...yke,...t}:yke},enabled:!!(s!=null&&s.id)})}function cmn(){const{user:s}=vs(),t=Kt();return yt({mutationFn:async n=>{if(!(s!=null&&s.id))throw new Error("Not authenticated");const{error:r}=await q.from("video_greeter_configs").upsert({user_id:s.id,...n},{onConflict:"user_id"});if(r)throw r},onSuccess:()=>{t.invalidateQueries({queryKey:["video-greeter-config"]}),ae.success("Saved")},onError:n=>ae.error(n.message||"Failed to save")})}function dmn({label:s,value:t,onChange:n,thumbnailUrl:r,placeholder:a="https://...",hint:i}){const l=N.useRef(null),[o,c]=N.useState(!1),d=async u=>{var p;const h=(p=u.target.files)==null?void 0:p[0];if(h){if(!h.type.startsWith("video/")){ae.error("Please select a video file");return}if(h.size>50*1024*1024){ae.error("Video must be under 50MB");return}c(!0);try{const f=h.name.split(".").pop()||"mp4",y=`lead-site/videos/${Date.now()}-${Math.random().toString(36).slice(2,6)}.${f}`,{error:_}=await q.storage.from("agent-uploads").upload(y,h,{upsert:!0});if(_)throw _;const{data:{publicUrl:v}}=q.storage.from("agent-uploads").getPublicUrl(y);n(v),ae.success("Video uploaded!")}catch(f){ae.error(f.message||"Upload failed")}finally{c(!1),l.current&&(l.current.value="")}}};return e.jsxs("div",{children:[e.jsx(ne,{children:s}),e.jsxs("div",{className:"flex gap-2",children:[e.jsx(ye,{value:t,onChange:u=>n(u.target.value),placeholder:a,className:"flex-1"}),e.jsxs(B,{type:"button",variant:"outline",size:"sm",className:"shrink-0 gap-1.5 h-9",onClick:()=>{var u;return(u=l.current)==null?void 0:u.click()},disabled:o,children:[o?e.jsx(rs,{className:"h-3.5 w-3.5 animate-spin"}):e.jsx(_a,{className:"h-3.5 w-3.5"}),o?"Uploading...":"Upload"]}),e.jsx("input",{ref:l,type:"file",accept:"video/*",className:"hidden",onChange:d})]}),i&&e.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:i}),t&&(()=>{const u=t.match(/(?:youtube\.com\/(?:watch\?v=|embed\/|shorts\/)|youtu\.be\/)([A-Za-z0-9_-]{11})/),h=u==null?void 0:u[1];return e.jsxs("div",{className:"relative group mt-2",children:[e.jsx("div",{className:`rounded-lg border border-border overflow-hidden bg-black w-full mx-auto ${h?"max-w-xl aspect-video":"max-w-sm aspect-[9/16]"}`,children:h?e.jsx("iframe",{src:`https://www.youtube.com/embed/${h}`,className:"w-full h-full",title:"Video preview",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0}):OP(t)?e.jsx(ATe,{sourceUrl:t,thumbnailUrl:r,autoPlay:!0,muted:!0,loop:!0,className:"w-full h-full object-contain"}):e.jsx("video",{src:t,className:"w-full h-full object-contain",controls:!0,muted:!0,preload:"metadata"})}),e.jsx(B,{type:"button",variant:"destructive",size:"icon",className:"absolute top-1 right-1 h-6 w-6 opacity-0 group-hover:opacity-100 transition-opacity",onClick:()=>n(""),children:e.jsx($n,{className:"h-3 w-3"})})]})})()]})}const umn=[{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 hmn({onVideoReady:s}){const[t,n]=N.useState(!1),[r,a]=N.useState("script"),[i,l]=N.useState(""),[o,c]=N.useState(!0),[d,u]=N.useState(!1),[h,p]=N.useState(0),[f,y]=N.useState(0),_=CN(),v=()=>{a("script"),l(""),p(0),y(0),c(!0)},j=S=>{!S&&(r==="uploading"||r==="processing")||(n(S),S||v())},w=N.useCallback(async(S,A)=>{a("uploading");try{const E="Video Greeter",{videoId:O,libraryId:D}=await t6(E),{uploadUrl:I,apiKey:F}=await s6(O),z=new XMLHttpRequest;z.upload.onprogress=ce=>{ce.lengthComputable&&p(ce.loaded/ce.total*100)},await new Promise((ce,me)=>{z.onload=()=>z.status>=200&&z.status<300?ce():me(new Error("Upload failed")),z.onerror=()=>me(new Error("Upload failed")),z.open("PUT",I),z.setRequestHeader("AccessKey",F),z.send(S)}),a("processing");let H=0;const Z=Date.now(),Y=9e4,W=`https://iframe.mediadelivery.net/embed/${D}/${O}`,ee=`https://iframe.mediadelivery.net/play/${D}/${O}`;for(;H<4;){if(await new Promise(me=>setTimeout(me,3e3)),Date.now()-Z>Y){const me=S.size/1048576,le=await _.mutateAsync({bunny_video_id:O,playback_url:ee,file_size_mb:me,title:E,status:"processing",touch_type:"video"});s({videoId:(le==null?void 0:le.id)||O,playbackUrl:W,thumbnailUrl:null}),ae.success("Video saved — still encoding. Will be ready shortly."),a("done"),setTimeout(()=>{n(!1),v()},1500);return}const ce=await Fw(O);if(H=ce.status,y(ce.encodeProgress||0),H===5||H===6)throw new Error("Video processing failed")}const se=await Fw(O),oe=(se.storageSize||S.size)/(1024*1024),he=await _.mutateAsync({bunny_video_id:O,playback_url:se.directPlayUrl||W,thumbnail_url:se.thumbnailUrl,preview_url:se.previewUrl||null,duration_seconds:se.length||A,file_size_mb:oe,title:E,status:"ready",touch_type:"video"});s({videoId:(he==null?void 0:he.id)||O,playbackUrl:se.directPlayUrl||W,thumbnailUrl:se.thumbnailUrl||null}),ae.success("Video recorded & added to your library!"),a("done"),setTimeout(()=>{n(!1),v()},1500)}catch(E){console.error(E),ae.error("Failed to process video. Please try again."),a("record")}},[_,s]);return e.jsxs(_s,{open:t,onOpenChange:j,children:[e.jsx(ki,{asChild:!0,children:e.jsxs(B,{variant:"default",size:"sm",className:"gap-1.5",children:[e.jsx(fr,{className:"h-4 w-4"}),"Record now"]})}),e.jsxs(bs,{className:"sm:max-w-3xl max-h-[92vh] overflow-y-auto",children:[e.jsx(js,{children:e.jsxs(ws,{className:"flex items-center gap-2",children:[e.jsx(un,{className:"h-5 w-5 text-primary"}),"Record your Video Greeter"]})}),r==="script"&&e.jsxs("div",{className:"space-y-4",children:[e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"1. Pick a script (optional)"}),e.jsx("p",{className:"text-xs text-muted-foreground mb-3",children:"Edit it to sound like you, or skip and freestyle."}),e.jsx(di,{className:"h-[280px] pr-3",children:e.jsx("div",{className:"grid sm:grid-cols-2 gap-3",children:umn.map(S=>e.jsxs(fe,{className:"p-3 cursor-pointer hover:border-primary transition-colors",onClick:()=>l(S.text),children:[e.jsxs("div",{className:"flex items-start justify-between gap-2 mb-1",children:[e.jsx("h4",{className:"font-medium text-sm",children:S.title}),e.jsx(Ue,{variant:"outline",className:"text-[10px] shrink-0",children:S.duration})]}),e.jsx("p",{className:"text-xs text-muted-foreground line-clamp-2",children:S.description})]},S.id))})})]}),e.jsxs("div",{children:[e.jsx("h3",{className:"font-semibold text-sm mb-1",children:"2. Edit your script"}),e.jsx(Ms,{rows:5,value:i,onChange:S=>l(S.target.value),placeholder:"Pick a script above or type your own. Leave blank to freestyle."})]}),e.jsxs("div",{className:"flex justify-end gap-2 pt-2 border-t",children:[e.jsx(B,{variant:"ghost",onClick:()=>{l(""),a("record")},children:"Skip — freestyle"}),e.jsxs(B,{onClick:()=>a("record"),children:[e.jsx(br,{className:"h-4 w-4 mr-1.5"})," Continue to recorder"]})]})]}),r==="record"&&e.jsxs("div",{className:"space-y-3",children:[e.jsx(i6,{maxDurationSeconds:60,onRecordingComplete:w,onRecordingStateChange:u,onError:S=>ae.error(S),teleprompterContent:o&&i?e.jsx(QLe,{text:i,isVisible:o,onToggleVisibility:()=>c(!1),isRecording:d,startCountdown:!1}):void 0}),e.jsxs("div",{className:"flex justify-between items-center",children:[e.jsx(B,{variant:"ghost",size:"sm",onClick:()=>a("script"),children:"← Back to script"}),i&&!o&&e.jsxs(B,{variant:"outline",size:"sm",onClick:()=>c(!0),children:[e.jsx(br,{className:"h-4 w-4 mr-1.5"})," Show teleprompter"]})]})]}),r==="uploading"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(rs,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Uploading video..."}),e.jsx(fi,{value:h,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(h),"%"]})]}),r==="processing"&&e.jsxs("div",{className:"flex flex-col items-center gap-4 py-12",children:[e.jsx(rs,{className:"h-10 w-10 animate-spin text-primary"}),e.jsx("p",{className:"text-sm font-medium",children:"Processing video..."}),e.jsx(fi,{value:f,className:"w-64"}),e.jsxs("p",{className:"text-xs text-muted-foreground",children:[Math.round(f),"%"]})]}),r==="done"&&e.jsxs("div",{className:"flex flex-col items-center gap-3 py-12",children:[e.jsx(Pi,{className:"h-12 w-12 text-emerald-500"}),e.jsx("p",{className:"text-sm font-medium",children:"Video attached to your greeter!"})]})]})]})}function mmn(){var A;const s=Ln(),{user:t}=vs(),{leadSite:n}=Ap(),{data:r}=lmn(),a=cmn(),{data:i=[]}=tbe(),l=sbe(),[o,c]=N.useState(null),[d,u]=N.useState({impressions:0,expands:0,ctaClicks:0,leads:0});if(N.useEffect(()=>{r&&!o&&c(r)},[r,o]),N.useEffect(()=>{t!=null&&t.id&&q.from("widget_events").select("event_type",{count:"exact"}).eq("user_id",t.id).eq("app_slug","video_greeter").then(({data:E})=>{const O=E||[];u({impressions:O.filter(D=>D.event_type==="impression").length,expands:O.filter(D=>D.event_type==="expand").length,ctaClicks:O.filter(D=>D.event_type==="cta_click").length,leads:O.filter(D=>D.event_type==="lead_capture").length})})},[t==null?void 0:t.id]),!o)return e.jsx(Cs,{title:"Video Greeter",children:e.jsx("div",{className:"p-8 text-sm text-muted-foreground",children:"Loading..."})});const h=((A=i.find(E=>E.app_slug==="video_greeter"))==null?void 0:A.enabled)??!1,p=E=>c({...o,...E}),f=E=>p({ctas:E}),y=()=>f([...o.ctas||[],{id:crypto.randomUUID(),label:"New Button",url:"https://",style:"primary"}]),_=E=>f((o.ctas||[]).filter(O=>O.id!==E)),v=(E,O)=>f((o.ctas||[]).map(D=>D.id===E?{...D,...O}:D)),j=()=>a.mutate(o),w=(n==null?void 0:n.subdomain_slug)||(t==null?void 0:t.id)||"",S=`